├── .coveragerc
├── .coveragerc_cpu
├── .github
├── ISSUE_TEMPLATE
│ └── bug_report.md
└── workflows
│ ├── paper-pdf.yml
│ ├── python-package.yml
│ └── python-publish.yml
├── .gitignore
├── .readthedocs.yaml
├── CONTRIBUTING.md
├── LICENSE
├── MANIFEST.in
├── README.md
├── coverage_command.txt
├── docs
├── benchmark.rst
├── conf.py
├── detailed_description.rst
├── example.inc
├── figs
│ ├── benchmark_cpu.jpg
│ ├── benchmark_gpu.jpg
│ ├── benchmark_gpu_setup.jpg
│ ├── update_fig.jpg
│ └── usage_example.jpg
├── index.rst
├── installation.rst
├── interface.rst
└── requirements_docs.txt
├── fimpy
├── __init__.py
├── cupy_kernels.py
├── fim_base.py
├── fim_cupy.py
├── fim_cutils
│ ├── __init__.py
│ └── fim_cutils.pyx
├── fim_np.py
├── perm_kernel_test.cu
├── solver.py
└── utils
│ ├── __init__.py
│ ├── comp.py
│ ├── cython
│ ├── __init__.py
│ └── comp.pyx
│ └── tsitsiklis.py
├── paper.bib
├── paper.md
├── pyproject.toml
├── setup.py
└── tests
├── benchmark_data
└── .gitignore
├── data
└── .gitignore
├── generate_benchmark_data.py
├── generate_doc_figs.py
├── generate_test_data.py
├── run_benchmark.py
├── test_custom_kernels.py
├── test_cython_methods.py
└── test_fim_solvers.py
/.coveragerc:
--------------------------------------------------------------------------------
1 | # https://coverage.readthedocs.io/en/latest/config.html
2 | # .coveragerc to control coverage.py
3 | [run]
4 | branch = True
5 | #omit = fim_cupy.py
6 |
7 | [report]
8 | # Regexes for lines to exclude from consideration
9 | exclude_lines =
10 | # Have to re-enable the standard pragma
11 | pragma: no cover
12 |
13 | # Don't complain about missing debug-only code:
14 | def __repr__
15 | if self\.debug
16 |
17 | # Don't complain if tests don't hit defensive assertion code:
18 | #raise AssertionError
19 | #raise NotImplementedError
20 |
21 | # Don't complain if non-runnable code isn't run:
22 | if 0:
23 | if __name__ == .__main__.:
24 |
25 | ignore_errors = True
26 |
27 | [html]
28 | directory = coverage_html
29 |
--------------------------------------------------------------------------------
/.coveragerc_cpu:
--------------------------------------------------------------------------------
1 | # https://coverage.readthedocs.io/en/latest/config.html
2 | # .coveragerc to control coverage.py
3 | [run]
4 | branch = True
5 | omit = fimpy/fim_cupy.py
6 |
7 | [report]
8 | # Regexes for lines to exclude from consideration
9 | exclude_lines =
10 | # Have to re-enable the standard pragma
11 | pragma: no cover
12 |
13 | # Don't complain about missing debug-only code:
14 | def __repr__
15 | if self\.debug
16 |
17 | # Don't complain if tests don't hit defensive assertion code:
18 | #raise AssertionError
19 | #raise NotImplementedError
20 |
21 | # Don't complain if non-runnable code isn't run:
22 | if 0:
23 | if __name__ == .__main__.:
24 | if cupy_enabled:
25 | if not cupy_available:
26 |
27 | ignore_errors = True
28 |
29 | [html]
30 | directory = coverage_html
31 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Template for bug reports
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the unexpected behavior
15 |
16 | **Please provide the following information:**
17 | - Operating system
18 | - Version numbers of
19 | - Python
20 | - Numpy
21 | - Cupy
22 |
23 | See [Contributing.md](https://github.com/thomgrand/fim-python/blob/master/CONTRIBUTING.md) for a script to automatically output the variables
24 |
25 | **Additional information [Optional]**
26 | Add any other information about the problem here.
27 |
--------------------------------------------------------------------------------
/.github/workflows/paper-pdf.yml:
--------------------------------------------------------------------------------
1 | #https://github.com/marketplace/actions/open-journals-pdf-generator
2 | on: [push]
3 |
4 | jobs:
5 | paper:
6 | runs-on: ubuntu-latest
7 | name: Paper Draft
8 | steps:
9 | - name: Checkout
10 | uses: actions/checkout@v2
11 | - name: Build draft PDF
12 | uses: openjournals/openjournals-draft-action@master
13 | with:
14 | journal: joss
15 | # This should be the path to the paper within your repo.
16 | paper-path: paper.md
17 | - name: Upload
18 | uses: actions/upload-artifact@v1
19 | with:
20 | name: paper
21 | # This is the output path where Pandoc will write the compiled
22 | # PDF. Note, this should be the same directory as the input
23 | # paper.md
24 | path: paper.pdf
25 |
--------------------------------------------------------------------------------
/.github/workflows/python-package.yml:
--------------------------------------------------------------------------------
1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions
2 | # For more information see: https://help.github.com/actions/language-and-framework-guides/using-python-with-github-actions
3 |
4 | name: CI Tests (CPU)
5 |
6 | on:
7 | push:
8 | branches: [ master ]
9 | pull_request:
10 | branches: [ master ]
11 |
12 | jobs:
13 |
14 | test_lib_pip_ubuntu:
15 |
16 | runs-on: ubuntu-latest
17 | strategy:
18 | fail-fast: false
19 | matrix:
20 | python-version: [3.7]
21 |
22 | steps:
23 | - uses: actions/checkout@v2
24 | - name: Set up Python ${{ matrix.python-version }}
25 | uses: actions/setup-python@v2
26 | with:
27 | python-version: ${{ matrix.python-version }}
28 | - name: Install with pip
29 | run: |
30 | python -m pip install --upgrade pip
31 | pip install -e .[tests]
32 | python tests/generate_test_data.py
33 | - name: Test with pytest
34 | run: |
35 | python -m pytest --cov-config=.coveragerc_cpu --cov=fimpy tests/
36 | bash <(curl -s https://codecov.io/bash) -t ${{ secrets.CODECOV_TOKEN }}
37 |
38 | test_lib_pip_windows:
39 |
40 | runs-on: windows-latest
41 | strategy:
42 | fail-fast: false
43 | matrix:
44 | python-version: [3.7]
45 |
46 | steps:
47 | - uses: actions/checkout@v2
48 | - name: Set up Python ${{ matrix.python-version }}
49 | uses: actions/setup-python@v2
50 | with:
51 | python-version: ${{ matrix.python-version }}
52 | - name: Install with pip
53 | run: |
54 | python -m pip install --upgrade pip
55 | pip install -e .[tests]
56 | python tests/generate_test_data.py
57 | - name: Test with pytest
58 | run: |
59 | python -m pytest --cov-config=.coveragerc_cpu --cov=fimpy tests/
60 |
61 | test_lib_pip_macos:
62 |
63 | runs-on: macos-latest
64 | strategy:
65 | fail-fast: false
66 | matrix:
67 | python-version: [3.7]
68 |
69 | steps:
70 | - uses: actions/checkout@v2
71 | - name: Set up Python ${{ matrix.python-version }}
72 | uses: actions/setup-python@v2
73 | with:
74 | python-version: ${{ matrix.python-version }}
75 | - name: Install with pip
76 | run: |
77 | python -m pip install --upgrade pip
78 | pip install -e .[tests]
79 | python tests/generate_test_data.py
80 | - name: Test with pytest
81 | run: |
82 | python -m pytest --cov-config=.coveragerc_cpu --cov=fimpy tests/
83 |
--------------------------------------------------------------------------------
/.github/workflows/python-publish.yml:
--------------------------------------------------------------------------------
1 | # This workflow will upload a Python Package using Twine when a release is created
2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3 |
4 | # This workflow uses actions that are not certified by GitHub.
5 | # They are provided by a third-party and are governed by
6 | # separate terms of service, privacy policy, and support
7 | # documentation.
8 |
9 | name: Upload Python Package
10 |
11 | on:
12 | release:
13 | types: [published]
14 |
15 | jobs:
16 | deploy:
17 |
18 | runs-on: ubuntu-latest
19 |
20 | steps:
21 | - uses: actions/checkout@v2
22 | - name: Set up Python
23 | uses: actions/setup-python@v2
24 | with:
25 | python-version: '3.x'
26 | - name: Install dependencies
27 | run: |
28 | python -m pip install --upgrade pip
29 | pip install build
30 | - name: Build package
31 | run: python -m build -s
32 | - name: Publish package
33 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29
34 | with:
35 | user: __token__
36 | password: ${{ secrets.PYPI_API_TOKEN }}
37 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | #Pip install files
2 | *.egg-info*
3 | *.pyc
4 | *__pycache__*
5 |
6 | #Cython temporaries
7 | *.cpp
8 | *.c
9 | *.cc
10 | *.pyd
11 |
12 | #Documentation build folder
13 | docs/_build/*
14 | docs/build/*
15 | docs/_autosummary*
16 | coverage_html/*
17 |
18 | #General build folders
19 | build/*
--------------------------------------------------------------------------------
/.readthedocs.yaml:
--------------------------------------------------------------------------------
1 | # .readthedocs.yaml
2 | # Read the Docs configuration file
3 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
4 |
5 | # Required
6 | version: 2
7 |
8 | # Build documentation in the docs/ directory with Sphinx
9 | sphinx:
10 | configuration: docs/conf.py
11 |
12 | # Optionally build your docs in additional formats such as PDF
13 | #formats:
14 | # - pdf
15 |
16 | # Optionally set the version of Python and requirements required to build your docs
17 | python:
18 | version: 3.7
19 | install:
20 | - requirements: docs/requirements_docs.txt
21 | - method: pip
22 | path: .
23 | extra_requirements:
24 | - docs
25 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing to FIM-Python
2 |
3 | Thank you for your interest in FIM-Python. Any help and contributions are appreciated.
4 |
5 |
6 | Reporting Bugs
7 | ---------------------
8 |
9 | Please submit bug reports to the [issue page](https://github.com/thomgrand/fim-python/issues). Make sure that you include all of the following:
10 | - Description of the bug
11 | - Steps to reconstruct the error
12 | - Operating system
13 | - Version numbers of
14 | - Python
15 | - Numpy
16 | - Cupy
17 |
18 | Fetching the version numbers and the operating system info can be automatically achieved by executing the following script in your python environment:
19 |
20 | ```python
21 | import platform
22 | import os
23 | print("OS Info: %s, %s, v%s" % (os.name, platform.system(), platform.release()))
24 |
25 | import numpy
26 | print("Numpy version: %s" % (numpy.__version__))
27 |
28 | try:
29 | import cupy
30 | print("GPU version, version of cupy: %s" % (cupy.__version__))
31 | except ImportError:
32 | print("CPU version only")
33 | ```
34 |
35 | Submitting Code
36 | --------------------
37 | FIM-Python uses the [pytest](https://docs.pytest.org) framework. Pip can take care of installing all necessary packages by listing the extra ``tests``:
38 | ```bash
39 | pip install fim-python[gpu,tests]
40 | ```
41 | The tests can be run by executing
42 | ```bash
43 | python tests/generate_test_data.py #First time only to generate the test examples
44 | python -m pytest tests
45 | ```
46 |
47 | Before opening a pull request for newly written code, please make sure that all tests are passing.
48 | In case you only have the CPU version, all tests for the GPU will be skipped.
49 | If you submit new features, please also write tests to ensure functionality of these features.
50 | The github-runner will also test pull-requests and committed versions of the library, but only on the CPU for the lack of a GPU on the runner.
51 |
52 | > **_Note:_** If you do **not** have a Cupy compatible GPU to test on, please clearly state this in your pull request, so somebody else from the community can test your code with all features enabled.
53 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | global-include *.pyx
2 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Fast Iterative Method - Numpy/Cupy
2 | This repository implements the Fast Iterative Method on [tetrahedral domains](https://epubs.siam.org/doi/abs/10.1137/120881956) and [triangulated surfaces](https://epubs.siam.org/doi/abs/10.1137/100788951) purely in python both for CPU (numpy) and GPU (cupy). The main focus is however on the GPU implementation, since it can be better exploited for very large domains.
3 |
4 | [](https://codecov.io/gh/thomgrand/fim-python)
5 | [](https://github.com/thomgrand/fim-python/actions/workflows/python-package.yml)
6 | [](https://doi.org/10.21105/joss.03641)
7 |
8 | # Details
9 | The anisotropic eikonal equation is given by
10 |
11 | 
12 |
13 |
14 | for given boundary conditions
15 |
16 | %20=%20g(\mathbf{x}_0))
17 |
18 | For a given anisotropic velocity, this can calculate the geodesic distance between a set of  and all points on the domain like shown in the figure.
19 |
20 | 
21 |
22 | Note that when using multiple , they are not guaranteed to be in the final solution if they are not a valid viscosity solution. A recommended read for more details on the subject is:
23 | Evans, Lawrence C. "Partial differential equations." *Graduate studies in mathematics* 19.2 (1998).
24 |
25 | # Installation
26 |
27 | The easiest way to install the library is using pip
28 | ```bash
29 | pip install fim-python[gpu] #GPU version
30 | ```
31 |
32 | If you don't have a compatible CUDA GPU, you can install the CPU only version to test the library, but the performance won't be comparable to the GPU version (see [Benchmark](#benchmark)).
33 |
34 | ```bash
35 | pip install fim-python #CPU version
36 | ```
37 |
38 | # Usage
39 |
40 | The main interface to create a solver object to use is [`create_fim_solver`](https://fim-python.readthedocs.io/en/latest/interface.html#fimpy.solver.create_fim_solver)
41 |
42 | ```python
43 | from fimpy.solver import create_fim_solver
44 |
45 | #Create a FIM solver, by default the GPU solver will be called with the active list
46 | #Set device='cpu' to run on cpu and use_active_list=False to use Jacobi method
47 | fim = create_fim_solver(points, elems, D)
48 | ```
49 |
50 | Example
51 | -------
52 |
53 | The following code reproduces the [above example](#details)
54 |
55 | ```python
56 | import numpy as np
57 | import cupy as cp
58 | from fimpy.solver import create_fim_solver
59 | from scipy.spatial import Delaunay
60 | import matplotlib.pyplot as plt
61 |
62 | #Create triangulated points in 2D
63 | x = np.linspace(-1, 1, num=50)
64 | X, Y = np.meshgrid(x, x)
65 | points = np.stack([X, Y], axis=-1).reshape([-1, 2]).astype(np.float32)
66 | elems = Delaunay(points).simplices
67 | elem_centers = np.mean(points[elems], axis=1)
68 |
69 | #The domain will have a small spot where movement will be slow
70 | velocity_f = lambda x: (1 / (1 + np.exp(3.5 - 25*np.linalg.norm(x - np.array([[0.33, 0.33]]), axis=-1)**2)))
71 | velocity_p = velocity_f(points) #For plotting
72 | velocity_e = velocity_f(elem_centers) #For computing
73 | D = np.eye(2, dtype=np.float32)[np.newaxis] * velocity_e[..., np.newaxis, np.newaxis] #Isotropic propagation
74 |
75 | x0 = np.array([np.argmin(np.linalg.norm(points, axis=-1), axis=0)])
76 | x0_vals = np.array([0.])
77 |
78 | #Create a FIM solver, by default the GPU solver will be called with the active list
79 | fim = create_fim_solver(points, elems, D)
80 | phi = fim.comp_fim(x0, x0_vals)
81 |
82 | #Plot the data of all points to the given x0 at the center of the domain
83 | fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True)
84 | cont_f1 = axes[0].contourf(X, Y, phi.get().reshape(X.shape))
85 | axes[0].set_title("Distance from center")
86 |
87 | cont_f2 = axes[1].contourf(X, Y, velocity_p.reshape(X.shape))
88 | axes[1].set_title("Assumed isotropic velocity")
89 | plt.show()
90 | ```
91 |
92 | A general rule of thumb: If you only need to evaluate the eikonal equation once for a mesh, the Jacobi version (`use_active_list=False`) will probably be quicker since its initial overhead is low.
93 | Repeated evaluations with different  or  favor the active list method for larger meshes.
94 | On the CPU, `use_active_list=True` outperforms the Jacobi approach for almost all cases.
95 |
96 | # Documentation
97 |
98 | [https://fim-python.readthedocs.io/en/latest](https://fim-python.readthedocs.io/en/latest)
99 |
100 | # Citation
101 |
102 | If you find this work useful in your research, please consider citing the [paper](https://doi.org/10.21105/joss.03641) in the [Journal of Open Source Software](https://joss.theoj.org/)
103 | ```bibtex
104 | @article{grandits_fast_2021,
105 | doi = {10.21105/joss.03641},
106 | url = {https://doi.org/10.21105/joss.03641},
107 | year = {2021},
108 | publisher = {The Open Journal},
109 | volume = {6},
110 | number = {66},
111 | pages = {3641},
112 | author = {Thomas Grandits},
113 | title = {A Fast Iterative Method Python package},
114 | journal = {Journal of Open Source Software}
115 | }
116 | ```
117 |
118 | # Benchmark
119 |
120 | Below you can see a performance benchmark of the library for tetrahedral domains (cube in ND), triangular surfaces (plane in ND), and line networks (randomly sampled point cloud in the ND cube with successive minimum spanning tree) from left to right.
121 | In all cases,  was placed in the middle of the domain.
122 | The dashed lines show the performance of the implementation using active lists, the solid lines use the Jacobi method (computing all updates in each iteration).
123 |
124 | 
125 |
126 | 
127 |
128 | The library works for an arbitrary number of dimensions (manifolds in N-D), but the versions for 2 and 3D received a few optimized kernels that speed up the computations.
129 |
130 | The steps to reproduce the benchmarks can be found in the documentation at [https://fim-python.readthedocs.io/en/latest/benchmark.html](https://fim-python.readthedocs.io/en/latest/benchmark.html)
131 |
132 | # Contributing
133 |
134 | See [Contributing](CONTRIBUTING.md) for more information on how to contribute.
135 |
136 | # License
137 |
138 | This library is licensed under the [GNU Affero General Public License](LICENSE).
139 | If you need the library issued under another license for commercial use, you can contact me via e-mail [tomdev (at) gmx.net](mailto:tomdev@gmx.net).
140 |
--------------------------------------------------------------------------------
/coverage_command.txt:
--------------------------------------------------------------------------------
1 | python -m pytest --cov-config=.coveragerc --cov=fimpy tests/ --cov-report html:coverage_html
2 |
--------------------------------------------------------------------------------
/docs/benchmark.rst:
--------------------------------------------------------------------------------
1 | Benchmark
2 | ============
3 |
4 | Both the *Jacobi* and *active list* methods have been tested on heterogeneous ND cubes.
5 | Here you can see the comparison of both their run- and setup-time.
6 | The dashed lines show the performance of the implementation using active lists, the solid lines use the Jacobi method (see :doc:`Detailed Description ` for more info).
7 |
8 | Runtime
9 | --------
10 |
11 | Below you can see a performance benchmark of the library for tetrahedral domains (cube in ND), triangular surfaces (plane in ND), and line networks (randomly sampled point cloud in the ND cube with successive minimum spanning tree) from left to right.
12 | In all cases, :math:`\mathbf{x}_0` was placed in the middle of the domain.
13 |
14 | .. image:: figs/benchmark_gpu.jpg
15 | :alt: Benchmark GPU
16 | :align: center
17 |
18 | .. image:: figs/benchmark_cpu.jpg
19 | :alt: Benchmark CPU
20 | :align: center
21 |
22 | The library works for an arbitrary number of dimensions (manifolds in N-D), but the versions for 2 and 3D received a few optimized kernels that speed up the computations.
23 |
24 | Setup Time
25 | ----------
26 |
27 | The active list method additionally needs to create a few mesh specific fields before computation to efficiently update the active list.
28 | This makes it best suited for repeated queries of the same mesh with different :math:`D, g, \mathbf{x}_0`.
29 | The figure below shows the setup time for both methods.
30 |
31 | .. image:: figs/benchmark_gpu_setup.jpg
32 | :alt: Setup Time GPU
33 | :align: center
34 |
35 | Run the Benchmark
36 | -------------
37 |
38 | Before running the benchmark, make sure the library was installed to run the tests and the documentation:
39 |
40 | .. code-block:: bash
41 |
42 | pip install fim-python[gpu,tests,docs]
43 |
44 | The benchmark can then be initiated by first generating the data and then running the actual benchmark
45 |
46 | .. code-block:: bash
47 |
48 | python tests/generate_benchmark_data.py
49 | python tests/run_benchmark.py
50 |
51 | The routine ``generate_benchmark_plot`` in ``tests/generate_docs_figs.py`` can be called to regenerate the documentation figures, including the above benchmark plot
52 |
53 | .. code-block:: bash
54 |
55 | python tests/generate_docs_figs.py
56 |
57 | .. note::
58 |
59 | The benchmark exhaustively tests the library for many different meshes and can therefore take one hour or more to finish.
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # Configuration file for the Sphinx documentation builder.
2 | #
3 | # This file only contains a selection of the most common options. For a full
4 | # list see the documentation:
5 | # https://www.sphinx-doc.org/en/master/usage/configuration.html
6 |
7 | # -- Path setup --------------------------------------------------------------
8 |
9 | # If extensions (or modules to document with autodoc) are in another directory,
10 | # add these directories to sys.path here. If the directory is relative to the
11 | # documentation root, use os.path.abspath to make it absolute, like shown here.
12 | #
13 | import os
14 | import sys
15 | #sys.path.insert(0, os.path.abspath('../')) #Only for local usage. Incompatible with readthedocs
16 | import fimpy
17 |
18 |
19 | # -- Project information -----------------------------------------------------
20 |
21 | project = 'FIM Python'
22 | copyright = '2021, Thomas Grandits'
23 | author = 'Thomas Grandits'
24 |
25 | # The full version, including alpha/beta/rc tags
26 | release = fimpy.__version__
27 |
28 |
29 | # -- General configuration ---------------------------------------------------
30 |
31 | # Add any Sphinx extension module names here, as strings. They can be
32 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
33 | # ones.
34 | extensions = ['sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.coverage', 'sphinx.ext.napoleon'
35 | ]
36 |
37 | autosummary_generate = True
38 |
39 | # Add any paths that contain templates here, relative to this directory.
40 | templates_path = ['_templates']
41 |
42 | # List of patterns, relative to source directory, that match files and
43 | # directories to ignore when looking for source files.
44 | # This pattern also affects html_static_path and html_extra_path.
45 | exclude_patterns = ['_build', 'Thumbs.db', '.DS_Store']
46 |
47 |
48 | # -- Options for HTML output -------------------------------------------------
49 |
50 | # The theme to use for HTML and HTML Help pages. See the documentation for
51 | # a list of builtin themes.
52 | #
53 | #html_theme = 'alabaster'
54 | #html_theme = 'sphinx_rtd_theme'
55 | html_theme = 'pydata_sphinx_theme'
56 |
57 | # Add any paths that contain custom static files (such as style sheets) here,
58 | # relative to this directory. They are copied after the builtin static files,
59 | # so a file named "default.css" will overwrite the builtin "default.css".
60 | html_static_path = ['_static']
61 |
62 |
63 | #https://stackoverflow.com/questions/5599254/how-to-use-sphinxs-autodoc-to-document-a-classs-init-self-method
64 | #def skip(app, what, name, obj, would_skip, options):
65 | # if name == "__init__":
66 | # return False
67 | # return would_skip
68 | #
69 | #def setup(app):
70 | # app.connect("autodoc-skip-member", skip)
71 |
--------------------------------------------------------------------------------
/docs/detailed_description.rst:
--------------------------------------------------------------------------------
1 | Detailed Description
2 | ====================
3 |
4 | The Fast Iterative Method locally computes an update rule, rooted in the Hamilton-Jacobi formalism of the eikonal problem, computing the path the front-wave will take through the current element.
5 | Since the algorithm is restricted to linear Lagrangian :math:`\mathcal{P}^1` elements, the path through an element will also be a line.
6 | To demonstrate the algorithm, consider a tetrahedron spanned by the four corners :math:`\mathbf{v}_1` through :math:`\mathbf{v}_4`.
7 | For the earliest arrival times associated to each corner, we will use the notation :math:`\phi_i = \phi(\mathbf{v}_i)`.
8 | The origin of a linear update from a face spanned by three vertices :math:`\mathbf{v}_1, \mathbf{v}_2, \mathbf{v}_3` to the fourth :math:`\mathbf{v}_4` is required to be inside said face.
9 | Mathematically this is described by the following set:
10 |
11 | .. math::
12 | \Delta_k = \left\{ \left( \lambda_1, \ldots, \lambda_k \right)^\top \middle\vert \sum_{i=1}^k \lambda_i = 1 \land \lambda_i \ge 0 \right\}
13 |
14 | The earliest arrival time :math:`\phi_4` can be found by solving the minimization problem which constitutes the local update rule
15 |
16 | .. math::
17 | \phi_4 = \min_{\lambda_1, \lambda_2} \, \sum_{i=1}^3\lambda_i \phi_i + \sqrt{\mathbf{e}_{\Delta}^\top D^{-1} \mathbf{e}_{\Delta}} \quad \text{s.t.: } \, \left( \lambda_1, \lambda_2, \lambda_3 \right)^\top \in \Delta_3
18 |
19 | for :math:`\lambda_3 = 1 - \lambda_1 - \lambda_2` and :math:`\mathbf{e}_{\Delta} = \mathbf{v}_4 - \sum_{i=1}^3 \lambda_i \mathbf{v}_i`.
20 | The picture below visualizes the update.
21 |
22 | .. image:: figs/update_fig.jpg
23 | :width: 300
24 | :alt: Update inside a single tetrahedron
25 | :align: center
26 |
27 | When updating a tetrahedron, we compute the update of each of the faces to the opposite vertex.
28 | The newly calculated value :math:`\phi_4` will only become the new value if it is strictly smaller than the old value.
29 |
30 | For triangles and lines, the algorithm behaves similarly but the update origin is limited to a side or vertex respectively.
31 | The internally implemented updates in the algorithm to solve the minimization problem are similar to the ones reported in `An inverse Eikonal method for identifying ventricular activation sequences from epicardial activation maps `_.
32 |
33 |
34 | Jacobi vs. Active List Method
35 | -----------------------------
36 | Two different methods are implemented in the repository:
37 | In the *Jacobi* method, the above local update rule is computed for all elements in each iteration until the change between two subsequent iterations is smaller than ``convergence_eps`` (:math:`10^{-9}` by default).
38 | This version of the algorithm is bested suited for the GPU, since it is optimal for a SIMD (single instruction multiple data) architecture.
39 |
40 | The *active list* method is more closely related to the method presented in the `paper `_:
41 | We keep track of all vertices that will be updated in the current iteration.
42 | Initially, we start off with the neighbor nodes to the initial points :math:`\mathbf{x}_0`.
43 | Once convergence has been reached for a vertex on the active list (according to ``convergence_eps``), its neighboring nodes will be recomputed and if the new value is smaller than the old, they will be added onto the active list.
44 | Convergence is achieved once the active list is empty.
45 |
46 | The active list method computes much fewer updates, but has the additional overhead of keeping track of its active list, ill-suited for the GPU.
47 | For larger meshes, the active list is still a better choice, but comes at the additional cost of a setup time (see :doc:`Benchmark `), making it best suited for repeated queries of the same mesh with different :math:`D, g, \mathbf{x}_0`.
48 |
--------------------------------------------------------------------------------
/docs/example.inc:
--------------------------------------------------------------------------------
1 | .. code-block:: python
2 |
3 | import numpy as np
4 | import cupy as cp
5 | from fimpy.solver import FIMPY
6 | from scipy.spatial import Delaunay
7 | import matplotlib.pyplot as plt
8 |
9 | #Create triangulated points in 2D
10 | x = np.linspace(-1, 1, num=50)
11 | X, Y = np.meshgrid(x, x)
12 | points = np.stack([X, Y], axis=-1).reshape([-1, 2]).astype(np.float32)
13 | elems = Delaunay(points).simplices
14 | elem_centers = np.mean(points[elems], axis=1)
15 |
16 | #The domain will have a small spot where movement will be slow
17 | velocity_f = lambda x: (1 / (1 + np.exp(3.5 - 25*np.linalg.norm(x - np.array([[0.33, 0.33]]), axis=-1)**2)))
18 | velocity_p = velocity_f(points) #For plotting
19 | velocity_e = velocity_f(elem_centers) #For computing
20 | D = np.eye(2, dtype=np.float32)[np.newaxis] * velocity_e[..., np.newaxis, np.newaxis] #Isotropic propagation
21 |
22 | x0 = np.array([np.argmin(np.linalg.norm(points, axis=-1), axis=0)])
23 | x0_vals = np.array([0.])
24 |
25 | #Create a FIM solver, by default the GPU solver will be called with the active list
26 | #Set device='cpu' to run on cpu and use_active_list=false to use Jacobi method
27 | fim = FIMPY.create_fim_solver(points, elems, D)
28 | phi = fim.comp_fim(x0, x0_vals)
29 |
30 | #Plot the data of all points to the given x0 at the center of the domain
31 | fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True)
32 | cont_f1 = axes[0].contourf(X, Y, phi.get().reshape(X.shape))
33 | axes[0].set_title("Distance from center")
34 |
35 | cont_f2 = axes[1].contourf(X, Y, velocity_p.reshape(X.shape))
36 | axes[1].set_title("Assumed isotropic velocity")
37 | plt.show()
38 |
--------------------------------------------------------------------------------
/docs/figs/benchmark_cpu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thomgrand/fim-python/1840fee9870341c37f43f2fcf45c273ab339f0cd/docs/figs/benchmark_cpu.jpg
--------------------------------------------------------------------------------
/docs/figs/benchmark_gpu.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thomgrand/fim-python/1840fee9870341c37f43f2fcf45c273ab339f0cd/docs/figs/benchmark_gpu.jpg
--------------------------------------------------------------------------------
/docs/figs/benchmark_gpu_setup.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thomgrand/fim-python/1840fee9870341c37f43f2fcf45c273ab339f0cd/docs/figs/benchmark_gpu_setup.jpg
--------------------------------------------------------------------------------
/docs/figs/update_fig.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thomgrand/fim-python/1840fee9870341c37f43f2fcf45c273ab339f0cd/docs/figs/update_fig.jpg
--------------------------------------------------------------------------------
/docs/figs/usage_example.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/thomgrand/fim-python/1840fee9870341c37f43f2fcf45c273ab339f0cd/docs/figs/usage_example.jpg
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | .. FIM Python documentation master file, created by
2 | sphinx-quickstart on Mon May 17 21:13:20 2021.
3 | You can adapt this file completely to your liking, but it should at least
4 | contain the root `toctree` directive.
5 |
6 | FIM-Python documentation
7 | ======================================
8 |
9 | .. contents:: Quick Start
10 | :depth: 3
11 |
12 | Introduction
13 | ------------
14 |
15 | This library implements the Fast Iterative method that solves the anisotropic eikonal equation on
16 | `triangulated surfaces `_,
17 | `tetrahedral meshes `_ and line networks
18 | (equivalent to the `Dijkstra's algorithm `_ in this case),
19 | for arbitrary dimensions.
20 |
21 | The anisotropic eikonal equation that is solved, is given by the partial differential equation
22 |
23 | .. math::
24 | \left\{
25 | \begin{array}{rll}
26 | \left<\nabla \phi, D \nabla \phi \right> &= 1 \quad &\text{on} \; \Omega \\
27 | \phi(\mathbf{x}_0) &= g(\mathbf{x}_0) \quad &\text{on} \; \Gamma
28 | \end{array}
29 | \right. .
30 |
31 | The library computes :math:`\phi` for a given :math:`D`, :math:`\mathbf{x}_0` and :math:`g`.
32 | In practice, this problem is often associated to computing the earliest arrival times :math:`\phi` from a set of given starting points :math:`\mathbf{x}_0` through a heterogeneous medium (i.e. different velocities are assigned throughout the medium).
33 |
34 | Usage
35 | ---------------------
36 | The following shorthand notations are important to know:
37 |
38 | - :math:`n`: Number of points
39 | - :math:`m`: Number of elements
40 | - :math:`d`: Dimensionality of the points and metrics (:math:`D \in \mathbb{R}^{d \times d}`)
41 | - :math:`d_e`: Number of vertices per elements (2, 3 and 4 for lines, triangles and tetrahedra respectively)
42 | - :math:`k`: Number of discrete points :math:`\mathbf{x}_0 \in \Gamma` and respective values in :math:`g(\mathbf{x}_0)`
43 | - :math:`M := D^{-1}`: The actual metric used in all computations. This is is computed internally and automatically by the library (no need for you to invert :math:`D`)
44 | - precision: The chosen precision for the solver at the initialization
45 |
46 | This example computes the solution to the anisotropic eikonal equation for a simple square domain
47 | :math:`\Omega = [-1, 1]^2`, with :math:`n = 50^2, d = 2, d_e = 3` and a given isotropic :math:`D`.
48 | This example requires additionally matplotlib and scipy.
49 |
50 |
51 | .. include:: example.inc
52 |
53 | You should see the following figure with the computed :math:`\phi` for the given :math:`D = c I`.
54 |
55 |
56 | .. image:: figs/usage_example.jpg
57 | :alt: Usage example
58 |
59 | .. include:: installation.rst
60 |
61 |
62 |
63 |
64 |
65 | Detailed Contents
66 | --------------
67 | .. toctree::
68 | :maxdepth: 2
69 |
70 | interface.rst
71 | detailed_description.rst
72 | benchmark.rst
73 |
74 |
75 | Module API
76 | --------------
77 |
78 | .. autosummary::
79 | :toctree: _autosummary
80 | :recursive:
81 | :caption: Module
82 |
83 | fimpy
84 |
85 |
86 | Indices and tables
87 | ------------------
88 |
89 | * :ref:`genindex`
90 | * :ref:`modindex`
91 | * :ref:`search`
92 |
--------------------------------------------------------------------------------
/docs/installation.rst:
--------------------------------------------------------------------------------
1 | Installation
2 | --------------
3 |
4 | To install, either clone the repository and install it:
5 |
6 | .. code-block:: bash
7 |
8 | git clone https://github.com/thomgrand/fim-python .
9 | pip install -e .[gpu]
10 |
11 |
12 | or simply install the library over `PyPI `_.
13 |
14 | .. code-block:: bash
15 |
16 | pip install fim-python[gpu]
17 |
18 | .. note::
19 |
20 | Installing the GPU version might take a while since many ``cupy`` modules are compiled using your system's ``nvcc`` compiler.
21 | You can install the ``cupy`` binaries first as mentioned `here `_, before installing ``fimpy``.
--------------------------------------------------------------------------------
/docs/interface.rst:
--------------------------------------------------------------------------------
1 |
2 | Interface Methods
3 | =================
4 | All different solvers can be generated using the interface class.
5 | Note that if you specify the gpu interface, but your system does not support it (or you did not install it), you will only get a cpu solver.
6 |
7 | .. automethod:: fimpy.solver.FIMPY.create_fim_solver
8 |
9 | Computing the anisotropic eikonal equation can be easily achieved by calling :meth:`fimpy.fim_base.FIMBase.comp_fim` on the returned solver.
10 |
11 | .. automethod:: fimpy.fim_base.FIMBase.comp_fim
12 |
13 | .. toctree::
14 | :maxdepth: 2
15 | :caption: Contents:
16 |
--------------------------------------------------------------------------------
/docs/requirements_docs.txt:
--------------------------------------------------------------------------------
1 | numpy
2 | cython
3 | sphinx
4 | pydata_sphinx_theme
5 |
--------------------------------------------------------------------------------
/fimpy/__init__.py:
--------------------------------------------------------------------------------
1 | #TODO: Import all symbols and methods here
2 | from .solver import create_fim_solver
3 |
4 | __version__ = "1.2.2"
5 | __author__ = "Thomas Grandits"
--------------------------------------------------------------------------------
/fimpy/cupy_kernels.py:
--------------------------------------------------------------------------------
1 | """This file contains some custom CUDA kernels, used in the CUDA implementation of FIMPY
2 | """
3 |
4 | compute_perm_kernel_str = (r'''
5 | extern "C" __global__
6 | void perm_kernel(const int* active_elems_perm, const int* active_inds,
7 | bool* perm_mask,
8 | const unsigned int active_elems_size,
9 | const unsigned int active_inds_size) {
10 | const int nr_perms = {active_perms};
11 | const int bidx = blockIdx.x;
12 | const int block_size = blockDim.x;
13 | const int tidx = block_size * bidx + threadIdx.x;
14 |
15 | for(int offset = tidx; offset < active_elems_size*nr_perms; offset+=block_size*{parallel_blocks})
16 | {
17 | const int point_i = active_elems_perm[offset];
18 | bool match = false;
19 | for(int active_i = 0; !match && (active_i < active_inds_size); active_i++)
20 | {
21 | if(active_inds[active_i] == point_i)
22 | {
23 | perm_mask[offset] = true;
24 | match = true;
25 | }
26 | }
27 | }
28 | }
29 | ''') #: CUDA kernel to compute a mask of all element permutations containing at least one active index. Old, less inefficient version not using shared memory.
30 |
31 | compute_perm_kernel_shared = (r'''
32 | extern "C"{
33 |
34 | //https://en.cppreference.com/w/cpp/algorithm/upper_bound
35 | /**
36 | * @brief Similar to https://en.cppreference.com/w/cpp/algorithm/upper_bound , but also works on
37 | * the CUDA device. Assumes the range to be sorted, but has O(log n) runtime in return.
38 | *
39 | * @param first Beginning of the range where to find the upper bound
40 | * @param last End (exlusive) of the range where to find the upper bound
41 | * @param value The value for which we want to find the upper bound
42 | * @return int* The upper bound location. =End if outside
43 | */
44 | __device__ int* upper_bound(int* first, int* last, const int& value)
45 | {
46 | int* it;
47 | int count, step;
48 | count = last - first;
49 |
50 | while (count > 0) {
51 | it = first;
52 | step = count / 2;
53 | it += step;
54 | if (value >= *it) {
55 | first = ++it;
56 | count -= step + 1;
57 | }
58 | else
59 | count = step;
60 | }
61 | return first;
62 | }
63 |
64 | __global__
65 | void perm_kernel(const int* active_elems_perm, const int* active_inds,
66 | bool* perm_mask,
67 | const unsigned int active_elems_size,
68 | const unsigned int active_inds_size) {
69 | const int nr_perms = {active_perms};
70 | const int bidx = blockIdx.x;
71 | const int block_size = blockDim.x;
72 | const int tidx_global = block_size * bidx + threadIdx.x;
73 | const int tidx_local = threadIdx.x;
74 | __shared__ int active_inds_buf[{shared_buf_size}];
75 | const int nr_shared_bufs_needed = static_cast(ceil(static_cast(active_inds_size) / {shared_buf_size}));
76 |
77 | for(int shared_buf_run = 0; shared_buf_run < nr_shared_bufs_needed; shared_buf_run++)
78 | {
79 | const int shared_buf_offset = {shared_buf_size} * shared_buf_run;
80 | const int current_active_inds_size = min({shared_buf_size}, active_inds_size - {shared_buf_size}*shared_buf_run);
81 | if(shared_buf_run > 0)
82 | __syncthreads();
83 |
84 | //Fill shared memory
85 | for(int active_i = tidx_local; active_i < current_active_inds_size; active_i += block_size)
86 | active_inds_buf[active_i] = active_inds[shared_buf_offset + active_i];
87 |
88 | __syncthreads();
89 |
90 | for(int elem_offset = tidx_global; elem_offset < active_elems_size*nr_perms; elem_offset+=block_size*{parallel_blocks})
91 | {
92 | const int point_i = active_elems_perm[elem_offset];
93 | bool match = perm_mask[elem_offset]; //Maybe already set in the last shared buffer run
94 | if(!match)
95 | {
96 | const int* bound = upper_bound(active_inds_buf, active_inds_buf + current_active_inds_size, point_i);
97 | const int idx = max(0, (int)((bound-1) - active_inds_buf));
98 | if(active_inds_buf[idx] == point_i)
99 | perm_mask[elem_offset] = true;
100 | }
101 | }
102 | }
103 | }
104 | }''') #: CUDA kernel to compute a mask of all element permutations containing at least one active index. New, more efficient version using shared memory.
105 |
--------------------------------------------------------------------------------
/fimpy/fim_base.py:
--------------------------------------------------------------------------------
1 | """This file contains the base implementation of the Fast Iterative Method, common to all solvers.
2 | """
3 |
4 | from typing import Type
5 | import numpy as np
6 | from itertools import permutations
7 | from abc import abstractmethod
8 | from .utils.tsitsiklis import norm_map
9 | from .fim_cutils import compute_point_elem_map_c, compute_neighborhood_map_c
10 |
11 | class FIMBase():
12 | """This abstract base class combines common functionality of Cupy and Numpy solvers
13 |
14 | Parameters
15 | ----------
16 | points : Union[np.ndarray (float), cp.ndarray (float)]
17 | Array of points, :math:`n \\times d`
18 | elems : Union[np.ndarray (int), cp.ndarray (int)]
19 | Array of elements, :math:`m \\times d_e`
20 | metrics : Union[np.ndarray (float), cp.ndarray (float)], optional
21 | Specifies the initial :math:`D \\in \\mathbb{R}^{d \\times d}` tensors.
22 | If not specified, you later need to provide them in :meth:`comp_fim`, by default None
23 | precision : np.dtype, optional
24 | precision of all calculations and the final result, by default np.float32
25 | comp_connectivities : bool, optional
26 | If set to true, both a neighborhood and point to element mapping will be computed.
27 | These are used to efficiently compute the active list.
28 | By default False
29 | """
30 |
31 | undef_val = 1e10 #: The value for points that have not been computed yet
32 | convergence_eps = 1e-9 #: The value of epsilon to check if a point has converged
33 |
34 | def __init__(self, points, elems, metrics=None, precision=np.float32, comp_connectivities=False):
35 | """
36 | """
37 | assert(np.issubdtype(points.dtype, np.floating))
38 | assert(np.issubdtype(elems.dtype, np.integer))
39 |
40 | assert(points.ndim == 2)
41 | #assert(points.shape[-1] in [1, 2, 3]) #TODO: Necessary?
42 | assert(elems.ndim == 2)
43 | assert(elems.shape[-1] in [2, 3, 4])
44 | elems = elems.astype(np.int32)
45 |
46 | self.nr_points = points.shape[0]
47 | self.nr_elems = elems.shape[0]
48 | assert(np.unique(elems).size == self.nr_points) #All points are part of at least one element
49 | assert(np.all(np.unique(elems) == np.arange(self.nr_points))) #All points are part of at least one element
50 |
51 | self.points = points.astype(precision)
52 | self.elems = np.ascontiguousarray(elems)
53 |
54 |
55 | if metrics is not None:
56 | self.check_metrics_argument(metrics)
57 | metrics = np.linalg.inv(metrics).astype(precision) #The inverse metric is used in the FIM algorithm
58 |
59 | self.metrics = metrics
60 |
61 | #General allocations
62 | self.active_list = np.zeros(shape=[self.nr_points], dtype=bool)
63 | self.elems_perm = self.compute_unique_elem_permutations()
64 | self.points_perm = self.points[self.elems_perm]
65 | self.phi_sol = np.ones_like(self.points[..., 0]) * self.undef_val
66 |
67 | self.elem_dims = self.elems.shape[-1]
68 | if comp_connectivities:
69 | self.nh_map = self.compute_neighborhood_map()
70 | self.point_elem_map = self.compute_point_elem_map()
71 |
72 | self.precision = precision
73 | self.dims = self.points.shape[-1]
74 | self.choose_update_alg()
75 |
76 | def choose_update_alg(self):
77 | """Selects the update step of the algorithm according to the provided element type.
78 |
79 | Raises
80 | ------
81 | TypeError
82 | If self.elem_dims is not in [2, 3, 4] (lines, triangles, tetrahedra)
83 | """
84 | if self.elem_dims == 2:
85 | self.update_all_points = self.calculate_all_line_updates
86 | self.update_specific_points = self.calculate_specific_line_updates
87 | elif self.elem_dims == 3:
88 | self.update_all_points = self.calculate_all_triang_updates
89 | self.update_specific_points = self.calculate_specific_triang_updates
90 | elif self.elem_dims == 4:
91 | self.update_all_points = self.calculate_all_tetra_updates
92 | self.update_specific_points = self.calculate_specific_tetra_updates
93 | else:
94 | raise TypeError("Unsupported number of points per element: %d. Supported are lines, triangles and tetrahedra (2, 3, 4)" % (self.elem_dims))
95 |
96 | def check_metrics_argument(self, metrics):
97 | """Checks the validity of the metric tensors (:math:`D \\in \\mathbb{R}^{d \\times d}`)
98 |
99 | Parameters
100 | ----------
101 | metrics : Union[np.ndarray (float), cp.ndarray (float)], optional
102 | The :math:`D \\in \\mathbb{R}^{d \\times d}` tensors.
103 | """
104 | assert(np.issubdtype(metrics.dtype, np.floating))
105 | assert(metrics.shape[0] == self.nr_elems) #One constant metric for each element
106 | assert(metrics.ndim == 3)
107 | assert(metrics.shape[-1] == metrics.shape[-2] and metrics.shape[-1] == self.points.shape[-1])
108 | assert(np.allclose(metrics - np.transpose(metrics, axes=(0, 2, 1)), 0., atol=1e-4)) #Symmetric
109 | assert(np.all(np.linalg.eigh(metrics)[0] > 1e-4)) #Positive definite
110 |
111 |
112 | def compute_unique_elem_permutations(self):
113 | """Returns all point permutations of each element (i.e. :math:`[M, d_e] \to [M, d_e, d_e]`).
114 |
115 | Returns
116 | -------
117 | ndarray (int)
118 | An [M, d_e, d_e] array containing all permutations.
119 | """
120 | if self.elems.shape[1] == 2: #Lines
121 | perms = np.array([[0, 1], [1, 0]])
122 | elif self.elems.shape[1] == 3: #Triangles
123 | perms = np.array([[0, 1, 2], [0, 2, 1], [1, 2, 0]])
124 | elif self.elems.shape[1] == 4: #Tetrahedra
125 | perms = np.array([[0, 1, 2, 3], [0, 1, 3, 2], [0, 2, 3, 1], [1, 2, 3, 0]])
126 |
127 | elems_perm = np.stack([self.elems[np.arange(self.nr_elems)[..., np.newaxis], perm[np.newaxis]] for perm in perms], axis=1)
128 | return elems_perm
129 |
130 | def compute_neighborhood_map(self):
131 | """Computes the neighborhood map for the given mesh.
132 |
133 | Returns
134 | -------
135 | ndarray (int)
136 | The [N, ?] array holding all neighbors for each point.
137 | shape[1] of the return value will be equal to the maximum neighbor connectivity.
138 | """
139 | max_point_elem_ratio = np.max(np.unique(self.elems, return_counts=True)[1])
140 | nh_map = np.zeros(shape=[self.nr_points, max_point_elem_ratio * self.elem_dims], dtype=np.int32)
141 |
142 | nh_map = np.array(compute_neighborhood_map_c(self.elems, nh_map))
143 |
144 | nh_map = np.sort(nh_map, axis=-1)
145 |
146 | # There may be cases where the ratio was an overestimate
147 | while nh_map.shape[1] > 1 and np.all(nh_map[..., -1] == nh_map[..., -2]):
148 | nh_map = nh_map[..., :-1]
149 |
150 | return nh_map
151 |
152 | def compute_point_elem_map(self):
153 | """Computes the point element mapping for each point.
154 |
155 | Returns
156 | -------
157 | ndarray (int)
158 | The [N, ?] array holding for each point all elements that it is contained in.
159 | shape[1] of the return value will be equal to the maximum point to element ratio.
160 | """
161 | max_point_elem_ratio = np.max(np.unique(self.elems, return_counts=True)[1])
162 | point_elem_map = np.zeros(shape=[self.nr_points, max_point_elem_ratio], dtype=np.int32)
163 | point_elem_map = np.sort(compute_point_elem_map_c(self.elems, point_elem_map), axis=-1)
164 | return point_elem_map
165 |
166 | def tsitsiklis_update_line(self, x1, x2, D, u1, lib=np):
167 | """Computes :math:`||\\mathbf{x}_2 - \\mathbf{x}_1||_M` in a broadcasted way.
168 |
169 | Parameters
170 | ----------
171 | x1 : ndarray (precision)
172 | An [..., N, d] array holding :math:`\\mathbf{x}_1`
173 | x2 : ndarray (precision)
174 | An [..., N, d] array holding :math:`\\mathbf{x}_2`
175 | D : ndarray (precision)
176 | An [..., N, d, d] array holding :math:`D`
177 | u1 : ndarray (precision)
178 | An [..., N] array holding :math:`u_1`
179 | lib : Union([np, cp]), optional
180 | Module that will be used to compute the norm, by default np
181 |
182 | Returns
183 | -------
184 | ndarray (precision)
185 | An [..., N] array that holds :math:`||\\mathbf{x}_2 - \\mathbf{x}_1||_M`
186 | """
187 | norm_f = norm_map[lib][D.shape[-1]][0]
188 | a1 = x2 - x1
189 | return u1 + norm_f(D, a1, a1)
190 |
191 | def tsitsiklis_update_point_sol(self, x1, x2, x3, D, u1, u2, lib=np):
192 | """Computes
193 |
194 | .. math::
195 | \\min\\{u_1 + ||\\mathbf{x}_3 - \\mathbf{x}_1||_M, u_2 + ||\\mathbf{x}_3 - \\mathbf{x}_2||_M\\}
196 |
197 | in a broadcasted way.
198 | For more information on the type and shape of the parameters and return value, see :meth:`tsitsiklis_update_line`.
199 | """
200 | norm_f = norm_map[lib][D.shape[-1]][0]
201 |
202 | a1 = x3 - x1
203 | a2 = x3 - x2
204 | u3_1 = u1 + norm_f(D, a1, a1)
205 | u3_2 = u2 + norm_f(D, a2, a2)
206 |
207 | return lib.minimum(u3_1, u3_2)
208 |
209 | def tsitsiklis_update_triang(self, x1, x2, x3, D, u1, u2, lib=np):
210 | """Computes the update inside a single triangle as
211 |
212 | .. math::
213 | \\min_{\\lambda} \\lambda u_1 + (1 - \\lambda) u_2 + ||\\mathbf{x}_3 - (\\lambda \\mathbf{x}_1 + (1 - \\lambda) \\mathbf{x}_2)||_M
214 |
215 | For more information on the type and shape of the parameters and return value, see :meth:`tsitsiklis_update_line`.
216 | """
217 | k = u1 - u2
218 | z2 = x2 - x3
219 | z1 = x1 - x2
220 |
221 | norm_f, norm_sqr_f = norm_map[lib][D.shape[-1]]
222 |
223 | p11 = norm_sqr_f(D, x1=z1, x2=z1)
224 | p12 = norm_sqr_f(D, x1=z1, x2=z2)
225 | p22 = norm_sqr_f(D, x1=z2, x2=z2)
226 | denominator = p11 - k**2
227 | sqrt_val = (p11 * p22 - p12**2) / denominator
228 | sqrt_invalid_mask = sqrt_val < 0.
229 | sqrt_op = lib.sqrt(sqrt_val)
230 | rhs = k * sqrt_op
231 | alpha1 = -(p12 + rhs) / p11
232 | alpha2 = -(p12 - rhs) / p11
233 | alpha1 = lib.minimum(lib.maximum(alpha1, 0.), 1.)
234 | alpha2 = lib.minimum(lib.maximum(alpha2, 0.), 1.)
235 |
236 | u3 = []
237 | for alpha in [alpha1, alpha2]:
238 | x = x3 - (alpha[..., lib.newaxis] * x1 + (1 - alpha[..., lib.newaxis]) * x2)
239 | u3.append(alpha * u1 + (1 - alpha) * u2
240 | + norm_f(D, x, x))
241 |
242 | u3 = lib.minimum(*u3)
243 | u3_point = self.tsitsiklis_update_point_sol(x1, x2, x3, D, u1, u2, lib=lib)
244 | u3_computed = lib.where(sqrt_invalid_mask, u3_point, u3)
245 | u3_final = u3_computed
246 |
247 | return u3_final
248 |
249 | def tsitsiklis_update_tetra_quadr(self, D, k, z1, z2, lib=np):
250 | """Computes the quadratic equation for the tetrahedra update in :meth:`calculate_tet_update`.
251 | """
252 | norm_f, norm_sqr_f = norm_map[lib][D.shape[-1]]
253 | p11 = norm_sqr_f(D, z1, z1)
254 | p12 = norm_sqr_f(D, z1, z2)
255 | p22 = norm_sqr_f(D, z2, z2)
256 | denominator = p11 - k*k
257 | sqrt_val = (p11 * p22 - (p12 * p12)) / denominator
258 | rhs = k * lib.sqrt(sqrt_val)
259 | alpha1 = -(p12 + rhs) / p11
260 | #alpha2 = -(p12 - rhs) / p11
261 |
262 | return alpha1 #, alpha2
263 |
264 | def tsitsiklis_update_tetra(self, x1, x2, x3, x4, D, u1, u2, u3, lib=np):
265 | """Computes the update inside a single tetrahedron by computing
266 |
267 | - the update inside the tetrahedron (:meth:`calculate_tet_update`)
268 | - the update on each face (:meth:`tsitsiklis_update_triang`)
269 |
270 | and taking the minimum across all possible values.
271 | For more information on the type and shape of the parameters and return value, see :meth:`tsitsiklis_update_line`.
272 | """
273 | u_tet = self.calculate_tet_update(x1, x2, x3, x4, D, u1, u2, u3, lib)
274 | u_tet = lib.where(lib.isnan(u_tet), lib.inf, u_tet)
275 |
276 | #Face calculations (Includes possible line calculations)
277 | u_triang = lib.minimum(self.tsitsiklis_update_triang(x1, x2, x4, D, u1, u2, lib),
278 | self.tsitsiklis_update_triang(x1, x3, x4, D, u1, u3, lib))
279 | u_triang = lib.minimum(u_triang,
280 | self.tsitsiklis_update_triang(x2, x3, x4, D, u2, u3, lib))
281 |
282 | return lib.minimum(u_triang, u_tet)
283 |
284 | def calculate_tet_update(self, x1, x2, x3, x4, D, u1, u2, u3, lib=np):
285 | """Computes the update inside a single tetrahedron as
286 |
287 | .. math::
288 | \\min_{\\lambda_1, \\lambda_2} \\lambda_1 u_1 + \\lambda_2 u_2 + \\lambda_3 u_3 + ||\\mathbf{x}_4 - \\mathbf{x}_{1, 2, 3}||_M
289 |
290 | for :math:`\\lambda_3 = 1 - \\lambda_1 - \\lambda_2` and :math:`\\mathbf{x}_{1, 2, 3} = \\lambda_1 \\mathbf{x}_1 + \\lambda_2 \\mathbf{x}_2 + \\lambda_3 \\mathbf{x}_3`.
291 | For more information on the type and shape of the parameters and return value, see :meth:`tsitsiklis_update_line`.
292 | """
293 | xs = lib.stack([x1, x2, x3, x4], axis=-1)
294 | us = lib.stack([u1, u2, u3], axis=-1)
295 | norm_f, norm_sqr_f = norm_map[lib][D.shape[-1]]
296 |
297 | y3 = x4 - x3
298 | y1 = x3 - x1
299 | y2 = x3 - x2
300 |
301 | k1 = u1 - u3
302 | k2 = u2 - u3
303 | #k3 = u3
304 |
305 | r11 = norm_sqr_f(D, y1, y1)
306 | r12 = norm_sqr_f(D, y1, y2)
307 | r13 = norm_sqr_f(D, y1, y3)
308 | r21 = r12
309 | r22 = norm_sqr_f(D, y2, y2)
310 | r23 = norm_sqr_f(D, y2, y3)
311 | r31 = r13
312 | r32 = r23
313 | #r33 = norm_sqr_f(D, y3, y3)
314 |
315 | A1 = k2 * r11 - k1 * r12
316 | A2 = k2 * r21 - k1 * r22
317 | B = k2 * r31 - k1 * r32
318 | k = k1 - A1 / A2 * k2
319 | #u = k3 - B / A2 * k2
320 | z1 = y1 - (A1 /A2)[..., lib.newaxis] * y2
321 | z2 = y3 - (B / A2)[..., lib.newaxis] * y2
322 |
323 | alpha1 = self.tsitsiklis_update_tetra_quadr(D, k, z1, z2, lib)
324 | alpha2 = -(B + alpha1 * A1) / A2
325 |
326 | special_case1 = ((A1 == 0) & (A2 == 0))
327 | alpha1 = lib.where(special_case1, (r12 * r23 - r13 * r22) / (r11 * r22 - (r12 * r12)), alpha1)
328 | alpha2 = lib.where(special_case1, (r12 * r13 - r11 * r23) / (r11 * r22 - (r12 * r12)), alpha2)
329 |
330 | special_case2 = ((A1 == 0) & ~special_case1)
331 | alpha1 = lib.where(special_case2, 0, alpha1)
332 | alpha2 = lib.where(special_case2, -B / A2, alpha2)
333 |
334 | special_case3 = ((A2 == 0) & ~special_case1 & ~special_case2)
335 | alpha1 = lib.where(special_case3, -B / A1, alpha1)
336 | alpha2 = lib.where(special_case3, 0, alpha2)
337 |
338 | alphas = lib.stack([alpha1, alpha2, 1 - alpha1 - alpha2], axis=-1)
339 | if alphas.ndim == xs.ndim - 1:
340 | alphas = alphas[..., lib.newaxis, :]
341 |
342 | dist = x4 - lib.sum(xs[..., :-1] * alphas, axis=-1) #dist = x4 - (alpha1 * x1 + alpha2 * x2 + alpha3 * x3)
343 | alphas = lib.squeeze(alphas)
344 | return lib.where(lib.any((alphas < 0) | (alphas > 1), axis=-1), lib.inf, norm_f(D, dist, dist) + lib.sum(alphas * us, axis=-1)) #(alpha1 * u1 + alpha2 * u2 + alpha3 * u3)
345 |
346 |
347 |
348 | def calculate_specific_triang_updates(self, elems_perm, xs_perm, D, us, lib=np):
349 | us_new = us.copy()
350 |
351 | #perms = np.array([[0, 1, 2], [0, 2, 1], [1, 2, 0]])
352 | us_perm = us[elems_perm]
353 |
354 | us_result = self.tsitsiklis_update_triang(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :],
355 | D, us_perm[..., 0], us_perm[..., 1], lib=lib)
356 |
357 | #Now we need to take the minimum result of old and all new
358 | lib.minimum.at(us_new, elems_perm[..., -1], us_result)
359 |
360 | return us_new
361 |
362 | def calculate_specific_line_updates(self, elems_perm, xs_perm, D, us, lib=np):
363 | us_new = us.copy()
364 | us_perm = us[elems_perm]
365 | us_result = self.tsitsiklis_update_line(xs_perm[..., 0, :], xs_perm[..., 1, :],
366 | D, us_perm[..., 0], lib=lib)
367 | lib.minimum.at(us_new, elems_perm[..., -1], us_result)
368 |
369 | return us_new
370 |
371 | def calculate_all_line_updates(self, elems_perm, xs_perm, D, us, lib=np):
372 | """Calculates all lines updates for all element permutations and computes their minimum as the new solution of :math:`\\phi`.
373 |
374 | Parameters
375 | ----------
376 | elems_perm : ndarray (int)
377 | All point permutations obtained using :meth:`compute_unique_elem_permutations`
378 | xs_perm : ndarray (float)
379 | All point coordinate permutations as an :math:`[M, d_e, d_e, d]` array.
380 | D : ndarray (float)
381 | An [M, d, d] array containing :math:`D`.
382 | us : ndarray (float)
383 | An [N] array containing the current solution of :math:`\\phi_k`.
384 | lib : library, optional
385 | Library to use for the computations, by default np
386 |
387 | Returns
388 | -------
389 | ndarray (float)
390 | An [N] array holding the new solution :math:`\\phi_{k+1}`.
391 | """
392 | us_new = us.copy()
393 | us_perm = us[elems_perm]
394 | D_broadcasted = D[..., lib.newaxis, :, :] #Add permutation dimension
395 |
396 | us_result = self.tsitsiklis_update_line(xs_perm[..., 0, :], xs_perm[..., 1, :],
397 | D_broadcasted, us_perm[..., 0], lib=lib)
398 | lib.minimum.at(us_new, elems_perm[..., -1], us_result)
399 |
400 | return us_new
401 |
402 | def calculate_all_triang_updates(self, elems_perm, xs_perm, D, us, lib=np):
403 | """Calculates all triangle updates for all element permutations and computes their minimum as the new solution of :math:`\\phi`.
404 | For more details on the parameters and return values, see :meth:`calculate_all_line_updates`.
405 | """
406 | us_new = us.copy()
407 |
408 | us_perm = us[elems_perm]
409 | D_broadcasted = D[..., lib.newaxis, :, :] #Add permutation dimension
410 |
411 | us_result = self.tsitsiklis_update_triang(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :],
412 | D_broadcasted, us_perm[..., 0], us_perm[..., 1], lib=lib)
413 |
414 | #Now we need to take the minimum result of old and all new
415 | lib.minimum.at(us_new, elems_perm[..., -1], us_result)
416 |
417 | return us_new
418 |
419 | def calculate_all_tetra_updates(self, elems_perm, xs_perm, D, us, lib=np):
420 | """Calculates all tetrahedral updates for all element permutations and computes their minimum as the new solution of :math:`\\phi`.
421 | For more details on the parameters and return values, see :meth:`calculate_all_line_updates`.
422 | """
423 | us_new = us.copy()
424 | us_perm = us[elems_perm]
425 | D_broadcasted = D[..., lib.newaxis, :, :] #Add permutation dimension
426 |
427 | us_result = self.tsitsiklis_update_tetra(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :], xs_perm[..., 3, :],
428 | D_broadcasted, us_perm[..., 0], us_perm[..., 1], us_perm[..., 2], lib=lib)
429 | lib.minimum.at(us_new, elems_perm[..., -1], us_result)
430 |
431 | return us_new
432 |
433 | def calculate_specific_tetra_updates(self, elems_perm, xs_perm, D, us, lib=np):
434 | us_new = us.copy()
435 | us_perm = us[elems_perm]
436 | us_result = self.tsitsiklis_update_tetra(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :], xs_perm[..., 3, :],
437 | D, us_perm[..., 0], us_perm[..., 1], us_perm[..., 2], lib=lib)
438 | lib.minimum.at(us_new, elems_perm[..., -1], us_result)
439 |
440 | return us_new
441 |
442 |
443 | @abstractmethod
444 | def _comp_fim(self, x0, x0_vals, metrics=None, max_iterations=int(1e10)):
445 | """Internal call to the concrete implementation of the FIM (see :meth:`comp_fim` for the parameter description).
446 | """
447 | ... # pragma: no cover
448 |
449 | def comp_fim(self, x0, x0_vals, metrics=None, max_iterations=int(1e10)):
450 | """Computes the solution :math:`\\phi` to the anisotropic eikonal equation
451 |
452 | .. math::
453 | \\left\\{
454 | \\begin{array}{rll}
455 | \\left<\\nabla \\phi, D \\nabla \\phi \\right> &= 1 \\quad &\\text{on} \\; \\Omega \\\\
456 | \\phi(\\mathbf{x}_0) &= g(\\mathbf{x}_0) \\quad &\\text{on} \\; \\Gamma
457 | \\end{array}
458 | \\right. .
459 |
460 | Parameters
461 | ----------
462 | x0 : ndarray (int)
463 | Array of [k] discrete point indices of the mesh where we prescribe initial values :math:`\\mathbf{x}_0`.
464 | x0_vals : ndarray (float)
465 | Array of [k] discrete prescribed initial values that prescribe :math:`g(\\mathbf{x}_0)`.
466 | metrics : np.ndarray(float), optional
467 | Specifies the tensor :math:`D` of the anisotropic eikonal equation as a discrete [m, d, d] array.
468 | This is optional **only** if you specified the metrics already at construction time (:class:`FIMBase`), by default None
469 | max_iterations : int, optional
470 | Maximum number of iterations before aborting the algorithm.
471 | If the algorithm stops before reaching convergence, some vertices might still be set to :attr:`undef_val`.
472 | By default int(1e10)
473 |
474 | Returns
475 | -------
476 | ndarray (float, cupy or numpy)
477 | The solution to the anisotropic eikonal equation, :math:`\\phi` as a [n] array.
478 | """
479 | #Suppress warnings of the computations, since they should be handled internally
480 | with np.errstate(divide='ignore', invalid='ignore', over='ignore'):
481 | #TODO: Maybe use identity in this case?
482 | assert metrics is not None or self.metrics is not None, f"Metrics (D) need to be provided in comp_fim, or at construction in __init__"
483 | if metrics is not None:
484 | self.check_metrics_argument(metrics)
485 | metrics = np.linalg.inv(metrics).astype(self.precision) #The inverse metric is used in the FIM algorithm
486 |
487 | return self._comp_fim(x0, x0_vals, metrics, max_iterations=max_iterations)
488 |
--------------------------------------------------------------------------------
/fimpy/fim_cupy.py:
--------------------------------------------------------------------------------
1 | """This file contains the GPU implementation of the Fast Iterative Method, based on cupy.
2 | """
3 |
4 | import numpy as np
5 |
6 | #Workaround for readthedocs
7 | try:
8 | import cupy as cp
9 | import cupyx as cpx
10 | from .utils.comp import metric_norm_matrix_2D_cupy, metric_norm_matrix_3D_cupy, metric_norm_matrix, metric_sqr_norm_matrix_2D_cupy, metric_sqr_norm_matrix_3D_cupy, metric_sqr_norm_matrix
11 | cupy_enabled = True
12 | except ImportError as err:
13 | cupy_enabled = False
14 |
15 | from .fim_base import FIMBase
16 | from .cupy_kernels import compute_perm_kernel_str, compute_perm_kernel_shared
17 |
18 | if cupy_enabled:
19 | @cp.fuse()
20 | def u3_comp_cupy_2D(x1, x2, x3, u1, u2, D):
21 | """Custom cupy implementation of :meth:`fimpy.fim_base.FIMBase.tsitsiklis_update_triang` to speed up computations for :math:`d = 2`.
22 | """
23 | k = u1 - u2
24 | z2 = x2 - x3
25 | z1 = x1 - x2
26 | p11 = metric_sqr_norm_matrix_2D_cupy(D, z1, z1)
27 | p12 = metric_sqr_norm_matrix_2D_cupy(D, z1, z2)
28 | p22 = metric_sqr_norm_matrix_2D_cupy(D, z2, z2)
29 | denominator = p11 - k**2
30 | sqrt_val = (p11 * p22 - p12**2) / denominator
31 | sqrt_invalid_mask = sqrt_val < 0.
32 | sqrt_op = cp.sqrt(sqrt_val)
33 | rhs = k * sqrt_op
34 | alpha1 = -(p12 + rhs) / p11
35 | alpha2 = -(p12 - rhs) / p11
36 | alpha1 = cp.minimum(cp.maximum(alpha1, 0.), 1.)
37 | alpha2 = cp.minimum(cp.maximum(alpha2, 0.), 1.)
38 |
39 | u3 = []
40 | for alpha in [alpha1, alpha2]:
41 | x = x3 - (alpha[..., cp.newaxis] * x1 + (1 - alpha[..., cp.newaxis]) * x2)
42 | u3.append(alpha * u1 + (1 - alpha) * u2
43 | + metric_norm_matrix_2D_cupy(D, x, x))
44 |
45 | return cp.minimum(*u3), sqrt_invalid_mask
46 |
47 | #@cp.fuse()
48 | def u3_comp_cupy_3D(x1, x2, x3, u1, u2, D):
49 | """Custom cupy implementation of :meth:`fimpy.fim_base.FIMBase.tsitsiklis_update_triang` to speed up computations for :math:`d = 3`.
50 | """
51 | k = u1 - u2
52 | z2 = x2 - x3
53 | z1 = x1 - x2
54 | p11 = metric_sqr_norm_matrix_3D_cupy(D, z1, z1)
55 | p12 = metric_sqr_norm_matrix_3D_cupy(D, z1, z2)
56 | p22 = metric_sqr_norm_matrix_3D_cupy(D, z2, z2)
57 | denominator = p11 - k**2
58 | sqrt_val = (p11 * p22 - p12**2) / denominator
59 | sqrt_invalid_mask = sqrt_val < 0.
60 | sqrt_op = cp.sqrt(sqrt_val)
61 | rhs = k * sqrt_op
62 | alpha1 = -(p12 + rhs) / p11
63 | alpha2 = -(p12 - rhs) / p11
64 | alpha1 = cp.minimum(cp.maximum(alpha1, 0.), 1.)
65 | alpha2 = cp.minimum(cp.maximum(alpha2, 0.), 1.)
66 |
67 | u3 = []
68 | for alpha in [alpha1, alpha2]:
69 | x = x3 - (alpha[..., cp.newaxis] * x1 + (1 - alpha[..., cp.newaxis]) * x2)
70 | u3.append(alpha * u1 + (1 - alpha) * u2
71 | + metric_norm_matrix_3D_cupy(D, x, x))
72 |
73 | return cp.minimum(*u3), sqrt_invalid_mask
74 |
75 |
76 | #@cp.fuse() #TODO: formal parameter space overflow
77 | def u3_comp_cupy_ND(x1, x2, x3, u1, u2, D):
78 | """Custom cupy implementation of :meth:`fimpy.fim_base.FIMBase.tsitsiklis_update_triang` to speed up computations for :math:`d \notin \{2, 3\}`.
79 | """
80 | #p11, p12, sqrt_invalid_mask, rhs = u3_comp_cupy_ND_part1(x1, x2, x3, u1, u2, D)
81 | #return u3_comp_cupy_ND_part2(p11, p12, rhs, x1, x2, x3, u1, u2, D), sqrt_invalid_mask
82 | k = u1 - u2
83 | z2 = x2 - x3
84 | z1 = x1 - x2
85 | p11 = metric_sqr_norm_matrix(D, z1, z1, cp)
86 | p12 = metric_sqr_norm_matrix(D, z1, z2, cp)
87 | p22 = metric_sqr_norm_matrix(D, z2, z2, cp)
88 | denominator = p11 - k**2
89 | sqrt_val = (p11 * p22 - p12**2) / denominator
90 | sqrt_invalid_mask = sqrt_val < 0.
91 | sqrt_op = cp.sqrt(sqrt_val)
92 | rhs = k * sqrt_op
93 | alpha1 = -(p12 + rhs) / p11
94 | alpha2 = -(p12 - rhs) / p11
95 | alpha1 = cp.minimum(cp.maximum(alpha1, 0.), 1.)
96 | alpha2 = cp.minimum(cp.maximum(alpha2, 0.), 1.)
97 |
98 | u3 = []
99 | for alpha in [alpha1, alpha2]:
100 | x = x3 - (alpha[..., cp.newaxis] * x1 + (1 - alpha[..., cp.newaxis]) * x2)
101 | u3.append(alpha * u1 + (1 - alpha) * u2
102 | + metric_norm_matrix(D, x, x, cp))
103 |
104 | return cp.minimum(*u3), sqrt_invalid_mask
105 |
106 | @cp.fuse()
107 | def tsitsiklis_update_tetra_quadr_cupy_3D(D, k, z1, z2):
108 | """Custom cupy implementation of :meth:`fimpy.fim_base.FIMBase.tsitsiklis_update_tetra_quadr` to speed up computations for :math:`d = 3`.
109 | """
110 | norm_sqr_f = metric_sqr_norm_matrix_3D_cupy
111 | p11 = norm_sqr_f(D, z1, z1)
112 | p12 = norm_sqr_f(D, z1, z2)
113 | p22 = norm_sqr_f(D, z2, z2)
114 | denominator = p11 - k*k
115 | sqrt_val = (p11 * p22 - (p12 * p12)) / denominator
116 | rhs = k * cp.sqrt(sqrt_val)
117 | alpha1 = -(p12 + rhs) / p11
118 | #alpha2 = -(p12 - rhs) / p11
119 |
120 | return alpha1 #, alpha2
121 |
122 | class FIMCupy(FIMBase):
123 | """This class implements the Fast Iterative Method on the GPU using cupy.
124 | The employed algorithm is the Jacobi algorithm, updating all nodes in each iteration.
125 | For details on the parameters, see :class:`fimpy.fim_base.FIMBase`.
126 | """
127 | def __init__(self, points, elems, metrics=None, precision=np.float32):
128 | super(FIMCupy, self).__init__(points, elems, metrics, precision, comp_connectivities=False)
129 | #Convert
130 | #self.nh_map = cp.array(self.nh_map)
131 | #self.point_elem_map = cp.array(self.point_elem_map)
132 | self.phi_sol = cp.array(self.phi_sol)
133 | self.points_perm = cp.array(self.points_perm)
134 | self.elems_perm = cp.array(self.elems_perm)
135 |
136 | if self.metrics is not None:
137 | self.metrics = cp.array(self.metrics)
138 |
139 | self.streams = [cp.cuda.Stream(non_blocking=False) for i in range(4)]
140 | self.mempool = cp.get_default_memory_pool()
141 |
142 | def free_gpu_mem(self):
143 | self.mempool.free_all_blocks()
144 |
145 | def calculate_all_line_updates(self, elems_perm, xs_perm, D, us, lib=np):
146 | us_new = us.copy()
147 | us_perm = us[elems_perm]
148 | D_broadcasted = D[..., cp.newaxis, :, :] #Add permutation dimension
149 |
150 | us_result = self.tsitsiklis_update_line(xs_perm[..., 0, :], xs_perm[..., 1, :],
151 | D_broadcasted, us_perm[..., 0], lib=cp)
152 | cp.minimum.at(us_new, elems_perm[..., -1], us_result)
153 |
154 | return us_new
155 |
156 | def calculate_all_triang_updates(self, elems_perm, xs_perm, D, us, lib=np):
157 | us_new = us.copy()
158 | us_perm = us[elems_perm]
159 | D_broadcasted = D[..., lib.newaxis, :, :]
160 |
161 | us_result = self.tsitsiklis_update_triang(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :],
162 | D_broadcasted, us_perm[..., 0], us_perm[..., 1], lib=lib)
163 |
164 | cp.minimum.at(us_new, elems_perm[..., -1], us_result)
165 | return us_new
166 |
167 | def tsitsiklis_update_tetra(self, x1, x2, x3, x4, D, u1, u2, u3, lib=np):
168 |
169 | with self.streams[0]:
170 | u_tet = self.calculate_tet_update(x1, x2, x3, x4, D, u1, u2, u3, cp)
171 | u_tet = lib.where(cp.isnan(u_tet), lib.inf, u_tet)
172 |
173 | #Face calculations (Includes possible line calculations)
174 | with self.streams[1]:
175 | triang1 = self.tsitsiklis_update_triang(x1, x2, x4, D, u1, u2, cp)
176 | with self.streams[2]:
177 | triang2 = self.tsitsiklis_update_triang(x1, x3, x4, D, u1, u3, cp)
178 | with self.streams[3]:
179 | triang3 = self.tsitsiklis_update_triang(x2, x3, x4, D, u2, u3, cp)
180 |
181 | u_triang = lib.minimum(triang1, triang2)
182 | u_triang = lib.minimum(u_triang, triang3)
183 |
184 | return lib.minimum(u_triang, u_tet)
185 |
186 | def calculate_all_tetra_updates(self, elems_perm, xs_perm, D, us, lib=np):
187 | us_new = us.copy()
188 | us_perm = us[elems_perm]
189 | D_broadcasted = D[..., cp.newaxis, :, :] #Add permutation dimension
190 |
191 | us_result = self.tsitsiklis_update_tetra(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :], xs_perm[..., 3, :],
192 | D_broadcasted, us_perm[..., 0], us_perm[..., 1], us_perm[..., 2], lib=cp)
193 | cp.minimum.at(us_new, elems_perm[..., -1], us_result)
194 |
195 | return us_new
196 |
197 |
198 | def _comp_fim(self, x0, x0_vals, metrics=None, max_iterations=int(1e10)):
199 | if metrics is None:
200 | metrics = self.metrics
201 |
202 | D = metrics
203 | self.phi_sol[:] = self.undef_val
204 | self.phi_sol[x0] = x0_vals
205 |
206 | if type(D) != cp.ndarray:
207 | D = cp.array(D)
208 |
209 | if D.dtype != self.precision:
210 | D = D.astype(self.precision)
211 |
212 | for i in range(max_iterations):
213 | u_new = self.update_all_points(self.elems_perm, self.points_perm, D, self.phi_sol,
214 | lib=cp)
215 |
216 | if cp.allclose(u_new, self.phi_sol):
217 | break
218 |
219 | self.phi_sol = u_new
220 |
221 | self.phi_sol = u_new
222 |
223 | return self.phi_sol.copy()
224 |
225 |
226 | def tsitsiklis_update_tetra_quadr(self, D, k, z1, z2, lib=np):
227 | if self.dims == 3:
228 | return tsitsiklis_update_tetra_quadr_cupy_3D(D, k, z1, z2)
229 | else:
230 | return super().tsitsiklis_update_tetra_quadr(D, k, z1, z2, cp)
231 |
232 |
233 | class FIMCupyAL(FIMBase):
234 | """This class implements the Fast Iterative Method on the GPU using cupy.
235 | The employed algorithm is the active list algorithm (as proposed in the original paper), updating only a current estimation of the wavefront.
236 | For details on the parameters, see :class:`fimpy.fim_base.FIMBase`.
237 | """
238 |
239 | def __init__(self, points, elems, metrics=None, precision=np.float32):
240 | super(FIMCupyAL, self).__init__(points, elems, metrics, precision, comp_connectivities=True)
241 | #Convert
242 | #self.build_linear_nh_elem_map()
243 | self.nh_map = cp.array(self.nh_map)
244 | self.point_elem_map = cp.array(self.point_elem_map)
245 | self.phi_sol = cp.array(self.phi_sol)
246 | self.points_perm = cp.array(self.points_perm)
247 | self.elems_perm = cp.array(self.elems_perm)
248 |
249 | if self.metrics is not None:
250 | self.metrics = cp.array(self.metrics)
251 |
252 | self.active_list = cp.array(self.active_list)
253 | self.mempool = cp.get_default_memory_pool()
254 |
255 | if self.dims == 2:
256 | self.u3_comp_cupy = u3_comp_cupy_2D
257 | elif self.dims == 3:
258 | self.u3_comp_cupy = u3_comp_cupy_3D
259 | else:
260 | self.u3_comp_cupy = u3_comp_cupy_ND
261 |
262 | self.parallel_blocks_perm_kernel = 128
263 | #self.block_dims = (1024,)
264 | #self.perm_kernel = cp.RawKernel(compute_perm_kernel_str.replace("{active_perms}", str(self.elem_dims)).replace("{parallel_blocks}", str(self.parallel_blocks_perm_kernel)),
265 | # 'perm_kernel') #, backend='nvcc') #, options=("--device-c",))
266 |
267 | #self.block_dims = (64, 16,1) #Old
268 | self.block_dims = (1024, 1,1)
269 | self.perm_kernel = cp.RawKernel(compute_perm_kernel_shared.replace("{active_perms}", str(self.elem_dims)).replace("{parallel_blocks}", str(self.parallel_blocks_perm_kernel)).replace("{shared_buf_size}", str(4096)),
270 | 'perm_kernel', options=('-std=c++11',)) #, backend='nvcc') #, options=("--device-c",))
271 | self.streams = [cp.cuda.Stream(non_blocking=False) for i in range(7)]
272 |
273 | #To replace cp.unique
274 | self.elem_unique_map = cp.zeros(shape=[self.nr_elems], dtype=cp.int32)
275 | self.elem_ones = cp.ones(shape=[self.nr_elems], dtype=cp.int32)
276 | self.points_unique_map = cp.zeros(shape=[self.nr_points], dtype=cp.int32)
277 | self.points_ones = cp.ones(shape=[self.nr_points], dtype=cp.int32)
278 |
279 | def comp_unique_map(self, inds, elem_map=True):
280 | """Efficient implementation to compute an unique list of indices of active elements/points
281 |
282 | Parameters
283 | ----------
284 | inds : ndarray (int)
285 | An [?] array containing the non-unique active element/point indices
286 | elem_map : bool, optional
287 | Marks if the unique indices you want to compute are point or element indices, by default True
288 |
289 | Returns
290 | -------
291 | ndarray (int)
292 | An [?] array holding the indices of the unique element/point indices.
293 | """
294 | if elem_map:
295 | cp.add.at(self.elem_unique_map, inds, self.elem_ones[inds])
296 | unique_inds = self.elem_unique_map.nonzero()[0]
297 | self.elem_unique_map[:] = 0 #Reset for next run
298 | else:
299 | cp.add.at(self.points_unique_map, inds, self.points_ones[inds])
300 | unique_inds = self.points_unique_map.nonzero()[0]
301 | self.points_unique_map[:] = 0 #Reset for next run
302 |
303 | return unique_inds
304 |
305 | def free_gpu_mem(self):
306 | self.mempool.free_all_blocks()
307 |
308 | def tsitsiklis_update_triang(self, x1, x2, x3, D, u1, u2, lib=np, use_streams=None):
309 |
310 | #Called for non tetra meshes -> Streams are available
311 | if self.elem_dims == 3:
312 | assert(use_streams is None)
313 | with self.streams[0]:
314 | u3, sqrt_invalid_mask = self.u3_comp_cupy(x1, x2, x3, u1, u2, D)
315 |
316 | with self.streams[1]:
317 | u3_point = self.tsitsiklis_update_point_sol(x1, x2, x3, D, u1, u2, lib=lib)
318 |
319 | #Use specific streams given by the calling function
320 | else:
321 | assert(use_streams is not None and len(use_streams) == 2)
322 | with use_streams[0]:
323 | u3, sqrt_invalid_mask = self.u3_comp_cupy(x1, x2, x3, u1, u2, D)
324 | with use_streams[1]:
325 | u3_point = self.tsitsiklis_update_point_sol(x1, x2, x3, D, u1, u2, lib=lib)
326 |
327 | #u3_point = u3_point_sol_cupy_2D(x1, x2, x3, D, u1, u2)
328 | u3_computed = lib.where(sqrt_invalid_mask, u3_point, u3)
329 | u3_final = u3_computed
330 |
331 | return u3_final
332 |
333 | def calculate_specific_triang_updates(self, elems_perm, xs_perm, D, us, lib=np):
334 | us_new = us.copy()
335 |
336 | us_perm = us[elems_perm]
337 |
338 | us_result = self.tsitsiklis_update_triang(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :],
339 | D, us_perm[..., 0], us_perm[..., 1], lib=lib)
340 |
341 | #Now we need to take the minimum result of old and all new
342 | cp.minimum.at(us_new, elems_perm[..., -1], us_result)
343 |
344 | return us_new
345 |
346 | def calculate_specific_line_updates(self, elems_perm, xs_perm, D, us, lib=np):
347 | us_new = us.copy()
348 | us_perm = us[elems_perm]
349 | us_result = self.tsitsiklis_update_line(xs_perm[..., 0, :], xs_perm[..., 1, :],
350 | D, us_perm[..., 0], lib=lib)
351 | cp.minimum.at(us_new, elems_perm[..., -1], us_result)
352 |
353 | return us_new
354 |
355 | def tsitsiklis_update_tetra(self, x1, x2, x3, x4, D, u1, u2, u3, lib=np):
356 |
357 | with self.streams[0]:
358 | u_tet = self.calculate_tet_update(x1, x2, x3, x4, D, u1, u2, u3, cp)
359 | u_tet = lib.where(cp.isnan(u_tet), lib.inf, u_tet)
360 |
361 | #Face calculations (Includes possible line calculations)
362 | triang1 = self.tsitsiklis_update_triang(x1, x2, x4, D, u1, u2, cp, (self.streams[1], self.streams[2]))
363 | triang2 = self.tsitsiklis_update_triang(x1, x3, x4, D, u1, u3, cp, (self.streams[3], self.streams[4]))
364 | triang3 = self.tsitsiklis_update_triang(x2, x3, x4, D, u2, u3, cp, (self.streams[5], self.streams[6]))
365 |
366 | u_triang = lib.minimum(triang1, triang2)
367 | u_triang = lib.minimum(u_triang, triang3)
368 |
369 | return lib.minimum(u_triang, u_tet)
370 |
371 | def tsitsiklis_update_tetra_quadr(self, D, k, z1, z2, lib=np):
372 | if self.dims == 3:
373 | return tsitsiklis_update_tetra_quadr_cupy_3D(D, k, z1, z2)
374 | else:
375 | return super().tsitsiklis_update_tetra_quadr(D, k, z1, z2, cp)
376 |
377 | def calculate_specific_tetra_updates(self, elems_perm, xs_perm, D, us, lib=np):
378 | us_new = us.copy()
379 | us_perm = us[elems_perm]
380 | us_result = self.tsitsiklis_update_tetra(xs_perm[..., 0, :], xs_perm[..., 1, :], xs_perm[..., 2, :], xs_perm[..., 3, :],
381 | D, us_perm[..., 0], us_perm[..., 1], us_perm[..., 2], lib=cp)
382 | cp.minimum.at(us_new, elems_perm[..., -1], us_result)
383 |
384 | return us_new
385 |
386 | def comp_marked_points(self, phi, D, active_inds, use_buffered_vals=False):
387 | """Computes the update of only the desired points.
388 |
389 | Parameters
390 | ----------
391 | phi : np.ndarray (precision)
392 | [N] array of the values for :math:`\\phi_i` to be used for the update.
393 | D : np.ndarray (precision)
394 | [M, d, d] array of :math:`M` to be used for the updates.
395 | active_inds : np.ndarray (int)
396 | [?] array of indices that will be updated
397 |
398 | Returns
399 | -------
400 | np.ndarray (precision)
401 | [N] array holding the updated values :math:`\\phi_{i+1}` where only indices found in ``active_inds`` were updated.
402 | """
403 | if active_inds.size == 0:
404 | return phi
405 |
406 | if not use_buffered_vals:
407 | #"""
408 | #active_elem_mask = np.any(self.elems[:, np.newaxis, :] == active_inds[np.newaxis, :, np.newaxis], axis=(-1, -2))
409 | #active_elem_inds = active_elem_mask.nonzero()[0]
410 | #tmp = cp.sort(self.point_elem_map[active_inds].reshape([-1])) #Performance test -> Future possible implementation
411 | #active_elem_inds = cp.unique(self.point_elem_map[active_inds]) #Compute only what's necessary #cp.unique(self.point_elem_map[active_inds].reshape([-1]))
412 | active_elem_inds = self.comp_unique_map(self.point_elem_map[active_inds].reshape([-1]), elem_map=True)
413 | #active_elem_inds = self.point_elem_map[active_inds].reshape([-1]) #Redundant computations
414 | active_elems_perm = self.elems_perm[active_elem_inds]
415 |
416 | #Custom kernel to avoid the huge memory overhead for comparisons
417 | perm_mask_output = cp.zeros(shape=active_elems_perm.shape[0:2], dtype=bool)
418 | #self.perm_kernel((1,), (1,), (cp.ascontiguousarray(active_elems_perm[..., -1].T), active_inds.astype(cp.int32), perm_mask_output, active_elems_perm.shape[0], active_inds.size))
419 | self.perm_kernel((self.parallel_blocks_perm_kernel,), self.block_dims, (cp.ascontiguousarray(active_elems_perm[..., -1]), active_inds.astype(cp.int32), perm_mask_output, active_elems_perm.shape[0], active_inds.size))
420 | #perm_mask_output = perm_mask_output.T
421 |
422 | #For testing
423 | #perm_mask = cp.any(active_elems_perm[..., -1, np.newaxis] == active_inds[np.newaxis, np.newaxis], axis=-1)
424 | #assert(cp.all(perm_mask == perm_mask_output))
425 |
426 | perm_inds = perm_mask_output.nonzero()
427 | #perm_cnts = np.sum(perm_mask, axis=-1)
428 | #perm_cumsum = np.concatenate([[0], np.cumsum(perm_cnts)])
429 | #assert (cp.all(cp.sum(perm_mask, axis=-1) > 0))
430 |
431 | self.active_elems_perm = active_elems_perm[perm_inds] # = self.elems_perm[active_elem_inds][perm_mask]
432 | self.active_points_perm = self.points_perm[active_elem_inds][perm_inds]
433 | #active_D = D[active_elem_inds]
434 | #active_D = D[active_elems_perm]
435 | self.active_D = D[active_elem_inds][perm_inds[0]] #cp.tile(D[active_elem_inds, np.newaxis], [1, active_elems_perm.shape[1], 1, 1])[perm_inds]
436 | #"""
437 | #active_elem_inds = cp.unique(self.point_elem_map[active_inds])
438 | #self.active_elems_perm, self.active_points_perm, self.active_D = tmp(self.elems_perm, self.point_elem_map, self.points_perm, D, active_inds, active_elem_inds)
439 | #active_elem_inds, active_elems_perm, active_points_perm, perm_inds, active_D = comp_marked_points_fuse(active_inds, self.point_elem_map, self.elems_perm)
440 | #active_elem_inds, active_elems_perm, perm_inds = comp_marked_points_njit(active_inds, self.point_elem_map, self.elems_perm)
441 | #active_elems_perm = active_elems_perm[perm_inds]
442 | #active_points_perm = self.points_perm[active_elem_inds][perm_inds]
443 | #active_D = np.tile(D[active_elem_inds, np.newaxis], [1, active_elems_perm.shape[1], 1, 1])[perm_inds]
444 |
445 | u_new = self.update_specific_points(self.active_elems_perm, # self.elems_perm,
446 | self.active_points_perm, #self.points_perm,
447 | self.active_D,
448 | phi,
449 | lib=cp)
450 |
451 | return u_new
452 |
453 |
454 | def _comp_fim(self, x0, x0_vals, metrics=None, max_iterations=int(1e10)):
455 | if metrics is None:
456 | metrics = self.metrics
457 |
458 | D = metrics
459 | self.phi_sol[:] = self.undef_val
460 | self.phi_sol[x0] = x0_vals
461 |
462 | if type(D) != cp.ndarray:
463 | D = cp.array(D)
464 |
465 | if D.dtype != self.precision:
466 | D = D.astype(self.precision)
467 |
468 | self.active_list[:] = False
469 | self.active_list[cp.unique(self.nh_map[x0])] = True
470 | update_al_interval = 1
471 | active_inds = self.active_list.nonzero()[0]
472 | for i in range(max_iterations):
473 | #active_points = self.points[self.active_list]
474 |
475 | u_new = self.comp_marked_points(self.phi_sol, D, active_inds, use_buffered_vals=(i != 0))
476 |
477 | if i % update_al_interval == 0:
478 | converged = ((cp.abs(u_new - self.phi_sol) < self.convergence_eps) & (self.active_list))
479 | converged_inds = converged.nonzero()[0]
480 | if converged_inds.size > 0:
481 | #converged_neighbors = cp.unique(self.nh_map[converged_inds])
482 | converged_neighbors = self.comp_unique_map(self.nh_map[converged_inds].reshape([-1]), elem_map=False)
483 | u_neighs = self.comp_marked_points(u_new, D, converged_neighbors)
484 | neighbors_needing_updates = converged_neighbors[((cp.abs(u_new[converged_neighbors] - u_neighs[converged_neighbors]) >= self.convergence_eps))]
485 | #Check if the neighbors converged
486 | self.active_list[converged_inds] = False #Remove converged points from the active list
487 | self.active_list[neighbors_needing_updates] = True #Add neighbors to the active list
488 | active_inds = self.active_list.nonzero()[0]
489 |
490 | #Use the newly computed values in the next iteration, since they are strictly smaller
491 | u_new = u_neighs
492 |
493 | if active_inds.size == 0: #cp.all(~self.active_list): #np.allclose(u_new, self.phi_sol, atol=self.convergence_eps):
494 | break
495 |
496 | self.phi_sol = u_new
497 |
498 | self.phi_sol = u_new
499 |
500 | return self.phi_sol.copy()
501 |
--------------------------------------------------------------------------------
/fimpy/fim_cutils/__init__.py:
--------------------------------------------------------------------------------
1 | """This subpackage contains the Cython implementations for multiple functions:
2 | * Generating the point to element maps
3 | * Generating the point to neighborhood maps
4 | * Computation of the permutation/active indices mask
5 |
6 | All of these are only used in solvers using the active list.
7 | """
8 |
9 | from .fim_cutils import compute_point_elem_map_c, compute_neighborhood_map_c, compute_perm_mask
10 |
--------------------------------------------------------------------------------
/fimpy/fim_cutils/fim_cutils.pyx:
--------------------------------------------------------------------------------
1 | # cython: infer_types=True
2 | # distutils: language=c++
3 | import numpy as np
4 | cimport cython
5 | from cython.parallel import prange
6 | from libcpp cimport bool as bool_t
7 |
8 | @cython.boundscheck(False)
9 | @cython.wraparound(False)
10 | def compute_point_elem_map_c(int[:, :] elems, int[:, :] point_elem_map):
11 | """Computes the point to element map, i.e. for each point the elements it is contained in.
12 | This function assumes all points are contained in at least one element.
13 |
14 | Parameters
15 | ----------
16 | elems : ndarray (int)
17 | An [M, d_e] array holding the mesh connectivity
18 | point_elem_map : ndarray (int)
19 | An [N, ?] array that will hold the result.
20 | Note that the last shape has to be at least long enough to hold the map for the point with the maximum number of contained elements.
21 | All points that are not contained in that many elements, will fill the array with the last occuring element index.
22 | """
23 | nr_elems = elems.shape[0]
24 | nr_points = point_elem_map.shape[0]
25 | max_point_elem_ratio = point_elem_map.shape[1]
26 | current_offsets_arr = np.zeros_like(point_elem_map[..., 0])
27 |
28 | cdef int[::1] current_offsets = current_offsets_arr
29 | cdef int offset, point
30 | for elem_i in range(nr_elems):
31 | for elem_j in range(elems.shape[1]):
32 | point = elems[elem_i, elem_j]
33 | offset = current_offsets[point]
34 | point_elem_map[point, offset] = elem_i
35 | current_offsets[point] += 1
36 |
37 | point_elem_map = point_elem_map[:, :np.max(current_offsets)]
38 | for point_i in range(nr_points):
39 | point_elem_map[point_i, current_offsets[point_i]:] = point_elem_map[point_i, current_offsets[point_i]-1]
40 |
41 | return point_elem_map
42 |
43 | @cython.boundscheck(False)
44 | @cython.wraparound(False)
45 | def compute_neighborhood_map_c(int[:, ::1] elems, int[:, ::1] nh_map):
46 | """Computes the point to neighborhood map, i.e. for each point the indices of its neighboring points.
47 | This function assumes all points are contained in at least one element.
48 |
49 | Parameters
50 | ----------
51 | elems : ndarray (int)
52 | An [M, d_e] array holding the mesh connectivity
53 | nh_map : ndarray (int)
54 | An [N, ?] array that will hold the result.
55 | Note that the last shape has to be at least long enough to hold the map for the point with the maximum number of neighbors.
56 | All points that do not have that many neighbors, will fill the array with the last occuring element index.
57 | """
58 | nh_map[:] = -1
59 | nr_points = nh_map.shape[0]
60 | nr_elems = elems.shape[0]
61 | current_offsets_arr = np.zeros_like(nh_map[..., 0])
62 | elem_range = np.arange(elems.shape[1], dtype=np.int32)
63 | cdef int[::1] inds, points, current_offsets
64 | cdef int point, offset, elem_i, single_ind, i, inds_size, elem_j, elem_dims
65 | elem_dims = elems.shape[1]
66 | current_offsets = current_offsets_arr
67 | inds = elem_range
68 | inds_size = elem_range.size
69 | for elem_i in range(nr_elems):
70 | points = elems[elem_i]
71 | for elem_j in prange(elem_dims, nogil=True):
72 | point = points[elem_j]
73 | #inds_arr = np.delete(elem_range, elem_j)
74 | #inds = inds_arr
75 | offset = current_offsets[point]
76 | #inds_size = inds.size
77 | for i in range(inds_size):
78 | if i != elem_j:
79 | single_ind = inds[i]
80 | nh_map[point, offset+i] = elems[elem_i, single_ind]
81 | current_offsets[point] += inds_size
82 |
83 | cdef int point_i, neigh_i, unique_neighs_size
84 | cdef int[::1] unique_neighs_view
85 | for point_i in range(nr_points):
86 | unique_neighs = np.unique(nh_map[point_i])
87 | unique_neighs = unique_neighs[unique_neighs != -1]
88 | unique_neighs_size = unique_neighs.size
89 | unique_neighs_view = unique_neighs
90 | for neigh_i in prange(nh_map.shape[1], nogil=True):
91 | if neigh_i < unique_neighs_size:
92 | nh_map[point_i, neigh_i] = unique_neighs_view[neigh_i]
93 | else:
94 | nh_map[point_i, neigh_i] = unique_neighs_view[unique_neighs_size-1]
95 |
96 |
97 | return nh_map
98 |
99 | @cython.boundscheck(False)
100 | @cython.wraparound(False)
101 | def compute_perm_mask(int[:, ::1] active_elems_perm, int[::1] active_inds):
102 | """Returns a mask with all active_elems_perm that have at least one active_inds in them.
103 | Equivalent to np.any(active_elems[..., np.newaxis] == active_inds[np.newaxis, np.newaxis], axis=-1), but does not require the full memory.
104 |
105 | Parameters
106 | ----------
107 | active_elems_perm : ndarray (int)
108 | An [a, b] array holding all the permuted element connectivities
109 | active_inds : ndarray (int)
110 | An [c] array with all active indices (points).
111 |
112 | Returns
113 | -------
114 | np.ndarray (bool)
115 | [a, b] array holding the computed mask.
116 | """
117 | cdef int nr_elems, nr_perms, nr_active_inds, elem_i, perm_i, active_i, active_ind
118 | nr_elems = active_elems_perm.shape[0]
119 | nr_perms = active_elems_perm.shape[1]
120 | nr_active_inds = active_inds.size
121 | perm_mask_arr = np.zeros(shape=[nr_elems, nr_perms], dtype=bool)
122 | cdef bool_t[:, ::1] perm_mask = perm_mask_arr
123 |
124 | for elem_i in prange(nr_elems, nogil=True):
125 | for perm_i in range(nr_perms):
126 | for active_i in range(nr_active_inds):
127 | if active_inds[active_i] == active_elems_perm[elem_i, perm_i]:
128 | perm_mask[elem_i, perm_i] = True
129 | break
130 |
131 | return perm_mask_arr
132 |
--------------------------------------------------------------------------------
/fimpy/fim_np.py:
--------------------------------------------------------------------------------
1 | """This file contains the CPU implementation of the Fast Iterative Method, based on numpy and cython.
2 | """
3 |
4 | from fimpy.utils.comp import metric_norm_matrix_3D_cython
5 | import numpy as np
6 | from .fim_base import FIMBase
7 | #from utils.nh_manager import calculate_all_triang_updates, calculate_specific_triang_updates
8 | from .fim_cutils import compute_perm_mask
9 |
10 | def tsitsiklis_update_triang_3D(x1, x2, x3, D, u1, u2, p11, p12, p22):
11 | """Custom numpy implementation of :meth:`fimpy.fim_base.FIMBase.tsitsiklis_update_triang` to speed up computations for :math:`d = 3`.
12 | """
13 | k = u1 - u2
14 | denominator = p11 - k**2
15 | sqrt_val = (p11 * p22 - p12**2) / denominator
16 | sqrt_invalid_mask = sqrt_val < 0.
17 | sqrt_op = np.sqrt(sqrt_val)
18 | rhs = k * sqrt_op
19 | alpha1 = -(p12 + rhs) / p11
20 | alpha2 = -(p12 - rhs) / p11
21 | alpha1 = np.minimum(np.maximum(alpha1, 0.), 1.)
22 | alpha2 = np.minimum(np.maximum(alpha2, 0.), 1.)
23 |
24 | u3 = []
25 | for alpha in [alpha1, alpha2]:
26 | x = x3 - (np.expand_dims(alpha, axis=-1) * x1 + (1 - np.expand_dims(alpha, axis=-1)) * x2)
27 | u3.append(alpha * u1 + (1 - alpha) * u2
28 | + metric_norm_matrix_3D_cython(D, x, x, ret_sqrt=True))
29 |
30 | return np.minimum(u3[0], u3[1]), sqrt_invalid_mask
31 |
32 |
33 | class FIMNP(FIMBase):
34 | """This class implements the Fast Iterative Method on the CPU using a combination of numpy and cython.
35 | The employed algorithm is the Jacobi algorithm, updating all nodes in each iteration.
36 | For details on the parameters, see :class:`fimpy.fim_base.FIMBase`.
37 | """
38 |
39 | def __init__(self, points, elems, metrics=None, precision=np.float32):
40 | super(FIMNP, self).__init__(points, elems, metrics, precision)
41 |
42 | def _comp_fim(self, x0, x0_vals, metrics=None, max_iterations=int(1e10)):
43 | if metrics is None:
44 | metrics = self.metrics
45 |
46 | D = metrics
47 | self.phi_sol = np.ones(shape=[self.nr_points], dtype=self.precision) * self.undef_val
48 | self.phi_sol[x0] = x0_vals
49 |
50 | if D.dtype != self.precision:
51 | D = D.astype(self.precision)
52 |
53 | for i in range(max_iterations):
54 | u_new = self.update_all_points(self.elems_perm, self.points_perm, D, self.phi_sol,
55 | lib=np)
56 |
57 | if np.allclose(u_new, self.phi_sol):
58 | break
59 |
60 | self.phi_sol = u_new
61 |
62 | self.phi_sol = u_new
63 |
64 | return self.phi_sol
65 |
66 | class FIMNPAL(FIMBase):
67 | """This class implements the Fast Iterative Method on the CPU using a combination of numpy and cython.
68 | The employed algorithm is the active list algorithm (as proposed in the original paper), updating only a current estimation of the wavefront.
69 | For details on the parameters, see :class:`fimpy.fim_base.FIMBase`.
70 | """
71 |
72 | def __init__(self, points, elems, metrics=None, precision=np.float32):
73 | super(FIMNPAL, self).__init__(points, elems, metrics, precision, comp_connectivities=True)
74 |
75 |
76 | def tsitsiklis_update_triang(self, x1, x2, x3, D, u1, u2, lib=np):
77 | """Custom numpy implementation of :meth:`fimpy.fim_base.FIMBase.tsitsiklis_update_triang` to speed up computations for :math:`d = 3`.
78 | """
79 |
80 | if self.dims == 3:
81 | z2 = x2 - x3
82 | z1 = x1 - x2
83 |
84 | p11 = metric_norm_matrix_3D_cython(D, x1=z1, x2=z1, ret_sqrt=False)
85 | p12 = metric_norm_matrix_3D_cython(D, x1=z1, x2=z2, ret_sqrt=False)
86 | p22 = metric_norm_matrix_3D_cython(D, x1=z2, x2=z2, ret_sqrt=False)
87 |
88 | u3, sqrt_invalid_mask = tsitsiklis_update_triang_3D(x1, x2, x3, D, u1, u2, p11, p12, p22)
89 | u3_point = self.tsitsiklis_update_point_sol(x1, x2, x3, D, u1, u2, lib=lib)
90 | u3_computed = lib.where(sqrt_invalid_mask, u3_point, u3)
91 | u3_final = u3_computed
92 |
93 | return u3_final
94 | else:
95 | return super(FIMNPAL, self).tsitsiklis_update_triang(x1, x2, x3, D, u1, u2)
96 |
97 | def comp_marked_points(self, phi, D, active_inds):
98 | """Computes the update of only the desired points.
99 |
100 | Parameters
101 | ----------
102 | phi : np.ndarray (precision)
103 | [N] array of the values for :math:`\\phi_i` to be used for the update.
104 | D : np.ndarray (precision)
105 | [M, d, d] array of :math:`M` to be used for the updates.
106 | active_inds : np.ndarray (int)
107 | [?] array of indices that will be updated
108 |
109 | Returns
110 | -------
111 | np.ndarray (precision)
112 | [N] array holding the updated values :math:`\\phi_{i+1}` where only indices found in ``active_inds`` were updated.
113 | """
114 |
115 | if active_inds.size == 0:
116 | return phi
117 |
118 | #active_elem_mask = np.any(self.elems[:, np.newaxis, :] == active_inds[np.newaxis, :, np.newaxis], axis=(-1, -2))
119 | #active_elem_inds = active_elem_mask.nonzero()[0]
120 | active_elem_inds = np.unique(self.point_elem_map[active_inds].reshape([-1]))
121 | active_elems_perm = self.elems_perm[active_elem_inds]
122 | #perm_mask = np.any(active_elems_perm[..., -1, np.newaxis] == active_inds[np.newaxis, np.newaxis], axis=-1)
123 | perm_mask = compute_perm_mask(np.ascontiguousarray(active_elems_perm[..., -1]), active_inds)
124 | #TODO: Testing
125 | #assert(np.all(perm_mask == np.any(active_elems_perm[..., -1, np.newaxis] == active_inds[np.newaxis, np.newaxis], axis=-1)))
126 | perm_inds = perm_mask.nonzero()
127 | #perm_cnts = np.sum(perm_mask, axis=-1)
128 | #perm_cumsum = np.concatenate([[0], np.cumsum(perm_cnts)])
129 | #assert (np.all(np.sum(perm_mask, axis=-1) > 0))
130 |
131 | active_elems_perm = active_elems_perm[perm_inds] # = self.elems_perm[active_elem_inds][perm_mask]
132 | active_points_perm = self.points_perm[active_elem_inds][perm_inds]
133 | #active_D = D[active_elem_inds]
134 | #active_D = D[active_elems_perm]
135 | active_D = D[active_elem_inds][perm_inds[0]]
136 | #active_D = np.tile(D[active_elem_inds, np.newaxis], [1, active_elems_perm.shape[1], 1, 1])[perm_inds]
137 |
138 | #active_elem_inds, active_elems_perm, perm_inds = comp_marked_points_njit(active_inds, self.point_elem_map, self.elems_perm)
139 | #active_elems_perm = active_elems_perm[perm_inds]
140 | #active_points_perm = self.points_perm[active_elem_inds][perm_inds]
141 | #active_D = np.tile(D[active_elem_inds, np.newaxis], [1, active_elems_perm.shape[1], 1, 1])[perm_inds]
142 | u_new = self.update_specific_points(active_elems_perm, # self.elems_perm,
143 | active_points_perm, #self.points_perm,
144 | active_D,
145 | phi,
146 | lib=np)
147 |
148 | return u_new
149 |
150 |
151 | def _comp_fim(self, x0, x0_vals, metrics=None, max_iterations=int(1e10)):
152 | if metrics is None:
153 | metrics = self.metrics
154 |
155 | D = metrics
156 | self.phi_sol = np.ones(shape=[self.nr_points], dtype=self.precision) * self.undef_val
157 | self.phi_sol[x0] = x0_vals
158 | self.active_list[:] = False
159 | self.active_list[np.unique(self.nh_map[x0])] = True
160 |
161 | if D.dtype != self.precision:
162 | D = D.astype(self.precision)
163 |
164 | for i in range(max_iterations):
165 | #active_points = self.points[self.active_list]
166 | active_inds = self.active_list.nonzero()[0].astype(np.int32)
167 |
168 | u_new = self.comp_marked_points(self.phi_sol, D, active_inds)
169 | converged = ((np.abs(u_new - self.phi_sol) < self.convergence_eps) & (self.active_list))
170 | converged_inds = converged.nonzero()[0]
171 | converged_neighbors = np.unique(self.nh_map[converged_inds])
172 | u_neighs = self.comp_marked_points(u_new, D, converged_neighbors)
173 | neighbors_needing_updates = converged_neighbors[((np.abs(u_new[converged_neighbors] - u_neighs[converged_neighbors]) >= self.convergence_eps))]
174 | #Check if the neighbors converged
175 | self.active_list[converged_inds] = False #Remove converged points from the active list
176 | self.active_list[neighbors_needing_updates] = True #Add neighbors to the active list
177 |
178 |
179 | if np.all(~self.active_list): #np.allclose(u_new, self.phi_sol, atol=self.convergence_eps):
180 | break
181 |
182 | self.phi_sol = u_new
183 |
184 | self.phi_sol = u_new
185 |
186 | return self.phi_sol
187 |
--------------------------------------------------------------------------------
/fimpy/perm_kernel_test.cu:
--------------------------------------------------------------------------------
1 | extern "C"{
2 |
3 | __device__ int* upperBound(int* first, int* last, const int& value)
4 | {
5 | int* it;
6 | int count, step;
7 | count = last - first;
8 |
9 | while (count > 0) {
10 | it = first;
11 | step = count / 2;
12 | it += step;
13 | if (value >= *it) {
14 | first = ++it;
15 | count -= step + 1;
16 | }
17 | else
18 | count = step;
19 | }
20 | return first;
21 | }
22 |
23 | __global__
24 | void perm_kernel(const int* active_elems_perm, const int* active_inds,
25 | bool* perm_mask,
26 | const unsigned int active_elems_size,
27 | const unsigned int active_inds_size) {
28 | const int nr_perms = {active_perms};
29 | const int bidx = blockIdx.x;
30 | const int block_size = blockDim.x;
31 | const int block_size_y = blockDim.y;
32 | const int tidx_global = block_size * bidx + threadIdx.x;
33 | const int tidx_local = threadIdx.x;
34 | //const int tidx_y = threadIdx.y;
35 | //const auto grid_size = gridDim.x * gridDim.y;
36 | //const auto blockidx = blockIdx.x + blockIdx.y*gridDim.x;
37 | //const auto block_size = blockDim.x * blockDim.y; // * blockDim.z;
38 | //const auto tidx = threadIdx.y * blockDim.x + threadIdx.x;
39 | __shared__ int active_inds_buf[{shared_buf_size}];
40 | const int nr_shared_bufs_needed = static_cast(ceil(static_cast(active_inds_size) / {shared_buf_size}));
41 |
42 | //printf("Test\n");
43 | for(int shared_buf_run = 0; shared_buf_run < nr_shared_bufs_needed; shared_buf_run++)
44 | {
45 | //printf("%d\n", shared_buf_run);
46 | const int shared_buf_offset = {shared_buf_size} * shared_buf_run;
47 | const int current_active_inds_size = min({shared_buf_size}, active_inds_size - {shared_buf_size}*shared_buf_run);
48 | printf("%d\n", current_active_inds_size);
49 | if(shared_buf_run > 0)
50 | __syncthreads();
51 |
52 | //Fill shared memory
53 | for(int active_i = tidx_local; active_i < current_active_inds_size; active_i += block_size)
54 | active_inds_buf[active_i] = active_inds[shared_buf_offset + active_i];
55 |
56 | __syncthreads();
57 |
58 | for(int elem_offset = tidx_global; elem_offset < active_elems_size*nr_perms; elem_offset+=block_size*{parallel_blocks})
59 | {
60 | const int point_i = active_elems_perm[elem_offset];
61 | bool match = perm_mask[elem_offset]; //Maybe already set in the last shared buffer run
62 | printf("elem_offset %d, %d\n", elem_offset, point_i);
63 | if(!match)
64 | {
65 | printf("Bounds: %x, %x\n", active_inds_buf, active_inds_buf + current_active_inds_size);
66 | printf("Range: %d\n", (active_inds_buf + current_active_inds_size) - active_inds_buf);
67 | const int* bound = upperBound(active_inds_buf, active_inds_buf + current_active_inds_size, point_i);
68 | const int* possible_equal_elem = ((active_inds_buf > (bound - 1)) ? active_inds_buf : (bound - 1));
69 | printf("Found: %x, %x, %d\n", bound, possible_equal_elem, *possible_equal_elem);
70 | if(*possible_equal_elem == point_i)
71 | perm_mask[elem_offset] = true;
72 | }
73 |
74 | //__syncthreads();
75 | }
76 | }
77 | }
78 | }
--------------------------------------------------------------------------------
/fimpy/solver.py:
--------------------------------------------------------------------------------
1 | """This file contains the interface to create the Fast Iterative Method solvers.
2 | """
3 |
4 | try:
5 | import cupy as cp
6 | from .fim_cupy import FIMCupyAL, FIMCupy
7 | cupy_available = True
8 | except ImportError as err:
9 | cupy_available = False
10 | print("Import of Cupy failed. The GPU version of fimpy will be unavailable. Message: %s" % (err))
11 |
12 | from .fim_base import FIMBase
13 | from .fim_np import FIMNP, FIMNPAL
14 | import numpy as np
15 | from typing import Union
16 |
17 | available_arr_t = (Union[np.ndarray, cp.ndarray] if cupy_available else np.ndarray)
18 |
19 | """Function responsible for creating the correct Fast Iterative Method solver
20 | """
21 | def create_fim_solver(points : available_arr_t, elems : available_arr_t, metrics : available_arr_t =None,
22 | precision=np.float32, device='cpu', use_active_list=True) -> FIMBase:
23 | """Creates a Fast Iterative Method solver for solving the anisotropic eikonal equation
24 |
25 | .. math::
26 | \\left\\{
27 | \\begin{array}{rll}
28 | \\left<\\nabla \\phi, D \\nabla \\phi \\right> &= 1 \\quad &\\text{on} \\; \\Omega \\\\
29 | \\phi(\\mathbf{x}_0) &= g(\\mathbf{x}_0) \\quad &\\text{on} \\; \\Gamma
30 | \\end{array}
31 | \\right. .
32 |
33 | Parameters
34 | ----------
35 | points : Union[np.ndarray (float), cp.ndarray (float)]
36 | Array of points, :math:`n \\times d`
37 | elems : Union[np.ndarray (int), cp.ndarray (int)]
38 | Array of elements, :math:`m \\times d_e`
39 | metrics : Union[np.ndarray (float), cp.ndarray (float)], optional
40 | Specifies the initial :math:`D \\in \\mathbb{R}^{d \\times d}` tensors.
41 | If not specified, you later need to provide them in :meth:`comp_fim `, by default None
42 | precision : np.dtype, optional
43 | precision of all calculations and the final result, by default np.float32
44 | device : str, optional
45 | Specifies the target device for the computations. One of [cpu, gpu], by default 'gpu'
46 | use_active_list : bool, optional
47 | If set to true, you will get an active list solver that only computes the necessary subset of points in each iteration.
48 | If set to false, a Jacobi solver will be returned that updates all points of the mesh in each iteration. By default True
49 |
50 | Returns
51 | -------
52 | FIMBase
53 | Returns a Fast Iterative Method solver
54 | """
55 | assert not device == 'gpu' or cupy_available, "Requested GPU which is not available"
56 |
57 | if device == 'cpu':
58 | return (FIMNPAL(points, elems, metrics, precision) if use_active_list else FIMNP(points, elems, metrics, precision))
59 | elif device == 'gpu':
60 | return (FIMCupyAL(points, elems, metrics, precision) if use_active_list else FIMCupy(points, elems, metrics, precision))
61 | else:
62 | assert False, f"Unknown device {device}, should be one of [cpu, gpu]"
63 |
64 | #Class for backwards compatibility
65 | from warnings import warn
66 | class FIMPY():
67 | def create_fim_solver(*args, **kwargs):
68 | warn("Using the FIMPY interface is deprecated and will be removed in future releases. Use the module function create_fim_solver directly.", DeprecationWarning, stacklevel=2)
69 | return create_fim_solver(*args, **kwargs)
70 |
--------------------------------------------------------------------------------
/fimpy/utils/__init__.py:
--------------------------------------------------------------------------------
1 | """This subpackage contains small custom functions to efficiently compute :math:`\\left` on the CPU and GPU for different dimensions :math:`d`.
2 | """
--------------------------------------------------------------------------------
/fimpy/utils/comp.py:
--------------------------------------------------------------------------------
1 | """This file contains small custom functions to compute :math:`\\left` for general and special dimensions :math:`d`.
2 | Note that all custom, efficient implementations assume that :math:`A` is a symmetric matrix.
3 | """
4 | import numpy as np
5 | from .cython.comp import metric_sqr_norm_matrix_2D_vec, metric_sqr_norm_matrix_3D_vec
6 | try:
7 | import cupy as cp
8 | cupy_enabled = True
9 | except ImportError as err:
10 | cupy_enabled = False
11 |
12 |
13 | def _broadcast_metric_params(A, x1, x2):
14 | """Broadcast the metric parameters as a preperation for the Cython functions.
15 | See :func:`metric_sqr_norm_matrix`.
16 | """
17 | if A.ndim == 4: #Broadcasting
18 | A = np.broadcast_to(A, [A.shape[0], max(A.shape[1], x1.shape[1]), x1.shape[-1], x1.shape[-1]])
19 | x1 = np.broadcast_to(x1, A.shape[:-1])
20 | x2 = np.broadcast_to(x2, A.shape[:-1])
21 |
22 | return A, x1, x2
23 |
24 |
25 | def metric_norm_matrix_2D_cython(A, x1, x2, ret_sqrt=True):
26 | """Custom implementation of :func:`metric_sqr_norm_matrix` for ``lib = np`` and :math:`d = 2`.
27 | """
28 | A, x1, x2 = _broadcast_metric_params(A, x1, x2)
29 | A_flat, x1_flat, x2_flat = A.reshape([-1, 2, 2]), x1.reshape([-1, 2]), x2.reshape([-1, 2])
30 | norm = np.empty(shape=A_flat.shape[0], dtype=A_flat.dtype)
31 | norm = np.array(metric_sqr_norm_matrix_2D_vec(A_flat, x1_flat, x2_flat, norm))
32 |
33 | if ret_sqrt:
34 | norm = np.sqrt(norm)
35 |
36 | return norm.reshape(A.shape[:-2])
37 |
38 | def metric_norm_matrix_3D_cython(A, x1, x2, ret_sqrt=True):
39 | """Custom implementation of :func:`metric_sqr_norm_matrix` for ``lib = np`` and :math:`d = 3`.
40 | """
41 | A, x1, x2 = _broadcast_metric_params(A, x1, x2)
42 | A_flat, x1_flat, x2_flat = A.reshape([-1, 3, 3]), x1.reshape([-1, 3]), x2.reshape([-1, 3])
43 | norm = np.empty(shape=A_flat.shape[0], dtype=A_flat.dtype)
44 | norm = np.array(metric_sqr_norm_matrix_3D_vec(A_flat, x1_flat, x2_flat, norm))
45 |
46 | if ret_sqrt:
47 | norm = np.sqrt(norm)
48 |
49 | return norm.reshape(A.shape[:-2])
50 |
51 |
52 | if cupy_enabled:
53 | @cp.fuse()
54 | def metric_sqr_norm_matrix_2D_cupy(A, x1, x2):
55 | """Custom implementation of :func:`metric_sqr_norm_matrix` for ``lib = cp`` and :math:`d = 3`.
56 | """
57 | a, b, c = A[..., 0, 0], A[..., 1, 1], A[..., 0, 1]
58 | return (x1[..., 0] * (a * x2[..., 0] + c * x2[..., 1]) + x1[..., 1] * (c * x2[..., 0] + b * x2[..., 1]))
59 |
60 | @cp.fuse()
61 | def metric_norm_matrix_2D_cupy(A, x1, x2):
62 | """Custom implementation of :func:`metric_norm_matrix` for ``lib = cp`` and :math:`d = 3`.
63 | """
64 | norm = metric_sqr_norm_matrix_2D_cupy(A, x1, x2)
65 | norm = cp.sqrt(norm)
66 |
67 | return norm
68 |
69 | @cp.fuse()
70 | def metric_sqr_norm_matrix_3D_cupy(A, x1, x2):
71 | """Custom implementation of :func:`metric_sqr_norm_matrix` for ``lib = cp`` and :math:`d = 3`.
72 | """
73 | a, b, c, d, e, f = A[..., 0, 0], A[..., 1, 1], A[..., 2, 2], A[..., 0, 1], A[..., 0, 2], A[..., 1, 2]
74 | norm = (x1[..., 0] * (a * x2[..., 0] + d * x2[..., 1] + e * x2[..., 2])
75 | + x1[..., 1] * (d * x2[..., 0] + b * x2[..., 1] + f * x2[..., 2])
76 | + x1[..., 2] * (e * x2[..., 0] + f * x2[..., 1] + c * x2[..., 2]))
77 |
78 | return norm
79 |
80 | @cp.fuse()
81 | def metric_norm_matrix_3D_cupy(A, x1, x2):
82 | """Custom implementation of :func:`metric_norm_matrix` for ``lib = cp`` and :math:`d = 3`.
83 | """
84 | norm = metric_sqr_norm_matrix_3D_cupy(A, x1, x2)
85 | norm = cp.sqrt(norm)
86 |
87 | return norm
88 |
89 |
90 | def metric_sqr_norm_matrix(A, x1, x2, lib=np):
91 | """Computes :math:`\\left` in a broadcasted fashion for arbitrary :math:`d`.
92 | Details on the parameters and the return value can be found in :func:`metric_norm_matrix`.
93 | """
94 | #assert(A.shape[-1] == x1.shape[-1] and A.shape[-2] == A.shape[-1])
95 |
96 | #assert(np.all(np.equal(x2.shape[-1], x1.shape[-1])))
97 |
98 | sqr_norm = lib.sum(lib.sum(A * x1[..., lib.newaxis], axis=-2) * x2, axis=-1)
99 | return sqr_norm
100 |
101 | def metric_norm_matrix(A, x1, x2, lib=np):
102 | """Computes :math:`\\sqrt{\\left}` in a broadcasted fashion for arbitrary :math:`d`
103 |
104 | Parameters
105 | ----------
106 | A : ndarray (float)
107 | An [..., d, d] array with the stack of matrices :math:`A`
108 | x1 : ndarray (float)
109 | An [..., d] array with the stack of vectors :math:`\\mathbf{x}_1`
110 | x2 : ndarray (float)
111 | An [..., d] array with the stack of vectors :math:`\\mathbf{x}_2`
112 | lib : library, optional
113 | Library used for the computations of the norm. Needs to implement a ``sum`` method.
114 | By default np
115 |
116 | Returns
117 | -------
118 | ndarray (float)
119 | An [...] array holding the computed norms :math:`\\sqrt{\\left}`.
120 | """
121 |
122 |
123 | #assert(A.shape[-1] == x1.shape[-1] and A.shape[-2] == A.shape[-1])
124 |
125 | #assert(np.all(np.equal(x2.shape[-1], x1.shape[-1])))
126 |
127 | sqr_norm = metric_sqr_norm_matrix(A, x1, x2, lib)
128 | return lib.sqrt(sqr_norm)
129 |
--------------------------------------------------------------------------------
/fimpy/utils/cython/__init__.py:
--------------------------------------------------------------------------------
1 | """This subpackage contains the Cython implementations for fast 2D and 3D metric norm computations.
2 | """
3 |
4 | from .comp import metric_sqr_norm_matrix_2D_vec, metric_sqr_norm_matrix_3D_vec #, sqrt_cython
--------------------------------------------------------------------------------
/fimpy/utils/cython/comp.pyx:
--------------------------------------------------------------------------------
1 | # cython: infer_types=True
2 | # distutils: language=c++
3 | cimport cython
4 | from cython.parallel cimport prange
5 | from libcpp.vector cimport vector
6 | from typing import Callable
7 | from libcpp cimport bool as bool_t
8 | from libc.math cimport sqrt
9 |
10 | import numpy as np
11 |
12 | ctypedef fused mat_t:
13 | float
14 | double
15 |
16 |
17 | ctypedef fused const_mat_t:
18 | const float
19 | const double
20 |
21 |
22 |
23 | @cython.boundscheck(False)
24 | @cython.wraparound(False)
25 | def metric_sqr_norm_matrix_2D_vec(const_mat_t[:, :, :] A, const_mat_t[:, :] x1, const_mat_t[:, :] x2, mat_t[::1] result):
26 | a, b, c = A[..., 0, 0], A[..., 1, 1], A[..., 0, 1]
27 |
28 | cdef const_mat_t[:] a_ = a
29 | cdef const_mat_t[:] b_ = b
30 | cdef const_mat_t[:] c_ = c
31 | cdef int rows, row_i
32 |
33 | rows = A.shape[0]
34 | for row_i in prange(rows, nogil=True):
35 | result[row_i] = (x1[row_i, 0] * (a_[row_i] * x2[row_i, 0] + c_[row_i] * x2[row_i, 1])
36 | + x1[row_i, 1] * (c_[row_i] * x2[row_i, 0] + b_[row_i] * x2[row_i, 1]))
37 |
38 |
39 | return result
40 |
41 | @cython.boundscheck(False)
42 | @cython.wraparound(False)
43 | def metric_sqr_norm_matrix_3D_vec(const_mat_t[:, :, :] A, const_mat_t[:, :] x1, const_mat_t[:, :] x2, mat_t[::1] result):
44 | a, b, c, d, e, f = A[..., 0, 0], A[..., 1, 1], A[..., 2, 2], A[..., 0, 1], A[..., 0, 2], A[..., 1, 2]
45 |
46 | cdef int rows, row_i
47 | cdef const_mat_t[:] a_ = a
48 | cdef const_mat_t[:] b_ = b
49 | cdef const_mat_t[:] c_ = c
50 | cdef const_mat_t[:] d_ = d
51 | cdef const_mat_t[:] e_ = e
52 | cdef const_mat_t[:] f_ = f
53 |
54 | cdef const_mat_t[:] x11_ = x1[..., 0]
55 | cdef const_mat_t[:] x12_ = x1[..., 1]
56 | cdef const_mat_t[:] x13_ = x1[..., 2]
57 | cdef const_mat_t[:] x21_ = x2[..., 0]
58 | cdef const_mat_t[:] x22_ = x2[..., 1]
59 | cdef const_mat_t[:] x23_ = x2[..., 2]
60 |
61 | rows = A.shape[0]
62 | for row_i in prange(rows, nogil=True):
63 | result[row_i] = (x11_[row_i] * (a_[row_i] * x21_[row_i] + d_[row_i] * x22_[row_i] + e_[row_i] * x23_[row_i])
64 | + x12_[row_i] * (d_[row_i] * x21_[row_i] + b_[row_i] * x22_[row_i] + f_[row_i] * x23_[row_i])
65 | + x13_[row_i] * (e_[row_i] * x21_[row_i] + f_[row_i] * x22_[row_i] + c_[row_i] * x23_[row_i]))
66 |
67 |
68 | return result
69 |
--------------------------------------------------------------------------------
/fimpy/utils/tsitsiklis.py:
--------------------------------------------------------------------------------
1 | """This file contains the norm_map, that is in general used to efficiently select the best and fastest function to compute norms of the type :math:`\\left`.
2 | """
3 | #import utility
4 | import numpy as np
5 | from .comp import metric_norm_matrix_2D_cython, metric_norm_matrix_3D_cython
6 | from .comp import metric_sqr_norm_matrix, metric_norm_matrix
7 | from collections import defaultdict
8 |
9 | norm_map = {np: defaultdict(lambda: (metric_norm_matrix, metric_sqr_norm_matrix))}
10 | norm_map[np][2] = (lambda A, x1, x2: metric_norm_matrix_2D_cython(A, x1, x2, True), lambda A, x1, x2: metric_norm_matrix_2D_cython(A, x1, x2, False))
11 | norm_map[np][3] = (lambda A, x1, x2: metric_norm_matrix_3D_cython(A, x1, x2, True), lambda A, x1, x2: metric_norm_matrix_3D_cython(A, x1, x2, False))
12 |
13 | try:
14 | import cupy as cp
15 | from .comp import metric_norm_matrix_2D_cupy, metric_norm_matrix_3D_cupy, metric_sqr_norm_matrix_2D_cupy, metric_sqr_norm_matrix_3D_cupy
16 | norm_map[cp] = defaultdict(lambda: (lambda A, x1, x2: metric_norm_matrix(A, x1, x2, cp), lambda A, x1, x2: metric_sqr_norm_matrix(A, x1, x2, cp)))
17 | norm_map[cp][2] = (lambda A, x1, x2: metric_norm_matrix_2D_cupy(A, x1, x2), lambda A, x1, x2: metric_sqr_norm_matrix_2D_cupy(A, x1, x2))
18 | norm_map[cp][3] = (lambda A, x1, x2: metric_norm_matrix_3D_cupy(A, x1, x2), lambda A, x1, x2: metric_sqr_norm_matrix_3D_cupy(A, x1, x2))
19 | except ImportError as err:
20 | ...
21 |
--------------------------------------------------------------------------------
/paper.bib:
--------------------------------------------------------------------------------
1 | @article{fu_fast_2011,
2 | title = {A {Fast} {Iterative} {Method} for {Solving} the {Eikonal} {Equation} on {Triangulated} {Surfaces}},
3 | volume = {33},
4 | issn = {1064-8275},
5 | url = {https://epubs.siam.org/doi/abs/10.1137/100788951},
6 | doi = {10.1137/100788951},
7 | number = {5},
8 | urldate = {2018-07-26},
9 | journal = {SIAM Journal on Scientific Computing},
10 | author = {Fu, Z. and Jeong, W. and Pan, Y. and Kirby, R. and Whitaker, R.},
11 | month = jan,
12 | year = {2011},
13 | pages = {2468--2488}
14 | }
15 |
16 | @book{evans_partial_2010,
17 | author = {Evans, Lawrence C.},
18 | title = {Partial differential equations},
19 | series = {Graduate Studies in Mathematics},
20 | volume = {19},
21 | edition = {Second},
22 | publisher = {American Mathematical Society, Providence, RI},
23 | year = {2010},
24 | pages = {xxii+749},
25 | ISBN = {978-0-8218-4974-3},
26 | doi = {10.1090/gsm/019},
27 | url = {https://doi.org/10.1090/gsm/019},
28 | }
29 |
30 | @article{fu_fast_2013,
31 | title = {A {Fast} {Iterative} {Method} for {Solving} the {Eikonal} {Equation} on {Tetrahedral} {Domains}},
32 | volume = {35},
33 | issn = {1064-8275},
34 | url = {https://epubs.siam.org/doi/abs/10.1137/120881956},
35 | doi = {10.1137/120881956},
36 | number = {5},
37 | urldate = {2018-07-26},
38 | journal = {SIAM Journal on Scientific Computing},
39 | author = {Fu, Z. and Kirby, R. and Whitaker, R.},
40 | month = jan,
41 | year = {2013},
42 | pages = {C473--C494}
43 | }
44 |
45 | @article{sethian_fast_1996,
46 | title={A fast marching level set method for monotonically advancing fronts},
47 | author={Sethian, James A},
48 | journal={Proceedings of the National Academy of Sciences},
49 | volume={93},
50 | number={4},
51 | pages={1591--1595},
52 | year={1996},
53 | publisher={National Acad. Sciences},
54 | doi = {10.1073/pnas.93.4.1591},
55 | }
56 |
57 | @book{franzone2014mathematical,
58 | title={Mathematical cardiac electrophysiology},
59 | author={Franzone, Piero Colli and Pavarino, Luca Franco and Scacchi, Simone},
60 | volume={13},
61 | year={2014},
62 | publisher={Springer},
63 | doi={10.1007/978-3-319-04801-7}
64 | }
65 |
66 | @article{grandits_inverse_2020,
67 | title = {An inverse {Eikonal} method for identifying ventricular activation sequences from epicardial activation maps},
68 | volume = {419},
69 | issn = {0021-9991},
70 | url = {http://www.sciencedirect.com/science/article/pii/S0021999120304745},
71 | doi = {10.1016/j.jcp.2020.109700},
72 | language = {en},
73 | urldate = {2020-07-21},
74 | journal = {Journal of Computational Physics},
75 | author = {Grandits, Thomas and Gillette, Karli and Neic, Aurel and Bayer, Jason and Vigmond, Edward and Pock, Thomas and Plank, Gernot},
76 | month = oct,
77 | year = {2020},
78 | keywords = {Fast iterative method, Fast marching, His-Purkinje system, Inverse Eikonal, Minimization},
79 | pages = {109700}
80 | }
81 |
82 |
--------------------------------------------------------------------------------
/paper.md:
--------------------------------------------------------------------------------
1 | ---
2 | title: 'A Fast Iterative Method Python package'
3 | tags:
4 | - Python
5 | - eikonal
6 | - partial differential equations
7 | - cuda
8 | authors:
9 | - name: Thomas Grandits
10 | affiliation: 1
11 | affiliations:
12 | - name: Institute of Computer Graphics and Vision, TU Graz
13 | index: 1
14 | date: July 2021
15 | bibliography: paper.bib
16 | ---
17 |
18 | # Summary
19 |
20 |
21 | The anisotropic eikonal equation is a non-linear partial differential equation, given by
22 | \begin{equation*}
23 | \left\{
24 | \begin{array}{rll}
25 | \left<\nabla \phi, D \nabla \phi \right> &= 1 \quad &\text{on} \; \Omega \\
26 | \phi(\mathbf{x}_0) &= g(\mathbf{x}_0) \quad &\text{on} \; \Gamma \subset \Omega
27 | \end{array}
28 | \right. .
29 | \end{equation*}
30 | In practice, this problem is often associated with computing the earliest arrival times $\phi$ of a wave from a set of given starting points $\mathbf{x}_0$ through a heterogeneous medium (i.e. different velocities are assigned throughout the medium).
31 | This equation yields infinitely many weak solutions [@evans_partial_2010] and can thus not be straight-forwardly solved using standard Finite Element approaches.
32 |
33 | ``fim-python`` implements the Fast Iterative Method (FIM), proposed in [@fu_fast_2013], purely in Python to solve the anisotropic eikonal equation by finding its unique viscosity solution.
34 | In this scenario, we compute $\phi$ on tetrahedral/triangular meshes or line networks for a given $D$, $\mathbf{x}_0$ and $g$.
35 | The method is implemented both on the CPU using [``numba``](https://numba.pydata.org/) and [``numpy``](https://numpy.org/), as well as the GPU with the help of [``cupy``](https://cupy.dev/) (depends on [CUDA](https://developer.nvidia.com/cuda-toolkit)).
36 | The library is meant to be easily and rapidly used for repeated evaluations on a mesh.
37 |
38 | The FIM locally computes an update rule to find the path the wavefront will take through a single element.
39 | Since the algorithm is restricted to linear elements, the path through an element will also be a straight line.
40 | In the case of tetrahedral domains, the FIM thus tries to find the path of the linear update from a face spanned by three vertices $\mathbf{v}_1, \mathbf{v}_2, \mathbf{v}_3$ to the opposite vertex $\mathbf{v}_4$.
41 | \autoref{fig:update} visualizes the update.
42 | For triangles and lines, the algorithm behaves similarly but the update origin is limited to a side or vertex respectively.
43 | The exact equations used to solve this problem in this repository were previously described (among others) in [@grandits_inverse_2020].
44 |
45 | { width=33% }
46 |
47 |
48 | Two different methods are implemented in ``fim-python``:
49 | In the *Jacobi* method, the above local update rule is computed for all elements in each iteration until the change between two subsequent iterations is smaller than a chosen $\varepsilon$.
50 | This version of the algorithm is bested suited for the GPU, since it is optimal for a SIMD (single instruction multiple data) architecture.
51 | The *active list* method is more closely related to the method presented in [@fu_fast_2013]:
52 | We keep track of all vertices that require a recomputation in the current iteration on a so-called active list which we keep up-to-date.
53 |
54 | # Comparison to other tools
55 |
56 | There are other tools available to solve variants of the eikonal equation, but they differ in functionality to ``fim-python``.
57 |
58 | [``scikit-fmm``](https://pypi.org/project/scikit-fmm/) implements the Fast Marching Method (FMM) [@sethian_fast_1996], which was designed to solve the isotropic eikonal equation ($D = c I$ for $c \in \mathbb{R}$ and $I$ being the identity matrix). The library works on uniform grids, rather than meshes.
59 |
60 | [``GPUTUM: Unstructured Eikonal``](https://github.com/SCIInstitute/SCI-Solver_Eikonal) implements the FIM in CUDA for triangulated surfaces and tetrahedral meshes, but has no Python bindings and is designed as a command line tool for single evaluations.
61 |
62 | # Statement of need
63 |
64 | The eikonal equation has many practical applications, including cardiac electrophysiology, image processing and geoscience, to approximate wave propagation through a medium.
65 | In the example of cardiac electrophysiology [@franzone2014mathematical], the electrical activation times $\phi$ are computed throughout the anisotropic heart muscle with varying conduction velocities $D$.
66 |
67 | ``fim-python`` tries to wrap the FIM for CPU and GPU into an easy-to-use Python package for multiple evaluations with a straight-forward installation over [PyPI](https://pypi.org/).
68 | This should provide engineers and researchers alike with an accessible tool that allows evaluations of the eikonal equation for general scenarios.
69 |
70 | # References
71 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = ["setuptools", "wheel", "Cython>=0.29.22"]
3 | build-backend = "setuptools.build_meta"
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 | from distutils.core import setup, Extension
3 | from setuptools.command.build_ext import build_ext
4 | from Cython.Build import cythonize
5 | import sys
6 | import os
7 |
8 | class build_ext_check_openmp(build_ext):
9 | def build_extensions(self):
10 | try:
11 | build_ext.build_extensions(self)
12 | except:
13 | # remove openmp flags
14 | for ext in self.extensions:
15 | ext.extra_compile_args = [f for f in ext.extra_compile_args if not f.endswith("openmp")]
16 | ext.extra_link_args = [f for f in ext.extra_link_args if not f.endswith("openmp")]
17 | print(ext.extra_compile_args)
18 | print(ext.extra_link_args)
19 | build_ext.build_extensions(self)
20 |
21 | if sys.platform.startswith("win32"):
22 | extra_compile_args = ["/O2", "/openmp"]
23 | extra_link_args = [] #["/openmp"]
24 | else:
25 | extra_compile_args = ["-O3", "-fopenmp"]
26 | extra_link_args = ["-fopenmp"]
27 |
28 | fim_cutils_extension = Extension(
29 | name="fimpy.fim_cutils.fim_cutils",
30 | sources=["fimpy/fim_cutils/fim_cutils.pyx"], # our Cython source
31 | language="c++", # generate C++ code
32 | extra_compile_args=extra_compile_args,
33 | extra_link_args=extra_link_args,
34 | )
35 |
36 | comp_cutils_extension = Extension(
37 | name="fimpy.utils.cython.comp",
38 | sources=["fimpy/utils/cython/comp.pyx"], # our Cython source
39 | language="c++", # generate C++ code
40 | extra_compile_args=extra_compile_args,
41 | extra_link_args=extra_link_args,
42 | )
43 |
44 | lib_requires_cpu = ["numpy", "Cython>=0.29.22"]
45 | lib_requires_gpu = ["cupy>=9.0"]
46 | test_requires_cpu = ["scipy", "pytest", "pytest-cov", "matplotlib", "pandas", "ipython"]
47 |
48 | with open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r') as readme:
49 | long_description = readme.read()
50 |
51 | setup(name="fim-python",
52 | version="1.2.2",
53 | description="This repository implements the Fast Iterative Method on tetrahedral domains and triangulated surfaces purely in python both for CPU (numpy) and GPU (cupy).",
54 | long_description=long_description,
55 | long_description_content_type="text/markdown",
56 | url="https://github.com/thomgrand/fim-python",
57 | packages=["fimpy", "fimpy.utils", "fimpy.fim_cutils", "fimpy.utils.cython"],
58 | install_requires=lib_requires_cpu,
59 | classifiers=[
60 | "Programming Language :: Python :: 3",
61 | "Programming Language :: Cython",
62 | "Topic :: Scientific/Engineering :: Mathematics",
63 | "Operating System :: POSIX :: Linux",
64 | "Operating System :: Microsoft :: Windows",
65 | "Environment :: GPU :: NVIDIA CUDA",
66 | "License :: OSI Approved :: GNU Affero General Public License v3",
67 | ],
68 | python_requires='>=3.6',
69 | author="Thomas Grandits",
70 | author_email="tomdev@gmx.net",
71 | license="AGPL",
72 | ext_modules = cythonize([fim_cutils_extension, comp_cutils_extension],
73 | compiler_directives={'language_level' : "3"}),
74 | cmdclass={ 'build_ext': build_ext_check_openmp },
75 | extras_require = {
76 | 'gpu': lib_requires_gpu,
77 | 'tests': test_requires_cpu,
78 | 'docs': ["sphinx", "pydata_sphinx_theme", "pandas", "ipython"]
79 | }
80 | )
81 |
82 |
--------------------------------------------------------------------------------
/tests/benchmark_data/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore everything in this directory
2 | *
3 | # Except this file
4 | !.gitignore
5 |
--------------------------------------------------------------------------------
/tests/data/.gitignore:
--------------------------------------------------------------------------------
1 | # Ignore everything in this directory
2 | *
3 | # Except this file
4 | !.gitignore
5 |
--------------------------------------------------------------------------------
/tests/generate_benchmark_data.py:
--------------------------------------------------------------------------------
1 | from generate_test_data import generate_test_data
2 |
3 | if __name__ == "__main__":
4 | generate_test_data(True)
--------------------------------------------------------------------------------
/tests/generate_doc_figs.py:
--------------------------------------------------------------------------------
1 | import numpy as np
2 | import matplotlib.pyplot as plt
3 | import os
4 | import numpy as np
5 | import cupy as cp
6 | import sys
7 | sys.path.append(".")
8 | from fimpy import create_fim_solver
9 | from scipy.spatial import Delaunay
10 | import matplotlib.pyplot as plt
11 | import matplotlib.colors
12 | import scipy.io as sio
13 | import pandas
14 | import json
15 |
16 | #TODO
17 | def generate_usage_example(save_fig=True):
18 | out_fname = os.path.join(os.path.dirname(__file__), *["..", "docs", "figs", "usage_example.jpg"])
19 | #Create triangulated points in 2D
20 | x = np.linspace(-1, 1, num=50)
21 | X, Y = np.meshgrid(x, x)
22 | points = np.stack([X, Y], axis=-1).reshape([-1, 2]).astype(np.float32)
23 | elems = Delaunay(points).simplices
24 | elem_centers = np.mean(points[elems], axis=1)
25 |
26 | #The domain will have a small spot where movement will be slow
27 | velocity_p = (1 / (1 + np.exp(3.5 - 25*np.linalg.norm(points - np.array([[0.33, 0.33]]), axis=-1)**2)))
28 | velocity_e = (1 / (1 + np.exp(3.5 - 25*np.linalg.norm(elem_centers - np.array([[0.33, 0.33]]), axis=-1)**2)))
29 | D = np.eye(2, dtype=np.float32)[np.newaxis] * velocity_e[..., np.newaxis, np.newaxis] #Isotropic propagation
30 |
31 | x0 = np.array([np.argmin(np.linalg.norm(points, axis=-1), axis=0)])
32 | x0_vals = np.array([0.])
33 |
34 | #Create a FIM solver, by default the GPU solver will be called with the active list
35 | fim = create_fim_solver(points, elems, D)
36 | phi = fim.comp_fim(x0, x0_vals)
37 |
38 | #Plot the data of all points to the given x0 at the center of the domain
39 | fig, axes = plt.subplots(nrows=1, ncols=2, sharey=True)
40 | cont_f1 = axes[0].contourf(X, Y, phi.get().reshape(X.shape))
41 | axes[0].set_title("Distance from center $\\phi(\\mathbf{x})$")
42 | scatter_h = axes[0].scatter(points[x0, 0], points[x0, 1], marker='x', color='r')
43 | #cbar = plt.colorbar(cont_f1)
44 | #cbar.set_label("$\\phi$")
45 | axes[0].legend([scatter_h], ["$\\mathbf{x}_0$"])
46 |
47 | cont_f2 = axes[1].contourf(X, Y, velocity_p.reshape(X.shape))
48 | axes[1].set_title("Assumed isotropic velocity $D(\\mathbf{x}) = c(\\mathbf{x}) I$")
49 | #cbar = plt.colorbar(cont_f2)
50 | #cbar.set_label("Velocity")
51 |
52 | fig.set_size_inches((10, 6))
53 | plt.tight_layout()
54 | if save_fig:
55 | fig.savefig(out_fname)
56 | else:
57 | plt.show()
58 |
59 | plt.close(fig)
60 |
61 | def generate_benchmark_plot(benchmark_data_fname, data_field, save_fig=True, fname_postfix="", title=None):
62 | with open(benchmark_data_fname, "r") as bench_f:
63 | benchmark_data = json.load(bench_f)
64 | out_fname = os.path.join(os.path.dirname(__file__), *["..", "docs", "figs", "benchmark"])
65 | all_pd_data = pandas.DataFrame(benchmark_data)
66 |
67 | all_dims = np.unique(all_pd_data["dims"])
68 | colors = plt.cm.brg(np.linspace(0, 1, num=all_dims.size))
69 |
70 | figs = []
71 | #GPU
72 | for device in ["gpu", "cpu"]:
73 | plt.gca().set_prop_cycle(None) #Reset color cycle
74 | pd_data = all_pd_data[all_pd_data["device"] == device]
75 | #colors = plt.cm.get_cmap('jet', all_dims.size)
76 | fig, axes = plt.subplots(nrows=1, ncols=3)
77 | lines_hs = {2: [], 3: [], 4: []}
78 | for elem_dim_i, elem_dims in enumerate([4, 3, 2]): #np.unique(pd_data["elem_dims"])):
79 | for dim_i, dims in enumerate([1, 2, 3, 5]): #enumerate(all_dims): #[1, 2, 3, 5]
80 | for use_active_list in [False, True]:
81 | plt.sca(axes[elem_dim_i])
82 | data = pd_data[(pd_data["active_list"] == use_active_list) & (pd_data["dims"] == dims) & (pd_data["elem_dims"] == elem_dims)]
83 |
84 | if data.size == 0:
85 | continue
86 |
87 | data = data.sort_values("resolution", ascending=False)
88 | h = 2 / data["resolution"]
89 | nr_elems = data["nr_elems"]
90 |
91 | label=("%d" % (dims) if not use_active_list else None) #('w. AL' if use_active_list else 'w/o AL')
92 | lines_h = axes[elem_dim_i].plot(nr_elems.values, data[data_field].values, linestyle=('--' if use_active_list else '-'), color=colors[dim_i], label=label) #color='b' if use_active_list else 'r')
93 |
94 | if not use_active_list:
95 | lines_hs[elem_dims].append((lines_h[0], dims))
96 |
97 |
98 | if elem_dim_i != 0:
99 | #axes[elem_dim_i].set_yticklabels([])
100 | pass
101 | else:
102 | plt.ylabel("Runtime [s]")
103 |
104 | #Make a nice title from the data
105 | plotted_data = pd_data[pd_data["elem_dims"] == elem_dims]["elem_fname"]
106 | if plotted_data.size > 0:
107 | axes[elem_dim_i].set_title(plotted_data.iat[0].capitalize().replace("_d", " D"))
108 | #axes[elem_dim_i].invert_xaxis()
109 | #plt.xlabel("$h$")
110 | plt.xlabel("#Elements")
111 | plt.xscale("log")
112 | plt.yscale("log")
113 | plt.grid(True, which='both', axis='both')
114 |
115 | #Search for valid handles
116 | used_elem_dims = list(lines_hs.keys())
117 | len_handles = np.array([len(lines_hs[written_dim]) for written_dim in used_elem_dims])
118 |
119 | if np.any(len_handles > 0):
120 | handles, plot_dims = zip(*lines_hs[used_elem_dims[int(np.where(len_handles > 0)[0][0])]])
121 | axes[1].legend(handles, plot_dims, title="$d=$", loc='center', bbox_to_anchor=(0.15, -0.3, 0.75, 0.25), borderpad=0.8, ncol=2)
122 |
123 | if title is None:
124 | fig.suptitle("Fimpy %s Benchmark" % (device.upper()))
125 | else:
126 | fig.suptitle(title % (device.upper()))
127 | fig.set_size_inches((14, 8))
128 | fig.tight_layout()
129 | figs.append(fig)
130 |
131 | if save_fig:
132 | fig.savefig(out_fname + "_%s%s" % (device, fname_postfix) + ".jpg")
133 | fig.savefig(out_fname + "_%s%s" % (device, fname_postfix) + ".pdf")
134 | plt.show()
135 | [plt.close(fig) for fig in figs]
136 | #plt.show()
137 | #pd_data.
138 |
139 | if __name__ == "__main__":
140 | #generate_usage_example(False)
141 | generate_benchmark_plot(os.path.join(os.path.dirname(__file__), "benchmark_results_w_cpu.json"), save_fig=True, data_field="runtime")
142 | generate_benchmark_plot(os.path.join(os.path.dirname(__file__), "benchmark_results_w_cpu.json"), save_fig=True, data_field="setup_time", fname_postfix="_setup", title="%s Setup Time")
143 |
--------------------------------------------------------------------------------
/tests/generate_test_data.py:
--------------------------------------------------------------------------------
1 | """
2 | Testcases:
3 | - Tube
4 | - Sphere
5 | - Cube
6 | - Simplified Heart
7 | - Network
8 | - Use vtkCutter to get 2D data
9 | - With and without anisotropy
10 |
11 | """
12 | import os
13 | from scipy.sparse import coo_matrix
14 | from scipy.sparse.csgraph import minimum_spanning_tree
15 | from scipy.spatial import Delaunay
16 | import numpy as np
17 | #import pyvista as pv
18 | #import vtk
19 | import scipy.io as sio
20 |
21 | test_dims = [1, 2, 3, 5]
22 | bench_dims = test_dims + [10, 20] #, 50] #, 100]
23 |
24 | test_elem_dims = [2, 3, 4]
25 |
26 | test_resolutions = {1: [10, 25, 50],
27 | 2: [5, 10],
28 | 3: [5, 10]}
29 |
30 | bench_resolutions = {1: test_resolutions[1] + [100, 200, 400, 800, 1500],
31 | 2: test_resolutions[2] + [25, 50, 100, 200, 300, 500], #1000],
32 | 3: test_resolutions[3] + [25, 50]} #, 75, 100]}
33 |
34 | elem_fnames = {2: "network", 3: "surface", 4: "tetra_domain"}
35 |
36 | isotropic_het_vel_f = lambda x, dims, scales=1: np.eye(dims)[np.newaxis] * (dims + 0.5 + np.sum(np.sin(x * 2*np.pi / scales), axis=-1))[:, np.newaxis, np.newaxis]
37 |
38 | sanity_size_check = lambda dims, elem_dims, resolution: dims >= 5 and ((elem_dims == 4 and resolution > 50) or (elem_dims == 4 and dims > 10 and resolution > 25)
39 | or (elem_dims == 3 and resolution > 300) or (elem_dims == 2 and resolution > 400))
40 |
41 | def generate_test_data(gen_bench_data=False):
42 |
43 | if gen_bench_data:
44 | data_dir = os.path.join(os.path.dirname(__file__), "benchmark_data")
45 | else:
46 | data_dir = os.path.join(os.path.dirname(__file__), "data")
47 |
48 | if not os.path.isdir(data_dir):
49 | os.mkdir(data_dir)
50 |
51 | for elem_dims in test_elem_dims:
52 | valid_dims = np.array(bench_dims if gen_bench_data else test_dims)
53 | valid_dims = valid_dims[valid_dims >= (elem_dims - 1)] #Request a proper manifold
54 | resolutions = (bench_resolutions if gen_bench_data else test_resolutions)
55 |
56 | for resolution in resolutions[elem_dims-1]:
57 | x = np.linspace(-1, 1, num=resolution)
58 |
59 | #Create the mesh
60 | #Line network
61 | if elem_dims == 2:
62 | pass #Will be calculated as a point cloud for each dimensional case
63 |
64 | #Triangular square surface
65 | elif elem_dims == 3:
66 | X, Y = np.meshgrid(x, x) #, indexing='ij')
67 | points = np.stack([X, Y], axis=-1).reshape([-1, 2])
68 | elems = Delaunay(points[..., :2]).simplices
69 |
70 | #Tetrahedral cube domain
71 | elif elem_dims == 4:
72 | points = np.stack(np.meshgrid(x, x, x, indexing='ij'), axis=-1).reshape([-1, 3])
73 | elems = Delaunay(points).simplices
74 |
75 | for dims in valid_dims:
76 | assert(elem_dims <= (dims+1))
77 |
78 | #Skip very large examples
79 | if sanity_size_check(dims, elem_dims, resolution):
80 | continue
81 |
82 | if elem_dims == 2:
83 | points = np.random.uniform(size=[x.size**2, dims])
84 | repetitions = np.minimum(points.shape[0]*15, points.shape[0]**2) // points.shape[0]
85 | rows = np.concatenate((np.arange(points.shape[0]),)*repetitions, axis=-1)
86 | cols = np.random.choice(points.shape[0], size=points.shape[0]*repetitions)
87 | while np.unique(cols).size != points.shape[0]:
88 | cols = np.random.choice(points.shape[0], size=points.shape[0]*repetitions)
89 | data = np.ones(rows.size)
90 | connectivity_mat = coo_matrix((data, (rows, cols)))
91 | connectivity_mat = 0.5 * (connectivity_mat + connectivity_mat.T).tocsc()
92 | span_tree = minimum_spanning_tree(connectivity_mat)
93 | span_tree.eliminate_zeros()
94 | elems = np.stack(span_tree.nonzero(), axis=-1)
95 |
96 |
97 | elem_fname = elem_fnames[elem_dims]
98 | #Fill the zero dimensions
99 | if points.shape[-1] < dims:
100 | points = np.concatenate([points, np.zeros(shape=[points.shape[0], dims - points.shape[1]])], axis=-1)
101 |
102 | elem_centers = np.mean(points[elems], axis=1)
103 | D = isotropic_het_vel_f(elem_centers, dims)
104 |
105 | fname = "elem_dims_%d_dims_%d_resolution_%d_%s.mat" % (elem_dims, dims, resolution, elem_fname)
106 | if gen_bench_data:
107 | data = {"elems": elems.astype(np.int32), "points": points.astype(np.float32), "D": D.astype(np.float32)}
108 | else:
109 | data = {"elems": elems, "points": points, "D": D}
110 | sio.savemat(os.path.join(data_dir, fname), data, do_compression=True)
111 | print("Created %s" % (fname))
112 | #ug = pv.UnstructuredGrid({vtk_elem_type: elems}, points)
113 | #ug.cell_arrays["D"] = D
114 | #ug.save(fname)
115 |
116 |
117 |
118 | if __name__ == "__main__":
119 | generate_test_data()
--------------------------------------------------------------------------------
/tests/run_benchmark.py:
--------------------------------------------------------------------------------
1 | import os
2 | import sys
3 | import numpy as np
4 | import cupy as cp
5 | #from cupy.cuda.memory import OutOfMemoryError
6 | from cupy.cuda.runtime import CUDARuntimeError
7 | import scipy.io as sio
8 | from fimpy.solver import create_fim_solver
9 | import time
10 | import timeit
11 | from IPython import get_ipython
12 | import json
13 |
14 | from generate_test_data import bench_dims, test_elem_dims, bench_resolutions, elem_fnames, sanity_size_check
15 |
16 | def run_single_test(device, use_active_list, dims, elem_dims, resolution, bench_dict=None):
17 | data_dir = os.path.join(os.path.dirname(__file__), "benchmark_data")
18 | ipython = get_ipython()
19 |
20 | elem_fname = elem_fnames[elem_dims]
21 | fname = "elem_dims_%d_dims_%d_resolution_%d_%s.mat" % (elem_dims, dims, resolution, elem_fname)
22 | fname = os.path.join(data_dir, fname)
23 | assert(os.path.isfile(fname)) #If you fail here, the generation of test data using generate_test_data.py failed or was not performed
24 |
25 | data = sio.loadmat(fname)
26 | points, elems, D = data["points"], data["elems"], data["D"]
27 | nr_points = points.shape[0]
28 |
29 | center_x0 = np.array([np.argmin(np.sum((points - np.mean(points, axis=0, keepdims=True))**2,
30 | axis=-1))])
31 | #x0_vals = np.array([0.])
32 |
33 | #Setup the solver
34 | bt = time.time()
35 | solver = create_fim_solver(points, elems, D, precision=np.float32, device=device, use_active_list=use_active_list)
36 | at = time.time()
37 | setup_time = at - bt
38 |
39 | x0 = center_x0
40 | x0_vals = np.array([0.])
41 |
42 | #Dry run for compilation
43 | bt = time.time()
44 | phi1 = solver.comp_fim(x0, x0_vals)
45 | at = time.time()
46 | init_run_time = at - bt
47 | #return #For profiling
48 |
49 | #
50 | def eval_fim():
51 | result = solver.comp_fim(x0, x0_vals)
52 | if device == 'gpu':
53 | cp.cuda.runtime.deviceSynchronize()
54 | return result
55 |
56 | if ipython is None:
57 | timing_avg = timeit.timeit(lambda: eval_fim(), number=5) / 5
58 | print("Setup time: %f, Avg. compute time: %f, First run time: %f" % (setup_time, timing_avg, init_run_time))
59 | else:
60 | timing = ipython.run_line_magic("timeit", "-o eval_fim()")
61 | timing_avg = timing.average
62 |
63 | if bench_dict is not None:
64 | bench_dict["device"].append(device)
65 | bench_dict["active_list"].append(use_active_list)
66 | bench_dict["dims"].append(dims)
67 | bench_dict["elem_dims"].append(elem_dims)
68 | bench_dict["runtime"].append(timing_avg)
69 | bench_dict["setup_time"].append(setup_time)
70 | bench_dict["elem_fname"].append(elem_fname)
71 | bench_dict["nr_points"].append(points.shape[0])
72 | bench_dict["nr_elems"].append(elems.shape[0])
73 | bench_dict["resolution"].append(resolution)
74 |
75 | print("Finished %s on %s, active list: %s" % (fname, device, use_active_list))
76 |
77 | return setup_time, timing_avg, solver, fname #, points.shape[0], elems.shape[0]
78 |
79 | if __name__ == "__main__":
80 | bench_dict = {"device": [], "active_list": [], "dims": [], "elem_dims": [], "runtime": [], "setup_time": [], "elem_fname": [], "nr_points": [], "nr_elems": [],
81 | "resolution": []}
82 |
83 | bt = time.time()
84 | for device in ['cpu', 'gpu']:
85 | for use_active_list in [True, False]:
86 |
87 | for dims in bench_dims:
88 | if device == 'cpu' and dims not in [1, 2, 3]: #if device == 'cpu' and not use_active_list and dims not in [1, 2, 3]:
89 | continue #TODO: Too slow currently (not using any multithreading)
90 |
91 | if device == 'cpu' and dims > 5:
92 | continue
93 |
94 | for elem_dims in test_elem_dims:
95 | if (dims < elem_dims - 1):
96 | continue
97 |
98 | #if dims > 5 and elem_dims > 2 and use_active_list: #elem_dims == 4 and use_active_list and dims > 3 and resolution > 10 and device == 'gpu':
99 | # continue #Very slow
100 |
101 | for resolution in bench_resolutions[elem_dims-1]:
102 | #Skip very large examples
103 | if sanity_size_check(dims, elem_dims, resolution):
104 | continue
105 |
106 | if elem_dims == 4 and resolution == 100:
107 | continue
108 |
109 | if device == 'cpu' and ((elem_dims == 2 and resolution > 500) or (elem_dims == 4 and resolution > 25) or (elem_dims == 3 and resolution > 250)):
110 | continue
111 |
112 | if device == 'cpu' and dims > 3 and elem_dims == 4 and resolution > 10:
113 | continue
114 |
115 | try:
116 | solver, fname = run_single_test(device, use_active_list, dims, elem_dims, resolution, bench_dict)[-2:]
117 |
118 | if hasattr(solver, 'mempool'):
119 | solver.mempool.free_all_blocks()
120 | except CUDARuntimeError as ex:
121 | print("A single benchmark failed with an exception (probably out of memory).", file=sys.stderr)
122 | print("Parameters: %d, %d, %d, %s" % (dims, elem_dims, resolution, use_active_list) , file=sys.stderr)
123 |
124 |
125 | with open(os.path.join(os.path.dirname(__file__), "benchmark_results_w_cpu.json"), "w") as bench_f:
126 | json.dump(bench_dict, bench_f, indent=2, sort_keys=True)
127 | #sio.savemat(os.path.join(os.path.dirname(__file__), "benchmark_results.mat"), bench_dict, do_compression=True)
128 |
129 | at = time.time()
130 | print("Benchmarking took %f seconds" % (at - bt))
--------------------------------------------------------------------------------
/tests/test_custom_kernels.py:
--------------------------------------------------------------------------------
1 | #import unittest
2 | import pytest
3 | #from .
4 | import numpy as np
5 | import os
6 | from fimpy.fim_cutils import compute_perm_mask, compute_point_elem_map_c, compute_neighborhood_map_c
7 | from scipy.spatial import Delaunay
8 | from itertools import combinations
9 |
10 | try:
11 | import cupy as cp
12 | from fimpy.cupy_kernels import compute_perm_kernel_str, compute_perm_kernel_shared
13 | cupy_enabled = True
14 | #raise ImportError("Test") #For testing the CPU only version
15 | except ImportError as err:
16 | print("Cupy import failed. The tests will skip the cupy tests")
17 | cupy_enabled = False
18 |
19 | class TestCustomKernels():
20 |
21 | def create_mesh(self, elem_dims, resolution):
22 | x = np.linspace(-1, 1, num=resolution)
23 | pts = np.stack(np.meshgrid(*((x,) * elem_dims), indexing='ij'), axis=-1).reshape([-1, elem_dims])
24 | elems = Delaunay(pts).simplices
25 | inds = np.arange(elem_dims+1)
26 | assert(elem_dims in [2, 3])
27 |
28 | if elem_dims == 2:
29 | perms = np.array([[0, 1, 2],
30 | [0, 2, 1],
31 | [2, 1, 0]])
32 | else:
33 | perms = np.array([[0, 1, 2, 3],
34 | [0, 1, 3, 2],
35 | [0, 3, 2, 1],
36 | [3, 1, 2, 0]])
37 | elems_perm = elems[np.arange(elems.shape[0])[:, np.newaxis, np.newaxis], perms[np.newaxis]]
38 |
39 | return pts, elems, elems_perm
40 |
41 | def comp_point_elem_map(self, elems, nr_points):
42 | #TODO: Export into function?
43 | max_point_elem_ratio = np.max(np.unique(elems, return_counts=True)[1])
44 | point_elem_map = np.zeros([nr_points, max_point_elem_ratio], dtype=np.int32)
45 | compute_point_elem_map_c(elems, point_elem_map)
46 | return point_elem_map
47 |
48 | def comp_neighborhood_map(self, elems, nr_points, elem_dims):
49 | max_point_elem_ratio = np.max(np.unique(elems, return_counts=True)[1])
50 | nh_map = np.zeros(shape=[nr_points, max_point_elem_ratio * elem_dims], dtype=np.int32)
51 |
52 | nh_map = np.array(compute_neighborhood_map_c(elems, nh_map))
53 |
54 | nh_map = np.sort(nh_map, axis=-1)
55 |
56 | # There may be cases where the ratio was an overestimate
57 | while nh_map.shape[1] > 1 and np.all(nh_map[..., -1] == nh_map[..., -2]):
58 | nh_map = nh_map[..., :-1]
59 |
60 | return nh_map
61 |
62 | @pytest.mark.skipif(not cupy_enabled, reason='Cupy could not be imported. GPU tests unavailable')
63 | @pytest.mark.parametrize('elem_dims', [3, 4])
64 | @pytest.mark.parametrize('resolution', [5, 10, 15])
65 | @pytest.mark.parametrize('nr_active_inds', [1, 20, 100])
66 | @pytest.mark.parametrize('parallel_blocks', [1, 4, 16])
67 | @pytest.mark.parametrize('threads_x', [1, 16, 32])
68 | @pytest.mark.parametrize('threads_y', [1]) #, 16, 32]) #New kernel with binary search does not use this
69 | @pytest.mark.parametrize('shared_buf_size', [1, 128, 2048])
70 | def test_perm_kernel_gpu2(self, elem_dims, resolution, nr_active_inds, parallel_blocks, threads_x, threads_y, shared_buf_size):
71 | pts, elems, elems_perm = self.create_mesh(elem_dims-1, resolution)
72 | nr_pts = pts.shape[0]
73 |
74 | elems_perm = cp.array(elems_perm)
75 | point_elem_map = cp.array(self.comp_point_elem_map(elems, nr_pts))
76 | active_inds = cp.sort(cp.array(np.random.choice(nr_pts, np.minimum(nr_active_inds, nr_pts), replace=False)))
77 | active_elem_inds = cp.unique(point_elem_map[active_inds].reshape([-1]))
78 | active_elems_perm = elems_perm[active_elem_inds]
79 |
80 | perm_kernel = cp.RawKernel(compute_perm_kernel_shared.replace("{active_perms}", str(elem_dims)).replace("{parallel_blocks}", str(parallel_blocks)).replace("{shared_buf_size}", str(shared_buf_size)),
81 | 'perm_kernel', options=('-std=c++11',), backend='nvcc')
82 | perm_kernel.compile()
83 | perm_mask_output = cp.zeros(shape=active_elems_perm.shape[0:2], dtype=bool)
84 | perm_kernel((parallel_blocks,), (threads_x,threads_y, 1), (cp.ascontiguousarray(active_elems_perm[..., -1]), active_inds.astype(cp.int32), perm_mask_output, active_elems_perm.shape[0], active_inds.size))
85 | #Broadcasted version is the ground truth
86 | perm_mask_gt = np.any(active_elems_perm[..., -1, np.newaxis] == active_inds[np.newaxis, np.newaxis], axis=-1)
87 | assert(np.all(perm_mask_output == perm_mask_gt))
88 |
89 | if __name__ == "__main__":
90 | self = TestCustomKernels()
91 | parallel_blocks = 4
92 | threads_x = 32
93 | threads_y = 1
94 | shared_buf_size = 1024
95 | nr_active_inds = 5
96 | elem_dims = 3
97 | resolution = 15
98 | pts, elems, elems_perm = self.create_mesh(elem_dims-1, resolution)
99 | nr_pts = pts.shape[0]
100 |
101 | elems_perm = cp.array(elems_perm)
102 | point_elem_map = cp.array(self.comp_point_elem_map(elems, nr_pts))
103 | active_inds = cp.sort(cp.array(np.random.choice(nr_pts, np.minimum(nr_active_inds, nr_pts), replace=False)))
104 | active_elem_inds = cp.unique(point_elem_map[active_inds].reshape([-1]))
105 | active_elems_perm = elems_perm[active_elem_inds]
106 |
107 | perm_kernel = cp.RawKernel(compute_perm_kernel_shared.replace("{active_perms}", str(elem_dims)).replace("{parallel_blocks}", str(parallel_blocks)).replace("{shared_buf_size}", str(shared_buf_size)),
108 | 'perm_kernel')
109 | perm_kernel.compile()
110 | perm_mask_output = cp.zeros(shape=active_elems_perm.shape[0:2], dtype=bool)
111 | perm_kernel((parallel_blocks,), (threads_x,threads_y, 1), (cp.ascontiguousarray(active_elems_perm[..., -1]), active_inds.astype(cp.int32), perm_mask_output, active_elems_perm.shape[0], active_inds.size))
112 | #Broadcasted version is the ground truth
113 | perm_mask_gt = np.any(active_elems_perm[..., -1, np.newaxis] == active_inds[np.newaxis, np.newaxis], axis=-1)
114 | assert(np.all(perm_mask_output == perm_mask_gt))
--------------------------------------------------------------------------------
/tests/test_cython_methods.py:
--------------------------------------------------------------------------------
1 | from fimpy.utils.comp import metric_norm_matrix_2D_cython, metric_norm_matrix_3D_cython
2 | import numpy as np
3 | import pytest
4 |
5 | class TestCythonMethods():
6 |
7 | @pytest.mark.parametrize("prec", [np.float32, np.float64])
8 | def test_2D_vec(self, prec):
9 | rtol = (1e-3 if prec == np.float32 else 1e-4)
10 | A = np.random.normal(size=(100, 2, 2)).astype(prec)
11 | A[..., 1, 0] = A[..., 0, 1] #Symmetrize
12 |
13 | z1 = np.random.normal(size=(100, 2)).astype(prec)
14 | z2 = np.random.normal(size=(100, 2)).astype(prec)
15 |
16 | expected_result = np.einsum('...x,...xy,...y->...', z1, A, z2)
17 | comp_result = metric_norm_matrix_2D_cython(A, z1, z2, ret_sqrt=False)
18 | assert np.allclose(expected_result, comp_result, rtol=rtol)
19 |
20 | #Broadcasted
21 | A = np.random.normal(size=(100, 1, 2, 2))
22 | A[..., 1, 0] = A[..., 0, 1] #Symmetrize
23 |
24 | z1 = np.random.normal(size=(100, 3, 2))
25 | z2 = np.random.normal(size=(100, 3, 2))
26 |
27 | expected_result = np.einsum('...x,...xy,...y->...', z1, A, z2)
28 | comp_result = metric_norm_matrix_2D_cython(A, z1, z2, ret_sqrt=False)
29 | assert np.allclose(expected_result, comp_result, rtol=rtol) #Broadcasted
30 |
31 | @pytest.mark.parametrize("prec", [np.float32, np.float64])
32 | def test_3D_vec(self, prec):
33 | rtol = (1e-3 if prec == np.float32 else 1e-4)
34 | A = np.random.normal(size=(100, 3, 3)).astype(prec)
35 | A[..., 1, 0] = A[..., 0, 1] #Symmetrize
36 | A[..., 2, 0] = A[..., 0, 2]
37 | A[..., 2, 1] = A[..., 1, 2]
38 |
39 | z1 = np.random.normal(size=(100, 3)).astype(prec)
40 | z2 = np.random.normal(size=(100, 3)).astype(prec)
41 |
42 | expected_result = np.einsum('...x,...xy,...y->...', z1, A, z2)
43 | comp_result = metric_norm_matrix_3D_cython(A, z1, z2, ret_sqrt=False)
44 | assert np.allclose(expected_result, comp_result, rtol=rtol) #Single vectorized
45 |
46 | #Broadcasted
47 | A = np.random.normal(size=(100, 1, 3, 3))
48 | A[..., 1, 0] = A[..., 0, 1] #Symmetrize
49 | A[..., 2, 0] = A[..., 0, 2]
50 | A[..., 2, 1] = A[..., 1, 2]
51 |
52 | z1 = np.random.normal(size=(100, 4, 3))
53 | z2 = np.random.normal(size=(100, 4, 3))
54 |
55 | expected_result = np.einsum('...x,...xy,...y->...', z1, A, z2)
56 | comp_result = metric_norm_matrix_3D_cython(A, z1, z2, ret_sqrt=False)
57 | assert np.allclose(expected_result, comp_result, rtol=rtol)
58 |
59 |
60 |
--------------------------------------------------------------------------------
/tests/test_fim_solvers.py:
--------------------------------------------------------------------------------
1 | #import unittest
2 | import pytest
3 | #from .
4 | from fimpy.solver import create_fim_solver
5 | from fimpy.solver import FIMPY #Deprecated interface
6 | import numpy as np
7 | import os
8 | import scipy.io as sio
9 | import pickle
10 |
11 | try:
12 | import cupy as cp
13 | cupy_enabled = True
14 | #raise ImportError("Test") #For testing the CPU only version
15 | except ImportError as err:
16 | print("Cupy import failed. The tests will skip the cupy tests")
17 | cupy_enabled = False
18 |
19 | class TestFIMSolversInit():
20 |
21 | @pytest.mark.parametrize('init_D', [True, False])
22 | @pytest.mark.parametrize('dims', [1, 2, 3])
23 | @pytest.mark.parametrize('precision', [np.float32, np.float64])
24 | @pytest.mark.parametrize('use_active_list', [True, False])
25 | @pytest.mark.parametrize('device', ['cpu', 'gpu'])
26 | def test_init(self, dims, init_D, precision, use_active_list, device):
27 | if device == 'gpu' and not cupy_enabled:
28 | pytest.skip(reason='Cupy could not be imported. GPU tests unavailable')
29 |
30 | points, elems = self.dummy_mesh(dims)
31 | D = None
32 | if init_D:
33 | D = np.eye(dims)[np.newaxis]
34 |
35 | fim_solver = create_fim_solver(points, elems, D, device=device, precision=precision, use_active_list=use_active_list)
36 | return fim_solver
37 |
38 | def dummy_mesh(self, dims):
39 | points = np.tile(np.linspace(0, 1, num=4)[:(dims+1)][:, np.newaxis], [1, dims])
40 | elems = np.arange(points.shape[0])[np.newaxis]
41 | return points, elems
42 |
43 | @pytest.mark.parametrize('precision', [np.float32, np.float64])
44 | def test_error_init(self, precision, device='cpu'):
45 | points = np.array([0.])
46 | elems = np.array([0])
47 |
48 | #Wrong dimensions
49 | with pytest.raises(Exception):
50 | create_fim_solver(points, elems)
51 |
52 | #Points not numeric
53 | points = np.array([[0, 0], [1, 0]]).astype(np.int32)
54 | elems = np.array([[0, 1]])
55 | with pytest.raises(Exception):
56 | create_fim_solver(points, elems)
57 |
58 | #D and elems not matching
59 | points = np.array([[0., 0], [1, 0]])
60 | elems = np.array([[0, 1]])
61 | D = np.tile(np.eye(2)[np.newaxis], [2, 1])
62 | with pytest.raises(Exception):
63 | create_fim_solver(points, elems, D)
64 |
65 | #elems references non-existant points
66 | points = np.array([[0., 0.], [1., 0.]])
67 | elems = np.array([[0, 1, 2]])
68 | with pytest.raises(Exception):
69 | create_fim_solver(points, elems, precision=precision, device=device)
70 |
71 |
72 | #points not contained in any element
73 | points = np.array([[0., 0.], [1., 0.], [0., 1.]])
74 | elems = np.array([[0, 1]])
75 | with pytest.raises(Exception):
76 | create_fim_solver(points, elems, precision=precision, device=device)
77 |
78 | #Unsupported element dimensions (Polygons and other elements)
79 | points = np.array([[0., 0.], [1., 0.], [0., 1.], [1., 1.], [-1., 0.]])
80 | elems = np.array([[0, 1, 2, 3, 4]])
81 | with pytest.raises(Exception):
82 | create_fim_solver(points, elems, precision=precision, device=device)
83 |
84 |
85 | @pytest.mark.skipif(not cupy_enabled, reason='Cupy could not be imported. GPU tests unavailable')
86 | @pytest.mark.parametrize('precision', [np.float32, np.float64])
87 | def test_error_init_gpu(self, precision):
88 | self.test_error_init(precision, 'gpu')
89 |
90 | def test_error_init_wrong_device(self):
91 | with pytest.raises(AssertionError):
92 | self.test_init(3, True, np.float32, use_active_list=False, device='undefined_device')
93 |
94 | def test_error_deprecated(self):
95 | solver2 = FIMPY.create_fim_solver(*self.dummy_mesh(2))
96 | solver = create_fim_solver(*self.dummy_mesh(2))
97 | assert pickle.dumps(solver) == pickle.dumps(solver2) #Serialized objects should be exactly the same
98 |
99 | @pytest.mark.parametrize('init_D', [True, False])
100 | @pytest.mark.parametrize('dims', [1, 2, 3])
101 | @pytest.mark.parametrize('precision', [np.float32, np.float64])
102 | @pytest.mark.parametrize('use_active_list', [True, False])
103 | @pytest.mark.parametrize('device', ['cpu', 'gpu'])
104 | def test_solver_serializable(self, dims, init_D, precision, use_active_list, device):
105 | solver = self.test_init(dims, init_D, precision, use_active_list, device)
106 | solver_ser = pickle.dumps(solver)
107 | solver_unser = pickle.loads(solver_ser)
108 | assert np.all(solver.points_perm == solver_unser.points_perm)
109 |
110 | from generate_test_data import test_dims, test_elem_dims, test_resolutions, elem_fnames
111 |
112 | class TestFIMSolversComputations():
113 |
114 | test_dir = os.path.join(__file__, "data")
115 |
116 | @pytest.mark.parametrize('precision', [np.float32, np.float64])
117 | @pytest.mark.parametrize('dims', test_dims)
118 | @pytest.mark.parametrize('elem_dims', test_elem_dims)
119 | @pytest.mark.parametrize('use_active_list', [True, False])
120 | def test_comp(self, dims, elem_dims, precision, use_active_list, device='cpu'):
121 | if (dims < elem_dims - 1):
122 | return
123 |
124 | np.random.seed(0)
125 | test_data_dir = os.path.join(os.path.dirname(__file__), "data")
126 | for resolution in test_resolutions[elem_dims-1]:
127 | fname = "elem_dims_%d_dims_%d_resolution_%d_%s.mat" % (elem_dims, dims, resolution, elem_fnames[elem_dims])
128 | fname = os.path.join(test_data_dir, fname)
129 | assert(os.path.isfile(fname)) #If you fail here, the generation of test data using generate_test_data.py failed or was not performed
130 |
131 | data = sio.loadmat(fname)
132 | points, elems, D = data["points"], data["elems"], data["D"]
133 | nr_points = points.shape[0]
134 |
135 | #D specified at initialization
136 | solver = create_fim_solver(points, elems, D, precision=precision, device=device, use_active_list=use_active_list)
137 | x0 = np.array([np.random.choice(nr_points)])
138 | x0_vals = np.array([0.])
139 | phi1 = solver.comp_fim(x0, x0_vals)
140 | assert(phi1.dtype == precision)
141 | assert(phi1.ndim == 1)
142 | assert(phi1.size == nr_points)
143 | assert(np.all(~np.isnan(phi1)))
144 |
145 | #D specified at computation
146 | solver = create_fim_solver(points, elems, precision=precision, device=device, use_active_list=use_active_list)
147 | #Fails without specifying D
148 | with pytest.raises(Exception):
149 | solver.comp_fim(x0, x0_vals)
150 |
151 | phi2 = solver.comp_fim(x0, x0_vals, D)
152 | assert(phi2.dtype == precision)
153 | assert(phi2.ndim == 1)
154 | assert(phi2.size == nr_points)
155 | assert(np.all(~np.isnan(phi2)))
156 |
157 | #Results should be the same
158 | assert(np.allclose(phi1, phi2))
159 |
160 |
161 |
162 |
163 | @pytest.mark.skipif(not cupy_enabled, reason='Cupy could not be imported. GPU tests unavailable')
164 | @pytest.mark.parametrize('precision', [np.float32, np.float64])
165 | @pytest.mark.parametrize('dims', test_dims)
166 | @pytest.mark.parametrize('elem_dims', test_elem_dims)
167 | @pytest.mark.parametrize('use_active_list', [True, False])
168 | def test_comp_gpu(self, dims, elem_dims, precision, use_active_list):
169 | self.test_comp(dims, elem_dims, precision, use_active_list=use_active_list, device='gpu')
170 |
--------------------------------------------------------------------------------