Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
FitResult.cxx
Go to the documentation of this file.
1// @(#)root/mathcore:$Id$
2// Author: L. Moneta Wed Aug 30 11:05:34 2006
3
4/**********************************************************************
5 * *
6 * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7 * *
8 * *
9 **********************************************************************/
10
11// Implementation file for class FitResult
12
13#include "Fit/FitResult.h"
14
15#include "Fit/FitConfig.h"
16
17#include "Fit/BinData.h"
18
19//#include "Fit/Chi2FCN.h"
20
21#include "Math/Minimizer.h"
22
23#include "Math/IParamFunction.h"
25
28
29#include "TMath.h"
31#include "Math/Error.h"
32
33#include <cassert>
34#include <cmath>
35#include <iostream>
36#include <iomanip>
37
38namespace ROOT {
39
40 namespace Fit {
41
42
43const int gInitialResultStatus = -99; // use this special convention to flag it when printing result
44
46 fValid(false), fNormalized(false), fNFree(0), fNdf(0), fNCalls(0),
47 fStatus(-1), fCovStatus(0), fVal(0), fEdm(-1), fChi2(-1)
48{
49 // Default constructor implementation.
50}
51
54 fNormalized(false),
55 fNFree(0),
56 fNdf(0),
57 fNCalls(0),
59 fCovStatus(0),
60 fVal(0),
61 fEdm(-1),
62 fChi2(-1),
63 fFitFunc(nullptr),
64 fParams(std::vector<double>( fconfig.NPar() ) ),
65 fErrors(std::vector<double>( fconfig.NPar() ) ),
66 fParNames(std::vector<std::string> ( fconfig.NPar() ) )
67{
68 // create a Fit result from a fit config (i.e. with initial parameter values
69 // and errors equal to step values
70 // The model function is NULL in this case
71
72 // set minimizer type and algorithm
73 fMinimType = fconfig.MinimizerType();
74 // append algorithm name for minimizer that support it
75 if ( (fMinimType.find("Fumili") == std::string::npos) )
76 {
77 if (!fconfig.MinimizerAlgoType().empty()) fMinimType += " / " + fconfig.MinimizerAlgoType();
78 }
79
80 // get parameter values and errors (step sizes)
81 unsigned int npar = fconfig.NPar();
82 for (unsigned int i = 0; i < npar; ++i ) {
83 const ParameterSettings & par = fconfig.ParSettings(i);
84 fParams[i] = par.Value();
85 fErrors[i] = par.StepSize();
86 fParNames[i] = par.Name();
87 if (par.IsFixed() ) fFixedParams[i] = true;
88 else fNFree++;
89 if (par.IsBound() ) {
90 double lower = (par.HasLowerLimit()) ? par.LowerLimit() : - std::numeric_limits<double>::infinity() ;
91 double upper = (par.HasUpperLimit()) ? par.UpperLimit() : std::numeric_limits<double>::infinity() ;
92 fBoundParams[i] = fParamBounds.size();
93 fParamBounds.push_back(std::make_pair(lower,upper));
94 }
95 }
96 std::cout << "create fit result from config - nfree " << fNFree << std::endl;
97}
98
99void FitResult::FillResult(const std::shared_ptr<ROOT::Math::Minimizer> & min, const FitConfig & fconfig, const std::shared_ptr<IModelFunction> & func,
100 bool isValid, unsigned int sizeOfData, int fitType, const ROOT::Math::IMultiGenFunction * chi2func, unsigned int ncalls )
101{
102 // Fill the FitResult after minimization using result from Minimizers
103
104 // minimizer must exist
105 assert(min);
106
107 fValid = isValid;
108 fNFree= min->NFree();
109 fNCalls = min->NCalls();
110 fStatus = min->Status();
111 fCovStatus= min->CovMatrixStatus();
112 fVal = min->MinValue();
113 fEdm = min->Edm();
114
115 fMinimizer= min;
116 fFitFunc = func;
117
118 fMinimType = fconfig.MinimizerName();
119
120 // replace ncalls if minimizer does not support it (they are taken then from the FitMethodFunction)
121 if (fNCalls == 0) fNCalls = ncalls;
122
123 const unsigned int npar = min->NDim();
124 if (npar == 0) return;
125
126 if (min->X() )
127 fParams = std::vector<double>(min->X(), min->X() + npar);
128 else {
129 // case minimizer does not provide minimum values (it failed) take from configuration
130 fParams.resize(npar);
131 for (unsigned int i = 0; i < npar; ++i ) {
132 fParams[i] = ( fconfig.ParSettings(i).Value() );
133 }
134 }
135
136 if (sizeOfData > min->NFree() ) fNdf = sizeOfData - min->NFree();
137
138
139 // set right parameters in function (in case minimizer did not do before)
140 // do also when fit is not valid
141 if (func ) {
142 // I think we can avoid cloning the model function
143 //fFitFunc = dynamic_cast<IModelFunction *>( func->Clone() );
144 //assert(fFitFunc);
145 fFitFunc->SetParameters(&fParams.front());
146 }
147 else {
148 // when no fFitFunc is present take parameters from FitConfig
149 fParNames.resize( npar );
150 for (unsigned int i = 0; i < npar; ++i ) {
151 fParNames[i] = fconfig.ParSettings(i).Name();
152 }
153 }
154
155
156 // check for fixed or limited parameters
157 unsigned int nfree = 0;
158 if (!fParamBounds.empty()) fParamBounds.clear();
159 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
160 const ParameterSettings & par = fconfig.ParSettings(ipar);
161 if (par.IsFixed() ) fFixedParams[ipar] = true;
162 else nfree++;
163 if (par.IsBound() ) {
164 double lower = (par.HasLowerLimit()) ? par.LowerLimit() : - std::numeric_limits<double>::infinity() ;
165 double upper = (par.HasUpperLimit()) ? par.UpperLimit() : std::numeric_limits<double>::infinity() ;
166 fBoundParams[ipar] = fParamBounds.size();
167 fParamBounds.push_back(std::make_pair(lower,upper));
168 }
169 }
170 // check if nfree (from FitConfig) and fNFree (from minimizer) are consistent
171 if (nfree != fNFree ) {
172 MATH_ERROR_MSG("FitResult","FitConfiguration and Minimizer result are not consistent");
173 std::cout << "Number of free parameters from FitConfig = " << nfree << std::endl;
174 std::cout << "Number of free parameters from Minimizer = " << fNFree << std::endl;
175 }
176
177 // if flag is binned compute a chi2 when a chi2 function is given
178 if (fitType == 1) {
179 if (chi2func == nullptr)
180 fChi2 = fVal;
181 else {
182 // compute chi2 equivalent for likelihood fits
183 // NB: empty bins are considered
184 fChi2 = (*chi2func)(&fParams[0]);
185 }
186 }
187 else if (fitType == 3) {
188 // case of binned likelihood fits (use Baker-Cousins chi2)
189 fChi2 = 2 * fVal;
190 }
191
192 // fill error matrix
193 // if minimizer provides error provides also error matrix
194 // clear in case of re-filling an existing result
195 if (!fCovMatrix.empty()) fCovMatrix.clear();
196 if (!fGlobalCC.empty()) fGlobalCC.clear();
197
198 if (min->Errors() != nullptr) {
199
200 fErrors = std::vector<double>(min->Errors(), min->Errors() + npar ) ;
201
202 if (fCovStatus != 0) {
203 unsigned int r = npar * ( npar + 1 )/2;
204 fCovMatrix.reserve(r);
205 for (unsigned int i = 0; i < npar; ++i)
206 for (unsigned int j = 0; j <= i; ++j)
207 fCovMatrix.push_back(min->CovMatrix(i,j) );
208 }
209 // minos errors are set separately when calling Fitter::CalculateMinosErrors()
210
211 // globalCC
212 fGlobalCC.reserve(npar);
213 for (unsigned int i = 0; i < npar; ++i) {
214 double globcc = min->GlobalCC(i);
215 if (globcc < 0) break; // it is not supported by that minimizer
216 fGlobalCC.push_back(globcc);
217 }
218
219 }
220
221}
222
223bool FitResult::Update(const std::shared_ptr<ROOT::Math::Minimizer> & min, const ROOT::Fit::FitConfig & fconfig, bool isValid, unsigned int ncalls) {
224 // update fit result with new status from minimizer
225 // ncalls if it is not zero is used instead of value from minimizer
226
227 fMinimizer = min;
228
229 // in case minimizer changes
230 fMinimType = fconfig.MinimizerName();
231
232 const unsigned int npar = fParams.size();
233 if (min->NDim() != npar ) {
234 MATH_ERROR_MSG("FitResult::Update","Wrong minimizer status ");
235 return false;
236 }
237 if (min->X() == nullptr ) {
238 MATH_ERROR_MSG("FitResult::Update","Invalid minimizer status ");
239 return false;
240 }
241 if (fNFree != min->NFree() ) {
242 MATH_ERROR_MSG("FitResult::Update","Configuration has changed ");
243 return false;
244 }
245
246 fValid = isValid;
247 // update minimum value
248 fVal = min->MinValue();
249 fEdm = min->Edm();
250 fStatus = min->Status();
251 fCovStatus = min->CovMatrixStatus();
252
253 // update number of function calls
254 if ( min->NCalls() > 0) fNCalls = min->NCalls();
255 else fNCalls = ncalls;
256
257 // copy parameter value and errors
258 std::copy(min->X(), min->X() + npar, fParams.begin());
259
260
261 // set parameters in fit model function
262 if (fFitFunc) fFitFunc->SetParameters(&fParams.front());
263
264 if (min->Errors() != nullptr) {
265
266 if (fErrors.size() != npar) fErrors.resize(npar);
267
268 std::copy(min->Errors(), min->Errors() + npar, fErrors.begin() ) ;
269
270 if (fCovStatus != 0) {
271
272 // update error matrix
273 unsigned int r = npar * ( npar + 1 )/2;
274 if (fCovMatrix.size() != r) fCovMatrix.resize(r);
275 unsigned int l = 0;
276 for (unsigned int i = 0; i < npar; ++i) {
277 for (unsigned int j = 0; j <= i; ++j)
278 fCovMatrix[l++] = min->CovMatrix(i,j);
279 }
280 }
281
282 // update global CC
283 if (fGlobalCC.size() != npar) fGlobalCC.resize(npar);
284 for (unsigned int i = 0; i < npar; ++i) {
285 double globcc = min->GlobalCC(i);
286 if (globcc < 0) {
287 fGlobalCC.clear();
288 break; // it is not supported by that minimizer
289 }
290 fGlobalCC[i] = globcc;
291 }
292
293 }
294 return true;
295}
296
298 // normalize errors and covariance matrix according to chi2 value
299 if (fNdf == 0 || fChi2 <= 0) return;
300 double s2 = fChi2/fNdf;
301 double s = std::sqrt(fChi2/fNdf);
302 for (unsigned int i = 0; i < fErrors.size() ; ++i)
303 fErrors[i] *= s;
304 for (unsigned int i = 0; i < fCovMatrix.size() ; ++i)
305 fCovMatrix[i] *= s2;
306
307 fNormalized = true;
308}
309
310void FitResult::SetChi2AndNdf(double chi2, unsigned int npoints) {
311 if (chi2 >= 0)
312 fChi2 = chi2;
313 if (npoints > fNFree )
314 fNdf = npoints - fNFree;
315 else
316 fNdf = 0;
317}
318
319double FitResult::Prob() const {
320 // fit probability
321 return ROOT::Math::chisquared_cdf_c(fChi2, static_cast<double>(fNdf) );
322}
323
324bool FitResult::HasMinosError(unsigned int i) const {
325 // query if the parameter i has the Minos error
326 std::map<unsigned int, std::pair<double,double> >::const_iterator itr = fMinosErrors.find(i);
327 return (itr != fMinosErrors.end() );
328}
329
330
331double FitResult::LowerError(unsigned int i) const {
332 // return lower Minos error for parameter i
333 // return the parabolic error if Minos error has not been calculated for the parameter i
334 std::map<unsigned int, std::pair<double,double> >::const_iterator itr = fMinosErrors.find(i);
335 return ( itr != fMinosErrors.end() ) ? itr->second.first : Error(i) ;
336}
337
338double FitResult::UpperError(unsigned int i) const {
339 // return upper Minos error for parameter i
340 // return the parabolic error if Minos error has not been calculated for the parameter i
341 std::map<unsigned int, std::pair<double,double> >::const_iterator itr = fMinosErrors.find(i);
342 return ( itr != fMinosErrors.end() ) ? itr->second.second : Error(i) ;
343}
344
345void FitResult::SetMinosError(unsigned int i, double elow, double eup) {
346 // set the Minos error for parameter i
347 fMinosErrors[i] = std::make_pair(elow,eup);
348}
349
350int FitResult::Index(const std::string & name) const {
351 // find index for given parameter name
352 if (! fFitFunc) return -1;
353 unsigned int npar = fParams.size();
354 for (unsigned int i = 0; i < npar; ++i)
355 if ( fFitFunc->ParameterName(i) == name) return i;
356
357 return -1; // case name is not found
358}
359
360bool FitResult::IsParameterBound(unsigned int ipar) const {
361 return fBoundParams.find(ipar) != fBoundParams.end();
362}
363
364bool FitResult::IsParameterFixed(unsigned int ipar) const {
365 return fFixedParams.find(ipar) != fFixedParams.end();
366}
367
368bool FitResult::ParameterBounds(unsigned int ipar, double & lower, double & upper) const {
369 std::map<unsigned int, unsigned int>::const_iterator itr = fBoundParams.find(ipar);
370 if (itr == fBoundParams.end() ) {
371 lower = -std::numeric_limits<Double_t>::infinity();
372 upper = std::numeric_limits<Double_t>::infinity();
373 return false;
374 }
375 assert(itr->second < fParamBounds.size() );
376 lower = fParamBounds[itr->second].first;
377 upper = fParamBounds[itr->second].second;
378 return true;
379}
380
381std::string FitResult::ParName(unsigned int ipar) const {
382 // return parameter name
383 if (fFitFunc) return fFitFunc->ParameterName(ipar);
384 else if (ipar < fParNames.size() ) return fParNames[ipar];
385 return "param_" + ROOT::Math::Util::ToString(ipar);
386}
387
388void FitResult::Print(std::ostream & os, bool doCovMatrix) const {
389 // print the result in the given stream
390 // need to add also minos errors , globalCC, etc..
391 unsigned int npar = fParams.size();
392 if (npar == 0) {
393 os << "<Empty FitResult>\n";
394 return;
395 }
396 os << "****************************************\n";
397 if (!fValid) {
399 os << " Invalid FitResult";
400 os << " (status = " << fStatus << " )";
401 }
402 else {
403 os << " FitResult before fitting";
404 }
405 os << "\n****************************************\n";
406 }
407
408 //os << " FitResult \n\n";
409 os << "Minimizer is " << fMinimType << std::endl;
410 const unsigned int nw = 25; // spacing for text
411 const unsigned int nn = 12; // spacing for numbers
412 const std::ios_base::fmtflags prFmt = os.setf(std::ios::left,std::ios::adjustfield); // set left alignment
413
414 if (fVal != fChi2 || fChi2 < 0)
415 os << std::left << std::setw(nw) << "MinFCN" << " = " << std::right << std::setw(nn) << fVal << std::endl;
416 if (fChi2 >= 0)
417 os << std::left << std::setw(nw) << "Chi2" << " = " << std::right << std::setw(nn) << fChi2 << std::endl;
418 os << std::left << std::setw(nw) << "NDf" << " = " << std::right << std::setw(nn) << fNdf << std::endl;
419 if (fMinimType.find("Linear") == std::string::npos) { // no need to print this for linear fits
420 if (fEdm >=0) os << std::left << std::setw(nw) << "Edm" << " = " << std::right << std::setw(nn) << fEdm << std::endl;
421 os << std::left << std::setw(nw) << "NCalls" << " = " << std::right << std::setw(nn) << fNCalls << std::endl;
422 }
423 for (unsigned int i = 0; i < npar; ++i) {
424 os << std::left << std::setw(nw) << GetParameterName(i);
425 os << " = " << std::right << std::setw(nn) << fParams[i];
426 if (IsParameterFixed(i) )
427 os << std::setw(9) << " " << std::setw(nn) << " " << " \t (fixed)";
428 else {
429 if (!fErrors.empty())
430 os << " +/- " << std::left << std::setw(nn) << fErrors[i] << std::right;
431 if (HasMinosError(i))
432 os << " " << std::left << std::setw(nn) << LowerError(i) << " +" << std::setw(nn) << UpperError(i)
433 << " (Minos) ";
434 if (IsParameterBound(i))
435 os << " \t (limited)";
436 }
437 os << std::endl;
438 }
439
440 // restore stremam adjustfield
441 if (prFmt != os.flags() ) os.setf(prFmt, std::ios::adjustfield);
442
444}
445
446void FitResult::PrintCovMatrix(std::ostream &os) const {
447 // print the covariance and correlation matrix
448 if (!fValid) return;
449 if (fCovMatrix.empty()) return;
450// os << "****************************************\n";
451 os << "\nCovariance Matrix:\n\n";
452 unsigned int npar = fParams.size();
453 const int kPrec = 5;
454 const int kWidth = 8;
455 const int parw = 12;
456 const int matw = kWidth+4;
457
458 // query previous precision and format flags
459 int prevPrec = os.precision(kPrec);
460 const std::ios_base::fmtflags prevFmt = os.flags();
461
462 os << std::setw(parw) << " " << "\t";
463 for (unsigned int i = 0; i < npar; ++i) {
464 if (!IsParameterFixed(i) ) {
465 os << std::right << std::setw(matw) << GetParameterName(i) ;
466 }
467 }
468 os << std::endl;
469 for (unsigned int i = 0; i < npar; ++i) {
470 if (!IsParameterFixed(i) ) {
471 os << std::left << std::setw(parw) << GetParameterName(i) << "\t";
472 for (unsigned int j = 0; j < npar; ++j) {
473 if (!IsParameterFixed(j) ) {
474 os.precision(kPrec); os.width(kWidth); os << std::right << std::setw(matw) << CovMatrix(i,j);
475 }
476 }
477 os << std::endl;
478 }
479 }
480// os << "****************************************\n";
481 os << "\nCorrelation Matrix:\n\n";
482 os << std::setw(parw) << " " << "\t";
483 for (unsigned int i = 0; i < npar; ++i) {
484 if (!IsParameterFixed(i) ) {
485 os << std::right << std::setw(matw) << GetParameterName(i) ;
486 }
487 }
488 os << std::endl;
489 for (unsigned int i = 0; i < npar; ++i) {
490 if (!IsParameterFixed(i) ) {
491 os << std::left << std::setw(parw) << std::left << GetParameterName(i) << "\t";
492 for (unsigned int j = 0; j < npar; ++j) {
493 if (!IsParameterFixed(j) ) {
494 os.precision(kPrec); os.width(kWidth); os << std::right << std::setw(matw) << Correlation(i,j);
495 }
496 }
497 os << std::endl;
498 }
499 }
500 // restore alignment and precision
501 os.setf(prevFmt, std::ios::adjustfield);
502 os.precision(prevPrec);
503}
504
505void FitResult::GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl, bool norm ) const {
506 // stride1 stride in coordinate stride2 stride in dimension space
507 // i.e. i-th point in k-dimension is x[ stride1 * i + stride2 * k]
508 // compute the confidence interval of the fit on the given data points
509 // the dimension of the data points must match the dimension of the fit function
510 // confidence intervals are returned in array ci
511
512 if (!fFitFunc) {
513 // check if model function exists
514 MATH_ERROR_MSG("FitResult::GetConfidenceIntervals","Cannot compute Confidence Intervals without fit model function");
515 return;
516 }
518
519 // use student quantile in case of normalized errors
520 double corrFactor = 1;
521 if (fChi2 <= 0 || fNdf == 0) norm = false;
522 if (norm)
523 corrFactor = TMath::StudentQuantile(0.5 + cl/2, fNdf) * std::sqrt( fChi2/fNdf );
524 else
525 // correction to apply to the errors given a CL different than 1 sigma (cl=0.683)
527
528
529
530 unsigned int ndim = fFitFunc->NDim();
531 unsigned int npar = fFitFunc->NPar();
532
533 std::vector<double> xpoint(ndim);
534 std::vector<double> grad(npar);
535 std::vector<double> vsum(npar);
536
537 // loop on the points
538 for (unsigned int ipoint = 0; ipoint < n; ++ipoint) {
539
540 for (unsigned int kdim = 0; kdim < ndim; ++kdim) {
541 unsigned int i = ipoint * stride1 + kdim * stride2;
542 assert(i < ndim*n);
543 xpoint[kdim] = x[i];
544 }
545
546 // calculate gradient of fitted function w.r.t the parameters
548 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
549 if (!IsParameterFixed(ipar)) {
551 d.SetFunction(fadapter);
552 // compute step size as a small fraction of the error
553 // (see numerical recipes in C 5.7.8) 1.E-5 is ~ (eps)^1/3
554 if ( fErrors[ipar] > 0 )
555 d.SetStepSize( std::max( fErrors[ipar]*1.E-5, 1.E-15) );
556 else
557 d.SetStepSize( std::min(std::max(fParams[ipar]*1.E-5, 1.E-15), 0.0001 ) );
558
559 grad[ipar] = d(fParams[ipar] ); // evaluate df/dp
560 }
561 else
562 grad[ipar] = 0.; // for fixed parameters
563 }
564
565 // multiply covariance matrix with gradient
566 vsum.assign(npar,0.0);
567 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
568 for (unsigned int jpar = 0; jpar < npar; ++jpar) {
569 vsum[ipar] += CovMatrix(ipar,jpar) * grad[jpar];
570 }
571 }
572 // multiply gradient by vsum
573 double r2 = 0;
574 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
575 r2 += grad[ipar] * vsum[ipar];
576 }
577 double r = std::sqrt(r2);
578 ci[ipoint] = r * corrFactor;
579 }
580}
581
582void FitResult::GetConfidenceIntervals(const BinData & data, double * ci, double cl, bool norm ) const {
583 // implement confidence intervals from a given bin data sets
584 // currently copy the data from Bindata.
585 // could implement otherwise directly
586 unsigned int ndim = data.NDim();
587 unsigned int np = data.NPoints();
588 std::vector<double> xdata( ndim * np );
589 for (unsigned int i = 0; i < np ; ++i) {
590 const double * x = data.Coords(i);
591 std::vector<double>::iterator itr = xdata.begin()+ ndim * i;
592 std::copy(x,x+ndim,itr);
593 }
594 // points are arranged as x0,y0,z0, ....xN,yN,zN (stride1=ndim, stride2=1)
595 GetConfidenceIntervals(np,ndim,1,&xdata.front(),ci,cl,norm);
596}
597
598std::vector<double> FitResult::GetConfidenceIntervals(double cl, bool norm ) const {
599 // implement confidence intervals using stored data sets (if can be retrieved from objective function)
600 // it works only in case of chi2 or binned likelihood fits
601 const BinData * data = FittedBinData();
602 std::vector<double> result;
603 if (data) {
604 result.resize(data->NPoints() );
605 GetConfidenceIntervals(*data, result.data(), cl, norm);
606 }
607 else {
608 MATH_ERROR_MSG("FitResult::GetConfidenceIntervals","Cannot compute Confidence Intervals without the fit bin data");
609 }
610 return result;
611}
612
613// const BinData * GetFitBinData() const {
614// // return a pointer to the binned data used in the fit
615// // works only for chi2 or binned likelihood fits
616// // thus when the objective function stored is a Chi2Func or a PoissonLikelihood
617// ROOT::Math::IMultiGenFunction * f = fObjFunc->get();
618// Chi2Function * chi2func = dynamic_cast<Chi2Function*>(f);
619// if (chi2func) return &(chi2func->Data());
620// PoissonLLFunction * pllfunc = dynamic_cast<PoissonLLFunction*>(f);
621// if (pllfunc) return &(pllfunc->Data());
622// Chi2GradFunction * chi2gradfunc = dynamic_cast<Chi2GradFunction*>(f);
623// if (chi2gradfunc) return &(chi2gradfunc->Data());
624// PoissonLLGradFunction * pllgradfunc = dynamic_cast<PoissonLLFunction*>(f);
625// if (pllgradfunc) return &(pllgradfunc->Data());
626// MATH_WARN_MSG("FitResult::GetFitBinData","Cannot return fit bin data set if objective function is not of a known type");
627// return nullptr;
628// }
629
631 return dynamic_cast<const BinData*> ( fFitData.get() );
632}
633
634////////////////////////////////////////////////////////////////////////////////
635/// Scan parameter ipar between value of xmin and xmax
636/// A array for x and y points should be provided
637
638bool FitResult::Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin, double xmax)
639{
640 if (!pntsx || !pntsy || !npoints)
641 return false;
642
643 if (!fMinimizer) {
644 MATH_ERROR_MSG("FitResult::Scan", "Minimizer is not available - cannot Scan");
645 return false;
646 }
647
648 return fMinimizer->Scan(ipar, npoints, pntsx, pntsy, xmin, xmax);
649}
650
651////////////////////////////////////////////////////////////////////////////////
652/// Create a 2D contour around the minimum for the parameter ipar and jpar
653/// if a minimum does not exist or is invalid it will return false
654/// A array for x and y points should be provided
655/// Pass optionally the confidence level, default is 0.683
656/// it is assumed that ErrorDef() defines the right error definition
657/// (i.e 1 sigma error for one parameter). If not the confidence level are scaled to new level
658
659bool FitResult::Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel)
660{
661 if (!pntsx || !pntsy || !npoints)
662 return false;
663
664 if (!fMinimizer) {
665 MATH_ERROR_MSG("FitResult::Contour", "Minimizer is not available - cannot produce Contour");
666 return false;
667 }
668
669 // get error level used for fitting
670 double upScale = fMinimizer->ErrorDef();
671
672 double upVal = TMath::ChisquareQuantile(confLevel, 2); // 2 is number of parameter we do the contour
673
674 // set required error definition in minimizer
675 fMinimizer->SetErrorDef(upScale * upVal);
676
677 bool ret = fMinimizer->Contour(ipar, jpar, npoints, pntsx, pntsy);
678
679 // restore the error level used for fitting
680 fMinimizer->SetErrorDef(upScale);
681
682 return ret;
683}
684
685 } // end namespace Fit
686
687} // end namespace ROOT
#define MATH_ERROR_MSG(loc, str)
Definition Error.h:83
#define d(i)
Definition RSha256.hxx:102
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 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 np
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 r
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
char name[80]
Definition TGX11.cxx:110
float xmin
float xmax
Bool_t fValid
Definition TProof.h:147
Int_t fStatus
Definition TProof.h:153
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition BinData.h:52
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition FitConfig.h:49
std::vector< double > fGlobalCC
global Correlation coefficient
Definition FitResult.h:363
unsigned int fNFree
number of fit free parameters (total parameters are in size of parameter vector)
Definition FitResult.h:345
bool Update(const std::shared_ptr< ROOT::Math::Minimizer > &min, const ROOT::Fit::FitConfig &fconfig, bool isValid, unsigned int ncalls=0)
Update the fit result with a new minimization status To be run only if same fit is performed with sam...
std::map< unsigned int, unsigned int > fBoundParams
list of limited parameters
Definition FitResult.h:358
const BinData * FittedBinData() const
return BinData used in the fit (return a nullptr in case a different fit is done or the data are not ...
void FillResult(const std::shared_ptr< ROOT::Math::Minimizer > &min, const FitConfig &fconfig, const std::shared_ptr< IModelFunction > &f, bool isValid, unsigned int sizeOfData=0, int fitType=1, const ROOT::Math::IMultiGenFunction *chi2func=nullptr, unsigned int ncalls=0)
Fill the fit result from a Minimizer instance after fitting Run also Minos if requested from the conf...
Definition FitResult.cxx:99
double UpperError(unsigned int i) const
upper Minos error. If Minos has not run for parameter i return the parabolic error
double fVal
minimum function value
Definition FitResult.h:350
double fEdm
expected distance from minimum
Definition FitResult.h:351
std::vector< double > fErrors
errors
Definition FitResult.h:361
std::shared_ptr< ROOT::Math::Minimizer > fMinimizer
! minimizer object used for fitting
Definition FitResult.h:353
bool fValid
flag for indicating valid fit
Definition FitResult.h:343
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
unsigned int fNdf
number of degree of freedom
Definition FitResult.h:346
double Error(unsigned int i) const
parameter error by index
Definition FitResult.h:179
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
Definition FitResult.h:215
void GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double *x, double *ci, double cl=0.95, bool norm=false) const
get confidence intervals for an array of n points x.
int fCovStatus
covariance matrix status code
Definition FitResult.h:349
bool Scan(unsigned int ipar, unsigned int &npoints, double *pntsx, double *pntsy, double xmin=0, double xmax=0)
scan likelihood value of parameter and fill the given graph.
FitResult()
Default constructor for an empty (non valid) fit result.
Definition FitResult.cxx:45
std::shared_ptr< FitData > fFitData
! data set used in the fit
Definition FitResult.h:356
std::string GetParameterName(unsigned int ipar) const
get name of parameter (deprecated)
Definition FitResult.h:327
bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const
retrieve parameter bounds - return false if parameter is not bound
std::vector< double > fParams
parameter values. Size is total number of parameters
Definition FitResult.h:360
std::vector< double > fCovMatrix
covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
Definition FitResult.h:362
void SetMinosError(unsigned int i, double elow, double eup)
set the Minos errors for parameter i (called by the Fitter class when running Minos)
void Print(std::ostream &os, bool covmat=false) const
print the result and optionally covariance matrix and correlations
double LowerError(unsigned int i) const
lower Minos error. If Minos has not run for parameter i return the parabolic error
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
unsigned int fNCalls
number of function calls
Definition FitResult.h:347
bool Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *pntsx, double *pntsy, double confLevel=0.683)
create contour of two parameters around the minimum pass as option confidence level: default is a val...
bool HasMinosError(unsigned int i) const
query if parameter i has the Minos error
std::vector< std::pair< double, double > > fParamBounds
parameter bounds
Definition FitResult.h:359
int fStatus
minimizer status code
Definition FitResult.h:348
double fChi2
fit chi2 value (different than fval in case of chi2 fits)
Definition FitResult.h:352
std::shared_ptr< IModelFunction > fFitFunc
! model function resulting from the fit.
Definition FitResult.h:355
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
Definition FitResult.h:357
std::string fMinimType
string indicating type of minimizer
Definition FitResult.h:365
double Correlation(unsigned int i, unsigned int j) const
retrieve correlation elements
Definition FitResult.h:225
int Index(const std::string &name) const
get index for parameter name (return -1 if not found)
double Prob() const
p value of the fit (chi2 probability)
std::string ParName(unsigned int i) const
name of the parameter
void NormalizeErrors()
normalize errors using chi2/ndf for chi2 fits
bool fNormalized
flag for indicating is errors are normalized
Definition FitResult.h:344
bool IsParameterBound(unsigned int ipar) const
query if a parameter is bound
std::vector< std::string > fParNames
parameter names (only with FCN only fits, when fFitFunc=0)
Definition FitResult.h:366
std::map< unsigned int, std::pair< double, double > > fMinosErrors
map contains the two Minos errors
Definition FitResult.h:364
void SetChi2AndNdf(double chi2, unsigned int npoints)
Set the chi2 and the ndf This function should be called when using an external FCN for fitting and on...
Class, describing value, limits and step size of the parameters Provides functionality also to set/re...
bool IsFixed() const
check if is fixed
bool HasUpperLimit() const
check if parameter has upper limit
double LowerLimit() const
return lower limit value
const std::string & Name() const
return name
bool HasLowerLimit() const
check if parameter has lower limit
double Value() const
return parameter value
double StepSize() const
return step size
double UpperLimit() const
return upper limit value
bool IsBound() const
check if is bound
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:63
OneDimParamFunctionAdapter class to wrap a multi-dim parametric function in one dimensional one.
User class for calculating the derivatives of a function.
const_iterator begin() const
double chisquared_cdf_c(double x, double r, double x0=0)
Complement of the cumulative distribution function of the distribution with degrees of freedom (upp...
double normal_quantile(double z, double sigma)
Inverse ( ) of the cumulative distribution function of the lower tail of the normal (Gaussian) distri...
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
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
const int gInitialResultStatus
Definition FitResult.cxx:43
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition Util.h:64
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
Double_t ChisquareQuantile(Double_t p, Double_t ndf)
Evaluate the quantiles of the chi-squared probability distribution function.
Definition TMath.cxx:2193
Double_t StudentQuantile(Double_t p, Double_t ndf, Bool_t lower_tail=kTRUE)
Computes quantiles of the Student's t-distribution 1st argument is the probability,...
Definition TMath.cxx:2673
TLine l
Definition textangle.C:4