tiamat-python 0.1.8__py3-none-any.whl

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.
tiamat/readers/zarr.py ADDED
@@ -0,0 +1,353 @@
1
+ """
2
+ Reader for OME-Zarr (Zarr v3 / OME-NGFF ≥0.5).
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import os
9
+ import zipfile
10
+ from functools import cached_property
11
+ from typing import Any, Dict, List, Tuple
12
+
13
+ import numpy as np
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
+ try:
17
+ import zarr # pylint: disable=import-error
18
+ from zarr.storage import ZipStore # pylint: disable=import-error
19
+
20
+ _ZARR_AVAILABLE = True
21
+ except Exception: # pragma: no cover
22
+ zarr = None # pylint: disable=import-error
23
+ ZipStore = None # pylint: disable=import-error
24
+ _ZARR_AVAILABLE = False
25
+
26
+ from tiamat.cache import instance_cache
27
+ from tiamat.io import ImageAccessor
28
+ from tiamat.metadata import ImageMetadata
29
+ from tiamat.readers.protocol import ImageReader
30
+
31
+
32
+ def _axis_to_dim(axis_name: str, md) -> Any:
33
+ """
34
+ Map ome-zarr specific axis labels to tiamat dimensions.
35
+ """
36
+ n = axis_name.lower()
37
+ return {
38
+ "x": md.dimensions.X,
39
+ "y": md.dimensions.Y,
40
+ "z": md.dimensions.Z,
41
+ "c": md.dimensions.C,
42
+ "t": md.dimensions.T,
43
+ }.get(n, md.dimensions.C)
44
+
45
+
46
+ class OmeZarrReader(ImageReader):
47
+ def __init__(self, fname: str):
48
+ self.fname = fname
49
+
50
+ @classmethod
51
+ def check_file(cls, fname) -> bool | int | float:
52
+ if not _ZARR_AVAILABLE:
53
+ # zarr not installed, we cannot do anything.
54
+ return False
55
+
56
+ lower = str(fname).lower()
57
+ is_zip = lower.endswith(".zarr.zip") or lower.endswith(".ome.zarr.zip")
58
+ is_dir_like = lower.endswith(".zarr") or lower.endswith(".ome.zarr")
59
+
60
+ if not (is_zip or is_dir_like):
61
+ return False
62
+
63
+ # Function to load zarr.json content
64
+ def load_zarr_json(json_bytes: bytes) -> dict | None:
65
+ try:
66
+ return json.loads(json_bytes)
67
+ except Exception:
68
+ return None
69
+
70
+ zarr_data = None
71
+
72
+ if is_zip:
73
+ # Check inside ZIP
74
+ try:
75
+ with zipfile.ZipFile(fname, "r") as zf:
76
+ if "zarr.json" not in zf.namelist():
77
+ return False
78
+ with zf.open("zarr.json") as f:
79
+ zarr_data = load_zarr_json(f.read())
80
+ except Exception:
81
+ return False
82
+
83
+ elif is_dir_like:
84
+ # Check inside directory
85
+ zarr_json_path = os.path.join(fname, "zarr.json")
86
+ if not os.path.exists(zarr_json_path):
87
+ return False
88
+ try:
89
+ with open(zarr_json_path, "r", encoding="utf-8") as f:
90
+ zarr_data = json.load(f)
91
+ except Exception:
92
+ return False
93
+
94
+ # Validate JSON structure
95
+ if not isinstance(zarr_data, dict):
96
+ return False
97
+
98
+ attributes = zarr_data.get("attributes")
99
+ if not isinstance(attributes, dict):
100
+ return False
101
+
102
+ if "ome" in attributes:
103
+ return 10 # or True, depending on your scoring scheme
104
+ return False
105
+
106
+ def read_image(self, accessor: ImageAccessor) -> np.ndarray:
107
+ from tiamat.readers.processing import access_and_rescale_image
108
+
109
+ axes = self.axes_names
110
+ # Normalize accessor.scale to a sequence
111
+ raw_scale = accessor.scale
112
+ if isinstance(raw_scale, (float, int)):
113
+ # single float: treat as uniform on all spatial axes
114
+ target_xy = (float(raw_scale), float(raw_scale))
115
+ target_z = float(raw_scale)
116
+ else:
117
+ # assume sequence
118
+ seq = list(raw_scale)
119
+ if len(seq) >= 3:
120
+ # interpret as (Z, Y, X)
121
+ target_z = float(seq[0])
122
+ target_xy = (float(seq[1]), float(seq[2]))
123
+ elif len(seq) == 2:
124
+ target_z = float(min(seq))
125
+ target_xy = (float(seq[0]), float(seq[1]))
126
+ else:
127
+ # fallback: treat everything as uniform
128
+ target_xy = (float(seq[0]), float(seq[0]))
129
+ target_z = float(seq[0])
130
+
131
+ per_axis_target: List[float] = []
132
+ for a in axes:
133
+ if a == "x":
134
+ per_axis_target.append(target_xy[1])
135
+ elif a == "y":
136
+ per_axis_target.append(target_xy[0])
137
+ elif a == "z":
138
+ per_axis_target.append(target_z)
139
+ else:
140
+ per_axis_target.append(1.0)
141
+
142
+ chosen_level = self._select_level_from_target(per_axis_target)
143
+ level_factors = self._level_factors(chosen_level)
144
+ arr = self._get_level_array(chosen_level)
145
+
146
+ return access_and_rescale_image(
147
+ image=arr,
148
+ metadata=self.read_metadata(),
149
+ accessor=accessor,
150
+ image_scale=tuple(level_factors),
151
+ )
152
+
153
+ @instance_cache
154
+ def read_metadata(self) -> ImageMetadata:
155
+ from tiamat import metadata as md
156
+
157
+ dims = [_axis_to_dim(ax, md) for ax in self.axes_names]
158
+ vmin, vmax = self.value_range
159
+
160
+ return md.ImageMetadata(
161
+ image_type=md.IMAGE_TYPE_IMAGE,
162
+ shape=self.shape,
163
+ dtype=self.dtype,
164
+ file_path=self.fname,
165
+ value_range=(vmin, vmax),
166
+ spacing=self.pixel_spacing,
167
+ dimensions=dims,
168
+ scales=self.scales,
169
+ additional_metadata=self._root_attrs,
170
+ )
171
+
172
+ # ---------------- Cached / internal helpers ---------------- #
173
+
174
+ @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.")
178
+ lower = self.fname.lower()
179
+ 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")
189
+
190
+ @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 {})
194
+ return attrs
195
+
196
+ @cached_property
197
+ def _ome_meta(self) -> Dict[str, Any]:
198
+ # Prefer "ome" namespace if present, otherwise treat root attrs as container
199
+ ome = self._root_attrs.get("ome")
200
+ if isinstance(ome, dict) and ome:
201
+ return ome
202
+ return self._root_attrs
203
+
204
+ @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:
208
+ raise ValueError("OME-Zarr attributes lack a valid 'multiscales' list.")
209
+ return ms
210
+
211
+ @cached_property
212
+ def _pyramid(self) -> Dict[str, Any]:
213
+ return self._multiscales[0]
214
+
215
+ @cached_property
216
+ def axes_names(self) -> List[str]:
217
+ axes = self._pyramid.get("axes")
218
+ if isinstance(axes, list) and axes:
219
+ if isinstance(axes[0], str):
220
+ return [a.lower() for a in axes]
221
+ if isinstance(axes[0], dict):
222
+ return [str(a.get("name", "")).lower() for a in axes]
223
+ # Fallback using array rank
224
+ a0 = self._get_level_array(0)
225
+ rank = a0.ndim
226
+ if rank == 2:
227
+ return ["y", "x"]
228
+ if rank == 3:
229
+ return ["c", "y", "x"]
230
+ if rank == 4:
231
+ return ["z", "c", "y", "x"]
232
+ if rank >= 5:
233
+ return ["t", "z", "c", "y", "x"][-rank:]
234
+ return ["y", "x"]
235
+
236
+ @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:
240
+ raise ValueError("OME-Zarr multiscales.datasets is missing or empty.")
241
+ return ds
242
+
243
+ @cached_property
244
+ def dtype(self) -> np.dtype:
245
+ return self._get_level_array(0).dtype
246
+
247
+ @cached_property
248
+ def shape(self) -> Tuple[int, ...]:
249
+ return tuple(int(x) for x in self._get_level_array(0).shape)
250
+
251
+ @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)
258
+ else:
259
+ raise TypeError(f"Cannot determine value range for dtype {dt}")
260
+ return info.min, info.max
261
+
262
+ @cached_property
263
+ def pixel_spacing(self) -> Tuple[float, ...]:
264
+ # Read level-0 coordinateTransformations -> scale vector; fallback 1.0
265
+ axes = self.axes_names
266
+ transforms = self._datasets[0].get("coordinateTransformations", [])
267
+ 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]
273
+ break
274
+ if scale_vec is None:
275
+ return tuple([1.0] * len(axes))
276
+ return tuple(scale_vec)
277
+
278
+ @cached_property
279
+ def scales(self) -> List[float]:
280
+ # XY downsample factors per level (relative to level 0); fallback heuristic if XY unknown
281
+ axes = self.axes_names
282
+ y_idx = axes.index("y") if "y" in axes else None
283
+ base = self._get_level_array(0).shape
284
+ base_y = base[y_idx] if y_idx is not None else None
285
+
286
+ factors: List[float] = []
287
+ for i, _ in enumerate(self._datasets):
288
+ a = self._get_level_array(i)
289
+ if base_y is not None:
290
+ f = base_y / float(a.shape[y_idx])
291
+ factors.append(float(f))
292
+ else:
293
+ factors.append(1.0 if i == 0 else max(2.0, factors[-1] * 2))
294
+ return factors
295
+
296
+ @instance_cache
297
+ def _get_level_array(self, level: int):
298
+ ds = self._datasets[level]
299
+ rel = ds.get("path")
300
+ if not isinstance(rel, str) or not rel:
301
+ raise ValueError(f"Invalid dataset path at level {level}.")
302
+ if rel not in self._root_group:
303
+ raise ValueError(f"Dataset '{rel}' not found in Zarr group.")
304
+ return self._root_group[rel]
305
+
306
+ @cached_property
307
+ def _spatial_indices(self) -> List[int]:
308
+ order = []
309
+ for a in ("z", "y", "x"):
310
+ if a in self.axes_names:
311
+ order.append(self.axes_names.index(a))
312
+ return order
313
+
314
+ @instance_cache
315
+ def _level_factors(self, level: int) -> List[float]:
316
+ base = self._get_level_array(0).shape
317
+ cur = self._get_level_array(level).shape
318
+ factors: List[float] = []
319
+ spatial = {"z", "y", "x"}
320
+ for i, a in enumerate(self.axes_names):
321
+ if a in spatial:
322
+ factors.append(float(base[i]) / float(cur[i]))
323
+ else:
324
+ factors.append(1.0)
325
+ return factors
326
+
327
+ def _select_level_from_target(self, per_axis_target: List[float]) -> int:
328
+ spatial_idx = self._spatial_indices
329
+
330
+ def meets_target(factors: List[float]) -> bool:
331
+ return all(factors[i] >= per_axis_target[i] for i in spatial_idx)
332
+
333
+ candidates = []
334
+ for lvl in range(len(self._datasets)):
335
+ f = self._level_factors(lvl)
336
+ if meets_target(f):
337
+ score = max((f[i] for i in spatial_idx), default=1.0)
338
+ candidates.append((score, lvl))
339
+
340
+ if candidates:
341
+ candidates.sort(key=lambda t: t[0])
342
+ return candidates[0][1]
343
+
344
+ # Fall back to coarsest
345
+ coarsest = 0
346
+ coarsest_score = -np.inf
347
+ for lvl in range(len(self._datasets)):
348
+ f = self._level_factors(lvl)
349
+ score = max((f[i] for i in spatial_idx), default=1.0)
350
+ if score > coarsest_score:
351
+ coarsest_score = score
352
+ coarsest = lvl
353
+ return coarsest
@@ -0,0 +1,153 @@
1
+ """
2
+ Pipeline serialization and instantiation from configuration dictionaries.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Callable
8
+ from functools import partial
9
+ from typing import Any
10
+
11
+ from tiamat.readers.protocol import ImageReader
12
+
13
+ # Example class registry
14
+ class_registry: dict[str, type] = {}
15
+
16
+
17
+ def register_class(cls: type) -> type:
18
+ """
19
+ Decorator to register a class for safe instantiation from configuration.
20
+
21
+ Args:
22
+ cls (Type): The class to register.
23
+
24
+ Returns:
25
+ Type: The registered class.
26
+ """
27
+ class_registry[cls.__name__] = cls
28
+ return cls
29
+
30
+
31
+ def create_instance(class_name: str, args: dict[str, Any]) -> Any:
32
+ """
33
+ Safely instantiate a registered class with arguments from a configuration dictionary.
34
+
35
+ Args:
36
+ class_name (str): The name of the class to instantiate.
37
+ args (Dict[str, Any]): Initialization arguments.
38
+
39
+ Returns:
40
+ Any: The instantiated object.
41
+
42
+ Raises:
43
+ ValueError: If the class is not registered.
44
+ """
45
+ if class_name not in class_registry:
46
+ raise ValueError(f"Class '{class_name}' is not registered.")
47
+
48
+ cls = class_registry[class_name]
49
+
50
+ if hasattr(cls, "from_json"):
51
+ return cls.from_json(args)
52
+ else:
53
+ # Validate provided arguments
54
+ allowed_args = cls.__init__.__code__.co_varnames[1 : cls.__init__.__code__.co_argcount]
55
+ filtered_args = {k: v for k, v in args.items() if k in allowed_args}
56
+
57
+ return cls(**filtered_args)
58
+
59
+
60
+ def make_object_from_config(config_entry: dict) -> Any:
61
+ """
62
+ Instantiate an object from a single configuration entry.
63
+
64
+ Args:
65
+ config_entry (dict): Dictionary with "class" and optional "args" keys.
66
+
67
+ Returns:
68
+ Any: Instantiated object.
69
+
70
+ Raises:
71
+ ValueError: If the config entry is missing the "class" key.
72
+ """
73
+ class_name = config_entry.get("class")
74
+ args = config_entry.get("args", {})
75
+
76
+ if class_name is None:
77
+ raise ValueError("Config entry must contain a 'class' key.")
78
+ return create_instance(class_name, args)
79
+
80
+
81
+ def get_reader_from_config(
82
+ config_reader: dict | None, reader_post_creation_hook: Callable | None = None
83
+ ) -> Callable[..., "ImageReader"]:
84
+ """
85
+ Get a reader constructor from configuration.
86
+
87
+ Args:
88
+ config_reader dict | None: Configuration dictionary for the reader.
89
+ reader_post_creation_hook Callable | None: Hook to modify the reader after construction.
90
+
91
+ Returns:
92
+ Callable[..., Any]: A reader constructor (possibly a partial).
93
+ """
94
+
95
+ if config_reader is None:
96
+ from tiamat.readers.factory import get_reader
97
+
98
+ if reader_post_creation_hook is None:
99
+ return get_reader
100
+ else:
101
+ return partial(reader_post_creation_hook, get_reader)
102
+
103
+ from tiamat.readers.factory import get_reader_from_registry
104
+
105
+ class_name = config_reader.get("class")
106
+ if class_name is None:
107
+ raise ValueError("Reader config must contain a 'class' key.")
108
+ cls = get_reader_from_registry(class_name)
109
+ args = config_reader.get("args", {})
110
+
111
+ if hasattr(cls, "from_json"):
112
+ return cls.from_json(args, reader_post_creation_hook=reader_post_creation_hook)
113
+ else:
114
+ # Validate provided arguments
115
+ allowed_args = cls.__init__.__code__.co_varnames[1 : cls.__init__.__code__.co_argcount]
116
+ filtered_args = {k: v for k, v in args.items() if k in allowed_args}
117
+
118
+ if reader_post_creation_hook is None:
119
+ return partial(cls, **filtered_args)
120
+ else:
121
+ return partial(reader_post_creation_hook, cls, **filtered_args)
122
+
123
+
124
+ def load_pipeline_from_config(
125
+ config: dict, auto_register_default_readers: bool = True, reader_post_creation_hook: Callable | None = None
126
+ ) -> Any:
127
+ """
128
+ Construct a pipeline from a configuration dictionary.
129
+
130
+ Args:
131
+ config (dict): Configuration dictionary defining transformers and reader.
132
+ auto_register_default_readers (bool): If True, registers built-in readers.
133
+ reader_post_creation_hook (Callable | None): Optional hook for customizing the reader.
134
+
135
+ Returns:
136
+ Pipeline: The constructed pipeline.
137
+ """
138
+ from .pipeline import Pipeline
139
+
140
+ if auto_register_default_readers:
141
+ from tiamat.readers import register_all_readers
142
+
143
+ register_all_readers()
144
+
145
+ return Pipeline(
146
+ transformers=[make_object_from_config(item) for item in config.get("transformers", [])],
147
+ access_transformers=[make_object_from_config(item) for item in config.get("access_transformers", [])],
148
+ image_transformers=[make_object_from_config(item) for item in config.get("image_transformers", [])],
149
+ reader_factory=get_reader_from_config(
150
+ config.get("reader", None), reader_post_creation_hook=reader_post_creation_hook
151
+ ),
152
+ auto_register_default_readers=False,
153
+ )
File without changes