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