Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RooAbsMinimizerFcn.cxx
Go to the documentation of this file.
1/// \cond ROOFIT_INTERNAL
2
3/*****************************************************************************
4 * Project: RooFit *
5 * Package: RooFitCore *
6 * @(#)root/roofitcore:$Id$
7 * Authors: *
8 * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
9 * PB, Patrick Bos, Netherlands eScience Center, p.bos@esciencecenter.nl *
10 * *
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//
19// RooAbsMinimizerFcn is an interface class to the ROOT::Math function
20// for minimization. It contains only the "logistics" of synchronizing
21// between Minuit and RooFit. Its subclasses implement actual interfacing
22// to Minuit by subclassing IMultiGenFunction or IMultiGradFunction.
23//
24
25#include "RooAbsMinimizerFcn.h"
26
27#include "RooAbsArg.h"
28#include "RooAbsPdf.h"
29#include "RooArgSet.h"
30#include "RooDataSet.h"
31#include "RooRealVar.h"
32#include "RooMsgService.h"
33#include "RooNaNPacker.h"
34
35#include "TClass.h"
36#include "TMatrixDSym.h"
37
38#include <fstream>
39#include <iomanip>
40
41RooAbsMinimizerFcn::RooAbsMinimizerFcn(RooArgList paramList, RooMinimizer *context) : _context{context}
42{
43 _allParams.add(paramList);
44
45 // Examine parameter list
46 for (RooAbsArg *param : _allParams) {
47
48 // Treat all non-RooRealVar parameters as constants (MINUIT cannot handle them)
49 if (!param->isConstant() && !canBeFloating(*param)) {
50 oocoutW(_context, Minimization) << "RooAbsMinimizerFcn::RooAbsMinimizerFcn: removing parameter "
51 << param->GetName() << " from list because it is not of type RooRealVar"
52 << std::endl;
53 }
54 }
55
56 _allParams.snapshot(_allParamsInit, false);
57
58 std::size_t iParam = 0;
59 for (RooAbsArg *param : _allParamsInit) {
60 if (!treatAsConstant(*param)) {
61 _floatableParamIndices.push_back(iParam);
62 }
63 ++iParam;
64 }
65}
66
67/// Internal function to synchronize TMinimizer with current
68/// information in RooAbsReal function parameters
69bool RooAbsMinimizerFcn::synchronizeParameterSettings(std::vector<ROOT::Fit::ParameterSettings> &parameters)
70{
71 // Synchronize MINUIT with function state
72
73 for (std::size_t i = 0; i < _allParams.size(); ++i) {
74 if (treatAsConstant(_allParamsInit[i]) && !treatAsConstant(_allParams[i])) {
75 std::stringstream ss;
76 ss << "RooMinimzer: the parameter named " << _allParams[i].GetName()
77 << " is not constant anymore, but it was constant at the time where the RooMinimizer was constructed."
78 " This is illegal. The other way around is supported: you can always change the constant flag of "
79 "parameters that were floating at the time the minimizer was instantiated.";
80 oocxcoutF(nullptr, LinkStateMgmt) << ss.str() << std::endl;
81 throw std::runtime_error(ss.str());
82 }
83 }
84
85 parameters.clear();
86
87 for (std::size_t index = 0; index < getNDim(); index++) {
88
89 auto &par = floatableParam(index);
90
91 // make sure the parameter are in dirty state to enable
92 // a real NLL computation when the minimizer calls the function the first time
93 // (see issue #7659)
94 par.setValueDirty();
95
96 // Set the limits, if not infinite
97 double pmin = par.hasMin() ? par.getMin() : 0.0;
98 double pmax = par.hasMax() ? par.getMax() : 0.0;
99
100 // Calculate step size
101 double pstep = par.getError();
102 if (pstep <= 0) {
103 // Floating parameter without error estimate
104 if (par.hasMin() && par.hasMax()) {
105 pstep = 0.1 * (pmax - pmin);
106
107 // Trim default choice of error if within 2 sigma of limit
108 if (pmax - par.getVal() < 2 * pstep) {
109 pstep = (pmax - par.getVal()) / 2;
110 } else if (par.getVal() - pmin < 2 * pstep) {
111 pstep = (par.getVal() - pmin) / 2;
112 }
113
114 // If trimming results in zero error, restore default
115 if (pstep == 0) {
116 pstep = 0.1 * (pmax - pmin);
117 }
118
119 } else {
120 pstep = 1;
121 }
122 if (cfg().verbose) {
123 oocoutW(_context, Minimization)
124 << "RooAbsMinimizerFcn::synchronize: WARNING: no initial error estimate available for " << par.GetName()
125 << ": using " << pstep << std::endl;
126 }
127 }
128
129 if (par.hasMin() && par.hasMax()) {
130 parameters.emplace_back(par.GetName(), par.getVal(), pstep, pmin, pmax);
131 } else {
132 parameters.emplace_back(par.GetName(), par.getVal(), pstep);
133 if (par.hasMin()) {
134 parameters.back().SetLowerLimit(pmin);
135 } else if (par.hasMax()) {
136 parameters.back().SetUpperLimit(pmax);
137 }
138 }
139
140 par.isConstant() ? parameters.back().Fix() : parameters.back().Release();
141 }
142
143 return false;
144}
145
146bool RooAbsMinimizerFcn::Synchronize(std::vector<ROOT::Fit::ParameterSettings> &parameters)
147{
148 return synchronizeParameterSettings(parameters);
149}
150
151/// Transfer MINUIT fit results back into RooFit objects.
152void RooAbsMinimizerFcn::BackProp()
153{
154 auto const &results = _context->fitter()->Result();
155
156 for (std::size_t index = 0; index < getNDim(); index++) {
157
158 auto &param = floatableParam(index);
159
160 double value = results.fParams[index];
161 SetPdfParamVal(index, value);
162
163 // Set the parabolic error
164 double err = results.fErrors[index];
165 param.setError(err);
166
167 double eminus = results.lowerError(index);
168 double eplus = results.upperError(index);
169
170 if (eplus > 0 || eminus < 0) {
171 // Store the asymmetric error, if it is available
172 param.setAsymError(eminus, eplus);
173 } else {
174 // Clear the asymmetric error
175 param.removeAsymError();
176 }
177 }
178}
179
180/// Change the file name for logging of a RooMinimizer of all MINUIT steppings
181/// through the parameter space. If inLogfile is null, the current log file
182/// is closed and logging is stopped.
183bool RooAbsMinimizerFcn::SetLogFile(const char *inLogfile)
184{
185 if (_logfile) {
186 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setLogFile: closing previous log file" << std::endl;
187 _logfile->close();
188 delete _logfile;
189 _logfile = nullptr;
190 }
191 _logfile = new std::ofstream(inLogfile);
192 if (!_logfile->good()) {
193 oocoutI(_context, Minimization) << "RooAbsMinimizerFcn::setLogFile: cannot open file " << inLogfile << std::endl;
194 _logfile->close();
195 delete _logfile;
196 _logfile = nullptr;
197 }
198
199 return false;
200}
201
202/// Apply results of given external covariance matrix. i.e. propagate its errors
203/// to all RRV parameter representations and give this matrix instead of the
204/// HESSE matrix at the next save() call
205void RooAbsMinimizerFcn::ApplyCovarianceMatrix(TMatrixDSym &V)
206{
207 for (unsigned int i = 0; i < getNDim(); i++) {
208 floatableParam(i).setError(std::sqrt(V(i, i)));
209 }
210}
211
212/// Set value of parameter i.
213bool RooAbsMinimizerFcn::SetPdfParamVal(int index, double value) const
214{
215 auto &par = floatableParam(index);
216
217 if (par.getVal() != value) {
218 if (cfg().verbose)
219 std::cout << par.GetName() << "=" << value << ", ";
220
221 par.setVal(value);
222 return true;
223 }
224
225 return false;
226}
227
228/// Print information about why evaluation failed.
229/// Using _printEvalErrors, the number of errors printed can be steered.
230/// Negative values disable printing.
231void RooAbsMinimizerFcn::printEvalErrors() const
232{
233 if (cfg().printEvalErrors < 0)
234 return;
235
236 std::ostringstream msg;
237 if (cfg().doEEWall) {
238 msg << "RooAbsMinimizerFcn: Minimized function has error status." << std::endl
239 << "Returning maximum FCN so far (" << _maxFCN
240 << ") to force MIGRAD to back out of this region. Error log follows.\n";
241 } else {
242 msg << "RooAbsMinimizerFcn: Minimized function has error status but is ignored.\n";
243 }
244
245 msg << "Parameter values: ";
246 for (std::size_t i = 0; i < getNDim(); ++i) {
247 auto &var = floatableParam(i);
248 msg << "\t" << var.GetName() << "=" << var.getVal();
249 }
250 msg << std::endl;
251
252 RooAbsReal::printEvalErrors(msg, cfg().printEvalErrors);
253 ooccoutW(_context, Minimization) << msg.str() << std::endl;
254}
255
256/// Apply corrections on the fvalue if errors were signaled.
257///
258/// Two kinds of errors are possible: 1. infinite or nan values (the latter
259/// can be a signaling nan, using RooNaNPacker) or 2. logEvalError-type errors.
260/// Both are caught here and fvalue is updated so that Minuit in turn is nudged
261/// to move the search outside of the problematic parameter space area.
262double RooAbsMinimizerFcn::applyEvalErrorHandling(double fvalue) const
263{
264 if (!std::isfinite(fvalue) || RooAbsReal::numEvalErrors() > 0 || fvalue > 1e30) {
265 printEvalErrors();
267 _numBadNLL++;
268
269 if (cfg().doEEWall) {
270 const double badness = RooNaNPacker::unpackNaN(fvalue);
271 fvalue = (std::isfinite(_maxFCN) ? _maxFCN : 0.) + cfg().recoverFromNaN * badness;
272 }
273 } else {
274 if (_evalCounter > 0 && _evalCounter == _numBadNLL) {
275 // This is the first time we get a valid function value; while before, the
276 // function was always invalid. For invalid cases, we returned values > 0.
277 // Now, we offset valid values such that they are < 0.
278 _funcOffset = -fvalue;
279 }
280 fvalue += _funcOffset;
281 _maxFCN = std::max(fvalue, _maxFCN);
282 }
283 return fvalue;
284}
285
286void RooAbsMinimizerFcn::finishDoEval() const
287{
288 _evalCounter++;
289}
290
291RooArgList RooAbsMinimizerFcn::floatParams() const
292{
293 RooArgList out;
294 for (RooAbsArg *param : _allParams) {
295 if (!treatAsConstant(*param))
296 out.add(*param);
297 }
298 return out;
299}
300
301RooArgList RooAbsMinimizerFcn::constParams() const
302{
303 RooArgList out;
304 for (RooAbsArg *param : _allParams) {
305 if (treatAsConstant(*param))
306 out.add(*param);
307 }
308 return out;
309}
310
311RooArgList RooAbsMinimizerFcn::initFloatParams() const
312{
313 RooArgList initFloatableParams;
314
315 for (RooAbsArg *param : _allParamsInit) {
316 if (!treatAsConstant(*param))
317 initFloatableParams.add(*param);
318 }
319
320 // Make sure we only return the initial parameters
321 // corresponding to currently floating parameters.
322 RooArgList out;
323 initFloatableParams.selectCommon(floatParams(), out);
324
325 return out;
326}
327
328/// \endcond
double badness
#define oocoutW(o, a)
#define oocoutI(o, a)
#define ooccoutW(o, a)
#define oocxcoutF(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
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
bool selectCommon(const RooAbsCollection &refColl, RooAbsCollection &outColl) const
Create a subset of the current collection, consisting only of those elements that are contained as we...
static Int_t numEvalErrors()
Return the number of logged evaluation errors since the last clearing.
static void printEvalErrors(std::ostream &os=std::cout, Int_t maxPerNode=10000000)
Print all outstanding logged evaluation error on the given ostream.
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
RooArgList is a container object that can hold multiple RooAbsArg objects.
Definition RooArgList.h:22
Wrapper class around ROOT::Math::Minimizer that provides a seamless interface between the minimizer f...
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:461
static float unpackNaN(double val)
If val is NaN and a this NaN has been tagged as containing a payload, unpack the float from the manti...