Logo ROOT  
Reference Guide
RooMinimizer.cxx
Go to the documentation of this file.
1 /*****************************************************************************
2  * Project: RooFit *
3  * Package: RooFitCore *
4  * @(#)root/roofitcore:$Id$
5  * Authors: *
6  * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7  * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8  * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
9  * *
10  * Redistribution and use in source and binary forms, *
11  * with or without modification, are permitted according to the terms *
12  * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
13  *****************************************************************************/
14 
15 /**
16 \file RooMinimizer.cxx
17 \class RooMinimizer
18 \ingroup Roofitcore
19 
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
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 {
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 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 
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  // 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) ;
675  fitRes->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
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 
695  fitRes->setStatusHistory(_statusHistory) ;
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
762  Double_t errdef= _theFitter->GetMinimizer()->ErrorDef();
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
802  _theFitter->Config().MinimizerOptions().SetErrorDef(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() ;
820  _cumulTimer.Start(_profileStart?kFALSE:kTRUE) ;
821  _profileStart = kTRUE ;
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() ;
851  _fcn->ApplyCovarianceMatrix(*_extV);
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())) {
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  TIter 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 
889  RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
890 
891  // Extract names of fit parameters
892  // and construct corresponding RooRealVars
893  RooArgList constPars("constPars") ;
894  RooArgList floatPars("floatPars") ;
895 
896  UInt_t i ;
897  for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
898 
899  TString varName(_theFitter->Result().GetParameterName(i));
900  Bool_t isConst(_theFitter->Result().IsParameterFixed(i)) ;
901 
902  Double_t xlo = _theFitter->Config().ParSettings(i).LowerLimit();
903  Double_t xhi = _theFitter->Config().ParSettings(i).UpperLimit();
904  Double_t xerr = _theFitter->Result().Error(i);
905  Double_t xval = _theFitter->Result().Value(i);
906 
907  RooRealVar* var ;
908  if (varList.getSize()==0) {
909 
910  if ((xlo<xhi) && !isConst) {
911  var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
912  } else {
913  var = new RooRealVar(varName,varName,xval) ;
914  }
915  var->setConstant(isConst) ;
916  } else {
917 
918  var = (RooRealVar*) varList.at(i)->Clone() ;
919  var->setConstant(isConst) ;
920  var->setVal(xval) ;
921  if (xlo<xhi) {
922  var->setRange(xlo,xhi) ;
923  }
924 
925  if (varName.CompareTo(var->GetName())) {
926  oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
927  << "' stored in variable '" << var->GetName() << "'" << endl ;
928  }
929 
930  }
931 
932  if (isConst) {
933  constPars.addOwned(*var) ;
934  } else {
935  var->setError(xerr) ;
936  floatPars.addOwned(*var) ;
937  }
938  }
939 
940  res->setConstParList(constPars) ;
941  res->setInitParList(floatPars) ;
942  res->setFinalParList(floatPars) ;
943  res->setMinNLL(_theFitter->Result().MinFcnValue()) ;
944  res->setEDM(_theFitter->Result().Edm()) ;
945  res->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
946  res->setStatus(_theFitter->Result().Status()) ;
947  std::vector<double> globalCC;
948  TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
949  TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
950  for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
951  globalCC.push_back(_theFitter->Result().GlobalCC(ic));
952  for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
953  corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
954  covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
955  }
956  }
957  res->fillCorrMatrix(globalCC,corrs,covs) ;
958 
959  return res;
960 
961 }
962 
963 #endif
RooAbsArg::Clone
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:84
RooFitResult::setNumInvalidNLL
void setNumInvalidNLL(Int_t val)
Definition: RooFitResult.h:172
RooMinimizer::minos
Int_t minos()
Execute MINOS.
Definition: RooMinimizer.cxx:410
RooMinimizer::improve
Int_t improve()
Execute IMPROVE.
Definition: RooMinimizer.cxx:565
n
const Int_t n
Definition: legend1.C:16
Minimizer.h
RooFit::Minimization
@ Minimization
Definition: RooGlobalFunc.h:60
RooRealVar::setVal
virtual void setVal(Double_t value)
Set value of variable to 'value'.
Definition: RooRealVar.cxx:257
RooMinimizer::fitter
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
Definition: RooMinimizer.cxx:256
kTRUE
const Bool_t kTRUE
Definition: RtypesCore.h:100
RooAbsReal.h
RooMinimizer::setEps
void setEps(Double_t eps)
Change MINUIT epsilon.
Definition: RooMinimizer.cxx:225
RooAbsReal::setEvalErrorLoggingMode
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
Definition: RooAbsReal.cxx:4848
RooAbsArg::DeActivate
@ DeActivate
Definition: RooAbsArg.h:388
RooMsgService.h
RooFitResult::setInitParList
void setInitParList(const RooArgList &list)
Fill the list of initial values of the floating parameters.
Definition: RooFitResult.cxx:157
RooMinimizer::save
RooFitResult * save(const char *name=0, const char *title=0)
Save and return a RooFitResult snapshot of current minimizer status.
Definition: RooMinimizer.cxx:635
RooMinimizer::~RooMinimizer
virtual ~RooMinimizer()
Destructor.
Definition: RooMinimizer.cxx:156
RooFitResult::fillCorrMatrix
void fillCorrMatrix()
Internal utility method to extract the correlation matrix and the global correlation coefficients fro...
Definition: RooFitResult.cxx:714
RooFit.h
RooFit::InputArguments
@ InputArguments
Definition: RooGlobalFunc.h:61
oocoutI
#define oocoutI(o, a)
Definition: RooMsgService.h:45
RooFitResult::setEDM
void setEDM(Double_t val)
Definition: RooFitResult.h:169
RooArgSet.h
RooMinimizer::setErrorLevel
void setErrorLevel(Double_t level)
Set the level for MINUIT error analysis to the given value.
Definition: RooMinimizer.cxx:214
RooMinimizer::setMaxFunctionCalls
void setMaxFunctionCalls(Int_t n)
Change maximum number of likelihood function calss from MINUIT (RooMinimizer default 500 * #parameter...
Definition: RooMinimizer.cxx:200
ClassImp
#define ClassImp(name)
Definition: Rtypes.h:364
Form
char * Form(const char *fmt,...)
RooMinimizer::profileStop
void profileStop()
Stop profiling timer and report results of last session.
Definition: RooMinimizer.cxx:829
RooMinimizer::RooMinimizer
RooMinimizer(RooAbsReal &function)
Construct MINUIT interface to given function.
Definition: RooMinimizer.cxx:110
TGraph.h
TStopwatch.h
RooAbsReal::CollectErrors
@ CollectErrors
Definition: RooAbsReal.h:325
coutE
#define coutE(a)
Definition: RooMsgService.h:33
coutW
#define coutW(a)
Definition: RooMsgService.h:32
RooArgList
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgList.h:21
RooAbsReal::getVal
Double_t getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition: RooAbsReal.h:91
RooFitResult::setFinalParList
void setFinalParList(const RooArgList &list)
Fill the list of final values of the floating parameters.
Definition: RooFitResult.cxx:177
RooMinimizer::setStrategy
void setStrategy(Int_t strat)
Change MINUIT strategy to istrat.
Definition: RooMinimizer.cxx:176
RooMinimizer::contour
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.
Definition: RooMinimizer.cxx:717
RooMinimizer::setOffsetting
void setOffsetting(Bool_t flag)
Enable internal likelihood offsetting for enhanced numeric precision.
Definition: RooMinimizer.cxx:235
RooMinimizer::cleanup
static void cleanup()
Cleanup method called by atexit handler installed by RooSentinel to delete all global heap objects wh...
Definition: RooMinimizer.cxx:88
RooAbsCollection::remove
virtual Bool_t remove(const RooAbsArg &var, Bool_t silent=kFALSE, Bool_t matchByNameOnly=kFALSE)
Remove the specified argument from our list.
Definition: RooAbsCollection.cxx:585
RooAbsCollection::find
RooAbsArg * find(const char *name) const
Find object with given name in list.
Definition: RooAbsCollection.cxx:810
TString::Contains
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:624
RooFitResult::setCovarianceMatrix
void setCovarianceMatrix(TMatrixDSym &V)
Store externally provided correlation matrix in this RooFitResult ;.
Definition: RooFitResult.cxx:1046
RooMinimizer::migrad
Int_t migrad()
Execute MIGRAD.
Definition: RooMinimizer.cxx:344
coutI
#define coutI(a)
Definition: RooMsgService.h:30
TClass.h
RooAbsReal
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:61
RooFitResult::setCovQual
void setCovQual(Int_t val)
Definition: RooFitResult.h:171
RooMinimizer::hesse
Int_t hesse()
Execute HESSE.
Definition: RooMinimizer.cxx:373
TMatrixTSym< Double_t >
RooArgList::at
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition: RooArgList.h:72
FitConfig.h
oocoutE
#define oocoutE(o, a)
Definition: RooMsgService.h:48
RooMinimizer::lastMinuitFit
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
Definition: RooMinimizer.cxx:857
TString
Basic string class.
Definition: TString.h:136
RooRealVar::setRange
void setRange(const char *name, Double_t min, Double_t max)
Set a fit or plotting range.
Definition: RooRealVar.cxx:526
RooAbsReal::clearEvalErrorLog
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
Definition: RooAbsReal.cxx:3795
RooMinimizer::setMaxIterations
void setMaxIterations(Int_t n)
Change maximum number of MINUIT iterations (RooMinimizer default 500 * #parameters)
Definition: RooMinimizer.cxx:188
bool
TIterator
Iterator abstract base class.
Definition: TIterator.h:30
operator+
TString operator+(const TString &s1, const TString &s2)
Use the special concatenation constructor.
Definition: TString.cxx:1499
RooFitResult
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
Definition: RooFitResult.h:40
TMatrixDSym.h
RooMinimizer::fit
RooFitResult * fit(const char *options)
Parse traditional RooAbsPdf::fitTo driver options.
Definition: RooMinimizer.cxx:283
RooMinimizerFcn
RooMinimizerFcn is an interface to the ROOT::Math::IBaseFunctionMultiDim, a function that ROOT's mini...
Definition: RooMinimizerFcn.h:33
RooPlot::addObject
void addObject(TObject *obj, Option_t *drawOptions="", Bool_t invisible=kFALSE)
Add a generic object to this plot.
Definition: RooPlot.cxx:422
RooFitResult::setStatus
void setStatus(Int_t val)
Definition: RooFitResult.h:170
RooFitResult::setConstParList
void setConstParList(const RooArgList &list)
Fill the list of constant parameters.
Definition: RooFitResult.cxx:137
RooMinimizer::_theFitter
static ROOT::Fit::Fitter * _theFitter
Definition: RooMinimizer.h:128
RooMinimizer::applyCovarianceMatrix
void applyCovarianceMatrix(TMatrixDSym &V)
Apply results of given external covariance matrix.
Definition: RooMinimizer.cxx:848
ROOT::Fit::Fitter
Fitter class, entry point for performing all type of fits.
Definition: Fitter.h:77
TMarker.h
size
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
RooAbsPdf.h
Double_t
kFALSE
const Bool_t kFALSE
Definition: RtypesCore.h:101
RooRealVar::setError
void setError(Double_t value)
Definition: RooRealVar.h:62
ROOT::R::function
void function(const Char_t *name_, T fun, const Char_t *docstring=0)
Definition: RExports.h:151
RooPlot.h
RooAbsCollection::createIterator
TIterator * createIterator(Bool_t dir=kIterForward) const
TIterator-style iteration over contained elements.
Definition: RooAbsCollection.h:178
RooPlot
A RooPlot is a plot frame and a container for graphics objects within that frame.
Definition: RooPlot.h:44
RooAbsCollection::add
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
Definition: RooAbsCollection.cxx:455
RooMinimizer::setMinimizerType
void setMinimizerType(const char *type)
Choose the minimiser algorithm.
Definition: RooMinimizer.cxx:245
RooRealVar.h
RooSentinel::activate
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
Definition: RooSentinel.cxx:57
TH2.h
RooAbsCollection::addOwned
virtual Bool_t addOwned(RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
Definition: RooAbsCollection.cxx:403
RooFitResult.h
TIterator::Next
virtual TObject * Next()=0
unsigned int
RooAbsArg::Activate
@ Activate
Definition: RooAbsArg.h:388
TIter::Next
TObject * Next()
Definition: TCollection.h:249
TString::CompareTo
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
Definition: TString.cxx:442
RooMinimizer::minimize
Int_t minimize(const char *type, const char *alg=0)
Minimise the function passed in the constructor.
Definition: RooMinimizer.cxx:312
TGraph
A TGraph is an object made of two arrays X and Y with npoints each.
Definition: TGraph.h:41
RooMinimizer::seek
Int_t seek()
Execute SEEK.
Definition: RooMinimizer.cxx:507
RooMinimizer.h
graph
Definition: graph.py:1
TObject
Mother of all ROOT objects.
Definition: TObject.h:37
RooFit::Parameters
RooCmdArg Parameters(const RooArgSet &params)
Definition: RooGlobalFunc.cxx:247
RooFitResult::setMinNLL
void setMinNLL(Double_t val)
Definition: RooFitResult.h:168
name
char name[80]
Definition: TGX11.cxx:110
RooAbsRealLValue::setConstant
void setConstant(Bool_t value=kTRUE)
Definition: RooAbsRealLValue.h:115
kBlue
@ kBlue
Definition: Rtypes.h:66
TIter
Definition: TCollection.h:233
RooAbsArg
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
Definition: RooAbsArg.h:72
TMarker
Manages Markers.
Definition: TMarker.h:22
TNamed::GetName
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
type
int type
Definition: TGX11.cxx:121
RooAbsReal::PrintErrors
@ PrintErrors
Definition: RooAbsReal.h:325
RooMinimizer::simplex
Int_t simplex()
Execute SIMPLEX.
Definition: RooMinimizer.cxx:536
TString::ToLower
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1150
RooRealVar
RooRealVar represents a variable that can be changed from the outside.
Definition: RooRealVar.h:39
RooFit::Eval
@ Eval
Definition: RooGlobalFunc.h:61
RooArgList.h
RooSentinel.h
RooAbsRealLValue.h
RooMsgService::instance
static RooMsgService & instance()
Return reference to singleton instance.
Definition: RooMsgService.cxx:366
RooMinimizer
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
Definition: RooMinimizer.h:40
RooMinimizer::optimizeConst
void optimizeConst(Int_t flag)
If flag is true, perform constant term optimization on function being minimized.
Definition: RooMinimizer.cxx:603
RooMinimizer::profileStart
void profileStart()
Start profiling timer.
Definition: RooMinimizer.cxx:816
RooAbsArg::isConstant
Bool_t isConstant() const
Check if the "Constant" attribute is set.
Definition: RooAbsArg.h:362
RooMinimizer::setPrintLevel
Int_t setPrintLevel(Int_t newLevel)
Change the MINUIT internal printing level.
Definition: RooMinimizer.cxx:591
RooAbsCollection::sort
void sort(Bool_t reverse=false)
Sort collection using std::sort and name comparison.
Definition: RooAbsCollection.cxx:1435
RooAbsCollection::getSize
Int_t getSize() const
Definition: RooAbsCollection.h:231
RooArgSet
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition: RooArgSet.h:33
RooAbsCollection::snapshot
RooAbsCollection * snapshot(Bool_t deepCopy=kTRUE) const
Take a snap shot of current collection contents.
Definition: RooAbsCollection.cxx:215
RooFitResult::setStatusHistory
void setStatusHistory(std::vector< std::pair< std::string, int > > &hist)
Definition: RooFitResult.h:177
int