Logo ROOT  
Reference Guide
RooMinimizer.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
9 * *
10 * Redistribution and use in source and binary forms, *
11 * with or without modification, are permitted according to the terms *
12 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
13 *****************************************************************************/
14
15/**
16\file RooMinimizer.cxx
17\class RooMinimizer
18\ingroup Roofitcore
19
20RooMinimizer is a wrapper class around ROOT::Fit:Fitter that
21provides a seamless interface between the minimizer functionality
22and the native RooFit interface.
23By default the Minimizer is MINUIT.
24RooMinimizer can minimize any RooAbsReal function with respect to
25its parameters. Usual choices for minimization are RooNLLVar
26and RooChi2Var
27RooMinimizer has methods corresponding to MINUIT functions like
28hesse(), migrad(), minos() etc. In each of these function calls
29the state of the MINUIT engine is synchronized with the state
30of the RooFit variables: any change in variables, change
31in the constant status etc is forwarded to MINUIT prior to
32execution of the MINUIT call. Afterwards the RooFit objects
33are resynchronized with the output state of MINUIT: changes
34parameter values, errors are propagated.
35Various methods are available to control verbosity, profiling,
36automatic PDF optimization.
37**/
38
39#ifndef __ROOFIT_NOROOMINIMIZER
40
41#include "RooFit.h"
42#include "Riostream.h"
43
44#include "TClass.h"
45
46#include <fstream>
47
48#include "TH1.h"
49#include "TH2.h"
50#include "TMarker.h"
51#include "TGraph.h"
52#include "Fit/FitConfig.h"
53#include "TStopwatch.h"
54#include "TDirectory.h"
55#include "TMatrixDSym.h"
56
57#include "RooArgSet.h"
58#include "RooArgList.h"
59#include "RooAbsReal.h"
60#include "RooAbsRealLValue.h"
61#include "RooRealVar.h"
62#include "RooAbsPdf.h"
63#include "RooSentinel.h"
64#include "RooMsgService.h"
65#include "RooPlot.h"
66
67
68#include "RooMinimizer.h"
69#include "RooFitResult.h"
70
71#include "Math/Minimizer.h"
72
73#if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
74char* operator+( streampos&, char* );
75#endif
76
77using namespace std;
78
80;
81
83
84
85
86////////////////////////////////////////////////////////////////////////////////
87/// Cleanup method called by atexit handler installed by RooSentinel
88/// to delete all global heap objects when the program is terminated
89
91{
92 if (_theFitter) {
93 delete _theFitter ;
94 _theFitter =0 ;
95 }
96}
97
98
99
100////////////////////////////////////////////////////////////////////////////////
101/// Construct MINUIT interface to given function. Function can be anything,
102/// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
103/// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
104/// of a RooNLLVar plus a penalty or constraint term. This class propagates
105/// all RooFit information (floating parameters, their values and errors)
106/// to MINUIT before each MINUIT call and propagates all MINUIT information
107/// back to the RooFit object at the end of each call (updated parameter
108/// values, their (asymmetric errors) etc. The default MINUIT error level
109/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
110/// value of the input function.
111
113{
115
116 // Store function reference
117 _extV = 0 ;
118 _func = &function ;
119 _optConst = kFALSE ;
120 _verbose = kFALSE ;
121 _profile = kFALSE ;
123 _printLevel = 1 ;
124 _minimizerType = "Minuit"; // default minimizer
125
126 if (_theFitter) delete _theFitter ;
130 setEps(1.0); // default tolerance
131 // default max number of calls
134
135 // Shut up for now
136 setPrintLevel(-1) ;
137
138 // Use +0.5 for 1-sigma errors
140
141 // Declare our parameters to MINUIT
144
145 // Now set default verbosity
146 if (RooMsgService::instance().silentMode()) {
147 setPrintLevel(-1) ;
148 } else {
149 setPrintLevel(1) ;
150 }
151}
152
153
154
155////////////////////////////////////////////////////////////////////////////////
156/// Destructor
157
159{
160 if (_extV) {
161 delete _extV ;
162 }
163
164 if (_fcn) {
165 delete _fcn;
166 }
167
168}
169
170
171
172////////////////////////////////////////////////////////////////////////////////
173/// Change MINUIT strategy to istrat. Accepted codes
174/// are 0,1,2 and represent MINUIT strategies for dealing
175/// most efficiently with fast FCNs (0), expensive FCNs (2)
176/// and 'intermediate' FCNs (1)
177
179{
181
182}
183
184
185
186////////////////////////////////////////////////////////////////////////////////
187/// Change maximum number of MINUIT iterations
188/// (RooMinimizer default 500 * #parameters)
189
191{
193}
194
195
196
197
198////////////////////////////////////////////////////////////////////////////////
199/// Change maximum number of likelihood function calss from MINUIT
200/// (RooMinimizer default 500 * #parameters)
201
203{
205}
206
207
208
209
210////////////////////////////////////////////////////////////////////////////////
211/// Set the level for MINUIT error analysis to the given
212/// value. This function overrides the default value
213/// that is taken in the RooMinimizer constructor from
214/// the defaultErrorLevel() method of the input function
215
217{
219
220}
221
222
223
224////////////////////////////////////////////////////////////////////////////////
225/// Change MINUIT epsilon
226
228{
230
231}
232
233
234////////////////////////////////////////////////////////////////////////////////
235/// Enable internal likelihood offsetting for enhanced numeric precision
236
238{
239 _func->enableOffsetting(flag) ;
240}
241
242
243
244
245////////////////////////////////////////////////////////////////////////////////
246/// Choose the minimiser algorithm.
248{
250}
251
252
253
254
255////////////////////////////////////////////////////////////////////////////////
256/// Return underlying ROOT fitter object
257
259{
260 return _theFitter ;
261}
262
263
264////////////////////////////////////////////////////////////////////////////////
265/// Return underlying ROOT fitter object
266
268{
269 return _theFitter ;
270}
271
272
273
274////////////////////////////////////////////////////////////////////////////////
275/// Parse traditional RooAbsPdf::fitTo driver options
276///
277/// m - Run Migrad only
278/// h - Run Hesse to estimate errors
279/// v - Verbose mode
280/// l - Log parameters after each Minuit steps to file
281/// t - Activate profile timer
282/// r - Save fit result
283/// 0 - Run Migrad with strategy 0
284
285RooFitResult* RooMinimizer::fit(const char* options)
286{
287 TString opts(options) ;
288 opts.ToLower() ;
289
290 // Initial configuration
291 if (opts.Contains("v")) setVerbose(1) ;
292 if (opts.Contains("t")) setProfile(1) ;
293 if (opts.Contains("l")) setLogFile(Form("%s.log",_func->GetName())) ;
294 if (opts.Contains("c")) optimizeConst(1) ;
295
296 // Fitting steps
297 if (opts.Contains("0")) setStrategy(0) ;
298 migrad() ;
299 if (opts.Contains("0")) setStrategy(1) ;
300 if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
301 if (!opts.Contains("m")) minos() ;
302
303 return (opts.Contains("r")) ? save() : 0 ;
304}
305
306
307
308
309////////////////////////////////////////////////////////////////////////////////
310/// Minimise the function passed in the constructor.
311/// \param[in] type Type of fitter to use, e.g. "Minuit" "Minuit2".
312/// \attention This overrides the default fitter of this RooMinimizer.
313/// \param[in] alg Fit algorithm to use. (Optional)
314Int_t RooMinimizer::minimize(const char* type, const char* alg)
315{
318
321
322 profileStart() ;
325
326 bool ret = _theFitter->FitFCN(*_fcn);
327 _status = ((ret) ? _theFitter->Result().Status() : -1);
328
330 profileStop() ;
332
333 saveStatus("MINIMIZE",_status) ;
334
335 return _status ;
336}
337
338
339
340////////////////////////////////////////////////////////////////////////////////
341/// Execute MIGRAD. Changes in parameter values
342/// and calculated errors are automatically
343/// propagated back the RooRealVars representing
344/// the floating parameters in the MINUIT operation.
345
347{
350 profileStart() ;
353
354 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migrad");
355 bool ret = _theFitter->FitFCN(*_fcn);
356 _status = ((ret) ? _theFitter->Result().Status() : -1);
357
359 profileStop() ;
361
362 saveStatus("MIGRAD",_status) ;
363
364 return _status ;
365}
366
367
368
369////////////////////////////////////////////////////////////////////////////////
370/// Execute HESSE. Changes in parameter values
371/// and calculated errors are automatically
372/// propagated back the RooRealVars representing
373/// the floating parameters in the MINUIT operation.
374
376{
377 if (_theFitter->GetMinimizer()==0) {
378 coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!"
379 << endl ;
380 _status = -1;
381 }
382 else {
383
386 profileStart() ;
389
391 bool ret = _theFitter->CalculateHessErrors();
392 _status = ((ret) ? _theFitter->Result().Status() : -1);
393
395 profileStop() ;
397
398 saveStatus("HESSE",_status) ;
399
400 }
401
402 return _status ;
403
404}
405
406////////////////////////////////////////////////////////////////////////////////
407/// Execute MINOS. Changes in parameter values
408/// and calculated errors are automatically
409/// propagated back the RooRealVars representing
410/// the floating parameters in the MINUIT operation.
411
413{
414 if (_theFitter->GetMinimizer()==0) {
415 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
416 << endl ;
417 _status = -1;
418 }
419 else {
420
423 profileStart() ;
426
428 bool ret = _theFitter->CalculateMinosErrors();
429 _status = ((ret) ? _theFitter->Result().Status() : -1);
430
432 profileStop() ;
434
435 saveStatus("MINOS",_status) ;
436
437 }
438
439 return _status ;
440
441}
442
443
444////////////////////////////////////////////////////////////////////////////////
445/// Execute MINOS for given list of parameters. Changes in parameter values
446/// and calculated errors are automatically
447/// propagated back the RooRealVars representing
448/// the floating parameters in the MINUIT operation.
449
450Int_t RooMinimizer::minos(const RooArgSet& minosParamList)
451{
452 if (_theFitter->GetMinimizer()==0) {
453 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
454 << endl ;
455 _status = -1;
456 }
457 else if (minosParamList.getSize()>0) {
458
461 profileStart() ;
464
465 // get list of parameters for Minos
466 TIterator* aIter = minosParamList.createIterator() ;
467 RooAbsArg* arg ;
468 std::vector<unsigned int> paramInd;
469 while((arg=(RooAbsArg*)aIter->Next())) {
470 RooAbsArg* par = _fcn->GetFloatParamList()->find(arg->GetName());
471 if (par && !par->isConstant()) {
472 Int_t index = _fcn->GetFloatParamList()->index(par);
473 paramInd.push_back(index);
474 }
475 }
476 delete aIter ;
477
478 if (paramInd.size()) {
479 // set the parameter indeces
480 _theFitter->Config().SetMinosErrors(paramInd);
481
483 bool ret = _theFitter->CalculateMinosErrors();
484 _status = ((ret) ? _theFitter->Result().Status() : -1);
485 // to avoid that following minimization computes automatically the Minos errors
487
488 }
489
491 profileStop() ;
493
494 saveStatus("MINOS",_status) ;
495
496 }
497
498 return _status ;
499}
500
501
502
503////////////////////////////////////////////////////////////////////////////////
504/// Execute SEEK. Changes in parameter values
505/// and calculated errors are automatically
506/// propagated back the RooRealVars representing
507/// the floating parameters in the MINUIT operation.
508
510{
513 profileStart() ;
516
517 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"seek");
518 bool ret = _theFitter->FitFCN(*_fcn);
519 _status = ((ret) ? _theFitter->Result().Status() : -1);
520
522 profileStop() ;
524
525 saveStatus("SEEK",_status) ;
526
527 return _status ;
528}
529
530
531
532////////////////////////////////////////////////////////////////////////////////
533/// Execute SIMPLEX. Changes in parameter values
534/// and calculated errors are automatically
535/// propagated back the RooRealVars representing
536/// the floating parameters in the MINUIT operation.
537
539{
542 profileStart() ;
545
546 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"simplex");
547 bool ret = _theFitter->FitFCN(*_fcn);
548 _status = ((ret) ? _theFitter->Result().Status() : -1);
549
551 profileStop() ;
553
554 saveStatus("SEEK",_status) ;
555
556 return _status ;
557}
558
559
560
561////////////////////////////////////////////////////////////////////////////////
562/// Execute IMPROVE. Changes in parameter values
563/// and calculated errors are automatically
564/// propagated back the RooRealVars representing
565/// the floating parameters in the MINUIT operation.
566
568{
571 profileStart() ;
574
575 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migradimproved");
576 bool ret = _theFitter->FitFCN(*_fcn);
577 _status = ((ret) ? _theFitter->Result().Status() : -1);
578
580 profileStop() ;
582
583 saveStatus("IMPROVE",_status) ;
584
585 return _status ;
586}
587
588
589
590////////////////////////////////////////////////////////////////////////////////
591/// Change the MINUIT internal printing level
592
594{
595 Int_t ret = _printLevel ;
597 _printLevel = newLevel+1 ;
598 return ret ;
599}
600
601////////////////////////////////////////////////////////////////////////////////
602/// If flag is true, perform constant term optimization on
603/// function being minimized.
604
606{
608
609 if (_optConst && !flag){
610 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: deactivating const optimization" << endl ;
612 _optConst = flag ;
613 } else if (!_optConst && flag) {
614 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: activating const optimization" << endl ;
616 _optConst = flag ;
617 } else if (_optConst && flag) {
618 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: const optimization already active" << endl ;
619 } else {
620 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: const optimization wasn't active" << endl ;
621 }
622
624
625}
626
627
628
629////////////////////////////////////////////////////////////////////////////////
630/// Save and return a RooFitResult snaphot of current minimizer status.
631/// This snapshot contains the values of all constant parameters,
632/// the value of all floating parameters at RooMinimizer construction and
633/// after the last MINUIT operation, the MINUIT status, variance quality,
634/// EDM setting, number of calls with evaluation problems, the minimized
635/// function value and the full correlation matrix
636
637RooFitResult* RooMinimizer::save(const char* userName, const char* userTitle)
638{
639 if (_theFitter->GetMinimizer()==0) {
640 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!"
641 << endl ;
642 return 0;
643 }
644
645 TString name,title ;
646 name = userName ? userName : Form("%s", _func->GetName()) ;
647 title = userTitle ? userTitle : Form("%s", _func->GetTitle()) ;
648 RooFitResult* fitRes = new RooFitResult(name,title) ;
649
650 // Move eventual fixed parameters in floatList to constList
651 Int_t i ;
652 RooArgList saveConstList(*(_fcn->GetConstParamList())) ;
653 RooArgList saveFloatInitList(*(_fcn->GetInitFloatParamList())) ;
654 RooArgList saveFloatFinalList(*(_fcn->GetFloatParamList())) ;
655 for (i=0 ; i<_fcn->GetFloatParamList()->getSize() ; i++) {
656 RooAbsArg* par = _fcn->GetFloatParamList()->at(i) ;
657 if (par->isConstant()) {
658 saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),kTRUE) ;
659 saveFloatFinalList.remove(*par) ;
660 saveConstList.add(*par) ;
661 }
662 }
663 saveConstList.sort() ;
664
665 fitRes->setConstParList(saveConstList) ;
666 fitRes->setInitParList(saveFloatInitList) ;
667
668 fitRes->setStatus(_status) ;
670 fitRes->setMinNLL(_theFitter->Result().MinFcnValue()) ;
672 fitRes->setEDM(_theFitter->Result().Edm()) ;
673 fitRes->setFinalParList(saveFloatFinalList) ;
674 if (!_extV) {
675 std::vector<double> globalCC;
676 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
677 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
678 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
679 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
680 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
681 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
682 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
683 }
684 }
685 fitRes->fillCorrMatrix(globalCC,corrs,covs) ;
686 } else {
687 fitRes->setCovarianceMatrix(*_extV) ;
688 }
689
691
692 return fitRes ;
693
694}
695
696////////////////////////////////////////////////////////////////////////////////
697/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
698/// \param[in] var1 The first parameter (x axis).
699/// \param[in] var2 The second parameter (y axis).
700/// \param[in] n1 First contour.
701/// \param[in] n2 Optional contour. 0 means don't draw.
702/// \param[in] n3 Optional contour. 0 means don't draw.
703/// \param[in] n4 Optional contour. 0 means don't draw.
704/// \param[in] n5 Optional contour. 0 means don't draw.
705/// \param[in] n6 Optional contour. 0 means don't draw.
706/// \param[in] npoints Number of points for evaluating the contour.
707///
708/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
709/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
710/// See ROOT::Math::Minimizer::ErrorDef().
711
713 Double_t n1, Double_t n2, Double_t n3,
714 Double_t n4, Double_t n5, Double_t n6, unsigned int npoints)
715{
716
717
718 RooArgList* params = _fcn->GetFloatParamList() ;
719 RooArgList* paramSave = (RooArgList*) params->snapshot() ;
720
721 // Verify that both variables are floating parameters of PDF
722 Int_t index1= _fcn->GetFloatParamList()->index(&var1);
723 if(index1 < 0) {
724 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
725 << ") ERROR: " << var1.GetName()
726 << " is not a floating parameter of "
727 << _func->GetName() << endl ;
728 return 0;
729 }
730
731 Int_t index2= _fcn->GetFloatParamList()->index(&var2);
732 if(index2 < 0) {
733 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
734 << ") ERROR: " << var2.GetName()
735 << " is not a floating parameter of PDF "
736 << _func->GetName() << endl ;
737 return 0;
738 }
739
740 // create and draw a frame
741 RooPlot* frame = new RooPlot(var1,var2) ;
742
743 // draw a point at the current parameter values
744 TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
745 frame->addObject(point) ;
746
747 // check first if a inimizer is available. If not means
748 // the minimization is not done , so do it
749 if (_theFitter->GetMinimizer()==0) {
750 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
751 << endl ;
752 return frame;
753 }
754
755
756 // remember our original value of ERRDEF
758
759 Double_t n[6] ;
760 n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
761
762 for (Int_t ic = 0 ; ic<6 ; ic++) {
763 if(n[ic] > 0) {
764
765 // set the value corresponding to an n1-sigma contour
766 _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
767
768 // calculate and draw the contour
769 Double_t *xcoor = new Double_t[npoints+1];
770 Double_t *ycoor = new Double_t[npoints+1];
771 bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
772
773 if (!ret) {
774 coutE(Minimization) << "RooMinimizer::contour("
775 << GetName()
776 << ") ERROR: MINUIT did not return a contour graph for n="
777 << n[ic] << endl ;
778 } else {
779 xcoor[npoints] = xcoor[0];
780 ycoor[npoints] = ycoor[0];
781 TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
782
783 graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ;
784 graph->SetLineStyle(ic+1) ;
785 graph->SetLineWidth(2) ;
786 graph->SetLineColor(kBlue) ;
787 frame->addObject(graph,"L") ;
788 }
789
790 delete [] xcoor;
791 delete [] ycoor;
792 }
793 }
794
795
796 // restore the original ERRDEF
798
799 // restore parameter values
800 *params = *paramSave ;
801 delete paramSave ;
802
803 return frame ;
804
805}
806
807
808////////////////////////////////////////////////////////////////////////////////
809/// Start profiling timer
810
812{
813 if (_profile) {
814 _timer.Start() ;
817 }
818}
819
820
821////////////////////////////////////////////////////////////////////////////////
822/// Stop profiling timer and report results of last session
823
825{
826 if (_profile) {
827 _timer.Stop() ;
828 _cumulTimer.Stop() ;
829 coutI(Minimization) << "Command timer: " ; _timer.Print() ;
830 coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
831 }
832}
833
834
835
836
837
838////////////////////////////////////////////////////////////////////////////////
839/// Apply results of given external covariance matrix. i.e. propagate its errors
840/// to all RRV parameter representations and give this matrix instead of the
841/// HESSE matrix at the next save() call
842
844{
845 _extV = (TMatrixDSym*) V.Clone() ;
847
848}
849
850
851
853{
854 // Import the results of the last fit performed, interpreting
855 // the fit parameters as the given varList of parameters.
856
857 if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
858 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
859 << endl ;
860 return 0;
861 }
862
863 // Verify length of supplied varList
864 if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
866 << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
867 << " or match the number of variables of the last fit ("
868 << _theFitter->Result().NTotalParameters() << ")" << endl ;
869 return 0 ;
870 }
871
872
873 // Verify that all members of varList are of type RooRealVar
874 TIterator* iter = varList.createIterator() ;
875 RooAbsArg* arg ;
876 while((arg=(RooAbsArg*)iter->Next())) {
877 if (!dynamic_cast<RooRealVar*>(arg)) {
878 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
879 << arg->GetName() << "' is not of type RooRealVar" << endl ;
880 return 0 ;
881 }
882 }
883 delete iter ;
884
885 RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
886
887 // Extract names of fit parameters
888 // and construct corresponding RooRealVars
889 RooArgList constPars("constPars") ;
890 RooArgList floatPars("floatPars") ;
891
892 UInt_t i ;
893 for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
894
897
900 Double_t xerr = _theFitter->Result().Error(i);
901 Double_t xval = _theFitter->Result().Value(i);
902
903 RooRealVar* var ;
904 if (varList.getSize()==0) {
905
906 if ((xlo<xhi) && !isConst) {
907 var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
908 } else {
909 var = new RooRealVar(varName,varName,xval) ;
910 }
911 var->setConstant(isConst) ;
912 } else {
913
914 var = (RooRealVar*) varList.at(i)->Clone() ;
915 var->setConstant(isConst) ;
916 var->setVal(xval) ;
917 if (xlo<xhi) {
918 var->setRange(xlo,xhi) ;
919 }
920
921 if (varName.CompareTo(var->GetName())) {
922 oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
923 << "' stored in variable '" << var->GetName() << "'" << endl ;
924 }
925
926 }
927
928 if (isConst) {
929 constPars.addOwned(*var) ;
930 } else {
931 var->setError(xerr) ;
932 floatPars.addOwned(*var) ;
933 }
934 }
935
936 res->setConstParList(constPars) ;
937 res->setInitParList(floatPars) ;
938 res->setFinalParList(floatPars) ;
940 res->setEDM(_theFitter->Result().Edm()) ;
942 res->setStatus(_theFitter->Result().Status()) ;
943 std::vector<double> globalCC;
944 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
945 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
946 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
947 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
948 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
949 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
950 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
951 }
952 }
953 res->fillCorrMatrix(globalCC,corrs,covs) ;
954
955 return res;
956
957}
958
959#endif
#define coutI(a)
Definition: RooMsgService.h:30
#define coutW(a)
Definition: RooMsgService.h:32
#define oocoutE(o, a)
Definition: RooMsgService.h:48
#define oocoutI(o, a)
Definition: RooMsgService.h:45
#define coutE(a)
Definition: RooMsgService.h:33
int Int_t
Definition: RtypesCore.h:43
unsigned int UInt_t
Definition: RtypesCore.h:44
const Bool_t kFALSE
Definition: RtypesCore.h:90
bool Bool_t
Definition: RtypesCore.h:61
double Double_t
Definition: RtypesCore.h:57
const Bool_t kTRUE
Definition: RtypesCore.h:89
#define ClassImp(name)
Definition: Rtypes.h:361
@ kBlue
Definition: Rtypes.h:64
char name[80]
Definition: TGX11.cxx:109
int type
Definition: TGX11.cxx:120
char * Form(const char *fmt,...)
TString operator+(const TString &s1, const TString &s2)
Use the special concatenation constructor.
Definition: TString.cxx:1474
void SetMinosErrors(bool on=true)
set Minos erros computation to be performed after fitting
Definition: FitConfig.h:230
void SetMinimizer(const char *type, const char *algo=0)
set minimizer type
Definition: FitConfig.h:180
const std::vector< ROOT::Fit::ParameterSettings > & ParamsSettings() const
get the vector of parameter settings (const method)
Definition: FitConfig.h:85
const ParameterSettings & ParSettings(unsigned int i) const
get the parameter settings for the i-th parameter (const method)
Definition: FitConfig.h:75
ROOT::Math::MinimizerOptions & MinimizerOptions()
access to the minimizer control parameter (non const method)
Definition: FitConfig.h:166
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
Definition: FitResult.cxx:404
double Error(unsigned int i) const
parameter error by index
Definition: FitResult.h:186
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
Definition: FitResult.h:216
double Value(unsigned int i) const
parameter value by index
Definition: FitResult.h:179
const std::vector< double > & Parameters() const
parameter values (return std::vector)
Definition: FitResult.h:174
std::string GetParameterName(unsigned int ipar) const
get name of parameter (deprecated)
Definition: FitResult.h:328
double MinFcnValue() const
Return value of the objective function (chi2 or likelihood) used in the fit.
Definition: FitResult.h:120
double Edm() const
Expected distance from minimum.
Definition: FitResult.h:126
double Correlation(unsigned int i, unsigned int j) const
retrieve correlation elements
Definition: FitResult.h:226
unsigned int NTotalParameters() const
get total number of parameters
Definition: FitResult.h:129
int Status() const
minimizer status code
Definition: FitResult.h:137
double GlobalCC(unsigned int i) const
parameter global correlation coefficient
Definition: FitResult.h:210
Fitter class, entry point for performing all type of fits.
Definition: Fitter.h:77
bool FitFCN(unsigned int npar, Function &fcn, const double *params=0, unsigned int dataSize=0, bool chi2fit=false)
Fit using the a generic FCN function as a C++ callable object implementing double () (const double *)...
Definition: Fitter.h:610
ROOT::Math::Minimizer * GetMinimizer() const
return pointer to last used minimizer (is NULL in case fit is not yet done) This pointer is guranteed...
Definition: Fitter.h:434
const FitResult & Result() const
get fit result
Definition: Fitter.h:384
const FitConfig & Config() const
access to the fit configuration (const method)
Definition: Fitter.h:412
bool CalculateMinosErrors()
perform an error analysis on the result using MINOS To be called only after fitting and when a minimi...
Definition: Fitter.cxx:731
bool CalculateHessErrors()
perform an error analysis on the result using the Hessian Errors are obtaied from the inverse of the ...
Definition: Fitter.cxx:655
double LowerLimit() const
return lower limit value
double UpperLimit() const
return upper limit value
void SetMaxFunctionCalls(unsigned int maxfcn)
set maximum of function calls
void SetStrategy(int stra)
set the strategy
void SetMaxIterations(unsigned int maxiter)
set maximum iterations (one iteration can have many function calls)
void SetErrorDef(double err)
set error def
void SetPrintLevel(int level)
set print level
void SetTolerance(double tol)
set the tolerance
void SetErrorDef(double up)
set scale for calculating the errors
Definition: Minimizer.h:466
virtual int CovMatrixStatus() const
return status of covariance matrix using Minuit convention {0 not calculated 1 approximated 2 made po...
Definition: Minimizer.h:318
double ErrorDef() const
return the statistical scale used for calculate the error is typically 1 for Chi2 and 0....
Definition: Minimizer.h:436
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:378
RooAbsArg is the common abstract base class for objects that represent a value (of arbitrary type) an...
Definition: RooAbsArg.h:73
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:85
virtual void constOptimizeTestStatistic(ConstOpCode opcode, Bool_t doAlsoTrackingOpt=kTRUE)
Interface function signaling a request to perform constant term optimization.
Definition: RooAbsArg.cxx:1705
@ DeActivate
Definition: RooAbsArg.h:374
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition: RooAbsArg.h:342
Int_t getSize() const
void sort(Bool_t reverse=false)
Sort collection using std::sort and name comparison.
RooAbsCollection * snapshot(Bool_t deepCopy=kTRUE) const
Take a snap shot of current collection contents.
virtual Bool_t addOwned(RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
Int_t index(const RooAbsArg *arg) const
Returns index of given arg, or -1 if arg is not in the collection.
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
virtual Bool_t remove(const RooAbsArg &var, Bool_t silent=kFALSE, Bool_t matchByNameOnly=kFALSE)
Remove the specified argument from our list.
TIterator * createIterator(Bool_t dir=kIterForward) const
TIterator-style iteration over contained elements.
RooAbsArg * find(const char *name) const
Find object with given name in list.
void setConstant(Bool_t value=kTRUE)
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:60
virtual Double_t defaultErrorLevel() const
Definition: RooAbsReal.h:224
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition: RooAbsReal.h:90
virtual void enableOffsetting(Bool_t)
Definition: RooAbsReal.h:342
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgList.h:21
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition: RooArgList.h:74
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:28
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Definition: RooFitResult.h:40
void fillCorrMatrix()
Internal utility method to extract the correlation matrix and the global correlation coefficients fro...
void setCovQual(Int_t val)
Definition: RooFitResult.h:170
void setMinNLL(Double_t val)
Definition: RooFitResult.h:167
void setNumInvalidNLL(Int_t val)
Definition: RooFitResult.h:171
void setStatus(Int_t val)
Definition: RooFitResult.h:169
void setConstParList(const RooArgList &list)
Fill the list of constant parameters.
void setCovarianceMatrix(TMatrixDSym &V)
Store externally provided correlation matrix in this RooFitResult ;.
void setEDM(Double_t val)
Definition: RooFitResult.h:168
void setStatusHistory(std::vector< std::pair< std::string, int > > &hist)
Definition: RooFitResult.h:176
void setInitParList(const RooArgList &list)
Fill the list of initial values of the floating parameters.
void setFinalParList(const RooArgList &list)
Fill the list of final values of the floating parameters.
Int_t GetNumInvalidNLL()
RooArgList * GetInitFloatParamList()
void ApplyCovarianceMatrix(TMatrixDSym &V)
virtual unsigned int NDim() const
Retrieve the dimension of the function.
Bool_t Synchronize(std::vector< ROOT::Fit::ParameterSettings > &parameters, Bool_t optConst, Bool_t verbose)
void BackProp(const ROOT::Fit::FitResult &results)
RooArgList * GetFloatParamList()
RooArgList * GetConstParamList()
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
Definition: RooMinimizer.h:38
Int_t _printLevel
Definition: RooMinimizer.h:108
RooMinimizerFcn * _fcn
Definition: RooMinimizer.h:121
std::vector< std::pair< std::string, int > > _statusHistory
Definition: RooMinimizer.h:126
RooMinimizer(RooAbsReal &function)
Construct MINUIT interface to given function.
Int_t hesse()
Execute HESSE.
void setMaxIterations(Int_t n)
Change maximum number of MINUIT iterations (RooMinimizer default 500 * #parameters)
RooFitResult * save(const char *name=0, const char *title=0)
Save and return a RooFitResult snaphot of current minimizer status.
void setMinimizerType(const char *type)
Choose the minimiser algorithm.
Bool_t _verbose
Definition: RooMinimizer.h:114
void saveStatus(const char *label, Int_t status)
Definition: RooMinimizer.h:83
Int_t improve()
Execute IMPROVE.
void profileStart()
Start profiling timer.
RooPlot * contour(RooRealVar &var1, RooRealVar &var2, Double_t n1=1, Double_t n2=2, Double_t n3=0, Double_t n4=0, Double_t n5=0, Double_t n6=0, unsigned int npoints=50)
Create and draw a TH2 with the error contours in the parameters var1 and var2.
Int_t migrad()
Execute MIGRAD.
Int_t minimize(const char *type, const char *alg=0)
Minimise the function passed in the constructor.
void profileStop()
Stop profiling timer and report results of last session.
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
RooFitResult * fit(const char *options)
Parse traditional RooAbsPdf::fitTo driver options.
void setOffsetting(Bool_t flag)
Enable internal likelihood offsetting for enhanced numeric precision.
TMatrixDSym * _extV
Definition: RooMinimizer.h:119
Int_t seek()
Execute SEEK.
Bool_t setLogFile(const char *logf=0)
Definition: RooMinimizer.h:76
void setProfile(Bool_t flag=kTRUE)
Definition: RooMinimizer.h:75
void setEps(Double_t eps)
Change MINUIT epsilon.
void setErrorLevel(Double_t level)
Set the level for MINUIT error analysis to the given value.
static ROOT::Fit::Fitter * _theFitter
Definition: RooMinimizer.h:124
static void cleanup()
Cleanup method called by atexit handler installed by RooSentinel to delete all global heap objects wh...
Int_t setPrintLevel(Int_t newLevel)
Change the MINUIT internal printing level.
TStopwatch _timer
Definition: RooMinimizer.h:115
void setMaxFunctionCalls(Int_t n)
Change maximum number of likelihood function calss from MINUIT (RooMinimizer default 500 * #parameter...
Int_t minos()
Execute MINOS.
RooAbsReal * _func
Definition: RooMinimizer.h:112
void applyCovarianceMatrix(TMatrixDSym &V)
Apply results of given external covariance matrix.
void optimizeConst(Int_t flag)
If flag is true, perform constant term optimization on function being minimized.
Int_t simplex()
Execute SIMPLEX.
Bool_t _optConst
Definition: RooMinimizer.h:110
Bool_t _profileStart
Definition: RooMinimizer.h:117
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
void setStrategy(Int_t strat)
Change MINUIT strategy to istrat.
std::string _minimizerType
Definition: RooMinimizer.h:122
TStopwatch _cumulTimer
Definition: RooMinimizer.h:116
Bool_t _profile
Definition: RooMinimizer.h:111
void setVerbose(Bool_t flag=kTRUE)
Definition: RooMinimizer.h:74
virtual ~RooMinimizer()
Destructor.
static RooMsgService & instance()
Return reference to singleton instance.
A RooPlot is a plot frame and a container for graphics objects within that frame.
Definition: RooPlot.h:44
void addObject(TObject *obj, Option_t *drawOptions="", Bool_t invisible=kFALSE)
Add a generic object to this plot.
Definition: RooPlot.cxx:443
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:35
void setError(Double_t value)
Definition: RooRealVar.h:64
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
Definition: RooRealVar.cxx:495
virtual void setVal(Double_t value)
Set value of variable to 'value'.
Definition: RooRealVar.cxx:225
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
Definition: RooSentinel.cxx:57
A TGraph is an object made of two arrays X and Y with npoints each.
Definition: TGraph.h:41
Iterator abstract base class.
Definition: TIterator.h:30
virtual TObject * Next()=0
Manages Markers.
Definition: TMarker.h:23
virtual const char * GetTitle() const
Returns title of object.
Definition: TNamed.h:48
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
Mother of all ROOT objects.
Definition: TObject.h:37
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:357
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition: TObject.cxx:144
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
Definition: TStopwatch.cxx:58
void Stop()
Stop the stopwatch.
Definition: TStopwatch.cxx:77
void Print(Option_t *option="") const
Print the real and cpu time passed between the start and stop events.
Definition: TStopwatch.cxx:219
Basic string class.
Definition: TString.h:131
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1125
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition: TString.cxx:418
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:619
RooCmdArg Parameters(const RooArgSet &params)
const Int_t n
Definition: legend1.C:16
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition: RExports.h:151
@ Minimization
Definition: RooGlobalFunc.h:67
@ InputArguments
Definition: RooGlobalFunc.h:68
Definition: graph.py:1