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.
@@ -0,0 +1,851 @@
1
+ """
2
+ Reader for image stacks and volume stacks.
3
+ """
4
+
5
+ from __future__ import annotations
6
+
7
+ import math
8
+ import re
9
+ from collections import defaultdict
10
+ from collections.abc import Callable, Iterable
11
+ from functools import cached_property, partial
12
+ from typing import Any
13
+
14
+ import numpy as np
15
+
16
+ from tiamat.cache import instance_cache, instance_cached_property
17
+ from tiamat.io import ImageAccessor
18
+ from tiamat.metadata import ImageMetadata, dimensions
19
+ from tiamat.readers.factory import get_reader
20
+ from tiamat.readers.protocol import ImageReader
21
+
22
+
23
+ def find_slices(fnames: str) -> list[str]:
24
+ """Find and sort slice files matching a glob pattern.
25
+
26
+ Args:
27
+ fnames (str): Unix shell-compatible file pattern.
28
+
29
+
30
+ Returns:
31
+ list[str]: Sorted list of file paths.
32
+ """
33
+ import glob
34
+
35
+ return sorted(glob.glob(fnames))
36
+
37
+
38
+ def compile_identifier(identifier: str | None) -> re.Pattern | None: #
39
+ """
40
+ Compile a regex pattern for extracting identifiers from file names.
41
+
42
+ Args:
43
+ identifier (str | None): Regex pattern with a capture group, or None.
44
+
45
+ Returns:
46
+ re.Pattern | None: Compiled regex pattern, or None if input is None.
47
+ """
48
+ if identifier is None:
49
+ return None
50
+ else:
51
+ # Parse the regex and see if there are any groups present
52
+ if "(" not in identifier:
53
+ # Add group if no group is present
54
+ identifier = f".*({identifier}).*"
55
+ return re.compile(identifier)
56
+
57
+
58
+ def get_reader_identifier(fname: str, identifier: re.Pattern) -> str:
59
+ """
60
+ Extract a reader identifier from a filename using a regex.
61
+
62
+ Args:
63
+ fname (str): Filename to match.
64
+ identifier (re.Pattern): Compiled regex pattern with a capture group.
65
+
66
+ Returns:
67
+ str: Extracted identifier.
68
+
69
+ Raises:
70
+ ValueError: If no match is found.
71
+ """
72
+ match = identifier.search(fname)
73
+ if not match:
74
+ raise ValueError(f'No match for identifier "{identifier}" in filename "{fname}"')
75
+
76
+ return match.group(1)
77
+
78
+
79
+ def select_slice_ix(
80
+ accessor: ImageAccessor, metadata: ImageMetadata, num_slices: int, slice_spacing: float = 1.0
81
+ ) -> list[int]:
82
+ """
83
+ Select slice indices for stack access given spacing and scale.
84
+
85
+ Args:
86
+ accessor (ImageAccessor): Accessor specifying slicing and scaling.
87
+ metadata (ImageMetadata): Metadata of the image stack.
88
+ num_slices (int): Number of available slices.
89
+ slice_spacing (float, optional): Spacing between slices. Defaults to 1.0.
90
+
91
+ Returns:
92
+ list[int]: Selected slice indices.
93
+
94
+ Raises:
95
+ AssertionError: If metadata does not represent a 3D image.
96
+ """
97
+ from tiamat.readers.processing import expand_to_length
98
+ from tiamat.transformers.coordinates import resolve_coordinate_slice
99
+
100
+ spatial_dims = metadata.spatial_dimensions
101
+
102
+ assert len(spatial_dims) == 3, "Only able to perform stack slicing for 3D images"
103
+
104
+ z_scale = expand_to_length(accessor.scale, 3)[-1] # x, y, z
105
+ z_shape = metadata.shape[spatial_dims[0]]
106
+ z_from, z_to = resolve_coordinate_slice(accessor.z, z_shape)
107
+
108
+ # Calculate minimum and maximum slice index to use
109
+ min_ix = z_from / slice_spacing
110
+ max_ix = z_to / slice_spacing
111
+
112
+ # Define step between slice indices to pick
113
+ step = 1 / z_scale
114
+ size = (z_to - z_from) / slice_spacing
115
+
116
+ # Start index is the center of the size or step (depending on which is smaller)
117
+ start_ix = min_ix + min(size, step) / 2
118
+
119
+ # Select indices starting with start_ix and step size
120
+ selected_ix = []
121
+ ix = start_ix
122
+ while True:
123
+ selected_ix.append(int(min(ix, min(max_ix, num_slices - 1))))
124
+ ix = ix + step
125
+ # Break condition accounting for rounding errors
126
+ if (ix - start_ix) + min(size, step) / 2 >= size:
127
+ break
128
+
129
+ return selected_ix
130
+
131
+
132
+ class ImageStackReader(ImageReader):
133
+ """Reader for stacks of 2D slices forming a 3D volume."""
134
+
135
+ def __init__(
136
+ self,
137
+ fnames: str | Iterable[str],
138
+ reader_identifier: str = None,
139
+ reader_factory: (
140
+ Callable[[str], ImageReader] | list[Callable[[str], ImageReader]] | dict[str, Callable[[str], ImageReader]]
141
+ ) = None,
142
+ slice_spacing: float = None,
143
+ stack_dimension: str = dimensions.Z,
144
+ missing_section_interpolation: str | None = None,
145
+ missing_section_fill_value: int | float = 0,
146
+ **reader_kwargs,
147
+ ) -> None:
148
+ """
149
+ Initialize an ImageStackReader.
150
+
151
+ Args:
152
+ fnames (str | Iterable[str]): File pattern or iterable of filenames.
153
+ reader_identifier (str | None, optional): Regex identifier for slice grouping.
154
+ reader_factory (Callable | list | dict, optional): Factory for slice readers.
155
+ slice_spacing (float | None, optional): Slice spacing. Defaults to isotropic spacing.
156
+ stack_dimension (str, optional): Dimension along which slices are stacked. Defaults to Z.
157
+ missing_section_interpolation (str | None, optional): Strategy for missing slices.
158
+ missing_section_fill_value (int | float, optional): Fill value for missing slices.
159
+ **reader_kwargs: Extra kwargs passed to reader factory.
160
+ """
161
+ self.fnames = fnames
162
+ self.reader_factory = reader_factory or get_reader
163
+
164
+ if isinstance(self.reader_factory, dict):
165
+ assert reader_identifier is not None
166
+ self.compiled_identifier = compile_identifier(reader_identifier)
167
+
168
+ self.slice_spacing = slice_spacing
169
+ self.stack_dimension = stack_dimension
170
+ self.missing_section_interpolation = missing_section_interpolation
171
+ self.missing_section_fill_value = missing_section_fill_value
172
+ self.reader_kwargs = reader_kwargs
173
+
174
+ @staticmethod
175
+ def fill_spacing(slice_spacing: float | None, spacing: Iterable[float]) -> tuple[float, float, float]:
176
+ """
177
+ Fill spacing for 3D stack.
178
+
179
+
180
+ Args:
181
+ slice_spacing (float | None): Explicit slice spacing.
182
+ spacing (Iterable[float]): In-plane spacing.
183
+
184
+
185
+ Returns:
186
+ tuple[float, float, float]: Full 3D spacing.
187
+ """
188
+ from tiamat.readers.processing import expand_to_length
189
+
190
+ if slice_spacing is None:
191
+ spacing_2d = expand_to_length(spacing, 2)
192
+ assert (
193
+ spacing_2d[0] == spacing_2d[1]
194
+ ), "StackReader assumes isotropic image spacing if slice_spacing is not provided"
195
+ return (*spacing_2d, spacing_2d[0])
196
+ else:
197
+ return (*expand_to_length(spacing, 2), slice_spacing)
198
+
199
+ def selected_slice_handles(self, slice_ix: Iterable[int]) -> list[ImageReader]:
200
+ """
201
+ select slice readers for given indices.
202
+
203
+ Args:
204
+ slice_ix (Iterable[int]): Slice indices.
205
+
206
+ Returns:
207
+ list[ImageReader]: Readers for selected slices.
208
+ """
209
+ from tiamat.readers.memory import ConstantReader
210
+
211
+ selected_slices = [self.slices[i] for i in slice_ix]
212
+
213
+ reader_list = []
214
+ if isinstance(self.reader_factory, dict):
215
+ # Loop over all selected files and assign corresponding reader via the identifier
216
+
217
+ for fname in selected_slices:
218
+ if fname is None:
219
+ # Missing section
220
+ reader_list.append(ConstantReader(self.missing_section_fill_value, self.prototype_metadata))
221
+ else:
222
+ # Existing section needs corresponding reader
223
+ identifier = get_reader_identifier(fname, self.compiled_identifier)
224
+ factory = self.reader_factory[identifier]
225
+ reader_list.append(factory(fname))
226
+
227
+ elif isinstance(self.reader_factory, (tuple, list)):
228
+ # Map each slice to reader at same slice index
229
+ selected_readers = [self.reader_factory[i] for i in slice_ix]
230
+ for factory, fname in zip(selected_readers, selected_slices):
231
+ reader_list.append(factory(fname))
232
+
233
+ else:
234
+ # Use same reader for all selected slices
235
+ for fname in selected_slices:
236
+ if fname is None:
237
+ reader_list.append(ConstantReader(self.missing_section_fill_value, self.prototype_metadata))
238
+ else:
239
+ reader_list.append(self.reader_factory(fname))
240
+
241
+ return reader_list
242
+
243
+ @property
244
+ def ordered_slice_handles(self):
245
+ """All slice handles in order."""
246
+ return self.selected_slice_handles(range(len(self.slices)))
247
+
248
+ @property
249
+ def prototype_slice_handle(self) -> ImageReader:
250
+ """Prototype slice handle for metadata inspection."""
251
+ selected_handles = self.selected_slice_handles([0])
252
+
253
+ return selected_handles[0]
254
+
255
+ @instance_cached_property
256
+ def prototype_metadata(self) -> ImageMetadata:
257
+ """Metadata from a prototype slice."""
258
+ metadata = self.prototype_slice_handle.read_metadata()
259
+
260
+ return metadata
261
+
262
+ @instance_cache
263
+ def read_metadata(self) -> ImageMetadata:
264
+ """Read metadata for the stack."""
265
+ from dataclasses import replace
266
+
267
+ # Load metadata from an arbitrary prototype slice
268
+ metadata = replace(self.prototype_metadata)
269
+
270
+ # Set file path
271
+ metadata.file_path = self.fnames
272
+
273
+ # Expand metadata for stack by simply expanding the shape
274
+ metadata.shape = tuple([self.num_slices, *metadata.shape])
275
+
276
+ # Set spacing
277
+ metadata.spacing = ImageStackReader.fill_spacing(self.slice_spacing, metadata.spacing)
278
+
279
+ # Set scales
280
+ metadata.scales = self.scales
281
+
282
+ metadata.dimensions = [
283
+ self.stack_dimension,
284
+ ] + list(metadata.dimensions)
285
+
286
+ metadata.additional_metadata["stack_dimension"] = self.stack_dimension
287
+
288
+ return metadata
289
+
290
+ def read_image(self, accessor: ImageAccessor) -> np.ndarray:
291
+ """Read stacked image for given accessor."""
292
+ from dataclasses import replace
293
+
294
+ metadata = self.read_metadata()
295
+
296
+ # Request only subset of slice handles neded for the requested scale
297
+ selected_slice_ix = select_slice_ix(accessor, metadata, self.num_slices)
298
+ slice_handles = self.selected_slice_handles(selected_slice_ix)
299
+
300
+ if len(slice_handles) == 0:
301
+ raise Exception("Requested empty stack")
302
+
303
+ # Remove z axis for 2D access from metadata
304
+ tmp_accessor = replace(accessor, z=None)
305
+ # if scale is tuple, remove z scale
306
+ if isinstance(tmp_accessor.scale, (tuple, list)):
307
+ if self.stack_dimension == dimensions.X:
308
+ tmp_accessor.scale = tmp_accessor.scale[1:]
309
+ elif self.stack_dimension == dimensions.Y:
310
+ tmp_accessor.scale = (tmp_accessor.scale[0], *tmp_accessor.scale[2:])
311
+ elif self.stack_dimension == dimensions.Z:
312
+ tmp_accessor.scale = tmp_accessor.scale[:2]
313
+
314
+ # TODO: Check if unnecessary and remove
315
+ # metadata = replace(tmp_accessor.metadata)
316
+ # metadata.shape = metadata.shape[1:]
317
+ # dimension_list = list(metadata.dimensions)
318
+ # dimension_list.remove(self.stack_dimension)
319
+
320
+ # # for each scale, remove the z scale
321
+ # if metadata.scales is not None:
322
+ # scales = list(metadata.scales)
323
+ # for i, s in enumerate(scales):
324
+ # if self.stack_dimension == dimensions.X:
325
+ # scales[i] = s[1:]
326
+ # elif self.stack_dimension == dimensions.Y:
327
+ # scales[i] = (s[0], *s[2:])
328
+ # elif self.stack_dimension == dimensions.Z:
329
+ # scales[i] = s[:2]
330
+ # else:
331
+ # raise ValueError(f"Unknown stack dimension {self.stack_dimension}")
332
+ # metadata.scales = tuple(scales)
333
+
334
+ # metadata.dimensions = dimension_list
335
+ # tmp_accessor.metadata = metadata
336
+
337
+ first_result = slice_handles[0].read_image(accessor=tmp_accessor)
338
+ # For efficiency, create empty array first, then write remaining data into arrays.
339
+ image = np.empty(
340
+ shape=([len(slice_handles), *first_result.shape]),
341
+ dtype=first_result.dtype,
342
+ )
343
+
344
+ # Reuse first result
345
+ image[0] = first_result
346
+ # Read and stack all remaining images.
347
+ for i, handle in enumerate(slice_handles[1:], 1):
348
+ image[i] = handle.read_image(accessor=tmp_accessor)
349
+
350
+ return image
351
+
352
+ @property
353
+ def file_handle(self) -> ImageReader:
354
+ """Representative file handle."""
355
+ return self.prototype_slice_handle
356
+
357
+ @cached_property
358
+ def slices(self) -> list[str | None]:
359
+ """Return list of slices, optionally with interpolation for missing sections."""
360
+ if hasattr(self.fnames, "__iter__") and not isinstance(self.fnames, str):
361
+ available_slices = list(self.fnames)
362
+ else:
363
+ available_slices = find_slices(fnames=self.fnames)
364
+
365
+ if self.compiled_identifier is None:
366
+ if isinstance(self.reader_factory, dict):
367
+ raise Exception("Using a dictionary as reader_factory requires a reader_identifier to be provided")
368
+ if self.missing_section_interpolation is None:
369
+ return available_slices
370
+ else:
371
+ raise Exception(
372
+ f"{self.missing_section_interpolation} missing_section_interpolation"
373
+ "requires reader_identifier to be provided"
374
+ )
375
+ else:
376
+ # Sort available slices by their reader_identifier
377
+ if isinstance(self.reader_factory, dict):
378
+ available_slices = [
379
+ f
380
+ for f in available_slices
381
+ if get_reader_identifier(f, self.compiled_identifier) in self.reader_factory.keys()
382
+ ]
383
+
384
+ available_keys = [int(get_reader_identifier(f, self.compiled_identifier)) for f in available_slices]
385
+ sorted_ix = np.argsort(available_keys)
386
+
387
+ if self.missing_section_interpolation is None:
388
+ # Only return available slices ordered by their identifier
389
+ ordered_slices = [available_slices[k] for k in sorted_ix]
390
+ else:
391
+ # Perform interpolation of gaps between ordered slices
392
+ ordered_slices = [available_slices[sorted_ix[0]]]
393
+
394
+ for i in range(len(available_keys) - 1):
395
+ gap = int(available_keys[sorted_ix[i + 1]] - available_keys[sorted_ix[i]])
396
+ missing = max(gap - 1, 0)
397
+
398
+ if missing >= 1:
399
+ if self.missing_section_interpolation.lower() == "nearest":
400
+ # Nearest neighbor interplation of missing slices
401
+ ordered_slices += [available_slices[sorted_ix[i]]] * math.ceil(missing / 2)
402
+ ordered_slices += [available_slices[sorted_ix[i + 1]]] * math.floor(missing / 2)
403
+ elif self.missing_section_interpolation.lower() == "constant":
404
+ # Fill gaps with None (will be filled with fill value later)
405
+ ordered_slices += [None] * missing
406
+ else:
407
+ raise AttributeError(
408
+ f"Unknown missing_section_interpolation: {self.missing_section_interpolation}"
409
+ )
410
+
411
+ ordered_slices.append(available_slices[sorted_ix[i + 1]])
412
+
413
+ return ordered_slices
414
+
415
+ @cached_property
416
+ def num_slices(self) -> int:
417
+ """Number of slices."""
418
+
419
+ return len(self.slices)
420
+
421
+ @classmethod
422
+ def check_file(cls, fname: str | list[str]) -> bool | int | float:
423
+ # StackReader requires initialization before being able to check the files
424
+ # TODO: Maybe check if fname refers to a list of files. Check if any readers
425
+ # exists for this filetype and return this one
426
+ return False
427
+
428
+ @classmethod
429
+ def from_json(cls, args: dict[str, Any], reader_post_creation_hook=None) -> Callable:
430
+ """Construct reader from JSON config."""
431
+ from tiamat.serialization import get_reader_from_config
432
+
433
+ reader_factory = args.get("reader_factory")
434
+
435
+ if isinstance(reader_factory, dict):
436
+ if "class" in reader_factory.keys():
437
+ # Single reader
438
+ reader = get_reader_from_config(reader_factory, reader_post_creation_hook=reader_post_creation_hook)
439
+ else:
440
+ # Stack of readers
441
+ reader = dict(
442
+ (k, get_reader_from_config(r, reader_post_creation_hook=reader_post_creation_hook))
443
+ for k, r in reader_factory.items()
444
+ )
445
+ elif hasattr(reader_factory, "__iter__"):
446
+ reader = tuple(
447
+ get_reader_from_config(r, reader_post_creation_hook=reader_post_creation_hook) for r in reader_factory
448
+ )
449
+ elif reader_factory is None:
450
+ reader = get_reader_from_config(reader_factory, reader_post_creation_hook=reader_post_creation_hook)
451
+ else:
452
+ raise Exception(f"Can't parse reader {reader}")
453
+
454
+ if reader_post_creation_hook is None:
455
+ return partial(
456
+ cls,
457
+ reader_factory=reader,
458
+ slice_spacing=float(args.get("slice_spacing")),
459
+ reader_identifier=args.get("reader_identifier"),
460
+ stack_dimension=args.get("stack_dimension", dimensions.Z),
461
+ missing_section_interpolation=args.get("missing_section_interpolation"),
462
+ missing_section_fill_value=args.get("missing_section_fill_value", 0),
463
+ )
464
+ else:
465
+ return partial(
466
+ reader_post_creation_hook,
467
+ cls,
468
+ reader_factory=reader,
469
+ slice_spacing=float(args.get("slice_spacing")),
470
+ reader_identifier=args.get("reader_identifier"),
471
+ stack_dimension=args.get("stack_dimension", dimensions.Z),
472
+ missing_section_interpolation=args.get("missing_section_interpolation"),
473
+ missing_section_fill_value=args.get("missing_section_fill_value", 0),
474
+ )
475
+
476
+ @cached_property
477
+ def scales(self) -> list[tuple[float, float, float]] | None:
478
+ """Return scales of the image stack.
479
+ To improve io, the scale along the stacked axis is set to 1.0
480
+ """
481
+
482
+ # for now, assert scale is same for all slices
483
+ metadata_first_slice = self.prototype_slice_handle.read_metadata()
484
+
485
+ if not hasattr(metadata_first_slice, "scales"):
486
+ return None
487
+ if metadata_first_slice.scales is None:
488
+ return None
489
+
490
+ spacing_3d = ImageStackReader.fill_spacing(self.slice_spacing, metadata_first_slice.spacing)
491
+ spacing = min(spacing_3d[0], spacing_3d[1])
492
+ slice_spacing = spacing_3d[2]
493
+
494
+ # TODO: make shure position of z is correct
495
+ scales = metadata_first_slice.scales
496
+
497
+ min_scale = 1.0 / self.num_slices
498
+
499
+ if isinstance(scales[0], Iterable):
500
+ scales = [(*s[:2], max(min((slice_spacing * s[0]) / spacing, 1.0), min_scale), *s[2:]) for s in scales]
501
+ elif isinstance(scales[0], (int, float)):
502
+ scales = [(s, s, max(min((slice_spacing * s) / spacing, 1.0), min_scale)) for s in scales]
503
+
504
+ return scales
505
+
506
+
507
+ class VolumeStackReader(ImageReader):
508
+ """
509
+ Reader for stacks of sub-volumes forming a larger 3D volume.
510
+
511
+
512
+ This reader concatenates multiple 3D sub-volumes along the Z axis (or, more
513
+ generally, along the first spatial dimension reported by the prototype
514
+ metadata), producing a single larger volume. Each sub-volume is read via a
515
+ provided reader factory and stitched together on-the-fly during reads.
516
+
517
+
518
+ Notes:
519
+ - If a mapping (``dict``) of reader factories is provided, files are
520
+ grouped by an identifier extracted from their filenames using
521
+ ``reader_identifier`` (a regex with a capture group).
522
+ - If multiple files match the same identifier key, the corresponding
523
+ factory is called with a ``tuple[str, ...]`` (see code comments).
524
+ """
525
+
526
+ def __init__(
527
+ self,
528
+ fnames: str | Iterable[str],
529
+ flag_const_shape: bool = False,
530
+ reader_identifier: str | None = None,
531
+ reader_factory: (
532
+ Callable[[str], ImageReader]
533
+ | Iterable[Callable[[str], ImageReader]]
534
+ | dict[str, Callable[[str], ImageReader]]
535
+ ) = None,
536
+ reader_kwargs: dict[str, Any] | None = None,
537
+ ) -> None:
538
+ """
539
+ Initialize a VolumeStackReader.
540
+
541
+ Args:
542
+ fnames (str | Iterable[str]): File pattern or iterable of filenames.
543
+ flag_const_shape (bool, optional): Whether all sub-volumes have the same shape. Defaults to False.
544
+ reader_identifier (str | None, optional): Regex for identifying files in a dict of factories.
545
+ reader_factory (Callable | Iterable | Dict, optional): Factory or factories to create sub-volume readers.
546
+ reader_kwargs (dict[str, Any], optional): Additional arguments passed to the factories.
547
+ """
548
+
549
+ self.fnames = fnames
550
+ self.flag_const_shape = flag_const_shape
551
+ self.reader_factory = reader_factory or get_reader
552
+
553
+ if isinstance(self.reader_factory, dict):
554
+ assert reader_identifier is not None
555
+ self.compiled_identifier = compile_identifier(reader_identifier)
556
+
557
+ self.reader_kwargs = reader_kwargs or {}
558
+
559
+ @cached_property
560
+ def slices(self) -> list[str]:
561
+ """
562
+ Return an ordered list of sub-volume file specifications.
563
+
564
+ If ``fnames`` is an iterable (and not a string), it is returned as a
565
+ list. Otherwise, the glob pattern in ``fnames`` is expanded and sorted.
566
+
567
+ Returns:
568
+ list[str]: List of file paths (or path specs) for sub-volumes.
569
+ """
570
+ if hasattr(self.fnames, "__iter__") and not isinstance(self.fnames, str):
571
+ return [fname for fname in self.fnames]
572
+ else:
573
+ return find_slices(fnames=self.fnames)
574
+
575
+ @cached_property
576
+ def num_slices(self) -> int:
577
+ """
578
+ Number of sub-volumes.
579
+
580
+ Returns:
581
+ int: Number of entries in :pyattr:`slices`.
582
+ """
583
+ return len(self.slices)
584
+
585
+ @cached_property
586
+ def _file_names_per_reader_identifier(self):
587
+ """
588
+ Map files to their reader identifiers.
589
+
590
+ Returns:
591
+ dict[str, list[str]]: Mapping of identifier -> list of matching file paths.
592
+ """
593
+ file_matches = defaultdict(list)
594
+ for fname in self.slices:
595
+ file_matches[get_reader_identifier(fname, self.compiled_identifier)].append(fname)
596
+ return file_matches
597
+
598
+ @property
599
+ def ordered_subvolume_handles(self) -> list[ImageReader]:
600
+ """
601
+ Create ImageReader handles for all sub-volumes, in order.
602
+
603
+ Behavior depends on `reader_factory` type:
604
+ - dict[str, Callable]: For each sorted key, find matching files.
605
+ Single or multiple files are passed to the factory.
606
+ - Iterable[Callable]: Zip slices and factories.
607
+ - Callable: Use the same factory for all slices.
608
+
609
+ Returns:
610
+ list[ImageReader]: List of instantiated sub-volume readers.
611
+
612
+ Notes:
613
+ - If a key maps to multiple files, the factory must accept a
614
+ sequence of paths.
615
+ # NOTE: This is implicit in the original code path.
616
+ """
617
+ if isinstance(self.reader_factory, dict):
618
+ reader_list = []
619
+ for k in sorted(self.reader_factory.keys()):
620
+ factory = self.reader_factory[k]
621
+ # Find all files that match k
622
+ file_matches = tuple(self._file_names_per_reader_identifier[k])
623
+ if len(file_matches) > 1:
624
+ reader_list.append(factory(file_matches))
625
+ if len(file_matches) == 1:
626
+ reader_list.append(factory(file_matches[0]))
627
+ return reader_list
628
+
629
+ elif hasattr(self.reader_factory, "__iter__"):
630
+ return [factory(fname, **self.reader_kwargs) for fname, factory in zip(self.slices, self.reader_factory)]
631
+
632
+ else:
633
+ return [self.reader_factory(fname, **self.reader_kwargs) for fname in self.slices]
634
+
635
+ @property
636
+ def prototype_subvolume_handle(self) -> ImageReader:
637
+ """
638
+ Return the first sub-volume handle as a prototype for metadata.
639
+
640
+ Returns:
641
+ ImageReader: The first instantiated sub-volume reader.
642
+ """
643
+ return self.ordered_subvolume_handles[0]
644
+
645
+ @cached_property
646
+ def subvolume_shapes(self) -> list[tuple[int, ...]]:
647
+ """
648
+ Return the shapes of all sub-volumes.
649
+
650
+ Returns:
651
+ list[tuple[int, ...]]: A list of shape tuples for each sub-volume.
652
+ """
653
+
654
+ subvolume_handles = self.ordered_subvolume_handles
655
+
656
+ if self.flag_const_shape:
657
+ metadata = subvolume_handles[0].read_metadata()
658
+ # logger.debug("VolumeStackReader subvolume_shapes: %s", metadata.shape)
659
+ return [(metadata.shape) for _ in range(len(subvolume_handles))]
660
+
661
+ return [handle.read_metadata().shape for handle in subvolume_handles]
662
+
663
+ @cached_property
664
+ def shape(self) -> tuple[int, ...]:
665
+ """
666
+ Compute the composite volume shape produced by concatenating all
667
+ sub-volumes along the Z dimension (first entry of spatial dims).
668
+
669
+ Returns:
670
+ tuple[int, ...]: Shape of the stitched volume.
671
+ """
672
+ metadata = self.ordered_subvolume_handles[0].read_metadata()
673
+ z_dim = metadata.spatial_dimensions[0]
674
+
675
+ shape = list(self.subvolume_shapes[0])
676
+ for s in self.subvolume_shapes[1:]:
677
+ shape[z_dim] = shape[z_dim] + s[z_dim]
678
+
679
+ return tuple(shape)
680
+
681
+ @instance_cache
682
+ def read_metadata(self) -> ImageMetadata:
683
+ """
684
+ Read and compose metadata for the stacked volume.
685
+
686
+ Returns:
687
+ ImageMetadata: Metadata of the stitched volume.
688
+ """
689
+ from dataclasses import replace
690
+
691
+ metadata = replace(self.ordered_subvolume_handles[0].read_metadata())
692
+
693
+ metadata.file_path = self.fnames
694
+
695
+ metadata.shape = self.shape
696
+
697
+ return metadata
698
+
699
+ def read_image(self, accessor: ImageAccessor) -> np.ndarray:
700
+ """
701
+ Read the stitched volume given an accessor.
702
+
703
+ The method determines the intersection of the requested Z-slice with
704
+ each sub-volume, reads those ranges, and inserts them into an output
705
+ buffer. The output shape along Z is determined by the requested range
706
+ and scale factor.
707
+
708
+ Args:
709
+ accessor (ImageAccessor): Accessor specifying coordinates (including Z-range) and scale.
710
+
711
+ Returns:
712
+ np.ndarray: Stitched image volume.
713
+
714
+ Raises:
715
+ ValueError: If no sub-volume handles are available.
716
+ """
717
+ import math
718
+ from dataclasses import replace
719
+
720
+ from tiamat.readers.processing import (
721
+ expand_to_length,
722
+ prepare_coordinate,
723
+ )
724
+ from tiamat.transformers.coordinates import resolve_coordinate_slice
725
+
726
+ metadata = self.read_metadata()
727
+ z_dim, y_dim, x_dim = metadata.spatial_dimensions
728
+
729
+ image_z_size = self.shape[z_dim]
730
+ image_scales = expand_to_length(accessor.scale, 3) # x, y, z
731
+
732
+ z_slice = prepare_coordinate(accessor.z)
733
+ z_from, z_to = resolve_coordinate_slice(z_slice, image_z_size)
734
+
735
+ out_image = None
736
+
737
+ # TODO: We might want to support padding in the future
738
+ def insert_array(array, offset):
739
+ nonlocal out_image
740
+
741
+ if out_image is None:
742
+ out_shape = list(array.shape)
743
+ out_shape[z_dim] = math.floor((z_to - z_from) * image_scales[-1])
744
+
745
+ out_image = np.zeros(
746
+ shape=out_shape,
747
+ dtype=array.dtype,
748
+ )
749
+
750
+ z_size = min(array.shape[z_dim], out_image.shape[z_dim] - offset)
751
+
752
+ index_to = [slice(None)] * len(out_image.shape)
753
+ index_to[z_dim] = slice(offset, offset + z_size)
754
+
755
+ index_from = [slice(None)] * len(out_image.shape)
756
+ index_from[z_dim] = slice(0, z_size)
757
+
758
+ out_image[tuple(index_to)] = array[tuple(index_from)]
759
+
760
+ # Build volume stack
761
+ cur_z_offset = 0
762
+ for handle, shape in zip(self.ordered_subvolume_handles, self.subvolume_shapes):
763
+ z_size = shape[z_dim]
764
+
765
+ # Use only slice handles with z slice overlap
766
+ if cur_z_offset + z_size > z_from and cur_z_offset < z_to:
767
+
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)
771
+
772
+ # Access subvolume and read from it
773
+ tmp_accessor = replace(accessor, z=(from_ix, to_ix))
774
+
775
+ # print("VolumeStackReader", accessor)
776
+ tmp_image = handle.read_image(accessor=tmp_accessor)
777
+
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
+ insert_array(tmp_image, scaled_z_offset)
783
+
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
788
+
789
+ return out_image
790
+
791
+ @classmethod
792
+ def check_file(cls, fname: str | list[str]) -> bool | int | float:
793
+ # StackReader requires initialization before being able to check the files
794
+ # TODO: Maybe check if fname refers to a list of files. Check if any readers
795
+ # exists for this filetype and return this one
796
+ return False
797
+
798
+ @classmethod
799
+ def from_json(cls, args: dict[str, Any], reader_post_creation_hook=None) -> Callable:
800
+ """
801
+ Construct a VolumeStackReader (or wrapper) from a JSON-like config.
802
+
803
+ Args:
804
+ args (dict): Configuration dictionary.
805
+ reader_post_creation_hook (Callable | None): Optional wrapper hook.
806
+
807
+ Returns:
808
+ Callable: Partial that instantiates the reader or invokes the hook.
809
+
810
+ Raises:
811
+ ValueError: If the ``reader_factory`` cannot be parsed.
812
+ """
813
+
814
+ from tiamat.serialization import get_reader_from_config
815
+
816
+ reader_factory = args.get("reader_factory")
817
+
818
+ if isinstance(reader_factory, dict):
819
+ if "class" in reader_factory.keys():
820
+ # Single reader
821
+ reader = get_reader_from_config(reader_factory, reader_post_creation_hook=reader_post_creation_hook)
822
+ else:
823
+ # Stack of readers
824
+ reader = dict(
825
+ (k, get_reader_from_config(r, reader_post_creation_hook=reader_post_creation_hook))
826
+ for k, r in reader_factory.items()
827
+ )
828
+ elif hasattr(reader_factory, "__iter__"):
829
+ reader = tuple(
830
+ get_reader_from_config(r, reader_post_creation_hook=reader_post_creation_hook) for r in reader_factory
831
+ )
832
+ elif reader_factory is None:
833
+ reader = get_reader_from_config(reader_factory, reader_post_creation_hook=reader_post_creation_hook)
834
+ else:
835
+ raise Exception(f"Can't parse reader {reader}")
836
+
837
+ if reader_post_creation_hook is None:
838
+ return partial(
839
+ cls,
840
+ flag_const_shape=args.get("flag_const_shape"),
841
+ reader_factory=reader,
842
+ reader_identifier=args.get("reader_identifier"),
843
+ )
844
+ else:
845
+ return partial(
846
+ reader_post_creation_hook,
847
+ cls,
848
+ flag_const_shape=args.get("flag_const_shape"),
849
+ reader_factory=reader,
850
+ reader_identifier=args.get("reader_identifier"),
851
+ )