Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
HFitInterface.cxx
Go to the documentation of this file.
1// @(#)root/hist:$Id$
2// Author: L. Moneta Thu Aug 31 10:40:20 2006
3
4/**********************************************************************
5 * *
6 * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7 * *
8 * *
9 **********************************************************************/
10
11// Implementation file for class TH1Interface
12
13#include "HFitInterface.h"
14
15#include "Fit/BinData.h"
16#include "Fit/SparseData.h"
17#include "Fit/FitResult.h"
18#include "Math/IParamFunction.h"
19
20#include <algorithm>
21#include <cassert>
22#include <cmath>
23#include <utility>
24#include <vector>
25
26#include "TH1.h"
27#include "THnBase.h"
28#include "TF1.h"
29#include "TGraph2D.h"
30#include "TGraph.h"
31#include "TGraphErrors.h"
32#include "TMultiGraph.h"
33#include "TList.h"
34#include "TError.h"
35
36
37//#define DEBUG
38#ifdef DEBUG
39#include "TClass.h"
40#include <iostream>
41#endif
42
43
44namespace ROOT {
45
46namespace Fit {
47
48// add a namespace to distinguish from the Graph functions
49namespace HFitInterface {
50
51
52bool IsPointOutOfRange(const TF1 * func, const double * x) {
53 // function to check if a point is outside range
54 if (func ==nullptr) return false;
55 return !func->IsInside(x);
56}
57
58bool AdjustError(const DataOptions & option, double & error, double value = 1) {
59 // adjust the given error according to the option
60 // return false when point must be skipped.
61 // When point error = 0, the point is kept if the option UseEmpty is set or if
62 // fErrors1 is set and the point value is not zero.
63 // The value should be used only for points representing counts (histograms), not for the graph.
64 // In the graph points with zero errors are by default skipped indepentently of the value.
65 // If one wants to keep the points, the option fUseEmpty must be set
66
67 if (error <= 0) {
68 if (option.fUseEmpty || (option.fErrors1 && std::abs(value) > 0 ) )
69 error = 1.; // set error to 1
70 else
71 return false; // skip bins with zero errors or empty
72 } else if (option.fErrors1)
73 error = 1; // set all error to 1 for non-empty bins
74 return true;
75}
76
77void ExamineRange(const TAxis * axis, std::pair<double,double> range,int &hxfirst,int &hxlast) {
78 // examine the range given with the pair on the given histogram axis
79 // correct in case the bin values hxfirst hxlast
80 double xlow = range.first;
81 double xhigh = range.second;
82#ifdef DEBUG
83 std::cout << "xlow " << xlow << " xhigh = " << xhigh << std::endl;
84#endif
85 // ignore ranges specified outside histogram range
86 int ilow = axis->FindFixBin(xlow);
87 int ihigh = axis->FindFixBin(xhigh);
88 if (ilow > hxlast || ihigh < hxfirst) {
89 Warning("ROOT::Fit::FillData","fit range is outside histogram range, no fit data for %s",axis->GetName());
90 }
91 // consider only range defined with-in histogram not oustide. Always exclude underflow/overflow
92 hxfirst = std::min( std::max( ilow, hxfirst), hxlast+1) ;
93 hxlast = std::max( std::min( ihigh, hxlast), hxfirst-1) ;
94 // exclude bins where range coverage is less than half bin width
95 if (hxfirst < hxlast) {
96 if ( axis->GetBinCenter(hxfirst) < xlow) hxfirst++;
97 if ( axis->GetBinCenter(hxlast) > xhigh) hxlast--;
98 }
99}
100
101
102} // end namespace HFitInterface
103
104
105void FillData(BinData & dv, const TH1 * hfit, TF1 * func)
106{
107 // Function to fill the binned Fit data structure from a TH1
108 // The dimension of the data is the same of the histogram dimension
109 // The function pointer is need in case of integral is used and to reject points
110 // rejected in the function
111
112 // the TF1 pointer cannot be constant since EvalPar and InitArgs are not const methods
113
114 // get fit option
115 const DataOptions & fitOpt = dv.Opt();
116
117
118 // store instead of bin center the bin edges
119 bool useBinEdges = fitOpt.fIntegral || fitOpt.fBinVolume;
120
121 assert(hfit != nullptr);
122
123 //std::cout << "creating Fit Data from histogram " << hfit->GetName() << std::endl;
124
125 // function by default has same range (use that one if requested otherwise use data one)
126
127
128 // get the range (add the function range ??)
129 // to check if inclusion/exclusion at end/point
130 const DataRange & range = dv.Range();
131
132 // Several disjoint ranges can be defined for each coordinate. Translate them
133 // once per axis into the list of selected bins. A coordinate without any
134 // range selects the full axis.
135 auto selectedBins = [&range](const TAxis *axis, unsigned int icoord, bool useRange) {
136 std::vector<int> bins;
137 const unsigned int nRanges = useRange ? range.Size(icoord) : 0;
138 for (unsigned int i = 0; i < std::max(nRanges, 1u); ++i) {
139 int first = axis->GetFirst();
140 int last = axis->GetLast();
141 if (nRanges != 0)
142 HFitInterface::ExamineRange(axis, range(icoord, i), first, last);
143 // The ranges are disjoint and sorted, but ExamineRange() selects the
144 // bin of a range that lies within a single bin even if the range does
145 // not cover the bin center. Two ranges can therefore select the same
146 // bin, which must not be taken twice.
147 if (!bins.empty())
148 first = std::max(first, bins.back() + 1);
149 for (int bin = first; bin <= last; ++bin)
150 bins.push_back(bin);
151 }
152 return bins;
153 };
154 const std::vector<int> xbins = selectedBins(hfit->GetXaxis(), 0, true);
155 const std::vector<int> ybins = selectedBins(hfit->GetYaxis(), 1, hfit->GetDimension() > 1);
156 const std::vector<int> zbins = selectedBins(hfit->GetZaxis(), 2, hfit->GetDimension() > 2);
157
158 int n = static_cast<int>(xbins.size() * ybins.size() * zbins.size());
159
160#ifdef DEBUG
161 std::cout << "THFitInterface: bins in x = " << xbins.size()
162 << " total bins " << n
163 << std::endl;
164#endif
165
166 // reserve n for more efficient usage
167 //dv.Data().reserve(n);
168
169 int hdim = hfit->GetDimension();
170 int ndim = hdim;
171 // case of function dimension less than histogram
172 if (func !=nullptr && func->GetNdim() == hdim-1) ndim = hdim-1;
173
174 assert( ndim > 0 );
175 //typedef BinPoint::CoordData CoordData;
176 //CoordData x = CoordData( hfit->GetDimension() );
178
179 double x[3];
180 double s[3];
181
182 const TAxis *xaxis = hfit->GetXaxis();
183 const TAxis *yaxis = hfit->GetYaxis();
184 const TAxis *zaxis = hfit->GetZaxis();
185
186 for (int binx : xbins) {
187 if (useBinEdges) {
188 x[0] = xaxis->GetBinLowEdge(binx);
189 s[0] = xaxis->GetBinUpEdge(binx);
190 }
191 else
192 x[0] = xaxis->GetBinCenter(binx);
193
194
195 for (int biny : ybins) {
196 if (useBinEdges) {
197 x[1] = yaxis->GetBinLowEdge(biny);
198 s[1] = yaxis->GetBinUpEdge(biny);
199 }
200 else
201 x[1] = yaxis->GetBinCenter(biny);
202
203 for (int binz : zbins) {
204 if (useBinEdges) {
205 x[2] = zaxis->GetBinLowEdge(binz);
206 s[2] = zaxis->GetBinUpEdge(binz);
207 }
208 else
209 x[2] = zaxis->GetBinCenter(binz);
210
211 // need to evaluate function to know about rejected points
212 // hugly but no other solutions
213 if (func != nullptr) {
214 TF1::RejectPoint(false);
215 (*func)( &x[0] ); // evaluate using stored function parameters
216 if (TF1::RejectedPoint() ) continue;
217 }
218
219
220 double value = hfit->GetBinContent(binx, biny, binz);
221 double error = hfit->GetBinError(binx, biny, binz);
222 if (!HFitInterface::AdjustError(fitOpt,error,value) ) continue;
223
224 if (ndim == hdim -1) {
225 // case of fitting a function with dimension -1
226 // point error is bin width y / sqrt(N) where N is the number of entries in the bin
227 // normalization of error will be wrong - but they will be rescaled in the fit
228 if (hdim == 2) dv.Add( x, x[1], yaxis->GetBinWidth(biny) / error );
229 if (hdim == 3) dv.Add( x, x[2], zaxis->GetBinWidth(binz) / error );
230 } else {
231 if (fitOpt.fErrors1)
232 dv.Add( x, value );
233 else
234 dv.Add( x, value, error );
235 if (useBinEdges) {
236 dv.AddBinUpEdge( s );
237 }
238 }
239
240
241#ifdef DEBUG
242 std::cout << "bin " << binx << " add point " << x[0] << " " << hfit->GetBinContent(binx) << std::endl;
243#endif
244
245 } // end loop on z bins
246 } // end loop on y bins
247 } // end loop on x axis
248
249
250#ifdef DEBUG
251 std::cout << "THFitInterface::FillData: Hist FitData size is " << dv.Size() << std::endl;
252#endif
253
254}
255
256////////////////////////////////////////////////////////////////////////////////
257/// Compute rough values of parameters for an exponential
258
260{
261 unsigned int n = data.Size();
262 if (n == 0) return;
263
264 // find xmin and xmax of the data
265 double valxmin;
266 double xmin = *(data.GetPoint(0,valxmin));
267 double xmax = xmin;
268 double valxmax = valxmin;
269
270 for (unsigned int i = 1; i < n; ++ i) {
271 double val;
272 double x = *(data.GetPoint(i,val) );
273 if (x < xmin) {
274 xmin = x;
275 valxmin = val;
276 }
277 else if (x > xmax) {
278 xmax = x;
279 valxmax = val;
280 }
281 }
282
283 // avoid negative values of valxmin/valxmax
284 if (valxmin <= 0 && valxmax > 0 ) valxmin = valxmax;
285 else if (valxmax <=0 && valxmin > 0) valxmax = valxmin;
286 else if (valxmin <=0 && valxmax <= 0) { valxmin = 1; valxmax = 1; }
287
288 double slope = std::log( valxmax/valxmin) / (xmax - xmin);
289 double constant = std::log(valxmin) - slope * xmin;
290 f1->SetParameters(constant, slope);
291}
292
293////////////////////////////////////////////////////////////////////////////////
294/// Compute rough values of parameters for a first-degree polynomial
295///
296/// Compute starting values for the weighted fit by using an unweighted least-squares line.
297///
298/// Only the first-degree case is handled; a higher degree returns unchanged.
299
301{
302 if (f1->GetNpar() != 2)
303 return;
304
305 unsigned int n = data.Size();
306 if (n < 2)
307 return;
308
309 double sumX = 0, sumY = 0, sumXSq = 0, sumXY = 0;
310 for (unsigned int i = 0; i < n; ++i) {
311 double val;
312 double x = *(data.GetPoint(i, val));
313 sumX += x;
314 sumY += val;
315 sumXSq += x * x;
316 sumXY += x * val;
317 }
318
319 // Vanishes when every point shares one x: no line to estimate, leave as is.
320 double det = n * sumXSq - sumX * sumX;
321 if (det == 0)
322 return;
323
324 double slope = (n * sumXY - sumX * sumY) / det;
325 f1->SetParameters((sumY - slope * sumX) / n, slope);
326}
327
328////////////////////////////////////////////////////////////////////////////////
329/// Compute Initial values of parameters for a gaussian
330/// derived from function H1InitGaus defined in TH1.cxx
331
333{
334
335 static const double sqrtpi = 2.506628;
336
337 // - Compute mean value and RMS of the data
338 unsigned int n = data.Size();
339 if (n == 0) return;
340 double sumx = 0;
341 double sumx2 = 0;
342 double allcha = 0;
343 double valmax = 0;
344 double rangex = data.Coords(n-1)[0] - data.Coords(0)[0];
345 // to avoid binwidth = 0 set arbitrarly to 1
346 double binwidth = 1;
347 if ( rangex > 0) binwidth = rangex;
348 double x0 = 0;
349 for (unsigned int i = 0; i < n; ++ i) {
350 double val;
351 double x = *(data.GetPoint(i,val) );
352 sumx += val*x;
353 sumx2 += val*x*x;
354 allcha += val;
355 if (val > valmax) valmax = val;
356 if (i > 0) {
357 double dx = x - x0;
358 if (dx < binwidth) binwidth = dx;
359 }
360 x0 = x;
361 }
362
363 if (allcha <= 0) return;
364 double mean = sumx/allcha;
365 double rms = sumx2/allcha - mean*mean;
366
367
368 if (rms > 0)
369 rms = std::sqrt(rms);
370 else
371 rms = binwidth*n/4;
372
373
374 //if the distribution is really gaussian, the best approximation
375 //is binwidx*allcha/(sqrtpi*rms)
376 //However, in case of non-gaussian tails, this underestimates
377 //the normalisation constant. In this case the maximum value
378 //is a better approximation.
379 //We take the average of both quantities
380
381// printf("valmax %f other %f bw %f allcha %f rms %f \n",valmax, binwidth*allcha/(sqrtpi*rms),
382// binwidth, allcha,rms );
383
384 double constant = 0.5*(valmax+ binwidth*allcha/(sqrtpi*rms));
385
386
387 //In case the mean value is outside the histo limits and
388 //the RMS is bigger than the range, we take
389 // mean = center of bins
390 // rms = half range
391// Double_t xmin = curHist->GetXaxis()->GetXmin();
392// Double_t xmax = curHist->GetXaxis()->GetXmax();
393// if ((mean < xmin || mean > xmax) && rms > (xmax-xmin)) {
394// mean = 0.5*(xmax+xmin);
395// rms = 0.5*(xmax-xmin);
396// }
397
398 f1->SetParameter(0,constant);
399 f1->SetParameter(1,mean);
400 f1->SetParameter(2,rms);
401 f1->SetParLimits(2,0,10*rms);
402
403
404#ifdef DEBUG
405 std::cout << "Gaussian initial par values" << constant << " " << mean << " " << rms << std::endl;
406#endif
407
408}
409
410////////////////////////////////////////////////////////////////////////////////
411/// Compute Initial values of parameters for a gaussian
412/// derived from function H1InitGaus defined in TH1.cxx
413
415{
416
417 static const double sqrtpi = 2.506628;
418
419 // - Compute mean value and RMS of the data
420 unsigned int n = data.Size();
421 if (n == 0) return;
422 double sumx = 0, sumy = 0;
423 double sumx2 = 0, sumy2 = 0;
424 double allcha = 0;
425 double valmax = 0;
426 double rangex = data.Coords(n-1)[0] - data.Coords(0)[0];
427 double rangey = data.Coords(n-1)[1] - data.Coords(0)[1];
428 // to avoid binwidthx = 0 set arbitrarly to 1
429 double binwidthx = 1, binwidthy = 1;
430 if ( rangex > 0) binwidthx = rangex;
431 if ( rangey > 0) binwidthy = rangey;
432 double x0 = 0, y0 = 0;
433 for (unsigned int i = 0; i < n; ++i) {
434 double val;
435 const double *coords = data.GetPoint(i,val);
436 double x = coords[0], y = coords[1];
437 sumx += val*x;
438 sumy += val*y;
439 sumx2 += val*x*x;
440 sumy2 += val*y*y;
441 allcha += val;
442 if (val > valmax) valmax = val;
443 if (i > 0) {
444 double dx = x - x0;
445 if (dx < binwidthx) binwidthx = dx;
446 double dy = y - y0;
447 if (dy < binwidthy) binwidthy = dy;
448 }
449 x0 = x;
450 y0 = y;
451 }
452
453 if (allcha <= 0) return;
454 double meanx = sumx/allcha, meany = sumy/allcha;
455 double rmsx = sumx2/allcha - meanx*meanx;
456 double rmsy = sumy2/allcha - meany*meany;
457
458
459 if (rmsx > 0)
460 rmsx = std::sqrt(rmsx);
461 else
462 rmsx = binwidthx*n/4;
463
464 if (rmsy > 0)
465 rmsy = std::sqrt(rmsy);
466 else
467 rmsy = binwidthy*n/4;
468
469
470 //if the distribution is really gaussian, the best approximation
471 //is binwidx*allcha/(sqrtpi*rmsx)
472 //However, in case of non-gaussian tails, this underestimates
473 //the normalisation constant. In this case the maximum value
474 //is a better approximation.
475 //We take the average of both quantities
476
477 double constant = 0.5 * (valmax+ binwidthx*allcha/(sqrtpi*rmsx))*
478 (valmax+ binwidthy*allcha/(sqrtpi*rmsy));
479
480 f1->SetParameter(0,constant);
481 f1->SetParameter(1,meanx);
482 f1->SetParameter(2,rmsx);
483 f1->SetParLimits(2,0,10*rmsx);
484 f1->SetParameter(3,meany);
485 f1->SetParameter(4,rmsy);
486 f1->SetParLimits(4,0,10*rmsy);
487
488#ifdef DEBUG
489 std::cout << "2D Gaussian initial par values"
490 << constant << " "
491 << meanx << " "
492 << rmsx
493 << meany << " "
494 << rmsy
495 << std::endl;
496#endif
497
498}
499
500// filling fit data from TGraph objects
501
503 // get type of data for TGraph objects
504 double *ex = gr->GetEX();
505 double *ey = gr->GetEY();
506 double * eyl = gr->GetEYlow();
507 double * eyh = gr->GetEYhigh();
508
509
510 // default case for graphs (when they have errors)
512 // if all errors are zero set option of using errors to 1
513 if (fitOpt.fErrors1 || ( ey == nullptr && ( eyl == nullptr || eyh == nullptr ) ) ) {
515 }
516 // need to treat case when all errors are zero
517 // note that by default fitOpt.fCoordError is true
518 else if ( ex != nullptr && fitOpt.fCoordErrors) {
519 // check that all errors are not zero
520 int i = 0;
521 while (i < gr->GetN() && type != BinData::kCoordError) {
522 if (ex[i] > 0) type = BinData::kCoordError;
523 ++i;
524 }
525 }
526 // case of asymmetric errors (by default fAsymErrors is true)
527 else if ( ( eyl != nullptr && eyh != nullptr) && fitOpt.fAsymErrors) {
528 // check also if that all errors are non zero's
529 int i = 0;
530 bool zeroErrorX = true;
531 bool zeroErrorY = true;
532 while (i < gr->GetN() && (zeroErrorX || zeroErrorY)) {
533 double e2X = ( gr->GetErrorXlow(i) + gr->GetErrorXhigh(i) );
534 double e2Y = eyl[i] + eyh[i];
535 zeroErrorX &= (e2X <= 0);
536 zeroErrorY &= (e2Y <= 0);
537 ++i;
538 }
539 if (zeroErrorX && zeroErrorY)
541 else if (!zeroErrorX && zeroErrorY)
543 else if (zeroErrorX && !zeroErrorY) {
545 fitOpt.fCoordErrors = false;
546 }
547 else {
549 }
550 }
551
552 // need to look also a case when all errors in y are zero
553 if ( ey != nullptr && type != BinData::kCoordError ) {
554 int i = 0;
555 bool zeroError = true;
556 while (i < gr->GetN() && zeroError) {
557 if (ey[i] > 0) zeroError = false;
558 ++i;
559 }
560 if (zeroError) type = BinData::kNoError;
561 }
562
563
564#ifdef DEBUG
565 std::cout << "type is " << type << " graph type is " << gr->IsA()->GetName() << std::endl;
566#endif
567
568 return type;
569}
570
572 // get type of data for TGraph2D object
573 double *ex = gr->GetEX();
574 double *ey = gr->GetEY();
575 double *ez = gr->GetEZ();
576
577 // default case for graphs (when they have errors)
579 // if all errors are zero set option of using errors to 1
580 if (fitOpt.fErrors1 || ez == nullptr ) {
582 }
583 else if ( ex != nullptr && ey!=nullptr && fitOpt.fCoordErrors) {
584 // check that all errors are not zero
585 int i = 0;
586 while (i < gr->GetN() && type != BinData::kCoordError) {
587 if (ex[i] > 0 || ey[i] > 0) type = BinData::kCoordError;
588 ++i;
589 }
590 }
591
592
593#ifdef DEBUG
594 std::cout << "type is " << type << " graph2D type is " << gr->IsA()->GetName() << std::endl;
595#endif
596
597 return type;
598}
599
600
601
602void DoFillData ( BinData & dv, const TGraph * gr, BinData::ErrorType type, TF1 * func ) {
603 // internal method to do the actual filling of the data
604 // given a graph and a multigraph
605
606 // get fit option
607 DataOptions & fitOpt = dv.Opt();
608
609 int nPoints = gr->GetN();
610 double *gx = gr->GetX();
611 double *gy = gr->GetY();
612
613 const DataRange & range = dv.Range();
614 bool useRange = ( range.Size(0) > 0);
615 double xmin = 0;
616 double xmax = 0;
617 range.GetRange(xmin,xmax);
618
619 dv.Initialize(nPoints,1, type);
620
621#ifdef DEBUG
622 std::cout << "DoFillData: graph npoints = " << nPoints << " type " << type << std::endl;
623 if (func) {
624 double a1,a2; func->GetRange(a1,a2); std::cout << "func range " << a1 << " " << a2 << std::endl;
625 }
626#endif
627
628 // Unlike histograms, graphs may have array of points created in
629 // non-ascending order along the X axis. This breaks fitting algorithm. We
630 // create a "remap" for the TGraph point indexes that provides ascending
631 // order of X values for the BinData
632 std::vector<std::pair<double, int>> indexRemap;
633 for (int i = 0; i < nPoints; ++i) {
634 indexRemap.emplace_back(gx[i], i);
635 }
636 std::sort(indexRemap.begin(), indexRemap.end());
637
638 double x[1];
639 for (int j = 0; j < nPoints; ++j) {
640
641 int i = indexRemap[j].second;
642 x[0] = gx[i];
643
644
645 if (useRange && ( x[0] < xmin || x[0] > xmax) ) continue;
646
647 // need to evaluate function to know about rejected points
648 // hugly but no other solutions
649 if (func) {
650 TF1::RejectPoint(false);
651 (*func)( x ); // evaluate using stored function parameters
652 if (TF1::RejectedPoint() ) continue;
653 }
654
655
656 if (fitOpt.fErrors1)
657 dv.Add( gx[i], gy[i] );
658
659 // for the errors use the getters by index to avoid cases when the arrays are zero
660 // (like in a case of a graph)
661 else if (type == BinData::kValueError) {
662 double errorY = gr->GetErrorY(i);
663 // should consider error = 0 as 1 ? Decide to skip points with zero errors
664 // in case want to keep points with error = 0 as errrors=1 need to set the option UseEmpty
665 if (!HFitInterface::AdjustError(fitOpt,errorY) ) continue;
666 dv.Add( gx[i], gy[i], errorY );
667
668#ifdef DEBUG
669 std::cout << "Point " << i << " " << gx[i] << " " << gy[i] << " " << errorY << std::endl;
670#endif
671
672
673 }
674 else { // case use error in x or asym errors
675 double errorX = 0;
676 if (fitOpt.fCoordErrors)
677 // shoulkd take combined average (sqrt(0.5(e1^2+e2^2)) or math average ?
678 // gr->GetErrorX(i) returns combined average
679 // use math average for same behaviour as before
680 errorX = std::max( 0.5 * ( gr->GetErrorXlow(i) + gr->GetErrorXhigh(i) ) , 0. ) ;
681
682
683 // adjust error in y according to option
684 double errorY = std::max(gr->GetErrorY(i), 0.);
685 // we do not check the return value since we check later if error in X and Y is zero for skipping the point
686 HFitInterface::AdjustError(fitOpt, errorY);
687
688 // skip points with total error = 0
689 if ( errorX <=0 && errorY <= 0 ) continue;
690
691
692 if (type == BinData::kAsymError) {
693 // asymmetric errors
694 dv.Add( gx[i], gy[i], errorX, gr->GetErrorYlow(i), gr->GetErrorYhigh(i) );
695 }
696 else {
697 // case symmetric Y errors
698 dv.Add( gx[i], gy[i], errorX, errorY );
699 }
700 }
701
702 }
703
704#ifdef DEBUG
705 std::cout << "TGraphFitInterface::FillData Graph FitData size is " << dv.Size() << std::endl;
706#endif
707
708}
709
710void FillData(SparseData & dv, const TH1 * h1, TF1 * /*func*/)
711{
712 const int dim = h1->GetDimension();
713 std::vector<double> min(dim);
714 std::vector<double> max(dim);
715
716 int ncells = h1->GetNcells();
717 for ( int i = 0; i < ncells; ++i ) {
718// printf("i: %d; OF: %d; UF: %d; C: %f\n"
719// , i
720// , h1->IsBinOverflow(i) , h1->IsBinUnderflow(i)
721// , h1->GetBinContent(i));
722 if ( !( h1->IsBinOverflow(i) || h1->IsBinUnderflow(i) )
723 && h1->GetBinContent(i))
724 {
725 int x,y,z;
726 h1->GetBinXYZ(i, x, y, z);
727
728// std::cout << "FILLDATA: h1(" << i << ")"
729// << "[" << h1->GetXaxis()->GetBinLowEdge(x) << "-" << h1->GetXaxis()->GetBinUpEdge(x) << "]";
730// if ( dim >= 2 )
731// std::cout << "[" << h1->GetYaxis()->GetBinLowEdge(y) << "-" << h1->GetYaxis()->GetBinUpEdge(y) << "]";
732// if ( dim >= 3 )
733// std::cout << "[" << h1->GetZaxis()->GetBinLowEdge(z) << "-" << h1->GetZaxis()->GetBinUpEdge(z) << "]";
734
735// std::cout << h1->GetBinContent(i) << std::endl;
736
737 min[0] = h1->GetXaxis()->GetBinLowEdge(x);
738 max[0] = h1->GetXaxis()->GetBinUpEdge(x);
739 if ( dim >= 2 )
740 {
741 min[1] = h1->GetYaxis()->GetBinLowEdge(y);
742 max[1] = h1->GetYaxis()->GetBinUpEdge(y);
743 }
744 if ( dim >= 3 ) {
745 min[2] = h1->GetZaxis()->GetBinLowEdge(z);
746 max[2] = h1->GetZaxis()->GetBinUpEdge(z);
747 }
748
749 dv.Add(min, max, h1->GetBinContent(i), h1->GetBinError(i));
750 }
751 }
752}
753
754void FillData(SparseData & dv, const THnBase * h1, TF1 * /*func*/)
755{
756 const int dim = h1->GetNdimensions();
757 std::vector<double> min(dim);
758 std::vector<double> max(dim);
759 std::vector<Int_t> coord(dim);
760
761 ULong64_t nEntries = h1->GetNbins();
762 for ( ULong64_t i = 0; i < nEntries; i++ )
763 {
764 double value = h1->GetBinContent( i, &coord[0] );
765 if ( !value ) continue;
766
767// std::cout << "FILLDATA(SparseData): h1(" << i << ")";
768
769 // Exclude underflows and overflows! (defect behaviour with the TH1*)
770 bool insertBox = true;
771 for ( int j = 0; j < dim && insertBox; ++j )
772 {
773 TAxis* axis = h1->GetAxis(j);
774 if ( ( axis->GetBinLowEdge(coord[j]) < axis->GetXmin() ) ||
775 ( axis->GetBinUpEdge(coord[j]) > axis->GetXmax() ) ) {
776 insertBox = false;
777 }
778 min[j] = h1->GetAxis(j)->GetBinLowEdge(coord[j]);
779 max[j] = h1->GetAxis(j)->GetBinUpEdge(coord[j]);
780 }
781 if ( !insertBox ) {
782// std::cout << "NOT INSERTED!"<< std::endl;
783 continue;
784 }
785
786// for ( int j = 0; j < dim; ++j )
787// {
788// std::cout << "[" << h1->GetAxis(j)->GetBinLowEdge(coord[j])
789// << "-" << h1->GetAxis(j)->GetBinUpEdge(coord[j]) << "]";
790// }
791// std::cout << h1->GetBinContent(i) << std::endl;
792
793 dv.Add(min, max, value, h1->GetBinError(i));
794 }
795}
796
797void FillData(BinData & dv, const THnBase * s1, TF1 * func)
798{
799 // Fill the Range of the THnBase
800 unsigned int const ndim = s1->GetNdimensions();
801 std::vector<double> xmin(ndim);
802 std::vector<double> xmax(ndim);
803 for ( unsigned int i = 0; i < ndim; ++i ) {
804 TAxis* axis = s1->GetAxis(i);
805 xmin[i] = axis->GetXmin();
806 xmax[i] = axis->GetXmax();
807 }
808
809 // Put default options, needed for the likelihood fitting of sparse
810 // data.
811 ROOT::Fit::DataOptions& dopt = dv.Opt();
812 //dopt.fUseEmpty = true;
813 // when using sparse data need to set option to use normalized bin volume, because sparse bins are merged together
814 //if (!dopt.fIntegral) dopt.fBinVolume = true;
815 dopt.fBinVolume = true;
816 dopt.fNormBinVolume = true;
817
818 // Get the sparse data
819 ROOT::Fit::SparseData d(ndim, &xmin[0], &xmax[0]);
820 ROOT::Fit::FillData(d, s1, func);
821
822// std::cout << "FillData(BinData & dv, const THnBase * s1, TF1 * func) (1)" << std::endl;
823
824 // Create the bin data from the sparse data
825 d.GetBinDataIntegral(dv);
826
827}
828
829void FillData ( BinData & dv, const TGraph * gr, TF1 * func ) {
830 // fill the data vector from a TGraph. Pass also the TF1 function which is
831 // needed in case to exclude points rejected by the function
832 assert(gr != nullptr);
833
834 // get fit option
835 DataOptions & fitOpt = dv.Opt();
836
838 // adjust option according to type
839 fitOpt.fErrors1 = (type == BinData::kNoError);
840 // set this if we want to have error=1 for points with zero errors (by default they are skipped)
841 // fitOpt.fUseEmpty = true;
842
843 // use coordinate or asym errors in case option is set and type is consistent
845 fitOpt.fAsymErrors &= (type == BinData::kAsymError);
846
847
848 // if data are filled already check if there are consistent - otherwise do nothing
849 if (dv.Size() > 0 && dv.NDim() == 1 ) {
850 // check if size is correct otherwise flag an errors
851 if ( dv.GetErrorType() != type ) {
852 Error("FillData","Inconsistent TGraph with previous data set- skip all graph data");
853 return;
854 }
855 }
856
857 DoFillData(dv, gr, type, func);
858
859}
860
861void FillData ( BinData & dv, const TMultiGraph * mg, TF1 * func ) {
862 // fill the data vector from a TMultiGraph. Pass also the TF1 function which is
863 // needed in case to exclude points rejected by the function
864 assert(mg != nullptr);
865
866 TList * grList = mg->GetListOfGraphs();
867 assert(grList != nullptr);
868
869#ifdef DEBUG
870// grList->Print();
871 TIter itr(grList, kIterBackward);
872 TObject *obj;
873 std::cout << "multi-graph list of graps: " << std::endl;
874 while ((obj = itr())) {
875 std::cout << obj->IsA()->GetName() << std::endl;
876 }
877
878#endif
879
880 // get fit option
881 DataOptions & fitOpt = dv.Opt();
882
883 // loop on the graphs to get the data type (use maximum)
884 TIter next(grList);
885
887 TGraph *gr = nullptr;
888 while ((gr = (TGraph*) next())) {
890 if (t > type ) type = t;
891 }
892 // adjust option according to type
893 fitOpt.fErrors1 = (type == BinData::kNoError);
894 // use coordinate or asym errors in case option is set and type is consistent
896 fitOpt.fAsymErrors &= (type == BinData::kAsymError);
897
898
899#ifdef DEBUG
900 std::cout << "Fitting MultiGraph of type " << type << std::endl;
901#endif
902
903 // fill the data now
904 next = grList;
905 while ((gr = (TGraph*) next())) {
906 DoFillData( dv, gr, type, func);
907 }
908
909#ifdef DEBUG
910 std::cout << "TGraphFitInterface::FillData MultiGraph FitData size is " << dv.Size() << std::endl;
911#endif
912
913}
914
915void FillData ( BinData & dv, const TGraph2D * gr, TF1 * func ) {
916 // fill the data vector from a TGraph2D. Pass also the TF1 function which is
917 // needed in case to exclude points rejected by the function
918 // in case of a pure TGraph
919 assert(gr != nullptr);
920
921 // get fit option
922 DataOptions & fitOpt = dv.Opt();
924 // adjust option according to type
925 fitOpt.fErrors1 = (type == BinData::kNoError);
927 fitOpt.fAsymErrors = false; // a TGraph2D with asymmetric errors does not exist
928
929 int nPoints = gr->GetN();
930 double *gx = gr->GetX();
931 double *gy = gr->GetY();
932 double *gz = gr->GetZ();
933
934 // if all errors are zero set option of using errors to 1
935 if ( gr->GetEZ() == nullptr) fitOpt.fErrors1 = true;
936
937 double x[2];
938 double ex[2];
939
940 // look at data range
941 const DataRange & range = dv.Range();
942 bool useRangeX = ( range.Size(0) > 0);
943 bool useRangeY = ( range.Size(1) > 0);
944 double xmin = 0;
945 double xmax = 0;
946 double ymin = 0;
947 double ymax = 0;
948 range.GetRange(xmin,xmax,ymin,ymax);
949
950 dv.Initialize(nPoints,2, type);
951
952 for ( int i = 0; i < nPoints; ++i) {
953
954 x[0] = gx[i];
955 x[1] = gy[i];
956
957 //if (fitOpt.fUseRange && HFitInterface::IsPointOutOfRange(func, x) ) continue;
958 if (useRangeX && ( x[0] < xmin || x[0] > xmax) ) continue;
959 if (useRangeY && ( x[1] < ymin || x[1] > ymax) ) continue;
960
961 // need to evaluate function to know about rejected points
962 // hugly but no other solutions
963 if (func) {
964 TF1::RejectPoint(false);
965 (*func)( x ); // evaluate using stored function parameters
966 if (TF1::RejectedPoint() ) continue;
967 }
968
969 if (type == BinData::kNoError) {
970 dv.Add( x, gz[i] );
971 continue;
972 }
973
974 double errorZ = gr->GetErrorZ(i);
975 if (!HFitInterface::AdjustError(fitOpt,errorZ) ) continue;
976
977 if (type == BinData::kValueError) {
978 dv.Add( x, gz[i], errorZ );
979 }
980 else if (type == BinData::kCoordError) { // case use error in coordinates (x and y)
981 ex[0] = std::max(gr->GetErrorX(i), 0.);
982 ex[1] = std::max(gr->GetErrorY(i), 0.);
983 dv.Add( x, gz[i], ex, errorZ );
984 }
985 else
986 assert(0); // should not go here
987
988#ifdef DEBUG
989 std::cout << "Point " << i << " " << gx[i] << " " << gy[i] << " " << errorZ << std::endl;
990#endif
991
992 }
993
994#ifdef DEBUG
995 std::cout << "THFitInterface::FillData Graph2D FitData size is " << dv.Size() << std::endl;
996#endif
997
998}
999
1000
1001// confidence intervals
1003 if (h1->GetDimension() != 1) {
1004 Error("GetConfidenceIntervals","Invalid object used for storing confidence intervals");
1005 return false;
1006 }
1007 // fill fit data sets with points to estimate cl.
1008 BinData d;
1009 FillData(d,h1,nullptr);
1010 gr->Set(d.NPoints() );
1011 double * ci = gr->GetEY(); // make CL values error of the graph
1012 result.GetConfidenceIntervals(d,ci,cl);
1013 // put function value as abscissa of the graph
1014 for (unsigned int ipoint = 0; ipoint < d.NPoints(); ++ipoint) {
1015 const double * x = d.Coords(ipoint);
1016 const ROOT::Math::IParamMultiFunction * func = result.FittedFunction();
1017 gr->SetPoint(ipoint, x[0], (*func)(x) );
1018 }
1019 return true;
1020}
1021
1022} // end namespace Fit
1023
1024} // end namespace ROOT
#define d(i)
Definition RSha256.hxx:102
#define s1(x)
Definition RSha256.hxx:91
unsigned long long ULong64_t
Portable unsigned long integer 8 bytes.
Definition RtypesCore.h:85
const Bool_t kIterBackward
Definition TCollection.h:43
void Error(const char *location, const char *msgfmt,...)
Use this function in case an error occurred.
Definition TError.cxx:208
void Warning(const char *location, const char *msgfmt,...)
Use this function in warning situations.
Definition TError.cxx:252
Option_t Option_t option
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 Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
float xmin
float ymin
float xmax
float ymax
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition BinData.h:52
void AddBinUpEdge(const double *xup)
add the bin width data, a pointer to an array with the bin upper edge information.
Definition BinData.cxx:613
ErrorType GetErrorType() const
retrieve the errortype
Definition BinData.h:562
void Add(double x, double y)
add one dim data with only coordinate and values
Definition BinData.cxx:408
void Initialize(unsigned int newPoints, unsigned int dim=1, ErrorType err=kValueError)
Preallocate a data set with given size, dimension and error type.
Definition BinData.h:122
class describing the range in the coordinates it supports multiple range in a coordinate.
Definition DataRange.h:35
unsigned int Size(unsigned int icoord=0) const
return range size for coordinate icoord (starts from zero) Size == 0 indicates no range is present [-...
Definition DataRange.h:71
void GetRange(unsigned int irange, unsigned int icoord, double &xmin, double &xmax) const
get the i-th range for given coordinate.
Definition DataRange.h:104
unsigned int Size() const
return number of fit points
Definition FitData.h:292
unsigned int NDim() const
return coordinate data dimension
Definition FitData.h:300
const DataOptions & Opt() const
access to options
Definition FitData.h:308
const DataRange & Range() const
access to range
Definition FitData.h:320
class containing the result of the fit and all the related information (fitted parameter values,...
Definition FitResult.h:44
SparseData class representing the data of a THNSparse histogram The data needs to be converted to a B...
Definition SparseData.h:35
void Add(std::vector< double > &min, std::vector< double > &max, const double content, const double error=1.0)
Adds a new bin specified by the vectors.
Class to manage histogram axis.
Definition TAxis.h:32
virtual Double_t GetBinCenter(Int_t bin) const
Return center of bin.
Definition TAxis.cxx:489
Double_t GetXmax() const
Definition TAxis.h:142
virtual Double_t GetBinLowEdge(Int_t bin) const
Return low edge of bin.
Definition TAxis.cxx:529
virtual Int_t FindFixBin(Double_t x) const
Find bin number corresponding to abscissa x
Definition TAxis.cxx:422
Int_t GetLast() const
Return last bin on the axis i.e.
Definition TAxis.cxx:480
Double_t GetXmin() const
Definition TAxis.h:141
virtual Double_t GetBinWidth(Int_t bin) const
Return bin width.
Definition TAxis.cxx:553
virtual Double_t GetBinUpEdge(Int_t bin) const
Return up edge of bin.
Definition TAxis.cxx:539
Int_t GetFirst() const
Return first bin on the axis i.e.
Definition TAxis.cxx:469
1-Dim function class
Definition TF1.h:182
static void RejectPoint(Bool_t reject=kTRUE)
Static function to set the global flag to reject points the fgRejectPoint global flag is tested by al...
Definition TF1.cxx:3724
virtual Int_t GetNpar() const
Definition TF1.h:446
virtual void GetRange(Double_t *xmin, Double_t *xmax) const
Return range of a generic N-D function.
Definition TF1.cxx:2330
virtual void SetParLimits(Int_t ipar, Double_t parmin, Double_t parmax)
Set lower and upper limits for parameter ipar.
Definition TF1.cxx:3563
static Bool_t RejectedPoint()
See TF1::RejectPoint above.
Definition TF1.cxx:3733
virtual void SetParameters(const Double_t *params)
Definition TF1.h:618
virtual void SetParameter(Int_t param, Double_t value)
Definition TF1.h:608
virtual Bool_t IsInside(const Double_t *x) const
return kTRUE if the point is inside the function range
Definition TF1.h:567
virtual Int_t GetNdim() const
Definition TF1.h:450
Graphics object made of three arrays X, Y and Z with the same number of points each.
Definition TGraph2D.h:41
A TGraphErrors is a TGraph with error bars.
Double_t GetErrorY(Int_t bin) const override
It returns the error along Y at point i.
Double_t * GetEX() const override
Double_t GetErrorX(Int_t bin) const override
It returns the error along X at point i.
Double_t * GetEY() const override
Double_t GetErrorXhigh(Int_t bin) const override
It returns the error along X at point i.
Double_t GetErrorYlow(Int_t bin) const override
It returns the error along Y at point i.
Double_t GetErrorYhigh(Int_t bin) const override
It returns the error along Y at point i.
TClass * IsA() const override
Double_t GetErrorXlow(Int_t bin) const override
It returns the error along X at point i.
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
Definition TGraph.cxx:2386
Double_t * GetY() const
Definition TGraph.h:139
virtual Double_t * GetEYlow() const
Definition TGraph.h:145
Int_t GetN() const
Definition TGraph.h:131
Double_t * GetX() const
Definition TGraph.h:138
virtual Double_t * GetEYhigh() const
Definition TGraph.h:144
virtual void Set(Int_t n)
Set number of points in the graph Existing coordinates are preserved New coordinates above fNpoints a...
Definition TGraph.cxx:2314
TH1 is the base class of all histogram classes in ROOT.
Definition TH1.h:126
TAxis * GetZaxis()
Definition TH1.h:603
virtual Double_t GetBinError(Int_t bin) const
Return value of error associated to bin number bin.
Definition TH1.cxx:9293
virtual Int_t GetDimension() const
Definition TH1.h:557
TAxis * GetXaxis()
Definition TH1.h:601
virtual void GetBinXYZ(Int_t binglobal, Int_t &binx, Int_t &biny, Int_t &binz) const
Return binx, biny, binz corresponding to the global bin number globalbin see TH1::GetBin function abo...
Definition TH1.cxx:5150
virtual Int_t GetNcells() const
Definition TH1.h:574
TAxis * GetYaxis()
Definition TH1.h:602
Bool_t IsBinUnderflow(Int_t bin, Int_t axis=0) const
Return true if the bin is underflow.
Definition TH1.cxx:5392
Bool_t IsBinOverflow(Int_t bin, Int_t axis=0) const
Return true if the bin is overflow.
Definition TH1.cxx:5360
virtual Double_t GetBinLowEdge(Int_t bin) const
Return bin lower edge for 1D histogram.
Definition TH1.cxx:9382
virtual Double_t GetBinContent(Int_t bin) const
Return content of bin number bin.
Definition TH1.cxx:5239
Multidimensional histogram base.
Definition THnBase.h:45
A doubly linked list.
Definition TList.h:38
A TMultiGraph is a collection of TGraph (or derived) objects.
Definition TMultiGraph.h:34
TList * GetListOfGraphs() const
Definition TMultiGraph.h:70
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
Mother of all ROOT objects.
Definition TObject.h:42
virtual TClass * IsA() const
Definition TObject.h:248
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
Double_t ey[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
TGraphErrors * gr
Definition legend1.C:25
Double_t ex[n]
Definition legend1.C:17
TH1F * h1
Definition legend1.C:5
TF1 * f1
Definition legend1.C:11
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
Definition HFitImpl.cxx:133
void ExamineRange(const TAxis *axis, std::pair< double, double > range, int &hxfirst, int &hxlast)
bool AdjustError(const DataOptions &option, double &error, double value=1)
bool IsPointOutOfRange(const TF1 *func, const double *x)
void InitPolynom(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for a polynomial function given the fit data Set the parameters to an unwei...
void Init2DGaus(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for 2D gaussian function given the fit data Set the sigma limits for zero t...
void FillData(BinData &dv, const TH1 *hist, TF1 *func=nullptr)
fill the data vector from a TH1.
void InitExpo(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for an exponential function given the fit data Set the constant and slope a...
void InitGaus(const ROOT::Fit::BinData &data, TF1 *f1)
compute initial parameter for gaussian function given the fit data Set the sigma limits for zero top ...
void DoFillData(BinData &dv, const TGraph *gr, BinData::ErrorType type, TF1 *func)
BinData::ErrorType GetDataType(const TGraph *gr, DataOptions &fitOpt)
bool GetConfidenceIntervals(const TH1 *h1, const ROOT::Fit::FitResult &r, TGraphErrors *gr, double cl=0.95)
compute confidence intervals at level cl for a fitted histogram h1 in a TGraphErrors gr
DataOptions : simple structure holding the options on how the data are filled.
Definition DataOptions.h:28
bool fErrors1
use all errors equal to 1, i.e. fit without errors (default is false)
Definition DataOptions.h:52
bool fAsymErrors
use asymmetric errors in the value when available, selecting them according to the on sign of residua...
Definition DataOptions.h:55
bool fNormBinVolume
normalize data by a normalized the bin volume (bin volume divided by a reference value)
Definition DataOptions.h:49
bool fIntegral
use integral of bin content instead of bin center (default is false)
Definition DataOptions.h:47
bool fBinVolume
normalize data by the bin volume (it is used in the Poisson likelihood fits)
Definition DataOptions.h:48
bool fCoordErrors
use errors on the x coordinates when available (default is true)
Definition DataOptions.h:54