-
Notifications
You must be signed in to change notification settings - Fork 76
/
Copy path_cascadetree.py
1627 lines (1394 loc) · 61.3 KB
/
_cascadetree.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 is an internal module for writing TTrees in the "cascading" file writer. TTrees
are more like TDirectories than they are like histograms in that they can create
objects, TBaskets, which have to be allocated through the FreeSegments.
The implementation in this module does not use the TTree infrastructure in
:doc:`uproot.models.TTree`, :doc:`uproot.models.TBranch`, and :doc:`uproot.models.TBasket`,
since the models intended for reading have to adapt to different class versions, but
a writer can always write the same class version, and because writing involves allocating
and sometimes freeing data.
See :doc:`uproot.writing._cascade` for a general overview of the cascading writer concept.
"""
import datetime
import math
import struct
import warnings
from collections.abc import Mapping
import numpy
import uproot.compression
import uproot.const
import uproot.reading
import uproot.serialization
_dtype_to_char = {
numpy.dtype("bool"): "O",
numpy.dtype(">i1"): "B",
numpy.dtype(">u1"): "b",
numpy.dtype(">i2"): "S",
numpy.dtype(">u2"): "s",
numpy.dtype(">i4"): "I",
numpy.dtype(">u4"): "i",
numpy.dtype(">i8"): "L",
numpy.dtype(">u8"): "l",
numpy.dtype(">f4"): "F",
numpy.dtype(">f8"): "D",
numpy.dtype(">U"): "C",
}
class Tree:
"""
Writes a TTree, including all TBranches, TLeaves, and (upon ``extend``) TBaskets.
Rather than treating TBranches as a separate object, this *writable* TTree writes
the whole metadata block in one function, so that interrelationships are easier
to preserve.
Writes the following class instance versions:
- TTree: version 20
- TBranch: version 13
- TLeaf: version 2
- TLeaf*: version 1
- TBasket: version 3
The ``write_anew`` method writes the whole tree, possibly for the first time, possibly
because it has been moved (exceeded its initial allocation of TBasket pointers).
The ``write_updates`` method rewrites the parts that change when new TBaskets are
added.
The ``extend`` method adds a TBasket to every TBranch.
The ``write_np_basket`` and ``write_jagged_basket`` methods write one TBasket in one
TBranch, either a rectilinear one from NumPy or a simple jagged array from Awkward Array.
See `ROOT TTree specification <https://github.com/root-project/root/blob/master/io/doc/TFile/ttree.md>`__.
"""
def __init__(
self,
directory,
name,
title,
branch_types,
freesegments,
counter_name,
field_name,
initial_basket_capacity,
resize_factor,
):
self._directory = directory
self._name = name
self._title = title
self._freesegments = freesegments
self._counter_name = counter_name
self._field_name = field_name
self._basket_capacity = initial_basket_capacity
self._resize_factor = resize_factor
if isinstance(branch_types, dict):
branch_types_items = branch_types.items()
else:
branch_types_items = branch_types
if len(branch_types) == 0:
raise ValueError("TTree must have at least one branch")
self._branch_data = []
self._branch_lookup = {}
for branch_name, branch_type in branch_types_items:
branch_dict = None
branch_dtype = None
branch_datashape = None
if isinstance(branch_type, Mapping) and all(
uproot._util.isstr(x) for x in branch_type
):
branch_dict = branch_type
else:
try:
if uproot._util.from_module(branch_type, "awkward"):
raise TypeError
if (
uproot._util.isstr(branch_type)
and branch_type.strip() == "bytes"
):
raise TypeError
branch_dtype = numpy.dtype(branch_type)
except TypeError as err:
try:
awkward = uproot.extras.awkward()
except ModuleNotFoundError as err:
raise TypeError(
f"not a NumPy dtype and 'awkward' cannot be imported: {branch_type!r}"
) from err
if isinstance(
branch_type,
(awkward.types.Type, awkward.types.ArrayType),
):
branch_datashape = branch_type
else:
try:
branch_datashape = awkward.types.from_datashape(
branch_type, highlevel=False
)
except Exception:
raise TypeError(
f"not a NumPy dtype or an Awkward datashape: {branch_type!r}"
) from err
if isinstance(branch_datashape, awkward.types.ArrayType):
branch_datashape = branch_datashape.content
branch_dtype = self._branch_ak_to_np(branch_datashape)
if branch_dict is not None:
if branch_name not in self._branch_lookup:
self._branch_lookup[branch_name] = len(self._branch_data)
self._branch_data.append(
{
"kind": "record",
"name": branch_name,
"keys": list(branch_dict),
}
)
for key, content in branch_dict.items():
subname = self._field_name(branch_name, key)
try:
dtype = numpy.dtype(content)
except Exception as err:
raise TypeError(
"values of a dict must be NumPy types\n\n key {} has type {}".format(
repr(key), repr(content)
)
) from err
self._branch_lookup[subname] = len(self._branch_data)
self._branch_data.append(
self._branch_np(subname, content, dtype)
)
elif branch_dtype is not None:
if branch_name not in self._branch_lookup:
self._branch_lookup[branch_name] = len(self._branch_data)
self._branch_data.append(
self._branch_np(branch_name, branch_type, branch_dtype)
)
else:
parameters = branch_datashape.parameters
if parameters is None:
parameters = {}
if parameters.get("__array__") == "string":
if branch_name not in self._branch_lookup:
self._branch_lookup[branch_name] = len(self._branch_data)
self._branch_data.append(
self._branch_np(branch_name, branch_type, numpy.dtype(str))
)
elif parameters.get("__array__") == "bytes":
raise NotImplementedError("array of bytes")
# 'awkward' is not in namespace
elif type(branch_datashape).__name__ == "ListType":
content = branch_datashape.content
counter_name = self._counter_name(branch_name)
counter_dtype = numpy.dtype(numpy.int32)
counter = self._branch_np(
counter_name, counter_dtype, counter_dtype, kind="counter"
)
if counter_name in self._branch_lookup:
# counters always replace non-counters
del self._branch_data[self._branch_lookup[counter_name]]
self._branch_lookup[counter_name] = len(self._branch_data)
self._branch_data.append(counter)
if type(content).__name__ == "RecordType":
if hasattr(content, "contents"):
contents = content.contents
else:
contents = content.fields()
keys = content.fields
if callable(keys):
keys = keys()
if keys is None:
keys = [str(x) for x in range(len(contents))]
if branch_name not in self._branch_lookup:
self._branch_lookup[branch_name] = len(self._branch_data)
self._branch_data.append(
{"kind": "record", "name": branch_name, "keys": keys}
)
for key, cont in zip(keys, contents):
subname = self._field_name(branch_name, key)
dtype = self._branch_ak_to_np(cont)
if dtype is None:
raise TypeError(
"fields of a record must be NumPy types, though the record itself may be in a jagged array\n\n field {} has type {}".format(
repr(key), str(cont)
)
)
if subname not in self._branch_lookup:
self._branch_lookup[subname] = len(
self._branch_data
)
self._branch_data.append(
self._branch_np(
subname, cont, dtype, counter=counter
)
)
else:
dt = self._branch_ak_to_np(content)
if dt is None:
raise TypeError(
"cannot write Awkward Array type to ROOT file:\n\n {}".format(
str(branch_datashape)
)
)
if branch_name not in self._branch_lookup:
self._branch_lookup[branch_name] = len(self._branch_data)
self._branch_data.append(
self._branch_np(branch_name, dt, dt, counter=counter)
)
elif type(branch_datashape).__name__ == "RecordType":
if hasattr(branch_datashape, "contents"):
contents = branch_datashape.contents
else:
contents = branch_datashape.fields()
keys = branch_datashape.fields
if callable(keys):
keys = keys()
if keys is None:
keys = [str(x) for x in range(len(contents))]
if branch_name not in self._branch_lookup:
self._branch_lookup[branch_name] = len(self._branch_data)
self._branch_data.append(
{"kind": "record", "name": branch_name, "keys": keys}
)
for key, content in zip(keys, contents):
subname = self._field_name(branch_name, key)
dtype = self._branch_ak_to_np(content)
if dtype is None:
raise TypeError(
"fields of a record must be NumPy types, though the record itself may be in a jagged array\n\n field {} has type {}".format(
repr(key), str(content)
)
)
if subname not in self._branch_lookup:
self._branch_lookup[subname] = len(self._branch_data)
self._branch_data.append(
self._branch_np(subname, content, dtype)
)
else:
raise TypeError(
"cannot write Awkward Array type to ROOT file:\n\n {}".format(
str(branch_datashape)
)
)
self._num_entries = 0
self._num_baskets = 0
self._metadata_start = None
self._metadata = {
"fTotBytes": 0,
"fZipBytes": 0,
"fSavedBytes": 0,
"fFlushedBytes": 0,
"fWeight": 1.0,
"fTimerInterval": 0,
"fScanField": 25,
"fUpdate": 0,
"fDefaultEntryOffsetLen": 1000,
"fNClusterRange": 0,
"fMaxEntries": 1000000000000,
"fMaxEntryLoop": 1000000000000,
"fMaxVirtualSize": 0,
"fAutoSave": -300000000,
"fAutoFlush": -30000000,
"fEstimate": 1000000,
}
self._key = None
def _branch_ak_to_np(self, branch_datashape):
if type(branch_datashape).__name__ == "UnknownType":
return numpy.dtype("float64")
elif type(branch_datashape).__name__ == "NumpyType":
return numpy.dtype(branch_datashape.primitive)
elif type(branch_datashape).__name__ == "PrimitiveType":
return numpy.dtype(branch_datashape.dtype)
elif type(branch_datashape).__name__ == "RegularType":
content = self._branch_ak_to_np(branch_datashape.content)
if content is None:
return None
elif content.subdtype is None:
dtype, shape = content, ()
else:
dtype, shape = content.subdtype
return numpy.dtype((dtype, (branch_datashape.size, *shape)))
else:
return None
def _branch_np(
self, branch_name, branch_type, branch_dtype, counter=None, kind="normal"
):
branch_dtype = branch_dtype.newbyteorder(">")
if branch_dtype.subdtype is None:
branch_shape = ()
else:
branch_dtype, branch_shape = branch_dtype.subdtype
letter = _dtype_to_char.get(branch_dtype)
if letter is None:
raise TypeError(f"cannot write NumPy dtype {branch_dtype} in TTree")
if branch_shape == ():
dims = ""
else:
dims = "".join("[" + str(x) + "]" for x in branch_shape)
title = f"{branch_name}{dims}/{letter}"
return {
"fName": branch_name,
"branch_type": branch_type,
"kind": kind,
"counter": counter,
"dtype": branch_dtype,
"shape": branch_shape,
"fTitle": title,
"compression": self._directory.freesegments.fileheader.compression,
"fBasketSize": 32000,
"fEntryOffsetLen": 0 if counter is None else 1000,
"fOffset": 0,
"fSplitLevel": 0,
"fFirstEntry": 0,
"fTotBytes": 0,
"fZipBytes": 0,
"fBasketBytes": numpy.zeros(
self._basket_capacity, uproot.models.TBranch._tbranch13_dtype1
),
"fBasketEntry": numpy.zeros(
self._basket_capacity, uproot.models.TBranch._tbranch13_dtype2
),
"fBasketSeek": numpy.zeros(
self._basket_capacity, uproot.models.TBranch._tbranch13_dtype3
),
"arrays_write_start": 0,
"arrays_write_stop": 0,
"metadata_start": None,
"basket_metadata_start": None,
"tleaf_reference_number": None,
"tleaf_maximum_value": 0,
"tleaf_special_struct": None,
}
def __repr__(self):
return "{}({}, {}, {}, {}, {}, {}, {})".format(
type(self).__name__,
self._directory,
self._name,
self._title,
[(datum["fName"], datum["branch_type"]) for datum in self._branch_data],
self._freesegments,
self._basket_capacity,
self._resize_factor,
)
@property
def directory(self):
return self._directory
@property
def key(self):
return self._key
@property
def name(self):
return self._key.name
@property
def title(self):
return self._key.title
@property
def branch_types(self):
return self._branch_types
@property
def freesegments(self):
return self._freesegments
@property
def counter_name(self):
return self._counter_name
@property
def field_name(self):
return self._field_name
@property
def basket_capacity(self):
return self._basket_capacity
@property
def resize_factor(self):
return self._resize_factor
@property
def location(self):
return self._key.location
@property
def num_entries(self):
return self._num_entries
@property
def num_baskets(self):
return self._num_baskets
def extend(self, file, sink, data):
# expand capacity if this would REACH (not EXCEED) the existing capacity
# that's because completely a full fBasketEntry has nowhere to put the
# number of entries in the last basket (it's a fencepost principle thing),
# forcing ROOT and Uproot to look it up from the basket header.
if self._num_baskets >= self._basket_capacity - 1:
self._basket_capacity = max(
self._basket_capacity + 1,
int(math.ceil(self._basket_capacity * self._resize_factor)),
)
for datum in self._branch_data:
if datum["kind"] == "record":
continue
fBasketBytes = datum["fBasketBytes"]
fBasketEntry = datum["fBasketEntry"]
fBasketSeek = datum["fBasketSeek"]
datum["fBasketBytes"] = numpy.zeros(
self._basket_capacity, uproot.models.TBranch._tbranch13_dtype1
)
datum["fBasketEntry"] = numpy.zeros(
self._basket_capacity, uproot.models.TBranch._tbranch13_dtype2
)
datum["fBasketSeek"] = numpy.zeros(
self._basket_capacity, uproot.models.TBranch._tbranch13_dtype3
)
datum["fBasketBytes"][: len(fBasketBytes)] = fBasketBytes
datum["fBasketEntry"][: len(fBasketEntry)] = fBasketEntry
datum["fBasketSeek"][: len(fBasketSeek)] = fBasketSeek
datum["fBasketEntry"][len(fBasketEntry)] = self._num_entries
oldloc = start = self._key.location
stop = start + self._key.num_bytes + self._key.compressed_bytes
self.write_anew(sink)
newloc = self._key.seek_location
file._move_tree(oldloc, newloc)
self._freesegments.release(start, stop)
sink.set_file_length(self._freesegments.fileheader.end)
sink.flush()
provided = None
if uproot._util.from_module(data, "pandas"):
import pandas
if isinstance(
data, pandas.DataFrame
) and uproot._util.pandas_has_attr_is_numeric(pandas)(data.index):
provided = dataframe_to_dict(data)
if uproot._util.from_module(data, "awkward"):
try:
awkward = uproot.extras.awkward()
except ModuleNotFoundError as err:
raise TypeError(
f"an Awkward Array was provided, but 'awkward' cannot be imported: {data!r}"
) from err
if isinstance(data, awkward.Array):
if data.ndim > 1 and not data.layout.purelist_isregular:
provided = {
self._counter_name(""): numpy.asarray(
awkward.num(data, axis=1), dtype=">u4"
)
}
else:
provided = {}
for k, v in zip(awkward.fields(data), awkward.unzip(data)):
provided[k] = v
if isinstance(data, numpy.ndarray) and data.dtype.fields is not None:
provided = recarray_to_dict(data)
if provided is None:
if not isinstance(data, Mapping) or not all(
uproot._util.isstr(x) for x in data
):
raise TypeError(
"'extend' requires a mapping from branch name (str) to arrays"
)
provided = {}
for k, v in data.items():
if not uproot._util.from_module(
v, "pandas"
) and not uproot._util.from_module(v, "awkward"):
if not hasattr(v, "dtype") and not isinstance(v, Mapping):
try:
with warnings.catch_warnings():
warnings.simplefilter(
"error", category=numpy.VisibleDeprecationWarning
)
v = numpy.array(v) # noqa: PLW2901 (overwriting v)
if v.dtype == numpy.dtype("O"):
raise Exception
except (numpy.VisibleDeprecationWarning, Exception):
try:
awkward = uproot.extras.awkward()
except ModuleNotFoundError as err:
raise TypeError(
f"NumPy dtype would be dtype('O'), so we won't use NumPy, but 'awkward' cannot be imported: {k}: {type(v)}"
) from err
v = awkward.from_iter(v) # noqa: PLW2901 (overwriting v)
if getattr(v, "dtype", None) == numpy.dtype("O"):
try:
awkward = uproot.extras.awkward()
except ModuleNotFoundError as err:
raise TypeError(
f"NumPy dtype is dtype('O'), so we won't use NumPy, but 'awkward' cannot be imported: {k}: {type(v)}"
) from err
v = awkward.from_iter(v) # noqa: PLW2901 (overwriting v)
if uproot._util.from_module(v, "awkward"):
try:
awkward = uproot.extras.awkward()
except ModuleNotFoundError as err:
raise TypeError(
f"an Awkward Array was provided, but 'awkward' cannot be imported: {k}: {type(v)}"
) from err
if (
isinstance(v, awkward.Array)
and v.ndim > 1
and not v.layout.purelist_isregular
):
kk = self._counter_name(k)
vv = numpy.asarray(awkward.num(v, axis=1), dtype=">u4")
if kk in provided and not numpy.array_equal(vv, provided[kk]):
raise ValueError(
f"branch {kk!r} provided both as an explicit array and generated as a counter, and they disagree"
)
provided[kk] = vv
if k in provided and not numpy.array_equal(v, provided[k]):
raise ValueError(
f"branch {kk!r} provided both as an explicit array and generated as a counter, and they disagree"
)
provided[k] = v
actual_branches = {}
for datum in self._branch_data:
if datum["kind"] == "record":
if datum["name"] in provided:
recordarray = provided.pop(datum["name"])
if uproot._util.from_module(recordarray, "pandas"):
import pandas
if isinstance(recordarray, pandas.DataFrame):
tmp = {"index": recordarray.index.values}
for column in recordarray.columns:
tmp[column] = recordarray[column]
recordarray = tmp
for key in datum["keys"]:
provided[self._field_name(datum["name"], key)] = recordarray[
key
]
elif datum["name"] == "":
for key in datum["keys"]:
provided[self._field_name(datum["name"], key)] = provided.pop(
key
)
else:
raise ValueError(
"'extend' must be given an array for every branch; missing {}".format(
repr(datum["name"])
)
)
else:
if datum["fName"] in provided:
actual_branches[datum["fName"]] = provided.pop(datum["fName"])
else:
raise ValueError(
"'extend' must be given an array for every branch; missing {}".format(
repr(datum["fName"])
)
)
if len(provided) != 0:
raise ValueError(
"'extend' was given data that do not correspond to any branch: {}".format(
", ".join(repr(x) for x in provided)
)
)
tofill = []
num_entries = None
for branch_name, branch_array in actual_branches.items():
if num_entries is None:
num_entries = len(branch_array)
elif num_entries != len(branch_array):
raise ValueError(
"'extend' must fill every branch with the same number of entries; {} has {} entries".format(
repr(branch_name),
len(branch_array),
)
)
datum = self._branch_data[self._branch_lookup[branch_name]]
if datum["kind"] == "record":
continue
if datum["counter"] is None:
if datum["dtype"] == ">U0":
lengths = numpy.asarray(awkward.num(branch_array.layout))
which_big = lengths >= 255
lengths_extension_offsets = numpy.empty(
len(branch_array.layout) + 1, numpy.int64
)
lengths_extension_offsets[0] = 0
numpy.cumsum(which_big * 4, out=lengths_extension_offsets[1:])
lengths_extension = awkward.contents.ListOffsetArray(
awkward.index.Index64(lengths_extension_offsets),
awkward.contents.NumpyArray(
lengths[which_big].astype(">u4").view("u1")
),
)
lengths[which_big] = 255
leafc_data_awkward = awkward.concatenate(
[
lengths.reshape(-1, 1).astype("u1"),
lengths_extension,
awkward.without_parameters(branch_array.layout),
],
axis=1,
)
big_endian = numpy.asarray(awkward.flatten(leafc_data_awkward))
big_endian_offsets = (
lengths_extension_offsets
+ numpy.asarray(branch_array.layout.offsets)
+ numpy.arange(len(branch_array.layout.offsets))
).astype(">i4", copy=True)
tofill.append(
(
branch_name,
datum["compression"],
big_endian,
big_endian_offsets,
)
)
else:
big_endian = uproot._util.ensure_numpy(branch_array).astype(
datum["dtype"]
)
if big_endian.shape != (len(branch_array),) + datum["shape"]:
raise ValueError(
"'extend' must fill branches with a consistent shape: has {}, trying to fill with {}".format(
datum["shape"],
big_endian.shape[1:],
)
)
tofill.append((branch_name, datum["compression"], big_endian, None))
if datum["kind"] == "counter":
datum["tleaf_maximum_value"] = max(
big_endian.max(), datum["tleaf_maximum_value"]
)
else:
try:
awkward = uproot.extras.awkward()
except ModuleNotFoundError as err:
raise TypeError(
f"a jagged array was provided (possibly as an iterable), but 'awkward' cannot be imported: {branch_name}: {branch_array!r}"
) from err
layout = branch_array.layout
while not isinstance(layout, awkward.contents.ListOffsetArray):
if isinstance(layout, awkward.contents.IndexedArray):
layout = layout.project()
elif isinstance(layout, awkward.contents.ListArray):
layout = layout.to_ListOffsetArray64(False)
else:
raise AssertionError(
"how did this pass the type check?\n\n" + repr(layout)
)
content = layout.content
offsets = numpy.asarray(layout.offsets)
if offsets[0] != 0:
content = content[offsets[0] :]
offsets = offsets - offsets[0]
if len(content) > offsets[-1]:
content = content[: offsets[-1]]
shape = [len(content)]
while not isinstance(content, awkward.contents.NumpyArray):
if isinstance(content, awkward.contents.IndexedArray):
content = content.project()
elif isinstance(content, awkward.contents.EmptyArray):
content = content.to_NumpyArray(dtype=numpy.float64)
elif isinstance(content, awkward.contents.RegularArray):
shape.append(content.size)
content = content.content
else:
raise AssertionError(
"how did this pass the type check?\n\n" + repr(content)
)
big_endian = numpy.asarray(content.data, dtype=datum["dtype"])
shape = tuple(shape) + big_endian.shape[1:]
if shape[1:] != datum["shape"]:
raise ValueError(
"'extend' must fill branches with a consistent shape: has {}, trying to fill with {}".format(
datum["shape"],
shape[1:],
)
)
big_endian_offsets = offsets.astype(">i4", copy=True)
tofill.append(
(
branch_name,
datum["compression"],
big_endian.reshape(-1),
big_endian_offsets,
)
)
# actually write baskets into the file
uncompressed_bytes = 0
compressed_bytes = 0
for branch_name, compression, big_endian, big_endian_offsets in tofill:
datum = self._branch_data[self._branch_lookup[branch_name]]
if datum["dtype"] == ">U0":
totbytes, zipbytes, location = self.write_string_basket(
sink, branch_name, compression, big_endian, big_endian_offsets
)
datum["fEntryOffsetLen"] = 4 * (len(big_endian_offsets) - 1)
elif big_endian_offsets is None:
totbytes, zipbytes, location = self.write_np_basket(
sink, branch_name, compression, big_endian
)
else:
totbytes, zipbytes, location = self.write_jagged_basket(
sink, branch_name, compression, big_endian, big_endian_offsets
)
datum["fEntryOffsetLen"] = 4 * (len(big_endian_offsets) - 1)
uncompressed_bytes += totbytes
compressed_bytes += zipbytes
datum["fTotBytes"] += totbytes
datum["fZipBytes"] += zipbytes
datum["fBasketBytes"][self._num_baskets] = zipbytes
if self._num_baskets + 1 < self._basket_capacity:
fBasketEntry = datum["fBasketEntry"]
i = self._num_baskets
fBasketEntry[i + 1] = num_entries + fBasketEntry[i]
datum["fBasketSeek"][self._num_baskets] = location
datum["arrays_write_stop"] = self._num_baskets + 1
# update TTree metadata in file
self._num_entries += num_entries
self._num_baskets += 1
self._metadata["fTotBytes"] += uncompressed_bytes
self._metadata["fZipBytes"] += compressed_bytes
self.write_updates(sink)
def write_anew(self, sink):
key_num_bytes = uproot.reading._key_format_big.size + 6
name_asbytes = self._name.encode(errors="surrogateescape")
title_asbytes = self._title.encode(errors="surrogateescape")
key_num_bytes += (1 if len(name_asbytes) < 255 else 5) + len(name_asbytes)
key_num_bytes += (1 if len(title_asbytes) < 255 else 5) + len(title_asbytes)
out = [None]
ttree_header_index = 0
tobject = uproot.models.TObject.Model_TObject.empty()
tnamed = uproot.models.TNamed.Model_TNamed.empty()
tnamed._bases.append(tobject)
tnamed._members["fTitle"] = self._title
tnamed._serialize(out, True, self._name, uproot.const.kMustCleanup)
# TAttLine v2, fLineColor: 602 fLineStyle: 1 fLineWidth: 1
# TAttFill v2, fFillColor: 0, fFillStyle: 1001
# TAttMarker v2, fMarkerColor: 1, fMarkerStyle: 1, fMarkerSize: 1.0
out.append(
b"@\x00\x00\x08\x00\x02\x02Z\x00\x01\x00\x01"
b"@\x00\x00\x06\x00\x02\x00\x00\x03\xe9"
b"@\x00\x00\n\x00\x02\x00\x01\x00\x01?\x80\x00\x00"
)
metadata_out_index = len(out)
out.append(
uproot.models.TTree._ttree20_format1.pack(
self._num_entries,
self._metadata["fTotBytes"],
self._metadata["fZipBytes"],
self._metadata["fSavedBytes"],
self._metadata["fFlushedBytes"],
self._metadata["fWeight"],
self._metadata["fTimerInterval"],
self._metadata["fScanField"],
self._metadata["fUpdate"],
self._metadata["fDefaultEntryOffsetLen"],
self._metadata["fNClusterRange"],
self._metadata["fMaxEntries"],
self._metadata["fMaxEntryLoop"],
self._metadata["fMaxVirtualSize"],
self._metadata["fAutoSave"],
self._metadata["fAutoFlush"],
self._metadata["fEstimate"],
)
)
# speedbump (0), fClusterRangeEnd (empty array),
# speedbump (0), fClusterSize (empty array)
# fIOFeatures (TIOFeatures)
out.append(b"\x00\x00@\x00\x00\x07\x00\x00\x1a\xa1/\x10\x00")
tleaf_reference_numbers = []
tobjarray_of_branches_index = len(out)
out.append(None)
num_branches = sum(
0 if datum["kind"] == "record" else 1 for datum in self._branch_data
)
# TObjArray header with fName: ""
out.append(b"\x00\x01\x00\x00\x00\x00\x03\x00@\x00\x00")
out.append(
uproot.models.TObjArray._tobjarray_format1.pack(
num_branches, # TObjArray fSize
0, # TObjArray fLowerBound
)
)
for datum in self._branch_data:
if datum["kind"] == "record":
continue
any_tbranch_index = len(out)
out.append(None)
out.append(b"TBranch\x00")
tbranch_index = len(out)
out.append(None)
tbranch_tobject = uproot.models.TObject.Model_TObject.empty()
tbranch_tnamed = uproot.models.TNamed.Model_TNamed.empty()
tbranch_tnamed._bases.append(tbranch_tobject)
tbranch_tnamed._members["fTitle"] = datum["fTitle"]
tbranch_tnamed._serialize(
out, True, datum["fName"], numpy.uint32(0x00400000)
)
# TAttFill v2, fFillColor: 0, fFillStyle: 1001
out.append(b"@\x00\x00\x06\x00\x02\x00\x00\x03\xe9")
assert sum(1 if x is None else 0 for x in out) == 4
datum["metadata_start"] = (6 + 6 + 8 + 6) + sum(
len(x) for x in out if x is not None
)
# Lie about the compression level so that ROOT checks and does the right thing.
# https://github.com/root-project/root/blob/87a998d48803bc207288d90038e60ff148827664/tree/tree/src/TBasket.cxx#L560-L578
# Without this, when small buffers are left uncompressed, ROOT complains about them not being compressed.
# (I don't know where the "no, really, this is uncompressed" bit is.)
fCompress = 0
out.append(
uproot.models.TBranch._tbranch13_format1.pack(
fCompress,
datum["fBasketSize"],
datum["fEntryOffsetLen"],
self._num_baskets, # fWriteBasket
self._num_entries, # fEntryNumber
)
)
# fIOFeatures (TIOFeatures)
out.append(b"@\x00\x00\x07\x00\x00\x1a\xa1/\x10\x00")
out.append(
uproot.models.TBranch._tbranch13_format2.pack(
datum["fOffset"],
self._basket_capacity, # fMaxBaskets
datum["fSplitLevel"],
self._num_entries, # fEntries
datum["fFirstEntry"],
datum["fTotBytes"],
datum["fZipBytes"],
)
)
# empty TObjArray of TBranches
out.append(
b"@\x00\x00\x15\x00\x03\x00\x01\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"
)
subtobjarray_of_leaves_index = len(out)
out.append(None)
# TObjArray header with fName: "", fSize: 1, fLowerBound: 0
out.append(
b"\x00\x01\x00\x00\x00\x00\x03\x00\x00\x00\x00\x00\x00\x00\x01\x00\x00\x00\x00"
)
absolute_location = key_num_bytes + sum(
len(x) for x in out if x is not None
)
absolute_location += 8 + 6 * (sum(1 if x is None else 0 for x in out) - 1)
datum["tleaf_reference_number"] = absolute_location + 2
tleaf_reference_numbers.append(datum["tleaf_reference_number"])