-
Notifications
You must be signed in to change notification settings - Fork 69
/
identify.py
2136 lines (1942 loc) · 80.2 KB
/
identify.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
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE
"""
This module defines a series of rules for identifying Python objects that can be written
to ROOT files and preparing them for writing.
The :doc:`uproot.writing.identify.add_to_directory` function is the most general in that
it recognizes data that could be converted into a TTree or into a normal object. It also
adds the data to a :doc:`uproot.writing.writable.WritableDirectory`.
The :doc:`uproot.writing.identify.to_writable` function recognizes all static objects
(everything but TTrees) as a series of rules, returning a :doc:`uproot.model.Model`
but not adding it to any :doc:`uproot.writing.writable.WritableDirectory`.
The (many) other functions in this module construct writable :doc:`uproot.model.Model`
objects from Python builtins and other writable models.
"""
from __future__ import annotations
from collections.abc import Mapping
import numpy
import uproot.compression
import uproot.extras
import uproot.pyroot
import uproot.writing._cascadetree
def add_to_directory(obj, name, directory, streamers):
"""
Args:
obj: Object to attempt to recognize as something that can be written to a
ROOT file.
name (str or None): Name to assign to the writable object.
directory (:doc:`uproot.writing.writable.WritableDirectory`): Directory to
add the object to, if successful.
streamers (list of :doc:`uproot.streamers.Model_TStreamerInfo`, :doc:`uproot.writable._cascade.RawStreamerInfo`, or constructor arguments for the latter): Collects
streamers to add to the output file so that all objects in it can be read
in any version of ROOT.
This function performs two tasks: it attempts to recognize ``obj`` as a writable
object and, if successful, writes it to a ``directory``.
It can recognize dynamic TTrees and static objects such as histograms. For only
static objects, without the additional concern of writing the resulting object
in a ``directory``, see :doc:`uproot.writing.identify.to_writable`.
Raises ``TypeError`` if ``obj`` is not recognized as writable data.
"""
is_ttree = False
if uproot._util.from_module(obj, "pandas"):
import pandas
if isinstance(
obj, pandas.DataFrame
) and uproot._util.pandas_has_attr_is_numeric(pandas)(obj.index):
obj = uproot.writing._cascadetree.dataframe_to_dict(obj)
if uproot._util.from_module(obj, "awkward"):
import awkward
if isinstance(obj, awkward.Array):
obj = {"": obj}
if isinstance(obj, numpy.ndarray) and obj.dtype.fields is not None:
obj = uproot.writing._cascadetree.recarray_to_dict(obj)
if isinstance(obj, Mapping) and all(isinstance(x, str) for x in obj):
data = {}
metadata = {}
for branch_name, branch_array in obj.items():
if uproot._util.from_module(branch_array, "pandas"):
import pandas
if isinstance(branch_array, pandas.DataFrame):
branch_array = uproot.writing._cascadetree.dataframe_to_dict( # noqa: PLW2901 (overwriting branch_array)
branch_array
)
if (
isinstance(branch_array, numpy.ndarray)
and branch_array.dtype.fields is not None
):
branch_array = uproot.writing._cascadetree.recarray_to_dict( # noqa: PLW2901 (overwriting branch_array)
branch_array
)
if isinstance(branch_array, Mapping) and all(
isinstance(x, str) for x in branch_array
):
datum = {}
metadatum = {}
for kk, vv in branch_array.items():
try:
vv = ( # noqa: PLW2901 (overwriting vv)
uproot._util.ensure_numpy(vv)
)
except TypeError:
raise TypeError(
f"unrecognizable array type {type(branch_array)} associated with {branch_name!r}"
) from None
datum[kk] = vv
branch_dtype = vv.dtype
branch_shape = vv.shape[1:]
if branch_shape != ():
branch_dtype = numpy.dtype((branch_dtype, branch_shape))
metadatum[kk] = branch_dtype
data[branch_name] = datum
metadata[branch_name] = metadatum
else:
if uproot._util.from_module(branch_array, "awkward"):
data[branch_name] = branch_array
metadata[branch_name] = branch_array.type
else:
try:
branch_array = uproot._util.ensure_numpy( # noqa: PLW2901 (overwriting branch_array)
branch_array
)
except TypeError:
awkward = uproot.extras.awkward()
try:
branch_array = awkward.from_iter( # noqa: PLW2901 (overwriting branch_array)
branch_array
)
except Exception:
raise TypeError(
f"unrecognizable array type {type(branch_array)} associated with {branch_name!r}"
) from None
else:
data[branch_name] = branch_array
metadata[branch_name] = awkward.type(branch_array)
else:
data[branch_name] = branch_array
branch_dtype = branch_array.dtype
branch_shape = branch_array.shape[1:]
if branch_shape != ():
branch_dtype = numpy.dtype((branch_dtype, branch_shape))
metadata[branch_name] = branch_dtype
else:
is_ttree = True
if is_ttree:
tree = directory.mktree(name, metadata)
tree.extend(data)
else:
writable = to_writable(obj)
for rawstreamer in writable.class_rawstreamers:
if isinstance(rawstreamer, tuple):
streamers.append(uproot.writing._cascade.RawStreamerInfo(*rawstreamer))
else:
streamers.append(rawstreamer)
uncompressed_data = writable.serialize(name=name)
compressed_data = uproot.compression.compress(
uncompressed_data, directory.file.compression
)
if hasattr(writable, "fTitle"):
title = writable.fTitle
elif writable.has_member("fTitle"):
title = writable.member("fTitle")
else:
title = ""
directory._cascading.add_object(
directory.file.sink,
writable.classname,
name,
title,
compressed_data,
len(uncompressed_data),
)
def to_writable(obj):
"""
Converts arbitrary Python object ``obj`` to a writable :doc:`uproot.model.Model`
if possible; raises ``TypeError`` otherwise.
This function is a series of rules that defines what Python data can or cannot be
written to ROOT files. For instance, a 2-tuple of NumPy arrays with the appropriate
dimensions is recognized as a histogram, since NumPy's ``np.histogram`` function
produces such objects.
This series of rules is expected to grow with time.
"""
# This is turns histogramdd-style into histogram2d-style.
if (
isinstance(obj, (tuple, list))
and 2 <= len(obj) <= 3 # might have a histogram title as the last item
and isinstance(obj[0], numpy.ndarray)
and isinstance(obj[1], (tuple, list))
and 2 <= len(obj[1]) <= 3 # 2D or 3D
and isinstance(obj[1][0], numpy.ndarray)
and isinstance(obj[1][1], numpy.ndarray)
and (len(obj[1]) == 2 or isinstance(obj[1][2], numpy.ndarray))
and all(len(x.shape) == 1 for x in obj[1])
and len(obj[0].shape) == len(obj[1])
):
obj = (obj[0], *tuple(obj[1]), *tuple(obj[2:]))
# This is the big if-elif-else chain of rules
if isinstance(obj, uproot.model.Model):
return obj.to_writable()
elif type(obj).__module__ == "cppyy.gbl":
import ROOT
if isinstance(obj, ROOT.TObject):
return uproot.pyroot._PyROOTWritable(obj)
else:
raise TypeError(
f"only instances of TObject can be written to files, not {type(obj).__name__}"
)
elif isinstance(obj, str):
return to_TObjString(obj)
elif (
hasattr(obj, "axes")
and hasattr(obj, "kind")
and hasattr(obj, "values")
and hasattr(obj, "variances")
and hasattr(obj, "counts")
):
# boost_histogram is used in _fXbins_maybe_regular *if* this is such a type
boost_histogram = None
if (
type(obj).__module__ == "boost_histogram"
or type(obj).__module__.startswith("boost_histogram.")
or type(obj).__module__ == "hist"
or type(obj).__module__.startswith("hist.")
):
import boost_histogram
if obj.kind != "COUNT" and obj.kind != "MEAN":
raise ValueError(
"PlottableHistogram can only be converted to ROOT TH* if kind='COUNT' or 'MEAN'"
)
ndim = len(obj.axes)
if not 1 <= ndim <= 3:
raise ValueError(
"PlottableHistogram can only be converted to ROOT TH* if it has between 1 and 3 axes (TH1, TH2, TH3)"
)
title = getattr(obj, "title", getattr(obj, "name", ""))
if title is None:
title = ""
try:
# using flow=True if supported
data = obj.values(flow=True)
fSumw2 = (
obj.variances(flow=True)
if boost_histogram is None
or obj.storage_type == boost_histogram.storage.Weight
else None
)
# and flow=True is different from flow=False (obj actually has flow bins)
data_noflow = obj.values(flow=False)
for flow, noflow in zip(data.shape, data_noflow.shape):
if flow != noflow + 2:
raise TypeError
except TypeError:
# flow=True is not supported, fallback to allocate-and-fill
tmp = obj.values()
s = tmp.shape
d = tmp.dtype.newbyteorder(">")
if ndim == 1:
data = numpy.zeros(s[0] + 2, dtype=d)
data[1:-1] = tmp
elif ndim == 2:
data = numpy.zeros((s[0] + 2, s[1] + 2), dtype=d)
data[1:-1, 1:-1] = tmp
elif ndim == 3:
data = numpy.zeros((s[0] + 2, s[1] + 2, s[2] + 2), dtype=d)
data[1:-1, 1:-1, 1:-1] = tmp
tmp = (
obj.variances()
if boost_histogram is None
or obj.storage_type == boost_histogram.storage.Weight
else None
)
fSumw2 = None
if tmp is not None:
s = tmp.shape
if ndim == 1:
fSumw2 = numpy.zeros(s[0] + 2, dtype=">f8")
fSumw2[1:-1] = tmp
elif ndim == 2:
fSumw2 = numpy.zeros((s[0] + 2, s[1] + 2), dtype=">f8")
fSumw2[1:-1, 1:-1] = tmp
elif ndim == 3:
fSumw2 = numpy.zeros((s[0] + 2, s[1] + 2, s[2] + 2), dtype=">f8")
fSumw2[1:-1, 1:-1, 1:-1] = tmp
else:
# continuing to use flow=True, because it is supported
data = data.astype(data.dtype.newbyteorder(">"))
if fSumw2 is not None:
fSumw2 = fSumw2.astype(">f8")
# we're assuming the PlottableHistogram ensures data.shape == weights.shape
if fSumw2 is not None:
assert data.shape == fSumw2.shape
# data are stored in transposed order for 2D and 3D
data = data.T.reshape(-1)
if fSumw2 is not None:
fSumw2 = fSumw2.T.reshape(-1)
# ROOT has fEntries = sum *without* weights, *with* flow bins
fEntries = data.sum()
# convert all axes in one list comprehension
axes = [
to_TAxis(
fName=default_name,
fTitle=getattr(axis, "label", getattr(obj, "name", "")),
fNbins=len(axis),
fXmin=axis.edges[0],
fXmax=axis.edges[-1],
fXbins=_fXbins_maybe_regular(axis, boost_histogram),
fLabels=_fLabels_maybe_categorical(axis, boost_histogram),
)
for axis, default_name in zip(obj.axes, ["xaxis", "yaxis", "zaxis"])
]
# make TH1, TH2, TH3 types independently
if len(axes) == 1:
if obj.kind == "MEAN":
if hasattr(obj, "storage_type"):
if "fSumw2" in obj.metadata.keys():
fSumw2 = obj.metadata["fSumw2"]
else:
raise ValueError(f"fSumw2 has not been set for {obj}")
return to_TProfile(
fName=None,
fTitle=title,
data=obj.values(flow=True),
fEntries=obj.size + 1,
fTsumw=obj.sum()["sum_of_weights"],
fTsumw2=obj.sum()["sum_of_weights_squared"],
fTsumwx=0,
fTsumwx2=0,
fTsumwy=0,
fTsumwy2=0,
fSumw2=fSumw2,
fBinEntries=obj.counts(flow=True),
fBinSumw2=numpy.asarray([], numpy.float64),
fXaxis=axes[0],
)
else:
return to_TProfile(
fName=None,
fTitle=title,
data=obj._bases[0]._bases[-1],
fEntries=obj.member("fEntries"),
fTsumw=obj.member("fTsumw"),
fTsumw2=obj.member("fTsumw2"),
fTsumwx=obj.member("fTsumwx"),
fTsumwx2=obj.member("fTsumwx2"),
fTsumwy=obj.member("fTsumwy"),
fTsumwy2=obj.member("fTsumwy2"),
fSumw2=obj.member("fSumw2"),
fBinEntries=obj.member("fBinEntries"),
fBinSumw2=obj.member("fBinSumw2"),
fXaxis=axes[0],
)
else:
fTsumw, fTsumw2, fTsumwx, fTsumwx2 = _root_stats_1d(
obj.values(flow=False), obj.axes[0].edges
)
return to_TH1x(
fName=None,
fTitle=title,
data=data,
fEntries=fEntries,
fTsumw=fTsumw,
fTsumw2=fTsumw2,
fTsumwx=fTsumwx,
fTsumwx2=fTsumwx2,
fSumw2=fSumw2,
fXaxis=axes[0],
)
elif len(axes) == 2:
if obj.kind == "MEAN":
raise NotImplementedError(
"2D PlottableHistogram with kind='MEAN' (i.e. 2D profile plots) not supported yet"
)
else:
(
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
) = _root_stats_2d(
obj.values(flow=False), obj.axes[0].edges, obj.axes[1].edges
)
return to_TH2x(
fName=None,
fTitle=title,
data=data,
fEntries=fEntries,
fTsumw=fTsumw,
fTsumw2=fTsumw2,
fTsumwx=fTsumwx,
fTsumwx2=fTsumwx2,
fTsumwy=fTsumwy,
fTsumwy2=fTsumwy2,
fTsumwxy=fTsumwxy,
fSumw2=fSumw2,
fXaxis=axes[0],
fYaxis=axes[1],
)
elif len(axes) == 3:
if obj.kind == "MEAN":
raise NotImplementedError(
"3D PlottableHistogram with kind='MEAN' (i.e. 3D profile plots) not supported yet"
)
else:
(
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fTsumwxz,
fTsumwyz,
) = _root_stats_3d(
obj.values(flow=False),
obj.axes[0].edges,
obj.axes[1].edges,
obj.axes[2].edges,
)
return to_TH3x(
fName=None,
fTitle=title,
data=data,
fEntries=fEntries,
fTsumw=fTsumw,
fTsumw2=fTsumw2,
fTsumwx=fTsumwx,
fTsumwx2=fTsumwx2,
fTsumwy=fTsumwy,
fTsumwy2=fTsumwy2,
fTsumwxy=fTsumwxy,
fTsumwz=fTsumwz,
fTsumwz2=fTsumwz2,
fTsumwxz=fTsumwxz,
fTsumwyz=fTsumwyz,
fSumw2=fSumw2,
fXaxis=axes[0],
fYaxis=axes[1],
fZaxis=axes[2],
)
elif (
isinstance(obj, (tuple, list))
and 2 <= len(obj) <= 5 # might have a histogram title as the last item
and all(isinstance(x, numpy.ndarray) for x in obj[:-1])
and isinstance(obj[-1], (numpy.ndarray, str))
and len(obj[0].shape) == sum(int(isinstance(x, numpy.ndarray)) for x in obj[1:])
and all(len(x.shape) == 1 for x in obj[1:] if isinstance(x, numpy.ndarray))
):
if isinstance(obj[-1], str):
obj, title = obj[:-1], obj[-1]
else:
title = ""
if len(obj) == 2:
(entries, edges) = obj
with_flow = numpy.empty(len(entries) + 2, dtype=">f8")
with_flow[1:-1] = entries
with_flow[0] = 0
with_flow[-1] = 0
fEntries = entries.sum()
fTsumw, fTsumw2, fTsumwx, fTsumwx2 = _root_stats_1d(entries, edges)
fNbins = len(edges) - 1
fXmin, fXmax = edges[0], edges[-1]
if numpy.allclose(
edges, numpy.linspace(fXmin, fXmax, len(edges), edges.dtype)
):
edges = numpy.array([], dtype=">f8")
else:
edges = edges.astype(">f8")
return to_TH1x(
fName=None,
fTitle=title,
data=with_flow,
fEntries=fEntries,
fTsumw=fTsumw,
fTsumw2=fTsumw2,
fTsumwx=fTsumwx,
fTsumwx2=fTsumwx2,
fSumw2=None,
fXaxis=to_TAxis(
fName="xaxis",
fTitle="",
fNbins=fNbins,
fXmin=fXmin,
fXmax=fXmax,
fXbins=edges,
),
)
elif len(obj) == 3:
(entries, xedges, yedges) = obj
fEntries = entries.sum()
(
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
) = _root_stats_2d(entries, xedges, yedges)
with_flow = numpy.zeros(
(entries.shape[0] + 2, entries.shape[1] + 2), dtype=">f8"
)
with_flow[1:-1, 1:-1] = entries
with_flow = with_flow.T.reshape(-1)
fXaxis_fNbins = len(xedges) - 1
fXmin, fXmax = xedges[0], xedges[-1]
if numpy.allclose(
xedges, numpy.linspace(fXmin, fXmax, len(xedges), xedges.dtype)
):
xedges = numpy.array([], dtype=">f8")
else:
xedges = xedges.astype(">f8")
fYaxis_fNbins = len(yedges) - 1
fYmin, fYmax = yedges[0], yedges[-1]
if numpy.allclose(
yedges, numpy.linspace(fYmin, fYmax, len(yedges), yedges.dtype)
):
yedges = numpy.array([], dtype=">f8")
else:
yedges = yedges.astype(">f8")
return to_TH2x(
fName=None,
fTitle=title,
data=with_flow,
fEntries=fEntries,
fTsumw=fTsumw,
fTsumw2=fTsumw2,
fTsumwx=fTsumwx,
fTsumwx2=fTsumwx2,
fTsumwy=fTsumwy,
fTsumwy2=fTsumwy2,
fTsumwxy=fTsumwxy,
fSumw2=None,
fXaxis=to_TAxis(
fName="xaxis",
fTitle="",
fNbins=fXaxis_fNbins,
fXmin=fXmin,
fXmax=fXmax,
fXbins=xedges,
),
fYaxis=to_TAxis(
fName="yaxis",
fTitle="",
fNbins=fYaxis_fNbins,
fXmin=fYmin,
fXmax=fYmax,
fXbins=yedges,
),
)
elif len(obj) == 4:
(entries, xedges, yedges, zedges) = obj
fEntries = entries.sum()
(
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fTsumwxz,
fTsumwyz,
) = _root_stats_3d(entries, xedges, yedges, zedges)
with_flow = numpy.zeros(
(entries.shape[0] + 2, entries.shape[1] + 2, entries.shape[2] + 2),
dtype=">f8",
)
with_flow[1:-1, 1:-1, 1:-1] = entries
with_flow = with_flow.T.reshape(-1)
fXaxis_fNbins = len(xedges) - 1
fXmin, fXmax = xedges[0], xedges[-1]
if numpy.allclose(
xedges, numpy.linspace(fXmin, fXmax, len(xedges), xedges.dtype)
):
xedges = numpy.array([], dtype=">f8")
else:
xedges = xedges.astype(">f8")
fYaxis_fNbins = len(yedges) - 1
fYmin, fYmax = yedges[0], yedges[-1]
if numpy.allclose(
yedges, numpy.linspace(fYmin, fYmax, len(yedges), yedges.dtype)
):
yedges = numpy.array([], dtype=">f8")
else:
yedges = yedges.astype(">f8")
fZaxis_fNbins = len(zedges) - 1
fZmin, fZmax = zedges[0], zedges[-1]
if numpy.allclose(
zedges, numpy.linspace(fZmin, fZmax, len(zedges), zedges.dtype)
):
zedges = numpy.array([], dtype=">f8")
else:
zedges = zedges.astype(">f8")
return to_TH3x(
fName=None,
fTitle=title,
data=with_flow,
fEntries=fEntries,
fTsumw=fTsumw,
fTsumw2=fTsumw2,
fTsumwx=fTsumwx,
fTsumwx2=fTsumwx2,
fTsumwy=fTsumwy,
fTsumwy2=fTsumwy2,
fTsumwxy=fTsumwxy,
fTsumwz=fTsumwz,
fTsumwz2=fTsumwz2,
fTsumwxz=fTsumwxz,
fTsumwyz=fTsumwyz,
fSumw2=None,
fXaxis=to_TAxis(
fName="xaxis",
fTitle="",
fNbins=fXaxis_fNbins,
fXmin=fXmin,
fXmax=fXmax,
fXbins=xedges,
),
fYaxis=to_TAxis(
fName="yaxis",
fTitle="",
fNbins=fYaxis_fNbins,
fXmin=fYmin,
fXmax=fYmax,
fXbins=yedges,
),
fZaxis=to_TAxis(
fName="zaxis",
fTitle="",
fNbins=fZaxis_fNbins,
fXmin=fZmin,
fXmax=fZmax,
fXbins=zedges,
),
)
else:
raise TypeError(
"unrecognized type cannot be written to a ROOT file: " + type(obj).__name__
)
def _fXbins_maybe_regular(axis, boost_histogram):
if boost_histogram is None:
edges = axis.edges
fXmin, fXmax = edges[0], edges[-1]
if numpy.allclose(edges, numpy.linspace(fXmin, fXmax, len(edges), edges.dtype)):
return numpy.array([], dtype=">f8")
else:
return edges.astype(">f8")
else:
if (
isinstance(axis, boost_histogram.axis.Regular)
and getattr(axis, "transform", None) is None
):
return numpy.array([], dtype=">f8")
else:
return axis.edges
def _fLabels_maybe_categorical(axis, boost_histogram):
if boost_histogram is None:
return None
if not isinstance(
axis, (boost_histogram.axis.IntCategory, boost_histogram.axis.StrCategory)
):
return None
labels = [str(label) for label in axis]
if isinstance(axis, boost_histogram.axis.IntCategory):
# Check labels are valid integers (this may be redundant)
for label in labels:
try:
int(label)
except ValueError:
raise ValueError(
f"IntCategory labels must be valid integers. Found {label!r} on axis {axis!r}"
) from None
labels = to_THashList([to_TObjString(label) for label in labels])
# we need to set the TObject.fUniqueID to the index of the bin as done by TAxis::SetBinLabel
for i, label in enumerate(labels):
label._bases[0]._members["@fUniqueID"] = i + 1
return labels
def _root_stats_1d(entries, edges):
centers = (edges[:-1] + edges[1:]) / 2.0
fTsumw = fTsumw2 = entries.sum()
fTsumwx = (entries * centers).sum()
fTsumwx2 = (entries * centers**2).sum()
return fTsumw, fTsumw2, fTsumwx, fTsumwx2
def _root_stats_2d(entries, xedges, yedges):
xcenters = (xedges[:-1] + xedges[1:]) / 2.0
ycenters = (yedges[:-1] + yedges[1:]) / 2.0
fTsumw = fTsumw2 = entries.sum()
fTsumwx = (entries.T * xcenters).sum()
fTsumwx2 = (entries.T * xcenters**2).sum()
fTsumwy = (entries * ycenters).sum()
fTsumwy2 = (entries * ycenters**2).sum()
fTsumwxy = ((entries * ycenters).T * xcenters).sum()
return fTsumw, fTsumw2, fTsumwx, fTsumwx2, fTsumwy, fTsumwy2, fTsumwxy
def _root_stats_3d(entries, xedges, yedges, zedges):
xcenters = (xedges[:-1] + xedges[1:]) / 2.0
ycenters = (yedges[:-1] + yedges[1:]) / 2.0
zcenters = (zedges[:-1] + zedges[1:]) / 2.0
fTsumw = fTsumw2 = entries.sum()
fTsumwx = (numpy.transpose(entries, (1, 2, 0)) * xcenters).sum()
fTsumwx2 = (numpy.transpose(entries, (1, 2, 0)) * xcenters**2).sum()
fTsumwy = (numpy.transpose(entries, (2, 0, 1)) * ycenters).sum()
fTsumwy2 = (numpy.transpose(entries, (2, 0, 1)) * ycenters**2).sum()
fTsumwz = (entries * zcenters).sum()
fTsumwz2 = (entries * zcenters**2).sum()
fTsumwxy = (
numpy.transpose(numpy.transpose(entries, (2, 0, 1)) * ycenters, (2, 0, 1))
* xcenters
).sum()
fTsumwxz = (numpy.transpose(entries * zcenters, (1, 2, 0)) * xcenters).sum()
fTsumwyz = (numpy.transpose(entries * zcenters, (2, 0, 1)) * ycenters).sum()
return (
fTsumw,
fTsumw2,
fTsumwx,
fTsumwx2,
fTsumwy,
fTsumwy2,
fTsumwxy,
fTsumwz,
fTsumwz2,
fTsumwxz,
fTsumwyz,
)
def to_TString(string):
"""
This function is for developers to create TString objects that can be
written to ROOT files, to implement conversion routines.
"""
tstring = uproot.models.TString.Model_TString(str(string))
tstring._deeply_writable = True
tstring._cursor = None
tstring._file = None
tstring._parent = None
tstring._members = {}
tstring._bases = []
tstring._num_bytes = None
tstring._instance_version = None
return tstring
def to_TObjString(string):
"""
This function is for developers to create TObjString objects that can be
written to ROOT files, to implement conversion routines.
"""
tobject = uproot.models.TObject.Model_TObject.empty()
tobjstring = uproot.models.TObjString.Model_TObjString(str(string))
tobjstring._deeply_writable = True
tobjstring._cursor = None
tobjstring._parent = None
tobjstring._members = {}
tobjstring._bases = (tobject,)
tobjstring._num_bytes = len(string) + (1 if len(string) < 255 else 5) + 16
tobjstring._instance_version = 1
return tobjstring
def to_TList(data, name=""):
"""
Args:
data (:doc:`uproot.model.Model`): Python iterable to convert into a TList.
name (str): Name of the list (usually empty: ``""``).
This function is for developers to create TList objects that can be
written to ROOT files, to implement conversion routines.
"""
if not all(isinstance(x, uproot.model.Model) for x in data):
raise TypeError(
"list to convert to TList must only contain ROOT objects (uproot.Model)"
)
tobject = uproot.models.TObject.Model_TObject.empty()
tlist = uproot.models.TList.Model_TList.empty()
tlist._bases.append(tobject)
tlist._members["fName"] = name
tlist._data = list(data)
tlist._members["fSize"] = len(tlist._data)
tlist._options = [b""] * len(tlist._data)
if all(x._deeply_writable for x in tlist._data):
tlist._deeply_writable = True
return tlist
def to_THashList(data, name=""):
"""
Args:
data (:doc:`uproot.model.Model`): Python iterable to convert into a THashList.
name (str): Name of the list (usually empty: ``""``).
This function is for developers to create THashList objects that can be
written to ROOT files, to implement conversion routines.
"""
if not all(isinstance(x, uproot.model.Model) for x in data):
raise TypeError(
"list to convert to THashList must only contain ROOT objects (uproot.Model)"
)
tlist = to_TList(data, name)
thashlist = uproot.models.THashList.Model_THashList.empty()
thashlist._bases.append(tlist)
return thashlist
def to_TArray(data):
"""
Args:
data (numpy.ndarray): The array to convert to big-endian and wrap as
TArrayC, TArrayS, TArrayI, TArrayL, TArrayF, or TArrayD, depending
on its dtype.
This function is for developers to create TArray objects that can be
written to ROOT files, to implement conversion routines.
"""
if data.ndim != 1:
raise ValueError("data to convert to TArray must be one-dimensional")
if issubclass(data.dtype.type, numpy.int8):
cls = uproot.models.TArray.Model_TArrayC
elif issubclass(data.dtype.type, numpy.int16):
cls = uproot.models.TArray.Model_TArrayS
elif issubclass(data.dtype.type, numpy.int32):
cls = uproot.models.TArray.Model_TArrayI
elif issubclass(data.dtype.type, numpy.int64):
cls = uproot.models.TArray.Model_TArrayL
elif issubclass(data.dtype.type, numpy.float32):
cls = uproot.models.TArray.Model_TArrayF
elif issubclass(data.dtype.type, numpy.float64):
cls = uproot.models.TArray.Model_TArrayD
else:
raise ValueError(
f"data to convert to TArray must have signed integer or floating-point type, not {data.dtype!r}"
)
tarray = cls.empty()
tarray._deeply_writable = True
tarray._members["fN"] = len(data)
tarray._data = data.astype(data.dtype.newbyteorder(">"))
return tarray
def to_TAxis(
fName,
fTitle,
fNbins,
fXmin,
fXmax,
fXbins=None,
fFirst=0,
fLast=0,
fBits2=0,
fTimeDisplay=False,
fTimeFormat="",
fLabels=None,
fModLabs=None,
fNdivisions=510,
fAxisColor=1,
fLabelColor=1,
fLabelFont=42,
fLabelOffset=0.005,
fLabelSize=0.035,
fTickLength=0.03,
fTitleOffset=1.0,
fTitleSize=0.035,
fTitleColor=1,
fTitleFont=42,
):
"""
Args:
fName (str): Internal name of axis, usually ``"xaxis"``, ``"yaxis"``, ``"zaxis"``.
fTitle (str): Internal title of axis, usually empty: ``""``.
fNbins (int): Number of bins. (https://root.cern.ch/doc/master/classTAxis.html)
fXmin (float): Low edge of first bin.
fXmax (float): Upper edge of last bin.
fXbins (None or numpy.ndarray of numpy.float64 or :doc:`uproot.models.TArray.Model_TArrayD`): Bin
edges array in X. None generates an empty array.
fFirst (int): First bin to display. 1 if no range defined NOTE: in some cases a zero is returned (see TAxis::SetRange)
fLast (int): Last bin to display. fNbins if no range defined NOTE: in some cases a zero is returned (see TAxis::SetRange)
fBits2 (int): Second bit status word.
fTimeDisplay (bool): On/off displaying time values instead of numerics.
fTimeFormat (str or :doc:`uproot.models.TString.Model_TString`): Date&time format, ex: 09/12/99 12:34:00.
fLabels (None or :doc:`uproot.models.THashList.Model_THashList`): List of labels.
fModLabs (None or :doc:`uproot.models.TList.Model_TList`): List of modified labels.
fNdivisions (int): Number of divisions(10000*n3 + 100*n2 + n1). (https://root.cern.ch/doc/master/classTAttAxis.html)
fAxisColor (int): Color of the line axis.
fLabelColor (int): Color of labels.
fLabelFont (int): Font for labels.
fLabelOffset (float): Offset of labels.
fLabelSize (float): Size of labels.
fTickLength (float): Length of tick marks.
fTitleOffset (float): Offset of axis title.
fTitleSize (float): Size of axis title.
fTitleColor (int): Color of axis title.
fTitleFont (int): Font for axis title.
This function is for developers to create TAxis objects that can be
written to ROOT files, to implement conversion routines.
"""
tobject = uproot.models.TObject.Model_TObject.empty()
tnamed = uproot.models.TNamed.Model_TNamed.empty()
tnamed._deeply_writable = True
tnamed._bases.append(tobject)
tnamed._members["fName"] = fName
tnamed._members["fTitle"] = fTitle
tattaxis = uproot.models.TAtt.Model_TAttAxis_v4.empty()
tattaxis._deeply_writable = True
tattaxis._members["fNdivisions"] = fNdivisions
tattaxis._members["fAxisColor"] = fAxisColor
tattaxis._members["fLabelColor"] = fLabelColor
tattaxis._members["fLabelFont"] = fLabelFont