-
-
Notifications
You must be signed in to change notification settings - Fork 290
/
core.py
3009 lines (2500 loc) · 101 KB
/
core.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
import binascii
import hashlib
import itertools
import math
import operator
import re
from functools import reduce
from typing import Any
import numpy as np
from numcodecs.compat import ensure_bytes
from zarr._storage.store import _prefix_to_attrs_key, assert_zarr_v3_api_available
from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.context import Context
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
from zarr.indexing import (
BasicIndexer,
CoordinateIndexer,
MaskIndexer,
OIndex,
OrthogonalIndexer,
VIndex,
BlockIndex,
BlockIndexer,
PartialChunkIterator,
check_fields,
check_no_multi_fields,
ensure_tuple,
err_too_many_indices,
is_contiguous_selection,
is_pure_fancy_indexing,
is_pure_orthogonal_indexing,
is_scalar,
pop_fields,
)
from zarr.storage import (
_get_hierarchy_metadata,
_prefix_to_array_key,
KVStore,
getsize,
listdir,
normalize_store_arg,
)
from zarr.util import (
ConstantMap,
all_equal,
InfoReporter,
check_array_shape,
human_readable_size,
is_total_slice,
nolock,
normalize_chunks,
normalize_resize_args,
normalize_shape,
normalize_storage_path,
PartialReadBuffer,
UncompressedPartialReadBufferV3,
ensure_ndarray_like,
)
# noinspection PyUnresolvedReferences
class Array:
"""Instantiate an array from an initialized store.
Parameters
----------
store : MutableMapping
Array store, already initialized.
path : string, optional
Storage path.
read_only : bool, optional
True if array should be protected against modification.
chunk_store : MutableMapping, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
synchronizer : object, optional
Array synchronizer.
cache_metadata : bool, optional
If True (default), array configuration metadata will be cached for the
lifetime of the object. If False, array metadata will be reloaded
prior to all data access and modification operations (may incur
overhead depending on storage and data access pattern).
cache_attrs : bool, optional
If True (default), user attributes will be cached for attribute read
operations. If False, user attributes are reloaded from the store prior
to all attribute read operations.
partial_decompress : bool, optional
If True and while the chunk_store is a FSStore and the compression used
is Blosc, when getting data from the array chunks will be partially
read and decompressed when possible.
.. versionadded:: 2.7
write_empty_chunks : bool, optional
If True, all chunks will be stored regardless of their contents. If
False (default), each chunk is compared to the array's fill value prior
to storing. If a chunk is uniformly equal to the fill value, then that
chunk is not be stored, and the store entry for that chunk's key is
deleted. This setting enables sparser storage, as only chunks with
non-fill-value data are stored, at the expense of overhead associated
with checking the data of each chunk.
.. versionadded:: 2.11
meta_array : array-like, optional
An array instance to use for determining arrays to create and return
to users. Use `numpy.empty(())` by default.
.. versionadded:: 2.13
Attributes
----------
store
path
name
read_only
chunk_store
shape
chunks
dtype
compression
compression_opts
dimension_separator
fill_value
order
synchronizer
filters
attrs
size
itemsize
nbytes
nbytes_stored
cdata_shape
nchunks
nchunks_initialized
is_view
info
vindex
oindex
blocks
write_empty_chunks
meta_array
Methods
-------
__getitem__
__setitem__
get_basic_selection
set_basic_selection
get_orthogonal_selection
set_orthogonal_selection
get_mask_selection
set_mask_selection
get_coordinate_selection
set_coordinate_selection
get_block_selection
set_block_selection
digest
hexdigest
resize
append
view
astype
"""
def __init__(
self,
store: Any, # BaseStore not strictly required due to normalize_store_arg
path=None,
read_only=False,
chunk_store=None,
synchronizer=None,
cache_metadata=True,
cache_attrs=True,
partial_decompress=False,
write_empty_chunks=True,
zarr_version=None,
meta_array=None,
):
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized
store = normalize_store_arg(store, zarr_version=zarr_version)
if zarr_version is None:
zarr_version = store._store_version
if zarr_version != 2:
assert_zarr_v3_api_available()
if chunk_store is not None:
chunk_store = normalize_store_arg(chunk_store, zarr_version=zarr_version)
self._store = store
self._chunk_store = chunk_store
self._transformed_chunk_store = None
self._path = normalize_storage_path(path)
if self._path:
self._key_prefix = self._path + "/"
else:
self._key_prefix = ""
self._read_only = bool(read_only)
self._synchronizer = synchronizer
self._cache_metadata = cache_metadata
self._is_view = False
self._partial_decompress = partial_decompress
self._write_empty_chunks = write_empty_chunks
if meta_array is not None:
self._meta_array = np.empty_like(meta_array, shape=())
else:
self._meta_array = np.empty(())
self._version = zarr_version
if self._version == 3:
self._data_key_prefix = "data/root/" + self._key_prefix
self._data_path = "data/root/" + self._path
self._hierarchy_metadata = _get_hierarchy_metadata(store=self._store)
self._metadata_key_suffix = self._hierarchy_metadata["metadata_key_suffix"]
# initialize metadata
self._load_metadata()
# initialize attributes
akey = _prefix_to_attrs_key(self._store, self._key_prefix)
self._attrs = Attributes(
store, key=akey, read_only=read_only, synchronizer=synchronizer, cache=cache_attrs
)
# initialize info reporter
self._info_reporter = InfoReporter(self)
# initialize indexing helpers
self._oindex = OIndex(self)
self._vindex = VIndex(self)
self._blocks = BlockIndex(self)
def _load_metadata(self):
"""(Re)load metadata from store."""
if self._synchronizer is None:
self._load_metadata_nosync()
else:
mkey = _prefix_to_array_key(self._store, self._key_prefix)
with self._synchronizer[mkey]:
self._load_metadata_nosync()
def _load_metadata_nosync(self):
try:
mkey = _prefix_to_array_key(self._store, self._key_prefix)
meta_bytes = self._store[mkey]
except KeyError:
raise ArrayNotFoundError(self._path)
else:
# decode and store metadata as instance members
meta = self._store._metadata_class.decode_array_metadata(meta_bytes)
self._meta = meta
self._shape = meta["shape"]
self._fill_value = meta["fill_value"]
dimension_separator = meta.get("dimension_separator", None)
if self._version == 2:
self._chunks = meta["chunks"]
self._dtype = meta["dtype"]
self._order = meta["order"]
if dimension_separator is None:
try:
dimension_separator = self._store._dimension_separator
except (AttributeError, KeyError):
pass
# Fallback for any stores which do not choose a default
if dimension_separator is None:
dimension_separator = "."
else:
self._chunks = meta["chunk_grid"]["chunk_shape"]
self._dtype = meta["data_type"]
self._order = meta["chunk_memory_layout"]
chunk_separator = meta["chunk_grid"]["separator"]
if dimension_separator is None:
dimension_separator = meta.get("dimension_separator", chunk_separator)
self._dimension_separator = dimension_separator
# setup compressor
compressor = meta.get("compressor", None)
if compressor is None:
self._compressor = None
elif self._version == 2:
self._compressor = get_codec(compressor)
else:
self._compressor = compressor
# setup filters
if self._version == 2:
filters = meta.get("filters", [])
else:
# TODO: storing filters under attributes for now since the v3
# array metadata does not have a 'filters' attribute.
filters = meta["attributes"].get("filters", [])
if filters:
filters = [get_codec(config) for config in filters]
self._filters = filters
if self._version == 3:
storage_transformers = meta.get("storage_transformers", [])
if storage_transformers:
transformed_store = self._chunk_store or self._store
for storage_transformer in storage_transformers[::-1]:
transformed_store = storage_transformer._copy_for_array(
self, transformed_store
)
self._transformed_chunk_store = transformed_store
def _refresh_metadata(self):
if not self._cache_metadata:
self._load_metadata()
def _refresh_metadata_nosync(self):
if not self._cache_metadata and not self._is_view:
self._load_metadata_nosync()
def _flush_metadata_nosync(self):
if self._is_view:
raise PermissionError("operation not permitted for views")
if self._compressor:
compressor_config = self._compressor.get_config()
else:
compressor_config = None
if self._filters:
filters_config = [f.get_config() for f in self._filters]
else:
filters_config = None
_compressor = compressor_config if self._version == 2 else self._compressor
meta = dict(
shape=self._shape,
compressor=_compressor,
fill_value=self._fill_value,
filters=filters_config,
)
if getattr(self._store, "_store_version", 2) == 2:
meta.update(dict(chunks=self._chunks, dtype=self._dtype, order=self._order))
else:
meta.update(
dict(
chunk_grid=dict(
type="regular",
chunk_shape=self._chunks,
separator=self._dimension_separator,
),
data_type=self._dtype,
chunk_memory_layout=self._order,
attributes=self.attrs.asdict(),
)
)
mkey = _prefix_to_array_key(self._store, self._key_prefix)
self._store[mkey] = self._store._metadata_class.encode_array_metadata(meta)
@property
def store(self):
"""A MutableMapping providing the underlying storage for the array."""
return self._store
@property
def path(self):
"""Storage path."""
return self._path
@property
def name(self):
"""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):
"""Final component of name."""
if self.name is not None:
return self.name.split("/")[-1]
return None
@property
def read_only(self):
"""A boolean, True if modification operations are not permitted."""
return self._read_only
@read_only.setter
def read_only(self, value):
self._read_only = bool(value)
@property
def chunk_store(self):
"""A MutableMapping providing the underlying storage for array chunks."""
if self._transformed_chunk_store is not None:
return self._transformed_chunk_store
elif self._chunk_store is not None:
return self._chunk_store
else:
return self._store
@property
def shape(self):
"""A tuple of integers describing the length of each dimension of
the array."""
# N.B., shape may change if array is resized, hence need to refresh
# metadata
self._refresh_metadata()
return self._shape
@shape.setter
def shape(self, value):
self.resize(value)
@property
def chunks(self):
"""A tuple of integers describing the length of each dimension of a
chunk of the array."""
return self._chunks
@property
def dtype(self):
"""The NumPy data type."""
return self._dtype
@property
def compressor(self):
"""Primary compression codec."""
return self._compressor
@property
def fill_value(self):
"""A value used for uninitialized portions of the array."""
return self._fill_value
@fill_value.setter
def fill_value(self, new):
self._fill_value = new
self._flush_metadata_nosync()
@property
def order(self):
"""A string indicating the order in which bytes are arranged within
chunks of the array."""
return self._order
@property
def filters(self):
"""One or more codecs used to transform data prior to compression."""
return self._filters
@property
def synchronizer(self):
"""Object used to synchronize write access to the array."""
return self._synchronizer
@property
def attrs(self):
"""A MutableMapping containing user-defined attributes. Note that
attribute values must be JSON serializable."""
return self._attrs
@property
def ndim(self):
"""Number of dimensions."""
return len(self._shape)
@property
def _size(self):
return reduce(operator.mul, self._shape, 1)
@property
def size(self):
"""The total number of elements in the array."""
# N.B., this property depends on shape, and shape may change if array
# is resized, hence need to refresh metadata
self._refresh_metadata()
return self._size
@property
def itemsize(self):
"""The size in bytes of each item in the array."""
return self.dtype.itemsize
@property
def _nbytes(self):
return self._size * self.itemsize
@property
def nbytes(self):
"""The total number of bytes that would be required to store the
array without compression."""
# N.B., this property depends on shape, and shape may change if array
# is resized, hence need to refresh metadata
self._refresh_metadata()
return self._nbytes
@property
def nbytes_stored(self):
"""The total number of stored bytes of data for the array. This
includes storage required for configuration metadata and user
attributes."""
m = getsize(self._store, self._path)
if self._chunk_store is None:
return m
else:
n = getsize(self._chunk_store, self._path)
if m < 0 or n < 0:
return -1
else:
return m + n
@property
def _cdata_shape(self):
if self._shape == ():
return (1,)
else:
return tuple(math.ceil(s / c) for s, c in zip(self._shape, self._chunks))
@property
def cdata_shape(self):
"""A tuple of integers describing the number of chunks along each
dimension of the array."""
self._refresh_metadata()
return self._cdata_shape
@property
def _nchunks(self):
return reduce(operator.mul, self._cdata_shape, 1)
@property
def nchunks(self):
"""Total number of chunks."""
self._refresh_metadata()
return self._nchunks
@property
def nchunks_initialized(self):
"""The number of chunks that have been initialized with some data."""
# count chunk keys
if self._version == 3:
# # key pattern for chunk keys
# prog = re.compile(r'\.'.join([r'c\d+'] * min(1, self.ndim)))
# # get chunk keys, excluding the prefix
# members = self.chunk_store.list_prefix(self._data_path)
# members = [k.split(self._data_key_prefix)[1] for k in members]
# # count the chunk keys
# return sum(1 for k in members if prog.match(k))
# key pattern for chunk keys
prog = re.compile(self._data_key_prefix + r"c\d+") # TODO: ndim == 0 case?
# get chunk keys, excluding the prefix
members = self.chunk_store.list_prefix(self._data_path)
# count the chunk keys
return sum(1 for k in members if prog.match(k))
else:
# key pattern for chunk keys
prog = re.compile(r"\.".join([r"\d+"] * min(1, self.ndim)))
# count chunk keys
return sum(1 for k in listdir(self.chunk_store, self._path) if prog.match(k))
# backwards compatibility
initialized = nchunks_initialized
@property
def is_view(self):
"""A boolean, True if this array is a view on another array."""
return self._is_view
@property
def oindex(self):
"""Shortcut for orthogonal (outer) indexing, see :func:`get_orthogonal_selection` and
:func:`set_orthogonal_selection` for documentation and examples."""
return self._oindex
@property
def vindex(self):
"""Shortcut for vectorized (inner) indexing, see :func:`get_coordinate_selection`,
:func:`set_coordinate_selection`, :func:`get_mask_selection` and
:func:`set_mask_selection` for documentation and examples."""
return self._vindex
@property
def blocks(self):
"""Shortcut for blocked chunked indexing, see :func:`get_block_selection` and
:func:`set_block_selection` for documentation and examples."""
return self._blocks
@property
def write_empty_chunks(self) -> bool:
"""A Boolean, True if chunks composed of the array's fill value
will be stored. If False, such chunks will not be stored.
"""
return self._write_empty_chunks
@property
def meta_array(self):
"""An array-like instance to use for determining arrays to create and return
to users.
"""
return self._meta_array
def __eq__(self, other):
return (
isinstance(other, Array)
and self.store == other.store
and self.read_only == other.read_only
and self.path == other.path
and not self._is_view
# N.B., no need to compare other properties, should be covered by
# store comparison
)
def __array__(self, *args):
a = self[...]
if args:
a = a.astype(args[0])
return a
def islice(self, start=None, end=None):
"""
Yield a generator for iterating over the entire or parts of the
array. Uses a cache so chunks only have to be decompressed once.
Parameters
----------
start : int, optional
Start index for the generator to start at. Defaults to 0.
end : int, optional
End index for the generator to stop at. Defaults to self.shape[0].
Yields
------
out : generator
A generator that can be used to iterate over the requested region
the array.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100))
Iterate over part of the array:
>>> for value in z.islice(25, 30): value;
25
26
27
28
29
"""
if len(self.shape) == 0:
# Same error as numpy
raise TypeError("iteration over a 0-d array")
if start is None:
start = 0
if end is None or end > self.shape[0]:
end = self.shape[0]
if not isinstance(start, int) or start < 0:
raise ValueError("start must be a nonnegative integer")
if not isinstance(end, int) or end < 0:
raise ValueError("end must be a nonnegative integer")
# Avoid repeatedly decompressing chunks by iterating over the chunks
# in the first dimension.
chunk_size = self.chunks[0]
chunk = None
for j in range(start, end):
if j % chunk_size == 0:
chunk = self[j : j + chunk_size]
# init chunk if we start offset of chunk borders
elif chunk is None:
chunk_start = j - j % chunk_size
chunk_end = chunk_start + chunk_size
chunk = self[chunk_start:chunk_end]
yield chunk[j % chunk_size]
def __iter__(self):
return self.islice()
def __len__(self):
if self.shape:
return self.shape[0]
else:
# 0-dimensional array, same error message as numpy
raise TypeError("len() of unsized object")
def __getitem__(self, selection):
"""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
-------
out : ndarray
A NumPy array containing the data for the requested region.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100))
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::
>>> z = zarr.array(np.arange(100).reshape(10, 10))
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]])
For arrays with a structured dtype, specific fields can be retrieved, e.g.::
>>> a = np.array([(b'aaa', 1, 4.2),
... (b'bbb', 2, 8.4),
... (b'ccc', 3, 12.6)],
... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
>>> z = zarr.array(a)
>>> z['foo']
array([b'aaa', b'bbb', b'ccc'],
dtype='|S3')
Notes
-----
Slices with step > 1 are supported, but slices with negative step are not.
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):
result = self.vindex[selection]
elif is_pure_orthogonal_indexing(pure_selection, self.ndim):
result = self.get_orthogonal_selection(pure_selection, fields=fields)
else:
result = self.get_basic_selection(pure_selection, fields=fields)
return result
def get_basic_selection(self, selection=Ellipsis, out=None, fields=None):
"""Retrieve data for an item or region of the array.
Parameters
----------
selection : tuple
A tuple specifying the requested item or region for each dimension of the
array. May be any combination of int and/or slice for multidimensional arrays.
out : ndarray, optional
If given, load the selected data directly into this array.
fields : str or sequence of str, optional
For arrays with a structured dtype, one or more fields can be specified to
extract data for.
Returns
-------
out : ndarray
A NumPy array containing the data for the requested region.
Examples
--------
Setup a 1-dimensional array::
>>> import zarr
>>> import numpy as np
>>> z = zarr.array(np.arange(100))
Retrieve a single item::
>>> z.get_basic_selection(5)
5
Retrieve a region via slicing::
>>> z.get_basic_selection(slice(5))
array([0, 1, 2, 3, 4])
>>> z.get_basic_selection(slice(-5, None))
array([95, 96, 97, 98, 99])
>>> z.get_basic_selection(slice(5, 10))
array([5, 6, 7, 8, 9])
>>> z.get_basic_selection(slice(5, 10, 2))
array([5, 7, 9])
>>> z.get_basic_selection(slice(None, None, 2))
array([ 0, 2, 4, ..., 94, 96, 98])
Setup a 2-dimensional array::
>>> z = zarr.array(np.arange(100).reshape(10, 10))
Retrieve an item::
>>> z.get_basic_selection((2, 2))
22
Retrieve a region via slicing::
>>> z.get_basic_selection((slice(1, 3), slice(1, 3)))
array([[11, 12],
[21, 22]])
>>> z.get_basic_selection((slice(1, 3), slice(None)))
array([[10, 11, 12, 13, 14, 15, 16, 17, 18, 19],
[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]])
>>> z.get_basic_selection((slice(None), slice(1, 3)))
array([[ 1, 2],
[11, 12],
[21, 22],
[31, 32],
[41, 42],
[51, 52],
[61, 62],
[71, 72],
[81, 82],
[91, 92]])
>>> z.get_basic_selection((slice(0, 5, 2), slice(0, 5, 2)))
array([[ 0, 2, 4],
[20, 22, 24],
[40, 42, 44]])
>>> z.get_basic_selection((slice(None, None, 2), slice(None, None, 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]])
For arrays with a structured dtype, specific fields can be retrieved, e.g.::
>>> a = np.array([(b'aaa', 1, 4.2),
... (b'bbb', 2, 8.4),
... (b'ccc', 3, 12.6)],
... dtype=[('foo', 'S3'), ('bar', 'i4'), ('baz', 'f8')])
>>> z = zarr.array(a)
>>> z.get_basic_selection(slice(2), fields='foo')
array([b'aaa', b'bbb'],
dtype='|S3')
Notes
-----
Slices with step > 1 are supported, but slices with negative step are not.
Currently this method provides the implementation for accessing data via the
square bracket notation (__getitem__). See :func:`__getitem__` for examples
using the alternative notation.
See Also
--------
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__, __setitem__
"""
# refresh metadata
if not self._cache_metadata:
self._load_metadata()
# check args
check_fields(fields, self._dtype)
# handle zero-dimensional arrays
if self._shape == ():
return self._get_basic_selection_zd(selection=selection, out=out, fields=fields)
else:
return self._get_basic_selection_nd(selection=selection, out=out, fields=fields)
def _get_basic_selection_zd(self, selection, out=None, fields=None):
# special case basic selection for zero-dimensional array
# check selection is valid
selection = ensure_tuple(selection)
if selection not in ((), (Ellipsis,)):
err_too_many_indices(selection, ())
try:
# obtain encoded data for chunk
ckey = self._chunk_key((0,))
cdata = self.chunk_store[ckey]
except KeyError:
# chunk not initialized
chunk = np.zeros_like(self._meta_array, shape=(), dtype=self._dtype)
if self._fill_value is not None:
chunk.fill(self._fill_value)
else:
chunk = self._decode_chunk(cdata)
# handle fields
if fields:
chunk = chunk[fields]
# handle selection of the scalar value via empty tuple
if out is None:
out = chunk[selection]