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 namespace std;
41
42RooAbsMinimizerFcn::RooAbsMinimizerFcn(RooArgList paramList, RooMinimizer *context) : _context(context)
43{
44 // Examine parameter list
45 _floatParamList.reset((RooArgList *)paramList.selectByAttrib("Constant", false));
46 if (_floatParamList->getSize() > 1) {
47 _floatParamList->sort();
48 }
49 _floatParamList->setName("floatParamList");
50
51 _constParamList.reset((RooArgList *)paramList.selectByAttrib("Constant", true));
52 if (_constParamList->getSize() > 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->getSize();
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 int index(0);
98
99 // Handle eventual migrations from constParamList -> floatParamList
100 for (index = 0; index < _constParamList->getSize(); index++) {
101
102 RooRealVar *par = dynamic_cast<RooRealVar *>(_constParamList->at(index));
103 if (!par)
104 continue;
105
106 RooRealVar *oldpar = dynamic_cast<RooRealVar *>(_initConstParamList->at(index));
107 if (!oldpar)
108 continue;
109
110 // Test if constness changed
111 if (!par->isConstant()) {
112
113 // Remove from constList, add to floatList
114 _constParamList->remove(*par);
115 _floatParamList->add(*par);
116 _initFloatParamList->addClone(*oldpar);
117 _initConstParamList->remove(*oldpar);
118 constStatChange = true;
119 _nDim++;
120
121 if (cfg().verbose) {
122 oocoutI(_context, Minimization)
123 << "RooAbsMinimizerFcn::synchronize: parameter " << par->GetName() << " is now floating." << endl;
124 }
125 }
126
127 // Test if value changed
128 if (par->getVal() != oldpar->getVal()) {
129 constValChange = true;
130 if (cfg().verbose) {
131 oocoutI(_context, Minimization)
132 << "RooAbsMinimizerFcn::synchronize: value of constant parameter " << par->GetName() << " changed from "
133 << oldpar->getVal() << " to " << par->getVal() << endl;
134 }
135 }
136 }
137
138 // Update reference list
140
141 // Synchronize MINUIT with function state
142 // Handle floatParamList
143 for (index = 0; index < _floatParamList->getSize(); index++) {
144 RooRealVar *par = dynamic_cast<RooRealVar *>(_floatParamList->at(index));
145
146 if (!par)
147 continue;
148
149 double pstep(0);
150 double pmin(0);
151 double pmax(0);
152
153 if (!par->isConstant()) {
154
155 // Verify that floating parameter is indeed of type RooRealVar
156 if (!par->IsA()->InheritsFrom(RooRealVar::Class())) {
157 oocoutW(_context, Minimization) << "RooAbsMinimizerFcn::fit: Error, non-constant parameter "
158 << par->GetName() << " is not of type RooRealVar, skipping" << endl;
159 _floatParamList->remove(*par);
160 index--;
161 _nDim--;
162 continue;
163 }
164 // make sure the parameter are in dirty state to enable
165 // a real NLL computation when the minimizer calls the function the first time
166 // (see issue #7659)
167 par->setValueDirty();
168
169 // Set the limits, if not infinite
170 if (par->hasMin())
171 pmin = par->getMin();
172 if (par->hasMax())
173 pmax = par->getMax();
174
175 // Calculate step size
176 pstep = par->getError();
177 if (pstep <= 0) {
178 // Floating parameter without error estitimate
179 if (par->hasMin() && par->hasMax()) {
180 pstep = 0.1 * (pmax - pmin);
181
182 // Trim default choice of error if within 2 sigma of limit
183 if (pmax - par->getVal() < 2 * pstep) {
184 pstep = (pmax - par->getVal()) / 2;
185 } else if (par->getVal() - pmin < 2 * pstep) {
186 pstep = (par->getVal() - pmin) / 2;
187 }
188
189 // If trimming results in zero error, restore default
190 if (pstep == 0) {
191 pstep = 0.1 * (pmax - pmin);
192 }
193
194 } else {
195 pstep = 1;
196 }
197 if (cfg().verbose) {
198 oocoutW(_context, Minimization)
199 << "RooAbsMinimizerFcn::synchronize: WARNING: no initial error estimate available for "
200 << par->GetName() << ": using " << pstep << endl;
201 }
202 }
203 } else {
204 pmin = par->getVal();
205 pmax = par->getVal();
206 }
207
208 // new parameter
209 if (index >= int(parameters.size())) {
210
211 if (par->hasMin() && par->hasMax()) {
212 parameters.emplace_back(par->GetName(), par->getVal(), pstep, pmin, pmax);
213 } else {
214 parameters.emplace_back(par->GetName(), par->getVal(), pstep);
215 if (par->hasMin())
216 parameters.back().SetLowerLimit(pmin);
217 else if (par->hasMax())
218 parameters.back().SetUpperLimit(pmax);
219 }
220
221 continue;
222 }
223
224 bool oldFixed = parameters[index].IsFixed();
225 double oldVar = parameters[index].Value();
226 double oldVerr = parameters[index].StepSize();
227 double oldVlo = parameters[index].LowerLimit();
228 double oldVhi = parameters[index].UpperLimit();
229
230 if (par->isConstant() && !oldFixed) {
231
232 // Parameter changes floating -> constant : update only value if necessary
233 if (oldVar != par->getVal()) {
234 parameters[index].SetValue(par->getVal());
235 if (cfg().verbose) {
236 oocoutI(_context, Minimization)
237 << "RooAbsMinimizerFcn::synchronize: value of parameter " << par->GetName() << " changed from "
238 << oldVar << " to " << par->getVal() << endl;
239 }
240 }
241 parameters[index].Fix();
242 constStatChange = true;
243 if (cfg().verbose) {
244 oocoutI(_context, Minimization)
245 << "RooAbsMinimizerFcn::synchronize: parameter " << par->GetName() << " is now fixed." << endl;
246 }
247
248 } else if (par->isConstant() && oldFixed) {
249
250 // Parameter changes constant -> constant : update only value if necessary
251 if (oldVar != par->getVal()) {
252 parameters[index].SetValue(par->getVal());
253 constValChange = true;
254
255 if (cfg().verbose) {
256 oocoutI(_context, Minimization)
257 << "RooAbsMinimizerFcn::synchronize: value of fixed parameter " << par->GetName() << " changed from "
258 << oldVar << " to " << par->getVal() << endl;
259 }
260 }
261
262 } else {
263 // Parameter changes constant -> floating
264 if (!par->isConstant() && oldFixed) {
265 parameters[index].Release();
266 constStatChange = true;
267
268 if (cfg().verbose) {
269 oocoutI(_context, Minimization)
270 << "RooAbsMinimizerFcn::synchronize: parameter " << par->GetName() << " is now floating." << endl;
271 }
272 }
273
274 // Parameter changes constant -> floating : update all if necessary
275 if (oldVar != par->getVal() || oldVlo != pmin || oldVhi != pmax || oldVerr != pstep) {
276 parameters[index].SetValue(par->getVal());
277 parameters[index].SetStepSize(pstep);
278 if (par->hasMin() && par->hasMax())
279 parameters[index].SetLimits(pmin, pmax);
280 else if (par->hasMin())
281 parameters[index].SetLowerLimit(pmin);
282 else if (par->hasMax())
283 parameters[index].SetUpperLimit(pmax);
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 0;
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 = 0;
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 = 0;
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;
470 _optConst = flag;
471 } else if (!_optConst && flag) {
472 if (_context->getPrintLevel() > -1)
473 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: activating const optimization"
474 << endl;
476 _optConst = flag;
477 } else if (_optConst && flag) {
478 if (_context->getPrintLevel() > -1)
479 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: const optimization already active"
480 << endl;
481 } else {
482 if (_context->getPrintLevel() > -1)
483 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setOptimizeConst: const optimization wasn't active"
484 << endl;
485 }
486}
487
488void RooAbsMinimizerFcn::optimizeConstantTerms(bool constStatChange, bool constValChange)
489{
490 auto ctx = _context->makeEvalErrorContext();
491
492 if (constStatChange) {
493
494 oocoutI(_context, Minimization)
495 << "RooAbsMinimizerFcn::optimizeConstantTerms: set of constant parameters changed, rerunning const optimizer"
496 << endl;
498 } else if (constValChange) {
499 oocoutI(_context, Minimization)
500 << "RooAbsMinimizerFcn::optimizeConstantTerms: constant parameter values changed, rerunning const optimizer"
501 << endl;
503 }
504}
505
506std::vector<double> RooAbsMinimizerFcn::getParameterValues() const
507{
508 // TODO: make a cache for this somewhere so it doesn't have to be recreated on each call
509 std::vector<double> values;
510 values.reserve(_nDim);
511
512 for (std::size_t index = 0; index < _nDim; ++index) {
514 values.push_back(par->getVal());
515 }
516
517 return values;
518}
#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:177
double Value(unsigned int i) const
parameter value by index
Definition FitResult.h:170
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:79
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:363
void setValueDirty()
Mark the element dirty. This forces a re-evaluation when a value is requested.
Definition RooAbsArg.h:490
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
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
static int getPrintLevel()
Get the MINUIT internal printing level.
std::unique_ptr< RooDataSet > _logDataSet
bool _loggingToDataSet
std::unique_ptr< RooAbsReal::EvalErrorContext > makeEvalErrorContext() const
RooRealVar represents a 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