Skip to content

fix: write PlottableHistogram axes that have no edges attribute - #1845

Merged
ariostas merged 4 commits into
scikit-hep:mainfrom
Aryapatel-007:Aryapatel-007/protocol-histogram-edges
Nov 20, 2026
Merged

ariostas merged 4 commits into
scikit-hep:mainfrom
Aryapatel-007:Aryapatel-007/protocol-histogram-edges

Conversation

@Aryapatel-007

@Aryapatel-007 Aryapatel-007 commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1339.

Writing a PlottableHistogram with f["h"] = h used axis.edges, which isn't part of the PlottableHistogram protocol, so a histogram whose axes only implement the protocol failed with AttributeError: ... has no attribute 'edges'.

uproot/writing/identify.py now computes each axis's edges and labels once, in _axis_edges_and_labels, and passes them to to_TAxis, _fXbins_maybe_regular and the _root_stats_* functions:

  • boost-histogram and hist axes use axis.edges, as before, and keep their category labels.
  • An axis with axis.traits.discrete gets integer edges and keeps its categories as labels (str(axis[i])).
  • Other axes use the (lower, upper) pairs from axis[i], whatever sequence type they are, so uhi's NumPyPlottableHistogram (whose .edges is N×2) can be written too.
  • An axis that can't be indexed this way still uses a flat .edges, as in test_1827_fix_writing.py.

The labels code of _fLabels_maybe_categorical is split out into _to_fLabels so discrete protocol axes can use it. A protocol histogram with kind="MEAN" now raises NotImplementedError instead of failing on obj._bases.

tests/test_1845_write_protocol_histogram.py covers protocol histograms in 1D, 2D and 3D, (lower, upper) pairs given as tuples, lists and arrays, discrete axes with string and integer categories, uhi's NumPyPlottableHistogram, the MEAN error, and agreement with the same histograms written from hist. Locally, it and the existing writing tests (test_1827, test_0046, test_0167, test_0580, test_1829_cov_interp_identify and others) give 265 passed and 88 skipped (tests that need ROOT), every changed line is covered, and pre-commit run passes on the changed files.

AI disclosure: I used Claude Code (Claude Opus 5.5) to help write this change and its tests.

@github-actions github-actions Bot added the type/fix PR title type: fix (set automatically) label Nov 15, 2026
@Aryapatel-007
Aryapatel-007 marked this pull request as ready for review November 15, 2026 16:24

@ariostas ariostas left a comment

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 🤖

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.

Comment thread src/uproot/writing/identify.py Outdated
if edges is not None:
return numpy.asarray(edges() if callable(edges) else edges)

if len(axis) == 0 or not isinstance(axis[0], tuple):

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 🤖

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.

Comment thread src/uproot/writing/identify.py Outdated
fXmin=_axis_edges(axis)[0],
fXmax=_axis_edges(axis)[-1],
fXbins=_fXbins_maybe_regular(axis, boost_histogram),
fLabels=_fLabels_maybe_categorical(axis, boost_histogram),

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 🤖

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 recovered

Before 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.

Comment thread src/uproot/writing/identify.py Outdated
fNbins=len(axis),
fXmin=axis.edges[0],
fXmax=axis.edges[-1],
fXmin=_axis_edges(axis)[0],

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 🤖

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.

Comment thread src/uproot/writing/identify.py Outdated
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])

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 🤖

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).

Comment thread src/uproot/writing/identify.py Outdated
"""
edges = getattr(axis, "edges", None)
if edges is not None:
return numpy.asarray(edges() if callable(edges) else edges)

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 🤖

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

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_....

@ariostas

Copy link
Copy Markdown
Member

🤖 AI text below 🤖

A follow-up on the approach. I think _axis_edges should decide based on whether the histogram is a boost-histogram, rather than on whether the axis has an .edges attribute. .edges isn't part of the protocol, and when an axis isn't from boost-histogram it doesn't necessarily mean a flat array of edges. For example, uhi's own reference implementation stores .edges as an N×2 array of (lower, upper) pairs, so it can't be written, either on main or with this PR:

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-dimensional

This isn't a regression, but checking .edges first keeps the problem. Also, the callable(edges) case doesn't seem reachable: uproot's own histograms are handled earlier by the isinstance(obj, uproot.model.Model) branch.

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 _to_fLabels would be the second half of the current _fLabels_maybe_categorical (the THashList and fUniqueID part), split out. to_TAxis, _fXbins_maybe_regular and the _root_stats_* calls would then take these precomputed edges instead of the axis. This would address most of the review comments in one change:

  • Discrete and continuous axes are told apart by traits.discrete, which is the protocol's own flag, so pairs given as lists or arrays give correct edges.
  • Discrete protocol axes keep their labels.
  • The edges are computed once per axis and always as float64.
  • uhi's NumPyPlottableHistogram can be written too.
  • The edit to the MEAN branch isn't needed anymore.

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

codecov Bot commented Nov 16, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (71fbf03) to head (8a08c2a).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
Files with missing lines Coverage Δ
src/uproot/writing/identify.py 100.00% <100.00%> (ø)

... and 1 file with indirect coverage changes

@ariostas ariostas added this to the v5.7.8 milestone Nov 16, 2026
Aryapatel-007 and others added 3 commits November 20, 2026 12:21
… 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

@ariostas ariostas left a comment

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.

Thank you, @Aryapatel-007!

@ariostas
ariostas enabled auto-merge (squash) November 20, 2026 12:51
@ariostas
ariostas merged commit 04d392a into scikit-hep:main Nov 20, 2026
21 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

type/fix PR title type: fix (set automatically)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Usage of non-PlottableHistogram attributes edges in to_writeable

2 participants