-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathnodes.py
More file actions
3276 lines (2810 loc) · 110 KB
/
nodes.py
File metadata and controls
3276 lines (2810 loc) · 110 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Node object and convenience functions for the OME-NGFF (OME-Zarr) Hierarchy."""
# TODO: remove this in the future (PEP deferred for 3.11, now 3.12?)
from __future__ import annotations
import logging
import math
import os
import shutil
from collections.abc import Generator
from copy import deepcopy
from datetime import datetime
from functools import cached_property
from pathlib import Path
from typing import (
Any,
ClassVar,
Literal,
overload,
)
import numpy as np
import xarray as xr
import zarr
from natsort import natsorted
from numpy.typing import ArrayLike, DTypeLike, NDArray
from pydantic import ValidationError
from iohub.core import ArraySpec, NGFFArray, get_implementation
from iohub.core.compat import get_ome_attrs
from iohub.core.config import ImplementationConfig
from iohub.core.errors import StoreOpenError
from iohub.core.protocol import ZarrImplementation
from iohub.core.types import StorePath
from iohub.core.utils import normalize_path, pad_shape
from iohub.ngff.display import channel_display_settings
from iohub.ngff.models import (
AcquisitionMeta,
AxisMeta,
Bioformats2RawMeta,
ChannelAxisMeta,
DatasetMeta,
ImageMeta,
ImagesMeta,
LabelColorMeta,
LabelImageMeta,
LabelsMeta,
MultiScaleMeta,
OMEROMeta,
PlateAxisMeta,
PlateMeta,
PositionLabelMeta,
RDefsMeta,
SpaceAxisMeta,
TimeAxisMeta,
TransformationMeta,
WellGroupMeta,
WellIndexMeta,
WindowDict,
)
_logger = logging.getLogger(__name__)
# Type alias for position specification tuples in create_positions
type PositionSpec = (
tuple[str, str, str]
| tuple[str, str, str, int | None]
| tuple[str, str, str, int | None, int | None]
| tuple[str, str, str, int | None, int | None, int]
)
def _is_fslike(store_path) -> bool:
"""Check if store_path is a filesystem path (str, Path, os.PathLike) vs a Store object."""
return isinstance(store_path, (str, os.PathLike))
def _open_store(
store_path,
mode: Literal["r", "r+", "a", "w", "w-"],
version: Literal["0.4", "0.5"],
implementation: str | None = None,
implementation_config: ImplementationConfig | None = None,
):
is_fs = _is_fslike(store_path)
if is_fs:
store_path = Path(store_path).resolve()
if not store_path.exists() and mode in ("r", "r+"):
raise FileNotFoundError(f"Dataset directory not found at {store_path!s}.")
if version not in ("0.4", "0.5"):
_logger.warning(
f"IOHub is only tested against OME-NGFF v0.4 and v0.5. Requested version {version} may not work properly."
)
impl = get_implementation(implementation, implementation_config)
try:
zarr_format = None
if mode in ("w", "w-") or (is_fs and mode == "a" and not store_path.exists()):
zarr_format = 2 if version == "0.4" else 3
root = impl.open_group(store_path, mode=mode, zarr_format=zarr_format)
except (FileNotFoundError, FileExistsError, PermissionError):
raise
except Exception as e:
raise StoreOpenError(f"Cannot open Zarr root group at {store_path!r}") from e
return root, impl
def _scale_integers(values: tuple[int, ...], factor: int) -> tuple[int, ...]:
"""Divide all values by factor, rounding up (ceiling division)."""
return tuple(math.ceil(v / factor) for v in values)
def _scale_dims(values: tuple[int, ...], axes: set[int]) -> tuple[int, ...]:
"""Halve values at the given indices, rounding up (ceiling division)."""
return tuple(math.ceil(v / 2) if i in axes else v for i, v in enumerate(values))
def _case_insensitive_local_fs() -> bool:
"""Check if the local filesystem is case-insensitive."""
return Path(__file__.lower()).exists() and Path(__file__.upper()).exists()
class NGFFNode:
"""A node (group level in Zarr) in an NGFF dataset."""
_MEMBER_TYPE: type[NGFFNode | NGFFArray]
_impl: ZarrImplementation
_DEFAULT_AXES: ClassVar[list] = [
TimeAxisMeta(name="T", unit="second"),
ChannelAxisMeta(name="C"),
*[SpaceAxisMeta(name=i, unit="micrometer") for i in ("Z", "Y", "X")],
]
def __init__(
self,
group: zarr.Group,
parse_meta: bool = True,
channel_names: list[str] | None = None,
axes: list[AxisMeta] | None = None,
version: Literal["0.4", "0.5"] = "0.5",
overwriting_creation: bool = False,
impl: ZarrImplementation | None = None,
):
if channel_names is not None:
self.channel_names = channel_names
elif not parse_meta:
raise ValueError("Channel names need to be provided or in metadata.")
if axes is not None:
self.axes = axes
self._group = group
self._overwrite = overwriting_creation
self._version: Literal["0.4", "0.5"] = version
self._impl = impl
if self._impl is None:
raise TypeError(
f"{type(self).__name__} requires an impl= argument. "
"Use open_ome_zarr() rather than constructing nodes directly."
)
if parse_meta:
self._parse_meta()
# TODO: properly check the underlying storage type
# This works for now as only the local filesystem is supported
self._case_insensitive_fs = _case_insensitive_local_fs()
@cached_property
def axes(self):
"""Axes metadata. Lazily resolves to defaults if not set."""
return self._DEFAULT_AXES
@cached_property
def channel_names(self):
"""Channel names. Subclasses override for lazy resolution."""
raise AttributeError("Channel names not available. Provide channel_names or ensure metadata is parseable.")
@property
def zgroup(self):
"""Corresponding Zarr group of the node."""
return self._group
@property
def zattrs(self):
"""Zarr attributes of the node.
Assignments will modify the metadata file.
"""
return self._group.attrs
@property
def maybe_wrapped_ome_attrs(self):
"""Container of OME metadata attributes."""
return get_ome_attrs(self.zattrs)
@property
def version(self) -> Literal["0.4", "0.5"]:
"""NGFF version"""
return self._version
@property
def _parent_path(self):
"""The parent Zarr group path of the node.
None for the root node.
"""
if self._group.name == "/":
return None
else:
return Path(self._group.name).parent
@property
def _member_names(self):
"""Array keys for leaf nodes (Position/PositionLabel), group keys for container nodes."""
if issubclass(self._MEMBER_TYPE, NGFFArray):
return self.array_keys()
return self.group_keys()
@property
def _child_attrs(self):
"""Attributes to pass on when constructing child type instances"""
return {
"version": self._version,
"axes": self.axes,
"channel_names": self.channel_names,
"overwriting_creation": self._overwrite,
"impl": self._impl,
}
def __len__(self):
return len(self._member_names)
def __getitem__(self, key):
key = normalize_path(str(key))
levels = len(key.split("/")) - 1
item_type = self._MEMBER_TYPE
for _ in range(levels):
item_type = item_type._MEMBER_TYPE
if issubclass(item_type, NGFFArray):
try:
handle = self._impl.open_array(self._group, key)
except (FileNotFoundError, KeyError) as err:
raise KeyError(key) from err
return item_type.from_handle(handle, self._impl)
else:
znode = self.zgroup.get(key)
if not znode:
raise KeyError(key)
return item_type(group=znode, parse_meta=True, **self._child_attrs)
def __setitem__(self, key, value):
raise NotImplementedError
def __delitem__(self, key):
""".. Warning: this does NOT clean up metadata!"""
key = normalize_path(str(key))
del self._group[key]
def __contains__(self, key):
key = normalize_path(str(key))
if not self._case_insensitive_fs:
return key in self._member_names
for name in self._member_names:
if key.lower() != name.lower():
continue
if key != name:
_logger.warning(
f"Key '{key}' matched member '{name}'. This may not work on case-sensitive filesystems."
)
return True
return False
def __iter__(self):
yield from self._member_names
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.close()
def group_keys(self):
"""Sorted list of keys to all the child zgroups (if any).
Returns
-------
list[str]
"""
return self._impl.group_keys(self._group)
def array_keys(self):
"""Sorted list of keys to all the child zarrays (if any).
Returns
-------
list[str]
"""
return self._impl.array_keys(self._group)
def is_root(self):
"""Whether this node is the root node
Returns
-------
bool
"""
return self._group.name == "/"
def is_leaf(self):
"""Wheter this node is a leaf node,
meaning that no child Zarr group is present.
Usually a position/fov node for NGFF-HCS if True.
Returns
-------
bool
"""
return not self.group_keys()
def print_tree(self, level: int | None = None):
"""Print hierarchy of the node to stdout.
Parameters
----------
level : int, optional
Maximum depth to show, by default None
"""
print(self.zgroup.tree(level=level))
def iteritems(self):
for key in self._member_names:
try:
yield key, self[key]
except Exception: # noqa: BLE001 — partial iteration, skip corrupt items
_logger.warning(f"Skipped item at {key}: invalid {type(self._MEMBER_TYPE)}.")
def get_channel_index(self, name: str) -> int:
"""Get the index of a given channel in the channel list.
Parameters
----------
name : str
Name of the channel.
Returns
-------
int
Index of the channel.
"""
if name not in self.channel_names:
raise ValueError(f"Channel {name} is not in the existing channels: {self.channel_names}")
return self.channel_names.index(name)
def _warn_invalid_meta(self):
msg = f"Zarr group at {self._group.path} does not have valid metadata for {type(self)}"
_logger.warning(msg)
def _parse_meta(self):
"""Parse and set NGFF metadata from `.zattrs`."""
raise NotImplementedError
def _dump_ome(self, ome: dict):
"""Dump OME metadata to the `.zattrs` file."""
if self.version == "0.4":
self.zattrs.update(ome)
elif self.version == "0.5":
if "version" not in ome:
ome["version"] = "0.5"
self.zattrs["ome"] = ome
def dump_meta(self):
"""Dumps metadata JSON to the `.zattrs` file."""
raise NotImplementedError
def close(self):
"""Close Zarr store."""
self._impl.close(self._group)
def _create_zarr_array(
self,
name: str,
shape: tuple[int, ...],
dtype,
chunks: tuple[int, ...],
shards_ratio: tuple[int, ...] | None,
dimension_names: list[str] | None = None,
):
"""Create a zarr array via the active implementation and return the native handle."""
if shards_ratio:
if len(shards_ratio) != len(shape):
raise ValueError(f"Sharding ratio length {len(shards_ratio)} does not match shape length {len(shape)}.")
shards = tuple(c * s for c, s in zip(chunks, shards_ratio, strict=False))
else:
shards = None
if shards is not None and self._zarr_format == 2:
raise ValueError(
"Sharding is not supported in Zarr v2 (OME-Zarr v0.4). Remove shards_ratio or use version='0.5'."
)
if self._zarr_format == 3:
spec = ArraySpec.create(
shape=shape,
dtype=dtype,
chunks=chunks,
shards=shards,
fill_value=0,
dimension_names=dimension_names or [ax.name for ax in self.axes[: len(shape)]],
)
return self._impl.create_array(self._group, name, spec, overwrite=self._overwrite)
return self._impl.create_array_v2(
self._group,
name,
shape=shape,
dtype=dtype,
chunks=chunks,
fill_value=0,
overwrite=self._overwrite,
)
@property
def _zarr_format(self) -> int:
return self._impl.get_zarr_format(self._group)
class ImageArray(NGFFArray):
"""Container object for image stored as a zarr array (up to 5D: TCZYX)"""
_SUPPORTED_DIMS = "TCZYX"
_N_DIMS = 5
@property
def frames(self):
return self._get_dim(0)
@property
def channels(self):
return self._get_dim(1)
@property
def slices(self):
return self._get_dim(2)
@property
def height(self):
return self._get_dim(3)
@property
def width(self):
return self._get_dim(4)
class TiledImageArray(ImageArray):
"""Container object for tiled image stored as a zarr array (up to 5D)."""
@property
def rows(self):
"""Number of rows in the tiles."""
return int(self.shape[-2] / self.chunks[-2])
@property
def columns(self):
"""Number of columns in the tiles."""
return int(self.shape[-1] / self.chunks[-1])
@property
def tiles(self):
"""A tuple of the tiled grid size (rows, columns)."""
return (self.rows, self.columns)
@property
def tile_shape(self):
"""Shape of a tile, the same as chunk size of the underlying array."""
return self.chunks
def get_tile(
self,
row: int,
column: int,
pre_dims: tuple[int | slice, ...] | None = None,
) -> NDArray:
"""Get a tile as an up-to-5D in-RAM NumPy array.
Parameters
----------
row : int
Row index.
column : int
Column index.
pre_dims : tuple[int | slice, ...], optional
Indices or slices for previous dimensions than rows and columns
with matching shape, e.g. (t, c, z) for 5D arrays,
by default None (select all).
Returns
-------
NDArray
"""
self._check_rc(row, column)
return self[self.get_tile_slice(row, column, pre_dims=pre_dims)]
def write_tile(
self,
data: ArrayLike,
row: int,
column: int,
pre_dims: tuple[int | slice, ...] | None = None,
) -> None:
"""Write a tile in the Zarr store.
Parameters
----------
data : ArrayLike
Value to store.
row : int
Row index.
column : int
Column index.
pre_dims : tuple[int | slice, ...], optional
Indices or slices for previous dimensions than rows and columns
with matching shape, e.g. (t, c, z) for 5D arrays,
by default None (select all).
"""
self._check_rc(row, column)
self[self.get_tile_slice(row, column, pre_dims=pre_dims)] = data
def get_tile_slice(
self,
row: int,
column: int,
pre_dims: tuple[int | slice, ...] | None = None,
) -> tuple[slice, ...]:
"""Get the slices for a tile in the underlying array.
Parameters
----------
row : int
Row index.
column : int
Column index.
pre_dims : tuple[int | slice, ...], optional
Indices or slices for previous dimensions than rows and columns
with matching shape, e.g. (t, c, z) for 5D arrays,
by default None (select all).
Returns
-------
tuple[slice, ...]
Tuple of slices for all the dimensions of the array.
"""
self._check_rc(row, column)
y, x = self.chunks[-2:]
r_slice = slice(row * y, (row + 1) * y)
c_slice = slice(column * x, (column + 1) * x)
pad = [slice(None)] * (len(self.shape) - 2)
if pre_dims is not None:
try:
if len(pre_dims) != len(pad):
raise IndexError(f"Length of `pre_dims` should be {len(pad)}, got {len(pre_dims)}.")
except TypeError as err:
raise TypeError(f"Argument `pre_dims` should be a sequence, got type {type(pre_dims)}.") from err
for i, sel in enumerate(pre_dims):
if isinstance(sel, int):
sel = slice(sel)
if sel is not None:
pad[i] = sel
return (*pad, r_slice, c_slice)
@staticmethod
def _check_rc(row: int, column: int):
if not (isinstance(row, int) and isinstance(column, int)):
raise TypeError("Row and column indices must be integers.")
class LabelsArray(NGFFArray):
"""Container for labels stored as zarr array (4D: TZYX)"""
_SUPPORTED_DIMS = "TZYX"
_N_DIMS = 4
@property
def frames(self):
"""Number of time frames in the labels array."""
return self._get_dim(0)
@property
def slices(self):
"""Number of Z slices in the labels array."""
return self._get_dim(1)
@property
def height(self):
"""Height (Y dimension) of the labels array."""
return self._get_dim(2)
@property
def width(self):
"""Width (X dimension) of the labels array."""
return self._get_dim(3)
def downscale(self):
"""Labels downscaling is not supported."""
raise NotImplementedError("Downscaling is not implemented for labels arrays.")
class PositionLabel(NGFFNode):
"""Multiscale label image group containing LabelsArray pyramid levels.
This class manages label images according to NGFF specification where
each label image MUST implement the multiscales specification with the
same number of scale levels as the original image.
Parameters
----------
group : zarr.Group
Zarr hierarchy group object for the label image
parse_meta : bool, optional
Whether to parse NGFF metadata in `.zattrs`, by default True
axes : list[AxisMeta], optional
List of axes for TZYX dimensions (no channel), by default None
version : Literal["0.4", "0.5"]
OME-NGFF specification version
colors : dict[int, list[int]], optional
Color mapping for label values, by default None
properties : list[dict[str, Any]], optional
Properties for label values, by default None
overwriting_creation : bool, optional
Whether to overwrite existing arrays, by default False
Attributes
----------
version : Literal["0.4", "0.5"]
OME-NGFF specification version
zgroup : Group
Zarr group holding label arrays
zattr : Attributes
Zarr attributes of the group
axes : list[AxisMeta]
Axes metadata (TZYX, no channel)
"""
_MEMBER_TYPE = LabelsArray
def __init__(
self,
group,
parse_meta: bool = True,
axes: list[AxisMeta] | None = None,
version: Literal["0.4", "0.5"] = "0.5",
colors: dict[int, list[int]] | None = None,
properties: list[dict[str, Any]] | None = None,
overwriting_creation: bool = False,
impl: ZarrImplementation | None = None,
):
if axes:
self.axes = [ax for ax in axes if ax.type != "channel"]
else:
self.axes = [
TimeAxisMeta(name="T", unit="second"),
*[SpaceAxisMeta(name=i, unit="micrometer") for i in ("Z", "Y", "X")],
]
super().__init__(
group=group,
parse_meta=parse_meta,
channel_names=["label"],
axes=self.axes,
version=version,
overwriting_creation=overwriting_creation,
impl=impl,
)
self._colors = colors
self._properties = properties
def _parse_meta(self):
"""Parse multiscales and image-label metadata."""
try:
attrs = dict(self.maybe_wrapped_ome_attrs)
if "version" not in attrs:
attrs["version"] = self.version
self.metadata = LabelImageMeta.model_validate(attrs)
except ValidationError as e:
_logger.warning(str(e))
self._warn_invalid_meta()
def dump_meta(self):
"""Dump metadata to zarr.json file."""
ome = self.metadata.model_dump(exclude_none=True, by_alias=True)
self._dump_ome(ome)
@property
def data(self) -> LabelsArray:
"""Alias for the highest-resolution label array ('0')."""
try:
return self["0"]
except KeyError as err:
raise KeyError(f"There is no array named '0' in the group of: {self.array_keys()}") from err
def __getitem__(self, key: int | str) -> LabelsArray:
key = normalize_path(str(key))
try:
handle = self._impl.open_array(self._group, key)
except (FileNotFoundError, KeyError) as err:
raise KeyError(key) from err
return LabelsArray.from_handle(handle, self._impl)
def create_label(
self,
level: str,
data: NDArray,
chunks: tuple[int, ...] | None = None,
shards_ratio: tuple[int, ...] | None = None,
transform: list[TransformationMeta] | None = None,
) -> LabelsArray:
"""Create a label array at a specific resolution level.
Parallel to :meth:`Position.create_image` for creating label
arrays at specific multiscale resolution levels.
Parameters
----------
level : str
Resolution level name (e.g., "0", "1", "2")
data : NDArray
Label data (integer array, TZYX format)
chunks : tuple[int, ...], optional
Chunk size, by default None
shards_ratio : tuple[int, ...], optional
Sharding ratio for each dimension, by default None.
transform : list[TransformationMeta], optional
Coordinate transformations for this level, by default None
Returns
-------
LabelsArray
Created label array
"""
if not isinstance(data, np.ndarray):
raise TypeError("Label data must be a NumPy array")
if not np.issubdtype(data.dtype, np.integer):
raise ValueError(f"Label data must be an integer dtype, got {data.dtype}.")
arr = self.create_zeros(
level=level,
shape=data.shape,
dtype=data.dtype,
chunks=chunks,
shards_ratio=shards_ratio,
transform=transform,
)
arr[...] = data
return arr
def create_zeros(
self,
level: str,
shape: tuple[int, ...],
dtype: DTypeLike,
chunks: tuple[int, ...] | None = None,
shards_ratio: tuple[int, ...] | None = None,
transform: list[TransformationMeta] | None = None,
) -> LabelsArray:
"""Create a zero-filled label array at a specific resolution level.
Parameters
----------
level : str
Resolution level name
shape : tuple[int, ...]
Array shape (TZYX)
dtype : DTypeLike
Integer data type for labels
chunks : tuple[int, ...], optional
Chunk size, by default None
shards_ratio : tuple[int, ...], optional
Sharding ratio for each dimension, by default None.
transform : list[TransformationMeta], optional
Coordinate transformations, by default None
Returns
-------
LabelsArray
Zero-filled label array
"""
if not np.issubdtype(dtype, np.integer):
raise ValueError(f"Labels must use integer dtype, got {dtype}")
if not chunks:
chunks = pad_shape(shape[-3:], target=len(shape))
arr_handle = self._create_zarr_array(level, shape, dtype, chunks, shards_ratio)
lbl_arr = LabelsArray.from_handle(arr_handle, self._impl)
self._create_label_meta(level, transform=transform)
return lbl_arr
def initialize_pyramid(self, levels: int, source_level: str = "0") -> None:
"""Initialize multiscale pyramid for label image.
Parameters
----------
levels : int
Total number of pyramid levels
source_level : str, optional
Source level to downscale from, by default "0"
"""
if source_level not in self:
raise KeyError(f"Source level '{source_level}' not found")
source_array = self[source_level]
for level in range(1, levels):
factor = 2**level
downscaled_shape = source_array.shape[:-3] + tuple(math.ceil(s / factor) for s in source_array.shape[-3:])
downscaled_chunks = pad_shape(
tuple(math.ceil(c / factor) for c in source_array.chunks[-3:]),
target=len(downscaled_shape),
)
transforms = [
TransformationMeta(type="scale", scale=[1.0] * (len(source_array.shape) - 3) + [float(factor)] * 3)
]
self.create_zeros(
level=str(level),
shape=downscaled_shape,
dtype=source_array.dtype,
chunks=downscaled_chunks,
transform=transforms,
)
def _create_label_meta(
self,
level: str,
transform: list[TransformationMeta] | None = None,
):
"""Create or update multiscales metadata for this label image."""
if not transform:
transform = [TransformationMeta(type="scale", scale=[1.0] * len(self.axes))]
dataset_meta = DatasetMeta(path=level, coordinate_transformations=transform)
image_label_meta = self._create_image_label_meta()
if not hasattr(self, "metadata"):
self.metadata = LabelImageMeta(
multiscales=[
MultiScaleMeta(
version=self.version,
axes=self.axes,
datasets=[dataset_meta],
name=self._group.basename,
coordinate_transformations=None,
)
],
image_label=image_label_meta,
version=self.version,
)
elif dataset_meta.path not in self.metadata.multiscales[0].get_dataset_paths():
self.metadata.multiscales[0].datasets.append(dataset_meta)
self.dump_meta()
def _create_image_label_meta(self) -> PositionLabelMeta:
"""Create image-label metadata from colors and properties."""
# Prepare colors
label_colors = []
if self._colors:
for label_value, rgba in self._colors.items():
# Ensure RGBA format
if len(rgba) == 3:
rgba = [*rgba, 255] # Add alpha
# Convert to 0-1 range for Pydantic (serialized as 0-255)
# Validate bounds and handle numpy integer types
rgba_normalized = []
for val in rgba:
# Convert numpy types to Python types
if hasattr(val, "item"):
val = val.item()
# Validate bounds
if not (0 <= val <= 255):
raise ValueError(f"Color values must be 0-255, got {val}")
# Normalize: values > 1 are assumed 0-255 scale
if isinstance(val, int) or val > 1:
rgba_normalized.append(val / 255.0)
else:
rgba_normalized.append(float(val))
label_colors.append(LabelColorMeta(label_value=label_value, rgba=rgba_normalized))
label_properties = []
if self._properties:
for prop in self._properties:
if "label_id" in prop:
prop = prop.copy()
prop["label-value"] = prop.pop("label_id")
elif "label-value" not in prop:
_logger.warning(f"Skipping property without 'label-value' field: {list(prop.keys())}")
continue
label_properties.append(prop)
return PositionLabelMeta(
colors=label_colors if label_colors else [],
properties=label_properties if label_properties else [],
source={"image": "../../"}, # Reference to parent image
)
class Position(NGFFNode):
"""The Zarr group level directly containing multiscale image arrays.
Parameters
----------
group : zarr.Group
Zarr heirarchy group object
parse_meta : bool, optional
Whether to parse NGFF metadata in `.zattrs`, by default True
channel_names : list[str], optional
List of channel names, by default None
axes : list[AxisMeta], optional
List of axes (`ngff_meta.AxisMeta`, up to 5D), by default None
overwriting_creation : bool, optional
Whether to overwrite or error upon creating an existing child item,
by default False
Attributes
----------
version : Literal["0.4", "0.5"]
OME-NGFF specification version
zgroup : Group
Root Zarr group holding arrays
zattr : Attributes
Zarr attributes of the group
channel_names : list[str]
Name of the channels
axes : list[AxisMeta]
Axes metadata
"""
_MEMBER_TYPE = ImageArray
def __init__(
self,
group: zarr.Group,
parse_meta: bool = True,
channel_names: list[str] | None = None,
axes: list[AxisMeta] | None = None,
version: Literal["0.4", "0.5"] = "0.5",
overwriting_creation: bool = False,
impl: ZarrImplementation | None = None,
):
super().__init__(
group=group,
parse_meta=parse_meta,
channel_names=channel_names,
axes=axes,
version=version,
overwriting_creation=overwriting_creation,
impl=impl,
)
def _set_meta(self):
self.axes = self.metadata.multiscales[0].axes
if self.metadata.omero is not None:
self.channel_names = [c.label for c in self.metadata.omero.channels]
else:
_logger.warning("OMERO metadata not found. Using channel indices as channel names.")
example_image: ImageArray = self[self.metadata.multiscales[0].datasets[0].path]
self.channel_names = list(range(example_image.channels))
def _parse_meta(self):
try:
attrs = dict(self.maybe_wrapped_ome_attrs)
if "version" not in attrs:
attrs["version"] = self.version
self.metadata = ImagesMeta.model_validate(attrs)
self._set_meta()
except ValidationError as e:
_logger.warning(str(e))
self._warn_invalid_meta()
def dump_meta(self):
"""Dumps metadata JSON to the `.zattrs` file."""
ome = self.metadata.model_dump(exclude_none=True, by_alias=True)
self._dump_ome(ome)
@property
def _member_names(self):
return self.array_keys()
@property
def data(self):
""".. warning::
This property does *NOT* aim to retrieve all the arrays.
And it may also fail to retrive any data if arrays exist but
are not named conventionally.
Alias for an array named '0' in the position,
which is usually the raw data (or the finest resolution in a pyramid).
Returns
-------
ImageArray
Raises