Logo ROOT   6.10/09
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 #include "Riostream.h"
43 
44 #include "TClass.h"
45 
46 #include <fstream>
47 #include <iomanip>
48 
49 #include "TH1.h"
50 #include "TH2.h"
51 #include "TMarker.h"
52 #include "TGraph.h"
53 #include "Fit/FitConfig.h"
54 #include "TStopwatch.h"
55 #include "TDirectory.h"
56 #include "TMatrixDSym.h"
57 
58 #include "RooArgSet.h"
59 #include "RooArgList.h"
60 #include "RooAbsReal.h"
61 #include "RooAbsRealLValue.h"
62 #include "RooRealVar.h"
63 #include "RooAbsPdf.h"
64 #include "RooSentinel.h"
65 #include "RooMsgService.h"
66 #include "RooPlot.h"
67 
68 
69 #include "RooMinimizer.h"
70 #include "RooFitResult.h"
71 
72 #include "Math/Minimizer.h"
73 
74 #if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
75 char* operator+( streampos&, char* );
76 #endif
77 
78 using namespace std;
79 
81 ;
82 
84 
85 
86 
87 ////////////////////////////////////////////////////////////////////////////////
88 /// Cleanup method called by atexit handler installed by RooSentinel
89 /// to delete all global heap objects when the program is terminated
90 
92 {
93  if (_theFitter) {
94  delete _theFitter ;
95  _theFitter =0 ;
96  }
97 }
98 
99 
100 
101 ////////////////////////////////////////////////////////////////////////////////
102 /// Construct MINUIT interface to given function. Function can be anything,
103 /// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
104 /// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
105 /// of a RooNLLVar plus a penalty or constraint term. This class propagates
106 /// all RooFit information (floating parameters, their values and errors)
107 /// to MINUIT before each MINUIT call and propagates all MINUIT information
108 /// back to the RooFit object at the end of each call (updated parameter
109 /// values, their (asymmetric errors) etc. The default MINUIT error level
110 /// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
111 /// value of the input function.
112 
114 {
116 
117  // Store function reference
118  _extV = 0 ;
119  _func = &function ;
120  _optConst = kFALSE ;
121  _verbose = kFALSE ;
122  _profile = kFALSE ;
123  _profileStart = kFALSE ;
124  _printLevel = 1 ;
125  _minimizerType = "Minuit"; // default minimizer
126 
127  if (_theFitter) delete _theFitter ;
128  _theFitter = new ROOT::Fit::Fitter;
129  _fcn = new RooMinimizerFcn(_func,this,_verbose);
130  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
131  setEps(1.0); // default tolerance
132  // default max number of calls
133  _theFitter->Config().MinimizerOptions().SetMaxIterations(500*_fcn->NDim());
134  _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(500*_fcn->NDim());
135 
136  // Shut up for now
137  setPrintLevel(-1) ;
138 
139  // Use +0.5 for 1-sigma errors
140  setErrorLevel(_func->defaultErrorLevel()) ;
141 
142  // Declare our parameters to MINUIT
143  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
144  _optConst,_verbose) ;
145 
146  // Now set default verbosity
148  setPrintLevel(-1) ;
149  } else {
150  setPrintLevel(1) ;
151  }
152 }
153 
154 
155 
156 ////////////////////////////////////////////////////////////////////////////////
157 /// Destructor
158 
160 {
161  if (_extV) {
162  delete _extV ;
163  }
164 
165  if (_fcn) {
166  delete _fcn;
167  }
168 
169 }
170 
171 
172 
173 ////////////////////////////////////////////////////////////////////////////////
174 /// Change MINUIT strategy to istrat. Accepted codes
175 /// are 0,1,2 and represent MINUIT strategies for dealing
176 /// most efficiently with fast FCNs (0), expensive FCNs (2)
177 /// and 'intermediate' FCNs (1)
178 
180 {
181  _theFitter->Config().MinimizerOptions().SetStrategy(istrat);
182 
183 }
184 
185 
186 
187 ////////////////////////////////////////////////////////////////////////////////
188 /// Change maximum number of MINUIT iterations
189 /// (RooMinimizer default 500 * #parameters)
190 
192 {
193  _theFitter->Config().MinimizerOptions().SetMaxIterations(n);
194 }
195 
196 
197 
198 
199 ////////////////////////////////////////////////////////////////////////////////
200 /// Change maximum number of likelihood function calss from MINUIT
201 /// (RooMinimizer default 500 * #parameters)
202 
204 {
205  _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(n);
206 }
207 
208 
209 
210 
211 ////////////////////////////////////////////////////////////////////////////////
212 /// Set the level for MINUIT error analysis to the given
213 /// value. This function overrides the default value
214 /// that is taken in the RooMinimizer constructor from
215 /// the defaultErrorLevel() method of the input function
216 
218 {
219  _theFitter->Config().MinimizerOptions().SetErrorDef(level);
220 
221 }
222 
223 
224 
225 ////////////////////////////////////////////////////////////////////////////////
226 /// Change MINUIT epsilon
227 
229 {
230  _theFitter->Config().MinimizerOptions().SetTolerance(eps);
231 
232 }
233 
234 
235 ////////////////////////////////////////////////////////////////////////////////
236 /// Enable internal likelihood offsetting for enhanced numeric precision
237 
239 {
240  _func->enableOffsetting(flag) ;
241 }
242 
243 
244 
245 
246 ////////////////////////////////////////////////////////////////////////////////
247 /// Choose the minimzer algorithm.
248 
250 {
251  _minimizerType = type;
252 }
253 
254 
255 
256 
257 ////////////////////////////////////////////////////////////////////////////////
258 /// Return underlying ROOT fitter object
259 
261 {
262  return _theFitter ;
263 }
264 
265 
266 ////////////////////////////////////////////////////////////////////////////////
267 /// Return underlying ROOT fitter object
268 
270 {
271  return _theFitter ;
272 }
273 
274 
275 
276 ////////////////////////////////////////////////////////////////////////////////
277 /// Parse traditional RooAbsPdf::fitTo driver options
278 ///
279 /// m - Run Migrad only
280 /// h - Run Hesse to estimate errors
281 /// v - Verbose mode
282 /// l - Log parameters after each Minuit steps to file
283 /// t - Activate profile timer
284 /// r - Save fit result
285 /// 0 - Run Migrad with strategy 0
286 
287 RooFitResult* RooMinimizer::fit(const char* options)
288 {
289  TString opts(options) ;
290  opts.ToLower() ;
291 
292  // Initial configuration
293  if (opts.Contains("v")) setVerbose(1) ;
294  if (opts.Contains("t")) setProfile(1) ;
295  if (opts.Contains("l")) setLogFile(Form("%s.log",_func->GetName())) ;
296  if (opts.Contains("c")) optimizeConst(1) ;
297 
298  // Fitting steps
299  if (opts.Contains("0")) setStrategy(0) ;
300  migrad() ;
301  if (opts.Contains("0")) setStrategy(1) ;
302  if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
303  if (!opts.Contains("m")) minos() ;
304 
305  return (opts.Contains("r")) ? save() : 0 ;
306 }
307 
308 
309 
310 
311 ////////////////////////////////////////////////////////////////////////////////
312 
313 Int_t RooMinimizer::minimize(const char* type, const char* alg)
314 {
315  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
316  _optConst,_verbose) ;
317 
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 parameters var1 and v2 at up to 6 'sigma' settings
696 /// where 'sigma' is calculated as n*n*errorLevel
697 
699  Double_t n1, Double_t n2, Double_t n3,
700  Double_t n4, Double_t n5, Double_t n6)
701 {
702 
703 
704  RooArgList* params = _fcn->GetFloatParamList() ;
705  RooArgList* paramSave = (RooArgList*) params->snapshot() ;
706 
707  // Verify that both variables are floating parameters of PDF
708  Int_t index1= _fcn->GetFloatParamList()->index(&var1);
709  if(index1 < 0) {
710  coutE(Minimization) << "RooMinimizer::contour(" << GetName()
711  << ") ERROR: " << var1.GetName()
712  << " is not a floating parameter of "
713  << _func->GetName() << endl ;
714  return 0;
715  }
716 
717  Int_t index2= _fcn->GetFloatParamList()->index(&var2);
718  if(index2 < 0) {
719  coutE(Minimization) << "RooMinimizer::contour(" << GetName()
720  << ") ERROR: " << var2.GetName()
721  << " is not a floating parameter of PDF "
722  << _func->GetName() << endl ;
723  return 0;
724  }
725 
726  // create and draw a frame
727  RooPlot* frame = new RooPlot(var1,var2) ;
728 
729  // draw a point at the current parameter values
730  TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
731  frame->addObject(point) ;
732 
733  // check first if a inimizer is available. If not means
734  // the minimization is not done , so do it
735  if (_theFitter->GetMinimizer()==0) {
736  coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
737  << endl ;
738  return frame;
739  }
740 
741 
742  // remember our original value of ERRDEF
743  Double_t errdef= _theFitter->GetMinimizer()->ErrorDef();
744 
745  Double_t n[6] ;
746  n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
747  unsigned int npoints(50);
748 
749  for (Int_t ic = 0 ; ic<6 ; ic++) {
750  if(n[ic] > 0) {
751 
752  // set the value corresponding to an n1-sigma contour
753  _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
754 
755  // calculate and draw the contour
756  Double_t *xcoor = new Double_t[npoints+1];
757  Double_t *ycoor = new Double_t[npoints+1];
758  bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
759 
760  if (!ret) {
761  coutE(Minimization) << "RooMinimizer::contour("
762  << GetName()
763  << ") ERROR: MINUIT did not return a contour graph for n="
764  << n[ic] << endl ;
765  } else {
766  xcoor[npoints] = xcoor[0];
767  ycoor[npoints] = ycoor[0];
768  TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
769 
770  graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ;
771  graph->SetLineStyle(ic+1) ;
772  graph->SetLineWidth(2) ;
773  graph->SetLineColor(kBlue) ;
774  frame->addObject(graph,"L") ;
775  }
776 
777  delete [] xcoor;
778  delete [] ycoor;
779  }
780  }
781 
782 
783  // restore the original ERRDEF
784  _theFitter->Config().MinimizerOptions().SetErrorDef(errdef);
785 
786  // restore parameter values
787  *params = *paramSave ;
788  delete paramSave ;
789 
790  return frame ;
791 
792 }
793 
794 
795 ////////////////////////////////////////////////////////////////////////////////
796 /// Start profiling timer
797 
799 {
800  if (_profile) {
801  _timer.Start() ;
802  _cumulTimer.Start(_profileStart?kFALSE:kTRUE) ;
803  _profileStart = kTRUE ;
804  }
805 }
806 
807 
808 ////////////////////////////////////////////////////////////////////////////////
809 /// Stop profiling timer and report results of last session
810 
812 {
813  if (_profile) {
814  _timer.Stop() ;
815  _cumulTimer.Stop() ;
816  coutI(Minimization) << "Command timer: " ; _timer.Print() ;
817  coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
818  }
819 }
820 
821 
822 
823 
824 
825 ////////////////////////////////////////////////////////////////////////////////
826 /// Apply results of given external covariance matrix. i.e. propagate its errors
827 /// to all RRV parameter representations and give this matrix instead of the
828 /// HESSE matrix at the next save() call
829 
831 {
832  _extV = (TMatrixDSym*) V.Clone() ;
833  _fcn->ApplyCovarianceMatrix(*_extV);
834 
835 }
836 
837 
838 
840 {
841  // Import the results of the last fit performed, interpreting
842  // the fit parameters as the given varList of parameters.
843 
844  if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
845  oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
846  << endl ;
847  return 0;
848  }
849 
850  // Verify length of supplied varList
851  if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
853  << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
854  << " or match the number of variables of the last fit ("
855  << _theFitter->Result().NTotalParameters() << ")" << endl ;
856  return 0 ;
857  }
858 
859 
860  // Verify that all members of varList are of type RooRealVar
861  TIterator* iter = varList.createIterator() ;
862  RooAbsArg* arg ;
863  while((arg=(RooAbsArg*)iter->Next())) {
864  if (!dynamic_cast<RooRealVar*>(arg)) {
865  oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
866  << arg->GetName() << "' is not of type RooRealVar" << endl ;
867  return 0 ;
868  }
869  }
870  delete iter ;
871 
872  RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
873 
874  // Extract names of fit parameters
875  // and construct corresponding RooRealVars
876  RooArgList constPars("constPars") ;
877  RooArgList floatPars("floatPars") ;
878 
879  UInt_t i ;
880  for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
881 
882  TString varName(_theFitter->Result().GetParameterName(i));
883  Bool_t isConst(_theFitter->Result().IsParameterFixed(i)) ;
884 
885  Double_t xlo = _theFitter->Config().ParSettings(i).LowerLimit();
886  Double_t xhi = _theFitter->Config().ParSettings(i).UpperLimit();
887  Double_t xerr = _theFitter->Result().Error(i);
888  Double_t xval = _theFitter->Result().Value(i);
889 
890  RooRealVar* var ;
891  if (varList.getSize()==0) {
892 
893  if ((xlo<xhi) && !isConst) {
894  var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
895  } else {
896  var = new RooRealVar(varName,varName,xval) ;
897  }
898  var->setConstant(isConst) ;
899  } else {
900 
901  var = (RooRealVar*) varList.at(i)->Clone() ;
902  var->setConstant(isConst) ;
903  var->setVal(xval) ;
904  if (xlo<xhi) {
905  var->setRange(xlo,xhi) ;
906  }
907 
908  if (varName.CompareTo(var->GetName())) {
909  oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
910  << "' stored in variable '" << var->GetName() << "'" << endl ;
911  }
912 
913  }
914 
915  if (isConst) {
916  constPars.addOwned(*var) ;
917  } else {
918  var->setError(xerr) ;
919  floatPars.addOwned(*var) ;
920  }
921  }
922 
923  res->setConstParList(constPars) ;
924  res->setInitParList(floatPars) ;
925  res->setFinalParList(floatPars) ;
926  res->setMinNLL(_theFitter->Result().MinFcnValue()) ;
927  res->setEDM(_theFitter->Result().Edm()) ;
928  res->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
929  res->setStatus(_theFitter->Result().Status()) ;
930  std::vector<double> globalCC;
931  TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
932  TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
933  for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
934  globalCC.push_back(_theFitter->Result().GlobalCC(ic));
935  for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
936  corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
937  covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
938  }
939  }
940  res->fillCorrMatrix(globalCC,corrs,covs) ;
941 
942  return res;
943 
944 }
945 
946 #endif
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:47
std::string GetName(const std::string &scope_name)
Definition: Cppyy.cxx:145
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition: TAttLine.h:43
double par[1]
Definition: unuranDistr.cxx:38
TIterator * createIterator(Bool_t dir=kIterForward) const
#define coutE(a)
Definition: RooMsgService.h:34
virtual Bool_t add(const RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
void sort(Bool_t reverse=kFALSE)
Definition: RooArgList.h:72
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.
virtual ~RooMinimizer()
Destructor.
void addObject(TObject *obj, Option_t *drawOptions="", Bool_t invisible=kFALSE)
Add a generic object to this plot.
Definition: RooPlot.cxx:392
virtual Bool_t addOwned(RooAbsArg &var, Bool_t silent=kFALSE)
Add the specified argument to list.
#define coutI(a)
Definition: RooMsgService.h:31
Double_t getVal(const RooArgSet *set=0) const
Definition: RooAbsReal.h:64
Int_t improve()
Execute IMPROVE.
virtual void SetName(const char *name)
Set the name of the TNamed.
Definition: TNamed.cxx:131
#define oocoutI(o, a)
Definition: RooMsgService.h:44
void setStatus(Int_t val)
Definition: RooFitResult.h:167
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
Manages Markers.
Definition: TMarker.h:23
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:75
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:33
void setInitParList(const RooArgList &list)
Fill the list of initial values of the floating parameters.
Iterator abstract base class.
Definition: TIterator.h:30
void setMinimizerType(const char *type)
Choose the minimzer 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:166
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:47
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:146
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:1448
RooRealVar represents a fundamental (non-derived) real valued object.
Definition: RooRealVar.h:36
void setMinNLL(Double_t val)
Definition: RooFitResult.h:165
virtual void setVal(Double_t value)
Set value of variable to &#39;value&#39;.
Definition: RooRealVar.cxx:205
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition: TAttLine.h:40
bool minos
Definition: testMinim.cxx:33
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: An owning collection is returned containing clones o...
RooAbsArg * at(Int_t idx) const
Definition: RooArgList.h:84
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
unsigned int UInt_t
Definition: RtypesCore.h:42
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:41
const Bool_t kFALSE
Definition: RtypesCore.h:92
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
Definition: RooSentinel.cxx:71
void setConstParList(const RooArgList &list)
Fill the list of constant parameters.
#define ClassImp(name)
Definition: Rtypes.h:336
RooAbsArg * find(const char *name) const
Find object with given name in list.
double Double_t
Definition: RtypesCore.h:55
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
Definition: RooAbsReal.h:53
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
Int_t minimize(const char *type, const char *alg=0)
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition: TAttLine.h:42
void profileStop()
Stop profiling timer and report results of last session.
void setRange(const char *name, Double_t min, Double_t max)
Set range named &#39;name to [min,max].
Definition: RooRealVar.cxx:449
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:151
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.
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)
Create and draw a TH2 with the error contours in parameters var1 and v2 at up to 6 &#39;sigma&#39; settings w...
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 Graph is a graphics object made of two arrays X and Y with npoints each.
Definition: TGraph.h:41
void setCovQual(Int_t val)
Definition: RooFitResult.h:168
static void cleanup()
Cleanup method called by atexit handler installed by RooSentinel to delete all global heap objects wh...
Definition: Rtypes.h:56
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:66
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:91
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
void profileStart()
Start profiling timer.
const Int_t n
Definition: legend1.C:16
Bool_t isConstant() const
Definition: RooAbsArg.h:266
void setError(Double_t value)
Definition: RooRealVar.h:55