From ecd3ebdbdc9bbf17b6aec68ee0a7473614b77b7f Mon Sep 17 00:00:00 2001 From: Wim Pomp Date: Sat, 14 Nov 2026 18:40:19 +0100 Subject: [PATCH] - implemented first bits --- .github/workflows/publish_crates.yml | 66 ++++++++ .github/workflows/publish_pypi.yml | 128 ++++++++++++++ .gitignore | 4 + Cargo.toml | 27 +++ LICENSE | 18 -- LICENSE-APACHE | 201 ++++++++++++++++++++++ LICENSE-MIT | 27 +++ README.md | 6 +- py/py.typed | 0 py/smoll/__init__.py | 63 +++++++ py/smoll/smoll_rs/__init__.pyi | 17 ++ py/smoll/smoll_rs/detection.pyi | 29 ++++ py/smoll/smoll_rs/filter.pyi | 46 ++++++ pyproject.toml | 47 ++++++ src/detection.rs | 238 +++++++++++++++++++++++++++ src/error.rs | 15 ++ src/filter.rs | 112 +++++++++++++ src/lib.rs | 5 + src/py.rs | 87 ++++++++++ src/py/detection.rs | 113 +++++++++++++ src/py/filter.rs | 75 +++++++++ 21 files changed, 1305 insertions(+), 19 deletions(-) create mode 100644 .github/workflows/publish_crates.yml create mode 100644 .github/workflows/publish_pypi.yml create mode 100644 Cargo.toml delete mode 100644 LICENSE create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT create mode 100644 py/py.typed create mode 100644 py/smoll/__init__.py create mode 100644 py/smoll/smoll_rs/__init__.pyi create mode 100644 py/smoll/smoll_rs/detection.pyi create mode 100644 py/smoll/smoll_rs/filter.pyi create mode 100644 pyproject.toml create mode 100644 src/detection.rs create mode 100644 src/error.rs create mode 100644 src/filter.rs create mode 100644 src/lib.rs create mode 100644 src/py.rs create mode 100644 src/py/detection.rs create mode 100644 src/py/filter.rs diff --git a/.github/workflows/publish_crates.yml b/.github/workflows/publish_crates.yml new file mode 100644 index 0000000..46d69ee --- /dev/null +++ b/.github/workflows/publish_crates.yml @@ -0,0 +1,66 @@ +name: Publish + +on: [workflow_dispatch] + +permissions: + contents: read + +jobs: + crates_io_publish: + name: Publish (crates.io) + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v6 + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: | + ~/.cargo + key: cache-ubuntu-cargo-publish + + - name: Install Rust + run: |- + export PATH="$HOME/.cargo/bin:$PATH" + if ! command -v rustc >/dev/null 2>&1; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y + else + rustup update + fi + cargo install cargo-release + shell: bash + + # allow-branch HEAD is because GitHub actions switches + # to the tag while building, which is a detached head + + # Publishing is currently messy, because: + # + # * `peace_rt_model_core` exports `NativeError` or `WebError` depending on the target. + # * `peace_rt_model_web` fails to build when publishing the workspace for a native target. + # * `peace_rt_model_web` still needs its dependencies to be published before it can be + # published. + # * `peace_rt_model_hack` needs `peace_rt_model_web` to be published before it can be + # published. + # + # We *could* pass through `--no-verify` so `cargo` doesn't build the crate before publishing, + # which is reasonable, since this job only runs after the Linux, Windows, and WASM builds + # have passed. + - name: "cargo release publish" + run: |- + export PATH="$HOME/.cargo/bin:$PATH" + cargo login ${{ secrets.CRATES_IO_API_TOKEN }} + cargo release \ + publish \ + --workspace \ + --all-features \ + --allow-branch "main" \ + --no-confirm \ + --no-verify \ + --execute + + - name: Store cache + uses: actions/cache/save@v4 + with: + path: | + ~/.cargo + key: cache-ubuntu-cargo-publish diff --git a/.github/workflows/publish_pypi.yml b/.github/workflows/publish_pypi.yml new file mode 100644 index 0000000..24460b6 --- /dev/null +++ b/.github/workflows/publish_pypi.yml @@ -0,0 +1,128 @@ +name: CI + +on: [workflow_dispatch] + +permissions: + contents: read + +jobs: + pypi_publish: + name: Publish (pypi.org) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v6 + - uses: actions/setup-python@v5 + with: + python-version: 3.x + + - name: Restore cache + uses: actions/cache/restore@v4 + with: + path: | + ~/.cache/pip + ~/.cache/pip-wheel + ~/.cache/sccache + ~/.cache/cargo-xwin + ~/.cargo + ~/.osxcross + key: cache-ubuntu-maturin-cross-compile + + - name: Install llvm + run: | + if ! command -v llvm-dlltool >/dev/null 2>&1; then + sudo apt update + sudo apt install -y llvm + fi + shell: bash + + - name: Install clang + run: | + if ! command -v clang >/dev/null 2>&1; then + sudo apt update + sudo apt install -y clang + fi + shell: bash + + - name: Install Rust + run: | + export PATH="$HOME/.cargo/bin:$PATH" + if ! command -v rustc >/dev/null 2>&1; then + curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y + else + rustup update + fi + rustup default stable + shell: bash + + - name: Install sccache and maturin + run: | + export PATH="$HOME/.cargo/bin:$PATH" + python -m pip install --upgrade pip + pip install maturin ziglang + if ! command -v sccache >/dev/null 2>&1; then + cargo install sccache || pip install sccache + fi + shell: bash + + - name: Install xwin + run: | + export PATH="$HOME/.cargo/bin:$PATH" + if ! command -v cargo-xwin >/dev/null 2>&1; then + cargo install cargo-xwin || pip install cargo-xwin + cargo xwin cache xwin + fi + shell: bash + + - name: Install osxcross + run: | + export PATH="$HOME/.osxcross/bin:$PATH" + if ! command -v osxcross >/dev/null 2>&1; then + wget ${{ secrets.OSXCROSS_LINK }} -O osxcross.tar.gz + tar -xzf osxcross.tar.gz -C ~/ + mv ~/osxcross ~/.osxcross + fi + + - name: Build wheels + run: | + export PATH="$HOME/.cargo/bin:$HOME/.osxcross/bin:$PATH" + rm -rf dist + maturin sdist --out dist + + rustup target add x86_64-unknown-linux-gnu + maturin build --release --out dist --target x86_64-unknown-linux-gnu --zig --auditwheel repair + rustup target add aarch64-unknown-linux-gnu + maturin build --release --out dist --target aarch64-unknown-linux-gnu --zig --auditwheel repair + rustup target add x86_64-unknown-linux-musl + maturin build --release --out dist --target x86_64-unknown-linux-musl --zig --auditwheel repair + rustup target add aarch64-unknown-linux-musl + maturin build --release --out dist --target aarch64-unknown-linux-musl --zig --auditwheel repair + + rustup target add x86_64-pc-windows-msvc + maturin build --release --out dist --target x86_64-pc-windows-msvc --auditwheel repair + rustup target add aarch64-pc-windows-msvc + maturin build --release --out dist --target aarch64-pc-windows-msvc --auditwheel repair + + rustup target add x86_64-apple-darwin + maturin build --release --out dist --target x86_64-apple-darwin --zig --auditwheel repair + rustup target add aarch64-apple-darwin + maturin build --release --out dist --target aarch64-apple-darwin --zig --auditwheel repair + + - name: Store cache + uses: actions/cache/save@v4 + with: + path: | + ~/.cache/pip + ~/.cache/pip-wheel + ~/.cache/sccache + ~/.cache/cargo-xwin + ~/.cargo + ~/.osxcross + key: cache-ubuntu-maturin-cross-compile + + - name: Publish to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + with: + skip-existing: true + password: ${{ secrets.PYPI_API_TOKEN }} + env: + GITHUB_WORKFLOW_REF: 1.10.1 diff --git a/.gitignore b/.gitignore index 5730393..2906a3b 100644 --- a/.gitignore +++ b/.gitignore @@ -192,3 +192,7 @@ cython_debug/ # PyPI configuration file .pypirc +.agentbridge +.idea +Cargo.lock + diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..61978cd --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "smoll" +version = "0.0.1" +edition = "2024" +rust-version = "1.88.0" +authors = ["Wim Pomp "] +license = "MIT OR Apache-2.0" +description = "Single MOLecule Localization." +repository = "https://git.pomppervova.nl/wim/smoll" +documentation = "https://docs.rs/smoll" +readme = "README.md" +keywords = ["science", "microscopy", "single-molecule", "detection", "localization"] +categories = ["computer-vision", "science"] + +[dependencies] +itertools = "0.15" +ndarray = { version = "0.17", features = ["rayon"] } +ndrustfft = "0.6" +num = "0.4" +numpy = { version = "0.30", optional = true } +pyo3 = { version = "0.30", features = ["abi3-py310", "anyhow", "generate-import-lib", "multiple-pymethods"], optional = true } +pyo3-stub-gen = { version = "0.23", optional = true } +strum = { version = "0.28", features = ["derive"] } +thiserror = "2" + +[features] +python = ["dep:pyo3", "dep:numpy", "dep:pyo3-stub-gen"] \ No newline at end of file diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d394586..0000000 --- a/LICENSE +++ /dev/null @@ -1,18 +0,0 @@ -MIT License - -Copyright (c) 2026 wim - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and -associated documentation files (the "Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the -following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial -portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT -LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO -EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER -IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..f8e5e5e --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..5a3aa7f --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,27 @@ +Copyright (c) 2015 - 2021 Ulrik Sverdrup "bluss", + Jim Turner, + and ndarray developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 03752bf..b9d302f 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,7 @@ # smoll -A rust/python library for Single MOLecule Localization \ No newline at end of file +A Rust/Python library for Single MOLecule Localization. + +Implemented so far: +- Difference of Gaussian filter +- Finding particles using a local maximum filter and thresholding \ No newline at end of file diff --git a/py/py.typed b/py/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/py/smoll/__init__.py b/py/smoll/__init__.py new file mode 100644 index 0000000..f1ff8a3 --- /dev/null +++ b/py/smoll/__init__.py @@ -0,0 +1,63 @@ +from __future__ import annotations + +import os +import sys +import warnings +from importlib.metadata import version +from pathlib import Path +from typing import TYPE_CHECKING + +import numpy as np +from numpy.typing import ArrayLike + +os.environ["RUST_BACKTRACE"] = "full" +os.environ["COLORBT_SHOW_HIDDEN"] = "1" + +from .smoll_rs import generate_stub +from .smoll_rs import detection, filter + +sys.modules["smoll.detection"] = detection +sys.modules["smoll.filter"] = filter + +try: + __version__ = version(Path(__file__).parent.name) +except Exception: # noqa + __version__ = "unknown" + +try: + with open(Path(__file__).parent.parent / ".git" / "HEAD") as g: + head = g.read().split(":")[1].strip() + with open(Path(__file__).parent.parent / ".git" / head) as h: + __git_commit_hash__ = h.read().rstrip("\n") +except Exception: # noqa + __git_commit_hash__ = "unknown" + + +__all__ = ["detection", "filter"] + + +def smoll_generate_stub(): + if len(sys.argv) > 1: + path = Path(sys.argv[1]).resolve() + else: + path = Path.cwd().resolve() + nd = path / "py" / "smoll" + if (nd / "__init__.pyi").exists(): + (nd / "__init__.pyi").rename(nd / "smoll.pyi") + try: + if (nd / "__init__.py").exists(): + generate_stub(str(path)) # noqa + else: + raise ModuleNotFoundError(str(nd / "__init__.py")) + rs = nd / "smoll_rs" + rs.mkdir(parents=True, exist_ok=True) + (nd / "__init__.pyi").rename(rs / "__init__.pyi") + for stub in nd.glob("**/__init__.pyi"): + if stub.parent != rs: + stub.rename((rs / stub.parent.name).with_suffix(".pyi")) + stub.parent.rmdir() + except Exception as e: + raise e + finally: + if (nd / "smoll.pyi").exists(): + (nd / "smoll.pyi").rename(nd / "__init__.pyi") diff --git a/py/smoll/smoll_rs/__init__.pyi b/py/smoll/smoll_rs/__init__.pyi new file mode 100644 index 0000000..9103870 --- /dev/null +++ b/py/smoll/smoll_rs/__init__.pyi @@ -0,0 +1,17 @@ +# This file is automatically generated by pyo3_stub_gen +# ruff: noqa: E501, F401, F403, F405 + +import builtins +from . import detection +from . import filter + +__all__ = [ + "detection", + "filter", + "generate_stub", +] + +def generate_stub(dest_path: builtins.str) -> None: + r""" + generates .pyi files + """ diff --git a/py/smoll/smoll_rs/detection.pyi b/py/smoll/smoll_rs/detection.pyi new file mode 100644 index 0000000..a0b6733 --- /dev/null +++ b/py/smoll/smoll_rs/detection.pyi @@ -0,0 +1,29 @@ +# This file is automatically generated by pyo3_stub_gen +# ruff: noqa: E501, F401, F403, F405 + +import builtins +import numpy +import numpy.typing +import typing + +__all__ = [ + "Detector", + "Filter", + "local_maxima", +] + +class Detector: + @staticmethod + def abs(threshold: builtins.float) -> Detector: ... + @staticmethod + def std(threshold: builtins.float) -> Detector: ... + def detect(self, array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.uint64]: ... + +class Filter: + @staticmethod + def dog(lower: typing.Sequence[builtins.float], upper: typing.Sequence[builtins.float]) -> Filter: ... + @staticmethod + def log() -> Filter: ... + def filter(self, array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]: ... + +def local_maxima(array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.uint64]: ... diff --git a/py/smoll/smoll_rs/filter.pyi b/py/smoll/smoll_rs/filter.pyi new file mode 100644 index 0000000..7b9b51c --- /dev/null +++ b/py/smoll/smoll_rs/filter.pyi @@ -0,0 +1,46 @@ +# This file is automatically generated by pyo3_stub_gen +# ruff: noqa: E501, F401, F403, F405 + +import builtins +import numpy +import numpy.typing +import typing + +__all__ = [ + "fft", + "fft_freq", + "fft_shift", + "gaussian", + "gaussian_kernel", + "gaussian_smooth", + "ifft", +] + +def fft(array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.complex128]: + r""" + Fourier transform + """ + +def fft_freq(size: builtins.int) -> numpy.typing.NDArray[numpy.float64]: ... +def fft_shift(array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.float64]: ... +def gaussian( + x: typing.Sequence[builtins.float], mu: builtins.float, sigma: builtins.float +) -> builtins.list[builtins.float]: ... +def gaussian_kernel( + shape: typing.Sequence[builtins.int], sigma: typing.Sequence[builtins.float] +) -> numpy.typing.NDArray[numpy.complex128]: + r""" + Gaussian kernel in frequency space + """ + +def gaussian_smooth( + array: numpy.typing.ArrayLike, sigma: typing.Sequence[builtins.float] +) -> numpy.typing.NDArray[numpy.float64]: + r""" + smooth an array using a Gaussian kernel + """ + +def ifft(array: numpy.typing.ArrayLike) -> numpy.typing.NDArray[numpy.complex128]: + r""" + inverse Fourier transform + """ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..49e2e0c --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,47 @@ +[build-system] +requires = ["maturin>=1.9.4,<2.0"] +build-backend = "maturin" + +[project] +name = "smoll" +dynamic = [ + "version", + "description", + "readme", + "license", + "license-files", + "authors", + "maintainers", + "keywords", + "urls", +] +requires-python = ">=3.10" +classifiers = [ + "License :: OSI Approved :: Apache Software License", + "License :: OSI Approved :: MIT License", + "Programming Language :: Rust", + "Programming Language :: Python", + "Programming Language :: Python :: 3", +] + +dependencies = [ + "numpy >= 1.16.0", +] + +[project.optional-dependencies] +test = ["pytest", "tifffile", "imagecodecs"] + +[project.scripts] +smoll_generate_stub = "smoll:smoll_generate_stub" + +[tool.maturin] +python-source = "py" +features = ["python"] +module-name = "smoll.smoll_rs" + +[tool.isort] +line_length = 119 + +[tool.ruff] +line-length = 119 +indent-width = 4 \ No newline at end of file diff --git a/src/detection.rs b/src/detection.rs new file mode 100644 index 0000000..6c848c3 --- /dev/null +++ b/src/detection.rs @@ -0,0 +1,238 @@ +use crate::error::Error; +use crate::filter::gaussian_smooth; +use itertools::Itertools; +use ndarray::{Array, Array2, AsArray, Axis, Dimension, IntoDimension, stack}; +use std::cmp::Ordering; + +pub trait Filter { + type Error; + + fn filter_array<'a, A, D>(&self, array: A) -> Result, Self::Error> + where + A: AsArray<'a, f64, D>, + D: Dimension; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct DoG { + lower: Vec, + upper: Vec, +} + +impl DoG { + pub fn new(lower: Vec, upper: Vec) -> Self { + Self { lower, upper } + } +} + +impl Filter for DoG { + type Error = Error; + + fn filter_array<'a, A, D>(&self, array: A) -> Result, Self::Error> + where + A: AsArray<'a, f64, D>, + D: Dimension, + { + let array = array.into(); + Ok(gaussian_smooth(&array, &self.lower)? - gaussian_smooth(array, &self.upper)?) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct LoG {} + +impl LoG { + pub fn new() -> Self { + Self {} + } +} + +impl Default for LoG { + fn default() -> Self { + Self::new() + } +} + +impl Filter for LoG { + type Error = Error; + + fn filter_array<'a, A, D>(&self, _array: A) -> Result, Self::Error> + where + A: AsArray<'a, f64, D>, + D: Dimension, + { + todo!() + } +} + +pub trait Detector { + type Error; + + fn detect<'a, A, D>(&self, array: A) -> Result, Self::Error> + where + A: AsArray<'a, f64, D>, + D: Dimension; +} + +#[derive(Debug, Clone, PartialEq)] +pub struct AbsoluteThreshold { + pub threshold: f64, +} + +impl Detector for AbsoluteThreshold { + type Error = Error; + + fn detect<'a, A, D>(&self, array: A) -> Result, Self::Error> + where + A: AsArray<'a, f64, D>, + D: Dimension, + { + let array = array.into().into_dyn(); + let candidates = local_maxima(array.view()); + + let a = candidates + .rows() + .into_iter() + .filter(|&x| { + if let Some(s) = x.as_slice() { + array[s] > self.threshold + } else { + let s = x.to_vec(); + array[s.as_slice()] > self.threshold + } + }) + .collect::>(); + + Ok(stack(Axis(0), &a)?) + } +} + +#[derive(Debug, Clone, PartialEq)] +pub struct StdThreshold { + pub threshold: f64, +} + +impl Detector for StdThreshold { + type Error = Error; + + fn detect<'a, A, D>(&self, array: A) -> Result, Self::Error> + where + A: AsArray<'a, f64, D>, + D: Dimension, + { + let array = array.into().into_dyn(); + let std = array.std(0.0) * self.threshold; + let candidates = local_maxima(array.view()); + + let a = candidates + .rows() + .into_iter() + .filter(|&x| { + if let Some(s) = x.as_slice() { + array[s] > std + } else { + let s = x.to_vec(); + array[s.as_slice()] > std + } + }) + .collect::>(); + + Ok(stack(Axis(0), &a)?) + } +} + +/// Find all indices of the strict local maxima of `frame`. +/// +/// A point is a strict local maximum if it is **strictly** greater than +/// every point in its direct neighborhood: the `3^dim - 1` points at +/// Chebyshev distance 1 (including diagonal neighbors), excluding itself. +/// Edge points have fewer in-bounds neighbors, and a point with no in-bounds +/// neighbors at all is vacuously a local maximum. +/// +/// Since the comparison is strict, plateaus (points equal to a neighbor) and +/// NaN values are never maxima. +/// +/// The result has shape (n_maxima, dim), holding one index per row, ordered by +/// the arrays logical (row-major) iteration order. +/// +/// # Examples +/// +/// ``` +/// use ndarray::Array; +/// use smoll::maxima::local_maxima; +/// +/// let frame = Array::from_shape_vec((2, 2), vec![1., 2., 3., 4.]).unwrap(); +/// let maxima = local_maxima(frame.view()); +/// assert_eq!(maxima, Array::from_shape_vec((1, 2), vec![1, 1]).unwrap()); +/// ``` +pub fn local_maxima<'a, A, D>(frame: A) -> Array2 +where + A: AsArray<'a, f64, D>, + D: Dimension, +{ + let frame = frame.into(); + let shape = frame.shape(); + let ndim = frame.ndim(); + + // All relative offsets of the direct neighborhood: one of `{-1, 0, 1}` + // per axis, with the zero offset excluded. + let offsets: Vec> = (0..ndim) + .map(|_| -1i8..=1) + .multi_cartesian_product() + .filter(|off| off.iter().any(|&d| d != 0)) + .collect(); + + // Coordinates of the maxima, stacked one row at a time. + let mut coords = Vec::new(); + for (position, ¢er) in frame.indexed_iter() { + let index = position.into_dimension(); + let coord = index.as_array_view(); + + let mut is_max = true; + for off in &offsets { + let mut neighbor = index.clone(); + let mut out_of_bounds = false; + for (axis, &d) in off.iter().enumerate() { + match d { + -1 => { + if coord[axis] == 0 { + out_of_bounds = true; + break; + } + neighbor[axis] -= 1; + } + 1 => { + if coord[axis] + 1 >= shape[axis] { + out_of_bounds = true; + break; + } + neighbor[axis] += 1; + } + _ => {} + } + } + if out_of_bounds { + continue; + } + // Must be strictly greater than this neighbor; `NaN` on either + // side of the comparison fails the test. The neighbor is + // guaranteed to be in bounds. + if let Some(Ordering::Less) = + center.partial_cmp(frame.get(neighbor).expect("neighbor out of bounds")) + { + is_max = false; + break; + } + } + if is_max { + coords.extend(coord.iter().copied()); + } + } + + let count = coords.len().checked_div(ndim).unwrap_or(frame.len()); + + // Guaranteed to fit: exactly `ndim` coordinates are pushed per maximum. + let maxima: Array2 = + Array2::::from_shape_vec((count, ndim), coords).expect("shape/length mismatch"); + maxima +} diff --git a/src/error.rs b/src/error.rs new file mode 100644 index 0000000..552a0d0 --- /dev/null +++ b/src/error.rs @@ -0,0 +1,15 @@ +use strum::IntoStaticStr; +use thiserror::Error; + +#[derive(Debug, Error, IntoStaticStr)] +pub enum Error { + #[error(transparent)] + ShapeError(#[from] ndarray::ShapeError), +} + +impl Error { + /// the name of the error variant as a static string + pub fn variant_name(&self) -> &'static str { + self.into() + } +} diff --git a/src/filter.rs b/src/filter.rs new file mode 100644 index 0000000..dfca1d3 --- /dev/null +++ b/src/filter.rs @@ -0,0 +1,112 @@ +//! Module containing gaussian smooth functions as well as helper functions to calculate ND fast +//! fourier transforms + +use crate::error::Error; +use itertools::Itertools; +use ndarray::{Array, Array1, ArrayD, AsArray, Axis, Dimension, RemoveAxis, concatenate, s}; +use ndrustfft::{FftHandler, Normalization, ndfft_par, ndifft_par}; +use num::Complex; +use num::traits::FloatConst; +use std::ops::MulAssign; + +/// Fourier transform +pub fn fft<'a, A, D>(array: A) -> Result, D>, Error> +where + A: AsArray<'a, f64, D>, + D: Dimension, +{ + let mut input = array.into().mapv(|i| Complex::new(i, 0.0)); + let shape = input.shape().to_vec(); + let mut tmp = ArrayD::zeros(shape.clone()).into_dimensionality()?; + for (i, s) in shape.iter().enumerate() { + let handler = FftHandler::new(*s).normalization(Normalization::None); + ndfft_par(&input.view(), &mut tmp.view_mut(), &handler, i); + std::mem::swap(&mut input, &mut tmp); + } + Ok(input) +} + +/// inverse Fourier transform +pub fn ifft<'a, A, D>(array: A) -> Result, D>, Error> +where + A: AsArray<'a, Complex, D>, + D: Dimension, +{ + let mut input = array.into().to_owned(); + let shape = input.shape().to_vec(); + let mut tmp = ArrayD::zeros(shape.clone()).into_dimensionality()?; + for (i, s) in shape.iter().enumerate() { + let handler = FftHandler::new(*s).normalization(Normalization::None); + ndifft_par(&input.view(), &mut tmp.view_mut(), &handler, i); + std::mem::swap(&mut input, &mut tmp); + } + Ok(input / Complex::from(shape.iter().product::() as f64)) +} + +pub fn fft_freq(size: usize) -> Array1 { + // let s = size as isize; + // let h = s / 2; + // (-h..h).map(|i| (i % s - s) as f64 / s as f64).collect() + + let val = 1.0 / size as f64; + let mut results = Array1::zeros(size); + let n = (size - 1) / 2 + 1; + let p1 = Array1::range(0.0, n as f64, 1.0); + results.slice_mut(s![..n]).assign(&p1); + let p2 = Array1::range(-((size / 2) as f64), 0.0, 1.0); + results.slice_mut(s![n..]).assign(&p2); + results * val +} + +pub fn fft_shift<'a, A, T, D>(x: A) -> Array +where + A: AsArray<'a, T, D>, + T: 'a + Clone, + D: Dimension + RemoveAxis, +{ + let mut x = x.into().to_owned(); + let shift = x.shape().iter().map(|i| i / 2).collect::>(); + for (i, s) in shift.iter().enumerate() { + let (a, b) = x.view().split_at(Axis(i), *s); + x = concatenate(Axis(i), &[b, a]).unwrap(); + } + x +} + +pub fn gaussian(x: &[f64], mu: f64, sigma: f64) -> Vec { + let a = 2.0 * sigma.powi(2); + let b = (a * f64::PI()).sqrt(); + x.iter() + .map(|i| (-(i - mu).powi(2) / a).exp() / b) + .collect() +} + +/// Gaussian kernel in frequency space +pub fn gaussian_kernel(shape: &[usize], sigma: &[f64]) -> Result, D>, Error> +where + D: Dimension, +{ + let mut g = Array::ones(shape).into_dimensionality()?; + for (i, (s, t)) in shape.iter().zip_eq(sigma.iter()).enumerate() { + let a = 0.5 / t.powi(2); + let f = (-(f64::PI() * fft_freq(*s)).powi(2) / a) + .exp() + .mapv(Complex::from); + for mut lane in g.lanes_mut(Axis(i)) { + lane.mul_assign(&f); + } + } + Ok(g) +} + +/// smooth an array using a Gaussian kernel +pub fn gaussian_smooth<'a, A, D>(array: A, sigma: &[f64]) -> Result, Error> +where + A: AsArray<'a, f64, D>, + D: Dimension, +{ + let array = array.into().to_owned(); + let shape = array.shape(); + let kernel = gaussian_kernel::(shape, sigma)?; + Ok(ifft((kernel * fft(array.view())?).view())?.mapv(|i| i.re)) +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..bacb23b --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,5 @@ +pub mod detection; +pub mod error; +pub mod filter; +#[cfg(feature = "python")] +mod py; diff --git a/src/py.rs b/src/py.rs new file mode 100644 index 0000000..4beff70 --- /dev/null +++ b/src/py.rs @@ -0,0 +1,87 @@ +mod detection; +mod filter; + +use crate::error::Error; +use pyo3::exceptions::PyRuntimeError; +use pyo3::prelude::*; +use pyo3_stub_gen::derive::gen_stub_pyfunction; +use pyo3_stub_gen::{StubGenConfig, StubInfo}; +use std::error::Error as StdError; +use std::path::PathBuf; + +fn format_error_chain(err: &Error) -> String { + let mut msg = format!("[{}] {err}", err.variant_name()); + let mut source = err.source(); + while let Some(s) = source { + msg.push_str(&format!("\n |-> {s}")); + source = s.source(); + } + msg +} + +impl From for PyErr { + #[track_caller] + fn from(err: Error) -> PyErr { + let location = std::panic::Location::caller(); + let msg = format!("{}: {}", location, format_error_chain(&err)); + PyRuntimeError::new_err(msg) + } +} + +/// generates .pyi files +#[gen_stub_pyfunction] +#[pyfunction] +pub fn generate_stub(dest_path: String) -> PyResult<()> { + Ok(StubInfo::from_project_root( + "smoll".to_string(), + PathBuf::from(dest_path).join("py"), + true, + StubGenConfig::default(), + )? + .generate()?) +} + +#[pymodule] +#[pyo3(name = "smoll_rs")] +mod smoll_rs { + use pyo3::prelude::*; + + #[pymodule_export] + use super::generate_stub; + + #[pymodule] + mod detection { + #[pymodule_export] + use super::super::detection::PyFilter; + + #[pymodule_export] + use super::super::detection::PyDetector; + + #[pymodule_export] + use super::super::detection::local_maxima; + } + + #[pymodule] + mod filter { + #[pymodule_export] + use super::super::filter::fft; + + #[pymodule_export] + use super::super::filter::ifft; + + #[pymodule_export] + use super::super::filter::fft_freq; + + #[pymodule_export] + use super::super::filter::fft_shift; + + #[pymodule_export] + use super::super::filter::gaussian; + + #[pymodule_export] + use super::super::filter::gaussian_kernel; + + #[pymodule_export] + use super::super::filter::gaussian_smooth; + } +} diff --git a/src/py/detection.rs b/src/py/detection.rs new file mode 100644 index 0000000..72b6276 --- /dev/null +++ b/src/py/detection.rs @@ -0,0 +1,113 @@ +use crate::detection; +use crate::detection::{AbsoluteThreshold, Detector, DoG, Filter, LoG, StdThreshold}; +use numpy::{AllowTypeChange, IntoPyArray, PyArray2, PyArrayDyn, PyArrayLikeDyn}; +use pyo3::prelude::*; +use pyo3_stub_gen::derive::*; + +#[derive(Debug, Clone, PartialEq)] +enum Filters { + DoG(DoG), + LoG(LoG), +} + +#[gen_stub_pyclass] +#[pyclass(subclass, from_py_object, name = "Filter", module = "smoll.detection")] +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct PyFilter { + inner: Filters, +} + +#[gen_stub_pymethods] +#[pymethods] +impl PyFilter { + #[staticmethod] + fn dog(lower: Vec, upper: Vec) -> Self { + Self { + inner: Filters::DoG(DoG::new(lower, upper)), + } + } + + #[staticmethod] + fn log() -> Self { + Self { + inner: Filters::LoG(LoG::new()), + } + } + + fn filter<'py>( + &self, + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyArrayLikeDyn, + ) -> PyResult>> { + let array = array.as_array(); + Ok(match self.inner { + Filters::DoG(ref dog) => dog.filter_array(array)?, + Filters::LoG(ref log) => log.filter_array(array)?, + } + .into_pyarray(py)) + } +} + +#[gen_stub_pyfunction(module = "smoll.detection")] +#[pyfunction] +pub(crate) fn local_maxima<'py>( + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyArrayLikeDyn, +) -> Bound<'py, PyArray2> { + detection::local_maxima(array.as_array()) + .mapv(|i| i as u64) + .into_pyarray(py) +} + +#[derive(Debug, Clone, PartialEq)] +enum Detectors { + Absolute(AbsoluteThreshold), + Std(StdThreshold), +} + +#[gen_stub_pyclass] +#[pyclass( + subclass, + from_py_object, + name = "Detector", + module = "smoll.detection" +)] +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct PyDetector { + inner: Detectors, +} + +#[gen_stub_pymethods] +#[pymethods] +impl PyDetector { + #[staticmethod] + fn abs(threshold: f64) -> Self { + Self { + inner: Detectors::Absolute(AbsoluteThreshold { threshold }), + } + } + + #[staticmethod] + fn std(threshold: f64) -> Self { + Self { + inner: Detectors::Std(StdThreshold { threshold }), + } + } + + fn detect<'py>( + &self, + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyArrayLikeDyn, + ) -> PyResult>> { + let array = array.as_array(); + Ok(match self.inner { + Detectors::Absolute(ref abs) => abs.detect(array)?, + Detectors::Std(ref std) => std.detect(array)?, + } + .mapv(|i| i as u64) + .into_pyarray(py)) + } +} diff --git a/src/py/filter.rs b/src/py/filter.rs new file mode 100644 index 0000000..adebdb9 --- /dev/null +++ b/src/py/filter.rs @@ -0,0 +1,75 @@ +use crate::filter; +use numpy::{ + AllowTypeChange, IntoPyArray, PyArray1, PyArrayDyn, PyArrayLikeDyn, PyArrayMethods, + PyReadonlyArrayDyn, +}; +use pyo3::PyResult; +use pyo3::prelude::*; +use pyo3_stub_gen::derive::*; + +/// Fourier transform +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn fft<'py>( + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyArrayLikeDyn, +) -> PyResult>>> { + Ok(filter::fft(array.as_array())?.into_pyarray(py)) +} + +/// inverse Fourier transform +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn ifft<'py>( + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyReadonlyArrayDyn<'py, num::Complex>, +) -> PyResult>>> { + Ok(filter::ifft(array.readonly().as_array())?.into_pyarray(py)) +} + +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn fft_freq<'py>(py: Python<'py>, size: usize) -> Bound<'py, PyArray1> { + filter::fft_freq(size).into_pyarray(py) +} + +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn fft_shift<'py>( + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyArrayLikeDyn, +) -> Bound<'py, PyArrayDyn> { + filter::fft_shift(array.as_array()).into_pyarray(py) +} + +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn gaussian(x: Vec, mu: f64, sigma: f64) -> Vec { + filter::gaussian(&x, mu, sigma) +} + +/// Gaussian kernel in frequency space +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn gaussian_kernel<'py>( + py: Python<'py>, + shape: Vec, + sigma: Vec, +) -> PyResult>>> { + Ok(filter::gaussian_kernel(&shape, &sigma)?.into_pyarray(py)) +} + +/// smooth an array using a Gaussian kernel +#[gen_stub_pyfunction(module = "smoll.filter")] +#[pyfunction] +pub(crate) fn gaussian_smooth<'py>( + py: Python<'py>, + #[gen_stub(override_type(type_repr="numpy.typing.ArrayLike", imports=("numpy.typing")))] + array: PyArrayLikeDyn, + sigma: Vec, +) -> PyResult>> { + Ok(filter::gaussian_smooth(array.as_array(), &sigma)?.into_pyarray(py)) +}