Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add io and cli #21

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/zarr_arr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
except ImportError:
raise ImportError("Please `pip install zarr aiohttp` to run this example")


# url = "https://uk1s3.embassy.ebi.ac.uk/idr/zarr/v0.4/idr0062A/6001240.zarr"
URL = "https://s3.embl.de/i2k-2020/ngff-example-data/v0.4/tczyx.ome.zarr"
zarr_arr = zarr.open(URL, mode="r")

Expand Down
9 changes: 9 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,21 @@ classifiers = [
]
dependencies = ["qtpy", "numpy", "superqt[cmap,iconify]"]

[project.scripts]
ndv = "ndv.cli:main"

# https://peps.python.org/pep-0621/#dependencies-optional-dependencies
[project.optional-dependencies]
pyqt = ["pyqt6"]
vispy = ["vispy", "pyopengl"]
pyside = ["pyside6"]
pygfx = ["pygfx"]
io = [
"aicsimageio[all]",
"bioformats_jar",
"readlif",
"aicspylibczi",
]
third_party_arrays = [
"aiohttp", # for zarr example
"jax[cpu]",
Expand Down
20 changes: 20 additions & 0 deletions src/ndv/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""command-line program."""

import argparse

Check warning on line 3 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L3

Added line #L3 was not covered by tests

from ndv.util import imshow

Check warning on line 5 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L5

Added line #L5 was not covered by tests


def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description="ndv: ndarray viewer")
parser.add_argument("path", type=str, help="The filename of the numpy file to view")
return parser.parse_args()

Check warning on line 11 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L8-L11

Added lines #L8 - L11 were not covered by tests


def main() -> None:

Check warning on line 14 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L14

Added line #L14 was not covered by tests
"""Run the command-line program."""
from ndv import io

Check warning on line 16 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L16

Added line #L16 was not covered by tests

args = _parse_args()

Check warning on line 18 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L18

Added line #L18 was not covered by tests

imshow(io.imread(args.path))

Check warning on line 20 in src/ndv/cli.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/cli.py#L20

Added line #L20 was not covered by tests
43 changes: 43 additions & 0 deletions src/ndv/io.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""All the io we can think of."""

from __future__ import annotations

Check warning on line 3 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L3

Added line #L3 was not covered by tests

from textwrap import indent, wrap
from typing import TYPE_CHECKING, Any

Check warning on line 6 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L5-L6

Added lines #L5 - L6 were not covered by tests

import numpy as np

Check warning on line 8 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L8

Added line #L8 was not covered by tests

if TYPE_CHECKING:
from pathlib import Path

import xarray as xr


def imread(path: str | Path) -> Any:

Check warning on line 16 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L16

Added line #L16 was not covered by tests
"""Just read the thing already."""

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

😂

path_str = str(path)
if path_str.endswith(".npy"):
return np.load(path_str)
errors = {}
try:
return _read_aicsimageio(path)
except Exception as e:
errors["aicsimageio"] = e

Check warning on line 25 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L18-L25

Added lines #L18 - L25 were not covered by tests

raise ValueError(_format_error_message(errors))

Check warning on line 27 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L27

Added line #L27 was not covered by tests


def _format_error_message(errors: dict[str, Exception]) -> str:
lines = ["Could not read file. Here are all the things we tried", ""]
for _key, value in errors.items():
lines.append(f"{_key}:")
wrapped = wrap(str(value), width=120)
indented = indent("\n".join(wrapped), " ")
lines.append(indented)
return "\n".join(lines)

Check warning on line 37 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L30-L37

Added lines #L30 - L37 were not covered by tests


def _read_aicsimageio(path: str | Path) -> xr.DataArray:
from aicsimageio import AICSImage

Check warning on line 41 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L40-L41

Added lines #L40 - L41 were not covered by tests

return AICSImage(str(path)).xarray_dask_data

Check warning on line 43 in src/ndv/io.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/io.py#L43

Added line #L43 was not covered by tests
27 changes: 23 additions & 4 deletions src/ndv/viewer/_data_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from __future__ import annotations

import json
import logging
import sys
from abc import abstractmethod
Expand Down Expand Up @@ -97,9 +98,10 @@
# be automatically detected (assuming they have been imported by this point)
for subclass in sorted(_recurse_subclasses(cls), key=lambda x: x.PRIORITY):
with suppress(Exception):
if subclass.supports(data):
logging.debug(f"Using {subclass.__name__} to wrap {type(data)}")
return subclass(data)
if not subclass.supports(data):
continue
logging.debug(f"Using {subclass.__name__} to wrap {type(data)}")
return subclass(data)
raise NotImplementedError(f"Don't know how to wrap type {type(data)}")

def __init__(self, data: ArrayT) -> None:
Expand Down Expand Up @@ -219,10 +221,27 @@
super().__init__(data)
import tensorstore as ts

spec = self.data.spec().to_json()
labels: Sequence[Hashable] | None = None
self._ts = ts
if (tform := spec.get("transform")) and ("input_labels" in tform):
labels = [str(x) for x in tform["input_labels"]]
elif (

Check warning on line 229 in src/ndv/viewer/_data_wrapper.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/viewer/_data_wrapper.py#L229

Added line #L229 was not covered by tests
str(spec.get("driver")).startswith("zarr")
and (zattrs := self.data.kvstore.read(".zattrs").result().value)
and isinstance((zattr_dict := json.loads(zattrs)), dict)
and "_ARRAY_DIMENSIONS" in zattr_dict
):
labels = zattr_dict["_ARRAY_DIMENSIONS"]

Check warning on line 235 in src/ndv/viewer/_data_wrapper.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/viewer/_data_wrapper.py#L235

Added line #L235 was not covered by tests

if isinstance(labels, Sequence) and len(labels) == len(self._data.domain):
self._labels: list[Hashable] = [str(x) for x in labels]
self._data = self.data[ts.d[:].label[self._labels]]
else:
self._labels = list(range(len(self._data.domain)))

Check warning on line 241 in src/ndv/viewer/_data_wrapper.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/viewer/_data_wrapper.py#L241

Added line #L241 was not covered by tests

def sizes(self) -> Mapping[Hashable, int]:
return {dim.label: dim.size for dim in self._data.domain}
return dict(zip(self._labels, self._data.domain.shape))

def isel(self, indexers: Indices) -> np.ndarray:
result = (
Expand Down
6 changes: 5 additions & 1 deletion src/ndv/viewer/_viewer.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import logging
from collections import defaultdict
from itertools import cycle
from typing import TYPE_CHECKING, Literal, cast
Expand Down Expand Up @@ -258,7 +259,6 @@
"""
# store the data
self._data_wrapper = DataWrapper.create(data)

# set channel axis
self._channel_axis = self._data_wrapper.guess_channel_axis()

Expand Down Expand Up @@ -458,6 +458,10 @@
if future.cancelled():
return

if exc := future.exception():
logging.error(f"Error getting data: {exc}")
return

Check warning on line 463 in src/ndv/viewer/_viewer.py

View check run for this annotation

Codecov / codecov/patch

src/ndv/viewer/_viewer.py#L462-L463

Added lines #L462 - L463 were not covered by tests

for idx, datum in future.result():
self._update_canvas_data(datum, idx)
self._canvas.refresh()
Expand Down