Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Write a histogram. #405

Merged
merged 13 commits into from
Aug 6, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/uproot/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,17 @@
range = eval("range")


def tobytes(array):
"""
Calls ``array.tobytes()`` or its older equivalent, ``array.tostring()``,
depending on what's available in this NumPy version.
"""
if hasattr(array, "tobytes"):
return array.tobytes()
else:
return array.tostring()


def isint(x):
"""
Returns True if and only if ``x`` is an integer (including NumPy, not
Expand Down
17 changes: 16 additions & 1 deletion src/uproot/_writing.py
Original file line number Diff line number Diff line change
Expand Up @@ -967,7 +967,7 @@ def deserialize(cls, raw_bytes, location, key, freesegments, file_path, uuid):
rawstreamers.append(
RawStreamerInfo(
location + start,
uncompressed.raw_data[start:stop].tobytes(),
uproot._util.tobytes(uncompressed.raw_data[start:stop]),
streamer.name,
streamer.class_version,
)
Expand Down Expand Up @@ -2185,3 +2185,18 @@ def update_existing(sink, initial_directory_bytes, uuid_function):
return CascadingFile(
fileheader, streamers, freesegments, rootdirectory, tlist_of_streamers
)


_serialize_string_small = struct.Struct(">B")
_serialize_string_big = struct.Struct(">BI")


def serialize_string(string):
"""
FIXME: docstring
"""
as_bytes = string.encode(errors="surrogateescape")
if len(as_bytes) < 255:
return _serialize_string_small.pack(len(as_bytes)) + as_bytes
else:
return _serialize_string_big.pack(255, len(as_bytes)) + as_bytes
1 change: 1 addition & 0 deletions src/uproot/const.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

kIsOnHeap = numpy.uint32(0x01000000)
kNotDeleted = numpy.uint32(0x02000000)
kMustCleanup = numpy.uint32(1 << 3)
kIsReferenced = numpy.uint32(1 << 4)

kMapOffset = 2
Expand Down
5 changes: 1 addition & 4 deletions src/uproot/interpretation/strings.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,10 +227,7 @@ def basket_array(
offsets[0] = 0
numpy.cumsum(counts, out=offsets[1:])

if hasattr(data, "tobytes"):
data = data.tobytes()
else:
data = data.tostring()
data = uproot._util.tobytes(data)
output = StringArray(offsets, data)

self.hook_after_basket_array(
Expand Down
74 changes: 70 additions & 4 deletions src/uproot/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,11 +91,14 @@ def reset_classes():
reload(uproot.models.TObjString)
reload(uproot.models.TAtt)
reload(uproot.models.TRef)

reload(uproot.models.TTree)
reload(uproot.models.TBranch)
reload(uproot.models.TLeaf)
reload(uproot.models.TBasket)
reload(uproot.models.RNTuple)
reload(uproot.models.TH)
reload(uproot.models.TGraph)


_classname_regularize = re.compile(r"\s*(<|>|::)\s*")
Expand Down Expand Up @@ -361,6 +364,7 @@ class Model(object):
class_streamer = None
class_rawstreamers = ()
writable = False
_deeply_writable = False
behaviors = ()

def __repr__(self):
Expand Down Expand Up @@ -721,6 +725,7 @@ def empty(cls):
self._cursor = None
self._file = None
self._parent = None
self._concrete = None
self._members = {}
self._bases = []
self._num_bytes = None
Expand Down Expand Up @@ -757,7 +762,6 @@ def read(cls, chunk, cursor, context, file, selffile, parent, concrete=None):
self._file = selffile
self._parent = parent
self._concrete = concrete

self._members = {}
self._bases = []
self._num_bytes = None
Expand Down Expand Up @@ -956,9 +960,71 @@ def hook_before_postprocess(self, **kwargs):
"""
pass

def _serialize(self, out, header, name):
def _to_writable_postprocess(self, original):
pass

def _to_writable(self, concrete):
cls = None
if self.writable:
cls = type(self)
else:
dispatch = uproot.classes.get(self.classname)
if dispatch is not None:
for versioned_cls in dispatch.known_versions.values():
if versioned_cls.writable:
cls = versioned_cls
break

if cls is None:
raise NotImplementedError(
"this ROOT type is not writable: {0}".format(self.classname)
)
else:
out = cls.__new__(cls)
out._cursor = self._cursor
out._file = self._file
out._parent = self._parent
out._concrete = concrete
out._num_bytes = self._num_bytes
out._instance_version = classname_decode(cls.__name__)[1]
out._is_memberwise = self._is_memberwise

if concrete is None:
concrete = out

out._bases = []
for base in self._bases:
out._bases.append(base._to_writable(concrete))

out._members = {}
for key, value in self._members.items():
if isinstance(value, Model):
out._members[key] = value._to_writable(None)
else:
out._members[key] = value

out._to_writable_postprocess(self)
return out

def to_writable(self):
"""
Args:
obj (:doc:`uproot.model.Model` instance of the same C++ class): The
object to convert to this class version.

Returns a writable version of this object or raises a NotImplementedError
if no writable version exists.
"""
if self._deeply_writable:
return self
else:
return self._to_writable(None)

def _serialize(self, out, header, name, tobject_flags):
raise NotImplementedError(
"serialize method not implemented on {0}".format(type(self).__name__)
"can't write {0} instances yet ('serialize' method not implemented)".format(
type(self).__name__
)
)

def serialize(self, name=None):
Expand All @@ -972,7 +1038,7 @@ def serialize(self, name=None):
NotImplementedError).
"""
out = []
self._serialize(out, True, name)
self._serialize(out, True, name, numpy.uint32(0x00000000))
return b"".join(out)


Expand Down
18 changes: 18 additions & 0 deletions src/uproot/models/TArray.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,24 @@ def awkward_form(
parameters={"uproot": {"as": "TArray"}},
)

writable = True

def _to_writable_postprocess(self, original):
self._data = original._data

def _serialize(self, out, header, name, tobject_flags):
where = len(out)
for x in self._bases:
x._serialize(out, True, None, tobject_flags)

out.append(_tarray_format1.pack(self._members["fN"]))
out.append(uproot._util.tobytes(self._data))

if header:
num_bytes = sum(len(x) for x in out[where:])
version = 1
out.insert(where, uproot.serialization.numbytes_version(num_bytes, version))


class Model_TArrayC(Model_TArray):
"""
Expand Down
84 changes: 76 additions & 8 deletions src/uproot/models/TAtt.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,24 @@ def awkward_form(
)
return awkward.forms.RecordForm(contents, parameters={"__record__": "TAttLine"})

writable = True

def _serialize(self, out, header, name, tobject_flags):
where = len(out)
for x in self._bases:
x._serialize(out, True, None, tobject_flags)
out.append(
_tattline1_format1.pack(
self._members["fLineColor"],
self._members["fLineStyle"],
self._members["fLineWidth"],
)
)
if header:
num_bytes = sum(len(x) for x in out[where:])
version = 2
out.insert(where, uproot.serialization.numbytes_version(num_bytes, version))

base_names_versions = []
member_names = ["fLineColor", "fLineStyle", "fLineWidth"]
class_flags = {}
Expand Down Expand Up @@ -305,6 +323,23 @@ def awkward_form(
)
return awkward.forms.RecordForm(contents, parameters={"__record__": "TAttFill"})

writable = True

def _serialize(self, out, header, name, tobject_flags):
where = len(out)
for x in self._bases:
x._serialize(out, True, None, tobject_flags)
out.append(
_tattfill2_format1.pack(
self._members["fFillColor"],
self._members["fFillStyle"],
)
)
if header:
num_bytes = sum(len(x) for x in out[where:])
version = 2
out.insert(where, uproot.serialization.numbytes_version(num_bytes, version))

base_names_versions = []
member_names = ["fFillColor", "fFillStyle"]
class_flags = {}
Expand Down Expand Up @@ -392,6 +427,24 @@ def awkward_form(
contents, parameters={"__record__": "TAttMarker"}
)

writable = True

def _serialize(self, out, header, name, tobject_flags):
where = len(out)
for x in self._bases:
x._serialize(out, True, None, tobject_flags)
out.append(
_tattmarker2_format1.pack(
self._members["fMarkerColor"],
self._members["fMarkerStyle"],
self._members["fMarkerSize"],
)
)
if header:
num_bytes = sum(len(x) for x in out[where:])
version = 2
out.insert(where, uproot.serialization.numbytes_version(num_bytes, version))

base_names_versions = []
member_names = ["fMarkerColor", "fMarkerStyle", "fMarkserSize"]
class_flags = {}
Expand All @@ -414,7 +467,8 @@ class Model_TAttAxis_v4(uproot.model.VersionedModel):
def read_members(self, chunk, cursor, context, file):
if self.is_memberwise:
raise NotImplementedError(
"memberwise serialization of {0}\nin file {1}".format(
"""memberwise serialization of {0}
in file {1}""".format(
type(self).__name__, self.file.file_path
)
)
Expand Down Expand Up @@ -600,11 +654,25 @@ def awkward_form(

writable = True

def _serialize(self, out, header, name):
def _serialize(self, out, header, name, tobject_flags):
where = len(out)
for x in self._bases:
x._serialize(out, True, name)
raise NotImplementedError("FIXME")
x._serialize(out, True, None, tobject_flags)
out.append(
self._format0.pack(
self._members["fNdivisions"],
self._members["fAxisColor"],
self._members["fLabelColor"],
self._members["fLabelFont"],
self._members["fLabelOffset"],
self._members["fLabelSize"],
self._members["fTickLength"],
self._members["fTitleOffset"],
self._members["fTitleSize"],
self._members["fTitleColor"],
self._members["fTitleFont"],
)
)
if header:
num_bytes = sum(len(x) for x in out[where:])
version = 4
Expand All @@ -627,7 +695,8 @@ class Model_TAtt3D_v1(uproot.model.VersionedModel):
def read_members(self, chunk, cursor, context, file):
if self.is_memberwise:
raise NotImplementedError(
"memberwise serialization of {0}\nin file {1}".format(
"""memberwise serialization of {0}
in file {1}""".format(
type(self).__name__, self.file.file_path
)
)
Expand Down Expand Up @@ -689,11 +758,10 @@ def awkward_form(

writable = True

def _serialize(self, out, header, name):
def _serialize(self, out, header, name, tobject_flags):
where = len(out)
for x in self._bases:
x._serialize(out, True, name)
raise NotImplementedError("FIXME")
x._serialize(out, True, None, tobject_flags)
if header:
num_bytes = sum(len(x) for x in out[where:])
version = 1
Expand Down
Loading