-
-
Notifications
You must be signed in to change notification settings - Fork 304
/
Copy pathgroup.py
2953 lines (2540 loc) · 106 KB
/
group.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
from __future__ import annotations
import asyncio
import itertools
import json
import logging
import warnings
from collections import defaultdict
from dataclasses import asdict, dataclass, field, fields, replace
from typing import TYPE_CHECKING, Literal, TypeVar, assert_never, cast, overload
import numpy as np
import numpy.typing as npt
from typing_extensions import deprecated
import zarr.api.asynchronous as async_api
from zarr._compat import _deprecate_positional_args
from zarr.abc.metadata import Metadata
from zarr.abc.store import Store, set_or_delete
from zarr.core._info import GroupInfo
from zarr.core.array import (
Array,
AsyncArray,
CompressorLike,
CompressorsLike,
FiltersLike,
SerializerLike,
ShardsLike,
_build_parents,
_parse_deprecated_compressor,
create_array,
)
from zarr.core.attributes import Attributes
from zarr.core.buffer import default_buffer_prototype
from zarr.core.common import (
JSON,
ZARR_JSON,
ZARRAY_JSON,
ZATTRS_JSON,
ZGROUP_JSON,
ZMETADATA_V2_JSON,
ChunkCoords,
NodeType,
ShapeLike,
ZarrFormat,
parse_shapelike,
)
from zarr.core.config import config
from zarr.core.metadata import ArrayV2Metadata, ArrayV3Metadata
from zarr.core.metadata.v3 import V3JsonEncoder
from zarr.core.sync import SyncMixin, sync
from zarr.errors import MetadataValidationError
from zarr.storage import StoreLike, StorePath
from zarr.storage._common import ensure_no_existing_node, make_store_path
if TYPE_CHECKING:
from collections.abc import AsyncGenerator, Generator, Iterable, Iterator
from typing import Any
from zarr.core.array_spec import ArrayConfig, ArrayConfigLike
from zarr.core.buffer import Buffer, BufferPrototype
from zarr.core.chunk_key_encodings import ChunkKeyEncoding, ChunkKeyEncodingLike
from zarr.core.common import MemoryOrder
logger = logging.getLogger("zarr.group")
DefaultT = TypeVar("DefaultT")
def parse_zarr_format(data: Any) -> ZarrFormat:
"""Parse the zarr_format field from metadata."""
if data in (2, 3):
return cast(ZarrFormat, data)
msg = f"Invalid zarr_format. Expected one of 2 or 3. Got {data}."
raise ValueError(msg)
def parse_node_type(data: Any) -> NodeType:
"""Parse the node_type field from metadata."""
if data in ("array", "group"):
return cast(Literal["array", "group"], data)
raise MetadataValidationError("node_type", "array or group", data)
# todo: convert None to empty dict
def parse_attributes(data: Any) -> dict[str, Any]:
"""Parse the attributes field from metadata."""
if data is None:
return {}
elif isinstance(data, dict) and all(isinstance(k, str) for k in data):
return data
msg = f"Expected dict with string keys. Got {type(data)} instead."
raise TypeError(msg)
@overload
def _parse_async_node(node: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]) -> Array: ...
@overload
def _parse_async_node(node: AsyncGroup) -> Group: ...
def _parse_async_node(
node: AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup,
) -> Array | Group:
"""Wrap an AsyncArray in an Array, or an AsyncGroup in a Group."""
if isinstance(node, AsyncArray):
return Array(node)
elif isinstance(node, AsyncGroup):
return Group(node)
else:
raise TypeError(f"Unknown node type, got {type(node)}")
@dataclass(frozen=True)
class ConsolidatedMetadata:
"""
Consolidated Metadata for this Group.
This stores the metadata of child nodes below this group. Any child groups
will have their consolidated metadata set appropriately.
"""
metadata: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata]
kind: Literal["inline"] = "inline"
must_understand: Literal[False] = False
def to_dict(self) -> dict[str, JSON]:
return {
"kind": self.kind,
"must_understand": self.must_understand,
"metadata": {k: v.to_dict() for k, v in self.flattened_metadata.items()},
}
@classmethod
def from_dict(cls, data: dict[str, JSON]) -> ConsolidatedMetadata:
data = dict(data)
kind = data.get("kind")
if kind != "inline":
raise ValueError(f"Consolidated metadata kind='{kind}' is not supported.")
raw_metadata = data.get("metadata")
if not isinstance(raw_metadata, dict):
raise TypeError(f"Unexpected type for 'metadata': {type(raw_metadata)}")
metadata: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] = {}
if raw_metadata:
for k, v in raw_metadata.items():
if not isinstance(v, dict):
raise TypeError(
f"Invalid value for metadata items. key='{k}', type='{type(v).__name__}'"
)
# zarr_format is present in v2 and v3.
zarr_format = parse_zarr_format(v["zarr_format"])
if zarr_format == 3:
node_type = parse_node_type(v.get("node_type", None))
if node_type == "group":
metadata[k] = GroupMetadata.from_dict(v)
elif node_type == "array":
metadata[k] = ArrayV3Metadata.from_dict(v)
else:
assert_never(node_type)
elif zarr_format == 2:
if "shape" in v:
metadata[k] = ArrayV2Metadata.from_dict(v)
else:
metadata[k] = GroupMetadata.from_dict(v)
else:
assert_never(zarr_format)
cls._flat_to_nested(metadata)
return cls(metadata=metadata)
@staticmethod
def _flat_to_nested(
metadata: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata],
) -> None:
"""
Convert a flat metadata representation to a nested one.
Notes
-----
Flat metadata is used when persisting the consolidated metadata. The keys
include the full path, not just the node name. The key prefixes can be
used to determine which nodes are children of which other nodes.
Nested metadata is used in-memory. The outermost level will only have the
*immediate* children of the Group. All nested child groups will be stored
under the consolidated metadata of their immediate parent.
"""
# We have a flat mapping from {k: v} where the keys include the *full*
# path segment:
# {
# "/a/b": { group_metadata },
# "/a/b/array-0": { array_metadata },
# "/a/b/array-1": { array_metadata },
# }
#
# We want to reorganize the metadata such that each Group contains the
# array metadata of its immediate children.
# In the example, the group at `/a/b` will have consolidated metadata
# for its children `array-0` and `array-1`.
#
# metadata = dict(metadata)
keys = sorted(metadata, key=lambda k: k.count("/"))
grouped = {
k: list(v) for k, v in itertools.groupby(keys, key=lambda k: k.rsplit("/", 1)[0])
}
# we go top down and directly manipulate metadata.
for key, children_keys in grouped.items():
# key is a key like "a", "a/b", "a/b/c"
# The basic idea is to find the immediate parent (so "", "a", or "a/b")
# and update that node's consolidated metadata to include the metadata
# in children_keys
*prefixes, name = key.split("/")
parent = metadata
while prefixes:
# e.g. a/b/c has a parent "a/b". Walk through to get
# metadata["a"]["b"]
part = prefixes.pop(0)
# we can assume that parent[part] here is a group
# otherwise we wouldn't have a node with this `part` prefix.
# We can also assume that the parent node will have consolidated metadata,
# because we're walking top to bottom.
parent = parent[part].consolidated_metadata.metadata # type: ignore[union-attr]
node = parent[name]
children_keys = list(children_keys)
if isinstance(node, ArrayV2Metadata | ArrayV3Metadata):
# These are already present, either thanks to being an array in the
# root, or by being collected as a child in the else clause
continue
children_keys = list(children_keys)
# We pop from metadata, since we're *moving* this under group
children = {
child_key.split("/")[-1]: metadata.pop(child_key)
for child_key in children_keys
if child_key != key
}
parent[name] = replace(
node, consolidated_metadata=ConsolidatedMetadata(metadata=children)
)
@property
def flattened_metadata(self) -> dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata]:
"""
Return the flattened representation of Consolidated Metadata.
The returned dictionary will have a key for each child node in the hierarchy
under this group. Under the default (nested) representation available through
``self.metadata``, the dictionary only contains keys for immediate children.
The keys of the dictionary will include the full path to a child node from
the current group, where segments are joined by ``/``.
Examples
--------
>>> cm = ConsolidatedMetadata(
... metadata={
... "group-0": GroupMetadata(
... consolidated_metadata=ConsolidatedMetadata(
... {
... "group-0-0": GroupMetadata(),
... }
... )
... ),
... "group-1": GroupMetadata(),
... }
... )
{'group-0': GroupMetadata(attributes={}, zarr_format=3, consolidated_metadata=None, node_type='group'),
'group-0/group-0-0': GroupMetadata(attributes={}, zarr_format=3, consolidated_metadata=None, node_type='group'),
'group-1': GroupMetadata(attributes={}, zarr_format=3, consolidated_metadata=None, node_type='group')}
"""
metadata = {}
def flatten(
key: str, group: GroupMetadata | ArrayV2Metadata | ArrayV3Metadata
) -> dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata]:
children: dict[str, ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] = {}
if isinstance(group, ArrayV2Metadata | ArrayV3Metadata):
children[key] = group
else:
if group.consolidated_metadata and group.consolidated_metadata.metadata is not None:
children[key] = replace(
group, consolidated_metadata=ConsolidatedMetadata(metadata={})
)
for name, val in group.consolidated_metadata.metadata.items():
full_key = f"{key}/{name}"
if isinstance(val, GroupMetadata):
children.update(flatten(full_key, val))
else:
children[full_key] = val
else:
children[key] = replace(group, consolidated_metadata=None)
return children
for k, v in self.metadata.items():
metadata.update(flatten(k, v))
return metadata
@dataclass(frozen=True)
class GroupMetadata(Metadata):
"""
Metadata for a Group.
"""
attributes: dict[str, Any] = field(default_factory=dict)
zarr_format: ZarrFormat = 3
consolidated_metadata: ConsolidatedMetadata | None = None
node_type: Literal["group"] = field(default="group", init=False)
def to_buffer_dict(self, prototype: BufferPrototype) -> dict[str, Buffer]:
json_indent = config.get("json_indent")
if self.zarr_format == 3:
return {
ZARR_JSON: prototype.buffer.from_bytes(
json.dumps(self.to_dict(), cls=V3JsonEncoder).encode()
)
}
else:
items = {
ZGROUP_JSON: prototype.buffer.from_bytes(
json.dumps({"zarr_format": self.zarr_format}, indent=json_indent).encode()
),
ZATTRS_JSON: prototype.buffer.from_bytes(
json.dumps(self.attributes, indent=json_indent).encode()
),
}
if self.consolidated_metadata:
d = {
ZGROUP_JSON: {"zarr_format": self.zarr_format},
ZATTRS_JSON: self.attributes,
}
consolidated_metadata = self.consolidated_metadata.to_dict()["metadata"]
assert isinstance(consolidated_metadata, dict)
for k, v in consolidated_metadata.items():
attrs = v.pop("attributes", None)
d[f"{k}/{ZATTRS_JSON}"] = attrs
if "shape" in v:
# it's an array
d[f"{k}/{ZARRAY_JSON}"] = v
else:
d[f"{k}/{ZGROUP_JSON}"] = {
"zarr_format": self.zarr_format,
"consolidated_metadata": {
"metadata": {},
"must_understand": False,
"kind": "inline",
},
}
items[ZMETADATA_V2_JSON] = prototype.buffer.from_bytes(
json.dumps(
{"metadata": d, "zarr_consolidated_format": 1},
cls=V3JsonEncoder,
).encode()
)
return items
def __init__(
self,
attributes: dict[str, Any] | None = None,
zarr_format: ZarrFormat = 3,
consolidated_metadata: ConsolidatedMetadata | None = None,
) -> None:
attributes_parsed = parse_attributes(attributes)
zarr_format_parsed = parse_zarr_format(zarr_format)
object.__setattr__(self, "attributes", attributes_parsed)
object.__setattr__(self, "zarr_format", zarr_format_parsed)
object.__setattr__(self, "consolidated_metadata", consolidated_metadata)
@classmethod
def from_dict(cls, data: dict[str, Any]) -> GroupMetadata:
data = dict(data)
assert data.pop("node_type", None) in ("group", None)
consolidated_metadata = data.pop("consolidated_metadata", None)
if consolidated_metadata:
data["consolidated_metadata"] = ConsolidatedMetadata.from_dict(consolidated_metadata)
zarr_format = data.get("zarr_format")
if zarr_format == 2 or zarr_format is None:
# zarr v2 allowed arbitrary keys here.
# We don't want the GroupMetadata constructor to fail just because someone put an
# extra key in the metadata.
expected = {x.name for x in fields(cls)}
data = {k: v for k, v in data.items() if k in expected}
return cls(**data)
def to_dict(self) -> dict[str, Any]:
result = asdict(replace(self, consolidated_metadata=None))
if self.consolidated_metadata:
result["consolidated_metadata"] = self.consolidated_metadata.to_dict()
return result
@dataclass(frozen=True)
class AsyncGroup:
"""
Asynchronous Group object.
"""
metadata: GroupMetadata
store_path: StorePath
@classmethod
async def from_store(
cls,
store: StoreLike,
*,
attributes: dict[str, Any] | None = None,
overwrite: bool = False,
zarr_format: ZarrFormat = 3,
) -> AsyncGroup:
store_path = await make_store_path(store)
if overwrite:
if store_path.store.supports_deletes:
await store_path.delete_dir()
else:
await ensure_no_existing_node(store_path, zarr_format=zarr_format)
else:
await ensure_no_existing_node(store_path, zarr_format=zarr_format)
attributes = attributes or {}
group = cls(
metadata=GroupMetadata(attributes=attributes, zarr_format=zarr_format),
store_path=store_path,
)
await group._save_metadata(ensure_parents=True)
return group
@classmethod
async def open(
cls,
store: StoreLike,
zarr_format: ZarrFormat | None = 3,
use_consolidated: bool | str | None = None,
) -> AsyncGroup:
"""Open a new AsyncGroup
Parameters
----------
store : StoreLike
zarr_format : {2, 3}, optional
use_consolidated : bool or str, default None
Whether to use consolidated metadata.
By default, consolidated metadata is used if it's present in the
store (in the ``zarr.json`` for Zarr format 3 and in the ``.zmetadata`` file
for Zarr format 2).
To explicitly require consolidated metadata, set ``use_consolidated=True``,
which will raise an exception if consolidated metadata is not found.
To explicitly *not* use consolidated metadata, set ``use_consolidated=False``,
which will fall back to using the regular, non consolidated metadata.
Zarr format 2 allowed configuring the key storing the consolidated metadata
(``.zmetadata`` by default). Specify the custom key as ``use_consolidated``
to load consolidated metadata from a non-default key.
"""
store_path = await make_store_path(store)
consolidated_key = ZMETADATA_V2_JSON
if (zarr_format == 2 or zarr_format is None) and isinstance(use_consolidated, str):
consolidated_key = use_consolidated
if zarr_format == 2:
paths = [store_path / ZGROUP_JSON, store_path / ZATTRS_JSON]
if use_consolidated or use_consolidated is None:
paths.append(store_path / consolidated_key)
zgroup_bytes, zattrs_bytes, *rest = await asyncio.gather(
*[path.get() for path in paths]
)
if zgroup_bytes is None:
raise FileNotFoundError(store_path)
if use_consolidated or use_consolidated is None:
maybe_consolidated_metadata_bytes = rest[0]
else:
maybe_consolidated_metadata_bytes = None
elif zarr_format == 3:
zarr_json_bytes = await (store_path / ZARR_JSON).get()
if zarr_json_bytes is None:
raise FileNotFoundError(store_path)
elif zarr_format is None:
(
zarr_json_bytes,
zgroup_bytes,
zattrs_bytes,
maybe_consolidated_metadata_bytes,
) = await asyncio.gather(
(store_path / ZARR_JSON).get(),
(store_path / ZGROUP_JSON).get(),
(store_path / ZATTRS_JSON).get(),
(store_path / str(consolidated_key)).get(),
)
if zarr_json_bytes is not None and zgroup_bytes is not None:
# warn and favor v3
msg = f"Both zarr.json (Zarr format 3) and .zgroup (Zarr format 2) metadata objects exist at {store_path}. Zarr format 3 will be used."
warnings.warn(msg, stacklevel=1)
if zarr_json_bytes is None and zgroup_bytes is None:
raise FileNotFoundError(
f"could not find zarr.json or .zgroup objects in {store_path}"
)
# set zarr_format based on which keys were found
if zarr_json_bytes is not None:
zarr_format = 3
else:
zarr_format = 2
else:
raise MetadataValidationError("zarr_format", "2, 3, or None", zarr_format)
if zarr_format == 2:
# this is checked above, asserting here for mypy
assert zgroup_bytes is not None
if use_consolidated and maybe_consolidated_metadata_bytes is None:
# the user requested consolidated metadata, but it was missing
raise ValueError(consolidated_key)
elif use_consolidated is False:
# the user explicitly opted out of consolidated_metadata.
# Discard anything we might have read.
maybe_consolidated_metadata_bytes = None
return cls._from_bytes_v2(
store_path, zgroup_bytes, zattrs_bytes, maybe_consolidated_metadata_bytes
)
else:
# V3 groups are comprised of a zarr.json object
assert zarr_json_bytes is not None
if not isinstance(use_consolidated, bool | None):
raise TypeError("use_consolidated must be a bool or None for Zarr format 3.")
return cls._from_bytes_v3(
store_path,
zarr_json_bytes,
use_consolidated=use_consolidated,
)
@classmethod
def _from_bytes_v2(
cls,
store_path: StorePath,
zgroup_bytes: Buffer,
zattrs_bytes: Buffer | None,
consolidated_metadata_bytes: Buffer | None,
) -> AsyncGroup:
# V2 groups are comprised of a .zgroup and .zattrs objects
zgroup = json.loads(zgroup_bytes.to_bytes())
zattrs = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {}
group_metadata = {**zgroup, "attributes": zattrs}
if consolidated_metadata_bytes is not None:
v2_consolidated_metadata = json.loads(consolidated_metadata_bytes.to_bytes())
v2_consolidated_metadata = v2_consolidated_metadata["metadata"]
# We already read zattrs and zgroup. Should we ignore these?
v2_consolidated_metadata.pop(".zattrs", None)
v2_consolidated_metadata.pop(".zgroup", None)
consolidated_metadata: defaultdict[str, dict[str, Any]] = defaultdict(dict)
# keys like air/.zarray, air/.zattrs
for k, v in v2_consolidated_metadata.items():
path, kind = k.rsplit("/.", 1)
if kind == "zarray":
consolidated_metadata[path].update(v)
elif kind == "zattrs":
consolidated_metadata[path]["attributes"] = v
elif kind == "zgroup":
consolidated_metadata[path].update(v)
else:
raise ValueError(f"Invalid file type '{kind}' at path '{path}")
group_metadata["consolidated_metadata"] = {
"metadata": dict(consolidated_metadata),
"kind": "inline",
"must_understand": False,
}
return cls.from_dict(store_path, group_metadata)
@classmethod
def _from_bytes_v3(
cls,
store_path: StorePath,
zarr_json_bytes: Buffer,
use_consolidated: bool | None,
) -> AsyncGroup:
group_metadata = json.loads(zarr_json_bytes.to_bytes())
if use_consolidated and group_metadata.get("consolidated_metadata") is None:
msg = f"Consolidated metadata requested with 'use_consolidated=True' but not found in '{store_path.path}'."
raise ValueError(msg)
elif use_consolidated is False:
# Drop consolidated metadata if it's there.
group_metadata.pop("consolidated_metadata", None)
return cls.from_dict(store_path, group_metadata)
@classmethod
def from_dict(
cls,
store_path: StorePath,
data: dict[str, Any],
) -> AsyncGroup:
return cls(
metadata=GroupMetadata.from_dict(data),
store_path=store_path,
)
async def setitem(self, key: str, value: Any) -> None:
"""
Fastpath for creating a new array
New arrays will be created with default array settings for the array type.
Parameters
----------
key : str
Array name
value : array-like
Array data
"""
path = self.store_path / key
await async_api.save_array(
store=path, arr=value, zarr_format=self.metadata.zarr_format, overwrite=True
)
async def getitem(
self,
key: str,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup:
"""
Get a subarray or subgroup from the group.
Parameters
----------
key : str
Array or group name
Returns
-------
AsyncArray or AsyncGroup
"""
store_path = self.store_path / key
logger.debug("key=%s, store_path=%s", key, store_path)
metadata: ArrayV2Metadata | ArrayV3Metadata | GroupMetadata
# Consolidated metadata lets us avoid some I/O operations so try that first.
if self.metadata.consolidated_metadata is not None:
return self._getitem_consolidated(store_path, key, prefix=self.name)
# Note:
# in zarr-python v2, we first check if `key` references an Array, else if `key` references
# a group,using standalone `contains_array` and `contains_group` functions. These functions
# are reusable, but for v3 they would perform redundant I/O operations.
# Not clear how much of that strategy we want to keep here.
elif self.metadata.zarr_format == 3:
zarr_json_bytes = await (store_path / ZARR_JSON).get()
if zarr_json_bytes is None:
raise KeyError(key)
else:
zarr_json = json.loads(zarr_json_bytes.to_bytes())
metadata = _build_metadata_v3(zarr_json)
return _build_node_v3(metadata, store_path)
elif self.metadata.zarr_format == 2:
# Q: how do we like optimistically fetching .zgroup, .zarray, and .zattrs?
# This guarantees that we will always make at least one extra request to the store
zgroup_bytes, zarray_bytes, zattrs_bytes = await asyncio.gather(
(store_path / ZGROUP_JSON).get(),
(store_path / ZARRAY_JSON).get(),
(store_path / ZATTRS_JSON).get(),
)
if zgroup_bytes is None and zarray_bytes is None:
raise KeyError(key)
# unpack the zarray, if this is None then we must be opening a group
zarray = json.loads(zarray_bytes.to_bytes()) if zarray_bytes else None
zgroup = json.loads(zgroup_bytes.to_bytes()) if zgroup_bytes else None
# unpack the zattrs, this can be None if no attrs were written
zattrs = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {}
if zarray is not None:
metadata = _build_metadata_v2(zarray, zattrs)
return _build_node_v2(metadata=metadata, store_path=store_path)
else:
# this is just for mypy
if TYPE_CHECKING:
assert zgroup is not None
metadata = _build_metadata_v2(zgroup, zattrs)
return _build_node_v2(metadata=metadata, store_path=store_path)
else:
raise ValueError(f"unexpected zarr_format: {self.metadata.zarr_format}")
def _getitem_consolidated(
self, store_path: StorePath, key: str, prefix: str
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata] | AsyncGroup:
# getitem, in the special case where we have consolidated metadata.
# Note that this is a regular def (non async) function.
# This shouldn't do any additional I/O.
# the caller needs to verify this!
assert self.metadata.consolidated_metadata is not None
# we support nested getitems like group/subgroup/array
indexers = key.split("/")
indexers.reverse()
metadata: ArrayV2Metadata | ArrayV3Metadata | GroupMetadata = self.metadata
while indexers:
indexer = indexers.pop()
if isinstance(metadata, ArrayV2Metadata | ArrayV3Metadata):
# we've indexed into an array with group["array/subarray"]. Invalid.
raise KeyError(key)
if metadata.consolidated_metadata is None:
# we've indexed into a group without consolidated metadata.
# This isn't normal; typically, consolidated metadata
# will include explicit markers for when there are no child
# nodes as metadata={}.
# We have some freedom in exactly how we interpret this case.
# For now, we treat None as the same as {}, i.e. we don't
# have any children.
raise KeyError(key)
try:
metadata = metadata.consolidated_metadata.metadata[indexer]
except KeyError as e:
# The Group Metadata has consolidated metadata, but the key
# isn't present. We trust this to mean that the key isn't in
# the hierarchy, and *don't* fall back to checking the store.
msg = f"'{key}' not found in consolidated metadata."
raise KeyError(msg) from e
# update store_path to ensure that AsyncArray/Group.name is correct
if prefix != "/":
key = "/".join([prefix.lstrip("/"), key])
store_path = StorePath(store=store_path.store, path=key)
if isinstance(metadata, GroupMetadata):
return AsyncGroup(metadata=metadata, store_path=store_path)
else:
return AsyncArray(metadata=metadata, store_path=store_path)
async def delitem(self, key: str) -> None:
"""Delete a group member.
Parameters
----------
key : str
Array or group name
"""
store_path = self.store_path / key
await store_path.delete_dir()
if self.metadata.consolidated_metadata:
self.metadata.consolidated_metadata.metadata.pop(key, None)
await self._save_metadata()
async def get(
self, key: str, default: DefaultT | None = None
) -> AsyncArray[Any] | AsyncGroup | DefaultT | None:
"""Obtain a group member, returning default if not found.
Parameters
----------
key : str
Group member name.
default : object
Default value to return if key is not found (default: None).
Returns
-------
object
Group member (AsyncArray or AsyncGroup) or default if not found.
"""
try:
return await self.getitem(key)
except KeyError:
return default
async def _save_metadata(self, ensure_parents: bool = False) -> None:
to_save = self.metadata.to_buffer_dict(default_buffer_prototype())
awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()]
if ensure_parents:
parents = _build_parents(self)
for parent in parents:
awaitables.extend(
[
(parent.store_path / key).set_if_not_exists(value)
for key, value in parent.metadata.to_buffer_dict(
default_buffer_prototype()
).items()
]
)
await asyncio.gather(*awaitables)
@property
def path(self) -> str:
"""Storage path."""
return self.store_path.path
@property
def name(self) -> str:
"""Group name following h5py convention."""
if self.path:
# follow h5py convention: add leading slash
name = self.path
if name[0] != "/":
name = "/" + name
return name
return "/"
@property
def basename(self) -> str:
"""Final component of name."""
return self.name.split("/")[-1]
@property
def attrs(self) -> dict[str, Any]:
return self.metadata.attributes
@property
def info(self) -> Any:
"""
Return a visual representation of the statically known information about a group.
Note that this doesn't include dynamic information, like the number of child
Groups or Arrays.
Returns
-------
GroupInfo
See Also
--------
AsyncGroup.info_complete
All information about a group, including dynamic information
"""
if self.metadata.consolidated_metadata:
members = list(self.metadata.consolidated_metadata.flattened_metadata.values())
else:
members = None
return self._info(members=members)
async def info_complete(self) -> Any:
"""
Return all the information for a group.
This includes dynamic information like the number
of child Groups or Arrays. If this group doesn't contain consolidated
metadata then this will need to read from the backing Store.
Returns
-------
GroupInfo
See Also
--------
AsyncGroup.info
"""
members = [x[1].metadata async for x in self.members(max_depth=None)]
return self._info(members=members)
def _info(
self, members: list[ArrayV2Metadata | ArrayV3Metadata | GroupMetadata] | None = None
) -> Any:
kwargs = {}
if members is not None:
kwargs["_count_members"] = len(members)
count_arrays = 0
count_groups = 0
for member in members:
if isinstance(member, GroupMetadata):
count_groups += 1
else:
count_arrays += 1
kwargs["_count_arrays"] = count_arrays
kwargs["_count_groups"] = count_groups
return GroupInfo(
_name=self.store_path.path,
_read_only=self.read_only,
_store_type=type(self.store_path.store).__name__,
_zarr_format=self.metadata.zarr_format,
# maybe do a typeddict
**kwargs, # type: ignore[arg-type]
)
@property
def store(self) -> Store:
return self.store_path.store
@property
def read_only(self) -> bool:
# Backwards compatibility for 2.x
return self.store_path.read_only
@property
def synchronizer(self) -> None:
# Backwards compatibility for 2.x
# Not implemented in 3.x yet.
return None
async def create_group(
self,
name: str,
*,
overwrite: bool = False,
attributes: dict[str, Any] | None = None,
) -> AsyncGroup:
"""Create a sub-group.
Parameters
----------
name : str
Group name.
overwrite : bool, optional
If True, do not raise an error if the group already exists.
attributes : dict, optional
Group attributes.
Returns
-------
g : AsyncGroup
"""
attributes = attributes or {}
return await type(self).from_store(
self.store_path / name,
attributes=attributes,
overwrite=overwrite,
zarr_format=self.metadata.zarr_format,
)
async def require_group(self, name: str, overwrite: bool = False) -> AsyncGroup:
"""Obtain a sub-group, creating one if it doesn't exist.
Parameters
----------
name : str
Group name.
overwrite : bool, optional
Overwrite any existing group with given `name` if present.
Returns
-------
g : AsyncGroup
"""
if overwrite:
# TODO: check that overwrite=True errors if an array exists where the group is being created
grp = await self.create_group(name, overwrite=True)
else:
try:
item: (
AsyncGroup | AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]
) = await self.getitem(name)
if not isinstance(item, AsyncGroup):
raise TypeError(
f"Incompatible object ({item.__class__.__name__}) already exists"
)
assert isinstance(item, AsyncGroup) # make mypy happy
grp = item
except KeyError:
grp = await self.create_group(name)
return grp
async def require_groups(self, *names: str) -> tuple[AsyncGroup, ...]:
"""Convenience method to require multiple groups in a single call.
Parameters
----------
*names : str
Group names.
Returns
-------
Tuple[AsyncGroup, ...]
"""
if not names: