-
Notifications
You must be signed in to change notification settings - Fork 68
/
cursor.py
628 lines (554 loc) · 23.8 KB
/
cursor.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
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE
"""
This module defines the :doc:`uproot.source.cursor.Cursor`, which maintains
a thread-local pointer into a :doc:`uproot.source.chunk.Chunk` and performs
the lowest level of interpretation (numbers, strings, raw arrays, etc.).
"""
from __future__ import annotations
import datetime
import struct
import sys
import numpy
import uproot
_printable_characters = (
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLM"
"NOPQRSTUVWXYZ!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~ "
)
_raw_double32 = struct.Struct(">f")
_raw_float16 = struct.Struct(">BH")
# https://github.com/jblomer/root/blob/ntuple-binary-format-v1/tree/ntuple/v7/doc/specifications.md#basic-types
_rntuple_string_length = struct.Struct("<I")
_rntuple_datetime = struct.Struct("<Q")
class Cursor:
"""
Args:
index (int): Global seek position in the ROOT file or local position
in an uncompressed :doc:`uproot.source.chunk.Chunk`.
origin (int): Zero-point for numerical keys in ``refs``.
refs (None or dict): References to data already read in
:doc:`uproot.deserialization.read_object_any`.
Represents a seek point in a ROOT file, which may be held for later
reference or advanced while interpreting data from a
:doc:`uproot.source.chunk.Chunk`.
A cursor also holds references to previously read data that might be
requested by :doc:`uproot.deserialization.read_object_any`.
"""
def __init__(self, index: int, origin: int = 0, refs: dict | None = None):
self._index = index
self._origin = origin
self._refs = refs
def __repr__(self):
o = "" if self._origin == 0 else f", origin={self._origin}"
if self._refs is None or len(self._refs) == 0:
r = ""
elif self._refs is None or len(self._refs) < 3:
r = ", {} refs: {}".format(
len(self._refs), ", ".join(str(x) for x in self._refs)
)
else:
r = ", {} refs: {}...".format(
len(self._refs), ", ".join(str(x) for x in list(self._refs)[:3])
)
return f"Cursor({self._index}{o}{r})"
@property
def index(self) -> int:
"""
Global seek position in the ROOT file or local position in an
uncompressed :doc:`uproot.source.chunk.Chunk`.
"""
return self._index
@property
def origin(self) -> int:
"""
Zero-point for numerical keys in
:ref:`uproot.source.cursor.Cursor.refs`.
"""
return self._origin
@property
def refs(self) -> dict:
"""
References to data already read in
:doc:`uproot.deserialization.read_object_any`.
"""
if self._refs is None:
self._refs = {}
return self._refs
def displacement(self, other: Cursor = None) -> int:
"""
The number of bytes between this :doc:`uproot.source.cursor.Cursor`
and its :ref:`uproot.source.cursor.Cursor.origin` (if None)
or the ``other`` :doc:`uproot.source.cursor.Cursor` (if provided).
If the displacement is positive, ``self`` is later in the file than the
``origin`` or ``other``; if negative, it is earlier.
"""
if other is None:
return self._index - self._origin
else:
return self._index - other._index
def copy(self, link_refs: bool = True) -> Cursor:
"""
Returns a copy of this :doc:`uproot.source.cursor.Cursor`. If
``link_refs`` is True, any :ref:`uproot.source.cursor.Cursor.refs`
will be *referenced*, rather than *copied*.
"""
if link_refs or self._refs is None:
return Cursor(self._index, origin=self._origin, refs=self._refs)
else:
return Cursor(self._index, origin=self._origin, refs=dict(self._refs))
def move_to(self, index: int):
"""
Move the :ref:`uproot.source.cursor.Cursor.index` to a specified seek
position.
"""
self._index = index
def skip(self, num_bytes: int):
"""
Move the :ref:`uproot.source.cursor.Cursor.index` forward
``num_bytes``.
"""
self._index += num_bytes
def skip_after(self, obj):
"""
Move the :ref:`uproot.source.cursor.Cursor.index` just after an object
that has a starting ``obj.cursor`` and an expected ``obj.num_bytes``.
"""
start_cursor = getattr(obj, "cursor", None)
num_bytes = getattr(obj, "num_bytes", None)
if (
start_cursor is None
or not isinstance(start_cursor, Cursor)
or num_bytes is None
):
raise TypeError(
"Cursor.skip_after can only be used on an object with a "
f"`cursor` and `num_bytes`, not {type(obj)}"
)
self._index = start_cursor.index + num_bytes
def skip_over(self, chunk: uproot.source.chunk.Chunk, context: dict):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
Move the :ref:`uproot.source.cursor.Cursor.index` to a seek position
beyond the serialized data for an object that can be interpreted with
:doc:`uproot.deserialization.numbytes_version`.
Returns True if successful (cursor has moved), False otherwise (cursor
has NOT moved).
"""
num_bytes, version, is_memberwise = uproot.deserialization.numbytes_version(
chunk, self, context, move=False
)
if num_bytes is None:
return False
else:
self._index += num_bytes
return True
def fields(
self,
chunk: uproot.source.chunk.Chunk,
format: struct.Struct,
context: dict,
move: bool = True,
):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
format (``struct.Struct``): Specification to interpret the bytes of
data.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` with a
specified format. Returns a tuple of data whose types and length are
determined by the ``format``.
"""
start = self._index
stop = start + format.size
if move:
self._index = stop
return format.unpack(chunk.get(start, stop, self, context))
def field(
self,
chunk: uproot.source.chunk.Chunk,
format: struct.Struct,
context: dict,
move: bool = True,
):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
format (``struct.Struct``): Specification to interpret the bytes of
data.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` with a
format that only specifies one field, returning a single item instead of
a tuple.
"""
start = self._index
stop = start + format.size
if move:
self._index = stop
return format.unpack(chunk.get(start, stop, self, context))[0]
def double32(
self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True
) -> float:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as
ROOT's ``Double32_t`` type, returning the Python ``float``.
"""
# https://github.com/root-project/root/blob/e87a6311278f859ca749b491af4e9a2caed39161/io/io/src/TBufferFile.cxx#L448-L464
start = self._index
stop = start + _raw_double32.size
if move:
self._index = stop
return _raw_double32.unpack(chunk.get(start, stop, self, context))[0]
def float16(
self,
chunk: uproot.source.chunk.Chunk,
num_bits: int,
context: dict,
move: bool = True,
) -> float:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
num_bits (int): Number of bits in the mantissa.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as
ROOT's ``Float16_t`` type, returning the Python ``float``.
"""
# https://github.com/root-project/root/blob/e87a6311278f859ca749b491af4e9a2caed39161/io/io/src/TBufferFile.cxx#L432-L442
# https://github.com/root-project/root/blob/e87a6311278f859ca749b491af4e9a2caed39161/io/io/src/TBufferFile.cxx#L482-L499
start = self._index
stop = start + _raw_float16.size
if move:
self._index = stop
exponent, mantissa = _raw_float16.unpack(chunk.get(start, stop, self, context))
out = numpy.array([exponent], numpy.int32)
out <<= 23
out |= (mantissa & ((1 << (num_bits + 1)) - 1)) << (23 - num_bits)
out = out.view(numpy.float32)
if (1 << (num_bits + 1) & mantissa) != 0:
out = -out
return out.item()
def byte(self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a raw
byte.
"""
out = chunk.get(self._index, self._index + 1, self, context)
if move:
self._index += 1
return out
def bytes(self, chunk, length, context, move=True):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
length (int): Number of bytes to retrieve.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as raw
bytes with a given ``length``.
"""
start = self._index
stop = start + length
if move:
self._index = stop
return chunk.get(start, stop, self, context)
def array(
self,
chunk: uproot.source.chunk.Chunk,
length: int,
dtype: numpy.dtype,
context: dict,
move: bool = True,
) -> numpy.ndarray:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
length (int): Number of bytes to retrieve.
dtype (``numpy.dtype``): Data type for the array.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a
one-dimensional array with a given ``length`` and ``dtype``.
"""
start = self._index
stop = start + length * dtype.itemsize
if move:
self._index = stop
return numpy.frombuffer(chunk.get(start, stop, self, context), dtype=dtype)
_u1 = numpy.dtype("u1")
_i4 = numpy.dtype(">i4")
def bytestring(
self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True
) -> bytes:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a
bytestring.
The first byte is taken to be the length of the subsequent string unless
it is equal to 255, in which case, the next 4 bytes are taken to be an
``numpy.int32`` length.
"""
start = self._index
stop = start + 1
length = chunk.get(start, stop, self, context)[0]
if length == 255:
start = stop
stop = start + 4
length_data = chunk.get(start, stop, self, context)
length = numpy.frombuffer(length_data, dtype=self._u1).view(self._i4)[0]
start = stop
stop = start + int(length)
if move:
self._index = stop
return uproot._util.tobytes(chunk.get(start, stop, self, context))
def string(
self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True
) -> str:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a
UTF-8 encoded string.
The first byte is taken to be the length of the subsequent string unless
it is equal to 255, in which case, the next 4 bytes are taken to be an
``numpy.int32`` length.
"""
return self.bytestring(chunk, context, move=move).decode(
errors="surrogateescape"
)
def bytestring_with_length(
self,
chunk: uproot.source.chunk.Chunk,
context: dict,
length: int,
move: bool = True,
) -> bytes:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
length (int): Number of bytes in the bytestring.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a
bytestring.
"""
start = self._index
stop = start + length
if move:
self._index = stop
data = chunk.get(start, stop, self, context)
return uproot._util.tobytes(data)
def string_with_length(
self,
chunk: uproot.source.chunk.Chunk,
context: dict,
length: int,
move: bool = True,
) -> str:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
length (int): Number of bytes in the string.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a
UTF-8 encoded string.
"""
return self.bytestring_with_length(chunk, context, length, move=move).decode(
errors="surrogateescape"
)
def classname(
self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True
) -> str:
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Buffer of contiguous data
from the file :doc:`uproot.source.chunk.Source`.
context (dict): Auxiliary data used in deserialization.
move (bool): If True, move the
:ref:`uproot.source.cursor.Cursor.index` past the fields;
otherwise, leave it where it is.
Interpret data at this :ref:`uproot.source.cursor.Cursor.index` as a
null-terminated, UTF-8 encoded string.
"""
remainder = chunk.remainder(self._index, self, context)
local_stop = 0
char = None
while char != 0:
if local_stop > len(remainder):
raise OSError(
f"""C-style string has no terminator (null byte) in Chunk {self._start}:{self._stop}
of file path {self._source.file_path}"""
)
char = remainder[local_stop]
local_stop += 1
if move:
self._index += local_stop
return uproot._util.tobytes(remainder[: local_stop - 1]).decode(
errors="surrogateescape"
)
def rntuple_string(
self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True
) -> str:
if move:
length = self.field(chunk, _rntuple_string_length, context)
return self.string_with_length(chunk, context, length)
else:
index = self._index
out = self.rntuple_string(chunk, context, move=True)
self._index = index
return out
def rntuple_datetime(
self, chunk: uproot.source.chunk.Chunk, context: dict, move: bool = True
) -> datetime.datetime:
raw = self.field(chunk, _rntuple_datetime, context, move=move)
return datetime.datetime.fromtimestamp(raw)
def debug(
self,
chunk: uproot.source.chunk.Chunk,
context: dict = {}, # noqa: B006 (it's not actually mutated in the function)
limit_bytes: int | None = None,
dtype: numpy.dtype = None,
offset: int = 0,
stream=sys.stdout,
):
"""
Args:
chunk (:doc:`uproot.source.chunk.Chunk`): Data to examine.
context (dict): Auxiliary data used in deserialization.
limit_bytes (None or int): Number of bytes to limit the output to.
A line of debugging output (without any ``offset``) is 20 bytes,
so multiples of 20 show full lines. If None, everything is
shown to the end of the :doc:`uproot.source.chunk.Chunk`,
which might be large.
dtype (None, ``numpy.dtype``, or its constructor argument): If None,
present only the bytes as decimal values (0-255). Otherwise,
also interpret them as an array of a given NumPy type.
offset (int): Number of bytes to skip before interpreting a ``dtype``;
can be helpful if the numerical values are out of phase with
the first byte shown. Not to be confused with ``skip_bytes``,
which determines which bytes are shown at all. Any ``offset``
values that are equivalent modulo ``dtype.itemsize`` show
equivalent interpretations.
stream (object with a ``write(str)`` method): Stream to write the
debugging output to.
Peek at data by printing it to the ``stream`` (usually stdout). The data
are always presented as decimal bytes and ASCII characters, but may
also be interpreted as numbers.
Example output with ``dtype=">f4"`` and ``offset=3``.
.. code-block::
--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-
123 123 123 63 140 204 205 64 12 204 205 64 83 51 51 64 140 204 205 64
{ { { ? --- --- --- @ --- --- --- @ S 3 3 @ --- --- --- @
1.1 2.2 3.3 4.4
--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-
176 0 0 64 211 51 51 64 246 102 102 65 12 204 205 65 30 102 102 66
--- --- --- @ --- 3 3 @ --- f f A --- --- --- A --- f f B
5.5 6.6 7.7 8.8 9.9
--+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+-
202 0 0 67 74 0 0 67 151 128 0 123 123
--- --- --- C J --- --- C --- --- --- { {
101.0 202.0 303.0
"""
data = chunk.remainder(self._index, self, context)
if limit_bytes is not None:
data = data[:limit_bytes]
if dtype is not None:
if not isinstance(dtype, numpy.dtype):
dtype = numpy.dtype(dtype)
interpreted = [None] * len(data)
i = offset
interpreted_length = (
(len(data) - offset) // dtype.itemsize
) * dtype.itemsize
for x in data[offset : offset + interpreted_length].view(dtype):
i += dtype.itemsize
interpreted[i - 1] = x
formatter = f"{{0:>{dtype.itemsize * 4 - 1}.{dtype.itemsize * 4 - 1}s}}"
for line_start in range(0, int(numpy.ceil(len(data) / 20.0)) * 20, 20):
line_data = data[line_start : line_start + 20]
prefix = ""
if dtype is not None:
nones = 0
for x in interpreted[line_start:]:
if x is None:
nones += 1
else:
break
fill = max(0, dtype.itemsize - 1 - nones)
line_interpreted = [None] * fill + interpreted[
line_start : line_start + 20
]
prefix = " " * fill
interpreted_prefix = " " * (fill + nones + 1 - dtype.itemsize)
stream.write(prefix + ("--+-" * 20) + "\n")
stream.write(prefix + " ".join(f"{x:3d}" for x in line_data) + "\n")
stream.write(
prefix
+ " ".join(
f"{x:>3c}" if chr(x) in _printable_characters else "---"
for x in line_data
)
+ "\n"
)
if dtype is not None:
stream.write(
interpreted_prefix
+ " ".join(
formatter.format(str(x))
for x in line_interpreted
if x is not None
)
+ "\n"
)