-
Notifications
You must be signed in to change notification settings - Fork 6
/
ngff.py
1491 lines (1321 loc) · 45.2 KB
/
ngff.py
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
# TODO: remove this in the future (PEP deferred for 3.11, now 3.12?)
from __future__ import annotations
import logging
import os
from typing import TYPE_CHECKING, Generator, List, Literal, Tuple, Union
import numpy as np
import zarr
from numcodecs import Blosc
from numpy.typing import ArrayLike, DTypeLike, NDArray
from pydantic import ValidationError
from zarr.util import normalize_storage_path
from iohub.lf_utils import channel_display_settings
from iohub.ngff_meta import (
TO_DICT_SETTINGS,
AcquisitionMeta,
AxisMeta,
DatasetMeta,
ImageMeta,
ImagesMeta,
MultiScaleMeta,
OMEROMeta,
PlateAxisMeta,
PlateMeta,
RDefsMeta,
TransformationMeta,
WellGroupMeta,
WellIndexMeta,
)
if TYPE_CHECKING:
from _typeshed import StrOrBytesPath
def _pad_shape(shape: tuple[int], target: int = 5):
"""Pad shape tuple to a target length."""
pad = target - len(shape)
return (1,) * pad + shape
def _open_store(
store_path: StrOrBytesPath,
mode: Literal["r", "r+", "a", "w", "w-"],
version: Literal["0.1", "0.4"],
synchronizer=None,
):
if not os.path.isdir(store_path) and mode in ("r", "r+"):
raise FileNotFoundError(
f"Dataset directory not found at {store_path}."
)
if version != "0.4":
logging.warning(
"\n".join(
"IOHub is only tested against OME-NGFF v0.4.",
f"Requested version {version} may not work properly.",
)
)
dimension_separator = None
else:
dimension_separator = "/"
try:
store = zarr.DirectoryStore(
store_path, dimension_separator=dimension_separator
)
root = zarr.open_group(store, mode=mode, synchronizer=synchronizer)
except Exception as e:
raise RuntimeError(
f"Cannot open Zarr root group at {store_path}"
) from e
return root
class NGFFNode:
"""A node (group level in Zarr) in an NGFF dataset."""
_MEMBER_TYPE = None
_DEFAULT_AXES = [
AxisMeta(name="T", type="time", unit="second"),
AxisMeta(name="C", type="channel"),
*[
AxisMeta(name=i, type="space", unit="micrometer")
for i in ("Z", "Y", "X")
],
]
def __init__(
self,
group: zarr.Group,
parse_meta: bool = True,
channel_names: list[str] = None,
axes: list[AxisMeta] = None,
version: Literal["0.1", "0.4"] = "0.4",
overwriting_creation: bool = False,
):
if channel_names:
self._channel_names = channel_names
elif not parse_meta:
raise ValueError(
"Channel names need to be provided or in metadata."
)
if axes:
self.axes = axes
self._group = group
self._overwrite = overwriting_creation
self._version = version
if parse_meta:
self._parse_meta()
if not hasattr(self, "axes"):
self.axes = self._DEFAULT_AXES
@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 version(self):
"""NGFF version"""
return self._version
@property
def channel_names(self):
return self._channel_names
@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 os.path.dirname(self._group.name)
@property
def _member_names(self):
"""Group keys (default) or array keys (overridden)."""
return self.group_keys()
@property
def _child_attrs(self):
"""Attributes to pass on when constructing child type instances"""
return dict(
version=self._version,
axes=self.axes,
channel_names=self._channel_names,
overwriting_creation=self._overwrite,
)
def __len__(self):
return len(self._member_names)
def __getitem__(self, key):
key = normalize_storage_path(key)
znode = self.zgroup.get(key)
if not znode:
raise KeyError(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, zarr.Array):
return item_type(znode)
else:
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_storage_path(key)
if key in self._member_names:
del self[key]
def __contains__(self, key):
key = normalize_storage_path(key)
return key in self._member_names
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 sorted(list(self._group.group_keys()))
def array_keys(self):
"""Sorted list of keys to all the child zarrays (if any).
Returns
-------
list[str]
"""
return sorted(list(self._group.array_keys()))
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):
"""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:
logging.warning(
"Skipped item at {}: invalid {}.".format(
key, type(self._MEMBER_TYPE)
)
)
def get_channel_index(self, name: str):
"""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 not hasattr(self, "_channel_names"):
raise AttributeError(
"Channel names are not set for this NGFF node. "
f"Cannot get the index for channel name '{name}'"
)
if name not in self._channel_names:
raise ValueError(
f"Channel {name} is not in "
f"the existing channels: {self._channel_names}"
)
return self._channel_names.index(name)
def _warn_invalid_meta(self):
msg = "Zarr group at {} does not have valid metadata for {}".format(
self._group.path, type(self)
)
logging.warning(msg)
def _parse_meta(self):
"""Parse and set NGFF metadata from `.zattrs`."""
raise NotImplementedError
def dump_meta(self):
"""Dumps metadata JSON to the `.zattrs` file."""
raise NotImplementedError
def close(self):
"""Close Zarr store."""
self._group.store.close()
class ImageArray(zarr.Array):
"""Container object for image stored as a zarr array (up to 5D)"""
def __init__(self, zarray: zarr.Array):
super().__init__(
store=zarray._store,
path=zarray._path,
read_only=zarray._read_only,
chunk_store=zarray._chunk_store,
synchronizer=zarray._synchronizer,
cache_metadata=zarray._cache_metadata,
cache_attrs=zarray._attrs.cache,
partial_decompress=zarray._partial_decompress,
write_empty_chunks=zarray._write_empty_chunks,
zarr_version=zarray._version,
meta_array=zarray._meta_array,
)
self._get_dims()
def _get_dims(self):
(
self.frames,
self.channels,
self.slices,
self.height,
self.width,
) = _pad_shape(self.shape, target=5)
def numpy(self):
"""Return the whole image as an in-RAM NumPy array.
`self.numpy()` is equivalent to `self[:]`."""
return self[:]
def downscale(self):
raise NotImplementedError
def tensorstore(self):
raise NotImplementedError
class TiledImageArray(ImageArray):
"""Container object for tiled image stored as a zarr array (up to 5D)."""
def __init__(self, zarray: zarr.Array):
super().__init__(zarray)
@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[Union[int, slice, None]] = None,
):
"""Get a tile as an up-to-5D in-RAM NumPy array.
Parameters
----------
row : int
Row index.
column : int
Column index.
pre_dims : tuple[Union[int, slice, None]], 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[Union[int, slice, 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[Union[int, slice, None]], 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[Union[int, slice, None]] = None,
):
"""Get the slices for a tile in the underlying array.
Parameters
----------
row : int
Row index.
column : int
Column index.
pre_dims : tuple[Union[int, slice, None]], 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)}, "
f"got {len(pre_dims)}."
)
except TypeError:
raise TypeError(
"Argument `pre_dims` should be a sequence, "
f"got type {type(pre_dims)}."
)
for i, sel in enumerate(pre_dims):
if sel is not None:
pad[i] = sel
return tuple(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 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.1", "0.4"]
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,
axes: list[AxisMeta] = None,
version: Literal["0.1", "0.4"] = "0.4",
overwriting_creation: bool = False,
):
super().__init__(
group=group,
parse_meta=parse_meta,
channel_names=channel_names,
axes=axes,
version=version,
overwriting_creation=overwriting_creation,
)
def _parse_meta(self):
multiscales = self.zattrs.get("multiscales")
omero = self.zattrs.get("omero")
if multiscales and omero:
try:
self.metadata = ImagesMeta(
multiscales=multiscales, omero=omero
)
self._channel_names = [
c.label for c in self.metadata.omero.channels
]
self.axes = self.metadata.multiscales[0].axes
except ValidationError:
self._warn_invalid_meta()
else:
self._warn_invalid_meta()
def dump_meta(self):
"""Dumps metadata JSON to the `.zattrs` file."""
self.zattrs.update(**self.metadata.dict(**TO_DICT_SETTINGS))
@property
def _storage_options(self):
return {
"compressor": Blosc(
cname="zstd", clevel=1, shuffle=Blosc.BITSHUFFLE
),
"overwrite": self._overwrite,
}
@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
------
KeyError
If no array is named '0'.
Notes
-----
Do not depend on this in non-interactive code!
The name is hard-coded and is not guaranteed
by the OME-NGFF specification.
"""
try:
return self["0"]
except KeyError:
raise KeyError(
"There is no array named '0' "
f"in the group of: {self.array_keys()}"
)
def __getitem__(self, key: Union[int, str]):
"""Get an image array member of the position.
E.g. Raw-coordinates image, a multi-scale level, or labels
Parameters
----------
key : Union[int, str]
Name or path to the image array.
Integer key is converted to string (name).
Returns
-------
ImageArray
Container object for image stored as a zarr array (up to 5D)
"""
return super().__getitem__(key)
def __setitem__(self, key, value: NDArray):
"""Write an up-to-5D image with default settings."""
key = normalize_storage_path(key)
if not isinstance(value, np.ndarray):
raise TypeError(
f"Value must be a NumPy array. Got type {type(value)}."
)
self.create_image(key, value)
def images(self) -> Generator[tuple[str, ImageArray]]:
"""Returns a generator that iterate over the name and value
of all the image arrays in the group.
Yields
------
tuple[str, ImageArray]
Name and image array object.
"""
yield from self.iteritems()
def create_image(
self,
name: str,
data: NDArray,
chunks: tuple[int] = None,
transform: List[TransformationMeta] = None,
check_shape: bool = True,
):
"""Create a new image array in the position.
Parameters
----------
name : str
Name key of the new image.
data : NDArray
Image data.
chunks : tuple[int], optional
Chunk size, by default None.
ZYX stack size will be used if not specified.
transform : List[TransformationMeta], optional
List of coordinate transformations, by default None.
Should be specified for a non-native resolution level.
check_shape : bool, optional
Whether to check if image shape matches dataset axes,
by default True
Returns
-------
ImageArray
Container object for image stored as a zarr array (up to 5D)
"""
if not chunks:
chunks = self._default_chunks(data.shape, 3)
if check_shape:
self._check_shape(data.shape)
img_arr = ImageArray(
self._group.array(
name, data, chunks=chunks, **self._storage_options
)
)
self._create_image_meta(img_arr.basename, transform=transform)
return img_arr
def create_zeros(
self,
name: str,
shape: tuple[int],
dtype: DTypeLike,
chunks: tuple[int] = None,
transform: List[TransformationMeta] = None,
check_shape: bool = True,
):
"""Create a new zero-filled image array in the position.
Under default zarr-python settings of lazy writing,
this will not write the array values,
but only create a ``.zarray`` file.
This is useful for writing larger-than-RAM images
and/or writing from multiprocesses in chunks.
Parameters
----------
name : str
Name key of the new image.
shape : tuple
Image shape.
dtype : DTypeLike
Data type.
chunks : tuple[int], optional
Chunk size, by default None.
ZYX stack size will be used if not specified.
transform : List[TransformationMeta], optional
List of coordinate transformations, by default None.
Should be specified for a non-native resolution level.
check_shape : bool, optional
Whether to check if image shape matches dataset axes,
by default True
Returns
-------
ImageArray
Container object for a zero-filled image as a lazy zarr array
"""
if not chunks:
chunks = self._default_chunks(shape, 3)
if check_shape:
self._check_shape(shape)
img_arr = ImageArray(
self._group.zeros(
name,
shape=shape,
dtype=dtype,
chunks=chunks,
**self._storage_options,
)
)
self._create_image_meta(img_arr.basename, transform=transform)
return img_arr
@staticmethod
def _default_chunks(shape, last_data_dims: int):
chunks = shape[-min(last_data_dims, len(shape)) :]
return _pad_shape(chunks, target=len(shape))
def _check_shape(self, data_shape: tuple[int]):
if len(data_shape) != len(self.axes):
raise ValueError(
f"Image has {len(data_shape)} dimensions, "
f"while the dataset has {len(self.axes)}."
)
num_ch = len(self.channel_names)
if ch_axis := self._find_axis("channel"):
msg = (
f"Image has {data_shape[ch_axis]} channels, "
f"while the dataset has {num_ch}."
)
if data_shape[ch_axis] > num_ch:
raise ValueError(msg)
elif data_shape[ch_axis] < num_ch:
logging.warning(msg)
else:
logging.info(
"Dataset channel axis is not set. "
"Skipping channel shape check."
)
def _create_image_meta(
self,
name: str,
transform: List[TransformationMeta] = None,
extra_meta: dict = None,
):
if not transform:
transform = [TransformationMeta(type="identity")]
dataset_meta = DatasetMeta(
path=name, coordinate_transformations=transform
)
if not hasattr(self, "metadata"):
self.metadata = ImagesMeta(
multiscales=[
MultiScaleMeta(
version=self.version,
axes=self.axes,
datasets=[dataset_meta],
name=name,
coordinateTransformations=transform,
metadata=extra_meta,
)
],
omero=self._omero_meta(id=0, name=self._group.basename),
)
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 _omero_meta(
self,
id: int,
name: str,
clims: List[Tuple[float, float, float, float]] = None,
):
if not clims:
clims = [None] * len(self.channel_names)
channels = []
for i, (channel_name, clim) in enumerate(
zip(self.channel_names, clims)
):
if i == 0:
first_chan = True
channels.append(
channel_display_settings(
channel_name, clim=clim, first_chan=first_chan
)
)
omero_meta = OMEROMeta(
version=self.version,
id=id,
name=name,
channels=channels,
rdefs=RDefsMeta(default_t=0, default_z=0),
)
return omero_meta
def _find_axis(self, axis_type):
for i, axis in enumerate(self.axes):
if axis.type == axis_type:
return i
return None
def _get_channel_axis(self):
if (ch_ax := self._find_axis("channel")) is None:
raise KeyError(
"Axis 'channel' does not exist. "
"Please update `self.axes` first."
)
else:
return ch_ax
def append_channel(self, chan_name: str, resize_arrays: bool = True):
"""Append a channel to the end of the channel list.
Parameters
----------
chan_name : str
Name of the new channel
resize_arrays : bool, optional
Whether to resize all the image arrays for the new channel,
by default True
"""
if chan_name in self._channel_names:
raise ValueError(f"Channel name '{chan_name}' already exists.")
self._channel_names.append(chan_name)
if resize_arrays:
for _, img in self.images():
ch_ax = self._get_channel_axis()
shape = list(img.shape)
if ch_ax < len(shape):
shape[ch_ax] += 1
# prepend axis
elif ch_ax == len(shape):
shape = _pad_shape(tuple(shape), target=len(shape) + 1)
else:
raise IndexError(
f"Cannot infer channel axis for shape {shape}."
)
img.resize(shape)
if "omero" in self.metadata.dict().keys():
self.metadata.omero.channels.append(
channel_display_settings(chan_name)
)
self.dump_meta()
def rename_channel(self, old: str, new: str):
"""Rename a channel in the channel list.
Parameters
----------
old : str
Current name of the channel
new : str
New name of the channel
"""
ch_idx = self.get_channel_index(old)
self._channel_names[ch_idx] = new
if hasattr(self.metadata, "omero"):
self.metadata.omero.channels[ch_idx].label = new
self.dump_meta()
def update_channel(self, chan_name: str, target: str, data: ArrayLike):
"""Update a channel slice of the target image array with new data.
The incoming data shape needs to be the same as the target array
except for the non-existent channel dimension.
For example a TCZYX array of shape (2, 3, 4, 1024, 2048) can be updated
with data of shape (2, 4, 1024, 2048)
Parameters
----------
chan_name : str
Channel name
target: str
Name of the image array to update
data : ArrayLike
New data array to write
Notes
-----
This method is a syntactical variation
of assigning values to the slice with the `=` operator,
and users are encouraged to use array indexing directly.
"""
img = self[target]
ch_idx = self.get_channel_index(chan_name)
ch_ax = self._get_channel_axis()
ortho_sel = [slice(None)] * len(img.shape)
ortho_sel[ch_ax] = ch_idx
img.set_orthogonal_selection(tuple(ortho_sel), data)
class TiledPosition(Position):
_MEMBER_TYPE = TiledImageArray
def make_tiles(
self,
name: str,
grid_shape: tuple[int, int],
tile_shape: tuple[int],
dtype: DTypeLike,
transform: List[TransformationMeta] = None,
chunk_dims: int = 2,
):
"""Make a tiled image array filled with zeros.
Chunk size is inferred from tile shape.
Parameters
----------
name : str
Name of the array.
grid_shape : tuple[int, int]
2-tuple of the tiling grid shape (rows, columns).
tile_shape : tuple[int]
Shape of each tile (up to 5D).
dtype : DTypeLike
Data type in NumPy convention
transform : List[TransformationMeta], optional
List of coordinate transformations, by default None.
Should be specified for a non-native resolution level.
chunk_dims : int, optional
Non-singleton dimensions of the chunksize,
by default 2 (chunk by 2D (y, x) tile size).
Returns
-------
TiledImageArray
"""
xy_shape = tuple(np.array(grid_shape) * np.array(tile_shape[-2:]))
tiles = TiledImageArray(
self._group.zeros(
name=name,
shape=tile_shape[:-2] + xy_shape,
dtype=dtype,
chunks=self._default_chunks(
shape=tile_shape, last_data_dims=chunk_dims
),
**self._storage_options,
)
)
self._create_image_meta(tiles.basename, transform=transform)
return tiles
class Well(NGFFNode):
"""The Zarr group level containing position groups.
Parameters
----------
group : zarr.Group
Zarr heirarchy group object
parse_meta : bool, optional
Whether to parse NGFF metadata in `.zattrs`, by default True
version : Literal["0.1", "0.4"]
OME-NGFF specification version
overwriting_creation : bool, optional
Whether to overwrite or error upon creating an existing child item,
by default False
Attributes
----------
version : Literal["0.1", "0.4"]
OME-NGFF specification version
zgroup : Group
Root Zarr group holding arrays
zattr : Attributes
Zarr attributes of the group
"""
_MEMBER_TYPE = Position
def __init__(
self,
group: zarr.Group,
parse_meta: bool = True,
channel_names: list[str] = None,
axes: list[AxisMeta] = None,
version: Literal["0.1", "0.4"] = "0.4",
overwriting_creation: bool = False,
):
super().__init__(
group=group,
parse_meta=parse_meta,
channel_names=channel_names,
axes=axes,
version=version,
overwriting_creation=overwriting_creation,
)