diff --git a/.github/workflows/test_and_deploy.yml b/.github/workflows/test_and_deploy.yml new file mode 100644 index 0000000..0480091 --- /dev/null +++ b/.github/workflows/test_and_deploy.yml @@ -0,0 +1,90 @@ +# This workflows will upload a Python Package using Twine when a release is created +# For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries + +name: tests + +on: + push: + branches: + - main + - npe2 + tags: + - "v*" # Push events to matching v*, i.e. v1.0, v20.15.10 + pull_request: + branches: + - main + - npe2 + workflow_dispatch: + +jobs: + test: + name: ${{ matrix.platform }} py${{ matrix.python-version }} + runs-on: ${{ matrix.platform }} + strategy: + matrix: + platform: [ubuntu-latest, windows-latest, macos-latest] + python-version: ['3.8', '3.9', '3.10'] + + steps: + - uses: actions/checkout@v3 + + - name: Set up Python ${{ matrix.python-version }} + uses: actions/setup-python@v4 + with: + python-version: ${{ matrix.python-version }} + + # these libraries enable testing on Qt on linux + - uses: tlambert03/setup-qt-libs@v1 + + # strategy borrowed from vispy for installing opengl libs on windows + - name: Install Windows OpenGL + if: runner.os == 'Windows' + run: | + git clone --depth 1 https://github.com/pyvista/gl-ci-helpers.git + powershell gl-ci-helpers/appveyor/install_opengl.ps1 + + # note: if you need dependencies from conda, considering using + # setup-miniconda: https://github.com/conda-incubator/setup-miniconda + # and + # tox-conda: https://github.com/tox-dev/tox-conda + - name: Install dependencies + run: | + python -m pip install --upgrade pip + python -m pip install setuptools tox tox-gh-actions + + # this runs the platform-specific tests declared in tox.ini + - name: Test with tox + uses: aganders3/headless-gui@v1 + with: + run: python -m tox + env: + PLATFORM: ${{ matrix.platform }} + + - name: Coverage + uses: codecov/codecov-action@v3 + + deploy: + # this will run when you have tagged a commit, starting with "v*" + # and requires that you have put your twine API key in your + # github secrets (see readme for details) + needs: [test] + runs-on: ubuntu-latest + if: contains(github.ref, 'tags') + steps: + - uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.x" + - name: Install dependencies + run: | + python -m pip install --upgrade pip + pip install -U setuptools setuptools_scm wheel twine build + - name: Build and publish + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.TWINE_API_KEY }} + run: | + git tag + python -m build . + twine upload dist/* diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..73d56d3 --- /dev/null +++ b/.gitignore @@ -0,0 +1,84 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +env/ +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +*.egg-info/ +.installed.cfg +*.egg + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*,cover +.hypothesis/ +.napari_cache + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py + +# Flask instance folder +instance/ + +# Sphinx documentation +docs/_build/ + +# MkDocs documentation +/site/ + +# PyBuilder +target/ + +# Pycharm and VSCode +.idea/ +venv/ +.vscode/ + +# IPython Notebook +.ipynb_checkpoints + +# pyenv +.python-version + +# OS +.DS_Store + +# written by setuptools_scm +**/_version.py diff --git a/.napari-hub/DESCRIPTION.md b/.napari-hub/DESCRIPTION.md new file mode 100644 index 0000000..7ecdd97 --- /dev/null +++ b/.napari-hub/DESCRIPTION.md @@ -0,0 +1,9 @@ + + +The developer has not yet provided a napari-hub specific description. diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..ce6cc96 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,27 @@ +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.2.0 + hooks: + - id: check-docstring-first + - id: end-of-file-fixer + - id: trailing-whitespace + exclude: ^\.napari-hub/.* + - id: check-yaml # checks for correct yaml syntax for github actions ex. + - repo: https://github.com/charliermarsh/ruff-pre-commit + rev: v0.0.256 + hooks: + - id: ruff + - repo: https://github.com/psf/black + rev: 22.3.0 + hooks: + - id: black + - repo: https://github.com/tlambert03/napari-plugin-checks + rev: v0.3.0 + hooks: + - id: napari-plugin-checks + # https://mypy.readthedocs.io/en/stable/introduction.html + # you may wish to add this as well! + # - repo: https://github.com/pre-commit/mirrors-mypy + # rev: v0.910-1 + # hooks: + # - id: mypy diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..cebd794 --- /dev/null +++ b/LICENSE @@ -0,0 +1,22 @@ + +The MIT License (MIT) + +Copyright (c) 2024 Martin Schorb + +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/MANIFEST.in b/MANIFEST.in new file mode 100644 index 0000000..f3155af --- /dev/null +++ b/MANIFEST.in @@ -0,0 +1,5 @@ +include LICENSE +include README.md + +recursive-exclude * __pycache__ +recursive-exclude * *.py[co] diff --git a/README.md b/README.md new file mode 100644 index 0000000..0a9c3f2 --- /dev/null +++ b/README.md @@ -0,0 +1,61 @@ +# mobie-napari-bridge + +[![License MIT](https://img.shields.io/pypi/l/mobie-napari-bridge.svg?color=green)](https://github.com/githubuser/mobie-napari-bridge/raw/main/LICENSE) +[![PyPI](https://img.shields.io/pypi/v/mobie-napari-bridge.svg?color=green)](https://pypi.org/project/mobie-napari-bridge) +[![Python Version](https://img.shields.io/pypi/pyversions/mobie-napari-bridge.svg?color=green)](https://python.org) +[![tests](https://github.com/githubuser/mobie-napari-bridge/workflows/tests/badge.svg)](https://github.com/githubuser/mobie-napari-bridge/actions) +[![codecov](https://codecov.io/gh/githubuser/mobie-napari-bridge/branch/main/graph/badge.svg)](https://codecov.io/gh/githubuser/mobie-napari-bridge) +[![napari hub](https://img.shields.io/endpoint?url=https://api.napari-hub.org/shields/mobie-napari-bridge)](https://napari-hub.org/plugins/mobie-napari-bridge) + +A plugin to interact with MoBIE projects + +---------------------------------- + +This [napari] plugin was generated with [Cookiecutter] using [@napari]'s [cookiecutter-napari-plugin] template. + + + +## Installation + +You can install `mobie-napari-bridge` via [pip]: + + pip install mobie-napari-bridge + + + + +## Contributing + +Contributions are very welcome. Tests can be run with [tox], please ensure +the coverage at least stays the same before you submit a pull request. + +## License + +Distributed under the terms of the [MIT] license, +"mobie-napari-bridge" is free and open source software + +## Issues + +If you encounter any problems, please [file an issue] along with a detailed description. + +[napari]: https://github.com/napari/napari +[Cookiecutter]: https://github.com/audreyr/cookiecutter +[@napari]: https://github.com/napari +[MIT]: http://opensource.org/licenses/MIT +[BSD-3]: http://opensource.org/licenses/BSD-3-Clause +[GNU GPL v3.0]: http://www.gnu.org/licenses/gpl-3.0.txt +[GNU LGPL v3.0]: http://www.gnu.org/licenses/lgpl-3.0.txt +[Apache Software License 2.0]: http://www.apache.org/licenses/LICENSE-2.0 +[Mozilla Public License 2.0]: https://www.mozilla.org/media/MPL/2.0/index.txt +[cookiecutter-napari-plugin]: https://github.com/napari/cookiecutter-napari-plugin + +[napari]: https://github.com/napari/napari +[tox]: https://tox.readthedocs.io/en/latest/ +[pip]: https://pypi.org/project/pip/ +[PyPI]: https://pypi.org/ diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..422dc2d --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,56 @@ +[build-system] +requires = ["setuptools>=42.0.0", "wheel"] +build-backend = "setuptools.build_meta" + + + +[tool.black] +line-length = 79 +target-version = ['py38', 'py39', 'py310'] + + +[tool.ruff] +line-length = 79 +select = [ + "E", "F", "W", #flake8 + "UP", # pyupgrade + "I", # isort + "BLE", # flake8-blind-exception + "B", # flake8-bugbear + "A", # flake8-builtins + "C4", # flake8-comprehensions + "ISC", # flake8-implicit-str-concat + "G", # flake8-logging-format + "PIE", # flake8-pie + "SIM", # flake8-simplify +] +ignore = [ + "E501", # line too long. let black handle this + "UP006", "UP007", # type annotation. As using magicgui require runtime type annotation then we disable this. + "SIM117", # flake8-simplify - some of merged with statements are not looking great with black, reanble after drop python 3.9 +] + +exclude = [ + ".bzr", + ".direnv", + ".eggs", + ".git", + ".mypy_cache", + ".pants.d", + ".ruff_cache", + ".svn", + ".tox", + ".venv", + "__pypackages__", + "_build", + "buck-out", + "build", + "dist", + "node_modules", + "venv", + "*vendored*", + "*_vendor*", +] + +target-version = "py38" +fix = true diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..ce5e9d7 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,60 @@ +[metadata] +name = mobie-napari-bridge +version = attr: mobie_napari_bridge.__version__ +description = A plugin to interact with MoBIE projects +long_description = file: README.md +long_description_content_type = text/markdown + +author = Martin Schorb +author_email = schorb@embl.de +license = MIT +license_files = LICENSE +classifiers = + Development Status :: 2 - Pre-Alpha + Framework :: napari + Intended Audience :: Developers + License :: OSI Approved :: MIT License + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3 :: Only + Programming Language :: Python :: 3.8 + Programming Language :: Python :: 3.9 + Programming Language :: Python :: 3.10 + Topic :: Scientific/Engineering :: Image Processing + + +[options] +packages = find: +install_requires = + numpy + magicgui + qtpy + scikit-image + +python_requires = >=3.8 +include_package_data = True +package_dir = + =src + +# add your package requirements here + +[options.packages.find] +where = src + +[options.entry_points] +napari.manifest = + mobie-napari-bridge = mobie_napari_bridge:napari.yaml + +[options.extras_require] +testing = + tox + pytest # https://docs.pytest.org/en/latest/contents.html + pytest-cov # https://pytest-cov.readthedocs.io/en/latest/ + pytest-qt # https://pytest-qt.readthedocs.io/en/latest/ + napari + pyqt5 + + +[options.package_data] +* = *.yaml diff --git a/src/mobie_napari_bridge/__init__.py b/src/mobie_napari_bridge/__init__.py new file mode 100644 index 0000000..f7e5404 --- /dev/null +++ b/src/mobie_napari_bridge/__init__.py @@ -0,0 +1,17 @@ +__version__ = "0.0.1" + +from ._reader import napari_get_reader +from ._sample_data import make_sample_data +from ._widget import ExampleQWidget, ImageThreshold, threshold_autogenerate_widget, threshold_magic_widget +from ._writer import write_multiple, write_single_image + +__all__ = ( + "napari_get_reader", + "write_single_image", + "write_multiple", + "make_sample_data", + "ExampleQWidget", + "ImageThreshold", + "threshold_autogenerate_widget", + "threshold_magic_widget", +) diff --git a/src/mobie_napari_bridge/_reader.py b/src/mobie_napari_bridge/_reader.py new file mode 100644 index 0000000..8d93ff9 --- /dev/null +++ b/src/mobie_napari_bridge/_reader.py @@ -0,0 +1,72 @@ +""" +This module is an example of a barebones numpy reader plugin for napari. + +It implements the Reader specification, but your plugin may choose to +implement multiple readers or even other plugin contributions. see: +https://napari.org/stable/plugins/guides.html?#readers +""" +import numpy as np + + +def napari_get_reader(path): + """A basic implementation of a Reader contribution. + + Parameters + ---------- + path : str or list of str + Path to file, or list of paths. + + Returns + ------- + function or None + If the path is a recognized format, return a function that accepts the + same path or list of paths, and returns a list of layer data tuples. + """ + if isinstance(path, list): + # reader plugins may be handed single path, or a list of paths. + # if it is a list, it is assumed to be an image stack... + # so we are only going to look at the first file. + path = path[0] + + # if we know we cannot read the file, we immediately return None. + if not path.endswith(".npy"): + return None + + # otherwise we return the *function* that can read ``path``. + return reader_function + + +def reader_function(path): + """Take a path or list of paths and return a list of LayerData tuples. + + Readers are expected to return data as a list of tuples, where each tuple + is (data, [add_kwargs, [layer_type]]), "add_kwargs" and "layer_type" are + both optional. + + Parameters + ---------- + path : str or list of str + Path to file, or list of paths. + + Returns + ------- + layer_data : list of tuples + A list of LayerData tuples where each tuple in the list contains + (data, metadata, layer_type), where data is a numpy array, metadata is + a dict of keyword arguments for the corresponding viewer.add_* method + in napari, and layer_type is a lower-case string naming the type of + layer. Both "meta", and "layer_type" are optional. napari will + default to layer_type=="image" if not provided + """ + # handle both a string and a list of strings + paths = [path] if isinstance(path, str) else path + # load all files into array + arrays = [np.load(_path) for _path in paths] + # stack arrays into single array + data = np.squeeze(np.stack(arrays)) + + # optional kwargs for the corresponding viewer.add_* method + add_kwargs = {} + + layer_type = "image" # optional, default is "image" + return [(data, add_kwargs, layer_type)] diff --git a/src/mobie_napari_bridge/_sample_data.py b/src/mobie_napari_bridge/_sample_data.py new file mode 100644 index 0000000..453db51 --- /dev/null +++ b/src/mobie_napari_bridge/_sample_data.py @@ -0,0 +1,21 @@ +""" +This module is an example of a barebones sample data provider for napari. + +It implements the "sample data" specification. +see: https://napari.org/stable/plugins/guides.html?#sample-data + +Replace code below according to your needs. +""" +from __future__ import annotations + +import numpy + + +def make_sample_data(): + """Generates an image""" + # Return list of tuples + # [(data1, add_image_kwargs1), (data2, add_image_kwargs2)] + # Check the documentation for more information about the + # add_image_kwargs + # https://napari.org/stable/api/napari.Viewer.html#napari.Viewer.add_image + return [(numpy.random.rand(512, 512), {})] diff --git a/src/mobie_napari_bridge/_tests/__init__.py b/src/mobie_napari_bridge/_tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/mobie_napari_bridge/_tests/test_reader.py b/src/mobie_napari_bridge/_tests/test_reader.py new file mode 100644 index 0000000..4e4d535 --- /dev/null +++ b/src/mobie_napari_bridge/_tests/test_reader.py @@ -0,0 +1,31 @@ +import numpy as np + +from mobie_napari_bridge import napari_get_reader + + +# tmp_path is a pytest fixture +def test_reader(tmp_path): + """An example of how you might test your plugin.""" + + # write some fake data using your supported file format + my_test_file = str(tmp_path / "myfile.npy") + original_data = np.random.rand(20, 20) + np.save(my_test_file, original_data) + + # try to read it back in + reader = napari_get_reader(my_test_file) + assert callable(reader) + + # make sure we're delivering the right format + layer_data_list = reader(my_test_file) + assert isinstance(layer_data_list, list) and len(layer_data_list) > 0 + layer_data_tuple = layer_data_list[0] + assert isinstance(layer_data_tuple, tuple) and len(layer_data_tuple) > 0 + + # make sure it's the same as it started + np.testing.assert_allclose(original_data, layer_data_tuple[0]) + + +def test_get_reader_pass(): + reader = napari_get_reader("fake.file") + assert reader is None diff --git a/src/mobie_napari_bridge/_tests/test_sample_data.py b/src/mobie_napari_bridge/_tests/test_sample_data.py new file mode 100644 index 0000000..c78c69d --- /dev/null +++ b/src/mobie_napari_bridge/_tests/test_sample_data.py @@ -0,0 +1,7 @@ +# from mobie_napari_bridge import make_sample_data + +# add your tests here... + + +def test_something(): + pass diff --git a/src/mobie_napari_bridge/_tests/test_widget.py b/src/mobie_napari_bridge/_tests/test_widget.py new file mode 100644 index 0000000..c6f7aa6 --- /dev/null +++ b/src/mobie_napari_bridge/_tests/test_widget.py @@ -0,0 +1,66 @@ +import numpy as np + +from mobie_napari_bridge._widget import ( + ExampleQWidget, + ImageThreshold, + threshold_autogenerate_widget, + threshold_magic_widget, +) + + +def test_threshold_autogenerate_widget(): + # because our "widget" is a pure function, we can call it and + # test it independently of napari + im_data = np.random.random((100, 100)) + thresholded = threshold_autogenerate_widget(im_data, 0.5) + assert thresholded.shape == im_data.shape + # etc. + + +# make_napari_viewer is a pytest fixture that returns a napari viewer object +# you don't need to import it, as long as napari is installed +# in your testing environment +def test_threshold_magic_widget(make_napari_viewer): + viewer = make_napari_viewer() + layer = viewer.add_image(np.random.random((100, 100))) + + # our widget will be a MagicFactory or FunctionGui instance + my_widget = threshold_magic_widget() + + # if we "call" this object, it'll execute our function + thresholded = my_widget(viewer.layers[0], 0.5) + assert thresholded.shape == layer.data.shape + # etc. + + +def test_image_threshold_widget(make_napari_viewer): + viewer = make_napari_viewer() + layer = viewer.add_image(np.random.random((100, 100))) + my_widget = ImageThreshold(viewer) + + # because we saved our widgets as attributes of the container + # we can set their values without having to "interact" with the viewer + my_widget._image_layer_combo.value = layer + my_widget._threshold_slider.value = 0.5 + + # this allows us to run our functions directly and ensure + # correct results + my_widget._threshold_im() + assert len(viewer.layers) == 2 + + +# capsys is a pytest fixture that captures stdout and stderr output streams +def test_example_q_widget(make_napari_viewer, capsys): + # make viewer and add an image layer using our fixture + viewer = make_napari_viewer() + viewer.add_image(np.random.random((100, 100))) + + # create our widget, passing in the viewer + my_widget = ExampleQWidget(viewer) + + # call our widget method + my_widget._on_click() + + # read captured output and check that it's as we expected + captured = capsys.readouterr() + assert captured.out == "napari has 1 layers\n" diff --git a/src/mobie_napari_bridge/_tests/test_writer.py b/src/mobie_napari_bridge/_tests/test_writer.py new file mode 100644 index 0000000..d31f8b4 --- /dev/null +++ b/src/mobie_napari_bridge/_tests/test_writer.py @@ -0,0 +1,7 @@ +# from mobie_napari_bridge import write_single_image, write_multiple + +# add your tests here... + + +def test_something(): + pass diff --git a/src/mobie_napari_bridge/_widget.py b/src/mobie_napari_bridge/_widget.py new file mode 100644 index 0000000..ed8c358 --- /dev/null +++ b/src/mobie_napari_bridge/_widget.py @@ -0,0 +1,128 @@ +""" +This module contains four napari widgets declared in +different ways: + +- a pure Python function flagged with `autogenerate: true` + in the plugin manifest. Type annotations are used by + magicgui to generate widgets for each parameter. Best + suited for simple processing tasks - usually taking + in and/or returning a layer. +- a `magic_factory` decorated function. The `magic_factory` + decorator allows us to customize aspects of the resulting + GUI, including the widgets associated with each parameter. + Best used when you have a very simple processing task, + but want some control over the autogenerated widgets. If you + find yourself needing to define lots of nested functions to achieve + your functionality, maybe look at the `Container` widget! +- a `magicgui.widgets.Container` subclass. This provides lots + of flexibility and customization options while still supporting + `magicgui` widgets and convenience methods for creating widgets + from type annotations. If you want to customize your widgets and + connect callbacks, this is the best widget option for you. +- a `QWidget` subclass. This provides maximal flexibility but requires + full specification of widget layouts, callbacks, events, etc. + +References: +- Widget specification: https://napari.org/stable/plugins/guides.html?#widgets +- magicgui docs: https://pyapp-kit.github.io/magicgui/ + +Replace code below according to your needs. +""" +from typing import TYPE_CHECKING + +from magicgui import magic_factory +from magicgui.widgets import CheckBox, Container, create_widget +from qtpy.QtWidgets import QHBoxLayout, QPushButton, QWidget +from skimage.util import img_as_float + +if TYPE_CHECKING: + import napari + + +# Uses the `autogenerate: true` flag in the plugin manifest +# to indicate it should be wrapped as a magicgui to autogenerate +# a widget. +def threshold_autogenerate_widget( + img: "napari.types.ImageData", + threshold: "float", +) -> "napari.types.LabelsData": + return img_as_float(img) > threshold + + +# the magic_factory decorator lets us customize aspects of our widget +# we specify a widget type for the threshold parameter +# and use auto_call=True so the function is called whenever +# the value of a parameter changes +@magic_factory( + threshold={"widget_type": "FloatSlider", "max": 1}, auto_call=True +) +def threshold_magic_widget( + img_layer: "napari.layers.Image", threshold: "float" +) -> "napari.types.LabelsData": + return img_as_float(img_layer.data) > threshold + + +# if we want even more control over our widget, we can use +# magicgui `Container` +class ImageThreshold(Container): + def __init__(self, viewer: "napari.viewer.Viewer"): + super().__init__() + self._viewer = viewer + # use create_widget to generate widgets from type annotations + self._image_layer_combo = create_widget( + label="Image", annotation="napari.layers.Image" + ) + self._threshold_slider = create_widget( + label="Threshold", annotation=float, widget_type="FloatSlider" + ) + self._threshold_slider.min = 0 + self._threshold_slider.max = 1 + # use magicgui widgets directly + self._invert_checkbox = CheckBox(text="Keep pixels below threshold") + + # connect your own callbacks + self._threshold_slider.changed.connect(self._threshold_im) + self._invert_checkbox.changed.connect(self._threshold_im) + + # append into/extend the container with your widgets + self.extend( + [ + self._image_layer_combo, + self._threshold_slider, + self._invert_checkbox, + ] + ) + + def _threshold_im(self): + image_layer = self._image_layer_combo.value + if image_layer is None: + return + + image = img_as_float(image_layer.data) + name = image_layer.name + "_thresholded" + threshold = self._threshold_slider.value + if self._invert_checkbox.value: + thresholded = image < threshold + else: + thresholded = image > threshold + if name in self._viewer.layers: + self._viewer.layers[name].data = thresholded + else: + self._viewer.add_labels(thresholded, name=name) + + +class ExampleQWidget(QWidget): + # your QWidget.__init__ can optionally request the napari viewer instance + # use a type annotation of 'napari.viewer.Viewer' for any parameter + def __init__(self, viewer: "napari.viewer.Viewer"): + super().__init__() + self.viewer = viewer + + btn = QPushButton("Click me!") + btn.clicked.connect(self._on_click) + + self.setLayout(QHBoxLayout()) + self.layout().addWidget(btn) + + def _on_click(self): + print("napari has", len(self.viewer.layers), "layers") diff --git a/src/mobie_napari_bridge/_writer.py b/src/mobie_napari_bridge/_writer.py new file mode 100644 index 0000000..e67fcc9 --- /dev/null +++ b/src/mobie_napari_bridge/_writer.py @@ -0,0 +1,64 @@ +""" +This module is an example of a barebones writer plugin for napari. + +It implements the Writer specification. +see: https://napari.org/stable/plugins/guides.html?#writers + +Replace code below according to your needs. +""" +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, List, Sequence, Tuple, Union + +if TYPE_CHECKING: + DataType = Union[Any, Sequence[Any]] + FullLayerData = Tuple[DataType, dict, str] + + +def write_single_image(path: str, data: Any, meta: dict) -> List[str]: + """Writes a single image layer. + + Parameters + ---------- + path : str + A string path indicating where to save the image file. + data : The layer data + The `.data` attribute from the napari layer. + meta : dict + A dictionary containing all other attributes from the napari layer + (excluding the `.data` layer attribute). + + Returns + ------- + [path] : A list containing the string path to the saved file. + """ + + # implement your writer logic here ... + + # return path to any file(s) that were successfully written + return [path] + + +def write_multiple(path: str, data: List[FullLayerData]) -> List[str]: + """Writes multiple layers of different types. + + Parameters + ---------- + path : str + A string path indicating where to save the data file(s). + data : A list of layer tuples. + Tuples contain three elements: (data, meta, layer_type) + `data` is the layer data + `meta` is a dictionary containing all other metadata attributes + from the napari layer (excluding the `.data` layer attribute). + `layer_type` is a string, eg: "image", "labels", "surface", etc. + + Returns + ------- + [path] : A list containing (potentially multiple) string paths to the saved file(s). + """ + + # implement your writer logic here ... + + # return path to any file(s) that were successfully written + return [path] diff --git a/src/mobie_napari_bridge/napari.yaml b/src/mobie_napari_bridge/napari.yaml new file mode 100644 index 0000000..a61f654 --- /dev/null +++ b/src/mobie_napari_bridge/napari.yaml @@ -0,0 +1,57 @@ +name: mobie-napari-bridge +display_name: MoBIE Bridge +# use 'hidden' to remove plugin from napari hub search results +visibility: public +# see https://napari.org/stable/plugins/manifest.html for valid categories +categories: ["Annotation", "Segmentation", "Acquisition"] +contributions: + commands: + - id: mobie-napari-bridge.get_reader + python_name: mobie_napari_bridge._reader:napari_get_reader + title: Open data with MoBIE Bridge + - id: mobie-napari-bridge.write_multiple + python_name: mobie_napari_bridge._writer:write_multiple + title: Save multi-layer data with MoBIE Bridge + - id: mobie-napari-bridge.write_single_image + python_name: mobie_napari_bridge._writer:write_single_image + title: Save image data with MoBIE Bridge + - id: mobie-napari-bridge.make_sample_data + python_name: mobie_napari_bridge._sample_data:make_sample_data + title: Load sample data from MoBIE Bridge + - id: mobie-napari-bridge.make_container_widget + python_name: mobie_napari_bridge:ImageThreshold + title: Make threshold Container widget + - id: mobie-napari-bridge.make_magic_widget + python_name: mobie_napari_bridge:threshold_magic_widget + title: Make threshold magic widget + - id: mobie-napari-bridge.make_function_widget + python_name: mobie_napari_bridge:threshold_autogenerate_widget + title: Make threshold function widget + - id: mobie-napari-bridge.make_qwidget + python_name: mobie_napari_bridge:ExampleQWidget + title: Make example QWidget + readers: + - command: mobie-napari-bridge.get_reader + accepts_directories: false + filename_patterns: ['*.npy'] + writers: + - command: mobie-napari-bridge.write_multiple + layer_types: ['image*','labels*'] + filename_extensions: [] + - command: mobie-napari-bridge.write_single_image + layer_types: ['image'] + filename_extensions: ['.npy'] + sample_data: + - command: mobie-napari-bridge.make_sample_data + display_name: MoBIE Bridge + key: unique_id.1 + widgets: + - command: mobie-napari-bridge.make_container_widget + display_name: Container Threshold + - command: mobie-napari-bridge.make_magic_widget + display_name: Magic Threshold + - command: mobie-napari-bridge.make_function_widget + autogenerate: true + display_name: Autogenerate Threshold + - command: mobie-napari-bridge.make_qwidget + display_name: Example QWidget diff --git a/tox.ini b/tox.ini new file mode 100644 index 0000000..30aff9a --- /dev/null +++ b/tox.ini @@ -0,0 +1,32 @@ +# For more information about tox, see https://tox.readthedocs.io/en/latest/ +[tox] +envlist = py{38,39,310}-{linux,macos,windows} +isolated_build=true + +[gh-actions] +python = + 3.8: py38 + 3.9: py39 + 3.10: py310 + +[gh-actions:env] +PLATFORM = + ubuntu-latest: linux + macos-latest: macos + windows-latest: windows + +[testenv] +platform = + macos: darwin + linux: linux + windows: win32 +passenv = + CI + GITHUB_ACTIONS + DISPLAY + XAUTHORITY + NUMPY_EXPERIMENTAL_ARRAY_FUNCTION + PYVISTA_OFF_SCREEN +extras = + testing +commands = pytest -v --color=yes --cov=mobie_napari_bridge --cov-report=xml