pax_global_header 0000666 0000000 0000000 00000000064 14134252050 0014506 g ustar 00root root 0000000 0000000 52 comment=0f907a014f2caf517f8eaeb3067f136d9afb6ee1
dmsh-0.2.18/ 0000775 0000000 0000000 00000000000 14134252050 0012531 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/.codecov.yml 0000664 0000000 0000000 00000000014 14134252050 0014747 0 ustar 00root root 0000000 0000000 comment: no
dmsh-0.2.18/.flake8 0000664 0000000 0000000 00000000153 14134252050 0013703 0 ustar 00root root 0000000 0000000 [flake8]
ignore = E203, E266, E501, W503
max-line-length = 80
max-complexity = 18
select = B,C,E,F,W,T4,B9
dmsh-0.2.18/.github/ 0000775 0000000 0000000 00000000000 14134252050 0014071 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/.github/workflows/ 0000775 0000000 0000000 00000000000 14134252050 0016126 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/.github/workflows/ci.yml 0000664 0000000 0000000 00000001503 14134252050 0017243 0 ustar 00root root 0000000 0000000 name: ci
on:
push:
branches:
- main
pull_request:
branches:
- main
jobs:
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
- name: Test with tox
run: |
pip install tox
tox -- --cov dmsh --cov-report xml --cov-report term
- uses: codecov/codecov-action@v1
if: ${{ matrix.python-version == '3.9' }}
dmsh-0.2.18/.gitignore 0000664 0000000 0000000 00000000164 14134252050 0014522 0 ustar 00root root 0000000 0000000 *.pyc
*.swp
*.prof
MANIFEST
README.rst
dist/
build/
.coverage
.cache/
*.egg-info/
.pytest_cache/
.tox/
coverage.xml
dmsh-0.2.18/.pre-commit-config.yaml 0000664 0000000 0000000 00000000453 14134252050 0017014 0 ustar 00root root 0000000 0000000 repos:
- repo: https://github.com/PyCQA/isort
rev: 5.9.3
hooks:
- id: isort
- repo: https://github.com/psf/black
rev: 21.8b0
hooks:
- id: black
language_version: python3
- repo: https://github.com/PyCQA/flake8
rev: 3.9.2
hooks:
- id: flake8
dmsh-0.2.18/LICENSE 0000664 0000000 0000000 00000104516 14134252050 0013545 0 ustar 00root root 0000000 0000000 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
.
dmsh-0.2.18/README.md 0000664 0000000 0000000 00000023356 14134252050 0014021 0 ustar 00root root 0000000 0000000
The worst mesh generator you'll ever use.
[](https://pypi.org/project/dmsh/)
[](https://repology.org/project/python:dmsh/versions)
[](https://pypi.org/project/dmsh/)
[](https://doi.org/10.5281/zenodo.4728039)
[](https://github.com/nschloe/dmsh)
[](https://pypistats.org/packages/dmsh)
[](https://discord.gg/PBCCvwHqpv)
[](https://github.com/nschloe/dmsh/actions?query=workflow%3Aci)
[](https://app.codecov.io/gh/nschloe/dmsh)
[](https://lgtm.com/projects/g/nschloe/dmsh)
[](https://github.com/psf/black)
Inspired by [distmesh](http://persson.berkeley.edu/distmesh/), dmsh can be slow,
requires a lot of memory, and isn't terribly robust either.
On the plus side,
- it's got a user-friendly interface,
- is pure Python (and hence easily installable on any system), and
- it produces pretty high-quality meshes.
Combined with [optimesh](https://github.com/nschloe/optimesh), dmsh produces the
highest-quality 2D meshes in the west.
### Examples
#### Primitives
|
|
|
|
| :-----------------------------------------------------------------------------: | :--------------------------------------------------------------------------------: | :------------------------------------------------------------------------------: |
```python
import dmsh
import meshio
import optimesh
geo = dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.1)
# optionally optimize the mesh
X, cells = optimesh.optimize_points_cells(X, cells, "CVT (full)", 1.0e-10, 100)
# visualize the mesh
dmsh.helpers.show(X, cells, geo)
# and write it to a file
meshio.Mesh(X, {"triangle": cells}).write("circle.vtk")
```
```python
import dmsh
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0)
X, cells = dmsh.generate(geo, 0.1)
```
```python
import dmsh
geo = dmsh.Polygon(
[
[0.0, 0.0],
[1.1, 0.0],
[1.2, 0.5],
[0.7, 0.6],
[2.0, 1.0],
[1.0, 2.0],
[0.5, 1.5],
]
)
X, cells = dmsh.generate(geo, 0.1)
```
#### Combinations
##### Difference
|
|
|
|
| :--------------------------------------------------------------: | :----------------------------------------------------------------: | :-----------------------------------------------------------------------------------: |
```python
import dmsh
geo = dmsh.Circle([-0.5, 0.0], 1.0) - dmsh.Circle([+0.5, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.1)
```
```python
import dmsh
geo = dmsh.Circle([0.0, 0.0], 1.0) - dmsh.Polygon([[0.0, 0.0], [1.5, 0.4], [1.5, -0.4]])
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
```
The following example uses a nonconstant edge length; it depends on the distance to the
circle `c`.
```python
import dmsh
import numpy as np
r = dmsh.Rectangle(-1.0, +1.0, -1.0, +1.0)
c = dmsh.Circle([0.0, 0.0], 0.3)
geo = r - c
X, cells = dmsh.generate(geo, lambda pts: np.abs(c.dist(pts)) / 5 + 0.05, tol=1.0e-10)
```
##### Union
|
|
|
|
| :-----------------------------------------------------------------------: | :--------------------------------------------------------------------------: | :-----------------------------------------------------------------------------: |
```python
import dmsh
geo = dmsh.Circle([-0.5, 0.0], 1.0) + dmsh.Circle([+0.5, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.15)
```
```python
import dmsh
geo = dmsh.Rectangle(-1.0, +0.5, -1.0, +0.5) + dmsh.Rectangle(-0.5, +1.0, -0.5, +1.0)
X, cells = dmsh.generate(geo, 0.15)
```
```python
import dmsh
import numpy as np
angles = np.pi * np.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0])
geo = dmsh.Union(
[
dmsh.Circle([np.cos(angles[0]), np.sin(angles[0])], 1.0),
dmsh.Circle([np.cos(angles[1]), np.sin(angles[1])], 1.0),
dmsh.Circle([np.cos(angles[2]), np.sin(angles[2])], 1.0),
]
)
X, cells = dmsh.generate(geo, 0.15)
```
#### Intersection
|
|
|
|
| :------------------------------------------------------------------------------: | :------------------------------------------------------------------------------------: | :---------------------------------------------------------------------------------------: |
```python
import dmsh
geo = dmsh.Circle([0.0, -0.5], 1.0) & dmsh.Circle([0.0, +0.5], 1.0)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
```
```python
import dmsh
import numpy as np
angles = np.pi * np.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0])
geo = dmsh.Intersection(
[
dmsh.Circle([np.cos(angles[0]), np.sin(angles[0])], 1.5),
dmsh.Circle([np.cos(angles[1]), np.sin(angles[1])], 1.5),
dmsh.Circle([np.cos(angles[2]), np.sin(angles[2])], 1.5),
]
)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
```
The following uses the `HalfSpace` primtive for cutting off a circle.
```python
import dmsh
geo = dmsh.HalfSpace([1.0, 1.0]) & dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.1)
```
### Rotation, translation, scaling
|
|
|
| :------------------------------------------------------------------: | :-----------------------------------------------------------------: |
```python
import dmsh
import numpy as np
geo = dmsh.Rotation(dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0), 0.1 * np.pi)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
```
```python
import dmsh
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0) + [1.0, 1.0]
X, cells = dmsh.generate(geo, 0.1)
```
```python
import dmsh
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0) * 2.0
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-5)
```
### Local refinement
All objects can be used to refine the mesh according to the distance to the object;
e.g. a `Path`:
```python
import dmsh
geo = dmsh.Rectangle(0.0, 1.0, 0.0, 1.0)
p1 = dmsh.Path([[0.4, 0.6], [0.6, 0.4]])
def edge_size(x):
return 0.03 + 0.1 * p1.dist(x)
X, cells = dmsh.generate(geo, edge_size, tol=1.0e-10)
```
### Custom shapes
It is also possible to define your own geometry. Simply create a class derived from
`dmsh.Geometry` that contains a `dist` method and a method to project points onto the
boundary.
```python
import dmsh
import numpy as np
class MyDisk(dmsh.Geometry):
def __init__(self):
self.r = 1.0
self.x0 = [0.0, 0.0]
bounding_box = [-1.0, 1.0, -1.0, 1.0]
feature_points = np.array([[], []]).T
super().__init__(bounding_box, feature_points)
def dist(self, x):
assert x.shape[0] == 2
y = (x.T - self.x0).T
return np.sqrt(np.einsum("i...,i...->...", y, y)) - self.r
def boundary_step(self, x):
# project onto the circle
y = (x.T - self.x0).T
r = np.sqrt(np.einsum("ij,ij->j", y, y))
return ((y / r * self.r).T + self.x0).T
geo = MyDisk()
X, cells = dmsh.generate(geo, 0.1)
```
### Debugging
|  |  |
| :--------------------------------------------------------------------: | :---------------------------------------------------------------------------: |
dmsh is rather fragile, but sometimes the break-downs are due to an incorrectly defined
geometry. Use
```
geo.show()
```
to inspect the level set function of your domain. (It must be negative inside the
domain and positive outside. The 0-level set forms the domain boundary.)
### Installation
dmsh is [available from the Python Package
Index](https://pypi.org/project/dmsh/), so simply type
```
pip install dmsh
```
to install.
### Testing
To run the dmsh unit tests, check out this repository and type
```
tox
```
### License
This software is published under the [MIT
license](https://en.wikipedia.org/wiki/MIT_License).
dmsh-0.2.18/justfile 0000664 0000000 0000000 00000001455 14134252050 0014306 0 ustar 00root root 0000000 0000000 version := `python3 -c "from configparser import ConfigParser; p = ConfigParser(); p.read('setup.cfg'); print(p['metadata']['version'])"`
default:
@echo "\"just publish\"?"
tag:
@if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
curl -H "Authorization: token `cat ~/.github-access-token`" -d '{"tag_name": "v{{version}}"}' https://api.github.com/repos/nschloe/dmsh/releases
upload: clean
@if [ "$(git rev-parse --abbrev-ref HEAD)" != "main" ]; then exit 1; fi
# https://stackoverflow.com/a/58756491/353337
python3 -m build --sdist --wheel .
twine upload dist/*
publish: tag upload
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 .
dmsh-0.2.18/pyproject.toml 0000664 0000000 0000000 00000000176 14134252050 0015451 0 ustar 00root root 0000000 0000000 [build-system]
requires = ["setuptools>=42", "wheel"]
build-backend = "setuptools.build_meta"
[tool.isort]
profile = "black"
dmsh-0.2.18/setup.cfg 0000664 0000000 0000000 00000002426 14134252050 0014356 0 ustar 00root root 0000000 0000000 [metadata]
name = dmsh
version = 0.2.18
author = Nico Schlömer
author_email = nico.schloemer@gmail.com
description = High-quality 2D mesh generator based on distmesh
url = https://github.com/nschloe/dmsh
project_urls =
Code=https://github.com/nschloe/dmsh
Issues=https://github.com/nschloe/dmsh/issues
Funding=https://github.com/sponsors/nschloe
long_description = file: README.md
long_description_content_type = text/markdown
license = GPL-3.0-or-later
classifiers =
Development Status :: 4 - Beta
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
[options]
package_dir =
=src
packages = find:
install_requires =
importlib_metadata;python_version<"3.8"
meshplex >= 0.16.0, < 0.17.0
npx
numpy
scipy
python_requires = >=3.7
[options.packages.find]
where=src
[options.extras_require]
all = matplotlib
plot = matplotlib
dmsh-0.2.18/src/ 0000775 0000000 0000000 00000000000 14134252050 0013320 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/src/dmsh/ 0000775 0000000 0000000 00000000000 14134252050 0014253 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/src/dmsh/__about__.py 0000664 0000000 0000000 00000000326 14134252050 0016534 0 ustar 00root root 0000000 0000000 try:
# Python 3.8
from importlib import metadata
except ImportError:
import importlib_metadata as metadata
try:
__version__ = metadata.version("dmsh")
except Exception:
__version__ = "unknown"
dmsh-0.2.18/src/dmsh/__init__.py 0000664 0000000 0000000 00000001052 14134252050 0016362 0 ustar 00root root 0000000 0000000 from .__about__ import __version__
from .geometry import (
Circle,
Difference,
Ellipse,
Geometry,
HalfSpace,
Intersection,
Path,
Polygon,
Rectangle,
Rotation,
Scaling,
Stretch,
Translation,
Union,
)
from .main import generate
__all__ = [
"__version__",
"generate",
"Circle",
"Difference",
"Ellipse",
"Geometry",
"HalfSpace",
"Intersection",
"Path",
"Polygon",
"Rectangle",
"Rotation",
"Stretch",
"Scaling",
"Translation",
"Union",
]
dmsh-0.2.18/src/dmsh/geometry/ 0000775 0000000 0000000 00000000000 14134252050 0016106 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/src/dmsh/geometry/__init__.py 0000664 0000000 0000000 00000001072 14134252050 0020217 0 ustar 00root root 0000000 0000000 from .circle import Circle
from .ellipse import Ellipse
from .geometry import (
Difference,
Geometry,
Intersection,
Scaling,
Stretch,
Translation,
Union,
)
from .halfspace import HalfSpace
from .path import Path
from .polygon import Polygon
from .rectangle import Rectangle
from .rotation import Rotation
__all__ = [
"Circle",
"Difference",
"Ellipse",
"Geometry",
"HalfSpace",
"Intersection",
"Path",
"Polygon",
"Rectangle",
"Rotation",
"Scaling",
"Stretch",
"Translation",
"Union",
]
dmsh-0.2.18/src/dmsh/geometry/circle.py 0000664 0000000 0000000 00000003157 14134252050 0017727 0 ustar 00root root 0000000 0000000 from typing import Tuple
import numpy as np
from .geometry import Geometry
class CirclePath:
def __init__(self, x0: Tuple[float, float], r: float):
self.x0 = x0
self.r = r
def p(self, t):
v = np.array([np.cos(2 * np.pi * t), np.sin(2 * np.pi * t)])
return ((self.r * v).T + self.x0).T
def dp_dt(self, t):
return (
self.r
* 2
* np.pi
* np.array([-np.sin(2 * np.pi * t), np.cos(2 * np.pi * t)])
)
class Circle(Geometry):
def __init__(self, x0, r):
self.x0 = x0
self.r = r
bounding_box = [x0[0] - r, x0[0] + r, x0[1] - r, x0[1] + r]
self.paths = [CirclePath(x0, r)]
feature_points = np.array([[], []]).T
super().__init__(bounding_box, feature_points)
def dist(self, x):
assert x.shape[0] == 2
y = (x.T - self.x0).T
return np.sqrt(np.einsum("i...,i...->...", y, y)) - self.r
def boundary_step(self, x):
# simply project onto the circle
y = (x.T - self.x0).T
r = np.sqrt(np.einsum("ij,ij->j", y, y))
return ((y / r * self.r).T + self.x0).T
def plot(self, level_set=True):
import matplotlib.pyplot as plt
if level_set:
X, Y, Z = self._get_xyz()
alpha = np.max(np.abs(Z))
cf = plt.contourf(
X, Y, Z, levels=20, cmap=plt.cm.coolwarm, vmin=-alpha, vmax=alpha
)
plt.colorbar(cf)
circle1 = plt.Circle(self.x0, self.r, color="k", fill=False)
plt.gca().add_patch(circle1)
plt.gca().set_aspect("equal")
dmsh-0.2.18/src/dmsh/geometry/ellipse.py 0000664 0000000 0000000 00000002702 14134252050 0020116 0 ustar 00root root 0000000 0000000 import numpy as np
from ..helpers import multi_newton
from .geometry import Geometry
class Ellipse(Geometry):
def __init__(self, x0, a, b):
super().__init__()
self.x0 = x0
self.a = a
self.b = b
self.bounding_box = [x0[0] - a, x0[0] + a, x0[1] - b, x0[1] + b]
self.feature_points = np.array([])
def dist(self, x):
assert x.shape[0] == 2
return (
((x[0] - self.x0[0]) / self.a) ** 2
+ ((x[1] - self.x0[1]) / self.b) ** 2
- 1.0
)
def _boundary_step(self, x):
ax = (x[0] - self.x0[0]) / self.a
ay = (x[1] - self.x0[1]) / self.b
alpha = ax ** 2 + ay ** 2 - 1.0
jac = np.array([4 * alpha * ax / self.a, 4 * alpha * ay / self.b])
dalpha_dx = 2 * ax / self.a
dalpha_dy = 2 * ay / self.b
hess = np.array(
[
[
4 * dalpha_dx * ax / self.a + 4 * alpha / self.a ** 2,
4 * dalpha_dy * ax / self.a,
],
[
4 * dalpha_dx * ay / self.b,
4 * dalpha_dy * ay / self.b + 4 * alpha / self.b ** 2,
],
]
)
p = -np.linalg.solve(np.moveaxis(hess, -1, 0), jac.T)
return x + p.T
def boundary_step(self, x):
return multi_newton(
x.T, self.dist, self._boundary_step, 1.0e-10, max_num_steps=10
).T
dmsh-0.2.18/src/dmsh/geometry/geometry.py 0000664 0000000 0000000 00000025427 14134252050 0020325 0 ustar 00root root 0000000 0000000 import numpy as np
from ..helpers import find_feature_points
class Geometry:
def __init__(self, bounding_box, feature_points):
self.bounding_box = bounding_box
self.feature_points = feature_points
def _get_xyz(self, nx=101, ny=101):
x0, x1, y0, y1 = self.bounding_box
w = x1 - x0
h = x1 - x0
x = np.linspace(x0 - w * 0.1, x1 + w * 0.1, nx)
y = np.linspace(y0 - h * 0.1, y1 + h * 0.1, ny)
X, Y = np.meshgrid(x, y)
Z = self.dist(np.array([X, Y]))
return X, Y, Z
def dist(self, _):
raise NotImplementedError("dist() not implemented")
def _plot_level_set(self):
import matplotlib.pyplot as plt
X, Y, Z = self._get_xyz()
alpha = np.max(np.abs(Z))
cf = plt.contourf(
X, Y, Z, levels=20, cmap=plt.cm.coolwarm, vmin=-alpha, vmax=alpha
)
plt.colorbar(cf)
def plot(self, level_set=True):
import matplotlib.pyplot as plt
X, Y, Z = self._get_xyz()
if level_set:
alpha = np.max(np.abs(Z))
cf = plt.contourf(
X, Y, Z, levels=20, cmap=plt.cm.coolwarm, vmin=-alpha, vmax=alpha
)
plt.colorbar(cf)
# mark the 0-level (the domain boundary)
plt.contour(X, Y, Z, levels=[0.0], colors="k")
plt.gca().set_aspect("equal")
def show(self, *args, **kwargs):
import matplotlib.pyplot as plt
self.plot(*args, **kwargs)
plt.show()
def __add__(self, obj):
if isinstance(obj, Geometry):
return Union([self, obj])
return Translation(self, obj)
def __radd__(self, obj):
return self.__add__(obj)
def __sub__(self, obj):
if isinstance(obj, Geometry):
return Difference(self, obj)
return Translation(self, -obj)
def __and__(self, obj):
return Intersection([self, obj])
def __or__(self, obj):
return Union([self, obj])
def __mul__(self, alpha: float):
return Scaling(self, alpha)
def __rmul__(self, alpha: float):
return self.__mul__(alpha)
def stretch(self, obj):
return Stretch(self, obj)
class Union(Geometry):
def __init__(self, geometries):
self.geometries = geometries
bounding_box = [
np.min([geo.bounding_box[0] for geo in geometries]),
np.max([geo.bounding_box[1] for geo in geometries]),
np.min([geo.bounding_box[2] for geo in geometries]),
np.max([geo.bounding_box[3] for geo in geometries]),
]
fp = [geo.feature_points for geo in geometries]
fp.append(find_feature_points(geometries))
feature_points = np.concatenate(fp)
# Only keep the feature points on the outer boundary
alpha = np.array([geo.dist(feature_points.T) for geo in geometries])
tol = 1.0e-5
is_on_boundary = np.all(alpha > -tol, axis=0)
feature_points = feature_points[is_on_boundary]
self.paths = [path for geo in self.geometries for path in geo.paths]
super().__init__(bounding_box, feature_points)
def dist(self, x):
return np.min([geo.dist(x) for geo in self.geometries], axis=0)
def boundary_step(self, x, tol=1.0e-12, max_steps=100):
# step for the is_inside with the smallest value
x = np.asarray(x)
alpha = np.array([geo.dist(x) for geo in self.geometries])
step = 0
while np.any(np.abs(np.min(alpha, axis=0)) > tol):
assert step <= max_steps, "Exceeded maximum number of boundary steps."
step += 1
# If the point has a positive geo distance, it is outside of the domain. In
# this case, move it to the geo boundary with the smallest distance.
# If the point is strictly inside all geometries, move it to the furthest
# geometry boundary.
mask = np.all(alpha > tol, axis=0) | np.any(alpha < -tol, axis=0)
x_tmp = x[:, mask]
idx = np.argmin(alpha[:, mask], axis=0)
for k, geo in enumerate(self.geometries):
if np.any(idx == k):
x_tmp[:, idx == k] = geo.boundary_step(x_tmp[:, idx == k])
x[:, mask] = x_tmp
alpha = np.array([geo.dist(x) for geo in self.geometries])
return x
class Stretch(Geometry):
def __init__(self, geometry, v):
self.geometry = geometry
self.alpha = np.sqrt(np.dot(v, v))
self.v = v / self.alpha
# bounding box
bb = geometry.bounding_box
corners = np.array(
[[bb[0], bb[2]], [bb[1], bb[2]], [bb[1], bb[3]], [bb[0], bb[3]]]
)
vx = np.multiply.outer(np.dot(self.v, corners.T), self.v)
stretched_corners = (vx * self.alpha + (corners - vx)).T
bounding_box = [
np.min(stretched_corners[0]),
np.max(stretched_corners[0]),
np.min(stretched_corners[1]),
np.max(stretched_corners[1]),
]
super().__init__(bounding_box, feature_points=[])
def dist(self, x):
# scale the component of x in direction v by 1/alpha
x_shape = x.shape
assert x.shape[0] == 2
x = x.reshape(2, -1)
vx = np.multiply.outer(np.dot(self.v, x), self.v)
y = vx / self.alpha + (x.T - vx)
y = y.T.reshape(x_shape)
return self.geometry.dist(y)
def boundary_step(self, x):
vx = np.multiply.outer(np.dot(self.v, x), self.v)
y = vx / self.alpha + (x.T - vx)
y2 = self.geometry.boundary_step(y.T)
vy2 = np.multiply.outer(np.dot(self.v, y2), self.v)
return (vy2 * self.alpha + (y2.T - vy2)).T
class Difference(Geometry):
def __init__(self, geo0, geo1):
self.geo0 = geo0
self.geo1 = geo1
fp = [geo0.feature_points, geo1.feature_points]
fp.append(find_feature_points([geo0, geo1]))
feature_points = np.concatenate(fp)
# Only keep the feature points on the outer boundary
alpha = self.dist(feature_points.T)
tol = 1.0e-5
is_on_boundary = (-tol < alpha) & (alpha < tol)
feature_points = feature_points[is_on_boundary]
self.paths = [path for geo in [geo0, geo1] for path in geo.paths]
super().__init__(geo0.bounding_box, feature_points)
def dist(self, x):
return np.max([self.geo0.dist(x), -self.geo1.dist(x)], axis=0)
# Choose tolerance above sqrt(machine_eps). This is necessary as the polygon
# dist() is only accurate to that precision.
def boundary_step(self, x, tol=1.0e-12, max_steps=100):
# Scale the tolerance with the domain diameter. This is necessary at least for
# polygons where the distance calculation is flawed with round-off proportional
# to the edge lengths.
try:
tol *= self.geo0.diameter
except AttributeError:
pass
alpha = np.array([self.geo0.dist(x), -self.geo1.dist(x)])
mask = np.any(alpha > tol, axis=0) | np.all(alpha < -tol, axis=0)
step = 0
while np.any(mask):
assert step <= max_steps, "Exceeded maximum number of boundary steps."
step += 1
x_tmp = x[:, mask]
idx = np.argmax(alpha[:, mask], axis=0)
if np.any(idx == 0):
x_tmp[:, idx == 0] = self.geo0.boundary_step(x_tmp[:, idx == 0])
if np.any(idx == 1):
x_tmp[:, idx == 1] = self.geo1.boundary_step(x_tmp[:, idx == 1])
x[:, mask] = x_tmp
alpha = np.array([self.geo0.dist(x), -self.geo1.dist(x)])
mask = np.any(alpha > tol, axis=0) | np.all(alpha < -tol, axis=0)
return x
class Translation(Geometry):
def __init__(self, geometry, v):
self.geometry = geometry
self.v = v
bounding_box = [
geometry.bounding_box[0] + v[0],
geometry.bounding_box[1] + v[0],
geometry.bounding_box[2] + v[1],
geometry.bounding_box[3] + v[1],
]
super().__init__(bounding_box, feature_points=[])
def dist(self, x):
return self.geometry.dist((x.T - self.v).T)
def boundary_step(self, x):
return (self.geometry.boundary_step((x.T - self.v).T).T + self.v).T
class Intersection(Geometry):
def __init__(self, geometries):
self.geometries = geometries
bounding_box = [
np.max([geo.bounding_box[0] for geo in geometries]),
np.min([geo.bounding_box[1] for geo in geometries]),
np.max([geo.bounding_box[2] for geo in geometries]),
np.min([geo.bounding_box[3] for geo in geometries]),
]
feature_points = find_feature_points(geometries)
# filter out the feature points outside the intersection
feature_points = feature_points[
np.all(
[geo.dist(feature_points.T) < 1.0e-10 for geo in geometries],
axis=0,
)
]
self.paths = [path for geo in self.geometries for path in geo.paths]
super().__init__(bounding_box, feature_points)
def dist(self, x):
return np.max([geo.dist(x) for geo in self.geometries], axis=0)
def boundary_step(self, x, tol=1.0e-12, max_steps=100):
# step for the is_inside with the smallest value
x = np.asarray(x)
alpha = np.array([geo.dist(x) for geo in self.geometries])
step = 0
while np.any(np.abs(np.max(alpha, axis=0)) > tol):
assert step <= max_steps, "Exceeded maximum number of boundary steps."
step += 1
# If the point has a positive geo distance, it is outside of the domain. In
# this case, move it to the geo boundary with the largest distance.
# If the point is strictly inside all geometries, move it to the closest
# geometry boundary.
# Both of these cases correspond to finding the domain with the max dist
# value.
mask = np.any(alpha > tol, axis=0) | np.all(alpha < -tol, axis=0)
x_tmp = x[:, mask]
alpha_pos = alpha[:, mask]
idx = np.argmax(alpha_pos, axis=0)
for k, geo in enumerate(self.geometries):
if np.any(idx == k):
x_tmp[:, idx == k] = geo.boundary_step(x_tmp[:, idx == k])
x[:, mask] = x_tmp
alpha = np.array([geo.dist(x) for geo in self.geometries])
return x
class Scaling(Geometry):
def __init__(self, geometry: Geometry, alpha: float):
self.geometry = geometry
self.alpha = alpha
bounding_box = alpha * np.array(geometry.bounding_box)
super().__init__(bounding_box, feature_points=[])
def dist(self, x):
return self.geometry.dist(x / self.alpha)
def boundary_step(self, x):
return self.geometry.boundary_step(x / self.alpha) * self.alpha
dmsh-0.2.18/src/dmsh/geometry/halfspace.py 0000664 0000000 0000000 00000002646 14134252050 0020416 0 ustar 00root root 0000000 0000000 import numpy as np
from .geometry import Geometry
class LinePath:
def __init__(self, v, tangent):
self.v = v
self.tangent = tangent
def p(self, t):
"""This parametrization of the line is (inf, inf) for t=0 and t=1."""
# Don't warn on division by 0
with np.errstate(divide="ignore"):
out = (
np.multiply.outer(self.tangent, (2 * t - 1) / t / (1 - t)).T + self.v
).T
return out
def dp_dt(self, t):
with np.errstate(divide="ignore"):
dt = 1 / t ** 2 + 1 / (1 - t) ** 2
return np.multiply.outer(self.tangent, dt)
class HalfSpace(Geometry):
def __init__(self, normal, alpha=0.0):
self.normal = normal
self.alpha = alpha
bounding_box = [-np.inf, +np.inf, -np.inf, +np.inf]
# One point on the line:
v = self.normal / np.dot(self.normal, self.normal) * self.alpha
tangent = np.array([-self.normal[1], self.normal[0]])
self.paths = [LinePath(v, tangent)]
super().__init__(bounding_box, feature_points=[])
def dist(self, x):
assert x.shape[0] == 2
out = self.alpha - np.dot(self.normal, x.reshape(x.shape[0], -1))
return out.reshape(x.shape[1:])
def boundary_step(self, x):
beta = self.alpha - np.dot(self.normal, x) / np.dot(self.normal, self.normal)
return x + np.multiply.outer(self.normal, beta)
dmsh-0.2.18/src/dmsh/geometry/path.py 0000664 0000000 0000000 00000001760 14134252050 0017420 0 ustar 00root root 0000000 0000000 import numpy as np
from . import pypathlib
class LineSegmentPath:
def __init__(self, x0, x1):
self.x0 = x0
self.x1 = x1
return
def p(self, t):
return np.multiply.outer(self.x0, 1 - t) + np.multiply.outer(self.x1, t)
def dp_dt(self, t):
ones = np.ones(t.shape)
return np.multiply.outer(self.x0, -ones) + np.multiply.outer(self.x1, ones)
class Path:
def __init__(self, points):
points = np.array(points)
self.path = pypathlib.Path(points)
self.bounding_box = [
np.min(points[:, 0]),
np.max(points[:, 0]),
np.min(points[:, 1]),
np.max(points[:, 1]),
]
self.feature_points = points
self.paths = [
LineSegmentPath(p0, p1) for p0, p1 in zip(points[:-1], points[1:])
]
return
def dist(self, x):
return self.path.distance(x.T)
def boundary_step(self, x):
return self.path.closest_points(x.T).T
dmsh-0.2.18/src/dmsh/geometry/polygon.py 0000664 0000000 0000000 00000002750 14134252050 0020153 0 ustar 00root root 0000000 0000000 import numpy as np
from . import pypathlib
from .geometry import Geometry
class LineSegmentPath:
def __init__(self, x0, x1):
self.x0 = x0
self.x1 = x1
def p(self, t):
return np.multiply.outer(self.x0, 1 - t) + np.multiply.outer(self.x1, t)
def dp_dt(self, t):
ones = np.ones(t.shape)
return np.multiply.outer(self.x0, -ones) + np.multiply.outer(self.x1, ones)
class Polygon(Geometry):
def __init__(self, points):
points = np.asarray(points)
bounding_box = [
np.min(points[:, 0]),
np.max(points[:, 0]),
np.min(points[:, 1]),
np.max(points[:, 1]),
]
self.polygon = pypathlib.ClosedPath(points)
self.paths = [
LineSegmentPath(p0, p1)
for p0, p1 in zip(points, np.roll(points, -1, axis=0))
]
self.diameter = self.polygon.diameter
super().__init__(bounding_box, feature_points=points)
def dist(self, x):
assert x.shape[0] == 2
X = x.reshape(2, -1)
out = self.polygon.signed_distance(X.T)
return out.reshape(x.shape[1:])
def boundary_step(self, x):
return self.polygon.closest_points(x.T).T
def plot(self, level_set=True):
import matplotlib.pyplot as plt
if level_set:
self._plot_level_set()
obj = plt.Polygon(self.feature_points, color="k", fill=False)
plt.gca().add_patch(obj)
plt.gca().set_aspect("equal")
dmsh-0.2.18/src/dmsh/geometry/pypathlib/ 0000775 0000000 0000000 00000000000 14134252050 0020102 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/src/dmsh/geometry/pypathlib/__init__.py 0000664 0000000 0000000 00000000150 14134252050 0022207 0 ustar 00root root 0000000 0000000 from .closed_path import ClosedPath
from .path import Path
__all__ = [
"ClosedPath",
"Path",
]
dmsh-0.2.18/src/dmsh/geometry/pypathlib/closed_path.py 0000664 0000000 0000000 00000005452 14134252050 0022747 0 ustar 00root root 0000000 0000000 import numpy as np
from .helpers import shoelace
from .path import Path
class ClosedPath(Path):
def __init__(self, points):
closed_points = np.concatenate([points, [points[0]]])
super().__init__(closed_points)
assert self.points.shape[0] > 2
assert self.points.shape[1] == 2
self.area = 0.5 * shoelace(self.points)
self.positive_orientation = self.area >= 0
if self.area < 0:
self.area = -self.area
self._is_convex_node = None
return
def signed_squared_distance(self, x):
"""Negative inside the polygon."""
x = np.array(x)
assert x.shape[1] == 2
t, dist2, idx = self._all_distances(x)
contains_points = self._contains_points(t, x, idx)
dist2[contains_points] *= -1
return dist2
def signed_distance(self, x):
"""Negative inside the polygon."""
x = np.array(x)
assert x.shape[1] == 2
t, dist2, idx = self._all_distances(x)
dist = np.sqrt(dist2)
contains_points = self._contains_points(t, x, idx)
dist[contains_points] *= -1
return dist
def _contains_points(self, t, x, idx):
r = np.arange(idx.shape[0])
contains_points = np.zeros(x.shape[0], dtype=bool)
pts0 = self.points
pts1 = np.roll(self.points, -1, axis=0)
# If the point is closest to a polygon edge, check which which side of the edge
# it is on.
is_closest_to_side = (0.0 < t[r, idx]) & (t[r, idx] < 1.0)
tri = np.array(
[
x[is_closest_to_side],
pts0[idx[is_closest_to_side]],
pts1[idx[is_closest_to_side]],
]
)
contains_points[is_closest_to_side] = (
shoelace(tri) > 0.0
) == self.positive_orientation
# If the point is closest to a polygon node, check if the node is convex or
# concave.
is_closest_to_pt0 = t[r, idx] <= 0.0
contains_points[is_closest_to_pt0] = ~self.is_convex_node[
idx[is_closest_to_pt0]
]
is_closest_to_pt1 = 1.0 <= t[r, idx]
n = self.points.shape[0] - 1
contains_points[is_closest_to_pt1] = ~self.is_convex_node[
(idx[is_closest_to_pt1] + 1) % n
]
return contains_points
def contains_points(self, x, tol=1.0e-15):
return self.signed_distance(x) < tol
@property
def is_convex_node(self):
points = self.points[:-1]
if self._is_convex_node is None:
tri = np.array(
[np.roll(points, +1, axis=0), points, np.roll(points, -1, axis=0)]
)
self._is_convex_node = np.equal(
shoelace(tri) >= 0, self.positive_orientation
)
return self._is_convex_node
dmsh-0.2.18/src/dmsh/geometry/pypathlib/helpers.py 0000664 0000000 0000000 00000000242 14134252050 0022114 0 ustar 00root root 0000000 0000000 import numpy as np
def shoelace(x):
previous = np.roll(x, 1, axis=0)
return np.sum(x[..., 1] * previous[..., 0] - x[..., 0] * previous[..., 1], axis=0)
dmsh-0.2.18/src/dmsh/geometry/pypathlib/path.py 0000664 0000000 0000000 00000006676 14134252050 0021427 0 ustar 00root root 0000000 0000000 import numpy as np
class Path:
def __init__(self, points):
self.points = np.asarray(points)
assert self.points.shape[1] == 2
self.edges = self.points[1:] - self.points[:-1]
self.e_dot_e = np.einsum("ij,ij->i", self.edges, self.edges)
assert np.all(
self.e_dot_e > 1.0e-12
), f"Edges of 0 length are not permitted (squared edge lengths: {self.e_dot_e})"
def _all_distances(self, x):
x = np.asarray(x)
assert x.shape[1] == 2
if self.points.shape[0] == 1:
# In case there is only one point, i.e., no sides.
diff = x[:, None] - self.points[None, :]
dist2_points = np.einsum("ijk,ijk->ij", diff, diff)
idx = np.zeros(dist2_points.shape[0], dtype=int)
t = 0.0
return t, dist2_points.T, idx
# Find closest point for each side segment
#
diff = x[:, None] - self.points[None, :-1]
t = np.einsum("ijk,jk->ij", diff, self.edges) / self.e_dot_e
t[t < 0.0] = 0.0
t[t > 1.0] = 1.0
# The squared distance from the point x to the infinite line defined by the
# points x0, x1 (e = x1 - x0) is , where proj is the
# projection of x onto the line. The expression can be simplified to
#
# ( - **2) /
#
# but this expression is numerically disadvantageous. (For example, the
# expression can become negative due to round-off.) Simply compute the
# projection and the dot product.
x_min_proj = diff - t[:, :, None] * self.edges[None, :, :]
dist2_sides = np.einsum("ijk,ijk->ij", x_min_proj, x_min_proj)
idx = np.argmin(dist2_sides, axis=1)
dist2_sides = dist2_sides[np.arange(idx.shape[0]), idx]
# t-parameter for each side, the squared min distance, and the index of the
# closest side
return t, dist2_sides, idx
@property
def diameter(self):
# compute distance from all points to each other
diff = self.points[:, None] - self.points[None, :]
dist2 = np.einsum("ijk,ijk->ij", diff, diff)
return np.sqrt(np.max(dist2))
def squared_distance(self, x):
"""Get the squared distance of all points x to the polygon."""
x = np.asarray(x)
assert x.shape[1] == 2
_, dist2_sides, _ = self._all_distances(x)
return dist2_sides
def distance(self, x):
"""Get the distance of all points x to the polygon."""
return np.sqrt(self.squared_distance(x))
def closest_points(self, x):
"""Get the closest points on the polygon."""
x = np.asarray(x)
assert x.shape[1] == 2
t, _, idx = self._all_distances(x)
pts0 = self.points[idx]
pts1 = np.roll(self.points, -1, axis=0)[idx]
r = np.arange(t.shape[0])
t0 = t[r, idx]
closest_points = (pts0.T * (1 - t0)).T + (pts1.T * t0).T
return closest_points
def plot(self, color="#1f77b4"):
import matplotlib.pyplot as plt
x = np.concatenate([self.points[:, 0], [self.points[0, 0]]])
y = np.concatenate([self.points[:, 1], [self.points[0, 1]]])
plt.plot(x, y, "-", color=color)
plt.axis("square")
def show(self, *args, **kwargs):
import matplotlib.pyplot as plt
self.plot(*args, **kwargs)
plt.show()
dmsh-0.2.18/src/dmsh/geometry/rectangle.py 0000664 0000000 0000000 00000005314 14134252050 0020427 0 ustar 00root root 0000000 0000000 import numpy as np
from .geometry import Geometry
from .polygon import LineSegmentPath
class Rectangle(Geometry):
# One could simply make Rectangle a child class of Polygon. However, boundary steps
# can be inaccurate for polygons (there is some computation involved).
def __init__(self, x0, x1, y0, y1):
assert x0 < x1
assert y0 < y1
self.x0 = x0
self.x1 = x1
self.y0 = y0
self.y1 = y1
self.points = np.array([[x0, y0], [x1, y0], [x1, y1], [x0, y1]])
bounding_box = [
np.min(self.points[:, 0]),
np.max(self.points[:, 0]),
np.min(self.points[:, 1]),
np.max(self.points[:, 1]),
]
self.paths = [
LineSegmentPath(p0, p1)
for p0, p1 in zip(self.points, np.roll(self.points, -1, axis=0))
]
super().__init__(bounding_box, feature_points=self.points)
def dist(self, x):
# outside dist
# https://gamedev.stackexchange.com/a/44496
x = np.asarray(x)
w = self.x1 - self.x0
h = self.y1 - self.y0
cx = (self.x0 + self.x1) / 2
cy = (self.y0 + self.y1) / 2
dx = np.abs(x[0] - cx) - w / 2
dy = np.abs(x[1] - cy) - h / 2
is_inside = (dx <= 0) & (dy <= 0)
dx[dx < 0.0] = 0.0
dy[dy < 0.0] = 0.0
dist = np.sqrt(dx ** 2 + dy ** 2)
# inside dist
a = np.array(
[
x[0, is_inside] - self.x0,
self.x1 - x[0, is_inside],
x[1, is_inside] - self.y0,
self.y1 - x[1, is_inside],
]
)
dist[is_inside] = -np.min(a, axis=0)
return dist
def boundary_step(self, x):
x = np.asarray(x)
assert x.shape[0] == 2
is_one_dimensional = False
if len(x.shape) == 1:
is_one_dimensional = True
x = x.reshape(-1, 1)
cx = (self.x0 + self.x1) / 2
cy = (self.y0 + self.y1) / 2
w = self.x1 - self.x0
h = self.y1 - self.y0
X = x[0] - cx
Y = x[1] - cy
# Take care of the outside points
X[X < -w / 2] = -w / 2
X[X > +w / 2] = +w / 2
Y[Y < -h / 2] = -h / 2
Y[Y > +h / 2] = +h / 2
# Interior points
is_interior = (-w / 2 < X) & (X < w / 2) & (-h / 2 < Y) & (Y < h / 2)
a = h * X < w * Y
b = -h * X < w * Y
Y[is_interior & a & b] = h / 2
Y[is_interior & ~a & ~b] = -h / 2
X[is_interior & ~a & b] = w / 2
X[is_interior & a & ~b] = -w / 2
X += cx
Y += cy
out = np.array([X, Y])
if is_one_dimensional:
out = out.reshape(-1)
return out
dmsh-0.2.18/src/dmsh/geometry/rotation.py 0000664 0000000 0000000 00000002251 14134252050 0020317 0 ustar 00root root 0000000 0000000 import numpy as np
from .geometry import Geometry
class Rotation(Geometry):
def __init__(self, geometry, angle):
self.geometry = geometry
self.R = np.array(
[
[+np.cos(angle), -np.sin(angle)],
[+np.sin(angle), +np.cos(angle)],
]
)
self.R_inv = np.array(
[
[+np.cos(angle), +np.sin(angle)],
[-np.sin(angle), +np.cos(angle)],
]
)
# bounding box
bb = geometry.bounding_box
corners = np.array(
[[bb[0], bb[2]], [bb[1], bb[2]], [bb[1], bb[3]], [bb[0], bb[3]]]
)
rotated_corners = np.dot(self.R, corners.T)
bounding_box = [
np.min(rotated_corners[0]),
np.max(rotated_corners[0]),
np.min(rotated_corners[1]),
np.max(rotated_corners[1]),
]
super().__init__(bounding_box, feature_points=[])
def dist(self, x):
return self.geometry.dist(np.dot(self.R_inv, x))
def boundary_step(self, x):
y = np.dot(self.R_inv, x)
y2 = self.geometry.boundary_step(y)
return np.dot(self.R, y2)
dmsh-0.2.18/src/dmsh/helpers.py 0000664 0000000 0000000 00000012657 14134252050 0016302 0 ustar 00root root 0000000 0000000 from __future__ import annotations
from typing import Callable
import numpy as np
def multi_newton(
x0: np.ndarray,
is_inside: Callable,
boundary_step: Callable,
tol: float,
max_num_steps: int = 10,
) -> np.ndarray:
"""Newton's minimization method for multiple starting points."""
x = x0.copy()
fx = is_inside(x.T)
k = 0
mask = np.abs(fx) > tol
while np.any(mask):
x[mask] = boundary_step(x[mask].T).T
fx = is_inside(x.T)
mask = np.abs(fx) > tol
k += 1
if k >= max_num_steps:
break
return x
def show(pts, cells, geo, title: str | None = None, full_screen: bool = True):
import matplotlib.pyplot as plt
eps = 1.0e-10
# highlight outside points in C3, and points which aren't part of any cell in C4
is_part_of_cell = np.zeros(len(pts), dtype=bool)
is_part_of_cell[cells.flat] = True
is_inside = geo.dist(pts.T) < eps
sp = pts[is_inside & is_part_of_cell]
plt.plot(sp[:, 0], sp[:, 1], ".", color="C0")
sp = pts[~is_inside]
plt.plot(sp[:, 0], sp[:, 1], ".", color="C3")
sp = pts[~is_part_of_cell]
plt.plot(sp[:, 0], sp[:, 1], ".", color="k")
# plt.plot(pts[~is_inside, 0], pts[~is_part_of_cell, 1], ".", color="k")
plt.triplot(pts[:, 0], pts[:, 1], cells)
plt.axis("square")
# show cells indices
# for idx, barycenter in enumerate(np.sum(pts[cells], axis=1) / 3):
# plt.plot(*barycenter, "xk")
# plt.text(
# *barycenter, idx, horizontalalignment="center", verticalalignment="center"
# )
# show node indices
# for idx, pt in enumerate(pts):
# plt.text(
# *pt, idx, horizontalalignment="center", verticalalignment="center"
# )
if full_screen:
figManager = plt.get_current_fig_manager()
try:
figManager.window.showMaximized()
except AttributeError:
# Some backends have no window (e.g., Agg)
pass
if title is not None:
plt.title(title)
try:
geo.show(level_set=False)
except AttributeError:
pass
def find_feature_points(geometries, num_steps: int = 10):
n = len(geometries)
# collect path pairs
path_pairs = [
[item0, item1]
for i in range(n)
for j in range(i + 1, n)
for item0 in geometries[i].paths
for item1 in geometries[j].paths
]
points = np.column_stack(
[
_find_feature_points_between_two_paths(path0, path1, num_steps)
for path0, path1 in path_pairs
]
)
if points.shape[1] > 0:
points = unique_float_cols(points)
return points.T
def _find_feature_points_between_two_paths(path0, path1, num_steps, nx=11, ny=11):
"""Given two geometries with their parametrization, this methods finds feature
points, i.e., points where the boundaries meet. This is done by casting a net over
the parameter space and performing `num_steps` Newton steps. Found solutions are
checked for uniqueness.
"""
# Throw a net
t0, t1 = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 1.0, ny))
t = np.array([t0, t1]).reshape(2, -1)
# t = np.random.rand(2, 100)
tol = 1.0e-20
# multi_newton(x0, is_inside, boundary_step, tol, max_num_steps=10):
solutions = []
for k in range(num_steps):
f_t = path0.p(t[0]) - path1.p(t[1])
# remove all inf values
is_infinite = np.any(np.isinf(f_t), axis=0)
if np.any(is_infinite):
t = t[:, ~is_infinite]
f_t = f_t[:, ~is_infinite]
f_dot_f = np.einsum("ij,ij->j", f_t, f_t)
is_sol = f_dot_f < tol
if np.any(is_sol):
solutions.append(t[:, is_sol])
# remove all converged solutions
t = t[:, ~is_sol]
f_t = f_t[:, ~is_sol]
jac_t = np.moveaxis(np.stack([path0.dp_dt(t[0]), -path1.dp_dt(t[1])]), 0, 1)
# Kick out singular matrices
det = jac_t[0, 0] * jac_t[1, 1] - jac_t[0, 1] * jac_t[1, 0]
is_singular = np.abs(det) < 1.0e-13
if np.any(is_singular):
t = t[:, ~is_singular]
f_t = f_t[:, ~is_singular]
jac_t = jac_t[..., ~is_singular]
# Simply make it explicitly.
sols = []
for k in range(f_t.shape[-1]):
try:
sols.append(np.linalg.solve(jac_t[..., k], f_t[:, k]))
except np.linalg.linalg.LinAlgError:
# singular matrix
sols.append(np.zeros(f_t[:, k].shape))
sols = np.array(sols).T
# Newton step
t -= sols
# Kick out everything that leaves the unit square
still_good = np.all((0.0 <= t) & (t <= 1.0), axis=0)
t = t[:, still_good]
if solutions:
unique_sols = unique_float_cols(np.column_stack(solutions))
points0 = path0.p(unique_sols[0])
# points1 = path1.p(unique_sols[1])
else:
points0 = np.array([[], []])
return points0
def unique_float_cols(data: np.ndarray, k: int = 0, tol: float = 1.0e-10):
"""In a (k, n) array `data`, find the unique columns."""
if k == data.shape[0]:
return data[:, 0]
idx = np.argsort(data[k])
data = data[:, idx]
diff = data[k, 1:] - data[k, :-1]
cut = diff > tol
idx = np.where(cut)[0]
chunks = np.split(data, idx + 1, axis=1)
out = np.column_stack([unique_float_cols(chunk, k + 1, tol) for chunk in chunks])
return out
dmsh-0.2.18/src/dmsh/main.py 0000664 0000000 0000000 00000026753 14134252050 0015566 0 ustar 00root root 0000000 0000000 from __future__ import annotations
import math
from typing import Callable
import meshplex
import npx
import numpy as np
import scipy.spatial
from .geometry import Geometry
from .helpers import show as show_mesh
def _create_cells(pts, geo: Geometry):
# compute Delaunay triangulation
tri = scipy.spatial.Delaunay(pts)
cells = tri.simplices.copy()
# kick out all cells whose barycenter is not in the geometry
bc = np.sum(pts[cells], axis=1) / 3.0
cells = cells[geo.dist(bc.T) < 0.0]
# # kick out all cells whose barycenter or edge midpoints are not in the geometry
# btol = 1.0e-3
# bc = np.sum(pts[cells], axis=1) / 3.0
# barycenter_inside = geo.dist(bc.T) < btol
# # Remove cells which are (partly) outside of the domain. Check at the midpoint of
# # all edges.
# mid0 = (pts[cells[:, 1]] + pts[cells[:, 2]]) / 2
# mid1 = (pts[cells[:, 2]] + pts[cells[:, 0]]) / 2
# mid2 = (pts[cells[:, 0]] + pts[cells[:, 1]]) / 2
# edge_midpoints_inside = (
# (geo.dist(mid0.T) < btol)
# & (geo.dist(mid1.T) < btol)
# & (geo.dist(mid2.T) < btol)
# )
# cells = cells[barycenter_inside & edge_midpoints_inside]
return cells
def _recell_and_boundary_step(mesh, geo, flip_tol):
# We could do a _create_cells() here, but inverted boundary cell removal plus Lawson
# flips produce the same result and are much cheaper. This is because, most of the
# time, there are no cells to be removed and no edges to be flipped. (The flip is
# still a fairly expensive operation.)
while True:
idx = mesh.is_boundary_point
points_new = mesh.points.copy()
points_new[idx] = geo.boundary_step(points_new[idx].T).T
mesh.points = points_new
#
num_removed_cells = mesh.remove_boundary_cells(
lambda is_bdry_cell: mesh.compute_signed_cell_volumes(is_bdry_cell)
< 1.0e-10
)
#
# The flip has to come right after the boundary cell removal to prevent
# "degenerate cell" errors.
mesh.flip_until_delaunay(tol=flip_tol)
#
if num_removed_cells == 0:
break
# Last kick out all boundary cells whose barycenters are not in the geometry.
mesh.remove_boundary_cells(
lambda is_bdry_cell: geo.dist(mesh.compute_cell_centroids(is_bdry_cell).T) > 0.0
)
def create_staggered_grid(h, bounding_box):
x_step = h
y_step = h * np.sqrt(3) / 2
bb_width = bounding_box[1] - bounding_box[0]
bb_height = bounding_box[3] - bounding_box[2]
midpoint = [
(bounding_box[0] + bounding_box[1]) / 2,
(bounding_box[2] + bounding_box[3]) / 2,
]
num_x_steps = int(bb_width / x_step)
if num_x_steps % 2 == 1:
num_x_steps -= 1
num_y_steps = int(bb_height / y_step)
if num_y_steps % 2 == 1:
num_y_steps -= 1
# Generate initial (staggered) point list from bounding box.
# Make sure that the midpoint is one point in the grid.
x2 = num_x_steps // 2
y2 = num_y_steps // 2
x, y = np.meshgrid(
midpoint[0] + x_step * np.arange(-x2, x2 + 1),
midpoint[1] + y_step * np.arange(-y2, y2 + 1),
)
# Staggered, such that the midpoint is not moved.
# Unconditionally move to the right, then add more points to the left.
offset = (y2 + 1) % 2
x[offset::2] += h / 2
out = np.column_stack([x.reshape(-1), y.reshape(-1)])
# add points in the staggered lines to preserve symmetry
n = 2 * (-(-y2 // 2))
extra = np.empty((n, 2))
extra[:, 0] = midpoint[0] - x_step * x2 - h / 2
extra[:, 1] = midpoint[1] + y_step * np.arange(-y2 + offset, y2 + 1, 2)
out = np.concatenate([out, extra])
return out
# def get_max_step(mesh):
# # Some methods are stable (CPT), others can break down if the mesh isn't very
# # smooth. A break-down manifests, for example, in a step size that lets triangles
# # become fully flat or even "overshoot". After that, anything can happen. To prevent
# # this, restrict the maximum step size to half of the minimum the incircle radius of
# # all adjacent cells. This makes sure that triangles cannot "flip".
# #
# max_step = np.full(mesh.points.shape[0], np.inf)
# np.minimum.at(
# max_step, mesh.cells("points").reshape(-1), np.repeat(mesh.cell_inradius, 3),
# )
# max_step *= 0.5
# return max_step
def generate(
geo: Geometry,
target_edge_size: float | Callable,
# smoothing_method="distmesh",
tol: float = 1.0e-5,
random_seed: int = 0,
show: bool = False,
max_steps: int = 10000,
verbose: bool = False,
flip_tol: float = 0.0,
):
target_edge_size_function = (
target_edge_size
if callable(target_edge_size)
else lambda pts: np.full(pts.shape[1], target_edge_size)
)
# Find h0 from edge_size (function)
if callable(target_edge_size):
# Find h0 by sampling
h00 = (geo.bounding_box[1] - geo.bounding_box[0]) / 100
pts = create_staggered_grid(h00, geo.bounding_box)
sizes = target_edge_size_function(pts.T)
assert np.all(
sizes > 0.0
), "target_edge_size_function must be strictly positive."
h0 = np.min(sizes)
else:
h0 = target_edge_size
pts = create_staggered_grid(h0, geo.bounding_box)
eps = 1.0e-10
# remove points outside of the region
pts = pts[geo.dist(pts.T) < eps]
# evaluate the element size function, remove points according to it
alpha = 1.0 / target_edge_size_function(pts.T) ** 2
rng = np.random.default_rng(random_seed)
pts = pts[rng.random(pts.shape[0]) < alpha / np.max(alpha)]
num_feature_points = len(geo.feature_points)
if num_feature_points > 0:
# remove all points which are equal to a feature point
diff = np.array([[pt - fp for fp in geo.feature_points] for pt in pts])
dist = np.einsum("...k,...k->...", diff, diff)
ftol = h0 / 10
equals_feature_point = np.any(dist < ftol ** 2, axis=1)
pts = pts[~equals_feature_point]
# Add feature points
pts = np.concatenate([geo.feature_points, pts])
cells = _create_cells(pts, geo)
mesh = meshplex.MeshTri(pts, cells)
# When creating a mesh for the staggered grid, degenerate cells can very well occur
# at the boundary, where points sit in a straight line. Remove those cells.
mesh.remove_cells(mesh.q_radius_ratio < 1.0e-10)
# # move boundary points to the boundary exactly
# is_boundary_point = mesh.is_boundary_point.copy()
# mesh.points[is_boundary_point] = geo.boundary_step(
# mesh.points[is_boundary_point].T
# ).T
# print(sum(is_boundary_point))
# show_mesh(pts, cells, geo)
# exit(1)
# if smoothing_method == "odt":
# points, cells = optimesh.odt.fixed_point_uniform(
# mesh.points,
# mesh.cells("points"),
# max_num_steps=max_steps,
# verbose=verbose,
# boundary_step=geo.boundary_step,
# )
# else:
# assert smoothing_method == "distmesh"
dim = 2
mesh = distmesh_smoothing(
mesh,
geo,
num_feature_points,
target_edge_size_function,
max_steps,
tol,
verbose,
show,
delta_t=0.2,
f_scale=1 + 0.4 / 2 ** (dim - 1), # from the original article
flip_tol=flip_tol,
)
points = mesh.points
cells = mesh.cells("points")
return points, cells
def distmesh_smoothing(
mesh,
geo,
num_feature_points,
target_edge_size_function,
max_steps,
tol,
verbose,
show,
delta_t,
f_scale,
flip_tol=0.0,
):
mesh.create_edges()
k = 0
move2 = [0.0]
while True:
# print()
# print(f"step {k}")
if verbose:
print(f"step {k}")
if k > max_steps:
if verbose:
print(f"Exceeded max_steps ({max_steps}).")
break
k += 1
if show:
print(f"max move: {math.sqrt(max(move2)):.3e}")
show_mesh(mesh.points, mesh.cells("points"), geo)
edges = mesh.edges["points"]
edges_vec_normalized = mesh.points[edges[:, 1]] - mesh.points[edges[:, 0]]
edge_lengths = np.sqrt(
np.einsum("ij,ij->i", edges_vec_normalized, edges_vec_normalized)
)
edges_vec_normalized /= edge_lengths[..., None]
# Evaluate element sizes at edge midpoints
edge_midpoints = (mesh.points[edges[:, 1]] + mesh.points[edges[:, 0]]) / 2
p = target_edge_size_function(edge_midpoints.T)
target_lengths = (
f_scale * p * np.sqrt(np.dot(edge_lengths, edge_lengths) / np.dot(p, p))
)
force_abs = target_lengths - edge_lengths
# only consider repulsive forces
force_abs[force_abs < 0.0] = 0.0
# In , there's a suggestion for a
# better forcing function. The below doesn't seem to work too well though.
#
# Need to set delta_t to 1.0e-2 or smaller to accommodate for the missing factor
# `target_lengths`.
# force_type = "persson"
# relative_length = edge_lengths / target_lengths
# if force_type.lower() == "persson":
# force_abs = 1.0 - relative_length
# # only consider repulsive forces
# force_abs[relative_length > 1.0] = 0.0
# else:
# assert force_type.lower() == "bossens"
# force_abs = (1 - relative_length ** 4) * np.exp(-(relative_length ** 4))
# force vectors
force = edges_vec_normalized * force_abs[..., None]
n = mesh.points.shape[0]
force_per_point = npx.sum_at(-force, edges[:, 0], minlength=n) + npx.sum_at(
+force, edges[:, 1], minlength=n
)
update = delta_t * force_per_point
# # Limit the max step size to avoid overshoots
# TODO this doesn't work for distmesh smoothing. hm.
# mesh = meshplex.MeshTri(pts, cells)
# max_step = get_max_step(mesh)
# step_lengths = np.sqrt(np.einsum("ij,ij->i", update, update))
# idx = step_lengths > max_step
# update[idx] *= (max_step / step_lengths)[idx, None]
# # alpha = np.min(max_step / step_lengths)
# # update *= alpha
points_old = mesh.points.copy()
# update coordinates
points_new = mesh.points + update
# leave feature points untouched
points_new[:num_feature_points] = mesh.points[:num_feature_points]
mesh.points = points_new
# Some mesh boundary points may have been moved off of the domain boundary,
# either because they were pushed outside or because they just became boundary
# points by way of cell removal. Move them all (back) onto the domain boundary.
# is_outside = geo.dist(points_new.T) > 0.0
# idx = is_outside
# Alternative: Push all boundary points (the ones _inside_ the geometry as well)
# back to the boundary.
# idx = is_outside | is_boundary_point
_recell_and_boundary_step(mesh, geo, flip_tol)
diff = points_new - points_old
move2 = np.einsum("ij,ij->i", diff, diff)
if verbose:
print(f"max_move: {np.sqrt(np.max(move2)):.6e}")
if np.all(move2 < tol ** 2):
break
# The cell removal steps in _recell_and_boundary_step() might create points which
# aren't part of any cell (dangling points). Remove them now.
mesh.remove_dangling_points()
return mesh
dmsh-0.2.18/tests/ 0000775 0000000 0000000 00000000000 14134252050 0013673 5 ustar 00root root 0000000 0000000 dmsh-0.2.18/tests/compare-speed.py 0000664 0000000 0000000 00000006264 14134252050 0017001 0 ustar 00root root 0000000 0000000 import time
import matplotlib.pyplot as plt
import meshplex
import numpy as np
import pygmsh
import dmsh
def _compute_num_boundary_points(total_num_points):
# The number of boundary points, the total number of points, and the number of cells
# are connected by two equations (the second of which is approximate).
#
# Euler:
# 2 * num_points - num_boundary_edges - 2 = num_cells
#
# edge_length = 2 * np.pi / num_boundary_points
# tri_area = np.sqrt(3) / 4 * edge_length ** 2
# num_cells = int(np.pi / tri_area)
#
# num_boundary_points = num_boundary_edges
#
# Hence:
# 2 * num_points =
# num_boundary_points + 2 + np.pi / (np.sqrt(3) / 4 * (2 * np.pi / num_boundary_points) ** 2)
#
# We need to solve
#
# + num_boundary_points ** 2
# + (sqrt(3) * pi) * num_boundary_points
# + (2 - 2 * num_points) * (sqrt(3) * pi)
# = 0
#
# for the number of boundary points.
sqrt3_pi = np.sqrt(3) * np.pi
num_boundary_points = -sqrt3_pi / 2 + np.sqrt(
3 / 4 * np.pi ** 2 - (2 - 2 * total_num_points) * sqrt3_pi
)
return num_boundary_points
def dmsh_circle(num_points):
target_edge_length = 2 * np.pi / _compute_num_boundary_points(num_points)
geo = dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(geo, target_edge_length)
return X, cells
def gmsh_circle(num_points):
geom = pygmsh.built_in.Geometry()
target_edge_length = 2 * np.pi / _compute_num_boundary_points(num_points)
geom.add_circle(
[0.0, 0.0, 0.0], 1.0, lcar=target_edge_length, num_sections=4, compound=True
)
mesh = pygmsh.generate_mesh(geom, remove_lower_dim_cells=True, verbose=False)
return mesh.points[:, :2], mesh.cells[0].data
data = {
"dmsh": {"n": [], "time": [], "q": [], "version": dmsh.__version__},
"gmsh": {"n": [], "time": [], "q": [], "version": pygmsh.get_gmsh_version()},
}
for num_points in range(1000, 10000, 1000):
print(num_points)
# dmsh
t = time.time()
pts, cells = dmsh_circle(num_points)
t = time.time() - t
mesh = meshplex.MeshTri(pts, cells)
avg_q = np.sum(mesh.cell_quality) / len(mesh.cell_quality)
data["dmsh"]["n"].append(len(pts))
data["dmsh"]["time"].append(t)
data["dmsh"]["q"].append(avg_q)
# gmsh
t = time.time()
pts, cells = gmsh_circle(num_points)
t = time.time() - t
mesh = meshplex.MeshTri(pts, cells)
avg_q = np.sum(mesh.cell_quality) / len(mesh.cell_quality)
data["gmsh"]["n"].append(len(pts))
data["gmsh"]["time"].append(t)
data["gmsh"]["q"].append(avg_q)
# plot condition number
for key, value in data.items():
plt.plot(value["n"], value["time"], "-x", label=key + " " + value["version"])
plt.xlabel("num points")
plt.title("generation time [s]")
plt.grid()
plt.legend()
plt.show()
# plt.savefig("time.svg", transparent=True, bbox_inches="tight")
plt.close()
# plot CG iterations number
for key, value in data.items():
plt.plot(value["n"], value["q"], "-x", label=key + " " + value["version"])
plt.xlabel("num points")
plt.title("average cell quality")
plt.grid()
plt.legend()
plt.show()
# plt.savefig("average-cell-quality.svg", transparent=True, bbox_inches="tight")
plt.close()
dmsh-0.2.18/tests/generate-readme-plots.py 0000664 0000000 0000000 00000006460 14134252050 0020437 0 ustar 00root root 0000000 0000000 import meshio
import numpy as np
import optimesh
import dmsh
def save(X, cells, filename):
meshio.Mesh(X, {"triangle": cells}).write(
filename, image_width=100, stroke_width=0.5
)
geo = dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.1)
# optionally optimize the mesh
X, cells = optimesh.optimize_points_cells(X, cells, "CVT (full)", 1.0e-10, 100)
save(X, cells, "circle.svg")
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0)
X, cells = dmsh.generate(geo, 0.1)
save(X, cells, "rectangle.svg")
geo = dmsh.Polygon(
[
[0.0, 0.0],
[1.1, 0.0],
[1.2, 0.5],
[0.7, 0.6],
[2.0, 1.0],
[1.0, 2.0],
[0.5, 1.5],
]
)
X, cells = dmsh.generate(geo, 0.1)
save(X, cells, "polygon.svg")
geo = dmsh.Difference(dmsh.Circle([-0.5, 0.0], 1.0), dmsh.Circle([+0.5, 0.0], 1.0))
X, cells = dmsh.generate(geo, 0.1)
save(X, cells, "moon.svg")
geo = dmsh.Difference(
dmsh.Circle([0.0, 0.0], 1.0),
dmsh.Polygon([[0.0, 0.0], [1.5, 0.4], [1.5, -0.4]]),
)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
save(X, cells, "pacman.svg")
r = dmsh.Rectangle(-1.0, +1.0, -1.0, +1.0)
c = dmsh.Circle([0.0, 0.0], 0.3)
geo = dmsh.Difference(r, c)
X, cells = dmsh.generate(geo, lambda pts: np.abs(c.dist(pts)) / 5 + 0.05, tol=1.0e-10)
save(X, cells, "rectangle-hole-refinement.svg")
geo = dmsh.Union([dmsh.Circle([-0.5, 0.0], 1.0), dmsh.Circle([+0.5, 0.0], 1.0)])
X, cells = dmsh.generate(geo, 0.15)
save(X, cells, "union-circles.svg")
geo = dmsh.Union(
[dmsh.Rectangle(-1.0, +0.5, -1.0, +0.5), dmsh.Rectangle(-0.5, +1.0, -0.5, +1.0)]
)
X, cells = dmsh.generate(geo, 0.15)
save(X, cells, "union-rectangles.svg")
angles = np.pi * np.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0])
geo = dmsh.Union(
[
dmsh.Circle([np.cos(angles[0]), np.sin(angles[0])], 1.0),
dmsh.Circle([np.cos(angles[1]), np.sin(angles[1])], 1.0),
dmsh.Circle([np.cos(angles[2]), np.sin(angles[2])], 1.0),
]
)
X, cells = dmsh.generate(geo, 0.15)
save(X, cells, "union-three-circles.svg")
geo = dmsh.Intersection([dmsh.Circle([0.0, -0.5], 1.0), dmsh.Circle([0.0, +0.5], 1.0)])
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
save(X, cells, "intersection-circles.svg")
angles = np.pi * np.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0])
geo = dmsh.Intersection(
[
dmsh.Circle([np.cos(angles[0]), np.sin(angles[0])], 1.5),
dmsh.Circle([np.cos(angles[1]), np.sin(angles[1])], 1.5),
dmsh.Circle([np.cos(angles[2]), np.sin(angles[2])], 1.5),
]
)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
save(X, cells, "intersection-three-circles.svg")
geo = dmsh.Intersection(
[
dmsh.HalfSpace(np.sqrt(0.5) * np.array([1.0, 1.0]), 0.0),
dmsh.Circle([0.0, 0.0], 1.0),
]
)
X, cells = dmsh.generate(geo, 0.1)
save(X, cells, "intersection-circle-halfspace.svg")
geo = dmsh.Rotation(dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0), 0.1 * np.pi)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-10)
save(X, cells, "rotation.svg")
geo = dmsh.Scaling(dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0), 2.0)
X, cells = dmsh.generate(geo, 0.1, tol=1.0e-5)
save(X, cells, "scaling.svg")
geo = dmsh.Rectangle(0.0, 1.0, 0.0, 1.0)
p1 = dmsh.Path([[0.4, 0.6], [0.6, 0.4]])
X, cells = dmsh.generate(geo, edge_size=lambda x: 0.03 + 0.1 * p1.dist(x), tol=1.0e-10)
save(X, cells, "local-refinement.svg")
dmsh-0.2.18/tests/helpers.py 0000664 0000000 0000000 00000001634 14134252050 0015713 0 ustar 00root root 0000000 0000000 import numpy as np
def assert_equality(a, b, tol):
a = np.asarray(a)
b = np.asarray(b)
fmt_a = ", ".join(["{:.16e}"] * len(a))
fmt_b = ", ".join(["{:.16e}"] * len(b))
assert np.all(np.abs(a - b) < tol), f"[{fmt_a}]\n[{fmt_b}]".format(*a, *b)
def assert_norm_equality(X, ref_norm, tol):
ref_norm = np.asarray(ref_norm)
vals = np.array(
[
np.linalg.norm(X, ord=1),
np.linalg.norm(X, ord=2),
np.linalg.norm(X, ord=np.inf),
]
)
assert np.all(
np.abs(vals - ref_norm) < tol * ref_norm
), "Expected: [{:.16e}, {:.16e}, {:.16e}]\nComputed: [{:.16e}, {:.16e}, {:.16e}]".format(
*ref_norm, *vals
)
def save(filename, X, cells):
import meshplex
mesh = meshplex.MeshTri(X, cells)
mesh.save(
filename,
show_coedges=False,
show_axes=False,
nondelaunay_edge_color="k",
)
dmsh-0.2.18/tests/justfile 0000664 0000000 0000000 00000000314 14134252050 0015441 0 ustar 00root root 0000000 0000000 default:
@echo `just png`?
png:
for file in test_*.py; do \
python3 $$file; \
done
for file in *.png; do convert $$file -trim -resize x200 $$file; done
for file in *.png; do optipng $$file; done
dmsh-0.2.18/tests/logo.py 0000664 0000000 0000000 00000000205 14134252050 0015202 0 ustar 00root root 0000000 0000000 import meshio
import meshzoo
points, cells = meshzoo.triangle(2)
meshio.write_points_cells("logo.svg", points, {"triangle": cells})
dmsh-0.2.18/tests/test_circle.py 0000664 0000000 0000000 00000002724 14134252050 0016552 0 ustar 00root root 0000000 0000000 import meshplex
import numpy as np
import pytest
from helpers import assert_norm_equality
import dmsh
@pytest.mark.parametrize(
"radius,ref_norms",
[
(0.1, [3.2592107070061820e02, 1.4190745248684369e01, 1.0000000000000000e00]),
(0.4, [18.899253166, 3.70111746, 1.0]),
],
)
def test_circle(radius, ref_norms, show=False):
geo = dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(geo, radius, show=show, max_steps=100)
meshplex.MeshTri(X, cells).show()
# make sure the origin is part of the mesh
assert np.sum(np.einsum("ij,ij->i", X, X) < 1.0e-6) == 1
assert_norm_equality(X.flatten(), ref_norms, 1.0e-5)
return X, cells
# with these target edge lengths, dmsh once produced weird results near the boundary
@pytest.mark.parametrize(
"target_edge_length", [0.07273, 0.07272, 0.07271, 0.0711, 0.03591]
)
def test_degenerate_circle(target_edge_length):
geo = dmsh.Circle([0.0, 0.0], 1.0)
X, cells = dmsh.generate(
geo, target_edge_length, show=False, max_steps=200, verbose=True
)
mesh = meshplex.MeshTri(X, cells)
min_q = np.min(mesh.q_radius_ratio)
assert min_q > 0.5, f"min cell quality: {min_q:.3f}"
def test_boundary_step():
geo = dmsh.Circle([0.1, 0.2], 1.0)
np.random.seed(0)
pts = np.random.uniform(-1.0, 1.0, (2, 100))
pts = geo.boundary_step(pts)
tol = 1.0e-12
assert np.all(np.abs(geo.dist(pts)) < tol)
if __name__ == "__main__":
test_boundary_step()
dmsh-0.2.18/tests/test_closed_path.py 0000664 0000000 0000000 00000012221 14134252050 0017567 0 ustar 00root root 0000000 0000000 import numpy as np
from dmsh.geometry import pypathlib
def test_show():
path = pypathlib.ClosedPath([[0.0, 0.0], [1.0, 0.0], [1.1, 1.1], [0.1, 1.0]])
path.show()
def test_convex():
path = pypathlib.ClosedPath([[0.0, 0.0], [1.0, 0.0], [1.1, 1.1], [0.1, 1.0]])
ref = 1.045
assert abs(path.area - ref) < 1.0e-12 * ref
assert path.positive_orientation
assert all(path.is_convex_node)
def test_orientation():
path = pypathlib.ClosedPath([[0.1, 1.0], [1.1, 1.1], [1.0, 0.0], [0.0, 0.0]])
ref = 1.045
assert abs(path.area - ref) < 1.0e-12 * ref
assert not path.positive_orientation
assert all(path.is_convex_node)
def test_concave():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.1, 1.1], [0.1, 1.0]]
)
ref = 0.965
assert abs(path.area - ref) < 1.0e-12 * ref
assert path.positive_orientation
assert np.array_equal(path.is_convex_node, [True, True, False, True, True])
def test_concave_counterclock():
path = pypathlib.ClosedPath(
[[0.1, 1.0], [1.1, 1.1], [0.9, 0.5], [1.0, 0.0], [0.0, 0.0]]
)
ref = 0.965
assert abs(path.area - ref) < 1.0e-12 * ref
assert not path.positive_orientation
assert np.array_equal(path.is_convex_node, [True, True, False, True, True])
def test_squared_distance():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]]
)
dist = path.squared_distance(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
ref = np.array([0.01, 0.16, 1.0 / 104.0, 0.01, 0.02, 0.0])
assert np.all(np.abs(dist - ref) < 1.0e-12)
def test_distance():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]]
)
dist = path.distance(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
ref = np.array([0.1, 0.4, np.sqrt(1.0 / 104.0), 0.1, np.sqrt(2) / 10, 0.0])
assert np.all(np.abs(dist - ref) < 1.0e-12)
def test_signed_distance():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]]
)
dist = path.signed_distance(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
print(dist)
ref = np.array([-0.1, -0.4, np.sqrt(1.0 / 104.0), 0.1, np.sqrt(2) / 10, 0.0])
assert np.all(np.abs(dist - ref) < 1.0e-12)
def test_inside():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]]
)
contains_points = path.contains_points(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
assert np.array_equal(contains_points, [True, True, False, False, False, True])
def test_closest_points():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]]
)
closest_points = path.closest_points(
[
[0.2, 0.1],
[0.5, 0.5],
[1.0, 0.5 + 1.0e-12],
[0.0, 1.1],
[-0.1, 1.1],
[1.0, 1.0],
]
)
ref = np.array(
[
[0.2, 0.0],
[0.9, 0.5],
[9.0384615384615385e-01, 5.1923076923076927e-01],
[0.0, 1.0],
[0.0, 1.0],
[1.0, 1.0],
]
)
assert np.all(np.abs(closest_points - ref) < 1.0e-12)
def test_signed_squared_distance():
path = pypathlib.ClosedPath(
[[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]]
)
dist = path.signed_squared_distance(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
ref = np.array([-0.01, -0.16, 1.0 / 104.0, 0.01, 0.02, 0.0])
assert np.all(np.abs(dist - ref) < 1.0e-12)
def test_sharp_angle():
path = pypathlib.ClosedPath(
[
[0.0, 0.0],
[1.0, 0.0],
[1.0, 0.45],
[0.6, 0.5],
[1.0, 0.55],
[1.0, 1.0],
[0.0, 1.0],
]
)
contains_points = path.contains_points([[0.5, 0.4], [0.5, 0.6]])
assert np.all(contains_points)
dist = path.signed_squared_distance([[0.5, 0.4], [0.5, 0.6]])
ref = np.array([-0.02, -0.02])
assert np.all(np.abs(dist - ref) < 1.0e-12)
def test_project_distance():
path = pypathlib.ClosedPath(
[
[0.0, 0.0],
[1.5, 0.4],
[1.0, 1.0],
]
)
closest_points = path.closest_points(
[
[0.5, 0.1],
[0.5, 0.2],
[0.5, 0.3],
[0.5, 0.4],
[0.5, 0.5],
]
)
# closest_points = np.array([4.9170124481327798e-01, 1.3112033195020747e-01])
# closest_points = np.array([4.9170124481327804e-01, 1.3112033195020747e-01])
# the projected point should be _on_ the polygon
dist = path.distance(closest_points)
assert np.all(dist < 1.0e-12)
# def test_two_points():
# path = pypathlib.ClosedPath([[-0.5, 1.0], [+0.5, 1.0]])
# contains_points = path.contains_points([[0.0, 0.0], [0.0, 2.0]])
# assert np.array_equal(contains_points, [False, False])
if __name__ == "__main__":
test_closest_points()
dmsh-0.2.18/tests/test_difference.py 0000664 0000000 0000000 00000004144 14134252050 0017401 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality
import dmsh
def test_difference(show=False):
geo = dmsh.Circle([-0.5, 0.0], 1.0) - dmsh.Circle([+0.5, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.1, show=show, max_steps=100)
geo.plot()
ref_norms = [2.9409044729708609e02, 1.5855488859739937e01, 1.5000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-6)
return X, cells
def test_boundary_step():
geo = dmsh.Difference(dmsh.Circle([-0.5, 0.0], 1.0), dmsh.Circle([+0.5, 0.0], 1.0))
pts = np.array(
[
[-2.1, 0.0],
[0.1, 0.0],
[-1.4, 0.0],
[-0.6, 0.0],
]
)
pts = geo.boundary_step(pts.T).T
ref = np.array([[-1.5, 0.0], [-0.5, 0.0], [-1.5, 0.0], [-0.5, 0.0]])
assert np.all(np.abs(pts - ref) < 1.0e-10)
def test_boundary_step2():
geo = dmsh.Difference(dmsh.Circle([-0.5, 0.0], 1.0), dmsh.Circle([+0.5, 0.0], 1.0))
np.random.seed(0)
pts = np.random.uniform(-2.0, 2.0, (2, 100))
pts = geo.boundary_step(pts)
# geo.plot()
# import matplotlib.pyplot as plt
# plt.plot(pts[0], pts[1], "xk")
# plt.show()
assert np.all(np.abs(geo.dist(pts)) < 1.0e-12)
def test_boundary_step_pacman():
geo = dmsh.Difference(
dmsh.Circle([0.0, 0.0], 1.0),
dmsh.Polygon([[0.0, 0.0], [1.5, 0.4], [1.5, -0.4]]),
)
# np.random.seed(0)
# pts = np.random.uniform(-2.0, 2.0, (2, 100))
# pts = np.array([[-2.0, 0.0]])
# pts = np.array([[-0.1, 0.0]])
# pts = np.array([[0.0, 2.0]])
# pts = np.array([[0.0, 0.9]])
# pts = np.array([[2.0, 0.1]])
# pts = np.array([[0.1, 0.1]])
# pts = np.array([[0.7, 0.1]])
pts = np.array([[0.5, 0.1]])
pts = pts.T
print(pts.T.shape)
pts = geo.boundary_step(pts)
geo.plot()
import matplotlib.pyplot as plt
plt.plot(pts[0], pts[1], "xk")
plt.show()
# assert np.all(np.abs(geo.dist(pts)) < 1.0e-12)
if __name__ == "__main__":
# from helpers import save
X, cells = test_difference(show=True)
# save("difference.png", X, cells)
# test_boundary_step_pacman()
dmsh-0.2.18/tests/test_ellipse.py 0000664 0000000 0000000 00000000765 14134252050 0016751 0 ustar 00root root 0000000 0000000 import pytest
from helpers import assert_norm_equality, save
import dmsh
@pytest.mark.skip
def test_ellipse(show=False):
geo = dmsh.Ellipse([0.0, 0.0], 2.0, 1.0)
X, cells = dmsh.generate(geo, 0.2, show=show)
geo.plot()
ref_norms = [2.5108941453435716e02, 1.5652963447587933e01, 1.9890264390440919e00]
assert_norm_equality(X.flatten(), ref_norms, 2.0e-2)
return X, cells
if __name__ == "__main__":
X, cells = test_ellipse(show=True)
save("ellipse.png", X, cells)
dmsh-0.2.18/tests/test_halfspace.py 0000664 0000000 0000000 00000001143 14134252050 0017231 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality, save
import dmsh
def test_halfspace(show=False):
geo = dmsh.Intersection(
[
dmsh.HalfSpace(np.sqrt(0.5) * np.array([1.0, 1.0])),
dmsh.Circle([0.0, 0.0], 1.0),
]
)
X, cells = dmsh.generate(geo, 0.1, show=show, max_steps=100)
ref_norms = [1.6399670188761661e02, 1.0011048291798387e01, 9.9959986881486440e-01]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-6)
return X, cells
if __name__ == "__main__":
X, cells = test_halfspace(show=True)
save("halfspace.png", X, cells)
dmsh-0.2.18/tests/test_intersection.py 0000664 0000000 0000000 00000003753 14134252050 0020022 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality, save
import dmsh
def test_intersection(show=False):
geo = dmsh.Circle([0.0, -0.5], 1.0) & dmsh.Circle([0.0, +0.5], 1.0)
X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10, max_steps=100)
geo.plot()
ref_norms = [8.6491736892894920e01, 6.1568624411912278e00, 8.6602540378466342e-01]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
def test_intersection_circles(show=False):
angles = np.pi * np.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0])
geo = dmsh.Intersection(
[
dmsh.Circle([np.cos(angles[0]), np.sin(angles[0])], 1.5),
dmsh.Circle([np.cos(angles[1]), np.sin(angles[1])], 1.5),
dmsh.Circle([np.cos(angles[2]), np.sin(angles[2])], 1.5),
]
)
X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10, max_steps=100)
ref_norms = [6.7661318585210836e01, 5.0568863746561723e00, 7.2474487138537913e-01]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
def test_boundary_step():
geo = dmsh.Circle([0.0, -0.5], 1.0) & dmsh.Circle([0.0, +0.5], 1.0)
pts = np.array([[0.0, -5.0], [0.0, 4.1]])
pts = geo.boundary_step(pts.T).T
ref = np.array([[0.0, -0.5], [0.0, 0.5]])
assert np.all(np.abs(pts - ref) < 1.0e-10)
pts = np.array([[0.0, -0.1], [0.0, 0.1]])
pts = geo.boundary_step(pts.T).T
ref = np.array([[0.0, -0.5], [0.0, 0.5]])
assert np.all(np.abs(pts - ref) < 1.0e-10)
def test_boundary_step2():
geo = dmsh.Circle([0.0, -0.5], 1.0) & dmsh.Circle([0.0, +0.5], 1.0)
np.random.seed(0)
pts = np.random.uniform(-1.0, 1.0, (2, 100))
pts = geo.boundary_step(pts)
# geo.plot()
# import matplotlib.pyplot as plt
# plt.plot(pts[0], pts[1], "xk")
# plt.show()
assert np.all(np.abs(geo.dist(pts)) < 1.0e-7)
if __name__ == "__main__":
X, cells = test_intersection(show=True)
save("intersection.png", X, cells)
# test_boundary_step2()
dmsh-0.2.18/tests/test_large.py 0000664 0000000 0000000 00000001017 14134252050 0016375 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality
import dmsh
def test_large(show=False):
# https://github.com/nschloe/dmsh/issues/11
r = dmsh.Rectangle(-10.0, +20.0, -10.0, +20.0)
c = dmsh.Circle([0.0, 0.0], 3)
geo = dmsh.Difference(r, c)
X, cells = dmsh.generate(geo, 2.0, tol=1.0e-5, max_steps=100, show=show)
ref_norms = [4.6292581642363657e03, 2.4187329297982635e02, 2.0000000000000000e01]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-4)
if __name__ == "__main__":
test_large(show=True)
dmsh-0.2.18/tests/test_pacman.py 0000664 0000000 0000000 00000001121 14134252050 0016536 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality
import dmsh
def test_pacman(show=False):
geo = dmsh.Difference(
dmsh.Circle([0.0, 0.0], 1.0),
dmsh.Polygon([[0.0, 0.0], [1.5, 0.4], [1.5, -0.4]]),
)
X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-5, max_steps=100)
ref_norms = [3.0173012692535394e02, 1.3565685453257570e01, 9.9999999999884770e-01]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
if __name__ == "__main__":
X, cells = test_pacman(show=True)
# from helpers import save
# save("pacman.png", X, cells)
dmsh-0.2.18/tests/test_path.py 0000664 0000000 0000000 00000001412 14134252050 0016236 0 ustar 00root root 0000000 0000000 import numpy as np
from dmsh.geometry import pypathlib
def test_squared_distance():
path = pypathlib.Path([[0.0, 0.0], [1.0, 0.0], [0.9, 0.5], [1.0, 1.0], [0.0, 1.0]])
dist = path.squared_distance(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
ref = np.array([0.01, 0.16, 1.0 / 104.0, 0.01, 0.02, 0.0])
assert np.all(np.abs(dist - ref) < 1.0e-12)
return
def test_one_point():
path = pypathlib.Path([[0.0, 0.0]])
dist = path.squared_distance(
[[0.2, 0.1], [0.5, 0.5], [1.0, 0.5], [0.0, 1.1], [-0.1, 1.1], [1.0, 1.0]]
)
ref = np.array([0.05, 0.5, 1.25, 1.21, 1.22, 2.0])
assert np.all(np.abs(dist - ref) < 1.0e-12)
return
if __name__ == "__main__":
test_squared_distance()
dmsh-0.2.18/tests/test_polygon.py 0000664 0000000 0000000 00000002405 14134252050 0016774 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality
import dmsh
def test(show=False):
geo = dmsh.Polygon(
[
[0.0, 0.0],
[1.1, 0.0],
[1.2, 0.5],
[0.7, 0.6],
[2.0, 1.0],
[1.0, 2.0],
[0.5, 1.5],
]
)
# geo.show()
X, cells = dmsh.generate(geo, 0.1, show=show, max_steps=100)
ref_norms = [4.1426056822140765e02, 2.1830112296142847e01, 2.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-5)
return X, cells
def test_boundary_step2(plot=False):
geo = dmsh.Polygon(
[
[0.0, 0.0],
[1.1, 0.0],
[1.2, 0.5],
[0.7, 0.6],
[2.0, 1.0],
[1.0, 2.0],
[0.5, 1.5],
]
)
np.random.seed(0)
pts = np.random.uniform(-2.0, 2.0, (2, 100))
pts = geo.boundary_step(pts)
if plot:
geo.plot()
import matplotlib.pyplot as plt
plt.plot(pts[0], pts[1], "xk")
plt.show()
dist = geo.dist(pts)
assert np.all(np.abs(dist) < 1.0e-12)
if __name__ == "__main__":
# from helpers import save
# X, cells = test(show=False)
# save("polygon.svg", X, cells)
test_boundary_step2(plot=True)
dmsh-0.2.18/tests/test_quarter_annulus.py 0000664 0000000 0000000 00000001461 14134252050 0020536 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality
import dmsh
def test_quarter_annulus():
h = 0.05
disk0 = dmsh.Circle([0.0, 0.0], 0.25)
disk1 = dmsh.Circle([0.0, 0.0], 1.0)
diff0 = dmsh.Difference(disk1, disk0)
rect = dmsh.Rectangle(0.0, 1.0, 0.0, 1.0)
quarter = dmsh.Intersection([diff0, rect])
points, cells = dmsh.generate(
quarter,
lambda x: h + 0.1 * np.abs(disk0.dist(x)),
tol=1.0e-10,
max_steps=100,
)
ref_norms = [7.7455372708027483e01, 6.5770003813066431e00, 1.0000000000000000e00]
assert_norm_equality(points.flatten(), ref_norms, 1.0e-10)
return points, cells
if __name__ == "__main__":
import meshio
points, cells = test_quarter_annulus()
meshio.Mesh(points, {"triangle": cells}).write("out.vtk")
dmsh-0.2.18/tests/test_rectangle.py 0000664 0000000 0000000 00000004544 14134252050 0017257 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality, save
import dmsh
def test_boundary_step():
geo = dmsh.Rectangle(-2.0, +2.0, -1.0, +1.0)
# Check boundary steps
out = geo.boundary_step([0.1, 0.0])
assert np.all(np.abs(out - [2.0, 0.0]) < 1.0e-10)
out = geo.boundary_step([0.0, 0.1])
assert np.all(np.abs(out - [0.0, 1.0]) < 1.0e-10)
out = geo.boundary_step([-0.1, 0.0])
assert np.all(np.abs(out - [-2.0, 0.0]) < 1.0e-10)
out = geo.boundary_step([0.0, -0.1])
assert np.all(np.abs(out - [0.0, -1.0]) < 1.0e-10)
out = geo.boundary_step([2.1, 0.037])
assert np.all(np.abs(out - [2.0, 0.037]) < 1.0e-10)
out = geo.boundary_step([0.037, 1.1])
assert np.all(np.abs(out - [0.037, 1.0]) < 1.0e-10)
out = geo.boundary_step([-2.1, 0.037])
assert np.all(np.abs(out - [-2.0, 0.037]) < 1.0e-10)
out = geo.boundary_step([0.037, -1.1])
assert np.all(np.abs(out - [0.037, -1.0]) < 1.0e-10)
out = geo.boundary_step([2.1, 1.1])
assert np.all(np.abs(out - [2.0, 1.0]) < 1.0e-10)
out = geo.boundary_step([-2.1, 1.1])
assert np.all(np.abs(out - [-2.0, 1.0]) < 1.0e-10)
out = geo.boundary_step([2.1, -1.1])
assert np.all(np.abs(out - [2.0, -1.0]) < 1.0e-10)
out = geo.boundary_step([-2.1, -1.1])
assert np.all(np.abs(out - [-2.0, -1.0]) < 1.0e-10)
def test_rectangle(show=False):
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0)
X, cells = dmsh.generate(geo, 0.1, show=show, max_steps=100)
ref_norms = [9.7172325705673779e02, 3.1615286239175994e01, 2.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
def test_duplicate_points(show=False):
# https://github.com/nschloe/dmsh/issues/66
# geo = dmsh.Rectangle(0.0, 1.8, 0.0, 0.41)
# points, cells = dmsh.generate(geo, 0.2, tol=2e-2, show=show)
# is_part_of_cell = np.zeros(len(points), dtype=bool)
# is_part_of_cell[cells.flat] = True
# assert np.all(is_part_of_cell)
geo = dmsh.Rectangle(0.0, 1.4, 0.0, 0.41)
points, cells = dmsh.generate(geo, 0.025, tol=1e-5, show=show, max_steps=1)
is_part_of_cell = np.zeros(len(points), dtype=bool)
is_part_of_cell[cells.flat] = True
assert np.all(is_part_of_cell)
if __name__ == "__main__":
# test_duplicate_points(show=True)
X, cells = test_rectangle(show=False)
save("rectangle.png", X, cells)
dmsh-0.2.18/tests/test_rectangle_hole.py 0000664 0000000 0000000 00000001625 14134252050 0020263 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality
import dmsh
def test_rectangle_hole(show=False):
geo = dmsh.Difference(
dmsh.Rectangle(60, 330, 380, 650), dmsh.Rectangle(143, 245, 440, 543)
)
X, cells = dmsh.generate(
geo, 20, tol=1.0e-5, show=show, flip_tol=1.0e-10, max_steps=100
)
ref_norms = [1.2931633675576400e05, 7.6377328985582844e03, 6.5000000000000000e02]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
def test_rectangle_hole2(show=False):
geo = dmsh.Difference(
dmsh.Rectangle(0.0, 5.0, 0.0, 5.0),
dmsh.Polygon([[1, 1], [4, 1], [4, 4], [1, 4]]),
)
X, cells = dmsh.generate(geo, 1.0, show=show, tol=1.0e-3, max_steps=100)
ref_norms = [1.3990406144096474e02, 2.2917592510234346e01, 5.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-2)
if __name__ == "__main__":
test_rectangle_hole2(show=True)
dmsh-0.2.18/tests/test_refinement_point_line.py 0000664 0000000 0000000 00000001160 14134252050 0021656 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality, save
import dmsh
def test(show=False):
geo = dmsh.Rectangle(0.0, 1.0, 0.0, 1.0)
# p0 = dmsh.Path([[0.0, 0.0]])
p1 = dmsh.Path([[0.4, 0.6], [0.6, 0.4]])
def edge_size(x):
return 0.03 + 0.1 * p1.dist(x)
X, cells = dmsh.generate(geo, edge_size, show=show, tol=1.0e-10, max_steps=100)
ref_norms = [3.7918105331047593e02, 1.5473837427489348e01, 1.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-3)
return X, cells
if __name__ == "__main__":
X, cells = test(show=False)
save("refinement_line.png", X, cells)
dmsh-0.2.18/tests/test_rotation.py 0000664 0000000 0000000 00000001007 14134252050 0017141 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality, save
import dmsh
def test(show=False):
geo = dmsh.Rotation(dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0), 0.1 * np.pi)
X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-10, max_steps=100)
ref_norms = [9.4730152857365385e02, 3.1160562530932285e01, 2.2111300269652543e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
if __name__ == "__main__":
X, cells = test(show=False)
save("rotation.png", X, cells)
dmsh-0.2.18/tests/test_scaling.py 0000664 0000000 0000000 00000001052 14134252050 0016722 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality, save
import dmsh
def test(show=False):
# should both work
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0) * 2.0
geo = 2.0 * dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0)
X, cells = dmsh.generate(geo, 0.1, show=show, tol=1.0e-5, max_steps=100)
ref_norms = [7.6829959173892494e03, 1.2466061090733828e02, 4.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-7)
return X, cells
if __name__ == "__main__":
X, cells = test(show=False)
save("scaling.png", X, cells)
dmsh-0.2.18/tests/test_show_level_set.py 0000664 0000000 0000000 00000000265 14134252050 0020331 0 ustar 00root root 0000000 0000000 import dmsh
def test_show():
# geo = dmsh.Circle([0.0, 0.0], 1.0)
geo = dmsh.Rectangle(-1.0, +1.0, -1.0, +1.0)
geo.show()
if __name__ == "__main__":
test_show()
dmsh-0.2.18/tests/test_speed.py 0000664 0000000 0000000 00000002047 14134252050 0016407 0 ustar 00root root 0000000 0000000 import numpy as np
import perfplot
import pytest
from matplotlib import path
from dmsh.geometry import pypathlib
@pytest.mark.skip(reason="fails on gh-actions for some reason")
def test_speed(n=3):
path_pts = [[0, 0], [0, 1], [1, 1], [1, 0]]
path0 = path.Path(path_pts)
path1 = pypathlib.ClosedPath(path_pts)
def _mpl_path(pts):
return path0.contains_points(pts)
def _pypathlib_contains_points(pts):
return path1.contains_points(pts)
np.random.seed(0)
perfplot.show(
setup=lambda n: np.random.rand(n, 2),
kernels=[_mpl_path, _pypathlib_contains_points],
n_range=[2 ** k for k in range(n)],
labels=["matplotlib.path.contains_points", "pypathlib.contains_points"],
logx=True,
logy=True,
xlabel="num points",
)
def benchmark():
path_pts = [[0, 0], [0, 1], [1, 1], [1, 0]]
path1 = pypathlib.ClosedPath(path_pts)
pts = np.random.rand(5000000, 2)
path1.contains_points(pts)
if __name__ == "__main__":
# test_speed(20)
benchmark()
dmsh-0.2.18/tests/test_square_hole_refined.py 0000664 0000000 0000000 00000001216 14134252050 0021307 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_norm_equality, save
import dmsh
def test(show=False):
r = dmsh.Rectangle(-1.0, +1.0, -1.0, +1.0)
c = dmsh.Circle([0.0, 0.0], 0.3)
geo = dmsh.Difference(r, c)
X, cells = dmsh.generate(
geo,
lambda pts: np.abs(c.dist(pts)) / 5 + 0.05,
show=show,
tol=1.0e-10,
max_steps=100,
)
ref_norms = [2.3686099753024831e02, 1.1750558136202198e01, 1.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-2)
return X, cells
if __name__ == "__main__":
X, cells = test(show=True)
save("square_hole_refined.png", X, cells)
dmsh-0.2.18/tests/test_stretch.py 0000664 0000000 0000000 00000000751 14134252050 0016763 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality, save
import dmsh
def test(show=False):
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0).stretch([1.0, 1.0])
X, cells = dmsh.generate(geo, 0.3, show=show, tol=1.0e-3, max_steps=100)
ref_norms = [1.9006907971528796e02, 1.5666202908904914e01, 2.6213203435596428e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-2)
return X, cells
if __name__ == "__main__":
X, cells = test(show=False)
save("stretch.png", X, cells)
dmsh-0.2.18/tests/test_translation.py 0000664 0000000 0000000 00000000741 14134252050 0017644 0 ustar 00root root 0000000 0000000 from helpers import assert_norm_equality
import dmsh
def test(show=False):
# should both work
geo = [1.0, 1.0] + dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0)
geo = dmsh.Rectangle(-1.0, +2.0, -1.0, +1.0) + [1.0, 1.0]
X, _ = dmsh.generate(geo, 0.1, show=show, max_steps=100)
ref_norms = [1.7524999999999998e03, 5.5612899955332637e01, 3.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-7)
if __name__ == "__main__":
test(show=False)
dmsh-0.2.18/tests/test_union.py 0000664 0000000 0000000 00000005304 14134252050 0016436 0 ustar 00root root 0000000 0000000 import numpy as np
from helpers import assert_equality, assert_norm_equality
import dmsh
def test_union_circles(show=False):
geo = dmsh.Circle([-0.5, 0.0], 1.0) + dmsh.Circle([+0.5, 0.0], 1.0)
X, cells = dmsh.generate(geo, 0.15, show=show, tol=1.0e-5, max_steps=100)
geo.plot()
ref_norms = [3.0080546580519666e02, 1.5775854476745508e01, 1.5000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
def test_union_rectangles(show=False):
geo = dmsh.Rectangle(-1.0, +0.5, -1.0, +0.5) | dmsh.Rectangle(
-0.5, +1.0, -0.5, +1.0
)
X, cells = dmsh.generate(geo, 0.15, show=show, tol=1.0e-5, max_steps=100)
ref_norms = [1.8417796811774514e02, 1.1277323166424049e01, 1.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
def test_union_three_circles(show=False):
angles = np.pi * np.array([3.0 / 6.0, 7.0 / 6.0, 11.0 / 6.0])
geo = dmsh.Union(
[
dmsh.Circle([np.cos(angles[0]), np.sin(angles[0])], 1.0),
dmsh.Circle([np.cos(angles[1]), np.sin(angles[1])], 1.0),
dmsh.Circle([np.cos(angles[2]), np.sin(angles[2])], 1.0),
]
)
X, cells = dmsh.generate(geo, 0.2, show=show, tol=1.0e-5, max_steps=100)
ref_norms = [4.0359760255235619e02, 2.1162741423521961e01, 2.0000000000000000e00]
assert_norm_equality(X.flatten(), ref_norms, 1.0e-10)
return X, cells
def test_boundary_step():
geo = dmsh.Union([dmsh.Circle([-0.5, 0.0], 1.0), dmsh.Circle([+0.5, 0.0], 1.0)])
a = geo.boundary_step([-0.5, 0.9])
assert np.array_equal(a, [-0.5, 1.0])
a = geo.boundary_step([-0.5, 0.6])
assert np.array_equal(a, [-0.5, 1.0])
a = geo.boundary_step([0.05, 0.05])
assert_equality(a, [-4.4469961425821203e-01, 9.9846976285554556e-01], 1.0e-10)
pts = np.array([[-5.0, 0.0], [4.1, 0.0]])
pts = geo.boundary_step(pts.T).T
ref = np.array([[-1.5, 0.0], [1.5, 0.0]])
assert np.all(np.abs(pts - ref) < 1.0e-10)
pts = np.array([[-0.9, 0.0], [1.1, 0.0]])
pts = geo.boundary_step(pts.T).T
ref = np.array([[-1.5, 0.0], [1.5, 0.0]])
assert np.all(np.abs(pts - ref) < 1.0e-10)
def test_boundary_step2():
geo = dmsh.Union([dmsh.Circle([-0.5, 0.0], 1.0), dmsh.Circle([+0.5, 0.0], 1.0)])
np.random.seed(0)
pts = np.random.uniform(-2.0, 2.0, (2, 100))
pts = geo.boundary_step(pts)
# geo.plot()
# import matplotlib.pyplot as plt
# plt.plot(pts[0], pts[1], "xk")
# plt.show()
assert np.all(np.abs(geo.dist(pts)) < 1.0e-12)
if __name__ == "__main__":
# from helpers import save
X, cells = test_union_circles(show=True)
# save("union.png", X, cells)
# test_boundary_step2()
dmsh-0.2.18/tox.ini 0000664 0000000 0000000 00000000266 14134252050 0014050 0 ustar 00root root 0000000 0000000 [tox]
envlist = py3
isolated_build = True
[testenv]
deps =
optimesh
perfplot
pytest
pytest-codeblocks
pytest-cov
extras = all
commands =
pytest {posargs} --codeblocks