ROOT  6.07/01
Reference Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
TBackCompFitter.cxx
Go to the documentation of this file.
1 // @(#)root/hist:$Id$
2 // Author: Lorenzo Moneta
3 
4 /*************************************************************************
5  * Copyright (C) 1995-2012, Rene Brun and Fons Rademakers. *
6  * All rights reserved. *
7  * *
8  * For the licensing terms see $ROOTSYS/LICENSE. *
9  * For the list of contributors see $ROOTSYS/README/CREDITS. *
10  *************************************************************************/
11 
12 ////////////////////////////////////////////////////////////////////////////////
13 /** \class TBackCompFitter
14  \ingroup Hist
15  \brief Backward compatible implementation of TVirtualFitter
16 
17 Backward compatible implementation of TVirtualFitter using the
18 class ROOT::Fit::Fitter. This class is created after fitting an
19 histogram (TH1), TGraph or TTree and provides in addition to the
20 methods of the TVirtualFitter hooks to access the fit result class
21 (ROOT::Fit::FitResult), the fit configuration
22 (ROOT::Fit::FitConfig) or the fit data (ROOT::Fit::FitData) using
23 
24 ~~~~~~~~{.cpp}
25  TBackCompFitter * fitter = (TBackCompFitter *) TVirtualFitter::GetFitter();
26  ROOT::Fit::FitResult & result = fitter->GetFitResult();
27  result.Print(std::cout);
28 ~~~~~~~~
29 
30 Methods for getting the confidence level or contours are also
31 provided. Note that after a new calls to TH1::Fit (or similar) the
32 class will be deleted and all reference to the FitResult, FitConfig
33 or minimizer will be invalid. One could eventually copying the
34 class before issuing a new fit to avoid deleting this information.
35 *///////////////////////////////////////////////////////////////////////////////
36 
37 #include "TROOT.h"
38 #include "TBackCompFitter.h"
39 
40 
41 #include "TMethodCall.h"
42 #include "TInterpreter.h"
43 
44 #include "Math/Util.h"
45 
46 #include <iostream>
47 #include <cassert>
48 
49 //needed by GetCondifenceLevel
50 #include "Math/IParamFunction.h"
51 #include "TH1.h"
52 #include "TH2.h"
53 #include "TH3.h"
54 #include "TMath.h"
55 #include "TGraph.h"
56 #include "TGraphErrors.h"
57 #include "TGraph2DErrors.h"
58 #include "TMultiGraph.h"
59 #include "HFitInterface.h"
60 #include "Math/Minimizer.h"
61 #include "Fit/BinData.h"
62 #include "Fit/FitConfig.h"
63 #include "Fit/UnBinData.h"
65 #include "Fit/LogLikelihoodFCN.h"
66 #include "Fit/Chi2FCN.h"
67 #include "Fit/FcnAdapter.h"
68 #include "TFitResult.h"
69 
70 //#define DEBUG 1
71 
72 
74 
75 
76 
77 ////////////////////////////////////////////////////////////////////////////////
78 /// Constructor needed by TVirtualFitter interface. Same behavior as default constructor.
79 /// initialize setting name and the global pointer
80 
82  fMinimizer(0),
83  fObjFunc(0),
84  fModelFunc(0)
85 {
86  SetName("BCFitter");
87 }
88 
89 ////////////////////////////////////////////////////////////////////////////////
90 /// Constructor used after having fit using directly ROOT::Fit::Fitter
91 /// will create a dummy fitter copying configuration and parameter settings
92 
93 TBackCompFitter::TBackCompFitter(const std::shared_ptr<ROOT::Fit::Fitter> & fitter, const std::shared_ptr<ROOT::Fit::FitData> & data) :
94  fFitData(data),
95  fFitter(fitter),
96  fMinimizer(0),
97  fObjFunc(0),
98  fModelFunc(0)
99 {
100  SetName("LastFitter");
101 }
102 
103 ////////////////////////////////////////////////////////////////////////////////
104 /// Destructor - delete the managed objects
105 
107  if (fMinimizer) delete fMinimizer;
108  if (fObjFunc) delete fObjFunc;
109  if (fModelFunc) delete fModelFunc;
110 }
111 
112 ////////////////////////////////////////////////////////////////////////////////
113 /// Do chisquare calculations in case of likelihood fits
114 /// Do evaluation a the minimum only
115 
117  const std::vector<double> & minpar = fFitter->Result().Parameters();
118  assert (npar == (int) minpar.size() );
119  double diff = 0;
120  double s = 0;
121  for (int i =0; i < npar; ++i) {
122  diff += std::abs( params[i] - minpar[i] );
123  s += minpar[i];
124  }
125 
126  if (diff > s * 1.E-12 ) Warning("Chisquare","given parameter values are not at minimum - chi2 at minimum is returned");
127  return fFitter->Result().Chi2();
128 }
129 
130 ////////////////////////////////////////////////////////////////////////////////
131 /// Clear resources for consecutive fits
132 
134  // need to do something here ??? to be seen
135 }
136 
137 ////////////////////////////////////////////////////////////////////////////////
138 /// Execute the command (Fortran Minuit compatible interface)
139 
140 Int_t TBackCompFitter::ExecuteCommand(const char *command, Double_t *args, Int_t nargs) {
141 #ifdef DEBUG
142  std::cout<<"Execute command= "<<command<<std::endl;
143 #endif
144 
145  // set also number of parameters in obj function
146  DoSetDimension();
147 
148  TString scommand(command);
149  scommand.ToUpper();
150 
151  // MIGRAD
152  if (scommand.Contains("MIG")) {
153  if (!fObjFunc) {
154  Error("ExecuteCommand","FCN must set before executing this command");
155  return -1;
156  }
157 
158  fFitter->Config().SetMinimizer(GetDefaultFitter(), "Migrad");
159  bool ret = fFitter->FitFCN(*fObjFunc);
160  return (ret) ? 0 : -1;
161  }
162 
163  //Minimize
164  if (scommand.Contains("MINI")) {
165 
166  fFitter->Config().SetMinimizer(GetDefaultFitter(), "Minimize");
167  if (!fObjFunc) {
168  Error("ExecuteCommand","FCN must set before executing this command");
169  return -1;
170  }
171  bool ret = fFitter->FitFCN(*fObjFunc);
172  return (ret) ? 0 : -1;
173  }
174  //Simplex
175  if (scommand.Contains("SIM")) {
176 
177  if (!fObjFunc) {
178  Error("ExecuteCommand","FCN must set before executing this command");
179  return -1;
180  }
181 
182  fFitter->Config().SetMinimizer(GetDefaultFitter(), "Simplex");
183  bool ret = fFitter->FitFCN(*fObjFunc);
184  return (ret) ? 0 : -1;
185  }
186  //SCan
187  if (scommand.Contains("SCA")) {
188 
189  if (!fObjFunc) {
190  Error("ExecuteCommand","FCN must set before executing this command");
191  return -1;
192  }
193 
194  fFitter->Config().SetMinimizer(GetDefaultFitter(), "Scan");
195  bool ret = fFitter->FitFCN(*fObjFunc);
196  return (ret) ? 0 : -1;
197  }
198  // MINOS
199  else if (scommand.Contains("MINO")) {
200 
201  if (fFitter->Config().MinosErrors() ) return 0;
202 
203  if (!fObjFunc) {
204  Error("ExecuteCommand","FCN must set before executing this command");
205  return -1;
206  }
207  // do only MINOS. need access to minimizer. For the moment re-run fitting with minos options
208  fFitter->Config().SetMinosErrors(true);
209  // set new parameter values
210 
211  fFitter->Config().SetMinimizer(GetDefaultFitter(), "Migrad"); // redo -minimization with Minos
212  bool ret = fFitter->FitFCN(*fObjFunc);
213  return (ret) ? 0 : -1;
214 
215  }
216  //HESSE
217  else if (scommand.Contains("HES")) {
218 
219  if (fFitter->Config().ParabErrors() ) return 0;
220 
221  if (!fObjFunc) {
222  Error("ExecuteCommand","FCN must set before executing this command");
223  return -1;
224  }
225 
226  // do only HESSE. need access to minimizer. For the moment re-run fitting with hesse options
227  fFitter->Config().SetParabErrors(true);
228  fFitter->Config().SetMinimizer(GetDefaultFitter(), "Migrad"); // redo -minimization with Minos
229  bool ret = fFitter->FitFCN(*fObjFunc);
230  return (ret) ? 0 : -1;
231  }
232 
233  // FIX
234  else if (scommand.Contains("FIX")) {
235  for(int i = 0; i < nargs; i++) {
236  FixParameter(int(args[i])-1);
237  }
238  return 0;
239  }
240  // SET LIMIT (upper and lower)
241  else if (scommand.Contains("SET LIM")) {
242  if (nargs < 3) {
243  Error("ExecuteCommand","Invalid parameters given in SET LIMIT");
244  return -1;
245  }
246  int ipar = int(args[0]);
247  if (!ValidParameterIndex(ipar) ) return -1;
248  double low = args[1];
249  double up = args[2];
250  fFitter->Config().ParSettings(ipar).SetLimits(low,up);
251  return 0;
252  }
253  // SET PRINT
254  else if (scommand.Contains("SET PRIN")) {
255  if (nargs < 1) return -1;
256  fFitter->Config().MinimizerOptions().SetPrintLevel(int(args[0]) );
257  return 0;
258  }
259  // SET ERR
260  else if (scommand.Contains("SET ERR")) {
261  if (nargs < 1) return -1;
262  fFitter->Config().MinimizerOptions().SetPrintLevel(int( args[0]) );
263  return 0;
264  }
265  // SET STRATEGY
266  else if (scommand.Contains("SET STR")) {
267  if (nargs < 1) return -1;
268  fFitter->Config().MinimizerOptions().SetStrategy(int(args[0]) );
269  return 0;
270  }
271  //SET GRAD (not impl.)
272  else if (scommand.Contains("SET GRA")) {
273  // not yet available
274  // fGradient = true;
275  return -1;
276  }
277  //SET NOW (not impl.)
278  else if (scommand.Contains("SET NOW")) {
279  // no warning (works only for TMinuit)
280  // fGradient = true;
281  return -1;
282  }
283  // CALL FCN
284  else if (scommand.Contains("CALL FCN")) {
285  // call fcn function (global pointer to free function)
286 
287  if (nargs < 1 || fFCN == 0 ) return -1;
288  int npar = fObjFunc->NDim();
289  // use values in fit result if existing otherwise in ParameterSettings
290  std::vector<double> params(npar);
291  for (int i = 0; i < npar; ++i)
292  params[i] = GetParameter(i);
293 
294  double fval = 0;
295  (*fFCN)(npar, 0, fval, &params[0],int(args[0]) ) ;
296  return 0;
297  }
298  else {
299  // other commands passed
300  Error("ExecuteCommand","Invalid or not supported command given %s",command);
301  return -1;
302  }
303 }
304 
305 ////////////////////////////////////////////////////////////////////////////////
306 /// Check if ipar is a valid parameter index
307 
309  int nps = fFitter->Config().ParamsSettings().size();
310  if (ipar < 0 || ipar >= nps ) {
311  std::string msg = ROOT::Math::Util::ToString(ipar) + " is an invalid Parameter index";
312  Error("ValidParameterIndex","%s",msg.c_str());
313  return false;
314  }
315  return true;
316 }
317 
318 ////////////////////////////////////////////////////////////////////////////////
319 /// Fix the parameter
320 
322  if (ValidParameterIndex(ipar) )
323  fFitter->Config().ParSettings(ipar).Fix();
324 }
325 
326 ////////////////////////////////////////////////////////////////////////////////
327 /// Computes point-by-point confidence intervals for the fitted function.
328 /// \param n number of points
329 /// \param ndim dimensions of points
330 /// \param x points, at which to compute the intervals, for ndim > 1
331 /// should be in order: (x0,y0, x1, y1, ... xn, yn)
332 /// \param ci computed intervals are returned in this array
333 /// \param cl confidence level, default=0.95
334 ///
335 /// NOTE, that the intervals are approximate for nonlinear(in parameters) models
336 
338 {
339  if (!fFitter->Result().IsValid()) {
340  Error("GetConfidenceIntervals","Cannot compute confidence intervals with an invalide fit result");
341  return;
342  }
343 
344  fFitter->Result().GetConfidenceIntervals(n,ndim,1,x,ci,cl);
345 }
346 
347 ////////////////////////////////////////////////////////////////////////////////
348 /// Computes confidence intervals at level cl. Default is 0.95
349 /// The TObject parameter can be a TGraphErrors, a TGraph2DErrors or a TH1,2,3.
350 /// For Graphs, confidence intervals are computed for each point,
351 /// the value of the graph at that point is set to the function value at that
352 /// point, and the graph y-errors (or z-errors) are set to the value of
353 /// the confidence interval at that point.
354 /// For Histograms, confidence intervals are computed for each bin center
355 /// The bin content of this bin is then set to the function value at the bin
356 /// center, and the bin error is set to the confidence interval value.
357 //
358 /// NOTE: confidence intervals are approximate for nonlinear models!
359 ///
360 /// Allowed combinations:
361 ///
362 /// Fitted object | Passed object
363 /// --------------------------|------------------
364 /// TGraph | TGraphErrors, TH1
365 /// TGraphErrors, AsymmErrors | TGraphErrors, TH1
366 /// TH1 | TGraphErrors, TH1
367 /// TGraph2D | TGraph2DErrors, TH2
368 /// TGraph2DErrors | TGraph2DErrors, TH2
369 /// TH2 | TGraph2DErrors, TH2
370 /// TH3 | TH3
371 
373 {
374  if (!fFitter->Result().IsValid() ) {
375  Error("GetConfidenceIntervals","Cannot compute confidence intervals with an invalide fit result");
376  return;
377  }
378 
379  // get data dimension from fit object
380  int datadim = 1;
381  TObject * fitobj = GetObjectFit();
382  if (!fitobj) {
383  Error("GetConfidenceIntervals","Cannot compute confidence intervals without a fitting object");
384  return;
385  }
386 
387  if (fitobj->InheritsFrom(TGraph2D::Class())) datadim = 2;
388  if (fitobj->InheritsFrom(TH1::Class())) {
389  TH1 * h1 = dynamic_cast<TH1*>(fitobj);
390  assert(h1 != 0);
391  datadim = h1->GetDimension();
392  }
393 
394  if (datadim == 1) {
395  if (!obj->InheritsFrom(TGraphErrors::Class()) && !obj->InheritsFrom(TH1::Class() ) ) {
396  Error("GetConfidenceIntervals", "Invalid object passed for storing confidence level data, must be a TGraphErrors or a TH1");
397  return;
398  }
399  }
400  if (datadim == 2) {
401  if (!obj->InheritsFrom(TGraph2DErrors::Class()) && !obj->InheritsFrom(TH2::Class() ) ) {
402  Error("GetConfidenceIntervals", "Invalid object passed for storing confidence level data, must be a TGraph2DErrors or a TH2");
403  return;
404  }
405  }
406  if (datadim == 3) {
407  if (!obj->InheritsFrom(TH3::Class() ) ) {
408  Error("GetConfidenceIntervals", "Invalid object passed for storing confidence level data, must be a TH3");
409  return;
410  }
411  }
412 
413  // fill bin data (for the moment use all ranges) according to object passed
414  ROOT::Fit::BinData data;
415  data.Opt().fUseEmpty = true; // need to use all bins of given histograms
416  // call appropriate function according to type of object
417  if (obj->InheritsFrom(TGraph::Class()) )
418  ROOT::Fit::FillData(data, dynamic_cast<TGraph *>(obj) );
419  else if (obj->InheritsFrom(TGraph2D::Class()) )
420  ROOT::Fit::FillData(data, dynamic_cast<TGraph2D *>(obj) );
421 // else if (obj->InheritsFrom(TMultiGraph::Class()) )
422 // ROOT::Fit::FillData(data, dynamic_cast<TMultiGraph *>(obj) );
423  else if (obj->InheritsFrom(TH1::Class()) )
424  ROOT::Fit::FillData(data, dynamic_cast<TH1 *>(obj) );
425 
426 
427  unsigned int n = data.Size();
428 
429  std::vector<double> ci( n );
430 
431  fFitter->Result().GetConfidenceIntervals(data,&ci[0],cl);
432 
433  const ROOT::Math::IParamMultiFunction * func = fFitter->Result().FittedFunction();
434  assert(func != 0);
435 
436  // fill now the object with cl data
437  for (unsigned int i = 0; i < n; ++i) {
438  const double * x = data.Coords(i);
439  double y = (*func)( x ); // function is evaluated using its parameters
440 
441  if (obj->InheritsFrom(TGraphErrors::Class()) ) {
442  TGraphErrors * gr = dynamic_cast<TGraphErrors *> (obj);
443  assert(gr != 0);
444  gr->SetPoint(i, *x, y);
445  gr->SetPointError(i, 0, ci[i]);
446  }
447  if (obj->InheritsFrom(TGraph2DErrors::Class()) ) {
448  TGraph2DErrors * gr = dynamic_cast<TGraph2DErrors *> (obj);
449  assert(gr != 0);
450  gr->SetPoint(i, x[0], x[1], y);
451  gr->SetPointError(i, 0, 0, ci[i]);
452  }
453  if (obj->InheritsFrom(TH1::Class()) ) {
454  TH1 * h1 = dynamic_cast<TH1 *> (obj);
455  assert(h1 != 0);
456  int ibin = 0;
457  if (datadim == 1) ibin = h1->FindBin(*x);
458  if (datadim == 2) ibin = h1->FindBin(x[0],x[1]);
459  if (datadim == 3) ibin = h1->FindBin(x[0],x[1],x[2]);
460  h1->SetBinContent(ibin, y);
461  h1->SetBinError(ibin, ci[i]);
462  }
463  }
464 
465 }
466 
467 ////////////////////////////////////////////////////////////////////////////////
468 /// Get the error matrix in a pointer to a NxN array.
469 /// excluding the fixed parameters
470 
472  unsigned int nfreepar = GetNumberFreeParameters();
473  unsigned int ntotpar = GetNumberTotalParameters();
474 
475  if (fCovar.size() != nfreepar*nfreepar )
476  fCovar.resize(nfreepar*nfreepar);
477 
478  if (!fFitter->Result().IsValid() ) {
479  Warning("GetCovarianceMatrix","Invalid fit result");
480  return 0;
481  }
482 
483  unsigned int l = 0;
484  for (unsigned int i = 0; i < ntotpar; ++i) {
485  if (fFitter->Config().ParSettings(i).IsFixed() ) continue;
486  unsigned int m = 0;
487  for (unsigned int j = 0; j < ntotpar; ++j) {
488  if (fFitter->Config().ParSettings(j).IsFixed() ) continue;
489  unsigned int index = nfreepar*l + m;
490  assert(index < fCovar.size() );
491  fCovar[index] = fFitter->Result().CovMatrix(i,j);
492  m++;
493  }
494  l++;
495  }
496  return &(fCovar.front());
497 }
498 
499 ////////////////////////////////////////////////////////////////////////////////
500 /// Get error matrix element (return all zero if matrix is not available)
501 
503  unsigned int np2 = fCovar.size();
504  unsigned int npar = GetNumberFreeParameters();
505  if ( np2 == 0 || np2 != npar *npar ) {
506  double * c = GetCovarianceMatrix();
507  if (c == 0) return 0;
508  }
509  return fCovar[i*npar + j];
510 }
511 
512 ////////////////////////////////////////////////////////////////////////////////
513 /// Get fit errors
514 
515 Int_t TBackCompFitter::GetErrors(Int_t ipar,Double_t &eplus, Double_t &eminus, Double_t &eparab, Double_t &globcc) const {
516  if (!ValidParameterIndex(ipar) ) return -1;
517 
518  const ROOT::Fit::FitResult & result = fFitter->Result();
519  if (!result.IsValid() ) {
520  Warning("GetErrors","Invalid fit result");
521  return -1;
522  }
523 
524  eparab = result.Error(ipar);
525  eplus = result.UpperError(ipar);
526  eminus = result.LowerError(ipar);
527  globcc = result.GlobalCC(ipar);
528  return 0;
529 }
530 
531 ////////////////////////////////////////////////////////////////////////////////
532 /// Number of total parameters
533 
535  return fFitter->Result().NTotalParameters();
536 }
538  // number of variable parameters
539  return fFitter->Result().NFreeParameters();
540 }
541 
542 ////////////////////////////////////////////////////////////////////////////////
543 /// Parameter error
544 
546  if (fFitter->Result().IsEmpty() ) {
547  if (ValidParameterIndex(ipar) ) return fFitter->Config().ParSettings(ipar).StepSize();
548  else return 0;
549  }
550  return fFitter->Result().Error(ipar);
551 }
552 
553 ////////////////////////////////////////////////////////////////////////////////
554 /// Parameter value
555 
557  if (fFitter->Result().IsEmpty() ) {
558  if (ValidParameterIndex(ipar) ) return fFitter->Config().ParSettings(ipar).Value();
559  else return 0;
560  }
561  return fFitter->Result().Value(ipar);
562 }
563 
564 ////////////////////////////////////////////////////////////////////////////////
565 /// Get all parameter info (name, value, errors)
566 
568  if (!ValidParameterIndex(ipar) ) {
569  return -1;
570  }
571  const std::string & pname = fFitter->Config().ParSettings(ipar).Name();
572  const char * c = pname.c_str();
573  std::copy(c,c + pname.size(),name);
574 
575  if (fFitter->Result().IsEmpty() ) {
576  value = fFitter->Config().ParSettings(ipar).Value();
577  verr = fFitter->Config().ParSettings(ipar).Value(); // error is step size in this case
578  vlow = fFitter->Config().ParSettings(ipar).LowerLimit(); // vlow is lower limit in this case
579  vhigh = fFitter->Config().ParSettings(ipar).UpperLimit(); // vlow is lower limit in this case
580  return 1;
581  }
582  else {
583  value = fFitter->Result().Value(ipar);
584  verr = fFitter->Result().Error(ipar);
585  vlow = fFitter->Result().LowerError(ipar);
586  vhigh = fFitter->Result().UpperError(ipar);
587  }
588  return 0;
589 }
590 
591 ////////////////////////////////////////////////////////////////////////////////
592 /// Return name of parameter ipar
593 
594 const char *TBackCompFitter::GetParName(Int_t ipar) const {
595  if (!ValidParameterIndex(ipar) ) {
596  return 0;
597  }
598  return fFitter->Config().ParSettings(ipar).Name().c_str();
599 }
600 
601 ////////////////////////////////////////////////////////////////////////////////
602 /// Get fit statistical information
603 
604 Int_t TBackCompFitter::GetStats(Double_t &amin, Double_t &edm, Double_t &errdef, Int_t &nvpar, Int_t &nparx) const {
605  const ROOT::Fit::FitResult & result = fFitter->Result();
606  amin = result.MinFcnValue();
607  edm = result.Edm();
608  errdef = fFitter->Config().MinimizerOptions().ErrorDef();
609  nvpar = result.NFreeParameters();
610  nparx = result.NTotalParameters();
611  return 0;
612 }
613 
614 ////////////////////////////////////////////////////////////////////////////////
615 /// Sum of log (un-needed)
616 
618  Warning("GetSumLog","Dummy method - returned 0");
619  return 0.;
620 }
621 
622 ////////////////////////////////////////////////////////////////////////////////
623 /// Query if parameter ipar is fixed
624 
626  if (!ValidParameterIndex(ipar) ) {
627  return false;
628  }
629  return fFitter->Config().ParSettings(ipar).IsFixed();
630 }
631 
632 ////////////////////////////////////////////////////////////////////////////////
633 /// Print the fit result.
634 /// Use PrintResults function in case of Minuit for old -style printing
635 
637  if (fFitter->GetMinimizer() && fFitter->Config().MinimizerType() == "Minuit")
638  fFitter->GetMinimizer()->PrintResults();
639  else {
640  if (level > 0) fFitter->Result().Print(std::cout);
641  if (level > 1) fFitter->Result().PrintCovMatrix(std::cout);
642  }
643  // need to print minos errors and globalCC + other info
644 }
645 
646 ////////////////////////////////////////////////////////////////////////////////
647 /// Release a fit parameter
648 
650  if (ValidParameterIndex(ipar) )
651  fFitter->Config().ParSettings(ipar).Release();
652 }
653 
654 ////////////////////////////////////////////////////////////////////////////////
655 /// Set fit method (chi2 or likelihood).
656 /// According to the method the appropriate FCN function will be created
657 
658 void TBackCompFitter::SetFitMethod(const char *) {
659  Info("SetFitMethod","non supported method");
660 }
661 
662 ////////////////////////////////////////////////////////////////////////////////
663 /// Set (add) a new fit parameter passing initial value, step size (verr) and parameter limits
664 /// if vlow > vhigh the parameter is unbounded
665 /// if the stepsize (verr) == 0 the parameter is treated as fixed
666 
667 Int_t TBackCompFitter::SetParameter(Int_t ipar,const char *parname,Double_t value,Double_t verr,Double_t vlow, Double_t vhigh) {
668  std::vector<ROOT::Fit::ParameterSettings> & parlist = fFitter->Config().ParamsSettings();
669  if ( ipar >= (int) parlist.size() ) parlist.resize(ipar+1);
670  ROOT::Fit::ParameterSettings ps(parname, value, verr);
671  if (verr == 0) ps.Fix();
672  if (vlow < vhigh) ps.SetLimits(vlow, vhigh);
673  parlist[ipar] = ps;
674  return 0;
675 }
676 
677 //______________________________________________________________________________
678 // static method evaluating FCN
679 // void TBackCompFitter::FCN( int &, double * , double & f, double * x , int /* iflag */) {
680 // // get static instance of fitter
681 // TBackCompFitter * fitter = dynamic_cast<TBackCompFitter *>(TVirtualFitter::GetFitter());
682 // assert(fitter);
683 // if (fitter->fObjFunc == 0) fitter->RecreateFCN();
684 // assert(fitter->fObjFunc);
685 // f = (*(fitter.fObjFunc) )(x);
686 // }
687 
688 ////////////////////////////////////////////////////////////////////////////////
689 /// Recreate a minimizer instance using the function and data
690 /// set objective function in minimizers function to re-create FCN from stored data object and fit options
691 
693  assert(fFitData.get());
694 
695  // case of standard fits (not made fia Fitter::FitFCN)
696  if (fFitter->Result().FittedFunction() != 0) {
697 
698  if (fModelFunc) delete fModelFunc;
699  fModelFunc = dynamic_cast<ROOT::Math::IParamMultiFunction *>((fFitter->Result().FittedFunction())->Clone());
701 
702  // create fcn functions, should consider also gradient case
703  const ROOT::Fit::BinData * bindata = dynamic_cast<const ROOT::Fit::BinData *>(fFitData.get());
704  if (bindata) {
705  if (GetFitOption().Like )
707  else
709  }
710  else {
711  const ROOT::Fit::UnBinData * unbindata = dynamic_cast<const ROOT::Fit::UnBinData *>(fFitData.get());
712  assert(unbindata);
714  }
715  }
716 
717  // recreate the minimizer
718  fMinimizer = fFitter->Config().CreateMinimizer();
719  if (fMinimizer == 0) {
720  Error("SetMinimizerFunction","cannot create minimizer %s",fFitter->Config().MinimizerType().c_str() );
721  }
722  else {
723  if (!fObjFunc) {
724  Error("SetMinimizerFunction","Object Function pointer is NULL");
725  }
726  else
728  }
729 
730 }
731 
732 ////////////////////////////////////////////////////////////////////////////////
733 /// Override setFCN to use the Adapter to Minuit2 FCN interface
734 /// To set the address of the minimization function
735 
737 {
738  fFCN = fcn;
739  if (fObjFunc) delete fObjFunc;
741  DoSetDimension();
742 }
743 
744 
745 ////////////////////////////////////////////////////////////////////////////////
746 /// Static function called when SetFCN is called in interactive mode
747 
748 void InteractiveFCNm2(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag)
749 {
750  // get method call from static instance
751  TMethodCall *m = (TVirtualFitter::GetFitter())->GetMethodCall();
752  if (!m) return;
753 
754  Long_t args[5];
755  args[0] = (Long_t)&npar;
756  args[1] = (Long_t)gin;
757  args[2] = (Long_t)&f;
758  args[3] = (Long_t)u;
759  args[4] = (Long_t)flag;
760  m->SetParamPtrs(args);
762  m->Execute(result);
763 }
764 
765 ////////////////////////////////////////////////////////////////////////////////
766 /// Set the address of the minimization function
767 /// this function is called by CINT instead of the function above
768 
770 {
771  if (!fcn) return;
772 
773  const char *funcname = gCling->Getp2f2funcname(fcn);
774  if (funcname) {
775  fMethodCall = new TMethodCall();
776  fMethodCall->InitWithPrototype(funcname,"Int_t&,Double_t*,Double_t&,Double_t*,Int_t");
777  }
779  // set the static instance (required by InteractiveFCNm)
781 
782  if (fObjFunc) delete fObjFunc;
784  DoSetDimension();
785 }
786 
787 ////////////////////////////////////////////////////////////////////////////////
788 /// Set the objective function for fitting
789 /// Needed if fitting directly using TBackCompFitter class
790 /// The class clones a copy of the function and manages it
791 
793  if (fObjFunc) delete fObjFunc;
794  fObjFunc = fcn->Clone();
795 }
796 
797 ////////////////////////////////////////////////////////////////////////////////
798 /// Private method to set dimension in objective function
799 
801  if (!fObjFunc) return;
802  ROOT::Fit::FcnAdapter * fobj = dynamic_cast<ROOT::Fit::FcnAdapter*>(fObjFunc);
803  assert(fobj != 0);
804  int ndim = fFitter->Config().ParamsSettings().size();
805  if (ndim != 0) fobj->SetDimension(ndim);
806 }
807 
808 ////////////////////////////////////////////////////////////////////////////////
809 /// Return a pointer to the objective function (FCN)
810 /// If fitting directly using TBackCompFitter the pointer is managed by the class,
811 /// which has been set previously when calling SetObjFunction or SetFCN
812 /// Otherwise if the class is used in the backward compatible mode (e.g. after having fitted a TH1)
813 /// the return pointer will be valid after fitting and as long a new fit will not be done.
814 
816  if (fObjFunc) return fObjFunc;
817  return fFitter->GetFCN();
818 }
819 
820 ////////////////////////////////////////////////////////////////////////////////
821 /// Return a pointer to the minimizer.
822 /// the return pointer will be valid after fitting and as long a new fit will not be done.
823 /// For keeping a minimizer pointer the method ReCreateMinimizer() could eventually be used
824 
826  if (fMinimizer) return fMinimizer;
827  return fFitter->GetMinimizer();
828 }
829 
830 ////////////////////////////////////////////////////////////////////////////////
831 /// Return a new copy of the TFitResult object which needs to be deleted later by the user
832 
834  if (!fFitter.get() ) return 0;
835  return new TFitResult( fFitter->Result() );
836 }
837 
838 ////////////////////////////////////////////////////////////////////////////////
839 /// Scan parameter ipar between value of xmin and xmax
840 /// A graph must be given which will be on return filled with the scan resul
841 /// If the graph size is zero, a default size n = 40 will be used
842 
843 bool TBackCompFitter::Scan(unsigned int ipar, TGraph * gr, double xmin, double xmax )
844 {
845 
846  if (!gr) return false;
847  ROOT::Math::Minimizer * minimizer = fFitter->GetMinimizer();
848  if (!minimizer) {
849  Error("Scan","Minimizer is not available - cannot scan before fitting");
850  return false;
851  }
852 
853  unsigned int npoints = gr->GetN();
854  if (npoints == 0) {
855  npoints = 40;
856  gr->Set(npoints);
857  }
858  bool ret = minimizer->Scan( ipar, npoints, gr->GetX(), gr->GetY(), xmin, xmax);
859  if ((int) npoints < gr->GetN() ) gr->Set(npoints);
860  return ret;
861 }
862 
863 //______________________________________________________________________________
864 // bool TBackCompFitter::Scan2D(unsigned int ipar, unsigned int jpar, TGraph2D * gr,
865 // double xmin = 0, double xmax = 0, double ymin = 0, double ymax = 0) {
866 // // scan the parameters ipar between values of [xmin,xmax] and
867 // // jpar between values of [ymin,ymax] and
868 // // a graph2D must be given which will be on return filled with the scan resul
869 // // If the graph size is zero, a default size n = 20x20 will be used
870 // //*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*-*
871 
872 // if (!gr) return false;
873 // if (!fMinimizer) {
874 // Error("Scan","Minimizer is not available - cannot scan before fitting");
875 // return false;
876 // }
877 // unsigned int npoints = gr->GetN();
878 // if (npoints == 0) {
879 // npoints = 40;
880 // gr->Set(npoints);
881 // }
882 // // to be implemented
883 // for (unsigned int ix = 0; ix < npoints; ++ix) {
884 // return fMinimizer->Scan( ipar, npoints, gr->GetX(), gr->GetY(), xmin, xmax);
885 
886 // }
887 
888 ////////////////////////////////////////////////////////////////////////////////
889 /// Create a 2D contour around the minimum for the parameter ipar and jpar
890 /// if a minimum does not exist or is invalid it will return false
891 /// on exit a TGraph is filled with the contour points
892 /// the number of contur points is determined by the size of the TGraph.
893 /// if the size is zero a default number of points = 20 is used
894 /// pass optionally the confidence level, default is 0.683
895 /// it is assumed that ErrorDef() defines the right error definition
896 /// (i.e 1 sigma error for one parameter). If not the confidence level are scaled to new level
897 
898 bool TBackCompFitter::Contour(unsigned int ipar, unsigned int jpar, TGraph * gr, double confLevel) {
899  if (!gr) return false;
900  ROOT::Math::Minimizer * minimizer = fFitter->GetMinimizer();
901  if (!minimizer) {
902  Error("Scan","Minimizer is not available - cannot scan before fitting");
903  return false;
904  }
905 
906  // get error level used for fitting
907  double upScale = fFitter->Config().MinimizerOptions().ErrorDef();
908 
909  double upVal = TMath::ChisquareQuantile( confLevel, 2); // 2 is number of parameter we do the contour
910 
911  // set required error definition in minimizer
912  minimizer->SetErrorDef (upScale * upVal);
913 
914  unsigned int npoints = gr->GetN();
915  if (npoints == 0) {
916  npoints = 40;
917  gr->Set(npoints);
918  }
919  bool ret = minimizer->Contour( ipar, jpar, npoints, gr->GetX(), gr->GetY());
920  if ((int) npoints < gr->GetN() ) gr->Set(npoints);
921 
922  // restore the error level used for fitting
923  minimizer->SetErrorDef ( upScale);
924 
925  return ret;
926 }
927 
928 
void DoSetDimension()
Private method to set dimension in objective function.
virtual Bool_t IsFixed(Int_t ipar) const
Query if parameter ipar is fixed.
virtual Int_t FindBin(Double_t x, Double_t y=0, Double_t z=0)
Return Global bin number corresponding to x,y,z.
Definition: TH1.cxx:3478
float xmin
Definition: THbookFile.cxx:93
virtual Int_t GetNumberFreeParameters() const
bool ValidParameterIndex(int ipar) const
Check if ipar is a valid parameter index.
void SetErrorDef(double up)
set scale for calculating the errors
Definition: Minimizer.h:472
void fcn(Int_t &npar, Double_t *gin, Double_t &f, Double_t *par, Int_t iflag)
Definition: Ifit.C:26
virtual void Clear(Option_t *option="")
Clear resources for consecutive fits.
bool Contour(unsigned int ipar, unsigned int jpar, TGraph *gr, double confLevel=0.683)
Create a 2D contour around the minimum for the parameter ipar and jpar if a minimum does not exist or...
virtual Bool_t InheritsFrom(const char *classname) const
Returns kTRUE if object inherits from class "classname".
Definition: TObject.cxx:487
virtual Int_t GetNumberTotalParameters() const
Number of total parameters.
virtual Int_t ExecuteCommand(const char *command, Double_t *args, Int_t nargs)
Execute the command (Fortran Minuit compatible interface)
return c
const char Option_t
Definition: RtypesCore.h:62
virtual Foption_t GetFitOption() const
#define assert(cond)
Definition: unittest.h:542
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
Class, describing value, limits and step size of the parameters Provides functionality also to set/re...
virtual Int_t GetDimension() const
Definition: TH1.h:283
bool Scan(unsigned int ipar, TGraph *gr, double xmin=0, double xmax=0)
Scan parameter ipar between value of xmin and xmax A graph must be given which will be on return fill...
virtual void SetName(const char *name)
Change (i.e.
Definition: TNamed.cxx:128
virtual void Info(const char *method, const char *msgfmt,...) const
Issue info message.
Definition: TObject.cxx:892
tuple pname
Definition: tree.py:131
ROOT::Math::Minimizer * fMinimizer
pointer to fitter object
virtual const char * GetParName(Int_t ipar) const
Return name of parameter ipar.
void ToUpper()
Change string to upper case.
Definition: TString.cxx:1088
LogLikelihoodFCN class for likelihood fits.
void ReCreateMinimizer()
Recreate a minimizer instance using the function and data set objective function in minimizers functi...
virtual Double_t GetParError(Int_t ipar) const
Parameter error.
Basic string class.
Definition: TString.h:137
virtual void SetFCN(void(*fcn)(Int_t &, Double_t *, Double_t &f, Double_t *, Int_t))
Override setFCN to use the Adapter to Minuit2 FCN interface To set the address of the minimization fu...
Class describing the unbinned data sets (just x coordinates values) of any dimensions.
Definition: UnBinData.h:47
Backward compatible implementation of TVirtualFitter.
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
double Edm() const
Expected distance from minimum.
Definition: FitResult.h:131
Int_t GetN() const
Definition: TGraph.h:132
virtual Int_t GetErrors(Int_t ipar, Double_t &eplus, Double_t &eminus, Double_t &eparab, Double_t &globcc) const
Get fit errors.
TFile * f
static const char * GetDefaultFitter()
static: return the name of the default fitter
unsigned int Size() const
return number of fit points
Definition: BinData.h:447
void SetParamPtrs(void *paramArr, Int_t nparam=-1)
ParamArr is an array containing the function argument values.
Double_t * GetY() const
Definition: TGraph.h:140
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_t ChisquareQuantile(Double_t p, Double_t ndf)
Evaluate the quantiles of the chi-squared probability distribution function.
Definition: TMath.cxx:2141
Double_t x[n]
Definition: legend1.C:17
TBackCompFitter()
Constructor needed by TVirtualFitter interface.
Extends the ROOT::Fit::Result class with a TNamed inheritance providing easy possibility for I/O...
Definition: TFitResult.h:36
class evaluating the log likelihood for binned Poisson likelihood fits it is template to distinguish ...
void Class()
Definition: Class.C:29
virtual ~TBackCompFitter()
Destructor - delete the managed objects.
virtual void SetPointError(Int_t i, Double_t ex, Double_t ey, Double_t ez)
Set ex, ey and ez values for point number i.
Abstract Minimizer class, defining the interface for the various minimizer (like Minuit2, Minuit, GSL, etc..) Plug-in's exist in ROOT to be able to instantiate the derived classes like ROOT::Math::GSLMinimizer or ROOT::Math::Minuit2Minimizer via the plug-in manager.
Definition: Minimizer.h:86
static Vc_ALWAYS_INLINE Vector< T > abs(const Vector< T > &x)
Definition: vector.h:450
virtual bool Contour(unsigned int ivar, unsigned int jvar, unsigned int &npoints, double *xi, double *xj)
find the contour points (xi, xj) of the function for parameter ivar and jvar around the minimum The c...
Definition: Minimizer.h:387
void Fix()
fix the parameter
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition: TNamed.cxx:63
Method or function calling interface.
Definition: TMethodCall.h:41
virtual void Error(const char *method, const char *msgfmt,...) const
Issue error message.
Definition: TObject.cxx:918
TH1F * h1
Definition: legend1.C:5
virtual void SetBinError(Int_t bin, Double_t error)
see convention for numbering bins in TH1::GetBin
Definition: TH1.cxx:8528
virtual void FixParameter(Int_t ipar)
Fix the parameter.
static void SetFitter(TVirtualFitter *fitter, Int_t maxpar=25)
Static function to set an alternative fitter.
virtual void SetObjFunction(ROOT::Math::IMultiGenFunction *f)
Set the objective function for fitting Needed if fitting directly using TBackCompFitter class The cla...
unsigned int NFreeParameters() const
get total number of free parameters
Definition: FitResult.h:139
virtual Double_t GetParameter(Int_t ipar) const
Parameter value.
void InteractiveFCNm2(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag)
Static function called when SetFCN is called in interactive mode.
Chi2FCN class for binnned fits using the least square methods.
Definition: Chi2FCN.h:68
ROOT::Math::IMultiGenFunction * fObjFunc
bool IsValid() const
True if fit successful, otherwise false.
Definition: FitResult.h:119
virtual void SetFunction(const ROOT::Math::IMultiGenFunction &func)=0
set the function to minimize
void FillData(BinData &dv, const TH1 *hist, TF1 *func=0)
fill the data vector from a TH1.
Double_t * GetX() const
Definition: TGraph.h:139
IParamFunction interface (abstract class) describing multi-dimensional parameteric functions It is a ...
ClassImp(TBackCompFitter)
virtual unsigned int NDim() const =0
Retrieve the dimension of the function.
virtual void SetBinContent(Int_t bin, Double_t content)
Set bin content see convention for numbering bins in TH1::GetBin In case the bin number is greater th...
Definition: TH1.cxx:8543
TMarker * m
Definition: textangle.C:8
ROOT::Math::Minimizer * GetMinimizer() const
Return a pointer to the minimizer.
static TVirtualFitter * GetFitter()
static: return the current Fitter
Double_t E()
Definition: TMath.h:54
virtual Double_t GetSumLog(Int_t i)
Sum of log (un-needed)
const double * Coords(unsigned int ipoint) const
return a pointer to the coordinates data for the given fit point
Definition: BinData.h:226
virtual Double_t * GetCovarianceMatrix() const
Get the error matrix in a pointer to a NxN array.
TLine * l
Definition: textangle.C:4
int Like
Definition: Foption.h:34
Class describing the binned data sets : vectors of x coordinates, y values and optionally error on y ...
Definition: BinData.h:61
float xmax
Definition: THbookFile.cxx:93
TGraphErrors * gr
Definition: legend1.C:25
virtual void PrintResults(Int_t level, Double_t amin) const
Print the fit result.
void InitWithPrototype(TClass *cl, const char *method, const char *proto, Bool_t objectIsConst=kFALSE, ROOT::EFunctionMatchMode mode=ROOT::kConversionMatch)
Initialize the method invocation environment.
long Long_t
Definition: RtypesCore.h:50
virtual void ReleaseParameter(Int_t ipar)
Release a fit parameter.
class containg the result of the fit and all the related information (fitted parameter values...
Definition: FitResult.h:52
virtual Double_t GetCovarianceMatrixElement(Int_t i, Int_t j) const
Get error matrix element (return all zero if matrix is not available)
std::shared_ptr< ROOT::Fit::FitData > fFitData
virtual void SetPoint(Int_t i, Double_t x, Double_t y, Double_t z)
Set x, y and z values for point number i.
double Double_t
Definition: RtypesCore.h:55
TFitResult * GetTFitResult() const
Return a new copy of the TFitResult object which needs to be deleted later by the user...
double Error(unsigned int i) const
parameter error by index
Definition: FitResult.h:191
Double_t y[n]
Definition: legend1.C:17
double func(double *x, double *p)
Definition: stressTF1.cxx:213
The TH1 histogram class.
Definition: TH1.h:80
#define name(a, b)
Definition: linkTestLib0.cpp:5
Mother of all ROOT objects.
Definition: TObject.h:58
double MinFcnValue() const
Return value of the objective function (chi2 or likelihood) used in the fit.
Definition: FitResult.h:125
virtual void SetPoint(Int_t i, Double_t x, Double_t y)
Set x and y values for point number i.
Definition: TGraph.cxx:2127
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition: Util.h:42
std::vector< double > fCovar
void Execute(const char *, const char *, int *=0)
Execute method on this object with the given parameter string, e.g.
Definition: TMethodCall.h:68
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
virtual TObject * GetObjectFit() const
A Graph is a graphics object made of two arrays X and Y with npoints each.
Definition: TGraph.h:53
virtual Int_t GetStats(Double_t &amin, Double_t &edm, Double_t &errdef, Int_t &nvpar, Int_t &nparx) const
Get fit statistical information.
virtual Int_t SetParameter(Int_t ipar, const char *parname, Double_t value, Double_t verr, Double_t vlow, Double_t vhigh)
Set (add) a new fit parameter passing initial value, step size (verr) and parameter limits if vlow > ...
A TGraphErrors is a TGraph with error bars.
Definition: TGraphErrors.h:28
const DataOptions & Opt() const
access to options
Definition: DataVector.h:97
void(* fFCN)(Int_t &npar, Double_t *gin, Double_t &f, Double_t *u, Int_t flag)
std::shared_ptr< ROOT::Fit::Fitter > fFitter
data of the fit
void SetLimits(double low, double up)
set a double side limit, if low == up the parameter is fixed if low > up the limits are removed ...
virtual const char * Getp2f2funcname(void *) const
Definition: TInterpreter.h:213
virtual bool Scan(unsigned int ivar, unsigned int &nstep, double *x, double *y, double xmin=0, double xmax=0)
scan function minimum for variable i.
Definition: Minimizer.h:375
double result[121]
ROOT::Math::IMultiGenFunction * GetObjFunction() const
Return a pointer to the objective function (FCN) If fitting directly using TBackCompFitter the pointe...
unsigned int NTotalParameters() const
get total number of parameters
Definition: FitResult.h:134
virtual void GetConfidenceIntervals(Int_t n, Int_t ndim, const Double_t *x, Double_t *ci, Double_t cl=0.95)
Computes point-by-point confidence intervals for the fitted function.
virtual Double_t Chisquare(Int_t npar, Double_t *params) const
Do chisquare calculations in case of likelihood fits Do evaluation a the minimum only.
void SetDimension(int dim)
Definition: FcnAdapter.h:46
R__EXTERN TInterpreter * gCling
Definition: TInterpreter.h:504
virtual void SetPointError(Double_t ex, Double_t ey)
Set ex and ey values for point pointed by the mouse.
Documentation for the abstract class IBaseFunctionMultiDim.
Definition: IFunction.h:63
virtual void Set(Int_t n)
Set number of points in the graph Existing coordinates are preserved New coordinates above fNpoints a...
Definition: TGraph.cxx:2076
TObject * obj
float value
Definition: math.cpp:443
virtual void SetFitMethod(const char *name)
Set fit method (chi2 or likelihood).
const Int_t n
Definition: legend1.C:16
ROOT::Math::IParamMultiFunction * fModelFunc
virtual IBaseFunctionMultiDim * Clone() const =0
Clone a function.
TMethodCall * fMethodCall
double GlobalCC(unsigned int i) const
parameter global correlation coefficient
Definition: FitResult.h:215
Graph 2D class with errors.
virtual void Warning(const char *method, const char *msgfmt,...) const
Issue warning message.
Definition: TObject.cxx:904