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