commit b8d00014d6d405eb7d8a6ec79d414109e80b0211 Author: Kenneth Jao Date: Sun Sep 19 02:53:43 2021 -0400 Initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1c0bba1 --- /dev/null +++ b/.gitignore @@ -0,0 +1,9 @@ +.venv +__pycache__ +src/build +src/packsim.c + +*.so + +figures +simulations \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f288702 --- /dev/null +++ b/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/README.md b/README.md new file mode 100644 index 0000000..7390259 --- /dev/null +++ b/README.md @@ -0,0 +1 @@ +# packsim \ No newline at end of file diff --git a/build.sh b/build.sh new file mode 100644 index 0000000..8fd28f1 --- /dev/null +++ b/build.sh @@ -0,0 +1,3 @@ +cd src +python3 setup.py build_ext --inplace --quiet +mv *.so ../ \ No newline at end of file diff --git a/check_width_exists.py b/check_width_exists.py new file mode 100644 index 0000000..c108839 --- /dev/null +++ b/check_width_exists.py @@ -0,0 +1,17 @@ +from pathlib import Path +import sys, numpy as np + +def main(): + n = int(sys.argv[1]) + all_widths = set(np.round(np.arange(3, 10.05, 0.05), 2)) + for file in Path(f"simulations/Radial[T]T - N{n}R4.0").iterdir(): + i = file.name.index("x") + all_widths.remove(float(file.name[i-4:i])) + + remain_widths = sorted(list(all_widths))[::-1] + print(remain_widths) + print([int(round((10-w)/.05)) for w in remain_widths]) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/packsim.py b/packsim.py new file mode 100644 index 0000000..6f82bb8 --- /dev/null +++ b/packsim.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 + +from __future__ import annotations +import argparse, json +from simulation import Diagram, Flow, Search, Shrink + + +def get_diagram(sim, t): + if t == "flow": + diagram = Diagram(sim, np.array([["voronoi", "energy"]])) + elif t == "stats": + diagram = Diagram(sim, np.array([ + ["voronoi", "eigs", "site_edge_count"], + ["site_isos", "site_energies", "edge_lengths"] + ]), cumulative=False) + elif t == "eigs": + diagram = Diagram(sim, np.array([["voronoi", "eigs"]])) + elif t == "shrink": + diagram = Diagram(sim, np.array([["voronoi", "avg_radius", "isoparam_avg"]]), cumulative=False) + + return diagram + + +def main(): + # Loading configuration and settings. + parser = argparse.ArgumentParser("Processes packing simulations.") + parser.add_argument('sim_conf', metavar='path/to/config', + help="configuration file for a simulation") + parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', default=False, + help="suppress all normal output") + parser.add_argument('-l', '--log', dest='log_steps', action='store_true', default=50, + help="number of iterations before logging") + parser.add_argument('-i', '--input', dest='input_file') + parser.add_argument('-o', '--output', dest='output_file') + + args = parser.parse_args() + + if args.input_file is None: + config_sim(args) + else: + loaded_sim(args) + + +def config_sim(args): + with open(args.sim_conf) as f: + params = json.load(f) + + calc_params, sim_params = params["calc"], params["sim"] + n, w, h, r, energy = calc_params["n_objects"], calc_params["width"], calc_params["height"], \ + calc_params["natural_radius"], calc_params["energy"] + + mode, thres, step = sim_params["mode"], sim_params["threshold"], sim_params["step_size"] + + # Running simulation + if mode == "flow": + sim = Flow(n, w, h, r, energy, thres, step) + elif mode == "search": + sim = Search(n, w, h, r, energy, thres, step, sim_params["manifold_step"], + sim_params["count"]) + elif mode == "shrink": + sim = Shrink(n, w, h, r, energy, thres, step, sim_params["delta_width"], + sim_params["stop_width"]) + + sim.initialize() + sim.run(not args.quiet, args.log_steps) + + +def loaded_sim(args): + pass + + +if __name__ == '__main__': + try: + main() + except KeyboardInterrupt: + print("Program terminated by user.") \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..a71c412 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +cycler==0.10.0 +Cython==0.29.24 +kiwisolver==1.3.1 +matplotlib==3.4.3 +numpy==1.21.2 +Pillow==8.3.1 +pyparsing==2.4.7 +python-dateutil==2.8.2 +scipy==1.7.1 +six==1.16.0 diff --git a/shrink_energy_comparison.py b/shrink_energy_comparison.py new file mode 100644 index 0000000..d2bab3c --- /dev/null +++ b/shrink_energy_comparison.py @@ -0,0 +1,165 @@ +#!/usr/bin/env python3 + +from __future__ import annotations +from typing import List +from simulation import Diagram, Simulation +import argparse, numpy as np +import matplotlib.pyplot as plt +from pathlib import Path + + +def get_torus_config_energies(n: int, widths: np.ndarray, h: float, r: float, + energy: str) -> Tuple[np.ndarray, np.ndarray]: + torus_min_energies, torus_max_energies = np.empty(widths.shape), np.empty(widths.shape) + for i, w in enumerate(widths): + sim = Simulation(n, w, h, r, energy) + + for c in range(1,n): # Ignore 0, tends to error. + sim.add_frame(torus=(1,c)) + sim.add_frame(torus=(c,1)) + + hashes = int(21*i/len(widths)) + print(f'Generating at width {w:.02f}... ' + \ + f'|{"#"*hashes}{" "*(20-hashes)}| {i+1}/{len(widths)}, {2*c}/{2*(n-1)}' + \ + f' completed.', flush=True, end='\r') + + torus_min_energies[i] = min([frame.energy for frame in sim.frames]) + torus_max_energies[i] = max([frame.energy for frame in sim.frames]) + + print(flush=True) + return torus_min_energies, torus_max_energies + + +# def equal_shape_eigs(n, widths, h, r): +# n,w,h,r = 57, 10, 10, 4 # Domain settings +# thres, step_size = 10e-5, 5e-2 # Simulation settings +# log_steps = 50 +# energy = "radial-t" + +# sims = [None]*n*2 +# energies = {} + +# for x in range(1,n): +# sim = TravelEQ(n, w, h, r, energy, thres, step_size, log_steps) +# sim2 = TravelEQ(n, w, h, r, energy, thres, step_size, log_steps) +# #frame = FindEQ(n, w, h, r, "radial-t", POOL, thres, step_size, log_steps) +# for j in range(141): +# sim.w = 10-j*.05 +# sim2.w = 10-j*.05 +# sim.add_frame(None, (1,x), 0) +# sim2.add_frame(None, (x, 1), 0) +# #sim.initialize(torus=(1,x)) + +# energies[(1,x)] = sim[0].energy +# energies[(x,1)] = sim2[0].energy + +# sims[x] = list([y.energy for y in sim.frames]) +# sims[x+n] = list([y.energy for y in sim2.frames]) +# #k1 = np.concatenate(sim.frames[0].process(sim.frames[0].grad, sim.frames[0].get_ranges())) +# #print(np.linalg.norm(k1)) + +# # hess = sim.frames[0].hessian(10e-5) +# # eigs = np.sort(np.linalg.eig(hess)[0]) +# # sim.frames[0].stats["eigs"] = eigs + +# # diagram = Diagram(sim, np.array([["voronoi", "eigs"]])) +# #diagram = Diagram(sim, np.array([["voronoi"]])) +# #diagram.render_static(0, filename=f'EqualShape/EqualShapeN{n}/{str((1, x))}') + +# print(min(energies, key=energies.get)) + +# return sims + + +def main(): + # Loading arguments. + parser = argparse.ArgumentParser("Compiles the equilibriums for each width into a diagram.") + parser.add_argument('sims_path', metavar='path/to/folder', + help="folder that contains simulation files.") + parser.add_argument('-q', '--quiet', dest='quiet', action='store_true', default=False, + help="suppress all normal output") + parser.add_argument('-o', '--output', dest='output_file') + + args = parser.parse_args() + + sims = [] + files = list(Path(args.sims_path).iterdir()) + + for i, file in enumerate(files): + sims.append(Simulation.load(file)) + + hashes = int(21*i/len(files)) + print(f'Loading simulations... |{"#"*hashes}{" "*(20-hashes)}|' + \ + f' {i+1}/{len(files)} simulations loaded.', flush=True, end='\r') + print(flush=True) + sims.sort(key=lambda x: x.w) + + widths = np.asarray([sim.w for sim in sims]) + + min_frames = [min(sim.frames, key=lambda x: x.energy) for sim in sims] + max_frames = [max(sim.frames, key=lambda x: x.energy) for sim in sims] + + min_energies = np.asarray([frame.energy for frame in min_frames]) + max_energies = np.asarray([frame.energy for frame in max_frames]) + + torus_min_energies, torus_max_energies = get_torus_config_energies( + sims[0].n, widths, sims[0].h, sims[0].r, sims[0].energy + ) + + min_markers = [np.var(frame.stats["site_areas"]) <= 1e-8 for frame in min_frames] + max_markers = [np.var(frame.stats["site_areas"]) <= 1e-8 for frame in max_frames] + + # Torus minimum energies used as reference. + + fig, ax = plt.subplots(figsize=(16, 8)) + #ax.plot(widths, nums) + # for i, equal_sim in enumerate(equal_sims): + # if i in [0, n]: + # continue + + # ax.plot(widths, + # np.asarray(equal_sims[i]) - reference, + # color="orange", alpha=0.5, linewidth=0.5, zorder=3 + # ) + + ax.plot(widths, torus_min_energies - torus_min_energies, color='C1') + ax.plot(widths, min_energies - torus_min_energies, color='C0') + ax.plot(widths, max_energies - torus_min_energies, color='C0', linestyle='dotted') + #ax.plot(widths, torus_max_energies - torus_min_energies, color='C1', linestyle='dotted') + + for i, marker in enumerate(min_markers): + if marker: + ax.scatter(widths[i], min_energies[i]-torus_min_energies[i], + marker='H', color="orange", s=20, zorder=4) + else: + ax.scatter(widths[i], min_energies[i]-torus_min_energies[i], + marker='d', color="blue", s=20, zorder=4) + + for i, marker in enumerate(max_markers): + if marker: + ax.scatter(widths[i], max_energies[i]-torus_min_energies[i], + marker='H', edgecolors="orange", s=20, facecolors='none', zorder=4) + else: + ax.scatter(widths[i], max_energies[i]-torus_min_energies[i], + marker='d', edgecolors="blue", s=20, facecolors='none', zorder=4) + + + ax.invert_xaxis() + ax.title.set_text('Reduced Energy vs. Width') + ax.set_xlabel("Width") + ax.set_ylabel("Reduced Energy") + ax.grid(zorder=0) + + #ax.set_xticks([round(w,2) for w in widths[::-2]]) + #ax.set_yticks(np.arange(-920, 1120, 40)) + #ax.set_xticklabels(ax.get_xticks(), rotation = 90) + + plt.tight_layout() + + fig.savefig(f"figures/WidthsEnergyComparison - N{sims[0].n}.png") + +if __name__ == "__main__": + try: + main() + except KeyboardInterrupt: + print("Program terminated by user.") \ No newline at end of file diff --git a/simulation.py b/simulation.py new file mode 100644 index 0000000..2049320 --- /dev/null +++ b/simulation.py @@ -0,0 +1,734 @@ +from __future__ import annotations +from typing import Tuple, List + +import matplotlib.pyplot as plt +from matplotlib.ticker import MaxNLocator, FormatStrFormatter +import os, math, random, time, pickle, scipy, numpy as np + +from packsim import VoronoiContainer, AreaEnergy, RadialALEnergy, RadialTEnergy +from timeit import default_timer as timer + + +INT = np.int64 +FLOAT = np.float64 + +SYMM = np.array([[1,0], [1,1], [0,1], [-1,1], [-1,0], [-1,-1], [0,-1], [1,-1]]) + +def gen_filepath(sim: Simulation, ext: str, parent_dir='figures') -> str: + """ + Generates a filename based on the simulation. + :param sim: [Simulation] simulation to generate file for. + :param ext: [str] file extension. + :return: [str] string for filename. + """ + energy = {AreaEnergy: "Area", RadialALEnergy: "Radial[AL]", + RadialTEnergy: "Radial[T]"}[sim.energy] + mode = {Flow: "F", Search: "T", Shrink: "S"}[type(sim)] + + base_filename = f'{energy}{mode} - N{sim[0].n}R{sim[0].r} - {round(sim[0].w, 2):.2f}x{sim[0].h}' + base_path = f'{parent_dir}/{base_filename}' + + i = 1 + if ext == "": + path = base_path + while os.path.isdir(path): + path = base_path + f'({i})' + i += 1 + else: + path = base_path + "." + ext + while os.path.isfile(path): + path = base_path + f'({i}).{ext}' + i += 1 + return path + + +class Diagram(): + """ + Class for generating diagrams. + :param sim: [Simulation] Simulation class containing dynamics. + :param diagrams: [np.ndarray] selects which diagrams to show. + """ + + __slots__ = ['sim', 'diagrams', 'cumulative'] + + def __init__(self, sim: Simulation, diagrams: np.ndarray, cumulative: bool = True): + self.sim = sim + self.diagrams = np.atleast_2d(diagrams) + self.cumulative = cumulative + + + def generate_frame(self, frame: int): + """ + Generates one frame for the plot. + :param frame: [int] frame index to draw. + :param scale: [float] how much of the domain to draw. + :param area: [bool] set to false to not label areas. + :param only: [bool] set to True to only render diagram. + """ + shape = self.diagrams.shape + fig, axes = plt.subplots(*shape, figsize=(shape[1]*8, shape[0]*8)) + if self.diagrams.shape == (1,1): + getattr(self, str(self.diagrams[0][0]) + '_plot')(frame, axes) + else: + axes = np.atleast_2d(axes) + it = np.nditer(self.diagrams, flags=["multi_index"]) + for diagram in it: + if diagram == "": + continue + getattr(self, str(diagram) + '_plot')(frame, axes[it.multi_index]) + + plt.tight_layout() + + + def voronoi_plot(self, i: int, ax): + n,w,h = self.sim[i].n, self.sim[i].w, self.sim[i].h + scale = 1.5 + area = n <= 60 + + scipy.spatial.voronoi_plot_2d(self.sim[i].vor_data, ax, show_vertices=False, + point_size = 7-n/100) + ax.plot([-w, 2*w], [0, 0], 'r') + ax.plot([-w, 2*w], [h, h], 'r') + ax.plot([0,0], [-h, 2*h], 'r') + ax.plot([w, w], [-h, 2*h], 'r') + ax.axis('equal') + ax.set_xlim([(1-scale)*w/2, (1+scale)*w/2]) + ax.set_ylim([(1-scale)*h/2, (1+scale)*h/2]) + ax.title.set_text("Voronoi Visualization") + + props = dict(boxstyle='round', facecolor='wheat', alpha=0.8) + + # if area: + # global SYMM + # for site_index in range(n): + # for s in np.concatenate(([[0,0]], SYMM)): + # txt = ax.text(*(site.vec + s*self.sim[i].dim), + # str(round(site.cache("area"), 3))) + # txt.set_clip_on(True) + + ax.text(0.05, 0.95, f'Energy: {self.sim[i].energy}', transform=ax.transAxes, fontsize=14, + verticalalignment='top', bbox=props) + + + def energy_plot(self, i: int, ax): + ax.set_xlim([0, len(self.sim)]) + try: + ax.plot([0, len(self.sim)], [self.sim[i].minimum, self.sim[i].minimum], 'red') + except AttributeError: + pass + + energies = [self.sim[j].energy for j in range(i+1)] + ax.plot(list(range(i+1)), energies) + ax.title.set_text('Energy vs. Time') + max_value = round(self.sim[0].energy) + min_value = round(self.sim[-1].energy) + diff = max_value-min_value + ax.set_yticks(np.arange(int(min_value-diff/5), int(max_value+diff/5), diff/25)) + ax.set_xlabel("Iterations") + ax.set_ylabel("Energy") + ax.grid() + + + def site_areas_plot(self, i: int, ax): + regular_area = self.sim[i].w*self.sim[i].h/self.sim[i].n + y, x = self.sim.generate_bar_info("site_areas", i, self.cumulative, + avg=True, reg=regular_area) + + ax.bar(x, y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Site Areas') + ax.set_xlabel("Area") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.ticklabel_format(useOffset=False) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + # for xtick, color in zip(ax.get_xticklabels(), areas_bar[2]): + # if color != 'C0': + # xtick.set_color(color) + + + def site_edge_count_plot(self, i: int, ax): + y, x = self.sim.generate_bar_info("site_edge_count", i, self.cumulative, + bounds=(1, 11), avg=True) + + ax.bar(x, y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Edges per Site') + ax.set_xlabel("Number of Edges") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.set_xticklabels([int(z) for z in x]) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + + + def site_isos_plot(self, i: int, ax): + regular_area = self.sim[i].w*self.sim[i].h/self.sim[i].n + regular_edge = math.sqrt(2*regular_area/(3*math.sqrt(3))) + regular_isoparam = 4*math.pi*regular_area/(6*regular_edge)**2 + + y, x = self.sim.generate_bar_info("site_isos", i, self.cumulative, bounds=(0,1), + avg=True, reg=regular_isoparam) + + ax.bar(x, y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Isoparametric Values') + ax.set_xlabel("Isoparametric Value") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.ticklabel_format(useOffset=False) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + # for xtick, color in zip(ax.get_xticklabels(), isoparam_bar[2]): + # if color != 'C0': + # xtick.set_color(color) + + + def site_energies_plot(self, i: int, ax): + y, x = self.sim.generate_bar_info("site_energies", i, self.cumulative, avg=True) + + ax.bar(x, y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Site Energies') + ax.set_xlabel("Energy") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.ticklabel_format(useOffset=False) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + + + def avg_radius_plot(self, i: int, ax): + y, x = self.sim.generate_bar_info("avg_radius", i, self.cumulative, avg=True) + ax.bar(x, y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Site Average Radii') + ax.set_xlabel("Average Radius") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.ticklabel_format(useOffset=False) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + + + def isoparam_avg_plot(self, i: int, ax): + y, x = self.sim.generate_bar_info("isoparam_avg", i, self.cumulative, avg=True) + + ax.bar(x,y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Site Isoperimetric Averages') + ax.set_xlabel("Isoperimetric Average") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.ticklabel_format(useOffset=False) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + + + def edge_lengths_plot(self, i: int, ax): + regular_area = self.sim[i].w*self.sim[i].h/self.sim[i].n + regular_edge = math.sqrt(2*regular_area/(3*math.sqrt(3))) + y, x = self.sim.generate_bar_info("edge_lengths", i, self.cumulative, + 30, avg=True, reg=regular_edge) + + ax.bar(x, y, width=0.8*(x[1]-x[0])) + ax.title.set_text('Edge Lengths') + ax.set_xlabel("Length") + ax.set_ylabel("Average Occurances") + ax.set_xticks(x) + ax.set_xticklabels(ax.get_xticks(), rotation = 90) + ax.xaxis.set_major_formatter(FormatStrFormatter('%.3f')) + #ax.ticklabel_format(useOffset=False) + ax.yaxis.set_major_locator(MaxNLocator(integer=True)) + # for xtick, color in zip(ax.get_xticklabels(), lengths_bar[2]): + # if color != 'C0': + # xtick.set_color(color) + + + def eigs_plot(self, i: int, ax): + eigs = self.sim[i].stats["eigs"] + ax.plot(list(range(len(eigs))), eigs, marker='o', linestyle='dashed', color='C0') + ax.plot([0,len(eigs)], [0, 0], color="red") + ax.title.set_text('Hessian Eigenvalues') + ax.set_xlabel("") + ax.set_ylabel("Value") + + + def render_static(self, i: int, j: int = None, filename = None): + """ + Renders single frames. + :param filename: [str] name of file. + :param i: [int] index of frame to start rendering. + :param j: [j] index of frame to stop rendering. + :param only: [bool] set to True to only render diagram. + """ + if j is None: + j = len(self.sim)-1 + + length = j+1-i + if length == 1: + if filename is None: + path = gen_filepath(self.sim, "png") + else: + path = f'figures/{filename}.png' + + self.generate_frame(i) + plt.savefig(path) + plt.close() + + print(f'Wrote to \"{path}\"') + else: + if filename is None: + path = gen_filepath(self.sim, "") + else: + path = f'figures/{filename}' + + os.mkdir(path) + for frame in range(i, j+1): + self.generate_frame(frame) + if frame % 20 == 0: + print(f'Rendered frame {frame}/{length} : {100*frame/length:.2f}%') + plt.savefig(f'{path}/img{frame:03}.png') + plt.close() + + print(f'Wrote to folder \"{path}\"') + + + def render_video(self, time = 30, fps = None, filename = None): + """ + Renders plot(s) into image. + :param scale: [float] how much of the domain to draw. + :param area: [bool] set to false to not label area. + :param filename: [str] name for static image. + :param fps: [float] fps for image. + :param only: [bool] set to True to only render diagram. + """ + if fps is None: + if type(self.sim) == Flow: + fps = min(len(self.sim)/time, 30) + else: + fps = 5 + + step = len(self.sim)/(fps*time) if fps == 30 else 1 + # Iterate through desired frames. + try: + os.mkdir("figures/temp") + except FileExistsError: + pass + + print("Generating frames...") + frames = min(len(self.sim), int(fps * time)) + for j in range(frames): + self.generate_frame(int(j*step)) + if j % 20 == 0: + print(f'Rendered frame {j}/{frames} : {100*j/frames:.2f}%') + plt.savefig(f'figures/temp/img{j:03}.png') + plt.close() + + + if filename is None: + path = gen_filepath(self.sim, "mp4") + else: + path = f'figures/{filename}.mp4' + + # Convert to gif. + print("Assembling MP4...") + os.system(f'ffmpeg -hide_banner -loglevel error -r {fps} -i figures/temp/img%03d.png' + \ + f' -c:v libx264 -crf 18 -preset slow -pix_fmt yuv420p -vf' + \ + f' "scale=trunc(iw/2)*2:trunc(ih/2)*2" -f mp4 "{path}"') + + # Remove files. + for j in range(frames): + os.remove(f'figures/temp/img{j:03}.png') + + os.rmdir("figures/temp") + print(f'Wrote to \"{path}\".') + + +class Simulation: + """ + Class for running simulations. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param energy: energy to use to calculate. Can + pass in class directly or use string. + """ + + __slots__ = ['n', 'w', 'h', 'r', 'energy', 'frames'] + + def __init__(self, n: int, w: float, h: float, r: float, energy: str): + self.n, self.w, self.h, self.r = int(n), w, h, r + self.frames = [] + if self.n < 2: + raise ValueError("Number of objects should be larger than 2!") + + if self.w <= 0: + raise ValueError("Width needs to be nonzero and positive!") + + if self.h <= 0: + raise ValueError("Height needs to be nonzero and positive!") + + if isinstance(energy, str): + try: + self.energy = {"area": AreaEnergy, "radial-al": RadialALEnergy, + "radial-t" : RadialTEnergy}[energy.lower()] + except KeyError: + raise ValueError("Invalid Energy!") + else: + if energy not in [AreaEnergy, RadialALEnergy, RadialTEnergy]: + raise ValueError("Invalid Energy!") + self.energy = energy + + def __getitem__(self, key: int) -> VoronoiContainer: + return self.frames[key] + + def __len__(self): + return len(self.frames) + + + def initialize(self, points = None, torus = None, jitter = 0): + """ + Initializes the simulation + :param points: Can be multiple types. Takes list-like data types. + :param torus: Used or generating torus points. L value. + :param jitter: [int] Add random*jitter movement to initial data. + """ + self.add_frame(points, torus, jitter) + + + def add_frame(self, points = None, torus = None, jitter = 0.0): + """ + Adds a new frame to this simulation. + :param points: Can be multiple types. Takes list-like data types. + :param torus: Used or generating torus points. L value. + :param jitter: [int] Add random*jitter movement to initial data. + """ + dim = np.array([self.w, self.h]) + if not (points is None): + points = np.asarray(points) + if points.shape[1] != 2: + raise ValueError("Improper shape, points are 2 dimensional.") + elif not torus is None: + points = Simulation.torus_sites(self.n, self.w, self.h, torus) + else: + points = dim * np.random.random_sample((self.n, 2)) + + points += (jitter*np.random.random_sample((self.n, 2)).astype(FLOAT)) % dim + + self.frames.append(self.energy(self.n, self.w, self.h, self.r, points)) + + + def generate_bar_info(self, stat: str, i: int, cumulative: bool, bins: int = 10, + bounds: Tuple[float] = None, avg: bool = False, reg = None) -> Tuple: + """ + Gets the bar info for matplotlib from the ith to jth frame. + :param stat: [str] name of statistic to obtain. + :param i: [int] frame to obtain + :param cumulative: [bool] Will obtain all stats up to the ith frame if True. + :param bins: [int] number of bins for the bar graph. + :param bound: [Tuple[float]] lower and upper bounds for the bins. If not set, + automatically take the min and max value. + :param avg: [bool] Averages the counts over the number of frames if True. + :param mark: If not None, set a specific marker. + :return: [Tuple] returns a tuple of labels, values, and colors. + """ + if cumulative: + values = np.concatenate([f.stats[stat] for f in self.frames[:(i+1)]]) + else: + values = self.frames[i].stats[stat] + + bins = 9 + if np.var(values) <= 1e-8: + hist = np.zeros((bins,)) + val = np.average(values) + hist[(bins+1) // 2 - 1] = len(values) + bin_list = np.linspace(0, val, bins//2+1, endpoint=True) + bin_list = np.concatenate((bin_list, (bin_list+val)[1:])) + return hist, bin_list[not (bins%2):] + + hist, bin_edges = np.histogram(values, bins=bins, range=bounds) + bin_list = [(bin_edges[i] + bin_edges[i+1])/2 for i in range(len(bin_edges)-1)] + + if avg and cumulative: + return hist / (i+1), bin_list + + return hist, bin_list + + # colors = ["C0"]*bins + # if reg >= lb and reg <= ub: + # colors[int((reg-lb)*bins/diff)] = "C3" + + # return (labels, count, colors) + + + def get_distinct(self) -> Simulation: + distinct_eigs = [] + new_frames = [] + + for frame in self.frames: + new_eigs = frame.stats["eigs"] + + is_in = False + for eigs in distinct_eigs: + if np.allclose(new_eigs, eigs, atol=1e-4): + is_in = True + + if not is_in: + distinct_eigs.append(new_eigs) + new_frames.append(frame) + continue + + new_sim = self.__class__(self.n, self.w, self.h, self.r, self.energy) + new_sim.frames = new_frames + return new_sim + + + def save(self, filename: str = None): + """ + Saves the points at every point into a file. + :filename: [str] name of the file + """ + if filename is None: + path = gen_filepath(self, "sim", "simulations") + else: + path = f'simulations/{filename}.sim' + + # Convert sites to NumPy array. + arr = np.zeros((len(self.frames), self.n, 2)) + arr = np.stack([frame.site_arr for frame in self.frames]) + #stats = [frame.stats for frame in self.frames] + + all_info = [] + for frame in self.frames: + frame_info = dict() + frame_info["arr"] = frame.site_arr + frame_info["energy"] = {AreaEnergy: "Area", RadialALEnergy: "Radial[AL]", + RadialTEnergy: "Radial[T]"}[sim.energy] + frame_info["params"] = (frame.n, frame.w, frame.h, frame.r) + all_info.append(frame_info) + + with open(path, 'wb') as output: + pickle.dump((all_info, self.__class__), output, pickle.HIGHEST_PROTOCOL) + print("Wrote to " + path) + + + @staticmethod + def load(filename: str) -> Simulation: + """ + Loads the points at every point into a file. + :param filename: [str] name of the file + """ + frames = [] + with open(filename, 'rb') as data: + all_info, sim_class = pickle.load(data) + sim = sim_class(*all_info[0]["params"], all_info[0]["energy"], 0, 0, 0, 0) + for frame_info in all_info: + frames.append(frame_info["energy"](*frame_info["params"], frame_info["arr"])) + frames[-1].stats = frame_info["stats"] + + sim.frames = frames + return sim + + + @staticmethod + def torus_sites(n: int, w: float, h: float, L: Tuple[int]): + """ + Returns the points when you wrap a line + around a torus, like in the periodic domain. + :param n: [int] amount of points. + :param w: [float] width of the domain. + :param h: [float] height of the domain. + :param L: [Tuple[int]] L = (u,v) + """ + dim = np.array([[w, h]]) + L = np.array(L) + return (np.array([1,1])/2 + np.concatenate([(i*dim*L/n) for i in range(n)])) % dim + + +class Flow(Simulation): + """ + Class for finding an equilibrium from initial points. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param energy: [str] energy to use to calculate. + :param thres: [float] threshold for close enough to equilibrium. + :param step_size: [float] size to step by for iteration. + """ + + __slots__ = ['thres', 'step_size'] + + def __init__(self, n: int, w: float, h: float, r: float, energy: str, thres: float, + step_size: float): + super().__init__(n, w, h, r, energy) + self.thres, self.step_size = thres, step_size + + + def run(self, log, log_steps): + """ + Runs the simulation. + :param log: [bool] will log if True. + """ + if log: + print(f'Find - N = {self.n}, R = {self.r}, {self.w} X {self.h}', flush=True) + i, grad_mag = 0, float('inf') + + ## Replace with adaptive step size eventually!!!!!! + + trial = 2 + while grad_mag > self.thres: # Get to threshold. + # Iterate and generate next frame using Euler method. + start = timer() + new_sites, DE = self.frames[i].iterate(self.step_size) + orig_step = self.energy(self.n, self.w, self.h, self.r, new_sites) + grad_mag = np.linalg.norm(DE) + end = timer() + + + if orig_step.energy < self.frames[i].energy: # If energy decreases. + if trial < 20: # Try increasing step size for 10 times. + factor = 1 + .1**trial + + test_step = self.energy(self.n, self.w, self.h, self.r, + self.frames[i].add_sites(self.step_size*factor*DE)) + # If increased step has less energy than original step. + if test_step.energy < orig_step.energy: + self.step_size *= factor + trial = max(2, trial-1) + grad_mag = np.linalg.norm(DE) + new_step = test_step + else: # Otherwise, increases trials, and use original. + trial += 1 + new_step = orig_step + else: + new_step = orig_step + else: # Step size too large, decrease and reset trial counter. + self.step_size /= (1 + .1**(trial-1)) + trial = 1 + new_sites, DE = self.frames[i].iterate(self.step_size) + new_step = self.energy(self.n, self.w, self.h, self.r, new_sites) + self.frames.append(new_step) + + self.step_size = max(10e-4, self.step_size) + i += 1 + + if(log and i % log_steps == 0): + print(f'Iteration: {i:05} | Energy: {self.frames[i].energy: .5f}' + \ + f' | Gradient: {grad_mag:.8f} | Step: {self.step_size: .5f} | ' + \ + f'Time: {end-start: .3f}', flush=True) + + +class Search(Simulation): + """ + Class for traversing to other equilibriums from an equilbrium. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param energy: [str] energy to use to calculate. + :param thres: [float] threshold for when to stop. + :param kernel_step: [float] size to step when jumping off kernel. + :param iter_step: [float] size to step by for iteration. + :param iter: [int] number of iterations + """ + + __slots__ = ['thres', 'iter_step', 'kernel_step', 'iter'] + + def __init__(self, n: int, w: float, h: float, r: float, energy: str, thres, + iter_step: float, kernel_step: float, iter: int): + super().__init__(n, w, h, r, energy) + self.thres, self.iter = thres, iter + self.kernel_step, self.iter_step = kernel_step, iter_step + + + def run(self, log, log_steps): + """ + Runs the simulation. + :param log: [bool] will log if True. + """ + + if log: + print(f'Travel - N = {self.n}, R = {self.r}, {self.w} X {self.h}', flush=True) + + dim = np.array([self.w, self.h]) + fixed = random.randint(0, self.n-1) + center = dim / 2 + new_sites = self.frames[0].site_arr + # Move fixed point to center. + for i in range(self.iter): + # Get to equilibrium. + sim = Flow(self.n, self.w, self.h, self.r, self.energy, self.thres, + self.iter_step) + sim.initialize(new_sites) + sim.run(log, log_steps) + + self.frames[i] = sim[-1] # Replace frame with equilibrium frame. + if log: + print(f'Equilibrium: {i:04}\n') + # Calculate kernel, and travel in some direction. + + hess = self.frames[i].hessian(10e-5) + ns = scipy.linalg.null_space(hess, 10e-4).T + + #self.frames[i].get_statistics() + eigs = np.sort(np.linalg.eig(hess)[0]) + self.frames[i].stats["eigs"] = eigs + + zero_eigs = np.count_nonzero(np.isclose(eigs, np.zeros((len(eigs),)), atol=1e-4)) + if zero_eigs != 2: + print("WARNING, 0 EIGS NOT 2", zero_eigs) + + if i == self.iter-1: + break + + if len(ns) <= 2: + new_sites = dim * np.random.random_sample((self.n, 2)) + else: + vec = ns[random.randint(0, len(ns)-1)] # Choose random vector + new_sites = self.frames[i].add_sites(self.kernel_step*vec.reshape((self.n, 2))) + + new_sites += (center - new_sites[fixed]) % dim # Offset + self.frames.append(None) + + +class Shrink(Simulation): + """ + Class for traversing to other equilibriums from an equilbrium. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param energy: [str] energy to use to calculate. + :param thres: [float] threshold for when to stop. + :param w_change: [float] percent to change w each iteration. + :param stop_w: [int] percentage at which to stop iterating. + :param step_size: [float] size to step by for iteration. + """ + + __slots__ = ['thres', 'w_change', 'stop_w', 'step_size'] + + def __init__(self, n: int, w: float, h: float, r: float, energy: str, thres: float, + step_size: float, w_change: float, stop_w: float): + super().__init__(n, w, h, r, energy) + self.thres, self.step_size = thres, step_size + self.w_change, self.stop_w = w*w_change, w*stop_w + + + def run(self, log, log_steps): + """ + Runs the simulation. + :param log: [bool] will log if True. + """ + if log: + print(f'Shrink - N = {self.n}, R = {self.r}, {self.w} X {self.h}', flush=True) + + while self.w >= self.stop_w: + # Get to equilibrium. + sim = Flow(self.n, self.w, self.h, self.r, self.energy, self.thres, + self.step_size) + sim.initialize(self.frames[-1].site_arr) + sim.run(log, log_steps) + + self.frames.append(sim[-1]) # Replace frame with equilibrium frame. + self.frames[-1].get_statistics() + if log: + print(f'Width: {self.w:.4f}\n') + + self.w -= self.w_change + + del self.frames[0] + +TravelEQ = Search + diff --git a/src/core.pyx b/src/core.pyx new file mode 100644 index 0000000..ebd109f --- /dev/null +++ b/src/core.pyx @@ -0,0 +1,385 @@ +import array, scipy.spatial, numpy as np +from cython.parallel import parallel, prange + +cimport numpy as np +from cpython cimport array +from libc.stdlib cimport malloc, realloc, calloc, free +from libc.math cimport isnan, NAN, pi as PI, M_PI_2 as PI_2, \ + sqrt, log, sin, cos, tan, acos, fabs +from packsim cimport INT_T, FLOAT_T, Init, IArray, FArray, BitSet, Vector2D, Matrix2x2, \ + VectorSelfOps, VectorCopyOps, MatrixSelfOps, MatrixCopyOps, \ + SiteCacheMap, EdgeCacheMap, VoronoiInfo, Site, HalfEdge + +#### Constants #### + +INT = np.int64 +FLOAT = np.float64 + +cdef FLOAT_T TAU = 2*PI +# In most cases, the amount of edges relevant to a gradient will +# not exceed this number. However, we assign a growth rate of 8 edges, +# when dynamically allocating. +cdef INT_T EDGE_ARR_SIZE = 32 + +cdef Init init +init.IArray, init.FArray, init.BitSet, init.Vector2D, init.Matrix2x2 = \ + init_iarray, init_farray, init_bitset, init_vector2d, init_matrix2x2 + +cdef VectorSelfOps VSO +cdef VectorCopyOps VCO +cdef MatrixSelfOps MSO +cdef MatrixCopyOps MCO + +VSO.neg, VSO.vadd, VSO.vsub, VSO.vmul, VSO.vdiv, VSO.sadd, VSO.ssub, VSO.smul, VSO.sdiv = \ + v_neg_s, v_vadd_s, v_vsub_s, v_vmul_s, v_vdiv_s, v_sadd_s, v_ssub_s, v_smul_s, v_sdiv_s +VSO.matmul = v_matmul_s + +VCO.neg, VCO.vadd, VCO.vsub, VCO.vmul, VCO.vdiv, VCO.sadd, VCO.ssub, VCO.smul, VCO.sdiv = \ + v_neg_c, v_vadd_c, v_vsub_c, v_vmul_c, v_vdiv_c, v_sadd_c, v_ssub_c, v_smul_c, v_sdiv_c +VCO.matmul = v_matmul_c + +MSO.neg, MSO.madd, MSO.msub, MSO.mmul, MSO.mdiv, MSO.sadd, MSO.ssub, MSO.smul, MSO.sdiv = \ + m_neg_s, m_madd_s, m_msub_s, m_mmul_s, m_mdiv_s, m_sadd_s, m_ssub_s, m_smul_s, m_sdiv_s +MSO.matmul = m_matmul_s + +MCO.neg, MCO.madd, MCO.msub, MCO.mmul, MCO.mdiv, MCO.sadd, MCO.ssub, MCO.smul, MCO.sdiv = \ + m_neg_c, m_madd_c, m_msub_c, m_mmul_c, m_mdiv_c, m_sadd_c, m_ssub_c, m_smul_c, m_sdiv_c +MCO.matmul = m_matmul_c + +cdef Vector2D NAN_VECTOR = init.Vector2D(NAN, NAN) +cdef Matrix2x2 NAN_MATRIX = init.Matrix2x2(NAN, NAN, NAN, NAN) + +cdef FLOAT_T[18] SYMM = [0,0, 1,0, 1,1, 0,1, -1,1, -1,0, -1,-1, 0,-1, 1,-1] +cdef Matrix2x2 R = init.Matrix2x2(0, -1, 1, 0) + +""" +If bound checking is desired, uncomment out ..._valid_indices functions. +""" + +#### IArray Methods #### + +cdef inline IArray init_iarray(INT_T* arr, (INT_T, INT_T) shape) nogil: + cdef IArray iarray + iarray.arr, iarray.shape = arr, shape + + iarray.get = iarray_get + iarray.set = iarray_set + return iarray + +cdef inline bint iarray_valid_indices(IArray* self, (INT_T, INT_T) index) nogil: + if index[0] > self.shape[0] or index[1] > self.shape[1]: + with gil: + raise IndexError(f"Index out of range for IArray with shape {self.shape}") + +cdef inline INT_T iarray_get(IArray* self, (INT_T, INT_T) index) nogil: + #iarray_valid_indices(&self, index) + return self.arr[index[0]*self.shape[1] + index[1]] + +cdef inline void iarray_set(IArray* self, (INT_T, INT_T) index, INT_T val) nogil: + #iarray_valid_indices(&self, index) + self.arr[index[0]*self.shape[1] + index[1]] = val + + +#### FArray Methods #### + +cdef inline FArray init_farray(FLOAT_T* arr, (INT_T, INT_T) shape) nogil: + cdef FArray farray + farray.arr, farray.shape = arr, shape + + farray.get = farray_get + farray.set = farray_set + return farray + +cdef inline bint farray_valid_indices(FArray* self, (INT_T, INT_T) index) nogil: + if index[0] > self.shape[0] or index[1] > self.shape[1]: + with gil: + raise IndexError(f"Index out of range for FArray with shape {self.shape}") + +cdef inline FLOAT_T farray_get(FArray* self, (INT_T, INT_T) index) nogil: + #iarray_valid_indices(&self, index) + return self.arr[index[0]*self.shape[1] + index[1]] + +cdef inline void farray_set(FArray* self, (INT_T, INT_T) index, FLOAT_T val) nogil: + #iarray_valid_indices(&self, index) + self.arr[index[0]*self.shape[1] + index[1]] = val + + +#### IList Methods #### + +# cdef inline IList init_ilist() nogil: +# cdef IList ilist +# ilist.size = EDGE_ARR_SIZE +# ilist.length = 0 +# ilist.data = malloc(self.size * sizeof(INT_T)) + +# ilist.append, ilist.free = ilist_append, ilist_free + +# return ilist + +# cdef inline void ilist_append(IList* self, INT_T) nogil: +# if self.size == self.length: +# ilist.data = realloc((self.size+8) * sizeof(INT_T)) +# self.size += 8 + +# self.data[self.length] == INT_T +# self.length += 1 + +# cdef inline void ilist_free(IList* self) nogil: +# free(self.data) + +#### BitSet Methods #### + +cdef inline BitSet init_bitset(INT_T elements) nogil: + cdef BitSet bitset + bitset.bits = calloc(((elements/sizeof(INT_T))+1), sizeof(INT_T)) + + bitset.add, bitset.free = bitset_add, bitset_free + return bitset + +cdef inline bint bitset_add(BitSet* self, INT_T val) nogil: + cdef INT_T index, rel_index, old + index = val/sizeof(INT_T) + old = self.bits[index] + rel_index = val - index*sizeof(INT_T) + + self.bits[index] = (1 << rel_index) | old # New value. + + return old == self.bits[index] # Means 1 was already there. + +cdef inline void bitset_free(BitSet* self) nogil: + free(self.bits) + +#### Vector2D Methods #### +""" +Prefix 'v' stands for vector, element by element operation. +Prefix 's' stands for scalar, broadcasted operation. +Suffix 'w' stands for write, overwriting current value. +Suffix 'n' stands for new, copying to a new location. + +While it's possible to chain 'new' operations, when possible, +avoid this, so fewer objects are needed. +""" + +cdef inline Vector2D init_vector2d(FLOAT_T x, FLOAT_T y) nogil: + cdef Vector2D vec + vec.x, vec.y = x, y + vec.self, vec.copy = VSO, VCO + + vec.equals, vec.rot, vec.dot, vec.mag = v_equals, rot, dot, mag + + return vec + + +cdef inline bint v_equals(Vector2D* self, Vector2D w) nogil: + return ((self.x == w.x) and (self.y == w.y)) + +cdef inline Vector2D* v_neg_s(Vector2D* self) nogil: + self.x = -self.x + self.y = -self.y + return self + +cdef inline Vector2D* v_vadd_s(Vector2D* self, Vector2D w) nogil: + self.x += w.x + self.y += w.y + return self + +cdef inline Vector2D* v_vsub_s(Vector2D* self, Vector2D w) nogil: + self.x -= w.x + self.y -= w.y + return self + +cdef inline Vector2D* v_vmul_s(Vector2D* self, Vector2D w) nogil: + self.x *= w.x + self.y *= w.y + return self + +cdef inline Vector2D* v_vdiv_s(Vector2D* self, Vector2D w) nogil: + self.x /= w.x + self.y /= w.y + return self + +cdef inline Vector2D* v_sadd_s(Vector2D* self, FLOAT_T s) nogil: + self.x += s + self.y += s + return self + +cdef inline Vector2D* v_ssub_s(Vector2D* self, FLOAT_T s) nogil: + self.x -= s + self.y -= s + return self + +cdef inline Vector2D* v_smul_s(Vector2D* self, FLOAT_T s) nogil: + self.x *= s + self.y *= s + return self + +cdef inline Vector2D* v_sdiv_s(Vector2D* self, FLOAT_T s) nogil: + self.x /= s + self.y /= s + return self + +cdef inline Vector2D* v_matmul_s(Vector2D* self, Matrix2x2 m) nogil: + self.x, self.y = self.x*m.a + self.y*m.c, self.x*m.b + self.y*m.d + return self + +cdef inline Vector2D v_neg_c(Vector2D* self) nogil: + return init.Vector2D(-self.x, -self.y) + +cdef inline Vector2D v_vadd_c(Vector2D* self, Vector2D w) nogil: + return init.Vector2D(self.x + w.x, self.y + w.y) + +cdef inline Vector2D v_vsub_c(Vector2D* self, Vector2D w) nogil: + return init.Vector2D(self.x - w.x, self.y - w.y) + +cdef inline Vector2D v_vmul_c(Vector2D* self, Vector2D w) nogil: + return init.Vector2D(self.x * w.x, self.y * w.y) + +cdef inline Vector2D v_vdiv_c(Vector2D* self, Vector2D w) nogil: + return init.Vector2D(self.x / w.x, self.y / w.y) + +cdef inline Vector2D v_sadd_c(Vector2D* self, FLOAT_T s) nogil: + return init.Vector2D(self.x + s, self.y + s) + +cdef inline Vector2D v_ssub_c(Vector2D* self, FLOAT_T s) nogil: + return init.Vector2D(self.x + s, self.y + s) + +cdef inline Vector2D v_smul_c(Vector2D* self, FLOAT_T s) nogil: + return init.Vector2D(self.x * s, self.y * s) + +cdef inline Vector2D v_sdiv_c(Vector2D* self, FLOAT_T s) nogil: + return init.Vector2D(self.x / s, self.y / s) + +cdef inline Vector2D v_matmul_c(Vector2D* self, Matrix2x2 m) nogil: + return init.Vector2D( + self.x*m.a + self.y*m.c, self.x*m.b + self.y*m.d + ) + +cdef inline Vector2D rot(Vector2D* self) nogil: + return init.Vector2D(-self.y, self.x) + +cdef inline FLOAT_T dot(Vector2D* self, Vector2D w) nogil: + return self.x*w.x + self.y*w.y + +cdef inline FLOAT_T mag(Vector2D* self) nogil: + return sqrt((self.x*self.x + self.y*self.y)) + + +#### Matrix2x2 Methods #### + +cdef inline Matrix2x2 init_matrix2x2(FLOAT_T a, FLOAT_T b, FLOAT_T c, FLOAT_T d) nogil: + cdef Matrix2x2 matrix + matrix.a, matrix.b, matrix.c, matrix.d = a, b, c, d + matrix.self, matrix.copy = MSO, MCO + + matrix.equals, matrix.vecmul = m_equals, m_vecmul + + return matrix + +cdef inline bint m_equals(Matrix2x2* self, Matrix2x2 m) nogil: + return ( + (self.a == m.a) and (self.b == m.b) and (self.c == m.c) and (self.d == m.d) + ) + +cdef inline Vector2D m_vecmul(Matrix2x2* self, Vector2D v) nogil: + return init.Vector2D( + self.a*v.x + self.b*v.y, self.c*v.x + self.d*v.y + ) + +cdef inline Matrix2x2* m_neg_s(Matrix2x2* self) nogil: + self.a, self.b, self.c, self.d = -self.a, -self.b, -self.c, -self.d + return self + +cdef inline Matrix2x2* m_madd_s(Matrix2x2* self, Matrix2x2 m) nogil: + self.a += m.a + self.b += m.b + self.c += m.c + self.d += m.d + return self + +cdef inline Matrix2x2* m_msub_s(Matrix2x2* self, Matrix2x2 m) nogil: + self.a -= m.a + self.b -= m.b + self.c -= m.c + self.d -= m.d + return self + +cdef inline Matrix2x2* m_mmul_s(Matrix2x2* self, Matrix2x2 m) nogil: + self.a *= m.a + self.b *= m.b + self.c *= m.c + self.d *= m.d + return self + +cdef inline Matrix2x2* m_mdiv_s(Matrix2x2* self, Matrix2x2 m) nogil: + self.a /= m.a + self.b /= m.b + self.c /= m.c + self.d /= m.d + return self + +cdef inline Matrix2x2* m_sadd_s(Matrix2x2* self, FLOAT_T s) nogil: + self.a += s + self.b += s + self.c += s + self.d += s + return self + +cdef inline Matrix2x2* m_ssub_s(Matrix2x2* self, FLOAT_T s) nogil: + self.a -= s + self.b -= s + self.c -= s + self.d -= s + return self + +cdef inline Matrix2x2* m_smul_s(Matrix2x2* self, FLOAT_T s) nogil: + self.a *= s + self.b *= s + self.c *= s + self.d *= s + return self + +cdef inline Matrix2x2* m_sdiv_s(Matrix2x2* self, FLOAT_T s) nogil: + self.a /= s + self.b /= s + self.c /= s + self.d /= s + return self + +cdef inline Matrix2x2* m_matmul_s(Matrix2x2* self, Matrix2x2 m) nogil: + self.a, self.b, self.c, self.d = \ + self.a*m.a + self.b*m.c, self.a*m.b + self.b*m.d, \ + self.c*m.a + self.d*m.c, self.c*m.b + self.d*m.d + return self + +cdef inline Matrix2x2 m_neg_c(Matrix2x2* self) nogil: + return init.Matrix2x2(-self.a, -self.b, -self.c, -self.d) + +cdef inline Matrix2x2 m_madd_c(Matrix2x2* self, Matrix2x2 m) nogil: + return init.Matrix2x2(self.a+m.a, self.b+m.b, self.c+m.c, self.d+m.d) + +cdef inline Matrix2x2 m_msub_c(Matrix2x2* self, Matrix2x2 m) nogil: + return init.Matrix2x2(self.a-m.a, self.b-m.b, self.c-m.c, self.d-m.d) + +cdef inline Matrix2x2 m_mmul_c(Matrix2x2* self, Matrix2x2 m) nogil: + return init.Matrix2x2(self.a*m.a, self.b*m.b, self.c*m.c, self.d*m.d) + +cdef inline Matrix2x2 m_mdiv_c(Matrix2x2* self, Matrix2x2 m) nogil: + return init.Matrix2x2(self.a/m.a, self.b/m.b, self.c/m.c, self.d/m.d) + +cdef inline Matrix2x2 m_sadd_c(Matrix2x2* self, FLOAT_T s) nogil: + return init.Matrix2x2(self.a+s, self.b+s, self.c+s, self.d+s) + +cdef inline Matrix2x2 m_ssub_c(Matrix2x2* self, FLOAT_T s) nogil: + return init.Matrix2x2(self.a-s, self.b-s, self.c-s, self.d-s) + +cdef inline Matrix2x2 m_smul_c(Matrix2x2* self, FLOAT_T s) nogil: + return init.Matrix2x2(self.a*s, self.b*s, self.c*s, self.d*s) + +cdef inline Matrix2x2 m_sdiv_c(Matrix2x2* self, FLOAT_T s) nogil: + return init.Matrix2x2(self.a/s, self.b/s, self.c/s, self.d/s) + +cdef inline Matrix2x2 m_matmul_c(Matrix2x2* self, Matrix2x2 m) nogil: + return init.Matrix2x2( + self.a*m.a + self.b*m.c, self.a*m.b + self.b*m.d, + self.c*m.a + self.d*m.c, self.c*m.b + self.d*m.d + ) \ No newline at end of file diff --git a/src/energy.pyx b/src/energy.pyx new file mode 100644 index 0000000..526e141 --- /dev/null +++ b/src/energy.pyx @@ -0,0 +1,343 @@ +cdef class AreaEnergy(VoronoiContainer): + """ + Class for formulas relevant to the Area energy. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param sites: [np.ndarray] collection of sites. + """ + def __init__(AreaEnergy self, INT_T n, FLOAT_T w, FLOAT_T h, FLOAT_T r, + np.ndarray[FLOAT_T, ndim=2] site_arr): + self.edge_cache_map = &AREA_EDGE_CACHE_MAP + self.energy = 0.0 + + super().__init__(n, w, h, r, site_arr) + self.minimum = (n)*(w*h/(n)-PI*r**2)**2 + + + cdef void precompute(self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + cdef Site xi + cdef HalfEdge em, e, ep + cdef Vector2D vdiff + cdef FLOAT_T A = PI*self.r**2 + cdef FLOAT_T energy = 0 + + cdef INT_T i, j + for i in prange(self.sites.shape[0], nogil=True): + xi = init.Site(i, &info) + e = xi.edge(&xi) + xi.cache.energy(&xi, + (xi.cache.area(&xi, NAN) - A)**2 + ) + if i < self.n: + energy += xi.cache.energy(&xi, NAN) + + for j in prange(xi.edge_num(&xi)): + em, ep = e.prev(&e), e.next(&e) + vdiff = em.origin(&em) + vdiff.self.vsub(&vdiff, ep.origin(&ep)) + e.cache.dVdv(&e, R.vecmul(&R, vdiff)) + e.cache.H(&e, VoronoiContainer.calc_H(em, e)) + + e = e.next(&e) + + self.energy = energy + + + cdef void calc_grad(self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + cdef Site xi, xf + cdef HalfEdge e, f + cdef Vector2D dedxi_p + cdef BitSet edge_set + + cdef INT_T num_edges = self.edges.shape[0] + cdef FLOAT_T A = PI*self.r**2 + + cdef FLOAT_T [:, ::1] dedx = np.zeros((self.n, 2), dtype=FLOAT) + + cdef INT_T i, j + for i in prange(self.n, nogil=True): + xi = init.Site(i, &info) + e = xi.edge(&xi) + edge_set = init.BitSet(num_edges) + for j in prange(xi.edge_num(&xi)): # Looping through site edges. + f = e + while True: # Circling this vertex. + if not edge_set.add(&edge_set, f.arr_index): + xf = f.face(&f) + dedxi_p = f.cache.dVdv(&f, NAN_VECTOR) #dVdv + dedxi_p.self.smul(&dedxi_p, xf.cache.area(&xf, NAN) - A) + dedxi_p.self.matmul(&dedxi_p, e.cache.H(&e, NAN_MATRIX)) + dedx[i][0] -= dedxi_p.x + dedx[i][1] -= dedxi_p.y + + f = f.twin(&f) + f = f.next(&f) + if f.arr_index == e.arr_index: + break + + e = e.next(&e) + edge_set.free(&edge_set) + self.grad = dedx + + +cdef class RadialALEnergy(VoronoiContainer): + """ + Class for formulas relevant to the Area energy. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param sites: [np.ndarray] collection of sites. + """ + def __init__(AreaEnergy self, INT_T n, FLOAT_T w, FLOAT_T h, FLOAT_T r, + np.ndarray[FLOAT_T, ndim=2] site_arr): + #self.edge_cache_map = &AREA_EDGE_CACHE_MAP + self.energy = 0.0 + + super().__init__(n, w, h, r, site_arr) + + + cdef void precompute(self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + pass + + + cdef void calc_grad(self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + pass + + +cdef class RadialTEnergy(VoronoiContainer): + """ + Class for formulas relevant to the Area energy. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param sites: [np.ndarray] collection of sites. + """ + def __init__(AreaEnergy self, INT_T n, FLOAT_T w, FLOAT_T h, FLOAT_T r, + np.ndarray[FLOAT_T, ndim=2] site_arr): + self.edge_cache_map = &RADIALT_EDGE_CACHE_MAP + self.energy = 0.0 + + super().__init__(n, w, h, r, site_arr) + + + cdef void precompute(self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + cdef Site xi + cdef HalfEdge em, e + cdef Vector2D Rnla, i2p + + # All energy has a 2pir_0 term. + cdef FLOAT_T [:] site_energy = np.full(self.sites.shape[0], TAU*self.r**2) + cdef FLOAT_T [:] avg_radii = np.zeros(self.sites.shape[0]) + cdef FLOAT_T energy, r0, t, tp, B, lntan, cot, cscm, cscp, FA, int_r2d, int_rd + energy, r0 = 0, self.r + + cdef INT_T i, j + for i in prange(self.sites.shape[0], nogil=True): + xi = init.Site(i, &info) + e = xi.edge(&xi) + for j in prange(xi.edge_num(&xi)): + em = e.prev(&e) + e.cache.H(&e, VoronoiContainer.calc_H(em, e)) + t = Calc.phi(e) + + e.cache.phi(&e, t) + Rnla = e.cache.la(&e, NAN_VECTOR) + Rnla.self.neg(&Rnla) + Rnla = Rnla.rot(&Rnla) + + if Rnla.x < 0: + e.cache.B(&e, -acos((Rnla.y/e.cache.la_mag(&e, NAN)))) + else: + e.cache.B(&e, acos((Rnla.y/e.cache.la_mag(&e, NAN)))) + + i2p = Calc.I2(e, r0, t) + e.cache.i2p(&e, i2p) + e = e.next(&e) + + # For looping again to calculate integrals. + em = xi.edge(&xi) + for j in prange(xi.edge_num(&xi)): + e = em.next(&em) + B = em.cache.B(&em, NAN) + t, tp = em.cache.phi(&em, NAN), e.cache.phi(&e, NAN) + + lntan = (log(fabs(tan(((tp+B)/2))))) - \ + (log(fabs(tan(((t+B)/2))))) + + cot = -1/((tan((tp+B)))) + \ + 1/((tan((t+B)))) + + cscm, cscp = 1/((sin((t+B)))), \ + 1/((sin((tp+B)))) + + em.cache.lntan(&em, lntan) + em.cache.cot(&em, cot) + em.cache.csc(&em, cscp-cscm) + em.cache.csc2(&em, cscp**2 - cscm**2) + FA = (em.cache.F(&em, NAN)/em.cache.la_mag(&em, NAN)) + + int_r2d, int_rd = FA**2*cot, FA*lntan + + avg_radii[i] += int_rd + site_energy[i] += int_r2d - 2*r0*int_rd + + em = em.next(&em) + + xi.cache.avg_radius(&xi, avg_radii[i]/TAU) + xi.cache.energy(&xi, site_energy[i]) + if i < self.n: + energy += site_energy[i] + + self.energy = energy + + cdef void calc_grad(self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + cdef Site xi + cdef HalfEdge e, fm, f + cdef Vector2D dedxi_p + cdef BitSet edge_set + + cdef INT_T num_edges = self.edges.shape[0] + cdef FLOAT_T r0 = self.r + + cdef FLOAT_T [:, ::1] dedx = np.zeros((self.n, 2), dtype=FLOAT) + + cdef INT_T i, j + for i in prange(self.n, nogil=True): + xi = init.Site(i, &info) + e = xi.edge(&xi) + edge_set = init.BitSet(num_edges) + + for j in prange(xi.edge_num(&xi)): # Looping through site edges. + f = e + while True: # Circling this vertex. + fm = f.prev(&f) + if not edge_set.add(&edge_set, f.arr_index): + dedxi_p = Calc.radialt_edge_grad(f, xi, r0) + dedx[i][0] -= dedxi_p.x + dedx[i][1] -= dedxi_p.y + + if not edge_set.add(&edge_set, fm.arr_index): + dedxi_p = Calc.radialt_edge_grad(fm, xi, r0) + dedx[i][0] -= dedxi_p.x + dedx[i][1] -= dedxi_p.y + + + f = f.twin(&f) + f = f.next(&f) + + if f.arr_index == e.arr_index: + break + + e = e.next(&e) + edge_set.free(&edge_set) + self.grad = dedx + + +cdef class Calc: + @staticmethod + cdef inline FLOAT_T phi(HalfEdge e) nogil: + cdef Vector2D da = e.cache.da(&e, NAN_VECTOR) + cdef FLOAT_T angle = acos((da.x/e.cache.da_mag(&e, NAN))) + return angle if da.y >= 0 else TAU - angle + + @staticmethod + cdef inline Vector2D I2(HalfEdge e, FLOAT_T r0, FLOAT_T t) nogil: + cdef Vector2D Rda = e.cache.da(&e, NAN_VECTOR) + Rda = Rda.rot(&Rda) + + cdef Vector2D Rcircle = init.Vector2D( + -sin(t), cos(t) + ) + cdef FLOAT_T p = e.cache.F(&e, NAN) / Rcircle.dot(&Rcircle, e.cache.la(&e, NAN_VECTOR)) + p = ((p - r0)**2)/(Rda.dot(&Rda, Rda)) + Rda.self.smul(&Rda, p) + + return Rda + + @staticmethod + cdef Vector2D radialt_edge_grad(HalfEdge e, Site xi, FLOAT_T r0) nogil: + cdef Site xe + cdef HalfEdge ep + cdef Vector2D Rda, i2ps, fp, gterms, q + cdef Matrix2x2 ha, hap, hdiff + + cdef FLOAT_T t1, t2, lntan, cot, csc, csc2, sinB, cosB, sinBp, cosBp, F, A, B + + xe = e.face(&e) + ep = e.next(&e) + F, A, B = e.cache.F(&e, NAN), e.cache.la_mag(&e, NAN), e.cache.B(&e, NAN) + t1, t2 = e.cache.phi(&e, NAN), ep.cache.phi(&ep, NAN) + lntan, cot, csc, csc2 = e.cache.lntan(&e, NAN), e.cache.cot(&e, NAN), \ + e.cache.csc(&e, NAN), e.cache.csc2(&e, NAN) + + sinB, cosB = (sin((B))), (cos((B))) + sinBp, cosBp = (sin((B-PI_2))), \ + (cos((B-PI_2))) + + + + ha, hap = e.get_H(&e, xi), ep.get_H(&ep, xi) + hdiff = hap.copy.msub(&hap, ha) + # If edge is part of differentiated site. + if xe.index(&xe) == xi.index(&xi): + ha.self.msub(&ha, init.Matrix2x2(1.0, 0.0, 0.0, 1.0)) + hap.self.msub(&hap, init.Matrix2x2(1.0, 0.0, 0.0, 1.0)) + + i2ps = ep.cache.i2p(&ep, NAN_VECTOR) + i2ps.self.matmul(&i2ps, hap) + + q = e.cache.i2p(&e, NAN_VECTOR) + q.self.matmul(&q, ha) + + i2ps.self.vsub(&i2ps, q) + + Rda = e.cache.da(&e, NAN_VECTOR) + Rda = Rda.rot(&Rda) + + fp = e.cache.la(&e, NAN_VECTOR) + fp.self.matmul(&fp, R.copy.matmul(&R, ha)) + fp.self.vadd(&fp, Rda.copy.matmul(&Rda, hdiff)) + fp.self.smul(&fp, (F/A**2)*cot - (r0/A)*lntan) + + gterms = init.Vector2D( + cosBp*lntan + sinBp*csc, + cosB*lntan + sinB*csc + ) + gterms.self.smul(>erms, r0*F/A**2) + + q = init.Vector2D( + 0.5*sinBp*csc2 + cosBp*cot, + 0.5*sinB*csc2 + cosB*cot + ) + q.self.smul(&q, -F**2/A**3) + + gterms.self.vadd(>erms, q) + gterms = gterms.rot(>erms) + gterms.self.matmul(>erms, hdiff) + + fp.self.vadd(&fp, gterms) + fp.self.smul(&fp, 2) + + return i2ps.copy.vadd(&i2ps, fp) \ No newline at end of file diff --git a/src/packsim.pxd b/src/packsim.pxd new file mode 100644 index 0000000..9d3d546 --- /dev/null +++ b/src/packsim.pxd @@ -0,0 +1,255 @@ +cimport numpy as np + +# Cython Types. +ctypedef np.int64_t INT_T +ctypedef np.float64_t FLOAT_T + +# Stores initialization functions. +cdef struct Init: + IArray (*IArray)(INT_T*, (INT_T, INT_T)) nogil + FArray (*FArray)(FLOAT_T*, (INT_T, INT_T)) nogil + #IList (*IList)() nogil + BitSet (*BitSet)(INT_T) nogil + Vector2D (*Vector2D)(FLOAT_T, FLOAT_T) nogil + Matrix2x2 (*Matrix2x2)(FLOAT_T, FLOAT_T, FLOAT_T, FLOAT_T) nogil + SiteCacheMap (*SiteCacheMap)(INT_T, INT_T, INT_T, INT_T, INT_T) nogil + EdgeCacheMap (*EdgeCacheMap)(INT_T, INT_T, INT_T, INT_T, INT_T, INT_T, INT_T, INT_T, + INT_T, INT_T, INT_T, INT_T, INT_T, INT_T, INT_T, INT_T) nogil + VoronoiInfo (*VoronoiInfo)(INT_T [:, ::1], INT_T[:, ::1], FLOAT_T[:, ::1], + FLOAT_T[:, ::1], FLOAT_T[:, ::1], FLOAT_T[:, ::1], + EdgeCacheMap*) nogil + Site (*Site)(INT_T, VoronoiInfo*) nogil + HalfEdge (*HalfEdge)(INT_T, VoronoiInfo*) nogil + +# Integer Array psuedo-class for continguous arrays. +cdef struct IArray: + INT_T* arr + (INT_T, INT_T) shape + + INT_T (*get)(IArray*, (INT_T, INT_T)) nogil + void (*set)(IArray*, (INT_T, INT_T), INT_T) nogil + +# Float Array psuedo-class for continguous arrays. +ctypedef struct FArray: + FLOAT_T* arr + (INT_T, INT_T) shape + + FLOAT_T (*get)(FArray*, (INT_T, INT_T)) nogil + void (*set)(FArray*, (INT_T, INT_T), FLOAT_T) nogil + +# Simple append-only dynamic integer array. +# ctypedef struct IList: +# INT_T* data +# INT_T size, length + +# void (*append)(IList*, INT_T) nogil +# void (*free)(IList*) nogil + +# Uses an array of bits to determine if value in set. +ctypedef struct BitSet: + INT_T* bits + + bint (*add)(BitSet*, INT_T) nogil + void (*free)(BitSet*) nogil + +# Psuedo-operator definitions. +ctypedef Vector2D* (*VectorSelfVecOp)(Vector2D*, Vector2D) nogil +ctypedef Vector2D (*VectorCopyVecOp)(Vector2D*, Vector2D) nogil +ctypedef Vector2D* (*VectorSelfSclOp)(Vector2D*, FLOAT_T) nogil +ctypedef Vector2D (*VectorCopySclOp)(Vector2D*, FLOAT_T) nogil + +ctypedef Matrix2x2* (*MatrixSelfMatOp)(Matrix2x2*, Matrix2x2) nogil +ctypedef Matrix2x2 (*MatrixCopyMatOp)(Matrix2x2*, Matrix2x2) nogil +ctypedef Matrix2x2* (*MatrixSelfSclOp)(Matrix2x2*, FLOAT_T) nogil +ctypedef Matrix2x2 (*MatrixCopySclOp)(Matrix2x2*, FLOAT_T) nogil + + +ctypedef struct VectorSelfOps: + Vector2D* (*neg)(Vector2D*) nogil + + VectorSelfVecOp vadd + VectorSelfVecOp vsub + VectorSelfVecOp vmul + VectorSelfVecOp vdiv + Vector2D* (*matmul)(Vector2D*, Matrix2x2) nogil + + VectorSelfSclOp sadd + VectorSelfSclOp ssub + VectorSelfSclOp smul + VectorSelfSclOp sdiv + + +ctypedef struct VectorCopyOps: + Vector2D (*neg)(Vector2D*) nogil + + VectorCopyVecOp vadd + VectorCopyVecOp vsub + VectorCopyVecOp vmul + VectorCopyVecOp vdiv + Vector2D (*matmul)(Vector2D*, Matrix2x2) nogil + + VectorCopySclOp sadd + VectorCopySclOp ssub + VectorCopySclOp smul + VectorCopySclOp sdiv + + +ctypedef struct MatrixSelfOps: + Matrix2x2* (*neg)(Matrix2x2*) nogil + + MatrixSelfMatOp madd + MatrixSelfMatOp msub + MatrixSelfMatOp mmul + MatrixSelfMatOp mdiv + MatrixSelfMatOp matmul + + MatrixSelfSclOp sadd + MatrixSelfSclOp ssub + MatrixSelfSclOp smul + MatrixSelfSclOp sdiv + + +ctypedef struct MatrixCopyOps: + Matrix2x2 (*neg)(Matrix2x2*) nogil + + MatrixCopyMatOp madd + MatrixCopyMatOp msub + MatrixCopyMatOp mmul + MatrixCopyMatOp mdiv + MatrixCopyMatOp matmul + + MatrixCopySclOp sadd + MatrixCopySclOp ssub + MatrixCopySclOp smul + MatrixCopySclOp sdiv + +# Psuedo-class for a 2-dimensional vector. No orientation. +ctypedef struct Vector2D: + FLOAT_T x, y + VectorSelfOps self + VectorCopyOps copy + + bint (*equals)(Vector2D*, Vector2D) nogil + Vector2D (*rot)(Vector2D*) nogil + FLOAT_T (*dot)(Vector2D*, Vector2D) nogil + FLOAT_T (*mag)(Vector2D*) nogil + +# Psuedo-class for a 2x2 matrix. +ctypedef struct Matrix2x2: + FLOAT_T a, b, c, d + MatrixSelfOps self + MatrixCopyOps copy + + bint (*equals)(Matrix2x2*, Matrix2x2) nogil + Vector2D (*vecmul)(Matrix2x2*, Vector2D) nogil + +# Psuedo-class that handles caching for sites. +ctypedef struct SiteCacheMap: + INT_T iarea, iperim, iisoparam, ienergy, iavg_radius + + FLOAT_T (*area)(Site*, FLOAT_T) nogil + FLOAT_T (*perim)(Site*, FLOAT_T) nogil + FLOAT_T (*isoparam)(Site*, FLOAT_T) nogil + FLOAT_T (*energy)(Site*, FLOAT_T) nogil + FLOAT_T (*avg_radius)(Site*, FLOAT_T) nogil + +# Psuedo-class that handles caching for edges. +ctypedef struct EdgeCacheMap: + INT_T iH, ila, ila_mag, ida, ida_mag, ixij, idVdv, iphi, iB, iF, ii2p,\ + ilntan, icot, icsc, icsc2, size + + Matrix2x2 (*H)(HalfEdge*, Matrix2x2) nogil + + Vector2D (*la)(HalfEdge*, Vector2D) nogil + Vector2D (*da)(HalfEdge*, Vector2D) nogil + Vector2D (*xij)(HalfEdge*, Vector2D) nogil + Vector2D (*dVdv)(HalfEdge*, Vector2D) nogil + Vector2D (*i2p)(HalfEdge*, Vector2D) nogil + + FLOAT_T (*la_mag)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*da_mag)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*phi)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*B)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*F)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*lntan)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*cot)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*csc)(HalfEdge*, FLOAT_T) nogil + FLOAT_T (*csc2)(HalfEdge*, FLOAT_T) nogil + +# Psuedo-class to just contain all pertaining info for sites and edges. +ctypedef struct VoronoiInfo: + IArray sites, edges + FArray points, vertices, site_cache, edge_cache + EdgeCacheMap* edge_cache_map + +# Psuedo-class for a Site. +ctypedef struct Site: + INT_T arr_index + VoronoiInfo* info + SiteCacheMap* cache + + INT_T (*index)(Site*) nogil + Vector2D (*vec)(Site*) nogil + HalfEdge (*edge)(Site*) nogil + INT_T (*edge_num)(Site*) nogil + +# Psuedo-class for an HalfEdge. +ctypedef struct HalfEdge: + INT_T orig_arr_index, arr_index + VoronoiInfo* info + EdgeCacheMap* cache + + INT_T (*origin_index)(HalfEdge*) nogil + Vector2D (*origin)(HalfEdge*) nogil + Site (*face)(HalfEdge*) nogil + HalfEdge (*next)(HalfEdge*) nogil + HalfEdge (*prev)(HalfEdge*) nogil + HalfEdge (*twin)(HalfEdge*) nogil + Matrix2x2 (*get_H)(HalfEdge*, Site) nogil + + +cdef class VoronoiContainer: + cdef readonly INT_T n + cdef readonly FLOAT_T w, h, r, energy + cdef FLOAT_T [2] dim + cdef FLOAT_T [:, ::1] points, vertices, site_cache, edge_cache, grad + cdef INT_T [:, ::1] sites, edges + cdef EdgeCacheMap* edge_cache_map + cdef dict __dict__ + + cdef void calculate_voronoi(VoronoiContainer self, + np.ndarray[FLOAT_T, ndim=2] site_arr) except * + cdef void generate_dcel(VoronoiContainer self) except * + cdef void common_cache(VoronoiContainer self) except * + cdef void precompute(self) except * + cdef void calc_grad(self) except * + cdef void get_statistics(VoronoiContainer self) except * + + @staticmethod + cdef inline Matrix2x2 calc_H(HalfEdge, HalfEdge) nogil + @staticmethod + cdef inline bint sign(FLOAT_T [::1], FLOAT_T [::1], FLOAT_T [::1]) + + +cdef class AreaEnergy(VoronoiContainer): + cdef readonly FLOAT_T minimum + cdef void precompute(self) except * + cdef void calc_grad(self) except * + + +cdef class RadialALEnergy(VoronoiContainer): + cdef void precompute(self) except * + cdef void calc_grad(self) except * + + +cdef class RadialTEnergy(VoronoiContainer): + cdef void precompute(self) except * + cdef void calc_grad(self) except * + +cdef class Calc: + @staticmethod + cdef inline FLOAT_T phi(HalfEdge) nogil + @staticmethod + cdef inline Vector2D I2(HalfEdge, FLOAT_T, FLOAT_T) nogil + @staticmethod + cdef Vector2D radialt_edge_grad(HalfEdge, Site, FLOAT_T) nogil \ No newline at end of file diff --git a/src/packsim.pyx b/src/packsim.pyx new file mode 100644 index 0000000..ab12540 --- /dev/null +++ b/src/packsim.pyx @@ -0,0 +1,3 @@ +include "core.pyx" +include "voronoi_dcel.pyx" +include "energy.pyx" \ No newline at end of file diff --git a/src/setup.py b/src/setup.py new file mode 100644 index 0000000..0f97c87 --- /dev/null +++ b/src/setup.py @@ -0,0 +1,22 @@ +from setuptools import Extension, setup +from Cython.Build import cythonize +import numpy + +MODULE_NAME = "packsim" + +ext_modules = [ + Extension( + MODULE_NAME, + [f'{MODULE_NAME}.pyx'], + extra_compile_args=['-fopenmp'], + extra_link_args=['-fopenmp'] + ) +] + +setup( + name=MODULE_NAME, + ext_modules = cythonize(ext_modules, compiler_directives={ + 'language_level': 3, 'boundscheck' : False, 'wraparound': False, 'cdivision' : True + }), + include_dirs = [numpy.get_include()] +) \ No newline at end of file diff --git a/src/voronoi_dcel.pyx b/src/voronoi_dcel.pyx new file mode 100644 index 0000000..5358f5d --- /dev/null +++ b/src/voronoi_dcel.pyx @@ -0,0 +1,722 @@ +from packsim cimport SiteCacheMap, EdgeCacheMap, VoronoiInfo, Site, HalfEdge + +#### Constants #### + +init.SiteCacheMap, init.EdgeCacheMap, init.VoronoiInfo, init.Site, init.HalfEdge = \ + init_sitecachemap, init_edgecachemap, init_voronoiinfo, init_site, init_halfedge + +cdef SiteCacheMap SITE_CACHE_MAP = init.SiteCacheMap(0, 1, 2, 3, 4) + +cdef EdgeCacheMap AREA_EDGE_CACHE_MAP = init.EdgeCacheMap(0, 4, 6, 8, 10, -1, 12, 13, + -1, -1, -1, -1, -1, -1, -1, 14) +cdef EdgeCacheMap RADIALT_EDGE_CACHE_MAP = init.EdgeCacheMap(0, 4, 6, 8, -1, 10, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21) + +#### SiteCacheMap Methods #### + +cdef inline SiteCacheMap init_sitecachemap(INT_T iarea, INT_T iperim, INT_T iisoparam, + INT_T ienergy, INT_T iavg_radius) nogil: + cdef SiteCacheMap sc + sc.iarea, sc.iperim, sc.iisoparam, sc.ienergy, sc.iavg_radius = \ + iarea, iperim, iisoparam, ienergy, iavg_radius + + sc.area, sc.perim, sc.isoparam, sc.energy, sc.avg_radius = \ + area, perim, isoparam, energy, avg_radius + + return sc + + +cdef inline FLOAT_T area(Site* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.site_cache.get(&self.info.site_cache, + (self.arr_index, self.cache.iarea) + ) + else: + self.info.site_cache.set(&self.info.site_cache, + (self.arr_index, self.cache.iarea), val) + return val + +cdef inline FLOAT_T perim(Site* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.site_cache.get(&self.info.site_cache, + (self.arr_index, self.cache.iperim) + ) + else: + self.info.site_cache.set(&self.info.site_cache, + (self.arr_index, self.cache.iperim), val) + return val + +cdef inline FLOAT_T isoparam(Site* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.site_cache.get(&self.info.site_cache, + (self.arr_index, self.cache.iisoparam) + ) + else: + self.info.site_cache.set(&self.info.site_cache, + (self.arr_index, self.cache.iisoparam), val) + return val + +cdef inline FLOAT_T energy(Site* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.site_cache.get(&self.info.site_cache, + (self.arr_index, self.cache.ienergy) + ) + else: + self.info.site_cache.set(&self.info.site_cache, + (self.arr_index, self.cache.ienergy), val) + return val + +cdef inline FLOAT_T avg_radius(Site* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.site_cache.get(&self.info.site_cache, + (self.arr_index, self.cache.iavg_radius) + ) + else: + self.info.site_cache.set(&self.info.site_cache, + (self.arr_index, self.cache.iavg_radius), val) + return val + + +#### EdgeCacheMap Methods #### + +cdef inline EdgeCacheMap init_edgecachemap(INT_T iH, INT_T ila, INT_T ida, INT_T ixij, + INT_T idVdv, INT_T ii2p, INT_T ila_mag, INT_T ida_mag, INT_T iphi, INT_T iB, + INT_T iF, INT_T ilntan, INT_T icot, INT_T icsc, INT_T icsc2, INT_T size) nogil: + cdef EdgeCacheMap ec + ec.iH, ec.ila, ec.ida, ec.ixij, ec.idVdv, ec.ii2p, ec.ila_mag, ec.ida_mag, ec.iphi, \ + ec.iB, ec.iF, ec.ilntan, ec.icot, ec.icsc, ec.icsc2 = iH, ila, ida, ixij, idVdv, ii2p, \ + ila_mag, ida_mag, iphi, iB, iF, ilntan, icot, icsc, icsc2 + ec.size = size + + ec.H, ec.la, ec.da, ec.xij, ec.dVdv, ec.i2p, ec.la_mag, ec.da_mag, ec.phi, ec.B, ec.F, \ + ec.lntan, ec.cot, ec.csc, ec.csc2 = H, la, da, xij, dVdv, i2p, la_mag, da_mag, phi, \ + B, F, lntan, cot, csc, csc2 + + return ec + + +cdef inline Matrix2x2 H(HalfEdge* self, Matrix2x2 val) nogil: + if isnan(val.a): + return init.Matrix2x2( + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iH) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iH+1) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iH+2) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iH+3) + ), + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iH), val.a) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iH+1), val.b) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iH+2), val.c) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iH+3), val.d) + return val + +cdef inline Vector2D la(HalfEdge* self, Vector2D val) nogil: + if isnan(val.x): + return init.Vector2D( + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ila) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ila+1) + ) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ila), val.x) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ila+1), val.y) + return val + +cdef inline Vector2D da(HalfEdge* self, Vector2D val) nogil: + if isnan(val.x): + return init.Vector2D( + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ida) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ida+1) + ) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ida), val.x) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ida+1), val.y) + return val + +cdef inline Vector2D xij(HalfEdge* self, Vector2D val) nogil: + if isnan(val.x): + return init.Vector2D( + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ixij) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ixij+1) + ) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ixij), val.x) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ixij+1), val.y) + return val + +cdef inline Vector2D dVdv(HalfEdge* self, Vector2D val) nogil: + if isnan(val.x): + return init.Vector2D( + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.idVdv) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.idVdv+1) + ) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.idVdv), val.x) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.idVdv+1), val.y) + return val + +cdef inline Vector2D i2p(HalfEdge* self, Vector2D val) nogil: + if isnan(val.x): + return init.Vector2D( + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ii2p) + ), + self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ii2p+1) + ) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ii2p), val.x) + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ii2p+1), val.y) + return val + +cdef inline FLOAT_T la_mag(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ila_mag) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ila_mag), val) + return val + +cdef inline FLOAT_T da_mag(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ida_mag) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ida_mag), val) + return val + +cdef inline FLOAT_T phi(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iphi) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iphi), val) + return val + +cdef inline FLOAT_T B(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iB) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iB), val) + return val + +cdef inline FLOAT_T F(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.iF) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.iF), val) + return val + +cdef inline FLOAT_T lntan(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.ilntan) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.ilntan), val) + return val + +cdef inline FLOAT_T cot(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.icot) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.icot), val) + return val + +cdef inline FLOAT_T csc(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.icsc) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.icsc), val) + return val + +cdef inline FLOAT_T csc2(HalfEdge* self, FLOAT_T val) nogil: + if isnan(val): + return self.info.edge_cache.get(&self.info.edge_cache, + (self.arr_index, self.cache.icsc2) + ) + else: + self.info.edge_cache.set(&self.info.edge_cache, + (self.arr_index, self.cache.icsc2), val) + return val + + +#### VoronoiInfo Methods #### + +cdef inline VoronoiInfo init_voronoiinfo(INT_T [:, ::1] sites, INT_T [:, ::1] edges, + FLOAT_T [:, ::1] points, FLOAT_T [:, ::1] vertices, + FLOAT_T [:, ::1] site_cache, FLOAT_T [:, ::1] edge_cache, + EdgeCacheMap* edge_cache_map) nogil: + cdef VoronoiInfo info + info.sites = init_iarray(&sites[0,0], (sites.shape[0], sites.shape[1])) + info.edges = init_iarray(&edges[0,0], (edges.shape[0], edges.shape[1])) + info.points = init_farray(&points[0,0], (points.shape[0], points.shape[1])) + info.vertices = init_farray(&vertices[0,0], + (vertices.shape[0], vertices.shape[1]) + ) + info.site_cache = init_farray(&site_cache[0,0], + (site_cache.shape[0], site_cache.shape[1]) + ) + info.edge_cache = init_farray(&edge_cache[0,0], + (edge_cache.shape[0], edge_cache.shape[1]) + ) + info.edge_cache_map = edge_cache_map + + return info + + +#### Site Methods #### + +cdef inline Site init_site(INT_T arr_index, VoronoiInfo* info) nogil: + cdef Site site + site.arr_index, site.info, site.cache = arr_index, info, &SITE_CACHE_MAP + + site.index, site.vec, site.edge, site.edge_num = index, vec, edge, edge_num + + return site + + +cdef inline INT_T index(Site* self) nogil: + return self.info.sites.get(&self.info.sites, (self.arr_index, 0)) + +cdef inline Vector2D vec(Site* self) nogil: + return init.Vector2D( + self.info.points.get(&self.info.points, (self.index(self), 0)), + self.info.points.get(&self.info.points, (self.index(self), 1)) + ) + +cdef inline HalfEdge edge(Site* self) nogil: + return init.HalfEdge( + self.info.sites.get(&self.info.sites, (self.arr_index, 1)), self.info + ) + +cdef inline INT_T edge_num(Site* self) nogil: + return self.info.sites.get(&self.info.sites, (self.arr_index, 2)) + + +#### HalfEdge Methods #### + +cdef inline HalfEdge init_halfedge(INT_T arr_index, VoronoiInfo* info) nogil: + cdef HalfEdge edge + edge.arr_index, edge.info, edge.cache = arr_index, info, info.edge_cache_map + edge.orig_arr_index = arr_index + + edge.origin_index, edge.origin, edge.face, edge.next, edge.prev, edge.twin, edge.get_H = \ + origin_index, origin, face, edge_next, prev, twin, get_H + + return edge + + +cdef inline INT_T origin_index(HalfEdge* self) nogil: + return self.info.edges.get(&self.info.edges, (self.arr_index, 0)) + +cdef inline Vector2D origin(HalfEdge* self) nogil: + return init.Vector2D( + self.info.vertices.get(&self.info.vertices, (self.origin_index(self), 0)), + self.info.vertices.get(&self.info.vertices, (self.origin_index(self), 1)) + ) + +cdef inline Site face(HalfEdge* self) nogil: + return init.Site( + self.info.edges.get(&self.info.edges, (self.arr_index, 1)), self.info + ) + +cdef inline HalfEdge edge_next(HalfEdge* self) nogil: + + return init.HalfEdge( + self.info.edges.get(&self.info.edges, (self.arr_index, 2)), self.info + ) + +cdef inline HalfEdge prev(HalfEdge* self) nogil: + return init.HalfEdge( + self.info.edges.get(&self.info.edges, (self.arr_index, 3)), self.info + ) + +cdef inline HalfEdge twin(HalfEdge* self) nogil: + return init.HalfEdge( + self.info.edges.get(&self.info.edges, (self.arr_index, 4)), self.info + ) + +cdef inline Matrix2x2 get_H(HalfEdge* self, Site xi) nogil: + cdef INT_T this_e = self.origin_index(self) + cdef HalfEdge s_e = xi.edge(&xi) + cdef INT_T i + + for i in range(xi.edge_num(&xi)): + if s_e.origin_index(&s_e) == this_e: + return s_e.cache.H(&s_e, NAN_MATRIX) + s_e = s_e.next(&s_e) + return init.Matrix2x2(0.0, 0.0, 0.0, 0.0) + + +cdef class VoronoiContainer: + """ + Class for Voronoi diagrams, stored in a modified DCEL. + :param n: [int] how many sites to generate. + :param w: [float] width of the bounding domain. + :param h: [float] height of the bounding domain. + :param r: [float] radius of zero energy circle. + :param sites: np.ndarray collection of sites. + """ + + def __init__(VoronoiContainer self, INT_T n, FLOAT_T w, FLOAT_T h, FLOAT_T r, object site_arr): + self.n, self.w, self.h, self.r = n, w, h, r + self.dim = [w, h] + + self.calculate_voronoi(site_arr.astype(FLOAT)) + self.generate_dcel() + + self.common_cache() + self.precompute() + self.calc_grad() + self.get_statistics() + + # #print(np.asarray(self.site_cache[0])) + # print(np.asarray(self.edges[:6])) + # #print(np.asarray(self.edge_cache[:6])) + # print(self.gradient) + + + cdef void calculate_voronoi(VoronoiContainer self, + np.ndarray[FLOAT_T, ndim=2] site_arr) except *: + """ + Does all necessary computation and caching once points are set. + :param site_arr: initial points for this container. + """ + global SYMM + cdef np.ndarray[FLOAT_T, ndim=2] symm = np.asarray(SYMM).reshape(9,2) + cdef np.ndarray[FLOAT_T, ndim=1] dim = np.asarray(self.dim) + cdef np.ndarray[FLOAT_T, ndim=2] full_site_arr = np.empty((self.n*9+8, 2), dtype=FLOAT) + + # Generate periodic sites and sites that bound periodic sites. + cdef INT_T i + for i in range(9): + full_site_arr[self.n*i:self.n*(i+1)] = site_arr + symm[i]*dim + if i > 0: + full_site_arr[9*self.n+i-1] = dim/2 + 2*dim*symm[i] + + # Use SciPy to compute the Voronoi set. + self.scipy_vor = scipy.spatial.Voronoi(full_site_arr) + self.points = self.scipy_vor.points + self.vertices = self.scipy_vor.vertices + + + cdef void generate_dcel(VoronoiContainer self) except *: + cdef INT_T npoints = self.n*9+8 + cdef array.array int_tmplt = array.array('q', []) + + cdef np.ndarray[INT_T, ndim=1] offsets = np.zeros(self.n*9+1, dtype=INT) + cdef array.array vert_indices = array.clone(int_tmplt, 0, False) + + # Flatten regions into array, so it can be used later. + cdef INT_T i + for i in range(self.n*9): + verts = self.scipy_vor.regions[self.scipy_vor.point_region[i]] + offsets[i+1] = offsets[i] + len(verts) # Build offsets. + vert_indices.extend(array.array('q', verts)) # Flatten + + # Get vertices of original N sites. + cdef np.ndarray[INT_T, ndim=1] vert_indices_np = np.asarray(vert_indices) + cdef np.ndarray[INT_T, ndim=1] border_sites = np.unique(np.searchsorted( + np.asarray(offsets), # Check indices where below matches would be inserted + np.nonzero(np.isin( # Indices of other verts being in bound verts. + vert_indices_np[offsets[self.n]:], # Rest of the verts to check. + np.unique(vert_indices_np[:offsets[self.n]]) # Bound verts + ))[0] + offsets[self.n], + side='right' # If on index == offset_number, should be part of the next site. + ) - 1) # Subtract by one to get actual site number. + + cdef INT_T border_num = len(border_sites) + + # Build sites array. + # [Site Index, Edge Index/Offset, Edge Count] + self.sites = np.empty((self.n+border_num, 3), dtype=INT) + self.sites.base[:self.n, 0] = np.arange(self.n, dtype=INT) + self.sites.base[self.n:, 0] = border_sites + self.sites.base[:self.n+1, 1] = offsets[:self.n+1] + for i in range(self.n): + self.sites[i, 2] = self.sites[i+1, 1] - self.sites[i, 1] + + cdef INT_T edge_count = offsets[self.n] + cdef INT_T diff + for i in range(border_num): + diff = offsets[border_sites[i]+1] - offsets[border_sites[i]] + edge_count += diff + self.sites[self.n+i, 2] = diff + if i < border_num - 1: + self.sites[self.n+i+1, 1] = self.sites[self.n+i, 1] + diff + + # Build edges array + # [Origin Index, Site Index, Next Index, Prev Index, Twin Index] + self.edges = np.empty((edge_count, 5), dtype=INT) + cdef np.ndarray[INT_T, ndim=1] site_verts + cdef INT_T j, site_i, edge_i, edge_offset, vert_num, twin_index, prev_res + + edge_indices = dict() + + for i in range(self.n + border_num): + site_i = self.sites[i, 0] + edge_offset = self.sites[i, 1] + site_verts = vert_indices_np[offsets[site_i]:offsets[site_i+1]] + + # Scipy outputs sorted vertices, but reverse if not counterclockwise. + if not VoronoiContainer.sign(self.points[site_i], + self.vertices[site_verts[0]], self.vertices[site_verts[1]]): + site_verts = np.flip(site_verts) + + vert_num = offsets[site_i+1] - offsets[site_i] + + for j in range(vert_num): + edge_i = edge_offset+j + self.edges[edge_i, 0] = site_verts[j] + self.edges[edge_i, 1] = i + # Add vert_num because of C modulo to get always positive. + self.edges[edge_i, 2] = (j+vert_num+1) % vert_num + edge_offset + self.edges[edge_i, 3] = (j+vert_num-1) % vert_num + edge_offset + + # Get reversed tuple to theck for twin. + twin_index = edge_indices.get( + (site_verts[(j+1) % vert_num], site_verts[j] + ), -1) + + self.edges[edge_i, 4] = twin_index + if twin_index == -1: + edge_indices[(site_verts[j], site_verts[(j+1) % vert_num])] = \ + j + edge_offset + else: + self.edges[twin_index, 4] = j + edge_offset + + self.site_cache = np.empty((self.n + border_num, 5), dtype=FLOAT) + self.edge_cache = np.empty((edge_count, self.edge_cache_map.size), dtype=FLOAT) + + + cdef void common_cache(VoronoiContainer self) except *: + cdef VoronoiInfo info = init.VoronoiInfo(self.sites, self.edges, self.points, + self.vertices, self.site_cache, self.edge_cache, self.edge_cache_map) + + cdef Site xi + cdef HalfEdge em, ep + cdef Vector2D p, q, la, da, Rla + + cdef FLOAT_T [:] area = np.zeros(self.sites.shape[0], dtype=FLOAT) + cdef FLOAT_T [:] perim = np.zeros(self.sites.shape[0], dtype=FLOAT) + + cdef INT_T i, j + cdef FLOAT_T e_area, la_mag + for i in prange(self.sites.shape[0], nogil=True): + xi = init.Site(i, &info) + em = xi.edge(&xi) + for j in prange(xi.edge_num(&xi)): + ep = em.next(&em) + p, q = em.origin(&em), ep.origin(&ep) + la, da = q.copy.vsub(&q, p), p.copy.vsub(&p, xi.vec(&xi)) # vp - vm, vm - xi + + la_mag = la.mag(&la) + e_area = la.dot(&la, da.rot(&da)) + Rla = la.rot(&la) + + em.cache.la(&em, la) + em.cache.la_mag(&em, la_mag) + em.cache.da(&em, da) + em.cache.da_mag(&em, da.mag(&da)) + em.cache.xij(&em, Rla.copy.smul(&Rla, -e_area/la.dot(&la, la))) + + if info.edge_cache_map.iF != -1: + em.cache.F(&em, e_area) + + area[i] += e_area + perim[i] += la_mag + + em = em.next(&em) + + xi.cache.area(&xi, area[i]/2) + xi.cache.perim(&xi, perim[i]) + xi.cache.isoparam(&xi, 2*PI*area[i]/(perim[i]*perim[i])) + + + @staticmethod + cdef inline Matrix2x2 calc_H(HalfEdge em, HalfEdge ep) nogil: + cdef Vector2D xmv, xpv, im, mp, right, Rpm, Rim, f + cdef Matrix2x2 h + cdef FLOAT_T im2, mp2 + + # Vectors from xi to xm and xp. + xmv, xpv = em.cache.xij(&em, NAN_VECTOR), ep.cache.xij(&ep, NAN_VECTOR) + im, mp = xmv.copy.neg(&xmv), xmv.copy.vsub(&xmv, xpv) # -xmv, xmv - xpv + im2, mp2 = -(xmv.dot(&xmv, xmv)), xmv.dot(&xmv, xmv) - xpv.dot(&xpv, xpv) + # (-xmv*xmv, xmv*xmv - xpv*xpv) + right = init.Vector2D(im2, mp2) + Rpm, Rim = R.vecmul(&R, mp.copy.neg(&mp)), im.rot(&im) # R*-mp, R*im + + h = init.Matrix2x2(Rpm.x, Rim.x, Rpm.y, Rim.y) # [Rpm | Rim], h is temporary. + f = h.vecmul(&h, right) # [Rpm | Rim]*right + h = R.copy.smul(&R, mp2*(2*mp.dot(&mp, Rim))) # fp*g, g is a scalar. + # (fp*g - f*gp)/(g**2). f is a column vector, gp = 2*Rpm is a row vector. + h.self.msub(&h, init.Matrix2x2( + f.x*2*Rpm.x, f.x*2*Rpm.y, f.y*2*Rpm.x, f.y*2*Rpm.y + )) + h.self.sdiv(&h, (2*mp.dot(&mp, Rim))**2) + + return h + + + @staticmethod + cdef inline bint sign(FLOAT_T [::1] ref, FLOAT_T [::1] p, FLOAT_T [::1] q): + """ + Outputs if p2 - self is counterclockwise of p1 - self. + :param p1: [List[float]] first vector + :param p2: [List[float]] second vector + :return: [bool] returns if counterclockwise. + """ + return ((q[0] - ref[0])*-(p[1] - ref[1]) + \ + (q[1] - ref[1])*(p[0] - ref[0])) >= 0 + + # global ROT + # cdef np.ndarray[FLOAT_T, ndim=2] rot = np.asarray(ROT).reshape(2,2) + # return (q - ref).dot(rot.dot(p - ref)) >= 0 + + cdef void precompute(self) except *: + pass + + cdef void calc_grad(self) except *: + pass + + cdef void get_statistics(self) except *: + self.stats = {} + cache = self.site_cache[:self.n, :] + + self.stats["site_areas"] = np.asarray(cache[:, SITE_CACHE_MAP.iarea]) + edge_count = np.empty((self.n,)) + for i in range(self.n): + edge_count[i] = len(self.vor_data.regions[self.vor_data.point_region[i]]) + self.stats["site_edge_count"] = edge_count + + self.stats["site_isos"] = np.asarray(cache[:, SITE_CACHE_MAP.iisoparam]) + self.stats["site_energies"] = np.asarray(cache[:, SITE_CACHE_MAP.ienergy]) + self.stats["avg_radius"] = np.asarray(cache[:, SITE_CACHE_MAP.iavg_radius]) + + self.stats["isoparam_avg"] = self.stats["site_areas"] / \ + (PI*self.stats["avg_radius"]**2) + + edges = np.asarray(self.edges) + + mask = np.nonzero(edges[:, 0] != -1)[0] + all_edges = mask[(mask % 2 == 0)] + caches = edges[all_edges, 4] + + edge_cache = np.asarray(self.edge_cache) + + self.stats["edge_lengths"] = edge_cache[caches, self.edge_cache_map.ila_mag] + + @property + def site_arr(self): + return np.asarray(self.points[:self.n], dtype=FLOAT) + + @property + def vor_data(self): + return self.scipy_vor + + @property + def gradient(self): + return np.asarray(self.grad, dtype=FLOAT) + + def add_sites(self, add): + return (self.site_arr + add) % np.asarray(self.dim, dtype=FLOAT) + + def iterate(self, FLOAT_T step): + k1 = self.gradient + + k2 = self.__class__(self.n, self.w, self.h, self.r, + self.add_sites(step*k1/2) + ).gradient + + k3 = self.__class__(self.n, self.w, self.h, self.r, + self.add_sites(step*(-k1+ 2*k2)) + ).gradient + + return self.add_sites((step/6)*(k1+2*k2+k3)), k1 + + def hessian(self, d: float) -> np.ndarray: + """ + Obtains the approximate Hessian. + :param d: [float] small d for approximation. + :return: 2Nx2N array that represents Hessian. + """ + HE = np.zeros((2*self.n, 2*self.n)) + new_sites = np.copy(self.site_arr) # Maintain one copy for speed. + for i in range(self.n): + for j in range(2): + mod = self.w if j == 0 else self.h + new_sites[i][j] = (new_sites[i][j] + d) % mod + Ep = self.__class__(self.n, self.w, self.h, self.r, new_sites) + new_sites[i][j] = (new_sites[i][j] - 2*d) % mod + Em = self.__class__(self.n, self.w, self.h, self.r, new_sites) + new_sites[i][j] = (new_sites[i][j] + d) % mod + + HE[:, 2*i+j] = ((Ep.gradient - Em.gradient)/(2*d)).flatten() + + # Average out discrepencies, since it should be symmetric. + for i in range(2*self.n): + for j in range(i, 2*self.n): + HE[i][j] = (HE[i][j] + HE[j][i])/2 + HE[j][i] = HE[i][j] + + return HE + diff --git a/test_sim.json b/test_sim.json new file mode 100644 index 0000000..9171858 --- /dev/null +++ b/test_sim.json @@ -0,0 +1,33 @@ +{ + "calc": { + "n_objects": 10, + "width": 10.0, + "height": 10.0, + "natural_radius": 4.0, + "energy": "radial-t" + }, + "sim": { + "mode": "flow", + "step_size": 0.05, + "threshold": 0.0001 + } +} + +/* +# ARR = np.array([ +# [1, 1], [3, 1], [5, 1], +# [1, 3], [3, 3], [5, 3], +# [1, 5], [3, 5], [5, 5], +# [1, 7], [3, 7], [5, 7], +# [1, 9], [3, 9], [5, 9], +# [7, 1], [8, 1], [9, 1], +# [7, 2], [8, 2], [9, 2], +# [7, 3], [8, 3], [9, 3], +# [7, 4], [8, 4], [9, 4], +# [7, 5], [8, 5], [9, 5], +# [7, 6], [8, 6], [9, 6], +# [7, 7], [8, 7], [9, 7], +# [7, 8], [8, 8], [9, 8], +# [7, 9], [8, 9], [9, 9], +# ], dtype=float) +*/ \ No newline at end of file