Repository navigation
Conversation
ariostas
left a comment
There was a problem hiding this comment.
🤖 AI text below 🤖
Thanks for this! Writing protocol-only histograms with plain (lower, upper) tuple axes works now, and I checked that the new tests pass. I found a few cases that still go wrong, mostly by writing a file without raising any error. Details are in the inline comments. All the reproducers below use these helpers, which are a trimmed version of the classes in the new test:
import numpy as np
import uproot
class Traits:
def __init__(self, d): self.circular = False; self.discrete = d
class Axis:
def __init__(self, edges=None, labels=None, pair=tuple):
self._e = None if edges is None else np.asarray(edges, float)
self._l = labels; self._pair = pair
self.traits = Traits(labels is not None)
def __len__(self): return len(self._l) if self._l is not None else len(self._e) - 1
def __getitem__(self, i):
if self._l is not None: return self._l[i]
return self._pair((self._e[i], self._e[i + 1]))
def __iter__(self): return (self[i] for i in range(len(self)))
def __eq__(self, o): return list(self) == list(o)
class Hist:
def __init__(self, *axes, kind="COUNT"):
self.axes = axes; self.kind = kind
shape = tuple(len(a) for a in axes)
self._v = np.arange(1, np.prod(shape) + 1, dtype=float).reshape(shape)
def values(self): return self._v
def variances(self): return self._v
def counts(self): return self._v
def roundtrip(h):
with uproot.recreate("t.root") as f:
f["h"] = h
return uproot.open("t.root")["h"]Profiles (kind="MEAN") still fail. I'm putting this one here because identify.py:369 isn't in the diff.
roundtrip(Hist(Axis([0, 1, 2, 3]), kind="MEAN"))
# AttributeError: 'Hist' object has no attribute '_bases'A protocol histogram has no storage_type, so it takes the else branch, which is only meant for re-writing uproot's own TProfile (obj._bases, obj.member(...)). This isn't a regression, because on main the same case already fails earlier with the .edges error. But the PR description says protocol histograms can be written, so it would be good to either support this or raise a clear NotImplementedError for protocol profiles.
| if edges is not None: | ||
| return numpy.asarray(edges() if callable(edges) else edges) | ||
|
|
||
| if len(axis) == 0 or not isinstance(axis[0], tuple): |
There was a problem hiding this comment.
🤖 AI text below 🤖
isinstance(axis[0], tuple) decides whether the axis is continuous, so a continuous axis whose items are any other length-2 sequence is treated as categorical, and the file is silently wrong:
r = roundtrip(Hist(Axis([0, 1, 5, 10], pair=np.array))) # pair=list gives the same result
r.axes[0].edges() # [0. 1. 2. 3.] expected [0. 1. 5. 10.]
r.member("fTsumwx") # 11.0 expected 29.0 (what tuple pairs give)The protocol does specify tuples, so this is about robustness more than spec compliance. Still, axis.traits.discrete is the protocol's own way to tell the two kinds of axis apart, and your test axes already set it. Switching on it would give either correct edges or a clear error instead of a wrong histogram.
| fXmin=_axis_edges(axis)[0], | ||
| fXmax=_axis_edges(axis)[-1], | ||
| fXbins=_fXbins_maybe_regular(axis, boost_histogram), | ||
| fLabels=_fLabels_maybe_categorical(axis, boost_histogram), |
There was a problem hiding this comment.
🤖 AI text below 🤖
Discrete protocol axes are written now, but their categories are lost. _fLabels_maybe_categorical returns None whenever boost_histogram is None, and _axis_edges gives them edges 0..n:
r = roundtrip(Hist(Axis(labels=["a", "b", "c"])))
r.axes[0].labels() # None expected ['a', 'b', 'c']
r = roundtrip(Hist(Axis(labels=[1, 5, 10])))
r.axes[0].edges(), r.axes[0].labels()
# ([0. 1. 2. 3.], None): the values 1, 5, 10 can't be recoveredBefore this PR, these cases raised an error, so now the category information is dropped with no warning. Could fLabels be built from str(axis[i]) whenever axis.traits.discrete is true, not only for boost-histogram category axes? The discrete-axis test would then also need to check the labels, since right now it only checks the edges.
| fNbins=len(axis), | ||
| fXmin=axis.edges[0], | ||
| fXmax=axis.edges[-1], | ||
| fXmin=_axis_edges(axis)[0], |
There was a problem hiding this comment.
🤖 AI text below 🤖
Minor: _axis_edges(axis) is computed several times per axis: here twice, once more inside _fXbins_maybe_regular, and again for the _root_stats_* calls. For protocol axes, each call is a Python loop over every bin, so computing the edges once per axis and passing them along would avoid the repeated work.
| else: | ||
| # Regular axis: prepend and append a bin width to edges for flow bins. | ||
| _edges = obj.axes[0].edges | ||
| _edges = _axis_edges(obj.axes[0]) |
There was a problem hiding this comment.
🤖 AI text below 🤖
Minor: this branch is only reached when hasattr(obj, "storage_type"), which means a boost-histogram, so the axis always has .edges. That's the same reasoning the PR uses to leave the boost branch of _fXbins_maybe_regular alone. I'd keep obj.axes[0].edges here, so the code doesn't suggest that protocol profiles are supported (see the MEAN note in the review summary).
| """ | ||
| edges = getattr(axis, "edges", None) | ||
| if edges is not None: | ||
| return numpy.asarray(edges() if callable(edges) else edges) |
There was a problem hiding this comment.
🤖 AI text below 🤖
Minor: the fallback path below produces float64, but this path keeps whatever dtype the axis provides. Adding dtype=numpy.float64 here would make the two paths consistent.
| @@ -0,0 +1,130 @@ | |||
| # BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE | |||
There was a problem hiding this comment.
🤖 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_....
|
🤖 AI text below 🤖 A follow-up on the approach. I think import numpy as np
import uproot
from uhi.numpy_plottable import NumPyPlottableHistogram
h = NumPyPlottableHistogram(np.array([1.0, 2.0, 3.0]), np.array([0.0, 1.0, 5.0, 10.0]))
h.axes[0].edges.shape # (3, 2)
with uproot.recreate("u.root") as f:
f["h"] = h
# ValueError: data to convert to TArray must be one-dimensionalThis isn't a regression, but checking A suggestion: compute the edges and labels once per axis, at the top of the PlottableHistogram branch, and pass the results along: def _axis_edges_and_labels(axis, boost_histogram):
if boost_histogram is not None:
# known type: fast path, labels handled as today
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)
pairs = numpy.asarray([axis[i] for i in range(n)], dtype=numpy.float64).reshape(n, 2)
return numpy.append(pairs[:, 0], pairs[-1, 1]), None
axis_info = [_axis_edges_and_labels(a, boost_histogram) for a in obj.axes]Here
A protocol-only histogram with a very large axis still goes through a Python loop over the bins, but only once per axis, and only when the protocol is all there is to work with. |
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files
|
… labels Compute each axis's edges and labels once. boost-histogram axes use .edges; other axes use axis.traits.discrete to keep category labels, axis[i] pairs for continuous axes, and a flat .edges for axes that can't be indexed. Protocol histograms with kind='MEAN' raise NotImplementedError. Rename the test after the PR.
…tegorical _axis_edges_and_labels only calls it for boost-histogram and hist objects, so boost_histogram is never None there, and the early return can't be covered. Assisted-by: Claude Code:claude-opus-5-5
Fixes #1339.
Writing a PlottableHistogram with
f["h"] = husedaxis.edges, which isn't part of the PlottableHistogram protocol, so a histogram whose axes only implement the protocol failed withAttributeError: ... has no attribute 'edges'.uproot/writing/identify.pynow computes each axis's edges and labels once, in_axis_edges_and_labels, and passes them toto_TAxis,_fXbins_maybe_regularand the_root_stats_*functions:axis.edges, as before, and keep their category labels.axis.traits.discretegets integer edges and keeps its categories as labels (str(axis[i])).(lower, upper)pairs fromaxis[i], whatever sequence type they are, so uhi'sNumPyPlottableHistogram(whose.edgesis N×2) can be written too..edges, as intest_1827_fix_writing.py.The labels code of
_fLabels_maybe_categoricalis split out into_to_fLabelsso discrete protocol axes can use it. A protocol histogram withkind="MEAN"now raisesNotImplementedErrorinstead of failing onobj._bases.tests/test_1845_write_protocol_histogram.pycovers protocol histograms in 1D, 2D and 3D,(lower, upper)pairs given as tuples, lists and arrays, discrete axes with string and integer categories, uhi'sNumPyPlottableHistogram, theMEANerror, and agreement with the same histograms written fromhist. Locally, it and the existing writing tests (test_1827,test_0046,test_0167,test_0580,test_1829_cov_interp_identifyand others) give 265 passed and 88 skipped (tests that need ROOT), every changed line is covered, andpre-commit runpasses on the changed files.AI disclosure: I used Claude Code (Claude Opus 5.5) to help write this change and its tests.