tiamat-python 0.1.11__tar.gz → 0.1.12__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/PKG-INFO +2 -2
  2. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/pyproject.toml +1 -1
  3. tiamat_python-0.1.12/tiamat/metadata/metadata.py +206 -0
  4. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/stack.py +24 -17
  5. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/zarr.py +192 -94
  6. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat_python.egg-info/PKG-INFO +2 -2
  7. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat_python.egg-info/requires.txt +3 -1
  8. tiamat_python-0.1.11/tiamat/metadata/metadata.py +0 -118
  9. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/LICENSE +0 -0
  10. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/README.md +0 -0
  11. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/README.rst +0 -0
  12. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/setup.cfg +0 -0
  13. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/setup.py +0 -0
  14. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tests/test_metadata.py +0 -0
  15. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tests/test_package.py +0 -0
  16. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/__init__.py +0 -0
  17. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/array.py +0 -0
  18. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/cache.py +0 -0
  19. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/cli.py +0 -0
  20. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/constants.py +0 -0
  21. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/errors.py +0 -0
  22. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/io.py +0 -0
  23. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/metadata/__init__.py +0 -0
  24. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/metadata/dimensions.py +0 -0
  25. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/pipeline.py +0 -0
  26. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/__init__.py +0 -0
  27. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/factory.py +0 -0
  28. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/generic.py +0 -0
  29. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/memory.py +0 -0
  30. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/nifti.py +0 -0
  31. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/pipeline.py +0 -0
  32. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/processing.py +0 -0
  33. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/readers/protocol.py +0 -0
  34. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/serialization.py +0 -0
  35. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/__init__.py +0 -0
  36. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/access.py +0 -0
  37. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/affine.py +0 -0
  38. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/axes.py +0 -0
  39. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/color.py +0 -0
  40. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/coordinates.py +0 -0
  41. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/dfield.py +0 -0
  42. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/metadata.py +0 -0
  43. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/normalization.py +0 -0
  44. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/protocol.py +0 -0
  45. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat/transformers/view.py +0 -0
  46. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat_python.egg-info/SOURCES.txt +0 -0
  47. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat_python.egg-info/dependency_links.txt +0 -0
  48. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat_python.egg-info/entry_points.txt +0 -0
  49. {tiamat_python-0.1.11 → tiamat_python-0.1.12}/tiamat_python.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tiamat-python
3
- Version: 0.1.11
3
+ Version: 0.1.12
4
4
  Summary: Tiled Image Access, Manipulation, and Analysis Toolkit
5
5
  Author-email: "Big Data Analytics Group, Forschungszentrum Juelich, Institute of Neuroscience and Medicine (INM-1)" <inm1-bda@fz-juelich.de>
6
6
  License:
@@ -233,7 +233,7 @@ Requires-Dist: flake8; extra == "dev"
233
233
  Requires-Dist: pre-commit; extra == "dev"
234
234
  Requires-Dist: pytest; extra == "dev"
235
235
  Provides-Extra: zarr
236
- Requires-Dist: zarr; extra == "zarr"
236
+ Requires-Dist: tensorstore; python_version >= "3.11" and extra == "zarr"
237
237
  Dynamic: license-file
238
238
 
239
239
  <p align="center">
@@ -48,7 +48,7 @@ tiamat = "tiamat.cli:cli"
48
48
 
49
49
  [project.optional-dependencies]
50
50
  dev = ["autopep8", "flake8", "pre-commit", "pytest"]
51
- zarr = ["zarr"]
51
+ zarr = ["tensorstore; python_version >= '3.11'"]
52
52
 
53
53
  [project.urls]
54
54
  homepage = "https://www.fz-juelich.de/de/inm/inm-1"
@@ -0,0 +1,206 @@
1
+ """
2
+ Metadata on images.
3
+ """
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass, field
7
+ from itertools import product, repeat
8
+
9
+ import numpy as np
10
+
11
+ import tiamat.metadata.dimensions as dimensions
12
+
13
+ # Image types
14
+ IMAGE_TYPE_SEGMENTATION = "segmentation" # an image with discrete values, e.g., a mask or a segmentation.
15
+ IMAGE_TYPE_IMAGE = "image" # an image with continuous values (e.g., a microscopy image).
16
+ IMAGE_TYPE_VECTOR = "vector" # an image with continuous vector values (e.g., a deformation field).
17
+
18
+
19
+ def get_dtype_limits(dtype):
20
+ """Returns the min and max values for a given dtype.
21
+
22
+ Supports numpy dtypes (integer or float)
23
+
24
+ Args:
25
+ dtype: numpy dtype
26
+
27
+ Returns:
28
+ tuple: min and max value of the dtype.
29
+ """
30
+
31
+ dtype = np.dtype(dtype)
32
+
33
+ if issubclass(dtype.type, np.integer):
34
+ info = np.iinfo(dtype)
35
+ elif issubclass(dtype.type, np.floating):
36
+ info = np.finfo(dtype)
37
+ else:
38
+ raise RuntimeError(f"{dtype} is not a valid dtype")
39
+ return info.min, info.max
40
+
41
+
42
+ @dataclass
43
+ class ImageMetadata:
44
+ """
45
+ Metadata describing an image result and its storage properties.
46
+
47
+ Attributes
48
+ ----------
49
+ image_type:
50
+ Logical type of the image defining how its data should be interpreted.
51
+ Typical examples include raw intensity images, segmentation masks,
52
+ or vector fields.
53
+
54
+ Must be one of:
55
+
56
+ - ``tiamat.metadata.IMAGE_TYPE_SEGMENTATION``
57
+ - ``tiamat.metadata.IMAGE_TYPE_IMAGE``
58
+ - ``tiamat.metadata.IMAGE_TYPE_VECTOR``
59
+
60
+ shape:
61
+ Shape of the image array at full resolution, expressed as a tuple
62
+ of integers describing the number of pixels or voxels along each
63
+ dimension.
64
+
65
+ The default dimension order is ``(z, y, x)``. This order matches the
66
+ typical indexing order used in NumPy arrays and ensures efficient
67
+ memory access.
68
+
69
+ value_range:
70
+ Expected minimum and maximum values of the image data, given as
71
+ ``(min, max)``.
72
+
73
+ The range is typically derived from the limits of ``dtype``,
74
+ but can also refer to the expected modality-specific limits.
75
+
76
+ This information may be used for normalization, data type conversion,
77
+ or visualization.
78
+
79
+ dtype:
80
+ NumPy data type used to store the image values.
81
+
82
+ dimensions:
83
+ Ordered names of the dimensions corresponding to ``shape``.
84
+ Valid dimension names are defined in ``tiamat.metadata.dimensions``.
85
+
86
+ The default order is ``(y, x, c)``, with the channel dimension
87
+ placed last.
88
+
89
+ file_path:
90
+ Path or collection of paths pointing to the file(s) storing the
91
+ image data.
92
+
93
+ Multiple paths typically indicate that the image data is read from
94
+ multiple files (for example an image stack). May be ``None`` if
95
+ the image is not associated with files on disk.
96
+
97
+ spacing:
98
+ Physical spacing between pixels or voxels at full resolution,
99
+ expressed in micrometers.
100
+
101
+ The value may be a single scalar (uniform spacing) or a tuple
102
+ specifying spacing per spatial dimension. Spacing is defined only
103
+ for spatial dimensions and does not apply to channel dimensions.
104
+
105
+ The dimension order follows ``(x, y)`` or ``(x, y, z)``.
106
+
107
+ additional_metadata:
108
+ Dictionary containing arbitrary additional metadata that is not
109
+ covered by the standard attributes.
110
+
111
+ This dictionary may contain reader-specific metadata or metadata
112
+ generated by the transform_metadata functions.
113
+
114
+ scales:
115
+ Scaling factors describing the available resolution levels of the
116
+ image (for example in a multi-resolution pyramid).
117
+
118
+ The value may be a single scale or an iterable of scales if multiple
119
+ resolutions are available.
120
+
121
+ Each scale may be either:
122
+
123
+ - a single numeric value for isotropic scaling, or
124
+ - a tuple specifying one scale value per spatial dimension.
125
+
126
+ A scale of ``1.0`` refers to the image at full resolution. Smaller
127
+ values indicate downsampled versions relative to the original size
128
+ (e.g. ``0.5`` corresponds to a downsampling factor of two).
129
+
130
+ The dimension order follows ``(x, y)`` or ``(x, y, z)``.
131
+ """
132
+
133
+ image_type: str
134
+ shape: tuple
135
+ value_range: tuple
136
+ dtype: np.dtype
137
+ dimensions: list[str, ...] | tuple[str, ...] = (dimensions.Y, dimensions.X, dimensions.C)
138
+ file_path: Iterable[str] | str | None = None
139
+ spacing: float | tuple[float, ...] | None = None
140
+ additional_metadata: dict = field(default_factory=dict)
141
+ scales: float | int | Iterable[float | int] | None = None
142
+
143
+ @property
144
+ def spatial_dimensions(self):
145
+ """
146
+ Returns indices of spatial dimensions, excluding channels
147
+ """
148
+ return tuple(
149
+ self.dimensions.index(dimension)
150
+ for dimension in dimensions.SPATIAL_DIMENSIONS
151
+ if dimension in self.dimensions
152
+ )
153
+
154
+ @property
155
+ def channel_dimensions(self):
156
+ """
157
+ Returns indices of channels, excluding spatial dimensions
158
+ """
159
+ return tuple(index for index, _ in enumerate(self.shape) if index not in self.spatial_dimensions)
160
+
161
+ @property
162
+ def spatial_shape(self):
163
+ """
164
+ Spatial shape of the image array, ignoring channel dimensions
165
+ """
166
+ return tuple(self.shape[i] for i in self.spatial_dimensions)
167
+
168
+ @spatial_shape.setter
169
+ def spatial_shape(self, shape):
170
+ shape_list = list(self.shape)
171
+ for i, ix in enumerate(self.spatial_dimensions):
172
+ shape_list[ix] = shape[i]
173
+ self.shape = tuple(shape_list)
174
+
175
+ @property
176
+ def extents(self):
177
+ """
178
+ Extents of the image. Provided as a list of tuple of coordinates.
179
+ Extrapolated by shape. Can be set, and will then return the set value.
180
+ Delete the property to revert to the default behavior.
181
+ """
182
+ if hasattr(self, "_extents"):
183
+ return self._extents
184
+ extents = list(zip(repeat(0), self.shape))
185
+ return list(product(*extents))
186
+
187
+ @extents.deleter
188
+ def extents(self):
189
+ delattr(self, "_extents")
190
+
191
+ def __repr__(self):
192
+ return (
193
+ f"ImageMetadata(\n"
194
+ f" image_type={self.image_type},\n"
195
+ f" shape={self.shape},\n"
196
+ f" value_range={self.value_range},\n"
197
+ f" dtype={self.dtype},\n"
198
+ f" spacing={self.spacing},\n"
199
+ f" dimensions=({','.join(self.dimensions)}),\n"
200
+ f" additional_metadata={self.additional_metadata},\n"
201
+ f" scales={self.scales}\n"
202
+ f")"
203
+ )
204
+
205
+ def __str__(self):
206
+ return self.__repr__()
@@ -757,34 +757,41 @@ class VolumeStackReader(ImageReader):
757
757
 
758
758
  out_image[tuple(index_to)] = array[tuple(index_from)]
759
759
 
760
- # Build volume stack
761
- cur_z_offset = 0
760
+ # Current offset each subvolume
761
+ volume_z_offset = 0
762
+
763
+ # Current coverage of read image data
764
+ coverage_offset = z_from
765
+
766
+ # Iterate all subvolumes
762
767
  for handle, shape in zip(self.ordered_subvolume_handles, self.subvolume_shapes):
768
+ # Size of the current subvolume
763
769
  z_size = shape[z_dim]
764
770
 
765
- # Use only slice handles with z slice overlap
766
- if cur_z_offset + z_size > z_from and cur_z_offset < z_to:
771
+ # Access only required subvolumes that lay in the accessor range and are not covered yet
772
+ if volume_z_offset + z_size > coverage_offset and volume_z_offset < z_to:
767
773
 
768
- # From, to slice for image access
769
- from_ix = max(z_from - cur_z_offset, 0)
770
- to_ix = min(z_to - cur_z_offset, z_size)
774
+ # Define access slice for the subvolume
775
+ from_ix = coverage_offset - volume_z_offset
776
+ to_ix = min(z_to - volume_z_offset, z_size)
771
777
 
772
778
  # Access subvolume and read from it
773
779
  tmp_accessor = replace(accessor, z=(from_ix, to_ix))
774
-
775
- # print("VolumeStackReader", accessor)
776
780
  tmp_image = handle.read_image(accessor=tmp_accessor)
777
781
 
778
- # Position in the output array to place the image
779
- scaled_z_offset = math.floor(max(cur_z_offset - z_from, 0) * image_scales[-1])
780
-
781
- # Insert the result in the array at specific offfset
782
+ # Position result in the output array
783
+ scaled_z_offset = math.floor(max(coverage_offset - z_from, 0) * image_scales[-1])
782
784
  insert_array(tmp_image, scaled_z_offset)
783
785
 
784
- # Output image might cover more than z_size
785
- cur_z_offset += z_size # tmp_image.shape[z_dim] / image_scales[-1]
786
- else:
787
- cur_z_offset += z_size
786
+ # Actual coverage of the newly read image data
787
+ tmp_coverage = tmp_image.shape[z_dim]
788
+ scaled_coverage = math.floor(tmp_coverage / image_scales[-1])
789
+
790
+ # Update total coverage of read image data
791
+ coverage_offset = coverage_offset + scaled_coverage
792
+
793
+ # Prepare offset for the next subvolume
794
+ volume_z_offset += z_size
788
795
 
789
796
  return out_image
790
797
 
@@ -1,5 +1,5 @@
1
1
  """
2
- Reader for OME-Zarr (Zarr v3 / OME-NGFF ≥0.5).
2
+ Reader for OME-Zarr (Zarr v3 / OME-NGFF >=0.5).
3
3
  """
4
4
 
5
5
  from __future__ import annotations
@@ -8,20 +8,17 @@ import json
8
8
  import os
9
9
  import zipfile
10
10
  from functools import cached_property
11
- from typing import Any, Dict, List, Tuple
11
+ from typing import Any, NamedTuple
12
12
 
13
13
  import numpy as np
14
14
 
15
- # We try to import zarr here. If it is not available, this reader will not register itself as available (see check_file)
16
15
  try:
17
- import zarr # pylint: disable=import-error
18
- from zarr.storage import ZipStore # pylint: disable=import-error
16
+ import tensorstore as ts # pylint: disable=import-error
19
17
 
20
- _ZARR_AVAILABLE = True
18
+ _TENSORSTORE_AVAILABLE = True
21
19
  except Exception: # pragma: no cover
22
- zarr = None # pylint: disable=import-error
23
- ZipStore = None # pylint: disable=import-error
24
- _ZARR_AVAILABLE = False
20
+ ts = None # pylint: disable=import-error
21
+ _TENSORSTORE_AVAILABLE = False
25
22
 
26
23
  from tiamat.cache import instance_cache
27
24
  from tiamat.io import ImageAccessor
@@ -29,6 +26,57 @@ from tiamat.metadata import ImageMetadata
29
26
  from tiamat.readers.protocol import ImageReader
30
27
 
31
28
 
29
+ # retrieved from https://ngff.openmicroscopy.org/specifications/0.5/index.html#axes-metadata
30
+ # on 2026-03-05
31
+
32
+ class SiUnit(NamedTuple):
33
+ symbol: str
34
+ exponent: int
35
+ prefix: str
36
+
37
+
38
+ base_to_si_units = [
39
+ SiUnit(**d)
40
+ for d in [
41
+ {"symbol": "Y", "exponent": 24, "prefix": "yotta"},
42
+ {"symbol": "Z", "exponent": 21, "prefix": "zetta"},
43
+ {"symbol": "E", "exponent": 18, "prefix": "exa"},
44
+ {"symbol": "P", "exponent": 15, "prefix": "peta"},
45
+ {"symbol": "T", "exponent": 12, "prefix": "tera"},
46
+ {"symbol": "G", "exponent": 9, "prefix": "giga"},
47
+ {"symbol": "M", "exponent": 6, "prefix": "mega"},
48
+ {"symbol": "k", "exponent": 3, "prefix": "kilo"},
49
+ {"symbol": "", "exponent": 0, "prefix": ""},
50
+ {"symbol": "m", "exponent": -3, "prefix": "milli"},
51
+ {"symbol": "µ", "exponent": -6, "prefix": "micro"},
52
+ {"symbol": "u", "exponent": -6, "prefix": "micro"},
53
+ {"symbol": "n", "exponent": -9, "prefix": "nano"},
54
+ {"symbol": "p", "exponent": -12, "prefix": "pico"},
55
+ {"symbol": "f", "exponent": -15, "prefix": "femto"},
56
+ {"symbol": "a", "exponent": -18, "prefix": "atto"},
57
+ {"symbol": "z", "exponent": -21, "prefix": "zepto"},
58
+ {"symbol": "y", "exponent": -24, "prefix": "yocto"},
59
+ {"symbol": "h", "exponent": 2, "prefix": "hecto"},
60
+ {"symbol": "d", "exponent": -1, "prefix": "deci"},
61
+ {"symbol": "c", "exponent": -2, "prefix": "centi"},
62
+ ]
63
+ ]
64
+
65
+ meter_to_spatial_units = {
66
+ "angstrom": 1e-10,
67
+ "foot": 0.3048,
68
+ "inch": 0.0254,
69
+ "mile": 1609.34,
70
+ "parsec": 3.0856775814913673e16,
71
+ "yard": 0.9144,
72
+ }
73
+
74
+ spatial_units_to_micron = {
75
+ **{unit: 1e6 / value for unit, value in meter_to_spatial_units.items()},
76
+ **{f"{v.prefix}meter": 10 ** (6 + v.exponent) for v in base_to_si_units},
77
+ }
78
+
79
+
32
80
  def _axis_to_dim(axis_name: str, md) -> Any:
33
81
  """
34
82
  Map ome-zarr specific axis labels to tiamat dimensions.
@@ -43,14 +91,40 @@ def _axis_to_dim(axis_name: str, md) -> Any:
43
91
  }.get(n, md.dimensions.C)
44
92
 
45
93
 
94
+ class _TensorStoreArrayAdapter:
95
+ """
96
+ Small ndarray-like wrapper around a TensorStore array handle.
97
+ """
98
+
99
+ def __init__(self, store):
100
+ self._store = store
101
+
102
+ @property
103
+ def dtype(self) -> np.dtype:
104
+ return np.dtype(self._store.dtype.numpy_dtype)
105
+
106
+ @property
107
+ def shape(self) -> tuple[int, ...]:
108
+ return tuple(int(x) for x in self._store.shape)
109
+
110
+ @property
111
+ def ndim(self) -> int:
112
+ return len(self.shape)
113
+
114
+ def __getitem__(self, item):
115
+ view = self._store[item]
116
+ if hasattr(view, "read"):
117
+ return np.asarray(view.read().result())
118
+ return np.asarray(view)
119
+
120
+
46
121
  class OmeZarrReader(ImageReader):
47
122
  def __init__(self, fname: str):
48
123
  self.fname = fname
49
124
 
50
125
  @classmethod
51
126
  def check_file(cls, fname) -> bool | int | float:
52
- if not _ZARR_AVAILABLE:
53
- # zarr not installed, we cannot do anything.
127
+ if not _TENSORSTORE_AVAILABLE:
54
128
  return False
55
129
 
56
130
  lower = str(fname).lower()
@@ -60,7 +134,6 @@ class OmeZarrReader(ImageReader):
60
134
  if not (is_zip or is_dir_like):
61
135
  return False
62
136
 
63
- # Function to load zarr.json content
64
137
  def load_zarr_json(json_bytes: bytes) -> dict | None:
65
138
  try:
66
139
  return json.loads(json_bytes)
@@ -70,7 +143,6 @@ class OmeZarrReader(ImageReader):
70
143
  zarr_data = None
71
144
 
72
145
  if is_zip:
73
- # Check inside ZIP
74
146
  try:
75
147
  with zipfile.ZipFile(fname, "r") as zf:
76
148
  if "zarr.json" not in zf.namelist():
@@ -81,7 +153,6 @@ class OmeZarrReader(ImageReader):
81
153
  return False
82
154
 
83
155
  elif is_dir_like:
84
- # Check inside directory
85
156
  zarr_json_path = os.path.join(fname, "zarr.json")
86
157
  if not os.path.exists(zarr_json_path):
87
158
  return False
@@ -91,7 +162,6 @@ class OmeZarrReader(ImageReader):
91
162
  except Exception:
92
163
  return False
93
164
 
94
- # Validate JSON structure
95
165
  if not isinstance(zarr_data, dict):
96
166
  return False
97
167
 
@@ -100,41 +170,36 @@ class OmeZarrReader(ImageReader):
100
170
  return False
101
171
 
102
172
  if "ome" in attributes:
103
- return 10 # or True, depending on your scoring scheme
173
+ return 10
104
174
  return False
105
175
 
106
176
  def read_image(self, accessor: ImageAccessor) -> np.ndarray:
107
177
  from tiamat.readers.processing import access_and_rescale_image
108
178
 
109
179
  axes = self.axes_names
110
- # Normalize accessor.scale to a sequence
111
180
  raw_scale = accessor.scale
112
181
  if isinstance(raw_scale, (float, int)):
113
- # single float: treat as uniform on all spatial axes
114
182
  target_xy = (float(raw_scale), float(raw_scale))
115
183
  target_z = float(raw_scale)
116
184
  else:
117
- # assume sequence
118
185
  seq = list(raw_scale)
119
186
  if len(seq) >= 3:
120
- # interpret as (Z, Y, X)
121
187
  target_z = float(seq[0])
122
188
  target_xy = (float(seq[1]), float(seq[2]))
123
189
  elif len(seq) == 2:
124
190
  target_z = float(min(seq))
125
191
  target_xy = (float(seq[0]), float(seq[1]))
126
192
  else:
127
- # fallback: treat everything as uniform
128
193
  target_xy = (float(seq[0]), float(seq[0]))
129
194
  target_z = float(seq[0])
130
195
 
131
- per_axis_target: List[float] = []
132
- for a in axes:
133
- if a == "x":
196
+ per_axis_target = []
197
+ for axis_name in axes:
198
+ if axis_name == "x":
134
199
  per_axis_target.append(target_xy[1])
135
- elif a == "y":
200
+ elif axis_name == "y":
136
201
  per_axis_target.append(target_xy[0])
137
- elif a == "z":
202
+ elif axis_name == "z":
138
203
  per_axis_target.append(target_z)
139
204
  else:
140
205
  per_axis_target.append(1.0)
@@ -169,58 +234,78 @@ class OmeZarrReader(ImageReader):
169
234
  additional_metadata=self._root_attrs,
170
235
  )
171
236
 
172
- # ---------------- Cached / internal helpers ---------------- #
173
-
174
237
  @cached_property
175
- def _root_group(self):
176
- if not _ZARR_AVAILABLE:
177
- raise ImportError("zarr is not installed. Install `zarr` to read OME-Zarr data.")
238
+ def _kvstore_spec(self) -> dict[str, Any]:
178
239
  lower = self.fname.lower()
179
240
  if lower.endswith(".zip"):
180
- if ZipStore is None:
181
- raise ImportError("zarr ZipStore is not available.")
182
- if not os.path.exists(self.fname):
183
- raise FileNotFoundError(self.fname)
184
- store = ZipStore(self.fname, mode="r")
185
- return zarr.open_group(store=store, mode="r")
186
- if not (os.path.isdir(self.fname) or os.path.exists(self.fname)):
187
- raise FileNotFoundError(self.fname)
188
- return zarr.open_group(self.fname, mode="r")
241
+ return {
242
+ "driver": "zip",
243
+ "base": {
244
+ "driver": "file",
245
+ "path": self.fname,
246
+ },
247
+ }
248
+
249
+ path = self.fname
250
+ if os.path.isdir(path) and not path.endswith(os.sep):
251
+ path += os.sep
252
+
253
+ return {
254
+ "driver": "file",
255
+ "path": path,
256
+ }
257
+
258
+ @cached_property
259
+ def _kvstore(self):
260
+ if not _TENSORSTORE_AVAILABLE:
261
+ raise ImportError(
262
+ "tensorstore is not installed. Install `tensorstore` to read OME-Zarr data."
263
+ )
264
+ return ts.KvStore.open(self._kvstore_spec).result()
189
265
 
190
266
  @cached_property
191
- def _root_attrs(self) -> Dict[str, Any]:
192
- # Zarr v3: metadata is surfaced via .attrs (backed by zarr.json)
193
- attrs = dict(getattr(self._root_group, "attrs", {}) or {})
267
+ def _root_attrs(self) -> dict[str, Any]:
268
+ result = self._kvstore.read("zarr.json").result()
269
+ if getattr(result, "state", None) != "value":
270
+ raise ValueError("OME-Zarr root metadata 'zarr.json' is missing.")
271
+
272
+ try:
273
+ root_meta = json.loads(result.value)
274
+ except Exception as exc: # pragma: no cover
275
+ raise ValueError("OME-Zarr root metadata 'zarr.json' is invalid JSON.") from exc
276
+
277
+ attrs = root_meta.get("attributes")
278
+ if not isinstance(attrs, dict):
279
+ raise ValueError("OME-Zarr root metadata is missing 'attributes'.")
194
280
  return attrs
195
281
 
196
282
  @cached_property
197
- def _ome_meta(self) -> Dict[str, Any]:
198
- # Prefer "ome" namespace if present, otherwise treat root attrs as container
283
+ def _ome_meta(self) -> dict[str, Any]:
199
284
  ome = self._root_attrs.get("ome")
200
285
  if isinstance(ome, dict) and ome:
201
286
  return ome
202
287
  return self._root_attrs
203
288
 
204
289
  @cached_property
205
- def _multiscales(self) -> List[Dict[str, Any]]:
206
- ms = self._ome_meta.get("multiscales")
207
- if not isinstance(ms, list) or not ms:
290
+ def _multiscales(self) -> list[dict[str, Any]]:
291
+ multiscales = self._ome_meta.get("multiscales")
292
+ if not isinstance(multiscales, list) or not multiscales:
208
293
  raise ValueError("OME-Zarr attributes lack a valid 'multiscales' list.")
209
- return ms
294
+ return multiscales
210
295
 
211
296
  @cached_property
212
- def _pyramid(self) -> Dict[str, Any]:
297
+ def _pyramid(self) -> dict[str, Any]:
213
298
  return self._multiscales[0]
214
299
 
215
300
  @cached_property
216
- def axes_names(self) -> List[str]:
301
+ def axes_names(self) -> list[str]:
217
302
  axes = self._pyramid.get("axes")
218
303
  if isinstance(axes, list) and axes:
219
304
  if isinstance(axes[0], str):
220
- return [a.lower() for a in axes]
305
+ return [axis_name.lower() for axis_name in axes]
221
306
  if isinstance(axes[0], dict):
222
- return [str(a.get("name", "")).lower() for a in axes]
223
- # Fallback using array rank
307
+ return [str(axis.get("name", "")).lower() for axis in axes]
308
+
224
309
  a0 = self._get_level_array(0)
225
310
  rank = a0.ndim
226
311
  if rank == 2:
@@ -234,66 +319,73 @@ class OmeZarrReader(ImageReader):
234
319
  return ["y", "x"]
235
320
 
236
321
  @cached_property
237
- def _datasets(self) -> List[Dict[str, Any]]:
238
- ds = self._pyramid.get("datasets")
239
- if not isinstance(ds, list) or not ds:
322
+ def _datasets(self) -> list[dict[str, Any]]:
323
+ datasets = self._pyramid.get("datasets")
324
+ if not isinstance(datasets, list) or not datasets:
240
325
  raise ValueError("OME-Zarr multiscales.datasets is missing or empty.")
241
- return ds
326
+ return datasets
242
327
 
243
328
  @cached_property
244
329
  def dtype(self) -> np.dtype:
245
330
  return self._get_level_array(0).dtype
246
331
 
247
332
  @cached_property
248
- def shape(self) -> Tuple[int, ...]:
333
+ def shape(self) -> tuple[int, ...]:
249
334
  return tuple(int(x) for x in self._get_level_array(0).shape)
250
335
 
251
336
  @cached_property
252
- def value_range(self) -> Tuple[float | int, float | int]:
253
- dt = self.dtype
254
- if np.issubdtype(dt, np.integer):
255
- info = np.iinfo(dt)
256
- elif np.issubdtype(dt, np.floating):
257
- info = np.finfo(dt)
337
+ def value_range(self) -> tuple[float | int, float | int]:
338
+ dtype = self.dtype
339
+ if np.issubdtype(dtype, np.integer):
340
+ info = np.iinfo(dtype)
341
+ elif np.issubdtype(dtype, np.floating):
342
+ info = np.finfo(dtype)
258
343
  else:
259
- raise TypeError(f"Cannot determine value range for dtype {dt}")
344
+ raise TypeError(f"Cannot determine value range for dtype {dtype}")
260
345
  return info.min, info.max
261
346
 
262
347
  @cached_property
263
- def pixel_spacing(self) -> Tuple[float, ...]:
264
- # Read level-0 coordinateTransformations -> scale vector; fallback 1.0
348
+ def pixel_spacing(self) -> tuple[float, ...]:
265
349
  axes = self.axes_names
350
+
351
+ mul_factor: list[float] = []
352
+ for axis in self._pyramid.get("axes", []):
353
+ unit = axis.get("unit")
354
+ if factor := spatial_units_to_micron.get(unit):
355
+ mul_factor.append(factor)
356
+ else:
357
+ raise RuntimeError(f"zarr unit {unit} either not recognized or factor not yet encoded.")
358
+
266
359
  transforms = self._datasets[0].get("coordinateTransformations", [])
267
360
  scale_vec = None
268
- for t in transforms or []:
269
- if isinstance(t, dict) and t.get("type") == "scale":
270
- v = t.get("scale")
271
- if isinstance(v, list) and len(v) == len(axes):
272
- scale_vec = [float(x) for x in v]
361
+ for transform in transforms or []:
362
+ if isinstance(transform, dict) and transform.get("type") == "scale":
363
+ scale = transform.get("scale")
364
+ if isinstance(scale, list) and len(scale) == len(axes) == len(mul_factor):
365
+ scale_vec = [float(x) * factor for x, factor in zip(scale, mul_factor)]
273
366
  break
274
367
  if scale_vec is None:
275
368
  return tuple([1.0] * len(axes))
276
369
  return tuple(scale_vec)
277
370
 
278
371
  @instance_cache
279
- def _level_factors(self, level: int) -> List[float]:
372
+ def _level_factors(self, level: int) -> list[float]:
280
373
  base = self._get_level_array(0).shape
281
374
  cur = self._get_level_array(level).shape
282
- factors: List[float] = []
375
+ factors = []
283
376
  spatial = {"z", "y", "x"}
284
- for i, a in enumerate(self.axes_names):
285
- if a in spatial:
377
+ for i, axis_name in enumerate(self.axes_names):
378
+ if axis_name in spatial:
286
379
  factors.append(float(cur[i]) / float(base[i]))
287
380
  else:
288
381
  factors.append(1.0)
289
382
  return factors
290
383
 
291
384
  @cached_property
292
- def scales(self) -> List[float]:
385
+ def scales(self) -> list[tuple[float, ...]]:
293
386
  factors = []
294
387
  for lvl in range(len(self._datasets)):
295
388
  factors.append(tuple(self._level_factors(lvl)[::-1]))
296
-
297
389
  return factors
298
390
 
299
391
  @instance_cache
@@ -302,41 +394,47 @@ class OmeZarrReader(ImageReader):
302
394
  rel = ds.get("path")
303
395
  if not isinstance(rel, str) or not rel:
304
396
  raise ValueError(f"Invalid dataset path at level {level}.")
305
- if rel not in self._root_group:
306
- raise ValueError(f"Dataset '{rel}' not found in Zarr group.")
307
- return self._root_group[rel]
397
+
398
+ store = ts.open(
399
+ {
400
+ "driver": "zarr3",
401
+ "kvstore": self._kvstore_spec,
402
+ "path": rel,
403
+ },
404
+ read=True,
405
+ ).result()
406
+ return _TensorStoreArrayAdapter(store)
308
407
 
309
408
  @cached_property
310
- def _spatial_indices(self) -> List[int]:
409
+ def _spatial_indices(self) -> list[int]:
311
410
  order = []
312
- for a in ("z", "y", "x"):
313
- if a in self.axes_names:
314
- order.append(self.axes_names.index(a))
411
+ for axis_name in ("z", "y", "x"):
412
+ if axis_name in self.axes_names:
413
+ order.append(self.axes_names.index(axis_name))
315
414
  return order
316
415
 
317
- def _select_level_from_target(self, per_axis_target: List[float]) -> int:
416
+ def _select_level_from_target(self, per_axis_target: list[float]) -> int:
318
417
  spatial_idx = self._spatial_indices
319
418
 
320
- def meets_target(factors: List[float]) -> bool:
419
+ def meets_target(factors: list[float]) -> bool:
321
420
  return all(factors[i] >= per_axis_target[i] for i in spatial_idx)
322
421
 
323
422
  candidates = []
324
423
  for lvl in range(len(self._datasets)):
325
- f = self._level_factors(lvl)
326
- if meets_target(f):
327
- score = max((f[i] for i in spatial_idx), default=1.0)
424
+ factors = self._level_factors(lvl)
425
+ if meets_target(factors):
426
+ score = max((factors[i] for i in spatial_idx), default=1.0)
328
427
  candidates.append((score, lvl))
329
428
 
330
429
  if candidates:
331
430
  candidates.sort(key=lambda t: t[0])
332
431
  return candidates[0][1]
333
432
 
334
- # Fall back to coarsest
335
433
  coarsest = 0
336
434
  coarsest_score = -np.inf
337
435
  for lvl in range(len(self._datasets)):
338
- f = self._level_factors(lvl)
339
- score = max((f[i] for i in spatial_idx), default=1.0)
436
+ factors = self._level_factors(lvl)
437
+ score = max((factors[i] for i in spatial_idx), default=1.0)
340
438
  if score > coarsest_score:
341
439
  coarsest_score = score
342
440
  coarsest = lvl
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tiamat-python
3
- Version: 0.1.11
3
+ Version: 0.1.12
4
4
  Summary: Tiled Image Access, Manipulation, and Analysis Toolkit
5
5
  Author-email: "Big Data Analytics Group, Forschungszentrum Juelich, Institute of Neuroscience and Medicine (INM-1)" <inm1-bda@fz-juelich.de>
6
6
  License:
@@ -233,7 +233,7 @@ Requires-Dist: flake8; extra == "dev"
233
233
  Requires-Dist: pre-commit; extra == "dev"
234
234
  Requires-Dist: pytest; extra == "dev"
235
235
  Provides-Extra: zarr
236
- Requires-Dist: zarr; extra == "zarr"
236
+ Requires-Dist: tensorstore; python_version >= "3.11" and extra == "zarr"
237
237
  Dynamic: license-file
238
238
 
239
239
  <p align="center">
@@ -13,4 +13,6 @@ pre-commit
13
13
  pytest
14
14
 
15
15
  [zarr]
16
- zarr
16
+
17
+ [zarr:python_version >= "3.11"]
18
+ tensorstore
@@ -1,118 +0,0 @@
1
- """
2
- Metadata on images.
3
- """
4
-
5
- from collections.abc import Iterable
6
- from dataclasses import dataclass, field
7
- from itertools import product, repeat
8
-
9
- import numpy as np
10
-
11
- import tiamat.metadata.dimensions as dimensions
12
-
13
- # Image types
14
- IMAGE_TYPE_SEGMENTATION = "segmentation" # an image with discrete values, e.g., a mask or a segmentation.
15
- IMAGE_TYPE_IMAGE = "image" # an image with continuous values (e.g., a microscopy image).
16
- IMAGE_TYPE_VECTOR = "vector" # an image with continuous vector values (e.g., a deformation field).
17
-
18
-
19
- def get_dtype_limits(dtype):
20
- """Returns the min and max values for a given dtype.
21
-
22
- Supports numpy dtypes (integer or float)
23
-
24
- Args:
25
- dtype: numpy dtype
26
-
27
- Returns:
28
- tuple: min and max value of the dtype.
29
- """
30
-
31
- dtype = np.dtype(dtype)
32
-
33
- if issubclass(dtype.type, np.integer):
34
- info = np.iinfo(dtype)
35
- elif issubclass(dtype.type, np.floating):
36
- info = np.finfo(dtype)
37
- else:
38
- raise RuntimeError(f"{dtype} is not a valid dtype")
39
- return info.min, info.max
40
-
41
-
42
- @dataclass
43
- class ImageMetadata:
44
- """
45
- Metadata of an image.
46
- """
47
-
48
- image_type: str
49
- shape: tuple
50
- value_range: tuple
51
- dtype: np.dtype
52
- dimensions: list[str, ...] | tuple[str, ...] = (dimensions.Y, dimensions.X, dimensions.C)
53
- file_path: Iterable[str] | str | None = None
54
- spacing: float | tuple[float, ...] | None = None
55
- additional_metadata: dict = field(default_factory=dict)
56
- scales: float | int | Iterable[float | int] | None = None
57
-
58
- @property
59
- def spatial_dimensions(self):
60
- """
61
- Returns indices of spatial axes, excluding channels
62
- """
63
- return tuple(
64
- self.dimensions.index(dimension)
65
- for dimension in dimensions.SPATIAL_DIMENSIONS
66
- if dimension in self.dimensions
67
- )
68
-
69
- @property
70
- def channel_dimensions(self):
71
- """
72
- Returns indices of channels, excluding spatial axes
73
- """
74
- return tuple(index for index, _ in enumerate(self.shape) if index not in self.spatial_dimensions)
75
-
76
- @property
77
- def spatial_shape(self):
78
- return tuple(self.shape[i] for i in self.spatial_dimensions)
79
-
80
- @spatial_shape.setter
81
- def spatial_shape(self, shape):
82
- shape_list = list(self.shape)
83
- for i, ix in enumerate(self.spatial_dimensions):
84
- shape_list[ix] = shape[i]
85
- self.shape = tuple(shape_list)
86
-
87
- @property
88
- def extents(self):
89
- """
90
- Extents of the image. Provided as a list of tuple of coordinates.
91
- Extrapolated by shape. Can be set, and will then return the set value.
92
- Delete the property to revert to the default behavior.
93
- """
94
- if hasattr(self, "_extents"):
95
- return self._extents
96
- extents = list(zip(repeat(0), self.shape))
97
- return list(product(*extents))
98
-
99
- @extents.deleter
100
- def extents(self):
101
- delattr(self, "_extents")
102
-
103
- def __repr__(self):
104
- return (
105
- f"ImageMetadata(\n"
106
- f" image_type={self.image_type},\n"
107
- f" shape={self.shape},\n"
108
- f" value_range={self.value_range},\n"
109
- f" dtype={self.dtype},\n"
110
- f" spacing={self.spacing},\n"
111
- f" dimensions=({','.join(self.dimensions)}),\n"
112
- f" additional_metadata={self.additional_metadata},\n"
113
- f" scales={self.scales}\n"
114
- f")"
115
- )
116
-
117
- def __str__(self):
118
- return self.__repr__()
File without changes
File without changes
File without changes
File without changes