tiamat-python 0.1.11__tar.gz → 0.1.13__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 (50) hide show
  1. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/PKG-INFO +2 -2
  2. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/pyproject.toml +1 -1
  3. tiamat_python-0.1.13/tiamat/metadata/metadata.py +246 -0
  4. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/pipeline.py +10 -4
  5. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/processing.py +7 -3
  6. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/stack.py +31 -17
  7. tiamat_python-0.1.13/tiamat/readers/zarr.py +450 -0
  8. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/serialization.py +10 -0
  9. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/color.py +0 -1
  10. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat_python.egg-info/PKG-INFO +2 -2
  11. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat_python.egg-info/requires.txt +3 -1
  12. tiamat_python-0.1.11/tiamat/metadata/metadata.py +0 -118
  13. tiamat_python-0.1.11/tiamat/readers/zarr.py +0 -343
  14. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/LICENSE +0 -0
  15. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/README.md +0 -0
  16. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/README.rst +0 -0
  17. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/setup.cfg +0 -0
  18. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/setup.py +0 -0
  19. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tests/test_metadata.py +0 -0
  20. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tests/test_package.py +0 -0
  21. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/__init__.py +0 -0
  22. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/array.py +0 -0
  23. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/cache.py +0 -0
  24. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/cli.py +0 -0
  25. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/constants.py +0 -0
  26. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/errors.py +0 -0
  27. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/io.py +0 -0
  28. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/metadata/__init__.py +0 -0
  29. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/metadata/dimensions.py +0 -0
  30. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/__init__.py +0 -0
  31. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/factory.py +0 -0
  32. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/generic.py +0 -0
  33. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/memory.py +0 -0
  34. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/nifti.py +0 -0
  35. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/pipeline.py +0 -0
  36. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/readers/protocol.py +0 -0
  37. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/__init__.py +0 -0
  38. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/access.py +0 -0
  39. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/affine.py +0 -0
  40. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/axes.py +0 -0
  41. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/coordinates.py +0 -0
  42. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/dfield.py +0 -0
  43. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/metadata.py +0 -0
  44. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/normalization.py +0 -0
  45. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/protocol.py +0 -0
  46. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat/transformers/view.py +0 -0
  47. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat_python.egg-info/SOURCES.txt +0 -0
  48. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat_python.egg-info/dependency_links.txt +0 -0
  49. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/tiamat_python.egg-info/entry_points.txt +0 -0
  50. {tiamat_python-0.1.11 → tiamat_python-0.1.13}/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.13
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,246 @@
1
+ """
2
+ Metadata on images.
3
+ """
4
+
5
+ from collections.abc import Iterable
6
+ from dataclasses import dataclass, field, fields
7
+ from itertools import product, repeat
8
+ from typing import Any, Mapping
9
+
10
+ import numpy as np
11
+
12
+ import tiamat.metadata.dimensions as dimensions
13
+
14
+ # Image types
15
+ IMAGE_TYPE_SEGMENTATION = "segmentation" # an image with discrete values, e.g., a mask or a segmentation.
16
+ IMAGE_TYPE_IMAGE = "image" # an image with continuous values (e.g., a microscopy image).
17
+ IMAGE_TYPE_VECTOR = "vector" # an image with continuous vector values (e.g., a deformation field).
18
+
19
+
20
+ def get_dtype_limits(dtype):
21
+ """Returns the min and max values for a given dtype.
22
+
23
+ Supports numpy dtypes (integer or float)
24
+
25
+ Args:
26
+ dtype: numpy dtype
27
+
28
+ Returns:
29
+ tuple: min and max value of the dtype.
30
+ """
31
+
32
+ dtype = np.dtype(dtype)
33
+
34
+ if issubclass(dtype.type, np.integer):
35
+ info = np.iinfo(dtype)
36
+ elif issubclass(dtype.type, np.floating):
37
+ info = np.finfo(dtype)
38
+ else:
39
+ raise RuntimeError(f"{dtype} is not a valid dtype")
40
+ return info.min, info.max
41
+
42
+
43
+ @dataclass
44
+ class ImageMetadata:
45
+ """
46
+ Metadata describing an image result and its storage properties.
47
+
48
+ Attributes
49
+ ----------
50
+ image_type:
51
+ Logical type of the image defining how its data should be interpreted.
52
+ Typical examples include raw intensity images, segmentation masks,
53
+ or vector fields.
54
+
55
+ Must be one of:
56
+
57
+ - ``tiamat.metadata.IMAGE_TYPE_SEGMENTATION``
58
+ - ``tiamat.metadata.IMAGE_TYPE_IMAGE``
59
+ - ``tiamat.metadata.IMAGE_TYPE_VECTOR``
60
+
61
+ shape:
62
+ Shape of the image array at full resolution, expressed as a tuple
63
+ of integers describing the number of pixels or voxels along each
64
+ dimension.
65
+
66
+ The default dimension order is ``(z, y, x)``. This order matches the
67
+ typical indexing order used in NumPy arrays and ensures efficient
68
+ memory access.
69
+
70
+ value_range:
71
+ Expected minimum and maximum values of the image data, given as
72
+ ``(min, max)``.
73
+
74
+ The range is typically derived from the limits of ``dtype``,
75
+ but can also refer to the expected modality-specific limits.
76
+
77
+ This information may be used for normalization, data type conversion,
78
+ or visualization.
79
+
80
+ dtype:
81
+ NumPy data type used to store the image values.
82
+
83
+ dimensions:
84
+ Ordered names of the dimensions corresponding to ``shape``.
85
+ Valid dimension names are defined in ``tiamat.metadata.dimensions``.
86
+
87
+ The default order is ``(y, x, c)``, with the channel dimension
88
+ placed last.
89
+
90
+ file_path:
91
+ Path or collection of paths pointing to the file(s) storing the
92
+ image data.
93
+
94
+ Multiple paths typically indicate that the image data is read from
95
+ multiple files (for example an image stack). May be ``None`` if
96
+ the image is not associated with files on disk.
97
+
98
+ spacing:
99
+ Physical spacing between pixels or voxels at full resolution,
100
+ expressed in micrometers.
101
+
102
+ The value may be a single scalar (uniform spacing) or a tuple
103
+ specifying spacing per spatial dimension. Spacing is defined only
104
+ for spatial dimensions and does not apply to channel dimensions.
105
+
106
+ The dimension order follows ``(x, y)`` or ``(x, y, z)``.
107
+
108
+ additional_metadata:
109
+ Dictionary containing arbitrary additional metadata that is not
110
+ covered by the standard attributes.
111
+
112
+ This dictionary may contain reader-specific metadata or metadata
113
+ generated by the transform_metadata functions.
114
+
115
+ scales:
116
+ Scaling factors describing the available resolution levels of the
117
+ image (for example in a multi-resolution pyramid).
118
+
119
+ The value may be a single scale or an iterable of scales if multiple
120
+ resolutions are available.
121
+
122
+ Each scale may be either:
123
+
124
+ - a single numeric value for isotropic scaling, or
125
+ - a tuple specifying one scale value per spatial dimension.
126
+
127
+ A scale of ``1.0`` refers to the image at full resolution. Smaller
128
+ values indicate downsampled versions relative to the original size
129
+ (e.g. ``0.5`` corresponds to a downsampling factor of two).
130
+
131
+ The dimension order follows ``(x, y)`` or ``(x, y, z)``.
132
+ """
133
+
134
+ image_type: str
135
+ shape: tuple
136
+ value_range: tuple
137
+ dtype: np.dtype
138
+ dimensions: list[str, ...] | tuple[str, ...] = (dimensions.Y, dimensions.X, dimensions.C)
139
+ file_path: Iterable[str] | str | None = None
140
+ spacing: float | tuple[float, ...] | None = None
141
+ additional_metadata: dict = field(default_factory=dict)
142
+ scales: float | int | Iterable[float | int] | Iterable[tuple[float | int, ...]] | None = None
143
+
144
+ @property
145
+ def spatial_dimensions(self):
146
+ """
147
+ Returns indices of spatial dimensions, excluding channels
148
+ """
149
+ return tuple(
150
+ self.dimensions.index(dimension)
151
+ for dimension in dimensions.SPATIAL_DIMENSIONS
152
+ if dimension in self.dimensions
153
+ )
154
+
155
+ @property
156
+ def channel_dimensions(self):
157
+ """
158
+ Returns indices of channels, excluding spatial dimensions
159
+ """
160
+ return tuple(index for index, _ in enumerate(self.shape) if index not in self.spatial_dimensions)
161
+
162
+ @property
163
+ def spatial_shape(self):
164
+ """
165
+ Spatial shape of the image array, ignoring channel dimensions
166
+ """
167
+ return tuple(self.shape[i] for i in self.spatial_dimensions)
168
+
169
+ @spatial_shape.setter
170
+ def spatial_shape(self, shape):
171
+ shape_list = list(self.shape)
172
+ for i, ix in enumerate(self.spatial_dimensions):
173
+ shape_list[ix] = shape[i]
174
+ self.shape = tuple(shape_list)
175
+
176
+ @property
177
+ def extents(self):
178
+ """
179
+ Extents of the image. Provided as a list of tuple of coordinates.
180
+ Extrapolated by shape. Can be set, and will then return the set value.
181
+ Delete the property to revert to the default behavior.
182
+ """
183
+ if hasattr(self, "_extents"):
184
+ return self._extents
185
+ extents = list(zip(repeat(0), self.shape))
186
+ return list(product(*extents))
187
+
188
+ @extents.deleter
189
+ def extents(self):
190
+ delattr(self, "_extents")
191
+
192
+ def __repr__(self):
193
+ return (
194
+ f"ImageMetadata(\n"
195
+ f" image_type={self.image_type},\n"
196
+ f" shape={self.shape},\n"
197
+ f" value_range={self.value_range},\n"
198
+ f" dtype={self.dtype},\n"
199
+ f" spacing={self.spacing},\n"
200
+ f" dimensions=({','.join(self.dimensions)}),\n"
201
+ f" additional_metadata={self.additional_metadata},\n"
202
+ f" scales={self.scales}\n"
203
+ f")"
204
+ )
205
+
206
+ def __str__(self):
207
+ return self.__repr__()
208
+
209
+
210
+ def _convert_metadata_value(key: str, value: Any) -> Any:
211
+ """Convert metadata values to match ImageMetadata field conventions."""
212
+ if key in {"shape", "value_range", "dimensions", "spacing"}:
213
+ if isinstance(value, list):
214
+ return tuple(value)
215
+
216
+ if key == "dtype":
217
+ if isinstance(value, str):
218
+ return np.dtype(value)
219
+
220
+ if key == "scales":
221
+ if isinstance(value, list):
222
+ if value and all(isinstance(v, (list, tuple)) for v in value):
223
+ return [tuple(v) for v in value]
224
+
225
+ return value
226
+
227
+
228
+ def update_metadata_from_dict(
229
+ image_metadata: ImageMetadata,
230
+ update_dict: Mapping[str, Any],
231
+ ) -> ImageMetadata:
232
+ """
233
+ Update an ImageMetadata instance from a dict.
234
+
235
+ Matching keys update dataclass fields; unknown keys are stored in
236
+ ``additional_metadata``.
237
+ """
238
+ valid_fields = {f.name for f in fields(image_metadata)}
239
+
240
+ for key, value in update_dict.items():
241
+ if key in valid_fields:
242
+ setattr(image_metadata, key, _convert_metadata_value(key, value))
243
+ else:
244
+ image_metadata.additional_metadata[key] = value
245
+
246
+ return image_metadata
@@ -5,10 +5,10 @@ Helper functions for running a tiamat processing pipeline.
5
5
  from __future__ import annotations
6
6
 
7
7
  from collections.abc import Callable, Iterable
8
- from typing import Any
8
+ from typing import Any, Mapping
9
9
 
10
10
  from .io import ImageAccessor, ImageResult
11
- from .metadata import ImageMetadata
11
+ from .metadata import ImageMetadata, update_metadata_from_dict
12
12
  from .readers.factory import get_reader
13
13
  from .readers.protocol import ImageReader
14
14
  from .transformers.protocol import Transformer
@@ -29,6 +29,7 @@ class Pipeline:
29
29
  image_transformers: Iterable[Transformer] | None = None,
30
30
  reader_factory: Callable[[str], ImageReader] | None = None,
31
31
  auto_register_default_readers: bool = True,
32
+ metadata_overrides: Mapping[str, Any] | None = None,
32
33
  ):
33
34
  """
34
35
  Initializes the Pipeline.
@@ -41,6 +42,8 @@ class Pipeline:
41
42
  Cannot be used together with `transformers`.
42
43
  reader_factory (Callable[[str], ImageReader] | None): Function returning a reader for a given file name.
43
44
  auto_register_default_readers (bool): Whether to auto-register default readers on pipeline call.
45
+ metadata_overrides (Mapping[str, Any] | None): Optional metadata values that override or extend
46
+ metadata returned by the reader. Unknown keys are stored in ``additional_metadata``.
44
47
  """
45
48
  if transformers:
46
49
  assert (
@@ -60,6 +63,8 @@ class Pipeline:
60
63
  self.reader_factory = reader_factory or get_reader
61
64
  self.auto_register_default_readers = auto_register_default_readers
62
65
 
66
+ self.metadata_overrides = metadata_overrides if metadata_overrides is not None else {}
67
+
63
68
  def __call__(
64
69
  self,
65
70
  file_name: str,
@@ -87,7 +92,7 @@ class Pipeline:
87
92
  reader = self.reader_factory(file_name, **reader_kwargs)
88
93
 
89
94
  # Forward rollout of metadata through transformers
90
- metadata = [reader.read_metadata()]
95
+ metadata = [update_metadata_from_dict(reader.read_metadata(), self.metadata_overrides)]
91
96
 
92
97
  for transformer in self.transformers:
93
98
  # Check for transformers that do not implement transform_metadata
@@ -135,10 +140,11 @@ class Pipeline:
135
140
  from dataclasses import replace
136
141
 
137
142
  reader = self.reader_factory(file_name, **reader_kwargs)
138
- metadata = reader.read_metadata()
143
+ metadata = update_metadata_from_dict(reader.read_metadata(), self.metadata_overrides)
139
144
  # backwards pass through the transformers to transform the accessor
140
145
  for transformer in self.transformers:
141
146
  if hasattr(transformer, "transform_metadata"):
142
147
  # check for transformers that do not implement transform_metadata
143
148
  metadata = transformer.transform_metadata(metadata=replace(metadata))
149
+
144
150
  return metadata
@@ -49,9 +49,13 @@ def expand_to_length(value: Any, length: int) -> list[Any]:
49
49
  Returns:
50
50
  List of length `length`.
51
51
  """
52
- if not isinstance(value, (list, tuple, np.ndarray)):
53
- return [value] * length
54
- elif len(value) == 1:
52
+
53
+ if np.ndim(value) == 0:
54
+ if isinstance(value, np.ndarray):
55
+ return [value.item()] * length
56
+ else:
57
+ return [value] * length
58
+ if len(value) == 1:
55
59
  return [value[0]] * length
56
60
  return value
57
61
 
@@ -187,7 +187,9 @@ class ImageStackReader(ImageReader):
187
187
  """
188
188
  from tiamat.readers.processing import expand_to_length
189
189
 
190
- if slice_spacing is None:
190
+ if hasattr(spacing, "__len__") and len(spacing) == 3:
191
+ return spacing
192
+ elif slice_spacing is None:
191
193
  spacing_2d = expand_to_length(spacing, 2)
192
194
  assert (
193
195
  spacing_2d[0] == spacing_2d[1]
@@ -757,34 +759,46 @@ class VolumeStackReader(ImageReader):
757
759
 
758
760
  out_image[tuple(index_to)] = array[tuple(index_from)]
759
761
 
760
- # Build volume stack
761
- cur_z_offset = 0
762
+ # Current offset each subvolume
763
+ volume_z_offset = 0
764
+
765
+ # Current coverage of read image data
766
+ coverage_offset = z_from
767
+
768
+ # Iterate all subvolumes
762
769
  for handle, shape in zip(self.ordered_subvolume_handles, self.subvolume_shapes):
770
+ # Size of the current subvolume
763
771
  z_size = shape[z_dim]
764
772
 
765
- # Use only slice handles with z slice overlap
766
- if cur_z_offset + z_size > z_from and cur_z_offset < z_to:
773
+ # Everything read
774
+ if coverage_offset >= z_to:
775
+ break
767
776
 
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)
777
+ # Access only required subvolumes that lay in the accessor range and are not covered yet
778
+ if volume_z_offset + z_size > coverage_offset and volume_z_offset < z_to:
779
+
780
+ # Define access slice for the subvolume
781
+ from_ix = coverage_offset - volume_z_offset
782
+ to_ix = min(z_to - volume_z_offset, z_size)
771
783
 
772
784
  # Access subvolume and read from it
773
785
  tmp_accessor = replace(accessor, z=(from_ix, to_ix))
774
786
 
775
- # print("VolumeStackReader", accessor)
776
787
  tmp_image = handle.read_image(accessor=tmp_accessor)
777
788
 
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
789
+ # Position result in the output array
790
+ scaled_z_offset = math.floor(max(coverage_offset - z_from, 0) * image_scales[-1])
782
791
  insert_array(tmp_image, scaled_z_offset)
783
792
 
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
793
+ # Actual coverage of the newly read image data
794
+ tmp_coverage = tmp_image.shape[z_dim]
795
+ scaled_coverage = math.floor(tmp_coverage / image_scales[-1])
796
+
797
+ # Update total coverage of read image data
798
+ coverage_offset = coverage_offset + scaled_coverage
799
+
800
+ # Prepare offset for the next subvolume
801
+ volume_z_offset += z_size
788
802
 
789
803
  return out_image
790
804