Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
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 * PB, Patrick Bos, NL eScience Center, p.bos@esciencecenter.nl *
10 * *
11 * Redistribution and use in source and binary forms, *
12 * with or without modification, are permitted according to the terms *
13 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
14 *****************************************************************************/
15
16/**
17\file RooMinimizer.cxx
18\class RooMinimizer
19\ingroup Roofitcore
20
21RooMinimizer is a wrapper class around ROOT::Fit:Fitter that
22provides a seamless interface between the minimizer functionality
23and the native RooFit interface.
24By default the Minimizer is MINUIT for classic FcnMode and MINUIT2
25for gradient FcnMode.
26RooMinimizer can minimize any RooAbsReal function with respect to
27its parameters. Usual choices for minimization are RooNLLVar
28and RooChi2Var
29RooMinimizer has methods corresponding to MINUIT functions like
30hesse(), migrad(), minos() etc. In each of these function calls
31the state of the MINUIT engine is synchronized with the state
32of the RooFit variables: any change in variables, change
33in the constant status etc is forwarded to MINUIT prior to
34execution of the MINUIT call. Afterwards the RooFit objects
35are resynchronized with the output state of MINUIT: changes
36parameter values, errors are propagated.
37Various methods are available to control verbosity, profiling,
38automatic PDF optimization.
39**/
40
41#include "RooMinimizer.h"
42
43#include "RooFit.h"
44#include "RooArgSet.h"
45#include "RooArgList.h"
46#include "RooAbsReal.h"
47#include "RooAbsRealLValue.h"
48#include "RooRealVar.h"
49#include "RooAbsPdf.h"
50#include "RooSentinel.h"
51#include "RooMsgService.h"
52#include "RooPlot.h"
53#include "RooMinimizerFcn.h"
54#include "RooGradMinimizerFcn.h"
55#include "RooFitResult.h"
57
58#include "TClass.h"
59#include "Math/Minimizer.h"
60#include "TH2.h"
61#include "TMarker.h"
62#include "TGraph.h"
63#include "Fit/FitConfig.h"
64#include "TStopwatch.h"
65#include "TMatrixDSym.h"
66
67#include <iostream>
68#include <fstream>
69
70#if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
71char* operator+( streampos&, char* );
72#endif
73
74using namespace std;
75
77;
78
80
81
82
83////////////////////////////////////////////////////////////////////////////////
84/// Cleanup method called by atexit handler installed by RooSentinel
85/// to delete all global heap objects when the program is terminated
86
88{
89 if (_theFitter) {
90 delete _theFitter ;
91 _theFitter =0 ;
92 }
93}
94
95
96
97////////////////////////////////////////////////////////////////////////////////
98/// Construct MINUIT interface to given function. Function can be anything,
99/// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
100/// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
101/// of a RooNLLVar plus a penalty or constraint term. This class propagates
102/// all RooFit information (floating parameters, their values and errors)
103/// to MINUIT before each MINUIT call and propagates all MINUIT information
104/// back to the RooFit object at the end of each call (updated parameter
105/// values, their (asymmetric errors) etc. The default MINUIT error level
106/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
107/// value of the input function.
108
109RooMinimizer::RooMinimizer(RooAbsReal &function, FcnMode fcnMode) : _fcnMode(fcnMode)
110{
112
113 switch (_fcnMode) {
114 case FcnMode::classic: {
115 _fcn = new RooMinimizerFcn(&function, this, _verbose);
116 break;
117 }
118 case FcnMode::gradient: {
119 _fcn = new RooGradMinimizerFcn(&function, this, _verbose);
120 setMinimizerType("Minuit2");
121 break;
122 }
124 throw std::logic_error("In RooMinimizer constructor: fcnMode::generic_wrapper cannot be used on a RooAbsReal! "
125 "Please use the TestStatistics::RooAbsL based constructor instead.");
126 }
127 default: {
128 throw std::logic_error("In RooMinimizer constructor: fcnMode has an unsupported value!");
129 }
130 }
131
132 initMinimizerFcnDependentPart(function.defaultErrorLevel());
133}
134
135RooMinimizer::RooMinimizer(std::shared_ptr<RooFit::TestStatistics::RooAbsL> likelihood,
138 : _fcnMode(FcnMode::generic_wrapper)
139{
141 _fcn = new RooFit::TestStatistics::MinuitFcnGrad(likelihood, this, _theFitter->Config().ParamsSettings(), likelihoodMode,
142 likelihoodGradientMode, _verbose);
143 initMinimizerFcnDependentPart(likelihood->defaultErrorLevel());
144}
145
146// constructor helpers
147
148/// Initialize the part of the minimizer that is independent of the function to be minimized
150{
152
153 if (_theFitter) {
154 delete _theFitter;
155 }
158 setEps(1.0); // default tolerance
159}
160
161/// Initialize the part of the minimizer that is dependent on the function to be minimized
163{
164 // default max number of calls
167
168 // Shut up for now
169 setPrintLevel(-1);
170
171 // Use +0.5 for 1-sigma errors
172 setErrorLevel(defaultErrorLevel);
173
174 // Declare our parameters to MINUIT
176
177 // Now set default verbosity
178 if (RooMsgService::instance().silentMode()) {
179 setPrintLevel(-1);
180 } else {
181 setPrintLevel(1);
182 }
183}
184
185
186////////////////////////////////////////////////////////////////////////////////
187/// Destructor
188
190{
191 if (_extV) {
192 delete _extV ;
193 }
194
195 if (_fcn) {
196 delete _fcn;
197 }
198
199}
200
201
202
203////////////////////////////////////////////////////////////////////////////////
204/// Change MINUIT strategy to istrat. Accepted codes
205/// are 0,1,2 and represent MINUIT strategies for dealing
206/// most efficiently with fast FCNs (0), expensive FCNs (2)
207/// and 'intermediate' FCNs (1)
208
210{
212
213}
214
215
216
217////////////////////////////////////////////////////////////////////////////////
218/// Change maximum number of MINUIT iterations
219/// (RooMinimizer default 500 * #parameters)
220
222{
224}
225
226
227
228
229////////////////////////////////////////////////////////////////////////////////
230/// Change maximum number of likelihood function calss from MINUIT
231/// (RooMinimizer default 500 * #parameters)
232
234{
236}
237
238
239
240
241////////////////////////////////////////////////////////////////////////////////
242/// Set the level for MINUIT error analysis to the given
243/// value. This function overrides the default value
244/// that is taken in the RooMinimizer constructor from
245/// the defaultErrorLevel() method of the input function
246
248{
250
251}
252
253
254
255////////////////////////////////////////////////////////////////////////////////
256/// Change MINUIT epsilon
257
259{
261
262}
263
264
265////////////////////////////////////////////////////////////////////////////////
266/// Enable internal likelihood offsetting for enhanced numeric precision
267
269{
270 _fcn->setOffsetting(flag);
271}
272
273
274////////////////////////////////////////////////////////////////////////////////
275/// Choose the minimizer algorithm.
276
278{
279 if (_fcnMode != FcnMode::classic && strcmp(type, "Minuit2") != 0) {
280 throw std::invalid_argument("In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!");
281 }
283}
284
285
286
287
288////////////////////////////////////////////////////////////////////////////////
289/// Return underlying ROOT fitter object
290
292{
293 return _theFitter ;
294}
295
296
297////////////////////////////////////////////////////////////////////////////////
298/// Return underlying ROOT fitter object
299
301{
302 return _theFitter ;
303}
304
305
306
307////////////////////////////////////////////////////////////////////////////////
308/// Parse traditional RooAbsPdf::fitTo driver options
309///
310/// m - Run Migrad only
311/// h - Run Hesse to estimate errors
312/// v - Verbose mode
313/// l - Log parameters after each Minuit steps to file
314/// t - Activate profile timer
315/// r - Save fit result
316/// 0 - Run Migrad with strategy 0
317
318RooFitResult* RooMinimizer::fit(const char* options)
319{
320 TString opts(options) ;
321 opts.ToLower() ;
322
323 // Initial configuration
324 if (opts.Contains("v")) setVerbose(1) ;
325 if (opts.Contains("t")) setProfile(1) ;
326 if (opts.Contains("l")) setLogFile(Form("%s.log",_fcn->getFunctionName().c_str())) ;
327 if (opts.Contains("c")) optimizeConst(1) ;
328
329 // Fitting steps
330 if (opts.Contains("0")) setStrategy(0) ;
331 migrad() ;
332 if (opts.Contains("0")) setStrategy(1) ;
333 if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
334 if (!opts.Contains("m")) minos() ;
335
336 return (opts.Contains("r")) ? save() : 0 ;
337}
338
339
341 bool ret;
342
343 switch (_fcnMode) {
344 case FcnMode::classic: {
345 ret = _theFitter->FitFCN(*dynamic_cast<RooMinimizerFcn *>(_fcn));
346 break;
347 }
348 case FcnMode::gradient: {
349 ret = _theFitter->FitFCN(*dynamic_cast<RooGradMinimizerFcn *>(_fcn));
350 break;
351 }
354 break;
355 }
356 default: {
357 throw std::logic_error("In RooMinimizer::fitFcn: _fcnMode has an unsupported value!");
358 }
359 }
360
361 return ret;
362}
363
364
365////////////////////////////////////////////////////////////////////////////////
366/// Minimise the function passed in the constructor.
367/// \param[in] type Type of fitter to use, e.g. "Minuit" "Minuit2".
368/// \attention This overrides the default fitter of this RooMinimizer.
369/// \param[in] alg Fit algorithm to use. (Optional)
370Int_t RooMinimizer::minimize(const char* type, const char* alg)
371{
374
377
378 profileStart() ;
381
382 bool ret = fitFcn();
383 _status = ((ret) ? _theFitter->Result().Status() : -1);
384
386 profileStop() ;
388
389 saveStatus("MINIMIZE",_status) ;
390
391 return _status ;
392}
393
394
395
396////////////////////////////////////////////////////////////////////////////////
397/// Execute MIGRAD. Changes in parameter values
398/// and calculated errors are automatically
399/// propagated back the RooRealVars representing
400/// the floating parameters in the MINUIT operation.
401
403{
406 profileStart() ;
409
410 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migrad");
411 bool ret = fitFcn();
412 _status = ((ret) ? _theFitter->Result().Status() : -1);
413
415 profileStop() ;
417
418 saveStatus("MIGRAD",_status) ;
419
420 return _status ;
421}
422
423
424
425////////////////////////////////////////////////////////////////////////////////
426/// Execute HESSE. Changes in parameter values
427/// and calculated errors are automatically
428/// propagated back the RooRealVars representing
429/// the floating parameters in the MINUIT operation.
430
432{
433 if (_theFitter->GetMinimizer()==0) {
434 coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!"
435 << endl ;
436 _status = -1;
437 }
438 else {
439
442 profileStart() ;
445
447 bool ret = _theFitter->CalculateHessErrors();
448 _status = ((ret) ? _theFitter->Result().Status() : -1);
449
451 profileStop() ;
453
454 saveStatus("HESSE",_status) ;
455
456 }
457
458 return _status ;
459
460}
461
462////////////////////////////////////////////////////////////////////////////////
463/// Execute MINOS. Changes in parameter values
464/// and calculated errors are automatically
465/// propagated back the RooRealVars representing
466/// the floating parameters in the MINUIT operation.
467
469{
470 if (_theFitter->GetMinimizer()==0) {
471 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
472 << endl ;
473 _status = -1;
474 }
475 else {
476
479 profileStart() ;
482
484 bool ret = _theFitter->CalculateMinosErrors();
485 _status = ((ret) ? _theFitter->Result().Status() : -1);
486
488 profileStop() ;
490
491 saveStatus("MINOS",_status) ;
492
493 }
494
495 return _status ;
496
497}
498
499
500////////////////////////////////////////////////////////////////////////////////
501/// Execute MINOS for given list of parameters. Changes in parameter values
502/// and calculated errors are automatically
503/// propagated back the RooRealVars representing
504/// the floating parameters in the MINUIT operation.
505
506Int_t RooMinimizer::minos(const RooArgSet& minosParamList)
507{
508 if (_theFitter->GetMinimizer()==0) {
509 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
510 << endl ;
511 _status = -1;
512 }
513 else if (minosParamList.getSize()>0) {
514
517 profileStart() ;
520
521 // get list of parameters for Minos
522 TIterator* aIter = minosParamList.createIterator() ;
523 RooAbsArg* arg ;
524 std::vector<unsigned int> paramInd;
525 while((arg=(RooAbsArg*)aIter->Next())) {
526 RooAbsArg* par = _fcn->GetFloatParamList()->find(arg->GetName());
527 if (par && !par->isConstant()) {
528 Int_t index = _fcn->GetFloatParamList()->index(par);
529 paramInd.push_back(index);
530 }
531 }
532 delete aIter ;
533
534 if (paramInd.size()) {
535 // set the parameter indeces
536 _theFitter->Config().SetMinosErrors(paramInd);
537
539 bool ret = _theFitter->CalculateMinosErrors();
540 _status = ((ret) ? _theFitter->Result().Status() : -1);
541 // to avoid that following minimization computes automatically the Minos errors
543
544 }
545
547 profileStop() ;
549
550 saveStatus("MINOS",_status) ;
551
552 }
553
554 return _status ;
555}
556
557
558
559////////////////////////////////////////////////////////////////////////////////
560/// Execute SEEK. Changes in parameter values
561/// and calculated errors are automatically
562/// propagated back the RooRealVars representing
563/// the floating parameters in the MINUIT operation.
564
566{
569 profileStart() ;
572
573 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"seek");
574 bool ret = fitFcn();
575 _status = ((ret) ? _theFitter->Result().Status() : -1);
576
578 profileStop() ;
580
581 saveStatus("SEEK",_status) ;
582
583 return _status ;
584}
585
586
587
588////////////////////////////////////////////////////////////////////////////////
589/// Execute SIMPLEX. Changes in parameter values
590/// and calculated errors are automatically
591/// propagated back the RooRealVars representing
592/// the floating parameters in the MINUIT operation.
593
595{
598 profileStart() ;
601
602 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"simplex");
603 bool ret = fitFcn();
604 _status = ((ret) ? _theFitter->Result().Status() : -1);
605
607 profileStop() ;
609
610 saveStatus("SEEK",_status) ;
611
612 return _status ;
613}
614
615
616
617////////////////////////////////////////////////////////////////////////////////
618/// Execute IMPROVE. Changes in parameter values
619/// and calculated errors are automatically
620/// propagated back the RooRealVars representing
621/// the floating parameters in the MINUIT operation.
622
624{
627 profileStart() ;
630
631 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migradimproved");
632 bool ret = fitFcn();
633 _status = ((ret) ? _theFitter->Result().Status() : -1);
634
636 profileStop() ;
638
639 saveStatus("IMPROVE",_status) ;
640
641 return _status ;
642}
643
644
645
646////////////////////////////////////////////////////////////////////////////////
647/// Change the MINUIT internal printing level
648
650{
651 Int_t ret = _printLevel ;
653 _printLevel = newLevel+1 ;
654 return ret ;
655}
656
657////////////////////////////////////////////////////////////////////////////////
658/// If flag is true, perform constant term optimization on
659/// function being minimized.
660
662{
663 _fcn->setOptimizeConst(flag);
664}
665
666
667
668////////////////////////////////////////////////////////////////////////////////
669/// Save and return a RooFitResult snapshot of current minimizer status.
670/// This snapshot contains the values of all constant parameters,
671/// the value of all floating parameters at RooMinimizer construction and
672/// after the last MINUIT operation, the MINUIT status, variance quality,
673/// EDM setting, number of calls with evaluation problems, the minimized
674/// function value and the full correlation matrix.
675
676RooFitResult* RooMinimizer::save(const char* userName, const char* userTitle)
677{
678 if (_theFitter->GetMinimizer()==0) {
679 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!"
680 << endl ;
681 return 0;
682 }
683
684 TString name,title ;
685 name = userName ? userName : Form("%s", _fcn->getFunctionName().c_str()) ;
686 title = userTitle ? userTitle : Form("%s", _fcn->getFunctionTitle().c_str()) ;
687 RooFitResult* fitRes = new RooFitResult(name,title) ;
688
689 // Move eventual fixed parameters in floatList to constList
690 Int_t i ;
691 RooArgList saveConstList(*(_fcn->GetConstParamList())) ;
692 RooArgList saveFloatInitList(*(_fcn->GetInitFloatParamList())) ;
693 RooArgList saveFloatFinalList(*(_fcn->GetFloatParamList())) ;
694 for (i=0 ; i<_fcn->GetFloatParamList()->getSize() ; i++) {
695 RooAbsArg* par = _fcn->GetFloatParamList()->at(i) ;
696 if (par->isConstant()) {
697 saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),kTRUE) ;
698 saveFloatFinalList.remove(*par) ;
699 saveConstList.add(*par) ;
700 }
701 }
702 saveConstList.sort() ;
703
704 fitRes->setConstParList(saveConstList) ;
705 fitRes->setInitParList(saveFloatInitList) ;
706
707 // The fitter often clones the function. We therefore have to ask it for its copy.
708 const auto fitFcn = dynamic_cast<const RooMinimizerFcn*>(_theFitter->GetFCN());
709 double removeOffset = 0.;
710 if (fitFcn) {
711 fitRes->setNumInvalidNLL(fitFcn->GetNumInvalidNLL());
712 removeOffset = - fitFcn->getOffset();
713 }
714
715 fitRes->setStatus(_status) ;
717 fitRes->setMinNLL(_theFitter->Result().MinFcnValue() + removeOffset);
718 fitRes->setEDM(_theFitter->Result().Edm()) ;
719 fitRes->setFinalParList(saveFloatFinalList) ;
720 if (!_extV) {
721 std::vector<double> globalCC;
722 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
723 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
724 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
725 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
726 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
727 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
728 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
729 }
730 }
731 fitRes->fillCorrMatrix(globalCC,corrs,covs) ;
732 } else {
733 fitRes->setCovarianceMatrix(*_extV) ;
734 }
735
737
738 return fitRes ;
739
740}
741
742////////////////////////////////////////////////////////////////////////////////
743/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
744/// \param[in] var1 The first parameter (x axis).
745/// \param[in] var2 The second parameter (y axis).
746/// \param[in] n1 First contour.
747/// \param[in] n2 Optional contour. 0 means don't draw.
748/// \param[in] n3 Optional contour. 0 means don't draw.
749/// \param[in] n4 Optional contour. 0 means don't draw.
750/// \param[in] n5 Optional contour. 0 means don't draw.
751/// \param[in] n6 Optional contour. 0 means don't draw.
752/// \param[in] npoints Number of points for evaluating the contour.
753///
754/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
755/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
756/// See ROOT::Math::Minimizer::ErrorDef().
757
759 Double_t n1, Double_t n2, Double_t n3,
760 Double_t n4, Double_t n5, Double_t n6, unsigned int npoints)
761{
762
763
764 RooArgList* params = _fcn->GetFloatParamList() ;
765 RooArgList* paramSave = (RooArgList*) params->snapshot() ;
766
767 // Verify that both variables are floating parameters of PDF
768 Int_t index1= _fcn->GetFloatParamList()->index(&var1);
769 if(index1 < 0) {
770 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
771 << ") ERROR: " << var1.GetName()
772 << " is not a floating parameter of "
773 << _fcn->getFunctionName() << endl ;
774 return 0;
775 }
776
777 Int_t index2= _fcn->GetFloatParamList()->index(&var2);
778 if(index2 < 0) {
779 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
780 << ") ERROR: " << var2.GetName()
781 << " is not a floating parameter of PDF "
782 << _fcn->getFunctionName() << endl ;
783 return 0;
784 }
785
786 // create and draw a frame
787 RooPlot* frame = new RooPlot(var1,var2) ;
788
789 // draw a point at the current parameter values
790 TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
791 frame->addObject(point) ;
792
793 // check first if a inimizer is available. If not means
794 // the minimization is not done , so do it
795 if (_theFitter->GetMinimizer()==0) {
796 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
797 << endl ;
798 return frame;
799 }
800
801
802 // remember our original value of ERRDEF
804
805 Double_t n[6] ;
806 n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
807
808 for (Int_t ic = 0 ; ic<6 ; ic++) {
809 if(n[ic] > 0) {
810
811 // set the value corresponding to an n1-sigma contour
812 _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
813
814 // calculate and draw the contour
815 Double_t *xcoor = new Double_t[npoints+1];
816 Double_t *ycoor = new Double_t[npoints+1];
817 bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
818
819 if (!ret) {
820 coutE(Minimization) << "RooMinimizer::contour("
821 << GetName()
822 << ") ERROR: MINUIT did not return a contour graph for n="
823 << n[ic] << endl ;
824 } else {
825 xcoor[npoints] = xcoor[0];
826 ycoor[npoints] = ycoor[0];
827 TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
828
829 graph->SetName(Form("contour_%s_n%f",_fcn->getFunctionName().c_str(),n[ic])) ;
830 graph->SetLineStyle(ic+1) ;
831 graph->SetLineWidth(2) ;
832 graph->SetLineColor(kBlue) ;
833 frame->addObject(graph,"L") ;
834 }
835
836 delete [] xcoor;
837 delete [] ycoor;
838 }
839 }
840
841
842 // restore the original ERRDEF
844
845 // restore parameter values
846 params->assign(*paramSave) ;
847 delete paramSave ;
848
849 return frame ;
850
851}
852
853
854////////////////////////////////////////////////////////////////////////////////
855/// Start profiling timer
856
858{
859 if (_profile) {
860 _timer.Start() ;
863 }
864}
865
866
867////////////////////////////////////////////////////////////////////////////////
868/// Stop profiling timer and report results of last session
869
871{
872 if (_profile) {
873 _timer.Stop() ;
874 _cumulTimer.Stop() ;
875 coutI(Minimization) << "Command timer: " ; _timer.Print() ;
876 coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
877 }
878}
879
880
882{
883 return fitter()->GetFCN();
884}
885
886
888{
889 if (getFitterMultiGenFcn()) {
890 return getFitterMultiGenFcn();
891 } else {
892 switch (_fcnMode) {
893 case FcnMode::classic: {
894 return static_cast<ROOT::Math::IMultiGenFunction *>(dynamic_cast<RooMinimizerFcn *>(_fcn));
895 }
896 case FcnMode::gradient: {
897 return static_cast<ROOT::Math::IMultiGenFunction *>(dynamic_cast<RooGradMinimizerFcn *>(_fcn));
898 }
900 return static_cast<ROOT::Math::IMultiGenFunction *>(dynamic_cast<RooFit::TestStatistics::MinuitFcnGrad *>(_fcn));
901 }
902 default: {
903 throw std::logic_error("In RooMinimizer::getMultiGenFcn: _fcnMode has an unsupported value!");
904 }
905 }
906 }
907}
908
909
911{
912 if (getFitterMultiGenFcn()) {
913 switch (_fcnMode) {
914 case FcnMode::classic: {
915 return static_cast<RooAbsMinimizerFcn *>(dynamic_cast<RooMinimizerFcn *>(getFitterMultiGenFcn()));
916 }
917 case FcnMode::gradient: {
918 return static_cast<RooAbsMinimizerFcn *>(dynamic_cast<RooGradMinimizerFcn *>(getFitterMultiGenFcn()));
919 }
921 return static_cast<RooAbsMinimizerFcn *>(dynamic_cast<RooFit::TestStatistics::MinuitFcnGrad *>(getFitterMultiGenFcn()));
922 }
923 default: {
924 throw std::logic_error("In RooMinimizer::fitterFcn: _fcnMode has an unsupported value!");
925 }
926 }
927 } else {
928 return _fcn;
929 }
930}
931
933{
934 // to avoid code duplication, we just reuse the const function and cast constness away
935 return const_cast<RooAbsMinimizerFcn *>( static_cast<const RooMinimizer&>(*this).fitterFcn() );
936}
937
938
939////////////////////////////////////////////////////////////////////////////////
940/// Apply results of given external covariance matrix. i.e. propagate its errors
941/// to all RRV parameter representations and give this matrix instead of the
942/// HESSE matrix at the next save() call
943
945{
946 _extV = (TMatrixDSym*) V.Clone() ;
948
949}
950
951
952
954{
955 // Import the results of the last fit performed, interpreting
956 // the fit parameters as the given varList of parameters.
957
958 if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
959 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
960 << endl ;
961 return 0;
962 }
963
964 // Verify length of supplied varList
965 if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
966 oocoutE((TObject*)0,InputArguments)
967 << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
968 << " or match the number of variables of the last fit ("
969 << _theFitter->Result().NTotalParameters() << ")" << endl ;
970 return 0 ;
971 }
972
973
974 // Verify that all members of varList are of type RooRealVar
975 TIter iter = varList.createIterator() ;
976 RooAbsArg* arg ;
977 while((arg=(RooAbsArg*)iter.Next())) {
978 if (!dynamic_cast<RooRealVar*>(arg)) {
979 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
980 << arg->GetName() << "' is not of type RooRealVar" << endl ;
981 return 0 ;
982 }
983 }
984
985 RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
986
987 // Extract names of fit parameters
988 // and construct corresponding RooRealVars
989 RooArgList constPars("constPars") ;
990 RooArgList floatPars("floatPars") ;
991
992 UInt_t i ;
993 for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
994
997
1000 Double_t xerr = _theFitter->Result().Error(i);
1001 Double_t xval = _theFitter->Result().Value(i);
1002
1003 RooRealVar* var ;
1004 if (varList.getSize()==0) {
1005
1006 if ((xlo<xhi) && !isConst) {
1007 var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
1008 } else {
1009 var = new RooRealVar(varName,varName,xval) ;
1010 }
1011 var->setConstant(isConst) ;
1012 } else {
1013
1014 var = (RooRealVar*) varList.at(i)->Clone() ;
1015 var->setConstant(isConst) ;
1016 var->setVal(xval) ;
1017 if (xlo<xhi) {
1018 var->setRange(xlo,xhi) ;
1019 }
1020
1021 if (varName.CompareTo(var->GetName())) {
1022 oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
1023 << "' stored in variable '" << var->GetName() << "'" << endl ;
1024 }
1025
1026 }
1027
1028 if (isConst) {
1029 constPars.addOwned(*var) ;
1030 } else {
1031 var->setError(xerr) ;
1032 floatPars.addOwned(*var) ;
1033 }
1034 }
1035
1036 res->setConstParList(constPars) ;
1037 res->setInitParList(floatPars) ;
1038 res->setFinalParList(floatPars) ;
1040 res->setEDM(_theFitter->Result().Edm()) ;
1042 res->setStatus(_theFitter->Result().Status()) ;
1043 std::vector<double> globalCC;
1044 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
1045 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
1046 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
1047 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
1048 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
1049 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
1050 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
1051 }
1052 }
1053 res->fillCorrMatrix(globalCC,corrs,covs) ;
1054
1055 return res;
1056
1057}
1058
1060{
1061 return _printLevel;
1062}
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#define coutI(a)
#define coutW(a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
const Bool_t kFALSE
Definition RtypesCore.h:101
const Bool_t kTRUE
Definition RtypesCore.h:100
#define ClassImp(name)
Definition Rtypes.h:364
@ kBlue
Definition Rtypes.h:66
char name[80]
Definition TGX11.cxx:110
int type
Definition TGX11.cxx:121
char * Form(const char *fmt,...)
TString operator+(const TString &s1, const TString &s2)
Use the special concatenation constructor.
Definition TString.cxx:1499
void SetMinosErrors(bool on=true)
set Minos erros computation to be performed after fitting
Definition FitConfig.h:231
void SetMinimizer(const char *type, const char *algo=0)
set minimizer type
Definition FitConfig.h:181
const std::vector< ROOT::Fit::ParameterSettings > & ParamsSettings() const
get the vector of parameter settings (const method)
Definition FitConfig.h:86
const ParameterSettings & ParSettings(unsigned int i) const
get the parameter settings for the i-th parameter (const method)
Definition FitConfig.h:76
ROOT::Math::MinimizerOptions & MinimizerOptions()
access to the minimizer control parameter (non const method)
Definition FitConfig.h:167
bool IsParameterFixed(unsigned int ipar) const
query if a parameter is fixed
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
ROOT::Math::IMultiGenFunction * GetFCN() const
return pointer to last used objective function (is NULL in case fit is not yet done) This pointer wil...
Definition Fitter.h:445
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
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:62
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:463
virtual int CovMatrixStatus() const
return status of covariance matrix using Minuit convention {0 not calculated 1 approximated 2 made po...
Definition Minimizer.h:315
double ErrorDef() const
return the statistical scale used for calculate the error is typically 1 for Chi2 and 0....
Definition Minimizer.h:433
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:375
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition RooAbsArg.h:69
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition RooAbsArg.h:81
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:377
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.
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.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
virtual Bool_t addOwned(RooAbsArg &var, Bool_t silent=kFALSE)
Add an argument and transfer the ownership to the collection.
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.
RooArgList * GetInitFloatParamList()
void setOptimizeConst(Int_t flag)
virtual Bool_t Synchronize(std::vector< ROOT::Fit::ParameterSettings > &parameters, Bool_t optConst, Bool_t verbose)
Like synchronizeParameterSettings, Synchronize informs Minuit through its parameter_settings vector o...
RooArgList * GetConstParamList()
void BackProp(const ROOT::Fit::FitResult &results)
Put Minuit results back into RooFit objects.
virtual std::string getFunctionName() const =0
RooMinimizer sometimes needs the name of the minimized function. Implement this in the derived class.
virtual std::string getFunctionTitle() const =0
RooMinimizer sometimes needs the title of the minimized function. Implement this in the derived class...
void ApplyCovarianceMatrix(TMatrixDSym &V)
Set different external covariance matrix.
RooArgList * GetFloatParamList()
Logistics.
unsigned int getNDim() const
virtual void setOffsetting(Bool_t flag)=0
Enable or disable offsetting on the function to be minimized, which enhances numerical precision.
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:64
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:94
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:22
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:35
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
void fillCorrMatrix()
Internal utility method to extract the correlation matrix and the global correlation coefficients fro...
void setCovQual(Int_t val)
void setMinNLL(Double_t val)
void setNumInvalidNLL(Int_t val)
void setStatus(Int_t val)
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)
void setStatusHistory(std::vector< std::pair< std::string, int > > &hist)
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.
Minuit-RooMinimizer interface which synchronizes parameter data and coordinates evaluation of likelih...
RooMinimizerFcn is an interface to the ROOT::Math::IBaseFunctionMultiDim, a function that ROOT's mini...
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
std::vector< std::pair< std::string, int > > _statusHistory
void initMinimizerFirstPart()
Initialize the part of the minimizer that is independent of the function to be minimized.
RooMinimizer(RooAbsReal &function, FcnMode fcnMode=FcnMode::classic)
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 snapshot of current minimizer status.
void setMinimizerType(const char *type)
Choose the minimizer algorithm.
void saveStatus(const char *label, Int_t status)
Int_t improve()
Execute IMPROVE.
FcnMode _fcnMode
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 initMinimizerFcnDependentPart(double defaultErrorLevel)
Initialize the part of the minimizer that is dependent on the function to be minimized.
RooFitResult * fit(const char *options) R__DEPRECATED(6
Parse traditional RooAbsPdf::fitTo driver options.
void profileStop()
Stop profiling timer and report results of last session.
ROOT::Math::IMultiGenFunction * getFitterMultiGenFcn() const
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
const RooAbsMinimizerFcn * fitterFcn() const
void setOffsetting(Bool_t flag)
Enable internal likelihood offsetting for enhanced numeric precision.
TMatrixDSym * _extV
Int_t seek()
Execute SEEK.
Bool_t setLogFile(const char *logf=0)
void setProfile(Bool_t flag=kTRUE)
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
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
void setMaxFunctionCalls(Int_t n)
Change maximum number of likelihood function calss from MINUIT (RooMinimizer default 500 * #parameter...
Int_t minos()
Execute MINOS.
void applyCovarianceMatrix(TMatrixDSym &V)
Apply results of given external covariance matrix.
bool fitFcn() const
~RooMinimizer() override
Destructor.
void optimizeConst(Int_t flag)
If flag is true, perform constant term optimization on function being minimized.
ROOT::Math::IMultiGenFunction * getMultiGenFcn() const
Int_t simplex()
Execute SIMPLEX.
Bool_t _profileStart
Int_t getPrintLevel() const
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
void setStrategy(Int_t strat)
Change MINUIT strategy to istrat.
std::string _minimizerType
TStopwatch _cumulTimer
RooAbsMinimizerFcn * _fcn
void setVerbose(Bool_t flag=kTRUE)
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:392
RooRealVar represents a variable that can be changed from the outside.
Definition RooRealVar.h:39
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.
virtual void setVal(Double_t value)
Set value of variable to 'value'.
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
A TGraph is an object made of two arrays X and Y with npoints each.
Definition TGraph.h:41
TObject * Next()
Iterator abstract base class.
Definition TIterator.h:30
virtual TObject * Next()=0
Manages Markers.
Definition TMarker.h:22
virtual const char * GetName() const
Returns name of object.
Definition TNamed.h:47
Mother of all ROOT objects.
Definition TObject.h:41
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:429
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition TObject.cxx:216
void Start(Bool_t reset=kTRUE)
Start the stopwatch.
void Stop()
Stop the stopwatch.
void Print(Option_t *option="") const
Print the real and cpu time passed between the start and stop events.
Basic string class.
Definition TString.h:136
void ToLower()
Change string to lower-case.
Definition TString.cxx:1150
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition TString.cxx:442
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition TString.h:624
const Int_t n
Definition legend1.C:16
Definition graph.py:1