This repository has been archived by the owner on Oct 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
interface.py
6893 lines (5724 loc) · 385 KB
/
interface.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
#!/usr/bin/env python
# BSD 3-Clause License; see https://github.com/scikit-hep/aghast/blob/master/LICENSE
import collections
import ctypes
import functools
import math
import numbers
import operator
import os
import struct
import sys
try:
from collections.abc import Iterable
except ImportError:
from collections import Iterable
import numpy
import flatbuffers
import aghast.aghast_generated.MetadataLanguage
import aghast.aghast_generated.Metadata
import aghast.aghast_generated.DecorationLanguage
import aghast.aghast_generated.Decoration
import aghast.aghast_generated.DType
import aghast.aghast_generated.Endianness
import aghast.aghast_generated.DimensionOrder
import aghast.aghast_generated.Filter
import aghast.aghast_generated.Slice
import aghast.aghast_generated.ExternalSource
import aghast.aghast_generated.RawInlineBuffer
import aghast.aghast_generated.RawExternalBuffer
import aghast.aghast_generated.InterpretedInlineBuffer
import aghast.aghast_generated.InterpretedInlineInt64Buffer
import aghast.aghast_generated.InterpretedInlineFloat64Buffer
import aghast.aghast_generated.InterpretedExternalBuffer
import aghast.aghast_generated.RawBuffer
import aghast.aghast_generated.InterpretedBuffer
import aghast.aghast_generated.StatisticFilter
import aghast.aghast_generated.Moments
import aghast.aghast_generated.Extremes
import aghast.aghast_generated.Quantiles
import aghast.aghast_generated.Modes
import aghast.aghast_generated.Statistics
import aghast.aghast_generated.Covariance
import aghast.aghast_generated.BinLocation
import aghast.aghast_generated.IntegerBinning
import aghast.aghast_generated.RealInterval
import aghast.aghast_generated.NonRealMapping
import aghast.aghast_generated.RealOverflow
import aghast.aghast_generated.RegularBinning
import aghast.aghast_generated.HexagonalCoordinates
import aghast.aghast_generated.HexagonalBinning
import aghast.aghast_generated.EdgesBinning
import aghast.aghast_generated.OverlappingFillStrategy
import aghast.aghast_generated.IrregularBinning
import aghast.aghast_generated.CategoryBinning
import aghast.aghast_generated.SparseRegularBinning
import aghast.aghast_generated.FractionLayout
import aghast.aghast_generated.FractionErrorMethod
import aghast.aghast_generated.FractionBinning
import aghast.aghast_generated.PredicateBinning
import aghast.aghast_generated.Assignment
import aghast.aghast_generated.Variation
import aghast.aghast_generated.SystematicUnits
import aghast.aghast_generated.VariationBinning
import aghast.aghast_generated.Binning
import aghast.aghast_generated.Axis
import aghast.aghast_generated.Profile
import aghast.aghast_generated.UnweightedCounts
import aghast.aghast_generated.WeightedCounts
import aghast.aghast_generated.Counts
import aghast.aghast_generated.Parameter
import aghast.aghast_generated.ParameterizedFunction
import aghast.aghast_generated.EvaluatedFunction
import aghast.aghast_generated.FunctionData
import aghast.aghast_generated.Function
import aghast.aghast_generated.BinnedEvaluatedFunction
import aghast.aghast_generated.FunctionObjectData
import aghast.aghast_generated.FunctionObject
import aghast.aghast_generated.Histogram
import aghast.aghast_generated.Page
import aghast.aghast_generated.ColumnChunk
import aghast.aghast_generated.Chunk
import aghast.aghast_generated.Column
import aghast.aghast_generated.NtupleInstance
import aghast.aghast_generated.Ntuple
import aghast.aghast_generated.ObjectData
import aghast.aghast_generated.Object
import aghast.aghast_generated.Collection
import aghast.checktype
MININT64 = -9223372036854775808
MAXINT64 = 9223372036854775807
def _sameedges(one, two):
assert isinstance(one, numpy.ndarray) and isinstance(two, numpy.ndarray)
if len(one) != len(two):
return False
if len(one) == 1:
return one[0] - two[0] < 1e-6
gap = min((one[1:] - one[:-1]).min(), (two[1:] - two[:-1]).min())
if gap <= 0:
return False
return (numpy.absolute(one - two) / gap < 1e-6).all()
def _name2fb(name):
return "".join(x.capitalize() for x in name.split("_"))
def typedproperty(check):
@property
def prop(self):
private = "_" + check.paramname
if not hasattr(self, private):
assert hasattr(self, "_flatbuffers"), "not derived from a flatbuffer or not properly initialized"
fbname = _name2fb(check.paramname)
fbnamelen = fbname + "Length"
fbnamelookup = fbname + "Lookup"
fbnametag = fbname + "ByTag"
if hasattr(self._flatbuffers, fbnametag):
value = getattr(self._flatbuffers, fbnametag)()
aghast.checktype.setparent(self, value)
elif hasattr(self._flatbuffers, fbnamelookup):
value = aghast.checktype.FBLookup(getattr(self._flatbuffers, fbnamelen)(), getattr(self._flatbuffers, fbnamelookup), getattr(self._flatbuffers, fbname), check, self)
elif hasattr(self._flatbuffers, fbnamelen):
value = aghast.checktype.FBVector(getattr(self._flatbuffers, fbnamelen)(), getattr(self._flatbuffers, fbname), check, self)
else:
value = check.fromflatbuffers(getattr(self._flatbuffers, fbname)())
aghast.checktype.setparent(self, value)
setattr(self, private, value)
return getattr(self, private)
@prop.setter
def prop(self, value):
value = check(value)
aghast.checktype.setparent(self, value)
setattr(self, "_" + check.paramname, value)
return prop
def _valid(obj, seen, recursive):
if obj is None:
pass
elif isinstance(obj, Ghast):
if id(obj) in seen:
raise ValueError("hierarchy is recursively nested")
seen.add(id(obj))
obj._validtypes()
obj._valid(seen, recursive)
elif isinstance(obj, aghast.checktype.Vector):
for x in obj:
_valid(x, seen, recursive)
elif isinstance(obj, aghast.checktype.Lookup):
for x in obj.values():
_valid(x, seen, recursive)
else:
raise AssertionError(type(obj))
def _getbykey(self, field, where):
lookup = "_lookup_" + field
if not hasattr(self, lookup):
values = getattr(self, field)
if isinstance(values, aghast.checktype.Vector):
setattr(self, lookup, {x.identifier: x for x in values})
if len(getattr(self, lookup)) != len(values):
raise ValueError("{0}.{1} keys must be unique".format(type(self).__name__, field))
elif isinstance(values, aghast.checktype.Lookup):
setattr(self, lookup, values)
else:
raise AssertionError(type(values))
return getattr(self, lookup)[where]
class _MockFlatbuffers(object):
class _ByTag(object):
__slots__ = ["getdata", "gettype", "lookup"]
def __init__(self, getdata, gettype, lookup):
self.getdata = getdata
self.gettype = gettype
self.lookup = lookup
def __call__(self):
data = self.getdata()
try:
interface, deserializer = self.lookup[self.gettype()]
except KeyError:
return None
fb = deserializer()
fb.Init(data.Bytes, data.Pos)
return interface._fromflatbuffers(fb)
class _LocIndexer(object):
def __init__(self, obj, isiloc):
self.obj = obj
self._isiloc = isiloc
def __getitem__(self, where):
if not isinstance(where, tuple):
where = (where,)
node = self.obj
binnings = ()
while hasattr(node, "_parent"):
node = node._parent
binnings = tuple(x.binning for x in node.axis) + binnings
return self.obj._getloc(self._isiloc, where, binnings)
################################################# Ghast
class Ghast(object):
def __repr__(self):
if "identifier" in self._params:
identifier = " " + repr(self.identifier)
elif hasattr(self, "_identifier"):
identifier = " " + repr(self._identifier)
else:
identifier = ""
return "<{0}{1} at 0x{2:012x}>".format(type(self).__name__, identifier, id(self))
def _shape(self, path, shape):
for x in path:
if self is x:
raise ValueError("hierarchy is recursively nested")
path = (self,) + path
if hasattr(self, "_parent"):
return self._parent._shape(path, shape)
elif shape == ():
return (1,)
else:
return shape
def _validtypes(self):
for n, x in self._params.items():
x(getattr(self, n))
def _valid(self, seen, recursive):
pass
def checkvalid(self, recursive=True):
self._valid(set(), recursive)
@property
def isvalid(self):
try:
self.checkvalid()
except ValueError:
return False
else:
return True
def detached(self, reclaim=False, exceptions=()):
if reclaim:
if hasattr(self, "_parent"):
del self._parent
return self
else:
return self._detached(True, exceptions=exceptions)
def _detached(self, top, exceptions=()):
if not top and not hasattr(self, "_parent"):
return self
else:
out = type(self).__new__(type(self))
if hasattr(self, "_flatbuffers"):
out._flatbuffers = self._flatbuffers
for n in self._params:
if n not in exceptions:
private = "_" + n
if hasattr(self, private):
x = getattr(self, private)
if isinstance(x, (Ghast, aghast.checktype.Vector, aghast.checktype.Lookup)):
x = x._detached(False)
aghast.checktype.setparent(out, x)
setattr(out, private, x)
return out
@classmethod
def _fromflatbuffers(cls, fb):
out = cls.__new__(cls)
out._flatbuffers = fb
return out
def _toflatbuffers(self, builder):
raise NotImplementedError("missing _toflatbuffers implementation in {0}".format(type(self)))
def dump(self, indent="", width=100, end="\n", file=sys.stdout, flush=False):
file.write(self._dump(indent, width, end))
file.write(end)
if flush:
file.flush()
def __eq__(self, other):
if self is other:
return True
if getattr(self, "_flatbuffers", None) is not None and self._flatbuffers is getattr(other, "_flatbuffers", None):
return True
if type(self) is not type(other):
return False
for n in self._params:
selfn = getattr(self, n)
othern = getattr(other, n)
if selfn is None or isinstance(selfn, (Ghast, Enum)):
if selfn != othern:
return False
elif isinstance(selfn, numpy.ndarray) and isinstance(othern, numpy.ndarray):
if not (selfn.shape == othern.shape and (selfn == othern).all()):
return False
elif isinstance(selfn, aghast.checktype.Lookup):
assert isinstance(othern, aghast.checktype.Lookup)
if not set(selfn) == set(othern):
return False
for x in selfn:
if selfn[x] != othern[x]:
return False
else:
try:
if len(selfn) != len(othern):
return False
except TypeError:
if selfn != othern:
return False
else:
for x, y in zip(selfn, othern):
if x != y:
return False
else:
return True
def __ne__(self, other):
return not self.__eq__(other)
################################################# Enum
class Enum(object):
def __init__(self, name, value):
self.name = name
self.value = value
def __repr__(self):
return self.base + "." + self.name
def __str__(self):
return self.base + "." + self.name
def __hash__(self):
return hash(self.name)
def __eq__(self, other):
return self is other or (isinstance(other, type(self)) and self.value == other.value)
def __ne__(self, other):
return not self.__eq__(other)
################################################# Object
class Object(Ghast):
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
def __add__(self, other):
pairs, triples = Collection._pairs_triples(getattr(self, "_parent", None), getattr(other, "_parent", None))
out = self.detached()
out._add(other, pairs, triples, noclobber=True)
return out
def __iadd__(self, other):
pairs, triples = Collection._pairs_triples(getattr(self, "_parent", None), getattr(other, "_parent", None))
self._add(other, pairs, triples, noclobber=False)
return self
@property
def loc(self):
return _LocIndexer(self, False)
@property
def iloc(self):
return _LocIndexer(self, True)
@classmethod
def _fromflatbuffers(cls, fb):
interface, deserializer = _ObjectData_lookup[fb.DataType()]
data = fb.Data()
fb2 = deserializer()
fb2.Init(data.Bytes, data.Pos)
return interface._fromflatbuffers(fb, fb2)
def __getstate__(self):
return self.tobuffer()
def __setstate__(self, state):
out = Object._fromflatbuffers(aghast.aghast_generated.Object.Object.GetRootAsObject(state, 0))
self._flatbuffers = out._flatbuffers
def tobuffer(self):
self.checkvalid()
builder = flatbuffers.Builder(1024)
builder.Finish(self._toflatbuffers(builder))
return builder.Output()
def toarray(self):
return numpy.frombuffer(self.tobuffer(), dtype=numpy.uint8)
def tofile(self, file):
self.checkvalid()
opened = False
if not hasattr(file, "write"):
file = open(file, "wb")
opened = True
if not hasattr(file, "tell"):
class FileLike(object):
def __init__(self, file):
self.file = file
self.offset = 0
def write(self, data):
self.file.write(data)
self.offset += len(data)
def close(self):
try:
self.file.close()
except:
pass
def tell(self):
return self.offset
file = FileLike(file)
try:
file.write(b"gast")
builder = flatbuffers.Builder(1024)
builder.Finish(self._toflatbuffers(builder))
offset = file.tell()
file.write(builder.Output())
file.write(struct.pack("<Q", offset))
file.write(b"gast")
finally:
if opened:
file.close()
def frombuffer(buffer, checkvalid=False, offset=0):
out = Object._fromflatbuffers(aghast.aghast_generated.Object.Object.GetRootAsObject(buffer, offset))
if checkvalid:
out.checkvalid()
return out
def fromarray(array, checkvalid=False):
return frombuffer(array, checkvalid=checkvalid)
def fromfile(file, mode="r+", checkvalid=False):
if isinstance(file, str):
file = numpy.memmap(file, dtype=numpy.uint8, mode=mode)
if file[:4].tostring() != b"gast":
raise OSError("file does not begin with magic 'gast'")
if file[-4:].tostring() != b"gast":
raise OSError("file does not end with magic 'gast'")
offset, = struct.unpack("<Q", file[-12:-4])
return frombuffer(file[offset:-12], checkvalid=checkvalid)
def _dumpstring(obj):
if obj.count("\n") > 0:
return "''" + repr(obj).replace("\\n", end) + "''"
else:
return repr(obj)
def _dumpline(obj, args, indent, width, end):
preamble = type(obj).__name__ + "("
linear = ", ".join(args)
if len(indent) + len(preamble) + len(linear) + 1 > width:
return preamble + ",".join(end + indent + " " + x for x in args) + ")"
else:
return preamble + linear + ")"
def _dumplist(objs, indent, width, end):
out = ("," + end + indent + " ").join(objs)
if len(objs) > 0 or objs[0].counts("\n") > 0:
return out + end + indent + " "
return out
def _dumpeq(data, indent, end):
if data.count(end) > 0:
return end + indent + " " + data
else:
return data
def _dumparray(obj, indent, end):
asarray = str(obj)
if asarray.count("\n") > 0:
return end + indent + " " + asarray.replace("\n", end + indent + " ")
else:
return "[" + " ".join("%g" % x for x in obj) + "]"
################################################# Metadata
class MetadataLanguageEnum(Enum):
base = "Metadata"
class Metadata(Ghast):
unspecified = MetadataLanguageEnum("unspecified", aghast.aghast_generated.MetadataLanguage.MetadataLanguage.meta_unspecified)
json = MetadataLanguageEnum("json", aghast.aghast_generated.MetadataLanguage.MetadataLanguage.meta_json)
language = [unspecified, json]
_params = {
"data": aghast.checktype.CheckString("Metadata", "data", required=True),
"language": aghast.checktype.CheckEnum("Metadata", "language", required=True, choices=language),
}
data = typedproperty(_params["data"])
language = typedproperty(_params["language"])
description = "Optional container for applications to attach metadata to histograms, functions, ntuples, and collections."
validity_rules = ()
long_description = """
Anything that an application needs to track that is not or won't be encoded in aghast structures may be attached as metadata. The *data* are expressed as a string in some *language*, such as JSON.
Graphical properties of plots are not encoded in aghast, but they may use <<Decoration>> for graphics-specific metadata.
"""
def __init__(self, data, language=unspecified):
self.data = data
self.language = language
def _toflatbuffers(self, builder):
data = builder.CreateString(self.data.encode("utf-8"))
aghast.aghast_generated.Metadata.MetadataStart(builder)
aghast.aghast_generated.Metadata.MetadataAddData(builder, data)
if self.language != self.unspecified:
aghast.aghast_generated.Metadata.MetadataAddLanguage(builder, self.language.value)
return aghast.aghast_generated.Metadata.MetadataEnd(builder)
def _dump(self, indent, width, end):
args = ["data={0}".format(_dumpstring(self.data))]
if self.language != self.unspecified:
args.append("language={0}".format(repr(self.language)))
return _dumpline(self, args, indent, width, end)
################################################# Decoration
class DecorationLanguageEnum(Enum):
base = "Decoration"
class Decoration(Ghast):
unspecified = DecorationLanguageEnum("unspecified", aghast.aghast_generated.DecorationLanguage.DecorationLanguage.deco_unspecified)
css = DecorationLanguageEnum("css", aghast.aghast_generated.DecorationLanguage.DecorationLanguage.deco_css)
vega = DecorationLanguageEnum("vega", aghast.aghast_generated.DecorationLanguage.DecorationLanguage.deco_vega)
json = DecorationLanguageEnum("json", aghast.aghast_generated.DecorationLanguage.DecorationLanguage.deco_json)
language = [unspecified, css, vega, json]
_params = {
"data": aghast.checktype.CheckString("Decoration", "data", required=True),
"language": aghast.checktype.CheckEnum("Decoration", "language", required=True, choices=language),
}
data = typedproperty(_params["data"])
language = typedproperty(_params["language"])
description = "Optional container for applications to attach graphical properties to histograms, functions, ntuples, and collections."
validity_rules = ()
long_description = """
The aghast specification does not encode any graphical properties, such as colors or arrangements of a plot. However, an application may want to save or communicate these properties. The <<Decoration>> class is intended to hold this information.
The *data* are expressed as a string in some *language*, such as CSS, Vega, or JSON format.
"""
def __init__(self, data, language=unspecified):
self.data = data
self.language = language
def _toflatbuffers(self, builder):
data = builder.CreateString(self.data.encode("utf-8"))
aghast.aghast_generated.Decoration.DecorationStart(builder)
aghast.aghast_generated.Decoration.DecorationAddData(builder, data)
if self.language != self.unspecified:
aghast.aghast_generated.Decoration.DecorationAddLanguage(builder, self.language.value)
return aghast.aghast_generated.Decoration.DecorationEnd(builder)
def _dump(self, indent, width, end):
args = ["data={0}".format(_dumpstring(self.data))]
if self.language != self.unspecified:
args.append("language={0}".format(repr(self.language)))
return _dumpline(self, args, indent, width, end)
################################################# Buffers
class BufferFilterEnum(Enum):
base = "Buffer"
class Buffer(Ghast):
none = BufferFilterEnum("none", aghast.aghast_generated.Filter.Filter.filter_none)
gzip = BufferFilterEnum("gzip", aghast.aghast_generated.Filter.Filter.filter_gzip)
lzma = BufferFilterEnum("lzma", aghast.aghast_generated.Filter.Filter.filter_lzma)
lz4 = BufferFilterEnum("lz4", aghast.aghast_generated.Filter.Filter.filter_lz4)
filters = [none, gzip, lzma, lz4]
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
class InlineBuffer(object):
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
class ExternalSourceEnum(Enum):
base = "ExternalBuffer"
class ExternalBuffer(object):
memory = ExternalSourceEnum("memory", aghast.aghast_generated.ExternalSource.ExternalSource.external_memory)
samefile = ExternalSourceEnum("samefile", aghast.aghast_generated.ExternalSource.ExternalSource.external_samefile)
file = ExternalSourceEnum("file", aghast.aghast_generated.ExternalSource.ExternalSource.external_file)
url = ExternalSourceEnum("url", aghast.aghast_generated.ExternalSource.ExternalSource.external_url)
sources = [memory, samefile, file, url]
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
class RawBuffer(object):
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
class DTypeEnum(Enum):
base = "Interpretation"
def __init__(self, name, value, dtype):
super(DTypeEnum, self).__init__(name, value)
self.dtype = dtype
class EndiannessEnum(Enum):
base = "Interpretation"
def __init__(self, name, value, endianness):
super(EndiannessEnum, self).__init__(name, value)
self.endianness = endianness
class Interpretation(object):
none = DTypeEnum("none", aghast.aghast_generated.DType.DType.dtype_none, numpy.dtype(numpy.uint8))
bool = DTypeEnum("bool", aghast.aghast_generated.DType.DType.dtype_bool, numpy.dtype(numpy.bool_))
int8 = DTypeEnum("int8", aghast.aghast_generated.DType.DType.dtype_int8, numpy.dtype(numpy.int8))
uint8 = DTypeEnum("uint8", aghast.aghast_generated.DType.DType.dtype_uint8, numpy.dtype(numpy.uint8))
int16 = DTypeEnum("int16", aghast.aghast_generated.DType.DType.dtype_int16, numpy.dtype(numpy.int16))
uint16 = DTypeEnum("uint16", aghast.aghast_generated.DType.DType.dtype_uint16, numpy.dtype(numpy.uint16))
int32 = DTypeEnum("int32", aghast.aghast_generated.DType.DType.dtype_int32, numpy.dtype(numpy.int32))
uint32 = DTypeEnum("uint32", aghast.aghast_generated.DType.DType.dtype_uint32, numpy.dtype(numpy.uint32))
int64 = DTypeEnum("int64", aghast.aghast_generated.DType.DType.dtype_int64, numpy.dtype(numpy.int64))
uint64 = DTypeEnum("uint64", aghast.aghast_generated.DType.DType.dtype_uint64, numpy.dtype(numpy.uint64))
float32 = DTypeEnum("float32", aghast.aghast_generated.DType.DType.dtype_float32, numpy.dtype(numpy.float32))
float64 = DTypeEnum("float64", aghast.aghast_generated.DType.DType.dtype_float64, numpy.dtype(numpy.float64))
dtypes = [none, bool, int8, uint8, int16, uint16, int32, uint32, int64, uint64, float32, float64]
little_endian = EndiannessEnum("little_endian", aghast.aghast_generated.Endianness.Endianness.little_endian, "<")
big_endian = EndiannessEnum("big_endian", aghast.aghast_generated.Endianness.Endianness.big_endian, ">")
endiannesses = [little_endian, big_endian]
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
@property
def numpy_dtype(self):
return self.dtype.dtype.newbyteorder(self.endianness.endianness)
@classmethod
def from_numpy_dtype(cls, dtype):
dtype = numpy.dtype(dtype)
if dtype.byteorder == "=":
endianness = cls.little_endian if sys.byteorder == "little" else cls.big_endian
elif dtype.byteorder == ">":
endianness = cls.big_endian
elif dtype.byteorder == "<" or dtype.byteorder == "|":
endianness = cls.little_endian
if dtype.kind == "b":
return cls.bool, endianness
elif dtype.kind == "i":
if dtype.itemsize == 1:
return cls.int8, endianness
elif dtype.itemsize == 2:
return cls.int16, endianness
elif dtype.itemsize == 4:
return cls.int32, endianness
elif dtype.itemsize == 8:
return cls.int64, endianness
elif dtype.kind == "u":
if dtype.itemsize == 1:
return cls.uint8, endianness
elif dtype.itemsize == 2:
return cls.uint16, endianness
elif dtype.itemsize == 4:
return cls.uint32, endianness
elif dtype.itemsize == 8:
return cls.uint64, endianness
elif dtype.kind == "f":
if dtype.itemsize == 4:
return cls.float32, endianness
elif dtype.itemsize == 8:
return cls.float64, endianness
raise ValueError("numpy dtype {0} does not correspond to any Interpretation dtype, endianness pair".format(str(dtype)))
class DimensionOrderEnum(Enum):
base = "InterpretedBuffer"
def __init__(self, name, value, dimension_order):
super(DimensionOrderEnum, self).__init__(name, value)
self.dimension_order = dimension_order
class InterpretedBuffer(Interpretation):
c_order = DimensionOrderEnum("c_order", aghast.aghast_generated.DimensionOrder.DimensionOrder.c_order, "C")
fortran_order = DimensionOrderEnum("fortran", aghast.aghast_generated.DimensionOrder.DimensionOrder.fortran_order, "F")
orders = [c_order, fortran_order]
def __init__(self):
raise TypeError("{0} is an abstract base class; do not construct".format(type(self).__name__))
def _reindex(self, oldshape, indexes):
order = "c" if self.dimension_order == self.c_order else "f"
dtype = self.numpy_dtype
buf = self.flatarray.reshape(oldshape, order=order)
for i, index in list(enumerate(indexes))[::-1]:
if index is None:
buf = buf.sum(axis=i)
if not isinstance(index, (bool, numpy.bool, numpy.bool_)) and isinstance(index, (numbers.Integral, numpy.integer)):
buf = buf[(slice(None),)*i + (index,)]
indexes = [x for x in indexes if isinstance(x, (numpy.ndarray, slice))]
for i, index in enumerate(indexes):
if isinstance(index, numpy.ndarray) and issubclass(index.dtype.type, (numpy.bool, numpy.bool_)):
buf = numpy.compress(index, buf, axis=i)
elif isinstance(index, numpy.ndarray) and issubclass(index.dtype.type, numpy.integer):
if os.name == "nt": # Windows Numpy take requires 32-bit indexes
index = index.astype(numpy.int32)
buf = numpy.take(buf, index, axis=i)
else:
buf = buf[(slice(None),)*i + (index,)]
return buf
def _rebin(self, oldshape, pairs):
order = "c" if self.dimension_order == self.c_order else "f"
dtype = self.numpy_dtype
buf = self.flatarray.reshape(oldshape, order=order)
original = buf
i = len(oldshape)
newshape = ()
for binning, selfmap in pairs[::-1]:
assert isinstance(selfmap, tuple)
i -= len(selfmap)
if binning is None:
buf = buf.sum(axis=i)
else:
newshape = binning._binshape() + newshape
newbuf = numpy.zeros(oldshape[:i] + newshape, dtype=dtype, order=order)
for j in range(len(selfmap)):
if isinstance(selfmap[j], numpy.ndarray):
clear = (selfmap[j] < 0)
if clear.any():
if buf is original:
buf = buf.copy()
buf[(Ellipsis, clear) + (slice(None),)*(len(selfmap) - j - 1)] = 0
selfmap[j][clear] = 0
numpy.add.at(newbuf, i*(slice(None),) + selfmap, buf)
buf = newbuf
if len(buf.shape) == 0:
buf = buf.reshape(1)
if self.dtype == InterpretedBuffer.int64 and self.endianness == InterpretedBuffer.little_endian and self.dimension_order == self.dimension_order == InterpretedBuffer.c_order:
return InterpretedInlineInt64Buffer(buf.view(numpy.uint8))
elif self.dtype == InterpretedBuffer.float64 and self.endianness == InterpretedBuffer.little_endian and self.dimension_order == self.dimension_order == InterpretedBuffer.c_order:
return InterpretedInlineFloat64Buffer(buf.view(numpy.uint8))
else:
return InterpretedInlineBuffer(buf.view(numpy.uint8),
filters=None,
postfilter_slice=None,
dtype=self.dtype,
endianness=self.endianness,
dimension_order=self.dimension_order)
def _remap(self, newshape, selfmap):
order = "c" if self.dimension_order == self.c_order else "f"
dtype = self.numpy_dtype
buf = self.flatarray
oldshape = tuple(len(sm) if sm is not None else ns for ns, sm in zip(newshape, selfmap))
for i in range(len(newshape) - 1, -1, -1):
if selfmap[i] is not None:
newbuf = numpy.zeros(oldshape[:i] + newshape[i:], dtype=dtype, order=order)
newbuf[i*(slice(None),) + (selfmap[i],)] = buf.reshape((-1, len(selfmap[i])) + newshape[i + 1 :], order=order)
buf = newbuf
if self.dtype == InterpretedBuffer.int64 and self.endianness == InterpretedBuffer.little_endian and self.dimension_order == self.dimension_order == InterpretedBuffer.c_order:
return InterpretedInlineInt64Buffer(buf.view(numpy.uint8))
elif self.dtype == InterpretedBuffer.float64 and self.endianness == InterpretedBuffer.little_endian and self.dimension_order == self.dimension_order == InterpretedBuffer.c_order:
return InterpretedInlineFloat64Buffer(buf.view(numpy.uint8))
else:
return InterpretedInlineBuffer(buf.view(numpy.uint8),
filters=None,
postfilter_slice=None,
dtype=self.dtype,
endianness=self.endianness,
dimension_order=self.dimension_order)
def _dontclobber(self, other):
return self.dtype != other.dtype or self.endianness != other.endianness or self.dimension_order != other.dimension_order
def _add(self, other, noclobber, op=numpy.add):
if noclobber:
out = op(self.flatarray, other.flatarray) # FIXME: what if they have different dimension_orders?
dtype, endianness = self.from_numpy_dtype(out.dtype)
if (dtype == InterpretedInlineFloat64Buffer.dtype.fget(None) and
endianness == InterpretedInlineFloat64Buffer.endianness.fget(None) and
self.dimension_order == InterpretedInlineFloat64Buffer.dimension_order.fget(None) and
other.dimension_order == InterpretedInlineFloat64Buffer.dimension_order.fget(None)):
return InterpretedInlineFloat64Buffer(out.view(numpy.uint8))
elif (dtype == InterpretedInlineInt64Buffer.dtype.fget(None) and
endianness == InterpretedInlineInt64Buffer.endianness.fget(None) and
self.dimension_order == InterpretedInlineInt64Buffer.dimension_order.fget(None) and
other.dimension_order == InterpretedInlineInt64Buffer.dimension_order.fget(None)):
return InterpretedInlineInt64Buffer(out.view(numpy.uint8))
elif isinstance(self, InterpretedInlineBuffer) or isinstance(other, InterpretedInlineBuffer):
return InterpretedInlineBuffer(out.view(numpy.uint8),
filters=None,
postfilter_slice=None,
dtype=dtype,
endianness=endianness,
dimension_order=self.fortran_order if numpy.isfortran(out) else self.c_order)
else:
raise AssertionError((type(self), type(other)))
else:
array = self.flatarray
op(array, other.flatarray, out=array)
return self
################################################# RawInlineBuffer
class RawInlineBuffer(Buffer, RawBuffer, InlineBuffer):
_params = {
"buffer": aghast.checktype.CheckBuffer("RawInlineBuffer", "buffer", required=True),
}
buffer = typedproperty(_params["buffer"])
description = "A generic, uninterpreted array in the Flatbuffers hierarchy; used for small buffers, like <<Ntuple>> pages, that are interpreted centrally, as in an <<Ntuple>> column."
validity_rules = ()
long_description = """
This array class does not provide its own interpretation in terms of data type and dimension order. The interpretation must be provided elsewhere, such as in an ntuple's <<Column>>. This is to avoid repeating (and possibly introduce conflicting) interpretation metadata for many buffers whose type is identical but are stored in pages for performance reasons.
The *buffer* is the actual data, encoded in Flatbuffers as an array of bytes with known length.
"""
def __init__(self, buffer):
self.buffer = buffer
@property
def numbytes(self):
return len(self.buffer)
@property
def array(self):
return numpy.frombuffer(self.buffer, dtype=InterpretedBuffer.none.dtype)
@classmethod
def _fromflatbuffers(cls, fb):
out = cls.__new__(cls)
out._flatbuffers = _MockFlatbuffers()
out._flatbuffers.Buffer = fb.BufferAsNumpy
return out
def _toflatbuffers(self, builder):
aghast.aghast_generated.RawInlineBuffer.RawInlineBufferStartBufferVector(builder, len(self.buffer))
builder.head = builder.head - len(self.buffer)
builder.Bytes[builder.head : builder.head + len(self.buffer)] = self.buffer.tostring()
buffer = builder.EndVector(len(self.buffer))
aghast.aghast_generated.RawInlineBuffer.RawInlineBufferStart(builder)
aghast.aghast_generated.RawInlineBuffer.RawInlineBufferAddBuffer(builder, buffer)
return aghast.aghast_generated.RawInlineBuffer.RawInlineBufferEnd(builder)
def _dump(self, indent, width, end):
args = ["buffer={0}".format(_dumparray(self.flatarray, indent + " ", end))]
return _dumpline(self, args, indent, width, end)
################################################# RawExternalBuffer
class RawExternalBuffer(Buffer, RawBuffer, ExternalBuffer):
_params = {
"pointer": aghast.checktype.CheckInteger("RawExternalBuffer", "pointer", required=True, min=0),
"numbytes": aghast.checktype.CheckInteger("RawExternalBuffer", "numbytes", required=True, min=0),
"external_source": aghast.checktype.CheckEnum("RawExternalBuffer", "external_source", required=False, choices=ExternalBuffer.sources),
}
pointer = typedproperty(_params["pointer"])
numbytes = typedproperty(_params["numbytes"])
external_source = typedproperty(_params["external_source"])
description = "A generic, uninterpreted array stored outside the Flatbuffers hierarchy; used for small buffers, like <<Ntuple>> pages, that are interpreted centrally, as in an <<Ntuple>> column."
validity_rules = ()
long_description = """
This array class is like <<RawInlineBuffer>>, but its contents are outside of the Flatbuffers hierarchy. Instead of a *buffer* property, it has a *pointer* and a *numbytes* to specify the source of bytes.
If the *external_source* is `memory`, then the *pointer* and *numbytes* are interpreted as a raw array in memory. If the *external_source* is `samefile`, then the *pointer* is taken to be a seek position in the same file that stores the Flatbuffer (assuming the Flatbuffer resides in a file). If *external_source* is `file`, then the *location* property is taken to be a file path, and the *pointer* is taken to be a seek position in that file. If *external_source* is `url`, then the *location* property is taken to be a URL and the bytes are requested by HTTP.
"""
def __init__(self, pointer, numbytes, external_source=ExternalBuffer.memory):
self.pointer = pointer
self.numbytes = numbytes
self.external_source = external_source
@property
def array(self):
return numpy.ctypeslib.as_array(ctypes.cast(self.pointer, ctypes.POINTER(ctypes.c_uint8)), shape=(self.numbytes,))
def _toflatbuffers(self, builder):
aghast.aghast_generated.RawExternalBuffer.RawExternalBufferStart(builder)
aghast.aghast_generated.RawExternalBuffer.RawExternalBufferAddPointer(builder, self.pointer)
aghast.aghast_generated.RawExternalBuffer.RawExternalBufferAddNumbytes(builder, self.numbytes)
if self.external_source != ExternalBuffer.memory:
aghast.aghast_generated.RawExternalBuffer.RawExternalBufferAddExternalSource(builder, self.external_source.value)
return aghast.aghast_generated.RawExternalBuffer.RawExternalBufferEnd(builder)
def _dump(self, indent, width, end):
args = ["pointer={0}".format(repr(self.pointer)), "numbytes={0}".format(repr(self.numbytes))]
if self.external_source != ExternalBuffer.memory:
args.append("external_source={0}".format(repr(self.external_source)))
return _dumpline(self, args, indent, width, end)
################################################# InterpretedInlineBuffer
class InterpretedInlineBuffer(Buffer, InterpretedBuffer, InlineBuffer):
_params = {
"buffer": aghast.checktype.CheckBuffer("InterpretedInlineBuffer", "buffer", required=True),
"filters": aghast.checktype.CheckVector("InterpretedInlineBuffer", "filters", required=False, type=Buffer.filters),
"postfilter_slice": aghast.checktype.CheckSlice("InterpretedInlineBuffer", "postfilter_slice", required=False),
"dtype": aghast.checktype.CheckEnum("InterpretedInlineBuffer", "dtype", required=False, choices=InterpretedBuffer.dtypes),
"endianness": aghast.checktype.CheckEnum("InterpretedInlineBuffer", "endianness", required=False, choices=InterpretedBuffer.endiannesses),
"dimension_order": aghast.checktype.CheckEnum("InterpretedInlineBuffer", "dimension_order", required=False, choices=InterpretedBuffer.orders),
}
buffer = typedproperty(_params["buffer"])
filters = typedproperty(_params["filters"])
postfilter_slice = typedproperty(_params["postfilter_slice"])
dtype = typedproperty(_params["dtype"])
endianness = typedproperty(_params["endianness"])
dimension_order = typedproperty(_params["dimension_order"])
description = "A generic array in the Flatbuffers hierarchy; used for any quantity that can have different values in different <<Histogram>> or <<BinnedEvaluatedFunction>> bins."
validity_rules = ("The *postfilter_slice*'s *step* cannot be zero.",
"The number of items in the *buffer* must be equal to the number of bins at this level of the hierarchy.")
long_description = """
This array class provides its own interpretation in terms of data type and dimension order. It does not specify its own shape, the number of bins in each dimension, because that is given by its position in the hierarchy. If it is the <<UnweightedCounts>> of a <<Histogram>>, for instance, it must be reshapable to fit the number of bins implied by the <<Histogram>> *axis*.
The *buffer* is the actual data, encoded in Flatbuffers as an array of bytes with known length.
The list of *filters* are applied to convert bytes in the *buffer* into an array. Typically, *filters* are compression algorithms such as `gzip`, `lzma`, and `lz4`, but they may be any predefined transformation (e.g. zigzag deencoding of integers or affine mappings from integers to floating point numbers may be added in the future). If there is more than one filter, the output of each step is provided as input to the next.
The *postfilter_slice*, if provided, selects a subset of the bytes returned by the last filter (or directly in the *buffer* if there are no *filters*). A slice has the following structure:
struct Slice {
start: long;
stop: long;
step: int;
has_start: bool;
has_stop: bool;
has_step: bool;
}
though in Python, a builtin `slice` object should be provided to this class's constructor. The *postfilter_slice* is interpreted according to Python's rules (negative indexes, start-inclusive and stop-exclusive, clipping-not-errors if beyond the range, etc.).
The *dtype* is the numeric type of the array, which includes `bool`, all signed and unsigned integers from 8 bits to 64 bits, and IEEE 754 floating point types with 32 or 64 bits. The `none` interpretation is presumed, if necessary, to be unsigned, 8 bit integers.
The *endianness* may be `little_endian` or `big_endian`; the former is used by most recent architectures.
The *dimension_order* may be `c_order` to follow the C programming language's convention or `fortran` to follow the FORTRAN programming language's convention. The *dimension_order* only has an effect when shaping an array with more than one dimension.
"""
def __init__(self, buffer, filters=None, postfilter_slice=None, dtype=InterpretedBuffer.none, endianness=InterpretedBuffer.little_endian, dimension_order=InterpretedBuffer.c_order):
self.buffer = buffer
self.filters = filters
self.postfilter_slice = postfilter_slice
self.dtype = dtype