/
core.py
executable file
·1797 lines (1549 loc) · 71.6 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
# -*- coding: utf-8 -*-
"""Provide the base classes and functions for the :py:class:`Stoner.DataFolder` class."""
__all__ = ["baseFolder"]
from collections.abc import Iterable, MutableSequence
import fnmatch
import re
from itertools import islice
from copy import copy, deepcopy
from inspect import isclass
import os.path as path
import numpy as np
from ..compat import int_types, string_types, commonpath, _pattern_type
from ..tools import operator, isiterable, all_type, get_option
from ..core.base import regexpDict, typeHintedDict
from ..core.base import metadataObject
from .utils import pathjoin
from .each import Item as EachItem
from .metadata import MetadataProxy
from .groups import GroupsDict
regexp_type = (_pattern_type,)
def _add_core_(result, other):
"""Implement the core logic of the addition operator.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
if isinstance(other, baseFolder):
if isclass(other.type) and issubclass(other.type, result.type):
result.extend(list(other.files))
for grp in other.groups:
if grp in result.groups:
result.groups[grp] += other.groups[grp] # recursely merge groups
else:
result.groups[grp] = copy(other.groups[grp])
else:
raise RuntimeError(
f"Incompatible types ({other.type} must be a subclass of {result.type}) in the two folders."
)
elif isinstance(other, result.type):
result.append(other)
else:
result = NotImplemented
return result
def _div_core_(result, other):
"""Implement the divide operator as a grouping function."""
if isinstance(other, string_types + (list, tuple)):
result.group(other)
return result
if isinstance(other, int_types): # Simple decimate
for i in range(other):
result.add_group(f"Group {i}")
for ix in range(len(result)):
d = result.__getter__(ix, instantiate=None)
group = ix % other
result.groups[f"Group {group}"].__setter__(result.__lookup__(ix), d)
result.__clear__()
return result
return NotImplemented
def _sub_core_(result, other):
"""Implement the core logic of the subtraction operator.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
calls = [
(int_types, _sub_core_int_),
(string_types, _sub_core_string_),
(metadataObject, _sub_core_data_),
(baseFolder, _sub_core_folder_),
(Iterable, _sub_core_iterable_),
]
for typ, func in calls:
if isinstance(other, typ):
result = func(result, other)
break
else:
result = NotImplemented
return result
def _sub_core_int_(result, other):
"""Remove indexed file."""
delname = result.__names__()[other]
result.__deleter__(delname)
return result
def _sub_core_string_(result, other):
"""Remove named file."""
if other in result.__names__():
result.__deleter__(other)
else:
raise RuntimeError(f"{other} is not in the folder.")
return result
def _sub_core_data_(result, other):
"""Remove a data object."""
othername = getattr(other, "filename", getattr(other, "title", None))
if othername in result.__names__():
result.__deleter__(othername)
else:
raise RuntimeError(f"{othername} is not in the folder.")
return result
def _sub_core_folder_(result, other):
"""Remove a folder."""
if isclass(other.type) and issubclass(other.type, result.type):
for othername in other.ls:
if othername in result:
result.__deleter__(othername)
for othergroup in other.groups:
if othergroup in result.groups:
result.groups[othergroup] -= other.groups[othergroup]
else:
raise RuntimeError(
f"Incompatible types ({other.type} must be a subclass of {result.type}) in the two folders."
)
return result
def _sub_core_iterable_(result, other):
"""Iterate to remove iterables."""
for c in sorted(other):
_sub_core_(result, c)
return result
def _build_select_function(kargs, arg):
"""Build a select function from an a list of keywords and a keyword name.
Args:
kargs (dict):
The keyword arguments passed to the select function.
arg (str):
Name of the keyword argument we're considering.
Returns:
tuple of:
Callable function that takes two arguments and returns a boolean if the two arguments match.
str name of key to look up
"""
parts = arg.split("__")
negate = kargs.pop("negate", False)
if parts[-1] in operator and len(parts) > 1:
if len(parts) > 2 and parts[-2] == "not":
end = -2
negate = True
else:
end = -1
negate = False
arg = "__".join(parts[:end])
op = parts[-1]
else:
if isinstance(kargs[arg], tuple) and len(kargs[arg] == 2):
op = "between" # Assume two length tuples are testing for range
elif not isinstance(kargs[arg], string_types) and isiterable(kargs[arg]):
op = "in" # Assume other iterables are testing for membership
else: # Everything else is exact matches
op = "eq"
func = operator[op]
if negate:
func = lambda k, v: not func(k, v)
return func, arg
class baseFolder(MutableSequence):
"""A base class for objectFolders that supports both a sequence of objects and a mapping of instances of itself.
Attributes:
groups(GroupsDict):
A dictionary of similar baseFolder instances
objects(regexptDict):
A dictionary of metadataObjects
_defaults (dict):
A dictionary of default balues for the constructor of the class when combined with mixin classes
_no_defaults (list):
A list of default parameters to veto when setting the constructor.
Properties:
depth (int):
The maximum number of levels of nested groups in the folder
files (list of str or metadataObject):
The individual objects or their names if they are not loaded
instance (metadataObject):
An empty instance of the data type stored in the folder
loaded (generator of (str name, metadataObject value):
Iterate over only the loaded into memory items of the folder
ls (list of str):
The names of the objects in the folder, loaded or not
lsgrp (list of str):
The names of all the groups in the folder
mindepth (int):
Fhe minimum level of nesting groups in the folder.
not_empty (iterator of metadaaObject):
Iterates over all members of the folder that have non-zero length
shape (tuple):
A data structure that indicates the structure of the objectFolder - tuple of number of files and
dictionary of the shape of each group.
type (subclass of metadtaObject):
The class of objects sotred in this folder
Notes:
A baseFolder is a multable sequence object that should store a mapping of instances of some sort of data
object (typically a :py:class:`Stoner.Core.metadataobject`) which can be iterated over in a reproducible and
predicatable way as well as being accessed by a key. The other requirement is that it stores a mapping to
objects of its own type to allow an in-memory tree object to be constructed.
Additional functionality is built in by providing mixin classes that override the accessors for the data
object store. Minimally this should include
- __lookup__ take a keyname and return a canonical accessor key
- __names__ returns the ordered list of mapping keys to the object store
- __getter__ returns a single instance of the data object referenced by a canonical key
- __setter__ add or overwrite an instance of the object store by canonical key
- __inserter__ insert an instance into a specific place in the Folder
- __deleter__ remove an instance of a data object by canonical key
- __clear__ remove all instance
- __clone__ create a new copy of the mixin's state kinformation
"""
# pylint: disable=no-member
_defaults = (
{}
) # A Dictionary of default values that will be combined with other classes to make a global set of defaults
_no_defaults = [] # A list of dewfaults to remove becayse they clash with subclass methods etc.
def __new__(cls, *args, **kargs):
"""Create the underlying storage attributes.
We do this in __new__ so that the mixin classes can access baseFolders state storage before baseFolder does
further __init__() work.
"""
self = super(baseFolder, cls).__new__(cls)
self._debug = kargs.pop("debug", False)
self._object_attrs = dict()
self._last_name = 0
self._groups = GroupsDict(base=self)
self._objects = regexpDict()
self._instance = None
self._object_attrs = dict()
self._key = None
self._type = metadataObject
self._loader = None
self._instance_attrs = set()
self._root = "."
self._default_store = None
self.directory = None
return self
def __init__(self, *args, **kargs):
"""Initialise the baseFolder.
Notes:
- Creates empty groups and objects stres
- Sets all keyword arguments as attributes unless otherwise overwriting an existing attribute
- stores other arguments in self.args
- iterates over the multuiple inheritance tree and eplaces any interface methods with ones from
the mixin classes
- calls the mixin init methods.
"""
for k in self.defaults:
setattr(self, k, kargs.pop(k, self.defaults[k]))
if len(args) == 1 and isinstance(args[0], baseFolder): # Special case for type changing.
self.args = ()
self.kargs = {}
self.__init_from_other(args[0])
else:
self.args = copy(args)
self.kargs = copy(kargs)
# List of routines that define the interface for manipulating the objects stored in the folder
for k in list(self.kargs.keys()): # Store keyword parameters as attributes
if not hasattr(self, k) or k in ["type", "kargs", "args"]:
value = kargs.pop(k, None)
self.__setattr__(k, value)
if self.debug:
print(f"Setting self.{k} to {value}")
self.directory = getattr(self, "directory", None) # pointless hack for pylint
super().__init__()
###########################################################################
################### Properties of baseFolder ##############################
@property
def clone(self):
"""Clone just does a deepcopy as a property for compatibility with :py:class:`Stoner.Core.DataFile`."""
return self.__clone__()
@property
def defaults(self):
"""Build a single list of all of our defaults by iterating over the __mro__, caching the result."""
if getattr(self, "_default_store", None) is None:
self._default_store = dict() # pylint: disable=attribute-defined-outside-init
for cls in reversed(type(self).__mro__):
if hasattr(cls, "_defaults"):
self._default_store.update(cls._defaults)
for cls in reversed(type(self).__mro__):
if hasattr(cls, "_no_defaults"):
for k in cls._no_defaults:
self._default_store.pop(k, None)
return self._default_store
@property
def debug(self):
"""Just read the local debug value."""
return self._debug
@debug.setter
def debug(self, value):
"""Recursely set the debug value."""
self._debug = value
self._object_attrs["debug"] = value
for _, member in self.loaded:
member.debug = value
for grp in self.groups:
self.groups[grp].debug = value
@property
def depth(self):
"""Give the maximum number of levels of group below the current objectFolder."""
if len(self.groups) == 0:
r = 0
else:
r = 1
for g in self.groups:
r = max(r, self.groups[g].depth + 1)
return r
@property
def each(self):
"""Return a :py:class:`Stoner.folders.each.item` proxy object.
This is for calling attributes of the member type of the folder.
"""
return EachItem(self)
@property
def files(self):
"""Return an iterator of potentially unloaded named objects."""
return [self.__getter__(i, instantiate=None) for i in range(len(self))]
@files.setter
def files(self, value):
"""Just a wrapper to clear and then set the objects."""
if isiterable(value):
self.__clear__()
for i, v in enumerate(value):
self.insert(i, v)
@property
def groups(self):
"""Subfolders are held in an ordered dictionary of groups."""
self._groups.base = self
return self._groups
@groups.setter
def groups(self, value):
"""Ensure groups gets set as a :py:class:`regexpDict`."""
if not isinstance(value, GroupsDict):
self._groups = GroupsDict(deepcopy(value), base=self)
else:
self._groups = GroupsDict({g: v.clone for g, v in value.items()})
self._groups.base = self
@property
def instance(self):
"""Return a default instance of the type of object in the folder."""
if self._instance is None:
self._instance = self._type()
return self._instance
@property
def is_empty(self):
"""Return True if the folder is empty."""
return len(self) == 0 and len(self.groups) == 0
@property
def key(self):
"""Allow overriding for getting and setting the key in mixins."""
return self._key
@key.setter
def key(self, value):
"""Set the folder's key."""
self._key = value
@property
def layout(self):
"""Return a tuple that describes the number of files and groups in the folder."""
return (len(self), {k: grp.layout for k, grp in self.groups.items()})
@property
def loaded(self):
"""Iterate only over those members of the folder in memory."""
for f in self.__names__():
val = self.__getter__(f, instantiate=None)
if isinstance(val, self.type):
yield f, val
@property
def loader(self):
"""Return a callable that will load the files on demand."""
if self._loader is None:
self._loader = self.type
return self._loader
@loader.setter
def loader(self, value):
"""Set the loader class ensuring that it is a metadataObject."""
if isclass(value) and issubclass(value, metadataObject):
self._loader = value
@property
def ls(self):
"""List just the names of the objects in the folder."""
for f in self.__names__():
yield f
@property
def lsgrp(self):
"""Return a list of the groups as a generator."""
for k in self.groups:
yield k
@property
def metadata(self):
"""Return a :py:class:`Stoner.folders.metadata.MetadataProxy` object.
This allows for operations on combined metadata.
"""
return MetadataProxy(self)
@property
def mindepth(self):
"""Give the minimum number of levels of group below the current objectFolder."""
if len(self.groups) == 0:
r = 0
else:
r = 1e6
for g in self.groups:
r = min(r, self.groups[g].depth + 1)
return r
@property
def not_empty(self):
"""Iterate over the objectFolder that checks whether the loaded metadataObject objects have any data.
Returns the next non-empty DatFile member of the objectFolder.
Note:
not_empty will also silently skip over any cases where loading the metadataObject object will raise
and exception.
"""
for d in self:
if len(d) == 0:
continue
yield (d)
@property
def objects(self):
"""Return the objects in the folder are stored in a :py:class:`regexpDict`."""
return self._objects
@objects.setter
def objects(self, value):
"""Ensure we keep the objects in a :py:class:`regexpDict`."""
if not isinstance(value, regexpDict):
self._objects = regexpDict(value)
else:
self._objects = value
@property
def setas(self):
"""Return the proxy for the setas attribute for each object in the folder."""
return self.each.setas
@setas.setter
def setas(self, value):
"""Set a value to the proxy setas object for each item in the folder."""
self.each.setas = value
@property
def shape(self):
"""Return a data structure that is characteristic of the objectFolder's shape."""
grp_shape = {k: self[k].shape for k in self.groups}
return (len(self), grp_shape)
@property
def root(self):
"""Return the real folder root."""
return self._root
@root.setter
def root(self, value):
"""Set the folder root."""
self._root = value
@property
def trunkdepth(self):
"""Return the number of levels of group before a group with files is found."""
if self.files:
return 0
return min([self.groups[g].trunkdepth for g in self.groups]) + 1
@property
def type(self):
"""Return the (sub)class of the :py:class:`Stoner.Core.metadataObject` instances."""
return self._type
@type.setter
def type(self, value):
"""Ensure that type is a subclass of metadataObject."""
if isclass(value) and issubclass(value, metadataObject):
self._type = value
elif isinstance(value, metadataObject):
self._type = type(value)
else:
raise TypeError(f"{type(value)} os neither a subclass nor instance of metadataObject")
self._instance = None # Reset the instance cache
################### Methods for subclasses to override to handle storage #####
def __lookup__(self, name):
"""Stub for other classes to implement.
Parameters:
name(str):
Name of an object
Returns:
A key in whatever form the :py:meth:`baseFolder.__getter__` will accept.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
if isinstance(name, int_types):
name = self.__names__()[name]
elif name not in self.__names__():
name = self._objects.__lookup__(name)
return name
def __names__(self):
"""Stub method to return a list of names of all objects that can be indexed for __getter__.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
return list(self.objects.keys())
def __getter__(self, name, instantiate=True):
"""Stub method to do whatever is needed to transform a key to a metadataObject.
Parameters:
name (key type):
The canonical mapping key to get the dataObject. By default
the baseFolder class uses a :py:class:`regexpDict` to store objects in.
Keyword Arguments:
instantiate (bool):
If True (default) then always return a metadataObject. If False, the __getter__ method may return a
key that can be used by it later to actually get the metadataObject. If None, then will return
whatever is held in the object cache, either instance
or name.
Returns:
(metadataObject):
The metadataObject
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
name = self.__lookup__(name)
if instantiate is None:
return self.objects[name]
if not instantiate:
return name
name = self.objects[name]
if not isinstance(name, self._type):
raise KeyError(f"{name} is not a valid {self._type}")
return self._update_from_object_attrs(name)
def __setter__(self, name, value, force_insert=False):
"""Stub to setting routine to store a metadataObject.
Parameters:
name (string)
the named object to write - may be an existing or new name
value (metadataObject):
the value to store.
Keyword Parameters:
force_insert (bool):
Ensures the new item is always inserted as a new item and does not replace and existing one.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
if name is None:
name = self.make_name()
if force_insert:
self.objects.update({name: value})
else:
self.objects[name] = value
def __inserter__(self, ix, name, value):
"""Insert the element into a specific place in our data folder.
Parameters:
ix (int):
the index value to insert at, must be 0 to len(self)-1
name (str):
the string name to add as a key
value (self.type):
the value to be inserted.
Note:
This is written in a way to be generic, but might be better implemented if storage is customised.
"""
names = list(self.__names__())
values = [self.__getter__(n, instantiate=None) for n in names]
names.insert(ix, name)
values.insert(ix, value)
self.__clear__()
for n, v in zip(names, values):
self.__setter__(n, v)
def __deleter__(self, ix):
"""Delete an object from the baseFolder.
Parameters:
ix(str):
Index to delete, should be within +- the lengthe length of the folder.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
del self.objects[ix]
def __clear__(self):
"""Clear all stored :py:class:`Stoner.Core.metadataObject` instances stored.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
for n in self.__names__():
self.__deleter__(self.__lookup__(n))
def __clone__(self, other=None, attrs_only=False):
"""Do whatever is necessary to copy attributes from self to other.
Note:
We're in the base class here, so we don't call super() if we can't handle this, then we're stuffed!
"""
if other is None and not attrs_only:
return deepcopy(self)
if other is None:
other = type(self)()
for arg in self.defaults:
if hasattr(self, arg):
setattr(other, arg, getattr(self, arg))
other.key = self.key
other.args = self.args
other.kargs = self.kargs
other.type = self.type
other.debug = self.debug
for k in self.kargs:
if not hasattr(other, k):
setattr(other, k, self.kargs[k])
for k in self._instance_attrs:
setattr(other, k, getattr(self, k))
if not attrs_only:
for g in self.groups:
other.groups[g] = self.groups[g].__clone__(other=type(other)(), attrs_only=attrs_only)
for k in self.__names__():
other.__setter__(k, self.__getter__(k, instantiate=None))
return other
###########################################################################
######## Methods to implement the MutableMapping abstract methods #########
######## And to provide a mapping interface that mainly access groups #####
def __getitem__(self, name):
"""Try to get either a group or an object.
Parameters:
name(str, int,slice):
Which objects to return from the folder.
Returns:
Either a baseFolder instance or a metadataObject instance or raises KeyError
How the indexing works depends on the data type of the parameter *name*:
- str, regexp
Then it is checked first against the groups and then against the objects
dictionaries - both will fall back to a regular expression if necessary.
- int
Then the _index attribute is used to find a matching object key.
- slice
Then a new :py:class:`baseFolder` is constructed by cloning he current one, but without
any groups or files. The new :py:class:`baseFolder` is populated with entries
from the current folder according tot he usual slice definition. This has the advantage
of not loading the objects in the folder into memory if a :py:class:`DiskBasedFolderMixin` is
used.
"""
if name in self.groups and not isinstance(name, int_types):
return self.groups[name]
if isinstance(name, string_types + regexp_type):
if name in self.objects:
name = self.__lookup__(name)
return self.__getter__(name)
name = self.__lookup__(name)
return self.__getter__(name)
if isinstance(name, int_types):
if -len(self) < name < len(self):
return self.__getter__(self.__lookup__(name), instantiate=True)
raise IndexError(f"{name} is out of range.")
if isinstance(name, slice): # Possibly ought to return another Folder?
other = self.__clone__(attrs_only=True)
for iname in islice(self.__names__(), name.start, name.stop, name.step):
item = self.__getter__(iname)
if hasattr(item, "filename"):
item.filename = iname
other.append(item)
return other
if isinstance(name, tuple): # recurse indexing through tree with a tuple
item = self[name[0]]
if len(name) > 2:
name = tuple(name[1:])
elif len(name) == 1:
return item
else:
name = name[1]
if isinstance(item, self._type):
return item[name]
if isinstance(item, type(self)):
if all_type(name, (int_types, slice)): # Looks like we're accessing data arrays
test = (len(item),) + item[0].data[name].shape
output = np.array([]).view(item[0].data.__class__)
for data in item:
append = data[name]
if not isinstance(append, np.ndarray):
append = append.asarray()
output = np.append(output, append)
output = output.reshape(test)
return output
try:
return item[name]
except KeyError:
if name in item.metadata.common_keys:
return item.metadata.slice(name, output="Data")
if self.debug:
print(name)
raise
raise KeyError(f"Can't index the baseFolder with {name}")
raise KeyError(f"Can't index the baseFolder with {name}")
def __setitem__(self, name, value):
"""Attempt to store a value in either the groups or objects.
Parameters:
name(str or int):
If the name is a string and the value is a baseFolder, then assumes we're accessing
a group. if name is an integer, then it must be a metadataObject.
value (baseFolder,metadataObject,str):
The value to be storred.
"""
if isinstance(name, string_types):
if isinstance(value, baseFolder):
self.groups[name] = value
else:
self.__setter__(self.__lookup__(name), value)
elif isinstance(name, int_types):
if -len(self) < name < len(self):
self.__setter__(self.__lookup__(name), value)
else:
raise IndexError(f"{name} is out of range")
else:
raise KeyError(f"{name} is not a valid key for baseFolder")
def __delitem__(self, name):
"""Attempt to delete an item from either a group or list of files.
Parameters:
name(str,int):
IF name is a string, then it is checked first against the groups and then
against the objects. If name is an int then it s checked against the _index.
"""
if isinstance(name, string_types):
if name in self.groups:
del self.groups[name]
elif name in self.objects:
self.__deleter__(self.__lookup__(name))
else:
raise KeyError(f"Can't use {name} as a key to delete in baseFolder. ({self.__names__()})")
elif isinstance(name, int_types):
if -len(self) < name <= len(self):
self.__deleter__(self.__lookup__(name))
else:
raise IndexError(f"{name} is out of range.")
elif isinstance(name, slice):
indices = name.indices(len(self))
name = range(*indices)
for ix in sorted(name, reverse=True):
del self[ix]
else:
raise KeyError(f"Can't use {name} as a key to delete in baseFolder. ({repr(self.__names__())})")
def __contains__(self, name):
"""Check whether name is in a list of groups or in the list of names."""
return name in self.groups or name in self.__names__()
def __len__(self):
"""Allow len(:py:class:`baseFolder`) works as expected."""
return len(self.__names__())
###########################################################################
###################### Standard Special Methods ###########################
def __add__(self, other):
"""Implement the addition operator for baseFolder and metadataObjects."""
result = deepcopy(self)
result = _add_core_(result, other)
return result
def __iadd__(self, other):
"""Implement the addition operator for baseFolder and metadataObjects."""
result = self
result = _add_core_(result, other)
return result
def __truediv__(self, other):
"""Implement the divide operator as a grouping function for a :py:class:`baseFolder`."""
result = deepcopy(self)
return _div_core_(result, other)
def __itruediv__(self, other):
"""Implement the divide operator as an in-place a grouping function for a :py:class:`baseFolder`."""
result = self
return _div_core_(result, other)
def __eq__(self, other):
"""Test whether two objectFolders are the same."""
if not isinstance(other, baseFolder):
return False
if other.shape != self.shape:
return False
for mine, theirs in zip(self.groups, other.groups):
if mine != theirs:
return False
if self.groups[mine] != other.groups[theirs]:
return False
for mine, theirs in zip(sorted(self.ls), sorted(other.ls)):
if self[mine] != other[theirs]:
return False
return True
def __invert__(self):
"""For a :py:class:`naseFolder`, inverting means either flattening or unflattening the folder.
If we have no sub-groups then we assume we are unflattening the Folder and that the object names have
embedded path separators.
If we have sub-groups then we assume that we need to flatten the data..
"""
result = deepcopy(self)
if len(result.groups) == 0:
result.unflatten()
else:
result.flatten()
return result
def __iter__(self):
"""Iterate over objects."""
return self.__next__()
def __next__(self):
"""Python 3.x style iterator function."""
for n in self.__names__():
member = self.__getter__(n, instantiate=True)
if member is None:
continue
yield member
def __rmatmul__(self, other):
"""Implement callable@DataFolder as a generic iterate a function over DataFolder members.
Returns:
An object that supports __call__ and knows about this DataFolder.
"""
if not callable(other):
return NotImplemented
return self.each.__rmatmul__(other) # Just bounce it onto the each object
def __sub__(self, other):
"""Implement the addition operator for baseFolder and metadataObjects."""
result = deepcopy(self)
result = _sub_core_(result, other)
return result
def __isub__(self, other):
"""Implement the addition operator for baseFolder and metadataObjects."""
result = self
result = _sub_core_(result, other)
return result
def __deepcopy__(self, memo):
"""Provide support for copy.deepcopy to work."""
cls = type(self)
result = cls.__new__(cls)
memo[id(self)] = result
for k, v in self.__dict__.items():
try:
setattr(result, k, deepcopy(v, memo))
except (TypeError, ValueError, RecursionError):
try:
setattr(result, k, copy(v))
except (TypeError, ValueError, RecursionError):
setattr(result, k, v) # Fallback to just assign the original value if no copy possible
return result
def __repr__(self):
"""Print a summary of the objectFolder structure.
Returns:
A string representation of the current objectFolder object
"""
short = get_option("short_folder_rrepr")
cls = type(self).__name__
pth = self.key
pattern = getattr(self, "pattern", "")
string = f"{cls}({pth}) with pattern {pattern} has {len(self)} files and {len(self.groups)} groups\n"
if not short:
for row in self.ls:
string += "\t" + row + "\n"
for g in self.groups: # iterate over groups
r = self.groups[g].__repr__()
for line in r.split("\n"): # indent each line by one tab
string += "\t" + line + "\n"
return string.strip()
def __reversed__(self):
"""Create an iterator function that runs backwards through the stored objects."""
for n in reversed(self.__names__()):
member = self.__getter__(n, instantiate=True)
if member is None:
continue
yield member
def __delattr__(self, name):
"""Handle removing an attribute from the folder, including proxied attributes."""
if name.startswith("_") or name in [
"debug",
"groups",
"args",
"kargs",
"objects",
"key",
]: # pass ddirectly through for private attributes
raise AttributeError(f"{name} is a protected attribute and may not be deleted!")
super().__delattr__(name)
###########################################################################
###################### Private Methods ####################################
def __init_from_other(self, other):
other.__clone__(other=self)
def _marshall(self, layout=None, data=None):
"""Return the baseFolder as a list of the members including the groups.
Keyword Arguments:
layout (tuple):
number of entries and a dictionary of the groups as generated by :py:property:`baseFolder.layout`
data (list):
list of entries to be marshalled if *layout* is defined.
Returns:
(list or self):