Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooHist.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * *
9 * Copyright (c) 2000-2005, Regents of the University of California *
10 * and Stanford University. All rights reserved. *
11 * *
12 * Redistribution and use in source and binary forms, *
13 * with or without modification, are permitted according to the terms *
14 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15 *****************************************************************************/
16
17/**
18\file RooHist.cxx
19\class RooHist
20\ingroup Roofitcore
21
22Graphical representation of binned data based on the
23TGraphAsymmErrors class. Error bars are calculated using either Poisson
24or Binomial statistics. A RooHist is used to represent histograms in
25a RooPlot.
26**/
27
28#include "RooHist.h"
29
30#include "RooAbsRealLValue.h"
31#include "RooUniformBinning.h"
32#include "RooHistError.h"
33#include "RooCurve.h"
34#include "RooMsgService.h"
35#include "RooProduct.h"
36#include "RooConstVar.h"
37
38#include "TH1.h"
39#include "Riostream.h"
40#include <iomanip>
41
42
43
44////////////////////////////////////////////////////////////////////////////////
45/// Create an empty histogram that can be filled with the addBin()
46/// and addAsymmetryBin() methods. Use the optional parameter to
47/// specify the confidence level in units of sigma to use for
48/// calculating error bars. The nominal bin width specifies the
49/// default used by addBin(), and is used to set the relative
50/// normalization of bins with different widths.
51
52RooHist::RooHist(double nominalBinWidth, double nSigma, double /*xErrorFrac*/, double /*scaleFactor*/)
53 : _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
54{
55 initialize();
56}
57
58
59////////////////////////////////////////////////////////////////////////////////
60/// Create a histogram from the contents of the specified TH1 object
61/// which may have fixed or variable bin widths. Error bars are
62/// calculated using Poisson statistics. Prints a warning and rounds
63/// any bins with non-integer contents. Use the optional parameter to
64/// specify the confidence level in units of sigma to use for
65/// calculating error bars. The nominal bin width specifies the
66/// default used by addBin(), and is used to set the relative
67/// normalization of bins with different widths. If not set, the
68/// nominal bin width is calculated as range/nbins.
69
71 bool correctForBinWidth, double scaleFactor)
72 : _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
73{
74 if(etype == RooAbsData::Poisson && correctForBinWidth == false) {
75 throw std::invalid_argument(
76 "To ensure consistent behavior prior releases, it's not possible to create a RooHist from a TH1 with no bin width correction when using Poisson errors.");
77 }
78
79 initialize();
80 // copy the input histogram's name and title
81 SetName(data.GetName());
82 SetTitle(data.GetTitle());
83 // calculate our nominal bin width if necessary
84 if(_nominalBinWidth == 0) {
85 const TAxis *axis= ((TH1&)data).GetXaxis();
86 if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins();
87 }
88 setYAxisLabel(data.GetYaxis()->GetTitle());
89
90 // initialize our contents from the input histogram's contents
91 Int_t nbin= data.GetNbinsX();
92 for(Int_t bin= 1; bin <= nbin; bin++) {
93 Axis_t x= data.GetBinCenter(bin);
94 Stat_t y= data.GetBinContent(bin);
95 Stat_t dy = data.GetBinError(bin) ;
96 if (etype==RooAbsData::Poisson) {
97 addBin(x,y,data.GetBinWidth(bin),xErrorFrac,scaleFactor);
98 } else if (etype==RooAbsData::SumW2) {
99 addBinWithError(x,y,dy,dy,data.GetBinWidth(bin),xErrorFrac,correctForBinWidth,scaleFactor);
100 } else {
101 addBinWithError(x,y,0,0,data.GetBinWidth(bin),xErrorFrac,correctForBinWidth,scaleFactor);
102 }
103 }
104 // add over/underflow bins to our event count
105 _entries+= data.GetBinContent(0) + data.GetBinContent(nbin+1);
106}
107
108
109
110////////////////////////////////////////////////////////////////////////////////
111/// Create a histogram from the asymmetry between the specified TH1 objects
112/// which may have fixed or variable bin widths, but which must both have
113/// the same binning. The asymmetry is calculated as (1-2)/(1+2). Error bars are
114/// calculated using Binomial statistics. Prints a warning and rounds
115/// any bins with non-integer contents. Use the optional parameter to
116/// specify the confidence level in units of sigma to use for
117/// calculating error bars. The nominal bin width specifies the
118/// default used by addAsymmetryBin(), and is used to set the relative
119/// normalization of bins with different widths. If not set, the
120/// nominal bin width is calculated as range/nbins.
121
123 double xErrorFrac, bool efficiency, double scaleFactor)
124 : _nominalBinWidth(nominalBinWidth), _nSigma(nSigma), _rawEntries(-1)
125{
126 initialize();
127 // copy the first input histogram's name and title
128 SetName(data1.GetName());
129 SetTitle(data1.GetTitle());
130 // calculate our nominal bin width if necessary
131 if(_nominalBinWidth == 0) {
132 const TAxis *axis= data1.GetXaxis();
133 if(axis->GetNbins() > 0) _nominalBinWidth= (axis->GetXmax() - axis->GetXmin())/axis->GetNbins();
134 }
135
136 if (!efficiency) {
137 setYAxisLabel(Form("Asymmetry (%s - %s)/(%s + %s)",
138 data1.GetName(),data2.GetName(),data1.GetName(),data2.GetName()));
139 } else {
140 setYAxisLabel(Form("Efficiency (%s)/(%s + %s)",
141 data1.GetName(),data1.GetName(),data2.GetName()));
142 }
143 // initialize our contents from the input histogram contents
144 Int_t nbin= data1.GetNbinsX();
145 if(data2.GetNbinsX() != nbin) {
146 coutE(InputArguments) << "RooHist::RooHist: histograms have different number of bins" << std::endl;
147 return;
148 }
149 for(Int_t bin= 1; bin <= nbin; bin++) {
150 Axis_t x= data1.GetBinCenter(bin);
151 if(std::abs(data2.GetBinCenter(bin)-x)>1e-10) {
152 coutW(InputArguments) << "RooHist::RooHist: histograms have different centers for bin " << bin << std::endl;
153 }
154 Stat_t y1= data1.GetBinContent(bin);
155 Stat_t y2= data2.GetBinContent(bin);
156 if (!efficiency) {
157
158 if (etype==RooAbsData::Poisson) {
159 addAsymmetryBin(x,roundBin(y1),roundBin(y2),data1.GetBinWidth(bin),xErrorFrac,scaleFactor);
160 } else if (etype==RooAbsData::SumW2) {
161 Stat_t dy1= data1.GetBinError(bin);
162 Stat_t dy2= data2.GetBinError(bin);
163 addAsymmetryBinWithError(x,y1,y2,dy1,dy2,data1.GetBinWidth(bin),xErrorFrac,scaleFactor);
164 } else {
165 addAsymmetryBinWithError(x,y1,y2,0,0,data1.GetBinWidth(bin),xErrorFrac,scaleFactor);
166 }
167
168 } else {
169
170 if (etype==RooAbsData::Poisson) {
171 addEfficiencyBin(x,roundBin(y1),roundBin(y2),data1.GetBinWidth(bin),xErrorFrac,scaleFactor);
172 } else if (etype==RooAbsData::SumW2) {
173 Stat_t dy1= data1.GetBinError(bin);
174 Stat_t dy2= data2.GetBinError(bin);
175 addEfficiencyBinWithError(x,y1,y2,dy1,dy2,data1.GetBinWidth(bin),xErrorFrac,scaleFactor);
176 } else {
177 addEfficiencyBinWithError(x,y1,y2,0,0,data1.GetBinWidth(bin),xErrorFrac,scaleFactor);
178 }
179
180 }
181
182 }
183 // we do not have a meaningful number of entries
184 _entries= -1;
185}
186
187
188
189////////////////////////////////////////////////////////////////////////////////
190/// Create histogram as sum of two existing histograms. If Poisson errors are selected the histograms are
191/// added and Poisson confidence intervals are calculated for the summed content. If wgt1 and wgt2 are not
192/// 1 in this mode, a warning message is printed. If SumW2 errors are selected the histograms are added
193/// and the histograms errors are added in quadrature, taking the weights into account.
194
196 double xErrorFrac)
197 : _nominalBinWidth(hist1._nominalBinWidth), _nSigma(hist1._nSigma), _rawEntries(-1)
198{
199 // Initialize the histogram
200 initialize() ;
201
202 // Copy all non-content properties from hist1
203 SetName(hist1.GetName()) ;
204 SetTitle(hist1.GetTitle()) ;
205
206 setYAxisLabel(hist1.getYAxisLabel()) ;
207
208 if (!hist1.hasIdenticalBinning(hist2)) {
209 coutE(InputArguments) << "RooHist::RooHist input histograms have incompatible binning, combined histogram will remain empty" << std::endl ;
210 return ;
211 }
212
213 if (etype==RooAbsData::Poisson) {
214 // Add histograms with Poisson errors
215
216 // Issue warning if weights are not 1
217 if (wgt1!=1.0 || wgt2 != 1.0) {
218 coutW(InputArguments) << "RooHist::RooHist: WARNING: Poisson errors of weighted sum of two histograms is not well defined! " << std::endl
219 << " Summed histogram bins will rounded to nearest integer for Poisson confidence interval calculation" << std::endl ;
220 }
221
222 // Add histograms, calculate Poisson confidence interval on sum value
223 Int_t i;
224 Int_t n = hist1.GetN();
225 for(i=0 ; i<n ; i++) {
226 double x1;
227 double y1;
228 double x2;
229 double y2;
230 double dx1;
231 hist1.GetPoint(i,x1,y1) ;
232 dx1 = hist1.GetErrorX(i) ;
233 hist2.GetPoint(i,x2,y2) ;
235 }
236
237 } else {
238 // Add histograms with SumW2 errors
239
240 // Add histograms, calculate combined sum-of-weights error
241 Int_t i;
242 Int_t n = hist1.GetN();
243 for(i=0 ; i<n ; i++) {
244 double x1;
245 double y1;
246 double x2;
247 double y2;
248 double dx1;
249 double dy1;
250 double dy2;
251 hist1.GetPoint(i,x1,y1) ;
252 dx1 = hist1.GetErrorX(i) ;
253 dy1 = hist1.GetErrorY(i) ;
254 dy2 = hist2.GetErrorY(i) ;
255 hist2.GetPoint(i,x2,y2) ;
256 double dy = sqrt(wgt1*wgt1*dy1*dy1+wgt2*wgt2*dy2*dy2) ;
258 }
259 }
260
261}
262
263
264////////////////////////////////////////////////////////////////////////////////
265/// Create histogram from a pdf or function. Errors are computed based on the fit result provided.
266///
267/// This signature is intended for unfolding/deconvolution scenarios,
268/// where a pdf is constructed as "data minus background" and is thus
269/// intended to be displayed as "data" (or at least data-like).
270/// Usage of this signature is triggered by the draw style "P" in RooAbsReal::plotOn.
271///
272/// More details.
273/// \param[in] f The function to be plotted.
274/// \param[in] x The variable on the x-axis
275/// \param[in] xErrorFrac Size of the error in x as a fraction of the bin width
276/// \param[in] scaleFactor arbitrary scaling of the y-values
277/// \param[in] normVars variables over which to normalize
278/// \param[in] fr fit result
279RooHist::RooHist(const RooAbsReal &f, RooAbsRealLValue &x, double xErrorFrac, double scaleFactor,
280 const RooArgSet *normVars, const RooFitResult *fr)
281 : _nSigma(1), _rawEntries(-1)
282{
283 // grab the function's name and title
284 SetName(f.GetName());
285 std::string title{f.GetTitle()};
286 SetTitle(title.c_str());
287 // append " ( [<funit> ][/ <xunit> ])" to our y-axis label if necessary
288 if(0 != strlen(f.getUnit()) || 0 != strlen(x.getUnit())) {
289 title += " ( ";
290 if(0 != strlen(f.getUnit())) {
291 title += f.getUnit();
292 title += " ";
293 }
294 if(0 != strlen(x.getUnit())) {
295 title += "/ ";
296 title += x.getUnit();
297 title += " ";
298 }
299 title += ")";
300 }
301 setYAxisLabel(title.c_str());
302
303 RooProduct scaledFunc{"scaled_func", "scaled_func", {f, RooFit::RooConst(scaleFactor)}};
304 std::unique_ptr<RooAbsFunc> funcPtr{scaledFunc.bindVars(x, normVars, true)};
305
306 // calculate the points to add to our curve. A variable with no binning
307 // explicitly set reports zero bins; in that case fall back to the historical
308 // default bin count for plotting, using a local binning so that the user's
309 // variable is not mutated.
310 const RooAbsBinning *xbinning = &x.getBinning();
311 std::unique_ptr<RooUniformBinning> defaultBinning;
312 if (x.numBins() == 0) {
313 defaultBinning = std::make_unique<RooUniformBinning>(x.getMin(), x.getMax(), RooAbsRealLValue::DefaultNBins);
314 xbinning = defaultBinning.get();
315 }
316 int xbins = xbinning->numBins();
317 RooArgSet nset;
318 if(normVars) nset.add(*normVars);
319 for(int i=0; i<xbins; ++i){
320 double xval = xbinning->binCenter(i);
321 double xwidth = xbinning->binWidth(i);
323 double yval = (*funcPtr)(&xval);
324 double yerr = std::sqrt(yval);
325 if(fr) yerr = f.getPropagatedError(*fr,nset);
327 _entries += yval;
328 }
329 _nominalBinWidth = 1.;
330}
331
332
333////////////////////////////////////////////////////////////////////////////////
334/// Perform common initialization for all constructors.
335
337{
339}
340
341
342////////////////////////////////////////////////////////////////////////////////
343/// Return the number of events of the dataset associated with this RooHist.
344/// This is the number of events in the RooHist itself, unless a different
345/// value was specified through setRawEntries()
346
348{
349 return (_rawEntries==-1 ? _entries : _rawEntries) ;
350}
351
352
353////////////////////////////////////////////////////////////////////////////////
354/// Calculate integral of histogram in given range
355
356double RooHist::getFitRangeNEvt(double xlo, double xhi) const
357{
358 double sum(0) ;
359 for (int i=0 ; i<GetN() ; i++) {
360 double x;
361 double y;
362
363 GetPoint(i,x,y) ;
364
365 if (x>=xlo && x<=xhi) {
366 // We have to use the original weights of the histogram, because the
367 // scaled points have nothing to do anymore with event weights in the
368 // case of non-uniform binning. For backwards compatibility with the
369 // RooHist version 1, we first need to check if the `_originalWeights`
370 // member is filled.
371 sum += _originalWeights.empty() ? y : _originalWeights[i];
372 }
373 }
374
375 if (_rawEntries!=-1) {
376 coutW(Plotting) << "RooHist::getFitRangeNEvt() WARNING: The number of normalisation events associated to histogram " << GetName() << " is not equal to number of events in this histogram."
377 << "\n\t\t This is due a cut being applied while plotting the data. Automatic normalisation over a sub-range of a plot variable assumes"
378 << "\n\t\t that the effect of that cut is uniform across the plot, which may be an incorrect assumption. To obtain a correct normalisation, it needs to be passed explicitly:"
379 << "\n\t\t\t data->plotOn(frame01,CutRange(\"SB1\"));"
380 << "\n\t\t\t const double nData = data->sumEntries(\"\", \"SB1\"); //or the cut string such as sumEntries(\"x > 0.\");"
381 << "\n\t\t\t model.plotOn(frame01, RooFit::Normalization(nData, RooAbsReal::NumEvent), ProjectionRange(\"SB1\"));" << std::endl ;
383 }
384
385 return sum ;
386}
387
388
389////////////////////////////////////////////////////////////////////////////////
390/// Return the nearest positive integer to the input value
391/// and print a warning if an adjustment is required.
392
394{
395 if(y < 0) {
396 coutW(Plotting) << fName << "::roundBin: rounding negative bin contents to zero: " << y << std::endl;
397 return 0;
398 }
399 Int_t n= (Int_t)(y+0.5);
400 if(std::abs(y-n)>1e-6) {
401 coutW(Plotting) << fName << "::roundBin: rounding non-integer bin contents: " << y << std::endl;
402 }
403 return n;
404}
405
406
407void RooHist::addPoint(Axis_t binCenter, double y, double yscale, double exlow, double exhigh, double eylow, double eyhigh)
408{
409 const int index = GetN();
410 SetPoint(index, binCenter, y*yscale);
411
412 // If the scale is negative, the low and high errors must be swapped
413 if(std::abs(yscale) < 0) {
414 std::swap(eylow, eyhigh);
415 }
416
417 SetPointError(index, exlow, exhigh, std::abs(yscale) * eylow, std::abs(yscale) * eyhigh);
418
421
422 // We also track the original weights of the histogram, because if we only
423 // have info on the scaled points it's not possible anymore to compute the
424 // number of events in a subrange of the RooHist.
425 _originalWeights.resize(index + 1);
427}
428
429
430////////////////////////////////////////////////////////////////////////////////
431/// Add a bin to this histogram with the specified integer bin contents
432/// and using an error bar calculated with Poisson statistics. The bin width
433/// is used to set the relative scale of bins with different widths.
434
435void RooHist::addBin(Axis_t binCenter, double n, double binWidth, double xErrorFrac, double scaleFactor)
436{
437 if (n<0) {
438 coutW(Plotting) << "RooHist::addBin(" << GetName() << ") WARNING: negative entry set to zero when Poisson error bars are requested" << std::endl ;
439 }
440
441 double scale= 1;
442 if(binWidth > 0) {
443 scale= _nominalBinWidth/binWidth;
444 }
445 _entries+= n;
446
447 // calculate Poisson errors for this bin
448 double ym;
449 double yp;
450 double dx(0.5 * binWidth);
451
452 if (std::abs((double)((n-Int_t(n))>1e-5))) {
453 // need interpolation
454 double ym1(0);
455 double yp1(0);
456 double ym2(0);
457 double yp2(0);
458 Int_t n1 = Int_t(n) ;
459 Int_t n2 = n1+1 ;
460 if(!RooHistError::instance().getPoissonInterval(n1,ym1,yp1,_nSigma) ||
461 !RooHistError::instance().getPoissonInterval(n2,ym2,yp2,_nSigma)) {
462 coutE(Plotting) << "RooHist::addBin: unable to add bin with " << n << " events" << std::endl;
463 }
464 ym = ym1 + (n-n1)*(ym2-ym1) ;
465 yp = yp1 + (n-n1)*(yp2-yp1) ;
466 coutW(Plotting) << "RooHist::addBin(" << GetName()
467 << ") WARNING: non-integer bin entry " << n << " with Poisson errors, interpolating between Poisson errors of adjacent integer" << std::endl ;
468 } else {
469 // integer case
470 if(!RooHistError::instance().getPoissonInterval(Int_t(n),ym,yp,_nSigma)) {
471 coutE(Plotting) << "RooHist::addBin: unable to add bin with " << n << " events" << std::endl;
472 return;
473 }
474 }
475
476 addPoint(binCenter,n, scale*scaleFactor,dx*xErrorFrac,dx*xErrorFrac, n-ym, yp-n);
477}
478
479
480
481////////////////////////////////////////////////////////////////////////////////
482/// Add a bin to this histogram with the specified bin contents
483/// and error. The bin width is used to set the relative scale of
484/// bins with different widths.
485
486void RooHist::addBinWithError(Axis_t binCenter, double n, double elow, double ehigh, double binWidth,
487 double xErrorFrac, bool correctForBinWidth, double scaleFactor)
488{
489 double scale= 1;
490 if(binWidth > 0 && correctForBinWidth) {
491 scale= _nominalBinWidth/binWidth;
492 }
493 _entries+= n;
494
495 double dx(0.5*binWidth) ;
496 addPoint(binCenter,n, scale*scaleFactor,dx*xErrorFrac,dx*xErrorFrac, elow, ehigh);
497}
498
499
500
501
502////////////////////////////////////////////////////////////////////////////////
503/// Add a bin to this histogram with the specified bin contents
504/// and error. The bin width is used to set the relative scale of
505/// bins with different widths.
506
507void RooHist::addBinWithXYError(Axis_t binCenter, double n, double exlow, double exhigh, double eylow, double eyhigh,
508 double scaleFactor)
509{
510 _entries+= n;
511
512 addPoint(binCenter, n, scaleFactor,exlow,exhigh, eylow, eyhigh);
513}
514
515
516
517
518
519////////////////////////////////////////////////////////////////////////////////
520/// Add a bin to this histogram with the value (n1-n2)/(n1+n2)
521/// using an error bar calculated with Binomial statistics.
522
523void RooHist::addAsymmetryBin(Axis_t binCenter, Int_t n1, Int_t n2, double binWidth, double xErrorFrac, double scaleFactor)
524{
525 // calculate Binomial errors for this bin
526 double ym;
527 double yp;
528 double dx(0.5 * binWidth);
529 if(!RooHistError::instance().getBinomialIntervalAsym(n1,n2,ym,yp,_nSigma)) {
530 coutE(Plotting) << "RooHist::addAsymmetryBin: unable to calculate binomial error for bin with " << n1 << "," << n2 << " events" << std::endl;
531 return;
532 }
533
534 const Int_t denominator = n1 + n2;
535 double a = 0 == denominator ? 0. : (double)(n1 - n2) / (denominator);
536 addPoint(binCenter, a, scaleFactor,dx*xErrorFrac,dx*xErrorFrac, a-ym, yp-a);
537}
538
539
540
541////////////////////////////////////////////////////////////////////////////////
542/// Add a bin to this histogram with the value (n1-n2)/(n1+n2)
543/// using an error bar calculated with Binomial statistics.
544
545void RooHist::addAsymmetryBinWithError(Axis_t binCenter, double n1, double n2, double en1, double en2, double binWidth, double xErrorFrac, double scaleFactor)
546{
547 // calculate Binomial errors for this bin
548 double ym;
549 double yp;
550 double dx(0.5 * binWidth);
551 double a= (double)(n1-n2)/(n1+n2);
552
553 double error = 2*sqrt( pow(en1,2)*pow(n2,2) + pow(en2,2)*pow(n1,2) ) / pow(n1+n2,2) ;
554 ym=a-error ;
555 yp=a+error ;
556
557 addPoint(binCenter,a, scaleFactor, dx*xErrorFrac,dx*xErrorFrac, a-ym, yp-a);
558}
559
560
561
562////////////////////////////////////////////////////////////////////////////////
563/// Add a bin to this histogram with the value n1/(n1+n2)
564/// using an error bar calculated with Binomial statistics.
565
566void RooHist::addEfficiencyBin(Axis_t binCenter, Int_t n1, Int_t n2, double binWidth, double xErrorFrac, double scaleFactor)
567{
568 double a= (double)(n1)/(n1+n2);
569
570 // calculate Binomial errors for this bin
571 double ym;
572 double yp;
573 double dx(0.5 * binWidth);
574 if(!RooHistError::instance().getBinomialIntervalEff(n1,n2,ym,yp,_nSigma)) {
575 coutE(Plotting) << "RooHist::addEfficiencyBin: unable to calculate binomial error for bin with " << n1 << "," << n2 << " events" << std::endl;
576 return;
577 }
578
579 addPoint(binCenter,a, scaleFactor,dx*xErrorFrac,dx*xErrorFrac, a-ym, yp-a);
580}
581
582
583
584////////////////////////////////////////////////////////////////////////////////
585/// Add a bin to this histogram with the value n1/(n1+n2)
586/// using an error bar calculated with Binomial statistics.
587
588void RooHist::addEfficiencyBinWithError(Axis_t binCenter, double n1, double n2, double en1, double en2, double binWidth, double xErrorFrac, double scaleFactor)
589{
590 double a= (double)(n1)/(n1+n2);
591
592 double error = sqrt( pow(en1,2)*pow(n2,2) + pow(en2,2)*pow(n1,2) ) / pow(n1+n2,2) ;
593
594 // calculate Binomial errors for this bin
595 double ym;
596 double yp;
597 double dx(0.5 * binWidth);
598 ym=a-error ;
599 yp=a+error ;
600
601
602 addPoint(binCenter,a, scaleFactor,dx*xErrorFrac,dx*xErrorFrac, a-ym, yp-a);
603}
604
605
606////////////////////////////////////////////////////////////////////////////////
607/// Return true if binning of this RooHist is identical to that of 'other'
608
610{
611 // First check if number of bins is the same
612 if (GetN() != other.GetN()) {
613 return false ;
614 }
615
616 // Next require that all bin centers are the same
617 Int_t i ;
618 for (i=0 ; i<GetN() ; i++) {
619 double x1;
620 double x2;
621 double y1;
622 double y2;
623
624 GetPoint(i,x1,y1) ;
625 other.GetPoint(i,x2,y2) ;
626
627 if (std::abs(x1-x2) > 1e-10 * _nominalBinWidth) {
628 return false ;
629 }
630
631 }
632
633 return true ;
634}
635
636
637
638////////////////////////////////////////////////////////////////////////////////
639/// Return true if contents of this RooHist is identical within given
640/// relative tolerance to that of 'other'
641
642bool RooHist::isIdentical(const RooHist& other, double tol, bool verbose) const
643{
644 // Make temporary TH1s output of RooHists to perform Kolmogorov test
645 TDirectory::TContext ctx{nullptr}; // No self-registration to directories
646 TH1F h_self("h_self","h_self",GetN(),0,1) ;
647 TH1F h_other("h_other", "h_other", GetN(), 0, 1);
648
649 for (Int_t i=0 ; i<GetN() ; i++) {
650 h_self.SetBinContent(i+1,GetY()[i]) ;
651 h_other.SetBinContent(i+1,other.GetY()[i]) ;
652 }
653
654 double M = h_self.KolmogorovTest(&h_other,"M") ;
655 if (M>tol) {
656 double kprob = h_self.KolmogorovTest(&h_other) ;
657 if(verbose) std::cout << "RooHist::isIdentical() tolerance exceeded M=" << M << " (tol=" << tol << "), corresponding prob = " << kprob << std::endl ;
658 return false ;
659 }
660
661 return true ;
662}
663
664
665
666////////////////////////////////////////////////////////////////////////////////
667/// Print info about this histogram to the specified output stream.
668///
669/// Standard: number of entries
670/// Shape: error CL and maximum value
671/// Verbose: print our bin contents and errors
672
673void RooHist::printMultiline(std::ostream& os, Int_t contents, bool verbose, TString indent) const
674{
675 RooPlotable::printMultiline(os,contents,verbose,indent);
676 os << indent << "--- RooHist ---" << std::endl;
677 Int_t n= GetN();
678 os << indent << " Contains " << n << " bins" << std::endl;
679 if(verbose) {
680 os << indent << " Errors calculated at" << _nSigma << "-sigma CL" << std::endl;
681 os << indent << " Bin Contents:" << std::endl;
682 for(Int_t i= 0; i < n; i++) {
683 os << indent << std::setw(3) << i << ") x= " << fX[i];
684 if(fEXhigh[i] > 0 || fEXlow[i] > 0) {
685 os << " +" << fEXhigh[i] << " -" << fEXlow[i];
686 }
687 os << " , y = " << fY[i] << " +" << fEYhigh[i] << " -" << fEYlow[i] << std::endl;
688 }
689 }
690}
691
692
693
694////////////////////////////////////////////////////////////////////////////////
695/// Print name of RooHist
696
697void RooHist::printName(std::ostream& os) const
698{
699 os << GetName() ;
700}
701
702
703
704////////////////////////////////////////////////////////////////////////////////
705/// Print title of RooHist
706
707void RooHist::printTitle(std::ostream& os) const
708{
709 os << GetTitle() ;
710}
711
712
713
714////////////////////////////////////////////////////////////////////////////////
715/// Print class name of RooHist
716
717void RooHist::printClassName(std::ostream& os) const
718{
719 os << ClassName() ;
720}
721
722
723std::unique_ptr<RooHist> RooHist::createEmptyResidHist(const RooCurve& curve, bool normalize) const
724{
725 // Copy all non-content properties from hist1
726 auto hist = std::make_unique<RooHist>(_nominalBinWidth) ;
727 const std::string name = GetName() + std::string("_") + curve.GetName();
728 const std::string title = GetTitle() + std::string(" and ") + curve.GetTitle();
729 hist->SetName(((normalize ? "pull_" : "resid_") + name).c_str()) ;
730 hist->SetTitle(((normalize ? "Pull of " : "Residual of ") + title).c_str()) ;
731
732 return hist;
733}
734
735
736void RooHist::fillResidHist(RooHist & residHist, const RooCurve& curve,bool normalize, bool useAverage) const
737{
738 // Determine range of curve
739 double xstart;
740 double xstop;
741 double y;
742 curve.GetPoint(0,xstart,y) ;
743 curve.GetPoint(curve.GetN()-1,xstop,y) ;
744
745 // Add histograms, calculate Poisson confidence interval on sum value
746 for(Int_t i=0 ; i<GetN() ; i++) {
747 double x;
748 double point;
749 GetPoint(i,x,point) ;
750
751 // Only calculate pull for bins inside curve range
753
754 double yy ;
755 if (useAverage) {
756 double exl = GetErrorXlow(i);
757 double exh = GetErrorXhigh(i) ;
758 if (exl<=0 ) exl = GetErrorX(i);
759 if (exh<=0 ) exh = GetErrorX(i);
760 if (exl<=0 ) exl = 0.5*getNominalBinWidth();
761 if (exh<=0 ) exh = 0.5*getNominalBinWidth();
762 yy = point - curve.average(x-exl,x+exh) ;
763 } else {
764 yy = point - curve.interpolate(x) ;
765 }
766
767 double dyl = GetErrorYlow(i) ;
768 double dyh = GetErrorYhigh(i) ;
769 if (normalize) {
770 double norm = (yy>0?dyl:dyh);
771 if (norm==0.) {
772 coutW(Plotting) << "RooHist::makeResisHist(" << GetName() << ") WARNING: point " << i << " has zero error, setting residual to zero" << std::endl;
773 yy=0 ;
774 dyh=0 ;
775 dyl=0 ;
776 } else {
777 yy /= norm;
778 dyh /= norm;
779 dyl /= norm;
780 }
781 }
782 residHist.addBinWithError(x,yy,dyl,dyh);
783 }
784}
785
786
787////////////////////////////////////////////////////////////////////////////////
788/// Create and return RooHist containing residuals w.r.t to given curve.
789/// If normalize is true, the residuals are normalized by the histogram
790/// errors creating a RooHist with pull values
791
792RooHist* RooHist::makeResidHist(const RooCurve& curve, bool normalize, bool useAverage) const
793{
794 RooHist* hist = createEmptyResidHist(curve, normalize).release();
795 fillResidHist(*hist, curve, normalize, useAverage);
796 return hist ;
797}
#define f(i)
Definition RSha256.hxx:104
#define a(i)
Definition RSha256.hxx:99
#define e(i)
Definition RSha256.hxx:103
#define coutW(a)
#define coutE(a)
int Int_t
Signed integer 4 bytes (int)
Definition RtypesCore.h:60
static void indent(ostringstream &buf, int indent_level)
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void data
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char x2
Option_t Option_t TPoint TPoint const char x1
Option_t Option_t TPoint TPoint const char y2
Option_t Option_t SetMarkerStyle
Option_t Option_t TPoint TPoint const char y1
char name[80]
Definition TGX11.cxx:148
char * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Definition TString.cxx:2570
Abstract base class for RooRealVar binning definitions.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Abstract base class for objects that represent a real value that may appear on the left hand side of ...
static constexpr int DefaultNBins
Historical default number of bins, injected by routines that need a concrete bin count when a variabl...
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
One-dimensional graphical representation of a real-valued function.
Definition RooCurve.h:36
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
static const RooHistError & instance()
Return a reference to a singleton object that is created the first time this method is called.
Graphical representation of binned data based on the TGraphAsymmErrors class.
Definition RooHist.h:29
RooHist * makeResidHist(const RooCurve &curve, bool normalize=false, bool useAverage=false) const
Create and return RooHist containing residuals w.r.t to given curve.
Definition RooHist.cxx:792
double _nominalBinWidth
Average bin width.
Definition RooHist.h:98
double _rawEntries
Number of entries in source dataset.
Definition RooHist.h:101
void printClassName(std::ostream &os) const override
Print class name of RooHist.
Definition RooHist.cxx:717
void addEfficiencyBin(Axis_t binCenter, Int_t n1, Int_t n2, double binWidth=0, double xErrorFrac=1.0, double scaleFactor=1.0)
Add a bin to this histogram with the value n1/(n1+n2) using an error bar calculated with Binomial sta...
Definition RooHist.cxx:566
void fillResidHist(RooHist &residHist, const RooCurve &curve, bool normalize=false, bool useAverage=false) const
Definition RooHist.cxx:736
void initialize()
Perform common initialization for all constructors.
Definition RooHist.cxx:336
void addBinWithError(Axis_t binCenter, double n, double elow, double ehigh, double binWidth=0, double xErrorFrac=1.0, bool correctForBinWidth=true, double scaleFactor=1.0)
Add a bin to this histogram with the specified bin contents and error.
Definition RooHist.cxx:486
void addEfficiencyBinWithError(Axis_t binCenter, double n1, double n2, double en1, double en2, double binWidth=0, double xErrorFrac=1.0, double scaleFactor=1.0)
Add a bin to this histogram with the value n1/(n1+n2) using an error bar calculated with Binomial sta...
Definition RooHist.cxx:588
RooHist()
Definition RooHist.h:31
void printName(std::ostream &os) const override
Print name of RooHist.
Definition RooHist.cxx:697
void printMultiline(std::ostream &os, Int_t content, bool verbose=false, TString indent="") const override
Print info about this histogram to the specified output stream.
Definition RooHist.cxx:673
std::unique_ptr< RooHist > createEmptyResidHist(const RooCurve &curve, bool normalize=false) const
Definition RooHist.cxx:723
void printTitle(std::ostream &os) const override
Print title of RooHist.
Definition RooHist.cxx:707
std::vector< double > _originalWeights
The original bin weights that were passed to the RooHist::addBin functions before scaling and bin wid...
Definition RooHist.h:103
double getNominalBinWidth() const
Definition RooHist.h:73
void addAsymmetryBinWithError(Axis_t binCenter, double n1, double n2, double en1, double en2, double binWidth=0, double xErrorFrac=1.0, double scaleFactor=1.0)
Add a bin to this histogram with the value (n1-n2)/(n1+n2) using an error bar calculated with Binomia...
Definition RooHist.cxx:545
double _entries
Number of entries in histogram.
Definition RooHist.h:100
Int_t roundBin(double y)
Return the nearest positive integer to the input value and print a warning if an adjustment is requir...
Definition RooHist.cxx:393
bool isIdentical(const RooHist &other, double tol=1e-6, bool verbose=true) const
Return true if contents of this RooHist is identical within given relative tolerance to that of 'othe...
Definition RooHist.cxx:642
void addAsymmetryBin(Axis_t binCenter, Int_t n1, Int_t n2, double binWidth=0, double xErrorFrac=1.0, double scaleFactor=1.0)
Add a bin to this histogram with the value (n1-n2)/(n1+n2) using an error bar calculated with Binomia...
Definition RooHist.cxx:523
double _nSigma
Number of 'sigmas' error bars represent.
Definition RooHist.h:99
void addBin(Axis_t binCenter, double n, double binWidth=0, double xErrorFrac=1.0, double scaleFactor=1.0)
Add a bin to this histogram with the specified integer bin contents and using an error bar calculated...
Definition RooHist.cxx:435
void addPoint(Axis_t binCenter, double y, double yscale, double exlow, double exhigh, double eylow, double eyhigh)
Definition RooHist.cxx:407
bool hasIdenticalBinning(const RooHist &other) const
Return true if binning of this RooHist is identical to that of 'other'.
Definition RooHist.cxx:609
double getFitRangeNEvt() const override
Return the number of events of the dataset associated with this RooHist.
Definition RooHist.cxx:347
void addBinWithXYError(Axis_t binCenter, double n, double exlow, double exhigh, double eylow, double eyhigh, double scaleFactor=1.0)
Add a bin to this histogram with the specified bin contents and error.
Definition RooHist.cxx:507
void printMultiline(std::ostream &os, Int_t contents, bool verbose=false, TString indent="") const override
Print detailed information.
void updateYAxisLimits(double y)
Definition RooPlotable.h:30
void setYAxisLabel(const char *label)
Definition RooPlotable.h:29
Represents the product of a given set of RooAbsReal objects.
Definition RooProduct.h:29
Class to manage histogram axis.
Definition TAxis.h:32
Double_t GetXmax() const
Definition TAxis.h:142
Double_t GetXmin() const
Definition TAxis.h:141
Int_t GetNbins() const
Definition TAxis.h:127
TDirectory::TContext keeps track and restore the current directory.
Definition TDirectory.h:89
Double_t * fEXhigh
[fNpoints] array of X high errors
virtual void SetPointError(Double_t exl, Double_t exh, Double_t eyl, Double_t eyh)
Set ex and ey values for point pointed by the mouse.
Double_t GetErrorXhigh(Int_t i) const override
Get high error on X.
Double_t * fEYhigh
[fNpoints] array of Y high errors
Double_t GetErrorYhigh(Int_t i) const override
Get high error on Y.
Double_t GetErrorXlow(Int_t i) const override
Get low error on X.
Double_t * fEYlow
[fNpoints] array of Y low errors
Double_t * fEXlow
[fNpoints] array of X low errors
Double_t GetErrorYlow(Int_t i) const override
Get low error on Y.
Double_t GetErrorX(Int_t bin) const override
Returns the combined error along X at point i by computing the average of the lower and upper varianc...
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
Definition TGraph.cxx:2389
Double_t * GetY() const
Definition TGraph.h:139
Int_t GetN() const
Definition TGraph.h:131
Double_t * fY
[fNpoints] array of Y points
Definition TGraph.h:48
void SetName(const char *name="") override
Set graph name.
Definition TGraph.cxx:2428
Double_t * fX
[fNpoints] array of X points
Definition TGraph.h:47
void SetTitle(const char *title="") override
Change (i.e.
Definition TGraph.cxx:2444
virtual Int_t GetPoint(Int_t i, Double_t &x, Double_t &y) const
Get x and y values for point number i.
Definition TGraph.cxx:1565
1-D histogram with a float per channel (see TH1 documentation)
Definition TH1.h:878
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:109
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
const char * GetTitle() const override
Returns title of object.
Definition TNamed.h:50
TString fName
Definition TNamed.h:32
virtual const char * ClassName() const
Returns name of class to which the object belongs.
Definition TObject.cxx:227
Basic string class.
Definition TString.h:138
RooConstVar & RooConst(double val)
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2338