-
-
Notifications
You must be signed in to change notification settings - Fork 324
/
Copy pathhierarchy.py
1620 lines (1384 loc) · 51.9 KB
/
hierarchy.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 warnings
from collections.abc import MutableMapping
from itertools import islice
import numpy as np
from zarr._storage.store import (
_get_metadata_suffix,
data_root,
meta_root,
DEFAULT_ZARR_VERSION,
assert_zarr_v3_api_available,
)
from zarr.attrs import Attributes
from zarr.core import Array
from zarr.creation import (
array,
create,
empty,
empty_like,
full,
full_like,
ones,
ones_like,
zeros,
zeros_like,
)
from zarr.errors import (
ContainsArrayError,
ContainsGroupError,
ArrayNotFoundError,
GroupNotFoundError,
ReadOnlyError,
)
from zarr.storage import (
_get_hierarchy_metadata,
_prefix_to_group_key,
BaseStore,
MemoryStore,
attrs_key,
contains_array,
contains_group,
group_meta_key,
init_group,
listdir,
normalize_store_arg,
rename,
rmdir,
)
from zarr._storage.v3 import MemoryStoreV3
from zarr.util import (
InfoReporter,
TreeViewer,
is_valid_python_name,
nolock,
normalize_shape,
normalize_storage_path,
)
class Group(MutableMapping):
"""Instantiate a group from an initialized store.
Parameters
----------
store : MutableMapping
Group store, already initialized.
If the Group is used in a context manager, and the store has a ``close`` method,
it will be called on exit.
path : string, optional
Group path.
read_only : bool, optional
True if group 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.
[DEPRECATED since version 2.18.4] This argument is deprecated and will be
removed in version 3.0. See
`GH2495 <https://github.com/zarr-developers/zarr-python/issues/2495>`_
for more information.
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.
synchronizer : object, optional
Array synchronizer.
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
synchronizer
attrs
info
meta_array
Methods
-------
__len__
__iter__
__contains__
__getitem__
__enter__
__exit__
group_keys
groups
array_keys
arrays
visit
visitkeys
visitvalues
visititems
tree
create_group
require_group
create_groups
require_groups
create_dataset
require_dataset
create
empty
zeros
ones
full
array
empty_like
zeros_like
ones_like
full_like
info
move
"""
def __init__(
self,
store,
path=None,
read_only=False,
chunk_store=None,
cache_attrs=True,
synchronizer=None,
zarr_version=None,
*,
meta_array=None,
):
store: BaseStore = _normalize_store_arg(store, zarr_version=zarr_version)
if zarr_version is None:
zarr_version = getattr(store, "_store_version", DEFAULT_ZARR_VERSION)
if zarr_version != 2:
assert_zarr_v3_api_available()
if chunk_store is not None:
warnings.warn(
"chunk_store is deprecated and will be removed in a Zarr-Python version 3, see "
"https://github.com/zarr-developers/zarr-python/issues/2495 for more information.",
FutureWarning,
stacklevel=2,
)
chunk_store: BaseStore = _normalize_store_arg(chunk_store, zarr_version=zarr_version)
self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
if self._path:
self._key_prefix = self._path + "/"
else:
self._key_prefix = ""
self._read_only = read_only
self._synchronizer = synchronizer
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 = _get_metadata_suffix(store=self._store)
# guard conditions
if contains_array(store, path=self._path):
raise ContainsArrayError(path)
# initialize metadata
mkey = None
try:
mkey = _prefix_to_group_key(self._store, self._key_prefix)
assert not mkey.endswith("root/.group")
meta_bytes = store[mkey]
except KeyError as e:
if self._version == 2:
raise GroupNotFoundError(path) from e
else:
implicit_prefix = meta_root + self._key_prefix
if self._store.list_prefix(implicit_prefix):
# implicit group does not have any metadata
self._meta = None
else:
raise GroupNotFoundError(path) from e
else:
self._meta = self._store._metadata_class.decode_group_metadata(meta_bytes)
# setup attributes
if self._version == 2:
akey = self._key_prefix + attrs_key
else:
# Note: mkey doesn't actually exist for implicit groups, but the
# object can still be created.
akey = mkey
self._attrs = Attributes(
store,
key=akey,
read_only=read_only,
cache=cache_attrs,
synchronizer=synchronizer,
cached_dict=self._meta["attributes"] if self._version == 3 and self._meta else None,
)
# setup info
@property
def store(self):
"""A MutableMapping providing the underlying storage for the group."""
return self._store
@property
def path(self):
"""Storage path."""
return self._path
@property
def name(self):
"""Group name following h5py convention."""
if self._path:
# follow h5py convention: add leading slash
name = self._path
if name[0] != "/":
name = "/" + name
return name
return "/"
@property
def basename(self):
"""Final component of name."""
return self.name.split("/")[-1]
@property
def read_only(self):
"""A boolean, True if modification operations are not permitted."""
return self._read_only
@property
def chunk_store(self):
"""A MutableMapping providing the underlying storage for array chunks."""
if self._chunk_store is None:
return self._store
else:
return self._chunk_store
@property
def synchronizer(self):
"""Object used to synchronize write access to groups and arrays."""
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 info(self):
"""Return diagnostic information about the group."""
return InfoReporter(self)
@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, Group)
and self._store == other.store
and self._read_only == other.read_only
and self._path == other.path
# N.B., no need to compare attributes, should be covered by
# store comparison
)
def __iter__(self):
"""Return an iterator over group member names.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> for name in g1:
... print(name)
bar
baz
foo
quux
"""
if getattr(self._store, "_store_version", 2) == 2:
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_array(self._store, path) or contains_group(self._store, path):
yield key
else:
# TODO: Should this iterate over data folders and/or metadata
# folders and/or metadata files
dir_path = meta_root + self._key_prefix
name_start = len(dir_path)
keys, prefixes = self._store.list_dir(dir_path)
# yield any groups or arrays
sfx = self._metadata_key_suffix
for key in keys:
len_suffix = len(".group") + len(sfx) # same for .array
if key.endswith((".group" + sfx, ".array" + sfx)):
yield key[name_start:-len_suffix]
# also yield any implicit groups
for prefix in prefixes:
prefix = prefix.rstrip("/")
# only implicit if there is no .group.sfx file
if prefix + ".group" + sfx not in self._store:
yield prefix[name_start:]
# Note: omit data/root/ to avoid duplicate listings
# any group in data/root/ must has an entry in meta/root/
def __len__(self):
"""Number of members."""
return sum(1 for _ in self)
def __repr__(self):
t = type(self)
r = f"<{t.__module__}.{t.__name__}"
if self.name:
r += f" {self.name!r}"
if self._read_only:
r += " read-only"
r += ">"
return r
def __enter__(self):
"""Return the Group for use as a context manager."""
return self
def __exit__(self, exc_type, exc_val, exc_tb):
"""Call the close method of the underlying Store."""
self.store.close()
def info_items(self):
def typestr(o):
return f"{type(o).__module__}.{type(o).__name__}"
items = []
# basic info
if self.name is not None:
items += [("Name", self.name)]
items += [
("Type", typestr(self)),
("Read-only", str(self.read_only)),
]
# synchronizer
if self._synchronizer is not None:
items += [("Synchronizer type", typestr(self._synchronizer))]
# storage info
items += [("Store type", typestr(self._store))]
if self._chunk_store is not None:
items += [("Chunk store type", typestr(self._chunk_store))]
# members
items += [("No. members", len(self))]
array_keys = sorted(self.array_keys())
group_keys = sorted(self.group_keys())
items += [("No. arrays", len(array_keys))]
items += [("No. groups", len(group_keys))]
if array_keys:
items += [("Arrays", ", ".join(array_keys))]
if group_keys:
items += [("Groups", ", ".join(group_keys))]
return items
def __getstate__(self):
return {
"store": self._store,
"path": self._path,
"read_only": self._read_only,
"chunk_store": self._chunk_store,
"cache_attrs": self._attrs.cache,
"synchronizer": self._synchronizer,
"zarr_version": self._version,
"meta_array": self._meta_array,
}
def __setstate__(self, state):
self.__init__(**state)
def _item_path(self, item):
absolute = isinstance(item, str) and item and item[0] == "/"
path = normalize_storage_path(item)
if not absolute and self._path:
path = self._key_prefix + path
return path
def __contains__(self, item):
"""Test for group membership.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> d1 = g1.create_dataset('bar', shape=100, chunks=10)
>>> 'foo' in g1
True
>>> 'bar' in g1
True
>>> 'baz' in g1
False
"""
path = self._item_path(item)
return contains_array(self._store, path) or contains_group(
self._store, path, explicit_only=False
)
def __getitem__(self, item):
"""Obtain a group member.
Parameters
----------
item : string
Member name or path.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> d1 = g1.create_dataset('foo/bar/baz', shape=100, chunks=10)
>>> g1['foo']
<zarr.hierarchy.Group '/foo'>
>>> g1['foo/bar']
<zarr.hierarchy.Group '/foo/bar'>
>>> g1['foo/bar/baz']
<zarr.core.Array '/foo/bar/baz' (100,) float64>
"""
path = self._item_path(item)
try:
return Array(
self._store,
read_only=self._read_only,
path=path,
chunk_store=self._chunk_store,
synchronizer=self._synchronizer,
cache_attrs=self.attrs.cache,
zarr_version=self._version,
meta_array=self._meta_array,
)
except ArrayNotFoundError:
pass
try:
return Group(
self._store,
read_only=self._read_only,
path=path,
chunk_store=self._chunk_store,
cache_attrs=self.attrs.cache,
synchronizer=self._synchronizer,
zarr_version=self._version,
meta_array=self._meta_array,
)
except GroupNotFoundError:
pass
if self._version == 3:
implicit_group = meta_root + path + "/"
# non-empty folder in the metadata path implies an implicit group
if self._store.list_prefix(implicit_group):
return Group(
self._store,
read_only=self._read_only,
path=path,
chunk_store=self._chunk_store,
cache_attrs=self.attrs.cache,
synchronizer=self._synchronizer,
zarr_version=self._version,
meta_array=self._meta_array,
)
else:
raise KeyError(item)
else:
raise KeyError(item)
def __setitem__(self, item, value):
self.array(item, value, overwrite=True)
def __delitem__(self, item):
return self._write_op(self._delitem_nosync, item)
def _delitem_nosync(self, item):
path = self._item_path(item)
if contains_array(self._store, path) or contains_group(
self._store, path, explicit_only=False
):
rmdir(self._store, path)
else:
raise KeyError(item)
def __getattr__(self, item):
# https://github.com/jupyter/notebook/issues/2014
# Save a possibly expensive lookup (for e.g. against cloud stores)
# Note: The _ipython_display_ method is required to display the right info as a side-effect.
# It is simpler to pretend it doesn't exist.
if item in ["_ipython_canary_method_should_not_exist_", "_ipython_display_"]:
raise AttributeError
# allow access to group members via dot notation
try:
return self.__getitem__(item)
except KeyError as e:
raise AttributeError from e
def __dir__(self):
# noinspection PyUnresolvedReferences
base = super().__dir__()
keys = sorted(set(base + list(self)))
keys = [k for k in keys if is_valid_python_name(k)]
return keys
def _ipython_key_completions_(self):
return sorted(self)
def group_keys(self):
"""Return an iterator over member names for groups only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.group_keys())
['bar', 'foo']
"""
if self._version == 2:
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_group(self._store, path):
yield key
else:
dir_name = meta_root + self._path
group_sfx = ".group" + self._metadata_key_suffix
# The fact that we call sorted means this can't be a streaming generator.
# The keys are already in memory.
all_keys = sorted(listdir(self._store, dir_name))
for key in all_keys:
if key.endswith(group_sfx):
key = key[: -len(group_sfx)]
if key in all_keys:
# otherwise we will double count this group
continue
path = self._key_prefix + key
if path.endswith(".array" + self._metadata_key_suffix):
# skip array keys
continue
if contains_group(self._store, path, explicit_only=False):
yield key
def groups(self):
"""Return an iterator over (name, value) pairs for groups only.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> for n, v in g1.groups():
... print(n, type(v))
bar <class 'zarr.hierarchy.Group'>
foo <class 'zarr.hierarchy.Group'>
"""
if self._version == 2:
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_group(self._store, path, explicit_only=False):
yield key, Group(
self._store,
path=path,
read_only=self._read_only,
chunk_store=self._chunk_store,
cache_attrs=self.attrs.cache,
synchronizer=self._synchronizer,
zarr_version=self._version,
)
else:
for key in self.group_keys():
path = self._key_prefix + key
yield key, Group(
self._store,
path=path,
read_only=self._read_only,
chunk_store=self._chunk_store,
cache_attrs=self.attrs.cache,
synchronizer=self._synchronizer,
zarr_version=self._version,
)
def array_keys(self, recurse=False):
"""Return an iterator over member names for arrays only.
Parameters
----------
recurse : recurse, optional
Option to return member names for all arrays, even from groups
below the current one. If False, only member names for arrays in
the current group will be returned. Default value is False.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> sorted(g1.array_keys())
['baz', 'quux']
"""
return self._array_iter(keys_only=True, method="array_keys", recurse=recurse)
def arrays(self, recurse=False):
"""Return an iterator over (name, value) pairs for arrays only.
Parameters
----------
recurse : recurse, optional
Option to return (name, value) pairs for all arrays, even from groups
below the current one. If False, only (name, value) pairs for arrays in
the current group will be returned. Default value is False.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> d1 = g1.create_dataset('baz', shape=100, chunks=10)
>>> d2 = g1.create_dataset('quux', shape=200, chunks=20)
>>> for n, v in g1.arrays():
... print(n, type(v))
baz <class 'zarr.core.Array'>
quux <class 'zarr.core.Array'>
"""
return self._array_iter(keys_only=False, method="arrays", recurse=recurse)
def _array_iter(self, keys_only, method, recurse):
if self._version == 2:
for key in sorted(listdir(self._store, self._path)):
path = self._key_prefix + key
if contains_array(self._store, path):
_key = key.rstrip("/")
yield _key if keys_only else (_key, self[key])
elif recurse and contains_group(self._store, path):
group = self[key]
yield from getattr(group, method)(recurse=recurse)
else:
dir_name = meta_root + self._path
array_sfx = ".array" + self._metadata_key_suffix
group_sfx = ".group" + self._metadata_key_suffix
for key in sorted(listdir(self._store, dir_name)):
if key.endswith(array_sfx):
key = key[: -len(array_sfx)]
_key = key.rstrip("/")
yield _key if keys_only else (_key, self[key])
path = self._key_prefix + key
assert not path.startswith("meta/")
if key.endswith(group_sfx):
# skip group metadata keys
continue
elif recurse and contains_group(self._store, path):
group = self[key]
yield from getattr(group, method)(recurse=recurse)
def visitvalues(self, func):
"""Run ``func`` on each object.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(obj):
... print(obj)
>>> g1.visitvalues(print_visitor)
<zarr.hierarchy.Group '/bar'>
<zarr.hierarchy.Group '/bar/baz'>
<zarr.hierarchy.Group '/bar/quux'>
<zarr.hierarchy.Group '/foo'>
>>> g3.visitvalues(print_visitor)
<zarr.hierarchy.Group '/bar/baz'>
<zarr.hierarchy.Group '/bar/quux'>
"""
def _visit(obj):
yield obj
keys = sorted(getattr(obj, "keys", lambda: [])())
for k in keys:
yield from _visit(obj[k])
for each_obj in islice(_visit(self), 1, None):
value = func(each_obj)
if value is not None:
return value
def visit(self, func):
"""Run ``func`` on each object's path.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(name):
... print(name)
>>> g1.visit(print_visitor)
bar
bar/baz
bar/quux
foo
>>> g3.visit(print_visitor)
baz
quux
Search for members matching some name query can be implemented using
``visit`` that is, ``find`` and ``findall``. Consider the following
tree::
/
├── aaa
│ └── bbb
│ └── ccc
│ └── aaa
├── bar
└── foo
It is created as follows:
>>> root = zarr.group()
>>> foo = root.create_group("foo")
>>> bar = root.create_group("bar")
>>> root.create_group("aaa").create_group("bbb").create_group("ccc").create_group("aaa")
<zarr.hierarchy.Group '/aaa/bbb/ccc/aaa'>
For ``find``, the first path that matches a given pattern (for example
"aaa") is returned. Note that a non-None value is returned in the visit
function to stop further iteration.
>>> import re
>>> pattern = re.compile("aaa")
>>> found = None
>>> def find(path):
... global found
... if pattern.search(path) is not None:
... found = path
... return True
...
>>> root.visit(find)
True
>>> print(found)
aaa
For ``findall``, all the results are gathered into a list
>>> pattern = re.compile("aaa")
>>> found = []
>>> def findall(path):
... if pattern.search(path) is not None:
... found.append(path)
...
>>> root.visit(findall)
>>> print(found)
['aaa', 'aaa/bbb', 'aaa/bbb/ccc', 'aaa/bbb/ccc/aaa']
To match only on the last part of the path, use a greedy regex to filter
out the prefix:
>>> prefix_pattern = re.compile(r".*/")
>>> pattern = re.compile("aaa")
>>> found = []
>>> def findall(path):
... match = prefix_pattern.match(path)
... if match is None:
... name = path
... else:
... _, end = match.span()
... name = path[end:]
... if pattern.search(name) is not None:
... found.append(path)
... return None
...
>>> root.visit(findall)
>>> print(found)
['aaa', 'aaa/bbb/ccc/aaa']
"""
base_len = len(self.name)
return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/")))
def visitkeys(self, func):
"""An alias for :py:meth:`~Group.visit`."""
return self.visit(func)
def visititems(self, func):
"""Run ``func`` on each object's path and the object itself.
Note: If ``func`` returns ``None`` (or doesn't return),
iteration continues. However, if ``func`` returns
anything else, it ceases and returns that value.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> def print_visitor(name, obj):
... print((name, obj))
>>> g1.visititems(print_visitor)
('bar', <zarr.hierarchy.Group '/bar'>)
('bar/baz', <zarr.hierarchy.Group '/bar/baz'>)
('bar/quux', <zarr.hierarchy.Group '/bar/quux'>)
('foo', <zarr.hierarchy.Group '/foo'>)
>>> g3.visititems(print_visitor)
('baz', <zarr.hierarchy.Group '/bar/baz'>)
('quux', <zarr.hierarchy.Group '/bar/quux'>)
"""
base_len = len(self.name)
return self.visitvalues(lambda o: func(o.name[base_len:].lstrip("/"), o))
def tree(self, expand=False, level=None):
"""Provide a ``print``-able display of the hierarchy.
Parameters
----------
expand : bool, optional
Only relevant for HTML representation. If True, tree will be fully expanded.
level : int, optional
Maximum depth to descend into hierarchy.
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g3.create_group('baz')
>>> g5 = g3.create_group('quux')
>>> d1 = g5.create_dataset('baz', shape=100, chunks=10)
>>> g1.tree()
/
├── bar
│ ├── baz
│ └── quux
│ └── baz (100,) float64
└── foo
>>> g1.tree(level=2)
/
├── bar
│ ├── baz
│ └── quux
└── foo
>>> g3.tree()
bar
├── baz
└── quux
└── baz (100,) float64
Notes
-----
Please note that this is an experimental feature. The behaviour of this
function is still evolving and the default output and/or parameters may change
in future versions.
"""
return TreeViewer(self, expand=expand, level=level)
def _write_op(self, f, *args, **kwargs):
# guard condition
if self._read_only:
raise ReadOnlyError()
if self._synchronizer is None:
# no synchronization
lock = nolock
else:
# synchronize on the root group
lock = self._synchronizer[group_meta_key]
with lock:
return f(*args, **kwargs)
def create_group(self, name, overwrite=False):
"""Create a sub-group.
Parameters
----------
name : string
Group name.
overwrite : bool, optional
If True, overwrite any existing array with the given name.
Returns
-------
g : zarr.hierarchy.Group
Examples
--------
>>> import zarr
>>> g1 = zarr.group()
>>> g2 = g1.create_group('foo')
>>> g3 = g1.create_group('bar')
>>> g4 = g1.create_group('baz/quux')
"""
return self._write_op(self._create_group_nosync, name, overwrite=overwrite)
def _create_group_nosync(self, name, overwrite=False):
path = self._item_path(name)
# create terminal group
init_group(self._store, path=path, chunk_store=self._chunk_store, overwrite=overwrite)
return Group(
self._store,
path=path,
read_only=self._read_only,