Skip to content

fix: TProfile reading, writing and to_hist fixes - #1766

Open
ariostas wants to merge 33 commits into
mainfrom
fix-tprofile-issues
Open

ariostas wants to merge 33 commits into
mainfrom
fix-tprofile-issues

Conversation

@ariostas

@ariostas ariostas commented Oct 19, 2026 •

Copy link
Copy Markdown
Member

🤖 AI text below 🤖

This fixes a set of TProfile problems found by comparing Uproot with ROOT 6.40 bin by bin, for reading, to_hist, hist → TProfile writing, and ROOT → Uproot → ROOT round trips. There is one commit per group of fixes, so it can be reviewed commit by commit. Fixes for PyROOT conversion and for other histogram writing problems found along the way are in #1768 and #1769 (which is stacked on this PR).

1. NaN sum of squared weights in empty bins (to_boost)
sum_of_weights_squared was computed as sumw**2 / neff, which is 0/0 in empty bins of weighted profiles. That NaN was then written to fBinSumw2, and in ROOT Add/Merge/hadd gave infinite errors. It now comes straight from fBinSumw2, which is mathematically the same value.

2. hist → TProfile writing

  • fTsumwx/fTsumwx2 included the flow bins, so ROOT's GetMean(1)/GetStdDev(1) were wrong.
  • Integer axes and axes without flow bins crashed. Padding now follows the axis's underflow/overflow traits.
  • Mean storage wrote a full fBinSumw2, so it read back as WeightedMean. It now writes an empty one, as ROOT does for unweighted profiles.
  • fEntries now includes the flow bins.
  • Non-dict metadata no longer crashes.
  • Non-boost kind="MEAN" histograms now raise a clear TypeError (the old branch was dead code that raised AttributeError).
  • fErrorMode is kept in the to_hist metadata and restored when writing.
  • The docs now describe the limits of writing Mean/WeightedMean storage.

Written profiles now match equivalently filled ROOT profiles exactly, both per bin and in the global stats. This was checked for Regular, Variable, Integer, no-flow, IntCategory, StrCategory and Boolean axes, each with Mean and WeightedMean storage.

3. Axis labels ordered by bin number (also affects TH1/TH2/TH3)
ROOT stores labels in the order they were set, with the bin number in fUniqueID. Axes labeled out of order were silently mislabeled, and partially labeled axes crashed to_hist. Labels are now ordered by bin number, and partially labeled axes are treated as unlabeled, with a warning in to_hist that their labels are dropped. (ROOT leaves an axis partially labeled when it's filled with more labels than it has bins, which is the usual case for cutflows.)

4. ⚠️ Behavior change: errors()/variances() use the stored error option by default
The default error_mode is now None, meaning "use fErrorMode", which matches ROOT's GetBinError for TProfile, TProfile2D and TProfile3D. Profiles created with the "s" or "g" option previously gave different errors than ROOT by default. With the "i" option they differed only in bins whose values are all identical (for example, single-entry bins), since "i" otherwise gives the error on the mean. error_mode="" gives exactly the old behavior.

The docstrings now explain how ROOT's conventions differ from boost-histogram's variances() (for example, after to_hist), which is the remaining difference discussed in #1148:

  • boost-histogram applies Bessel's correction, and gives NaN for single-entry bins where ROOT gives 0.
  • With weights, boost-histogram divides the spread by the sum of weights, whereas ROOT divides by the effective number of entries. They agree only when all weights are 1.
  • boost-histogram always gives the error on the mean. For profiles with the "s", "i" or "g" option, errors() now follows that option, but to_hist().variances() does not.

5. Edge cases

  • to_boost no longer clamps the sum of squared deviations at 0. It can legitimately be negative with negative weights, and clamping changed the errors after a round trip. Only round-off is clamped now.
  • profile == profile no longer raises AttributeError.
  • A missing fBinSumw2 (TProfile class version 5 or older, from ROOT < 5.26) is treated as empty, as ROOT does.
  • Option "g" gives NaN errors for a negative sum of weights, as in ROOT, without a RuntimeWarning, and histograms with NaN bins are equal to themselves.
  • metadata["fErrorMode"] can be a string ("s", "i", "g"), as for errors(error_mode=...); an invalid one raises a clear ValueError.

6. Flow bins, stale fEntries and labeled underflow (these were also on main)

  • hist → TH1/TH2/TH3 writing (COUNT storage) had the same flow-bin problem as profiles: an axis with only one flow bin (for example Integer(underflow=False) or StrCategory) lost the flow contents. Missing flow bins are now padded with zeros using the axis traits for every boost-histogram or hist object, histogram or profile.
  • fEntries from to_hist metadata was written back even after the profile was filled or added to, so for example a + b was written with a's fEntries. to_hist now also records the total sum of weights in metadata["fEntries_sumw"], and the stored fEntries is only used while the bins still have that total. Otherwise it is recomputed. A user-set fEntries without fEntries_sumw is used as given.
  • boost-histogram category axes have no underflow bin, so to_hist can't keep a labeled axis's underflow. ROOT only fills it from numerical fills (unknown labels go to overflow). to_hist now warns when that bin isn't empty, instead of silently dropping it.
  • TAxis bin labels are cached instead of being rebuilt on every access, and Profile.weighted replaces three copies of the same code.

7. Global statistics, zero-weight bins and other additions

  • to_hist also keeps ROOT's fTsumw, fTsumw2, fTsumwx and fTsumwx2 in the metadata, and writing reuses them while the bins still give the same fTsumw. Before, the x sums were recomputed from bin centers, which changed GetMean(1)/GetStdDev(1), and fTsumw2 was wrong for a profile merged with a weighted one. ROOT's statistics are not reused if they were already out of date (SetBinContent, an uneven Rebin, ...), included the flow bins (SetStatOverflows), or were for a labeled axis whose range isn't [0, nbins]. Round trips now match ROOT exactly in all of these cases (checked after Merge, hadd, Rebin, Scale and with negative weights).
  • WeightedMean bins whose weights sum to zero (possible with negative weights) were written as NaN, which also made GetMean(2) NaN. They're written as empty, and to_hist warns when a ROOT profile has such a bin with content, which boost-histogram can't represent.
  • The stale-fEntries check no longer misses changes in the sum of weights smaller than 1e-8.
  • New to_numpy for TProfile, TProfile2D and TProfile3D (bin means and edges).
  • Uproot's warnings about dropped labels, underflow and zero-weight bins point at the user's code instead of Uproot's.

The PR's tests are consolidated in tests/test_1766_tprofile_reading.py, tests/test_1766_tprofile_writing.py and tests/test_1766_axes_and_flow.py, which include comparisons with ROOT for weighted and negative-weight 1D/2D/3D profiles with every error option.

Not included: TProfile2D/3D to_boost (#1681) and 2D/3D hist → profile writing (#1534). #1681 will need the same fBinSumw2 change as fix 1.

This PR was written with significant AI assistance (Claude Code).

TProfile.to_boost computed sum_of_weights_squared as sum(w)**2 / neff,
which is 0/0 in empty bins of weighted profiles. Writing the result back
put NaN into fBinSumw2, which breaks Add/Merge in ROOT. Since
neff = sum(w)**2 / fBinSumw2, use fBinSumw2 directly.

Assisted-by: Claude Code:claude-opus-5-5
- pad the flow bins based on the axis's underflow/overflow traits, so
  Integer axes and axes without flow bins no longer crash
- exclude the flow bins from fTsumwx/fTsumwx2, like the other statistics
- write an empty fBinSumw2 for Mean storage, as ROOT does for unweighted
  profiles, so that it reads back as Mean instead of WeightedMean
- include the flow bins in fEntries
- accept non-dict metadata
- raise a clear TypeError for MEAN histograms that aren't boost-histogram
  or hist objects, instead of an AttributeError
- keep fErrorMode in the to_hist metadata and restore it when writing
- document the limitations of writing Mean/WeightedMean storage

Assisted-by: Claude Code:claude-opus-5-5
ROOT keeps an axis's labels in the order they were set, with each label's
bin number in its fUniqueID. Uproot assumed insertion order, so axes
labeled out of order were mislabeled in labels(), iteration and to_hist,
and to_hist crashed on partially labeled axes. Labels are now ordered by
bin number, and axes that aren't fully labeled are treated as unlabeled.

Assisted-by: Claude Code:claude-opus-5-5
Profile.errors() and Profile.variances() now default to error_mode=None,
which uses the profile's own fErrorMode, as ROOT's GetBinError does.
Previously they always defaulted to the error on the mean, so profiles
created with the "s", "i" or "g" option gave different errors than ROOT.
Pass error_mode="" to get the old behavior.

Also document how these conventions differ from boost-histogram's
variances() after to_hist.

Assisted-by: Claude Code:claude-opus-5-5
- don't clamp the sum of squared deviations at 0 in to_boost: it can be
  legitimately negative with negative weights (ROOT takes its absolute
  value), so clamping changed the errors after a round trip. Only
  round-off residues are clamped now.
- add Profile._values_variances, so profile == profile no longer raises
- treat a missing fBinSumw2 (TProfile class version 5 or older, from
  ROOT < 5.26) as empty, as ROOT does, instead of raising KeyInFileError

Assisted-by: Claude Code:claude-opus-5-5
@github-actions github-actions Bot added the type/fix PR title type: fix (set automatically) label Oct 19, 2026
@codecov

codecov Bot commented Oct 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (7e49a5a) to head (7db56a0).
✅ All tests successful. No failed tests found.

Additional details and impacted files
Files with missing lines Coverage Δ
src/uproot/_util.py 100.00% <100.00%> (ø)
src/uproot/behaviors/TAxis.py 100.00% <100.00%> (ø)
src/uproot/behaviors/TH1.py 100.00% <100.00%> (ø)
src/uproot/behaviors/TProfile.py 100.00% <100.00%> (ø)
src/uproot/behaviors/TProfile2D.py 100.00% <ø> (ø)
src/uproot/behaviors/TProfile3D.py 100.00% <ø> (ø)
src/uproot/writing/identify.py 100.00% <100.00%> (ø)

- Pad missing underflow/overflow bins by axis traits for every boost-histogram
  or hist object, not just Mean storage, so COUNT histograms with only one flow
  bin (Integer(underflow=False), StrCategory, ...) keep their flow contents.
- Record the total sum of weights with fEntries in to_hist's metadata, and
  only write that fEntries back if the bins still have that total; profiles
  filled or added after to_hist get a recomputed fEntries.
- Warn when to_hist drops a non-empty underflow bin of a labeled axis, which
  boost-histogram category axes can't represent.
- Cache TAxis bin labels, and share one Profile.weighted.

Assisted-by: Claude Code:claude-opus-5-5
With weights, boost-histogram divides the spread by the sum of weights rather
than the effective number of entries, and it ignores the error option.

Assisted-by: Claude Code:claude-opus-5-5
…ted 2D/3D errors with ROOT

Merge the six test_1766 files into reading, writing, and axes/flow files,
parametrizing where tests only differed in their inputs. The PyROOT error
comparison now also covers weighted profiles and checks values and
effective entries.

Assisted-by: Claude Code:claude-opus-5-5
boost-histogram's mean is undefined (-inf) in a WeightedMean bin whose
weights sum to zero, which happens with negative weights. That NaN was
written to fArray and fSumw2, and from there into fTsumwy/fTsumwy2, so
ROOT's GetMean(2) was NaN. Write those bins as empty instead.

Assisted-by: Claude Code:claude-opus-5-5
…tries

numpy.isclose also has an absolute tolerance of 1e-8 by default, so adding
small weights after to_hist kept a stale fEntries.

Assisted-by: Claude Code:claude-opus-5-5
Writing a hist with metadata["fErrorMode"] = "s" failed with a struct.error.
Map the option through the same table that errors() and variances() use,
and raise a clear ValueError for unknown options.

Assisted-by: Claude Code:claude-opus-5-5
ROOT's error for option "g" is 1/sqrt(sum of weights), which is NaN for a
negative sum. Now that errors() follows fErrorMode by default, computing it
raised a RuntimeWarning, and profile == profile was False. Silence the
warning, and compare NaN bins as equal in Histogram.__eq__.

The PyROOT error comparison now also covers negative weights.

Assisted-by: Claude Code:claude-opus-5-5
When a labeled axis is filled with a new label, ROOT doubles its bins and
leaves the new ones unlabeled, which is the usual outcome for cutflows filled
by label. Such axes become numerical axes in to_hist, which silently dropped
their labels; now this warns.

Assisted-by: Claude Code:claude-opus-5-5
…um to zero

With negative weights, a ROOT profile bin can have a zero sum of weights but
a nonzero sum of weighted values. boost-histogram stores means, so it can't
represent that sum, and it was silently lost (wrong after ROOT Add/Merge/hadd
of the round-tripped profile). Now this warns.

Assisted-by: Claude Code:claude-opus-5-5
… unchanged

boost-histogram only knows bin centers and doesn't track ROOT's global sums,
so writing a profile back after to_hist recomputed fTsumwx/fTsumwx2 from bin
centers (which changed ROOT's GetMean(1)/GetStdDev(1)) and fTsumw2 from the
bins (which is wrong for a profile merged with a weighted one, which has no
fBinSumw2). Keep them in the metadata with ROOT's fTsumw, and reuse them if
the bins still give that fTsumw, as for fEntries. ROOT's own fTsumw already
differs from the bins' if its statistics are out of date (SetBinContent,
SetBinEntries, an uneven Rebin, ...) or include the flow bins
(SetStatOverflows), so those fall back to the bin centers. The x sums aren't
kept for a labeled axis whose range isn't [0, nbins], which is written back as
[0, nbins].

Assisted-by: Claude Code:claude-opus-5-5
Profiles don't inherit TH1's behaviors, so they had no to_numpy. It returns
the bin means with the bin edges, like to_numpy of histograms.

Assisted-by: Claude Code:claude-opus-5-5
The warnings about dropped labels, underflow and zero-weight bins are raised
at different depths (to_hist, to_boost), so a fixed stacklevel pointed into
Uproot. Attribute them to the first caller outside of Uproot instead.

Assisted-by: Claude Code:claude-opus-5-5
# Conflicts:
#	src/uproot/_util.py
#	src/uproot/behaviors/TAxis.py
#	src/uproot/behaviors/TProfile.py
#	src/uproot/writing/identify.py
The writer kept ROOT's global statistics only if ROOT's fTsumw matched the
bins' sum of weights to a relative 1e-12, which round-off can exceed with
many fills of weights that cancel; the x-statistics were then silently
replaced by bin-center estimates. Check that ROOT's statistics go with the
bins when reading, with a tolerance for round-off, and record the bins'
sums of weights (with math.fsum, which doesn't depend on the order of
summation) for the writer to compare exactly.

Assisted-by: Claude Code:claude-opus-5-5
A negative sum of squared deviations (possible with negative weights, or
after SetBinContent/SetBinEntries in ROOT) is kept as it is in to_boost, so
that writing back to ROOT gives the same sums, but boost-histogram's
variances() are then negative or NaN in those bins, while ROOT takes the
absolute value. Warn about it, like the other lossy parts of to_boost.

Assisted-by: Claude Code:claude-opus-5-5
boost-histogram can't keep the sum of weighted values of a bin whose
weights sum to zero (its mean is undefined), so such bins are written as
zero, unlike what ROOT would keep. Warn about it, as to_hist does in the
other direction.

Assisted-by: Claude Code:claude-opus-5-5
…rs say otherwise

If every label had a valid bin number but some bin was unlabeled (two
labels with the same bin number), the labels fell back to the order they
were set, ignoring their bin numbers. That fallback is now only for labels
without usable bin numbers, and the warning about dropped labels counts
labeled bins, not labels.

Assisted-by: Claude Code:claude-opus-5-5
Assisted-by: Claude Code:claude-opus-5-5
Assisted-by: Claude Code:claude-opus-5-5
…istics

The writer reused ROOT's fEntries, fTsumw, fTsumw2, fTsumwx and fTsumwx2
from the to_hist metadata if the bins' total sum of weights was unchanged,
but filling with weights that cancel, or reordering categories, changes the
bins without changing the total, so stale statistics were written. Record a
fingerprint of each bin's sums of weights and squared weights and of the
axis instead, and compare that.

Assisted-by: Claude Code:claude-opus-5-5
When more than one label has a bin's number, the first one is the bin's
(the last one was), and a label without a valid bin number is ignored
instead of making all labels be taken in the order they were set.

Assisted-by: Claude Code:claude-opus-5-5
…le-like objects

Objects with the members of an Uproot TProfile were written with
fErrorMode 0 and needed an fBinSumw2, which TProfile class versions before
6 don't have. Also let to_hist work without an fErrorMode, like errors().

Assisted-by: Claude Code:claude-opus-5-5
…metadata

Including that statistics without a bins fingerprint, set by hand or by
older versions of Uproot, are written as they are.

Assisted-by: Claude Code:claude-opus-5-5
…ve variances

- boost-histogram's mean stays NaN after a bin's weights have summed to
  zero, even once they no longer do, so writing such a hist put NaN into
  the bin contents, fSumw2, fTsumwy and fTsumwy2 without a warning (and
  silently zeroed its sum of squared deviations). Those bins' contents are
  lost, so write them as empty and warn.
- the round-off clamped in to_boost's sums of squared deviations grows
  with the number of fills that ROOT summed, so with ~1e7 fills a fixed
  relative 1e-10 was too small, giving unweighted profiles negative
  variances and a warning about negative weights. Scale it with the
  effective number of entries, and only mention negative weights in the
  warning for weighted profiles.

Assisted-by: Claude Code:claude-opus-5-5
Assisted-by: Claude Code:claude-opus-5-5
ROOT's error options are case-insensitive, but errors()/variances() and
the fErrorMode in a hist's metadata only accepted "s", "i" and "g", so
"S", "I" and "G" raised ValueError (when writing, even if the metadata
was otherwise unused).

Assisted-by: Claude Code:claude-opus-5-5
Parametrize tests that differed only in their inputs (complete and
incomplete axis labels, sums of squared deviations and their round-off,
undefined means, ROOT statistics round-off), build the test profiles with
one helper, and read the axes' flow bins from their traits.

Assisted-by: Claude Code:claude-opus-5-5
@ariostas
ariostas marked this pull request as ready for review November 25, 2026 22:34
@ariostas
ariostas requested a review from ianna November 25, 2026 22:35

This branch has not been deployed

No deployments
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.

1 participant