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 * 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"
56
57#include "TClass.h"
58#include "Math/Minimizer.h"
59#include "TH2.h"
60#include "TMarker.h"
61#include "TGraph.h"
62#include "Fit/FitConfig.h"
63#include "TStopwatch.h"
64#include "TMatrixDSym.h"
65
66#include <iostream>
67#include <fstream>
68
69#if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
70char* operator+( streampos&, char* );
71#endif
72
73using namespace std;
74
76;
77
79
80
81
82////////////////////////////////////////////////////////////////////////////////
83/// Cleanup method called by atexit handler installed by RooSentinel
84/// to delete all global heap objects when the program is terminated
85
87{
88 if (_theFitter) {
89 delete _theFitter ;
90 _theFitter =0 ;
91 }
92}
93
94
95
96////////////////////////////////////////////////////////////////////////////////
97/// Construct MINUIT interface to given function. Function can be anything,
98/// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
99/// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
100/// of a RooNLLVar plus a penalty or constraint term. This class propagates
101/// all RooFit information (floating parameters, their values and errors)
102/// to MINUIT before each MINUIT call and propagates all MINUIT information
103/// back to the RooFit object at the end of each call (updated parameter
104/// values, their (asymmetric errors) etc. The default MINUIT error level
105/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
106/// value of the input function.
107
109{
111
112 if (_theFitter) {
113 delete _theFitter;
114 }
117 setEps(1.0); // default tolerance
118
119 switch (_fcnMode) {
120 case FcnMode::classic: {
121 _fcn = new RooMinimizerFcn(&function, this, _verbose);
122 break;
123 }
124 case FcnMode::gradient: {
126 setMinimizerType("Minuit2");
127 break;
128 }
129 default: {
130 throw std::logic_error("In RooMinimizer constructor: fcnMode has an unsupported value!");
131 }
132 }
133
134 // default max number of calls
137
138 // Shut up for now
139 setPrintLevel(-1);
140
141 // Use +0.5 for 1-sigma errors
142 setErrorLevel(function.defaultErrorLevel());
143
144 // Declare our parameters to MINUIT
146
147 // Now set default verbosity
148 if (RooMsgService::instance().silentMode()) {
149 setPrintLevel(-1);
150 } else {
151 setPrintLevel(1);
152 }
153}
154
155// static function
156std::unique_ptr<RooMinimizer> RooMinimizer::create(RooAbsReal &function, FcnMode fcnMode) {
157 return std::make_unique<RooMinimizer>(function, fcnMode);
158}
159
160
161////////////////////////////////////////////////////////////////////////////////
162/// Destructor
163
165{
166 if (_extV) {
167 delete _extV ;
168 }
169
170 if (_fcn) {
171 delete _fcn;
172 }
173
174}
175
176
177
178////////////////////////////////////////////////////////////////////////////////
179/// Change MINUIT strategy to istrat. Accepted codes
180/// are 0,1,2 and represent MINUIT strategies for dealing
181/// most efficiently with fast FCNs (0), expensive FCNs (2)
182/// and 'intermediate' FCNs (1)
183
185{
187
188}
189
190
191
192////////////////////////////////////////////////////////////////////////////////
193/// Change maximum number of MINUIT iterations
194/// (RooMinimizer default 500 * #parameters)
195
197{
199}
200
201
202
203
204////////////////////////////////////////////////////////////////////////////////
205/// Change maximum number of likelihood function calss from MINUIT
206/// (RooMinimizer default 500 * #parameters)
207
209{
211}
212
213
214
215
216////////////////////////////////////////////////////////////////////////////////
217/// Set the level for MINUIT error analysis to the given
218/// value. This function overrides the default value
219/// that is taken in the RooMinimizer constructor from
220/// the defaultErrorLevel() method of the input function
221
223{
225
226}
227
228
229
230////////////////////////////////////////////////////////////////////////////////
231/// Change MINUIT epsilon
232
234{
236
237}
238
239
240////////////////////////////////////////////////////////////////////////////////
241/// Enable internal likelihood offsetting for enhanced numeric precision
242
244{
245 _fcn->setOffsetting(flag);
246}
247
248
249////////////////////////////////////////////////////////////////////////////////
250/// Choose the minimizer algorithm.
251
253{
254 if (_fcnMode != FcnMode::classic && strcmp(type, "Minuit2") != 0) {
255 throw std::invalid_argument("In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!");
256 }
258}
259
260
261
262
263////////////////////////////////////////////////////////////////////////////////
264/// Return underlying ROOT fitter object
265
267{
268 return _theFitter ;
269}
270
271
272////////////////////////////////////////////////////////////////////////////////
273/// Return underlying ROOT fitter object
274
276{
277 return _theFitter ;
278}
279
280
281
282////////////////////////////////////////////////////////////////////////////////
283/// Parse traditional RooAbsPdf::fitTo driver options
284///
285/// m - Run Migrad only
286/// h - Run Hesse to estimate errors
287/// v - Verbose mode
288/// l - Log parameters after each Minuit steps to file
289/// t - Activate profile timer
290/// r - Save fit result
291/// 0 - Run Migrad with strategy 0
292
293RooFitResult* RooMinimizer::fit(const char* options)
294{
295 TString opts(options) ;
296 opts.ToLower() ;
297
298 // Initial configuration
299 if (opts.Contains("v")) setVerbose(1) ;
300 if (opts.Contains("t")) setProfile(1) ;
301 if (opts.Contains("l")) setLogFile(Form("%s.log",_fcn->getFunctionName().c_str())) ;
302 if (opts.Contains("c")) optimizeConst(1) ;
303
304 // Fitting steps
305 if (opts.Contains("0")) setStrategy(0) ;
306 migrad() ;
307 if (opts.Contains("0")) setStrategy(1) ;
308 if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
309 if (!opts.Contains("m")) minos() ;
310
311 return (opts.Contains("r")) ? save() : 0 ;
312}
313
314
316 bool ret;
317
318 switch (_fcnMode) {
319 case FcnMode::classic: {
320 ret = _theFitter->FitFCN(*dynamic_cast<RooMinimizerFcn *>(_fcn));
321 break;
322 }
323 case FcnMode::gradient: {
324 ret = _theFitter->FitFCN(*dynamic_cast<RooGradMinimizerFcn *>(_fcn));
325 break;
326 }
329 break;
330 }
331 default: {
332 throw std::logic_error("In RooMinimizer::fitFcn: _fcnMode has an unsupported value!");
333 }
334 }
335
336 return ret;
337}
338
339
340////////////////////////////////////////////////////////////////////////////////
341/// Minimise the function passed in the constructor.
342/// \param[in] type Type of fitter to use, e.g. "Minuit" "Minuit2".
343/// \attention This overrides the default fitter of this RooMinimizer.
344/// \param[in] alg Fit algorithm to use. (Optional)
345Int_t RooMinimizer::minimize(const char* type, const char* alg)
346{
349
352
353 profileStart() ;
356
357 bool ret = fitFcn();
358 _status = ((ret) ? _theFitter->Result().Status() : -1);
359
361 profileStop() ;
363
364 saveStatus("MINIMIZE",_status) ;
365
366 return _status ;
367}
368
369
370
371////////////////////////////////////////////////////////////////////////////////
372/// Execute MIGRAD. Changes in parameter values
373/// and calculated errors are automatically
374/// propagated back the RooRealVars representing
375/// the floating parameters in the MINUIT operation.
376
378{
381 profileStart() ;
384
385 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migrad");
386 bool ret = fitFcn();
387 _status = ((ret) ? _theFitter->Result().Status() : -1);
388
390 profileStop() ;
392
393 saveStatus("MIGRAD",_status) ;
394
395 return _status ;
396}
397
398
399
400////////////////////////////////////////////////////////////////////////////////
401/// Execute HESSE. Changes in parameter values
402/// and calculated errors are automatically
403/// propagated back the RooRealVars representing
404/// the floating parameters in the MINUIT operation.
405
407{
408 if (_theFitter->GetMinimizer()==0) {
409 coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!"
410 << endl ;
411 _status = -1;
412 }
413 else {
414
417 profileStart() ;
420
422 bool ret = _theFitter->CalculateHessErrors();
423 _status = ((ret) ? _theFitter->Result().Status() : -1);
424
426 profileStop() ;
428
429 saveStatus("HESSE",_status) ;
430
431 }
432
433 return _status ;
434
435}
436
437////////////////////////////////////////////////////////////////////////////////
438/// Execute MINOS. Changes in parameter values
439/// and calculated errors are automatically
440/// propagated back the RooRealVars representing
441/// the floating parameters in the MINUIT operation.
442
444{
445 if (_theFitter->GetMinimizer()==0) {
446 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
447 << endl ;
448 _status = -1;
449 }
450 else {
451
454 profileStart() ;
457
459 bool ret = _theFitter->CalculateMinosErrors();
460 _status = ((ret) ? _theFitter->Result().Status() : -1);
461
463 profileStop() ;
465
466 saveStatus("MINOS",_status) ;
467
468 }
469
470 return _status ;
471
472}
473
474
475////////////////////////////////////////////////////////////////////////////////
476/// Execute MINOS for given list of parameters. Changes in parameter values
477/// and calculated errors are automatically
478/// propagated back the RooRealVars representing
479/// the floating parameters in the MINUIT operation.
480
481Int_t RooMinimizer::minos(const RooArgSet& minosParamList)
482{
483 if (_theFitter->GetMinimizer()==0) {
484 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
485 << endl ;
486 _status = -1;
487 }
488 else if (minosParamList.getSize()>0) {
489
492 profileStart() ;
495
496 // get list of parameters for Minos
497 TIterator* aIter = minosParamList.createIterator() ;
498 RooAbsArg* arg ;
499 std::vector<unsigned int> paramInd;
500 while((arg=(RooAbsArg*)aIter->Next())) {
501 RooAbsArg* par = _fcn->GetFloatParamList()->find(arg->GetName());
502 if (par && !par->isConstant()) {
503 Int_t index = _fcn->GetFloatParamList()->index(par);
504 paramInd.push_back(index);
505 }
506 }
507 delete aIter ;
508
509 if (paramInd.size()) {
510 // set the parameter indeces
511 _theFitter->Config().SetMinosErrors(paramInd);
512
514 bool ret = _theFitter->CalculateMinosErrors();
515 _status = ((ret) ? _theFitter->Result().Status() : -1);
516 // to avoid that following minimization computes automatically the Minos errors
518
519 }
520
522 profileStop() ;
524
525 saveStatus("MINOS",_status) ;
526
527 }
528
529 return _status ;
530}
531
532
533
534////////////////////////////////////////////////////////////////////////////////
535/// Execute SEEK. Changes in parameter values
536/// and calculated errors are automatically
537/// propagated back the RooRealVars representing
538/// the floating parameters in the MINUIT operation.
539
541{
544 profileStart() ;
547
548 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"seek");
549 bool ret = fitFcn();
550 _status = ((ret) ? _theFitter->Result().Status() : -1);
551
553 profileStop() ;
555
556 saveStatus("SEEK",_status) ;
557
558 return _status ;
559}
560
561
562
563////////////////////////////////////////////////////////////////////////////////
564/// Execute SIMPLEX. Changes in parameter values
565/// and calculated errors are automatically
566/// propagated back the RooRealVars representing
567/// the floating parameters in the MINUIT operation.
568
570{
573 profileStart() ;
576
577 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"simplex");
578 bool ret = fitFcn();
579 _status = ((ret) ? _theFitter->Result().Status() : -1);
580
582 profileStop() ;
584
585 saveStatus("SEEK",_status) ;
586
587 return _status ;
588}
589
590
591
592////////////////////////////////////////////////////////////////////////////////
593/// Execute IMPROVE. Changes in parameter values
594/// and calculated errors are automatically
595/// propagated back the RooRealVars representing
596/// the floating parameters in the MINUIT operation.
597
599{
602 profileStart() ;
605
606 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migradimproved");
607 bool ret = fitFcn();
608 _status = ((ret) ? _theFitter->Result().Status() : -1);
609
611 profileStop() ;
613
614 saveStatus("IMPROVE",_status) ;
615
616 return _status ;
617}
618
619
620
621////////////////////////////////////////////////////////////////////////////////
622/// Change the MINUIT internal printing level
623
625{
626 Int_t ret = _printLevel ;
628 _printLevel = newLevel+1 ;
629 return ret ;
630}
631
632////////////////////////////////////////////////////////////////////////////////
633/// If flag is true, perform constant term optimization on
634/// function being minimized.
635
637{
638 _fcn->setOptimizeConst(flag);
639}
640
641
642
643////////////////////////////////////////////////////////////////////////////////
644/// Save and return a RooFitResult snapshot of current minimizer status.
645/// This snapshot contains the values of all constant parameters,
646/// the value of all floating parameters at RooMinimizer construction and
647/// after the last MINUIT operation, the MINUIT status, variance quality,
648/// EDM setting, number of calls with evaluation problems, the minimized
649/// function value and the full correlation matrix.
650
651RooFitResult* RooMinimizer::save(const char* userName, const char* userTitle)
652{
653 if (_theFitter->GetMinimizer()==0) {
654 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!"
655 << endl ;
656 return 0;
657 }
658
659 TString name,title ;
660 name = userName ? userName : Form("%s", _fcn->getFunctionName().c_str()) ;
661 title = userTitle ? userTitle : Form("%s", _fcn->getFunctionTitle().c_str()) ;
662 RooFitResult* fitRes = new RooFitResult(name,title) ;
663
664 // Move eventual fixed parameters in floatList to constList
665 Int_t i ;
666 RooArgList saveConstList(*(_fcn->GetConstParamList())) ;
667 RooArgList saveFloatInitList(*(_fcn->GetInitFloatParamList())) ;
668 RooArgList saveFloatFinalList(*(_fcn->GetFloatParamList())) ;
669 for (i=0 ; i<_fcn->GetFloatParamList()->getSize() ; i++) {
670 RooAbsArg* par = _fcn->GetFloatParamList()->at(i) ;
671 if (par->isConstant()) {
672 saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),kTRUE) ;
673 saveFloatFinalList.remove(*par) ;
674 saveConstList.add(*par) ;
675 }
676 }
677 saveConstList.sort() ;
678
679 fitRes->setConstParList(saveConstList) ;
680 fitRes->setInitParList(saveFloatInitList) ;
681
682 // The fitter often clones the function. We therefore have to ask it for its copy.
683 const auto fitFcn = dynamic_cast<const RooMinimizerFcn*>(_theFitter->GetFCN());
684 double removeOffset = 0.;
685 if (fitFcn) {
686 fitRes->setNumInvalidNLL(fitFcn->GetNumInvalidNLL());
687 removeOffset = - fitFcn->getOffset();
688 }
689
690 fitRes->setStatus(_status) ;
692 fitRes->setMinNLL(_theFitter->Result().MinFcnValue() + removeOffset);
693 fitRes->setEDM(_theFitter->Result().Edm()) ;
694 fitRes->setFinalParList(saveFloatFinalList) ;
695 if (!_extV) {
696 std::vector<double> globalCC;
697 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
698 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
699 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
700 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
701 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
702 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
703 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
704 }
705 }
706 fitRes->fillCorrMatrix(globalCC,corrs,covs) ;
707 } else {
708 fitRes->setCovarianceMatrix(*_extV) ;
709 }
710
712
713 return fitRes ;
714
715}
716
717////////////////////////////////////////////////////////////////////////////////
718/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
719/// \param[in] var1 The first parameter (x axis).
720/// \param[in] var2 The second parameter (y axis).
721/// \param[in] n1 First contour.
722/// \param[in] n2 Optional contour. 0 means don't draw.
723/// \param[in] n3 Optional contour. 0 means don't draw.
724/// \param[in] n4 Optional contour. 0 means don't draw.
725/// \param[in] n5 Optional contour. 0 means don't draw.
726/// \param[in] n6 Optional contour. 0 means don't draw.
727/// \param[in] npoints Number of points for evaluating the contour.
728///
729/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
730/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
731/// See ROOT::Math::Minimizer::ErrorDef().
732
734 Double_t n1, Double_t n2, Double_t n3,
735 Double_t n4, Double_t n5, Double_t n6, unsigned int npoints)
736{
737
738
739 RooArgList* params = _fcn->GetFloatParamList() ;
740 RooArgList* paramSave = (RooArgList*) params->snapshot() ;
741
742 // Verify that both variables are floating parameters of PDF
743 Int_t index1= _fcn->GetFloatParamList()->index(&var1);
744 if(index1 < 0) {
745 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
746 << ") ERROR: " << var1.GetName()
747 << " is not a floating parameter of "
748 << _fcn->getFunctionName() << endl ;
749 return 0;
750 }
751
752 Int_t index2= _fcn->GetFloatParamList()->index(&var2);
753 if(index2 < 0) {
754 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
755 << ") ERROR: " << var2.GetName()
756 << " is not a floating parameter of PDF "
757 << _fcn->getFunctionName() << endl ;
758 return 0;
759 }
760
761 // create and draw a frame
762 RooPlot* frame = new RooPlot(var1,var2) ;
763
764 // draw a point at the current parameter values
765 TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
766 frame->addObject(point) ;
767
768 // check first if a inimizer is available. If not means
769 // the minimization is not done , so do it
770 if (_theFitter->GetMinimizer()==0) {
771 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
772 << endl ;
773 return frame;
774 }
775
776
777 // remember our original value of ERRDEF
779
780 Double_t n[6] ;
781 n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
782
783 for (Int_t ic = 0 ; ic<6 ; ic++) {
784 if(n[ic] > 0) {
785
786 // set the value corresponding to an n1-sigma contour
787 _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
788
789 // calculate and draw the contour
790 Double_t *xcoor = new Double_t[npoints+1];
791 Double_t *ycoor = new Double_t[npoints+1];
792 bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
793
794 if (!ret) {
795 coutE(Minimization) << "RooMinimizer::contour("
796 << GetName()
797 << ") ERROR: MINUIT did not return a contour graph for n="
798 << n[ic] << endl ;
799 } else {
800 xcoor[npoints] = xcoor[0];
801 ycoor[npoints] = ycoor[0];
802 TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
803
804 graph->SetName(Form("contour_%s_n%f",_fcn->getFunctionName().c_str(),n[ic])) ;
805 graph->SetLineStyle(ic+1) ;
806 graph->SetLineWidth(2) ;
807 graph->SetLineColor(kBlue) ;
808 frame->addObject(graph,"L") ;
809 }
810
811 delete [] xcoor;
812 delete [] ycoor;
813 }
814 }
815
816
817 // restore the original ERRDEF
819
820 // restore parameter values
821 params->assign(*paramSave) ;
822 delete paramSave ;
823
824 return frame ;
825
826}
827
828
829////////////////////////////////////////////////////////////////////////////////
830/// Start profiling timer
831
833{
834 if (_profile) {
835 _timer.Start() ;
838 }
839}
840
841
842////////////////////////////////////////////////////////////////////////////////
843/// Stop profiling timer and report results of last session
844
846{
847 if (_profile) {
848 _timer.Stop() ;
849 _cumulTimer.Stop() ;
850 coutI(Minimization) << "Command timer: " ; _timer.Print() ;
851 coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
852 }
853}
854
855
857{
858 return fitter()->GetFCN();
859}
860
861
863{
864 if (getFitterMultiGenFcn()) {
865 return getFitterMultiGenFcn();
866 } else {
867 switch (_fcnMode) {
868 case FcnMode::classic: {
869 return static_cast<ROOT::Math::IMultiGenFunction *>(dynamic_cast<RooMinimizerFcn *>(_fcn));
870 }
871 case FcnMode::gradient: {
872 return static_cast<ROOT::Math::IMultiGenFunction *>(dynamic_cast<RooGradMinimizerFcn *>(_fcn));
873 }
875 return static_cast<ROOT::Math::IMultiGenFunction *>(dynamic_cast<RooFit::TestStatistics::MinuitFcnGrad *>(_fcn));
876 }
877 default: {
878 throw std::logic_error("In RooMinimizer::getMultiGenFcn: _fcnMode has an unsupported value!");
879 }
880 }
881 }
882}
883
884
886{
887 if (getFitterMultiGenFcn()) {
888 switch (_fcnMode) {
889 case FcnMode::classic: {
890 return static_cast<RooAbsMinimizerFcn *>(dynamic_cast<RooMinimizerFcn *>(getFitterMultiGenFcn()));
891 }
892 case FcnMode::gradient: {
893 return static_cast<RooAbsMinimizerFcn *>(dynamic_cast<RooGradMinimizerFcn *>(getFitterMultiGenFcn()));
894 }
896 return static_cast<RooAbsMinimizerFcn *>(dynamic_cast<RooFit::TestStatistics::MinuitFcnGrad *>(getFitterMultiGenFcn()));
897 }
898 default: {
899 throw std::logic_error("In RooMinimizer::fitterFcn: _fcnMode has an unsupported value!");
900 }
901 }
902 } else {
903 return _fcn;
904 }
905}
906
908{
909 // to avoid code duplication, we just reuse the const function and cast constness away
910 return const_cast<RooAbsMinimizerFcn *>( static_cast<const RooMinimizer&>(*this).fitterFcn() );
911}
912
913
914////////////////////////////////////////////////////////////////////////////////
915/// Apply results of given external covariance matrix. i.e. propagate its errors
916/// to all RRV parameter representations and give this matrix instead of the
917/// HESSE matrix at the next save() call
918
920{
921 _extV = (TMatrixDSym*) V.Clone() ;
923
924}
925
926
927
929{
930 // Import the results of the last fit performed, interpreting
931 // the fit parameters as the given varList of parameters.
932
933 if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
934 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
935 << endl ;
936 return 0;
937 }
938
939 // Verify length of supplied varList
940 if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
942 << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
943 << " or match the number of variables of the last fit ("
944 << _theFitter->Result().NTotalParameters() << ")" << endl ;
945 return 0 ;
946 }
947
948
949 // Verify that all members of varList are of type RooRealVar
950 TIter iter = varList.createIterator() ;
951 RooAbsArg* arg ;
952 while((arg=(RooAbsArg*)iter.Next())) {
953 if (!dynamic_cast<RooRealVar*>(arg)) {
954 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
955 << arg->GetName() << "' is not of type RooRealVar" << endl ;
956 return 0 ;
957 }
958 }
959
960 RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
961
962 // Extract names of fit parameters
963 // and construct corresponding RooRealVars
964 RooArgList constPars("constPars") ;
965 RooArgList floatPars("floatPars") ;
966
967 UInt_t i ;
968 for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
969
972
975 Double_t xerr = _theFitter->Result().Error(i);
976 Double_t xval = _theFitter->Result().Value(i);
977
978 RooRealVar* var ;
979 if (varList.getSize()==0) {
980
981 if ((xlo<xhi) && !isConst) {
982 var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
983 } else {
984 var = new RooRealVar(varName,varName,xval) ;
985 }
986 var->setConstant(isConst) ;
987 } else {
988
989 var = (RooRealVar*) varList.at(i)->Clone() ;
990 var->setConstant(isConst) ;
991 var->setVal(xval) ;
992 if (xlo<xhi) {
993 var->setRange(xlo,xhi) ;
994 }
995
996 if (varName.CompareTo(var->GetName())) {
997 oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
998 << "' stored in variable '" << var->GetName() << "'" << endl ;
999 }
1000
1001 }
1002
1003 if (isConst) {
1004 constPars.addOwned(*var) ;
1005 } else {
1006 var->setError(xerr) ;
1007 floatPars.addOwned(*var) ;
1008 }
1009 }
1010
1011 res->setConstParList(constPars) ;
1012 res->setInitParList(floatPars) ;
1013 res->setFinalParList(floatPars) ;
1015 res->setEDM(_theFitter->Result().Edm()) ;
1017 res->setStatus(_theFitter->Result().Status()) ;
1018 std::vector<double> globalCC;
1019 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
1020 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
1021 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
1022 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
1023 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
1024 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
1025 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
1026 }
1027 }
1028 res->fillCorrMatrix(globalCC,corrs,covs) ;
1029
1030 return res;
1031
1032}
1033
1035{
1036 return _printLevel;
1037}
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
#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:45
unsigned int UInt_t
Definition: RtypesCore.h:46
const Bool_t kFALSE
Definition: RtypesCore.h:101
bool Bool_t
Definition: RtypesCore.h:63
double Double_t
Definition: RtypesCore.h:59
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
Definition: FitResult.cxx:409
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:72
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:84
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition: RooAbsArg.h:363
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 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.
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:61
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition: RooAbsReal.h:91
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.
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:172
void setMinNLL(Double_t val)
Definition: RooFitResult.h:169
void setNumInvalidNLL(Int_t val)
Definition: RooFitResult.h:173
void setStatus(Int_t val)
Definition: RooFitResult.h:171
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:170
void setStatusHistory(std::vector< std::pair< std::string, int > > &hist)
Definition: RooFitResult.h:178
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...
Definition: MinuitFcnGrad.h:52
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...
Definition: RooMinimizer.h:55
Int_t _printLevel
Definition: RooMinimizer.h:144
std::vector< std::pair< std::string, int > > _statusHistory
Definition: RooMinimizer.h:161
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.
Bool_t _verbose
Definition: RooMinimizer.h:148
void saveStatus(const char *label, Int_t status)
Definition: RooMinimizer.h:110
Int_t improve()
Execute IMPROVE.
FcnMode _fcnMode
Definition: RooMinimizer.h:157
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.
ROOT::Math::IMultiGenFunction * getFitterMultiGenFcn() const
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
const RooAbsMinimizerFcn * fitterFcn() const
RooFitResult * fit(const char *options)
Parse traditional RooAbsPdf::fitTo driver options.
static std::unique_ptr< RooMinimizer > create(RooAbsReal &function, FcnMode fcnMode=FcnMode::classic)
void setOffsetting(Bool_t flag)
Enable internal likelihood offsetting for enhanced numeric precision.
TMatrixDSym * _extV
Definition: RooMinimizer.h:153
Int_t seek()
Execute SEEK.
Bool_t setLogFile(const char *logf=0)
Definition: RooMinimizer.h:101
void setProfile(Bool_t flag=kTRUE)
Definition: RooMinimizer.h:100
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:159
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:149
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
Definition: RooMinimizer.h:151
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
Definition: RooMinimizer.h:156
TStopwatch _cumulTimer
Definition: RooMinimizer.h:150
Bool_t _profile
Definition: RooMinimizer.h:146
RooAbsMinimizerFcn * _fcn
Definition: RooMinimizer.h:155
void setVerbose(Bool_t flag=kTRUE)
Definition: RooMinimizer.h:99
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:422
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:39
void setError(Double_t value)
Definition: RooRealVar.h:62
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
Definition: RooRealVar.cxx:551
virtual void setVal(Double_t value)
Set value of variable to 'value'.
Definition: RooRealVar.cxx:282
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
Definition: RooSentinel.cxx:56
A TGraph is an object made of two arrays X and Y with npoints each.
Definition: TGraph.h:41
TObject * Next()
Definition: TCollection.h:251
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:37
virtual const char * GetName() const
Returns name of object.
Definition: TObject.cxx:359
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition: TObject.cxx:146
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: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
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:150
@ Minimization
Definition: RooGlobalFunc.h:60
@ InputArguments
Definition: RooGlobalFunc.h:61
Definition: graph.py:1