-
-
Notifications
You must be signed in to change notification settings - Fork 300
/
Copy patharray.py
3279 lines (2819 loc) · 110 KB
/
array.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 json
from asyncio import gather
from dataclasses import dataclass, field
from itertools import starmap
from logging import getLogger
from typing import TYPE_CHECKING, Any, Generic, Literal, cast, overload
import numpy as np
import numpy.typing as npt
from zarr._compat import _deprecate_positional_args
from zarr.abc.store import Store, set_or_delete
from zarr.codecs import _get_default_array_bytes_codec
from zarr.codecs._v2 import V2Codec
from zarr.core._info import ArrayInfo
from zarr.core.attributes import Attributes
from zarr.core.buffer import (
BufferPrototype,
NDArrayLike,
NDBuffer,
default_buffer_prototype,
)
from zarr.core.chunk_grids import RegularChunkGrid, normalize_chunks
from zarr.core.chunk_key_encodings import (
ChunkKeyEncoding,
DefaultChunkKeyEncoding,
V2ChunkKeyEncoding,
)
from zarr.core.common import (
JSON,
ZARR_JSON,
ZARRAY_JSON,
ZATTRS_JSON,
ChunkCoords,
MemoryOrder,
ShapeLike,
ZarrFormat,
concurrent_map,
parse_dtype,
parse_shapelike,
product,
)
from zarr.core.config import config, parse_indexing_order
from zarr.core.indexing import (
BasicIndexer,
BasicSelection,
BlockIndex,
BlockIndexer,
CoordinateIndexer,
CoordinateSelection,
Fields,
Indexer,
MaskIndexer,
MaskSelection,
OIndex,
OrthogonalIndexer,
OrthogonalSelection,
Selection,
VIndex,
_iter_grid,
ceildiv,
check_fields,
check_no_multi_fields,
is_pure_fancy_indexing,
is_pure_orthogonal_indexing,
is_scalar,
pop_fields,
)
from zarr.core.metadata import (
ArrayMetadata,
ArrayMetadataDict,
ArrayV2Metadata,
ArrayV2MetadataDict,
ArrayV3Metadata,
ArrayV3MetadataDict,
T_ArrayMetadata,
)
from zarr.core.metadata.v3 import parse_node_type_array
from zarr.core.sync import sync
from zarr.errors import MetadataValidationError
from zarr.registry import get_pipeline_class
from zarr.storage import StoreLike, make_store_path
from zarr.storage.common import StorePath, ensure_no_existing_node
if TYPE_CHECKING:
from collections.abc import Iterable, Iterator, Sequence
from typing import Self
from zarr.abc.codec import Codec, CodecPipeline
from zarr.core.group import AsyncGroup
# Array and AsyncArray are defined in the base ``zarr`` namespace
__all__ = ["create_codec_pipeline", "parse_array_metadata"]
logger = getLogger(__name__)
def parse_array_metadata(data: Any) -> ArrayMetadata:
if isinstance(data, ArrayMetadata):
return data
elif isinstance(data, dict):
if data["zarr_format"] == 3:
meta_out = ArrayV3Metadata.from_dict(data)
if len(meta_out.storage_transformers) > 0:
msg = (
f"Array metadata contains storage transformers: {meta_out.storage_transformers}."
"Arrays with storage transformers are not supported in zarr-python at this time."
)
raise ValueError(msg)
return meta_out
elif data["zarr_format"] == 2:
return ArrayV2Metadata.from_dict(data)
raise TypeError
def create_codec_pipeline(metadata: ArrayMetadata) -> CodecPipeline:
if isinstance(metadata, ArrayV3Metadata):
return get_pipeline_class().from_codecs(metadata.codecs)
elif isinstance(metadata, ArrayV2Metadata):
v2_codec = V2Codec(filters=metadata.filters, compressor=metadata.compressor)
return get_pipeline_class().from_codecs([v2_codec])
else:
raise TypeError
async def get_array_metadata(
store_path: StorePath, zarr_format: ZarrFormat | None = 3
) -> dict[str, JSON]:
if zarr_format == 2:
zarray_bytes, zattrs_bytes = await gather(
(store_path / ZARRAY_JSON).get(), (store_path / ZATTRS_JSON).get()
)
if zarray_bytes is None:
raise FileNotFoundError(store_path)
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, zarray_bytes, zattrs_bytes = await gather(
(store_path / ZARR_JSON).get(),
(store_path / ZARRAY_JSON).get(),
(store_path / ZATTRS_JSON).get(),
)
if zarr_json_bytes is not None and zarray_bytes is not None:
# TODO: revisit this exception type
# alternatively, we could warn and favor v3
raise ValueError("Both zarr.json and .zarray objects exist")
if zarr_json_bytes is None and zarray_bytes is None:
raise FileNotFoundError(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)
metadata_dict: dict[str, JSON]
if zarr_format == 2:
# V2 arrays are comprised of a .zarray and .zattrs objects
assert zarray_bytes is not None
metadata_dict = json.loads(zarray_bytes.to_bytes())
zattrs_dict = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {}
metadata_dict["attributes"] = zattrs_dict
else:
# V3 arrays are comprised of a zarr.json object
assert zarr_json_bytes is not None
metadata_dict = json.loads(zarr_json_bytes.to_bytes())
parse_node_type_array(metadata_dict.get("node_type"))
return metadata_dict
@dataclass(frozen=True)
class AsyncArray(Generic[T_ArrayMetadata]):
"""
An asynchronous array class representing a chunked array stored in a Zarr store.
Parameters
----------
metadata : ArrayMetadata
The metadata of the array.
store_path : StorePath
The path to the Zarr store.
order : {'C', 'F'}, optional
The order of the array data in memory, by default None.
Attributes
----------
metadata : ArrayMetadata
The metadata of the array.
store_path : StorePath
The path to the Zarr store.
codec_pipeline : CodecPipeline
The codec pipeline used for encoding and decoding chunks.
order : {'C', 'F'}
The order of the array data in memory.
"""
metadata: T_ArrayMetadata
store_path: StorePath
codec_pipeline: CodecPipeline = field(init=False)
order: MemoryOrder
@overload
def __init__(
self: AsyncArray[ArrayV2Metadata],
metadata: ArrayV2Metadata | ArrayV2MetadataDict,
store_path: StorePath,
order: MemoryOrder | None = None,
) -> None: ...
@overload
def __init__(
self: AsyncArray[ArrayV3Metadata],
metadata: ArrayV3Metadata | ArrayV3MetadataDict,
store_path: StorePath,
order: MemoryOrder | None = None,
) -> None: ...
def __init__(
self,
metadata: ArrayMetadata | ArrayMetadataDict,
store_path: StorePath,
order: MemoryOrder | None = None,
) -> None:
if isinstance(metadata, dict):
zarr_format = metadata["zarr_format"]
# TODO: remove this when we extensively type the dict representation of metadata
_metadata = cast(dict[str, JSON], metadata)
if zarr_format == 2:
metadata = ArrayV2Metadata.from_dict(_metadata)
elif zarr_format == 3:
metadata = ArrayV3Metadata.from_dict(_metadata)
else:
raise ValueError(f"Invalid zarr_format: {zarr_format}. Expected 2 or 3")
metadata_parsed = parse_array_metadata(metadata)
order_parsed = parse_indexing_order(order or config.get("array.order"))
object.__setattr__(self, "metadata", metadata_parsed)
object.__setattr__(self, "store_path", store_path)
object.__setattr__(self, "order", order_parsed)
object.__setattr__(self, "codec_pipeline", create_codec_pipeline(metadata=metadata_parsed))
# this overload defines the function signature when zarr_format is 2
@overload
@classmethod
async def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ShapeLike,
dtype: npt.DTypeLike,
zarr_format: Literal[2],
fill_value: Any | None = None,
attributes: dict[str, JSON] | None = None,
chunks: ShapeLike | None = None,
dimension_separator: Literal[".", "/"] | None = None,
order: MemoryOrder | None = None,
filters: list[dict[str, JSON]] | None = None,
compressor: dict[str, JSON] | None = None,
# runtime
exists_ok: bool = False,
data: npt.ArrayLike | None = None,
) -> AsyncArray[ArrayV2Metadata]: ...
# this overload defines the function signature when zarr_format is 3
@overload
@classmethod
async def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ShapeLike,
dtype: npt.DTypeLike,
zarr_format: Literal[3],
fill_value: Any | None = None,
attributes: dict[str, JSON] | None = None,
# v3 only
chunk_shape: ChunkCoords | None = None,
chunk_key_encoding: (
ChunkKeyEncoding
| tuple[Literal["default"], Literal[".", "/"]]
| tuple[Literal["v2"], Literal[".", "/"]]
| None
) = None,
codecs: Iterable[Codec | dict[str, JSON]] | None = None,
dimension_names: Iterable[str] | None = None,
# runtime
exists_ok: bool = False,
data: npt.ArrayLike | None = None,
) -> AsyncArray[ArrayV3Metadata]: ...
# this overload is necessary to handle the case where the `zarr_format` kwarg is unspecified
@overload
@classmethod
async def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ShapeLike,
dtype: npt.DTypeLike,
zarr_format: Literal[3] = 3,
fill_value: Any | None = None,
attributes: dict[str, JSON] | None = None,
# v3 only
chunk_shape: ChunkCoords | None = None,
chunk_key_encoding: (
ChunkKeyEncoding
| tuple[Literal["default"], Literal[".", "/"]]
| tuple[Literal["v2"], Literal[".", "/"]]
| None
) = None,
codecs: Iterable[Codec | dict[str, JSON]] | None = None,
dimension_names: Iterable[str] | None = None,
# runtime
exists_ok: bool = False,
data: npt.ArrayLike | None = None,
) -> AsyncArray[ArrayV3Metadata]: ...
@overload
@classmethod
async def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ShapeLike,
dtype: npt.DTypeLike,
zarr_format: ZarrFormat,
fill_value: Any | None = None,
attributes: dict[str, JSON] | None = None,
# v3 only
chunk_shape: ChunkCoords | None = None,
chunk_key_encoding: (
ChunkKeyEncoding
| tuple[Literal["default"], Literal[".", "/"]]
| tuple[Literal["v2"], Literal[".", "/"]]
| None
) = None,
codecs: Iterable[Codec | dict[str, JSON]] | None = None,
dimension_names: Iterable[str] | None = None,
# v2 only
chunks: ShapeLike | None = None,
dimension_separator: Literal[".", "/"] | None = None,
order: MemoryOrder | None = None,
filters: list[dict[str, JSON]] | None = None,
compressor: dict[str, JSON] | None = None,
# runtime
exists_ok: bool = False,
data: npt.ArrayLike | None = None,
) -> AsyncArray[ArrayV3Metadata] | AsyncArray[ArrayV2Metadata]: ...
@classmethod
async def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ShapeLike,
dtype: npt.DTypeLike,
zarr_format: ZarrFormat = 3,
fill_value: Any | None = None,
attributes: dict[str, JSON] | None = None,
# v3 only
chunk_shape: ChunkCoords | None = None,
chunk_key_encoding: (
ChunkKeyEncoding
| tuple[Literal["default"], Literal[".", "/"]]
| tuple[Literal["v2"], Literal[".", "/"]]
| None
) = None,
codecs: Iterable[Codec | dict[str, JSON]] | None = None,
dimension_names: Iterable[str] | None = None,
# v2 only
chunks: ShapeLike | None = None,
dimension_separator: Literal[".", "/"] | None = None,
order: MemoryOrder | None = None,
filters: list[dict[str, JSON]] | None = None,
compressor: dict[str, JSON] | None = None,
# runtime
exists_ok: bool = False,
data: npt.ArrayLike | None = None,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
"""
Method to create a new asynchronous array instance.
Parameters
----------
store : StoreLike
The store where the array will be created.
shape : ShapeLike
The shape of the array.
dtype : npt.DTypeLike
The data type of the array.
zarr_format : ZarrFormat, optional
The Zarr format version (default is 3).
fill_value : Any, optional
The fill value of the array (default is None).
attributes : dict[str, JSON], optional
The attributes of the array (default is None).
chunk_shape : ChunkCoords, optional
The shape of the array's chunks (default is None).
chunk_key_encoding : ChunkKeyEncoding, optional
The chunk key encoding (default is None).
codecs : Iterable[Codec | dict[str, JSON]], optional
The codecs used to encode the data (default is None).
dimension_names : Iterable[str], optional
The names of the dimensions (default is None).
chunks : ShapeLike, optional
The shape of the array's chunks (default is None).
V2 only. V3 arrays should not have 'chunks' parameter.
dimension_separator : Literal[".", "/"], optional
The dimension separator (default is None).
V2 only. V3 arrays cannot have a dimension separator.
order : Literal["C", "F"], optional
The order of the array (default is None).
filters : list[dict[str, JSON]], optional
The filters used to compress the data (default is None).
V2 only. V3 arrays should not have 'filters' parameter.
compressor : dict[str, JSON], optional
The compressor used to compress the data (default is None).
V2 only. V3 arrays should not have 'compressor' parameter.
exists_ok : bool, optional
Whether to raise an error if the store already exists (default is False).
data : npt.ArrayLike, optional
The data to be inserted into the array (default is None).
Returns
-------
AsyncArray
The created asynchronous array instance.
Examples
--------
>>> import zarr
>>> store = zarr.storage.MemoryStore(mode='w')
>>> async_arr = await zarr.core.array.AsyncArray.create(
>>> store=store,
>>> shape=(100,100),
>>> chunks=(10,10),
>>> dtype='i4',
>>> fill_value=0)
<AsyncArray memory://140349042942400 shape=(100, 100) dtype=int32>
"""
store_path = await make_store_path(store)
dtype_parsed = parse_dtype(dtype, zarr_format)
shape = parse_shapelike(shape)
if chunks is not None and chunk_shape is not None:
raise ValueError("Only one of chunk_shape or chunks can be provided.")
if chunks:
_chunks = normalize_chunks(chunks, shape, dtype_parsed.itemsize)
else:
_chunks = normalize_chunks(chunk_shape, shape, dtype_parsed.itemsize)
result: AsyncArray[ArrayV3Metadata] | AsyncArray[ArrayV2Metadata]
if zarr_format == 3:
if dimension_separator is not None:
raise ValueError(
"dimension_separator cannot be used for arrays with version 3. Use chunk_key_encoding instead."
)
if filters is not None:
raise ValueError(
"filters cannot be used for arrays with version 3. Use array-to-array codecs instead."
)
if compressor is not None:
raise ValueError(
"compressor cannot be used for arrays with version 3. Use bytes-to-bytes codecs instead."
)
result = await cls._create_v3(
store_path,
shape=shape,
dtype=dtype_parsed,
chunk_shape=_chunks,
fill_value=fill_value,
chunk_key_encoding=chunk_key_encoding,
codecs=codecs,
dimension_names=dimension_names,
attributes=attributes,
exists_ok=exists_ok,
order=order,
)
elif zarr_format == 2:
if dtype is str or dtype == "str":
# another special case: zarr v2 added the vlen-utf8 codec
vlen_codec: dict[str, JSON] = {"id": "vlen-utf8"}
if filters and not any(x["id"] == "vlen-utf8" for x in filters):
filters = list(filters) + [vlen_codec]
else:
filters = [vlen_codec]
if codecs is not None:
raise ValueError(
"codecs cannot be used for arrays with version 2. Use filters and compressor instead."
)
if chunk_key_encoding is not None:
raise ValueError(
"chunk_key_encoding cannot be used for arrays with version 2. Use dimension_separator instead."
)
if dimension_names is not None:
raise ValueError("dimension_names cannot be used for arrays with version 2.")
result = await cls._create_v2(
store_path,
shape=shape,
dtype=dtype_parsed,
chunks=_chunks,
dimension_separator=dimension_separator,
fill_value=fill_value,
order=order,
filters=filters,
compressor=compressor,
attributes=attributes,
exists_ok=exists_ok,
)
else:
raise ValueError(f"Insupported zarr_format. Got: {zarr_format}")
if data is not None:
# insert user-provided data
await result.setitem(..., data)
return result
@classmethod
async def _create_v3(
cls,
store_path: StorePath,
*,
shape: ShapeLike,
dtype: npt.DTypeLike,
chunk_shape: ChunkCoords,
fill_value: Any | None = None,
order: MemoryOrder | None = None,
chunk_key_encoding: (
ChunkKeyEncoding
| tuple[Literal["default"], Literal[".", "/"]]
| tuple[Literal["v2"], Literal[".", "/"]]
| None
) = None,
codecs: Iterable[Codec | dict[str, JSON]] | None = None,
dimension_names: Iterable[str] | None = None,
attributes: dict[str, JSON] | None = None,
exists_ok: bool = False,
) -> AsyncArray[ArrayV3Metadata]:
if exists_ok:
if store_path.store.supports_deletes:
await store_path.delete_dir()
else:
await ensure_no_existing_node(store_path, zarr_format=3)
else:
await ensure_no_existing_node(store_path, zarr_format=3)
shape = parse_shapelike(shape)
codecs = (
list(codecs)
if codecs is not None
else [_get_default_array_bytes_codec(np.dtype(dtype))]
)
if chunk_key_encoding is None:
chunk_key_encoding = ("default", "/")
assert chunk_key_encoding is not None
if isinstance(chunk_key_encoding, tuple):
chunk_key_encoding = (
V2ChunkKeyEncoding(separator=chunk_key_encoding[1])
if chunk_key_encoding[0] == "v2"
else DefaultChunkKeyEncoding(separator=chunk_key_encoding[1])
)
metadata = ArrayV3Metadata(
shape=shape,
data_type=dtype,
chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape),
chunk_key_encoding=chunk_key_encoding,
fill_value=fill_value,
codecs=codecs,
dimension_names=tuple(dimension_names) if dimension_names else None,
attributes=attributes or {},
)
array = cls(metadata=metadata, store_path=store_path, order=order)
await array._save_metadata(metadata, ensure_parents=True)
return array
@classmethod
async def _create_v2(
cls,
store_path: StorePath,
*,
shape: ChunkCoords,
dtype: npt.DTypeLike,
chunks: ChunkCoords,
dimension_separator: Literal[".", "/"] | None = None,
fill_value: None | float = None,
order: MemoryOrder | None = None,
filters: list[dict[str, JSON]] | None = None,
compressor: dict[str, JSON] | None = None,
attributes: dict[str, JSON] | None = None,
exists_ok: bool = False,
) -> AsyncArray[ArrayV2Metadata]:
if exists_ok:
if store_path.store.supports_deletes:
await store_path.delete_dir()
else:
await ensure_no_existing_node(store_path, zarr_format=2)
else:
await ensure_no_existing_node(store_path, zarr_format=2)
if order is None:
order = parse_indexing_order(config.get("array.order"))
if dimension_separator is None:
dimension_separator = "."
metadata = ArrayV2Metadata(
shape=shape,
dtype=np.dtype(dtype),
chunks=chunks,
order=order,
dimension_separator=dimension_separator,
fill_value=fill_value,
compressor=compressor,
filters=filters,
attributes=attributes,
)
array = cls(metadata=metadata, store_path=store_path, order=order)
await array._save_metadata(metadata, ensure_parents=True)
return array
@classmethod
def from_dict(
cls,
store_path: StorePath,
data: dict[str, JSON],
) -> AsyncArray[ArrayV3Metadata] | AsyncArray[ArrayV2Metadata]:
"""
Create a Zarr array from a dictionary, with support for both Zarr v2 and v3 metadata.
Parameters
----------
store_path : StorePath
The path within the store where the array should be created.
data : dict
A dictionary representing the array data. This dictionary should include necessary metadata
for the array, such as shape, dtype, and other attributes. The format of the metadata
will determine whether a Zarr v2 or v3 array is created.
Returns
-------
AsyncArray[ArrayV3Metadata] or AsyncArray[ArrayV2Metadata]
The created Zarr array, either using v2 or v3 metadata based on the provided data.
Raises
------
ValueError
If the dictionary data is invalid or incompatible with either Zarr v2 or v3 array creation.
"""
metadata = parse_array_metadata(data)
return cls(metadata=metadata, store_path=store_path)
@classmethod
async def open(
cls,
store: StoreLike,
zarr_format: ZarrFormat | None = 3,
) -> AsyncArray[ArrayV3Metadata] | AsyncArray[ArrayV2Metadata]:
"""
Async method to open an existing Zarr array from a given store.
Parameters
----------
store : StoreLike
The store containing the Zarr array.
zarr_format : ZarrFormat | None, optional
The Zarr format version (default is 3).
Returns
-------
AsyncArray
The opened Zarr array.
Examples
--------
>>> import zarr
>>> store = zarr.storage.MemoryStore(mode='w')
>>> async_arr = await AsyncArray.open(store) # doctest: +ELLIPSIS
<AsyncArray memory://... shape=(100, 100) dtype=int32>
"""
store_path = await make_store_path(store)
metadata_dict = await get_array_metadata(store_path, zarr_format=zarr_format)
# TODO: remove this cast when we have better type hints
_metadata_dict = cast(ArrayV3MetadataDict, metadata_dict)
return cls(store_path=store_path, metadata=_metadata_dict)
@property
def store(self) -> Store:
return self.store_path.store
@property
def ndim(self) -> int:
"""Returns the number of dimensions in the Array.
Returns
-------
int
The number of dimensions in the Array.
"""
return len(self.metadata.shape)
@property
def shape(self) -> ChunkCoords:
"""Returns the shape of the Array.
Returns
-------
tuple
The shape of the Array.
"""
return self.metadata.shape
@property
def chunks(self) -> ChunkCoords:
"""Returns the chunk shape of the Array.
Only defined for arrays using using `RegularChunkGrid`.
If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised.
Returns
-------
ChunkCoords:
The chunk shape of the Array.
"""
if isinstance(self.metadata.chunk_grid, RegularChunkGrid):
return self.metadata.chunk_grid.chunk_shape
msg = (
f"The `chunks` attribute is only defined for arrays using `RegularChunkGrid`."
f"This array has a {self.metadata.chunk_grid} instead."
)
raise NotImplementedError(msg)
@property
def size(self) -> int:
"""Returns the total number of elements in the array
Returns
-------
int
Total number of elements in the array
"""
return np.prod(self.metadata.shape).item()
@property
def dtype(self) -> np.dtype[Any]:
"""Returns the data type of the array.
Returns
-------
np.dtype
Data type of the array
"""
return self.metadata.dtype
@property
def attrs(self) -> dict[str, JSON]:
"""Returns the attributes of the array.
Returns
-------
dict
Attributes of the array
"""
return self.metadata.attributes
@property
def read_only(self) -> bool:
"""Returns True if the array is read-only.
Returns
-------
bool
True if the array is read-only
"""
# Backwards compatibility for 2.x
return self.store_path.read_only
@property
def path(self) -> str:
"""Storage path.
Returns
-------
str
The path to the array in the Zarr store.
"""
return self.store_path.path
@property
def name(self) -> str | None:
"""Array name following h5py convention.
Returns
-------
str
The name of the array.
"""
if self.path:
# follow h5py convention: add leading slash
name = self.path
if name[0] != "/":
name = "/" + name
return name
return None
@property
def basename(self) -> str | None:
"""Final component of name.
Returns
-------
str
The basename or final component of the array name.
"""
if self.name is not None:
return self.name.split("/")[-1]
return None
@property
def cdata_shape(self) -> ChunkCoords:
"""
The shape of the chunk grid for this array.
Returns
-------
Tuple[int]
The shape of the chunk grid for this array.
"""
return tuple(starmap(ceildiv, zip(self.shape, self.chunks, strict=False)))
@property
def nchunks(self) -> int:
"""
The number of chunks in the stored representation of this array.
Returns
-------
int
The total number of chunks in the array.
"""
return product(self.cdata_shape)
async def nchunks_initialized(self) -> int:
"""
Calculate the number of chunks that have been initialized, i.e. the number of chunks that have
been persisted to the storage backend.
Returns
-------
nchunks_initialized : int
The number of chunks that have been initialized.
Notes
-----
On :class:`AsyncArray` this is an asynchronous method, unlike the (synchronous)
property :attr:`Array.nchunks_initialized`.
Examples
--------
>>> arr = await zarr.api.asynchronous.create(shape=(10,), chunks=(2,))
>>> await arr.nchunks_initialized()
0
>>> await arr.setitem(slice(5), 1)
>>> await arr.nchunks_initialized()
3
"""
return len(await chunks_initialized(self))
async def nbytes_stored(self) -> int:
return await self.store_path.store.getsize_prefix(self.store_path.path)
def _iter_chunk_coords(
self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None
) -> Iterator[ChunkCoords]:
"""
Create an iterator over the coordinates of chunks in chunk grid space. If the `origin`
keyword is used, iteration will start at the chunk index specified by `origin`.
The default behavior is to start at the origin of the grid coordinate space.
If the `selection_shape` keyword is used, iteration will be bounded over a contiguous region
ranging from `[origin, origin selection_shape]`, where the upper bound is exclusive as
per python indexing conventions.
Parameters
----------
origin : Sequence[int] | None, default=None
The origin of the selection relative to the array's chunk grid.
selection_shape : Sequence[int] | None, default=None
The shape of the selection in chunk grid coordinates.
Yields
------
chunk_coords: ChunkCoords
The coordinates of each chunk in the selection.
"""
return _iter_grid(self.cdata_shape, origin=origin, selection_shape=selection_shape)
def _iter_chunk_keys(
self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None
) -> Iterator[str]:
"""
Iterate over the storage keys of each chunk, relative to an optional origin, and optionally
limited to a contiguous region in chunk grid coordinates.
Parameters
----------
origin : Sequence[int] | None, default=None
The origin of the selection relative to the array's chunk grid.
selection_shape : Sequence[int] | None, default=None
The shape of the selection in chunk grid coordinates.
Yields
------
key: str
The storage key of each chunk in the selection.
"""
# Iterate over the coordinates of chunks in chunk grid space.
for k in self._iter_chunk_coords(origin=origin, selection_shape=selection_shape):
# Encode the chunk key from the chunk coordinates.
yield self.metadata.encode_chunk_key(k)
def _iter_chunk_regions(
self, *, origin: Sequence[int] | None = None, selection_shape: Sequence[int] | None = None
) -> Iterator[tuple[slice, ...]]:
"""
Iterate over the regions spanned by each chunk.
Parameters
----------
origin : Sequence[int] | None, default=None
The origin of the selection relative to the array's chunk grid.
selection_shape : Sequence[int] | None, default=None
The shape of the selection in chunk grid coordinates.
Yields
------
region: tuple[slice, ...]
A tuple of slice objects representing the region spanned by each chunk in the selection.
"""
for cgrid_position in self._iter_chunk_coords(
origin=origin, selection_shape=selection_shape
):
out: tuple[slice, ...] = ()
for c_pos, c_shape in zip(cgrid_position, self.chunks, strict=False):
start = c_pos * c_shape
stop = start + c_shape
out += (slice(start, stop, 1),)
yield out
@property
def nbytes(self) -> int:
"""
The number of bytes that can be stored in this array.
"""
return self.nchunks * self.dtype.itemsize
async def _get_selection(
self,
indexer: Indexer,
*,
prototype: BufferPrototype,
out: NDBuffer | None = None,
fields: Fields | None = None,
) -> NDArrayLike:
# check fields are sensible
out_dtype = check_fields(fields, self.dtype)
# setup output buffer
if out is not None:
if isinstance(out, NDBuffer):
out_buffer = out
else:
raise TypeError(f"out argument needs to be an NDBuffer. Got {type(out)!r}")
if out_buffer.shape != indexer.shape:
raise ValueError(
f"shape of out argument doesn't match. Expected {indexer.shape}, got {out.shape}"
)
else: