Logo ROOT   master
Reference Guide
RooMinimizer.cxx
Go to the documentation of this file.
1 /*****************************************************************************
2  * Project: RooFit *
3  * Package: RooFitCore *
4  * @(#)root/roofitcore:$Id$
5  * Authors: *
6  * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7  * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8  * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
9  * *
10  * Redistribution and use in source and binary forms, *
11  * with or without modification, are permitted according to the terms *
12  * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
13  *****************************************************************************/
14 
15 /**
16 \file RooMinimizer.cxx
17 \class RooMinimizer
18 \ingroup Roofitcore
19 
20 RooMinimizer is a wrapper class around ROOT::Fit:Fitter that
21 provides a seamless interface between the minimizer functionality
22 and the native RooFit interface.
23 By default the Minimizer is MINUIT.
24 RooMinimizer can minimize any RooAbsReal function with respect to
25 its parameters. Usual choices for minimization are RooNLLVar
26 and RooChi2Var
27 RooMinimizer has methods corresponding to MINUIT functions like
28 hesse(), migrad(), minos() etc. In each of these function calls
29 the state of the MINUIT engine is synchronized with the state
30 of the RooFit variables: any change in variables, change
31 in the constant status etc is forwarded to MINUIT prior to
32 execution of the MINUIT call. Afterwards the RooFit objects
33 are resynchronized with the output state of MINUIT: changes
34 parameter values, errors are propagated.
35 Various methods are available to control verbosity, profiling,
36 automatic 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)
72 char* operator+( streampos&, char* );
73 #endif
74 
75 using 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 ;
120  _profileStart = kFALSE ;
121  _printLevel = 1 ;
122  _minimizerType = "Minuit"; // default minimizer
123 
124  if (_theFitter) delete _theFitter ;
125  _theFitter = new ROOT::Fit::Fitter;
126  _fcn = new RooMinimizerFcn(_func,this,_verbose);
127  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
128  setEps(1.0); // default tolerance
129  // default max number of calls
130  _theFitter->Config().MinimizerOptions().SetMaxIterations(500*_fcn->NDim());
131  _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(500*_fcn->NDim());
132 
133  // Shut up for now
134  setPrintLevel(-1) ;
135 
136  // Use +0.5 for 1-sigma errors
137  setErrorLevel(_func->defaultErrorLevel()) ;
138 
139  // Declare our parameters to MINUIT
140  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
141  _optConst,_verbose) ;
142 
143  // Now set default verbosity
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 {
178  _theFitter->Config().MinimizerOptions().SetStrategy(istrat);
179 
180 }
181 
182 
183 
184 ////////////////////////////////////////////////////////////////////////////////
185 /// Change maximum number of MINUIT iterations
186 /// (RooMinimizer default 500 * #parameters)
187 
189 {
190  _theFitter->Config().MinimizerOptions().SetMaxIterations(n);
191 }
192 
193 
194 
195 
196 ////////////////////////////////////////////////////////////////////////////////
197 /// Change maximum number of likelihood function calss from MINUIT
198 /// (RooMinimizer default 500 * #parameters)
199 
201 {
202  _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(n);
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 {
216  _theFitter->Config().MinimizerOptions().SetErrorDef(level);
217 
218 }
219 
220 
221 
222 ////////////////////////////////////////////////////////////////////////////////
223 /// Change MINUIT epsilon
224 
226 {
227  _theFitter->Config().MinimizerOptions().SetTolerance(eps);
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 {
247  _minimizerType = type;
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 
283 RooFitResult* 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)
312 Int_t RooMinimizer::minimize(const char* type, const char* alg)
313 {
314  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
315  _optConst,_verbose) ;
316 
317  _minimizerType = type;
318  _theFitter->Config().SetMinimizer(type,alg);
319 
320  profileStart() ;
323 
324  bool ret = _theFitter->FitFCN(*_fcn);
325  _status = ((ret) ? _theFitter->Result().Status() : -1);
326 
328  profileStop() ;
329  _fcn->BackProp(_theFitter->Result());
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 {
346  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
347  _optConst,_verbose) ;
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() ;
358  _fcn->BackProp(_theFitter->Result());
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 
382  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
383  _optConst,_verbose) ;
384  profileStart() ;
387 
388  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
389  bool ret = _theFitter->CalculateHessErrors();
390  _status = ((ret) ? _theFitter->Result().Status() : -1);
391 
393  profileStop() ;
394  _fcn->BackProp(_theFitter->Result());
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 
419  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
420  _optConst,_verbose) ;
421  profileStart() ;
424 
425  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
426  bool ret = _theFitter->CalculateMinosErrors();
427  _status = ((ret) ? _theFitter->Result().Status() : -1);
428 
430  profileStop() ;
431  _fcn->BackProp(_theFitter->Result());
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 
448 Int_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 
457  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
458  _optConst,_verbose) ;
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 
480  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
481  bool ret = _theFitter->CalculateMinosErrors();
482  _status = ((ret) ? _theFitter->Result().Status() : -1);
483  // to avoid that following minimization computes automatically the Minos errors
484  _theFitter->Config().SetMinosErrors(kFALSE);
485 
486  }
487 
489  profileStop() ;
490  _fcn->BackProp(_theFitter->Result());
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 {
509  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
510  _optConst,_verbose) ;
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() ;
521  _fcn->BackProp(_theFitter->Result());
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 {
538  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
539  _optConst,_verbose) ;
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() ;
550  _fcn->BackProp(_theFitter->Result());
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 {
567  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
568  _optConst,_verbose) ;
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() ;
579  _fcn->BackProp(_theFitter->Result());
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 ;
594  _theFitter->Config().MinimizerOptions().SetPrintLevel(newLevel+1);
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 ;
609  _func->constOptimizeTestStatistic(RooAbsArg::DeActivate) ;
610  _optConst = flag ;
611  } else if (!_optConst && flag) {
612  if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: activating const optimization" << endl ;
613  _func->constOptimizeTestStatistic(RooAbsArg::Activate,flag>1) ;
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 snaphot 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 
635 RooFitResult* 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  fitRes->setStatus(_status) ;
667  fitRes->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
668  fitRes->setMinNLL(_theFitter->Result().MinFcnValue()) ;
669  fitRes->setNumInvalidNLL(_fcn->GetNumInvalidNLL()) ;
670  fitRes->setEDM(_theFitter->Result().Edm()) ;
671  fitRes->setFinalParList(saveFloatFinalList) ;
672  if (!_extV) {
673  std::vector<double> globalCC;
674  TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
675  TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
676  for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
677  globalCC.push_back(_theFitter->Result().GlobalCC(ic));
678  for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
679  corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
680  covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
681  }
682  }
683  fitRes->fillCorrMatrix(globalCC,corrs,covs) ;
684  } else {
685  fitRes->setCovarianceMatrix(*_extV) ;
686  }
687 
688  fitRes->setStatusHistory(_statusHistory) ;
689 
690  return fitRes ;
691 
692 }
693 
694 ////////////////////////////////////////////////////////////////////////////////
695 /// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
696 /// \param[in] var1 The first parameter (x axis).
697 /// \param[in] var2 The second parameter (y axis).
698 /// \param[in] n1 First contour.
699 /// \param[in] n2 Optional contour. 0 means don't draw.
700 /// \param[in] n3 Optional contour. 0 means don't draw.
701 /// \param[in] n4 Optional contour. 0 means don't draw.
702 /// \param[in] n5 Optional contour. 0 means don't draw.
703 /// \param[in] n6 Optional contour. 0 means don't draw.
704 /// \param[in] npoints Number of points for evaluating the contour.
705 ///
706 /// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
707 /// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
708 /// See ROOT::Math::Minimizer::ErrorDef().
709 
711  Double_t n1, Double_t n2, Double_t n3,
712  Double_t n4, Double_t n5, Double_t n6, unsigned int npoints)
713 {
714 
715 
716  RooArgList* params = _fcn->GetFloatParamList() ;
717  RooArgList* paramSave = (RooArgList*) params->snapshot() ;
718 
719  // Verify that both variables are floating parameters of PDF
720  Int_t index1= _fcn->GetFloatParamList()->index(&var1);
721  if(index1 < 0) {
722  coutE(Minimization) << "RooMinimizer::contour(" << GetName()
723  << ") ERROR: " << var1.GetName()
724  << " is not a floating parameter of "
725  << _func->GetName() << endl ;
726  return 0;
727  }
728 
729  Int_t index2= _fcn->GetFloatParamList()->index(&var2);
730  if(index2 < 0) {
731  coutE(Minimization) << "RooMinimizer::contour(" << GetName()
732  << ") ERROR: " << var2.GetName()
733  << " is not a floating parameter of PDF "
734  << _func->GetName() << endl ;
735  return 0;
736  }
737 
738  // create and draw a frame
739  RooPlot* frame = new RooPlot(var1,var2) ;
740 
741  // draw a point at the current parameter values
742  TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
743  frame->addObject(point) ;
744 
745  // check first if a inimizer is available. If not means
746  // the minimization is not done , so do it
747  if (_theFitter->GetMinimizer()==0) {
748  coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
749  << endl ;
750  return frame;
751  }
752 
753 
754  // remember our original value of ERRDEF
755  Double_t errdef= _theFitter->GetMinimizer()->ErrorDef();
756 
757  Double_t n[6] ;
758  n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
759 
760  for (Int_t ic = 0 ; ic<6 ; ic++) {
761  if(n[ic] > 0) {
762 
763  // set the value corresponding to an n1-sigma contour
764  _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
765 
766  // calculate and draw the contour
767  Double_t *xcoor = new Double_t[npoints+1];
768  Double_t *ycoor = new Double_t[npoints+1];
769  bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
770 
771  if (!ret) {
772  coutE(Minimization) << "RooMinimizer::contour("
773  << GetName()
774  << ") ERROR: MINUIT did not return a contour graph for n="
775  << n[ic] << endl ;
776  } else {
777  xcoor[npoints] = xcoor[0];
778  ycoor[npoints] = ycoor[0];
779  TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
780 
781  graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ;
782  graph->SetLineStyle(ic+1) ;
783  graph->SetLineWidth(2) ;
784  graph->SetLineColor(kBlue) ;
785  frame->addObject(graph,"L") ;
786  }
787 
788  delete [] xcoor;
789  delete [] ycoor;
790  }
791  }
792 
793 
794  // restore the original ERRDEF
795  _theFitter->Config().MinimizerOptions().SetErrorDef(errdef);
796 
797  // restore parameter values
798  *params = *paramSave ;
799  delete paramSave ;
800 
801  return frame ;
802 
803 }
804 
805 
806 ////////////////////////////////////////////////////////////////////////////////
807 /// Start profiling timer
808 
810 {
811  if (_profile) {
812  _timer.Start() ;
813  _cumulTimer.Start(_profileStart?kFALSE:kTRUE) ;
814  _profileStart = kTRUE ;
815  }
816 }
817 
818 
819 ////////////////////////////////////////////////////////////////////////////////
820 /// Stop profiling timer and report results of last session
821 
823 {
824  if (_profile) {
825  _timer.Stop() ;
826  _cumulTimer.Stop() ;
827  coutI(Minimization) << "Command timer: " ; _timer.Print() ;
828  coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
829  }
830 }
831 
832 
833 
834 
835 
836 ////////////////////////////////////////////////////////////////////////////////
837 /// Apply results of given external covariance matrix. i.e. propagate its errors
838 /// to all RRV parameter representations and give this matrix instead of the
839 /// HESSE matrix at the next save() call
840 
842 {
843  _extV = (TMatrixDSym*) V.Clone() ;
844  _fcn->ApplyCovarianceMatrix(*_extV);
845 
846 }
847 
848 
849 
851 {
852  // Import the results of the last fit performed, interpreting
853  // the fit parameters as the given varList of parameters.
854 
855  if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
856  oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
857  << endl ;
858  return 0;
859  }
860 
861  // Verify length of supplied varList
862  if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
864  << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
865  << " or match the number of variables of the last fit ("
866  << _theFitter->Result().NTotalParameters() << ")" << endl ;
867  return 0 ;
868  }
869 
870 
871  // Verify that all members of varList are of type RooRealVar
872  TIterator* iter = varList.createIterator() ;
873  RooAbsArg* arg ;
874  while((arg=(RooAbsArg*)iter->Next())) {
875  if (!dynamic_cast<RooRealVar*>(arg)) {
876  oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
877  << arg->GetName() << "' is not of type RooRealVar" << endl ;
878  return 0 ;
879  }
880  }
881  delete iter ;
882 
883  RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
884 
885  // Extract names of fit parameters
886  // and construct corresponding RooRealVars
887  RooArgList constPars("constPars") ;
888  RooArgList floatPars("floatPars") ;
889 
890  UInt_t i ;
891  for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
892 
893  TString varName(_theFitter->Result().GetParameterName(i));
894  Bool_t isConst(_theFitter->Result().IsParameterFixed(i)) ;
895 
896  Double_t xlo = _theFitter->Config().ParSettings(i).LowerLimit();
897  Double_t xhi = _theFitter->Config().ParSettings(i).UpperLimit();
898  Double_t xerr = _theFitter->Result().Error(i);
899  Double_t xval = _theFitter->Result().Value(i);
900 
901  RooRealVar* var ;
902  if (varList.getSize()==0) {
903 
904  if ((xlo<xhi) && !isConst) {
905  var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
906  } else {
907  var = new RooRealVar(varName,varName,xval) ;
908  }
909  var->setConstant(isConst) ;
910  } else {
911 
912  var = (RooRealVar*) varList.at(i)->Clone() ;
913  var->setConstant(isConst) ;
914  var->setVal(xval) ;
915  if (xlo<xhi) {
916  var->setRange(xlo,xhi) ;
917  }
918 
919  if (varName.CompareTo(var->GetName())) {
920  oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
921  << "' stored in variable '" << var->GetName() << "'" << endl ;
922  }
923 
924  }
925 
926  if (isConst) {
927  constPars.addOwned(*var) ;
928  } else {
929  var->setError(xerr) ;
930  floatPars.addOwned(*var) ;
931  }
932  }
933 
934  res->setConstParList(constPars) ;
935  res->setInitParList(floatPars) ;
936  res->setFinalParList(floatPars) ;
937  res->setMinNLL(_theFitter->Result().MinFcnValue()) ;
938  res->setEDM(_theFitter->Result().Edm()) ;
939  res->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
940  res->setStatus(_theFitter->Result().Status()) ;
941  std::vector<double> globalCC;
942  TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
943  TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
944  for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
945  globalCC.push_back(_theFitter->Result().GlobalCC(ic));
946  for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
947  corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
948  covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
949  }
950  }
951  res->fillCorrMatrix(globalCC,corrs,covs) ;
952 
953  return res;
954 
955 }
956 
957 #endif
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
TIterator * createIterator(Bool_t dir=kIterForward) const
TIterator-style iteration over contained elements.
#define coutE(a)
Definition: RooMsgService.h:33
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
void optimizeConst(Int_t flag)
If flag is true, perform constant term optimization on function being minimized.
Int_t seek()
Execute SEEK.
void applyCovarianceMatrix(TMatrixDSym &V)
Apply results of given external covariance matrix.
unsigned int UInt_t
Definition: CPyCppyy.h:44
virtual ~RooMinimizer()
Destructor.
void addObject(TObject *obj, Option_t *drawOptions="", Bool_t invisible=kFALSE)
Add a generic object to this plot.
Definition: RooPlot.cxx:421
virtual Bool_t addOwned(RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
#define coutI(a)
Definition: RooMsgService.h:30
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:28
Int_t improve()
Execute IMPROVE.
int Int_t
Definition: CPyCppyy.h:43
#define oocoutI(o, a)
Definition: RooMsgService.h:45
void setStatus(Int_t val)
Definition: RooFitResult.h:169
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
Basic string class.
Definition: TString.h:131
Manages Markers.
Definition: TMarker.h:22
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Definition: RooFitResult.h:40
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1125
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:85
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
static RooMsgService & instance()
Return reference to singleton instance.
STL namespace.
#define coutW(a)
Definition: RooMsgService.h:32
void setInitParList(const RooArgList &list)
Fill the list of initial values of the floating parameters.
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.
Iterator abstract base class.
Definition: TIterator.h:30
void setMinimizerType(const char *type)
Choose the minimiser algorithm.
void setEps(Double_t eps)
Change MINUIT epsilon.
void setStrategy(Int_t strat)
Change MINUIT strategy to istrat.
void setEDM(Double_t val)
Definition: RooFitResult.h:168
Int_t simplex()
Execute SIMPLEX.
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
Bool_t silentMode() const
#define oocoutE(o, a)
Definition: RooMsgService.h:48
void sort(Bool_t reverse=false)
Sort collection using std::sort and name comparison.
RooMinimizer(RooAbsReal &function)
Construct MINUIT interface to given function.
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition: RExports.h:151
void setMaxIterations(Int_t n)
Change maximum number of MINUIT iterations (RooMinimizer default 500 * #parameters) ...
TString operator+(const TString &s1, const TString &s2)
Use the special concatenation constructor.
Definition: TString.cxx:1474
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:35
void setMinNLL(Double_t val)
Definition: RooFitResult.h:167
virtual void setVal(Double_t value)
Set value of variable to &#39;value&#39;.
Definition: RooRealVar.cxx:225
Int_t getSize() const
void setMaxFunctionCalls(Int_t n)
Change maximum number of likelihood function calss from MINUIT (RooMinimizer default 500 * #parameter...
RooAbsCollection * snapshot(Bool_t deepCopy=kTRUE) const
Take a snap shot of current collection contents.
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition: RooArgList.h:74
void setConstant(Bool_t value=kTRUE)
RooFitResult * save(const char *name=0, const char *title=0)
Save and return a RooFitResult snaphot of current minimizer status.
Fitter class, entry point for performing all type of fits.
Definition: Fitter.h:77
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition: RooAbsReal.h:90
char * Form(const char *fmt,...)
void setFinalParList(const RooArgList &list)
Fill the list of final values of the floating parameters.
Int_t migrad()
Execute MIGRAD.
Definition: graph.py:1
A RooPlot is a plot frame and a container for graphics objects within that frame. ...
Definition: RooPlot.h:44
const Bool_t kFALSE
Definition: RtypesCore.h:90
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
Definition: RooSentinel.cxx:57
void setConstParList(const RooArgList &list)
Fill the list of constant parameters.
#define ClassImp(name)
Definition: Rtypes.h:361
RooAbsArg * find(const char *name) const
Find object with given name in list.
double Double_t
Definition: RtypesCore.h:57
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:60
Int_t minos()
Execute MINOS.
void setErrorLevel(Double_t level)
Set the level for MINUIT error analysis to the given value.
int type
Definition: TGX11.cxx:120
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:619
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.
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
Definition: RooRealVar.cxx:495
Mother of all ROOT objects.
Definition: TObject.h:37
Int_t setPrintLevel(Int_t newLevel)
Change the MINUIT internal printing level.
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition: TObject.cxx:145
virtual Bool_t remove(const RooAbsArg &var, Bool_t silent=kFALSE, Bool_t matchByNameOnly=kFALSE)
Remove the specified argument from our list.
Int_t hesse()
Execute HESSE.
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
Definition: RooMinimizer.h:38
virtual TObject * Next()=0
A TGraph is an object made of two arrays X and Y with npoints each.
Definition: TGraph.h:41
void setCovQual(Int_t val)
Definition: RooFitResult.h:170
static void cleanup()
Cleanup method called by atexit handler installed by RooSentinel to delete all global heap objects wh...
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgList.h:21
Definition: Rtypes.h:64
static ROOT::Fit::Fitter * _theFitter
Definition: RooMinimizer.h:124
RooAbsArg is the common abstract base class for objects that represent a value (of arbitrary type) an...
Definition: RooAbsArg.h:73
void fillCorrMatrix()
Internal utility method to extract the correlation matrix and the global correlation coefficients fro...
void setOffsetting(Bool_t flag)
Enable internal likelihood offsetting for enhanced numeric precision.
RooFitResult * fit(const char *options)
Parse traditional RooAbsPdf::fitTo driver options.
const Bool_t kTRUE
Definition: RtypesCore.h:89
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
void profileStart()
Start profiling timer.
const Int_t n
Definition: legend1.C:16
char name[80]
Definition: TGX11.cxx:109
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition: RooAbsArg.h:360
void setError(Double_t value)
Definition: RooRealVar.h:64