-
-
Notifications
You must be signed in to change notification settings - Fork 286
/
storage.py
2996 lines (2499 loc) · 98.3 KB
/
storage.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
"""This module contains storage classes for use with Zarr arrays and groups.
Note that any object implementing the :class:`MutableMapping` interface from the
:mod:`collections` module in the Python standard library can be used as a Zarr
array store, as long as it accepts string (str) keys and bytes values.
In addition to the :class:`MutableMapping` interface, store classes may also implement
optional methods `listdir` (list members of a "directory") and `rmdir` (remove all
members of a "directory"). These methods should be implemented if the store class is
aware of the hierarchical organisation of resources within the store and can provide
efficient implementations. If these methods are not available, Zarr will fall back to
slower implementations that work via the :class:`MutableMapping` interface. Store
classes may also optionally implement a `rename` method (rename all members under a given
path) and a `getsize` method (return the size in bytes of a given value).
"""
import atexit
import errno
import glob
import multiprocessing
import operator
import os
import re
import shutil
import sys
import tempfile
import warnings
import zipfile
from collections import OrderedDict
from collections.abc import MutableMapping
from functools import lru_cache
from os import scandir
from pickle import PicklingError
from threading import Lock, RLock
from typing import Sequence, Mapping, Optional, Union, List, Tuple, Dict, Any
import uuid
import time
from numcodecs.abc import Codec
from numcodecs.compat import ensure_bytes, ensure_text, ensure_contiguous_ndarray_like
from numcodecs.registry import codec_registry
from zarr.context import Context
from zarr.types import PathLike as Path, DIMENSION_SEPARATOR
from zarr.util import NoLock
from zarr.errors import (
MetadataError,
BadCompressorError,
ContainsArrayError,
ContainsGroupError,
FSPathExistNotDir,
ReadOnlyError,
)
from zarr.meta import encode_array_metadata, encode_group_metadata
from zarr.util import (
buffer_size,
json_loads,
nolock,
normalize_chunks,
normalize_dimension_separator,
normalize_dtype,
normalize_fill_value,
normalize_order,
normalize_shape,
normalize_storage_path,
retry_call,
ensure_contiguous_ndarray_or_bytes,
)
from zarr._storage.absstore import ABSStore # noqa: F401
from zarr._storage.store import ( # noqa: F401
_get_hierarchy_metadata,
_get_metadata_suffix,
_listdir_from_keys,
_rename_from_keys,
_rename_metadata_v3,
_rmdir_from_keys,
_rmdir_from_keys_v3,
_path_to_prefix,
_prefix_to_array_key,
_prefix_to_group_key,
array_meta_key,
attrs_key,
data_root,
group_meta_key,
meta_root,
DEFAULT_ZARR_VERSION,
BaseStore,
Store,
)
__doctest_requires__ = {
("RedisStore", "RedisStore.*"): ["redis"],
("MongoDBStore", "MongoDBStore.*"): ["pymongo"],
("LRUStoreCache", "LRUStoreCache.*"): ["s3fs"],
}
try:
# noinspection PyUnresolvedReferences
from zarr.codecs import Blosc
default_compressor = Blosc()
except ImportError: # pragma: no cover
from zarr.codecs import Zlib
default_compressor = Zlib()
# allow MutableMapping for backwards compatibility
StoreLike = Union[BaseStore, MutableMapping]
def contains_array(store: StoreLike, path: Path = None) -> bool:
"""Return True if the store contains an array at the given logical path."""
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = _prefix_to_array_key(store, prefix)
return key in store
def contains_group(store: StoreLike, path: Path = None, explicit_only=True) -> bool:
"""Return True if the store contains a group at the given logical path."""
path = normalize_storage_path(path)
prefix = _path_to_prefix(path)
key = _prefix_to_group_key(store, prefix)
store_version = getattr(store, "_store_version", 2)
if store_version == 2 or explicit_only:
return key in store
else:
if key in store:
return True
# for v3, need to also handle implicit groups
sfx = _get_metadata_suffix(store) # type: ignore
implicit_prefix = key.replace(".group" + sfx, "")
if not implicit_prefix.endswith("/"):
implicit_prefix += "/"
if store.list_prefix(implicit_prefix): # type: ignore
return True
return False
def _normalize_store_arg_v2(store: Any, storage_options=None, mode="r") -> BaseStore:
# default to v2 store for backward compatibility
zarr_version = getattr(store, "_store_version", 2)
if zarr_version != 2:
raise ValueError("store must be a version 2 store")
if store is None:
store = KVStore(dict())
return store
if isinstance(store, os.PathLike):
store = os.fspath(store)
if FSStore._fsspec_installed():
import fsspec
if isinstance(store, fsspec.FSMap):
return FSStore(
store.root,
fs=store.fs,
mode=mode,
check=store.check,
create=store.create,
missing_exceptions=store.missing_exceptions,
**(storage_options or {}),
)
if isinstance(store, str):
if "://" in store or "::" in store:
return FSStore(store, mode=mode, **(storage_options or {}))
elif storage_options:
raise ValueError("storage_options passed with non-fsspec path")
if store.endswith(".zip"):
return ZipStore(store, mode=mode)
elif store.endswith(".n5"):
from zarr.n5 import N5Store
return N5Store(store)
else:
return DirectoryStore(store)
else:
store = Store._ensure_store(store)
return store
def normalize_store_arg(
store: Any, storage_options=None, mode="r", *, zarr_version=None
) -> BaseStore:
if zarr_version is None:
# default to v2 store for backward compatibility
zarr_version = getattr(store, "_store_version", DEFAULT_ZARR_VERSION)
if zarr_version == 2:
normalize_store = _normalize_store_arg_v2
elif zarr_version == 3:
from zarr._storage.v3 import _normalize_store_arg_v3
normalize_store = _normalize_store_arg_v3
else:
raise ValueError("zarr_version must be either 2 or 3")
return normalize_store(store, storage_options, mode)
def rmdir(store: StoreLike, path: Path = None):
"""Remove all items under the given path. If `store` provides a `rmdir` method,
this will be called, otherwise will fall back to implementation via the
`Store` interface."""
path = normalize_storage_path(path)
store_version = getattr(store, "_store_version", 2)
if hasattr(store, "rmdir") and store.is_erasable(): # type: ignore
# pass through
store.rmdir(path)
else:
# slow version, delete one key at a time
if store_version == 2:
_rmdir_from_keys(store, path)
else:
_rmdir_from_keys_v3(store, path) # type: ignore
def rename(store: Store, src_path: Path, dst_path: Path):
"""Rename all items under the given path. If `store` provides a `rename` method,
this will be called, otherwise will fall back to implementation via the
`Store` interface."""
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
if hasattr(store, "rename"):
# pass through
store.rename(src_path, dst_path)
else:
# slow version, delete one key at a time
_rename_from_keys(store, src_path, dst_path)
def listdir(store: BaseStore, path: Path = None):
"""Obtain a directory listing for the given path. If `store` provides a `listdir`
method, this will be called, otherwise will fall back to implementation via the
`MutableMapping` interface."""
path = normalize_storage_path(path)
if hasattr(store, "listdir"):
# pass through
return store.listdir(path)
else:
# slow version, iterate through all keys
warnings.warn(
f"Store {store} has no `listdir` method. From zarr 2.9 onwards "
"may want to inherit from `Store`.",
stacklevel=2,
)
return _listdir_from_keys(store, path)
def _getsize(store: BaseStore, path: Path = None) -> int:
# compute from size of values
if path and path in store:
v = store[path]
size = buffer_size(v)
else:
path = "" if path is None else normalize_storage_path(path)
size = 0
store_version = getattr(store, "_store_version", 2)
if store_version == 3:
if path == "":
# have to list the root folders without trailing / in this case
members = store.list_prefix(data_root.rstrip("/")) # type: ignore
members += store.list_prefix(meta_root.rstrip("/")) # type: ignore
else:
members = store.list_prefix(data_root + path) # type: ignore
members += store.list_prefix(meta_root + path) # type: ignore
# also include zarr.json?
# members += ['zarr.json']
else:
members = listdir(store, path)
prefix = _path_to_prefix(path)
members = [prefix + k for k in members]
for k in members:
try:
v = store[k]
except KeyError:
pass
else:
try:
size += buffer_size(v)
except TypeError:
return -1
return size
def getsize(store: BaseStore, path: Path = None) -> int:
"""Compute size of stored items for a given path. If `store` provides a `getsize`
method, this will be called, otherwise will return -1."""
if hasattr(store, "getsize"):
# pass through
path = normalize_storage_path(path)
return store.getsize(path)
elif isinstance(store, MutableMapping):
return _getsize(store, path)
else:
return -1
def _require_parent_group(
path: Optional[str],
store: StoreLike,
chunk_store: Optional[StoreLike],
overwrite: bool,
):
# assume path is normalized
if path:
segments = path.split("/")
for i in range(len(segments)):
p = "/".join(segments[:i])
if contains_array(store, p):
_init_group_metadata(store, path=p, chunk_store=chunk_store, overwrite=overwrite)
elif not contains_group(store, p):
_init_group_metadata(store, path=p, chunk_store=chunk_store)
def init_array(
store: StoreLike,
shape: Union[int, Tuple[int, ...]],
chunks: Union[bool, int, Tuple[int, ...]] = True,
dtype=None,
compressor="default",
fill_value=None,
order: str = "C",
overwrite: bool = False,
path: Optional[Path] = None,
chunk_store: Optional[StoreLike] = None,
filters=None,
object_codec=None,
dimension_separator: Optional[DIMENSION_SEPARATOR] = None,
storage_transformers=(),
):
"""Initialize an array store with the given configuration. Note that this is a low-level
function and there should be no need to call this directly from user code.
Parameters
----------
store : Store
A mapping that supports string keys and bytes-like values.
shape : int or tuple of ints
Array shape.
chunks : bool, int or tuple of ints, optional
Chunk shape. If True, will be guessed from `shape` and `dtype`. If
False, will be set to `shape`, i.e., single chunk for the whole array.
dtype : string or dtype, optional
NumPy dtype.
compressor : Codec, optional
Primary compressor.
fill_value : object
Default value to use for uninitialized portions of the array.
order : {'C', 'F'}, optional
Memory layout to be used within each chunk.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, bytes, optional
Path under which array is stored.
chunk_store : Store, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
filters : sequence, optional
Sequence of filters to use to encode chunk data prior to compression.
object_codec : Codec, optional
A codec to encode object arrays, only needed if dtype=object.
dimension_separator : {'.', '/'}, optional
Separator placed between the dimensions of a chunk.
Examples
--------
Initialize an array store::
>>> from zarr.storage import init_array, KVStore
>>> store = KVStore(dict())
>>> init_array(store, shape=(10000, 10000), chunks=(1000, 1000))
>>> sorted(store.keys())
['.zarray']
Array metadata is stored as JSON::
>>> print(store['.zarray'].decode())
{
"chunks": [
1000,
1000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "<f8",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
10000,
10000
],
"zarr_format": 2
}
Initialize an array using a storage path::
>>> store = KVStore(dict())
>>> init_array(store, shape=100000000, chunks=1000000, dtype='i1', path='foo')
>>> sorted(store.keys())
['.zgroup', 'foo/.zarray']
>>> print(store['foo/.zarray'].decode())
{
"chunks": [
1000000
],
"compressor": {
"blocksize": 0,
"clevel": 5,
"cname": "lz4",
"id": "blosc",
"shuffle": 1
},
"dtype": "|i1",
"fill_value": null,
"filters": null,
"order": "C",
"shape": [
100000000
],
"zarr_format": 2
}
Notes
-----
The initialisation process involves normalising all array metadata, encoding
as JSON and storing under the '.zarray' key.
"""
# normalize path
path = normalize_storage_path(path)
# ensure parent group initialized
store_version = getattr(store, "_store_version", 2)
if store_version < 3:
_require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite)
if store_version == 3 and "zarr.json" not in store:
# initialize with default zarr.json entry level metadata
store["zarr.json"] = store._metadata_class.encode_hierarchy_metadata(None) # type: ignore
if not compressor:
# compatibility with legacy tests using compressor=[]
compressor = None
_init_array_metadata(
store,
shape=shape,
chunks=chunks,
dtype=dtype,
compressor=compressor,
fill_value=fill_value,
order=order,
overwrite=overwrite,
path=path,
chunk_store=chunk_store,
filters=filters,
object_codec=object_codec,
dimension_separator=dimension_separator,
storage_transformers=storage_transformers,
)
def _init_array_metadata(
store: StoreLike,
shape,
chunks=None,
dtype=None,
compressor="default",
fill_value=None,
order="C",
overwrite=False,
path: Optional[str] = None,
chunk_store: Optional[StoreLike] = None,
filters=None,
object_codec=None,
dimension_separator: Optional[DIMENSION_SEPARATOR] = None,
storage_transformers=(),
):
store_version = getattr(store, "_store_version", 2)
path = normalize_storage_path(path)
# guard conditions
if overwrite:
if store_version == 2:
# attempt to delete any pre-existing array in store
rmdir(store, path)
if chunk_store is not None:
rmdir(chunk_store, path)
else:
group_meta_key = _prefix_to_group_key(store, _path_to_prefix(path))
array_meta_key = _prefix_to_array_key(store, _path_to_prefix(path))
data_prefix = data_root + _path_to_prefix(path)
# attempt to delete any pre-existing array in store
if array_meta_key in store:
store.erase(array_meta_key) # type: ignore
if group_meta_key in store:
store.erase(group_meta_key) # type: ignore
store.erase_prefix(data_prefix) # type: ignore
if chunk_store is not None:
chunk_store.erase_prefix(data_prefix) # type: ignore
if "/" in path:
# path is a subfolder of an existing array, remove that array
parent_path = "/".join(path.split("/")[:-1])
sfx = _get_metadata_suffix(store) # type: ignore
array_key = meta_root + parent_path + ".array" + sfx
if array_key in store:
store.erase(array_key) # type: ignore
if not overwrite:
if contains_array(store, path):
raise ContainsArrayError(path)
elif contains_group(store, path, explicit_only=False):
raise ContainsGroupError(path)
elif store_version == 3:
if "/" in path:
# cannot create an array within an existing array path
parent_path = "/".join(path.split("/")[:-1])
if contains_array(store, parent_path):
raise ContainsArrayError(path)
# normalize metadata
dtype, object_codec = normalize_dtype(dtype, object_codec)
shape = normalize_shape(shape) + dtype.shape
dtype = dtype.base
chunks = normalize_chunks(chunks, shape, dtype.itemsize)
order = normalize_order(order)
fill_value = normalize_fill_value(fill_value, dtype)
# optional array metadata
if dimension_separator is None and store_version == 2:
dimension_separator = getattr(store, "_dimension_separator", None)
dimension_separator = normalize_dimension_separator(dimension_separator)
# compressor prep
if shape == ():
# no point in compressing a 0-dimensional array, only a single value
compressor = None
elif compressor == "none":
# compatibility
compressor = None
elif compressor == "default":
compressor = default_compressor
# obtain compressor config
compressor_config = None
if compressor:
if store_version == 2:
try:
compressor_config = compressor.get_config()
except AttributeError as e:
raise BadCompressorError(compressor) from e
elif not isinstance(compressor, Codec):
raise ValueError("expected a numcodecs Codec for compressor")
# TODO: alternatively, could autoconvert str to a Codec
# e.g. 'zlib' -> numcodec.Zlib object
# compressor = numcodecs.get_codec({'id': compressor})
# obtain filters config
if filters:
# TODO: filters was removed from the metadata in v3
# raise error here if store_version > 2?
filters_config = [f.get_config() for f in filters]
else:
filters_config = []
# deal with object encoding
if dtype.hasobject:
if object_codec is None:
if not filters:
# there are no filters so we can be sure there is no object codec
raise ValueError("missing object_codec for object array")
else:
# one of the filters may be an object codec, issue a warning rather
# than raise an error to maintain backwards-compatibility
warnings.warn(
"missing object_codec for object array; this will raise a "
"ValueError in version 3.0",
FutureWarning,
)
else:
filters_config.insert(0, object_codec.get_config())
elif object_codec is not None:
warnings.warn("an object_codec is only needed for object arrays")
# use null to indicate no filters
if not filters_config:
filters_config = None # type: ignore
# initialize metadata
# TODO: don't store redundant dimension_separator for v3?
_compressor = compressor_config if store_version == 2 else compressor
meta = dict(
shape=shape,
compressor=_compressor,
fill_value=fill_value,
dimension_separator=dimension_separator,
)
if store_version < 3:
meta.update(dict(chunks=chunks, dtype=dtype, order=order, filters=filters_config))
assert not storage_transformers
else:
if dimension_separator is None:
dimension_separator = "/"
if filters_config:
attributes = {"filters": filters_config}
else:
attributes = {}
meta.update(
dict(
chunk_grid=dict(type="regular", chunk_shape=chunks, separator=dimension_separator),
chunk_memory_layout=order,
data_type=dtype,
attributes=attributes,
storage_transformers=storage_transformers,
)
)
key = _prefix_to_array_key(store, _path_to_prefix(path))
if hasattr(store, "_metadata_class"):
store[key] = store._metadata_class.encode_array_metadata(meta)
else:
store[key] = encode_array_metadata(meta)
# backwards compatibility
init_store = init_array
def init_group(
store: StoreLike,
overwrite: bool = False,
path: Path = None,
chunk_store: Optional[StoreLike] = None,
):
"""Initialize a group store. Note that this is a low-level function and there should be no
need to call this directly from user code.
Parameters
----------
store : Store
A mapping that supports string keys and byte sequence values.
overwrite : bool, optional
If True, erase all data in `store` prior to initialisation.
path : string, optional
Path under which array is stored.
chunk_store : Store, optional
Separate storage for chunks. If not provided, `store` will be used
for storage of both chunks and metadata.
"""
# normalize path
path = normalize_storage_path(path)
store_version = getattr(store, "_store_version", 2)
if store_version < 3:
# ensure parent group initialized
_require_parent_group(path, store=store, chunk_store=chunk_store, overwrite=overwrite)
if store_version == 3 and "zarr.json" not in store:
# initialize with default zarr.json entry level metadata
store["zarr.json"] = store._metadata_class.encode_hierarchy_metadata(None) # type: ignore
# initialise metadata
_init_group_metadata(store=store, overwrite=overwrite, path=path, chunk_store=chunk_store)
if store_version == 3:
# TODO: Should initializing a v3 group also create a corresponding
# empty folder under data/root/? I think probably not until there
# is actual data written there.
pass
def _init_group_metadata(
store: StoreLike,
overwrite: Optional[bool] = False,
path: Optional[str] = None,
chunk_store: Optional[StoreLike] = None,
):
store_version = getattr(store, "_store_version", 2)
path = normalize_storage_path(path)
# guard conditions
if overwrite:
if store_version == 2:
# attempt to delete any pre-existing items in store
rmdir(store, path)
if chunk_store is not None:
rmdir(chunk_store, path)
else:
group_meta_key = _prefix_to_group_key(store, _path_to_prefix(path))
array_meta_key = _prefix_to_array_key(store, _path_to_prefix(path))
data_prefix = data_root + _path_to_prefix(path)
meta_prefix = meta_root + _path_to_prefix(path)
# attempt to delete any pre-existing array in store
if array_meta_key in store:
store.erase(array_meta_key) # type: ignore
if group_meta_key in store:
store.erase(group_meta_key) # type: ignore
store.erase_prefix(data_prefix) # type: ignore
store.erase_prefix(meta_prefix) # type: ignore
if chunk_store is not None:
chunk_store.erase_prefix(data_prefix) # type: ignore
if not overwrite:
if contains_array(store, path):
raise ContainsArrayError(path)
elif contains_group(store, path):
raise ContainsGroupError(path)
elif store_version == 3 and "/" in path:
# cannot create a group overlapping with an existing array name
parent_path = "/".join(path.split("/")[:-1])
if contains_array(store, parent_path):
raise ContainsArrayError(path)
# initialize metadata
# N.B., currently no metadata properties are needed, however there may
# be in future
if store_version == 3:
meta = {"attributes": {}} # type: ignore
else:
meta = {}
key = _prefix_to_group_key(store, _path_to_prefix(path))
if hasattr(store, "_metadata_class"):
store[key] = store._metadata_class.encode_group_metadata(meta)
else:
store[key] = encode_group_metadata(meta)
def _dict_store_keys(d: Dict, prefix="", cls=dict):
for k in d.keys():
v = d[k]
if isinstance(v, cls):
yield from _dict_store_keys(v, prefix + k + "/", cls)
else:
yield prefix + k
class KVStore(Store):
"""
This provides a default implementation of a store interface around
a mutable mapping, to avoid having to test stores for presence of methods.
This, for most methods should just be a pass-through to the underlying KV
store which is likely to expose a MuttableMapping interface,
"""
def __init__(self, mutablemapping):
self._mutable_mapping = mutablemapping
def __getitem__(self, key):
return self._mutable_mapping[key]
def __setitem__(self, key, value):
self._mutable_mapping[key] = value
def __delitem__(self, key):
del self._mutable_mapping[key]
def __contains__(self, key):
return key in self._mutable_mapping
def get(self, key, default=None):
return self._mutable_mapping.get(key, default)
def values(self):
return self._mutable_mapping.values()
def __iter__(self):
return iter(self._mutable_mapping)
def __len__(self):
return len(self._mutable_mapping)
def __repr__(self):
return f"<{self.__class__.__name__}: \n{self._mutable_mapping!r}\n at {id(self):#x}>"
def __eq__(self, other):
if isinstance(other, KVStore):
return self._mutable_mapping == other._mutable_mapping
else:
return NotImplemented
class MemoryStore(Store):
"""Store class that uses a hierarchy of :class:`KVStore` objects, thus all data
will be held in main memory.
Examples
--------
This is the default class used when creating a group. E.g.::
>>> import zarr
>>> g = zarr.group()
>>> type(g.store)
<class 'zarr.storage.MemoryStore'>
Note that the default class when creating an array is the built-in
:class:`KVStore` class, i.e.::
>>> z = zarr.zeros(100)
>>> type(z.store)
<class 'zarr.storage.KVStore'>
Notes
-----
Safe to write in multiple threads.
"""
def __init__(self, root=None, cls=dict, dimension_separator=None):
if root is None:
self.root = cls()
else:
self.root = root
self.cls = cls
self.write_mutex = Lock()
self._dimension_separator = dimension_separator
def __getstate__(self):
return self.root, self.cls
def __setstate__(self, state):
root, cls = state
self.__init__(root=root, cls=cls)
def _get_parent(self, item: str):
parent = self.root
# split the item
segments = item.split("/")
# find the parent container
for k in segments[:-1]:
parent = parent[k]
if not isinstance(parent, self.cls):
raise KeyError(item)
return parent, segments[-1]
def _require_parent(self, item):
parent = self.root
# split the item
segments = item.split("/")
# require the parent container
for k in segments[:-1]:
try:
parent = parent[k]
except KeyError:
parent[k] = self.cls()
parent = parent[k]
else:
if not isinstance(parent, self.cls):
raise KeyError(item)
return parent, segments[-1]
def __getitem__(self, item: str):
parent, key = self._get_parent(item)
try:
value = parent[key]
except KeyError:
raise KeyError(item)
else:
if isinstance(value, self.cls):
raise KeyError(item)
else:
return value
def __setitem__(self, item: str, value):
with self.write_mutex:
parent, key = self._require_parent(item)
value = ensure_bytes(value)
parent[key] = value
def __delitem__(self, item: str):
with self.write_mutex:
parent, key = self._get_parent(item)
try:
del parent[key]
except KeyError:
raise KeyError(item)
def __contains__(self, item: str): # type: ignore[override]
try:
parent, key = self._get_parent(item)
value = parent[key]
except KeyError:
return False
else:
return not isinstance(value, self.cls)
def __eq__(self, other):
return isinstance(other, MemoryStore) and self.root == other.root and self.cls == other.cls
def keys(self):
yield from _dict_store_keys(self.root, cls=self.cls)
def __iter__(self):
return self.keys()
def __len__(self) -> int:
return sum(1 for _ in self.keys())
def listdir(self, path: Path = None) -> List[str]:
path = normalize_storage_path(path)
if path:
try:
parent, key = self._get_parent(path)
value = parent[key]
except KeyError:
return []
else:
value = self.root
if isinstance(value, self.cls):
return sorted(value.keys())
else:
return []
def rename(self, src_path: Path, dst_path: Path):
src_path = normalize_storage_path(src_path)
dst_path = normalize_storage_path(dst_path)
src_parent, src_key = self._get_parent(src_path)
dst_parent, dst_key = self._require_parent(dst_path)
dst_parent[dst_key] = src_parent.pop(src_key)
def rmdir(self, path: Path = None):
path = normalize_storage_path(path)
if path:
try:
parent, key = self._get_parent(path)
value = parent[key]
except KeyError:
return
else:
if isinstance(value, self.cls):
del parent[key]
else:
# clear out root
self.root = self.cls()
def getsize(self, path: Path = None):
path = normalize_storage_path(path)
# obtain value to return size of
value = None
if path:
try:
parent, key = self._get_parent(path)
value = parent[key]
except KeyError:
pass
else:
value = self.root
# obtain size of value
if value is None:
return 0
elif isinstance(value, self.cls):
# total size for directory
size = 0
for v in value.values():
if not isinstance(v, self.cls):
size += buffer_size(v)
return size
else:
return buffer_size(value)
def clear(self):
with self.write_mutex:
self.root.clear()
class DictStore(MemoryStore):
def __init__(self, *args, **kwargs):
warnings.warn(
"DictStore has been renamed to MemoryStore in 2.4.0 and "
"will be removed in the future. Please use MemoryStore.",
DeprecationWarning,
stacklevel=2,
)
super().__init__(*args, **kwargs)
class DirectoryStore(Store):
"""Storage class using directories and files on a standard file system.