-
-
Notifications
You must be signed in to change notification settings - Fork 327
/
Copy patharray.py
2022 lines (1725 loc) · 69.7 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
# Notes on what I've changed here:
# 1. Split Array into AsyncArray and Array
# 3. Added .size and .attrs methods
# 4. Temporarily disabled the creation of ArrayV2
# 5. Added from_dict to AsyncArray
# Questions to consider:
# 1. Was splitting the array into two classes really necessary?
from asyncio import gather
from collections.abc import Iterable
from dataclasses import dataclass, field, replace
from typing import Any, Literal, cast
import numpy as np
import numpy.typing as npt
from zarr.abc.codec import Codec, CodecPipeline
from zarr.abc.store import set_or_delete
from zarr.attributes import Attributes
from zarr.buffer import BufferPrototype, NDArrayLike, NDBuffer, default_buffer_prototype
from zarr.chunk_grids import RegularChunkGrid
from zarr.chunk_key_encodings import ChunkKeyEncoding, DefaultChunkKeyEncoding, V2ChunkKeyEncoding
from zarr.codecs import BytesCodec
from zarr.codecs._v2 import V2Compressor, V2Filters
from zarr.codecs.pipeline import BatchedCodecPipeline
from zarr.common import (
JSON,
ZARR_JSON,
ZARRAY_JSON,
ZATTRS_JSON,
ChunkCoords,
ZarrFormat,
concurrent_map,
product,
)
from zarr.config import config, parse_indexing_order
from zarr.indexing import (
BasicIndexer,
BasicSelection,
BlockIndex,
BlockIndexer,
CoordinateIndexer,
CoordinateSelection,
Fields,
Indexer,
MaskIndexer,
MaskSelection,
OIndex,
OrthogonalIndexer,
OrthogonalSelection,
Selection,
VIndex,
check_fields,
check_no_multi_fields,
is_pure_fancy_indexing,
is_pure_orthogonal_indexing,
is_scalar,
pop_fields,
)
from zarr.metadata import ArrayMetadata, ArrayV2Metadata, ArrayV3Metadata
from zarr.store import StoreLike, StorePath, make_store_path
from zarr.sync import sync
def parse_array_metadata(data: Any) -> ArrayV2Metadata | ArrayV3Metadata:
if isinstance(data, ArrayV2Metadata | ArrayV3Metadata):
return data
elif isinstance(data, dict):
if data["zarr_format"] == 3:
return ArrayV3Metadata.from_dict(data)
elif data["zarr_format"] == 2:
return ArrayV2Metadata.from_dict(data)
raise TypeError
def create_codec_pipeline(metadata: ArrayV2Metadata | ArrayV3Metadata) -> BatchedCodecPipeline:
if isinstance(metadata, ArrayV3Metadata):
return BatchedCodecPipeline.from_list(metadata.codecs)
elif isinstance(metadata, ArrayV2Metadata):
return BatchedCodecPipeline.from_list(
[V2Filters(metadata.filters or []), V2Compressor(metadata.compressor)]
)
else:
raise AssertionError
@dataclass(frozen=True)
class AsyncArray:
metadata: ArrayMetadata
store_path: StorePath
codec_pipeline: CodecPipeline = field(init=False)
order: Literal["C", "F"]
def __init__(
self,
metadata: ArrayMetadata,
store_path: StorePath,
order: Literal["C", "F"] | None = None,
):
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))
@classmethod
async def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ChunkCoords,
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: ChunkCoords | None = None,
dimension_separator: Literal[".", "/"] | None = None,
order: Literal["C", "F"] | None = None,
filters: list[dict[str, JSON]] | None = None,
compressor: dict[str, JSON] | None = None,
# runtime
exists_ok: bool = False,
) -> AsyncArray:
store_path = make_store_path(store)
if chunk_shape is None:
if chunks is None:
raise ValueError("Either chunk_shape or chunks needs to be provided.")
chunk_shape = chunks
elif chunks is not None:
raise ValueError("Only one of chunk_shape or chunks must be provided.")
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 order is not None:
raise ValueError(
"order cannot be used for arrays with version 3. Use a transpose codec 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."
)
return await cls._create_v3(
store_path,
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,
exists_ok=exists_ok,
)
elif zarr_format == 2:
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.")
return await cls._create_v2(
store_path,
shape=shape,
dtype=dtype,
chunks=chunk_shape,
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}")
@classmethod
async def _create_v3(
cls,
store_path: StorePath,
*,
shape: ChunkCoords,
dtype: npt.DTypeLike,
chunk_shape: ChunkCoords,
fill_value: Any | 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:
if not exists_ok:
assert not await (store_path / ZARR_JSON).exists()
codecs = list(codecs) if codecs is not None else [BytesCodec()]
if fill_value is None:
if dtype == np.dtype("bool"):
fill_value = False
else:
fill_value = 0
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)
await array._save_metadata(metadata)
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 | int | float = None,
order: Literal["C", "F"] | 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:
import numcodecs
if not exists_ok:
assert not await (store_path / ZARRAY_JSON).exists()
if order is None:
order = "C"
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=0 if fill_value is None else fill_value,
compressor=(
numcodecs.get_codec(compressor).get_config() if compressor is not None else None
),
filters=(
[numcodecs.get_codec(filter).get_config() for filter in filters]
if filters is not None
else None
),
attributes=attributes,
)
array = cls(metadata=metadata, store_path=store_path)
await array._save_metadata(metadata)
return array
@classmethod
def from_dict(
cls,
store_path: StorePath,
data: dict[str, JSON],
) -> AsyncArray:
metadata = parse_array_metadata(data)
async_array = cls(metadata=metadata, store_path=store_path)
return async_array
@classmethod
async def open(
cls,
store: StoreLike,
zarr_format: ZarrFormat | None = 3,
) -> AsyncArray:
store_path = make_store_path(store)
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 KeyError(store_path) # filenotfounderror?
elif zarr_format == 3:
zarr_json_bytes = await (store_path / ZARR_JSON).get()
if zarr_json_bytes is None:
raise KeyError(store_path) # filenotfounderror?
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 KeyError(store_path) # filenotfounderror?
# 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 ValueError(f"unexpected zarr_format: {zarr_format}")
if zarr_format == 2:
# V2 arrays are comprised of a .zarray and .zattrs objects
assert zarray_bytes is not None
zarray_dict = json.loads(zarray_bytes.to_bytes())
zattrs_dict = json.loads(zattrs_bytes.to_bytes()) if zattrs_bytes is not None else {}
zarray_dict["attributes"] = zattrs_dict
return cls(store_path=store_path, metadata=ArrayV2Metadata.from_dict(zarray_dict))
else:
# V3 arrays are comprised of a zarr.json object
assert zarr_json_bytes is not None
return cls(
store_path=store_path,
metadata=ArrayV3Metadata.from_dict(json.loads(zarr_json_bytes.to_bytes())),
)
@property
def ndim(self) -> int:
return len(self.metadata.shape)
@property
def shape(self) -> ChunkCoords:
return self.metadata.shape
@property
def chunks(self) -> ChunkCoords:
if isinstance(self.metadata.chunk_grid, RegularChunkGrid):
return self.metadata.chunk_grid.chunk_shape
else:
raise ValueError(
f"chunk attribute is only available for RegularChunkGrid, this array has a {self.metadata.chunk_grid}"
)
@property
def size(self) -> int:
return np.prod(self.metadata.shape).item()
@property
def dtype(self) -> np.dtype[Any]:
return self.metadata.dtype
@property
def attrs(self) -> dict[str, JSON]:
return self.metadata.attributes
@property
def read_only(self) -> bool:
return bool(not self.store_path.store.writeable)
@property
def path(self) -> str:
"""Storage path."""
return self.store_path.path
@property
def name(self) -> str | None:
"""Array name following h5py convention."""
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."""
if self.name is not None:
return self.name.split("/")[-1]
return None
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:
out_buffer = prototype.nd_buffer.create(
shape=indexer.shape,
dtype=out_dtype,
order=self.order,
fill_value=self.metadata.fill_value,
)
if product(indexer.shape) > 0:
# reading chunks and decoding them
await self.codec_pipeline.read(
[
(
self.store_path / self.metadata.encode_chunk_key(chunk_coords),
self.metadata.get_chunk_spec(chunk_coords, self.order, prototype=prototype),
chunk_selection,
out_selection,
)
for chunk_coords, chunk_selection, out_selection in indexer
],
out_buffer,
drop_axes=indexer.drop_axes,
)
return out_buffer.as_ndarray_like()
async def getitem(
self, selection: BasicSelection, *, prototype: BufferPrototype = default_buffer_prototype
) -> NDArrayLike:
indexer = BasicIndexer(
selection,
shape=self.metadata.shape,
chunk_grid=self.metadata.chunk_grid,
)
return await self._get_selection(indexer, prototype=prototype)
async def _save_metadata(self, metadata: ArrayMetadata) -> None:
to_save = metadata.to_buffer_dict()
awaitables = [set_or_delete(self.store_path / key, value) for key, value in to_save.items()]
await gather(*awaitables)
async def _set_selection(
self,
indexer: Indexer,
value: npt.ArrayLike,
*,
prototype: BufferPrototype,
fields: Fields | None = None,
) -> None:
# check fields are sensible
check_fields(fields, self.dtype)
fields = check_no_multi_fields(fields)
# check value shape
if np.isscalar(value):
value = np.asanyarray(value, dtype=self.metadata.dtype)
else:
if not hasattr(value, "shape"):
value = np.asarray(value, self.metadata.dtype)
# assert (
# value.shape == indexer.shape
# ), f"shape of value doesn't match indexer shape. Expected {indexer.shape}, got {value.shape}"
if not hasattr(value, "dtype") or value.dtype.name != self.metadata.dtype.name:
value = np.array(value, dtype=self.metadata.dtype, order="A")
value = cast(NDArrayLike, value)
# We accept any ndarray like object from the user and convert it
# to a NDBuffer (or subclass). From this point onwards, we only pass
# Buffer and NDBuffer between components.
value_buffer = prototype.nd_buffer.from_ndarray_like(value)
# merging with existing data and encoding chunks
await self.codec_pipeline.write(
[
(
self.store_path / self.metadata.encode_chunk_key(chunk_coords),
self.metadata.get_chunk_spec(chunk_coords, self.order, prototype),
chunk_selection,
out_selection,
)
for chunk_coords, chunk_selection, out_selection in indexer
],
value_buffer,
drop_axes=indexer.drop_axes,
)
async def setitem(
self,
selection: BasicSelection,
value: npt.ArrayLike,
prototype: BufferPrototype = default_buffer_prototype,
) -> None:
indexer = BasicIndexer(
selection,
shape=self.metadata.shape,
chunk_grid=self.metadata.chunk_grid,
)
return await self._set_selection(indexer, value, prototype=prototype)
async def resize(
self, new_shape: ChunkCoords, delete_outside_chunks: bool = True
) -> AsyncArray:
assert len(new_shape) == len(self.metadata.shape)
new_metadata = self.metadata.update_shape(new_shape)
# Remove all chunks outside of the new shape
old_chunk_coords = set(self.metadata.chunk_grid.all_chunk_coords(self.metadata.shape))
new_chunk_coords = set(self.metadata.chunk_grid.all_chunk_coords(new_shape))
if delete_outside_chunks:
async def _delete_key(key: str) -> None:
await (self.store_path / key).delete()
await concurrent_map(
[
(self.metadata.encode_chunk_key(chunk_coords),)
for chunk_coords in old_chunk_coords.difference(new_chunk_coords)
],
_delete_key,
config.get("async.concurrency"),
)
# Write new metadata
await self._save_metadata(new_metadata)
return replace(self, metadata=new_metadata)
async def update_attributes(self, new_attributes: dict[str, JSON]) -> AsyncArray:
new_metadata = self.metadata.update_attributes(new_attributes)
# Write new metadata
await self._save_metadata(new_metadata)
return replace(self, metadata=new_metadata)
def __repr__(self) -> str:
return f"<AsyncArray {self.store_path} shape={self.shape} dtype={self.dtype}>"
async def info(self) -> None:
raise NotImplementedError
@dataclass(frozen=True)
class Array:
_async_array: AsyncArray
@classmethod
def create(
cls,
store: StoreLike,
*,
# v2 and v3
shape: ChunkCoords,
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: ChunkCoords | None = None,
dimension_separator: Literal[".", "/"] | None = None,
order: Literal["C", "F"] | None = None,
filters: list[dict[str, JSON]] | None = None,
compressor: dict[str, JSON] | None = None,
# runtime
exists_ok: bool = False,
) -> Array:
async_array = sync(
AsyncArray.create(
store=store,
shape=shape,
dtype=dtype,
zarr_format=zarr_format,
attributes=attributes,
fill_value=fill_value,
chunk_shape=chunk_shape,
chunk_key_encoding=chunk_key_encoding,
codecs=codecs,
dimension_names=dimension_names,
chunks=chunks,
dimension_separator=dimension_separator,
order=order,
filters=filters,
compressor=compressor,
exists_ok=exists_ok,
),
)
return cls(async_array)
@classmethod
def from_dict(
cls,
store_path: StorePath,
data: dict[str, JSON],
) -> Array:
async_array = AsyncArray.from_dict(store_path=store_path, data=data)
return cls(async_array)
@classmethod
def open(
cls,
store: StoreLike,
) -> Array:
async_array = sync(AsyncArray.open(store))
return cls(async_array)
@property
def ndim(self) -> int:
return self._async_array.ndim
@property
def shape(self) -> ChunkCoords:
return self._async_array.shape
@property
def chunks(self) -> ChunkCoords:
return self._async_array.chunks
@property
def size(self) -> int:
return self._async_array.size
@property
def dtype(self) -> np.dtype[Any]:
return self._async_array.dtype
@property
def attrs(self) -> Attributes:
return Attributes(self)
@property
def path(self) -> str:
"""Storage path."""
return self._async_array.path
@property
def name(self) -> str | None:
"""Array name following h5py convention."""
return self._async_array.name
@property
def basename(self) -> str | None:
"""Final component of name."""
return self._async_array.basename
@property
def metadata(self) -> ArrayMetadata:
return self._async_array.metadata
@property
def store_path(self) -> StorePath:
return self._async_array.store_path
@property
def order(self) -> Literal["C", "F"]:
return self._async_array.order
@property
def read_only(self) -> bool:
return self._async_array.read_only
@property
def fill_value(self) -> Any:
return self.metadata.fill_value
def __array__(
self, dtype: npt.DTypeLike | None = None, copy: bool | None = None
) -> NDArrayLike:
"""
This method is used by numpy when converting zarr.Array into a numpy array.
For more information, see https://numpy.org/devdocs/user/basics.interoperability.html#the-array-method
"""
if copy is False:
msg = "`copy=False` is not supported. This method always creates a copy."
raise ValueError(msg)
arr_np = self[...]
if dtype is not None:
arr_np = arr_np.astype(dtype)
return arr_np
def __getitem__(self, selection: Selection) -> NDArrayLike:
"""Retrieve data for an item or region of the array.
Parameters
----------
selection : tuple
An integer index or slice or tuple of int/slice objects specifying the
requested item or region for each dimension of the array.
Returns
-------
NDArrayLike
An array-like containing the data for the requested region.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> data = np.arange(100, dtype="uint16")
>>> z = Array.create(
>>> StorePath(MemoryStore(mode="w")),
>>> shape=data.shape,
>>> chunk_shape=(10,),
>>> dtype=data.dtype,
>>> )
>>> z[:] = data
Retrieve a single item::
>>> z[5]
5
Retrieve a region via slicing::
>>> z[:5]
array([0, 1, 2, 3, 4])
>>> z[-5:]
array([95, 96, 97, 98, 99])
>>> z[5:10]
array([5, 6, 7, 8, 9])
>>> z[5:10:2]
array([5, 7, 9])
>>> z[::2]
array([ 0, 2, 4, ..., 94, 96, 98])
Load the entire array into memory::
>>> z[...]
array([ 0, 1, 2, ..., 97, 98, 99])
Setup a 2-dimensional array::
>>> data = np.arange(100, dtype="uint16").reshape(10, 10)
>>> z = Array.create(
>>> StorePath(MemoryStore(mode="w")),
>>> shape=data.shape,
>>> chunk_shape=(10, 10),
>>> dtype=data.dtype,
>>> )
>>> z[:] = data
Retrieve an item::
>>> z[2, 2]
22
Retrieve a region via slicing::
>>> z[1:3, 1:3]
array([[11, 12],
[21, 22]])
>>> z[1:3, :]
array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])
>>> z[:, 1:3]
array([[ 1, 2],
[11, 12],
[21, 22],
[31, 32],
[41, 42],
[51, 52],
[61, 62],
[71, 72],
[81, 82],
[91, 92]])
>>> z[0:5:2, 0:5:2]
array([[ 0, 2, 4],
[20, 22, 24],
[40, 42, 44]])
>>> z[::2, ::2]
array([[ 0, 2, 4, 6, 8],
[20, 22, 24, 26, 28],
[40, 42, 44, 46, 48],
[60, 62, 64, 66, 68],
[80, 82, 84, 86, 88]])
Load the entire array into memory::
>>> z[...]
array([[ 0, 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]])
Notes
-----
Slices with step > 1 are supported, but slices with negative step are not.
For arrays with a structured dtype, see zarr v2 for examples of how to use
fields
Currently the implementation for __getitem__ is provided by
:func:`vindex` if the indexing is pure fancy indexing (ie a
broadcast-compatible tuple of integer array indices), or by
:func:`set_basic_selection` otherwise.
Effectively, this means that the following indexing modes are supported:
- integer indexing
- slice indexing
- mixed slice and integer indexing
- boolean indexing
- fancy indexing (vectorized list of integers)
For specific indexing options including outer indexing, see the
methods listed under See Also.
See Also
--------
get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
set_orthogonal_selection, get_block_selection, set_block_selection,
vindex, oindex, blocks, __setitem__
"""
fields, pure_selection = pop_fields(selection)
if is_pure_fancy_indexing(pure_selection, self.ndim):
return self.vindex[cast(CoordinateSelection | MaskSelection, selection)]
elif is_pure_orthogonal_indexing(pure_selection, self.ndim):
return self.get_orthogonal_selection(pure_selection, fields=fields)
else:
return self.get_basic_selection(cast(BasicSelection, pure_selection), fields=fields)
def __setitem__(self, selection: Selection, value: npt.ArrayLike) -> None:
"""Modify data for an item or region of the array.
Parameters
----------
selection : tuple
An integer index or slice or tuple of int/slice specifying the requested
region for each dimension of the array.
value : npt.ArrayLike
An array-like containing the data to be stored in the selection.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> z = zarr.zeros(
>>> shape=(100,),
>>> store=StorePath(MemoryStore(mode="w")),
>>> chunk_shape=(5,),
>>> dtype="i4",
>>> )
Set all array elements to the same scalar value::
>>> z[...] = 42
>>> z[...]
array([42, 42, 42, ..., 42, 42, 42])
Set a portion of the array::
>>> z[:10] = np.arange(10)
>>> z[-10:] = np.arange(10)[::-1]
>>> z[...]
array([ 0, 1, 2, ..., 2, 1, 0])
Setup a 2-dimensional array::
>>> z = zarr.zeros(
>>> shape=(5, 5),
>>> store=StorePath(MemoryStore(mode="w")),
>>> chunk_shape=(5, 5),
>>> dtype="i4",
>>> )
Set all array elements to the same scalar value::
>>> z[...] = 42
Set a portion of the array::
>>> z[0, :] = np.arange(z.shape[1])
>>> z[:, 0] = np.arange(z.shape[0])
>>> z[...]
array([[ 0, 1, 2, 3, 4],
[ 1, 42, 42, 42, 42],
[ 2, 42, 42, 42, 42],
[ 3, 42, 42, 42, 42],
[ 4, 42, 42, 42, 42]])
Notes
-----
Slices with step > 1 are supported, but slices with negative step are not.
For arrays with a structured dtype, see zarr v2 for examples of how to use
fields
Currently the implementation for __setitem__ is provided by
:func:`vindex` if the indexing is pure fancy indexing (ie a
broadcast-compatible tuple of integer array indices), or by
:func:`set_basic_selection` otherwise.
Effectively, this means that the following indexing modes are supported:
- integer indexing
- slice indexing
- mixed slice and integer indexing
- boolean indexing
- fancy indexing (vectorized list of integers)
For specific indexing options including outer indexing, see the
methods listed under See Also.
See Also
--------
get_basic_selection, set_basic_selection, get_mask_selection, set_mask_selection,
get_coordinate_selection, set_coordinate_selection, get_orthogonal_selection,
set_orthogonal_selection, get_block_selection, set_block_selection,
vindex, oindex, blocks, __getitem__
"""
fields, pure_selection = pop_fields(selection)
if is_pure_fancy_indexing(pure_selection, self.ndim):
self.vindex[cast(CoordinateSelection | MaskSelection, selection)] = value
elif is_pure_orthogonal_indexing(pure_selection, self.ndim):
self.set_orthogonal_selection(pure_selection, value, fields=fields)
else:
self.set_basic_selection(cast(BasicSelection, pure_selection), value, fields=fields)
def get_basic_selection(
self,
selection: BasicSelection = Ellipsis,
*,
out: NDBuffer | None = None,
prototype: BufferPrototype = default_buffer_prototype,
fields: Fields | None = None,
) -> NDArrayLike:
"""Retrieve data for an item or region of the array.
Parameters