Skip to content
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
70 changes: 54 additions & 16 deletions src/uproot/writing/identify.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,19 +245,22 @@ def to_writable(obj):
# ROOT has fEntries = sum *without* weights, *with* flow bins
fEntries = data.sum()

# the edges and labels of each axis, computed once
axis_info = [_axis_edges_and_labels(axis, boost_histogram) for axis in obj.axes]

# 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),
fXmin=edges[0],
fXmax=edges[-1],
fXbins=_fXbins_maybe_regular(axis, edges, boost_histogram),
fLabels=labels,
)
for axis, default_name in zip(
obj.axes, ["xaxis", "yaxis", "zaxis"], strict=False
for axis, (edges, labels), default_name in zip(
obj.axes, axis_info, ["xaxis", "yaxis", "zaxis"], strict=False
)
]

Expand Down Expand Up @@ -370,6 +373,11 @@ def to_writable(obj):
fBinSumw2=_fBinSumw2,
fXaxis=axes[0],
)
elif not hasattr(obj, "_bases"):
raise NotImplementedError(
"1D PlottableHistogram with kind='MEAN' (i.e. 1D profile plots) "
"is only supported for boost-histogram and hist objects"
)
else:
return to_TProfile(
fName=None,
Expand All @@ -389,7 +397,7 @@ def to_writable(obj):
)
else:
fTsumw, fTsumw2, fTsumwx, fTsumwx2 = _root_stats_1d(
data_noflow, obj.axes[0].edges
data_noflow, axis_info[0][0]
)
return to_TH1x(
fName=None,
Expand Down Expand Up @@ -418,7 +426,7 @@ def to_writable(obj):
fTsumwy,
fTsumwy2,
fTsumwxy,
) = _root_stats_2d(data_noflow, obj.axes[0].edges, obj.axes[1].edges)
) = _root_stats_2d(data_noflow, axis_info[0][0], axis_info[1][0])
return to_TH2x(
fName=None,
fTitle=title,
Expand Down Expand Up @@ -456,9 +464,9 @@ def to_writable(obj):
fTsumwyz,
) = _root_stats_3d(
data_noflow,
obj.axes[0].edges,
obj.axes[1].edges,
obj.axes[2].edges,
axis_info[0][0],
axis_info[1][0],
axis_info[2][0],
)
return to_TH3x(
fName=None,
Expand Down Expand Up @@ -700,9 +708,38 @@ def to_writable(obj):
)


def _fXbins_maybe_regular(axis, boost_histogram):
def _axis_edges_and_labels(axis, boost_histogram):
"""
Returns the bin edges (as float64) and the TAxis labels (or None) of a
PlottableHistogram axis.

boost-histogram axes provide ``edges``. Other axes are read through the
PlottableHistogram protocol, in which ``axis[i]`` is a ``(lower, upper)``
pair for a continuous axis and a category for a discrete one
(``axis.traits.discrete``), whose labels are kept. An axis that can't be
indexed this way must have a flat array of ``edges``.
"""
if boost_histogram is not None:
return (
numpy.asarray(axis.edges, dtype=numpy.float64),
_fLabels_maybe_categorical(axis, boost_histogram),
)

n = len(axis)
if getattr(getattr(axis, "traits", None), "discrete", False):
labels = [str(axis[i]) for i in range(n)]
return numpy.arange(n + 1, dtype=numpy.float64), _to_fLabels(labels)

if not hasattr(axis, "__getitem__"):
return numpy.asarray(axis.edges, dtype=numpy.float64), None

pairs = numpy.asarray([axis[i] for i in range(n)], dtype=numpy.float64)
pairs = pairs.reshape(n, 2)
return numpy.append(pairs[:, 0], pairs[-1, 1]), None


def _fXbins_maybe_regular(axis, edges, 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))):
return numpy.array([], dtype=">f8")
Expand All @@ -719,16 +756,17 @@ def _fXbins_maybe_regular(axis, boost_histogram):


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]

return _to_fLabels(labels)


def _to_fLabels(labels):
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):
Expand Down
160 changes: 160 additions & 0 deletions tests/test_1845_write_protocol_histogram.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🤖 AI text below 🤖

Nit: the repo convention is from __future__ import annotations at the top of every module. Also, test files are usually numbered after the PR, so this would be test_1845_....


from __future__ import annotations

import numpy as np
import pytest

import uproot


class _Traits:
def __init__(self, discrete):
self.circular = False
self.discrete = discrete


class ProtocolAxis:
"""Implements the PlottableAxis protocol without an ``edges`` attribute."""

def __init__(self, edges=None, labels=None, pair=tuple):
self._edges = None if edges is None else np.asarray(edges, dtype=np.float64)
self._labels = labels
self._pair = pair
self.traits = _Traits(discrete=labels is not None)

def __len__(self):
return len(self._labels) if self._labels is not None else len(self._edges) - 1

def __getitem__(self, index):
if self._labels is not None:
return self._labels[index]
return self._pair((self._edges[index], self._edges[index + 1]))

def __iter__(self):
return (self[i] for i in range(len(self)))

def __eq__(self, other):
return list(self) == list(other)


class ProtocolHistogram:
"""Implements the PlottableHistogram protocol with ``ProtocolAxis`` axes."""

def __init__(self, *axes, kind="COUNT"):
self.axes = axes
self.kind = kind
shape = tuple(len(axis) for axis in axes)
self._values = np.arange(1, np.prod(shape) + 1, dtype=np.float64).reshape(shape)

def values(self):
return self._values

def variances(self):
return self._values

def counts(self):
return self._values


def roundtrip(tmp_path, h):
with uproot.recreate(tmp_path / "protocol.root") as fout:
fout["h"] = h
with uproot.open(tmp_path / "protocol.root") as fin:
return fin["h"]


@pytest.mark.parametrize(
"edges",
[
[[0, 1, 2, 3]],
[[0, 1, 5, 10]],
[[0, 1, 2], [0, 2, 4, 8]],
[[0, 1, 2], [0, 2, 4], [0, 3, 6, 9]],
],
ids=["1d-regular", "1d-variable", "2d", "3d"],
)
def test_write_protocol_histogram(tmp_path, edges):
h = ProtocolHistogram(*(ProtocolAxis(edges=e) for e in edges))
h_read = roundtrip(tmp_path, h)
for axis_read, axis_edges in zip(h_read.axes, edges, strict=True):
assert np.array_equal(axis_read.edges(), axis_edges)
assert np.array_equal(h_read.values(), h.values())
assert np.array_equal(h_read.variances(), h.variances())


@pytest.mark.parametrize(
"pair", [tuple, list, np.array], ids=["tuple", "list", "array"]
)
def test_write_protocol_histogram_pair_types(tmp_path, pair):
h = ProtocolHistogram(ProtocolAxis(edges=[0, 1, 5, 10], pair=pair))
h_read = roundtrip(tmp_path, h)
assert np.array_equal(h_read.axes[0].edges(), [0, 1, 5, 10])
assert h_read.member("fTsumwx") == pytest.approx(0.5 * 1 + 3 * 2 + 7.5 * 3)


@pytest.mark.parametrize(
("labels", "expected"),
[(["a", "b", "c"], ["a", "b", "c"]), ([1, 5, 10], ["1", "5", "10"])],
ids=["str", "int"],
)
def test_write_protocol_histogram_discrete_axis(tmp_path, labels, expected):
h = ProtocolHistogram(ProtocolAxis(labels=labels))
h_read = roundtrip(tmp_path, h)
assert np.array_equal(h_read.axes[0].edges(), [0, 1, 2, 3])
assert h_read.axes[0].labels() == expected
assert np.array_equal(h_read.values(), h.values())


def test_write_uhi_numpy_plottable_histogram(tmp_path):
numpy_plottable = pytest.importorskip("uhi.numpy_plottable")
h = numpy_plottable.NumPyPlottableHistogram(
np.array([1.0, 2.0, 3.0]), np.array([0.0, 1.0, 5.0, 10.0])
)
h_read = roundtrip(tmp_path, h)
assert np.array_equal(h_read.axes[0].edges(), [0, 1, 5, 10])
assert np.array_equal(h_read.values(), [1, 2, 3])


def test_write_protocol_profile_not_supported(tmp_path):
h = ProtocolHistogram(ProtocolAxis(edges=[0, 1, 2, 3]), kind="MEAN")
with pytest.raises(NotImplementedError, match=r"kind='MEAN'"):
with uproot.recreate(tmp_path / "protocol.root") as fout:
fout["h"] = h


@pytest.mark.parametrize(
"edges",
[[[0, 1, 2, 3]], [[0, 1, 5, 10]], [[0, 1, 2], [0, 2, 4, 8]]],
ids=["1d-regular", "1d-variable", "2d"],
)
def test_protocol_histogram_matches_hist(tmp_path, edges):
hist = pytest.importorskip("hist")

h_protocol = ProtocolHistogram(*(ProtocolAxis(edges=e) for e in edges))
h_hist = hist.Hist(*(hist.axis.Variable(e, flow=False) for e in edges))
h_hist[...] = h_protocol.values()

with uproot.recreate(tmp_path / "protocol.root") as fout:
fout["h"] = h_protocol
with uproot.recreate(tmp_path / "hist.root") as fout:
fout["h"] = h_hist

with uproot.open(tmp_path / "protocol.root") as fin:
from_protocol = fin["h"]
with uproot.open(tmp_path / "hist.root") as fin_hist:
from_hist = fin_hist["h"]
for axis_protocol, axis_hist in zip(
from_protocol.axes, from_hist.axes, strict=True
):
# evenly spaced edges are written without fXbins for a
# PlottableHistogram, but for a hist Variable axis with them, so
# compare the edges they describe
assert np.array_equal(axis_protocol.edges(), axis_hist.edges())
assert np.array_equal(
from_protocol.values(flow=True), from_hist.values(flow=True)
)
for name in ["fEntries", "fTsumw", "fTsumw2", "fTsumwx", "fTsumwx2"]:
assert from_protocol.member(name) == pytest.approx(
from_hist.member(name)
)
Loading