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 * *
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
43#include "TClass.h"
44
45#include <iostream>
46#include <fstream>
47
48#include "TH2.h"
49#include "TMarker.h"
50#include "TGraph.h"
51#include "Fit/FitConfig.h"
52#include "TStopwatch.h"
53#include "TMatrixDSym.h"
54
55#include "RooArgSet.h"
56#include "RooArgList.h"
57#include "RooAbsReal.h"
58#include "RooAbsRealLValue.h"
59#include "RooRealVar.h"
60#include "RooAbsPdf.h"
61#include "RooSentinel.h"
62#include "RooMsgService.h"
63#include "RooPlot.h"
64
65
66#include "RooMinimizer.h"
67#include "RooFitResult.h"
68
69#include "Math/Minimizer.h"
70
71#if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
72char* operator+( streampos&, char* );
73#endif
74
75using namespace std;
76
78;
79
81
82
83
84////////////////////////////////////////////////////////////////////////////////
85/// Cleanup method called by atexit handler installed by RooSentinel
86/// to delete all global heap objects when the program is terminated
87
89{
90 if (_theFitter) {
91 delete _theFitter ;
92 _theFitter =0 ;
93 }
94}
95
96
97
98////////////////////////////////////////////////////////////////////////////////
99/// Construct MINUIT interface to given function. Function can be anything,
100/// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
101/// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
102/// of a RooNLLVar plus a penalty or constraint term. This class propagates
103/// all RooFit information (floating parameters, their values and errors)
104/// to MINUIT before each MINUIT call and propagates all MINUIT information
105/// back to the RooFit object at the end of each call (updated parameter
106/// values, their (asymmetric errors) etc. The default MINUIT error level
107/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
108/// value of the input function.
109
111{
113
114 // Store function reference
115 _extV = 0 ;
116 _func = &function ;
117 _optConst = kFALSE ;
118 _verbose = kFALSE ;
119 _profile = kFALSE ;
121 _printLevel = 1 ;
122 _minimizerType = "Minuit"; // default minimizer
123
124 if (_theFitter) delete _theFitter ;
128 setEps(1.0); // default tolerance
129 // default max number of calls
132
133 // Shut up for now
134 setPrintLevel(-1) ;
135
136 // Use +0.5 for 1-sigma errors
138
139 // Declare our parameters to MINUIT
142
143 // Now set default verbosity
144 if (RooMsgService::instance().silentMode()) {
145 setPrintLevel(-1) ;
146 } else {
147 setPrintLevel(1) ;
148 }
149}
150
151
152
153////////////////////////////////////////////////////////////////////////////////
154/// Destructor
155
157{
158 if (_extV) {
159 delete _extV ;
160 }
161
162 if (_fcn) {
163 delete _fcn;
164 }
165
166}
167
168
169
170////////////////////////////////////////////////////////////////////////////////
171/// Change MINUIT strategy to istrat. Accepted codes
172/// are 0,1,2 and represent MINUIT strategies for dealing
173/// most efficiently with fast FCNs (0), expensive FCNs (2)
174/// and 'intermediate' FCNs (1)
175
177{
179
180}
181
182
183
184////////////////////////////////////////////////////////////////////////////////
185/// Change maximum number of MINUIT iterations
186/// (RooMinimizer default 500 * #parameters)
187
189{
191}
192
193
194
195
196////////////////////////////////////////////////////////////////////////////////
197/// Change maximum number of likelihood function calss from MINUIT
198/// (RooMinimizer default 500 * #parameters)
199
201{
203}
204
205
206
207
208////////////////////////////////////////////////////////////////////////////////
209/// Set the level for MINUIT error analysis to the given
210/// value. This function overrides the default value
211/// that is taken in the RooMinimizer constructor from
212/// the defaultErrorLevel() method of the input function
213
215{
217
218}
219
220
221
222////////////////////////////////////////////////////////////////////////////////
223/// Change MINUIT epsilon
224
226{
228
229}
230
231
232////////////////////////////////////////////////////////////////////////////////
233/// Enable internal likelihood offsetting for enhanced numeric precision
234
236{
237 _func->enableOffsetting(flag) ;
238}
239
240
241
242
243////////////////////////////////////////////////////////////////////////////////
244/// Choose the minimiser algorithm.
246{
248}
249
250
251
252
253////////////////////////////////////////////////////////////////////////////////
254/// Return underlying ROOT fitter object
255
257{
258 return _theFitter ;
259}
260
261
262////////////////////////////////////////////////////////////////////////////////
263/// Return underlying ROOT fitter object
264
266{
267 return _theFitter ;
268}
269
270
271
272////////////////////////////////////////////////////////////////////////////////
273/// Parse traditional RooAbsPdf::fitTo driver options
274///
275/// m - Run Migrad only
276/// h - Run Hesse to estimate errors
277/// v - Verbose mode
278/// l - Log parameters after each Minuit steps to file
279/// t - Activate profile timer
280/// r - Save fit result
281/// 0 - Run Migrad with strategy 0
282
283RooFitResult* RooMinimizer::fit(const char* options)
284{
285 TString opts(options) ;
286 opts.ToLower() ;
287
288 // Initial configuration
289 if (opts.Contains("v")) setVerbose(1) ;
290 if (opts.Contains("t")) setProfile(1) ;
291 if (opts.Contains("l")) setLogFile(Form("%s.log",_func->GetName())) ;
292 if (opts.Contains("c")) optimizeConst(1) ;
293
294 // Fitting steps
295 if (opts.Contains("0")) setStrategy(0) ;
296 migrad() ;
297 if (opts.Contains("0")) setStrategy(1) ;
298 if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
299 if (!opts.Contains("m")) minos() ;
300
301 return (opts.Contains("r")) ? save() : 0 ;
302}
303
304
305
306
307////////////////////////////////////////////////////////////////////////////////
308/// Minimise the function passed in the constructor.
309/// \param[in] type Type of fitter to use, e.g. "Minuit" "Minuit2".
310/// \attention This overrides the default fitter of this RooMinimizer.
311/// \param[in] alg Fit algorithm to use. (Optional)
312Int_t RooMinimizer::minimize(const char* type, const char* alg)
313{
316
319
320 profileStart() ;
323
324 bool ret = _theFitter->FitFCN(*_fcn);
325 _status = ((ret) ? _theFitter->Result().Status() : -1);
326
328 profileStop() ;
330
331 saveStatus("MINIMIZE",_status) ;
332
333 return _status ;
334}
335
336
337
338////////////////////////////////////////////////////////////////////////////////
339/// Execute MIGRAD. Changes in parameter values
340/// and calculated errors are automatically
341/// propagated back the RooRealVars representing
342/// the floating parameters in the MINUIT operation.
343
345{
348 profileStart() ;
351
352 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migrad");
353 bool ret = _theFitter->FitFCN(*_fcn);
354 _status = ((ret) ? _theFitter->Result().Status() : -1);
355
357 profileStop() ;
359
360 saveStatus("MIGRAD",_status) ;
361
362 return _status ;
363}
364
365
366
367////////////////////////////////////////////////////////////////////////////////
368/// Execute HESSE. Changes in parameter values
369/// and calculated errors are automatically
370/// propagated back the RooRealVars representing
371/// the floating parameters in the MINUIT operation.
372
374{
375 if (_theFitter->GetMinimizer()==0) {
376 coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!"
377 << endl ;
378 _status = -1;
379 }
380 else {
381
384 profileStart() ;
387
389 bool ret = _theFitter->CalculateHessErrors();
390 _status = ((ret) ? _theFitter->Result().Status() : -1);
391
393 profileStop() ;
395
396 saveStatus("HESSE",_status) ;
397
398 }
399
400 return _status ;
401
402}
403
404////////////////////////////////////////////////////////////////////////////////
405/// Execute MINOS. Changes in parameter values
406/// and calculated errors are automatically
407/// propagated back the RooRealVars representing
408/// the floating parameters in the MINUIT operation.
409
411{
412 if (_theFitter->GetMinimizer()==0) {
413 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
414 << endl ;
415 _status = -1;
416 }
417 else {
418
421 profileStart() ;
424
426 bool ret = _theFitter->CalculateMinosErrors();
427 _status = ((ret) ? _theFitter->Result().Status() : -1);
428
430 profileStop() ;
432
433 saveStatus("MINOS",_status) ;
434
435 }
436
437 return _status ;
438
439}
440
441
442////////////////////////////////////////////////////////////////////////////////
443/// Execute MINOS for given list of parameters. Changes in parameter values
444/// and calculated errors are automatically
445/// propagated back the RooRealVars representing
446/// the floating parameters in the MINUIT operation.
447
448Int_t RooMinimizer::minos(const RooArgSet& minosParamList)
449{
450 if (_theFitter->GetMinimizer()==0) {
451 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
452 << endl ;
453 _status = -1;
454 }
455 else if (minosParamList.getSize()>0) {
456
459 profileStart() ;
462
463 // get list of parameters for Minos
464 TIterator* aIter = minosParamList.createIterator() ;
465 RooAbsArg* arg ;
466 std::vector<unsigned int> paramInd;
467 while((arg=(RooAbsArg*)aIter->Next())) {
468 RooAbsArg* par = _fcn->GetFloatParamList()->find(arg->GetName());
469 if (par && !par->isConstant()) {
470 Int_t index = _fcn->GetFloatParamList()->index(par);
471 paramInd.push_back(index);
472 }
473 }
474 delete aIter ;
475
476 if (paramInd.size()) {
477 // set the parameter indeces
478 _theFitter->Config().SetMinosErrors(paramInd);
479
481 bool ret = _theFitter->CalculateMinosErrors();
482 _status = ((ret) ? _theFitter->Result().Status() : -1);
483 // to avoid that following minimization computes automatically the Minos errors
485
486 }
487
489 profileStop() ;
491
492 saveStatus("MINOS",_status) ;
493
494 }
495
496 return _status ;
497}
498
499
500
501////////////////////////////////////////////////////////////////////////////////
502/// Execute SEEK. Changes in parameter values
503/// and calculated errors are automatically
504/// propagated back the RooRealVars representing
505/// the floating parameters in the MINUIT operation.
506
508{
511 profileStart() ;
514
515 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"seek");
516 bool ret = _theFitter->FitFCN(*_fcn);
517 _status = ((ret) ? _theFitter->Result().Status() : -1);
518
520 profileStop() ;
522
523 saveStatus("SEEK",_status) ;
524
525 return _status ;
526}
527
528
529
530////////////////////////////////////////////////////////////////////////////////
531/// Execute SIMPLEX. Changes in parameter values
532/// and calculated errors are automatically
533/// propagated back the RooRealVars representing
534/// the floating parameters in the MINUIT operation.
535
537{
540 profileStart() ;
543
544 _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"simplex");
545 bool ret = _theFitter->FitFCN(*_fcn);
546 _status = ((ret) ? _theFitter->Result().Status() : -1);
547
549 profileStop() ;
551
552 saveStatus("SEEK",_status) ;
553
554 return _status ;
555}
556
557
558
559////////////////////////////////////////////////////////////////////////////////
560/// Execute IMPROVE. 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(),"migradimproved");
574 bool ret = _theFitter->FitFCN(*_fcn);
575 _status = ((ret) ? _theFitter->Result().Status() : -1);
576
578 profileStop() ;
580
581 saveStatus("IMPROVE",_status) ;
582
583 return _status ;
584}
585
586
587
588////////////////////////////////////////////////////////////////////////////////
589/// Change the MINUIT internal printing level
590
592{
593 Int_t ret = _printLevel ;
595 _printLevel = newLevel+1 ;
596 return ret ;
597}
598
599////////////////////////////////////////////////////////////////////////////////
600/// If flag is true, perform constant term optimization on
601/// function being minimized.
602
604{
606
607 if (_optConst && !flag){
608 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: deactivating const optimization" << endl ;
610 _optConst = flag ;
611 } else if (!_optConst && flag) {
612 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: activating const optimization" << endl ;
614 _optConst = flag ;
615 } else if (_optConst && flag) {
616 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: const optimization already active" << endl ;
617 } else {
618 if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: const optimization wasn't active" << endl ;
619 }
620
622
623}
624
625
626
627////////////////////////////////////////////////////////////////////////////////
628/// Save and return a RooFitResult snapshot of current minimizer status.
629/// This snapshot contains the values of all constant parameters,
630/// the value of all floating parameters at RooMinimizer construction and
631/// after the last MINUIT operation, the MINUIT status, variance quality,
632/// EDM setting, number of calls with evaluation problems, the minimized
633/// function value and the full correlation matrix.
634
635RooFitResult* RooMinimizer::save(const char* userName, const char* userTitle)
636{
637 if (_theFitter->GetMinimizer()==0) {
638 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!"
639 << endl ;
640 return 0;
641 }
642
643 TString name,title ;
644 name = userName ? userName : Form("%s", _func->GetName()) ;
645 title = userTitle ? userTitle : Form("%s", _func->GetTitle()) ;
646 RooFitResult* fitRes = new RooFitResult(name,title) ;
647
648 // Move eventual fixed parameters in floatList to constList
649 Int_t i ;
650 RooArgList saveConstList(*(_fcn->GetConstParamList())) ;
651 RooArgList saveFloatInitList(*(_fcn->GetInitFloatParamList())) ;
652 RooArgList saveFloatFinalList(*(_fcn->GetFloatParamList())) ;
653 for (i=0 ; i<_fcn->GetFloatParamList()->getSize() ; i++) {
654 RooAbsArg* par = _fcn->GetFloatParamList()->at(i) ;
655 if (par->isConstant()) {
656 saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),kTRUE) ;
657 saveFloatFinalList.remove(*par) ;
658 saveConstList.add(*par) ;
659 }
660 }
661 saveConstList.sort() ;
662
663 fitRes->setConstParList(saveConstList) ;
664 fitRes->setInitParList(saveFloatInitList) ;
665
666 // The fitter often clones the function. We therefore have to ask it for its copy.
667 const auto fitFcn = dynamic_cast<const RooMinimizerFcn*>(_theFitter->GetFCN());
668 double removeOffset = 0.;
669 if (fitFcn) {
670 fitRes->setNumInvalidNLL(fitFcn->GetNumInvalidNLL());
671 removeOffset = - fitFcn->getOffset();
672 }
673
674 fitRes->setStatus(_status) ;
676 fitRes->setMinNLL(_theFitter->Result().MinFcnValue() + removeOffset);
677 fitRes->setEDM(_theFitter->Result().Edm()) ;
678 fitRes->setFinalParList(saveFloatFinalList) ;
679 if (!_extV) {
680 std::vector<double> globalCC;
681 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
682 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
683 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
684 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
685 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
686 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
687 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
688 }
689 }
690 fitRes->fillCorrMatrix(globalCC,corrs,covs) ;
691 } else {
692 fitRes->setCovarianceMatrix(*_extV) ;
693 }
694
696
697 return fitRes ;
698
699}
700
701////////////////////////////////////////////////////////////////////////////////
702/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
703/// \param[in] var1 The first parameter (x axis).
704/// \param[in] var2 The second parameter (y axis).
705/// \param[in] n1 First contour.
706/// \param[in] n2 Optional contour. 0 means don't draw.
707/// \param[in] n3 Optional contour. 0 means don't draw.
708/// \param[in] n4 Optional contour. 0 means don't draw.
709/// \param[in] n5 Optional contour. 0 means don't draw.
710/// \param[in] n6 Optional contour. 0 means don't draw.
711/// \param[in] npoints Number of points for evaluating the contour.
712///
713/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
714/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
715/// See ROOT::Math::Minimizer::ErrorDef().
716
718 Double_t n1, Double_t n2, Double_t n3,
719 Double_t n4, Double_t n5, Double_t n6, unsigned int npoints)
720{
721
722
723 RooArgList* params = _fcn->GetFloatParamList() ;
724 RooArgList* paramSave = (RooArgList*) params->snapshot() ;
725
726 // Verify that both variables are floating parameters of PDF
727 Int_t index1= _fcn->GetFloatParamList()->index(&var1);
728 if(index1 < 0) {
729 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
730 << ") ERROR: " << var1.GetName()
731 << " is not a floating parameter of "
732 << _func->GetName() << endl ;
733 return 0;
734 }
735
736 Int_t index2= _fcn->GetFloatParamList()->index(&var2);
737 if(index2 < 0) {
738 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
739 << ") ERROR: " << var2.GetName()
740 << " is not a floating parameter of PDF "
741 << _func->GetName() << endl ;
742 return 0;
743 }
744
745 // create and draw a frame
746 RooPlot* frame = new RooPlot(var1,var2) ;
747
748 // draw a point at the current parameter values
749 TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
750 frame->addObject(point) ;
751
752 // check first if a inimizer is available. If not means
753 // the minimization is not done , so do it
754 if (_theFitter->GetMinimizer()==0) {
755 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
756 << endl ;
757 return frame;
758 }
759
760
761 // remember our original value of ERRDEF
763
764 Double_t n[6] ;
765 n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
766
767 for (Int_t ic = 0 ; ic<6 ; ic++) {
768 if(n[ic] > 0) {
769
770 // set the value corresponding to an n1-sigma contour
771 _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
772
773 // calculate and draw the contour
774 Double_t *xcoor = new Double_t[npoints+1];
775 Double_t *ycoor = new Double_t[npoints+1];
776 bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
777
778 if (!ret) {
779 coutE(Minimization) << "RooMinimizer::contour("
780 << GetName()
781 << ") ERROR: MINUIT did not return a contour graph for n="
782 << n[ic] << endl ;
783 } else {
784 xcoor[npoints] = xcoor[0];
785 ycoor[npoints] = ycoor[0];
786 TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
787
788 graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ;
789 graph->SetLineStyle(ic+1) ;
790 graph->SetLineWidth(2) ;
791 graph->SetLineColor(kBlue) ;
792 frame->addObject(graph,"L") ;
793 }
794
795 delete [] xcoor;
796 delete [] ycoor;
797 }
798 }
799
800
801 // restore the original ERRDEF
803
804 // restore parameter values
805 *params = *paramSave ;
806 delete paramSave ;
807
808 return frame ;
809
810}
811
812
813////////////////////////////////////////////////////////////////////////////////
814/// Start profiling timer
815
817{
818 if (_profile) {
819 _timer.Start() ;
822 }
823}
824
825
826////////////////////////////////////////////////////////////////////////////////
827/// Stop profiling timer and report results of last session
828
830{
831 if (_profile) {
832 _timer.Stop() ;
833 _cumulTimer.Stop() ;
834 coutI(Minimization) << "Command timer: " ; _timer.Print() ;
835 coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
836 }
837}
838
839
840
841
842
843////////////////////////////////////////////////////////////////////////////////
844/// Apply results of given external covariance matrix. i.e. propagate its errors
845/// to all RRV parameter representations and give this matrix instead of the
846/// HESSE matrix at the next save() call
847
849{
850 _extV = (TMatrixDSym*) V.Clone() ;
852
853}
854
855
856
858{
859 // Import the results of the last fit performed, interpreting
860 // the fit parameters as the given varList of parameters.
861
862 if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
863 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
864 << endl ;
865 return 0;
866 }
867
868 // Verify length of supplied varList
869 if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
870 oocoutE((TObject*)0,InputArguments)
871 << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
872 << " or match the number of variables of the last fit ("
873 << _theFitter->Result().NTotalParameters() << ")" << endl ;
874 return 0 ;
875 }
876
877
878 // Verify that all members of varList are of type RooRealVar
879 TIterator* iter = varList.createIterator() ;
880 RooAbsArg* arg ;
881 while((arg=(RooAbsArg*)iter->Next())) {
882 if (!dynamic_cast<RooRealVar*>(arg)) {
883 oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
884 << arg->GetName() << "' is not of type RooRealVar" << endl ;
885 return 0 ;
886 }
887 }
888 delete iter ;
889
890 RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
891
892 // Extract names of fit parameters
893 // and construct corresponding RooRealVars
894 RooArgList constPars("constPars") ;
895 RooArgList floatPars("floatPars") ;
896
897 UInt_t i ;
898 for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
899
902
905 Double_t xerr = _theFitter->Result().Error(i);
906 Double_t xval = _theFitter->Result().Value(i);
907
908 RooRealVar* var ;
909 if (varList.getSize()==0) {
910
911 if ((xlo<xhi) && !isConst) {
912 var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
913 } else {
914 var = new RooRealVar(varName,varName,xval) ;
915 }
916 var->setConstant(isConst) ;
917 } else {
918
919 var = (RooRealVar*) varList.at(i)->Clone() ;
920 var->setConstant(isConst) ;
921 var->setVal(xval) ;
922 if (xlo<xhi) {
923 var->setRange(xlo,xhi) ;
924 }
925
926 if (varName.CompareTo(var->GetName())) {
927 oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
928 << "' stored in variable '" << var->GetName() << "'" << endl ;
929 }
930
931 }
932
933 if (isConst) {
934 constPars.addOwned(*var) ;
935 } else {
936 var->setError(xerr) ;
937 floatPars.addOwned(*var) ;
938 }
939 }
940
941 res->setConstParList(constPars) ;
942 res->setInitParList(floatPars) ;
943 res->setFinalParList(floatPars) ;
945 res->setEDM(_theFitter->Result().Edm()) ;
947 res->setStatus(_theFitter->Result().Status()) ;
948 std::vector<double> globalCC;
949 TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
950 TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
951 for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
952 globalCC.push_back(_theFitter->Result().GlobalCC(ic));
953 for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
954 corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
955 covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
956 }
957 }
958 res->fillCorrMatrix(globalCC,corrs,covs) ;
959
960 return res;
961
962}
963
964#endif
#define coutI(a)
#define coutW(a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
const Bool_t kFALSE
Definition RtypesCore.h:92
const Bool_t kTRUE
Definition RtypesCore.h:91
#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:1494
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
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
virtual void constOptimizeTestStatistic(ConstOpCode opcode, Bool_t doAlsoTrackingOpt=kTRUE)
Interface function signaling a request to perform constant term optimization.
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:380
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:61
virtual Double_t defaultErrorLevel() const
Definition RooAbsReal.h:252
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:91
virtual void enableOffsetting(Bool_t)
Definition RooAbsReal.h:367
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:70
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:29
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.
RooMinimizerFcn is an interface to the ROOT::Math::IBaseFunctionMultiDim, a function that ROOT's mini...
RooArgList * GetInitFloatParamList()
void ApplyCovarianceMatrix(TMatrixDSym &V)
Apply results of given external covariance matrix.
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)
Internal function to synchronize TMinimizer with current information in RooAbsReal function parameter...
void BackProp(const ROOT::Fit::FitResult &results)
Transfer MINUIT fit results back into RooFit objects.
RooArgList * GetFloatParamList()
RooArgList * GetConstParamList()
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
RooMinimizerFcn * _fcn
std::vector< std::pair< std::string, int > > _statusHistory
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 snapshot of current minimizer status.
void setMinimizerType(const char *type)
Choose the minimiser algorithm.
void saveStatus(const char *label, Int_t status)
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
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.
RooAbsReal * _func
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 _profileStart
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
void setStrategy(Int_t strat)
Change MINUIT strategy to istrat.
std::string _minimizerType
TStopwatch _cumulTimer
void setVerbose(Bool_t flag=kTRUE)
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: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.
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
Iterator abstract base class.
Definition TIterator.h:30
virtual TObject * Next()=0
Manages Markers.
Definition TMarker.h:22
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: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.
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:1145
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition TString.cxx:438
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