├── .dockerignore ├── .github └── workflows │ ├── build_wheel.yml │ └── test.yml ├── .gitignore ├── AUTHORS ├── ChangeLog ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.md ├── automated_test.py ├── build_linux.sh ├── dijkstra3d.hpp ├── dijkstra3d.png ├── dijkstra3d.pyx ├── hedly.h ├── libdivide.h ├── manylinux1.Dockerfile ├── manylinux2010.Dockerfile ├── manylinux2014.Dockerfile ├── multi-color-self-touch.png ├── multimethod.png ├── perf.py ├── pyproject.toml ├── requirements.txt ├── requirements_dev.txt ├── setup.py ├── test.cpp └── tox.ini /.dockerignore: -------------------------------------------------------------------------------- 1 | build 2 | *.egg-info 3 | benchmarks 4 | __pycache__ 5 | manual_testing 6 | .eggs 7 | .git 8 | .tox 9 | .pytest_cache -------------------------------------------------------------------------------- /.github/workflows/build_wheel.yml: -------------------------------------------------------------------------------- 1 | name: Build Wheels 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | tags: 7 | - '*' 8 | env: 9 | CIBW_SKIP: cp27-* cp33-* cp34-* cp35-* cp36-* pp27* pp36* pp37* pp38* pp39* pp310* 10 | 11 | jobs: 12 | build_wheels: 13 | name: Build wheels on ${{matrix.arch}} for ${{ matrix.os }} 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [ubuntu-latest, windows-2019, macos-latest] 18 | arch: [auto] 19 | include: 20 | - os: ubuntu-latest 21 | arch: aarch64 22 | 23 | steps: 24 | - uses: actions/checkout@v4 25 | 26 | - name: Set up QEMU 27 | if: ${{ matrix.arch == 'aarch64' }} 28 | uses: docker/setup-qemu-action@v1 29 | 30 | - name: Build wheels 31 | uses: joerick/cibuildwheel@v2.22.0 32 | # to supply options, put them in 'env', like: 33 | env: 34 | CIBW_ARCHS_LINUX: ${{matrix.arch}} 35 | CIBW_BEFORE_BUILD: pip install numpy setuptools wheel cython twine pkginfo 36 | CIBW_ARCHS_MACOS: "x86_64 arm64" 37 | 38 | - uses: actions/upload-artifact@v2 39 | with: 40 | path: ./wheelhouse/*.whl 41 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - "*" 10 | 11 | jobs: 12 | run_tests: 13 | name: Test ${{ matrix.os }} Python ${{ matrix.python-version }} 14 | runs-on: ${{ matrix.os }} 15 | strategy: 16 | matrix: 17 | os: [ubuntu-latest, macos-latest, windows-2019] 18 | python-version: ["3.8", "3.9", "3.10", "3.11", "3.12"] 19 | 20 | steps: 21 | - name: Set up Python ${{ matrix.python-version }} 22 | uses: actions/setup-python@v2 23 | with: 24 | python-version: ${{ matrix.python-version }} 25 | package-dir: ./python 26 | 27 | - uses: actions/checkout@v2 28 | 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | python -m pip install pytest -r requirements.txt -r requirements_dev.txt cython setuptools wheel 33 | 34 | - name: Compile 35 | run: python setup.py develop 36 | 37 | - name: Test with pytest 38 | run: pytest -v -x automated_test.py 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Prerequisites 2 | *.d 3 | 4 | # Compiled Object files 5 | *.slo 6 | *.lo 7 | *.o 8 | *.obj 9 | 10 | # Precompiled Headers 11 | *.gch 12 | *.pch 13 | 14 | # Compiled Dynamic libraries 15 | *.so 16 | *.dylib 17 | *.dll 18 | 19 | # Fortran module files 20 | *.mod 21 | *.smod 22 | 23 | # Compiled Static libraries 24 | *.lai 25 | *.la 26 | *.a 27 | *.lib 28 | 29 | # Executables 30 | *.exe 31 | *.out 32 | *.app 33 | 34 | 35 | # Byte-compiled / optimized / DLL files 36 | __pycache__/ 37 | *.py[cod] 38 | *$py.class 39 | 40 | # C extensions 41 | *.so 42 | 43 | # Distribution / packaging 44 | .Python 45 | env/ 46 | build/ 47 | develop-eggs/ 48 | dist/ 49 | downloads/ 50 | eggs/ 51 | .eggs/ 52 | lib/ 53 | lib64/ 54 | parts/ 55 | sdist/ 56 | var/ 57 | wheels/ 58 | *.egg-info/ 59 | .installed.cfg 60 | *.egg 61 | 62 | # PyInstaller 63 | # Usually these files are written by a python script from a template 64 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 65 | *.manifest 66 | *.spec 67 | 68 | # Installer logs 69 | pip-log.txt 70 | pip-delete-this-directory.txt 71 | 72 | # Unit test / coverage reports 73 | htmlcov/ 74 | .tox/ 75 | .coverage 76 | .coverage.* 77 | .cache 78 | nosetests.xml 79 | coverage.xml 80 | *.cover 81 | .hypothesis/ 82 | 83 | # Translations 84 | *.mo 85 | *.pot 86 | 87 | # Django stuff: 88 | *.log 89 | local_settings.py 90 | 91 | # Flask stuff: 92 | instance/ 93 | .webassets-cache 94 | 95 | # Scrapy stuff: 96 | .scrapy 97 | 98 | # Sphinx documentation 99 | docs/_build/ 100 | 101 | # PyBuilder 102 | target/ 103 | 104 | # Jupyter Notebook 105 | .ipynb_checkpoints 106 | 107 | # pyenv 108 | .python-version 109 | 110 | # celery beat schedule file 111 | celerybeat-schedule 112 | 113 | # SageMath parsed files 114 | *.sage.py 115 | 116 | # dotenv 117 | .env 118 | 119 | # virtualenv 120 | .venv 121 | venv/ 122 | ENV/ 123 | 124 | # Spyder project settings 125 | .spyderproject 126 | .spyproject 127 | 128 | # Rope project settings 129 | .ropeproject 130 | 131 | # mkdocs documentation 132 | /site 133 | 134 | # mypy 135 | .mypy_cache/ 136 | .pytest_cache 137 | 138 | test.py 139 | test 140 | 141 | dijkstra3d.cpp -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | William Silversmith 2 | -------------------------------------------------------------------------------- /ChangeLog: -------------------------------------------------------------------------------- 1 | CHANGES 2 | ======= 3 | 4 | 1.6.0 5 | ----- 6 | 7 | * release(1.6.0): faster 6 and 18-way dijkstra 8 | * fix: CC -> CXX 9 | * chore: add py39 to build 10 | * perf: improve speed for dijkstra 6-way and 18-way 11 | * chore(build): add infrastructure for building manylinux2010 & 2014 12 | 13 | 1.5.1 14 | ----- 15 | 16 | * release(1.5.1): fix broken py38 release for MacOS 17 | * chore: update changelog 18 | 19 | 1.5.0 20 | ----- 21 | 22 | * release(1.5.0): adds free\_space\_radius to EDF 23 | * release(1.5.0): adds free\_space\_radius to EDF 24 | * chore: more requirements\_dev.txt changes 25 | * chore: create requirements\_dev.txt 26 | * chore: add tox.ini for mac builds 27 | * chore: add appveyor.yml for windows builds 28 | * chore: update to production/stable and update python versions to tested ones 29 | * test: add 3.8 to travis 30 | * perf: euclidean distance field acceleration (#11) 31 | 32 | 1.4.2 33 | ----- 34 | 35 | * release(1.4.2): fix 64-bit addressable in euclidean distance field 36 | * fix: ensure index is large enough for large images 37 | 38 | 1.4.1 39 | ----- 40 | 41 | * release(1.4.1): update libdivide to support clang compilation 42 | * chore: update libdivide.h 43 | * chore: update Changelog 44 | 45 | 1.4.0 46 | ----- 47 | 48 | * release(1.4.0): support 64-bit addressable arrays 49 | * feat: support arrays with 64-bit indices (#10) 50 | * docs: link connectivity numbers to their respective distance metrics 51 | * docs: eliminate duplicate text, specify finite weights 52 | 53 | 1.3.1 54 | ----- 55 | 56 | * release(1.3.1): improved heuristics for 6 and 18 connected compass 57 | * perf: add decent heuristic for 18 connected 58 | * fix: don't modify a const variable 59 | * chore: update ChangeLog 60 | * perf: use correct distance measure for 6 connected 61 | * fix: don't modify a const variable 62 | * chore: update ChangeLog 63 | 64 | 1.3.0 65 | ----- 66 | 67 | * release(1.3.0): adds connectivity and compass parameters 68 | * docs: improve performance test and documentation 69 | * docs: add random start/target performance numbers 70 | * docs: add description of how to use cpp compass search 71 | * docs: update benchmark with A\* 72 | * docs: show how to use the compass feature 73 | * test: additional tests for A\* search 74 | * feat: add A\* search via "compass" parameter to djikstra (#6) 75 | * feat: accept 4 and 8 connectivity for 2D images 76 | * fix: update description of connectivity for 2D 77 | * docs: add connectivity to README.md 78 | * feat: add support for 6 and 18 connectivities (#8) 79 | * chore: update ChangeLog 80 | 81 | 1.2.0 82 | ----- 83 | 84 | * release(1.2.0): bidirectional search option 85 | * docs: update with new benchmark 86 | * docs: add reference to original bidirectional search paper 87 | * feat: bidirectional dijkstra (#5) 88 | * docs: reword some sentences in README.md 89 | * fix: make python3.5 compile better on macOS 90 | * fix: replace size\_t with uint64\_t to make libdivide work on mac 91 | 92 | 1.1.0 93 | ----- 94 | 95 | * release(1.1.0): fortran + removing copy ops 96 | * feat+perf: mandate fortran order arrays + avoid copies (#4) 97 | * refactor: not necessary to pass loc to compute\_neighborhood 98 | * test: source == target 99 | * perf: simplify search when source == target 100 | * chore: update setup.cfg with markdown description content type 101 | * Update README.md 102 | * docs: added reference for early termination technique 103 | * chore: drop py34 from travis testing 104 | 105 | 1.0.1 106 | ----- 107 | 108 | * chore: drop py34 binary support 109 | * chore: version 1.0.1 110 | * refactor: remove experimental code comment 111 | * perf: use libdivide.h for faster x y z computation 112 | * docs: added link to PyPI 113 | 114 | 1.0.0 115 | ----- 116 | 117 | * chore: added py37 to setup.cfg 118 | * test: add Python 3.7 to travis testing 119 | * chore: add documentation and rename dijkstra to dijkstra3d 120 | * chore: setting up for PyPI distribution 121 | * test: fill out cpp test code with an example 122 | * docs: update timestamp 123 | * fix: euclidean\_distance\_field could be succeptible to non-boolean fields 124 | * perf: faster dijkstra3d 125 | * perf: faster euclidean distance field 126 | * perf: 10% faster 127 | * perf: bug in distance\_field3d was hurting performance a lot 128 | * fix: rows/cols swapped in path\_from\_parents 129 | * docs: updated module help 130 | * perf: added parental\_field and path\_from\_parents 131 | * docs: added anisotropy to euclidean\_distance\_field help 132 | * feat: euclidean distance field 133 | * feat: supported uints more fully for dijkstra 134 | * doc: why does fortran order work? idk 135 | * fix: simplified distance\_field 136 | * fix: reconciled various transpositions 137 | * test: added more complex test to dijkstra 138 | * fix: algorithm was not properly checking visited 139 | * fix: handle fortran order (by converting to C order..) 140 | * docs: elaborated on where different contributions to memory usage come from 141 | * docs: added benchmark 142 | * feat: added support for uints and bools 143 | * docs: added reference to Dijkstra paper 144 | * docs: how to use distance\_field, performance info 145 | * docs: added travis badge 146 | * test: added 3d tests 147 | * test: added automated tests 148 | * fix: pyx handle Fortran ordered arrays in distance\_field 149 | * fix: memory leak in distance field calculation 150 | * fix: accomodate 2d and 3d inputs to dijkstra 151 | * fix: row col depth assignment in distance\_field 152 | * fix: corrected neighbor calculation and signed bit is actually needed 153 | * feat: added prototype of distance\_field function 154 | * docs: show how to use 155 | * fix: made point cloud output sensible for 2D 156 | * refactor: broke dijkstra function into components for neatness 157 | * feat: running python code 158 | * feat: Cython bindings for dijkstra3d 159 | * feat: added dijkstra namespace, 2d and 3d functions 160 | * refactor: make x,y,z translation more explicit 161 | * perf: mostly eliminated compute\_neighborhood as a CPU suck 162 | * perf: shaved another 10sec off the 512^3 163 | * fix: removed pairing\_heap.hpp include 164 | * perf: switched to std::priority\_queue, 20% speedup 165 | * feat: moving to 26-hood 166 | * feat: moved to 18-hood from 6-hood 167 | * refactor: allocate heap instance on stack (not the full tree) 168 | * refactor: allocate neighborhood on the stack 169 | * fix: y coordinate computed incorrectly 170 | * feat: now returns st path as a vector of array indicies 171 | * perf: break out of the loop early, saves huge computation 172 | * perf: a more dangerous, but highly performant improvement to running time 173 | * perf: faster delmin through reserving vector size 174 | * fix: dijkstra working but kinda slow, but very low memory 175 | * fix: compilation warnings 176 | * fix: improper deletion of heap 177 | * fix: segmentation fault from accessing dist after free 178 | * wip: moving towards a heap based dijkstra 179 | * chore: add -std=c++11 to test compilation 180 | * perf: why use two operations when you can have one 181 | * fix: don't segfault when printing with no root 182 | * perf: ensure compiler can optimize forest.size() 183 | * fix: propogated "last" fix for odd sizes 184 | * fix: pairing heap now sorts numbers 185 | * docs: fixed formatting in a comment 186 | * test: added heap sort test 187 | * fix: construct PHNode correctly 188 | * fix: syntax errors in pairing\_heap.hpp 189 | * feat: untested pairing heap implementation 190 | * docs: added paper references 191 | * feat: a classic algorithm, O(V^2) 192 | * Initial commit 193 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 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 General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include dijkstra3d.hpp 2 | include libdivide.h 3 | include hedly.h 4 | include LICENSE 5 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | d: FORCE 2 | g++ -std=c++11 -O3 -ffast-math -g dijkstra3d.cpp -o d 3 | 4 | test: FORCE 5 | g++ -std=c++11 -O3 -ffast-math -g test.cpp -o test 6 | 7 | FORCE: -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![PyPI version](https://badge.fury.io/py/dijkstra3d.svg)](https://badge.fury.io/py/dijkstra3d) 2 | 3 | # dijkstra3d 4 | Dijkstra's Shortest Path variants for 6, 18, and 26-connected 3D Image Volumes or 4 and 8-connected 2D images. 5 | 6 | ```python 7 | import dijkstra3d 8 | import numpy as np 9 | 10 | field = np.ones((512, 512, 512), dtype=np.int32) 11 | source = (0,0,0) 12 | target = (511, 511, 511) 13 | 14 | 15 | # If you're working with a binary image with one color considered 16 | # foreground the other background, use this function. 17 | path = dijkstra3d.binary_dijkstra(field, source, target, background_color=0) 18 | path = dijkstra3d.binary_dijkstra( 19 | field, source, target, 20 | anisotropy=(2.0, 2.0, 1.0), 21 | ) 22 | 23 | # path is an [N,3] numpy array i.e. a list of x,y,z coordinates 24 | # terminates early, default is 26 connected 25 | path = dijkstra3d.dijkstra(field, source, target, connectivity=26) 26 | path = dijkstra3d.dijkstra(field, source, target, bidirectional=True) # 2x memory usage, faster 27 | 28 | # Use distance from target as a heuristic (A* search) 29 | # Does nothing if bidirectional=True (it's just not implemented) 30 | path = dijkstra3d.dijkstra(field, source, target, compass=True) 31 | 32 | # parental_field is a performance optimization on dijkstra for when you 33 | # want to return many target paths from a single source instead of 34 | # a single path to a single target. `parents` is a field of parent voxels 35 | # which can then be rapidly traversed to yield a path from the source. 36 | # The initial run is slower as we cannot stop early when a target is found 37 | # but computing many paths is much faster. The unsigned parental field is 38 | # increased by 1 so we can represent background as zero. So a value means 39 | # voxel+1. Use path_from_parents to compute a path from the source to a target. 40 | parents = dijkstra3d.parental_field(field, source=(0,0,0), connectivity=6) # default is 26 connected 41 | path = dijkstra3d.path_from_parents(parents, target=(511, 511, 511)) 42 | print(path.shape) 43 | 44 | # Given a boolean label "field" and a source vertex, compute 45 | # the anisotropic euclidean chamfer distance from the source to all labeled vertices. 46 | # Source can be a single point or a list of points. Accepts bool, (u)int8 dtypes. 47 | dist_field = dijkstra3d.euclidean_distance_field(field, source=(0,0,0), anisotropy=(4,4,40)) 48 | 49 | sources = [ (0,0,0), (10, 40, 232) ] 50 | dist_field = dijkstra3d.euclidean_distance_field( 51 | field, source=sources, anisotropy=(4,4,40) 52 | ) 53 | # You can return a map of source vertices to nearest voxels called 54 | # a feature map. 55 | dist_field, feature_map = dijkstra3d.euclidean_distance_field( 56 | field, source=sources, return_feature_map=True, 57 | ) 58 | 59 | # To make the EDF go faster add the free_space_radius parameter. It's only 60 | # safe to use if you know that some distance around the source point 61 | # is unobstructed space. For that region, we use an equation instead 62 | # of dijkstra's algorithm. Hybrid algorithm! free_space_radius is a physical 63 | # distance, meaning you must account for anisotropy in setting it. 64 | dist_field = dijkstra3d.euclidean_distance_field(field, source=(0,0,0), anisotropy=(4,4,40), free_space_radius=300) 65 | 66 | # You can also get one of the possibly multiple maxima locations instantly. 67 | dist_field, max_loc = dijkstra3d.euclidean_distance_field(field, source=(0,0,0), return_max_location=True) 68 | 69 | # Given a numerical field, for each directed edge from adjacent voxels A and B, 70 | # use B as the edge weight. In this fashion, compute the distance from a source 71 | # point for all finite voxels. 72 | dist_field = dijkstra3d.distance_field(field, source=(0,0,0)) # single source 73 | dist_field = dijkstra3d.distance_field(field, source=[ (0,0,0), (52, 55, 23) ]) # multi-source 74 | dist_field, max_loc = dijkstra3d.distance_field(field, source=(0,0,0), return_max_location=True) # get the location of one of the maxima 75 | 76 | # You can also provide a voxel connectivity graph to provide customized 77 | # constraints on the permissible directions of travel. The graph is a 78 | # uint32 image of equal size that contains a bitfield in each voxel 79 | # where each of the first 26-bits describes whether a direction is 80 | # passable. The description of this field can be seen here: 81 | # https://github.com/seung-lab/connected-components-3d/blob/3.2.0/cc3d_graphs.hpp#L73-L92 82 | # 83 | # The motivation for this feature is handling self-touching labels, but there 84 | # are many possible ways of using this. 85 | graph = np.zeros(field.shape, dtype=np.uint32) 86 | graph += 0xffffffff # all directions are permissible 87 | graph[5,5,5] = graph[5,5,5] & 0xfffffffe # sets +x direction as impassable at this voxel 88 | path = dijkstra.dijkstra(..., voxel_graph=graph) 89 | ``` 90 | 91 | Perform dijkstra's shortest path algorithm on a 3D image grid. Vertices are voxels and edges are the nearest neighbors. For 6 connected images, these are the faces of the voxel (L1: manhattan distance), 18 is faces and edges, 26 is faces, edges, and corners (L: chebyshev distance). For given input voxels A and B, the edge weight from A to B is B and from B to A is A. All weights must be finite and non-negative (incl. negative zero). 92 | 93 | ## What Problem does this Package Solve? 94 | 95 | This package was developed in the course of exploring TEASAR skeletonization of 3D image volumes (now available in [Kimimaro](https://github.com/seung-lab/kimimaro)). Other commonly available packages implementing Dijkstra used matricies or object graphs as their underlying implementation. In either case, these generic graph packages necessitate explicitly creating the graph's edges and vertices, which turned out to be a significant computational cost compared with the search time. Additionally, some implementations required memory quadratic in the number of vertices (e.g. an NxN matrix for N nodes) which becomes prohibitive for large arrays. In some cases, a compressed sparse matrix representation was used to remain within memory limits. 96 | 97 | Neither graph construction nor quadratic memory pressure are necessary for an image analysis application. The edges between voxels (3D pixels) are regular and implicit in the rectangular structure of the image. Additionally, the cost of each edge can be stored a single time instead of 26 times in contiguous uncompressed memory regions for faster performance. 98 | 99 | Previous rationals aside, the most recent version of dijkstra3d also includes an optional method for specifying the voxel connectivity graph for each voxel via a bitfield. We found that in order to solve a problem of label self-contacts, we needed to specify impermissible directions of travel for some voxels. This is still a rather compact and fast way to process the graph, so it doesn't really invalidate our previous contention. 100 | 101 | ## C++ Use 102 | 103 | ```cpp 104 | #include 105 | #include "dijkstra3d.hpp" 106 | 107 | // 3d array represented as 1d array 108 | float* labels = new float[512*512*512](); 109 | 110 | // x + sx * y + sx * sy * z 111 | int source = 0 + 512 * 5 + 512 * 512 * 3; // coordinate <0, 5, 3> 112 | int target = 128 + 512 * 128 + 512 * 512 * 128; // coordinate <128, 128, 128> 113 | 114 | vector path = dijkstra::dijkstra3d( 115 | labels, /*sx=*/512, /*sy=*/512, /*sz=*/512, 116 | source, target, /*connectivity=*/26 // 26 is default 117 | ); 118 | 119 | vector path = dijkstra::bidirectional_dijkstra3d( 120 | labels, /*sx=*/512, /*sy=*/512, /*sz=*/512, 121 | source, target, /*connectivity=*/26 // 26 is default 122 | ); 123 | 124 | // A* search using a distance to target heuristic 125 | vector path = dijkstra::compass_guided_dijkstra3d( 126 | labels, /*sx=*/512, /*sy=*/512, /*sz=*/512, 127 | source, target, /*connectivity=*/26 // 26 is default 128 | ); 129 | 130 | uint32_t* parents = dijkstra::parental_field3d( 131 | labels, /*sx=*/512, /*sy=*/512, /*sz=*/512, 132 | source, /*connectivity=*/26 // 26 is default 133 | ); 134 | vector path = dijkstra::query_shortest_path(parents, target); 135 | 136 | 137 | // Really a chamfer distance. 138 | // source can be a size_t (single source) or a std::vector (multi-source) 139 | float* field = dijkstra::euclidean_distance_field3d( 140 | labels, 141 | /*sx=*/512, /*sy=*/512, /*sz=*/512, 142 | /*wx=*/4, /*wy=*/4, /*wz=*/40, 143 | source, /*free_space_radius=*/0 // set to > 0 to switch on 144 | ); 145 | 146 | // source can be a size_t (single source) or a std::vector (multi-source) 147 | float* field = dijkstra::distance_field3d(labels, /*sx=*/512, /*sy=*/512, /*sz=*/512, source); 148 | ``` 149 | 150 | ## Python `pip` Binary Installation 151 | 152 | ```bash 153 | pip install dijkstra3d 154 | ``` 155 | 156 | ## Python `pip` Source Installation 157 | 158 | *Requires a C++ compiler.* 159 | 160 | ```bash 161 | pip install numpy 162 | pip install dijkstra3d 163 | ``` 164 | 165 | ## Python Direct Installation 166 | 167 | *Requires a C++ compiler.* 168 | 169 | ```bash 170 | git clone https://github.com/seung-lab/dijkstra3d.git 171 | cd dijkstra3d 172 | virtualenv -p python3 venv 173 | source venv/bin/activate 174 | pip install -r requirements.txt 175 | python setup.py develop 176 | ``` 177 | 178 | ## Performance 179 | 180 | I ran three algorithms on a field of ones from the bottom left corner to the top right corner of a 512x512x512 int8 image using a 3.7 GHz Intel i7-4920K CPU. Unidirectional search takes about 42 seconds (3.2 MVx/sec) with a maximum memory usage of about 1300 MB. In the unidirectional case, this test forces the algorithm to process nearly all of the volume (dijkstra aborts early when the target is found). In the bidirectional case, the volume is processed in about 11.8 seconds (11.3 MVx/sec) with a peak memory usage of about 2300 MB. The A* version processes the volume in 0.5 seconds (268.4 MVx/sec) with an identical memory profile to unidirectional search. A* works very well in this simple case, but may not be superior in all configurations. 181 | 182 | Theoretical unidirectional memory allocation breakdown: 128 MB source image, 512 MB distance field, 512 MB parents field (1152 MB). Theoretical bidirectional memory allocation breakdown: 128 MB source image, 2x 512 distance field, 2x 512 MB parental field (2176 MB). 183 | 184 |

185 | Fig. 1: A benchmark of dijkstra.dijkstra run on a 512<sup>3</sup> voxel field of ones from bottom left source to top right target. (black) unidirectional search (blue) bidirectional search (red) A* search aka compass=True.
186 | Fig. 1: A benchmark of dijkstra.dijkstra run on a 5123 voxel field of ones from bottom left source to top right target. (black) unidirectional search (blue) bidirectional search (red) A* search aka compass=True. 187 |

188 | 189 | ```python 190 | import numpy as np 191 | import time 192 | import dijkstra3d 193 | 194 | field = np.ones((512,512,512), order='F', dtype=np.int8) 195 | source = (0,0,0) 196 | target = (511,511,511) 197 | 198 | path = dijkstra3d.dijkstra(field, source, target) # black line 199 | path = dijkstra3d.dijkstra(field, source, target, bidirectional=True) # blue line 200 | path = dijkstra3d.dijkstra(field, source, target, compass=True) # red line 201 | ``` 202 | 203 |

204 | Fig. 2: A benchmark of dijkstra.dijkstra run on a 50<sup>3</sup> voxel field of random integers of increasing variation from random source to random target. (blue/squares) unidirectional search (yellow/triangles) bidirectional search (red/diamonds) A* search aka .compass=True.
205 | Fig. 2: A benchmark of dijkstra.dijkstra run on a 503 voxel field of random integers of increasing variation from random source to random target. (blue/squares) unidirectional search (yellow/triangles) bidirectional search (red/diamonds) A* search aka compass=True. 206 |

207 | 208 | ```python 209 | import numpy as np 210 | import time 211 | import dijkstra3d 212 | 213 | N = 250 214 | sx, sy, sz = 50, 50, 50 215 | 216 | def trial(bi, compass): 217 | for n in range(0, 100, 1): 218 | accum = 0 219 | for i in range(N): 220 | if n > 0: 221 | values = np.random.randint(1,n+1, size=(sx,sy,sz)) 222 | else: 223 | values = np.ones((sx,sy,sz)) 224 | values = np.asfortranarray(values) 225 | start = np.random.randint(0,min(sx,sy,sz), size=(3,)) 226 | target = np.random.randint(0,min(sx,sy,sz), size=(3,)) 227 | 228 | s = time.time() 229 | path_orig = dijkstra3d.dijkstra(values, start, target, bidirectional=bi, compass=compass) 230 | accum += (time.time() - s) 231 | 232 | MVx_per_sec = N * sx * sy * sz / accum / 1000000 233 | print(n, ',', '%.3f' % MVx_per_sec) 234 | 235 | print("Unidirectional") 236 | trial(False, False) 237 | print("Bidirectional") 238 | trial(True, False) 239 | print("Compass") 240 | trial(False, True) 241 | ``` 242 | 243 | ## Voxel Connectivity Graph 244 | 245 | You may optionally provide a unsigned 32-bit integer image that specifies the allowed directions of travel per voxel as a directed graph. Each voxel in the graph contains a bitfield of which only the lower 26 bits are used to specify allowed directions. The top 6 bits have no assigned meaning. It is possible to use smaller width bitfields for 2D images (uint8) or for undirected graphs (uint16), but they are not currently supported. Please open an Issue or Pull Request if you need this functionality. 246 | 247 | The specification below shows the meaning assigned to each bit. Bit 32 is the MSB, bit 1 is the LSB. Ones are allowed directions and zeros are disallowed directions. 248 | 249 | ``` 250 | 32 31 30 29 28 27 26 25 24 23 251 | ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ 252 | unused unused unused unused unused unused -x-y-z x-y-z -x+y-z +x+y-z 253 | 254 | 22 21 20 19 18 17 16 15 14 13 255 | ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ 256 | -x-y+z +x-y+z -x+y+z xyz -y-z y-z -x-z x-z -yz yz 257 | 258 | 12 11 10 9 8 7 6 5 4 3 259 | ------ ------ ------ ------ ------ ------ ------ ------ ------ ------ 260 | -xz xz -x-y x-y -xy xy -z +z -y +y 261 | 2 1 262 | ------ ------ 263 | -x +x 264 | ``` 265 | 266 | There is an assistive tool available for producing these graphs from adjacent labels in the [cc3d library](https://github.com/seung-lab/connected-components-3d). 267 | 268 | ## References 269 | 270 | 1. E. W. Dijkstra. "A Note on Two Problems in Connexion with Graphs" Numerische Mathematik 1. pp. 269-271. (1959) 271 | 2. E. W. Dijkstra. "Go To Statement Considered Harmful". Communications of the ACM. Vol. 11, No. 3, pp. 147-148. (1968) 272 | 3. Pohl, Ira. "Bi-directional Search", in Meltzer, Bernard; Michie, Donald (eds.), Machine Intelligence, 6, Edinburgh University Press, pp. 127-140. (1971) 273 | -------------------------------------------------------------------------------- /automated_test.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | from math import sqrt 4 | 5 | import numpy as np 6 | 7 | import dijkstra3d 8 | 9 | TEST_TYPES = ( 10 | np.float32, np.float64, 11 | np.uint64, np.uint32, np.uint16, np.uint8, 12 | np.int64, np.int32, np.int16, np.int8, 13 | bool 14 | ) 15 | 16 | @pytest.mark.parametrize("dtype", TEST_TYPES) 17 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 18 | @pytest.mark.parametrize("connectivity", [ 18, 26 ]) 19 | @pytest.mark.parametrize("compass", [ False, True ]) 20 | def test_dijkstra2d_10x10_26(dtype, bidirectional, connectivity, compass): 21 | values = np.ones((10,10,1), dtype=dtype) 22 | 23 | path = dijkstra3d.dijkstra( 24 | values, (1,1,0), (1,1,0), 25 | bidirectional=bidirectional, connectivity=connectivity, 26 | compass=compass 27 | ) 28 | assert len(path) == 1 29 | assert np.all(path == np.array([ [1,1,0] ])) 30 | 31 | path = dijkstra3d.dijkstra( 32 | values, (0,0,0), (3,0,0), 33 | bidirectional=bidirectional, connectivity=connectivity, 34 | compass=compass 35 | ) 36 | 37 | assert len(path) == 4 38 | assert np.all(path == np.array([ 39 | [0,0,0], 40 | [1,1,0], 41 | [2,1,0], 42 | [3,0,0], 43 | ])) or np.all(path == np.array([ 44 | [0,0,0], 45 | [1,1,0], 46 | [2,0,0], 47 | [3,0,0], 48 | ])) or np.all(path == np.array([ 49 | [0,0,0], 50 | [1,0,0], 51 | [2,1,0], 52 | [3,0,0], 53 | ])) or np.all(path == np.array([ 54 | [0,0,0], 55 | [1,0,0], 56 | [2,0,0], 57 | [3,0,0], 58 | ])) 59 | 60 | path = dijkstra3d.dijkstra( 61 | values, (0,0,0), (5,5,0), 62 | bidirectional=bidirectional, connectivity=connectivity, 63 | compass=compass 64 | ) 65 | 66 | assert len(path) == 6 67 | assert np.all(path == np.array([ 68 | [0,0,0], 69 | [1,1,0], 70 | [2,2,0], 71 | [3,3,0], 72 | [4,4,0], 73 | [5,5,0], 74 | ])) 75 | 76 | path = dijkstra3d.dijkstra( 77 | values, (0,0,0), (9,9,0), 78 | bidirectional=bidirectional, connectivity=connectivity, 79 | compass=compass 80 | ) 81 | 82 | assert len(path) == 10 83 | assert np.all(path == np.array([ 84 | [0,0,0], 85 | [1,1,0], 86 | [2,2,0], 87 | [3,3,0], 88 | [4,4,0], 89 | [5,5,0], 90 | [6,6,0], 91 | [7,7,0], 92 | [8,8,0], 93 | [9,9,0] 94 | ])) 95 | 96 | path = dijkstra3d.dijkstra(values, (2,1,0), (3,0,0), compass=compass) 97 | 98 | assert len(path) == 2 99 | assert np.all(path == np.array([ 100 | [2,1,0], 101 | [3,0,0], 102 | ])) 103 | 104 | path = dijkstra3d.dijkstra(values, (9,9,0), (5,5,0), compass=compass) 105 | 106 | assert len(path) == 5 107 | assert np.all(path == np.array([ 108 | [9,9,0], 109 | [8,8,0], 110 | [7,7,0], 111 | [6,6,0], 112 | [5,5,0], 113 | ])) 114 | 115 | @pytest.mark.parametrize("connectivity", [ 18, 26 ]) 116 | def test_binary_dijkstra2d_10x10_26(connectivity): 117 | values = np.ones((10,10,1), dtype=bool) 118 | 119 | path = dijkstra3d.binary_dijkstra( 120 | values, (1,1,0), (1,1,0), 121 | connectivity=connectivity, 122 | ) 123 | assert len(path) == 1 124 | assert np.all(path == np.array([ [1,1,0] ])) 125 | 126 | path = dijkstra3d.binary_dijkstra( 127 | values, (0,0,0), (3,0,0), 128 | connectivity=connectivity, 129 | ) 130 | 131 | assert len(path) == 4 132 | assert np.all(path == np.array([ 133 | [0,0,0], 134 | [1,1,0], 135 | [2,1,0], 136 | [3,0,0], 137 | ])) or np.all(path == np.array([ 138 | [0,0,0], 139 | [1,1,0], 140 | [2,0,0], 141 | [3,0,0], 142 | ])) or np.all(path == np.array([ 143 | [0,0,0], 144 | [1,0,0], 145 | [2,1,0], 146 | [3,0,0], 147 | ])) or np.all(path == np.array([ 148 | [0,0,0], 149 | [1,0,0], 150 | [2,0,0], 151 | [3,0,0], 152 | ])) 153 | 154 | path = dijkstra3d.binary_dijkstra( 155 | values, (0,0,0), (5,5,0), 156 | connectivity=connectivity 157 | ) 158 | 159 | assert len(path) == 6 160 | assert np.all(path == np.array([ 161 | [0,0,0], 162 | [1,1,0], 163 | [2,2,0], 164 | [3,3,0], 165 | [4,4,0], 166 | [5,5,0], 167 | ])) 168 | 169 | path = dijkstra3d.binary_dijkstra( 170 | values, (0,0,0), (9,9,0), 171 | connectivity=connectivity, 172 | ) 173 | 174 | assert len(path) == 10 175 | assert np.all(path == np.array([ 176 | [0,0,0], 177 | [1,1,0], 178 | [2,2,0], 179 | [3,3,0], 180 | [4,4,0], 181 | [5,5,0], 182 | [6,6,0], 183 | [7,7,0], 184 | [8,8,0], 185 | [9,9,0] 186 | ])) 187 | 188 | path = dijkstra3d.binary_dijkstra(values, (2,1,0), (3,0,0), connectivity=connectivity) 189 | 190 | assert len(path) == 2 191 | assert np.all(path == np.array([ 192 | [2,1,0], 193 | [3,0,0], 194 | ])) 195 | 196 | path = dijkstra3d.binary_dijkstra(values, (9,9,0), (5,5,0), connectivity=connectivity) 197 | 198 | assert len(path) == 5 199 | assert np.all(path == np.array([ 200 | [9,9,0], 201 | [8,8,0], 202 | [7,7,0], 203 | [6,6,0], 204 | [5,5,0], 205 | ])) 206 | 207 | values[5:,5:] = 0 208 | path = dijkstra3d.binary_dijkstra(values, (9,9,0), (5,5,0), connectivity=connectivity) 209 | assert path.size == 0 210 | path = dijkstra3d.binary_dijkstra(values, (9,9,0), (9,9,0), connectivity=connectivity) 211 | assert path.size == 0 212 | 213 | path = dijkstra3d.binary_dijkstra(values, (9,9,0), (9,9,0), connectivity=connectivity, background_color=1) 214 | assert np.all(path == np.array([[9,9,0]])) 215 | 216 | 217 | def test_dijkstra_3d_anisotropy(): 218 | def arclen(pnts): 219 | return np.sum(np.linalg.norm(np.diff(pnts.astype('float'), axis=0), axis=1)) 220 | 221 | field = np.ones([50, 50], order="F") 222 | source = [0, 0] 223 | target = [30, 49] 224 | std_path = dijkstra3d.dijkstra(field, source, target, anisotropy=None, connectivity=8) 225 | aniso_path = dijkstra3d.dijkstra(field, source, target, anisotropy=(1, 1), connectivity=8) 226 | 227 | assert std_path.size == aniso_path.size 228 | assert np.any(std_path != aniso_path) 229 | assert arclen(std_path) > arclen(aniso_path) 230 | 231 | 232 | @pytest.mark.parametrize("dtype", TEST_TYPES) 233 | @pytest.mark.parametrize("connectivity", [ 18, 26 ]) 234 | def test_value_target_dijkstra2d_10x10_26(dtype, connectivity): 235 | values = np.ones((10,10,1), dtype=dtype) 236 | values[1,1,0] = 0 237 | 238 | path = dijkstra3d.railroad( 239 | values, (1,1,0), connectivity=connectivity, 240 | ) 241 | assert len(path) == 1 242 | assert np.all(path == np.array([ [1,1,0] ])) 243 | 244 | path = dijkstra3d.railroad( 245 | values, (0,0,0), connectivity=connectivity, 246 | ) 247 | 248 | assert len(path) == 2 249 | assert np.all(path == np.array([ 250 | [0,0,0], 251 | [1,1,0], 252 | ])) 253 | 254 | values[:,:,:] = 1 255 | values[5,5,0] = 0 256 | 257 | path = dijkstra3d.railroad( 258 | values, (0,0,0), connectivity=connectivity, 259 | ) 260 | 261 | assert len(path) == 6 262 | assert np.all(path == np.array([ 263 | [0,0,0], 264 | [1,1,0], 265 | [2,2,0], 266 | [3,3,0], 267 | [4,4,0], 268 | [5,5,0], 269 | ])) 270 | 271 | values[:,:,:] = 1 272 | values[9,9,0] = 0 273 | path = dijkstra3d.railroad( 274 | values, (0,0,0), connectivity=connectivity, 275 | ) 276 | 277 | assert len(path) == 10 278 | assert np.all(path == np.array([ 279 | [0,0,0], 280 | [1,1,0], 281 | [2,2,0], 282 | [3,3,0], 283 | [4,4,0], 284 | [5,5,0], 285 | [6,6,0], 286 | [7,7,0], 287 | [8,8,0], 288 | [9,9,0] 289 | ])) 290 | 291 | # There are many more equal distance paths 292 | # for 6 connected... so we have to be less specific. 293 | @pytest.mark.parametrize("dtype", TEST_TYPES) 294 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 295 | @pytest.mark.parametrize("compass", [ False, True ]) 296 | def test_dijkstra2d_10x10_6(dtype, bidirectional, compass): 297 | values = np.ones((10,10,1), dtype=dtype) 298 | 299 | path = dijkstra3d.dijkstra( 300 | values, (1,1,0), (1,1,0), 301 | bidirectional=bidirectional, connectivity=6, 302 | compass=compass 303 | ) 304 | assert len(path) == 1 305 | assert np.all(path == np.array([ [1,1,0] ])) 306 | 307 | path = dijkstra3d.dijkstra( 308 | values, (0,0,0), (3,0,0), 309 | bidirectional=bidirectional, connectivity=6, 310 | compass=compass 311 | ) 312 | 313 | assert len(path) == 4 314 | assert np.all(path == np.array([ 315 | [0,0,0], 316 | [1,0,0], 317 | [2,0,0], 318 | [3,0,0], 319 | ])) 320 | 321 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 322 | @pytest.mark.parametrize("dtype", TEST_TYPES) 323 | @pytest.mark.parametrize("compass", [ False, True ]) 324 | def test_dijkstra2d_10x10_off_origin(bidirectional, dtype, compass): 325 | values = np.ones((10,10,1), dtype=dtype) 326 | 327 | path = dijkstra3d.dijkstra( 328 | values, (2,0,0), (3,0,0), 329 | bidirectional=bidirectional, compass=compass 330 | ) 331 | 332 | assert len(path) == 2 333 | assert np.all(path == np.array([ 334 | [2,0,0], 335 | [3,0,0], 336 | ])) 337 | 338 | path = dijkstra3d.dijkstra( 339 | values, (2,1,0), (3,0,0), 340 | bidirectional=bidirectional, compass=compass 341 | ) 342 | 343 | assert len(path) == 2 344 | assert np.all(path == np.array([ 345 | [2,1,0], 346 | [3,0,0], 347 | ])) 348 | 349 | path = dijkstra3d.dijkstra( 350 | values, (9,9,0), (5,5,0), 351 | bidirectional=bidirectional, compass=compass 352 | ) 353 | 354 | assert len(path) == 5 355 | assert np.all(path == np.array([ 356 | [9,9,0], 357 | [8,8,0], 358 | [7,7,0], 359 | [6,6,0], 360 | [5,5,0], 361 | ])) 362 | 363 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 364 | @pytest.mark.parametrize("dtype", TEST_TYPES) 365 | @pytest.mark.parametrize("compass", [ False, True ]) 366 | def test_dijkstra3d_3x3x3_26(bidirectional, dtype, compass): 367 | values = np.ones((3,3,3), dtype=dtype) 368 | 369 | path = dijkstra3d.dijkstra( 370 | values, (1,1,1), (1,1,1), 371 | bidirectional=bidirectional, connectivity=26, 372 | compass=compass 373 | ) 374 | assert len(path) == 1 375 | assert np.all(path == np.array([ [1,1,1] ])) 376 | 377 | path = dijkstra3d.dijkstra( 378 | values, (0,0,0), (2,2,2), 379 | bidirectional=bidirectional, connectivity=26 380 | ) 381 | 382 | assert np.all(path == np.array([ 383 | [0,0,0], 384 | [1,1,1], 385 | [2,2,2] 386 | ])) 387 | 388 | path = dijkstra3d.dijkstra( 389 | values, (2,2,2), (0,0,0), 390 | bidirectional=bidirectional, connectivity=26, 391 | compass=compass 392 | ) 393 | assert np.all(path == np.array([ 394 | [2,2,2], 395 | [1,1,1], 396 | [0,0,0] 397 | ])) 398 | 399 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 400 | @pytest.mark.parametrize("dtype", TEST_TYPES) 401 | @pytest.mark.parametrize("compass", [ False, True ]) 402 | def test_dijkstra3d_3x3x3_18(bidirectional, dtype, compass): 403 | values = np.ones((3,3,3), dtype=dtype) 404 | 405 | path = dijkstra3d.dijkstra( 406 | values, (1,1,1), (1,1,1), 407 | bidirectional=bidirectional, connectivity=18, 408 | compass=compass 409 | ) 410 | assert len(path) == 1 411 | assert np.all(path == np.array([ [1,1,1] ])) 412 | 413 | path = dijkstra3d.dijkstra( 414 | values, (0,0,0), (2,2,2), 415 | bidirectional=bidirectional, connectivity=18, 416 | compass=compass 417 | ) 418 | assert np.all(path == np.array([ 419 | [0,0,0], 420 | [1,0,1], 421 | [1,1,2], 422 | [2,2,2], 423 | ])) or np.all(path == np.array([ 424 | [0,0,0], 425 | [0,1,1], 426 | [1,1,2], 427 | [2,2,2], 428 | ])) or np.all(path == np.array([ 429 | [0,0,0], 430 | [0,1,1], 431 | [1,2,1], 432 | [2,2,2], 433 | ])) or np.all(path == np.array([ 434 | [0,0,0], 435 | [1,1,0], 436 | [1,2,1], 437 | [2,2,2], 438 | ])) 439 | 440 | path = dijkstra3d.dijkstra( 441 | values, (2,2,2), (0,0,0), 442 | bidirectional=bidirectional, connectivity=18, 443 | compass=compass 444 | ) 445 | assert np.all(path == np.array([ 446 | [2,2,2], 447 | [1,2,1], 448 | [1,1,0], 449 | [0,0,0] 450 | ])) or np.all(path == np.array([ 451 | [2,2,2], 452 | [1,2,1], 453 | [0,1,1], 454 | [0,0,0] 455 | ])) or np.all(path == np.array([ 456 | [2,2,2], 457 | [2,1,1], 458 | [1,0,1], 459 | [0,0,0] 460 | ])) or np.all(path == np.array([ 461 | [2,2,2], 462 | [1,1,2], 463 | [1,0,1], 464 | [0,0,0] 465 | ])) or np.all(path == np.array([ 466 | [2,2,2], 467 | [1,1,2], 468 | [1,1,0], 469 | [0,0,0] 470 | ])) or np.all(path == np.array([ 471 | [2,2,2], 472 | [2,1,1], 473 | [1,1,0], 474 | [0,0,0] 475 | ])) 476 | 477 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 478 | @pytest.mark.parametrize("dtype", TEST_TYPES) 479 | @pytest.mark.parametrize("compass", [ False, True ]) 480 | def test_dijkstra3d_3x3x3_6(bidirectional, dtype, compass): 481 | values = np.ones((3,3,3), dtype=dtype) 482 | 483 | path = dijkstra3d.dijkstra( 484 | values, (1,1,1), (1,1,1), 485 | bidirectional=bidirectional, connectivity=6, 486 | compass=compass 487 | ) 488 | assert len(path) == 1 489 | assert np.all(path == np.array([ [1,1,1] ])) 490 | 491 | path = dijkstra3d.dijkstra( 492 | values, (0,0,0), (2,2,2), 493 | bidirectional=bidirectional, connectivity=6, 494 | compass=compass 495 | ) 496 | assert len(path) == 7 497 | assert tuple(path[0]) == (0,0,0) 498 | assert tuple(path[-1]) == (2,2,2) 499 | 500 | path = dijkstra3d.dijkstra( 501 | values, (2,2,2), (0,0,0), 502 | bidirectional=bidirectional, connectivity=6, 503 | compass=compass 504 | ) 505 | assert len(path) == 7 506 | assert tuple(path[0]) == (2,2,2) 507 | assert tuple(path[-1]) == (0,0,0) 508 | 509 | def test_bidirectional(): 510 | x = 20000 511 | values = np.array([ 512 | [x, x, x, x, x, x, x, x, x, x], 513 | [x, x, x, x, x, x, x, x, x, x], 514 | [x, x, x, x, x, x, x, x, x, x], 515 | [x, 1, x, x, x, 6, x, x, x, x], 516 | [x, x, 1, x, 4, x, 7, x, x, x], # two paths: cost 22, length 8 517 | [x, x, x, 1, 8, x, 1, x, x, x], # cost 23, length 9 518 | [x, x, x, x, x, 8, x, 1, x, x], 519 | [x, x, x, x, x, x, x, x, 1, x], 520 | [x, x, x, x, x, x, x, x, x, x], 521 | [x, x, x, x, x, x, x, x, x, x], 522 | ]) 523 | 524 | path_reg = dijkstra3d.dijkstra(np.asfortranarray(values), (3,1), (7, 8), bidirectional=False) 525 | path_bi = dijkstra3d.dijkstra(np.asfortranarray(values), (3,1), (7, 8), bidirectional=True) 526 | 527 | print(path_reg) 528 | print(path_bi) 529 | 530 | assert np.all(path_reg == path_bi) 531 | 532 | assert len(path_bi) == 8 533 | assert np.all(path_bi == [ 534 | [3,1], 535 | [4,2], 536 | [5,3], 537 | [5,4], # critical 538 | [6,5], 539 | [5,6], 540 | [6,7], 541 | [7,8] 542 | ]) 543 | 544 | values = np.array([ 545 | [x, x, x, x, x, x, x, x, x, x], 546 | [x, x, x, x, x, x, x, x, x, x], 547 | [x, x, x, x, x, x, x, x, x, x], 548 | [x, x, x, 6, 6, 6, 6, x, x, x], 549 | [1, 1, 1, x, x, x, x, 6, 6, 6], # 42, 45 550 | [x, x, 9, x, x, x, 7, x, x, x], 551 | [x, x, 1, x, x, x, 1, x, x, x], 552 | [x, x, 1, x, x, x, 1, x, x, x], 553 | [x, x, 1, 1, 1, 1, 1, x, x, x], 554 | [x, x, x, x, x, x, x, x, x, x], 555 | ]) 556 | 557 | path_reg = dijkstra3d.dijkstra(np.asfortranarray(values), (4,0), (4, 9), bidirectional=False) 558 | path_bi = dijkstra3d.dijkstra(np.asfortranarray(values), (4,0), (4, 9), bidirectional=True) 559 | 560 | print(path_reg) 561 | print(path_bi) 562 | 563 | assert np.all(path_reg == path_bi) 564 | 565 | assert len(path_bi) == 14 566 | assert np.all(path_bi == [ 567 | [4,0], 568 | [4,1], 569 | # [4,2], 570 | [5,2], 571 | [6,2], 572 | [7,2], 573 | # [8,2], 574 | [8,3], 575 | [8,4], 576 | [8,5], 577 | # [8,6], 578 | [7,6], 579 | [6,6], 580 | [5,6], 581 | [4,7], 582 | [4,8], 583 | [4,9] 584 | ]) 585 | 586 | 587 | 588 | @pytest.mark.parametrize("bidirectional", [ False, True ]) 589 | @pytest.mark.parametrize("compass", [ False, True ]) 590 | def test_dijkstra_2d_loop(bidirectional, compass): 591 | x = 20000 592 | values = np.array([ 593 | [x, x, x, x, x, x, 0, x, x, x], 594 | [x, x, x, x, x, x, 0, x, x, x], 595 | [x, x, 1, x, 0, 0, 0, x, x, x], 596 | [x, x, 2, x, 0, x, 0, x, x, x], 597 | [x, 0, x, 3, x, x, 0, x, x, x], 598 | [x, 0, x, 4, 0, 0, 0, x, x, x], 599 | [x, 0, x, 5, x, x, x, x, x, x], 600 | [x, 0, x, 6, x, x, x, x, x, x], 601 | [x, 0, x, 7, x, x, x, x, x, x], 602 | [x, x, x, 1, 8, 9,10, x, x, x], 603 | [x, x, x, 4, x, x,11,12, x, x], 604 | [x, x, x, x, x, x, x, x,13,14], 605 | ], order='F') 606 | 607 | path = dijkstra3d.dijkstra(values, (2,2), (11, 9), bidirectional=bidirectional, compass=compass) 608 | correct_path = np.array([ 609 | [2, 2], 610 | [3, 2], 611 | [4, 3], 612 | [5, 4], 613 | [6, 3], 614 | [7, 3], 615 | [8, 3], 616 | [9, 4], 617 | [9, 5], 618 | [9, 6], 619 | [10, 7], 620 | [11, 8], 621 | [11, 9] 622 | ]) 623 | 624 | assert np.all(path == correct_path) 625 | 626 | @pytest.mark.parametrize("dtype", TEST_TYPES) 627 | def test_distance_field_2d(dtype): 628 | values = np.ones((5,5), dtype=dtype) 629 | 630 | field = dijkstra3d.distance_field(values, (0,0)) 631 | 632 | assert np.all(field == np.array([ 633 | [ 634 | [0, 1, 2, 3, 4], 635 | [1, 1, 2, 3, 4], 636 | [2, 2, 2, 3, 4], 637 | [3, 3, 3, 3, 4], 638 | [4, 4, 4, 4, 4], 639 | ] 640 | ])) 641 | 642 | field = dijkstra3d.distance_field(values, [ (0,0), (4,4) ]) 643 | 644 | assert np.all(field == np.array([ 645 | [ 646 | [0, 1, 2, 3, 4], 647 | [1, 1, 2, 3, 3], 648 | [2, 2, 2, 2, 2], 649 | [3, 3, 2, 1, 1], 650 | [4, 3, 2, 1, 0], 651 | ] 652 | ])) 653 | 654 | field = dijkstra3d.distance_field(values, [ (0,0), (2,2), (4,4) ]) 655 | 656 | assert np.all(field == np.array([ 657 | [ 658 | [0, 1, 2, 2, 2], 659 | [1, 1, 1, 1, 2], 660 | [2, 1, 0, 1, 2], 661 | [2, 1, 1, 1, 1], 662 | [2, 2, 2, 1, 0], 663 | ] 664 | ])) 665 | 666 | field = dijkstra3d.distance_field(values, (4,4)) 667 | 668 | assert np.all(field == np.array([ 669 | [ 670 | [4, 4, 4, 4, 4], 671 | [4, 3, 3, 3, 3], 672 | [4, 3, 2, 2, 2], 673 | [4, 3, 2, 1, 1], 674 | [4, 3, 2, 1, 0], 675 | ] 676 | ])) 677 | 678 | field = dijkstra3d.distance_field(values, (2,2)) 679 | 680 | assert np.all(field == np.array([ 681 | [ 682 | [2, 2, 2, 2, 2], 683 | [2, 1, 1, 1, 2], 684 | [2, 1, 0, 1, 2], 685 | [2, 1, 1, 1, 2], 686 | [2, 2, 2, 2, 2], 687 | ] 688 | ])) 689 | 690 | 691 | field = dijkstra3d.distance_field(values * 2, (2,2)) 692 | 693 | assert np.all(field == np.array([ 694 | [ 695 | [4, 4, 4, 4, 4], 696 | [4, 2, 2, 2, 4], 697 | [4, 2, 0, 2, 4], 698 | [4, 2, 2, 2, 4], 699 | [4, 4, 4, 4, 4], 700 | ] 701 | ])) 702 | 703 | field, max_loc = dijkstra3d.distance_field(values * 2, (2,2), return_max_location=True) 704 | assert field[max_loc] == np.max(field) 705 | 706 | 707 | @pytest.mark.parametrize("dtype", TEST_TYPES) 708 | def test_distance_field_2d_symmetric_26(dtype): 709 | values = np.ones((5, 5), dtype=dtype) 710 | 711 | field = dijkstra3d.distance_field(values, (0,0)) 712 | 713 | assert np.all(field == np.array([ 714 | [ 715 | [0, 1, 2, 3, 4], 716 | [1, 1, 2, 3, 4], 717 | [2, 2, 2, 3, 4], 718 | [3, 3, 3, 3, 4], 719 | [4, 4, 4, 4, 4], 720 | ] 721 | ])) 722 | 723 | field = dijkstra3d.distance_field(values, (4,4)) 724 | 725 | assert np.all(field == np.array([ 726 | [ 727 | [4, 4, 4, 4, 4], 728 | [4, 3, 3, 3, 3], 729 | [4, 3, 2, 2, 2], 730 | [4, 3, 2, 1, 1], 731 | [4, 3, 2, 1, 0], 732 | ] 733 | ])) 734 | 735 | field = dijkstra3d.distance_field(values, (2,2)) 736 | 737 | assert np.all(field == np.array([ 738 | [ 739 | [2, 2, 2, 2, 2], 740 | [2, 1, 1, 1, 2], 741 | [2, 1, 0, 1, 2], 742 | [2, 1, 1, 1, 2], 743 | [2, 2, 2, 2, 2], 744 | ] 745 | ])) 746 | 747 | field = dijkstra3d.distance_field(values * 2, (2,2)) 748 | 749 | assert np.all(field == np.array([ 750 | [ 751 | [4, 4, 4, 4, 4], 752 | [4, 2, 2, 2, 4], 753 | [4, 2, 0, 2, 4], 754 | [4, 2, 2, 2, 4], 755 | [4, 4, 4, 4, 4], 756 | ] 757 | ])) 758 | 759 | @pytest.mark.parametrize("dtype", TEST_TYPES) 760 | def test_distance_field_2d_symmetric_4(dtype): 761 | values = np.ones((5, 5), dtype=dtype) 762 | 763 | field = dijkstra3d.distance_field(values, (0,0), connectivity=4) 764 | 765 | assert np.all(field == np.array([ 766 | [ 767 | [0, 1, 2, 3, 4], 768 | [1, 2, 3, 4, 5], 769 | [2, 3, 4, 5, 6], 770 | [3, 4, 5, 6, 7], 771 | [4, 5, 6, 7, 8], 772 | ] 773 | ])) 774 | 775 | field = dijkstra3d.distance_field(values, (4,4), connectivity=4) 776 | 777 | assert np.all(field == np.array([ 778 | [ 779 | [8, 7, 6, 5, 4], 780 | [7, 6, 5, 4, 3], 781 | [6, 5, 4, 3, 2], 782 | [5, 4, 3, 2, 1], 783 | [4, 3, 2, 1, 0], 784 | ] 785 | ])) 786 | 787 | field = dijkstra3d.distance_field(values, (2,2), connectivity=4) 788 | 789 | assert np.all(field == np.array([ 790 | [ 791 | [4, 3, 2, 3, 4], 792 | [3, 2, 1, 2, 3], 793 | [2, 1, 0, 1, 2], 794 | [3, 2, 1, 2, 3], 795 | [4, 3, 2, 3, 4], 796 | ] 797 | ])) 798 | 799 | field = dijkstra3d.distance_field(values * 2, (2,2), connectivity=4) 800 | 801 | assert np.all(field == np.array([ 802 | [ 803 | [8, 6, 4, 6, 8], 804 | [6, 4, 2, 4, 6], 805 | [4, 2, 0, 2, 4], 806 | [6, 4, 2, 4, 6], 807 | [8, 6, 4, 6, 8], 808 | ] 809 | ])) 810 | 811 | @pytest.mark.parametrize("dtype", TEST_TYPES) 812 | def test_distance_field_2d_asymmetric(dtype): 813 | values = np.ones((5, 10), dtype=dtype) 814 | 815 | answer = np.array([ 816 | [1, 0, 1, 2, 3, 4, 5, 6, 7, 8], 817 | [1, 1, 1, 2, 3, 4, 5, 6, 7, 8], 818 | [2, 2, 2, 2, 3, 4, 5, 6, 7, 8], 819 | [3, 3, 3, 3, 3, 4, 5, 6, 7, 8], 820 | [4, 4, 4, 4, 4, 4, 5, 6, 7, 8], 821 | ], dtype=np.float32) 822 | 823 | field = dijkstra3d.distance_field(values, (0,1)) 824 | assert np.all(field == answer) 825 | 826 | @pytest.mark.parametrize('free_space_radius', (0,1,2,3,4,5,10)) 827 | def test_euclidean_distance_field_2d(free_space_radius): 828 | values = np.ones((2, 2), dtype=bool) 829 | 830 | sq2 = sqrt(2) 831 | sq3 = sqrt(3) 832 | 833 | answer = np.array([ 834 | [0, 1], 835 | [1, sq2], 836 | ], dtype=np.float32) 837 | 838 | field = dijkstra3d.euclidean_distance_field(values, (0,0), free_space_radius=free_space_radius) 839 | assert np.all(np.abs(field - answer) < 0.00001) 840 | 841 | values = np.ones((5, 5), dtype=bool) 842 | 843 | answer = np.array( 844 | [[0, 1. , 2. , 3. , 4. ], 845 | [1, 1.4142135 , 2.4142137, 3.4142137 , 4.4142137], 846 | [2, 2.4142137 , 2.828427 , 3.828427 , 4.8284273], 847 | [3, 3.4142137 , 3.828427 , 4.2426405 , 5.2426405], 848 | [4, 4.4142137 , 4.8284273, 5.2426405 , 5.656854 ]], 849 | dtype=np.float32) 850 | 851 | field, max_loc = dijkstra3d.euclidean_distance_field( 852 | values, (0,0,0), (1,1,1), 853 | free_space_radius=free_space_radius, 854 | return_max_location=True 855 | ) 856 | assert np.all(np.abs(field - answer) < 0.00001) 857 | assert max_loc == (4,4) 858 | 859 | answer = np.array([ 860 | [ 861 | [0, 1], 862 | [1, sq2], 863 | ], 864 | [ 865 | [1, sq2], 866 | [sq2, sq3], 867 | ] 868 | ], dtype=np.float32) 869 | 870 | values = np.ones((2, 2, 2), dtype=bool) 871 | field, max_loc = dijkstra3d.euclidean_distance_field( 872 | values, (0,0,0), (1,1,1), 873 | free_space_radius=free_space_radius, return_max_location=True 874 | ) 875 | assert np.all(np.abs(field - answer) < 0.00001) 876 | assert max_loc == (1,1,1) 877 | 878 | values = np.ones((2, 2, 2), dtype=bool) 879 | field = dijkstra3d.euclidean_distance_field(values, (1,1,1), (1,1,1), free_space_radius=free_space_radius) 880 | 881 | answer = np.array([ 882 | [ 883 | [sq3, sq2], 884 | [sq2, 1], 885 | ], 886 | [ 887 | [sq2, 1], 888 | [1, 0], 889 | ] 890 | ], dtype=np.float32) 891 | 892 | assert np.all(np.abs(field - answer) < 0.00001) 893 | 894 | # Multi-source 895 | values = np.ones((4,4), dtype=bool) 896 | field = dijkstra3d.euclidean_distance_field(values, [ (0,0), (3,3) ], free_space_radius=free_space_radius) 897 | 898 | answer = np.array([ 899 | [0, 1, 2, 3], 900 | [1, sq2, (1+sq2), 2], 901 | [2, (1+sq2), sq2, 1], 902 | [3, 2, 1, 0], 903 | ]) 904 | assert np.all(np.isclose(field, answer)) 905 | 906 | def test_euclidean_distance_field_2d_feature_map(): 907 | values = np.ones((7, 7, 1), dtype=bool) 908 | field, max_loc, feature_map = dijkstra3d.euclidean_distance_field(values, [0,0,0], return_max_location=True, return_feature_map=True) 909 | 910 | assert np.isclose( 911 | np.max(field), 912 | np.sqrt((values.shape[0] - 1) ** 2 + (values.shape[1] - 1) ** 2) 913 | ) 914 | assert max_loc == (6,6,0) 915 | 916 | assert np.all(np.unique(feature_map) == 1) 917 | 918 | sources = [ 919 | [0,0,0], 920 | [6,6,0] 921 | ] 922 | field, max_loc, feature_map = dijkstra3d.euclidean_distance_field(values, sources, return_max_location=True, return_feature_map=True) 923 | assert tuple(np.unique(feature_map)) == (1,2) 924 | 925 | sources = [ 926 | [0,0,0], 927 | [6,6,0], 928 | [6,6,0] 929 | ] 930 | field, max_loc, feature_map = dijkstra3d.euclidean_distance_field(values, sources, return_max_location=True, return_feature_map=True) 931 | assert tuple(np.unique(feature_map)) == (1,2) 932 | 933 | sources = [ 934 | [0,0,0], 935 | [6,6,0], 936 | [3,3,0], 937 | ] 938 | field, max_loc, feature_map = dijkstra3d.euclidean_distance_field(values, sources, return_max_location=True, return_feature_map=True) 939 | assert tuple(np.unique(feature_map)) == (1,2,3) 940 | 941 | result = np.array( 942 | [[[1, 1, 1, 2, 2, 2, 2], 943 | [1, 1, 2, 2, 2, 2, 2], 944 | [1, 2, 2, 2, 2, 2, 2], 945 | [2, 2, 2, 2, 2, 2, 3], 946 | [2, 2, 2, 2, 2, 3, 3], 947 | [2, 2, 2, 2, 3, 3, 3], 948 | [2, 2, 2, 3, 3, 3, 3],]]).T 949 | 950 | assert np.all(feature_map == result) 951 | 952 | @pytest.mark.parametrize('point', (np.random.randint(0,256, size=(3,)),)) 953 | def test_euclidean_distance_field_3d_free_space_eqn(point): 954 | point = tuple(point) 955 | print(point) 956 | values = np.ones((256, 256, 256), dtype=bool) 957 | field_dijk = dijkstra3d.euclidean_distance_field(values, point, free_space_radius=0) # free space off 958 | field_free = dijkstra3d.euclidean_distance_field(values, point, free_space_radius=10000) # free space 100% on 959 | 960 | assert np.all(np.abs(field_free - field_dijk) < 0.001) # there's some difference below this 961 | 962 | def test_compass(): 963 | field = np.array([ 964 | [6, 9, 7, 7, 1, 7, 4, 3, 5, 9], 965 | [4, 8, 7, 8, 1, 2, 5, 8, 3, 9], 966 | [5, 9, 4, 5, 7, 9, 2, 1, 5, 1], 967 | [1, 3, 6, 9, 6, 1, 7, 9, 5, 8], 968 | [2, 7, 3, 6, 1, 8, 9, 2, 1, 5], 969 | [7, 3, 7, 2, 9, 9, 8, 8, 9, 6], 970 | [3, 3, 8, 9, 3, 6, 8, 1, 6, 4], 971 | [9, 7, 5, 7, 9, 7, 8, 6, 7, 2], 972 | [6, 3, 7, 1, 1, 5, 2, 1, 3, 9], 973 | [2, 4, 8, 2, 9, 5, 2, 3, 3, 2], 974 | ]) 975 | start = (8,1) 976 | target = (1,5) 977 | dijkstra_path = dijkstra3d.dijkstra(field, start, target, compass=False) 978 | compass_path = dijkstra3d.dijkstra(field, start, target, compass=True) 979 | 980 | def path_len(path): 981 | length = 0 982 | for p in path: 983 | length += field[tuple(p)] 984 | return length 985 | 986 | if not np.all(dijkstra_path == compass_path): 987 | print(field) 988 | print(dijkstra_path) 989 | print("dijkstra cost: %d" % path_len(dijkstra_path)) 990 | print(compass_path) 991 | print("compass cost: %d" % path_len(compass_path)) 992 | 993 | assert np.all(dijkstra_path == compass_path) 994 | 995 | @pytest.mark.parametrize("dtype", TEST_TYPES) 996 | @pytest.mark.parametrize("compass", [ False, True ]) 997 | def test_dijkstra_parental(dtype, compass): 998 | values = np.ones((10,10), dtype=dtype, order='F') 999 | parents = dijkstra3d.parental_field(values, (0,0)) 1000 | path = dijkstra3d.path_from_parents(parents, (3,0)) 1001 | 1002 | assert len(path) == 4 1003 | assert np.all(path == np.array([ 1004 | [0,0], 1005 | [1,1], 1006 | [2,1], 1007 | [3,0], 1008 | ])) 1009 | 1010 | values = np.ones((10,10,1), dtype=dtype, order='F') 1011 | 1012 | parents = dijkstra3d.parental_field(values, (0,0,0)) 1013 | path = dijkstra3d.path_from_parents(parents, (3,0,0)) 1014 | 1015 | assert len(path) == 4 1016 | assert np.all(path == np.array([ 1017 | [0,0,0], 1018 | [1,1,0], 1019 | [2,1,0], 1020 | [3,0,0], 1021 | ])) 1022 | 1023 | def path_len(path, values): 1024 | length = 0 1025 | for p in path: 1026 | length += values[tuple(p)] 1027 | return length 1028 | 1029 | # Symmetric Test 1030 | for _ in range(500): 1031 | values = np.random.randint(1,10, size=(10,10,1)) 1032 | values = np.asfortranarray(values) 1033 | 1034 | start = np.random.randint(0,9, size=(3,)) 1035 | target = np.random.randint(0,9, size=(3,)) 1036 | start[2] = 0 1037 | target[2] = 0 1038 | 1039 | parents = dijkstra3d.parental_field(values, start) 1040 | path = dijkstra3d.path_from_parents(parents, target) 1041 | 1042 | path_orig = dijkstra3d.dijkstra(values, start, target, compass=compass) 1043 | 1044 | if path_len(path, values) != path_len(path_orig, values): 1045 | print(start, target) 1046 | print(path) 1047 | print(path_orig) 1048 | print(values[:,:,0]) 1049 | print('parents_path') 1050 | for p in path: 1051 | print(values[tuple(p)]) 1052 | print('compass_path') 1053 | for p in path_orig: 1054 | print(values[tuple(p)]) 1055 | 1056 | assert path_len(path, values) == path_len(path_orig, values) 1057 | 1058 | if compass == False: 1059 | assert np.all(path == path_orig) 1060 | 1061 | # Asymmetric Test 1062 | for _ in range(500): 1063 | values = np.random.randint(1,255, size=(11,10,10)) 1064 | values = np.asfortranarray(values) 1065 | 1066 | start = np.random.randint(0,9, size=(3,)) 1067 | target = np.random.randint(0,9, size=(3,)) 1068 | start[0] = np.random.randint(0,10) 1069 | target[0] = np.random.randint(0,10) 1070 | 1071 | parents = dijkstra3d.parental_field(values, start) 1072 | path = dijkstra3d.path_from_parents(parents, target) 1073 | 1074 | path_orig = dijkstra3d.dijkstra(values, start, target, compass=compass) 1075 | 1076 | if path_len(path, values) != path_len(path_orig, values): 1077 | print(start, target) 1078 | print(path) 1079 | print(path_orig) 1080 | 1081 | assert path_len(path, values) == path_len(path_orig, values) 1082 | 1083 | if not compass: 1084 | assert np.all(path == path_orig) 1085 | 1086 | def test_voxel_connectivity_graph(): 1087 | from PIL import Image 1088 | import cc3d 1089 | 1090 | img = Image.open("./multi-color-self-touch.png") 1091 | img = np.array(img) 1092 | root_img = img > 0 1093 | root_img = root_img.astype(np.float32) 1094 | root_img[root_img == 0] = np.inf 1095 | 1096 | boundary_x = 106 1097 | 1098 | graph = np.zeros(img.shape, dtype=np.uint8, order="F") 1099 | graph[:boundary_x] = cc3d.voxel_connectivity_graph(img[:boundary_x], connectivity=6) 1100 | graph[boundary_x:] =cc3d.voxel_connectivity_graph(img[boundary_x:], connectivity=6) 1101 | 1102 | path = dijkstra3d.dijkstra(root_img, (199,199), (173,170), connectivity=8, voxel_graph=graph) 1103 | 1104 | assert len(path) == 528 1105 | 1106 | 1107 | @pytest.mark.parametrize('bidirectional', (True, False)) 1108 | @pytest.mark.parametrize('compass', (True, False)) 1109 | def test_impossible_target_2d_6(bidirectional, compass): 1110 | img = np.ones((100, 100), dtype=np.uint8, order="F") 1111 | 1112 | def dijk(src, target, graph): 1113 | return dijkstra3d.dijkstra( 1114 | img, src, target, 1115 | connectivity=6, voxel_graph=graph, 1116 | bidirectional=bidirectional, compass=compass 1117 | ) 1118 | 1119 | path = dijk((0,0), (99,99), None) 1120 | assert len(path) > 0 1121 | 1122 | mkgraph = lambda: np.zeros(img.shape, dtype=np.uint32, order="F") + 0b1111 1123 | 1124 | graph = mkgraph() 1125 | path = dijk((0,0), (99,99), graph) 1126 | assert len(path) > 0 1127 | path = dijk((99,99), (0,0), graph) 1128 | assert len(path) > 0 1129 | 1130 | graph = mkgraph() 1131 | graph[50,:] = 0b1110 1132 | graph[51,:] = 0b1101 1133 | path = dijk((0,0), (99,99), graph) 1134 | assert len(path) == 0 1135 | 1136 | path = dijk((99,99), (0,0), graph) 1137 | assert len(path) == 0 1138 | 1139 | graph = mkgraph() 1140 | graph[:,50] = 0b1011 1141 | graph[:,51] = 0b0111 1142 | 1143 | path = dijk((0,0), (99,99), graph) 1144 | assert len(path) == 0 1145 | 1146 | path = dijk((99,99), (0,0), graph) 1147 | assert len(path) == 0 1148 | 1149 | 1150 | -------------------------------------------------------------------------------- /build_linux.sh: -------------------------------------------------------------------------------- 1 | #!/usr/local/bin/bash 2 | # docker build . -f manylinux1.Dockerfile --tag seunglab/dijkstra3d:manylinux1 3 | docker build . -f manylinux2010.Dockerfile --tag seunglab/dijkstra3d:manylinux2010 4 | docker build . -f manylinux2014.Dockerfile --tag seunglab/dijkstra3d:manylinux2014 5 | docker run -v $PWD/dist:/output seunglab/dijkstra3d:manylinux1 /bin/bash -c "cp -r wheelhouse/* /output" 6 | docker run -v $PWD/dist:/output seunglab/dijkstra3d:manylinux2010 /bin/bash -c "cp -r wheelhouse/* /output" 7 | docker run -v $PWD/dist:/output seunglab/dijkstra3d:manylinux2014 /bin/bash -c "cp -r wheelhouse/* /output" -------------------------------------------------------------------------------- /dijkstra3d.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seung-lab/dijkstra3d/75c58d7238c8d660e4e7e2c7d0f82b8302f2d67c/dijkstra3d.png -------------------------------------------------------------------------------- /dijkstra3d.pyx: -------------------------------------------------------------------------------- 1 | # cython: language_level=3 2 | """ 3 | Cython binding for C++ dijkstra's shortest path algorithm 4 | applied to 3D images. 5 | 6 | Contains: 7 | dijkstra - Find the shortest 26-connected path from source 8 | to target using the values of each voxel as edge weights.\ 9 | 10 | distance_field - Compute the distance field from a source 11 | voxel in an image using image voxel values as edge weights. 12 | 13 | euclidean_distance_field - Compute the euclidean distance 14 | to each voxel in a binary image from a source point. 15 | 16 | parental_field / path_from_parents - Same as dijkstra, 17 | but if you're computing dijkstra multiple times on 18 | the same image, this can be much much faster. 19 | 20 | 21 | Authors: William Silversmith, Izzy Turtle (@turtleizzy on Github) 22 | Affiliation: Seung Lab, Princeton Neuroscience Institute 23 | Date: August 2018 - May 2023 24 | """ 25 | 26 | from libc.stdlib cimport calloc, free 27 | from libc.stdint cimport ( 28 | int8_t, int16_t, int32_t, int64_t, 29 | uint8_t, uint16_t, uint32_t, uint64_t 30 | ) 31 | from cpython cimport array 32 | import array 33 | import sys 34 | 35 | import cython 36 | from libcpp.vector cimport vector 37 | cimport numpy as cnp 38 | import numpy as np 39 | 40 | cnp.import_array() 41 | 42 | import warnings 43 | 44 | __VERSION__ = '1.14.0' 45 | 46 | ctypedef fused UINT: 47 | uint8_t 48 | uint16_t 49 | uint32_t 50 | uint64_t 51 | 52 | class DimensionError(Exception): 53 | pass 54 | 55 | cdef extern from "dijkstra3d.hpp" namespace "dijkstra": 56 | cdef vector[OUT] dijkstra3d[T,OUT]( 57 | T* field, 58 | size_t sx, size_t sy, size_t sz, 59 | size_t source, size_t target, 60 | int connectivity, uint32_t* voxel_graph 61 | ) 62 | cdef vector[OUT] dijkstra3d_anisotropy[T,OUT]( 63 | T* field, 64 | size_t sx, size_t sy, size_t sz, 65 | size_t source, size_t target, 66 | int connectivity, 67 | float wx, float wy, float wz, 68 | uint32_t* voxel_graph 69 | ) 70 | cdef vector[OUT] binary_dijkstra3d[OUT]( 71 | uint8_t* field, 72 | size_t sx, size_t sy, size_t sz, 73 | size_t source, size_t target, 74 | int connectivity, 75 | float wx, float wy, float wz, 76 | uint8_t euclidean_metric, 77 | uint32_t* voxel_graph, 78 | int background_color 79 | ) 80 | cdef vector[OUT] bidirectional_dijkstra3d[T,OUT]( 81 | T* field, 82 | size_t sx, size_t sy, size_t sz, 83 | size_t source, size_t target, 84 | int connectivity, uint32_t* voxel_graph 85 | ) 86 | cdef vector[OUT] value_target_dijkstra3d[T,OUT]( 87 | T* field, 88 | size_t sx, size_t sy, size_t sz, 89 | size_t source, T target, 90 | int connectivity, 91 | uint32_t* voxel_connectivity_graph 92 | ) 93 | cdef vector[OUT] compass_guided_dijkstra3d[T,OUT]( 94 | T* field, 95 | size_t sx, size_t sy, size_t sz, 96 | size_t source, size_t target, 97 | int connectivity, float normalizer, 98 | uint32_t* voxel_graph 99 | ) 100 | cdef vector[OUT] compass_guided_dijkstra3d_anisotropy_line_preference[T,OUT]( 101 | T* field, 102 | size_t sx, size_t sy, size_t sz, 103 | size_t source, size_t target, 104 | int connectivity, float normalizer, float line_preference_weight, 105 | float wx, float wy, float wz, 106 | uint32_t* voxel_graph 107 | ) 108 | cdef float* distance_field3d[T]( 109 | T* field, 110 | size_t sx, size_t sy, size_t sz, 111 | vector[size_t] source, size_t connectivity, 112 | uint32_t* voxel_graph, size_t &max_loc 113 | ) 114 | cdef OUT* parental_field3d[T,OUT]( 115 | T* field, 116 | size_t sx, size_t sy, size_t sz, 117 | size_t source, OUT* parents, 118 | int connectivity, uint32_t* voxel_graph 119 | ) 120 | cdef float* euclidean_distance_field3d( 121 | uint8_t* field, 122 | size_t sx, size_t sy, size_t sz, 123 | float wx, float wy, float wz, 124 | vector[size_t] source, 125 | float free_space_radius, 126 | float* dist, 127 | uint32_t* voxel_graph, 128 | size_t &max_loc 129 | ) 130 | cdef OUT* edf_with_feature_map[OUT]( 131 | uint8_t* field, 132 | uint64_t sx, uint64_t sy, uint64_t sz, 133 | float wx, float wy, float wz, 134 | vector[uint64_t] &sources, 135 | float* dist, OUT* feature_map, 136 | size_t &max_loc 137 | ) 138 | cdef vector[T] query_shortest_path[T]( 139 | T* parents, T target 140 | ) 141 | 142 | def format_voxel_graph(voxel_graph): 143 | while voxel_graph.ndim < 3: 144 | voxel_graph = voxel_graph[..., np.newaxis] 145 | 146 | if not np.issubdtype(voxel_graph.dtype, np.uint32): 147 | voxel_graph = voxel_graph.astype(np.uint32, order="F") 148 | 149 | return np.asfortranarray(voxel_graph) 150 | 151 | @cython.binding(True) 152 | def dijkstra( 153 | data, source, target, 154 | bidirectional=False, connectivity=26, 155 | compass=False, compass_norm=-1, line_preference_weight=0, 156 | voxel_graph=None, 157 | anisotropy=None 158 | ): 159 | """ 160 | Perform dijkstra's shortest path algorithm 161 | on a 3D image grid. Vertices are voxels and 162 | edges are the 26 nearest neighbors (except 163 | for the edges of the image where the number 164 | of edges is reduced). 165 | 166 | For given input voxels A and B, the edge 167 | weight from A to B is B and from B to A is 168 | A. All weights must be non-negative (incl. 169 | negative zero). 170 | 171 | If anisotropy is provided, the edge weight is 172 | multiplied by the euclidean distance from the 173 | center of the voxel to the face, edge, or corner 174 | depending on the direction. 175 | 176 | Parameters: 177 | Data: Input weights in a 2D or 3D numpy array. 178 | source: (x,y,z) coordinate of starting voxel 179 | target: (x,y,z) coordinate of target voxel 180 | bidirectional: If True, use more memory but conduct 181 | a bidirectional search, which has the potential to be 182 | much faster. 183 | connectivity: 6 (faces), 18 (faces + edges), and 184 | 26 (faces + edges + corners) voxel graph connectivities 185 | are supported. For 2D images, 4 gets translated to 6, 186 | 8 gets translated to 18. 187 | compass: If True, A* search using the chessboard 188 | distance to target as the heuristic. This has the 189 | effect of guiding the search like using a compass. 190 | This option has no effect when bidirectional search 191 | is enabled as it is not supported yet. 192 | compass_norm: Allows you to manipulate the relative 193 | greed of the A* search. By default set to -1, which 194 | means the norm will be the field minimum, but you 195 | can choose whatever you want if you know what you're 196 | doing. 197 | voxel_graph: a bitwise representation of the premitted 198 | directions of travel between voxels. Generated from 199 | cc3d.voxel_connectivity_graph. 200 | (See https://github.com/seung-lab/connected-components-3d) 201 | anisotropy: If provided, [x,y,z] relative dimensions of each voxel 202 | in the x,y, and z dimensions. This changes the weighting 203 | calculation in the search by multiplying by the appropriate 204 | euclidean weight for faces, edges, and corners. 205 | 206 | Returns: 1D numpy array containing indices of the path from 207 | source to target including source and target. 208 | """ 209 | dims = len(data.shape) 210 | if dims not in (2,3): 211 | raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims)) 212 | 213 | if dims == 2: 214 | if connectivity == 4: 215 | connectivity = 6 216 | elif connectivity == 8: 217 | connectivity = 18 # or 26 but 18 might be faster 218 | 219 | if connectivity not in (6, 18, 26): 220 | raise ValueError( 221 | "Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity) 222 | ) 223 | 224 | if data.size == 0: 225 | return np.zeros(shape=(0,), dtype=np.uint32, order='F') 226 | 227 | _validate_coord(data, source) 228 | _validate_coord(data, target) 229 | 230 | if dims == 2: 231 | data = data[:, :, np.newaxis] 232 | source = list(source) + [ 0 ] 233 | target = list(target) + [ 0 ] 234 | 235 | if voxel_graph is not None: 236 | voxel_graph = format_voxel_graph(voxel_graph) 237 | 238 | data = np.asfortranarray(data) 239 | 240 | cdef size_t cols = data.shape[0] 241 | cdef size_t rows = data.shape[1] 242 | cdef size_t depth = data.shape[2] 243 | 244 | if anisotropy is None: 245 | path = _execute_dijkstra( 246 | data, source, target, connectivity, 247 | bidirectional, compass, compass_norm, 248 | voxel_graph 249 | ) 250 | else: 251 | anisotropy = list(anisotropy) 252 | while len(anisotropy) < 3: 253 | anisotropy.append(float(1)) 254 | 255 | if bidirectional: 256 | warnings.warn("bidirectional = True is not currently supported by \ 257 | anisotropy dijkstra3d. Fall back to vanilla dijkstra algorithm.") 258 | path = _execute_dijkstra_anisotropy( 259 | data, source, target, connectivity, 260 | anisotropy, compass, compass_norm, voxel_graph, line_preference_weight 261 | ) 262 | return _path_to_point_cloud(path, dims, rows, cols) 263 | 264 | @cython.binding(True) 265 | def railroad( 266 | data, source, 267 | connectivity=26, voxel_graph=None 268 | ): 269 | """ 270 | A "rail road" (a term defined by us) is the shortest 271 | last-mile path (the "road") from a target point to a 272 | "rail network" that includes the source point. A "rail" 273 | is a zero weighted path that acts as a strong attractor 274 | for the search algorithm. In the context of the 275 | skeletonization problem, such networks are assembled 276 | as a matter of course. It becomes more and more efficient 277 | to search for the rail network than for the target point. 278 | 279 | For given input voxels A and B, the edge 280 | weight from A to B is B and from B to A is 281 | A. All weights must be non-negative (incl. 282 | negative zero). 283 | 284 | Parameters: 285 | Data: Input weights in a 2D or 3D numpy array. 286 | source: (x,y,z) coordinate of starting voxel 287 | connectivity: 6 (faces), 18 (faces + edges), and 288 | 26 (faces + edges + corners) voxel graph connectivities 289 | are supported. For 2D images, 4 gets translated to 6, 290 | 8 gets translated to 18. 291 | voxel_graph: a bitwise representation of the premitted 292 | directions of travel between voxels. Generated from 293 | cc3d.voxel_connectivity_graph. 294 | (See https://github.com/seung-lab/connected-components-3d) 295 | 296 | Returns: 1D numpy array containing indices of the path from 297 | source to target including source and destination. 298 | """ 299 | dims = len(data.shape) 300 | if dims not in (2,3): 301 | raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims)) 302 | 303 | if dims == 2: 304 | if connectivity == 4: 305 | connectivity = 6 306 | elif connectivity == 8: 307 | connectivity = 18 # or 26 but 18 might be faster 308 | 309 | if connectivity not in (6, 18, 26): 310 | raise ValueError( 311 | "Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity) 312 | ) 313 | 314 | if data.size == 0: 315 | return np.zeros(shape=(0,), dtype=np.uint32, order='F') 316 | 317 | _validate_coord(data, source) 318 | 319 | if dims == 2: 320 | data = data[:, :, np.newaxis] 321 | source = list(source) + [ 0 ] 322 | 323 | if voxel_graph is not None: 324 | voxel_graph = format_voxel_graph(voxel_graph) 325 | 326 | data = np.asfortranarray(data) 327 | 328 | cdef size_t cols = data.shape[0] 329 | cdef size_t rows = data.shape[1] 330 | 331 | path = _execute_value_target_dijkstra( 332 | data, source, 333 | connectivity, voxel_graph 334 | ) 335 | 336 | return _path_to_point_cloud(path, dims, rows, cols) 337 | 338 | @cython.binding(True) 339 | def binary_dijkstra( 340 | data, source, target, 341 | connectivity=26, 342 | background_color=0, 343 | anisotropy=(1.0, 1.0, 1.0), 344 | euclidean_metric=True, 345 | voxel_graph=None 346 | ): 347 | """ 348 | Perform dijkstra's shortest path algorithm 349 | on a 3D image grid. Vertices are voxels and 350 | edges are the 26 nearest neighbors (except 351 | for the edges of the image where the number 352 | of edges is reduced). 353 | 354 | This version treats the data as a binary image 355 | with the background color set to 0 or 1. Background 356 | voxels will not be considered. 357 | 358 | Parameters: 359 | Data: Input weights in a 2D or 3D numpy array. 360 | source: (x,y,z) coordinate of starting voxel 361 | target: (x,y,z) coordinate of target voxel 362 | anisotropy: (wx,wy,wz) weights for each axial direction. 363 | background_color: 1 or 0, pick which color in a binary image 364 | will be considered background. 365 | connectivity: 6 (faces), 18 (faces + edges), and 366 | 26 (faces + edges + corners) voxel graph connectivities 367 | are supported. For 2D images, 4 gets translated to 6, 368 | 8 gets translated to 18. 369 | euclidean_metric: if True, treat the image as a euclidean 370 | space weighted by the anisotropy on x, y, and z. Otherwise, 371 | each movement in any direction, including diagonals, 372 | are evenly weighted. 373 | voxel_graph: a bitwise representation of the premitted 374 | directions of travel between voxels. Generated from 375 | cc3d.voxel_connectivity_graph. 376 | (See https://github.com/seung-lab/connected-components-3d) 377 | 378 | Returns: 1D numpy array containing indices of the path from 379 | source to target including source and target. 380 | """ 381 | dims = len(data.shape) 382 | if dims not in (2,3): 383 | raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims)) 384 | 385 | if dims == 2: 386 | if connectivity == 4: 387 | connectivity = 6 388 | elif connectivity == 8: 389 | connectivity = 18 # or 26 but 18 might be faster 390 | 391 | if connectivity not in (6, 18, 26): 392 | raise ValueError( 393 | "Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity) 394 | ) 395 | 396 | if not np.issubdtype(data.dtype, bool): 397 | raise ValueError(f"This function only accepts boolean type images. Got: {data.dtype}") 398 | 399 | if data.size == 0: 400 | return np.zeros(shape=(0,), dtype=np.uint32, order='F') 401 | 402 | _validate_coord(data, source) 403 | _validate_coord(data, target) 404 | 405 | if dims == 2: 406 | data = data[:, :, np.newaxis] 407 | source = list(source) + [ 0 ] 408 | target = list(target) + [ 0 ] 409 | 410 | if voxel_graph is not None: 411 | voxel_graph = format_voxel_graph(voxel_graph) 412 | 413 | data = np.asfortranarray(data) 414 | 415 | cdef size_t cols = data.shape[0] 416 | cdef size_t rows = data.shape[1] 417 | cdef size_t depth = data.shape[2] 418 | 419 | path = _execute_binary_dijkstra( 420 | data, source, target, connectivity, 421 | anisotropy[0], anisotropy[1], anisotropy[2], 422 | euclidean_metric, 423 | voxel_graph, background_color 424 | ) 425 | 426 | return _path_to_point_cloud(path, dims, rows, cols) 427 | 428 | @cython.binding(True) 429 | def distance_field( 430 | data, source, connectivity=26, 431 | voxel_graph=None, return_max_location=False 432 | ): 433 | """ 434 | Use dijkstra's shortest path algorithm 435 | on a 3D image grid to generate a weighted 436 | distance field from one or more source voxels. Vertices are 437 | voxels and edges are the 26 nearest neighbors 438 | (except for the edges of the image where 439 | the number of edges is reduced). 440 | 441 | For given input voxels A and B, the edge 442 | weight from A to B is B and from B to A is 443 | A. All weights must be non-negative (incl. 444 | negative zero). 445 | 446 | Parameters: 447 | data: Input weights in a 2D or 3D numpy array. 448 | source: (x,y,z) coordinate or list of coordinates 449 | of starting voxels. 450 | connectivity: 26, 18, or 6 connected. 451 | return_max_location: returns the coordinates of one 452 | of the possibly multiple maxima. 453 | 454 | Returns: 455 | let field = 2D or 3D numpy array with each index 456 | containing its distance from the source voxel. 457 | 458 | if return_max_location: 459 | return (field, (x,y,z) of max distance) 460 | else: 461 | return field 462 | """ 463 | dims = len(data.shape) 464 | if dims not in (2,3): 465 | raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims)) 466 | 467 | if dims == 2: 468 | if connectivity == 4: 469 | connectivity = 6 470 | elif connectivity == 8: 471 | connectivity = 18 # or 26 but 18 might be faster 472 | 473 | if connectivity not in (6, 18, 26): 474 | raise ValueError( 475 | "Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity) 476 | ) 477 | 478 | if data.size == 0: 479 | return np.zeros(shape=(0,), dtype=np.float32) 480 | 481 | source = np.array(source, dtype=np.uint64) 482 | if source.ndim == 1: 483 | source = source[np.newaxis, :] 484 | 485 | for src in source: 486 | _validate_coord(data, src) 487 | 488 | if source.shape[1] < 3: 489 | tmp = np.zeros((source.shape[0], 3), dtype=np.uint64) 490 | tmp[:, :source.shape[1]] = source[:,:] 491 | source = tmp 492 | 493 | while data.ndim < 3: 494 | data = data[..., np.newaxis] 495 | 496 | if voxel_graph is not None: 497 | voxel_graph = format_voxel_graph(voxel_graph) 498 | 499 | data = np.asfortranarray(data) 500 | 501 | field, max_loc = _execute_distance_field(data, source, connectivity, voxel_graph) 502 | if dims < 3: 503 | field = np.squeeze(field, axis=2) 504 | if dims < 2: 505 | field = np.squeeze(field, axis=1) 506 | 507 | if return_max_location: 508 | return field, np.unravel_index(max_loc, data.shape, order="F")[:dims] 509 | else: 510 | return field 511 | 512 | # parents is either uint32 or uint64 513 | def _path_from_parents_helper(cnp.ndarray[UINT, ndim=3] parents, target): 514 | cdef UINT[:,:,:] arr_memview 515 | cdef vector[UINT] path 516 | cdef UINT* path_ptr 517 | cdef UINT[:] vec_view 518 | 519 | cdef size_t sx = parents.shape[0] 520 | cdef size_t sy = parents.shape[1] 521 | cdef size_t sz = parents.shape[2] 522 | 523 | cdef UINT targ = target[0] + sx * (target[1] + sy * target[2]) 524 | 525 | arr_memview = parents 526 | path = query_shortest_path(&arr_memview[0,0,0], targ) 527 | path_ptr = &path[0] 528 | vec_view = path_ptr 529 | buf = bytearray(vec_view[:]) 530 | return np.frombuffer(buf, dtype=parents.dtype)[::-1] 531 | 532 | def path_from_parents(parents, target): 533 | ndim = parents.ndim 534 | while parents.ndim < 3: 535 | parents = parents[..., np.newaxis] 536 | 537 | while len(target) < 3: 538 | target += (0,) 539 | 540 | cdef size_t sx = parents.shape[0] 541 | cdef size_t sy = parents.shape[1] 542 | 543 | numpy_path = _path_from_parents_helper(parents, target) 544 | ptlist = _path_to_point_cloud(numpy_path, 3, sy, sx) 545 | return ptlist[:, :ndim] 546 | 547 | @cython.binding(True) 548 | def parental_field(data, source, connectivity=26, voxel_graph=None): 549 | """ 550 | Use dijkstra's shortest path algorithm 551 | on a 3D image grid to generate field of 552 | voxels that point to their parent voxel. 553 | 554 | This is used to execute dijkstra's algorithm 555 | once, and then query different targets for 556 | the path they represent. 557 | 558 | Parameters: 559 | data: Input weights in a 2D or 3D numpy array. 560 | source: (x,y,z) coordinate of starting voxel 561 | connectivity: 6 (faces), 18 (faces + edges), and 562 | 26 (faces + edges + corners) voxel graph connectivities 563 | are supported. For 2D images, 4 gets translated to 6, 564 | 8 gets translated to 18. 565 | 566 | Returns: 2D or 3D numpy array with each index 567 | containing the index of its parent. The root 568 | of a path has index 0. 569 | """ 570 | dims = len(data.shape) 571 | if dims not in (2,3): 572 | raise DimensionError("Only 2D and 3D image sources are supported. Got: " + str(dims)) 573 | 574 | if dims == 2: 575 | if connectivity == 4: 576 | connectivity = 6 577 | elif connectivity == 8: 578 | connectivity = 18 # or 26 but 18 might be faster 579 | 580 | if connectivity not in (6,18,26): 581 | raise ValueError( 582 | "Only 6, 18, and 26 connectivities are supported. Got: " + str(connectivity) 583 | ) 584 | 585 | if data.size == 0: 586 | return np.zeros(shape=(0,), dtype=np.float32) 587 | 588 | if dims == 1: 589 | data = data[:, np.newaxis, np.newaxis] 590 | source = ( source[0], 0, 0 ) 591 | if dims == 2: 592 | data = data[:, :, np.newaxis] 593 | source = ( source[0], source[1], 0 ) 594 | 595 | if voxel_graph is not None: 596 | voxel_graph = format_voxel_graph(voxel_graph) 597 | 598 | _validate_coord(data, source) 599 | 600 | data = np.asfortranarray(data) 601 | 602 | field = _execute_parental_field(data, source, connectivity, voxel_graph) 603 | if dims < 3: 604 | field = np.squeeze(field, axis=2) 605 | if dims < 2: 606 | field = np.squeeze(field, axis=1) 607 | 608 | return field 609 | 610 | @cython.binding(True) 611 | def euclidean_distance_field( 612 | data, source, anisotropy=(1,1,1), 613 | free_space_radius=0, voxel_graph=None, 614 | return_max_location=False, 615 | return_feature_map=False, 616 | ): 617 | """ 618 | Use dijkstra's shortest path algorithm 619 | on a 3D image grid to generate a weighted 620 | euclidean distance field from a source voxel 621 | from a binary image. Vertices are 622 | voxels and edges are the 26 nearest neighbors 623 | (except for the edges of the image where 624 | the number of edges is reduced). 625 | 626 | For given input voxels A and B, the edge 627 | weight from A to B is B and from B to A is 628 | A. All weights must be non-negative (incl. 629 | negative zero). 630 | 631 | Parameters: 632 | data: binary image represented as a 2D or 3D numpy array. 633 | source: (x,y,z) coordinate or list of coordinates 634 | of starting voxels 635 | anisotropy: (wx,wy,wz) weights for each axial direction. 636 | free_space_radius: (float, optional) if you know that the 637 | region surrounding the source is free space, we can use 638 | a much faster algorithm to fill in that volume. Value 639 | is physical radius (can get this from the EDT). 640 | voxel_graph: a bitwise representation of the premitted 641 | directions of travel between voxels. Generated from 642 | cc3d.voxel_connectivity_graph. 643 | (See https://github.com/seung-lab/connected-components-3d) 644 | return_max_location: returns the coordinates of one 645 | of the possibly multiple maxima. 646 | return_feature_map: return labeling of the image such 647 | that all the voxels nearest a given source point are 648 | a single label. At locations where two labels are 649 | equidistant, the numerically larger label wins (to 650 | differences in behavior on different platforms). 651 | 652 | Returns: 653 | let field = 2D or 3D numpy array with each index 654 | containing its distance from the source voxel. 655 | 656 | if return_max_location and return_feature_map: 657 | return (field, (x,y,z) of max distance, feature_map) 658 | elif return_max_location: 659 | return (field, (x,y,z) of max distance) 660 | elif return_feature_map: 661 | return (field, feature_map) 662 | else: 663 | return field 664 | """ 665 | dims = len(data.shape) 666 | if dims > 3: 667 | raise DimensionError(f"Only 2D and 3D image sources are supported. Got: {dims}") 668 | 669 | if data.size == 0: 670 | return np.zeros(shape=(0,), dtype=np.float32) 671 | 672 | source = np.array(source, dtype=np.uint64) 673 | if source.ndim == 1: 674 | source = source[np.newaxis, :] 675 | 676 | if source.shape[1] < 3: 677 | tmp = np.zeros((source.shape[0], 3), dtype=np.uint64) 678 | tmp[:, :source.shape[1]] = source[:,:] 679 | source = tmp 680 | 681 | while data.ndim < 3: 682 | data = data[..., np.newaxis] 683 | 684 | for src in source: 685 | _validate_coord(data, src) 686 | 687 | if voxel_graph is not None: 688 | voxel_graph = format_voxel_graph(voxel_graph) 689 | 690 | data = np.asfortranarray(data) 691 | 692 | if return_feature_map: 693 | field, feature_map, max_loc = _execute_euclidean_distance_field_w_feature_map( 694 | data, source, anisotropy, 695 | ) 696 | else: 697 | feature_map = None 698 | field, max_loc = _execute_euclidean_distance_field( 699 | data, source, anisotropy, 700 | free_space_radius, voxel_graph 701 | ) 702 | 703 | if dims < 3: 704 | field = np.squeeze(field, axis=2) 705 | if feature_map: 706 | feature_map = np.squeeze(feature_map, axis=2) 707 | if dims < 2: 708 | field = np.squeeze(field, axis=1) 709 | if feature_map: 710 | feature_map = np.squeeze(feature_map, axis=1) 711 | 712 | ret = [ field ] 713 | 714 | if return_max_location: 715 | ret.append( 716 | np.unravel_index(max_loc, data.shape, order="F")[:dims] 717 | ) 718 | if return_feature_map: 719 | ret.append(feature_map) 720 | 721 | if len(ret) == 1: 722 | return ret[0] 723 | return tuple(ret) 724 | 725 | def _validate_coord(data, coord): 726 | dims = len(data.shape) 727 | 728 | if len(coord) != dims: 729 | raise IndexError( 730 | "Coordinates must have the same dimension as the data. coord: {}, data shape: {}" 731 | .format(coord, data.shape) 732 | ) 733 | 734 | for i, size in enumerate(data.shape): 735 | if coord[i] < 0 or coord[i] >= size: 736 | raise IndexError("Selected voxel {} was not located inside the array.".format(coord)) 737 | 738 | def _path_to_point_cloud(path, dims, rows, cols): 739 | ptlist = np.zeros((path.shape[0], dims), dtype=np.uint32) 740 | 741 | cdef size_t sxy = rows * cols 742 | cdef size_t i = 0 743 | 744 | if dims == 3: 745 | for i, pt in enumerate(path): 746 | ptlist[ i, 0 ] = pt % cols 747 | ptlist[ i, 1 ] = (pt % sxy) / cols 748 | ptlist[ i, 2 ] = pt / sxy 749 | else: 750 | for i, pt in enumerate(path): 751 | ptlist[ i, 0 ] = pt % cols 752 | ptlist[ i, 1 ] = (pt % sxy) / cols 753 | 754 | return ptlist 755 | 756 | def _execute_value_target_dijkstra( 757 | data, source, 758 | int connectivity, voxel_graph=None 759 | ): 760 | cdef uint8_t[:,:,:] arr_memview8 761 | cdef uint16_t[:,:,:] arr_memview16 762 | cdef uint32_t[:,:,:] arr_memview32 763 | cdef uint64_t[:,:,:] arr_memview64 764 | cdef float[:,:,:] arr_memviewfloat 765 | cdef double[:,:,:] arr_memviewdouble 766 | 767 | cdef uint32_t[:,:,:] voxel_graph_memview 768 | cdef uint32_t* voxel_graph_ptr = NULL 769 | if voxel_graph is not None: 770 | voxel_graph_memview = voxel_graph 771 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 772 | 773 | cdef size_t sx = data.shape[0] 774 | cdef size_t sy = data.shape[1] 775 | cdef size_t sz = data.shape[2] 776 | 777 | cdef size_t src = source[0] + sx * (source[1] + sy * source[2]) 778 | 779 | cdef vector[uint32_t] output32 780 | cdef vector[uint64_t] output64 781 | 782 | sixtyfourbit = data.size > np.iinfo(np.uint32).max 783 | 784 | dtype = data.dtype 785 | 786 | if dtype == np.float32: 787 | arr_memviewfloat = data 788 | if sixtyfourbit: 789 | output64 = value_target_dijkstra3d[float, uint64_t]( 790 | &arr_memviewfloat[0,0,0], 791 | sx, sy, sz, 792 | src, 0, connectivity, 793 | voxel_graph_ptr 794 | ) 795 | else: 796 | output32 = value_target_dijkstra3d[float, uint32_t]( 797 | &arr_memviewfloat[0,0,0], 798 | sx, sy, sz, 799 | src, 0, connectivity, 800 | voxel_graph_ptr 801 | ) 802 | elif dtype == np.float64: 803 | arr_memviewdouble = data 804 | if sixtyfourbit: 805 | output64 = value_target_dijkstra3d[double, uint64_t]( 806 | &arr_memviewdouble[0,0,0], 807 | sx, sy, sz, 808 | src, 0, connectivity, 809 | voxel_graph_ptr 810 | ) 811 | else: 812 | output32 = value_target_dijkstra3d[double, uint32_t]( 813 | &arr_memviewdouble[0,0,0], 814 | sx, sy, sz, 815 | src, 0, connectivity, 816 | voxel_graph_ptr 817 | ) 818 | elif dtype in (np.int64, np.uint64): 819 | arr_memview64 = data.view(np.uint64) 820 | if sixtyfourbit: 821 | output64 = value_target_dijkstra3d[uint64_t, uint64_t]( 822 | &arr_memview64[0,0,0], 823 | sx, sy, sz, 824 | src, 0, connectivity, 825 | voxel_graph_ptr 826 | ) 827 | else: 828 | output32 = value_target_dijkstra3d[uint64_t, uint32_t]( 829 | &arr_memview64[0,0,0], 830 | sx, sy, sz, 831 | src, 0, connectivity, 832 | voxel_graph_ptr 833 | ) 834 | elif dtype in (np.int32, np.uint32): 835 | arr_memview32 = data.view(np.uint32) 836 | if sixtyfourbit: 837 | output64 = value_target_dijkstra3d[uint32_t, uint64_t]( 838 | &arr_memview32[0,0,0], 839 | sx, sy, sz, 840 | src, 0, connectivity, 841 | voxel_graph_ptr 842 | ) 843 | else: 844 | output32 = value_target_dijkstra3d[uint32_t, uint32_t]( 845 | &arr_memview32[0,0,0], 846 | sx, sy, sz, 847 | src, 0, connectivity, 848 | voxel_graph_ptr 849 | ) 850 | elif dtype in (np.int16, np.uint16): 851 | arr_memview16 = data.view(np.uint16) 852 | if sixtyfourbit: 853 | output64 = value_target_dijkstra3d[uint16_t, uint64_t]( 854 | &arr_memview16[0,0,0], 855 | sx, sy, sz, 856 | src, 0, connectivity, 857 | voxel_graph_ptr 858 | ) 859 | else: 860 | output32 = value_target_dijkstra3d[uint16_t, uint32_t]( 861 | &arr_memview16[0,0,0], 862 | sx, sy, sz, 863 | src, 0, connectivity, 864 | voxel_graph_ptr 865 | ) 866 | elif dtype in (np.int8, np.uint8, bool): 867 | arr_memview8 = data.view(np.uint8) 868 | if sixtyfourbit: 869 | output64 = value_target_dijkstra3d[uint8_t, uint64_t]( 870 | &arr_memview8[0,0,0], 871 | sx, sy, sz, 872 | src, 0, connectivity, 873 | voxel_graph_ptr 874 | ) 875 | else: 876 | output32 = value_target_dijkstra3d[uint8_t, uint32_t]( 877 | &arr_memview8[0,0,0], 878 | sx, sy, sz, 879 | src, 0, connectivity, 880 | voxel_graph_ptr 881 | ) 882 | 883 | cdef uint32_t* output_ptr32 884 | cdef uint64_t* output_ptr64 885 | 886 | cdef uint32_t[:] vec_view32 887 | cdef uint64_t[:] vec_view64 888 | 889 | if sixtyfourbit: 890 | output_ptr64 = &output64[0] 891 | if output64.size() == 0: 892 | return np.zeros((0,), dtype=np.uint64) 893 | vec_view64 = output_ptr64 894 | buf = bytearray(vec_view64[:]) 895 | output = np.frombuffer(buf, dtype=np.uint64) 896 | else: 897 | output_ptr32 = &output32[0] 898 | if output32.size() == 0: 899 | return np.zeros((0,), dtype=np.uint32) 900 | vec_view32 = output_ptr32 901 | buf = bytearray(vec_view32[:]) 902 | output = np.frombuffer(buf, dtype=np.uint32) 903 | 904 | return output[::-1] 905 | 906 | def _execute_dijkstra( 907 | data, source, target, int connectivity, 908 | bidirectional, compass, float compass_norm=-1, 909 | voxel_graph=None 910 | ): 911 | cdef uint8_t[:,:,:] arr_memview8 912 | cdef uint16_t[:,:,:] arr_memview16 913 | cdef uint32_t[:,:,:] arr_memview32 914 | cdef uint64_t[:,:,:] arr_memview64 915 | cdef float[:,:,:] arr_memviewfloat 916 | cdef double[:,:,:] arr_memviewdouble 917 | 918 | cdef uint32_t[:,:,:] voxel_graph_memview 919 | cdef uint32_t* voxel_graph_ptr = NULL 920 | if voxel_graph is not None: 921 | voxel_graph_memview = voxel_graph 922 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 923 | 924 | cdef size_t sx = data.shape[0] 925 | cdef size_t sy = data.shape[1] 926 | cdef size_t sz = data.shape[2] 927 | 928 | cdef size_t src = source[0] + sx * (source[1] + sy * source[2]) 929 | cdef size_t sink = target[0] + sx * (target[1] + sy * target[2]) 930 | 931 | cdef vector[uint32_t] output32 932 | cdef vector[uint64_t] output64 933 | 934 | sixtyfourbit = data.size > np.iinfo(np.uint32).max 935 | 936 | dtype = data.dtype 937 | 938 | if dtype == np.float32: 939 | arr_memviewfloat = data 940 | if bidirectional: 941 | if sixtyfourbit: 942 | output64 = bidirectional_dijkstra3d[float, uint64_t]( 943 | &arr_memviewfloat[0,0,0], 944 | sx, sy, sz, 945 | src, sink, connectivity, 946 | voxel_graph_ptr 947 | ) 948 | else: 949 | output32 = bidirectional_dijkstra3d[float, uint32_t]( 950 | &arr_memviewfloat[0,0,0], 951 | sx, sy, sz, 952 | src, sink, connectivity, 953 | voxel_graph_ptr 954 | ) 955 | elif compass: 956 | if sixtyfourbit: 957 | output64 = compass_guided_dijkstra3d[float, uint64_t]( 958 | &arr_memviewfloat[0,0,0], 959 | sx, sy, sz, 960 | src, sink, 961 | connectivity, compass_norm, 962 | voxel_graph_ptr 963 | ) 964 | else: 965 | output32 = compass_guided_dijkstra3d[float, uint32_t]( 966 | &arr_memviewfloat[0,0,0], 967 | sx, sy, sz, 968 | src, sink, 969 | connectivity, compass_norm, 970 | voxel_graph_ptr 971 | ) 972 | else: 973 | if sixtyfourbit: 974 | output64 = dijkstra3d[float, uint64_t]( 975 | &arr_memviewfloat[0,0,0], 976 | sx, sy, sz, 977 | src, sink, connectivity, 978 | voxel_graph_ptr 979 | ) 980 | else: 981 | output32 = dijkstra3d[float, uint32_t]( 982 | &arr_memviewfloat[0,0,0], 983 | sx, sy, sz, 984 | src, sink, connectivity, 985 | voxel_graph_ptr 986 | ) 987 | elif dtype == np.float64: 988 | arr_memviewdouble = data 989 | if bidirectional: 990 | if sixtyfourbit: 991 | output64 = bidirectional_dijkstra3d[double, uint64_t]( 992 | &arr_memviewdouble[0,0,0], 993 | sx, sy, sz, 994 | src, sink, connectivity, 995 | voxel_graph_ptr 996 | ) 997 | else: 998 | output32 = bidirectional_dijkstra3d[double, uint32_t]( 999 | &arr_memviewdouble[0,0,0], 1000 | sx, sy, sz, 1001 | src, sink, connectivity, 1002 | voxel_graph_ptr 1003 | ) 1004 | elif compass: 1005 | if sixtyfourbit: 1006 | output64 = compass_guided_dijkstra3d[double, uint64_t]( 1007 | &arr_memviewdouble[0,0,0], 1008 | sx, sy, sz, 1009 | src, sink, 1010 | connectivity, compass_norm, 1011 | voxel_graph_ptr 1012 | ) 1013 | else: 1014 | output32 = compass_guided_dijkstra3d[double, uint32_t]( 1015 | &arr_memviewdouble[0,0,0], 1016 | sx, sy, sz, 1017 | src, sink, 1018 | connectivity, compass_norm, 1019 | voxel_graph_ptr 1020 | ) 1021 | else: 1022 | if sixtyfourbit: 1023 | output64 = dijkstra3d[double, uint64_t]( 1024 | &arr_memviewdouble[0,0,0], 1025 | sx, sy, sz, 1026 | src, sink, connectivity, 1027 | voxel_graph_ptr 1028 | ) 1029 | else: 1030 | output32 = dijkstra3d[double, uint32_t]( 1031 | &arr_memviewdouble[0,0,0], 1032 | sx, sy, sz, 1033 | src, sink, connectivity, 1034 | voxel_graph_ptr 1035 | ) 1036 | elif dtype in (np.int64, np.uint64): 1037 | arr_memview64 = data.view(np.uint64) 1038 | if bidirectional: 1039 | if sixtyfourbit: 1040 | output64 = bidirectional_dijkstra3d[uint64_t, uint64_t]( 1041 | &arr_memview64[0,0,0], 1042 | sx, sy, sz, 1043 | src, sink, connectivity, 1044 | voxel_graph_ptr 1045 | ) 1046 | else: 1047 | output32 = bidirectional_dijkstra3d[uint64_t, uint32_t]( 1048 | &arr_memview64[0,0,0], 1049 | sx, sy, sz, 1050 | src, sink, connectivity, 1051 | voxel_graph_ptr 1052 | ) 1053 | elif compass: 1054 | if sixtyfourbit: 1055 | output64 = compass_guided_dijkstra3d[uint64_t, uint64_t]( 1056 | &arr_memview64[0,0,0], 1057 | sx, sy, sz, 1058 | src, sink, 1059 | connectivity, compass_norm, 1060 | voxel_graph_ptr 1061 | ) 1062 | else: 1063 | output32 = compass_guided_dijkstra3d[uint64_t, uint32_t]( 1064 | &arr_memview64[0,0,0], 1065 | sx, sy, sz, 1066 | src, sink, 1067 | connectivity, compass_norm, 1068 | voxel_graph_ptr 1069 | ) 1070 | else: 1071 | if sixtyfourbit: 1072 | output64 = dijkstra3d[uint64_t, uint64_t]( 1073 | &arr_memview64[0,0,0], 1074 | sx, sy, sz, 1075 | src, sink, connectivity, 1076 | voxel_graph_ptr 1077 | ) 1078 | else: 1079 | output32 = dijkstra3d[uint64_t, uint32_t]( 1080 | &arr_memview64[0,0,0], 1081 | sx, sy, sz, 1082 | src, sink, connectivity, 1083 | voxel_graph_ptr 1084 | ) 1085 | elif dtype in (np.int32, np.uint32): 1086 | arr_memview32 = data.view(np.uint32) 1087 | if bidirectional: 1088 | if sixtyfourbit: 1089 | output64 = bidirectional_dijkstra3d[uint32_t, uint64_t]( 1090 | &arr_memview32[0,0,0], 1091 | sx, sy, sz, 1092 | src, sink, connectivity, 1093 | voxel_graph_ptr 1094 | ) 1095 | else: 1096 | output32 = bidirectional_dijkstra3d[uint32_t, uint32_t]( 1097 | &arr_memview32[0,0,0], 1098 | sx, sy, sz, 1099 | src, sink, connectivity, 1100 | voxel_graph_ptr 1101 | ) 1102 | elif compass: 1103 | if sixtyfourbit: 1104 | output64 = compass_guided_dijkstra3d[uint32_t, uint64_t]( 1105 | &arr_memview32[0,0,0], 1106 | sx, sy, sz, 1107 | src, sink, 1108 | connectivity, compass_norm, 1109 | voxel_graph_ptr 1110 | ) 1111 | else: 1112 | output32 = compass_guided_dijkstra3d[uint32_t, uint32_t]( 1113 | &arr_memview32[0,0,0], 1114 | sx, sy, sz, 1115 | src, sink, 1116 | connectivity, compass_norm, 1117 | voxel_graph_ptr 1118 | ) 1119 | else: 1120 | if sixtyfourbit: 1121 | output64 = dijkstra3d[uint32_t, uint64_t]( 1122 | &arr_memview32[0,0,0], 1123 | sx, sy, sz, 1124 | src, sink, connectivity, 1125 | voxel_graph_ptr 1126 | ) 1127 | else: 1128 | output32 = dijkstra3d[uint32_t, uint32_t]( 1129 | &arr_memview32[0,0,0], 1130 | sx, sy, sz, 1131 | src, sink, connectivity, 1132 | voxel_graph_ptr 1133 | ) 1134 | elif dtype in (np.int16, np.uint16): 1135 | arr_memview16 = data.view(np.uint16) 1136 | if bidirectional: 1137 | if sixtyfourbit: 1138 | output64 = bidirectional_dijkstra3d[uint16_t, uint64_t]( 1139 | &arr_memview16[0,0,0], 1140 | sx, sy, sz, 1141 | src, sink, connectivity, 1142 | voxel_graph_ptr 1143 | ) 1144 | else: 1145 | output32 = bidirectional_dijkstra3d[uint16_t, uint32_t]( 1146 | &arr_memview16[0,0,0], 1147 | sx, sy, sz, 1148 | src, sink, connectivity, 1149 | voxel_graph_ptr 1150 | ) 1151 | elif compass: 1152 | if sixtyfourbit: 1153 | output64 = compass_guided_dijkstra3d[uint16_t, uint64_t]( 1154 | &arr_memview16[0,0,0], 1155 | sx, sy, sz, 1156 | src, sink, 1157 | connectivity, compass_norm, 1158 | voxel_graph_ptr 1159 | ) 1160 | else: 1161 | output32 = compass_guided_dijkstra3d[uint16_t, uint32_t]( 1162 | &arr_memview16[0,0,0], 1163 | sx, sy, sz, 1164 | src, sink, 1165 | connectivity, compass_norm, 1166 | voxel_graph_ptr 1167 | ) 1168 | else: 1169 | if sixtyfourbit: 1170 | output64 = dijkstra3d[uint16_t, uint64_t]( 1171 | &arr_memview16[0,0,0], 1172 | sx, sy, sz, 1173 | src, sink, connectivity, 1174 | voxel_graph_ptr 1175 | ) 1176 | else: 1177 | output32 = dijkstra3d[uint16_t, uint32_t]( 1178 | &arr_memview16[0,0,0], 1179 | sx, sy, sz, 1180 | src, sink, connectivity, 1181 | voxel_graph_ptr 1182 | ) 1183 | elif dtype in (np.int8, np.uint8, bool): 1184 | arr_memview8 = data.view(np.uint8) 1185 | if bidirectional: 1186 | if sixtyfourbit: 1187 | output64 = bidirectional_dijkstra3d[uint8_t, uint64_t]( 1188 | &arr_memview8[0,0,0], 1189 | sx, sy, sz, 1190 | src, sink, connectivity, 1191 | voxel_graph_ptr 1192 | ) 1193 | else: 1194 | output32 = bidirectional_dijkstra3d[uint8_t, uint32_t]( 1195 | &arr_memview8[0,0,0], 1196 | sx, sy, sz, 1197 | src, sink, connectivity, 1198 | voxel_graph_ptr 1199 | ) 1200 | elif compass: 1201 | if sixtyfourbit: 1202 | output64 = compass_guided_dijkstra3d[uint8_t, uint64_t]( 1203 | &arr_memview8[0,0,0], 1204 | sx, sy, sz, 1205 | src, sink, 1206 | connectivity, compass_norm, 1207 | voxel_graph_ptr 1208 | ) 1209 | else: 1210 | output32 = compass_guided_dijkstra3d[uint8_t, uint32_t]( 1211 | &arr_memview8[0,0,0], 1212 | sx, sy, sz, 1213 | src, sink, 1214 | connectivity, compass_norm, 1215 | voxel_graph_ptr 1216 | ) 1217 | else: 1218 | if sixtyfourbit: 1219 | output64 = dijkstra3d[uint8_t, uint64_t]( 1220 | &arr_memview8[0,0,0], 1221 | sx, sy, sz, 1222 | src, sink, connectivity, 1223 | voxel_graph_ptr 1224 | ) 1225 | else: 1226 | output32 = dijkstra3d[uint8_t, uint32_t]( 1227 | &arr_memview8[0,0,0], 1228 | sx, sy, sz, 1229 | src, sink, connectivity, 1230 | voxel_graph_ptr 1231 | ) 1232 | 1233 | cdef uint32_t* output_ptr32 1234 | cdef uint64_t* output_ptr64 1235 | 1236 | cdef uint32_t[:] vec_view32 1237 | cdef uint64_t[:] vec_view64 1238 | 1239 | if sixtyfourbit: 1240 | output_ptr64 = &output64[0] 1241 | if output64.size() == 0: 1242 | return np.zeros((0,), dtype=np.uint64) 1243 | vec_view64 = output_ptr64 1244 | buf = bytearray(vec_view64[:]) 1245 | output = np.frombuffer(buf, dtype=np.uint64) 1246 | else: 1247 | output_ptr32 = &output32[0] 1248 | if output32.size() == 0: 1249 | return np.zeros((0,), dtype=np.uint32) 1250 | vec_view32 = output_ptr32 1251 | buf = bytearray(vec_view32[:]) 1252 | output = np.frombuffer(buf, dtype=np.uint32) 1253 | 1254 | if bidirectional: 1255 | return output 1256 | else: 1257 | return output[::-1] 1258 | 1259 | def _execute_dijkstra_anisotropy( 1260 | data, source, target, int connectivity, 1261 | anisotropy, compass, float compass_norm=-1, voxel_graph=None, float line_preference_weight=0, 1262 | ): 1263 | cdef uint8_t[:,:,:] arr_memview8 1264 | cdef uint16_t[:,:,:] arr_memview16 1265 | cdef uint32_t[:,:,:] arr_memview32 1266 | cdef uint64_t[:,:,:] arr_memview64 1267 | cdef float[:,:,:] arr_memviewfloat 1268 | cdef double[:,:,:] arr_memviewdouble 1269 | 1270 | cdef uint32_t[:,:,:] voxel_graph_memview 1271 | cdef uint32_t* voxel_graph_ptr = NULL 1272 | if voxel_graph is not None: 1273 | voxel_graph_memview = voxel_graph 1274 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 1275 | 1276 | cdef size_t sx = data.shape[0] 1277 | cdef size_t sy = data.shape[1] 1278 | cdef size_t sz = data.shape[2] 1279 | 1280 | cdef float wx = anisotropy[0] 1281 | cdef float wy = anisotropy[1] 1282 | cdef float wz = anisotropy[2] 1283 | 1284 | cdef size_t src = source[0] + sx * (source[1] + sy * source[2]) 1285 | cdef size_t sink = target[0] + sx * (target[1] + sy * target[2]) 1286 | 1287 | cdef vector[uint32_t] output32 1288 | cdef vector[uint64_t] output64 1289 | 1290 | sixtyfourbit = data.size > np.iinfo(np.uint32).max 1291 | 1292 | dtype = data.dtype 1293 | 1294 | if dtype == np.float32: 1295 | arr_memviewfloat = data 1296 | if compass: 1297 | if sixtyfourbit: 1298 | output64 = compass_guided_dijkstra3d_anisotropy_line_preference[float, uint64_t]( 1299 | &arr_memviewfloat[0,0,0], 1300 | sx, sy, sz, 1301 | src, sink, connectivity, compass_norm, line_preference_weight, 1302 | wx, wy, wz, 1303 | voxel_graph_ptr 1304 | ) 1305 | else: 1306 | output32 = compass_guided_dijkstra3d_anisotropy_line_preference[float, uint32_t]( 1307 | &arr_memviewfloat[0,0,0], 1308 | sx, sy, sz, 1309 | src, sink, connectivity, compass_norm, line_preference_weight, 1310 | wx, wy, wz, 1311 | voxel_graph_ptr 1312 | ) 1313 | else: 1314 | if sixtyfourbit: 1315 | output64 = dijkstra3d_anisotropy[float, uint64_t]( 1316 | &arr_memviewfloat[0,0,0], 1317 | sx, sy, sz, 1318 | src, sink, connectivity, 1319 | wx, wy, wz, 1320 | voxel_graph_ptr 1321 | ) 1322 | else: 1323 | output32 = dijkstra3d_anisotropy[float, uint32_t]( 1324 | &arr_memviewfloat[0,0,0], 1325 | sx, sy, sz, 1326 | src, sink, connectivity, 1327 | wx, wy, wz, 1328 | voxel_graph_ptr 1329 | ) 1330 | elif dtype == np.float64: 1331 | arr_memviewdouble = data 1332 | if compass: 1333 | if sixtyfourbit: 1334 | output64 = compass_guided_dijkstra3d_anisotropy_line_preference[double, uint64_t]( 1335 | &arr_memviewdouble[0,0,0], 1336 | sx, sy, sz, 1337 | src, sink, connectivity, compass_norm, line_preference_weight, 1338 | wx, wy, wz, 1339 | voxel_graph_ptr 1340 | ) 1341 | else: 1342 | output32 = compass_guided_dijkstra3d_anisotropy_line_preference[double, uint32_t]( 1343 | &arr_memviewdouble[0,0,0], 1344 | sx, sy, sz, 1345 | src, sink, connectivity, compass_norm, line_preference_weight, 1346 | wx, wy, wz, 1347 | voxel_graph_ptr 1348 | ) 1349 | else: 1350 | if sixtyfourbit: 1351 | output64 = dijkstra3d_anisotropy[double, uint64_t]( 1352 | &arr_memviewdouble[0,0,0], 1353 | sx, sy, sz, 1354 | src, sink, connectivity, 1355 | wx, wy, wz, 1356 | voxel_graph_ptr 1357 | ) 1358 | else: 1359 | output32 = dijkstra3d_anisotropy[double, uint32_t]( 1360 | &arr_memviewdouble[0,0,0], 1361 | sx, sy, sz, 1362 | src, sink, connectivity, 1363 | wx, wy, wz, 1364 | voxel_graph_ptr 1365 | ) 1366 | elif dtype in (np.int64, np.uint64): 1367 | arr_memview64 = data.view(np.uint64) 1368 | if compass: 1369 | if sixtyfourbit: 1370 | output64 = compass_guided_dijkstra3d_anisotropy_line_preference[uint64_t, uint64_t]( 1371 | &arr_memview64[0,0,0], 1372 | sx, sy, sz, 1373 | src, sink, connectivity, compass_norm, line_preference_weight, 1374 | wx, wy, wz, 1375 | voxel_graph_ptr 1376 | ) 1377 | else: 1378 | output32 = compass_guided_dijkstra3d_anisotropy_line_preference[uint64_t, uint32_t]( 1379 | &arr_memview64[0,0,0], 1380 | sx, sy, sz, 1381 | src, sink, connectivity, compass_norm, line_preference_weight, 1382 | wx, wy, wz, 1383 | voxel_graph_ptr 1384 | ) 1385 | else: 1386 | if sixtyfourbit: 1387 | output64 = dijkstra3d_anisotropy[uint64_t, uint64_t]( 1388 | &arr_memview64[0,0,0], 1389 | sx, sy, sz, 1390 | src, sink, connectivity, 1391 | wx, wy, wz, 1392 | voxel_graph_ptr 1393 | ) 1394 | else: 1395 | output32 = dijkstra3d_anisotropy[uint64_t, uint32_t]( 1396 | &arr_memview64[0,0,0], 1397 | sx, sy, sz, 1398 | src, sink, connectivity, 1399 | wx, wy, wz, 1400 | voxel_graph_ptr 1401 | ) 1402 | elif dtype in (np.int32, np.uint32): 1403 | arr_memview32 = data.view(np.uint32) 1404 | if compass: 1405 | if sixtyfourbit: 1406 | output64 = compass_guided_dijkstra3d_anisotropy_line_preference[uint32_t, uint64_t]( 1407 | &arr_memview32[0,0,0], 1408 | sx, sy, sz, 1409 | src, sink, connectivity, compass_norm, line_preference_weight, 1410 | wx, wy, wz, 1411 | voxel_graph_ptr 1412 | ) 1413 | else: 1414 | output32 = compass_guided_dijkstra3d_anisotropy_line_preference[uint32_t, uint32_t]( 1415 | &arr_memview32[0,0,0], 1416 | sx, sy, sz, 1417 | src, sink, connectivity, compass_norm, line_preference_weight, 1418 | wx, wy, wz, 1419 | voxel_graph_ptr 1420 | ) 1421 | else: 1422 | if sixtyfourbit: 1423 | output64 = dijkstra3d_anisotropy[uint32_t, uint64_t]( 1424 | &arr_memview32[0,0,0], 1425 | sx, sy, sz, 1426 | src, sink, connectivity, 1427 | wx, wy, wz, 1428 | voxel_graph_ptr 1429 | ) 1430 | else: 1431 | output32 = dijkstra3d_anisotropy[uint32_t, uint32_t]( 1432 | &arr_memview32[0,0,0], 1433 | sx, sy, sz, 1434 | src, sink, connectivity, 1435 | wx, wy, wz, 1436 | voxel_graph_ptr 1437 | ) 1438 | elif dtype in (np.int16, np.uint16): 1439 | arr_memview16 = data.view(np.uint16) 1440 | if compass: 1441 | if sixtyfourbit: 1442 | output64 = compass_guided_dijkstra3d_anisotropy_line_preference[uint16_t, uint64_t]( 1443 | &arr_memview16[0,0,0], 1444 | sx, sy, sz, 1445 | src, sink, connectivity, compass_norm, line_preference_weight, 1446 | wx, wy, wz, 1447 | voxel_graph_ptr 1448 | ) 1449 | else: 1450 | output32 = compass_guided_dijkstra3d_anisotropy_line_preference[uint16_t, uint32_t]( 1451 | &arr_memview16[0,0,0], 1452 | sx, sy, sz, 1453 | src, sink, connectivity, compass_norm, line_preference_weight, 1454 | wx, wy, wz, 1455 | voxel_graph_ptr 1456 | ) 1457 | else: 1458 | if sixtyfourbit: 1459 | output64 = dijkstra3d_anisotropy[uint16_t, uint64_t]( 1460 | &arr_memview16[0,0,0], 1461 | sx, sy, sz, 1462 | src, sink, connectivity, 1463 | wx, wy, wz, 1464 | voxel_graph_ptr 1465 | ) 1466 | else: 1467 | output32 = dijkstra3d_anisotropy[uint16_t, uint32_t]( 1468 | &arr_memview16[0,0,0], 1469 | sx, sy, sz, 1470 | src, sink, connectivity, 1471 | wx, wy, wz, 1472 | voxel_graph_ptr 1473 | ) 1474 | elif dtype in (np.int8, np.uint8, bool): 1475 | arr_memview8 = data.view(np.uint8) 1476 | if compass: 1477 | if sixtyfourbit: 1478 | output64 = compass_guided_dijkstra3d_anisotropy_line_preference[uint8_t, uint64_t]( 1479 | &arr_memview8[0,0,0], 1480 | sx, sy, sz, 1481 | src, sink, connectivity, compass_norm, line_preference_weight, 1482 | wx, wy, wz, 1483 | voxel_graph_ptr 1484 | ) 1485 | else: 1486 | output32 = compass_guided_dijkstra3d_anisotropy_line_preference[uint8_t, uint32_t]( 1487 | &arr_memview8[0,0,0], 1488 | sx, sy, sz, 1489 | src, sink, connectivity, compass_norm, line_preference_weight, 1490 | wx, wy, wz, 1491 | voxel_graph_ptr 1492 | ) 1493 | else: 1494 | if sixtyfourbit: 1495 | output64 = dijkstra3d_anisotropy[uint8_t, uint64_t]( 1496 | &arr_memview8[0,0,0], 1497 | sx, sy, sz, 1498 | src, sink, connectivity, 1499 | wx, wy, wz, 1500 | voxel_graph_ptr 1501 | ) 1502 | else: 1503 | output32 = dijkstra3d_anisotropy[uint8_t, uint32_t]( 1504 | &arr_memview8[0,0,0], 1505 | sx, sy, sz, 1506 | src, sink, connectivity, 1507 | wx, wy, wz, 1508 | voxel_graph_ptr 1509 | ) 1510 | 1511 | cdef uint32_t* output_ptr32 1512 | cdef uint64_t* output_ptr64 1513 | 1514 | cdef uint32_t[:] vec_view32 1515 | cdef uint64_t[:] vec_view64 1516 | 1517 | if sixtyfourbit: 1518 | output_ptr64 = &output64[0] 1519 | if output64.size() == 0: 1520 | return np.zeros((0,), dtype=np.uint64) 1521 | vec_view64 = output_ptr64 1522 | buf = bytearray(vec_view64[:]) 1523 | output = np.frombuffer(buf, dtype=np.uint64) 1524 | else: 1525 | output_ptr32 = &output32[0] 1526 | if output32.size() == 0: 1527 | return np.zeros((0,), dtype=np.uint32) 1528 | vec_view32 = output_ptr32 1529 | buf = bytearray(vec_view32[:]) 1530 | output = np.frombuffer(buf, dtype=np.uint32) 1531 | 1532 | return output[::-1] 1533 | 1534 | def _execute_binary_dijkstra( 1535 | data, source, target, int connectivity, 1536 | float wx, float wy, float wz, 1537 | euclidean_metric = True, 1538 | voxel_graph=None, background_color=0 1539 | ): 1540 | cdef uint8_t[:,:,:] arr_memview8 1541 | 1542 | cdef uint32_t[:,:,:] voxel_graph_memview 1543 | cdef uint32_t* voxel_graph_ptr = NULL 1544 | if voxel_graph is not None: 1545 | voxel_graph_memview = voxel_graph 1546 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 1547 | 1548 | cdef size_t sx = data.shape[0] 1549 | cdef size_t sy = data.shape[1] 1550 | cdef size_t sz = data.shape[2] 1551 | 1552 | cdef size_t src = source[0] + sx * (source[1] + sy * source[2]) 1553 | cdef size_t sink = target[0] + sx * (target[1] + sy * target[2]) 1554 | 1555 | cdef vector[uint32_t] output32 1556 | cdef vector[uint64_t] output64 1557 | 1558 | sixtyfourbit = data.size > np.iinfo(np.uint32).max 1559 | 1560 | dtype = data.dtype 1561 | 1562 | if dtype == bool: 1563 | arr_memview8 = data.view(np.uint8) 1564 | if sixtyfourbit: 1565 | output64 = binary_dijkstra3d[uint64_t]( 1566 | &arr_memview8[0,0,0], 1567 | sx, sy, sz, 1568 | src, sink, 1569 | connectivity, 1570 | wx, wy, wz, 1571 | euclidean_metric, 1572 | voxel_graph_ptr, background_color 1573 | ) 1574 | else: 1575 | output32 = binary_dijkstra3d[uint32_t]( 1576 | &arr_memview8[0,0,0], 1577 | sx, sy, sz, 1578 | src, sink, 1579 | connectivity, 1580 | wx, wy, wz, 1581 | euclidean_metric, 1582 | voxel_graph_ptr, background_color 1583 | ) 1584 | else: 1585 | raise ValueError("Only bool dtype is supported.") 1586 | 1587 | cdef uint32_t* output_ptr32 1588 | cdef uint64_t* output_ptr64 1589 | 1590 | cdef uint32_t[:] vec_view32 1591 | cdef uint64_t[:] vec_view64 1592 | 1593 | if sixtyfourbit: 1594 | output_ptr64 = &output64[0] 1595 | if output64.size() == 0: 1596 | return np.zeros((0,), dtype=np.uint64) 1597 | vec_view64 = output_ptr64 1598 | buf = bytearray(vec_view64[:]) 1599 | output = np.frombuffer(buf, dtype=np.uint64) 1600 | else: 1601 | output_ptr32 = &output32[0] 1602 | if output32.size() == 0: 1603 | return np.zeros((0,), dtype=np.uint32) 1604 | vec_view32 = output_ptr32 1605 | buf = bytearray(vec_view32[:]) 1606 | output = np.frombuffer(buf, dtype=np.uint32) 1607 | 1608 | return output[::-1] 1609 | 1610 | def _execute_distance_field(data, sources, connectivity, voxel_graph): 1611 | cdef uint8_t[:,:,:] arr_memview8 1612 | cdef uint16_t[:,:,:] arr_memview16 1613 | cdef uint32_t[:,:,:] arr_memview32 1614 | cdef uint64_t[:,:,:] arr_memview64 1615 | cdef float[:,:,:] arr_memviewfloat 1616 | cdef double[:,:,:] arr_memviewdouble 1617 | 1618 | cdef uint32_t[:,:,:] voxel_graph_memview 1619 | cdef uint32_t* voxel_graph_ptr = NULL 1620 | if voxel_graph is not None: 1621 | voxel_graph_memview = voxel_graph 1622 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 1623 | 1624 | cdef size_t sx = data.shape[0] 1625 | cdef size_t sy = data.shape[1] 1626 | cdef size_t sz = data.shape[2] 1627 | 1628 | cdef vector[size_t] src 1629 | for source in sources: 1630 | src.push_back(source[0] + sx * (source[1] + sy * source[2])) 1631 | 1632 | cdef float* dist 1633 | cdef size_t max_loc = data.size + 1 1634 | 1635 | dtype = data.dtype 1636 | 1637 | if dtype == np.float32: 1638 | arr_memviewfloat = data 1639 | dist = distance_field3d[float]( 1640 | &arr_memviewfloat[0,0,0], 1641 | sx, sy, sz, 1642 | src, connectivity, 1643 | voxel_graph_ptr, max_loc 1644 | ) 1645 | elif dtype == np.float64: 1646 | arr_memviewdouble = data 1647 | dist = distance_field3d[double]( 1648 | &arr_memviewdouble[0,0,0], 1649 | sx, sy, sz, 1650 | src, connectivity, 1651 | voxel_graph_ptr, max_loc 1652 | ) 1653 | elif dtype in (np.int64, np.uint64): 1654 | arr_memview64 = data.view(np.uint64) 1655 | dist = distance_field3d[uint64_t]( 1656 | &arr_memview64[0,0,0], 1657 | sx, sy, sz, 1658 | src, connectivity, 1659 | voxel_graph_ptr, max_loc 1660 | ) 1661 | elif dtype in (np.uint32, np.int32): 1662 | arr_memview32 = data.view(np.uint32) 1663 | dist = distance_field3d[uint32_t]( 1664 | &arr_memview32[0,0,0], 1665 | sx, sy, sz, 1666 | src, connectivity, 1667 | voxel_graph_ptr, max_loc 1668 | ) 1669 | elif dtype in (np.int16, np.uint16): 1670 | arr_memview16 = data.view(np.uint16) 1671 | dist = distance_field3d[uint16_t]( 1672 | &arr_memview16[0,0,0], 1673 | sx, sy, sz, 1674 | src, connectivity, 1675 | voxel_graph_ptr, max_loc 1676 | ) 1677 | elif dtype in (np.int8, np.uint8, bool): 1678 | arr_memview8 = data.view(np.uint8) 1679 | dist = distance_field3d[uint8_t]( 1680 | &arr_memview8[0,0,0], 1681 | sx, sy, sz, 1682 | src, connectivity, 1683 | voxel_graph_ptr, max_loc 1684 | ) 1685 | else: 1686 | raise TypeError("Type {} not currently supported.".format(dtype)) 1687 | 1688 | cdef size_t voxels = sx * sy * sz 1689 | cdef float[:] dist_view = dist 1690 | 1691 | # This construct is required by python 2. 1692 | # Python 3 can just do np.frombuffer(vec_view, ...) 1693 | buf = bytearray(dist_view[:]) 1694 | free(dist) 1695 | buf = np.frombuffer(buf, dtype=np.float32).reshape(data.shape, order='F') 1696 | return buf, max_loc 1697 | 1698 | def _execute_parental_field(data, source, connectivity, voxel_graph): 1699 | cdef uint8_t[:,:,:] arr_memview8 1700 | cdef uint16_t[:,:,:] arr_memview16 1701 | cdef uint32_t[:,:,:] arr_memview32 1702 | cdef uint64_t[:,:,:] arr_memview64 1703 | cdef float[:,:,:] arr_memviewfloat 1704 | cdef double[:,:,:] arr_memviewdouble 1705 | 1706 | cdef uint32_t[:,:,:] voxel_graph_memview 1707 | cdef uint32_t* voxel_graph_ptr = NULL 1708 | if voxel_graph is not None: 1709 | voxel_graph_memview = voxel_graph 1710 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 1711 | 1712 | cdef size_t sx = data.shape[0] 1713 | cdef size_t sy = data.shape[1] 1714 | cdef size_t sz = data.shape[2] 1715 | 1716 | cdef size_t src = source[0] + sx * (source[1] + sy * source[2]) 1717 | 1718 | sixtyfourbit = data.size > np.iinfo(np.uint32).max 1719 | 1720 | cdef cnp.ndarray[uint32_t, ndim=3] parents32 1721 | cdef cnp.ndarray[uint64_t, ndim=3] parents64 1722 | 1723 | if sixtyfourbit: 1724 | parents64 = np.zeros( (sx,sy,sz), dtype=np.uint64, order='F' ) 1725 | else: 1726 | parents32 = np.zeros( (sx,sy,sz), dtype=np.uint32, order='F' ) 1727 | 1728 | dtype = data.dtype 1729 | 1730 | if dtype == np.float32: 1731 | arr_memviewfloat = data 1732 | if sixtyfourbit: 1733 | parental_field3d[float,uint64_t]( 1734 | &arr_memviewfloat[0,0,0], 1735 | sx, sy, sz, 1736 | src, &parents64[0,0,0], 1737 | connectivity, 1738 | voxel_graph_ptr 1739 | ) 1740 | else: 1741 | parental_field3d[float,uint32_t]( 1742 | &arr_memviewfloat[0,0,0], 1743 | sx, sy, sz, 1744 | src, &parents32[0,0,0], 1745 | connectivity, 1746 | voxel_graph_ptr 1747 | ) 1748 | elif dtype == np.float64: 1749 | arr_memviewdouble = data 1750 | if sixtyfourbit: 1751 | parental_field3d[double,uint64_t]( 1752 | &arr_memviewdouble[0,0,0], 1753 | sx, sy, sz, 1754 | src, &parents64[0,0,0], 1755 | connectivity, 1756 | voxel_graph_ptr 1757 | ) 1758 | else: 1759 | parental_field3d[double,uint32_t]( 1760 | &arr_memviewdouble[0,0,0], 1761 | sx, sy, sz, 1762 | src, &parents32[0,0,0], 1763 | connectivity, 1764 | voxel_graph_ptr 1765 | ) 1766 | elif dtype in (np.int64, np.uint64): 1767 | arr_memview64 = data.view(np.uint64) 1768 | if sixtyfourbit: 1769 | parental_field3d[uint64_t,uint64_t]( 1770 | &arr_memview64[0,0,0], 1771 | sx, sy, sz, 1772 | src, &parents64[0,0,0], 1773 | connectivity, 1774 | voxel_graph_ptr 1775 | ) 1776 | else: 1777 | parental_field3d[uint64_t,uint32_t]( 1778 | &arr_memview64[0,0,0], 1779 | sx, sy, sz, 1780 | src, &parents32[0,0,0], 1781 | connectivity, 1782 | voxel_graph_ptr 1783 | ) 1784 | elif dtype in (np.uint32, np.int32): 1785 | arr_memview32 = data.view(np.uint32) 1786 | if sixtyfourbit: 1787 | parental_field3d[uint32_t,uint64_t]( 1788 | &arr_memview32[0,0,0], 1789 | sx, sy, sz, 1790 | src, &parents64[0,0,0], 1791 | connectivity, 1792 | voxel_graph_ptr 1793 | ) 1794 | else: 1795 | parental_field3d[uint32_t,uint32_t]( 1796 | &arr_memview32[0,0,0], 1797 | sx, sy, sz, 1798 | src, &parents32[0,0,0], 1799 | connectivity, 1800 | voxel_graph_ptr 1801 | ) 1802 | elif dtype in (np.int16, np.uint16): 1803 | arr_memview16 = data.view(np.uint16) 1804 | if sixtyfourbit: 1805 | parental_field3d[uint16_t,uint64_t]( 1806 | &arr_memview16[0,0,0], 1807 | sx, sy, sz, 1808 | src, &parents64[0,0,0], 1809 | connectivity, 1810 | voxel_graph_ptr 1811 | ) 1812 | else: 1813 | parental_field3d[uint16_t,uint32_t]( 1814 | &arr_memview16[0,0,0], 1815 | sx, sy, sz, 1816 | src, &parents32[0,0,0], 1817 | connectivity, 1818 | voxel_graph_ptr 1819 | ) 1820 | elif dtype in (np.int8, np.uint8, bool): 1821 | arr_memview8 = data.view(np.uint8) 1822 | if sixtyfourbit: 1823 | parental_field3d[uint8_t,uint64_t]( 1824 | &arr_memview8[0,0,0], 1825 | sx, sy, sz, 1826 | src, &parents64[0,0,0], 1827 | connectivity, 1828 | voxel_graph_ptr 1829 | ) 1830 | else: 1831 | parental_field3d[uint8_t,uint32_t]( 1832 | &arr_memview8[0,0,0], 1833 | sx, sy, sz, 1834 | src, &parents32[0,0,0], 1835 | connectivity, 1836 | voxel_graph_ptr 1837 | ) 1838 | else: 1839 | raise TypeError("Type {} not currently supported.".format(dtype)) 1840 | 1841 | if sixtyfourbit: 1842 | return parents64 1843 | else: 1844 | return parents32 1845 | 1846 | def _execute_euclidean_distance_field( 1847 | data, sources, anisotropy, float free_space_radius=0, 1848 | voxel_graph=None 1849 | ): 1850 | cdef uint8_t[:,:,:] arr_memview8 1851 | 1852 | cdef uint32_t[:,:,:] voxel_graph_memview 1853 | cdef uint32_t* voxel_graph_ptr = NULL 1854 | if voxel_graph is not None: 1855 | voxel_graph_memview = voxel_graph 1856 | voxel_graph_ptr = &voxel_graph_memview[0,0,0] 1857 | 1858 | cdef size_t sx = data.shape[0] 1859 | cdef size_t sy = data.shape[1] 1860 | cdef size_t sz = data.shape[2] 1861 | 1862 | cdef float wx = anisotropy[0] 1863 | cdef float wy = anisotropy[1] 1864 | cdef float wz = anisotropy[2] 1865 | 1866 | cdef vector[size_t] src 1867 | for source in sources: 1868 | src.push_back(source[0] + sx * (source[1] + sy * source[2])) 1869 | 1870 | cdef cnp.ndarray[float, ndim=3] dist = np.zeros( (sx,sy,sz), dtype=np.float32, order='F' ) 1871 | 1872 | dtype = data.dtype 1873 | cdef size_t max_loc = data.size + 1 1874 | 1875 | if dtype in (np.int8, np.uint8, bool): 1876 | arr_memview8 = data.view(np.uint8) 1877 | euclidean_distance_field3d( 1878 | &arr_memview8[0,0,0], 1879 | sx, sy, sz, 1880 | wx, wy, wz, 1881 | src, free_space_radius, 1882 | &dist[0,0,0], 1883 | voxel_graph_ptr, 1884 | max_loc 1885 | ) 1886 | else: 1887 | raise TypeError("Type {} not currently supported.".format(dtype)) 1888 | 1889 | if max_loc == data.size + 1: 1890 | raise ValueError(f"Something went wrong during processing. max_loc: {max_loc}") 1891 | 1892 | return dist, max_loc 1893 | 1894 | def _execute_euclidean_distance_field_w_feature_map( 1895 | data, sources, anisotropy 1896 | ): 1897 | cdef uint8_t[:,:,:] arr_memview8 1898 | 1899 | cdef uint64_t sx = data.shape[0] 1900 | cdef uint64_t sy = data.shape[1] 1901 | cdef uint64_t sz = data.shape[2] 1902 | 1903 | cdef float wx = anisotropy[0] 1904 | cdef float wy = anisotropy[1] 1905 | cdef float wz = anisotropy[2] 1906 | 1907 | sources = np.unique(sources, axis=0) 1908 | 1909 | cdef vector[uint64_t] src 1910 | for source in sources: 1911 | src.push_back(source[0] + sx * (source[1] + sy * source[2])) 1912 | 1913 | cdef cnp.ndarray[float, ndim=3] dist = np.zeros( (sx,sy,sz), dtype=np.float32, order='F' ) 1914 | cdef cnp.ndarray[uint32_t, ndim=3] feature_map = np.zeros( (sx,sy,sz), dtype=np.uint32, order='F' ) 1915 | 1916 | dtype = data.dtype 1917 | cdef size_t max_loc = data.size + 1 1918 | 1919 | if dtype in (np.int8, np.uint8, bool): 1920 | arr_memview8 = data.view(np.uint8) 1921 | edf_with_feature_map[uint32_t]( 1922 | &arr_memview8[0,0,0], 1923 | sx, sy, sz, 1924 | wx, wy, wz, 1925 | src, 1926 | &dist[0,0,0], 1927 | &feature_map[0,0,0], 1928 | max_loc 1929 | ) 1930 | else: 1931 | raise TypeError(f"Type {dtype} not currently supported.") 1932 | 1933 | if max_loc == data.size + 1: 1934 | raise ValueError(f"Something went wrong during processing. max_loc: {max_loc}") 1935 | 1936 | return dist, feature_map, max_loc 1937 | 1938 | -------------------------------------------------------------------------------- /manylinux1.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM quay.io/pypa/manylinux1_x86_64 2 | MAINTAINER William Silversmith 3 | 4 | ADD . /dijkstra3d 5 | 6 | WORKDIR "/dijkstra3d" 7 | 8 | ENV CXX "g++" 9 | 10 | RUN rm -rf *.so build __pycache__ dist 11 | 12 | RUN /opt/python/cp36-cp36m/bin/pip3.6 install pip --upgrade 13 | RUN /opt/python/cp37-cp37m/bin/pip3.7 install pip --upgrade 14 | RUN /opt/python/cp38-cp38/bin/pip3.8 install pip --upgrade 15 | 16 | RUN /opt/python/cp36-cp36m/bin/pip3.6 install oldest-supported-numpy pytest 17 | RUN /opt/python/cp37-cp37m/bin/pip3.7 install oldest-supported-numpy pytest 18 | RUN /opt/python/cp38-cp38/bin/pip3.8 install oldest-supported-numpy pytest 19 | 20 | RUN /opt/python/cp36-cp36m/bin/python3.6 setup.py develop 21 | RUN /opt/python/cp37-cp37m/bin/python3.7 setup.py develop 22 | RUN /opt/python/cp38-cp38/bin/python3.8 setup.py develop 23 | 24 | RUN /opt/python/cp36-cp36m/bin/python3.6 -m pytest -v -x automated_test.py 25 | RUN /opt/python/cp37-cp37m/bin/python3.7 -m pytest -v -x automated_test.py 26 | RUN /opt/python/cp38-cp38/bin/python3.8 -m pytest -v -x automated_test.py 27 | 28 | RUN /opt/python/cp36-cp36m/bin/python3.6 setup.py bdist_wheel 29 | RUN /opt/python/cp37-cp37m/bin/python3.7 setup.py bdist_wheel 30 | RUN /opt/python/cp38-cp38/bin/python3.8 setup.py bdist_wheel 31 | 32 | RUN for whl in `ls dist/*.whl`; do auditwheel repair $whl; done 33 | -------------------------------------------------------------------------------- /manylinux2010.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM quay.io/pypa/manylinux2010_x86_64 2 | MAINTAINER William Silversmith 3 | 4 | ADD . /dijkstra3d 5 | 6 | WORKDIR "/dijkstra3d" 7 | 8 | ENV CXX "g++" 9 | 10 | RUN rm -rf *.so build __pycache__ dist 11 | 12 | RUN /opt/python/cp36-cp36m/bin/pip3.6 install pip --upgrade 13 | RUN /opt/python/cp37-cp37m/bin/pip3.7 install pip --upgrade 14 | RUN /opt/python/cp38-cp38/bin/pip3.8 install pip --upgrade 15 | 16 | RUN /opt/python/cp36-cp36m/bin/pip3.6 install oldest-supported-numpy pytest 17 | RUN /opt/python/cp37-cp37m/bin/pip3.7 install oldest-supported-numpy pytest 18 | RUN /opt/python/cp38-cp38/bin/pip3.8 install oldest-supported-numpy pytest 19 | 20 | RUN /opt/python/cp36-cp36m/bin/python3.6 setup.py develop 21 | RUN /opt/python/cp37-cp37m/bin/python3.7 setup.py develop 22 | RUN /opt/python/cp38-cp38/bin/python3.8 setup.py develop 23 | 24 | RUN /opt/python/cp36-cp36m/bin/python3.6 -m pytest -v -x automated_test.py 25 | RUN /opt/python/cp37-cp37m/bin/python3.7 -m pytest -v -x automated_test.py 26 | RUN /opt/python/cp38-cp38/bin/python3.8 -m pytest -v -x automated_test.py 27 | 28 | RUN /opt/python/cp36-cp36m/bin/python3.6 setup.py bdist_wheel 29 | RUN /opt/python/cp37-cp37m/bin/python3.7 setup.py bdist_wheel 30 | RUN /opt/python/cp38-cp38/bin/python3.8 setup.py bdist_wheel 31 | 32 | RUN for whl in `ls dist/*.whl`; do auditwheel repair $whl --plat manylinux2010_x86_64; done 33 | -------------------------------------------------------------------------------- /manylinux2014.Dockerfile: -------------------------------------------------------------------------------- 1 | FROM quay.io/pypa/manylinux2014_x86_64 2 | MAINTAINER William Silversmith 3 | 4 | ADD . /dijkstra3d 5 | 6 | WORKDIR "/dijkstra3d" 7 | 8 | ENV CXX "g++" 9 | 10 | RUN rm -rf *.so build __pycache__ dist 11 | 12 | RUN /opt/python/cp36-cp36m/bin/pip3.6 install pip --upgrade 13 | RUN /opt/python/cp37-cp37m/bin/pip3.7 install pip --upgrade 14 | RUN /opt/python/cp38-cp38/bin/pip3.8 install pip --upgrade 15 | RUN /opt/python/cp39-cp39/bin/pip3.9 install pip --upgrade 16 | 17 | RUN /opt/python/cp36-cp36m/bin/pip3.6 install oldest-supported-numpy pytest 18 | RUN /opt/python/cp37-cp37m/bin/pip3.7 install oldest-supported-numpy pytest 19 | RUN /opt/python/cp38-cp38/bin/pip3.8 install oldest-supported-numpy pytest 20 | RUN /opt/python/cp39-cp39/bin/pip3.9 install oldest-supported-numpy pytest 21 | 22 | RUN /opt/python/cp36-cp36m/bin/python3.6 setup.py develop 23 | RUN /opt/python/cp37-cp37m/bin/python3.7 setup.py develop 24 | RUN /opt/python/cp38-cp38/bin/python3.8 setup.py develop 25 | RUN /opt/python/cp39-cp39/bin/python3.9 setup.py develop 26 | 27 | RUN /opt/python/cp36-cp36m/bin/python3.6 -m pytest -v -x automated_test.py 28 | RUN /opt/python/cp37-cp37m/bin/python3.7 -m pytest -v -x automated_test.py 29 | RUN /opt/python/cp38-cp38/bin/python3.8 -m pytest -v -x automated_test.py 30 | RUN /opt/python/cp39-cp39/bin/python3.9 -m pytest -v -x automated_test.py 31 | 32 | RUN /opt/python/cp36-cp36m/bin/python3.6 setup.py bdist_wheel 33 | RUN /opt/python/cp37-cp37m/bin/python3.7 setup.py bdist_wheel 34 | RUN /opt/python/cp38-cp38/bin/python3.8 setup.py bdist_wheel 35 | RUN /opt/python/cp39-cp39/bin/python3.9 setup.py bdist_wheel 36 | 37 | RUN for whl in `ls dist/*.whl`; do auditwheel repair $whl --plat manylinux2014_x86_64; done 38 | -------------------------------------------------------------------------------- /multi-color-self-touch.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seung-lab/dijkstra3d/75c58d7238c8d660e4e7e2c7d0f82b8302f2d67c/multi-color-self-touch.png -------------------------------------------------------------------------------- /multimethod.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/seung-lab/dijkstra3d/75c58d7238c8d660e4e7e2c7d0f82b8302f2d67c/multimethod.png -------------------------------------------------------------------------------- /perf.py: -------------------------------------------------------------------------------- 1 | import dijkstra3d 2 | import numpy as np 3 | import time 4 | 5 | def edf(): 6 | print("Running edf.") 7 | N = 1 8 | sx, sy, sz = 256, 256, 256 9 | values = np.ones((sx,sy,sz), dtype=bool) 10 | for i in range(5): 11 | s = time.time() 12 | dijkstra3d.euclidean_distance_field(values, (100,100,100)) 13 | e = time.time() 14 | accum = e-s 15 | mvx = N * sx * sy * sz / accum / 1000000 16 | print(f"{mvx:.3f} MVx/sec ({accum:.3f} sec)") 17 | 18 | def bidiagonal_ones(): 19 | print("Running bidiagonal_ones.") 20 | N = 1 21 | sx, sy, sz = 512, 512, 512 22 | values = np.ones((sx,sy,sz), dtype=np.uint32) 23 | s = time.time() 24 | dijkstra3d.dijkstra(values, (0,0,0), (sx-1,sy-1,sz-1), bidirectional=True) 25 | e = time.time() 26 | accum = e-s 27 | mvx = N * sx * sy * sz / accum / 1000000 28 | print(f"{mvx:.3f} MVx/sec ({accum:.3f} sec)") 29 | 30 | 31 | def diagonal_ones(): 32 | print("Running diagonal_ones.") 33 | N = 1 34 | sx, sy, sz = 512, 512, 512 35 | values = np.ones((sx,sy,sz), dtype=np.uint32) 36 | s = time.time() 37 | dijkstra3d.dijkstra(values, (0,0,0), (sx-1,sy-1,sz-1), compass=False) 38 | e = time.time() 39 | accum = e-s 40 | mvx = N * sx * sy * sz / accum / 1000000 41 | print(f"{mvx:.3f} MVx/sec ({accum:.3f} sec)") 42 | 43 | def random_paths(): 44 | print("Running random_paths.") 45 | values = np.random.randint(1,255, size=(7,7,7)) 46 | values = np.asfortranarray(values) 47 | 48 | start = np.random.randint(0,7, size=(3,)) 49 | target = np.random.randint(0,7, size=(3,)) 50 | 51 | N = 1 52 | sx, sy, sz = 500, 500, 500 53 | for n in range(1, 100, 1): 54 | accum = 0 55 | for i in range(N): 56 | values = np.random.randint(1,n+1, size=(sx,sy,sz)) 57 | values = np.asfortranarray(values) 58 | # values = np.ones((sx,sy,sz)) / 1000 59 | start = np.random.randint(0,min(sx,sy,sz), size=(3,)) 60 | target = np.random.randint(0,min(sx,sy,sz), size=(3,)) 61 | 62 | s = time.time() 63 | path_orig = dijkstra3d.dijkstra(values, start, target, bidirectional=True) 64 | accum += (time.time() - s) 65 | 66 | mvx = N * sx * sy * sz / accum / 1000000 67 | print(f"{n} {mvx:.3f} MVx/sec ({accum:.3f} sec)") 68 | 69 | # edf() 70 | bidiagonal_ones() 71 | random_paths() 72 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=42", 4 | "wheel", 5 | "numpy", 6 | "cython", 7 | ] 8 | 9 | build-backend = "setuptools.build_meta" 10 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | numpy -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | connected-components-3d 2 | cython 3 | pillow 4 | pytest 5 | tox 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import os 2 | import setuptools 3 | import sys 4 | 5 | class NumpyImport: 6 | def __repr__(self): 7 | import numpy as np 8 | 9 | return np.get_include() 10 | 11 | __fspath__ = __repr__ 12 | 13 | def read(fname): 14 | with open(os.path.join(os.path.dirname(__file__), fname), 'rt') as f: 15 | return f.read() 16 | 17 | extra_compile_args = [ 18 | '-std=c++11', '-O3', '-ffast-math', 19 | ] 20 | 21 | if sys.platform == 'darwin': 22 | extra_compile_args += [ '-stdlib=libc++', '-mmacosx-version-min=10.9' ] 23 | 24 | setuptools.setup( 25 | name="dijkstra3d", 26 | version="1.15.1", 27 | python_requires=">=3.8,<4.0", 28 | setup_requires=['numpy','cython'], 29 | ext_modules=[ 30 | setuptools.Extension( 31 | 'dijkstra3d', 32 | sources=[ 'dijkstra3d.pyx' ], 33 | language='c++', 34 | include_dirs=[ str(NumpyImport()) ], 35 | extra_compile_args=extra_compile_args, 36 | ) 37 | ], 38 | url="https://github.com/seung-lab/dijkstra3d/", 39 | author="William Silversmith", 40 | author_email="ws9@princeton.edu", 41 | packages=setuptools.find_packages(), 42 | package_data={ 43 | 'dijkstra3d': [ 44 | 'LICENSE', 45 | ], 46 | }, 47 | description="Implementation of Dijkstra's Shortest Path algorithm on 3D images.", 48 | long_description=read('README.md'), 49 | long_description_content_type="text/markdown", 50 | license = "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 51 | classifiers=[ 52 | "Intended Audience :: Developers", 53 | "Development Status :: 5 - Production/Stable", 54 | "License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)", 55 | "Programming Language :: Python", 56 | "Programming Language :: Python :: 3", 57 | "Programming Language :: Python :: 3.8", 58 | "Programming Language :: Python :: 3.9", 59 | "Programming Language :: Python :: 3.10", 60 | "Programming Language :: Python :: 3.11", 61 | "Programming Language :: Python :: 3.12", 62 | "Topic :: Scientific/Engineering", 63 | "Intended Audience :: Science/Research", 64 | "Operating System :: POSIX", 65 | "Operating System :: MacOS", 66 | "Operating System :: Microsoft :: Windows :: Windows 10", 67 | ] 68 | ) 69 | 70 | 71 | 72 | 73 | 74 | -------------------------------------------------------------------------------- /test.cpp: -------------------------------------------------------------------------------- 1 | #include "dijkstra3d.hpp" 2 | #include 3 | #include 4 | #include 5 | 6 | int main () { 7 | const int dim = 256; 8 | const int voxels = dim * dim * dim; 9 | uint32_t* labels = new uint32_t[voxels]; 10 | for (int i = 0; i < voxels; i++) { 11 | labels[i] = 1; 12 | } 13 | 14 | std::vector x = dijkstra::dijkstra3d(labels, dim, dim, dim, 0, voxels - 1); 15 | 16 | printf("\n%d\n", x[0]); 17 | 18 | return 1; 19 | } 20 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py38,py39,py310,py311,py312 3 | 4 | [testenv] 5 | platform = darwin 6 | deps = 7 | oldest-supported-numpy 8 | -rrequirements_dev.txt 9 | 10 | commands = 11 | pytest -v -x automated_test.py 12 | python setup.py bdist_wheel --------------------------------------------------------------------------------