-
Notifications
You must be signed in to change notification settings - Fork 79
/
Copy pathpyroot.py
296 lines (230 loc) · 9.4 KB
/
pyroot.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
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE
"""
This module provides an interface between Uproot and PyROOT.
PyROOT is a *complete* set of ROOT bindings generated automatically from ROOT's
reflected C++ code. Uproot is a pure Python reimplementation of ROOT I/O, with
incomplete coverage of ROOT's suite of classes, but without an install-time
dependence on ROOT.
The only point of contact between Uproot and PyROOT is that they both recognize
the same *serialized* form of ROOT objects, so conversions in this module proceed
by serializing and deserializing the objects through a TMessage. This makes it
possible to
- convert any PyROOT object into its Uproot :doc:`uproot.model.Model` *if Uproot can read it* (which is possible for most classes)
- convert any Uproot :doc:`uproot.model.Model` into the corresponding PyROOT object *if Uproot can write it* (which is considerably more constrained; mostly just histograms).
This module also makes it possible for PyROOT objects to be added to ROOT files
that Uproot is writing (regardless of whether Uproot could read such objects).
"""
from __future__ import annotations
import threading
import uuid
import numpy
import uproot
def to_pyroot(obj, name=None):
"""
Args:
obj (:doc:`uproot.model.Model`): The Uproot model to convert.
name (str or None): A name for the new PyROOT object.
Converts an :doc:`uproot.model.Model` into a PyROOT object *if it is writable by Uproot*.
A minority of Uproot models are writable, mostly just histograms. Writability
is necessary for conversion to PyROOT because it is serialized through a
ROOT TMessage.
"""
import ROOT
if to_pyroot._Uproot_FromTMessage is None:
ROOT.gInterpreter.Declare(
"""
class _Uproot_FromTMessage : public TMessage {
public:
_Uproot_FromTMessage(void* buffer, Int_t size): TMessage(buffer, size) { }
};
"""
)
to_pyroot._Uproot_FromTMessage = ROOT._Uproot_FromTMessage
serialized = uproot.serialization.serialize_object_any(obj, name)
buffer = numpy.empty(len(serialized) + 8, numpy.uint8)
buffer[:8].view(numpy.uint64)[0] = ROOT.kMESS_OBJECT
buffer[8:] = numpy.frombuffer(serialized, numpy.uint8)
message = to_pyroot._Uproot_FromTMessage(buffer, len(buffer))
out = message.ReadObject(message.GetClass())
message.DetachBuffer()
return out
to_pyroot._Uproot_FromTMessage = None
def pyroot_to_buffer(obj):
"""
Args:
obj (PyROOT object inheriting from TObject): PyROOT object to serialize.
Serializes a PyROOT object into a NumPy array that is owned by this function.
This function is not thread-safe and the output buffer gets overwritten by
the next call to this function. It is essential for callers to copy the data
out of the returned buffer, perhaps by calling :doc:`uproot._util.tobytes` on
it or by assigning it into another array.
A lock is provided for safety: callers should always call this function within
the lock's context:
.. code-block:: python
with pyroot_to_buffer.lock:
return uproot._util.tobytes(pyroot_to_buffer(obj))
"""
import ROOT
if pyroot_to_buffer.sizer is None:
ROOT.gInterpreter.Declare(
"""
class _Uproot_buffer_sizer : public TObject {
public:
size_t buffer;
size_t newsize;
size_t oldsize;
};
char* _uproot_TMessage_reallocate(char* buffer, size_t newsize, size_t oldsize) {
_Uproot_buffer_sizer* ptr = reinterpret_cast<_Uproot_buffer_sizer*>(
(void*)TPython::Eval("__import__('uproot').pyroot.pyroot_to_buffer.sizer")
);
ptr->buffer = reinterpret_cast<size_t>(buffer);
ptr->newsize = newsize;
ptr->oldsize = oldsize;
TPython::Exec("__import__('uproot').pyroot.pyroot_to_buffer.reallocate()");
TPyReturn out = TPython::Eval("__import__('uproot').pyroot.pyroot_to_buffer.buffer.ctypes.data");
return reinterpret_cast<char*>((size_t)out);
}
void _uproot_TMessage_SetBuffer(TMessage& message, void* buffer, UInt_t newsize) {
message.SetBuffer(buffer, newsize, false, _uproot_TMessage_reallocate);
}
"""
)
pyroot_to_buffer.sizer = ROOT._Uproot_buffer_sizer()
pyroot_to_buffer.buffer = numpy.empty(1024, numpy.uint8)
def reallocate():
newbuf = numpy.empty(pyroot_to_buffer.sizer.newsize, numpy.uint8)
newbuf[: len(pyroot_to_buffer.buffer)] = pyroot_to_buffer.buffer
pyroot_to_buffer.buffer = newbuf
pyroot_to_buffer.reallocate = reallocate
message = ROOT.TMessage(ROOT.kMESS_OBJECT)
message.SetCompressionLevel(0)
ROOT._uproot_TMessage_SetBuffer(
message, pyroot_to_buffer.buffer, len(pyroot_to_buffer.buffer)
)
message.WriteObject(obj)
return pyroot_to_buffer.buffer[: message.Length()]
pyroot_to_buffer.lock = threading.Lock()
pyroot_to_buffer.sizer = None
pyroot_to_buffer.buffer = None
class _GetStreamersOnce:
_custom_classes = {}
_streamers = {}
_streamer_dependencies = {}
def __init__(self, obj):
self._obj = obj
def class_named(self, classname, version=None):
return uproot.reading.ReadOnlyFile.class_named(self, classname, version)
def streamers_named(self, classname):
return uproot.reading.ReadOnlyFile.streamers_named(self, classname)
def streamer_named(self, classname, version):
return uproot.reading.ReadOnlyFile.streamer_named(
self, classname, version=version
)
@property
def custom_classes(self):
return self._custom_classes
@property
def file_path(self):
return None
class ArrayFile:
def __init__(self, array):
self.array = array
self.current = 0
def seek(self, position):
self.current = position
def read(self, num_bytes):
position = self.current + num_bytes
out = self.array[self.current : position]
self.current = position
return out
@property
def streamers(self):
tclass = self._obj.IsA()
obj_classname = tclass.GetName()
obj_version = tclass.GetClassVersion()
if self._streamers.get(obj_classname, {}).get(obj_version, None) is None:
import ROOT
memfile = ROOT.TMemFile("noname.root", "new")
memfile.SetCompressionLevel(0)
memfile.WriteObjectAny(self._obj, self._obj.IsA(), "noname")
memfile.WriteStreamerInfo()
memfile.Close()
buffer = numpy.empty(memfile.GetEND(), numpy.uint8)
memfile.CopyTo(buffer, len(buffer))
file = uproot.open(_GetStreamersOnce.ArrayFile(buffer))
dependencies = self._streamer_dependencies[obj_classname, obj_version] = []
for classname, versions in file.file.streamers.items():
if classname not in self._streamers:
self._streamers[classname] = {}
for version, streamerinfo in versions.items():
self._streamers[classname][version] = streamerinfo
dependencies.append(streamerinfo)
return self._streamers
class _NoFile:
def __init__(self):
import ROOT
self._file_path = ""
self._options = {}
self._fVersion = ROOT.gROOT.GetVersionInt()
self._fBEGIN = 0
self._fEND = 0
self._fSeekFree = 0
self._fNbytesFree = 0
self._nfree = 0
self._fNbytesName = 0
self._fUnits = 0
self._fCompress = 0
self._fSeekInfo = 0
self._fNbytesInfo = 0
self._fUUID_version = 1
self._fUUID = uuid.UUID("00000000-0000-0000-0000-000000000000")
@property
def streamers(self):
return _GetStreamersOnce._streamers
@property
def custom_classes(self):
return _GetStreamersOnce._custom_classes
def from_pyroot(obj):
"""
Args:
obj (PyROOT object inheriting from TObject): PyROOT object to convert to
an Uproot :doc:`uproot.model.Model`.
Converts a PyROOT object into its corresponding Uproot :doc:`uproot.model.Model`
*if it is readable by Uproot*. Most ROOT classes are readable by Uproot. Readability
is necessary for conversion from PyROOT because the object is serialized through a
ROOT TMessage.
"""
with pyroot_to_buffer.lock:
buffer = pyroot_to_buffer(obj)
chunk = uproot.source.chunk.Chunk.wrap(None, buffer)
cursor = uproot.source.cursor.Cursor(0)
maybestreamers = _GetStreamersOnce(obj)
detatched = _NoFile()
return uproot.deserialization.read_object_any(
chunk, cursor, {}, maybestreamers, detatched, None
)
class _PyROOTWritable:
def __init__(self, obj):
self._obj = obj
@property
def class_rawstreamers(self):
tclass = self._obj.IsA()
key = (tclass.GetName(), tclass.GetClassVersion())
return _GetStreamersOnce._streamer_dependencies.get(key, [])
@property
def classname(self):
tclass = self._obj.IsA()
return tclass.GetName()
@property
def fTitle(self):
return self._obj.GetTitle()
def serialize(self, name=None):
if name is None or name == self._obj.GetName():
obj = self._obj
else:
obj = self._obj.Clone(name)
with pyroot_to_buffer.lock:
return uproot._util.tobytes(
pyroot_to_buffer(obj)[len(self.classname) + 9 :]
)