Logo ROOT   6.14/05
Reference Guide
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 
26 #include "Math/ProbFuncMathCore.h"
27 #include "Math/QuantFuncMathCore.h"
28 
29 #include "TMath.h"
31 #include "Math/Error.h"
32 
33 #include <cassert>
34 #include <cmath>
35 #include <iostream>
36 #include <iomanip>
37 
38 namespace ROOT {
39 
40  namespace Fit {
41 
42 
43 const 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 
52 FitResult::FitResult(const FitConfig & fconfig) :
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(0),
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 
100 void 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, bool binnedFit, 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 
120 
121  // set minimizer type
122  fMinimType = fconfig.MinimizerType();
123 
124  // append algorithm name for minimizer that support it
125  if ( (fMinimType.find("Fumili") == std::string::npos) &&
126  (fMinimType.find("GSLMultiFit") == std::string::npos)
127  ) {
128  if (fconfig.MinimizerAlgoType() != "") fMinimType += " / " + fconfig.MinimizerAlgoType();
129  }
130 
131  // replace ncalls if minimizer does not support it (they are taken then from the FitMethodFunction)
132  if (fNCalls == 0) fNCalls = ncalls;
133 
134  const unsigned int npar = min->NDim();
135  if (npar == 0) return;
136 
137  if (min->X() )
138  fParams = std::vector<double>(min->X(), min->X() + npar);
139  else {
140  // case minimizer does not provide minimum values (it failed) take from configuration
141  fParams.resize(npar);
142  for (unsigned int i = 0; i < npar; ++i ) {
143  fParams[i] = ( fconfig.ParSettings(i).Value() );
144  }
145  }
146 
147  if (sizeOfData > min->NFree() ) fNdf = sizeOfData - min->NFree();
148 
149 
150  // set right parameters in function (in case minimizer did not do before)
151  // do also when fit is not valid
152  if (func ) {
153  // I think we can avoid cloning the model function
154  //fFitFunc = dynamic_cast<IModelFunction *>( func->Clone() );
155  //assert(fFitFunc);
156  fFitFunc->SetParameters(&fParams.front());
157  }
158  else {
159  // when no fFitFunc is present take parameters from FitConfig
160  fParNames.reserve( npar );
161  for (unsigned int i = 0; i < npar; ++i ) {
162  fParNames.push_back( fconfig.ParSettings(i).Name() );
163  }
164  }
165 
166 
167  // check for fixed or limited parameters
168  unsigned int nfree = 0;
169  for (unsigned int ipar = 0; ipar < npar; ++ipar) {
170  const ParameterSettings & par = fconfig.ParSettings(ipar);
171  if (par.IsFixed() ) fFixedParams[ipar] = true;
172  else nfree++;
173  if (par.IsBound() ) {
174  double lower = (par.HasLowerLimit()) ? par.LowerLimit() : - std::numeric_limits<double>::infinity() ;
175  double upper = (par.HasUpperLimit()) ? par.UpperLimit() : std::numeric_limits<double>::infinity() ;
176  fBoundParams[ipar] = fParamBounds.size();
177  fParamBounds.push_back(std::make_pair(lower,upper));
178  }
179  }
180  // check if nfree (from FitConfig) and fNFree (from minimizer) are consistent
181  if (nfree != fNFree ) {
182  MATH_ERROR_MSG("FitResult","FitConfiguration and Minimizer result are not consistent");
183  std::cout << "Number of free parameters from FitConfig = " << nfree << std::endl;
184  std::cout << "Number of free parameters from Minimizer = " << fNFree << std::endl;
185  }
186 
187  // if flag is binned compute a chi2 when a chi2 function is given
188  if (binnedFit) {
189  if (chi2func == 0)
190  fChi2 = fVal;
191  else {
192  // compute chi2 equivalent for likelihood fits
193  // NB: empty bins are considered
194  fChi2 = (*chi2func)(&fParams[0]);
195  }
196  }
197 
198  // fill error matrix
199  // if minimizer provides error provides also error matrix
200  if (min->Errors() != 0) {
201 
202  fErrors = std::vector<double>(min->Errors(), min->Errors() + npar ) ;
203 
204  if (fCovStatus != 0) {
205  unsigned int r = npar * ( npar + 1 )/2;
206  fCovMatrix.reserve(r);
207  for (unsigned int i = 0; i < npar; ++i)
208  for (unsigned int j = 0; j <= i; ++j)
209  fCovMatrix.push_back(min->CovMatrix(i,j) );
210  }
211 
212  // minos errors
213  if (fValid && fconfig.MinosErrors()) {
214  const std::vector<unsigned int> & ipars = fconfig.MinosParams();
215  unsigned int n = (ipars.size() > 0) ? ipars.size() : npar;
216  for (unsigned int i = 0; i < n; ++i) {
217  double elow, eup;
218  unsigned int index = (ipars.size() > 0) ? ipars[i] : i;
219  bool ret = min->GetMinosError(index, elow, eup);
220  if (ret) SetMinosError(index, elow, eup);
221  }
222  }
223 
224  // globalCC
225  fGlobalCC.reserve(npar);
226  for (unsigned int i = 0; i < npar; ++i) {
227  double globcc = min->GlobalCC(i);
228  if (globcc < 0) break; // it is not supported by that minimizer
229  fGlobalCC.push_back(globcc);
230  }
231 
232  }
233 
234 }
235 
237  // destructor. FitResult manages the fit Function pointer
238  //if (fFitFunc) delete fFitFunc;
239 }
240 
242  fFitFunc(0)
243 {
244  // Implementation of copy constructor
245  (*this) = rhs;
246 }
247 
249  // Implementation of assignment operator.
250  if (this == &rhs) return *this; // time saving self-test
251 
252  // Manages the fitted function
253  // if (fFitFunc) delete fFitFunc;
254  // fFitFunc = 0;
255  // if (rhs.fFitFunc != 0 ) {
256  // fFitFunc = dynamic_cast<IModelFunction *>( (rhs.fFitFunc)->Clone() );
257  // assert(fFitFunc != 0);
258  // }
259 
260  // copy all other data members
261  fValid = rhs.fValid;
262  fNormalized = rhs.fNormalized;
263  fNFree = rhs.fNFree;
264  fNdf = rhs.fNdf;
265  fNCalls = rhs.fNCalls;
266  fCovStatus = rhs.fCovStatus;
267  fStatus = rhs.fStatus;
268  fVal = rhs.fVal;
269  fEdm = rhs.fEdm;
270  fChi2 = rhs.fChi2;
271  fMinimizer = rhs.fMinimizer;
272  fObjFunc = rhs.fObjFunc;
273  fFitFunc = rhs.fFitFunc;
274 
278  fParams = rhs.fParams;
279  fErrors = rhs.fErrors;
280  fCovMatrix = rhs.fCovMatrix;
281  fGlobalCC = rhs.fGlobalCC;
283 
284  fMinimType = rhs.fMinimType;
285  fParNames = rhs.fParNames;
286 
287  return *this;
288 
289 }
290 
291 bool FitResult::Update(const std::shared_ptr<ROOT::Math::Minimizer> & min, bool isValid, unsigned int ncalls) {
292  // update fit result with new status from minimizer
293  // ncalls if it is not zero is used instead of value from minimizer
294 
295  fMinimizer = min;
296 
297  const unsigned int npar = fParams.size();
298  if (min->NDim() != npar ) {
299  MATH_ERROR_MSG("FitResult::Update","Wrong minimizer status ");
300  return false;
301  }
302  if (min->X() == 0 ) {
303  MATH_ERROR_MSG("FitResult::Update","Invalid minimizer status ");
304  return false;
305  }
306  //fNFree = min->NFree();
307  if (fNFree != min->NFree() ) {
308  MATH_ERROR_MSG("FitResult::Update","Configuration has changed ");
309  return false;
310  }
311 
312  fValid = isValid;
313  // update minimum value
314  fVal = min->MinValue();
315  fEdm = min->Edm();
316  fStatus = min->Status();
317  fCovStatus = min->CovMatrixStatus();
318 
319  // update number of function calls
320  if ( min->NCalls() > 0) fNCalls = min->NCalls();
321  else fNCalls = ncalls;
322 
323  // copy parameter value and errors
324  std::copy(min->X(), min->X() + npar, fParams.begin());
325 
326 
327  // set parameters in fit model function
328  if (fFitFunc) fFitFunc->SetParameters(&fParams.front());
329 
330  if (min->Errors() != 0) {
331 
332  if (fErrors.size() != npar) fErrors.resize(npar);
333 
334  std::copy(min->Errors(), min->Errors() + npar, fErrors.begin() ) ;
335 
336  if (fCovStatus != 0) {
337 
338  // update error matrix
339  unsigned int r = npar * ( npar + 1 )/2;
340  if (fCovMatrix.size() != r) fCovMatrix.resize(r);
341  unsigned int l = 0;
342  for (unsigned int i = 0; i < npar; ++i) {
343  for (unsigned int j = 0; j <= i; ++j)
344  fCovMatrix[l++] = min->CovMatrix(i,j);
345  }
346  }
347 
348  // update global CC
349  if (fGlobalCC.size() != npar) fGlobalCC.resize(npar);
350  for (unsigned int i = 0; i < npar; ++i) {
351  double globcc = min->GlobalCC(i);
352  if (globcc < 0) {
353  fGlobalCC.clear();
354  break; // it is not supported by that minimizer
355  }
356  fGlobalCC[i] = globcc;
357  }
358 
359  }
360  return true;
361 }
362 
364  // normalize errors and covariance matrix according to chi2 value
365  if (fNdf == 0 || fChi2 <= 0) return;
366  double s2 = fChi2/fNdf;
367  double s = std::sqrt(fChi2/fNdf);
368  for (unsigned int i = 0; i < fErrors.size() ; ++i)
369  fErrors[i] *= s;
370  for (unsigned int i = 0; i < fCovMatrix.size() ; ++i)
371  fCovMatrix[i] *= s2;
372 
373  fNormalized = true;
374 }
375 
376 
377 double FitResult::Prob() const {
378  // fit probability
379  return ROOT::Math::chisquared_cdf_c(fChi2, static_cast<double>(fNdf) );
380 }
381 
382 bool FitResult::HasMinosError(unsigned int i) const {
383  // query if the parameter i has the Minos error
384  std::map<unsigned int, std::pair<double,double> >::const_iterator itr = fMinosErrors.find(i);
385  return (itr != fMinosErrors.end() );
386 }
387 
388 
389 double FitResult::LowerError(unsigned int i) const {
390  // return lower Minos error for parameter i
391  // return the parabolic error if Minos error has not been calculated for the parameter i
392  std::map<unsigned int, std::pair<double,double> >::const_iterator itr = fMinosErrors.find(i);
393  return ( itr != fMinosErrors.end() ) ? itr->second.first : Error(i) ;
394 }
395 
396 double FitResult::UpperError(unsigned int i) const {
397  // return upper Minos error for parameter i
398  // return the parabolic error if Minos error has not been calculated for the parameter i
399  std::map<unsigned int, std::pair<double,double> >::const_iterator itr = fMinosErrors.find(i);
400  return ( itr != fMinosErrors.end() ) ? itr->second.second : Error(i) ;
401 }
402 
403 void FitResult::SetMinosError(unsigned int i, double elow, double eup) {
404  // set the Minos error for parameter i
405  fMinosErrors[i] = std::make_pair(elow,eup);
406 }
407 
408 int FitResult::Index(const std::string & name) const {
409  // find index for given parameter name
410  if (! fFitFunc) return -1;
411  unsigned int npar = fParams.size();
412  for (unsigned int i = 0; i < npar; ++i)
413  if ( fFitFunc->ParameterName(i) == name) return i;
414 
415  return -1; // case name is not found
416 }
417 
418 bool FitResult::IsParameterBound(unsigned int ipar) const {
419  return fBoundParams.find(ipar) != fBoundParams.end();
420 }
421 
422 bool FitResult::IsParameterFixed(unsigned int ipar) const {
423  return fFixedParams.find(ipar) != fFixedParams.end();
424 }
425 
426 bool FitResult::ParameterBounds(unsigned int ipar, double & lower, double & upper) const {
427  std::map<unsigned int, unsigned int>::const_iterator itr = fBoundParams.find(ipar);
428  if (itr == fBoundParams.end() ) {
429  lower = -std::numeric_limits<Double_t>::infinity();
430  upper = std::numeric_limits<Double_t>::infinity();
431  return false;
432  }
433  assert(itr->second < fParamBounds.size() );
434  lower = fParamBounds[itr->second].first;
435  upper = fParamBounds[itr->second].second;
436  return false;
437 }
438 
439 std::string FitResult::ParName(unsigned int ipar) const {
440  // return parameter name
441  if (fFitFunc) return fFitFunc->ParameterName(ipar);
442  else if (ipar < fParNames.size() ) return fParNames[ipar];
443  return "param_" + ROOT::Math::Util::ToString(ipar);
444 }
445 
446 void FitResult::Print(std::ostream & os, bool doCovMatrix) const {
447  // print the result in the given stream
448  // need to add also minos errors , globalCC, etc..
449  unsigned int npar = fParams.size();
450  if (npar == 0) {
451  os << "<Empty FitResult>\n";
452  return;
453  }
454  os << "\n****************************************\n";
455  if (!fValid) {
456  if (fStatus != gInitialResultStatus) {
457  os << " Invalid FitResult";
458  os << " (status = " << fStatus << " )";
459  }
460  else {
461  os << " FitResult before fitting";
462  }
463  os << "\n****************************************\n";
464  }
465 
466  //os << " FitResult \n\n";
467  os << "Minimizer is " << fMinimType << std::endl;
468  const unsigned int nw = 25; // spacing for text
469  const unsigned int nn = 12; // spacing for numbers
470  const std::ios_base::fmtflags prFmt = os.setf(std::ios::left,std::ios::adjustfield); // set left alignment
471 
472  if (fVal != fChi2 || fChi2 < 0)
473  os << std::left << std::setw(nw) << "MinFCN" << " = " << std::right << std::setw(nn) << fVal << std::endl;
474  if (fChi2 >= 0)
475  os << std::left << std::setw(nw) << "Chi2" << " = " << std::right << std::setw(nn) << fChi2 << std::endl;
476  os << std::left << std::setw(nw) << "NDf" << " = " << std::right << std::setw(nn) << fNdf << std::endl;
477  if (fMinimType.find("Linear") == std::string::npos) { // no need to print this for linear fits
478  if (fEdm >=0) os << std::left << std::setw(nw) << "Edm" << " = " << std::right << std::setw(nn) << fEdm << std::endl;
479  os << std::left << std::setw(nw) << "NCalls" << " = " << std::right << std::setw(nn) << fNCalls << std::endl;
480  }
481  for (unsigned int i = 0; i < npar; ++i) {
482  os << std::left << std::setw(nw) << GetParameterName(i);
483  os << " = " << std::right << std::setw(nn) << fParams[i];
484  if (IsParameterFixed(i) )
485  os << std::setw(9) << " " << std::setw(nn) << " " << " \t (fixed)";
486  else {
487  if (fErrors.size() != 0)
488  os << " +/- " << std::left << std::setw(nn) << fErrors[i] << std::right;
489  if (IsParameterBound(i) )
490  os << " \t (limited)";
491  }
492  os << std::endl;
493  }
494 
495  // restore stremam adjustfield
496  if (prFmt != os.flags() ) os.setf(prFmt, std::ios::adjustfield);
497 
498  if (doCovMatrix) PrintCovMatrix(os);
499 }
500 
501 void FitResult::PrintCovMatrix(std::ostream &os) const {
502  // print the covariance and correlation matrix
503  if (!fValid) return;
504  if (fCovMatrix.size() == 0) return;
505 // os << "****************************************\n";
506  os << "\nCovariance Matrix:\n\n";
507  unsigned int npar = fParams.size();
508  const int kPrec = 5;
509  const int kWidth = 8;
510  const int parw = 12;
511  const int matw = kWidth+4;
512 
513  // query previous precision and format flags
514  int prevPrec = os.precision(kPrec);
515  const std::ios_base::fmtflags prevFmt = os.flags();
516 
517  os << std::setw(parw) << " " << "\t";
518  for (unsigned int i = 0; i < npar; ++i) {
519  if (!IsParameterFixed(i) ) {
520  os << std::right << std::setw(matw) << GetParameterName(i) ;
521  }
522  }
523  os << std::endl;
524  for (unsigned int i = 0; i < npar; ++i) {
525  if (!IsParameterFixed(i) ) {
526  os << std::left << std::setw(parw) << GetParameterName(i) << "\t";
527  for (unsigned int j = 0; j < npar; ++j) {
528  if (!IsParameterFixed(j) ) {
529  os.precision(kPrec); os.width(kWidth); os << std::right << std::setw(matw) << CovMatrix(i,j);
530  }
531  }
532  os << std::endl;
533  }
534  }
535 // os << "****************************************\n";
536  os << "\nCorrelation Matrix:\n\n";
537  os << std::setw(parw) << " " << "\t";
538  for (unsigned int i = 0; i < npar; ++i) {
539  if (!IsParameterFixed(i) ) {
540  os << std::right << std::setw(matw) << GetParameterName(i) ;
541  }
542  }
543  os << std::endl;
544  for (unsigned int i = 0; i < npar; ++i) {
545  if (!IsParameterFixed(i) ) {
546  os << std::left << std::setw(parw) << std::left << GetParameterName(i) << "\t";
547  for (unsigned int j = 0; j < npar; ++j) {
548  if (!IsParameterFixed(j) ) {
549  os.precision(kPrec); os.width(kWidth); os << std::right << std::setw(matw) << Correlation(i,j);
550  }
551  }
552  os << std::endl;
553  }
554  }
555  // restore alignment and precision
556  os.setf(prevFmt, std::ios::adjustfield);
557  os.precision(prevPrec);
558 }
559 
560 void FitResult::GetConfidenceIntervals(unsigned int n, unsigned int stride1, unsigned int stride2, const double * x, double * ci, double cl, bool norm ) const {
561  // stride1 stride in coordinate stride2 stride in dimension space
562  // i.e. i-th point in k-dimension is x[ stride1 * i + stride2 * k]
563  // compute the confidence interval of the fit on the given data points
564  // the dimension of the data points must match the dimension of the fit function
565  // confidence intervals are returned in array ci
566 
567  if (!fFitFunc) {
568  // check if model function exists
569  MATH_ERROR_MSG("FitResult::GetConfidenceIntervals","Cannot compute Confidence Intervals without fit model function");
570  return;
571  }
572  assert(fFitFunc);
573 
574  // use student quantile in case of normalized errors
575  double corrFactor = 1;
576  if (fChi2 <= 0 || fNdf == 0) norm = false;
577  if (norm)
578  corrFactor = TMath::StudentQuantile(0.5 + cl/2, fNdf) * std::sqrt( fChi2/fNdf );
579  else
580  // value to go up in chi2 (1: 1 sigma error(CL=0.683) , 4: 2 sigma errors
581  corrFactor = ROOT::Math::chisquared_quantile(cl, 1);
582 
583 
584 
585  unsigned int ndim = fFitFunc->NDim();
586  unsigned int npar = fFitFunc->NPar();
587 
588  std::vector<double> xpoint(ndim);
589  std::vector<double> grad(npar);
590  std::vector<double> vsum(npar);
591 
592  // loop on the points
593  for (unsigned int ipoint = 0; ipoint < n; ++ipoint) {
594 
595  for (unsigned int kdim = 0; kdim < ndim; ++kdim) {
596  unsigned int i = ipoint * stride1 + kdim * stride2;
597  assert(i < ndim*n);
598  xpoint[kdim] = x[i];
599  }
600 
601  // calculate gradient of fitted function w.r.t the parameters
602 
603  // check first if fFitFunction provides parameter gradient or not
604 
605  // does not provide gradient
606  // t.b.d : skip calculation for fixed parameters
608  for (unsigned int ipar = 0; ipar < npar; ++ipar) {
610  d.SetFunction(fadapter);
611  grad[ipar] = d(fParams[ipar] ); // evaluate df/dp
612  }
613 
614  // multiply covariance matrix with gradient
615  vsum.assign(npar,0.0);
616  for (unsigned int ipar = 0; ipar < npar; ++ipar) {
617  for (unsigned int jpar = 0; jpar < npar; ++jpar) {
618  vsum[ipar] += CovMatrix(ipar,jpar) * grad[jpar];
619  }
620  }
621  // multiply gradient by vsum
622  double r2 = 0;
623  for (unsigned int ipar = 0; ipar < npar; ++ipar) {
624  r2 += grad[ipar] * vsum[ipar];
625  }
626  double r = std::sqrt(r2);
627  ci[ipoint] = r * corrFactor;
628  }
629 }
630 
631 void FitResult::GetConfidenceIntervals(const BinData & data, double * ci, double cl, bool norm ) const {
632  // implement confidence intervals from a given bin data sets
633  // currently copy the data from Bindata.
634  // could implement otherwise directly
635  unsigned int ndim = data.NDim();
636  unsigned int np = data.NPoints();
637  std::vector<double> xdata( ndim * np );
638  for (unsigned int i = 0; i < np ; ++i) {
639  const double * x = data.Coords(i);
640  std::vector<double>::iterator itr = xdata.begin()+ ndim * i;
641  std::copy(x,x+ndim,itr);
642  }
643  // points are arraned as x0,y0,z0, ....xN,yN,zN (stride1=ndim, stride2=1)
644  GetConfidenceIntervals(np,ndim,1,&xdata.front(),ci,cl,norm);
645 }
646 
647 std::vector<double> FitResult::GetConfidenceIntervals(double cl, bool norm ) const {
648  // implement confidence intervals using stored data sets (if can be retrieved from objective function)
649  // it works only in case of chi2 or binned likelihood fits
650  const BinData * data = FittedBinData();
651  std::vector<double> result;
652  if (data) {
653  result.resize(data->NPoints() );
654  GetConfidenceIntervals(*data, result.data(), cl, norm);
655  }
656  else {
657  MATH_ERROR_MSG("FitResult::GetConfidenceIntervals","Cannot compute Confidence Intervals without the fit bin data");
658  }
659  return result;
660 }
661 
662 // const BinData * GetFitBinData() const {
663 // // return a pointer to the binned data used in the fit
664 // // works only for chi2 or binned likelihood fits
665 // // thus when the objective function stored is a Chi2Func or a PoissonLikelihood
666 // ROOT::Math::IMultiGenFunction * f = fObjFunc->get();
667 // Chi2Function * chi2func = dynamic_cast<Chi2Function*>(f);
668 // if (chi2func) return &(chi2func->Data());
669 // PoissonLLFunction * pllfunc = dynamic_cast<PoissonLLFunction*>(f);
670 // if (pllfunc) return &(pllfunc->Data());
671 // Chi2GradFunction * chi2gradfunc = dynamic_cast<Chi2GradFunction*>(f);
672 // if (chi2gradfunc) return &(chi2gradfunc->Data());
673 // PoissonLLGradFunction * pllgradfunc = dynamic_cast<PoissonLLFunction*>(f);
674 // if (pllgradfunc) return &(pllgradfunc->Data());
675 // MATH_WARN_MSG("FitResult::GetFitBinData","Cannot retrun fit bin data set if objective function is not of a known type");
676 // return nullptr;
677 // }
678 
680  return dynamic_cast<const BinData*> ( fFitData.get() );
681 }
682 
683 
684 
685  } // end namespace Fit
686 
687 } // end namespace ROOT
688 
int Index(const std::string &name) const
get index for parameter name (return -1 if not found)
Definition: FitResult.cxx:408
bool IsFixed() const
check if is fixed
std::string ParName(unsigned int i) const
name of the parameter
Definition: FitResult.cxx:439
std::shared_ptr< ROOT::Math::IMultiGenFunction > fObjFunc
minimizer object used for fitting
Definition: FitResult.h:348
Namespace for new ROOT classes and functions.
Definition: StringConv.hxx:21
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
Definition: FitResult.h:217
double Error(unsigned int i) const
parameter error by index
Definition: FitResult.h:187
unsigned int NPar() const
total number of parameters (abbreviation)
Definition: FitResult.h:132
Class, describing value, limits and step size of the parameters Provides functionality also to set/re...
Double_t StudentQuantile(Double_t p, Double_t ndf, Bool_t lower_tail=kTRUE)
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.
Definition: FitResult.cxx:560
const std::vector< unsigned int > & MinosParams() const
return vector of parameter indeces for which the Minos Error will be computed
Definition: FitConfig.h:215
const int gInitialResultStatus
Definition: FitResult.cxx:43
double Value() const
copy constructor and assignment operators (leave them to the compiler)
unsigned int NPar() const
number of parameters settings
Definition: FitConfig.h:95
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, bool binFit=true, const ROOT::Math::IMultiGenFunction *chi2func=0, 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:100
FitResult & operator=(const FitResult &rhs)
Assignment operator.
Definition: FitResult.cxx:248
double Prob() const
p value of the fit (chi2 probability)
Definition: FitResult.cxx:377
STL namespace.
const ParameterSettings & ParSettings(unsigned int i) const
get the parameter settings for the i-th parameter (const method)
Definition: FitConfig.h:75
bool HasMinosError(unsigned int i) const
query if parameter i has the Minos error
Definition: FitResult.cxx:382
std::map< unsigned int, bool > fFixedParams
data set used in the fit
Definition: FitResult.h:351
unsigned int fNCalls
Definition: FitResult.h:341
const double * Coords(unsigned int ipoint) const
return a pointer to the coordinates data for the given fit point
Definition: FitData.h:246
std::vector< double > fErrors
Definition: FitResult.h:355
unsigned int fNdf
Definition: FitResult.h:340
double sqrt(double)
Double_t x[n]
Definition: legend1.C:17
void SetFunction(const IGenFunction &f)
Set function for derivative calculation (copy the function if option has been enabled in the construc...
std::shared_ptr< FitData > fFitData
model function resulting from the fit.
Definition: FitResult.h:350
virtual ~FitResult()
Destructor.
Definition: FitResult.cxx:236
std::string GetParameterName(unsigned int ipar) const
get name of parameter (deprecated)
Definition: FitResult.h:320
double LowerError(unsigned int i) const
lower Minos error. If Minos has not run for parameter i return the parabolic error ...
Definition: FitResult.cxx:389
double StepSize() const
return step size
#define MATH_ERROR_MSG(loc, str)
Definition: Error.h:50
std::shared_ptr< ROOT::Math::Minimizer > fMinimizer
Definition: FitResult.h:347
Documentation for the abstract class IBaseFunctionMultiDim.
Definition: IFunction.h:62
std::shared_ptr< IModelFunction > fFitFunc
objective function used for fitting
Definition: FitResult.h:349
double Correlation(unsigned int i, unsigned int j) const
retrieve correlation elements
Definition: FitResult.h:227
std::map< unsigned int, std::pair< double, double > > fMinosErrors
Definition: FitResult.h:358
ROOT::R::TRInterface & r
Definition: Object.C:4
void SetMinosError(unsigned int i, double elow, double eup)
set the Minos errors for parameter i (called by the Fitter class when running Minos) ...
Definition: FitResult.cxx:403
bool HasUpperLimit() const
check if parameter has upper limit
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:53
double UpperError(unsigned int i) const
upper Minos error. If Minos has not run for parameter i return the parabolic error ...
Definition: FitResult.cxx:396
OneDimParamFunctionAdapter class to wrap a multi-dim parameteric function in one dimensional one...
#define d(i)
Definition: RSha256.hxx:102
double UpperLimit() const
return upper limit value
unsigned int fNFree
Definition: FitResult.h:339
class containg the result of the fit and all the related information (fitted parameter values...
Definition: FitResult.h:48
void PrintCovMatrix(std::ostream &os) const
print error matrix and correlations
Definition: FitResult.cxx:501
const std::string & Name() const
return name
void NormalizeErrors()
normalize errors using chi2/ndf for chi2 fits
Definition: FitResult.cxx:363
std::string fMinimType
Definition: FitResult.h:359
TFitResultPtr Fit(FitObject *h1, TF1 *f1, Foption_t &option, const ROOT::Math::MinimizerOptions &moption, const char *goption, ROOT::Fit::DataRange &range)
Definition: HFitImpl.cxx:134
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
Definition: FitResult.cxx:422
const std::string & MinimizerType() const
return type of minimizer package
Definition: FitConfig.h:188
static constexpr double s
std::vector< std::pair< double, double > > fParamBounds
Definition: FitResult.h:353
bool MinosErrors() const
do minos errros analysis on the parameters
Definition: FitConfig.h:205
std::vector< std::string > fParNames
Definition: FitResult.h:360
void Print(std::ostream &os, bool covmat=false) const
print the result and optionaly covariance matrix and correlations
Definition: FitResult.cxx:446
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 ...
Definition: FitResult.cxx:679
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition: Util.h:49
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...
auto * l
Definition: textangle.C:4
std::vector< double > fGlobalCC
Definition: FitResult.h:357
FitResult()
Default constructor for an empty (non valid) fit result.
Definition: FitResult.cxx:45
std::vector< double > fCovMatrix
Definition: FitResult.h:356
double LowerLimit() const
return lower limit value
std::map< unsigned int, unsigned int > fBoundParams
Definition: FitResult.h:352
bool ParameterBounds(unsigned int ipar, double &lower, double &upper) const
retrieve parameter bounds - return false if parameter is not bound
Definition: FitResult.cxx:426
std::vector< double > fParams
Definition: FitResult.h:354
unsigned int NPoints() const
return number of fit points
Definition: FitData.h:295
unsigned int NDim() const
return coordinate data dimension
Definition: FitData.h:311
bool IsBound() const
check if is bound
const Int_t n
Definition: legend1.C:16
User class for calculating the derivatives of a function.
char name[80]
Definition: TGX11.cxx:109
double chisquared_quantile(double z, double r)
Inverse ( ) of the cumulative distribution function of the lower tail of the distribution with degr...
bool IsParameterBound(unsigned int ipar) const
query if a parameter is bound
Definition: FitResult.cxx:418
bool HasLowerLimit() const
check if parameter has lower limit
bool Update(const std::shared_ptr< ROOT::Math::Minimizer > &min, 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...
Definition: FitResult.cxx:291
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition: FitConfig.h:46
const std::string & MinimizerAlgoType() const
return type of minimizer algorithms
Definition: FitConfig.h:193