Logo ROOT   6.30.04
Reference Guide
 All Namespaces Files Pages
RooMinuit.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  * *
9  * Copyright (c) 2000-2005, Regents of the University of California *
10  * and Stanford University. All rights reserved. *
11  * *
12  * Redistribution and use in source and binary forms, *
13  * with or without modification, are permitted according to the terms *
14  * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
15  *****************************************************************************/
16 
17 /**
18 \file RooMinuit.cxx
19 \class RooMinuit
20 \ingroup Roofitcore
21 
22 RooMinuit is a wrapper class around TFitter/TMinuit that
23 provides a seamless interface between the MINUIT functionality
24 and the native RooFit interface.
25 RooMinuit can minimize any RooAbsReal function with respect to
26 its parameters. Usual choices for minimization are RooNLLVar
27 and RooChi2Var
28 RooMinuit 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 Various methods are available to control verbosity, profiling,
37 automatic PDF optimization.
38 **/
39 
40 #include "RooFit.h"
41 #include "Riostream.h"
42 
43 #include "TClass.h"
44 
45 #include <fstream>
46 #include <iomanip>
47 #include "TH1.h"
48 #include "TH2.h"
49 #include "TMarker.h"
50 #include "TGraph.h"
51 #include "TStopwatch.h"
52 #include "TFitter.h"
53 #include "TMinuit.h"
54 #include "TDirectory.h"
55 #include "TMatrixDSym.h"
56 #include "RooMinuit.h"
57 #include "RooArgSet.h"
58 #include "RooArgList.h"
59 #include "RooAbsReal.h"
60 #include "RooAbsRealLValue.h"
61 #include "RooRealVar.h"
62 #include "RooFitResult.h"
63 #include "RooAbsPdf.h"
64 #include "RooSentinel.h"
65 #include "RooMsgService.h"
66 #include "RooPlot.h"
67 
68 
69 
70 #if (__GNUC__==3&&__GNUC_MINOR__==2&&__GNUC_PATCHLEVEL__==3)
71 char* operator+( streampos&, char* );
72 #endif
73 
74 using namespace std;
75 
76 ClassImp(RooMinuit);
77 ;
78 
79 TVirtualFitter *RooMinuit::_theFitter = 0 ;
80 
81 
82 
83 ////////////////////////////////////////////////////////////////////////////////
84 /// Cleanup method called by atexit handler installed by RooSentinel
85 /// to delete all global heap objects when the program is terminated
86 
87 void RooMinuit::cleanup()
88 {
89  if (_theFitter) {
90  delete _theFitter ;
91  _theFitter =0 ;
92  }
93 }
94 
95 
96 
97 ////////////////////////////////////////////////////////////////////////////////
98 /// Construct MINUIT interface to given function. Function can be anything,
99 /// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
100 /// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
101 /// of a RooNLLVar plus a penalty or constraint term. This class propagates
102 /// all RooFit information (floating parameters, their values and errors)
103 /// to MINUIT before each MINUIT call and propagates all MINUIT information
104 /// back to the RooFit object at the end of each call (updated parameter
105 /// values, their (asymmetric errors) etc. The default MINUIT error level
106 /// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
107 /// value of the input function.
108 
109 RooMinuit::RooMinuit(RooAbsReal& function)
110 {
111  RooSentinel::activate() ;
112 
113  // Store function reference
114  _evalCounter = 0 ;
115  _extV = 0 ;
116  _func = &function ;
117  _logfile = 0 ;
118  _optConst = kFALSE ;
119  _verbose = kFALSE ;
120  _profile = kFALSE ;
121  _handleLocalErrors = kTRUE ;
122  _printLevel = 1 ;
123  _printEvalErrors = 10 ;
124  _warnLevel = -999 ;
125  _maxEvalMult = 500 ;
126  _doEvalErrorWall = kTRUE ;
127 
128  // Examine parameter list
129  RooArgSet* paramSet = function.getParameters(RooArgSet()) ;
130  RooArgList paramList(*paramSet) ;
131  delete paramSet ;
132 
133  _floatParamList = (RooArgList*) paramList.selectByAttrib("Constant",kFALSE) ;
134  if (_floatParamList->getSize()>1) {
135  _floatParamList->sort() ;
136  }
137  _floatParamList->setName("floatParamList") ;
138 
139  _constParamList = (RooArgList*) paramList.selectByAttrib("Constant",kTRUE) ;
140  if (_constParamList->getSize()>1) {
141  _constParamList->sort() ;
142  }
143  _constParamList->setName("constParamList") ;
144 
145  // Remove all non-RooRealVar parameters from list (MINUIT cannot handle them)
146  TIterator* pIter = _floatParamList->createIterator() ;
147  RooAbsArg* arg ;
148  while((arg=(RooAbsArg*)pIter->Next())) {
149  if (!arg->IsA()->InheritsFrom(RooAbsRealLValue::Class())) {
150  coutW(Minimization) << "RooMinuit::RooMinuit: removing parameter " << arg->GetName()
151  << " from list because it is not of type RooRealVar" << endl ;
152  _floatParamList->remove(*arg) ;
153  }
154  }
155  _nPar = _floatParamList->getSize() ;
156  delete pIter ;
157 
158  updateFloatVec() ;
159 
160  // Save snapshot of initial lists
161  _initFloatParamList = (RooArgList*) _floatParamList->snapshot(kFALSE) ;
162  _initConstParamList = (RooArgList*) _constParamList->snapshot(kFALSE) ;
163 
164  // Initialize MINUIT
165  Int_t nPar= _floatParamList->getSize() + _constParamList->getSize() ;
166  if (_theFitter) delete _theFitter ;
167  _theFitter = new TFitter(nPar*2+1) ; //WVE Kludge, nPar*2 works around TMinuit memory allocation bug
168  _theFitter->SetObjectFit(this) ;
169 
170  // Shut up for now
171  setPrintLevel(-1) ;
172  _theFitter->Clear();
173 
174  // Tell MINUIT to use our global glue function
175  _theFitter->SetFCN(RooMinuitGlue);
176 
177  // Use +0.5 for 1-sigma errors
178  setErrorLevel(function.defaultErrorLevel()) ;
179 
180  // Declare our parameters to MINUIT
181  synchronize(kFALSE) ;
182 
183  // Reset the *largest* negative log-likelihood value we have seen so far
184  _maxFCN= -1e30 ;
185  _numBadNLL = 0 ;
186 
187  // Now set default verbosity
188  if (RooMsgService::instance().silentMode()) {
189  setWarnLevel(-1) ;
190  setPrintLevel(-1) ;
191  } else {
192  setWarnLevel(1) ;
193  setPrintLevel(1) ;
194  }
195 }
196 
197 
198 
199 ////////////////////////////////////////////////////////////////////////////////
200 /// Destructor
201 
202 RooMinuit::~RooMinuit()
203 {
204  delete _floatParamList ;
205  delete _initFloatParamList ;
206  delete _constParamList ;
207  delete _initConstParamList ;
208  if (_extV) {
209  delete _extV ;
210  }
211 }
212 
213 
214 
215 ////////////////////////////////////////////////////////////////////////////////
216 /// Change MINUIT strategy to istrat. Accepted codes
217 /// are 0,1,2 and represent MINUIT strategies for dealing
218 /// most efficiently with fast FCNs (0), expensive FCNs (2)
219 /// and 'intermediate' FCNs (1)
220 
221 void RooMinuit::setStrategy(Int_t istrat)
222 {
223  Double_t stratArg(istrat) ;
224  _theFitter->ExecuteCommand("SET STR",&stratArg,1) ;
225 }
226 
227 
228 
229 ////////////////////////////////////////////////////////////////////////////////
230 /// Set the level for MINUIT error analysis to the given
231 /// value. This function overrides the default value
232 /// that is taken in the RooMinuit constructor from
233 /// the defaultErrorLevel() method of the input function
234 
235 void RooMinuit::setErrorLevel(Double_t level)
236 {
237  _theFitter->ExecuteCommand("SET ERR",&level,1);
238 }
239 
240 
241 
242 ////////////////////////////////////////////////////////////////////////////////
243 /// Change MINUIT epsilon
244 
245 void RooMinuit::setEps(Double_t eps)
246 {
247  _theFitter->ExecuteCommand("SET EPS",&eps,1) ;
248 }
249 
250 
251 
252 ////////////////////////////////////////////////////////////////////////////////
253 /// Enable internal likelihood offsetting for enhanced numeric precision
254 
255 void RooMinuit::setOffsetting(Bool_t flag)
256 {
257  _func->enableOffsetting(flag) ;
258 }
259 
260 
261 ////////////////////////////////////////////////////////////////////////////////
262 /// Parse traditional RooAbsPdf::fitTo driver options
263 ///
264 /// s - Run Hesse first to estimate initial step size
265 /// m - Run Migrad only
266 /// h - Run Hesse to estimate errors
267 /// v - Verbose mode
268 /// l - Log parameters after each Minuit steps to file
269 /// t - Activate profile timer
270 /// r - Save fit result
271 /// 0 - Run Migrad with strategy 0
272 
273 RooFitResult* RooMinuit::fit(const char* options)
274 {
275  if (_floatParamList->getSize()==0) {
276  return 0 ;
277  }
278 
279  _theFitter->SetObjectFit(this) ;
280 
281  TString opts(options) ;
282  opts.ToLower() ;
283 
284  // Initial configuration
285  if (opts.Contains("v")) setVerbose(1) ;
286  if (opts.Contains("t")) setProfile(1) ;
287  if (opts.Contains("l")) setLogFile(Form("%s.log",_func->GetName())) ;
288  if (opts.Contains("c")) optimizeConst(1) ;
289 
290  // Fitting steps
291  if (opts.Contains("s")) hesse() ;
292  if (opts.Contains("0")) setStrategy(0) ;
293  migrad() ;
294  if (opts.Contains("0")) setStrategy(1) ;
295  if (opts.Contains("h")||!opts.Contains("m")) hesse() ;
296  if (!opts.Contains("m")) minos() ;
297 
298  return (opts.Contains("r")) ? save() : 0 ;
299 }
300 
301 
302 
303 ////////////////////////////////////////////////////////////////////////////////
304 /// Execute MIGRAD. Changes in parameter values
305 /// and calculated errors are automatically
306 /// propagated back the RooRealVars representing
307 /// the floating parameters in the MINUIT operation
308 
309 Int_t RooMinuit::migrad()
310 {
311  if (_floatParamList->getSize()==0) {
312  return -1 ;
313  }
314 
315  _theFitter->SetObjectFit(this) ;
316 
317  Double_t arglist[2];
318  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
319  arglist[1]= 1.0; // tolerance
320 
321  synchronize(_verbose) ;
322  profileStart() ;
323  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
324  RooAbsReal::clearEvalErrorLog() ;
325  _status= _theFitter->ExecuteCommand("MIGRAD",arglist,2);
326  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
327  profileStop() ;
328  backProp() ;
329 
330  saveStatus("MIGRAD",_status) ;
331 
332  return _status ;
333 }
334 
335 
336 
337 ////////////////////////////////////////////////////////////////////////////////
338 /// Execute HESSE. Changes in parameter values
339 /// and calculated errors are automatically
340 /// propagated back the RooRealVars representing
341 /// the floating parameters in the MINUIT operation
342 
343 Int_t RooMinuit::hesse()
344 {
345  if (_floatParamList->getSize()==0) {
346  return -1 ;
347  }
348 
349  _theFitter->SetObjectFit(this) ;
350 
351  Double_t arglist[2];
352  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
353 
354  synchronize(_verbose) ;
355  profileStart() ;
356  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
357  RooAbsReal::clearEvalErrorLog() ;
358  _status= _theFitter->ExecuteCommand("HESSE",arglist,1);
359  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
360  profileStop() ;
361  backProp() ;
362 
363  saveStatus("HESSE",_status) ;
364 
365  return _status ;
366 }
367 
368 
369 
370 ////////////////////////////////////////////////////////////////////////////////
371 /// Execute MINOS. Changes in parameter values
372 /// and calculated errors are automatically
373 /// propagated back the RooRealVars representing
374 /// the floating parameters in the MINUIT operation
375 
376 Int_t RooMinuit::minos()
377 {
378  if (_floatParamList->getSize()==0) {
379  return -1 ;
380  }
381 
382  _theFitter->SetObjectFit(this) ;
383 
384  Double_t arglist[2];
385  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
386 
387  synchronize(_verbose) ;
388  profileStart() ;
389  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
390  RooAbsReal::clearEvalErrorLog() ;
391  _status= _theFitter->ExecuteCommand("MINOS",arglist,1);
392  // check also the status of Minos looking at fCstatu
393  if (_status == 0 && gMinuit->fCstatu != "SUCCESSFUL") {
394  if (gMinuit->fCstatu == "FAILURE" ||
395  gMinuit->fCstatu == "PROBLEMS") _status = 5;
396  _status = 6;
397  }
398 
399  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
400  profileStop() ;
401  backProp() ;
402 
403  saveStatus("MINOS",_status) ;
404  return _status ;
405 }
406 
407 
408 // added FMV, 08/18/03
409 
410 ////////////////////////////////////////////////////////////////////////////////
411 /// Execute MINOS for given list of parameters. Changes in parameter values
412 /// and calculated errors are automatically
413 /// propagated back the RooRealVars representing
414 /// the floating parameters in the MINUIT operation
415 
416 Int_t RooMinuit::minos(const RooArgSet& minosParamList)
417 {
418  if (_floatParamList->getSize()==0) {
419  return -1 ;
420  }
421 
422  _theFitter->SetObjectFit(this) ;
423 
424  Int_t nMinosPar(0) ;
425  Double_t* arglist = new Double_t[_nPar+1];
426 
427  if (minosParamList.getSize()>0) {
428  TIterator* aIter = minosParamList.createIterator() ;
429  RooAbsArg* arg ;
430  while((arg=(RooAbsArg*)aIter->Next())) {
431  RooAbsArg* par = _floatParamList->find(arg->GetName());
432  if (par && !par->isConstant()) {
433  Int_t index = _floatParamList->index(par);
434  nMinosPar++;
435  arglist[nMinosPar]=index+1;
436  }
437  }
438  delete aIter ;
439  }
440  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
441 
442  synchronize(_verbose) ;
443  profileStart() ;
444  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
445  RooAbsReal::clearEvalErrorLog() ;
446  _status= _theFitter->ExecuteCommand("MINOS",arglist,1+nMinosPar);
447  // check also the status of Minos looking at fCstatu
448  if (_status == 0 && gMinuit->fCstatu != "SUCCESSFUL") {
449  if (gMinuit->fCstatu == "FAILURE" ||
450  gMinuit->fCstatu == "PROBLEMS") _status = 5;
451  _status = 6;
452  }
453  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
454  profileStop() ;
455  backProp() ;
456 
457  delete[] arglist ;
458 
459  saveStatus("MINOS",_status) ;
460 
461  return _status ;
462 }
463 
464 
465 
466 ////////////////////////////////////////////////////////////////////////////////
467 /// Execute SEEK. Changes in parameter values
468 /// and calculated errors are automatically
469 /// propagated back the RooRealVars representing
470 /// the floating parameters in the MINUIT operation
471 
472 Int_t RooMinuit::seek()
473 {
474  if (_floatParamList->getSize()==0) {
475  return -1 ;
476  }
477 
478  _theFitter->SetObjectFit(this) ;
479 
480  Double_t arglist[2];
481  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
482 
483  synchronize(_verbose) ;
484  profileStart() ;
485  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
486  RooAbsReal::clearEvalErrorLog() ;
487  _status= _theFitter->ExecuteCommand("SEEK",arglist,1);
488  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
489  profileStop() ;
490  backProp() ;
491 
492  saveStatus("SEEK",_status) ;
493 
494  return _status ;
495 }
496 
497 
498 
499 ////////////////////////////////////////////////////////////////////////////////
500 /// Execute SIMPLEX. Changes in parameter values
501 /// and calculated errors are automatically
502 /// propagated back the RooRealVars representing
503 /// the floating parameters in the MINUIT operation
504 
505 Int_t RooMinuit::simplex()
506 {
507  if (_floatParamList->getSize()==0) {
508  return -1 ;
509  }
510 
511  _theFitter->SetObjectFit(this) ;
512 
513  Double_t arglist[2];
514  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
515  arglist[1]= 1.0; // tolerance
516 
517  synchronize(_verbose) ;
518  profileStart() ;
519  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
520  RooAbsReal::clearEvalErrorLog() ;
521  _status= _theFitter->ExecuteCommand("SIMPLEX",arglist,2);
522  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
523  profileStop() ;
524  backProp() ;
525 
526  saveStatus("SIMPLEX",_status) ;
527 
528  return _status ;
529 }
530 
531 
532 
533 ////////////////////////////////////////////////////////////////////////////////
534 /// Execute IMPROVE. Changes in parameter values
535 /// and calculated errors are automatically
536 /// propagated back the RooRealVars representing
537 /// the floating parameters in the MINUIT operation
538 
539 Int_t RooMinuit::improve()
540 {
541  if (_floatParamList->getSize()==0) {
542  return -1 ;
543  }
544 
545  _theFitter->SetObjectFit(this) ;
546 
547  Double_t arglist[2];
548  arglist[0]= _maxEvalMult*_nPar; // maximum iterations
549 
550  synchronize(_verbose) ;
551  profileStart() ;
552  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
553  RooAbsReal::clearEvalErrorLog() ;
554  _status= _theFitter->ExecuteCommand("IMPROVE",arglist,1);
555  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
556  profileStop() ;
557  backProp() ;
558 
559  saveStatus("IMPROVE",_status) ;
560 
561  return _status ;
562 }
563 
564 
565 
566 ////////////////////////////////////////////////////////////////////////////////
567 /// Change the MINUIT internal printing level
568 
569 Int_t RooMinuit::setPrintLevel(Int_t newLevel)
570 {
571  Int_t ret = _printLevel ;
572  Double_t arg(newLevel) ;
573  _theFitter->ExecuteCommand("SET PRINT",&arg,1);
574  _printLevel = newLevel ;
575  return ret ;
576 }
577 
578 
579 
580 ////////////////////////////////////////////////////////////////////////////////
581 /// Instruct MINUIT to suppress warnings
582 
583 void RooMinuit::setNoWarn()
584 {
585  Double_t arg(0) ;
586  _theFitter->ExecuteCommand("SET NOWARNINGS",&arg,1);
587  _warnLevel = -1 ;
588 }
589 
590 
591 
592 ////////////////////////////////////////////////////////////////////////////////
593 /// Set MINUIT warning level to given level
594 
595 Int_t RooMinuit::setWarnLevel(Int_t newLevel)
596 {
597  if (newLevel==_warnLevel) {
598  return _warnLevel ;
599  }
600 
601  Int_t ret = _warnLevel ;
602  Double_t arg(newLevel) ;
603 
604  if (newLevel>=0) {
605  _theFitter->ExecuteCommand("SET WARNINGS",&arg,1);
606  } else {
607  Double_t arg2(0) ;
608  _theFitter->ExecuteCommand("SET NOWARNINGS",&arg2,1);
609  }
610  _warnLevel = newLevel ;
611 
612  return ret ;
613 }
614 
615 
616 
617 ////////////////////////////////////////////////////////////////////////////////
618 /// Internal function to synchronize TMinuit with current
619 /// information in RooAbsReal function parameters
620 
621 Bool_t RooMinuit::synchronize(Bool_t verbose)
622 {
623  Int_t oldPrint = setPrintLevel(-1) ;
624  gMinuit->fNwrmes[0] = 0; // to clear buffer
625  Int_t oldWarn = setWarnLevel(-1) ;
626 
627  Bool_t constValChange(kFALSE) ;
628  Bool_t constStatChange(kFALSE) ;
629 
630  Int_t index(0) ;
631 
632  // Handle eventual migrations from constParamList -> floatParamList
633  for(index= 0; index < _constParamList->getSize() ; index++) {
634  RooRealVar *par= dynamic_cast<RooRealVar*>(_constParamList->at(index)) ;
635  if (!par) continue ;
636 
637  RooRealVar *oldpar= dynamic_cast<RooRealVar*>(_initConstParamList->at(index)) ;
638  if (!oldpar) continue ;
639 
640  // Test if constness changed
641  if (!par->isConstant()) {
642 
643  // Remove from constList, add to floatList
644  _constParamList->remove(*par) ;
645  _floatParamList->add(*par) ;
646  _initFloatParamList->addClone(*oldpar) ;
647  _initConstParamList->remove(*oldpar) ;
648  constStatChange=kTRUE ;
649  _nPar++ ;
650 
651  if (verbose) {
652  coutI(Minimization) << "RooMinuit::synchronize: parameter " << par->GetName() << " is now floating." << endl ;
653  }
654  }
655 
656  // Test if value changed
657  if (par->getVal()!= oldpar->getVal()) {
658  constValChange=kTRUE ;
659  if (verbose) {
660  coutI(Minimization) << "RooMinuit::synchronize: value of constant parameter " << par->GetName()
661  << " changed from " << oldpar->getVal() << " to " << par->getVal() << endl ;
662  }
663  }
664 
665  }
666 
667  // Update reference list
668  *_initConstParamList = *_constParamList ;
669 
670 
671  // Synchronize MINUIT with function state
672  for(index= 0; index < _nPar; index++) {
673  RooRealVar *par= dynamic_cast<RooRealVar*>(_floatParamList->at(index)) ;
674  if (!par) continue ;
675 
676  Double_t pstep(0) ;
677  Double_t pmin(0) ;
678  Double_t pmax(0) ;
679 
680  if(!par->isConstant()) {
681 
682  // Verify that floating parameter is indeed of type RooRealVar
683  if (!par->IsA()->InheritsFrom(RooRealVar::Class())) {
684  coutW(Minimization) << "RooMinuit::fit: Error, non-constant parameter " << par->GetName()
685  << " is not of type RooRealVar, skipping" << endl ;
686  continue ;
687  }
688 
689  // Set the limits, if not infinite
690  if (par->hasMin() && par->hasMax()) {
691  pmin = par->getMin();
692  pmax = par->getMax();
693  }
694 
695  // Calculate step size
696  pstep= par->getError();
697  if(pstep <= 0) {
698  // Floating parameter without error estitimate
699  if (par->hasMin() && par->hasMax()) {
700  pstep= 0.1*(pmax-pmin);
701 
702  // Trim default choice of error if within 2 sigma of limit
703  if (pmax - par->getVal() < 2*pstep) {
704  pstep = (pmax - par->getVal())/2 ;
705  } else if (par->getVal() - pmin < 2*pstep) {
706  pstep = (par->getVal() - pmin )/2 ;
707  }
708 
709  // If trimming results in zero error, restore default
710  if (pstep==0) {
711  pstep= 0.1*(pmax-pmin);
712  }
713 
714  } else {
715  pstep=1 ;
716  }
717  if(_verbose) {
718  coutW(Minimization) << "RooMinuit::synchronize: WARNING: no initial error estimate available for "
719  << par->GetName() << ": using " << pstep << endl;
720  }
721  }
722  } else {
723  pmin = par->getVal() ;
724  pmax = par->getVal() ;
725  }
726 
727  // Extract previous information
728  Double_t oldVar,oldVerr,oldVlo,oldVhi ;
729  char oldParname[100] ;
730  Int_t ierr = _theFitter->GetParameter(index,oldParname,oldVar,oldVerr,oldVlo,oldVhi) ;
731 
732  // Determine if parameters is currently fixed in MINUIT
733 
734  Int_t ix ;
735  Bool_t oldFixed(kFALSE) ;
736  if (ierr>=0) {
737  for (ix = 1; ix <= gMinuit->fNpfix; ++ix) {
738  if (gMinuit->fIpfix[ix-1] == index+1) oldFixed=kTRUE ;
739  }
740  }
741 
742  if (par->isConstant() && !oldFixed) {
743 
744  // Parameter changes floating -> constant : update only value if necessary
745  if (oldVar!=par->getVal()) {
746  Double_t arglist[2] ;
747  arglist[0] = index+1 ;
748  arglist[1] = par->getVal() ;
749  _theFitter->ExecuteCommand("SET PAR",arglist,2) ;
750  if (verbose) {
751  coutI(Minimization) << "RooMinuit::synchronize: value of parameter " << par->GetName() << " changed from " << oldVar << " to " << par->getVal() << endl ;
752  }
753  }
754 
755  _theFitter->FixParameter(index) ;
756  constStatChange=kTRUE ;
757  if (verbose) {
758  coutI(Minimization) << "RooMinuit::synchronize: parameter " << par->GetName() << " is now fixed." << endl ;
759  }
760 
761  } else if (par->isConstant() && oldFixed) {
762 
763  // Parameter changes constant -> constant : update only value if necessary
764  if (oldVar!=par->getVal()) {
765  Double_t arglist[2] ;
766  arglist[0] = index+1 ;
767  arglist[1] = par->getVal() ;
768  _theFitter->ExecuteCommand("SET PAR",arglist,2) ;
769  constValChange=kTRUE ;
770 
771  if (verbose) {
772  coutI(Minimization) << "RooMinuit::synchronize: value of fixed parameter " << par->GetName() << " changed from " << oldVar << " to " << par->getVal() << endl ;
773  }
774  }
775 
776  } else {
777 
778  if (!par->isConstant() && oldFixed) {
779  _theFitter->ReleaseParameter(index) ;
780  constStatChange=kTRUE ;
781 
782  if (verbose) {
783  coutI(Minimization) << "RooMinuit::synchronize: parameter " << par->GetName() << " is now floating." << endl ;
784  }
785  }
786 
787  // Parameter changes constant -> floating : update all if necessary
788  if (oldVar!=par->getVal() || oldVlo!=pmin || oldVhi != pmax || oldVerr!=pstep) {
789  _theFitter->SetParameter(index, par->GetName(), par->getVal(), pstep, pmin, pmax);
790  }
791 
792  // Inform user about changes in verbose mode
793  if (verbose && ierr>=0) {
794  // if ierr<0, par was moved from the const list and a message was already printed
795 
796  if (oldVar!=par->getVal()) {
797  coutI(Minimization) << "RooMinuit::synchronize: value of parameter " << par->GetName() << " changed from " << oldVar << " to " << par->getVal() << endl ;
798  }
799  if (oldVlo!=pmin || oldVhi!=pmax) {
800  coutI(Minimization) << "RooMinuit::synchronize: limits of parameter " << par->GetName() << " changed from [" << oldVlo << "," << oldVhi
801  << "] to [" << pmin << "," << pmax << "]" << endl ;
802  }
803 
804  // If oldVerr=0, then parameter was previously fixed
805  if (oldVerr!=pstep && oldVerr!=0) {
806  coutI(Minimization) << "RooMinuit::synchronize: error/step size of parameter " << par->GetName() << " changed from " << oldVerr << " to " << pstep << endl ;
807  }
808  }
809  }
810  }
811 
812 
813  gMinuit->fNwrmes[0] = 0; // to clear buffer
814  oldWarn = setWarnLevel(oldWarn) ;
815  oldPrint = setPrintLevel(oldPrint) ;
816 
817  if (_optConst) {
818  if (constStatChange) {
819 
820  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
821 
822  coutI(Minimization) << "RooMinuit::synchronize: set of constant parameters changed, rerunning const optimizer" << endl ;
823  _func->constOptimizeTestStatistic(RooAbsArg::ConfigChange) ;
824  } else if (constValChange) {
825  coutI(Minimization) << "RooMinuit::synchronize: constant parameter values changed, rerunning const optimizer" << endl ;
826  _func->constOptimizeTestStatistic(RooAbsArg::ValueChange) ;
827  }
828 
829  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
830 
831  }
832 
833  updateFloatVec() ;
834 
835  return 0 ;
836 }
837 
838 
839 
840 
841 ////////////////////////////////////////////////////////////////////////////////
842 /// If flag is true, perform constant term optimization on
843 /// function being minimized.
844 
845 void RooMinuit::optimizeConst(Int_t flag)
846 {
847  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::CollectErrors) ;
848 
849  if (_optConst && !flag){
850  if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: deactivating const optimization" << endl ;
851  _func->constOptimizeTestStatistic(RooAbsArg::DeActivate,flag>1) ;
852  _optConst = flag ;
853  } else if (!_optConst && flag) {
854  if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: activating const optimization" << endl ;
855  _func->constOptimizeTestStatistic(RooAbsArg::Activate,flag>1) ;
856  _optConst = flag ;
857  } else if (_optConst && flag) {
858  if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: const optimization already active" << endl ;
859  } else {
860  if (_printLevel>-1) coutI(Minimization) << "RooMinuit::optimizeConst: const optimization wasn't active" << endl ;
861  }
862 
863  RooAbsReal::setEvalErrorLoggingMode(RooAbsReal::PrintErrors) ;
864 
865 }
866 
867 
868 
869 ////////////////////////////////////////////////////////////////////////////////
870 /// Save and return a RooFitResult snaphot of current minimizer status.
871 /// This snapshot contains the values of all constant parameters,
872 /// the value of all floating parameters at RooMinuit construction and
873 /// after the last MINUIT operation, the MINUIT status, variance quality,
874 /// EDM setting, number of calls with evaluation problems, the minimized
875 /// function value and the full correlation matrix
876 
877 RooFitResult* RooMinuit::save(const char* userName, const char* userTitle)
878 {
879  TString name,title ;
880  name = userName ? userName : Form("%s", _func->GetName()) ;
881  title = userTitle ? userTitle : Form("%s", _func->GetTitle()) ;
882 
883  if (_floatParamList->getSize()==0) {
884  RooFitResult* fitRes = new RooFitResult(name,title) ;
885  fitRes->setConstParList(*_constParamList) ;
886  fitRes->setInitParList(RooArgList()) ;
887  fitRes->setFinalParList(RooArgList()) ;
888  fitRes->setStatus(-999) ;
889  fitRes->setCovQual(-999) ;
890  fitRes->setMinNLL(_func->getVal()) ;
891  fitRes->setNumInvalidNLL(0) ;
892  fitRes->setEDM(-999) ;
893  return fitRes ;
894  }
895 
896  RooFitResult* fitRes = new RooFitResult(name,title) ;
897 
898  // Move eventual fixed parameters in floatList to constList
899  Int_t i ;
900  RooArgList saveConstList(*_constParamList) ;
901  RooArgList saveFloatInitList(*_initFloatParamList) ;
902  RooArgList saveFloatFinalList(*_floatParamList) ;
903  for (i=0 ; i<_floatParamList->getSize() ; i++) {
904  RooAbsArg* par = _floatParamList->at(i) ;
905  if (par->isConstant()) {
906  saveFloatInitList.remove(*saveFloatInitList.find(par->GetName()),kTRUE) ;
907  saveFloatFinalList.remove(*par) ;
908  saveConstList.add(*par) ;
909  }
910  }
911  saveConstList.sort() ;
912 
913  fitRes->setConstParList(saveConstList) ;
914  fitRes->setInitParList(saveFloatInitList) ;
915 
916  Double_t edm, errdef, minVal;
917  Int_t nvpar, nparx;
918  Int_t icode = _theFitter->GetStats(minVal, edm, errdef, nvpar, nparx);
919  fitRes->setStatus(_status) ;
920  fitRes->setCovQual(icode) ;
921  fitRes->setMinNLL(minVal) ;
922  fitRes->setNumInvalidNLL(_numBadNLL) ;
923  fitRes->setEDM(edm) ;
924  fitRes->setFinalParList(saveFloatFinalList) ;
925  if (!_extV) {
926  fitRes->fillCorrMatrix() ;
927  } else {
928  fitRes->setCovarianceMatrix(*_extV) ;
929  }
930 
931  fitRes->setStatusHistory(_statusHistory) ;
932 
933  return fitRes ;
934 }
935 
936 
937 
938 
939 ////////////////////////////////////////////////////////////////////////////////
940 /// Create and draw a TH2 with the error contours in parameters var1 and v2 at up to 6 'sigma' settings
941 /// where 'sigma' is calculated as n*n*errorLevel
942 
943 RooPlot* RooMinuit::contour(RooRealVar& var1, RooRealVar& var2, Double_t n1, Double_t n2, Double_t n3, Double_t n4, Double_t n5, Double_t n6)
944 {
945 
946  _theFitter->SetObjectFit(this) ;
947 
948  RooArgList* paramSave = (RooArgList*) _floatParamList->snapshot() ;
949 
950  // Verify that both variables are floating parameters of PDF
951  Int_t index1= _floatParamList->index(&var1);
952  if(index1 < 0) {
953  coutE(Minimization) << "RooMinuit::contour(" << GetName()
954  << ") ERROR: " << var1.GetName() << " is not a floating parameter of " << _func->GetName() << endl ;
955  return 0;
956  }
957 
958  Int_t index2= _floatParamList->index(&var2);
959  if(index2 < 0) {
960  coutE(Minimization) << "RooMinuit::contour(" << GetName()
961  << ") ERROR: " << var2.GetName() << " is not a floating parameter of PDF " << _func->GetName() << endl ;
962  return 0;
963  }
964 
965  // create and draw a frame
966  RooPlot* frame = new RooPlot(var1,var2) ;
967 
968  // draw a point at the current parameter values
969  TMarker *point= new TMarker(var1.getVal(), var2.getVal(), 8);
970  frame->addObject(point) ;
971 
972  // remember our original value of ERRDEF
973  Double_t errdef= gMinuit->fUp;
974 
975  Double_t n[6] ;
976  n[0] = n1 ; n[1] = n2 ; n[2] = n3 ; n[3] = n4 ; n[4] = n5 ; n[5] = n6 ;
977 
978 
979  for (Int_t ic = 0 ; ic<6 ; ic++) {
980  if(n[ic] > 0) {
981  // set the value corresponding to an n1-sigma contour
982  gMinuit->SetErrorDef(n[ic]*n[ic]*errdef);
983  // calculate and draw the contour
984  TGraph* graph= (TGraph*)gMinuit->Contour(50, index1, index2);
985  if (!graph) {
986  coutE(Minimization) << "RooMinuit::contour(" << GetName() << ") ERROR: MINUIT did not return a contour graph for n=" << n[ic] << endl ;
987  } else {
988  graph->SetName(Form("contour_%s_n%f",_func->GetName(),n[ic])) ;
989  graph->SetLineStyle(ic+1) ;
990  graph->SetLineWidth(2) ;
991  graph->SetLineColor(kBlue) ;
992  frame->addObject(graph,"L") ;
993  }
994  }
995  }
996 
997  // restore the original ERRDEF
998  gMinuit->SetErrorDef(errdef);
999 
1000  // restore parameter values
1001  *_floatParamList = *paramSave ;
1002  delete paramSave ;
1003 
1004 
1005  return frame ;
1006 }
1007 
1008 
1009 
1010 ////////////////////////////////////////////////////////////////////////////////
1011 /// Change the file name for logging of a RooMinuit of all MINUIT steppings
1012 /// through the parameter space. If inLogfile is null, the current log file
1013 /// is closed and logging is stopped.
1014 
1015 Bool_t RooMinuit::setLogFile(const char* inLogfile)
1016 {
1017  if (_logfile) {
1018  coutI(Minimization) << "RooMinuit::setLogFile: closing previous log file" << endl ;
1019  _logfile->close() ;
1020  delete _logfile ;
1021  _logfile = 0 ;
1022  }
1023  _logfile = new ofstream(inLogfile) ;
1024  if (!_logfile->good()) {
1025  coutI(Minimization) << "RooMinuit::setLogFile: cannot open file " << inLogfile << endl ;
1026  _logfile->close() ;
1027  delete _logfile ;
1028  _logfile= 0;
1029  }
1030  return kFALSE ;
1031 }
1032 
1033 
1034 
1035 ////////////////////////////////////////////////////////////////////////////////
1036 /// Access PDF parameter value by ordinal index (needed by MINUIT)
1037 
1038 Double_t RooMinuit::getPdfParamVal(Int_t index)
1039 {
1040  return ((RooRealVar*)_floatParamList->at(index))->getVal() ;
1041 }
1042 
1043 
1044 
1045 ////////////////////////////////////////////////////////////////////////////////
1046 /// Access PDF parameter error by ordinal index (needed by MINUIT)
1047 
1048 Double_t RooMinuit::getPdfParamErr(Int_t index)
1049 {
1050  return ((RooRealVar*)_floatParamList->at(index))->getError() ;
1051 }
1052 
1053 
1054 
1055 ////////////////////////////////////////////////////////////////////////////////
1056 /// Modify PDF parameter value by ordinal index (needed by MINUIT)
1057 
1058 Bool_t RooMinuit::setPdfParamVal(Int_t index, Double_t value, Bool_t verbose)
1059 {
1060  //RooRealVar* par = (RooRealVar*)_floatParamList->at(index) ;
1061  RooRealVar* par = (RooRealVar*)_floatParamVec[index] ;
1062 
1063  if (par->getVal()!=value) {
1064  if (verbose) cout << par->GetName() << "=" << value << ", " ;
1065  par->setVal(value) ;
1066  return kTRUE ;
1067  }
1068 
1069  return kFALSE ;
1070 }
1071 
1072 
1073 
1074 ////////////////////////////////////////////////////////////////////////////////
1075 /// Modify PDF parameter error by ordinal index (needed by MINUIT)
1076 
1077 void RooMinuit::setPdfParamErr(Int_t index, Double_t value)
1078 {
1079  ((RooRealVar*)_floatParamList->at(index))->setError(value) ;
1080 }
1081 
1082 
1083 
1084 ////////////////////////////////////////////////////////////////////////////////
1085 /// Modify PDF parameter error by ordinal index (needed by MINUIT)
1086 
1087 void RooMinuit::clearPdfParamAsymErr(Int_t index)
1088 {
1089  ((RooRealVar*)_floatParamList->at(index))->removeAsymError() ;
1090 }
1091 
1092 
1093 ////////////////////////////////////////////////////////////////////////////////
1094 /// Modify PDF parameter error by ordinal index (needed by MINUIT)
1095 
1096 void RooMinuit::setPdfParamErr(Int_t index, Double_t loVal, Double_t hiVal)
1097 {
1098  ((RooRealVar*)_floatParamList->at(index))->setAsymError(loVal,hiVal) ;
1099 }
1100 
1101 
1102 
1103 ////////////////////////////////////////////////////////////////////////////////
1104 /// Start profiling timer
1105 
1106 void RooMinuit::profileStart()
1107 {
1108  if (_profile) {
1109  _timer.Start() ;
1110  _cumulTimer.Start(kFALSE) ;
1111  }
1112 }
1113 
1114 
1115 
1116 
1117 ////////////////////////////////////////////////////////////////////////////////
1118 /// Stop profiling timer and report results of last session
1119 
1120 void RooMinuit::profileStop()
1121 {
1122  if (_profile) {
1123  _timer.Stop() ;
1124  _cumulTimer.Stop() ;
1125  coutI(Minimization) << "Command timer: " ; _timer.Print() ;
1126  coutI(Minimization) << "Session timer: " ; _cumulTimer.Print() ;
1127  }
1128 }
1129 
1130 
1131 
1132 
1133 
1134 ////////////////////////////////////////////////////////////////////////////////
1135 /// Transfer MINUIT fit results back into RooFit objects
1136 
1137 void RooMinuit::backProp()
1138 {
1139  Double_t val,err,vlo,vhi, eplus, eminus, eparab, globcc;
1140  char buffer[64000];
1141  Int_t index ;
1142  for(index= 0; index < _nPar; index++) {
1143  _theFitter->GetParameter(index, buffer, val, err, vlo, vhi);
1144  setPdfParamVal(index, val);
1145  _theFitter->GetErrors(index, eplus, eminus, eparab, globcc);
1146 
1147  // Set the parabolic error
1148  setPdfParamErr(index, err);
1149 
1150  if(eplus > 0 || eminus < 0) {
1151  // Store the asymmetric error, if it is available
1152  setPdfParamErr(index, eminus,eplus);
1153  } else {
1154  // Clear the asymmetric error
1155  clearPdfParamAsymErr(index) ;
1156  }
1157  }
1158 }
1159 
1160 
1161 ////////////////////////////////////////////////////////////////////////////////
1162 
1163 void RooMinuit::updateFloatVec()
1164 {
1165  _floatParamVec.clear() ;
1166  RooFIter iter = _floatParamList->fwdIterator() ;
1167  RooAbsArg* arg ;
1168  _floatParamVec.resize(_floatParamList->getSize()) ;
1169  Int_t i(0) ;
1170  while((arg=iter.next())) {
1171  _floatParamVec[i++] = arg ;
1172  }
1173 }
1174 
1175 
1176 
1177 ////////////////////////////////////////////////////////////////////////////////
1178 /// Apply results of given external covariance matrix. i.e. propagate its errors
1179 /// to all RRV parameter representations and give this matrix instead of the
1180 /// HESSE matrix at the next save() call
1181 
1182 void RooMinuit::applyCovarianceMatrix(TMatrixDSym& V)
1183 {
1184  _extV = (TMatrixDSym*) V.Clone() ;
1185 
1186  for (Int_t i=0 ; i<getNPar() ; i++) {
1187  // Skip fixed parameters
1188  if (_floatParamList->at(i)->isConstant()) {
1189  continue ;
1190  }
1191  RooMinuit* context = (RooMinuit*) RooMinuit::_theFitter->GetObjectFit() ;
1192  if (context && context->_verbose)
1193  cout << "setting parameter " << i << " error to " << sqrt((*_extV)(i,i)) << endl ;
1194  setPdfParamErr(i, sqrt((*_extV)(i,i))) ;
1195  }
1196 
1197 }
1198 
1199 
1200 
1201 
1202 void RooMinuitGlue(Int_t& /*np*/, Double_t* /*gin*/,
1203  Double_t &f, Double_t *par, Int_t /*flag*/)
1204 {
1205  // Static function that interfaces minuit with RooMinuit
1206 
1207  // Retrieve fit context and its components
1208  RooMinuit* context = (RooMinuit*) RooMinuit::_theFitter->GetObjectFit() ;
1209  ofstream* logf = context->logfile() ;
1210  Double_t& maxFCN = context->maxFCN() ;
1211  Bool_t verbose = context->_verbose ;
1212 
1213  // Set the parameter values for this iteration
1214  Int_t nPar= context->getNPar();
1215  for(Int_t index= 0; index < nPar; index++) {
1216  if (logf) (*logf) << par[index] << " " ;
1217  context->setPdfParamVal(index, par[index],verbose);
1218  }
1219 
1220  // Calculate the function for these parameters
1221  RooAbsReal::setHideOffset(kFALSE) ;
1222  f= context->_func->getVal() ;
1223  RooAbsReal::setHideOffset(kTRUE) ;
1224  context->_evalCounter++ ;
1225  if (RooAbsReal::numEvalErrors()>0 || f>1e30) {
1226 
1227  if (context->_printEvalErrors>=0) {
1228 
1229  if (context->_doEvalErrorWall) {
1230  oocoutW(context,Minimization) << "RooMinuitGlue: Minimized function has error status." << endl
1231  << "Returning maximum FCN so far (" << maxFCN
1232  << ") to force MIGRAD to back out of this region. Error log follows" << endl ;
1233  } else {
1234  oocoutW(context,Minimization) << "RooMinuitGlue: Minimized function has error status but is ignored" << endl ;
1235  }
1236 
1237  TIterator* iter = context->_floatParamList->createIterator() ;
1238  RooRealVar* var ;
1239  Bool_t first(kTRUE) ;
1240  ooccoutW(context,Minimization) << "Parameter values: " ;
1241  while((var=(RooRealVar*)iter->Next())) {
1242  if (first) { first = kFALSE ; } else ooccoutW(context,Minimization) << ", " ;
1243  ooccoutW(context,Minimization) << var->GetName() << "=" << var->getVal() ;
1244  }
1245  delete iter ;
1246  ooccoutW(context,Minimization) << endl ;
1247 
1248  RooAbsReal::printEvalErrors(ooccoutW(context,Minimization),context->_printEvalErrors) ;
1249  ooccoutW(context,Minimization) << endl ;
1250  }
1251 
1252  if (context->_doEvalErrorWall) {
1253  f = maxFCN+1 ;
1254  }
1255 
1256  RooAbsReal::clearEvalErrorLog() ;
1257  context->_numBadNLL++ ;
1258  } else if (f>maxFCN) {
1259  maxFCN = f ;
1260  }
1261 
1262  // Optional logging
1263  if (logf) (*logf) << setprecision(15) << f << setprecision(4) << endl;
1264  if (verbose) {
1265  cout << "\nprevFCN" << (context->_func->isOffsetting()?"-offset":"") << " = " << setprecision(10) << f << setprecision(4) << " " ;
1266  cout.flush() ;
1267  }
1268 }