pax_global_header00006660000000000000000000000064141747661550014532gustar00rootroot0000000000000052 comment=1a4118650fab05bbd284eb49c99f9185bdf6a927 pygmsh-7.1.17/000077500000000000000000000000001417476615500131365ustar00rootroot00000000000000pygmsh-7.1.17/.codecov.yml000066400000000000000000000000141417476615500153540ustar00rootroot00000000000000comment: no pygmsh-7.1.17/.flake8000066400000000000000000000001611417476615500143070ustar00rootroot00000000000000[flake8] ignore = E203, E266, E501, W503, E741 max-line-length = 80 max-complexity = 18 select = B,C,E,F,W,T4,B9 pygmsh-7.1.17/.github/000077500000000000000000000000001417476615500144765ustar00rootroot00000000000000pygmsh-7.1.17/.github/workflows/000077500000000000000000000000001417476615500165335ustar00rootroot00000000000000pygmsh-7.1.17/.github/workflows/ci.yml000066400000000000000000000023651417476615500176570ustar00rootroot00000000000000name: ci on: push: branches: - main pull_request: branches: - main jobs: doc: runs-on: ubuntu-latest steps: - uses: actions/setup-python@v2 with: python-version: "3.x" - uses: actions/checkout@v2 - run: | pip install sphinx sphinx-autodoc-typehints sphinx-build -M html doc/ build/ lint: runs-on: ubuntu-latest steps: - name: Check out repo uses: actions/checkout@v2 - name: Set up Python uses: actions/setup-python@v2 - name: Run pre-commit uses: pre-commit/action@v2.0.3 build: runs-on: ubuntu-latest strategy: matrix: python-version: ["3.7", "3.8", "3.9", "3.10"] steps: - uses: actions/setup-python@v2 with: python-version: ${{ matrix.python-version }} - uses: actions/checkout@v2 # install gmsh from system -- not sure why this is necessary - name: Install gmsh run: | sudo apt-get install -y python3-gmsh - name: Test with tox run: | pip install tox tox -- --cov pygmsh --cov-report xml --cov-report term - uses: codecov/codecov-action@v1 if: ${{ matrix.python-version == '3.9' }} pygmsh-7.1.17/.gitignore000066400000000000000000000002321417476615500151230ustar00rootroot00000000000000*.pyc *.geo *.msh *.e *.vtk *.vtu .DS_Store .cache/ .tox/ *.xml MANIFEST README.rst build/ dist/ pygmsh.egg-info/ doc/_build/ *.pos *.prof .pytest_cache/ pygmsh-7.1.17/.pre-commit-config.yaml000066400000000000000000000004551417476615500174230ustar00rootroot00000000000000repos: - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: - id: isort - repo: https://github.com/psf/black rev: 21.12b0 hooks: - id: black language_version: python3 - repo: https://github.com/PyCQA/flake8 rev: 4.0.1 hooks: - id: flake8 pygmsh-7.1.17/.readthedocs.yml000066400000000000000000000003061417476615500162230ustar00rootroot00000000000000version: 2 python: version: 3 # use pip for installation, see # install: - path: . method: pip pygmsh-7.1.17/CITATION.cff000066400000000000000000000004751417476615500150360ustar00rootroot00000000000000cff-version: 1.2.0 message: "If you use this software, please cite it as below." authors: - family-names: "Schlömer" given-names: "Nico" orcid: "https://orcid.org/0000-0001-5228-0946" title: "pygmsh: A Python frontend for Gmsh" doi: 10.5281/zenodo.1173105 url: https://github.com/nschloe/pygmsh license: GPL-3.0 pygmsh-7.1.17/LICENSE.txt000066400000000000000000001045131417476615500147650ustar00rootroot00000000000000 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 . pygmsh-7.1.17/MANIFEST.in000066400000000000000000000000311417476615500146660ustar00rootroot00000000000000include tests/helpers.py pygmsh-7.1.17/README.md000066400000000000000000000263541417476615500144270ustar00rootroot00000000000000

pygmsh

Gmsh for Python.

[![PyPi Version](https://img.shields.io/pypi/v/pygmsh.svg?style=flat-square)](https://pypi.org/project/pygmsh/) [![PyPI pyversions](https://img.shields.io/pypi/pyversions/pygmsh.svg?style=flat-square)](https://pypi.org/project/pygmsh/) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.1173105.svg?style=flat-square)](https://doi.org/10.5281/zenodo.1173105) [![GitHub stars](https://img.shields.io/github/stars/nschloe/pygmsh.svg?style=flat-square&logo=github&label=Stars&logoColor=white)](https://github.com/nschloe/pygmsh) [![PyPi downloads](https://img.shields.io/pypi/dm/pygmsh.svg?style=flat-square)](https://pypistats.org/packages/pygmsh) [![Discord](https://img.shields.io/static/v1?logo=discord&label=chat&message=on%20discord&color=7289da&style=flat-square)](https://discord.gg/hnTJ5MRX2Y) [![Documentation Status](https://readthedocs.org/projects/pygmsh/badge/?version=latest&style=flat-square)](https://pygmsh.readthedocs.io/en/latest/?badge=latest) [![gh-actions](https://img.shields.io/github/workflow/status/nschloe/pygmsh/ci?style=flat-square)](https://github.com/nschloe/pygmsh/actions?query=workflow%3Aci) [![codecov](https://img.shields.io/codecov/c/github/nschloe/pygmsh.svg?style=flat-square)](https://codecov.io/gh/nschloe/pygmsh) [![LGTM](https://img.shields.io/lgtm/grade/python/github/nschloe/pygmsh.svg?style=flat-square)](https://lgtm.com/projects/g/nschloe/pygmsh) [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square)](https://github.com/psf/black) pygmsh combines the power of [Gmsh](https://gmsh.info/) with the versatility of Python. It provides useful abstractions from Gmsh's own Python interface so you can create complex geometries more easily. To use, install Gmsh itself and pygmsh from [pypi](https://pypi.org/project/pygmsh/): ``` [sudo] apt install python3-gmsh pip install pygmsh ``` This document and the [`tests/`](https://github.com/nschloe/pygmsh/tree/main/tests/) directory contain many small examples. See [here](https://pygmsh.readthedocs.io/en/latest/index.html) for the full documentation. #### Flat shapes | | | | | :-------------------------------------------------------------------: | :------------------------------------------------------------------: | :-------------------------------------------------------------------: | | Polygon | Circle | (B-)Splines | Codes: ```python import pygmsh with pygmsh.geo.Geometry() as geom: geom.add_polygon( [ [0.0, 0.0], [1.0, -0.2], [1.1, 1.2], [0.1, 0.7], ], mesh_size=0.1, ) mesh = geom.generate_mesh() # mesh.points, mesh.cells, ... # mesh.write("out.vtk") ``` ```python import pygmsh with pygmsh.geo.Geometry() as geom: geom.add_circle([0.0, 0.0], 1.0, mesh_size=0.2) mesh = geom.generate_mesh() ``` ```python import pygmsh with pygmsh.geo.Geometry() as geom: lcar = 0.1 p1 = geom.add_point([0.0, 0.0], lcar) p2 = geom.add_point([1.0, 0.0], lcar) p3 = geom.add_point([1.0, 0.5], lcar) p4 = geom.add_point([1.0, 1.0], lcar) s1 = geom.add_bspline([p1, p2, p3, p4]) p2 = geom.add_point([0.0, 1.0], lcar) p3 = geom.add_point([0.5, 1.0], lcar) s2 = geom.add_spline([p4, p3, p2, p1]) ll = geom.add_curve_loop([s1, s2]) pl = geom.add_plane_surface(ll) mesh = geom.generate_mesh() ``` The return value is always a [meshio](https://pypi.org/project/meshio/) mesh, so to store it to a file you can ```python mesh.write("test.vtk") ``` The output file can be visualized with various tools, e.g., [ParaView](https://www.paraview.org/). With ```python pygmsh.write("test.msh") ``` you can access Gmsh's native file writer. #### Extrusions | | | | | :-------------------------------------------------------------------: | :-------------------------------------------------------------------: | :-----------------------------------------------------------------: | | `extrude` | `revolve` | `twist` | ```python import pygmsh with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [ [0.0, 0.0], [1.0, -0.2], [1.1, 1.2], [0.1, 0.7], ], mesh_size=0.1, ) geom.extrude(poly, [0.0, 0.3, 1.0], num_layers=5) mesh = geom.generate_mesh() ``` ```python from math import pi import pygmsh with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [ [0.0, 0.2, 0.0], [0.0, 1.2, 0.0], [0.0, 1.2, 1.0], ], mesh_size=0.1, ) geom.revolve(poly, [0.0, 0.0, 1.0], [0.0, 0.0, 0.0], 0.8 * pi) mesh = geom.generate_mesh() ``` ```python from math import pi import pygmsh with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [ [+0.0, +0.5], [-0.1, +0.1], [-0.5, +0.0], [-0.1, -0.1], [+0.0, -0.5], [+0.1, -0.1], [+0.5, +0.0], [+0.1, +0.1], ], mesh_size=0.05, ) geom.twist( poly, translation_axis=[0, 0, 1], rotation_axis=[0, 0, 1], point_on_axis=[0, 0, 0], angle=pi / 3, ) mesh = geom.generate_mesh() ``` #### OpenCASCADE | | | | | :------------------------------------------------------------------------: | :---------------------------------------------------------------------------: | :------------------------------------------------------------------: | | | | Gmsh also supports OpenCASCADE (`occ`), allowing for a CAD-style geometry specification. ```python from math import pi, cos import pygmsh with pygmsh.occ.Geometry() as geom: geom.characteristic_length_max = 0.1 r = 0.5 disks = [ geom.add_disk([-0.5 * cos(7 / 6 * pi), -0.25], 1.0), geom.add_disk([+0.5 * cos(7 / 6 * pi), -0.25], 1.0), geom.add_disk([0.0, 0.5], 1.0), ] geom.boolean_intersection(disks) mesh = geom.generate_mesh() ``` ```python # ellpsoid with holes import pygmsh with pygmsh.occ.Geometry() as geom: geom.characteristic_length_max = 0.1 ellipsoid = geom.add_ellipsoid([0.0, 0.0, 0.0], [1.0, 0.7, 0.5]) cylinders = [ geom.add_cylinder([-1.0, 0.0, 0.0], [2.0, 0.0, 0.0], 0.3), geom.add_cylinder([0.0, -1.0, 0.0], [0.0, 2.0, 0.0], 0.3), geom.add_cylinder([0.0, 0.0, -1.0], [0.0, 0.0, 2.0], 0.3), ] geom.boolean_difference(ellipsoid, geom.boolean_union(cylinders)) mesh = geom.generate_mesh() ``` ```python # puzzle piece import pygmsh with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.1 geom.characteristic_length_max = 0.1 rectangle = geom.add_rectangle([-1.0, -1.0, 0.0], 2.0, 2.0) disk1 = geom.add_disk([-1.2, 0.0, 0.0], 0.5) disk2 = geom.add_disk([+1.2, 0.0, 0.0], 0.5) disk3 = geom.add_disk([0.0, -0.9, 0.0], 0.5) disk4 = geom.add_disk([0.0, +0.9, 0.0], 0.5) flat = geom.boolean_difference( geom.boolean_union([rectangle, disk1, disk2]), geom.boolean_union([disk3, disk4]), ) geom.extrude(flat, [0, 0, 0.3]) mesh = geom.generate_mesh() ``` #### Mesh refinement/boundary layers | | | | | :---------------------------------------------------------------------: | :------------------------------------------------------------------------------: | :-------------------------------------------------------------------------------: | | | | ```python # boundary refinement import pygmsh with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [ [0.0, 0.0], [2.0, 0.0], [3.0, 1.0], [1.0, 2.0], [0.0, 1.0], ], mesh_size=0.3, ) field0 = geom.add_boundary_layer( edges_list=[poly.curves[0]], lcmin=0.05, lcmax=0.2, distmin=0.0, distmax=0.2, ) field1 = geom.add_boundary_layer( nodes_list=[poly.points[2]], lcmin=0.05, lcmax=0.2, distmin=0.1, distmax=0.4, ) geom.set_background_mesh([field0, field1], operator="Min") mesh = geom.generate_mesh() ``` ```python # mesh refinement with callback import pygmsh with pygmsh.geo.Geometry() as geom: geom.add_polygon( [ [-1.0, -1.0], [+1.0, -1.0], [+1.0, +1.0], [-1.0, +1.0], ] ) geom.set_mesh_size_callback( lambda dim, tag, x, y, z: 6.0e-2 + 2.0e-1 * (x ** 2 + y ** 2) ) mesh = geom.generate_mesh() ``` ```python # ball with mesh refinement from math import sqrt import pygmsh with pygmsh.occ.Geometry() as geom: geom.add_ball([0.0, 0.0, 0.0], 1.0) geom.set_mesh_size_callback( lambda dim, tag, x, y, z: abs(sqrt(x ** 2 + y ** 2 + z ** 2) - 0.5) + 0.1 ) mesh = geom.generate_mesh() ``` #### Optimization pygmsh can optimize existing meshes, too. ```python import meshio mesh = meshio.read("mymesh.vtk") optimized_mesh = pygmsh.optimize(mesh, method="") ``` You can also use the command-line utility ``` pygmsh-optimize input.vtk output.xdmf ``` where input and output can be any format supported by [meshio](https://pypi.org/project/meshio/). ### Testing To run the pygmsh unit tests, check out this repository and type ``` pytest ``` ### Building Documentation Docs are built using [Sphinx](http://www.sphinx-doc.org/en/stable/). To build, run ``` sphinx-build -b html doc doc/_build ``` ### License This software is published under the [GPLv3 license](https://www.gnu.org/licenses/gpl-3.0.en.html). pygmsh-7.1.17/doc/000077500000000000000000000000001417476615500137035ustar00rootroot00000000000000pygmsh-7.1.17/doc/Makefile000066400000000000000000000163611417476615500153520ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # User-friendly check for sphinx-build ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1) $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don't have Sphinx installed, grab it from http://sphinx-doc.org/) endif # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest coverage gettext help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " applehelp to make an Apple Help Book" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx" @echo " text to make text files" @echo " man to make manual pages" @echo " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @echo " changes to make an overview of all changed/added/deprecated items" @echo " xml to make Docutils-native XML files" @echo " pseudoxml to make pseudoxml-XML files for display purposes" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" @echo " coverage to run coverage check of the documentation (if enabled)" clean: rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/pygmsh.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/pygmsh.qhc" applehelp: $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp @echo @echo "Build finished. The help book is in $(BUILDDIR)/applehelp." @echo "N.B. You won't be able to view it unless you put it in" \ "~/Library/Documentation/Help or install it in your application" \ "bundle." devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/pygmsh" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/pygmsh" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." $(MAKE) -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." latexpdfja: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through platex and dvipdfmx..." $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." coverage: $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage @echo "Testing of coverage in the sources finished, look at the " \ "results in $(BUILDDIR)/coverage/python.txt." xml: $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml @echo @echo "Build finished. The XML files are in $(BUILDDIR)/xml." pseudoxml: $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml @echo @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml." pygmsh-7.1.17/doc/common.rst000066400000000000000000000026431417476615500157320ustar00rootroot00000000000000Common ====== Common functions shared between the geo and the occ kernels. Geometry -------- .. automodule:: pygmsh.common.geometry :members: :undoc-members: :show-inheritance: Bspline ------- .. automodule:: pygmsh.common.bspline :members: :undoc-members: :show-inheritance: CircleArc --------- .. automodule:: pygmsh.common.circle_arc :members: :undoc-members: :show-inheritance: EllipseArc ---------- .. automodule:: pygmsh.common.ellipse_arc :members: :undoc-members: :show-inheritance: LineBase -------- .. automodule:: pygmsh.common.line_base :members: :undoc-members: :show-inheritance: CurveLoop --------- .. automodule:: pygmsh.common.curve_loop :members: :undoc-members: :show-inheritance: Line ---- .. automodule:: pygmsh.common.line :members: :undoc-members: :show-inheritance: Point ----- .. automodule:: pygmsh.common.point :members: :undoc-members: :show-inheritance: Spline ------ .. automodule:: pygmsh.common.spline :members: :undoc-members: :show-inheritance: SurfaceLoop ----------- .. automodule:: pygmsh.common.surface_loop :members: :undoc-members: :show-inheritance: Surface ------- .. automodule:: pygmsh.common.surface :members: :undoc-members: :show-inheritance: Volume ------ .. automodule:: pygmsh.common.volume :members: :undoc-members: :show-inheritance: pygmsh-7.1.17/doc/conf.py000066400000000000000000000241421417476615500152050ustar00rootroot00000000000000# pygmsh documentation build configuration file, created by # sphinx-quickstart on Tue Oct 27 19:56:53 2015. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import os import sys from pathlib import Path from unittest import mock this_dir = Path(__file__).resolve().parent about = {} with open(this_dir / ".." / "src" / "pygmsh" / "__about__.py") as f: d = exec(f.read(), about) __version__ = about["__version__"] ON_RTD = os.environ.get("READTHEDOCS", None) == "True" MOCK_MODULES = ["meshio", "gmsh"] for mod_name in MOCK_MODULES: sys.modules[mod_name] = mock.Mock() # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. # sys.path.insert(0, os.path.abspath('.')) # -- General configuration ------------------------------------------------ # If your documentation needs a minimal Sphinx version, state it here. # needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ "sphinx.ext.autodoc", "sphinx.ext.mathjax", "sphinx.ext.napoleon", "sphinx_autodoc_typehints", ] # Napoleon settings napoleon_google_docstring = False napoleon_numpy_docstring = True napoleon_include_init_with_doc = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False napoleon_use_admonition_for_examples = False napoleon_use_admonition_for_notes = False napoleon_use_admonition_for_references = False napoleon_use_ivar = True napoleon_use_param = True napoleon_use_rtype = True # Add any paths that contain templates here, relative to this directory. templates_path = ["_templates"] # The suffix(es) of source filenames. # You can specify multiple suffix as a list of string: # source_suffix = ['.rst', '.md'] source_suffix = ".rst" # The encoding of source files. # source_encoding = 'utf-8-sig' # The master toctree document. master_doc = "index" # General information about the project. project = "pygmsh" copyright = "2013-2022, Nico Schlömer et al." author = "Nico Schlömer" # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = ".".join(__version__.split(".")[:2]) # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. # # This is also used if you do content translation via gettext catalogs. # Usually you set "language" from the command line for these cases. language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: # today = '' # Else, today_fmt is used as the format for a strftime call. # today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ["_build"] # The reST default role (used for this markup: `text`) to use for all # documents. # default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. # add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). # add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. # show_authors = False # The name of the Pygments (syntax highlighting) style to use. pygments_style = "sphinx" # A list of ignored prefixes for module index sorting. # modindex_common_prefix = [] # If true, keep warnings as "system message" paragraphs in the built documents. # keep_warnings = False # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = "default" if not ON_RTD: try: import sphinx_rtd_theme html_theme = "sphinx_rtd_theme" html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] except ImportError: pass # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. # html_theme_options = {} # Add any paths that contain custom themes here, relative to this directory. # html_theme_path = [] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". # html_title = None # A shorter title for the navigation bar. Default is the same as html_title. # html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. # html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. # html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". # html_static_path = ['_static'] # Add any extra paths that contain custom files (such as robots.txt or # .htaccess) here, relative to this directory. These files are copied # directly to the root of the documentation. # html_extra_path = [] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. # html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. # html_use_smartypants = True # Custom sidebar templates, maps document names to template names. # html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. # html_additional_pages = {} # If false, no module index is generated. # html_domain_indices = True # If false, no index is generated. # html_use_index = True # If true, the index is split into individual pages for each letter. # html_split_index = False # If true, links to the reST sources are added to the pages. # html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. # html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. # html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. # html_use_opensearch = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). # html_file_suffix = None # Language to be used for generating the HTML full-text search index. # Sphinx supports the following languages: # 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja' # 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr' # html_search_language = 'en' # A dictionary with options for the search language support, empty by default. # Now only 'ja' uses this config value # html_search_options = {'type': 'default'} # The name of a javascript file (relative to the configuration directory) that # implements a search results scorer. If empty, the default will be used. # html_search_scorer = 'scorer.js' # Output file base name for HTML help builder. htmlhelp_basename = "pygmshdoc" # -- Options for LaTeX output --------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). # 'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). # 'pointsize': '10pt', # Additional stuff for the LaTeX preamble. # 'preamble': '', # Latex figure (float) alignment # 'figure_align': 'htbp', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, # author, documentclass [howto, manual, or own class]). latex_documents = [ (master_doc, "pygmsh.tex", "pygmsh Documentation", "Nico Schlömer", "manual") ] # The name of an image file (relative to this directory) to place at the top of # the title page. # latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. # latex_use_parts = False # If true, show page references after internal links. # latex_show_pagerefs = False # If true, show URL addresses after external links. # latex_show_urls = False # Documents to append as an appendix to all manuals. # latex_appendices = [] # If false, no module index is generated. # latex_domain_indices = True # -- Options for manual page output --------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [(master_doc, "pygmsh", "pygmsh Documentation", [author], 1)] # If true, show URL addresses after external links. # man_show_urls = False # -- Options for Texinfo output ------------------------------------------- # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ( master_doc, "pygmsh", "pygmsh Documentation", author, "pygmsh", "Python interface for Gmsh", "Miscellaneous", ) ] # Documents to append as an appendix to all manuals. # texinfo_appendices = [] # If false, no module index is generated. # texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. # texinfo_show_urls = 'footnote' # If true, do not generate a @detailmenu in the "Top" node's menu. # texinfo_no_detailmenu = False pygmsh-7.1.17/doc/geo.rst000066400000000000000000000004721417476615500152120ustar00rootroot00000000000000Built-in Engine =============== The default Gmsh kernel with basic geometry construction functions. For advanced geometries it is recommended to use the openCASCADE kernel. .. automodule:: pygmsh.geo Geometry -------- .. automodule:: pygmsh.geo.geometry :members: :undoc-members: :show-inheritance: pygmsh-7.1.17/doc/index.rst000066400000000000000000000056211417476615500155500ustar00rootroot00000000000000.. pygmsh documentation master file, created by sphinx-quickstart on Tue Oct 27 19:56:53 2015. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to pygmsh's documentation! ================================== This class provides a Python interface for the Gmsh scripting language. It aims at working around some of Gmsh's inconveniences (e.g., having to manually assign an ID for every entity created) and providing access to Python's features. In Gmsh, the user must manually provide a unique ID for every point, curve, volume created. This can get messy when a lot of entities are created and it isn't clear which IDs are already in use. Some Gmsh commands even create new entities and silently reserve IDs in that way. This module tries to work around this by providing routines in the style of add_point(x) which _return_ the ID. To make variable names in Gmsh unique, keep track of how many points, circles, etc. have already been created. Variable names will then be p1, p2, etc. for points, c1, c2, etc. for circles and so on. Geometry Overview ----------------- Gmsh’s geometry module provides a simple CAD engine, using a boundary representation (“BRep”) approach: you need to first define points (using the Point command: see below), then lines (using Line, Circle, Spline, …, commands or by extruding points), then surfaces (using for example the Plane Surface or Surface commands, or by extruding lines), and finally volumes (using the Volume command or by extruding surfaces). These geometrical entities are called “elementary” in Gmsh’s jargon, and are assigned identification numbers (stricly positive) when they are created: 1. Each elementary point must possess a unique identification number; 2. Each elementary line must possess a unique identification number; 3. Each elementary surface must possess a unique identification number; 4. Each elementary volume must possess a unique identification number. Elementary geometrical entities can then be manipulated in various ways, for example using the Translate, Rotate, Scale or Symmetry commands. They can be deleted with the Delete command, provided that no higher-dimension entity references them. Zero or negative identification numbers are reserved by the system for special uses: do not use them in your scripts. Groups of elementary geometrical entities can also be defined and are called “physical” entities. These physical entities cannot be modified by geometry commands: their only purpose is to assemble elementary entities into larger groups so that they can be referred to by the mesh module as single entities. As is the case with elementary entities, each physical point, physical line, physical surface or physical volume must be assigned a unique identification number. Contents: .. toctree:: :maxdepth: 1 :caption: Table of Contents common geo occ pygmsh-7.1.17/doc/occ.rst000066400000000000000000000022421417476615500152010ustar00rootroot00000000000000openCASCADE Engine ================== Using the openCASCADE kernel instead of the built-in geometry kernel. Models can be built using constructive solid geometry, allowing for 2D and 3D polygon boolean operations. .. automodule:: pygmsh.occ Geometry -------- .. automodule:: pygmsh.occ.geometry :members: :undoc-members: :show-inheritance: Ball ---- .. automodule:: pygmsh.occ.ball :members: :undoc-members: :show-inheritance: Box --- .. automodule:: pygmsh.occ.box :members: :undoc-members: :show-inheritance: Cone ---- .. automodule:: pygmsh.occ.cone :members: :undoc-members: :show-inheritance: Cylinder -------- .. automodule:: pygmsh.occ.cylinder :members: :undoc-members: :show-inheritance: Disk ---- .. automodule:: pygmsh.occ.disk :members: :undoc-members: :show-inheritance: Rectangle --------- .. automodule:: pygmsh.occ.rectangle :members: :undoc-members: :show-inheritance: Torus ----- .. automodule:: pygmsh.occ.torus :members: :undoc-members: :show-inheritance: Wedge ----- .. automodule:: pygmsh.occ.wedge :members: :undoc-members: :show-inheritance: pygmsh-7.1.17/doc/requirements.txt000066400000000000000000000000731417476615500171670ustar00rootroot00000000000000mock numpy sphinxcontrib-napoleon sphinx-autodoc-typehints pygmsh-7.1.17/justfile000066400000000000000000000007131417476615500147070ustar00rootroot00000000000000version := `python3 -c "from src.pygmsh.__about__ import __version__; print(__version__)"` default: @echo "\"just publish\"?" publish: @if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi gh release create "v{{version}}" flit publish clean: @find . | grep -E "(__pycache__|\.pyc|\.pyo$)" | xargs rm -rf @rm -rf src/*.egg-info/ build/ dist/ .tox/ format: isort . black . blacken-docs README.md lint: black --check . flake8 . pygmsh-7.1.17/pyproject.toml000066400000000000000000000025541417476615500160600ustar00rootroot00000000000000[build-system] requires = ["flit_core >=3.2,<4"] build-backend = "flit_core.buildapi" [tool.isort] profile = "black" [project] name = "pygmsh" authors = [{name = "Nico Schlömer", email = "nico.schloemer@gmail.com"}] description = "Python frontend for Gmsh" readme = "README.md" license = {file = "LICENSE.txt"} classifiers = [ "Development Status :: 5 - Production/Stable", "Intended Audience :: Science/Research", "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", "Operating System :: OS Independent", "Programming Language :: Python", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.7", "Programming Language :: Python :: 3.8", "Programming Language :: Python :: 3.9", "Programming Language :: Python :: 3.10", "Topic :: Scientific/Engineering", "Topic :: Scientific/Engineering :: Mathematics", "Topic :: Utilities", ] dynamic = ["version"] requires-python = ">=3.7" dependencies = [ "gmsh", "meshio >= 4.3.2, <6", "numpy >= 1.20.0", ] keywords = ["mesh", "gmsh", "mesh generation", "mathematics", "engineering"] [project.urls] Code = "https://github.com/nschloe/pygmsh" Documentation = "https://pygmsh.readthedocs.io/en/latest" Funding = "https://github.com/sponsors/nschloe" Issues = "https://github.com/nschloe/pygmsh/issues" [project.scripts] pygmsh-optimize = "pygmsh._cli:optimize_cli" pygmsh-7.1.17/src/000077500000000000000000000000001417476615500137255ustar00rootroot00000000000000pygmsh-7.1.17/src/pygmsh/000077500000000000000000000000001417476615500152345ustar00rootroot00000000000000pygmsh-7.1.17/src/pygmsh/__about__.py000066400000000000000000000000271417476615500175130ustar00rootroot00000000000000__version__ = "7.1.17" pygmsh-7.1.17/src/pygmsh/__init__.py000066400000000000000000000004241417476615500173450ustar00rootroot00000000000000from . import geo, occ from .__about__ import __version__ from ._optimize import optimize from .helpers import orient_lines, rotation_matrix, write __all__ = [ "geo", "occ", "rotation_matrix", "orient_lines", "write", "optimize", "__version__", ] pygmsh-7.1.17/src/pygmsh/_cli.py000066400000000000000000000032041417476615500165130ustar00rootroot00000000000000import argparse from sys import version_info import meshio from .__about__ import __version__ from ._optimize import optimize def optimize_cli(argv=None): parser = argparse.ArgumentParser( description=("Optimize mesh."), formatter_class=argparse.RawTextHelpFormatter, ) parser.add_argument("infile", type=str, help="mesh to optimize") parser.add_argument("outfile", type=str, help="optimized mesh") parser.add_argument( "-q", "--quiet", dest="verbose", action="store_false", default=True, help="suppress output", ) parser.add_argument( "-m", "--method", default="", # Valid choices are on # https://gmsh.info/doc/texinfo/gmsh.html#Namespace-gmsh_002fmodel_002fmesh help='method (e.g., "", Netgen, ...)', ) parser.add_argument( "-v", "--version", action="version", version=_get_version_text(), help="display version information", ) args = parser.parse_args(argv) mesh = meshio.read(args.infile) optimize(mesh, method=args.method, verbose=args.verbose).write(args.outfile) def _get_version_text(): try: # Python 3.8 from importlib import metadata __gmsh_version__ = metadata.version("gmsh") except Exception: __gmsh_version__ = "unknown" return "\n".join( [ f"pygmsh {__version__} " f"[Gmsh {__gmsh_version__}, " f"Python {version_info.major}.{version_info.minor}.{version_info.micro}]", "Copyright (c) 2013-2022 Nico Schlömer et al.", ] ) pygmsh-7.1.17/src/pygmsh/_optimize.py000066400000000000000000000041621417476615500176100ustar00rootroot00000000000000import gmsh import meshio import numpy as np from .helpers import extract_to_meshio def optimize(mesh, method="", verbose=False): # mesh.remove_lower_dimensional_cells() mesh.cell_data = {} # read into meshio like # gmsh.initialize() # add dummy entity dim = 3 tag = gmsh.model.addDiscreteEntity(dim=dim) # nodes = np.arange(1, len(mesh.points) + 1) assert mesh.points.shape[1] == 3 gmsh.model.mesh.addNodes(dim, tag, nodes, mesh.points.flat) for cell_block in mesh.cells: gmsh.model.mesh.addElementsByType( tag, meshio.gmsh.meshio_to_gmsh_type[cell_block.type], [], cell_block.data.flatten() + 1, ) gmsh.model.mesh.optimize(method, force=True) mesh = extract_to_meshio() gmsh.finalize() # This writes a temporary file and reads it into gmsh ("merge"). There are other # ways of feeding gmsh a mesh # (https://gitlab.onelab.info/gmsh/gmsh/-/issues/1030#note_11435), but let's not do # that for now. # with tempfile.TemporaryDirectory() as tmpdirname: # tmpdir = Path(tmpdirname) # tmpfile = tmpdir / "tmp.msh" # mesh.write(tmpfile) # gmsh.initialize() # if verbose: # gmsh.option.setNumber("General.Terminal", 1) # gmsh.merge(str(tmpfile)) # # We need force=True because we're reading from a discrete mesh # gmsh.model.mesh.optimize(method, force=True) # mesh = extract_to_meshio() # gmsh.finalize() return mesh def print_stats(mesh): import termplotlib q = mesh.q_radius_ratio q_hist, q_bin_edges = np.histogram( q, bins=np.linspace(0.0, 1.0, num=41, endpoint=True) ) grid = termplotlib.subplot_grid((1, 2), column_widths=None, border_style=None) grid[0, 0].hist(q_hist, q_bin_edges, bar_width=1, strip=True) grid[0, 1].aprint(f"min quality: {np.min(q):5.3f}") grid[0, 1].aprint(f"avg quality: {np.average(q):5.3f}") grid[0, 1].aprint(f"max quality: {np.max(q):5.3f}") grid.show() pygmsh-7.1.17/src/pygmsh/common/000077500000000000000000000000001417476615500165245ustar00rootroot00000000000000pygmsh-7.1.17/src/pygmsh/common/__init__.py000066400000000000000000000001031417476615500206270ustar00rootroot00000000000000from .geometry import CommonGeometry __all__ = ["CommonGeometry"] pygmsh-7.1.17/src/pygmsh/common/bezier.py000066400000000000000000000010451417476615500203560ustar00rootroot00000000000000from __future__ import annotations from .line_base import LineBase from .point import Point class Bezier(LineBase): """ Creates a B-spline. Parameters ---------- control_points : Contains the identification numbers of the control points. """ def __init__(self, env, control_points: list[Point]): for c in control_points: assert isinstance(c, Point) assert len(control_points) > 1 id0 = env.addBezier([c._id for c in control_points]) super().__init__(id0, control_points) pygmsh-7.1.17/src/pygmsh/common/bspline.py000066400000000000000000000010471417476615500205340ustar00rootroot00000000000000from __future__ import annotations from .line_base import LineBase from .point import Point class BSpline(LineBase): """ Creates a B-spline. Parameters ---------- control_points : Contains the identification numbers of the control points. """ def __init__(self, env, control_points: list[Point]): for c in control_points: assert isinstance(c, Point) assert len(control_points) > 1 id0 = env.addBSpline([c._id for c in control_points]) super().__init__(id0, control_points) pygmsh-7.1.17/src/pygmsh/common/circle_arc.py000066400000000000000000000012431417476615500211640ustar00rootroot00000000000000from .line_base import LineBase from .point import Point class CircleArc(LineBase): """ Creates a circle arc. Parameters ---------- start : Coordinates of start point needed to construct circle-arc. center : Coordinates of center point needed to construct circle-arc. end : Coordinates of end point needed to construct circle-arc. """ def __init__(self, env, start: Point, center: Point, end: Point): assert isinstance(start, Point) assert isinstance(center, Point) assert isinstance(end, Point) id0 = env.addCircleArc(start._id, center._id, end._id) super().__init__(id0, [start, center, end]) pygmsh-7.1.17/src/pygmsh/common/curve_loop.py000066400000000000000000000022171417476615500212550ustar00rootroot00000000000000from __future__ import annotations class CurveLoop: """ Increments the Line ID every time a new object is created that inherits from LineBase. Parameters ---------- curves : Containing the lines defining the shape. Notes ----- A line loop must be a closed loop, and the elementary lines should be ordered and oriented (negating to specify reverse orientation). If the orientation is correct, but the ordering is wrong, Gmsh will actually reorder the list internally to create a consistent loop. """ dim = 1 def __init__(self, env, curves: list): for k in range(len(curves) - 1): assert curves[k].points[-1] == curves[k + 1].points[0] assert curves[-1].points[-1] == curves[0].points[0] self._id = env.addCurveLoop([c._id for c in curves]) self.dim_tag = (1, self._id) self.dim_tags = [self.dim_tag] self.curves = curves def __len__(self): return len(self.curves) def __repr__(self): curves = ", ".join([str(l._id) for l in self.curves]) return f"" pygmsh-7.1.17/src/pygmsh/common/dummy.py000066400000000000000000000004601417476615500202310ustar00rootroot00000000000000class Dummy: def __init__(self, dim, id0): assert isinstance(id0, int) self.dim = dim self.id = id0 self._id = id0 self.dim_tag = (dim, id0) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/common/ellipse_arc.py000066400000000000000000000021471417476615500213640ustar00rootroot00000000000000from .line_base import LineBase from .point import Point class EllipseArc(LineBase): """ Creates an ellipse arc. Parameters ---------- start : Coordinates of start point needed to construct elliptic arc. center : Coordinates of center point needed to construct elliptic arc. point_on_major_axis : Point on the center axis of ellipse. end : Coordinates of end point needed to construct elliptic arc. """ def __init__( self, env, start: Point, center: Point, point_on_major_axis: Point, end: Point ): assert isinstance(start, Point) assert isinstance(center, Point) assert isinstance(point_on_major_axis, Point) assert isinstance(end, Point) id0 = env.addEllipseArc(start._id, center._id, point_on_major_axis._id, end._id) super().__init__(id0, [start, center, end]) self.points = [start, center, end] self.point_on_major_axis = point_on_major_axis def __repr__(self): pts = ", ".join(str(p._id) for p in self.points) return f"" pygmsh-7.1.17/src/pygmsh/common/geometry.py000066400000000000000000000321551417476615500207370ustar00rootroot00000000000000from __future__ import annotations import warnings import gmsh from ..helpers import extract_to_meshio from .bezier import Bezier from .bspline import BSpline from .circle_arc import CircleArc from .curve_loop import CurveLoop from .dummy import Dummy from .ellipse_arc import EllipseArc from .line import Line from .plane_surface import PlaneSurface from .point import Point from .polygon import Polygon from .size_field import BoundaryLayer, SetBackgroundMesh from .spline import Spline from .surface import Surface from .surface_loop import SurfaceLoop from .volume import Volume class CommonGeometry: """Geometry base class containing all methods that can be shared between built-in and occ. """ def __init__(self, env, init_argv=None): self.env = env self.init_argv = init_argv self._COMPOUND_ENTITIES = [] self._RECOMBINE_ENTITIES = [] self._EMBED_QUEUE = [] self._TRANSFINITE_CURVE_QUEUE = [] self._TRANSFINITE_SURFACE_QUEUE = [] self._TRANSFINITE_VOLUME_QUEUE = [] self._AFTER_SYNC_QUEUE = [] self._SIZE_QUEUE = [] self._PHYSICAL_QUEUE = [] self._OUTWARD_NORMALS = [] def __enter__(self): gmsh.initialize([] if self.init_argv is None else self.init_argv) gmsh.model.add("pygmsh model") return self def __exit__(self, *_): try: # Gmsh >= 4.7.0 # https://gitlab.onelab.info/gmsh/gmsh/-/issues/1036 gmsh.model.mesh.removeSizeCallback() except AttributeError: pass gmsh.finalize() def synchronize(self): self.env.synchronize() def __repr__(self): return "" def add_bspline(self, *args, **kwargs): return BSpline(self.env, *args, **kwargs) def add_bezier(self, *args, **kwargs): return Bezier(self.env, *args, **kwargs) def add_circle_arc(self, *args, **kwargs): return CircleArc(self.env, *args, **kwargs) def add_ellipse_arc(self, *args, **kwargs): return EllipseArc(self.env, *args, **kwargs) def add_line(self, *args, **kwargs): return Line(self.env, *args, **kwargs) def add_curve_loop(self, *args, **kwargs): return CurveLoop(self.env, *args, **kwargs) def add_plane_surface(self, *args, **kwargs): return PlaneSurface(self.env, *args, **kwargs) def add_point(self, *args, **kwargs): return Point(self.env, *args, **kwargs) def add_spline(self, *args, **kwargs): return Spline(self.env, *args, **kwargs) def add_surface(self, *args, **kwargs): return Surface(self.env, *args, **kwargs) def add_surface_loop(self, *args, **kwargs): return SurfaceLoop(self.env, *args, **kwargs) def add_volume(self, *args, **kwargs): return Volume(self.env, *args, **kwargs) def add_polygon(self, *args, **kwargs): return Polygon(self, *args, **kwargs) def add_physical(self, entities, label: str | None = None): if label in [label for _, label in self._PHYSICAL_QUEUE]: raise ValueError(f'Label "{label}" already exists.') if not isinstance(entities, list): entities = [entities] # make sure the dimensionality is the same for all entities dim = entities[0].dim for e in entities: assert e.dim == dim if label is None: # 2021-02-18 warnings.warn( "Physical groups without label are deprecated. " 'Use add_physical(entities, "dummy").' ) else: if not isinstance(label, str): raise ValueError(f"Physical label must be string, not {type(label)}.") self._PHYSICAL_QUEUE.append((entities, label)) def set_transfinite_curve( self, curve, num_nodes: int, mesh_type: str, coeff: float ): assert mesh_type in ["Progression", "Bump", "Beta"] self._TRANSFINITE_CURVE_QUEUE.append((curve._id, num_nodes, mesh_type, coeff)) def set_transfinite_surface(self, surface, arrangement: str, corner_pts): corner_tags = [pt._id for pt in corner_pts] self._TRANSFINITE_SURFACE_QUEUE.append((surface._id, arrangement, corner_tags)) def set_transfinite_volume(self, volume, corner_pts): corner_tags = [pt._id for pt in corner_pts] self._TRANSFINITE_VOLUME_QUEUE.append((volume._id, corner_tags)) def set_recombined_surfaces(self, surfaces): for i, surface in enumerate(surfaces): assert surface.dim == 2, f"item {i} is not a surface" self._RECOMBINE_ENTITIES += [s.dim_tags[0] for s in surfaces] def extrude( self, input_entity, translation_axis: tuple[float, float, float], num_layers: int | list[int] | None = None, heights: list[float] | None = None, recombine: bool = False, ): """Extrusion of any entity along a given translation_axis.""" if isinstance(num_layers, int): num_layers = [num_layers] if num_layers is None: num_layers = [] assert heights is None heights = [] else: if heights is None: heights = [] else: assert len(num_layers) == len(heights) assert len(translation_axis) == 3 ie_list = input_entity if isinstance(input_entity, list) else [input_entity] out_dim_tags = self.env.extrude( [e.dim_tag for e in ie_list], *translation_axis, numElements=num_layers, heights=heights, recombine=recombine, ) top = Dummy(*out_dim_tags[0]) extruded = Dummy(*out_dim_tags[1]) lateral = [Dummy(*e) for e in out_dim_tags[2:]] return top, extruded, lateral def _revolve( self, input_entity, rotation_axis: tuple[float, float, float], point_on_axis: tuple[float, float, float], angle: float, num_layers: int | list[int] | None = None, heights: list[float] | None = None, recombine: bool = False, ): """Rotation of any entity around a given rotation_axis, about a given angle.""" if isinstance(num_layers, int): num_layers = [num_layers] if num_layers is None: num_layers = [] heights = [] else: if heights is None: heights = [] else: assert len(num_layers) == len(heights) assert len(point_on_axis) == 3 assert len(rotation_axis) == 3 out_dim_tags = self.env.revolve( input_entity.dim_tags, *point_on_axis, *rotation_axis, angle, numElements=num_layers, heights=heights, recombine=recombine, ) top = Dummy(*out_dim_tags[0]) extruded = Dummy(*out_dim_tags[1]) lateral = [Dummy(*e) for e in out_dim_tags[2:]] return top, extruded, lateral def translate(self, obj, vector: tuple[float, float, float]): """Translates input_entity itself by vector. Changes the input object. """ self.env.translate(obj.dim_tags, *vector) def rotate( self, obj, point: tuple[float, float, float], angle: float, axis: tuple[float, float, float], ): """Rotate input_entity around a given point with a given angle. Rotation axis has to be specified. Changes the input object. """ self.env.rotate(obj.dim_tags, *point, *axis, angle) def copy(self, obj): dim_tag = self.env.copy(obj.dim_tags) assert len(dim_tag) == 1 return Dummy(*dim_tag[0]) def symmetrize(self, obj, coefficients: tuple[float, float, float, float]): """Transforms all elementary entities symmetrically to a plane. The vector should contain four expressions giving the coefficients of the plane's equation. """ self.env.symmetrize(obj.dim_tags, *coefficients) def dilate( self, obj, x0: tuple[float, float, float], abc: tuple[float, float, float] ): self.env.dilate(obj.dim_tags, *x0, *abc) def mirror(self, obj, abcd: tuple[float, float, float, float]): self.env.mirror(obj.dim_tags, *abcd) def remove(self, obj, recursive: bool = False): self.env.remove(obj.dim_tags, recursive=recursive) def in_surface(self, input_entity, surface): """Embed the point(s) or curve(s) in the given surface. The surface mesh will conform to the mesh of the point(s) or curves(s). """ self._EMBED_QUEUE.append((input_entity, surface)) def in_volume(self, input_entity, volume): """Embed the point(s)/curve(s)/surface(s) in the given volume. The volume mesh will conform to the mesh of the input entities. """ self._EMBED_QUEUE.append((input_entity, volume)) def set_mesh_size_callback(self, fun, ignore_other_mesh_sizes=True): gmsh.model.mesh.setSizeCallback(fun) # # If a mesh size is set from a function, ignore the mesh sizes from the # entities. # # From : # ``` # To determine the size of mesh elements, Gmsh locally computes the minimum of # # 1) the size of the model bounding box; # 2) if `Mesh.CharacteristicLengthFromPoints' is set, the mesh size specified at # geometrical points; # 3) if `Mesh.CharacteristicLengthFromCurvature' is set, the mesh size based on # the curvature and `Mesh.MinimumElementsPerTwoPi'; # 4) the background mesh field; # 5) any per-entity mesh size constraint. # # This value is then constrained in the interval # [`Mesh.CharacteristicLengthMin', `Mesh.CharacteristicLengthMax'] and # multiplied by `Mesh.CharacteristicLengthFactor'. In addition, boundary mesh # sizes (on curves or surfaces) are interpolated inside the enclosed entity # (surface or volume, respectively) if the option # `Mesh.CharacteristicLengthExtendFromBoundary' is set (which is the case by # default). # ``` if ignore_other_mesh_sizes: gmsh.option.setNumber("Mesh.CharacteristicLengthExtendFromBoundary", 0) gmsh.option.setNumber("Mesh.CharacteristicLengthFromPoints", 0) gmsh.option.setNumber("Mesh.CharacteristicLengthFromCurvature", 0) def add_boundary_layer(self, *args, **kwargs): layer = BoundaryLayer(*args, **kwargs) self._AFTER_SYNC_QUEUE.append(layer) return layer def set_background_mesh(self, *args, **kwargs): setter = SetBackgroundMesh(*args, **kwargs) self._AFTER_SYNC_QUEUE.append(setter) def generate_mesh( # noqa: C901 self, dim: int = 3, order: int | None = None, # http://gmsh.info/doc/texinfo/gmsh.html#index-Mesh_002eAlgorithm algorithm: int | None = None, verbose: bool = False, ): """Return a meshio.Mesh, storing the mesh points, cells, and data, generated by Gmsh from the `self`. """ self.synchronize() for item in self._AFTER_SYNC_QUEUE: item.exec() for item, host in self._EMBED_QUEUE: gmsh.model.mesh.embed(item.dim, [item._id], host.dim, host._id) # set compound entities after sync for c in self._COMPOUND_ENTITIES: gmsh.model.mesh.setCompound(*c) for s in self._RECOMBINE_ENTITIES: gmsh.model.mesh.setRecombine(*s) for t in self._TRANSFINITE_CURVE_QUEUE: gmsh.model.mesh.setTransfiniteCurve(*t) for t in self._TRANSFINITE_SURFACE_QUEUE: gmsh.model.mesh.setTransfiniteSurface(*t) for e in self._TRANSFINITE_VOLUME_QUEUE: gmsh.model.mesh.setTransfiniteVolume(*e) for item, size in self._SIZE_QUEUE: gmsh.model.mesh.setSize( gmsh.model.getBoundary(item.dim_tags, False, False, True), size ) for entities, label in self._PHYSICAL_QUEUE: d = entities[0].dim assert all(e.dim == d for e in entities) tag = gmsh.model.addPhysicalGroup(d, [e._id for e in entities]) if label is not None: gmsh.model.setPhysicalName(d, tag, label) for entity in self._OUTWARD_NORMALS: gmsh.model.mesh.setOutwardOrientation(entity.id) gmsh.option.setNumber("General.Terminal", 1 if verbose else 0) # set algorithm # http://gmsh.info/doc/texinfo/gmsh.html#index-Mesh_002eAlgorithm if algorithm: gmsh.option.setNumber("Mesh.Algorithm", algorithm) gmsh.model.mesh.generate(dim) # setOrder() after generate(), see # if order is not None: gmsh.model.mesh.setOrder(order) return extract_to_meshio() def save_geometry(self, filename: str): # filename is typically a geo_unrolled or brep file self.synchronize() gmsh.write(filename) pygmsh-7.1.17/src/pygmsh/common/line.py000066400000000000000000000015241417476615500200270ustar00rootroot00000000000000from .line_base import LineBase from .point import Point class Line(LineBase): """ Creates a straight line segment. Parameters ---------- p0 : Point object that represents the start of the line. p1 : Point object that represents the end of the line. Attributes ---------- points : array-like[1][2] List containing the begin and end points of the line. """ dim = 1 def __init__(self, env, p0: Point, p1: Point): assert isinstance(p0, Point) assert isinstance(p1, Point) id0 = env.addLine(p0._id, p1._id) self.dim_tag = (1, id0) self.dim_tags = [self.dim_tag] super().__init__(id0, [p0, p1]) def __repr__(self): pts = ", ".join(str(p._id) for p in self.points) return f"" pygmsh-7.1.17/src/pygmsh/common/line_base.py000066400000000000000000000006501417476615500210200ustar00rootroot00000000000000from __future__ import annotations import copy class LineBase: dim = 1 def __init__(self, id0: int, points: list[int]): self._id = id0 self.dim_tag = (1, self._id) self.dim_tags = [self.dim_tag] self.points = points def __neg__(self): neg_self = copy.deepcopy(self) neg_self._id = -self._id neg_self.points = self.points[::-1] return neg_self pygmsh-7.1.17/src/pygmsh/common/plane_surface.py000066400000000000000000000032371417476615500217120ustar00rootroot00000000000000from .curve_loop import CurveLoop class PlaneSurface: """ Creates a plane surface. Parameters ---------- curve_loop : Object Each unique line in the line loop will be used for the surface construction. holes : list List of line loops that represents polygon holes. Notes ----- The first line loop defines the exterior boundary of the surface; all other line loops define holes in the surface. A line loop defining a hole should not have any lines in common with the exterior line loop (in which case it is not a hole, and the two surfaces should be defined separately). Likewise, a line loop defining a hole should not have any lines in common with another line loop defining a hole in the same surface (in which case the two line loops should be combined). """ dim = 2 def __init__(self, env, curve_loop, holes=None): assert isinstance(curve_loop, CurveLoop) self.curve_loop = curve_loop if holes is None: holes = [] # The input holes are either line loops or entities that contain line loops # (like polygons). self.holes = [h if isinstance(h, CurveLoop) else h.curve_loop for h in holes] self.num_edges = len(self.curve_loop) + sum(len(h) for h in self.holes) curve_loops = [self.curve_loop] + self.holes self._id = env.addPlaneSurface([ll._id for ll in curve_loops]) self.dim_tag = (2, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return ( "" ) pygmsh-7.1.17/src/pygmsh/common/point.py000066400000000000000000000017411417476615500202320ustar00rootroot00000000000000from __future__ import annotations class Point: """ Creates an elementary point. Parameters ---------- x : Give the coordinates X, Y (and Z) of the point in the three-dimensional Euclidean space. mesh_size : The prescribed mesh element size at this point. Attributes ---------- x : array-like Point coordinates. """ dim = 0 def __init__( self, env, x: tuple[float, float] | tuple[float, float, float], mesh_size: float | None = None, ): if len(x) == 2: x = (x[0], x[1], 0.0) assert len(x) == 3 self.x = x args = list(x) if mesh_size is not None: args.append(mesh_size) self._id = env.addPoint(*args) self.dim_tag = (0, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): X = ", ".join(str(x) for x in self.x) return f"" pygmsh-7.1.17/src/pygmsh/common/polygon.py000066400000000000000000000030251417476615500205650ustar00rootroot00000000000000from __future__ import annotations import numpy as np from numpy.typing import ArrayLike class Polygon: dim = 2 def __init__( self, host, points: ArrayLike, mesh_size: float | list[float | None] | None = None, holes=None, make_surface: bool = True, ): if holes is None: holes = [] else: assert make_surface points = np.asarray(points) if isinstance(mesh_size, list): assert len(points) == len(mesh_size) else: mesh_size = len(points) * [mesh_size] if points.shape[1] == 2: points = np.column_stack([points, np.zeros_like(points[:, 0])]) # Create points. self.points = [ host.add_point(x, mesh_size=size) for x, size in zip(points, mesh_size) ] # Create lines self.curves = [ host.add_line(self.points[k], self.points[k + 1]) for k in range(len(self.points) - 1) ] + [host.add_line(self.points[-1], self.points[0])] self.lines = self.curves self.curve_loop = host.add_curve_loop(self.curves) # self.surface = host.add_plane_surface(ll, holes) if make_surface else None if make_surface: self.surface = host.add_plane_surface(self.curve_loop, holes) self.dim_tag = self.surface.dim_tag self.dim_tags = self.surface.dim_tags self._id = self.surface._id def __repr__(self): return "" pygmsh-7.1.17/src/pygmsh/common/size_field.py000066400000000000000000000046231417476615500212200ustar00rootroot00000000000000import gmsh class BoundaryLayer: def __init__( self, lcmin, lcmax, distmin, distmax, edges_list=None, faces_list=None, nodes_list=None, num_points_per_curve=None, ): self.lcmin = lcmin self.lcmax = lcmax self.distmin = distmin self.distmax = distmax # Don't use [] as default argument, cf. # self.edges_list = edges_list or [] self.faces_list = faces_list or [] self.nodes_list = nodes_list or [] self.num_points_per_curve = num_points_per_curve def exec(self): tag1 = gmsh.model.mesh.field.add("Distance") if self.edges_list: gmsh.model.mesh.field.setNumbers( tag1, "EdgesList", [e._id for e in self.edges_list] ) # edge nodes must be specified, too, cf. # # nodes = list(set([p for e in self.edges_list for p in e.points])) # gmsh.model.mesh.field.setNumbers(tag1, "NodesList", [n._id for n in nodes]) if self.faces_list: gmsh.model.mesh.field.setNumbers( tag1, "FacesList", [f._id for f in self.faces_list] ) if self.nodes_list: gmsh.model.mesh.field.setNumbers( tag1, "NodesList", [n._id for n in self.nodes_list] ) if self.num_points_per_curve: gmsh.model.mesh.field.setNumber( tag1, "NumPointsPerCurve", self.num_points_per_curve ) tag2 = gmsh.model.mesh.field.add("Threshold") gmsh.model.mesh.field.setNumber(tag2, "IField", tag1) gmsh.model.mesh.field.setNumber(tag2, "LcMin", self.lcmin) gmsh.model.mesh.field.setNumber(tag2, "LcMax", self.lcmax) gmsh.model.mesh.field.setNumber(tag2, "DistMin", self.distmin) gmsh.model.mesh.field.setNumber(tag2, "DistMax", self.distmax) self.tag = tag2 class SetBackgroundMesh: def __init__(self, fields, operator): self.fields = fields self.operator = operator def exec(self): tag = gmsh.model.mesh.field.add(self.operator) gmsh.model.mesh.field.setNumbers( tag, "FieldsList", [f.tag for f in self.fields] ) gmsh.model.mesh.field.setAsBackgroundMesh(tag) pygmsh-7.1.17/src/pygmsh/common/spline.py000066400000000000000000000010141417476615500203640ustar00rootroot00000000000000from __future__ import annotations from .line_base import LineBase from .point import Point class Spline(LineBase): """ With the built-in geometry kernel this constructs a Catmull-Rom spline. Parameters ---------- points : List containing Point objects """ def __init__(self, env, points: list[Point]): for c in points: assert isinstance(c, Point) assert len(points) > 1 id0 = env.addSpline([c._id for c in points]) super().__init__(id0, points) pygmsh-7.1.17/src/pygmsh/common/surface.py000066400000000000000000000017341417476615500205330ustar00rootroot00000000000000from .curve_loop import CurveLoop class Surface: """ Generates a Surface from a CurveLoop. Parameters ---------- curve_loop : Object CurveLoop object that contains all the Line objects for the loop construction. Notes ----- With the built-in kernel, the first line loop should be composed of either three or four elementary lines. With the built-in kernel, the optional In Sphere argument forces the surface to be a spherical patch (the extra parameter gives the identification number of the center of the sphere). """ dim = 2 def __init__(self, env, curve_loop): assert isinstance(curve_loop, CurveLoop) self.curve_loop = curve_loop self.num_edges = len(curve_loop) self._id = env.addSurfaceFilling([self.curve_loop._id]) self.dim_tag = (2, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/common/surface_loop.py000066400000000000000000000012551417476615500215620ustar00rootroot00000000000000class SurfaceLoop: """ Creates a surface loop (a shell). Parameters ---------- surfaces : list Contain the identification numbers of all the elementary surfaces that constitute the surface loop. Notes ----- A surface loop must always represent a closed shell, and the elementary surfaces should be oriented consistently (using negative identification numbers to specify reverse orientation). """ dim = 2 def __init__(self, env, surfaces): self.surfaces = surfaces self._id = env.addSurfaceLoop([s._id for s in surfaces]) self.dim_tag = (2, self._id) self.dim_tags = [self.dim_tag] pygmsh-7.1.17/src/pygmsh/common/volume.py000066400000000000000000000023201417476615500204020ustar00rootroot00000000000000class Volume: """ Creates a volume. Parameters ---------- surface_loop : list Contain the identification numbers of all the surface loops defining the volume. holes : list List containing surface loop objects that represents polygon holes. Notes ----- The first surface loop defines the exterior boundary of the volume; all other surface loops define holes in the volume. A surface loop defining a hole should not have any surfaces in common with the exterior surface loop (in which case it is not a hole, and the two volumes should be defined separately). Likewise, a surface loop defining a hole should not have any surfaces in common with another surface loop defining a hole in the same volume (in which case the two surface loops should be combined). """ dim = 3 def __init__(self, env, surface_loop, holes=None): if holes is None: holes = [] self.surface_loop = surface_loop self.holes = holes surface_loops = [surface_loop] + holes self._id = env.addVolume([s._id for s in surface_loops]) self.dim_tag = (3, self._id) self.dim_tags = [self.dim_tag] pygmsh-7.1.17/src/pygmsh/geo/000077500000000000000000000000001417476615500160065ustar00rootroot00000000000000pygmsh-7.1.17/src/pygmsh/geo/__init__.py000066400000000000000000000000671417476615500201220ustar00rootroot00000000000000from .geometry import Geometry __all__ = ["Geometry"] pygmsh-7.1.17/src/pygmsh/geo/dummy.py000066400000000000000000000004321417476615500175120ustar00rootroot00000000000000class Dummy: def __init__(self, dim, id0): assert isinstance(id0, int) self.dim = dim self._id = id0 self.dim_tag = (dim, id0) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/geo/geometry.py000066400000000000000000000477441417476615500202330ustar00rootroot00000000000000from __future__ import annotations import math import gmsh import numpy as np from .. import common from .dummy import Dummy class Circle: def __init__( self, x0: list[float], radius: float, R, compound, num_sections: int, holes, curve_loop, plane_surface, mesh_size: float | None = None, ): self.x0 = x0 self.radius = radius self.mesh_size = mesh_size self.R = R self.compound = compound self.num_sections = num_sections self.holes = holes self.curve_loop = curve_loop self.plane_surface = plane_surface class Geometry(common.CommonGeometry): def __init__(self, init_argv=None): super().__init__(gmsh.model.geo, init_argv=init_argv) def revolve(self, *args, **kwargs): if len(args) >= 4: angle = args[3] else: assert "angle" in kwargs angle = kwargs["angle"] assert angle < math.pi return super()._revolve(*args, **kwargs) def twist( self, input_entity, translation_axis: list[float], rotation_axis: list[float], point_on_axis: list[float], angle: float, num_layers: int | list[int] | None = None, heights: list[float] | None = None, recombine: bool = False, ): """Twist (translation + rotation) of any entity along a given translation_axis, around a given rotation_axis, about a given angle. """ if isinstance(num_layers, int): num_layers = [num_layers] if num_layers is None: num_layers = [] heights = [] else: if heights is None: heights = [] else: assert len(num_layers) == len(heights) assert len(point_on_axis) == 3 assert len(rotation_axis) == 3 assert len(translation_axis) == 3 assert angle < math.pi out_dim_tags = self.env.twist( input_entity.dim_tags, *point_on_axis, *translation_axis, *rotation_axis, angle, numElements=num_layers, heights=heights, recombine=recombine, ) top = Dummy(*out_dim_tags[0]) extruded = Dummy(*out_dim_tags[1]) lateral = [Dummy(*e) for e in out_dim_tags[2:]] return top, extruded, lateral def add_circle( self, x0: list[float], radius: float, mesh_size: float | None = None, R=None, compound=False, num_sections: int = 3, holes=None, make_surface: bool = True, ): """Add circle in the :math:`x`-:math:`y`-plane.""" if holes is None: holes = [] else: assert make_surface # Define points that make the circle (midpoint and the four cardinal # directions). X = np.zeros((num_sections + 1, len(x0))) if num_sections == 4: # For accuracy, the points are provided explicitly. X[1:, [0, 1]] = np.array( [[radius, 0.0], [0.0, radius], [-radius, 0.0], [0.0, -radius]] ) else: X[1:, [0, 1]] = np.array( [ [ radius * np.cos(2 * np.pi * k / num_sections), radius * np.sin(2 * np.pi * k / num_sections), ] for k in range(num_sections) ] ) if R is not None: assert np.allclose( abs(np.linalg.eigvals(R)), np.ones(X.shape[1]) ), "The transformation matrix doesn't preserve circles; at least one eigenvalue lies off the unit circle." X = np.dot(X, R.T) X += x0 # Add Gmsh Points. p = [self.add_point(x, mesh_size=mesh_size) for x in X] # Define the circle arcs. arcs = [ self.add_circle_arc(p[k], p[0], p[k + 1]) for k in range(1, len(p) - 1) ] + [self.add_circle_arc(p[-1], p[0], p[1])] if compound: self._COMPOUND_ENTITIES.append((1, [arc._id for arc in arcs])) curve_loop = self.add_curve_loop(arcs) if make_surface: plane_surface = self.add_plane_surface(curve_loop, holes) if compound: self._COMPOUND_ENTITIES.append((2, [plane_surface._id])) else: plane_surface = None return Circle( x0, radius, R, compound, num_sections, holes, curve_loop, plane_surface, mesh_size=mesh_size, ) def add_rectangle( self, xmin: float, xmax: float, ymin: float, ymax: float, z: float, mesh_size: float | None = None, holes=None, make_surface: bool = True, ): return self.add_polygon( [[xmin, ymin, z], [xmax, ymin, z], [xmax, ymax, z], [xmin, ymax, z]], mesh_size=mesh_size, holes=holes, make_surface=make_surface, ) def add_ellipsoid( self, x0: list[float], radii: list[float], mesh_size: float | None = None, with_volume: bool = True, holes=None, ): """Creates an ellipsoid with radii around a given midpoint :math:`x_0`.""" if holes is None: holes = [] if holes: assert with_volume # Add points. p = [ self.add_point(x0, mesh_size=mesh_size), self.add_point([x0[0] + radii[0], x0[1], x0[2]], mesh_size=mesh_size), self.add_point([x0[0], x0[1] + radii[1], x0[2]], mesh_size=mesh_size), self.add_point([x0[0], x0[1], x0[2] + radii[2]], mesh_size=mesh_size), self.add_point([x0[0] - radii[0], x0[1], x0[2]], mesh_size=mesh_size), self.add_point([x0[0], x0[1] - radii[1], x0[2]], mesh_size=mesh_size), self.add_point([x0[0], x0[1], x0[2] - radii[2]], mesh_size=mesh_size), ] # Add skeleton. # Alternative for circles: # `self.add_circle_arc(a, b, c)` c = [ self.add_ellipse_arc(p[1], p[0], p[6], p[6]), self.add_ellipse_arc(p[6], p[0], p[4], p[4]), self.add_ellipse_arc(p[4], p[0], p[3], p[3]), self.add_ellipse_arc(p[3], p[0], p[1], p[1]), self.add_ellipse_arc(p[1], p[0], p[2], p[2]), self.add_ellipse_arc(p[2], p[0], p[4], p[4]), self.add_ellipse_arc(p[4], p[0], p[5], p[5]), self.add_ellipse_arc(p[5], p[0], p[1], p[1]), self.add_ellipse_arc(p[6], p[0], p[2], p[2]), self.add_ellipse_arc(p[2], p[0], p[3], p[3]), self.add_ellipse_arc(p[3], p[0], p[5], p[5]), self.add_ellipse_arc(p[5], p[0], p[6], p[6]), ] # Add surfaces (1/8th of the ball surface). # Make sure the loops are oriented outwards! ll = [ # one half self.add_curve_loop([c[4], c[9], c[3]]), self.add_curve_loop([c[8], -c[4], c[0]]), self.add_curve_loop([-c[9], c[5], c[2]]), self.add_curve_loop([-c[5], -c[8], c[1]]), # the other half self.add_curve_loop([c[7], -c[3], c[10]]), self.add_curve_loop([c[11], -c[0], -c[7]]), self.add_curve_loop([-c[10], -c[2], c[6]]), self.add_curve_loop([-c[1], -c[11], -c[6]]), ] # Create a surface for each line loop. s = [self.add_surface(l) for l in ll] # Combine the surfaces to avoid seams # # Cannot enable those yet, self._COMPOUND_ENTITIES.append((2, [surf._id for surf in s[:4]])) self._COMPOUND_ENTITIES.append((2, [surf._id for surf in s[4:]])) # Create the surface loop. surface_loop = self.add_surface_loop(s) # if holes: # # Create an array of surface loops; the first entry is the outer # # surface loop, the following ones are holes. # surface_loop = self.add_array([surface_loop] + holes) # Create volume. volume = self.add_volume(surface_loop, holes) if with_volume else None class Ellipsoid: dim = 3 def __init__(self, x0, radii, surface_loop, volume, mesh_size=None): self.x0 = x0 self.mesh_size = mesh_size self.radii = radii self.surface_loop = surface_loop self.volume = volume return return Ellipsoid(x0, radii, surface_loop, volume, mesh_size=mesh_size) def add_ball(self, x0: list[float], radius: float, **kwargs): return self.add_ellipsoid(x0, [radius, radius, radius], **kwargs) def add_box( self, x0: float, x1: float, y0: float, y1: float, z0: float, z1: float, mesh_size: float | None = None, with_volume: bool = True, holes=None, ): if holes is None: holes = [] if holes: assert with_volume # Define corner points. p = [ self.add_point([x1, y1, z1], mesh_size=mesh_size), self.add_point([x1, y1, z0], mesh_size=mesh_size), self.add_point([x1, y0, z1], mesh_size=mesh_size), self.add_point([x1, y0, z0], mesh_size=mesh_size), self.add_point([x0, y1, z1], mesh_size=mesh_size), self.add_point([x0, y1, z0], mesh_size=mesh_size), self.add_point([x0, y0, z1], mesh_size=mesh_size), self.add_point([x0, y0, z0], mesh_size=mesh_size), ] # Define edges. e = [ self.add_line(p[0], p[1]), self.add_line(p[0], p[2]), self.add_line(p[0], p[4]), self.add_line(p[1], p[3]), self.add_line(p[1], p[5]), self.add_line(p[2], p[3]), self.add_line(p[2], p[6]), self.add_line(p[3], p[7]), self.add_line(p[4], p[5]), self.add_line(p[4], p[6]), self.add_line(p[5], p[7]), self.add_line(p[6], p[7]), ] # Define the six line loops. ll = [ self.add_curve_loop([e[0], e[3], -e[5], -e[1]]), self.add_curve_loop([e[0], e[4], -e[8], -e[2]]), self.add_curve_loop([e[1], e[6], -e[9], -e[2]]), self.add_curve_loop([e[3], e[7], -e[10], -e[4]]), self.add_curve_loop([e[5], e[7], -e[11], -e[6]]), self.add_curve_loop([e[8], e[10], -e[11], -e[9]]), ] # Create a surface for each line loop. s = [self.add_surface(l) for l in ll] # Create the surface loop. surface_loop = self.add_surface_loop(s) # Create volume vol = self.add_volume(surface_loop, holes) if with_volume else None class Box: def __init__( self, x0, x1, y0, y1, z0, z1, surface_loop, volume, mesh_size=None ): self.x0 = x0 self.x1 = x1 self.y0 = y0 self.y1 = y1 self.z0 = z0 self.z1 = z1 self.mesh_size = mesh_size self.surface_loop = surface_loop self.volume = volume return Box(x0, x1, y0, y1, z0, z1, surface_loop, vol, mesh_size=mesh_size) def add_torus( self, irad: float, orad: float, mesh_size: float | None = None, R=np.eye(3), x0=np.array([0.0, 0.0, 0.0]), variant: str = "extrude_lines", ): if variant == "extrude_lines": return self._add_torus_extrude_lines( irad, orad, mesh_size=mesh_size, R=R, x0=x0 ) assert variant == "extrude_circle" return self._add_torus_extrude_circle( irad, orad, mesh_size=mesh_size, R=R, x0=x0 ) def _add_torus_extrude_lines( self, irad: float, orad: float, mesh_size: float = None, R=np.eye(3), x0=np.array([0.0, 0.0, 0.0]), ): """Create Gmsh code for the torus in the x-y plane under the coordinate transformation .. math:: \\hat{x} = R x + x_0. :param irad: inner radius of the torus :param orad: outer radius of the torus """ # Add circle x0t = np.dot(R, np.array([0.0, orad, 0.0])) # Get circles in y-z plane Rc = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) c = self.add_circle(x0 + x0t, irad, mesh_size=mesh_size, R=np.dot(R, Rc)) rot_axis = [0.0, 0.0, 1.0] rot_axis = np.dot(R, rot_axis) point_on_rot_axis = [0.0, 0.0, 0.0] point_on_rot_axis = np.dot(R, point_on_rot_axis) + x0 # Form the torus by extruding the circle three times by 2/3*pi. This # works around the inability of Gmsh to extrude by pi or more. The # Extrude() macro returns an array; the first [0] entry in the array is # the entity that has been extruded at the far end. This can be used # for the following Extrude() step. The second [1] entry of the array # is the surface that was created by the extrusion. previous = c.curve_loop.curves angle = 2 * np.pi / 3 all_surfaces = [] for _ in range(3): for k, p in enumerate(previous): # ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};}; # ... top, surf, _ = self.revolve( p, rotation_axis=rot_axis, point_on_axis=point_on_rot_axis, angle=angle, ) all_surfaces.append(surf) previous[k] = top # compound_surface = CompoundSurface(all_surfaces) surface_loop = self.add_surface_loop(all_surfaces) vol = self.add_volume(surface_loop) return vol def _add_torus_extrude_circle( self, irad, orad, mesh_size=None, R=np.eye(3), x0=np.array([0.0, 0.0, 0.0]), ): """Create Gmsh code for the torus under the coordinate transformation .. math:: \\hat{x} = R x + x_0. :param irad: inner radius of the torus :param orad: outer radius of the torus """ # Add circle x0t = np.dot(R, np.array([0.0, orad, 0.0])) Rc = np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) c = self.add_circle(x0 + x0t, irad, mesh_size=mesh_size, R=np.dot(R, Rc)) rot_axis = [0.0, 0.0, 1.0] rot_axis = np.dot(R, rot_axis) point_on_rot_axis = [0.0, 0.0, 0.0] point_on_rot_axis = np.dot(R, point_on_rot_axis) + x0 # Form the torus by extruding the circle three times by 2/3*pi. This # works around the inability of Gmsh to extrude by pi or more. The # Extrude() macro returns an array; the first [0] entry in the array is # the entity that has been extruded at the far end. This can be used # for the following Extrude() step. The second [1] entry of the array # is the surface that was created by the extrusion. The third [2-end] # is a list of all the planes of the lateral surface. previous = c.plane_surface all_volumes = [] num_steps = 3 for _ in range(num_steps): top, vol, _ = self.revolve( previous, rotation_axis=rot_axis, point_on_axis=point_on_rot_axis, angle=2 * np.pi / num_steps, ) previous = top all_volumes.append(vol) assert int(gmsh.__version__.split(".")[0]) self._COMPOUND_ENTITIES.append((3, [v._id for v in all_volumes])) def add_pipe( self, outer_radius, inner_radius, length, R=np.eye(3), x0=np.array([0.0, 0.0, 0.0]), mesh_size=None, variant="rectangle_rotation", ): if variant == "rectangle_rotation": return self._add_pipe_by_rectangle_rotation( outer_radius, inner_radius, length, R=R, x0=x0, mesh_size=mesh_size ) assert variant == "circle_extrusion" return self._add_pipe_by_circle_extrusion( outer_radius, inner_radius, length, R=R, x0=x0, mesh_size=mesh_size ) def _add_pipe_by_rectangle_rotation( self, outer_radius, inner_radius, length, R=np.eye(3), x0=np.array([0.0, 0.0, 0.0]), mesh_size=None, ): """Hollow cylinder. Define a rectangle, extrude it by rotation. """ X = np.array( [ [0.0, outer_radius, -0.5 * length], [0.0, outer_radius, +0.5 * length], [0.0, inner_radius, +0.5 * length], [0.0, inner_radius, -0.5 * length], ] ) # Apply transformation. X = [np.dot(R, x) + x0 for x in X] # Create points set. p = [self.add_point(x, mesh_size=mesh_size) for x in X] # Define edges. e = [ self.add_line(p[0], p[1]), self.add_line(p[1], p[2]), self.add_line(p[2], p[3]), self.add_line(p[3], p[0]), ] rot_axis = [0.0, 0.0, 1.0] rot_axis = np.dot(R, rot_axis) point_on_rot_axis = [0.0, 0.0, 0.0] point_on_rot_axis = np.dot(R, point_on_rot_axis) + x0 # Extrude all edges three times by 2*Pi/3. previous = e angle = 2 * np.pi / 3 all_surfaces = [] # com = [] for _ in range(3): for k, p in enumerate(previous): # ts1[] = Extrude {{0,0,1}, {0,0,0}, 2*Pi/3}{Line{tc1};}; top, surf, _ = self.revolve( p, rotation_axis=rot_axis, point_on_axis=point_on_rot_axis, angle=angle, ) # if k==0: # com.append(surf) # else: # all_names.appends(surf) all_surfaces.append(surf) previous[k] = top # # cs = CompoundSurface(com) # Now just add surface loop and volume. # all_surfaces = all_names + [cs] surface_loop = self.add_surface_loop(all_surfaces) vol = self.add_volume(surface_loop) return vol def _add_pipe_by_circle_extrusion( self, outer_radius, inner_radius, length, R=np.eye(3), x0=np.array([0.0, 0.0, 0.0]), mesh_size=None, ): """Hollow cylinder. Define a ring, extrude it by translation. """ # Define ring which to Extrude by translation. Rc = np.array([[0.0, 0.0, 1.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0]]) c_inner = self.add_circle( x0, inner_radius, mesh_size=mesh_size, R=np.dot(R, Rc), make_surface=False, ) circ = self.add_circle( x0, outer_radius, mesh_size=mesh_size, R=np.dot(R, Rc), holes=[c_inner.curve_loop], ) # Now Extrude the ring surface. _, vol, _ = self.extrude( circ.plane_surface, translation_axis=np.dot(R, [length, 0, 0]) ) return vol def in_surface(self, input_entity, surface): """Embed the point(s) or curve(s) in the given surface. The surface mesh will conform to the mesh of the point(s) or curves(s). """ self._EMBED_QUEUE.append((input_entity, surface)) def in_volume(self, input_entity, volume): """Embed the point(s)/curve(s)/surface(s) in the given volume. The volume mesh will conform to the mesh of the input entities. """ self._EMBED_QUEUE.append((input_entity, volume)) pygmsh-7.1.17/src/pygmsh/helpers.py000066400000000000000000000105211417476615500172470ustar00rootroot00000000000000import gmsh import meshio import numpy as np def write(filename: str): import gmsh gmsh.write(filename) def rotation_matrix(u, theta): """Return matrix that implements the rotation around the vector :math:`u` by the angle :math:`\\theta`, cf. https://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle. :param u: rotation vector :param theta: rotation angle """ assert np.isclose(np.inner(u, u), 1.0), "the rotation axis must be unitary" # Cross-product matrix. cpm = np.array([[0.0, -u[2], u[1]], [u[2], 0.0, -u[0]], [-u[1], u[0], 0.0]]) c = np.cos(theta) s = np.sin(theta) R = np.eye(3) * c + s * cpm + (1.0 - c) * np.outer(u, u) return R def orient_lines(lines): """Given a sequence of unordered and unoriented lines defining a closed polygon, returns a reordered list of reoriented lines of that polygon. :param lines: a sequence of lines defining a closed polygon """ # Categorise graph edges by their vertex pair ids point_pair_ids = np.array( [[line.points[0]._id, line.points[1]._id] for line in lines] ) # Indices of reordering order = np.arange(len(point_pair_ids), dtype=int) # Compute orientations where oriented[j] == False requires edge j to be reversed oriented = np.array([True] * len(point_pair_ids), dtype=bool) for j in range(1, len(point_pair_ids)): out = point_pair_ids[j - 1, 1] # edge out from vertex inn = point_pair_ids[j:, 0] # candidates for edge into vertices wh = np.where(inn == out)[0] + j if len(wh) == 0: # look for candidates in those which are not correctly oriented inn = point_pair_ids[j:, 1] wh = np.where(inn == out)[0] + j # reorient remaining edges point_pair_ids[j:] = np.flip(point_pair_ids[j:], axis=1) oriented[j:] ^= True # reorder point_pair_ids[[j, wh[0]]] = point_pair_ids[[wh[0], j]] order[[j, wh[0]]] = order[[wh[0], j]] # Reconstruct an ordered and oriented line loop lines = [lines[o] for o in order] lines = [lines[j] if oriented[j] else -lines[j] for j in range(len(oriented))] return lines def extract_to_meshio(): # extract point coords idx, points, _ = gmsh.model.mesh.getNodes() points = np.asarray(points).reshape(-1, 3) idx -= 1 srt = np.argsort(idx) assert np.all(idx[srt] == np.arange(len(idx))) points = points[srt] # extract cells elem_types, elem_tags, node_tags = gmsh.model.mesh.getElements() cells = [] for elem_type, elem_tags, node_tags in zip(elem_types, elem_tags, node_tags): # `elementName', `dim', `order', `numNodes', `localNodeCoord', # `numPrimaryNodes' num_nodes_per_cell = gmsh.model.mesh.getElementProperties(elem_type)[3] node_tags_reshaped = np.asarray(node_tags).reshape(-1, num_nodes_per_cell) - 1 node_tags_sorted = node_tags_reshaped[np.argsort(elem_tags)] cells.append( meshio.CellBlock( meshio.gmsh.gmsh_to_meshio_type[elem_type], node_tags_sorted ) ) cell_sets = {} for dim, tag in gmsh.model.getPhysicalGroups(): name = gmsh.model.getPhysicalName(dim, tag) cell_sets[name] = [[] for _ in range(len(cells))] for e in gmsh.model.getEntitiesForPhysicalGroup(dim, tag): # TODO node_tags? # elem_types, elem_tags, node_tags elem_types, elem_tags, _ = gmsh.model.mesh.getElements(dim, e) assert len(elem_types) == len(elem_tags) assert len(elem_types) == 1 elem_type = elem_types[0] elem_tags = elem_tags[0] meshio_cell_type = meshio.gmsh.gmsh_to_meshio_type[elem_type] # make sure that the cell type appears only once in the cell list # -- for now idx = [] for k, cell_block in enumerate(cells): if cell_block.type == meshio_cell_type: idx.append(k) assert len(idx) == 1 idx = idx[0] cell_sets[name][idx].append(elem_tags - 1) cell_sets[name] = [ (None if len(idcs) == 0 else np.concatenate(idcs)) for idcs in cell_sets[name] ] # make meshio mesh return meshio.Mesh(points, cells, cell_sets=cell_sets) pygmsh-7.1.17/src/pygmsh/occ/000077500000000000000000000000001417476615500160005ustar00rootroot00000000000000pygmsh-7.1.17/src/pygmsh/occ/__init__.py000066400000000000000000000000671417476615500201140ustar00rootroot00000000000000from .geometry import Geometry __all__ = ["Geometry"] pygmsh-7.1.17/src/pygmsh/occ/ball.py000066400000000000000000000021731417476615500172670ustar00rootroot00000000000000from math import pi import gmsh class Ball: """ Creates a sphere. Parameters ---------- center: array-like[3] Center of the ball. radius: float Radius of the ball. x0: float If specified and `x0 > -1`, the ball is cut off at `x0*radius` parallel to the y-z plane. x1: float If specified and `x1 < +1`, the ball is cut off at `x1*radius` parallel to the y-z plane. alpha: float If specified and `alpha < 2*pi`, the points between `alpha` and `2*pi` w.r.t. to the x-y plane are not part of the object. char_length: float If specified, sets the `Characteristic Length` property. """ dim = 3 def __init__(self, center, radius, angle1=-pi / 2, angle2=pi / 2, angle3=2 * pi): self.center = center self.radius = radius self._id = gmsh.model.occ.addSphere( *center, radius, angle1=angle1, angle2=angle2, angle3=angle3 ) self.dim_tag = (3, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/box.py000066400000000000000000000012231417476615500171400ustar00rootroot00000000000000import gmsh class Box: """ Creates a box. Parameters ---------- x0 : array-like[3] List containing the x, y, z values of the start point. extends : array-like[3] List of the 3 extents of the box edges. char_length : float Characteristic length of the mesh elements of this polygon. """ dim = 3 def __init__(self, x0, extents, char_length=None): assert len(x0) == 3 assert len(extents) == 3 self.x0 = x0 self.extents = extents self._id = gmsh.model.occ.addBox(*x0, *extents) self.dim_tag = (3, self._id) self.dim_tags = [self.dim_tag] pygmsh-7.1.17/src/pygmsh/occ/cone.py000066400000000000000000000016561417476615500173060ustar00rootroot00000000000000from math import pi import gmsh class Cone: """ Creates a cone. center : array-like[3] The 3 coordinates of the center of the first circular face. axis : array-like[3] The 3 components of the vector defining its axis. radius0 : float Radius of the first circle. radius1 : float Radius of the second circle. angle : float Angular opening of the the Cone. """ dim = 3 def __init__(self, center, axis, radius0, radius1, angle=2 * pi): assert len(center) == 3 assert len(axis) == 3 self.center = center self.axis = axis self.radius0 = radius0 self.radius1 = radius1 self._id = gmsh.model.occ.addCone(*center, *axis, radius0, radius1, angle=angle) self.dim_tag = (3, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/cylinder.py000066400000000000000000000015621417476615500201670ustar00rootroot00000000000000from math import pi import gmsh class Cylinder: """ Creates a cylinder. Parameters ---------- x0 : array-like[3] The 3 coordinates of the center of the first circular face. axis : array-like[3] The 3 components of the vector defining its axis. radius : float Radius value of the cylinder. angle : float Angular opening of the cylinder. """ dim = 3 def __init__(self, x0, axis, radius, angle=2 * pi): assert len(x0) == 3 assert len(axis) == 3 self.x0 = x0 self.axis = axis self.radius = radius self.angle = angle self._id = gmsh.model.occ.addCylinder(*x0, *axis, radius, angle=angle) self.dim_tag = (3, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/disk.py000066400000000000000000000017551417476615500173140ustar00rootroot00000000000000from __future__ import annotations import gmsh class Disk: """ Creates a disk. Parameters ---------- x0 : array-like[3] The 3 coordinates of the center of the disk face. radius0 : float Radius value of the disk. radius1 : float Radius along Y, leading to an ellipse. """ dim = 2 def __init__( self, x0: tuple[float, float] | tuple[float, float, float], radius0: float, radius1: float | None = None, ): if len(x0) == 2: x0 = (x0[0], x0[1], 0.0) assert len(x0) == 3 if radius1 is None: radius1 = radius0 assert radius0 >= radius1 self.x0 = x0 self.radius0 = radius0 self.radius1 = radius1 self._id = gmsh.model.occ.addDisk(*x0, radius0, radius1) self.dim_tag = (self.dim, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/dummy.py000066400000000000000000000004321417476615500175040ustar00rootroot00000000000000class Dummy: def __init__(self, dim, id0): assert isinstance(id0, int) self.dim = dim self._id = id0 self.dim_tag = (dim, id0) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/geometry.py000066400000000000000000000217101417476615500202060ustar00rootroot00000000000000import math import warnings from itertools import groupby import gmsh from .. import common from .ball import Ball from .box import Box from .cone import Cone from .cylinder import Cylinder from .disk import Disk from .dummy import Dummy from .rectangle import Rectangle from .torus import Torus from .wedge import Wedge # def _all_equal(iterable): g = groupby(iterable) return next(g, True) and not next(g, False) class Geometry(common.CommonGeometry): def __init__(self, init_argv=None): super().__init__(gmsh.model.occ, init_argv=init_argv) def __exit__(self, *_): # TODO remove once gmsh 4.7.0 is out long enough (out November 5, 2020) # gmsh.option.setNumber("Mesh.CharacteristicLengthMin", 0.0) gmsh.option.setNumber("Mesh.CharacteristicLengthMax", 1.0e22) gmsh.finalize() @property def characteristic_length_min(self): return gmsh.option.getNumber("Mesh.CharacteristicLengthMin") @property def characteristic_length_max(self): return gmsh.option.getNumber("Mesh.CharacteristicLengthMax") @characteristic_length_min.setter def characteristic_length_min(self, val): gmsh.option.setNumber("Mesh.CharacteristicLengthMin", val) @characteristic_length_max.setter def characteristic_length_max(self, val): gmsh.option.setNumber("Mesh.CharacteristicLengthMax", val) def force_outward_normals(self, tag): self._OUTWARD_NORMALS.append(tag) def revolve(self, *args, **kwargs): if len(args) >= 4: angle = args[3] else: assert "angle" in kwargs angle = kwargs["angle"] assert angle < 2 * math.pi return super()._revolve(*args, **kwargs) def add_rectangle(self, *args, mesh_size=None, **kwargs): entity = Rectangle(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((entity, mesh_size)) return entity def add_disk(self, *args, mesh_size=None, **kwargs): entity = Disk(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((entity, mesh_size)) return entity def add_ball(self, *args, mesh_size=None, **kwargs): obj = Ball(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((obj, mesh_size)) return obj def add_box(self, *args, mesh_size=None, **kwargs): box = Box(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((box, mesh_size)) return box def add_cone(self, *args, mesh_size=None, **kwargs): cone = Cone(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((cone, mesh_size)) return cone def add_cylinder(self, *args, mesh_size=None, **kwargs): cyl = Cylinder(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((cyl, mesh_size)) return cyl def add_ellipsoid(self, center, radii, mesh_size=None): obj = Ball(center, 1.0) self.dilate(obj, center, radii) if mesh_size is not None: self._SIZE_QUEUE.append((obj, mesh_size)) return obj def add_torus(self, *args, mesh_size=None, **kwargs): obj = Torus(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((obj, mesh_size)) return obj def add_wedge(self, *args, mesh_size=None, **kwargs): obj = Wedge(*args, **kwargs) if mesh_size is not None: self._SIZE_QUEUE.append((obj, mesh_size)) return obj def boolean_intersection( self, entities, delete_first: bool = True, delete_other: bool = True ): """Boolean intersection, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation. """ entities = [e if isinstance(e, list) else [e] for e in entities] ent = [e.dim_tag for e in entities[0]] # form subsequent intersections # https://gitlab.onelab.info/gmsh/gmsh/-/issues/999 for e in entities[1:]: out, _ = gmsh.model.occ.intersect( ent, [ee.dim_tag for ee in e], removeObject=delete_first, removeTool=delete_other, ) if len(out) == 0: raise RuntimeError("Empty intersection.") if not _all_equal(out): raise RuntimeError( f"Expected all-equal elements, but got dim_tags {out}" ) ent = [out[0]] # remove entities from SIZE_QUEUE if necessary all_entities = [] if delete_first: all_entities += entities[0] if delete_other: for e in entities[1:]: all_entities += e for s in self._SIZE_QUEUE: if s[0] in all_entities: warnings.warn( f"Specified mesh size for {s[0]} " "discarded in Boolean intersection operation." ) self._SIZE_QUEUE = [s for s in self._SIZE_QUEUE if s[0] not in all_entities] return [Dummy(*ent[0])] def boolean_union( self, entities, delete_first: bool = True, delete_other: bool = True ): """Boolean union, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation. """ entities = [e if isinstance(e, list) else [e] for e in entities] dim_tags, _ = gmsh.model.occ.fuse( [e.dim_tag for e in entities[0]], [ee.dim_tag for e in entities[1:] for ee in e], removeObject=delete_first, removeTool=delete_other, ) # remove entities from SIZE_QUEUE if necessary all_entities = [] if delete_first: all_entities += entities[0] if delete_other: for ent in entities[1:]: all_entities += ent for s in self._SIZE_QUEUE: if s[0] in all_entities: warnings.warn( f"Specified mesh size for {s[0]} " "discarded in Boolean union operation." ) self._SIZE_QUEUE = [s for s in self._SIZE_QUEUE if s[0] not in all_entities] return [Dummy(*dim_tag) for dim_tag in dim_tags] def boolean_difference( self, d0, d1, delete_first: bool = True, delete_other: bool = True ): """Boolean difference, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation. """ d0 = d0 if isinstance(d0, list) else [d0] d1 = d1 if isinstance(d1, list) else [d1] dim_tags, _ = gmsh.model.occ.cut( [d.dim_tag for d in d0], [d.dim_tag for d in d1], removeObject=delete_first, removeTool=delete_other, ) # remove entities from SIZE_QUEUE if necessary all_entities = [] if delete_first: all_entities += d0 if delete_other: all_entities += d1 for s in self._SIZE_QUEUE: if s[0] in all_entities: warnings.warn( f"Specified mesh size for {s[0]} " "discarded in Boolean difference operation." ) self._SIZE_QUEUE = [s for s in self._SIZE_QUEUE if s[0] not in all_entities] return [Dummy(*dim_tag) for dim_tag in dim_tags] def boolean_fragments( self, d0, d1, delete_first: bool = True, delete_other: bool = True ): """Boolean fragments, see https://gmsh.info/doc/texinfo/gmsh.html#Boolean-operations input_entity and tool_entity are called object and tool in gmsh documentation. """ d0 = d0 if isinstance(d0, list) else [d0] d1 = d1 if isinstance(d1, list) else [d1] dim_tags, _ = gmsh.model.occ.fragment( [d.dim_tag for d in d0], [d.dim_tag for d in d1], removeObject=delete_first, removeTool=delete_other, ) # remove entities from SIZE_QUEUE if necessary all_entities = [] if delete_first: all_entities += d0 if delete_other: all_entities += d1 for s in self._SIZE_QUEUE: if s[0] in all_entities: warnings.warn( f"Specified mesh size for {s[0]} " "discarded in Boolean fragments operation." ) self._SIZE_QUEUE = [s for s in self._SIZE_QUEUE if s[0] not in all_entities] return [Dummy(*dim_tag) for dim_tag in dim_tags] def import_shapes(self, filename: str): s = gmsh.model.occ.importShapes(filename) return [Dummy(*i) for i in s] pygmsh-7.1.17/src/pygmsh/occ/rectangle.py000066400000000000000000000017271417476615500203250ustar00rootroot00000000000000from __future__ import annotations import gmsh class Rectangle: """ Creates a rectangle. x0 : array-like[3] The 3 first expressions define the lower-left corner. a : float Rectangle width. b : float Rectangle height. corner_radius : float Defines a radius to round the rectangle corners. """ dim = 2 def __init__( self, x0: tuple[float, float, float], a: float, b: float, corner_radius: float | None = None, ): assert len(x0) == 3 self.x0 = x0 self.a = a self.b = b self.corner_radius = corner_radius if corner_radius is None: corner_radius = 0.0 self._id = gmsh.model.occ.addRectangle(*x0, a, b, roundedRadius=corner_radius) self.dim_tag = (self.dim, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/torus.py000066400000000000000000000013721417476615500175310ustar00rootroot00000000000000from math import pi import gmsh class Torus: """ Creates a torus. center : array-like[3] The 3 coordinates of its center. radius0 : float Inner radius. radius1 : float Outer radius. alpha : float Defines the angular opening. """ dim = 3 def __init__(self, center, radius0, radius1, alpha=2 * pi): assert len(center) == 3 self.center = center self.radius0 = radius0 self.radius1 = radius1 self.alpha = alpha self._id = gmsh.model.occ.addTorus(*center, radius0, radius1, angle=alpha) self.dim_tag = (3, self._id) self.dim_tags = [self.dim_tag] def __repr__(self): return f"" pygmsh-7.1.17/src/pygmsh/occ/wedge.py000066400000000000000000000011771417476615500174530ustar00rootroot00000000000000import gmsh class Wedge: """ Creates a right angular wedge. x0 : array-like[3] The 3 coordinates of the right-angle point. extends : array-like[3] List of the 3 extends of the box edges. top_extend : float Defines the top X extent. """ dim = 3 def __init__(self, x0, extents, top_extent=None): self.x0 = x0 self.extents = extents self.top_extent = top_extent self._id = gmsh.model.occ.addWedge(*x0, *extents, ltx=top_extent) self.dim_tags = [(3, self._id)] def __repr__(self): return f"" pygmsh-7.1.17/tests/000077500000000000000000000000001417476615500143005ustar00rootroot00000000000000pygmsh-7.1.17/tests/built_in/000077500000000000000000000000001417476615500161055ustar00rootroot00000000000000pygmsh-7.1.17/tests/built_in/helpers.py000066400000000000000000000051071417476615500201240ustar00rootroot00000000000000import math import numpy as np def prune_nodes(points, cells): # Only points/cells that actually used uvertices, uidx = np.unique(cells, return_inverse=True) cells = uidx.reshape(cells.shape) points = points[uvertices] return points, cells def get_triangle_volumes(pts, cells): # Works in any dimension; taken from voropy local_idx = np.array([[1, 2], [2, 0], [0, 1]]).T idx_hierarchy = cells.T[local_idx] half_edge_coords = pts[idx_hierarchy[1]] - pts[idx_hierarchy[0]] ei_dot_ej = np.einsum( "ijk, ijk->ij", half_edge_coords[[1, 2, 0]], half_edge_coords[[2, 0, 1]] ) vols = 0.5 * np.sqrt( +ei_dot_ej[2] * ei_dot_ej[0] + ei_dot_ej[0] * ei_dot_ej[1] + ei_dot_ej[1] * ei_dot_ej[2] ) return vols def get_simplex_volumes(pts, cells): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = np.concatenate([p, np.ones(list(p.shape[:2]) + [1])], axis=-1) return np.abs(np.linalg.det(p) / math.factorial(n)) def compute_volume(mesh): if "tetra" in mesh.cells_dict: vol = math.fsum( get_simplex_volumes(*prune_nodes(mesh.points, mesh.cells_dict["tetra"])) ) elif "triangle" in mesh.cells_dict or "quad" in mesh.cells_dict: vol = 0.0 if "triangle" in mesh.cells_dict: # triangles vol += math.fsum( get_triangle_volumes( *prune_nodes(mesh.points, mesh.cells_dict["triangle"]) ) ) if "quad" in mesh.cells_dict: # quad: treat as two triangles quads = mesh.cells_dict["quad"].T split_cells = np.column_stack( [[quads[0], quads[1], quads[2]], [quads[0], quads[2], quads[3]]] ).T vol += math.fsum( get_triangle_volumes(*prune_nodes(mesh.points, split_cells)) ) else: assert "line" in mesh.cells_dict segs = np.diff(mesh.points[mesh.cells_dict["line"]], axis=1).squeeze() vol = np.sum(np.sqrt(np.einsum("...j, ...j", segs, segs))) return vol def plot(filename, points, triangles): from matplotlib import pyplot as plt pts = points[:, :2] for e in triangles: for idx in [[0, 1], [1, 2], [2, 0]]: X = pts[e[idx]] plt.plot(X[:, 0], X[:, 1], "-k") plt.gca().set_aspect("equal", "datalim") plt.axis("off") # plt.show() plt.savefig(filename, transparent=True) pygmsh-7.1.17/tests/built_in/test_airfoil.py000066400000000000000000000123561417476615500211520ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(): # Airfoil coordinates airfoil_coordinates = np.array( [ [1.000000, 0.000000, 0.0], [0.999023, 0.000209, 0.0], [0.996095, 0.000832, 0.0], [0.991228, 0.001863, 0.0], [0.984438, 0.003289, 0.0], [0.975752, 0.005092, 0.0], [0.965201, 0.007252, 0.0], [0.952825, 0.009744, 0.0], [0.938669, 0.012538, 0.0], [0.922788, 0.015605, 0.0], [0.905240, 0.018910, 0.0], [0.886092, 0.022419, 0.0], [0.865417, 0.026096, 0.0], [0.843294, 0.029903, 0.0], [0.819807, 0.033804, 0.0], [0.795047, 0.037760, 0.0], [0.769109, 0.041734, 0.0], [0.742094, 0.045689, 0.0], [0.714107, 0.049588, 0.0], [0.685258, 0.053394, 0.0], [0.655659, 0.057071, 0.0], [0.625426, 0.060584, 0.0], [0.594680, 0.063897, 0.0], [0.563542, 0.066977, 0.0], [0.532136, 0.069789, 0.0], [0.500587, 0.072303, 0.0], [0.469022, 0.074486, 0.0], [0.437567, 0.076312, 0.0], [0.406350, 0.077752, 0.0], [0.375297, 0.078743, 0.0], [0.344680, 0.079180, 0.0], [0.314678, 0.079051, 0.0], [0.285418, 0.078355, 0.0], [0.257025, 0.077096, 0.0], [0.229618, 0.075287, 0.0], [0.203313, 0.072945, 0.0], [0.178222, 0.070096, 0.0], [0.154449, 0.066770, 0.0], [0.132094, 0.063005, 0.0], [0.111248, 0.058842, 0.0], [0.091996, 0.054325, 0.0], [0.074415, 0.049504, 0.0], [0.058573, 0.044427, 0.0], [0.044532, 0.039144, 0.0], [0.032343, 0.033704, 0.0], [0.022051, 0.028152, 0.0], [0.013692, 0.022531, 0.0], [0.007292, 0.016878, 0.0], [0.002870, 0.011224, 0.0], [0.000439, 0.005592, 0.0], [0.000000, 0.000000, 0.0], [0.001535, -0.005395, 0.0], [0.005015, -0.010439, 0.0], [0.010421, -0.015126, 0.0], [0.017725, -0.019451, 0.0], [0.026892, -0.023408, 0.0], [0.037880, -0.026990, 0.0], [0.050641, -0.030193, 0.0], [0.065120, -0.033014, 0.0], [0.081257, -0.035451, 0.0], [0.098987, -0.037507, 0.0], [0.118239, -0.039185, 0.0], [0.138937, -0.040493, 0.0], [0.161004, -0.041444, 0.0], [0.184354, -0.042054, 0.0], [0.208902, -0.042343, 0.0], [0.234555, -0.042335, 0.0], [0.261221, -0.042058, 0.0], [0.288802, -0.041541, 0.0], [0.317197, -0.040817, 0.0], [0.346303, -0.039923, 0.0], [0.376013, -0.038892, 0.0], [0.406269, -0.037757, 0.0], [0.437099, -0.036467, 0.0], [0.468187, -0.035009, 0.0], [0.499413, -0.033414, 0.0], [0.530654, -0.031708, 0.0], [0.561791, -0.029917, 0.0], [0.592701, -0.028066, 0.0], [0.623264, -0.026176, 0.0], [0.653358, -0.024269, 0.0], [0.682867, -0.022360, 0.0], [0.711672, -0.020466, 0.0], [0.739659, -0.018600, 0.0], [0.766718, -0.016774, 0.0], [0.792738, -0.014999, 0.0], [0.817617, -0.013284, 0.0], [0.841253, -0.011637, 0.0], [0.863551, -0.010068, 0.0], [0.884421, -0.008583, 0.0], [0.903777, -0.007191, 0.0], [0.921540, -0.005900, 0.0], [0.937637, -0.004717, 0.0], [0.952002, -0.003650, 0.0], [0.964576, -0.002708, 0.0], [0.975305, -0.001896, 0.0], [0.984145, -0.001222, 0.0], [0.991060, -0.000691, 0.0], [0.996020, -0.000308, 0.0], [0.999004, -0.000077, 0.0], ] ) # Scale airfoil to input coord coord = 1.0 airfoil_coordinates *= coord # Instantiate geometry object with pygmsh.geo.Geometry() as geom: # Create polygon for airfoil char_length = 1.0e-1 airfoil = geom.add_polygon(airfoil_coordinates, char_length, make_surface=False) # Create surface for numerical domain with an airfoil-shaped hole left_dist = 1.0 right_dist = 3.0 top_dist = 1.0 bottom_dist = 1.0 xmin = airfoil_coordinates[:, 0].min() - left_dist * coord xmax = airfoil_coordinates[:, 0].max() + right_dist * coord ymin = airfoil_coordinates[:, 1].min() - bottom_dist * coord ymax = airfoil_coordinates[:, 1].max() + top_dist * coord domainCoordinates = np.array( [[xmin, ymin, 0.0], [xmax, ymin, 0.0], [xmax, ymax, 0.0], [xmin, ymax, 0.0]] ) polygon = geom.add_polygon(domainCoordinates, char_length, holes=[airfoil]) geom.set_recombined_surfaces([polygon.surface]) ref = 10.525891646546 mesh = geom.generate_mesh() assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("airfoil.vtu") pygmsh-7.1.17/tests/built_in/test_bsplines.py000066400000000000000000000016751417476615500213460ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: lcar = 0.1 p1 = geom.add_point([0.0, 0.0, 0.0], lcar) p2 = geom.add_point([1.0, 0.0, 0.0], lcar) p3 = geom.add_point([1.0, 0.5, 0.0], lcar) p4 = geom.add_point([1.0, 1.0, 0.0], lcar) s1 = geom.add_bspline([p1, p2, p3, p4]) p2 = geom.add_point([0.0, 1.0, 0.0], lcar) p3 = geom.add_point([0.5, 1.0, 0.0], lcar) s2 = geom.add_bspline([p4, p3, p2, p1]) ll = geom.add_curve_loop([s1, s2]) pl = geom.add_plane_surface(ll) # test some __repr__ print(p1) print(ll) print(s1) print(pl) mesh = geom.generate_mesh(verbose=True) # ref = 0.9156598733673261 ref = 0.7474554072002251 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("bsplines.vtu") pygmsh-7.1.17/tests/built_in/test_circle.py000066400000000000000000000013551417476615500207630ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: geom.add_circle( [0.0, 0.0, 0.0], 1.0, mesh_size=0.1, num_sections=4, # If compound==False, the section borders have to be points of the # discretization. If using a compound circle, they don't; gmsh can # choose by itself where to point the circle points. compound=True, ) # geom.add_physical(c.plane_surface, "super disk") mesh = geom.generate_mesh() ref = 3.1363871677682247 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("circle.vtk") pygmsh-7.1.17/tests/built_in/test_circle_transform.py000066400000000000000000000011111417476615500230440ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(radius=1.0): with pygmsh.geo.Geometry() as geom: R = [ pygmsh.rotation_matrix(np.eye(1, 3, d)[0], theta) for d, theta in enumerate(np.pi / np.array([2.0, 3.0, 5])) ] geom.add_circle([7.0, 11.0, 13.0], radius, 0.1, R[0] @ R[1] @ R[2]) ref = np.pi * radius ** 2 mesh = geom.generate_mesh() assert np.isclose(compute_volume(mesh), ref, rtol=1e-2) return mesh if __name__ == "__main__": test().write("circle_transformed.vtk") pygmsh-7.1.17/tests/built_in/test_cube.py000066400000000000000000000005541417476615500204400ustar00rootroot00000000000000"""Creates a mesh on a cube. """ from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: geom.add_box(0, 1, 0, 1, 0, 1, 1.0) mesh = geom.generate_mesh() ref = 1.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("cube.vtu") pygmsh-7.1.17/tests/built_in/test_ellipsoid.py000066400000000000000000000006371417476615500215100ustar00rootroot00000000000000""" Creates a mesh for an ellipsoid. """ from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: geom.add_ellipsoid([0.0, 0.0, 0.0], [1.0, 0.5, 0.75], 0.05) mesh = geom.generate_mesh() ref = 1.5676038497587947 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("ellipsoid.vtu") pygmsh-7.1.17/tests/built_in/test_embed.py000066400000000000000000000030201417476615500205650ustar00rootroot00000000000000import pytest from helpers import compute_volume import pygmsh def test_in_surface(): with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [ [0, 0.3], [0, 1.1], [0.9, 1.1], [0.9, 0.3], [0.6, 0.7], [0.3, 0.7], [0.2, 0.4], ], mesh_size=[0.2, 0.2, 0.2, 0.2, 0.03, 0.03, 0.01], ) geom.in_surface(poly.lines[4], poly) geom.in_surface(poly.points[6], poly) mesh = geom.generate_mesh() ref = 0.505 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh # Exception: PLC Error: A segment and a facet intersect at point @pytest.mark.skip def test_in_volume(): with pygmsh.geo.Geometry() as geom: box = geom.add_box(-1, 2, -1, 2, 0, 1, mesh_size=0.5) poly = geom.add_polygon( [ [0.0, 0.3], [0.0, 1.1], [0.9, 1.1], [0.9, 0.3], [0.6, 0.7], [0.3, 0.7], [0.2, 0.4], ], mesh_size=[0.2, 0.2, 0.2, 0.2, 0.03, 0.03, 0.01], ) geom.in_volume(poly.lines[4], box.volume) geom.in_volume(poly.points[6], box.volume) geom.in_volume(poly, box.volume) mesh = geom.generate_mesh() ref = 30.505 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test_in_surface().write("test.vtk") pygmsh-7.1.17/tests/built_in/test_hex.py000066400000000000000000000022011417476615500202750ustar00rootroot00000000000000from itertools import permutations import meshio from helpers import compute_volume import pygmsh def test(lcar=1.0): with pygmsh.geo.Geometry() as geom: lbw = [2, 3, 5] points = [geom.add_point([x, 0.0, 0.0], lcar) for x in [0.0, lbw[0]]] line = geom.add_line(*points) _, rectangle, _ = geom.extrude( line, translation_axis=[0.0, lbw[1], 0.0], num_layers=lbw[1], recombine=True ) geom.extrude( rectangle, translation_axis=[0.0, 0.0, lbw[2]], num_layers=lbw[2], recombine=True, ) # compute_volume only supports 3D for tetras, but does return surface area for # quads mesh = geom.generate_mesh() # mesh.remove_lower_dimensional_cells() # mesh.remove_orphaned_nodes() ref = sum(l * w for l, w in permutations(lbw, 2)) # surface area # TODO compute hex volumes quad_mesh = meshio.Mesh(mesh.points, {"quad": mesh.cells_dict["quad"]}) assert abs(compute_volume(quad_mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": meshio.write("hex.vtu", test()) pygmsh-7.1.17/tests/built_in/test_hole_in_square.py000066400000000000000000000017631417476615500225220ustar00rootroot00000000000000import numpy as np import pygmsh def test(): # Characteristic length lcar = 1e-1 # Coordinates of lower-left and upper-right vertices of a square domain xmin = 0.0 xmax = 5.0 ymin = 0.0 ymax = 5.0 # Vertices of a square hole squareHoleCoordinates = np.array([[1.0, 1.0], [4.0, 1.0], [4.0, 4.0], [1.0, 4.0]]) with pygmsh.geo.Geometry() as geom: # Create square hole squareHole = geom.add_polygon(squareHoleCoordinates, lcar, make_surface=False) # Create square domain with square hole geom.add_rectangle( xmin, xmax, ymin, ymax, 0.0, lcar, holes=[squareHole.curve_loop] ) mesh = geom.generate_mesh(order=2) assert "triangle6" in mesh.cells_dict # TODO support for volumes of triangle6 # ref = 16.0 # from helpers import compute_volume # assert abs(compute_volume(points, cells) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("hole_in_square.vtu") pygmsh-7.1.17/tests/built_in/test_layers.py000066400000000000000000000017251417476615500210220ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(mesh_size=0.05): with pygmsh.geo.Geometry() as geom: # Draw a cross with a circular hole circ = geom.add_circle( [0.0, 0.0, 0.0], 0.1, mesh_size=mesh_size, make_surface=False ) poly = geom.add_polygon( [ [+0.0, +0.5, 0.0], [-0.1, +0.1, 0.0], [-0.5, +0.0, 0.0], [-0.1, -0.1, 0.0], [+0.0, -0.5, 0.0], [+0.1, -0.1, 0.0], [+0.5, +0.0, 0.0], [+0.1, +0.1, 0.0], ], mesh_size=mesh_size, holes=[circ], ) axis = [0, 0, 1.0] geom.extrude(poly, translation_axis=axis, num_layers=1) mesh = geom.generate_mesh() ref = 0.16951514066385628 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("layers.vtu") pygmsh-7.1.17/tests/built_in/test_pacman.py000066400000000000000000000026011417476615500207540ustar00rootroot00000000000000from helpers import compute_volume from numpy import cos, pi, sin import pygmsh def test(lcar=0.3): with pygmsh.geo.Geometry() as geom: r = 1.25 * 3.4 p1 = geom.add_point([0.0, 0.0, 0.0], lcar) # p2 = geom.add_point([+r, 0.0, 0.0], lcar) p3 = geom.add_point([-r, 0.0, 0.0], lcar) p4 = geom.add_point([0.0, +r, 0.0], lcar) p5 = geom.add_point([0.0, -r, 0.0], lcar) p6 = geom.add_point([r * cos(+pi / 12.0), r * sin(+pi / 12.0), 0.0], lcar) p7 = geom.add_point([r * cos(-pi / 12.0), r * sin(-pi / 12.0), 0.0], lcar) p8 = geom.add_point([0.5 * r, 0.0, 0.0], lcar) c0 = geom.add_circle_arc(p6, p1, p4) c1 = geom.add_circle_arc(p4, p1, p3) c2 = geom.add_circle_arc(p3, p1, p5) c3 = geom.add_circle_arc(p5, p1, p7) l1 = geom.add_line(p7, p8) l2 = geom.add_line(p8, p6) ll = geom.add_curve_loop([c0, c1, c2, c3, l1, l2]) pacman = geom.add_plane_surface(ll) # test setting physical groups geom.add_physical(p1, label="c") geom.add_physical(c0, label="arc") geom.add_physical(pacman, "dummy") geom.add_physical(pacman, label="77") mesh = geom.generate_mesh() ref = 54.312974717523744 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("pacman.vtu") pygmsh-7.1.17/tests/built_in/test_physical.py000066400000000000000000000013171417476615500213340ustar00rootroot00000000000000import meshio import pygmsh def test(lcar=0.5): with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]], lcar) top, volume, lat = geom.extrude(poly, [0, 0, 2]) geom.add_physical(poly, label="bottom") geom.add_physical(top, label="top") geom.add_physical(volume, label="volume") geom.add_physical(lat, label="lat") geom.add_physical(poly.lines[0], label="line") mesh = geom.generate_mesh() assert len(mesh.cell_sets) == 5 return mesh if __name__ == "__main__": test().write("physical.vtu") read_mesh = meshio.read("physical.vtu") assert len(read_mesh.cell_sets) == 5 pygmsh-7.1.17/tests/built_in/test_pipes.py000066400000000000000000000015651417476615500206450ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(): """Pipe with double-ring enclosure, rotated in space.""" with pygmsh.geo.Geometry() as geom: sqrt2on2 = 0.5 * np.sqrt(2.0) R = pygmsh.rotation_matrix([sqrt2on2, sqrt2on2, 0], np.pi / 6.0) geom.add_pipe( inner_radius=0.3, outer_radius=0.4, length=1.0, R=R, mesh_size=0.04 ) R = np.array([[0.0, 0.0, 1.0], [0.0, 1.0, 0.0], [1.0, 0.0, 0.0]]) geom.add_pipe( inner_radius=0.3, outer_radius=0.4, length=1.0, mesh_size=0.04, R=R, variant="circle_extrusion", ) mesh = geom.generate_mesh() ref = 0.43988203517453256 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("pipes.vtu") pygmsh-7.1.17/tests/built_in/test_quads.py000066400000000000000000000006441417476615500206370ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: rectangle = geom.add_rectangle(0.0, 1.0, 0.0, 1.0, 0.0, 0.1) geom.set_recombined_surfaces([rectangle.surface]) mesh = geom.generate_mesh(dim=2) ref = 1.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("quads.vtu") pygmsh-7.1.17/tests/built_in/test_recombine.py000066400000000000000000000024341417476615500214640ustar00rootroot00000000000000import numpy as np import pygmsh def test(): with pygmsh.geo.Geometry() as geom: pts = [ geom.add_point((0.0, 0.0, 0.0), mesh_size=1.0), geom.add_point((2.0, 0.0, 0.0), mesh_size=1.0), geom.add_point((0.0, 1.0, 0.0), mesh_size=1.0), geom.add_point((2.0, 1.0, 0.0), mesh_size=1.0), ] lines = [ geom.add_line(pts[0], pts[1]), geom.add_line(pts[1], pts[3]), geom.add_line(pts[3], pts[2]), geom.add_line(pts[2], pts[0]), ] ll0 = geom.add_curve_loop(lines) rs0 = geom.add_surface(ll0) geom.set_transfinite_curve(lines[3], 3, "Progression", 1.0) geom.set_transfinite_curve(lines[1], 3, "Progression", 1.0) geom.set_transfinite_curve(lines[2], 3, "Progression", 1.0) geom.set_transfinite_curve(lines[0], 3, "Progression", 1.0) geom.set_transfinite_surface(rs0, "Left", pts) geom.set_recombined_surfaces([rs0]) mesh = geom.generate_mesh() assert "quad" in mesh.cells_dict.keys() ref = np.array([[0, 4, 8, 7], [7, 8, 6, 2], [4, 1, 5, 8], [8, 5, 3, 6]]) assert np.array_equal(ref, mesh.cells_dict["quad"]) return mesh if __name__ == "__main__": test().write("rectangle_structured.vtu") pygmsh-7.1.17/tests/built_in/test_rectangle.py000066400000000000000000000005351417476615500214650ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: geom.add_rectangle(0.0, 1.0, 0.0, 1.0, 0.0, 0.1) mesh = geom.generate_mesh() ref = 1.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("rectangle.vtu") pygmsh-7.1.17/tests/built_in/test_rectangle_with_hole.py000066400000000000000000000012441417476615500235250ustar00rootroot00000000000000""" Creates a mesh for a square with a round hole. """ from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: circle = geom.add_circle( x0=[0.5, 0.5, 0.0], radius=0.25, mesh_size=0.1, num_sections=4, make_surface=False, ) geom.add_rectangle( 0.0, 1.0, 0.0, 1.0, 0.0, mesh_size=0.1, holes=[circle.curve_loop] ) mesh = geom.generate_mesh() ref = 0.8086582838174551 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("rectangle_with_hole.vtu") pygmsh-7.1.17/tests/built_in/test_regular_extrusion.py000066400000000000000000000015171417476615500233030ustar00rootroot00000000000000"""Creates regular cube mesh by extrusion. """ from helpers import compute_volume import pygmsh def test(): x = 5 y = 4 z = 3 x_layers = 10 y_layers = 5 z_layers = 3 with pygmsh.geo.Geometry() as geom: p = geom.add_point([0, 0, 0], 1) _, l, _ = geom.extrude(p, [x, 0, 0], num_layers=x_layers) _, s, _ = geom.extrude(l, [0, y, 0], num_layers=y_layers) geom.extrude(s, [0, 0, z], num_layers=z_layers) mesh = geom.generate_mesh() ref_vol = x * y * z assert abs(compute_volume(mesh) - ref_vol) < 1.0e-2 * ref_vol # Each grid-cell from layered extrusion will result in 6 tetrahedra. ref_tetras = 6 * x_layers * y_layers * z_layers assert len(mesh.cells_dict["tetra"]) == ref_tetras return mesh if __name__ == "__main__": test().write("cube.vtu") pygmsh-7.1.17/tests/built_in/test_rotated_layers.py000066400000000000000000000015561417476615500225460ustar00rootroot00000000000000from math import pi from helpers import compute_volume import pygmsh def test(mesh_size=0.05): with pygmsh.geo.Geometry() as geom: # Draw a square poly = geom.add_polygon( [ [+0.5, +0.0, 0.0], [+0.0, +0.5, 0.0], [-0.5, +0.0, 0.0], [+0.0, -0.5, 0.0], ], mesh_size=mesh_size, ) axis = [0, 0, 1.0] geom.twist( poly, translation_axis=axis, rotation_axis=axis, point_on_axis=[0.0, 0.0, 0.0], angle=0.5 * pi, num_layers=5, recombine=True, ) mesh = geom.generate_mesh() ref = 3.98156496566 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("rotated_layers.vtu") pygmsh-7.1.17/tests/built_in/test_rotation.py000066400000000000000000000023601417476615500213560ustar00rootroot00000000000000"""Test translation for all dimensions.""" import numpy as np import pygmsh def test_rotation2d(): """Rotation of a surface object.""" angle = np.pi / 5 # Generate reference geometry with pygmsh.geo.Geometry() as geom: rect = geom.add_rectangle(0.0, 2.0, 0.0, 1.0, 0.0, 0.1) mesh_unrot = geom.generate_mesh() vertex_index = mesh_unrot.cells_dict["vertex"] vertex_index = vertex_index.reshape((vertex_index.shape[0],)) with pygmsh.geo.Geometry() as geom: # Generate rotated geometry geom = pygmsh.geo.Geometry() rect = geom.add_rectangle(0.0, 2.0, 0.0, 1.0, 0.0, 0.1) geom.rotate(rect.surface, (0, 0, 0), angle, (0, 0, 1)) mesh = geom.generate_mesh() new_vertex_index = mesh.cells_dict["vertex"] new_vertex_index = new_vertex_index.reshape((new_vertex_index.shape[0],)) # Generate rotation matrix and compare with rotated geometry Rm = pygmsh.helpers.rotation_matrix([0, 0, 1], angle) for v, v_new in zip(vertex_index, new_vertex_index): point = mesh_unrot.points[v, :] rot_point = np.dot(Rm, point) new_point = mesh.points[v, :] assert np.allclose(rot_point, new_point) if __name__ == "__main__": test_rotation2d() pygmsh-7.1.17/tests/built_in/test_screw.py000066400000000000000000000020171417476615500206410ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(mesh_size=0.05): with pygmsh.geo.Geometry() as geom: # Draw a cross with a circular hole circ = geom.add_circle([0.0, 0.0], 0.1, mesh_size=mesh_size) poly = geom.add_polygon( [ [+0.0, +0.5], [-0.1, +0.1], [-0.5, +0.0], [-0.1, -0.1], [+0.0, -0.5], [+0.1, -0.1], [+0.5, +0.0], [+0.1, +0.1], ], mesh_size=mesh_size, holes=[circ], ) geom.twist( poly, translation_axis=[0.0, 0.0, 1.0], rotation_axis=[0.0, 0.0, 1.0], point_on_axis=[0.0, 0.0, 0.0], angle=2.0 / 6.0 * np.pi, ) mesh = geom.generate_mesh() ref = 0.16951514066385628 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("screw.vtu") pygmsh-7.1.17/tests/built_in/test_splines.py000066400000000000000000000014441417476615500211760ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: lcar = 0.1 p1 = geom.add_point([0.0, 0.0, 0.0], lcar) p2 = geom.add_point([1.0, 0.0, 0.0], lcar) p3 = geom.add_point([1.0, 0.5, 0.0], lcar) p4 = geom.add_point([1.0, 1.0, 0.0], lcar) s1 = geom.add_spline([p1, p2, p3, p4]) p2 = geom.add_point([0.0, 1.0, 0.0], lcar) p3 = geom.add_point([0.5, 1.0, 0.0], lcar) s2 = geom.add_spline([p4, p3, p2, p1]) ll = geom.add_curve_loop([s1, s2]) geom.add_plane_surface(ll) mesh = geom.generate_mesh() ref = 1.0809439490373247 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("splines.vtu") pygmsh-7.1.17/tests/built_in/test_subdomains.py000066400000000000000000000016031417476615500216620ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: lcar = 0.1 circle = geom.add_circle([0.5, 0.5, 0.0], 1.0, lcar) triangle = geom.add_polygon( [[2.0, -0.5, 0.0], [4.0, -0.5, 0.0], [4.0, 1.5, 0.0]], lcar ) rectangle = geom.add_rectangle(4.75, 6.25, -0.24, 1.25, 0.0, lcar) # hold all domain geom.add_polygon( [ [-1.0, -1.0, 0.0], [+7.0, -1.0, 0.0], [+7.0, +2.0, 0.0], [-1.0, +2.0, 0.0], ], lcar, holes=[circle.curve_loop, triangle.curve_loop, rectangle.curve_loop], ) mesh = geom.generate_mesh() ref = 24.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("subdomains.vtu") pygmsh-7.1.17/tests/built_in/test_swiss_cheese.py000066400000000000000000000016561417476615500222120ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(): X0 = np.array( [[+0.0, +0.0, 0.0], [+0.5, +0.3, 0.1], [-0.5, +0.3, 0.1], [+0.5, -0.3, 0.1]] ) R = np.array([0.1, 0.2, 0.1, 0.14]) with pygmsh.geo.Geometry() as geom: holes = [ geom.add_ball(x0, r, with_volume=False, mesh_size=0.2 * r).surface_loop for x0, r in zip(X0, R) ] # geom.add_box( # -1, 1, # -1, 1, # -1, 1, # mesh_size=0.2, # holes=holes # ) geom.add_ball([0, 0, 0], 1.0, mesh_size=0.2, holes=holes) # geom.add_physical_volume(ball, label="cheese") mesh = geom.generate_mesh(algorithm=5) ref = 4.07064892966291 assert abs(compute_volume(mesh) - ref) < 2.0e-2 * ref return mesh if __name__ == "__main__": test().write("swiss_cheese.vtu") pygmsh-7.1.17/tests/built_in/test_symmetrize.py000066400000000000000000000007701417476615500217320ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [[0.0, 0.5], [1.0, 0.5], [1.0, 1.0], [0.0, 1.0]], mesh_size=0.05, ) cp = geom.copy(poly) geom.symmetrize(cp, [0.0, 1.0, 0.0, -0.5]) mesh = geom.generate_mesh() ref = 1.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("symmetry.vtk") pygmsh-7.1.17/tests/built_in/test_tori.py000066400000000000000000000014251417476615500204750ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(irad=0.05, orad=0.6): """Torus, rotated in space.""" with pygmsh.geo.Geometry() as geom: R = pygmsh.rotation_matrix([1.0, 0.0, 0.0], np.pi / 2) geom.add_torus(irad=irad, orad=orad, mesh_size=0.03, x0=[0.0, 0.0, -1.0], R=R) R = pygmsh.rotation_matrix([0.0, 1.0, 0.0], np.pi / 2) geom.add_torus( irad=irad, orad=orad, mesh_size=0.03, x0=[0.0, 0.0, 1.0], variant="extrude_circle", ) mesh = geom.generate_mesh() ref = 2 * 2 * np.pi ** 2 * orad * irad ** 2 assert np.isclose(compute_volume(mesh), ref, rtol=5e-2) return mesh if __name__ == "__main__": test().write("torus.vtu") pygmsh-7.1.17/tests/built_in/test_torus.py000066400000000000000000000010371417476615500206730ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(irad=0.05, orad=0.6): """Torus, rotated in space.""" with pygmsh.geo.Geometry() as geom: R = pygmsh.rotation_matrix([1.0, 0.0, 0.0], np.pi / 2) geom.add_torus(irad=irad, orad=orad, mesh_size=0.03, x0=[0.0, 0.0, -1.0], R=R) mesh = geom.generate_mesh() ref = 2 * np.pi ** 2 * orad * irad ** 2 assert np.isclose(compute_volume(mesh), ref, rtol=5e-2) return mesh if __name__ == "__main__": test().write("torus.vtu") pygmsh-7.1.17/tests/built_in/test_torus_crowd.py000066400000000000000000000033571417476615500221000ustar00rootroot00000000000000import numpy as np from helpers import compute_volume import pygmsh def test(): # internal radius of torus irad = 0.15 # external radius of torus orad = 0.27 Z_pos = (irad + orad) * np.concatenate( [+np.ones(8), -np.ones(8), +np.ones(8), -np.ones(8)] ) Alpha = np.concatenate( [ np.arange(8) * np.pi / 4.0, np.arange(8) * np.pi / 4.0 + np.pi / 16.0, np.arange(8) * np.pi / 4.0, np.arange(8) * np.pi / 4.0 + np.pi / 16.0, ] ) A1 = ( (irad + orad) / np.tan(np.pi / 8.0) * np.concatenate( [1.6 * np.ones(8), 1.6 * np.ones(8), 1.9 * np.ones(8), 1.9 * np.ones(8)] ) ) with pygmsh.geo.Geometry() as geom: for alpha, a1, z in zip(Alpha, A1, Z_pos): # Rotate torus to the y-z-plane. R1 = pygmsh.rotation_matrix([0.0, 1.0, 0.0], 0.5 * np.pi) R2 = pygmsh.rotation_matrix([0.0, 0.0, 1.0], alpha) x0 = np.array([a1, 0.0, 0.0]) x1 = np.array([0.0, 0.0, z]) # First rotate to y-z-plane, then move out to a1, rotate by angle # alpha, move up by z. # # xnew = R2*(R1*x+x0) + x1 # geom.add_torus( irad=irad, orad=orad, mesh_size=0.1, R=np.dot(R2, R1), x0=np.dot(R2, x0) + x1, ) geom.add_box(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, mesh_size=0.3) mesh = geom.generate_mesh() ref = len(A1) * 2 * np.pi ** 2 * orad * irad ** 2 + 2.0 ** 3 assert np.isclose(compute_volume(mesh), ref, rtol=2e-2) return mesh if __name__ == "__main__": test().write("torus_crowd.vtu") pygmsh-7.1.17/tests/built_in/test_transfinite.py000066400000000000000000000007001417476615500220410ustar00rootroot00000000000000import pygmsh def test(lcar=0.1): with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0]], lcar ) geom.set_transfinite_surface(poly, "Left", corner_pts=[]) mesh = geom.generate_mesh() assert len(mesh.cells_dict["triangle"]) == 10 * 10 * 2 return mesh if __name__ == "__main__": test().write("transfinite.vtu") pygmsh-7.1.17/tests/built_in/test_unordered_unoriented.py000066400000000000000000000021061417476615500237400ustar00rootroot00000000000000import random import numpy as np from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: # Generate an approximation of a circle t = np.arange(0, 2.0 * np.pi, 0.05) x = np.column_stack([np.cos(t), np.sin(t), np.zeros_like(t)]) points = [geom.add_point(p) for p in x] # Shuffle the orientation of lines by point order o = [0 if k % 3 == 0 else 1 for k in range(len(points))] lines = [ geom.add_line(points[k + o[k]], points[k + (o[k] + 1) % 2]) for k in range(len(points) - 1) ] lines.append(geom.add_line(points[-1], points[0])) # Shuffle the order of lines random.seed(1) random.shuffle(lines) oriented_lines = pygmsh.orient_lines(lines) ll = geom.add_curve_loop(oriented_lines) geom.add_plane_surface(ll) mesh = geom.generate_mesh() ref = np.pi assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("physical.vtu") pygmsh-7.1.17/tests/built_in/test_volume.py000066400000000000000000000011151417476615500210230ustar00rootroot00000000000000import meshio import numpy as np from helpers import compute_volume def test_volume(): points = np.array( [ [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 0.0, 0.0], [3.0, 1.0, 0.0], [2.0, 1.0, 0.0], [1.0, 1.0, 0.0], [0.0, 1.0, 0.0], ] ) cells = { "triangle": np.array([[0, 1, 6], [0, 6, 7]]), "quad": np.array([[1, 2, 5, 6], [2, 3, 4, 5]]), } vol = compute_volume(meshio.Mesh(points, cells)) assert abs(vol - 3.0) < 1.0e-14 pygmsh-7.1.17/tests/helpers.py000066400000000000000000000051071417476615500163170ustar00rootroot00000000000000import math import numpy as np def prune_nodes(points, cells): # Only points/cells that actually used uvertices, uidx = np.unique(cells, return_inverse=True) cells = uidx.reshape(cells.shape) points = points[uvertices] return points, cells def get_triangle_volumes(pts, cells): # Works in any dimension; taken from voropy local_idx = np.array([[1, 2], [2, 0], [0, 1]]).T idx_hierarchy = cells.T[local_idx] half_edge_coords = pts[idx_hierarchy[1]] - pts[idx_hierarchy[0]] ei_dot_ej = np.einsum( "ijk, ijk->ij", half_edge_coords[[1, 2, 0]], half_edge_coords[[2, 0, 1]] ) vols = 0.5 * np.sqrt( +ei_dot_ej[2] * ei_dot_ej[0] + ei_dot_ej[0] * ei_dot_ej[1] + ei_dot_ej[1] * ei_dot_ej[2] ) return vols def get_simplex_volumes(pts, cells): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = np.concatenate([p, np.ones(list(p.shape[:2]) + [1])], axis=-1) return np.abs(np.linalg.det(p) / math.factorial(n)) def compute_volume(mesh): if "tetra" in mesh.cells_dict: vol = math.fsum( get_simplex_volumes(*prune_nodes(mesh.points, mesh.cells_dict["tetra"])) ) elif "triangle" in mesh.cells_dict or "quad" in mesh.cells_dict: vol = 0.0 if "triangle" in mesh.cells_dict: # triangles vol += math.fsum( get_triangle_volumes( *prune_nodes(mesh.points, mesh.cells_dict["triangle"]) ) ) if "quad" in mesh.cells_dict: # quad: treat as two triangles quads = mesh.cells_dict["quad"].T split_cells = np.column_stack( [[quads[0], quads[1], quads[2]], [quads[0], quads[2], quads[3]]] ).T vol += math.fsum( get_triangle_volumes(*prune_nodes(mesh.points, split_cells)) ) else: assert "line" in mesh.cells_dict segs = np.diff(mesh.points[mesh.cells_dict["line"]], axis=1).squeeze() vol = np.sum(np.sqrt(np.einsum("...j, ...j", segs, segs))) return vol def plot(filename, points, triangles): from matplotlib import pyplot as plt pts = points[:, :2] for e in triangles: for idx in [[0, 1], [1, 2], [2, 0]]: X = pts[e[idx]] plt.plot(X[:, 0], X[:, 1], "-k") plt.gca().set_aspect("equal", "datalim") plt.axis("off") # plt.show() plt.savefig(filename, transparent=True) pygmsh-7.1.17/tests/occ/000077500000000000000000000000001417476615500150445ustar00rootroot00000000000000pygmsh-7.1.17/tests/occ/helpers.py000066400000000000000000000051071417476615500170630ustar00rootroot00000000000000import math import numpy as np def prune_nodes(points, cells): # Only points/cells that actually used uvertices, uidx = np.unique(cells, return_inverse=True) cells = uidx.reshape(cells.shape) points = points[uvertices] return points, cells def get_triangle_volumes(pts, cells): # Works in any dimension; taken from voropy local_idx = np.array([[1, 2], [2, 0], [0, 1]]).T idx_hierarchy = cells.T[local_idx] half_edge_coords = pts[idx_hierarchy[1]] - pts[idx_hierarchy[0]] ei_dot_ej = np.einsum( "ijk, ijk->ij", half_edge_coords[[1, 2, 0]], half_edge_coords[[2, 0, 1]] ) vols = 0.5 * np.sqrt( +ei_dot_ej[2] * ei_dot_ej[0] + ei_dot_ej[0] * ei_dot_ej[1] + ei_dot_ej[1] * ei_dot_ej[2] ) return vols def get_simplex_volumes(pts, cells): """Signed volume of a simplex in nD. Note that signing only makes sense for n-simplices in R^n. """ n = pts.shape[1] assert cells.shape[1] == n + 1 p = pts[cells] p = np.concatenate([p, np.ones(list(p.shape[:2]) + [1])], axis=-1) return np.abs(np.linalg.det(p) / math.factorial(n)) def compute_volume(mesh): if "tetra" in mesh.cells_dict: vol = math.fsum( get_simplex_volumes(*prune_nodes(mesh.points, mesh.cells_dict["tetra"])) ) elif "triangle" in mesh.cells_dict or "quad" in mesh.cells_dict: vol = 0.0 if "triangle" in mesh.cells_dict: # triangles vol += math.fsum( get_triangle_volumes( *prune_nodes(mesh.points, mesh.cells_dict["triangle"]) ) ) if "quad" in mesh.cells_dict: # quad: treat as two triangles quads = mesh.cells_dict["quad"].T split_cells = np.column_stack( [[quads[0], quads[1], quads[2]], [quads[0], quads[2], quads[3]]] ).T vol += math.fsum( get_triangle_volumes(*prune_nodes(mesh.points, split_cells)) ) else: assert "line" in mesh.cells_dict segs = np.diff(mesh.points[mesh.cells_dict["line"]], axis=1).squeeze() vol = np.sum(np.sqrt(np.einsum("...j, ...j", segs, segs))) return vol def plot(filename, points, triangles): from matplotlib import pyplot as plt pts = points[:, :2] for e in triangles: for idx in [[0, 1], [1, 2], [2, 0]]: X = pts[e[idx]] plt.plot(X[:, 0], X[:, 1], "-k") plt.gca().set_aspect("equal", "datalim") plt.axis("off") # plt.show() plt.savefig(filename, transparent=True) pygmsh-7.1.17/tests/occ/test_ball_with_stick.py000066400000000000000000000020431417476615500216160ustar00rootroot00000000000000import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.1 geom.characteristic_length_max = 0.1 ball = geom.add_ball([0.0, 0.0, 0.0], 1.0) box1 = geom.add_box([0, 0, 0], [1, 1, 1]) box2 = geom.add_box([-2, -0.5, -0.5], [1.5, 0.8, 0.8]) cut = geom.boolean_difference(ball, box1) frag = geom.boolean_fragments(cut, box2) # The three fragments are: # frag[0]: The ball with two cuts # frag[1]: The intersection of the stick and the ball # frag[2]: The stick without the ball geom.add_physical([frag[0], frag[1]], label="Sphere cut by box 1") geom.add_physical(frag[2], label="Box 2 cut by sphere") mesh = geom.generate_mesh(algorithm=6) assert "Sphere cut by box 1" in mesh.cell_sets assert "Box 2 cut by sphere" in mesh.cell_sets # mesh.remove_lower_dimensional_cells() # mesh.sets_to_int_data() return mesh if __name__ == "__main__": test().write("ball-with-stick.vtu") pygmsh-7.1.17/tests/occ/test_logo.py000066400000000000000000000050121417476615500174130ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: # test setters, getters print(geom.characteristic_length_min) print(geom.characteristic_length_max) geom.characteristic_length_min = 2.0 geom.characteristic_length_max = 2.0 rect1 = geom.add_rectangle([10.0, 0.0, 0.0], 20.0, 40.0, corner_radius=5.0) rect2 = geom.add_rectangle([0.0, 10.0, 0.0], 40.0, 20.0, corner_radius=5.0) disk1 = geom.add_disk([14.5, 35.0, 0.0], 1.85) disk2 = geom.add_disk([25.5, 5.0, 0.0], 1.85) rect3 = geom.add_rectangle([10.0, 30.0, 0.0], 10.0, 1.0) rect4 = geom.add_rectangle([20.0, 9.0, 0.0], 10.0, 1.0) r1 = geom.add_rectangle([9.0, 0.0, 0.0], 21.0, 20.5, corner_radius=8.0) r2 = geom.add_rectangle([10.0, 00.0, 0.0], 20.0, 19.5, corner_radius=7.0) diff1 = geom.boolean_difference(r1, r2) r22 = geom.add_rectangle([9.0, 10.0, 0.0], 11.0, 11.0) inter1 = geom.boolean_intersection([diff1, r22]) r3 = geom.add_rectangle([10.0, 19.5, 0.0], 21.0, 21.0, corner_radius=8.0) r4 = geom.add_rectangle([10.0, 20.5, 0.0], 20.0, 20.0, corner_radius=7.0) diff2 = geom.boolean_difference(r3, r4) r33 = geom.add_rectangle([20.0, 19.0, 0.0], 11.0, 11.0) inter2 = geom.boolean_intersection([diff2, r33]) geom.boolean_difference( geom.boolean_union([rect1, rect2]), geom.boolean_union([disk1, disk2, rect3, rect4, inter1, inter2]), ) mesh = geom.generate_mesh() ref = 1082.4470502181903 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": mesh = test() points = mesh.points cells = mesh.get_cells_type("triangle") # import optimesh # # points, cells = optimesh.cvt.quasi_newton_uniform_lloyd( # # points, cells, 1.0e-5, 1000, omega=2.0, verbose=True # # ) # # points, cells = optimesh.cvt.quasi_newton_uniform_blocks( # # points, cells, 1.0e-5, 1000, verbose=True # # ) # points, cells = optimesh.cvt.quasi_newton_uniform_full( # points, cells, 1.0e-5, 1000, verbose=True # ) # # from helpers import plot # # plot("logo.png", points, {"triangle": cells}) import meshio # meshio.write_points_cells("logo.vtu", points, {"triangle": cells}) mesh = meshio.Mesh(points, {"triangle": cells}) meshio.svg.write( "logo.svg", mesh, float_fmt=".3f", stroke_width="1", force_width=300 ) pygmsh-7.1.17/tests/occ/test_meshio_logo.py000066400000000000000000000016361417476615500207670ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: container = geom.add_rectangle([0.0, 0.0, 0.0], 10.0, 10.0) letter_i = geom.add_rectangle([2.0, 2.0, 0.0], 1.0, 4.5) i_dot = geom.add_disk([2.5, 7.5, 0.0], 0.6) disk1 = geom.add_disk([6.25, 4.5, 0.0], 2.5) disk2 = geom.add_disk([6.25, 4.5, 0.0], 1.5) letter_o = geom.boolean_difference(disk1, disk2) geom.boolean_difference( container, geom.boolean_union([letter_i, i_dot, letter_o]) ) mesh = geom.generate_mesh() ref = 81.9131851877 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": # import meshio # meshio.write_points_cells('m.vtu', *test()) from helpers import plot mesh = test() plot("meshio_logo.png", mesh.points, mesh.get_cells_type("triangle")) pygmsh-7.1.17/tests/occ/test_opencascade_ball.py000066400000000000000000000005721417476615500217200ustar00rootroot00000000000000from math import pi from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_ball([0.0, 0.0, 0.0], 1.0, mesh_size=0.1) mesh = geom.generate_mesh() ref = 4 / 3 * pi assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_ball.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_boolean.py000066400000000000000000000047241417476615500224300ustar00rootroot00000000000000import math from helpers import compute_volume import pygmsh def test_union(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.1 geom.characteristic_length_max = 0.1 rectangle = geom.add_rectangle([-1.0, -1.0, 0.0], 2.0, 2.0) disk_w = geom.add_disk([-1.0, 0.0, 0.0], 0.5) disk_e = geom.add_disk([+1.0, 0.0, 0.0], 0.5) geom.boolean_union([rectangle, disk_w, disk_e]) mesh = geom.generate_mesh() ref = 4.780361 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh def test_intersection(): with pygmsh.occ.Geometry() as geom: angles = [math.pi * 3 / 6, math.pi * 7 / 6, math.pi * 11 / 6] disks = [ geom.add_disk([math.cos(angles[0]), math.sin(angles[0]), 0.0], 1.5), geom.add_disk([math.cos(angles[1]), math.sin(angles[1]), 0.0], 1.5), geom.add_disk([math.cos(angles[2]), math.sin(angles[2]), 0.0], 1.5), ] geom.boolean_intersection(disks) mesh = geom.generate_mesh() ref = 1.0290109753807914 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh def test_difference(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.1 geom.characteristic_length_max = 0.1 rectangle = geom.add_rectangle([-1.0, -1.0, 0.0], 2.0, 2.0) disk_w = geom.add_disk([-1.0, 0.0, 0.0], 0.5) disk_e = geom.add_disk([+1.0, 0.0, 0.0], 0.5) geom.boolean_union([disk_w, disk_e]) geom.boolean_difference(rectangle, geom.boolean_union([disk_w, disk_e])) mesh = geom.generate_mesh() ref = 3.2196387 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh def test_all(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.1 geom.characteristic_length_max = 0.1 rectangle = geom.add_rectangle([-1.0, -1.0, 0.0], 2.0, 2.0) disk1 = geom.add_disk([-1.0, 0.0, 0.0], 0.5) disk2 = geom.add_disk([+1.0, 0.0, 0.0], 0.5) union = geom.boolean_union([rectangle, disk1, disk2]) disk3 = geom.add_disk([0.0, -1.0, 0.0], 0.5) disk4 = geom.add_disk([0.0, +1.0, 0.0], 0.5) geom.boolean_difference(union, geom.boolean_union([disk3, disk4])) mesh = geom.generate_mesh() ref = 4.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test_difference().write("boolean.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_booleans.py000066400000000000000000000142671417476615500226160ustar00rootroot00000000000000"""Test module for boolean operations.""" import meshio import numpy as np import pytest from helpers import compute_volume import pygmsh def square_loop(geom): """Construct square using built in geometry.""" points = [ geom.add_point([-0.5, -0.5], 0.05), geom.add_point([-0.5, 0.5], 0.05), geom.add_point([0.5, 0.5], 0.05), geom.add_point([0.5, -0.5], 0.05), ] lines = [ geom.add_line(points[0], points[1]), geom.add_line(points[1], points[2]), geom.add_line(points[2], points[3]), geom.add_line(points[3], points[0]), ] return geom.add_curve_loop(lines) def circle_loop(geom): """construct circle using geo geometry module.""" points = [ geom.add_point([+0.0, +0.0], 0.05), geom.add_point([+0.0, +0.1], 0.05), geom.add_point([-0.1, +0.0], 0.05), geom.add_point([+0.0, -0.1], 0.05), geom.add_point([+0.1, +0.0], 0.05), ] quarter_circles = [ geom.add_circle_arc(points[1], points[0], points[2]), geom.add_circle_arc(points[2], points[0], points[3]), geom.add_circle_arc(points[3], points[0], points[4]), geom.add_circle_arc(points[4], points[0], points[1]), ] return geom.add_curve_loop(quarter_circles) def _square_hole_classical(geom): """Construct surface using builtin and boolean methods.""" # construct surface with hole using standard built in geom.characteristic_length_min = 0.05 geom.characteristic_length_max = 0.05 square = square_loop(geom) circle = circle_loop(geom) geom.add_plane_surface(square, [circle]) def _square_hole_cad(geom): # construct surface using boolean geom.characteristic_length_min = 0.05 geom.characteristic_length_max = 0.05 square2 = square_loop(geom) curve_loop2 = circle_loop(geom) surf1 = geom.add_plane_surface(square2) surf2 = geom.add_plane_surface(curve_loop2) geom.boolean_difference(surf1, surf2) @pytest.mark.parametrize("fun", [_square_hole_classical, _square_hole_cad]) def test_square_circle_hole(fun): """Test planar surface with holes. Construct it with boolean operations and verify that it is the same. """ with pygmsh.occ.Geometry() as geom: fun(geom) mesh = geom.generate_mesh() surf = 1 - 0.1 ** 2 * np.pi assert np.abs((compute_volume(mesh) - surf) / surf) < 1e-3 @pytest.mark.skip() def test_square_circle_slice(): """Test planar surface square with circular hole. Also test for surface area of fragments. """ with pygmsh.occ.Geometry() as geom: square = square_loop(geom) curve_loop = circle_loop(geom) surf1 = geom.add_plane_surface(square) surf2 = geom.add_plane_surface(curve_loop) geom.boolean_fragments(surf1, surf2) mesh = geom.generate_mesh() ref = 1.0 val = compute_volume(mesh) assert np.abs(val - ref) < 1e-3 * ref # Gmsh 4 default format MSH4 doesn't have geometrical entities. outer_mask = np.where(mesh.cell_data["gmsh:geometrical"][2] == 13)[0] outer_cells = {} outer_cells["triangle"] = mesh.cells_dict["triangle"][outer_mask] inner_mask = np.where(mesh.cell_data["gmsh:geometrical"][2] == 12)[0] inner_cells = {} inner_cells["triangle"] = mesh.cells_dict["triangle"][inner_mask] ref = 1 - 0.1 ** 2 * np.pi value = compute_volume(meshio.Mesh(mesh.points, outer_cells)) assert np.abs(value - ref) < 1e-2 * ref @pytest.mark.skip("cell data not working yet") def test_fragments_diff_union(): """Test planar surface with holes. Construct it with boolean operations and verify that it is the same. """ # construct surface using boolean with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.04 geom.characteristic_length_max = 0.04 square = square_loop(geom) surf1 = geom.add_plane_surface(square) curve_loop = circle_loop(geom) surf2 = geom.add_plane_surface(curve_loop) geom.add_physical([surf1], label="1") geom.add_physical([surf2], label="2") geom.boolean_difference(surf1, surf2, delete_other=False) mesh = geom.generate_mesh() ref = 1.0 assert np.abs(compute_volume(mesh) - ref) < 1e-3 * ref surf = 1 - 0.1 ** 2 * np.pi outer_mask = np.where(mesh.cell_data_dict["gmsh:geometrical"]["triangle"] == 1)[0] outer_cells = {} outer_cells["triangle"] = mesh.cells_dict["triangle"][outer_mask] inner_mask = np.where(mesh.cell_data_dict["gmsh:geometrical"]["triangle"] == 2)[0] inner_cells = {} inner_cells["triangle"] = mesh.cells_dict["triangle"][inner_mask] value = compute_volume(meshio.Mesh(mesh.points, outer_cells)) assert np.abs(value - surf) < 1e-2 * surf @pytest.mark.skip("cell data not working yet") def test_diff_physical_assignment(): """construct surface using boolean. Ensure that after a difference operation the initial volume physical label is kept for the operated geometry. """ with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.05 geom.characteristic_length_max = 0.05 square2 = square_loop(geom) curve_loop2 = circle_loop(geom) surf1 = geom.add_plane_surface(square2) surf2 = geom.add_plane_surface(curve_loop2) geom.add_physical(surf1, label="1") geom.boolean_difference(surf1, surf2) mesh = geom.generate_mesh() assert np.allclose( mesh.cell_data_dict["gmsh:geometrical"]["triangle"], np.ones(mesh.cells_dict["triangle"].shape[0]), ) surf = 1 - 0.1 ** 2 * np.pi assert np.abs((compute_volume(mesh) - surf) / surf) < 1e-3 def test_polygon_diff(): with pygmsh.occ.Geometry() as geom: poly = geom.add_polygon([[0.0, 0.0], [1.0, 0.0], [1.0, 1.0], [0.0, 1.0]]) disk = geom.add_disk([0, 0, 0], 0.5) geom.boolean_difference(poly, disk) def test_mesh_size_removal(): with pygmsh.occ.Geometry() as geom: box0 = geom.add_box([0.0, 0, 0], [1, 1, 1], mesh_size=0.1) box1 = geom.add_box([0.5, 0.5, 1], [0.5, 0.5, 1], mesh_size=0.2) geom.boolean_union([box0, box1]) geom.generate_mesh() if __name__ == "__main__": test_square_circle_slice() pygmsh-7.1.17/tests/occ/test_opencascade_box.py000066400000000000000000000005421417476615500215730ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_box([0.0, 0.0, 0.0], [1, 2, 3], mesh_size=0.1) mesh = geom.generate_mesh() ref = 6.0 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_box.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_builtin_mix.py000066400000000000000000000016061417476615500233300ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_max = 0.1 p0 = geom.add_point([-0.5, -0.5, 0], 0.01) p1 = geom.add_point([+0.5, -0.5, 0], 0.01) p2 = geom.add_point([+0.5, +0.5, 0], 0.01) p3 = geom.add_point([-0.5, +0.5, 0], 0.01) l0 = geom.add_line(p0, p1) l1 = geom.add_line(p1, p2) l2 = geom.add_line(p2, p3) l3 = geom.add_line(p3, p0) ll0 = geom.add_curve_loop([l0, l1, l2, l3]) square_builtin = geom.add_plane_surface(ll0) square_occ = geom.add_rectangle([0, 0, 0], 1.0, 1.0) geom.boolean_difference(square_occ, square_builtin) mesh = geom.generate_mesh() ref = 0.75 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("mix.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_cone.py000066400000000000000000000007671417476615500217400ustar00rootroot00000000000000from math import pi from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_cone( [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 1.0, 0.3, mesh_size=0.1, angle=1.25 * pi, ) mesh = geom.generate_mesh() ref = 0.90779252263 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_cone.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_cylinder.py000066400000000000000000000006701417476615500226160ustar00rootroot00000000000000from math import pi from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_cylinder( [0.0, 0.0, 0.0], [0.0, 0.0, 1.0], 0.5, 0.25 * pi, mesh_size=0.1 ) mesh = geom.generate_mesh() ref = 0.097625512963 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_cylinder.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_ellipsoid.py000066400000000000000000000006161417476615500227710ustar00rootroot00000000000000from math import pi from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_ellipsoid([1.0, 1.0, 1.0], [1.0, 2.0, 3.0], mesh_size=0.1) mesh = geom.generate_mesh() ref = 8.0 * pi assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_ellipsoid.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_extrude.py000066400000000000000000000046171417476615500224720ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_max = 0.05 rectangle = geom.add_rectangle([-1.0, -1.0, 0.0], 2.0, 2.0, corner_radius=0.2) disk1 = geom.add_disk([-1.2, 0.0, 0.0], 0.5) disk2 = geom.add_disk([+1.2, 0.0, 0.0], 0.5, 0.3) disk3 = geom.add_disk([0.0, -0.9, 0.0], 0.5) disk4 = geom.add_disk([0.0, +0.9, 0.0], 0.5) flat = geom.boolean_difference( geom.boolean_union([rectangle, disk1, disk2]), geom.boolean_union([disk3, disk4]), ) geom.extrude(flat, [0, 0, 0.3]) mesh = geom.generate_mesh() ref = 1.1742114942 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh def test2(): with pygmsh.occ.Geometry() as geom: geom.characteristic_length_max = 1.0 mesh_size = 1 h = 25 w = 10 length = 100 # x_fin = -0.5 * length cr = 1 f = 0.5 * w y = [-f, -f + cr, +f - cr, +f] z = [0.0, h - cr, h] f = 0.5 * cr x = [-f, f] points = [ geom.add_point((x[0], y[0], z[0]), mesh_size=mesh_size), geom.add_point((x[0], y[0], z[1]), mesh_size=mesh_size), geom.add_point((x[0], y[1], z[1]), mesh_size=mesh_size), geom.add_point((x[0], y[1], z[2]), mesh_size=mesh_size), geom.add_point((x[0], y[2], z[2]), mesh_size=mesh_size), geom.add_point((x[0], y[2], z[1]), mesh_size=mesh_size), geom.add_point((x[0], y[3], z[1]), mesh_size=mesh_size), geom.add_point((x[0], y[3], z[0]), mesh_size=mesh_size), ] lines = [ geom.add_line(points[0], points[1]), geom.add_circle_arc(points[1], points[2], points[3]), geom.add_line(points[3], points[4]), geom.add_circle_arc(points[4], points[5], points[6]), geom.add_line(points[6], points[7]), geom.add_line(points[7], points[0]), ] curve_loop = geom.add_curve_loop(lines) surface = geom.add_plane_surface(curve_loop) geom.extrude(surface, translation_axis=[length, 0, 0]) mesh = geom.generate_mesh() ref = 24941.503891355664 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_extrude.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_regular_extrusion.py000066400000000000000000000015171417476615500245670ustar00rootroot00000000000000"""Creates regular cube mesh by extrusion. """ from helpers import compute_volume import pygmsh def test(): x = 5 y = 4 z = 3 x_layers = 10 y_layers = 5 z_layers = 3 with pygmsh.occ.Geometry() as geom: p = geom.add_point([0, 0, 0], 1) _, l, _ = geom.extrude(p, [x, 0, 0], num_layers=x_layers) _, s, _ = geom.extrude(l, [0, y, 0], num_layers=y_layers) geom.extrude(s, [0, 0, z], num_layers=z_layers) mesh = geom.generate_mesh() ref_vol = x * y * z assert abs(compute_volume(mesh) - ref_vol) < 1.0e-2 * ref_vol # Each grid-cell from layered extrusion will result in 6 tetrahedrons. ref_tetras = 6 * x_layers * y_layers * z_layers assert len(mesh.cells_dict["tetra"]) == ref_tetras return mesh if __name__ == "__main__": test().write("cube.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_torus.py000066400000000000000000000006171417476615500221620ustar00rootroot00000000000000from math import pi from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_torus([0.0, 0.0, 0.0], 1.0, 0.3, 1.25 * pi, mesh_size=0.1) mesh = geom.generate_mesh() ref = 1.09994740709 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_torus.vtu") pygmsh-7.1.17/tests/occ/test_opencascade_wedge.py000066400000000000000000000005741417476615500221030ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test(): with pygmsh.occ.Geometry() as geom: geom.add_wedge([0.0, 0.0, 0.0], [1.0, 1.0, 1.0], top_extent=0.4, mesh_size=0.1) mesh = geom.generate_mesh() ref = 0.7 assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test().write("occ_wedge.vtu") pygmsh-7.1.17/tests/occ/test_refinement.py000066400000000000000000000006351417476615500206150ustar00rootroot00000000000000from math import sqrt import pytest import pygmsh @pytest.mark.skip("Only works in Gmsh 4.7.0+") def test(): with pygmsh.occ.Geometry() as geom: geom.add_ball([0.0, 0.0, 0.0], 1.0) geom.set_mesh_size_callback( lambda dim, tag, x, y, z: abs(sqrt(x ** 2 + y ** 2 + z ** 2) - 0.5) + 0.1 ) mesh = geom.generate_mesh() assert mesh.cells[0].data.shape[0] > 1500 pygmsh-7.1.17/tests/occ/test_translations.py000066400000000000000000000032321417476615500211760ustar00rootroot00000000000000"""Test translation for all dimensions.""" import numpy as np from helpers import compute_volume import pygmsh # def test_translation1d(): # """Translation of a line.""" # geom = pygmsh.geo.Geometry() # points = [] # for array in [[1, 0, 0], [0, 0, 0], [0, 1, 0]]: # points.append(geom.add_point(array, 0.5)) # circle = geom.add_circle_arc(*points) # # mesh = geom.generate_mesh() # geom.translate(circle, [1.5, 0, 0]) # translated_mesh = geom.generate_mesh() # points[:, 0] = points[:, 0] + 1.5 # assert np.allclose(points, translated_mesh.points) def test_translation2d(): """Translation of a surface object.""" with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.05 geom.characteristic_length_max = 0.05 disk = geom.add_disk([0, 0, 0], 1) disk2 = geom.add_disk([1.5, 0, 0], 1) geom.translate(disk, [1.5, 0, 0]) geom.boolean_union([disk2, disk]) mesh = geom.generate_mesh() surf = np.pi assert np.abs(compute_volume(mesh) - surf) < 1e-3 * surf def test_translation3d(): """Translation of a volume object.""" with pygmsh.occ.Geometry() as geom: geom.characteristic_length_min = 0.2 geom.characteristic_length_max = 0.2 ball = geom.add_ball([0, 0, 0], 1) ball2 = geom.add_ball([1.5, 0, 0], 1) geom.translate(ball, [1.5, 0, 0]) geom.boolean_union([ball2, ball]) mesh = geom.generate_mesh() surf = 4 / 3 * np.pi assert np.abs(compute_volume(mesh) - surf) < 2e-2 * surf if __name__ == "__main__": # test_translation1d() test_translation2d() test_translation3d() pygmsh-7.1.17/tests/test_boundary_layers.py000066400000000000000000000036511417476615500211200ustar00rootroot00000000000000from helpers import compute_volume import pygmsh def test_geo(): with pygmsh.geo.Geometry() as geom: poly = geom.add_polygon( [ [0.0, 0.0, 0.0], [2.0, 0.0, 0.0], [3.0, 1.0, 0.0], [1.0, 2.0, 0.0], [0.0, 1.0, 0.0], ], mesh_size=0.1, ) field0 = geom.add_boundary_layer( edges_list=[poly.curve_loop.curves[0]], lcmin=0.01, lcmax=0.1, distmin=0.0, distmax=0.2, ) field1 = geom.add_boundary_layer( nodes_list=[poly.curve_loop.curves[1].points[1]], lcmin=0.01, lcmax=0.1, distmin=0.0, distmax=0.2, ) geom.set_background_mesh([field0, field1], operator="Min") ref = 4.0 mesh = geom.generate_mesh() assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh def test_occ(): with pygmsh.occ.Geometry() as geom: geom.add_rectangle([0.0, 0.5, 0.0], 5.0, 0.5) edge1 = pygmsh.occ.dummy.Dummy(dim=1, id0=1) point1 = pygmsh.occ.dummy.Dummy(dim=0, id0=3) field0 = geom.add_boundary_layer( edges_list=[edge1], lcmin=0.01, lcmax=0.1, distmin=0.0, distmax=0.2, num_points_per_curve=50, ) field1 = geom.add_boundary_layer( nodes_list=[point1], lcmin=0.01, lcmax=0.1, distmin=0.0, distmax=0.2, num_points_per_curve=50, ) geom.set_background_mesh([field0, field1], operator="Min") ref = 2.5 mesh = geom.generate_mesh() assert abs(compute_volume(mesh) - ref) < 1.0e-2 * ref return mesh if __name__ == "__main__": test_geo().write("boundary_layers_geo.vtu") test_occ().write("boundary_layers_occ.vtu") pygmsh-7.1.17/tests/test_extrusion_entities.py000066400000000000000000000036311417476615500216600ustar00rootroot00000000000000"""Create several entities by extrusion, check that the expected sub-entities are returned and the resulting mesh is correct. """ import numpy as np import pytest import pygmsh @pytest.mark.parametrize("kernel", [pygmsh.geo, pygmsh.occ]) def test(kernel): with kernel.Geometry() as geom: p = geom.add_point([0, 0], 1) p_top, _, _ = geom.extrude(p, translation_axis=[1, 0, 0]) # The mesh should now contain exactly two points, the second one should be where # the translation pointed. mesh = geom.generate_mesh() assert len(mesh.points) == 2 assert np.array_equal(mesh.points[-1], [1, 0, 0]) # Check that the top entity (a PointBase) can be extruded correctly again. _, _, _ = geom.extrude(p_top, translation_axis=[1, 0, 0]) mesh = geom.generate_mesh() assert len(mesh.points) == 3 assert np.array_equal(mesh.points[-1], [2, 0, 0]) # Set up new geometry with one line. with kernel.Geometry() as geom: p1 = geom.add_point([0, 0], 1.0) p2 = geom.add_point([1, 0], 1.0) line = geom.add_line(p1, p2) l_top, _, _ = geom.extrude(line, [0, 1, 0]) mesh = geom.generate_mesh() assert len(mesh.points) == 5 assert np.array_equal(mesh.points[-2], [1, 1, 0]) # Check again for top entity (a LineBase). _, _, _ = geom.extrude(l_top, [0, 1, 0]) mesh = geom.generate_mesh() assert len(mesh.points) == 8 assert np.array_equal(mesh.points[-3], [1, 2, 0]) # Check that extrusion works on a Polygon poly = geom.add_polygon([[5.0, 0.0], [6.0, 0.0], [5.0, 1.0]], mesh_size=1e20) a, b, poly_lat = geom.extrude(poly, [0.0, 0.0, 1.0], num_layers=1) mesh = geom.generate_mesh() assert len(mesh.points) == 8 + 6 assert len(poly_lat) == 3 if __name__ == "__main__": test(pygmsh.geo) # test(pygmsh.occ) pygmsh-7.1.17/tests/test_helpers.py000066400000000000000000000010531417476615500173520ustar00rootroot00000000000000"""Tests module for helpers in tests.""" import numpy as np from helpers import compute_volume import pygmsh def test(): with pygmsh.geo.Geometry() as geom: geom.add_circle([0, 0, 0], 1, 0.1, make_surface=False) mesh = geom.generate_mesh() ref = 2 * np.pi assert np.abs(compute_volume(mesh) - ref) < 1e-2 * ref def test_save_geo(): with pygmsh.geo.Geometry() as geom: geom.add_circle([0, 0, 0], 1, 0.1, make_surface=False) geom.save_geometry("out.geo_unrolled") if __name__ == "__main__": test() pygmsh-7.1.17/tests/test_labels.py000066400000000000000000000004641417476615500171570ustar00rootroot00000000000000import pytest def test_raise_duplicate(): import pygmsh with pygmsh.geo.Geometry() as geom: p = geom.add_rectangle(-1, 1, -1, 1, z=0, mesh_size=1) geom.add_physical(p.lines[0], label="A") with pytest.raises(ValueError): geom.add_physical(p.lines[1], label="A") pygmsh-7.1.17/tests/test_optimize.py000066400000000000000000000003411417476615500175470ustar00rootroot00000000000000import pytest import pygmsh @pytest.mark.skip() def test(): with pygmsh.occ.Geometry() as geom: geom.add_ball([0.0, 0.0, 0.0], 1.0, mesh_size=0.1) mesh = geom.generate_mesh() pygmsh.optimize(mesh) pygmsh-7.1.17/tox.ini000066400000000000000000000002761417476615500144560ustar00rootroot00000000000000[tox] envlist = py3 isolated_build = True [testenv] deps = gmsh matplotlib pytest pytest-codeblocks pytest-cov extras = all commands = pytest {posargs} --codeblocks