root icon indicating copy to clipboard operation
root copied to clipboard

`RooPlot::chiSquare` returns `NaN` with `Expected` data errors due to division by zero

Open AlkaidCheng opened this issue 8 months ago • 9 comments

Check duplicate issues.

  • [ ] Checked for duplicates

Description

Description

Calculating the chi2 via RooPlot::chiSquare on data plotted with RooFit::DataError(RooAbsData::Expected) returns NaN. Because RooPlot::chiSquare only supports Neyman-style chi2, the behavior for Expected errors is undefined and causes a silent division by zero.

Reproducer

from array import array
import ROOT

bin_edge = [0., 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.5,
            0.55, 0.6, 0.65, 0.7, 0.75, 0.8, 0.85, 0.9, 0.95, 1.]
bin_content = [0, 0, 0, 0, 0, 1, 3, 16, 17, 14, 18, 18, 7, 5, 1, 0, 0, 0, 0, 0]

h = ROOT.TH1D("h", "h", len(bin_edge) - 1, array("d", bin_edge))
for i, val in enumerate(bin_content):
    h.SetBinContent(i + 1, val)
h.Sumw2(ROOT.kFALSE)

x = ROOT.RooRealVar("X", "x", 0.0, 1.0)
x.setBins(len(bin_edge) - 1)
data = ROOT.RooDataHist("dh", "dh", ROOT.RooArgList(x), h)

mu = ROOT.RooRealVar("mu", "mu", 0.5, 0.0, 1.0)
sig = ROOT.RooRealVar("sigma", "sigma", 0.1, 0.01, 0.5)
pdf = ROOT.RooGaussian("gauss", "gauss", x, mu, sig)
pdf.fitTo(data)

# Test both error types
for err_type, err_name in [(ROOT.RooAbsData.Poisson, "Poisson"), (ROOT.RooAbsData.Expected, "Expected")]:
    frame = x.frame()
    data.plotOn(frame, ROOT.RooFit.DataError(err_type), ROOT.RooFit.Name("h_data"))
    pdf.plotOn(frame, ROOT.RooFit.Name("p_curve"))
    chi2 = frame.chiSquare("p_curve", "h_data", 0)
    print(f"chi2 with {err_name} data error = {chi2}")

Output:

chi2 with Poisson data error = 0.590340854118924
chi2 with Expected data error = nan

Root Cause

  1. Zero Bin Errors: RooPlot defaults to SumW2 for RooHist if error_type != Poisson (RooHist.cxx#L236), yielding zero errors for unweighted data.
  2. Missing Safety Check: RooCurve::chiSquare divides by these errors without checking for zeros (RooCurve.cxx#L563), causing the NaN.

Proposed Solutions

  • Option 1: Raise an error if error_type = Expected is used during RooAbsData::plotOn.
  • Option 2: Fall back to Poisson errors and emit a RooFit::Warning.

Reproducer

See above

ROOT version

6.38.00

Installation method

conda

Operating system

Linux

Additional context

No response

AlkaidCheng avatar Mar 26 '26 08:03 AlkaidCheng

Thanks for reporting this! The more examples of RooPlot::chiSquare() I have where it behaves strange, the better. I think it would be nice to collect enough reasons to finally deprecate it, making RooAbsReal::createChi2() the one single entry point for chi2 test statistics in RooFit.

The RooPlot::chiSquare() documentation is extremely sparse:

Calculate and return reduced chi-squared between a curve and a histogram.

Adding to the problem that the definition unexpectedly depends on the data error, and the other problem that it doesn't evaluate the pdf directly but interpolates the plotted points, I see now a pretty fundamental problem.

If by default it uses the Poisson errors from the data, then what this function returns is some kind of chi-square with asymmetric Poisson confidence interface denominator, which is pretty ad hoc and I don't see it recommended anywhere. In fact it's an awkward chimera between the chi2 test and the more correct G-test based on the actual likelihood ratio. It still uses the chi-square approximation, but with a better approximation of the errors for the low-stats case from this Poisson intervals. But why not do g-test directly at this point and give a true Poisson-based tests statistic? People almost always plot true Poissonian data anyway.

So I would actually like to deprecate RooPlot::chiSquare() at this point. Would that be okay for you?

Optimally, we need to provide an alternative to people can get a quick chi-square distributed summary statistic from their plot, which is better than the current black box RooPlot::chiSquare(). I'm not sure if chiSquare() should be deprecated before we have implemented such an alternative, but at this point I actually think it should be deprecated ASAP. It's just too confusing.

guitargeek avatar Mar 26 '26 10:03 guitargeek

Actually what we want is the Poisson deviance, like in the example on Wikipedia: https://en.wikipedia.org/wiki/Deviance_(statistics)

Something like RooPLot::goodnessOfFit(std::string const & type), and then we implement something reasonable and well documented, for different statistics like goodnessOfFit("deviance") (the default) or goodnessOfFit("pearson"). Maybe even the old behaviour like goodnessOfFit("crazy_custom_chi_square") 😆

Or maybe just the "deviance" for now, if people don't explicitly request any chi-square approximation. In the end, people just want to get a number from their plot where "close to one means good", so why have multiple options when the true likelihood deviance is the best and always correct for Poisson data from counting experiments.

guitargeek avatar Mar 26 '26 10:03 guitargeek

@AlkaidCheng, what do you think about this plan?

guitargeek avatar Mar 26 '26 10:03 guitargeek

Hi @guitargeek , thanks for the detailed reply! I am all for deprecating RooPlot::chiSquare because:

  1. It maps the pdf into a curve and does interpolation of the bin edges to get the bin center. This is just completely counter intuitive and you basically always get a wrong value at the edge.
  2. It returns the chi2 / ndf by default which is also very confusing and counter intuitive.

Nevertheless, I believe there are still some legacy analysis codes that uses the RooPlot::chiSquare approach which could be breaking.

AlkaidCheng avatar Mar 26 '26 10:03 AlkaidCheng

As to whether RooAbsReal::createChi2 is the best I am not completely sure as it is limited to Neyman or Pearson style chi2. There's another way of getting the chi2 which uses the Baker-Cousin chi2 from RooFitResult, which I think could be even more robust. If RooAbsReal::createChi2 can support Baker-Cousin chi2, this would be perfect.

AlkaidCheng avatar Mar 26 '26 10:03 AlkaidCheng

Sure, it will be deprecated but only removed in ROOT 7. But I think in the end, people will be happy about a drop-in replacement that is statistically more correct

guitargeek avatar Mar 26 '26 10:03 guitargeek

And now that this thread became a catch-all for ideas: per-bin Poisson deviances would also be the right replacement for pulls

guitargeek avatar Mar 26 '26 10:03 guitargeek

Related to our discussion, there is something else that I wanted to do for years, and I think the time is right now:

  • https://github.com/root-project/root/pull/21703

guitargeek avatar Mar 26 '26 14:03 guitargeek

Hi @guitargeek , I have a opened a PR addressing this by introducing a small guard for zero bin errors. It includes a user warning and it also skips that iteration to avoid undefined behaviour.

This is the pull request: #21710

AyachiMishra avatar Mar 26 '26 16:03 AyachiMishra