-
-
Notifications
You must be signed in to change notification settings - Fork 325
/
Copy patharray.py
4770 lines (4150 loc) · 170 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
import warnings
from asyncio import gather
from collections.abc import Iterable
from dataclasses import dataclass, field, replace
from itertools import starmap
from logging import getLogger
from typing import (
TYPE_CHECKING,
Any,
Generic,
Literal,
TypeAlias,
TypedDict,
cast,
overload,
)
from warnings import warn
import numcodecs
import numcodecs.abc
import numpy as np
import numpy.typing as npt
from typing_extensions import deprecated
import zarr
from zarr._compat import _deprecate_positional_args
from zarr.abc.codec import ArrayArrayCodec, ArrayBytesCodec, BytesBytesCodec, Codec
from zarr.abc.store import Store, set_or_delete
from zarr.codecs._v2 import V2Codec
from zarr.core._info import ArrayInfo
from zarr.core.array_spec import ArrayConfig, ArrayConfigLike, parse_array_config
from zarr.core.attributes import Attributes
from zarr.core.buffer import (
BufferPrototype,
NDArrayLike,
NDArrayLikeOrScalar,
NDBuffer,
default_buffer_prototype,
)
from zarr.core.buffer.cpu import buffer_prototype as cpu_buffer_prototype
from zarr.core.chunk_grids import RegularChunkGrid, _auto_partition, normalize_chunks
from zarr.core.chunk_key_encodings import (
ChunkKeyEncoding,
ChunkKeyEncodingLike,
DefaultChunkKeyEncoding,
V2ChunkKeyEncoding,
)
from zarr.core.common import (
JSON,
ZARR_JSON,
ZARRAY_JSON,
ZATTRS_JSON,
ChunkCoords,
MemoryOrder,
ShapeLike,
ZarrFormat,
_default_zarr_format,
_warn_order_kwarg,
concurrent_map,
parse_dtype,
parse_order,
parse_shapelike,
product,
)
from zarr.core.config import config as zarr_config
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.v2 import (
_default_compressor,
_default_filters,
parse_compressor,
parse_filters,
)
from zarr.core.metadata.v3 import DataType, parse_node_type_array
from zarr.core.sync import sync
from zarr.errors import MetadataValidationError
from zarr.registry import (
_parse_array_array_codec,
_parse_array_bytes_codec,
_parse_bytes_bytes_codec,
get_pipeline_class,
)
from zarr.storage._common import StorePath, ensure_no_existing_node, make_store_path
if TYPE_CHECKING:
from collections.abc import Iterator, Sequence
from typing import Self
from zarr.abc.codec import CodecPipeline
from zarr.codecs.sharding import ShardingCodecIndexLocation
from zarr.core.group import AsyncGroup
from zarr.storage import StoreLike
# 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(prototype=cpu_buffer_prototype),
(store_path / ZATTRS_JSON).get(prototype=cpu_buffer_prototype),
)
if zarray_bytes is None:
raise FileNotFoundError(store_path)
elif zarr_format == 3:
zarr_json_bytes = await (store_path / ZARR_JSON).get(prototype=cpu_buffer_prototype)
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(prototype=cpu_buffer_prototype),
(store_path / ZARRAY_JSON).get(prototype=cpu_buffer_prototype),
(store_path / ZATTRS_JSON).get(prototype=cpu_buffer_prototype),
)
if zarr_json_bytes is not None and zarray_bytes is not None:
# warn and favor v3
msg = f"Both zarr.json (Zarr format 3) and .zarray (Zarr format 2) metadata objects exist at {store_path}. Zarr v3 will be used."
warnings.warn(msg, stacklevel=1)
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.
config : ArrayConfigLike, optional
The runtime configuration of the array, 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.
_config : ArrayConfig
The runtime configuration of the array.
"""
metadata: T_ArrayMetadata
store_path: StorePath
codec_pipeline: CodecPipeline = field(init=False)
_config: ArrayConfig
@overload
def __init__(
self: AsyncArray[ArrayV2Metadata],
metadata: ArrayV2Metadata | ArrayV2MetadataDict,
store_path: StorePath,
config: ArrayConfigLike | None = None,
) -> None: ...
@overload
def __init__(
self: AsyncArray[ArrayV3Metadata],
metadata: ArrayV3Metadata | ArrayV3MetadataDict,
store_path: StorePath,
config: ArrayConfigLike | None = None,
) -> None: ...
def __init__(
self,
metadata: ArrayMetadata | ArrayMetadataDict,
store_path: StorePath,
config: ArrayConfigLike | 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)
config_parsed = parse_array_config(config)
object.__setattr__(self, "metadata", metadata_parsed)
object.__setattr__(self, "store_path", store_path)
object.__setattr__(self, "_config", config_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
overwrite: bool = False,
data: npt.ArrayLike | None = None,
config: ArrayConfigLike | 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: ShapeLike | 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
overwrite: bool = False,
data: npt.ArrayLike | None = None,
config: ArrayConfigLike | None = None,
) -> AsyncArray[ArrayV3Metadata]: ...
@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: ShapeLike | 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
overwrite: bool = False,
data: npt.ArrayLike | None = None,
config: ArrayConfigLike | 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: ShapeLike | 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
overwrite: bool = False,
data: npt.ArrayLike | None = None,
config: ArrayConfigLike | None = None,
) -> AsyncArray[ArrayV3Metadata] | AsyncArray[ArrayV2Metadata]: ...
@classmethod
@deprecated("Use zarr.api.asynchronous.create_array instead.")
@_deprecate_positional_args
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: ShapeLike | None = None,
chunk_key_encoding: (
ChunkKeyEncodingLike
| 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
overwrite: bool = False,
data: npt.ArrayLike | None = None,
config: ArrayConfigLike | None = None,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
"""Method to create a new asynchronous array instance.
.. deprecated:: 3.0.0
Deprecated in favor of :func:`zarr.api.asynchronous.create_array`.
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
Zarr format 3 only. Zarr format 2 arrays should use `chunks` instead.
If not specified, default are guessed based on the shape and dtype.
chunk_key_encoding : ChunkKeyEncodingLike, optional
A specification of how the chunk keys are represented in storage.
Zarr format 3 only. Zarr format 2 arrays should use `dimension_separator` instead.
Default is ``("default", "/")``.
codecs : Sequence of Codecs or dicts, optional
An iterable of Codec or dict serializations of Codecs. The elements of
this collection specify the transformation from array values to stored bytes.
Zarr format 3 only. Zarr format 2 arrays should use ``filters`` and ``compressor`` instead.
If no codecs are provided, default codecs will be used:
- For numeric arrays, the default is ``BytesCodec`` and ``ZstdCodec``.
- For Unicode strings, the default is ``VLenUTF8Codec`` and ``ZstdCodec``.
- For bytes or objects, the default is ``VLenBytesCodec`` and ``ZstdCodec``.
These defaults can be changed by modifying the value of ``array.v3_default_filters``,
``array.v3_default_serializer`` and ``array.v3_default_compressors`` in :mod:`zarr.core.config`.
dimension_names : Iterable[str], optional
The names of the dimensions (default is None).
Zarr format 3 only. Zarr format 2 arrays should not use this parameter.
chunks : ShapeLike, optional
The shape of the array's chunks.
Zarr format 2 only. Zarr format 3 arrays should use ``chunk_shape`` instead.
If not specified, default are guessed based on the shape and dtype.
dimension_separator : Literal[".", "/"], optional
The dimension separator (default is ".").
Zarr format 2 only. Zarr format 3 arrays should use ``chunk_key_encoding`` instead.
order : Literal["C", "F"], optional
The memory of the array (default is "C").
If ``zarr_format`` is 2, this parameter sets the memory order of the array.
If `zarr_format`` is 3, then this parameter is deprecated, because memory order
is a runtime parameter for Zarr 3 arrays. The recommended way to specify the memory
order for Zarr 3 arrays is via the ``config`` parameter, e.g. ``{'config': 'C'}``.
filters : list[dict[str, JSON]], optional
Sequence of filters to use to encode chunk data prior to compression.
Zarr format 2 only. Zarr format 3 arrays should use ``codecs`` instead. If no ``filters``
are provided, a default set of filters will be used.
These defaults can be changed by modifying the value of ``array.v2_default_filters`` in :mod:`zarr.core.config`.
compressor : dict[str, JSON], optional
The compressor used to compress the data (default is None).
Zarr format 2 only. Zarr format 3 arrays should use ``codecs`` instead.
If no ``compressor`` is provided, a default compressor will be used:
- For numeric arrays, the default is ``ZstdCodec``.
- For Unicode strings, the default is ``VLenUTF8Codec``.
- For bytes or objects, the default is ``VLenBytesCodec``.
These defaults can be changed by modifying the value of ``array.v2_default_compressor`` in :mod:`zarr.core.config`.
overwrite : 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).
config : ArrayConfigLike, optional
Runtime configuration for the array.
Returns
-------
AsyncArray
The created asynchronous array instance.
"""
return await cls._create(
store,
# v2 and v3
shape=shape,
dtype=dtype,
zarr_format=zarr_format,
fill_value=fill_value,
attributes=attributes,
# v3 only
chunk_shape=chunk_shape,
chunk_key_encoding=chunk_key_encoding,
codecs=codecs,
dimension_names=dimension_names,
# v2 only
chunks=chunks,
dimension_separator=dimension_separator,
order=order,
filters=filters,
compressor=compressor,
# runtime
overwrite=overwrite,
data=data,
config=config,
)
@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: ShapeLike | None = None,
chunk_key_encoding: (
ChunkKeyEncodingLike
| 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
overwrite: bool = False,
data: npt.ArrayLike | None = None,
config: ArrayConfigLike | None = None,
) -> AsyncArray[ArrayV2Metadata] | AsyncArray[ArrayV3Metadata]:
"""Method to create a new asynchronous array instance.
See :func:`AsyncArray.create` for more details.
Deprecated in favor of :func:`zarr.api.asynchronous.create_array`.
"""
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)
config_parsed = parse_array_config(config)
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 zarr_format 3. Use chunk_key_encoding instead."
)
if filters is not None:
raise ValueError(
"filters cannot be used for arrays with zarr_format 3. Use array-to-array codecs instead."
)
if compressor is not None:
raise ValueError(
"compressor cannot be used for arrays with zarr_format 3. Use bytes-to-bytes codecs instead."
)
if order is not None:
_warn_order_kwarg()
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,
overwrite=overwrite,
config=config_parsed,
)
elif zarr_format == 2:
if codecs is not None:
raise ValueError(
"codecs cannot be used for arrays with zarr_format 2. Use filters and compressor instead."
)
if chunk_key_encoding is not None:
raise ValueError(
"chunk_key_encoding cannot be used for arrays with zarr_format 2. Use dimension_separator instead."
)
if dimension_names is not None:
raise ValueError("dimension_names cannot be used for arrays with zarr_format 2.")
if order is None:
order_parsed = parse_order(zarr_config.get("array.order"))
else:
order_parsed = order
result = await cls._create_v2(
store_path,
shape=shape,
dtype=dtype_parsed,
chunks=_chunks,
dimension_separator=dimension_separator,
fill_value=fill_value,
order=order_parsed,
config=config_parsed,
filters=filters,
compressor=compressor,
attributes=attributes,
overwrite=overwrite,
)
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
@staticmethod
def _create_metadata_v3(
shape: ShapeLike,
dtype: np.dtype[Any],
chunk_shape: ChunkCoords,
fill_value: Any | None = None,
chunk_key_encoding: ChunkKeyEncodingLike | None = None,
codecs: Iterable[Codec | dict[str, JSON]] | None = None,
dimension_names: Iterable[str] | None = None,
attributes: dict[str, JSON] | None = None,
) -> ArrayV3Metadata:
"""
Create an instance of ArrayV3Metadata.
"""
shape = parse_shapelike(shape)
codecs = list(codecs) if codecs is not None else _get_default_codecs(np.dtype(dtype))
chunk_key_encoding_parsed: ChunkKeyEncodingLike
if chunk_key_encoding is None:
chunk_key_encoding_parsed = {"name": "default", "separator": "/"}
else:
chunk_key_encoding_parsed = chunk_key_encoding
if dtype.kind in "UTS":
warn(
f"The dtype `{dtype}` is currently not part in the Zarr format 3 specification. It "
"may not be supported by other zarr implementations and may change in the future.",
category=UserWarning,
stacklevel=2,
)
chunk_grid_parsed = RegularChunkGrid(chunk_shape=chunk_shape)
return ArrayV3Metadata(
shape=shape,
data_type=dtype,
chunk_grid=chunk_grid_parsed,
chunk_key_encoding=chunk_key_encoding_parsed,
fill_value=fill_value,
codecs=codecs,
dimension_names=tuple(dimension_names) if dimension_names else None,
attributes=attributes or {},
)
@classmethod
async def _create_v3(
cls,
store_path: StorePath,
*,
shape: ShapeLike,
dtype: np.dtype[Any],
chunk_shape: ChunkCoords,
config: ArrayConfig,
fill_value: Any | None = None,
chunk_key_encoding: (
ChunkKeyEncodingLike
| 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,
overwrite: bool = False,
) -> AsyncArray[ArrayV3Metadata]:
if overwrite:
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)
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 = cls._create_metadata_v3(
shape=shape,
dtype=dtype,
chunk_shape=chunk_shape,
fill_value=fill_value,
chunk_key_encoding=chunk_key_encoding,
codecs=codecs,
dimension_names=dimension_names,
attributes=attributes,
)
array = cls(metadata=metadata, store_path=store_path, config=config)
await array._save_metadata(metadata, ensure_parents=True)
return array
@staticmethod
def _create_metadata_v2(
shape: ChunkCoords,
dtype: np.dtype[Any],
chunks: ChunkCoords,
order: MemoryOrder,
dimension_separator: Literal[".", "/"] | None = None,
fill_value: float | None = None,
filters: Iterable[dict[str, JSON] | numcodecs.abc.Codec] | None = None,
compressor: dict[str, JSON] | numcodecs.abc.Codec | None = None,
attributes: dict[str, JSON] | None = None,
) -> ArrayV2Metadata:
if dimension_separator is None:
dimension_separator = "."
dtype = parse_dtype(dtype, zarr_format=2)
# inject VLenUTF8 for str dtype if not already present
if np.issubdtype(dtype, np.str_):
filters = filters or []
from numcodecs.vlen import VLenUTF8
if not any(isinstance(x, VLenUTF8) or x["id"] == "vlen-utf8" for x in filters):
filters = list(filters) + [VLenUTF8()]
return 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,
)
@classmethod
async def _create_v2(
cls,
store_path: StorePath,
*,
shape: ChunkCoords,
dtype: np.dtype[Any],
chunks: ChunkCoords,
order: MemoryOrder,
config: ArrayConfig,
dimension_separator: Literal[".", "/"] | None = None,
fill_value: float | None = None,
filters: Iterable[dict[str, JSON] | numcodecs.abc.Codec] | None = None,
compressor: dict[str, JSON] | numcodecs.abc.Codec | None = None,
attributes: dict[str, JSON] | None = None,
overwrite: bool = False,
) -> AsyncArray[ArrayV2Metadata]:
if overwrite:
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)
metadata = cls._create_metadata_v2(
shape=shape,
dtype=dtype,
chunks=chunks,
order=order,
dimension_separator=dimension_separator,
fill_value=fill_value,
filters=filters,
compressor=compressor,
attributes=attributes,
)
array = cls(metadata=metadata, store_path=store_path, config=config)
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 format 2 and 3 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 format 2 or 3 array is created.
Returns
-------
AsyncArray[ArrayV3Metadata] or AsyncArray[ArrayV2Metadata]
The created Zarr array, either using Zarr format 2 or 3 metadata based on the provided data.
Raises
------
ValueError
If the dictionary data is invalid or incompatible with either Zarr format 2 or 3 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,
config: ArrayConfigLike | None = None,
) -> 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).
config : ArrayConfigLike, optional
Runtime configuration for the array.
Returns
-------
AsyncArray
The opened Zarr array.
Examples
--------
>>> import zarr
>>> store = zarr.storage.MemoryStore()
>>> 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, config=config)
@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.
If sharding is used the inner chunk shape is returned.
Only defined for arrays using using `RegularChunkGrid`.
If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised.
Returns
-------
ChunkCoords:
The chunk shape of the Array.
"""
return self.metadata.chunks
@property
def shards(self) -> ChunkCoords | None:
"""Returns the shard shape of the Array.
Returns None if sharding is not used.
Only defined for arrays using using `RegularChunkGrid`.
If array doesn't use `RegularChunkGrid`, `NotImplementedError` is raised.
Returns
-------
ChunkCoords:
The shard shape of the Array.
"""
return self.metadata.shards
@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 filters(self) -> tuple[numcodecs.abc.Codec, ...] | tuple[ArrayArrayCodec, ...]:
"""
Filters that are applied to each chunk of the array, in order, before serializing that
chunk to bytes.
"""
if self.metadata.zarr_format == 2:
filters = self.metadata.filters
if filters is None:
return ()
return filters
return tuple(
codec for codec in self.metadata.inner_codecs if isinstance(codec, ArrayArrayCodec)
)
@property
def serializer(self) -> ArrayBytesCodec | None:
"""
Array-to-bytes codec to use for serializing the chunks into bytes.
"""
if self.metadata.zarr_format == 2:
return None
return next(
codec for codec in self.metadata.inner_codecs if isinstance(codec, ArrayBytesCodec)
)