Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsMinimizerFcn.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
7 * PB, Patrick Bos, Netherlands eScience Center, p.bos@esciencecenter.nl *
8 * *
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// RooAbsMinimizerFcn is an interface class to the ROOT::Math function
18// for minimization. It contains only the "logistics" of synchronizing
19// between Minuit and RooFit. Its subclasses implement actual interfacing
20// to Minuit by subclassing IMultiGenFunction or IMultiGradFunction.
21//
22
23#include "RooAbsMinimizerFcn.h"
24
25#include "RooAbsArg.h"
26#include "RooAbsPdf.h"
27#include "RooArgSet.h"
28#include "RooDataSet.h"
29#include "RooRealVar.h"
30#include "RooAbsRealLValue.h"
31#include "RooMsgService.h"
32#include "RooNaNPacker.h"
33
34#include "TClass.h"
35#include "TMatrixDSym.h"
36
37#include <fstream>
38#include <iomanip>
39
40using std::endl, std::ofstream, std::cout;
41
42RooAbsMinimizerFcn::RooAbsMinimizerFcn(RooArgList paramList, RooMinimizer *context) : _context(context)
43{
44 // Examine parameter list
45 _floatParamList.reset(static_cast<RooArgList *>(paramList.selectByAttrib("Constant", false)));
46 if (_floatParamList->size() > 1) {
47 _floatParamList->sort();
48 }
49 _floatParamList->setName("floatParamList");
50
51 _constParamList.reset(static_cast<RooArgList *>(paramList.selectByAttrib("Constant", true)));
52 if (_constParamList->size() > 1) {
53 _constParamList->sort();
54 }
55 _constParamList->setName("constParamList");
56
57 // Remove all non-RooRealVar parameters from list (MINUIT cannot handle them)
58 for (unsigned int i = 0; i < _floatParamList->size();) { // Note: Counting loop, since removing from collection!
59 const RooAbsArg *arg = (*_floatParamList).at(i);
61 oocoutW(_context, Minimization) << "RooAbsMinimizerFcn::RooAbsMinimizerFcn: removing parameter "
62 << arg->GetName() << " from list because it is not of type RooRealVar" << endl;
63 _floatParamList->remove(*arg);
64 } else {
65 ++i;
66 }
67 }
68
69 _nDim = _floatParamList->size();
70
71 // Save snapshot of initial lists
72 _initFloatParamList = std::make_unique<RooArgList>();
73 _initConstParamList = std::make_unique<RooArgList>();
74 _floatParamList->snapshot(*_initFloatParamList, false);
75 _constParamList->snapshot(*_initConstParamList, false);
76}
77
79 : _context(other._context), _maxFCN(other._maxFCN), _funcOffset(other._funcOffset), _numBadNLL(other._numBadNLL),
80 _evalCounter(other._evalCounter), _nDim(other._nDim), _optConst(other._optConst),
81 _floatParamList(new RooArgList(*other._floatParamList)), _constParamList(new RooArgList(*other._constParamList)),
82 _initFloatParamList(std::make_unique<RooArgList>()), _initConstParamList(std::make_unique<RooArgList>()),
83 _logfile(other._logfile)
84{
85 other._initFloatParamList->snapshot(*_initFloatParamList, false);
86 other._initConstParamList->snapshot(*_initConstParamList, false);
87}
88
89/// Internal function to synchronize TMinimizer with current
90/// information in RooAbsReal function parameters
91bool RooAbsMinimizerFcn::synchronizeParameterSettings(std::vector<ROOT::Fit::ParameterSettings> &parameters,
92 bool optConst)
93{
94 bool constValChange(false);
95 bool constStatChange(false);
96
97 // Handle eventual migrations from constParamList -> floatParamList
98 for (std::size_t index = 0; index < _constParamList->size(); index++) {
99
100 RooRealVar *par = dynamic_cast<RooRealVar *>(_constParamList->at(index));
101 if (!par)
102 continue;
103
104 RooRealVar *oldpar = dynamic_cast<RooRealVar *>(_initConstParamList->at(index));
105 if (!oldpar)
106 continue;
107
108 // Test if constness changed
109 if (!par->isConstant()) {
110
111 // Remove from constList, add to floatList
112 _constParamList->remove(*par);
113 _floatParamList->add(*par);
114 _initFloatParamList->addClone(*oldpar);
115 _initConstParamList->remove(*oldpar);
116 constStatChange = true;
117 _nDim++;
118
119 if (cfg().verbose) {
120 oocoutI(_context, Minimization)
121 << "RooAbsMinimizerFcn::synchronize: parameter " << par->GetName() << " is now floating." << endl;
122 }
123 }
124
125 // Test if value changed
126 if (par->getVal() != oldpar->getVal()) {
127 constValChange = true;
128 if (cfg().verbose) {
129 oocoutI(_context, Minimization)
130 << "RooAbsMinimizerFcn::synchronize: value of constant parameter " << par->GetName() << " changed from "
131 << oldpar->getVal() << " to " << par->getVal() << endl;
132 }
133 }
134 }
135
136 // Update reference list
138
139 // Synchronize MINUIT with function state
140 // Handle floatParamList
141 for (std::size_t index = 0; index < _floatParamList->size(); index++) {
142 RooRealVar *par = dynamic_cast<RooRealVar *>(_floatParamList->at(index));
143
144 if (!par)
145 continue;
146
147 double pstep(0);
148 double pmin(0);
149 double pmax(0);
150
151 if (!par->isConstant()) {
152
153 // Verify that floating parameter is indeed of type RooRealVar
154 if (!par->IsA()->InheritsFrom(RooRealVar::Class())) {
155 oocoutW(_context, Minimization) << "RooAbsMinimizerFcn::fit: Error, non-constant parameter "
156 << par->GetName() << " is not of type RooRealVar, skipping" << endl;
157 _floatParamList->remove(*par);
158 index--;
159 _nDim--;
160 continue;
161 }
162 // make sure the parameter are in dirty state to enable
163 // a real NLL computation when the minimizer calls the function the first time
164 // (see issue #7659)
165 par->setValueDirty();
166
167 // Set the limits, if not infinite
168 if (par->hasMin())
169 pmin = par->getMin();
170 if (par->hasMax())
171 pmax = par->getMax();
172
173 // Calculate step size
174 pstep = par->getError();
175 if (pstep <= 0) {
176 // Floating parameter without error estitimate
177 if (par->hasMin() && par->hasMax()) {
178 pstep = 0.1 * (pmax - pmin);
179
180 // Trim default choice of error if within 2 sigma of limit
181 if (pmax - par->getVal() < 2 * pstep) {
182 pstep = (pmax - par->getVal()) / 2;
183 } else if (par->getVal() - pmin < 2 * pstep) {
184 pstep = (par->getVal() - pmin) / 2;
185 }
186
187 // If trimming results in zero error, restore default
188 if (pstep == 0) {
189 pstep = 0.1 * (pmax - pmin);
190 }
191
192 } else {
193 pstep = 1;
194 }
195 if (cfg().verbose) {
196 oocoutW(_context, Minimization)
197 << "RooAbsMinimizerFcn::synchronize: WARNING: no initial error estimate available for "
198 << par->GetName() << ": using " << pstep << endl;
199 }
200 }
201 } else {
202 pmin = par->getVal();
203 pmax = par->getVal();
204 }
205
206 // new parameter
207 if (index >= parameters.size()) {
208
209 if (par->hasMin() && par->hasMax()) {
210 parameters.emplace_back(par->GetName(), par->getVal(), pstep, pmin, pmax);
211 } else {
212 parameters.emplace_back(par->GetName(), par->getVal(), pstep);
213 if (par->hasMin()) {
214 parameters.back().SetLowerLimit(pmin);
215 } else if (par->hasMax()) {
216 parameters.back().SetUpperLimit(pmax);
217 }
218 }
219
220 continue;
221 }
222
223 bool oldFixed = parameters[index].IsFixed();
224 double oldVar = parameters[index].Value();
225 double oldVerr = parameters[index].StepSize();
226 double oldVlo = parameters[index].LowerLimit();
227 double oldVhi = parameters[index].UpperLimit();
228
229 if (par->isConstant() && !oldFixed) {
230
231 // Parameter changes floating -> constant : update only value if necessary
232 if (oldVar != par->getVal()) {
233 parameters[index].SetValue(par->getVal());
234 if (cfg().verbose) {
235 oocoutI(_context, Minimization)
236 << "RooAbsMinimizerFcn::synchronize: value of parameter " << par->GetName() << " changed from "
237 << oldVar << " to " << par->getVal() << endl;
238 }
239 }
240 parameters[index].Fix();
241 constStatChange = true;
242 if (cfg().verbose) {
243 oocoutI(_context, Minimization)
244 << "RooAbsMinimizerFcn::synchronize: parameter " << par->GetName() << " is now fixed." << endl;
245 }
246
247 } else if (par->isConstant() && oldFixed) {
248
249 // Parameter changes constant -> constant : update only value if necessary
250 if (oldVar != par->getVal()) {
251 parameters[index].SetValue(par->getVal());
252 constValChange = true;
253
254 if (cfg().verbose) {
255 oocoutI(_context, Minimization)
256 << "RooAbsMinimizerFcn::synchronize: value of fixed parameter " << par->GetName() << " changed from "
257 << oldVar << " to " << par->getVal() << endl;
258 }
259 }
260
261 } else {
262 // Parameter changes constant -> floating
263 if (!par->isConstant() && oldFixed) {
264 parameters[index].Release();
265 constStatChange = true;
266
267 if (cfg().verbose) {
268 oocoutI(_context, Minimization)
269 << "RooAbsMinimizerFcn::synchronize: parameter " << par->GetName() << " is now floating." << endl;
270 }
271 }
272
273 // Parameter changes constant -> floating : update all if necessary
274 if (oldVar != par->getVal() || oldVlo != pmin || oldVhi != pmax || oldVerr != pstep) {
275 parameters[index].SetValue(par->getVal());
276 parameters[index].SetStepSize(pstep);
277 if (par->hasMin() && par->hasMax()) {
278 parameters[index].SetLimits(pmin, pmax);
279 } else if (par->hasMin()) {
280 parameters[index].SetLowerLimit(pmin);
281 } else if (par->hasMax()) {
282 parameters[index].SetUpperLimit(pmax);
283 }
284 }
285
286 // Inform user about changes in verbose mode
287 if (cfg().verbose) {
288 // if ierr<0, par was moved from the const list and a message was already printed
289
290 if (oldVar != par->getVal()) {
291 oocoutI(_context, Minimization)
292 << "RooAbsMinimizerFcn::synchronize: value of parameter " << par->GetName() << " changed from "
293 << oldVar << " to " << par->getVal() << endl;
294 }
295 if (oldVlo != pmin || oldVhi != pmax) {
296 oocoutI(_context, Minimization)
297 << "RooAbsMinimizerFcn::synchronize: limits of parameter " << par->GetName() << " changed from ["
298 << oldVlo << "," << oldVhi << "] to [" << pmin << "," << pmax << "]" << endl;
299 }
300
301 // If oldVerr=0, then parameter was previously fixed
302 if (oldVerr != pstep && oldVerr != 0) {
303 oocoutI(_context, Minimization)
304 << "RooAbsMinimizerFcn::synchronize: error/step size of parameter " << par->GetName()
305 << " changed from " << oldVerr << " to " << pstep << endl;
306 }
307 }
308 }
309 }
310
311 if (optConst) {
312 optimizeConstantTerms(constStatChange, constValChange);
313 }
314
315 return false;
316}
317
318bool RooAbsMinimizerFcn::Synchronize(std::vector<ROOT::Fit::ParameterSettings> &parameters)
319{
320 return synchronizeParameterSettings(parameters, _optConst);
321}
322
323/// Modify PDF parameter error by ordinal index (needed by MINUIT)
325{
326 static_cast<RooRealVar *>(_floatParamList->at(index))->setError(value);
327}
328
329/// Modify PDF parameter error by ordinal index (needed by MINUIT)
331{
332 static_cast<RooRealVar *>(_floatParamList->at(index))->removeAsymError();
333}
334
335/// Modify PDF parameter error by ordinal index (needed by MINUIT)
336void RooAbsMinimizerFcn::SetPdfParamErr(int index, double loVal, double hiVal)
337{
338 static_cast<RooRealVar *>(_floatParamList->at(index))->setAsymError(loVal, hiVal);
339}
340
341/// Transfer MINUIT fit results back into RooFit objects.
343{
344 for (unsigned int index = 0; index < _nDim; index++) {
345 double value = results.Value(index);
347
348 // Set the parabolic error
349 double err = results.Error(index);
350 SetPdfParamErr(index, err);
351
352 double eminus = results.LowerError(index);
353 double eplus = results.UpperError(index);
354
355 if (eplus > 0 || eminus < 0) {
356 // Store the asymmetric error, if it is available
357 SetPdfParamErr(index, eminus, eplus);
358 } else {
359 // Clear the asymmetric error
361 }
362 }
363}
364
365/// Change the file name for logging of a RooMinimizer of all MINUIT steppings
366/// through the parameter space. If inLogfile is null, the current log file
367/// is closed and logging is stopped.
368bool RooAbsMinimizerFcn::SetLogFile(const char *inLogfile)
369{
370 if (_logfile) {
371 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setLogFile: closing previous log file" << endl;
372 _logfile->close();
373 delete _logfile;
374 _logfile = nullptr;
375 }
376 _logfile = new ofstream(inLogfile);
377 if (!_logfile->good()) {
378 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setLogFile: cannot open file " << inLogfile << endl;
379 _logfile->close();
380 delete _logfile;
381 _logfile = nullptr;
382 }
383
384 return false;
385}
386
387/// Apply results of given external covariance matrix. i.e. propagate its errors
388/// to all RRV parameter representations and give this matrix instead of the
389/// HESSE matrix at the next save() call
391{
392 for (unsigned int i = 0; i < _nDim; i++) {
393 // Skip fixed parameters
394 if (_floatParamList->at(i)->isConstant()) {
395 continue;
396 }
397 SetPdfParamErr(i, sqrt(V(i, i)));
398 }
399}
400
401/// Set value of parameter i.
403{
404 auto par = static_cast<RooRealVar *>(&(*_floatParamList)[index]);
405
406 if (par->getVal() != value) {
407 if (cfg().verbose)
408 cout << par->GetName() << "=" << value << ", ";
409
410 par->setVal(value);
411 return true;
412 }
413
414 return false;
415}
416
417/// Print information about why evaluation failed.
418/// Using _printEvalErrors, the number of errors printed can be steered.
419/// Negative values disable printing.
421{
422 if (cfg().printEvalErrors < 0)
423 return;
424
425 std::ostringstream msg;
426 if (cfg().doEEWall) {
427 msg << "RooAbsMinimizerFcn: Minimized function has error status." << endl
428 << "Returning maximum FCN so far (" << _maxFCN
429 << ") to force MIGRAD to back out of this region. Error log follows.\n";
430 } else {
431 msg << "RooAbsMinimizerFcn: Minimized function has error status but is ignored.\n";
432 }
433
434 msg << "Parameter values: ";
435 for (const auto par : *_floatParamList) {
436 auto var = static_cast<const RooRealVar *>(par);
437 msg << "\t" << var->GetName() << "=" << var->getVal();
438 }
439 msg << std::endl;
440
442 ooccoutW(_context, Minimization) << msg.str() << endl;
443}
444
446{
447
449
450 if (!_context->_logDataSet) {
451 const char *name = "minimizer_log_dataset";
452 _context->_logDataSet = std::make_unique<RooDataSet>(name, name, *_floatParamList);
453 }
454
456 }
457
458 _evalCounter++;
459}
460
462{
463 auto ctx = _context->makeEvalErrorContext();
464
465 if (_optConst && !flag) {
466 if (_context->getPrintLevel() > -1) {
467 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: deactivating const optimization"
468 << endl;
469 }
471 _optConst = flag;
472 } else if (!_optConst && flag) {
473 if (_context->getPrintLevel() > -1) {
474 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: activating const optimization"
475 << endl;
476 }
478 _optConst = flag;
479 } else if (_optConst && flag) {
480 if (_context->getPrintLevel() > -1) {
481 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: const optimization already active"
482 << endl;
483 }
484 } else {
485 if (_context->getPrintLevel() > -1) {
486 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: const optimization wasn't active"
487 << endl;
488 }
489 }
490}
491
492void RooAbsMinimizerFcn::optimizeConstantTerms(bool constStatChange, bool constValChange)
493{
494 auto ctx = _context->makeEvalErrorContext();
495
496 if (constStatChange) {
497
498 oocoutI(_context, Minimization)
499 << "RooAbsMinimizerFcn::optimizeConstantTerms: set of constant parameters changed, rerunning const optimizer"
500 << endl;
502 } else if (constValChange) {
503 oocoutI(_context, Minimization)
504 << "RooAbsMinimizerFcn::optimizeConstantTerms: constant parameter values changed, rerunning const optimizer"
505 << endl;
507 }
508}
509
510std::vector<double> RooAbsMinimizerFcn::getParameterValues() const
511{
512 // TODO: make a cache for this somewhere so it doesn't have to be recreated on each call
513 std::vector<double> values;
514 values.reserve(_nDim);
515
516 for (std::size_t index = 0; index < _nDim; ++index) {
517 RooRealVar *par = static_cast<RooRealVar *>(_floatParamList->at(index));
518 values.push_back(par->getVal());
519 }
520
521 return values;
522}
#define oocoutW(o, a)
#define oocoutI(o, a)
#define ooccoutW(o, a)
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
char name[80]
Definition TGX11.cxx:110
class containing the result of the fit and all the related information (fitted parameter values,...
Definition FitResult.h:47
double UpperError(unsigned int i) const
upper Minos error. If Minos has not run for parameter i return the parabolic error
double Error(unsigned int i) const
parameter error by index
Definition FitResult.h:179
double Value(unsigned int i) const
parameter value by index
Definition FitResult.h:172
double LowerError(unsigned int i) const
lower Minos error. If Minos has not run for parameter i return the parabolic error
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:361
void setValueDirty()
Mark the element dirty. This forces a re-evaluation when a value is requested.
Definition RooAbsArg.h:488
RooAbsCollection * selectByAttrib(const char *name, bool value) const
Create a subset of the current collection, consisting only of those elements with the specified attri...
void setOptimizeConst(Int_t flag)
std::unique_ptr< RooArgList > _floatParamList
bool SetLogFile(const char *inLogfile)
Change the file name for logging of a RooMinimizer of all MINUIT steppings through the parameter spac...
RooAbsMinimizerFcn(RooArgList paramList, RooMinimizer *context)
virtual bool Synchronize(std::vector< ROOT::Fit::ParameterSettings > &parameters)
Like synchronizeParameterSettings, Synchronize informs Minuit through its parameter_settings vector o...
virtual void setOptimizeConstOnFunction(RooAbsArg::ConstOpCode opcode, bool doAlsoTrackingOpt)=0
This function must be overridden in the derived class to pass on constant term optimization configura...
void BackProp(const ROOT::Fit::FitResult &results)
Put Minuit results back into RooFit objects.
RooMinimizer::Config const & cfg() const
void optimizeConstantTerms(bool constStatChange, bool constValChange)
void printEvalErrors() const
Print information about why evaluation failed.
void ClearPdfParamAsymErr(Int_t index)
Modify PDF parameter error by ordinal index (needed by MINUIT)
std::vector< double > getParameterValues() const
std::ofstream * _logfile
void SetPdfParamErr(Int_t index, double value)
Modify PDF parameter error by ordinal index (needed by MINUIT)
bool synchronizeParameterSettings(std::vector< ROOT::Fit::ParameterSettings > &parameters, bool optConst)
Informs Minuit through its parameter_settings vector of RooFit parameter properties.
void ApplyCovarianceMatrix(TMatrixDSym &V)
Set different external covariance matrix.
std::unique_ptr< RooArgList > _initConstParamList
std::unique_ptr< RooArgList > _constParamList
bool SetPdfParamVal(int index, double value) const
Set value of parameter i.
std::unique_ptr< RooArgList > _initFloatParamList
virtual double getMax(const char *name=nullptr) const
Get maximum of currently defined range.
bool hasMax(const char *name=nullptr) const
Check if variable has an upper bound.
static TClass * Class()
virtual double getMin(const char *name=nullptr) const
Get minimum of currently defined range.
bool hasMin(const char *name=nullptr) const
Check if variable has a lower bound.
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:103
static void printEvalErrors(std::ostream &os=std::cout, Int_t maxPerNode=10000000)
Print all outstanding logged evaluation error on the given ostream.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
Wrapper class around ROOT::Fit:Fitter that provides a seamless interface between the minimizer functi...
static int getPrintLevel()
Get the MINUIT internal printing level.
std::unique_ptr< RooDataSet > _logDataSet
bool _loggingToDataSet
std::unique_ptr< RooAbsReal::EvalErrorContext > makeEvalErrorContext() const
Variable that can be changed from the outside.
Definition RooRealVar.h:37
static TClass * Class()
double getError() const
Definition RooRealVar.h:58
TClass * IsA() const override
Definition RooRealVar.h:173
Bool_t InheritsFrom(const char *cl) const override
Return kTRUE if this class inherits from a class with name "classname".
Definition TClass.cxx:4874
const char * GetName() const override
Returns name of object.
Definition TNamed.h:47
TClass * IsA() const override
Definition TNamed.h:58