ROOT  6.06/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 //
17 // BEGIN_HTML
18 // RooMinimizer is a wrapper class around ROOT::Fit:Fitter that
19 // provides a seamless interface between the minimizer functionality
20 // and the native RooFit interface.
21 // <p>
22 // By default the Minimizer is MINUIT.
23 // <p>
24 // RooMinimizer can minimize any RooAbsReal function with respect to
25 // its parameters. Usual choices for minimization are RooNLLVar
26 // and RooChi2Var
27 // <p>
28 // RooMinimizer has methods corresponding to MINUIT functions like
29 // hesse(), migrad(), minos() etc. In each of these function calls
30 // the state of the MINUIT engine is synchronized with the state
31 // of the RooFit variables: any change in variables, change
32 // in the constant status etc is forwarded to MINUIT prior to
33 // execution of the MINUIT call. Afterwards the RooFit objects
34 // are resynchronized with the output state of MINUIT: changes
35 // parameter values, errors are propagated.
36 // <p>
37 // Various methods are available to control verbosity, profiling,
38 // automatic PDF optimization.
39 // END_HTML
40 //
41 
42 #ifndef __ROOFIT_NOROOMINIMIZER
43 
44 #include "RooFit.h"
45 #include "Riostream.h"
46 
47 #include "TClass.h"
48 
49 #include <fstream>
50 #include <iomanip>
51 
52 #include "TH1.h"
53 #include "TH2.h"
54 #include "TMarker.h"
55 #include "TGraph.h"
56 #include "TStopwatch.h"
57 #include "TDirectory.h"
58 #include "TMatrixDSym.h"
59 
60 #include "RooArgSet.h"
61 #include "RooArgList.h"
62 #include "RooAbsReal.h"
63 #include "RooAbsRealLValue.h"
64 #include "RooRealVar.h"
65 #include "RooAbsPdf.h"
66 #include "RooSentinel.h"
67 #include "RooMsgService.h"
68 #include "RooPlot.h"
69 
70 
71 #include "RooMinimizer.h"
72 #include "RooFitResult.h"
73 
74 #include "Math/Minimizer.h"
75 
76 #if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
77 char* operator+( streampos&, char* );
78 #endif
79 
80 using namespace std;
81 
83 ;
84 
85 ROOT::Fit::Fitter *RooMinimizer::_theFitter = 0 ;
86 
87 
88 
89 ////////////////////////////////////////////////////////////////////////////////
90 /// Cleanup method called by atexit handler installed by RooSentinel
91 /// to delete all global heap objects when the program is terminated
92 
94 {
95  if (_theFitter) {
96  delete _theFitter ;
97  _theFitter =0 ;
98  }
99 }
100 
101 
102 
103 ////////////////////////////////////////////////////////////////////////////////
104 /// Construct MINUIT interface to given function. Function can be anything,
105 /// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
106 /// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
107 /// of a RooNLLVar plus a penalty or constraint term. This class propagates
108 /// all RooFit information (floating parameters, their values and errors)
109 /// to MINUIT before each MINUIT call and propagates all MINUIT information
110 /// back to the RooFit object at the end of each call (updated parameter
111 /// values, their (asymmetric errors) etc. The default MINUIT error level
112 /// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
113 /// value of the input function.
114 
116 {
118 
119  // Store function reference
120  _extV = 0 ;
121  _func = &function ;
122  _optConst = kFALSE ;
123  _verbose = kFALSE ;
124  _profile = kFALSE ;
125  _profileStart = kFALSE ;
126  _printLevel = 1 ;
127  _minimizerType = "Minuit"; // default minimizer
128 
129  if (_theFitter) delete _theFitter ;
130  _theFitter = new ROOT::Fit::Fitter;
131  _fcn = new RooMinimizerFcn(_func,this,_verbose);
132  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
133  setEps(1.0); // default tolerance
134  // default max number of calls
135  _theFitter->Config().MinimizerOptions().SetMaxIterations(500*_fcn->NDim());
136  _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(500*_fcn->NDim());
137 
138  // Shut up for now
139  setPrintLevel(-1) ;
140 
141  // Use +0.5 for 1-sigma errors
142  setErrorLevel(_func->defaultErrorLevel()) ;
143 
144  // Declare our parameters to MINUIT
145  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
146  _optConst,_verbose) ;
147 
148  // Now set default verbosity
150  setPrintLevel(-1) ;
151  } else {
152  setPrintLevel(1) ;
153  }
154 }
155 
156 
157 
158 ////////////////////////////////////////////////////////////////////////////////
159 /// Destructor
160 
162 {
163  if (_extV) {
164  delete _extV ;
165  }
166 
167  if (_fcn) {
168  delete _fcn;
169  }
170 
171 }
172 
173 
174 
175 ////////////////////////////////////////////////////////////////////////////////
176 /// Change MINUIT strategy to istrat. Accepted codes
177 /// are 0,1,2 and represent MINUIT strategies for dealing
178 /// most efficiently with fast FCNs (0), expensive FCNs (2)
179 /// and 'intermediate' FCNs (1)
180 
182 {
183  _theFitter->Config().MinimizerOptions().SetStrategy(istrat);
184 
185 }
186 
187 
188 
189 ////////////////////////////////////////////////////////////////////////////////
190 /// Change maximum number of MINUIT iterations
191 /// (RooMinimizer default 500 * #parameters)
192 
194 {
195  _theFitter->Config().MinimizerOptions().SetMaxIterations(n);
196 }
197 
198 
199 
200 
201 ////////////////////////////////////////////////////////////////////////////////
202 /// Change maximum number of likelihood function calss from MINUIT
203 /// (RooMinimizer default 500 * #parameters)
204 
206 {
207  _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(n);
208 }
209 
210 
211 
212 
213 ////////////////////////////////////////////////////////////////////////////////
214 /// Set the level for MINUIT error analysis to the given
215 /// value. This function overrides the default value
216 /// that is taken in the RooMinimizer constructor from
217 /// the defaultErrorLevel() method of the input function
218 
220 {
221  _theFitter->Config().MinimizerOptions().SetErrorDef(level);
222 
223 }
224 
225 
226 
227 ////////////////////////////////////////////////////////////////////////////////
228 /// Change MINUIT epsilon
229 
231 {
232  _theFitter->Config().MinimizerOptions().SetTolerance(eps);
233 
234 }
235 
236 
237 ////////////////////////////////////////////////////////////////////////////////
238 /// Enable internal likelihood offsetting for enhanced numeric precision
239 
241 {
242  _func->enableOffsetting(flag) ;
243 }
244 
245 
246 
247 
248 ////////////////////////////////////////////////////////////////////////////////
249 /// Choose the minimzer algorithm.
250 
252 {
253  _minimizerType = type;
254 }
255 
256 
257 
258 
259 ////////////////////////////////////////////////////////////////////////////////
260 /// Return underlying ROOT fitter object
261 
263 {
264  return _theFitter ;
265 }
266 
267 
268 ////////////////////////////////////////////////////////////////////////////////
269 /// Return underlying ROOT fitter object
270 
272 {
273  return _theFitter ;
274 }
275 
276 
277 
278 ////////////////////////////////////////////////////////////////////////////////
279 /// Parse traditional RooAbsPdf::fitTo driver options
280 ///
281 /// m - Run Migrad only
282 /// h - Run Hesse to estimate errors
283 /// v - Verbose mode
284 /// l - Log parameters after each Minuit steps to file
285 /// t - Activate profile timer
286 /// r - Save fit result
287 /// 0 - Run Migrad with strategy 0
288 
289 RooFitResult* RooMinimizer::fit(const char* options)
290 {
291  TString opts(options) ;
292  opts.ToLower() ;
293 
294  // Initial configuration
295  if (opts.Contains("v")) setVerbose(1) ;
296  if (opts.Contains("t")) setProfile(1) ;
297  if (opts.Contains("l")) setLogFile(Form("%s.log",_func->GetName())) ;
298  if (opts.Contains("c")) optimizeConst(1) ;
299 
300  // Fitting steps
301  if (opts.Contains("0")) setStrategy(0) ;
302  migrad() ;
303  if (opts.Contains("0")) setStrategy(1) ;
304  if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
305  if (!opts.Contains("m")) minos() ;
306 
307  return (opts.Contains("r")) ? save() : 0 ;
308 }
309 
310 
311 
312 
313 ////////////////////////////////////////////////////////////////////////////////
314 
315 Int_t RooMinimizer::minimize(const char* type, const char* alg)
316 {
317  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
318  _optConst,_verbose) ;
319 
320  _theFitter->Config().SetMinimizer(type,alg);
321 
322  profileStart() ;
325 
326  bool ret = _theFitter->FitFCN(*_fcn);
327  _status = ((ret) ? _theFitter->Result().Status() : -1);
328 
330  profileStop() ;
331  _fcn->BackProp(_theFitter->Result());
332 
333  saveStatus("MINIMIZE",_status) ;
334 
335  return _status ;
336 }
337 
338 
339 
340 ////////////////////////////////////////////////////////////////////////////////
341 /// Execute MIGRAD. Changes in parameter values
342 /// and calculated errors are automatically
343 /// propagated back the RooRealVars representing
344 /// the floating parameters in the MINUIT operation
345 
347 {
348  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
349  _optConst,_verbose) ;
350  profileStart() ;
353 
354  _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migrad");
355  bool ret = _theFitter->FitFCN(*_fcn);
356  _status = ((ret) ? _theFitter->Result().Status() : -1);
357 
359  profileStop() ;
360  _fcn->BackProp(_theFitter->Result());
361 
362  saveStatus("MIGRAD",_status) ;
363 
364  return _status ;
365 }
366 
367 
368 
369 ////////////////////////////////////////////////////////////////////////////////
370 /// Execute HESSE. Changes in parameter values
371 /// and calculated errors are automatically
372 /// propagated back the RooRealVars representing
373 /// the floating parameters in the MINUIT operation
374 
376 {
377  if (_theFitter->GetMinimizer()==0) {
378  coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!"
379  << endl ;
380  _status = -1;
381  }
382  else {
383 
384  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
385  _optConst,_verbose) ;
386  profileStart() ;
389 
390  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
391  bool ret = _theFitter->CalculateHessErrors();
392  _status = ((ret) ? _theFitter->Result().Status() : -1);
393 
395  profileStop() ;
396  _fcn->BackProp(_theFitter->Result());
397 
398  saveStatus("HESSE",_status) ;
399 
400  }
401 
402  return _status ;
403 
404 }
405 
406 ////////////////////////////////////////////////////////////////////////////////
407 /// Execute MINOS. Changes in parameter values
408 /// and calculated errors are automatically
409 /// propagated back the RooRealVars representing
410 /// the floating parameters in the MINUIT operation
411 
413 {
414  if (_theFitter->GetMinimizer()==0) {
415  coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
416  << endl ;
417  _status = -1;
418  }
419  else {
420 
421  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
422  _optConst,_verbose) ;
423  profileStart() ;
426 
427  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
428  bool ret = _theFitter->CalculateMinosErrors();
429  _status = ((ret) ? _theFitter->Result().Status() : -1);
430 
432  profileStop() ;
433  _fcn->BackProp(_theFitter->Result());
434 
435  saveStatus("MINOS",_status) ;
436 
437  }
438 
439  return _status ;
440 
441 }
442 
443 
444 ////////////////////////////////////////////////////////////////////////////////
445 /// Execute MINOS for given list of parameters. Changes in parameter values
446 /// and calculated errors are automatically
447 /// propagated back the RooRealVars representing
448 /// the floating parameters in the MINUIT operation
449 
450 Int_t RooMinimizer::minos(const RooArgSet& minosParamList)
451 {
452  if (_theFitter->GetMinimizer()==0) {
453  coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!"
454  << endl ;
455  _status = -1;
456  }
457  else if (minosParamList.getSize()>0) {
458 
459  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
460  _optConst,_verbose) ;
461  profileStart() ;
464 
465  // get list of parameters for Minos
466  TIterator* aIter = minosParamList.createIterator() ;
467  RooAbsArg* arg ;
468  std::vector<unsigned int> paramInd;
469  while((arg=(RooAbsArg*)aIter->Next())) {
470  RooAbsArg* par = _fcn->GetFloatParamList()->find(arg->GetName());
471  if (par && !par->isConstant()) {
472  Int_t index = _fcn->GetFloatParamList()->index(par);
473  paramInd.push_back(index);
474  }
475  }
476  delete aIter ;
477 
478  if (paramInd.size()) {
479  // set the parameter indeces
480  _theFitter->Config().SetMinosErrors(paramInd);
481 
482  _theFitter->Config().SetMinimizer(_minimizerType.c_str());
483  bool ret = _theFitter->CalculateMinosErrors();
484  _status = ((ret) ? _theFitter->Result().Status() : -1);
485  // to avoid that following minimization computes automatically the Minos errors
486  _theFitter->Config().SetMinosErrors(kFALSE);
487 
488  }
489 
491  profileStop() ;
492  _fcn->BackProp(_theFitter->Result());
493 
494  saveStatus("MINOS",_status) ;
495 
496  }
497 
498  return _status ;
499 }
500 
501 
502 
503 ////////////////////////////////////////////////////////////////////////////////
504 /// Execute SEEK. Changes in parameter values
505 /// and calculated errors are automatically
506 /// propagated back the RooRealVars representing
507 /// the floating parameters in the MINUIT operation
508 
510 {
511  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
512  _optConst,_verbose) ;
513  profileStart() ;
516 
517  _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"seek");
518  bool ret = _theFitter->FitFCN(*_fcn);
519  _status = ((ret) ? _theFitter->Result().Status() : -1);
520 
522  profileStop() ;
523  _fcn->BackProp(_theFitter->Result());
524 
525  saveStatus("SEEK",_status) ;
526 
527  return _status ;
528 }
529 
530 
531 
532 ////////////////////////////////////////////////////////////////////////////////
533 /// Execute SIMPLEX. Changes in parameter values
534 /// and calculated errors are automatically
535 /// propagated back the RooRealVars representing
536 /// the floating parameters in the MINUIT operation
537 
539 {
540  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
541  _optConst,_verbose) ;
542  profileStart() ;
545 
546  _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"simplex");
547  bool ret = _theFitter->FitFCN(*_fcn);
548  _status = ((ret) ? _theFitter->Result().Status() : -1);
549 
551  profileStop() ;
552  _fcn->BackProp(_theFitter->Result());
553 
554  saveStatus("SEEK",_status) ;
555 
556  return _status ;
557 }
558 
559 
560 
561 ////////////////////////////////////////////////////////////////////////////////
562 /// Execute IMPROVE. Changes in parameter values
563 /// and calculated errors are automatically
564 /// propagated back the RooRealVars representing
565 /// the floating parameters in the MINUIT operation
566 
568 {
569  _fcn->Synchronize(_theFitter->Config().ParamsSettings(),
570  _optConst,_verbose) ;
571  profileStart() ;
574 
575  _theFitter->Config().SetMinimizer(_minimizerType.c_str(),"migradimproved");
576  bool ret = _theFitter->FitFCN(*_fcn);
577  _status = ((ret) ? _theFitter->Result().Status() : -1);
578 
580  profileStop() ;
581  _fcn->BackProp(_theFitter->Result());
582 
583  saveStatus("IMPROVE",_status) ;
584 
585  return _status ;
586 }
587 
588 
589 
590 ////////////////////////////////////////////////////////////////////////////////
591 /// Change the MINUIT internal printing level
592 
594 {
595  Int_t ret = _printLevel ;
596  _theFitter->Config().MinimizerOptions().SetPrintLevel(newLevel+1);
597  _printLevel = newLevel+1 ;
598  return ret ;
599 }
600 
601 ////////////////////////////////////////////////////////////////////////////////
602 /// If flag is true, perform constant term optimization on
603 /// function being minimized.
604 
606 {
608 
609  if (_optConst && !flag){
610  if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: deactivating const optimization" << endl ;
611  _func->constOptimizeTestStatistic(RooAbsArg::DeActivate) ;
612  _optConst = flag ;
613  } else if (!_optConst && flag) {
614  if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: activating const optimization" << endl ;
615  _func->constOptimizeTestStatistic(RooAbsArg::Activate,flag>1) ;
616  _optConst = flag ;
617  } else if (_optConst && flag) {
618  if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: const optimization already active" << endl ;
619  } else {
620  if (_printLevel>-1) coutI(Minimization) << "RooMinimizer::optimizeConst: const optimization wasn't active" << endl ;
621  }
622 
624 
625 }
626 
627 
628 
629 ////////////////////////////////////////////////////////////////////////////////
630 /// Save and return a RooFitResult snaphot of current minimizer status.
631 /// This snapshot contains the values of all constant parameters,
632 /// the value of all floating parameters at RooMinimizer construction and
633 /// after the last MINUIT operation, the MINUIT status, variance quality,
634 /// EDM setting, number of calls with evaluation problems, the minimized
635 /// function value and the full correlation matrix
636 
637 RooFitResult* RooMinimizer::save(const char* userName, const char* userTitle)
638 {
639  if (_theFitter->GetMinimizer()==0) {
640  coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!"
641  << endl ;
642  return 0;
643  }
644 
645  TString name,title ;
646  name = userName ? userName : Form("%s", _func->GetName()) ;
647  title = userTitle ? userTitle : Form("%s", _func->GetTitle()) ;
648  RooFitResult* fitRes = new RooFitResult(name,title) ;
649 
650  // Move eventual fixed parameters in floatList to constList
651  Int_t i ;
652  RooArgList saveConstList(*(_fcn->GetConstParamList())) ;
653  RooArgList saveFloatInitList(*(_fcn->GetInitFloatParamList())) ;
654  RooArgList saveFloatFinalList(*(_fcn->GetFloatParamList())) ;
655  for (i=0 ; i<_fcn->GetFloatParamList()->getSize() ; i++) {
656  RooAbsArg* par = _fcn->GetFloatParamList()->at(i) ;
657  if (par->isConstant()) {
658  saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),kTRUE) ;
659  saveFloatFinalList.remove(*par) ;
660  saveConstList.add(*par) ;
661  }
662  }
663  saveConstList.sort() ;
664 
665  fitRes->setConstParList(saveConstList) ;
666  fitRes->setInitParList(saveFloatInitList) ;
667 
668  fitRes->setStatus(_status) ;
669  fitRes->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
670  fitRes->setMinNLL(_theFitter->Result().MinFcnValue()) ;
671  fitRes->setNumInvalidNLL(_fcn->GetNumInvalidNLL()) ;
672  fitRes->setEDM(_theFitter->Result().Edm()) ;
673  fitRes->setFinalParList(saveFloatFinalList) ;
674  if (!_extV) {
675  std::vector<double> globalCC;
676  TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
677  TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
678  for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
679  globalCC.push_back(_theFitter->Result().GlobalCC(ic));
680  for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
681  corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
682  covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
683  }
684  }
685  fitRes->fillCorrMatrix(globalCC,corrs,covs) ;
686  } else {
687  fitRes->setCovarianceMatrix(*_extV) ;
688  }
689 
690  fitRes->setStatusHistory(_statusHistory) ;
691 
692  return fitRes ;
693 
694 }
695 
696 ////////////////////////////////////////////////////////////////////////////////
697 /// Create and draw a TH2 with the error contours in parameters var1 and v2 at up to 6 'sigma' settings
698 /// where 'sigma' is calculated as n*n*errorLevel
699 
701  Double_t n1, Double_t n2, Double_t n3,
702  Double_t n4, Double_t n5, Double_t n6)
703 {
704 
705 
706  RooArgList* params = _fcn->GetFloatParamList() ;
707  RooArgList* paramSave = (RooArgList*) params->snapshot() ;
708 
709  // Verify that both variables are floating parameters of PDF
710  Int_t index1= _fcn->GetFloatParamList()->index(&var1);
711  if(index1 < 0) {
712  coutE(Minimization) << "RooMinimizer::contour(" << GetName()
713  << ") ERROR: " << var1.GetName()
714  << " is not a floating parameter of "
715  << _func->GetName() << endl ;
716  return 0;
717  }
718 
719  Int_t index2= _fcn->GetFloatParamList()->index(&var2);
720  if(index2 < 0) {
721  coutE(Minimization) << "RooMinimizer::contour(" << GetName()
722  << ") ERROR: " << var2.GetName()
723  << " is not a floating parameter of PDF "
724  << _func->GetName() << endl ;
725  return 0;
726  }
727 
728  // create and draw a frame
729  RooPlot* frame = new RooPlot(var1,var2) ;
730 
731  // draw a point at the current parameter values
732  TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
733  frame->addObject(point) ;
734 
735  // check first if a inimizer is available. If not means
736  // the minimization is not done , so do it
737  if (_theFitter->GetMinimizer()==0) {
738  coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!"
739  << endl ;
740  return frame;
741  }
742 
743 
744  // remember our original value of ERRDEF
745  Double_t errdef= _theFitter->GetMinimizer()->ErrorDef();
746 
747  Double_t n[6] ;
748  n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
749  unsigned int npoints(50);
750 
751  for (Int_t ic = 0 ; ic<6 ; ic++) {
752  if(n[ic] > 0) {
753 
754  // set the value corresponding to an n1-sigma contour
755  _theFitter->GetMinimizer()->SetErrorDef(n[ic]*n[ic]*errdef);
756 
757  // calculate and draw the contour
758  Double_t *xcoor = new Double_t[npoints+1];
759  Double_t *ycoor = new Double_t[npoints+1];
760  bool ret = _theFitter->GetMinimizer()->Contour(index1,index2,npoints,xcoor,ycoor);
761 
762  if (!ret) {
763  coutE(Minimization) << "RooMinimizer::contour("
764  << GetName()
765  << ") ERROR: MINUIT did not return a contour graph for n="
766  << n[ic] << endl ;
767  } else {
768  xcoor[npoints] = xcoor[0];
769  ycoor[npoints] = ycoor[0];
770  TGraph* graph = new TGraph(npoints+1,xcoor,ycoor);
771 
772  graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ;
773  graph->SetLineStyle(ic+1) ;
774  graph->SetLineWidth(2) ;
775  graph->SetLineColor(kBlue) ;
776  frame->addObject(graph,"L") ;
777  }
778 
779  delete [] xcoor;
780  delete [] ycoor;
781  }
782  }
783 
784 
785  // restore the original ERRDEF
786  _theFitter->Config().MinimizerOptions().SetErrorDef(errdef);
787 
788  // restore parameter values
789  *params = *paramSave ;
790  delete paramSave ;
791 
792  return frame ;
793 
794 }
795 
796 
797 ////////////////////////////////////////////////////////////////////////////////
798 /// Start profiling timer
799 
801 {
802  if (_profile) {
803  _timer.Start() ;
804  _cumulTimer.Start(_profileStart?kFALSE:kTRUE) ;
805  _profileStart = kTRUE ;
806  }
807 }
808 
809 
810 ////////////////////////////////////////////////////////////////////////////////
811 /// Stop profiling timer and report results of last session
812 
814 {
815  if (_profile) {
816  _timer.Stop() ;
817  _cumulTimer.Stop() ;
818  coutI(Minimization) << "Command timer: " ; _timer.Print() ;
819  coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
820  }
821 }
822 
823 
824 
825 
826 
827 ////////////////////////////////////////////////////////////////////////////////
828 /// Apply results of given external covariance matrix. i.e. propagate its errors
829 /// to all RRV parameter representations and give this matrix instead of the
830 /// HESSE matrix at the next save() call
831 
833 {
834  _extV = (TMatrixDSym*) V.Clone() ;
835  _fcn->ApplyCovarianceMatrix(*_extV);
836 
837 }
838 
839 
840 
842 {
843  // Import the results of the last fit performed, interpreting
844  // the fit parameters as the given varList of parameters.
845 
846  if (_theFitter==0 || _theFitter->GetMinimizer()==0) {
847  oocoutE((TObject*)0,InputArguments) << "RooMinimizer::save: Error, run minimization before!"
848  << endl ;
849  return 0;
850  }
851 
852  // Verify length of supplied varList
853  if (varList.getSize()>0 && varList.getSize()!=Int_t(_theFitter->Result().NTotalParameters())) {
855  << "RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
856  << " or match the number of variables of the last fit ("
857  << _theFitter->Result().NTotalParameters() << ")" << endl ;
858  return 0 ;
859  }
860 
861 
862  // Verify that all members of varList are of type RooRealVar
863  TIterator* iter = varList.createIterator() ;
864  RooAbsArg* arg ;
865  while((arg=(RooAbsArg*)iter->Next())) {
866  if (!dynamic_cast<RooRealVar*>(arg)) {
867  oocoutE((TObject*)0,InputArguments) << "RooMinimizer::lastMinuitFit: ERROR: variable '"
868  << arg->GetName() << "' is not of type RooRealVar" << endl ;
869  return 0 ;
870  }
871  }
872  delete iter ;
873 
874  RooFitResult* res = new RooFitResult("lastMinuitFit","Last MINUIT fit") ;
875 
876  // Extract names of fit parameters
877  // and construct corresponding RooRealVars
878  RooArgList constPars("constPars") ;
879  RooArgList floatPars("floatPars") ;
880 
881  UInt_t i ;
882  for (i = 0; i < _theFitter->Result().NTotalParameters(); ++i) {
883 
884  TString varName(_theFitter->Result().GetParameterName(i));
885  Bool_t isConst(_theFitter->Result().IsParameterFixed(i)) ;
886 
887  Double_t xlo = _theFitter->Config().ParSettings(i).LowerLimit();
888  Double_t xhi = _theFitter->Config().ParSettings(i).UpperLimit();
889  Double_t xerr = _theFitter->Result().Error(i);
890  Double_t xval = _theFitter->Result().Value(i);
891 
892  RooRealVar* var ;
893  if (varList.getSize()==0) {
894 
895  if ((xlo<xhi) && !isConst) {
896  var = new RooRealVar(varName,varName,xval,xlo,xhi) ;
897  } else {
898  var = new RooRealVar(varName,varName,xval) ;
899  }
900  var->setConstant(isConst) ;
901  } else {
902 
903  var = (RooRealVar*) varList.at(i)->Clone() ;
904  var->setConstant(isConst) ;
905  var->setVal(xval) ;
906  if (xlo<xhi) {
907  var->setRange(xlo,xhi) ;
908  }
909 
910  if (varName.CompareTo(var->GetName())) {
911  oocoutI((TObject*)0,Eval) << "RooMinimizer::lastMinuitFit: fit parameter '" << varName
912  << "' stored in variable '" << var->GetName() << "'" << endl ;
913  }
914 
915  }
916 
917  if (isConst) {
918  constPars.addOwned(*var) ;
919  } else {
920  var->setError(xerr) ;
921  floatPars.addOwned(*var) ;
922  }
923  }
924 
925  res->setConstParList(constPars) ;
926  res->setInitParList(floatPars) ;
927  res->setFinalParList(floatPars) ;
928  res->setMinNLL(_theFitter->Result().MinFcnValue()) ;
929  res->setEDM(_theFitter->Result().Edm()) ;
930  res->setCovQual(_theFitter->GetMinimizer()->CovMatrixStatus()) ;
931  res->setStatus(_theFitter->Result().Status()) ;
932  std::vector<double> globalCC;
933  TMatrixDSym corrs(_theFitter->Result().Parameters().size()) ;
934  TMatrixDSym covs(_theFitter->Result().Parameters().size()) ;
935  for (UInt_t ic=0; ic<_theFitter->Result().Parameters().size(); ic++) {
936  globalCC.push_back(_theFitter->Result().GlobalCC(ic));
937  for (UInt_t ii=0; ii<_theFitter->Result().Parameters().size(); ii++) {
938  corrs(ic,ii) = _theFitter->Result().Correlation(ic,ii);
939  covs(ic,ii) = _theFitter->Result().CovMatrix(ic,ii);
940  }
941  }
942  res->fillCorrMatrix(globalCC,corrs,covs) ;
943 
944  return res;
945 
946 }
947 
948 #endif
virtual void SetLineWidth(Width_t lwidth)
Definition: TAttLine.h:57
double par[1]
Definition: unuranDistr.cxx:38
#define coutE(a)
Definition: RooMsgService.h:35
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
RooAbsCollection * snapshot(Bool_t deepCopy=kTRUE) const
Take a snap shot of current collection contents: An owning collection is returned containing clones o...
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:32
Int_t improve()
Execute IMPROVE.
virtual void SetName(const char *name)
Change (i.e.
Definition: TNamed.cxx:128
#define oocoutI(o, a)
Definition: RooMsgService.h:45
void setStatus(Int_t val)
Definition: RooFitResult.h:168
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
Basic string class.
Definition: TString.h:137
Manages Markers.
Definition: TMarker.h:40
void ToLower()
Change string to lower-case.
Definition: TString.cxx:1088
int Int_t
Definition: RtypesCore.h:41
bool Bool_t
Definition: RtypesCore.h:59
const Bool_t kFALSE
Definition: Rtypes.h:92
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:34
void setInitParList(const RooArgList &list)
Fill the list of initial values of the floating parameters.
Iterator abstract base class.
Definition: TIterator.h:32
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:167
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
Definition: TObject.cxx:203
Int_t simplex()
Execute SIMPLEX.
static void setEvalErrorLoggingMode(ErrorLoggingMode m)
Set evaluation error logging mode.
#define oocoutE(o, a)
Definition: RooMsgService.h:48
std::map< std::string, std::string >::const_iterator iter
Definition: TAlienJob.cxx:54
TIterator * createIterator(Bool_t dir=kIterForward) const
RooMinimizer(RooAbsReal &function)
Construct MINUIT interface to given function.
Double_t getVal(const RooArgSet *set=0) const
Definition: RooAbsReal.h:64
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:1437
void setMinNLL(Double_t val)
Definition: RooFitResult.h:166
virtual void setVal(Double_t value)
Set value of variable to 'value'.
Definition: RooRealVar.cxx:202
virtual void SetLineColor(Color_t lcolor)
Definition: TAttLine.h:54
bool minos
Definition: testMinim.cxx:33
void setMaxFunctionCalls(Int_t n)
Change maximum number of likelihood function calss from MINUIT (RooMinimizer default 500 * #parameter...
void function(const char *name_, T fun, const char *docstring=0)
Definition: RExports.h:159
RooAbsArg * find(const char *name) const
Find object with given name in list.
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:94
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.
virtual const char * GetName() const
Returns name of object.
Definition: TNamed.h:51
Bool_t isConstant() const
Definition: RooAbsArg.h:266
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
Definition: RooSentinel.cxx:70
void setConstParList(const RooArgList &list)
Fill the list of constant parameters.
RooAbsArg * at(Int_t idx) const
Definition: RooArgList.h:84
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.
virtual TObject * Clone(const char *newname=0) const
Make a clone of an object using the Streamer facility.
Definition: RooAbsArg.h:75
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)
Definition: TAttLine.h:56
#define name(a, b)
Definition: linkTestLib0.cpp:5
ClassImp(RooMinimizer)
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 'name to [min,max].
Definition: RooRealVar.cxx:446
Mother of all ROOT objects.
Definition: TObject.h:58
Int_t setPrintLevel(Int_t newLevel)
Change the MINUIT internal printing level.
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 'sigma' settings w...
Bool_t Contains(const char *pat, ECaseCompare cmp=kExact) const
Definition: TString.h:567
virtual TObject * Next()=0
A Graph is a graphics object made of two arrays X and Y with npoints each.
Definition: TGraph.h:53
void setCovQual(Int_t val)
Definition: RooFitResult.h:169
static void cleanup()
Cleanup method called by atexit handler installed by RooSentinel to delete all global heap objects wh...
Definition: Rtypes.h:61
Int_t getSize() const
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.
const Bool_t kTRUE
Definition: Rtypes.h:91
RooFitResult * fit(const char *options)
Parse traditional RooAbsPdf::fitTo driver options.
static RooFitResult * lastMinuitFit(const RooArgList &varList=RooArgList())
void profileStart()
Start profiling timer.
const Int_t n
Definition: legend1.C:16
void setError(Double_t value)
Definition: RooRealVar.h:56
Bool_t silentMode() const