Logo ROOT  
Reference Guide
Loading...
Searching...
No Matches
RooMinimizer.cxx
Go to the documentation of this file.
1/*****************************************************************************
2 * Project: RooFit *
3 * Package: RooFitCore *
4 * @(#)root/roofitcore:$Id$
5 * Authors: *
6 * WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu *
7 * DK, David Kirkby, UC Irvine, dkirkby@uci.edu *
8 * AL, Alfio Lazzaro, INFN Milan, alfio.lazzaro@mi.infn.it *
9 * PB, Patrick Bos, NL eScience Center, p.bos@esciencecenter.nl *
10 * *
11 * Redistribution and use in source and binary forms, *
12 * with or without modification, are permitted according to the terms *
13 * listed in LICENSE (http://roofit.sourceforge.net/license.txt) *
14 *****************************************************************************/
15
16/**
17\file RooMinimizer.cxx
18\class RooMinimizer
19\ingroup Roofitcore
20
21Wrapper class around ROOT::Math::Minimizer that
22provides a seamless interface between the minimizer functionality
23and the native RooFit interface.
24By default the Minimizer is Minuit 2.
25RooMinimizer can minimize any RooAbsReal function with respect to
26its parameters. Usual choices for minimization are the object returned by
27RooAbsPdf::createNLL() or RooAbsReal::createChi2().
28RooMinimizer has methods corresponding to MINUIT functions like
29hesse(), migrad(), minos() etc. In each of these function calls
30the state of the MINUIT engine is synchronized with the state
31of the RooFit variables: any change in variables, change
32in the constant status etc is forwarded to MINUIT prior to
33execution of the MINUIT call. Afterwards the RooFit objects
34are resynchronized with the output state of MINUIT: changes
35parameter values, errors are propagated.
36Various methods are available to control verbosity, profiling,
37automatic PDF optimization.
38**/
39
40#include "RooMinimizer.h"
41
42#include "RooAbsMinimizerFcn.h"
43#include "RooAbsReal.h"
44#include "RooArgList.h"
45#include "RooArgSet.h"
46#include "RooCategory.h"
47#include "RooDataSet.h"
48#include "RooEvaluatorWrapper.h"
51#include "RooFitResult.h"
52#include "RooHelpers.h"
53#include "RooMinimizerFcn.h"
54#include "RooMsgService.h"
55#include "RooMultiPdf.h"
56#include "RooPlot.h"
57#include "RooRealVar.h"
58#include "RooSentinel.h"
59#ifdef ROOFIT_MULTIPROCESS
63#endif
64
65#include "RooFitImplHelpers.h"
66
67#include <Fit/BasicFCN.h>
68#include <Math/Minimizer.h>
69#include <TClass.h>
70#include <TGraph.h>
71#include <TMarker.h>
72
73#include <fstream>
74#include <iostream>
75#include <stdexcept> // logic_error
76
77namespace {
78
79class FreezeDisconnectedParametersRAII {
80public:
81 FreezeDisconnectedParametersRAII(RooMinimizer const *minimizer, RooAbsMinimizerFcn const &fcn)
82 : _minimizer{minimizer}, _frozen{fcn.freezeDisconnectedParameters()}
83 {
84 if (!_frozen.empty()) {
85 oocoutI(_minimizer, Minimization) << "Freezing disconnected parameters: " << _frozen << std::endl;
86 }
87 }
88 ~FreezeDisconnectedParametersRAII()
89 {
90 if (!_frozen.empty()) {
91 oocoutI(_minimizer, Minimization) << "Unfreezing disconnected parameters: " << _frozen << std::endl;
92 }
93 RooHelpers::setAllConstant(_frozen, false);
94 }
95
96private:
97 RooMinimizer const *_minimizer = nullptr;
98 RooArgSet _frozen;
99};
100
101std::vector<std::vector<int>> generateOrthogonalCombinations(const std::vector<int> &maxValues)
102{
103 std::vector<std::vector<int>> combos;
104 std::vector<int> base(maxValues.size(), 0);
105 combos.push_back(base);
106 for (size_t i = 0; i < maxValues.size(); ++i) {
107 for (int v = 1; v < maxValues[i]; ++v) {
108 std::vector<int> tmp = base;
109 tmp[i] = v;
110 combos.push_back(tmp);
111 }
112 }
113 return combos;
114}
115
116void reorderCombinations(std::vector<std::vector<int>> &combos, const std::vector<int> &max,
117 const std::vector<int> &base)
118{
119 for (auto &combo : combos) {
120 for (size_t i = 0; i < combo.size(); ++i) {
121 combo[i] = (combo[i] + base[i]) % max[i];
122 }
123 }
124}
125
126// The RooEvaluatorWrapper uses its own logic to decide what needs to be
127// re-evaluated. We can therefore disable the regular dirty state propagation
128// temporarily during minimization. However, some RooAbsArgs shared with other
129// regular RooFit computation graphs outside the minimized likelihood, so we
130// have to make sure that the operation mode is reset after the minimization.
131//
132// This should be called before running any routine via the _minimizer data
133// member. The RAII object should only be destructed after the routine is done.
134std::unique_ptr<ChangeOperModeRAII> setOperModesDirty(RooAbsReal &function)
135{
136 if (auto *wrapper = dynamic_cast<RooFit::Experimental::RooEvaluatorWrapper *>(&function)) {
137 return wrapper->setOperModes(RooAbsArg::ADirty);
138 }
139 return {};
140}
141
142} // namespace
143
144////////////////////////////////////////////////////////////////////////////////
145/// Construct MINUIT interface to given function. Function can be anything,
146/// but is typically a -log(likelihood) implemented by RooNLLVar or a chi^2
147/// (implemented by RooChi2Var). Other frequent use cases are a RooAddition
148/// of a RooNLLVar plus a penalty or constraint term. This class propagates
149/// all RooFit information (floating parameters, their values and errors)
150/// to MINUIT before each MINUIT call and propagates all MINUIT information
151/// back to the RooFit object at the end of each call (updated parameter
152/// values, their (asymmetric errors) etc. The default MINUIT error level
153/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
154/// value of the input function.
155
156/// Constructor that accepts all configuration in struct with RooAbsReal likelihood
157RooMinimizer::RooMinimizer(RooAbsReal &function, Config const &cfg) : _function{function}, _cfg(cfg)
158{
160 auto nll_real = dynamic_cast<RooFit::TestStatistics::RooRealL *>(&function);
161 if (nll_real != nullptr) {
162 if (_cfg.parallelize != 0) { // new test statistic with multiprocessing library with
163 // parallel likelihood or parallel gradient
164#ifdef ROOFIT_MULTIPROCESS
165 if (!_cfg.enableParallelGradient) {
166 // Note that this is necessary because there is currently no serial-mode LikelihoodGradientWrapper.
167 // We intend to repurpose RooGradMinimizerFcn to build such a LikelihoodGradientSerial class.
168 coutI(InputArguments) << "Modular likelihood detected and likelihood parallelization requested, "
169 << "also setting parallel gradient calculation mode." << std::endl;
170 _cfg.enableParallelGradient = true;
171 }
172 // If _cfg.parallelize is larger than zero set the number of workers to that value. Otherwise do not do
173 // anything and let RooFit::MultiProcess handle the number of workers
174 if (_cfg.parallelize > 0)
177
178 _fcn = std::make_unique<RooFit::TestStatistics::MinuitFcnGrad>(
179 nll_real->getRooAbsL(), this, _config.ParamsSettings(),
181 static_cast<RooFit::TestStatistics::LikelihoodMode>(int(_cfg.enableParallelDescent))},
183#else
184 throw std::logic_error(
185 "Parallel minimization requested, but ROOT was not compiled with multiprocessing enabled, "
186 "please recompile with -Droofit_multiprocess=ON for parallel evaluation");
187#endif
188 } else { // modular test statistic non parallel
189 coutW(InputArguments)
190 << "Requested modular likelihood without gradient parallelization, some features such as offsetting "
191 << "may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl;
192 // The RooRealL that is used in the case where the modular likelihood is being passed to a RooMinimizerFcn does
193 // not have offsetting implemented. Therefore, offsetting will not work in this case. Other features might also
194 // not work since the RooRealL was not intended for minimization. Further development is required to make the
195 // MinuitFcnGrad also handle serial gradient minimization. The MinuitFcnGrad accepts a RooAbsL and has
196 // offsetting implemented, thus omitting the need for RooRealL minimization altogether.
197 _fcn = std::make_unique<RooMinimizerFcn>(&function, this);
198 }
199 } else {
200 if (_cfg.parallelize != 0) { // Old test statistic with parallel likelihood or gradient
201 throw std::logic_error("In RooMinimizer constructor: Selected likelihood evaluation but a "
202 "non-modular likelihood was given. Please supply ModularL(true) as an "
203 "argument to createNLL for modular likelihoods to use likelihood "
204 "or gradient parallelization.");
205 }
206 _fcn = std::make_unique<RooMinimizerFcn>(&function, this);
207 }
208 initMinimizerFcnDependentPart(function.defaultErrorLevel());
209};
210
211/// Initialize the part of the minimizer that is independent of the function to be minimized
213{
214 RooSentinel::activate();
216
217 _config.SetMinimizer(_cfg.minimizerType.c_str());
218 setEps(1.0); // default tolerance
219}
220
221/// Initialize the part of the minimizer that is dependent on the function to be minimized
223{
224 // default max number of calls
225 _config.MinimizerOptions().SetMaxIterations(500 * _fcn->getNDim());
226 _config.MinimizerOptions().SetMaxFunctionCalls(500 * _fcn->getNDim());
227
228 // Shut up for now
229 setPrintLevel(-1);
230
231 // Use +0.5 for 1-sigma errors
232 setErrorLevel(defaultErrorLevel);
233
234 // Declare our parameters to MINUIT
235 _fcn->Synchronize(_config.ParamsSettings());
236
237 // Now set default verbosity
238 setPrintLevel(RooMsgService::instance().silentMode() ? -1 : 1);
239
240 // Set user defined and default _fcn config
241 setLogFile(_cfg.logf);
242
243 // Likelihood holds information on offsetting in old style, so do not set here unless explicitly set by user
244 if (_cfg.offsetting != -1) {
245 setOffsetting(_cfg.offsetting);
246 }
247}
248
249////////////////////////////////////////////////////////////////////////////////
250/// Destructor
251
253
254////////////////////////////////////////////////////////////////////////////////
255/// Change MINUIT strategy to istrat. Accepted codes
256/// are 0,1,2 and represent MINUIT strategies for dealing
257/// most efficiently with fast FCNs (0), expensive FCNs (2)
258/// and 'intermediate' FCNs (1)
259
261{
262 _config.MinimizerOptions().SetStrategy(istrat);
263}
264
265////////////////////////////////////////////////////////////////////////////////
266/// Change maximum number of MINUIT iterations
267/// (RooMinimizer default 500 * #%parameters)
268
270{
271 _config.MinimizerOptions().SetMaxIterations(n);
272}
273
274////////////////////////////////////////////////////////////////////////////////
275/// Change maximum number of likelihood function class from MINUIT
276/// (RooMinimizer default 500 * #%parameters)
277
279{
280 _config.MinimizerOptions().SetMaxFunctionCalls(n);
281}
282
283////////////////////////////////////////////////////////////////////////////////
284/// Set the level for MINUIT error analysis to the given
285/// value. This function overrides the default value
286/// that is taken in the RooMinimizer constructor from
287/// the defaultErrorLevel() method of the input function
288
290{
291 _config.MinimizerOptions().SetErrorDef(level);
292}
293
294////////////////////////////////////////////////////////////////////////////////
295/// Change MINUIT epsilon
296
297void RooMinimizer::setEps(double eps)
298{
299 _config.MinimizerOptions().SetTolerance(eps);
300}
301
302////////////////////////////////////////////////////////////////////////////////
303/// Enable internal likelihood offsetting for enhanced numeric precision
304
306{
307 _cfg.offsetting = flag;
308 _fcn->setOffsetting(_cfg.offsetting);
309}
310
311////////////////////////////////////////////////////////////////////////////////
312/// Choose the minimizer algorithm.
313///
314/// Passing an empty string selects the default minimizer type returned by
315/// ROOT::Math::MinimizerOptions::DefaultMinimizerType().
316
317void RooMinimizer::setMinimizerType(std::string const &type)
318{
319 _cfg.minimizerType = type.empty() ? ROOT::Math::MinimizerOptions::DefaultMinimizerType() : type;
320
321 if ((_cfg.parallelize != 0) && _cfg.minimizerType != "Minuit2") {
322 std::stringstream ss;
323 ss << "In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!";
324 if (type.empty()) {
325 ss << "\nPlease set it as your default minimizer via "
326 "ROOT::Math::MinimizerOptions::SetDefaultMinimizer(\"Minuit2\").";
327 }
328 throw std::invalid_argument(ss.str());
329 }
330}
331
332void RooMinimizer::determineStatus(bool fitterReturnValue)
333{
334 // Minuit-given status:
335 _status = fitterReturnValue ? _result->fStatus : -1;
336
337 // RooFit-based additional failed state information:
338 if (evalCounter() <= _fcn->GetNumInvalidNLL()) {
339 coutE(Minimization) << "RooMinimizer: all function calls during minimization gave invalid NLL values!"
340 << std::endl;
341 }
342}
343
344////////////////////////////////////////////////////////////////////////////////
345/// Minimise the function passed in the constructor.
346/// \param[in] type Type of fitter to use, e.g. "Minuit" "Minuit2". Passing an
347/// empty string will select the default minimizer type of the
348/// RooMinimizer, as returned by
349/// ROOT::Math::MinimizerOptions::DefaultMinimizerType().
350/// \attention This overrides the default fitter of this RooMinimizer.
351/// \param[in] alg Fit algorithm to use. (Optional)
352int RooMinimizer::minimize(const char *type, const char *alg)
353{
354
355 if (_cfg.timingAnalysis) {
356#ifdef ROOFIT_MULTIPROCESS
358#else
359 throw std::logic_error("ProcessTimer, but ROOT was not compiled with multiprocessing enabled, "
360 "please recompile with -Droofit_multiprocess=ON for logging with the "
361 "ProcessTimer.");
362#endif
363 }
364 _fcn->Synchronize(_config.ParamsSettings());
365
366 setMinimizerType(type);
367 _config.SetMinimizer(_cfg.minimizerType.c_str(), alg);
368
369 profileStart();
370 {
371 auto ctx = makeEvalErrorContext();
372
373 bool ret = fitFCN();
375 }
376 profileStop();
377 _fcn->BackProp();
378
379 saveStatus("MINIMIZE", _status);
380
381 return _status;
382}
383
384////////////////////////////////////////////////////////////////////////////////
385/// Execute MIGRAD. Changes in parameter values
386/// and calculated errors are automatically
387/// propagated back the RooRealVars representing
388/// the floating parameters in the MINUIT operation.
389
391{
392 return exec("migrad", "MIGRAD");
393}
394
395int RooMinimizer::exec(std::string const &algoName, std::string const &statusName)
396{
397 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
398
399 _fcn->Synchronize(_config.ParamsSettings());
400 profileStart();
401 {
402 auto ctx = makeEvalErrorContext();
403
404 bool ret = false;
405 if (algoName == "hesse") {
406 // HESSE has a special entry point in the ROOT::Math::Fitter
407 _config.SetMinimizer(_cfg.minimizerType.c_str());
409 } else if (algoName == "minos") {
410 // MINOS has a special entry point in the ROOT::Math::Fitter
411 _config.SetMinimizer(_cfg.minimizerType.c_str());
413 } else {
414 _config.SetMinimizer(_cfg.minimizerType.c_str(), algoName.c_str());
415 ret = fitFCN();
416 }
418 }
419 profileStop();
420 _fcn->BackProp();
421
422 saveStatus(statusName.c_str(), _status);
423
424 return _status;
425}
426
427////////////////////////////////////////////////////////////////////////////////
428/// Execute HESSE. Changes in parameter values
429/// and calculated errors are automatically
430/// propagated back the RooRealVars representing
431/// the floating parameters in the MINUIT operation.
432
434{
435 if (_minimizer == nullptr) {
436 coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!" << std::endl;
437 _status = -1;
438 return _status;
439 }
440
441 return exec("hesse", "HESSE");
442}
443
444////////////////////////////////////////////////////////////////////////////////
445/// Execute MINOS. Changes in parameter values
446/// and calculated errors are automatically
447/// propagated back the RooRealVars representing
448/// the floating parameters in the MINUIT operation.
449
451{
452 if (_minimizer == nullptr) {
453 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
454 _status = -1;
455 return _status;
456 }
457
458 return exec("minos", "MINOS");
459}
460
461////////////////////////////////////////////////////////////////////////////////
462/// Execute MINOS for given list of parameters. Changes in parameter values
463/// and calculated errors are automatically
464/// propagated back the RooRealVars representing
465/// the floating parameters in the MINUIT operation.
466
467int RooMinimizer::minos(const RooArgSet &minosParamList)
468{
469 if (_minimizer == nullptr) {
470 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
471 _status = -1;
472 } else if (!minosParamList.empty()) {
473 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
474
475 _fcn->Synchronize(_config.ParamsSettings());
476 profileStart();
477 {
478 auto ctx = makeEvalErrorContext();
479
480 // get list of parameters for Minos
481 std::vector<unsigned int> paramInd;
482 RooArgList floatParams = _fcn->floatParams();
483 for (RooAbsArg *arg : minosParamList) {
484 RooAbsArg *par = floatParams.find(arg->GetName());
485 if (par && !par->isConstant()) {
486 int index = floatParams.index(par);
487 paramInd.push_back(index);
488 }
489 }
490
491 if (!paramInd.empty()) {
492 // set the parameter indices
493 _config.SetMinosErrors(paramInd);
494
495 _config.SetMinimizer(_cfg.minimizerType.c_str());
496 bool ret = calculateMinosErrors();
498 // to avoid that following minimization computes automatically the Minos errors
499 _config.SetMinosErrors(false);
500 }
501 }
502 profileStop();
503 _fcn->BackProp();
504
505 saveStatus("MINOS", _status);
506 }
507
508 return _status;
509}
510
511////////////////////////////////////////////////////////////////////////////////
512/// Execute SEEK. Changes in parameter values
513/// and calculated errors are automatically
514/// propagated back the RooRealVars representing
515/// the floating parameters in the MINUIT operation.
516
518{
519 return exec("seek", "SEEK");
520}
521
522////////////////////////////////////////////////////////////////////////////////
523/// Execute SIMPLEX. Changes in parameter values
524/// and calculated errors are automatically
525/// propagated back the RooRealVars representing
526/// the floating parameters in the MINUIT operation.
527
529{
530 return exec("simplex", "SIMPLEX");
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
540{
541 return exec("migradimproved", "IMPROVE");
542}
543
544////////////////////////////////////////////////////////////////////////////////
545/// Change the MINUIT internal printing level
546
548{
549 _config.MinimizerOptions().SetPrintLevel(newLevel + 1);
550}
551
552////////////////////////////////////////////////////////////////////////////////
553/// Get the MINUIT internal printing level
554
556{
557 return _config.MinimizerOptions().PrintLevel() + 1;
558}
559
560////////////////////////////////////////////////////////////////////////////////
561/// \deprecated Has no effect anymore. Functionality was removed in ROOT 6.42,
562/// and this function is kept as an empty shell that does nothing (for API
563/// compatibility between different ROOT versions).
564
565void RooMinimizer::optimizeConst(int /*flag*/) {}
566
567////////////////////////////////////////////////////////////////////////////////
568/// Save and return a RooFitResult snapshot of current minimizer status.
569/// This snapshot contains the values of all constant parameters,
570/// the value of all floating parameters at RooMinimizer construction and
571/// after the last MINUIT operation, the MINUIT status, variance quality,
572/// EDM setting, number of calls with evaluation problems, the minimized
573/// function value and the full correlation matrix.
574
575RooFit::OwningPtr<RooFitResult> RooMinimizer::save(const char *userName, const char *userTitle)
576{
577 if (_minimizer == nullptr) {
578 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
579 return nullptr;
580 }
581
582 std::string name = userName ? std::string{userName} : _fcn->getFunctionName();
583 std::string title = userTitle ? std::string{userTitle} : _fcn->getFunctionTitle();
584 auto fitRes = std::make_unique<RooFitResult>(name.c_str(), title.c_str());
585
586 fitRes->setConstParList(_fcn->constParams());
587
588 fitRes->setNumInvalidNLL(_fcn->GetNumInvalidNLL());
589
590 fitRes->setStatus(_status);
591 fitRes->setCovQual(_minimizer->CovMatrixStatus());
592 fitRes->setMinNLL(_result->fVal - _fcn->getOffset());
593 fitRes->setEDM(_result->fEdm);
594
595 fitRes->setInitParList(_fcn->initFloatParams());
596 fitRes->setFinalParList(_fcn->floatParams());
597
598 if (!_extV) {
599 fillCorrMatrix(*fitRes);
600 } else {
601 fitRes->setCovarianceMatrix(*_extV);
602 }
603
604 fitRes->setStatusHistory(_statusHistory);
605
606 return RooFit::makeOwningPtr(std::move(fitRes));
607}
608
609namespace {
610
611/// retrieve covariance matrix element
612double covMatrix(std::vector<double> const &covMat, unsigned int i, unsigned int j)
613{
614 if (covMat.empty())
615 return 0; // no matrix is available in case of non-valid fits
616 return j < i ? covMat[j + i * (i + 1) / 2] : covMat[i + j * (j + 1) / 2];
617}
618
619/// retrieve correlation elements
620double correlation(std::vector<double> const &covMat, unsigned int i, unsigned int j)
621{
622 if (covMat.empty())
623 return 0; // no matrix is available in case of non-valid fits
624 double tmp = covMatrix(covMat, i, i) * covMatrix(covMat, j, j);
625 return tmp > 0 ? covMatrix(covMat, i, j) / std::sqrt(tmp) : 0;
626}
627
628} // namespace
629
631{
632 const std::size_t nParams = _fcn->getNDim();
633 TMatrixDSym corrs(nParams);
634 TMatrixDSym covs(nParams);
635 std::vector<double> globalCC = _minimizer->GlobalCC();
636 globalCC.resize(nParams); // pad with zeros
637 for (std::size_t ic = 0; ic < nParams; ic++) {
638 for (std::size_t ii = 0; ii < nParams; ii++) {
639 corrs(ic, ii) = correlation(_result->fCovMatrix, ic, ii);
640 covs(ic, ii) = covMatrix(_result->fCovMatrix, ic, ii);
641 }
642 }
643 fitRes.fillCorrMatrix(globalCC, corrs, covs);
644}
645
646////////////////////////////////////////////////////////////////////////////////
647/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
648/// \param[in] var1 The first parameter (x axis).
649/// \param[in] var2 The second parameter (y axis).
650/// \param[in] n1 First contour.
651/// \param[in] n2 Optional contour. 0 means don't draw.
652/// \param[in] n3 Optional contour. 0 means don't draw.
653/// \param[in] n4 Optional contour. 0 means don't draw.
654/// \param[in] n5 Optional contour. 0 means don't draw.
655/// \param[in] n6 Optional contour. 0 means don't draw.
656/// \param[in] npoints Number of points for evaluating the contour.
657///
658/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
659/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
660/// See ROOT::Math::Minimizer::ErrorDef().
661
662RooPlot *RooMinimizer::contour(RooRealVar &var1, RooRealVar &var2, double n1, double n2, double n3, double n4,
663 double n5, double n6, unsigned int npoints)
664{
665 RooArgList params = _fcn->floatParams();
666 RooArgList paramSave;
667 params.snapshot(paramSave);
668
669 // Verify that both variables are floating parameters of PDF
670 int index1 = params.index(&var1);
671 if (index1 < 0) {
672 coutE(Minimization) << "RooMinimizer::contour(" << GetName() << ") ERROR: " << var1.GetName()
673 << " is not a floating parameter of " << _fcn->getFunctionName() << std::endl;
674 return nullptr;
675 }
676
677 int index2 = params.index(&var2);
678 if (index2 < 0) {
679 coutE(Minimization) << "RooMinimizer::contour(" << GetName() << ") ERROR: " << var2.GetName()
680 << " is not a floating parameter of PDF " << _fcn->getFunctionName() << std::endl;
681 return nullptr;
682 }
683
684 // create and draw a frame
685 RooPlot *frame = new RooPlot(var1, var2);
686
687 // draw a point at the current parameter values
688 TMarker *point = new TMarker(var1.getVal(), var2.getVal(), 8);
689 frame->addObject(point);
690
691 // check first if a inimizer is available. If not means
692 // the minimization is not done , so do it
693 if (_minimizer == nullptr) {
694 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!" << std::endl;
695 return frame;
696 }
697
698 // remember our original value of ERRDEF
699 double errdef = _minimizer->ErrorDef();
700
701 double n[6];
702 n[0] = n1;
703 n[1] = n2;
704 n[2] = n3;
705 n[3] = n4;
706 n[4] = n5;
707 n[5] = n6;
708
709 auto operModeRAII = setOperModesDirty(_function);
710 for (int ic = 0; ic < 6; ic++) {
711 if (n[ic] > 0) {
712
713 // set the value corresponding to an n1-sigma contour
714 _minimizer->SetErrorDef(n[ic] * n[ic] * errdef);
715
716 // calculate and draw the contour
717 std::vector<double> xcoor(npoints + 1);
718 std::vector<double> ycoor(npoints + 1);
719 bool ret = _minimizer->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
720
721 if (!ret) {
722 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
723 << ") ERROR: MINUIT did not return a contour graph for n=" << n[ic] << std::endl;
724 } else {
725 xcoor[npoints] = xcoor[0];
726 ycoor[npoints] = ycoor[0];
727 TGraph *graph = new TGraph(npoints + 1, xcoor.data(), ycoor.data());
728
729 std::stringstream name;
730 name << "contour_" << _fcn->getFunctionName() << "_n" << n[ic];
731 graph->SetName(name.str().c_str());
732 graph->SetLineStyle(ic + 1);
733 graph->SetLineWidth(2);
734 graph->SetLineColor(kBlue);
735 frame->addObject(graph, "L");
736 }
737 }
738 }
739
740 // restore the original ERRDEF
741 _minimizer->SetErrorDef(errdef);
742
743 // restore parameter values
744 params.assign(paramSave);
745
746 return frame;
747}
748
749////////////////////////////////////////////////////////////////////////////////
750/// Add parameters in metadata field to process timer
751
753{
754#ifdef ROOFIT_MULTIPROCESS
755 // parameter indices for use in timing heat matrix
756 std::vector<std::string> parameter_names;
757 for (RooAbsArg *parameter : _fcn->floatParams()) {
758 parameter_names.push_back(parameter->GetName());
759 if (_cfg.verbose) {
760 coutI(Minimization) << "parameter name: " << parameter_names.back() << std::endl;
761 }
762 }
764#else
765 coutI(Minimization) << "Not adding parameters to processtimer because multiprocessing is not enabled." << std::endl;
766#endif
767}
768
769////////////////////////////////////////////////////////////////////////////////
770/// Start profiling timer
771
773{
774 if (_cfg.profile) {
775 _timer.Start();
776 _cumulTimer.Start(_profileStart ? false : true);
777 _profileStart = true;
778 }
779}
780
781////////////////////////////////////////////////////////////////////////////////
782/// Stop profiling timer and report results of last session
783
785{
786 if (_cfg.profile) {
787 _timer.Stop();
788 _cumulTimer.Stop();
789 coutI(Minimization) << "Command timer: ";
790 _timer.Print();
791 coutI(Minimization) << "Session timer: ";
792 _cumulTimer.Print();
793 }
794}
795
796////////////////////////////////////////////////////////////////////////////////
797/// Apply results of given external covariance matrix. i.e. propagate its errors
798/// to all RRV parameter representations and give this matrix instead of the
799/// HESSE matrix at the next save() call
800
802{
803 _extV.reset(static_cast<TMatrixDSym *>(V.Clone()));
804 _fcn->ApplyCovarianceMatrix(*_extV);
805}
806
808{
809 // Import the results of the last fit performed, interpreting
810 // the fit parameters as the given varList of parameters.
811
812 if (_minimizer == nullptr) {
813 oocoutE(nullptr, InputArguments) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
814 return nullptr;
815 }
816
817 auto res = std::make_unique<RooFitResult>("lastMinuitFit", "Last MINUIT fit");
818
819 // Extract names of fit parameters
820 // and construct corresponding RooRealVars
821 RooArgList constPars("constPars");
822 RooArgList floatPars("floatPars");
823
824 const RooArgList floatParsFromFcn = _fcn->floatParams();
825
826 for (unsigned int i = 0; i < _fcn->getNDim(); ++i) {
827
828 TString varName(floatParsFromFcn.at(i)->GetName());
829 bool isConst(_result->isParameterFixed(i));
830
831 double xlo = _config.ParSettings(i).LowerLimit();
832 double xhi = _config.ParSettings(i).UpperLimit();
833 double xerr = _result->error(i);
834 double xval = _result->fParams[i];
835
836 std::unique_ptr<RooRealVar> var;
837
838 if ((xlo < xhi) && !isConst) {
839 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
840 } else {
841 var = std::make_unique<RooRealVar>(varName, varName, xval);
842 }
843 var->setConstant(isConst);
844
845 if (isConst) {
846 constPars.addOwned(std::move(var));
847 } else {
848 var->setError(xerr);
849 floatPars.addOwned(std::move(var));
850 }
851 }
852
853 res->setConstParList(constPars);
854 res->setInitParList(floatPars);
855 res->setFinalParList(floatPars);
856 res->setMinNLL(_result->fVal);
857 res->setEDM(_result->fEdm);
858 res->setCovQual(_minimizer->CovMatrixStatus());
859 res->setStatus(_result->fStatus);
860 fillCorrMatrix(*res);
861
862 return RooFit::makeOwningPtr(std::move(res));
863}
864
865/// Try to recover from invalid function values. When invalid function values
866/// are encountered, a penalty term is returned to the minimiser to make it
867/// back off. This sets the strength of this penalty. \note A strength of zero
868/// is equivalent to a constant penalty (= the gradient vanishes, ROOT < 6.24).
869/// Positive values lead to a gradient pointing away from the undefined
870/// regions. Use ~10 to force the minimiser away from invalid function values.
872{
873 _cfg.recoverFromNaN = strength;
874}
875
876bool RooMinimizer::setLogFile(const char *logf)
877{
878 _cfg.logf = logf;
879 return _cfg.logf ? _fcn->SetLogFile(_cfg.logf) : false;
880}
881
883{
884 return _fcn->evalCounter();
885}
887{
888 _fcn->zeroEvalCount();
889}
890
892{
893 return _fcn->getNDim();
894}
895
896std::ofstream *RooMinimizer::logfile()
897{
898 return _fcn->GetLogFile();
899}
901{
902 return _fcn->GetMaxFCN();
903}
905{
906 return _fcn->getOffset();
907}
908
909std::unique_ptr<RooAbsReal::EvalErrorContext> RooMinimizer::makeEvalErrorContext() const
910{
912 // If evaluation error printing is disabled, we don't need to collect the
913 // errors and only need to count them. This significantly reduces the
914 // performance overhead when having evaluation errors.
915 auto m = _cfg.printEvalErrors < 0 ? RooAbsReal::CountErrors : RooAbsReal::CollectErrors;
916 return std::make_unique<RooAbsReal::EvalErrorContext>(m);
917}
918
920{
921 // fit a user provided FCN function
922 // create fit parameter settings
923
924 auto operModeRAII = setOperModesDirty(_function);
925
926 // Check number of parameters
927 unsigned int npar = getNPar();
928 if (npar == 0) {
929 coutE(Minimization) << "RooMinimizer::fitFCN(): FCN function has zero parameters" << std::endl;
930 return false;
931 }
932
933 // initiate the minimizer
935
936 // Identify floating RooCategory parameters
937 RooArgSet floatingCats;
938 for (auto arg : _fcn->allParams()) {
939 if (arg->isCategory() && !arg->isConstant())
940 floatingCats.add(*arg);
941 }
942
943 std::vector<RooCategory *> pdfIndices;
944 for (auto *arg : floatingCats) {
945 if (auto *cat = dynamic_cast<RooCategory *>(arg))
946 pdfIndices.push_back(cat);
947 }
948
949 const size_t nPdfs = pdfIndices.size();
950
951 // Identify floating continuous parameters (RooRealVar)
952 RooArgSet floatReals;
953 for (auto arg : _fcn->allParams()) {
954 if (!arg->isCategory() && !arg->isConstant())
955 floatReals.add(*arg);
956 }
957
958 if (nPdfs == 0) {
959 coutI(Minimization) << "[fitFCN] No discrete parameters, performing continuous minimization only" << std::endl;
960 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
961 bool isValid = _minimizer->Minimize();
962 if (!_result)
963 _result = std::make_unique<FitResult>();
964 fillResult(isValid);
965 if (isValid)
967 return isValid;
968 }
969
970 // set also new parameter values and errors in FitConfig
971 // Prepare discrete indices
972 std::vector<int> maxIndices;
973 for (auto *cat : pdfIndices)
974 maxIndices.push_back(cat->size());
975
976 std::set<std::vector<int>> tried;
977 std::map<std::vector<int>, double> nllMap;
978 std::vector<int> bestIndices(nPdfs, 0);
979 double bestNLL = 1e30;
980
981 bool improved = true;
982 while (improved) {
983 improved = false;
984 auto combos = generateOrthogonalCombinations(maxIndices);
985 reorderCombinations(combos, maxIndices, bestIndices);
986
987 for (const auto &combo : combos) {
988 if (tried.count(combo))
989 continue;
990
991 for (size_t i = 0; i < nPdfs; ++i)
992 pdfIndices[i]->setIndex(combo[i]);
993
994 // Freeze categories during continuous minimization
995 std::vector<bool> wasConst(nPdfs);
996 for (size_t i = 0; i < nPdfs; ++i) {
997 wasConst[i] = pdfIndices[i]->isConstant();
998 pdfIndices[i]->setConstant(true);
999 }
1000 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
1001 _minimizer->Minimize();
1002
1003 for (size_t i = 0; i < nPdfs; ++i)
1004 pdfIndices[i]->setConstant(wasConst[i]);
1005
1006 double val = _minimizer->MinValue();
1007 tried.insert(combo);
1008 nllMap[combo] = val;
1009
1010 if (val < bestNLL) {
1011 bestNLL = val;
1012 bestIndices = combo;
1013 improved = true;
1014 }
1015 }
1016 }
1017
1018 for (size_t i = 0; i < nPdfs; ++i) {
1019 pdfIndices[i]->setIndex(bestIndices[i]);
1020 }
1021
1022 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
1023 _minimizer->Minimize();
1024
1025 coutI(Minimization) << "All NLL Values per Combination:" << std::endl;
1026 for (const auto &entry : nllMap) {
1027 const auto &combo = entry.first;
1028 double val = entry.second;
1029
1030 std::stringstream ss;
1031 ss << "Combo: [";
1032 for (size_t i = 0; i < combo.size(); ++i) {
1033 ss << combo[i];
1034 if (i + 1 < combo.size())
1035 ss << ", ";
1036 }
1037 ss << "], NLL: " << val;
1038
1039 coutI(Minimization) << ss.str() << std::endl;
1040 }
1041
1042 std::stringstream ssBest;
1043 ssBest << "DP Best Indices: [";
1044 for (size_t i = 0; i < bestIndices.size(); ++i) {
1045 ssBest << bestIndices[i];
1046 if (i + 1 < bestIndices.size())
1047 ssBest << ", ";
1048 }
1049 ssBest << "], NLL = " << bestNLL;
1050
1051 coutI(Minimization) << ssBest.str() << std::endl;
1052
1053 if (!_result)
1054 _result = std::make_unique<FitResult>();
1055 fillResult(true);
1057
1058 return true;
1059}
1061{
1062 // compute the Hesse errors according to configuration
1063 // set in the parameters and append value in fit result
1064
1065 auto operModeRAII = setOperModesDirty(_function);
1066
1067 // update minimizer (recreate if not done or if name has changed
1068 if (!updateMinimizerOptions()) {
1069 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
1070 return false;
1071 }
1072
1073 // run Hesse
1074 bool ret = _minimizer->Hesse();
1075 if (!ret)
1076 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error when calculating Hessian" << std::endl;
1077
1078 // update minimizer results with what comes out from Hesse
1079 // in case is empty - create from a FitConfig
1080 if (_result->fParams.empty())
1081 _result = std::make_unique<FitResult>(_config);
1082
1083 // re-give a minimizer instance in case it has been changed
1084 ret |= update(ret);
1085
1086 // set also new errors in FitConfig
1087 if (ret)
1089
1090 return ret;
1091}
1092
1094{
1095 // compute the Minos errors according to configuration
1096 // set in the parameters and append value in fit result
1097 // normally Minos errors are computed just after the minimization
1098 // (in DoMinimization) aftewr minimizing if the
1099 // FitConfig::MinosErrors() flag is set
1100
1101 auto operModeRAII = setOperModesDirty(_function);
1102
1103 // update minimizer (but cannot re-create in this case). Must use an existing one
1104 if (!updateMinimizerOptions(false)) {
1105 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
1106 return false;
1107 }
1108
1109 const std::vector<unsigned int> &ipars = _config.MinosParams();
1110 unsigned int n = (!ipars.empty()) ? ipars.size() : _fcn->getNDim();
1111 bool ok = false;
1112
1113 int iparNewMin = 0;
1114 int iparMax = n;
1115 int iter = 0;
1116 // rerun minos for the parameters run before a new Minimum has been found
1117 do {
1118 if (iparNewMin > 0)
1119 coutI(Minimization) << "RooMinimizer::calculateMinosErrors() Run again Minos for some parameters because a "
1120 "new Minimum has been found"
1121 << std::endl;
1122 iparNewMin = 0;
1123 for (int i = 0; i < iparMax; ++i) {
1124 double elow, eup;
1125 unsigned int index = (!ipars.empty()) ? ipars[i] : i;
1126 bool ret = _minimizer->GetMinosError(index, elow, eup);
1127 // flags case when a new minimum has been found
1128 if ((_minimizer->MinosStatus() & 8) != 0) {
1129 iparNewMin = i;
1130 }
1131 if (ret)
1132 _result->fMinosErrors.emplace(index, std::make_pair(elow, eup));
1133 ok |= ret;
1134 }
1135
1136 iparMax = iparNewMin;
1137 iter++; // to avoid infinite looping
1138 } while (iparNewMin > 0 && iter < 10);
1139 if (!ok) {
1140 coutE(Minimization)
1141 << "RooMinimizer::calculateMinosErrors() Minos error calculation failed for all the selected parameters"
1142 << std::endl;
1143 }
1144
1145 // re-give a minimizer instance in case it has been changed
1146 // but maintain previous valid status. Do not set result to false if minos failed
1147 ok &= update(_result->fValid);
1148
1149 return ok;
1150}
1151
1153{
1154 _minimizer = std::unique_ptr<ROOT::Math::Minimizer>(_config.CreateMinimizer());
1155 _fcn->initMinimizer(*_minimizer, this);
1156 _minimizer->SetVariables(_config.ParamsSettings().begin(), _config.ParamsSettings().end());
1157
1158 if (_cfg.setInitialCovariance) {
1159 std::vector<double> v;
1160 for (std::size_t i = 0; i < _fcn->getNDim(); ++i) {
1161 RooRealVar &param = _fcn->floatableParam(i);
1162 v.push_back(param.getError() * param.getError());
1163 }
1164 _minimizer->SetCovarianceDiag(v, v.size());
1165 }
1166}
1167
1168bool RooMinimizer::updateMinimizerOptions(bool canDifferentMinim)
1169{
1170 // update minimizer options when re-doing a Fit or computing Hesse or Minos errors
1171
1172 // create a new minimizer if it is different type
1173 // minimizer type string stored in FitResult is "minimizer name" + " / " + minimizer algo
1174 std::string newMinimType = _config.MinimizerName();
1175 if (_minimizer && _result && newMinimType != _result->fMinimType) {
1176 // if a different minimizer is allowed (e.g. when calling Hesse)
1177 if (canDifferentMinim) {
1178 std::string msg = "Using now " + newMinimType;
1179 coutI(Minimization) << "RooMinimizer::updateMinimizerOptions(): " << msg << std::endl;
1180 initMinimizer();
1181 } else {
1182 std::string msg = "Cannot change minimizer. Continue using " + _result->fMinimType;
1183 coutW(Minimization) << "RooMinimizer::updateMinimizerOptions() " << msg << std::endl;
1184 }
1185 }
1186
1187 // create minimizer if it was not done before
1188 if (!_minimizer) {
1189 initMinimizer();
1190 }
1191
1192 // set new minimizer options (but not functions and parameters)
1193 _minimizer->SetOptions(_config.MinimizerOptions());
1194 return true;
1195}
1196
1198{
1199 // update the fit configuration after a fit using the obtained result
1200 if (_result->fParams.empty() || !_result->fValid)
1201 return;
1202 for (unsigned int i = 0; i < _config.NPar(); ++i) {
1203 ROOT::Fit::ParameterSettings &par = _config.ParSettings(i);
1204 par.SetValue(_result->fParams[i]);
1205 if (_result->error(i) > 0)
1206 par.SetStepSize(_result->error(i));
1207 }
1208}
1209
1211 : fStatus(-99), // use this special convention to flag it when printing result
1212 fCovStatus(0),
1213 fParams(fconfig.NPar()),
1214 fErrors(fconfig.NPar())
1215{
1216 // create a Fit result from a fit config (i.e. with initial parameter values
1217 // and errors equal to step values
1218 // The model function is NULL in this case
1219
1220 // set minimizer type and algorithm
1221 fMinimType = fconfig.MinimizerType();
1222 // append algorithm name for minimizer that support it
1223 if ((fMinimType.find("Fumili") == std::string::npos) && (fMinimType.find("GSLMultiFit") == std::string::npos)) {
1224 if (!fconfig.MinimizerAlgoType().empty())
1225 fMinimType += " / " + fconfig.MinimizerAlgoType();
1226 }
1227
1228 // get parameter values and errors (step sizes)
1229 for (unsigned int i = 0; i < fconfig.NPar(); ++i) {
1230 const ROOT::Fit::ParameterSettings &par = fconfig.ParSettings(i);
1231 fParams[i] = par.Value();
1232 fErrors[i] = par.StepSize();
1233 if (par.IsFixed())
1234 fFixedParams[i] = true;
1235 }
1236}
1237
1239{
1241 ROOT::Fit::FitConfig const &fconfig = _config;
1242
1243 // Fill the FitResult after minimization using result from Minimizers
1244
1245 _result->fValid = isValid;
1246 _result->fStatus = min.Status();
1247 _result->fCovStatus = min.CovMatrixStatus();
1248 _result->fVal = min.MinValue();
1249 _result->fEdm = min.Edm();
1250
1251 _result->fMinimType = fconfig.MinimizerName();
1252
1253 const unsigned int npar = min.NDim();
1254 if (npar == 0)
1255 return;
1256
1257 if (min.X())
1258 _result->fParams = std::vector<double>(min.X(), min.X() + npar);
1259 else {
1260 // case minimizer does not provide minimum values (it failed) take from configuration
1261 _result->fParams.resize(npar);
1262 for (unsigned int i = 0; i < npar; ++i) {
1263 _result->fParams[i] = (fconfig.ParSettings(i).Value());
1264 }
1265 }
1266
1267 // check for fixed or limited parameters
1268 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
1269 if (fconfig.ParSettings(ipar).IsFixed())
1270 _result->fFixedParams[ipar] = true;
1271 }
1272
1273 // fill error matrix
1274 // if minimizer provides error provides also error matrix
1275 // clear in case of re-filling an existing result
1276 _result->fCovMatrix.clear();
1277
1278 if (min.Errors() != nullptr) {
1279 updateErrors();
1280 }
1281}
1282
1283bool RooMinimizer::update(bool isValid)
1284{
1286 ROOT::Fit::FitConfig const &fconfig = _config;
1287
1288 // update fit result with new status from minimizer
1289 // ncalls if it is not zero is used instead of value from minimizer
1290
1291 // in case minimizer changes
1292 _result->fMinimType = fconfig.MinimizerName();
1293
1294 const std::size_t npar = _result->fParams.size();
1295
1296 _result->fValid = isValid;
1297 // update minimum value
1298 _result->fVal = min.MinValue();
1299 _result->fEdm = min.Edm();
1300 _result->fStatus = min.Status();
1301 _result->fCovStatus = min.CovMatrixStatus();
1302
1303 // copy parameter value and errors
1304 std::copy(min.X(), min.X() + npar, _result->fParams.begin());
1305
1306 if (min.Errors() != nullptr) {
1307 updateErrors();
1308 }
1309 return true;
1310}
1311
1313{
1315 const std::size_t npar = _result->fParams.size();
1316
1317 _result->fErrors.resize(npar);
1318 std::copy(min.Errors(), min.Errors() + npar, _result->fErrors.begin());
1319
1320 if (_result->fCovStatus != 0) {
1321
1322 // update error matrix
1323 unsigned int r = npar * (npar + 1) / 2;
1324 _result->fCovMatrix.resize(r);
1325 unsigned int l = 0;
1326 for (unsigned int i = 0; i < npar; ++i) {
1327 for (unsigned int j = 0; j <= i; ++j)
1328 _result->fCovMatrix[l++] = min.CovMatrix(i, j);
1329 }
1330 }
1331 // minos errors are set separately when calling Fitter::CalculateMinosErrors()
1332}
1333
1334double RooMinimizer::FitResult::lowerError(unsigned int i) const
1335{
1336 // return lower Minos error for parameter i
1337 // return the parabolic error if Minos error has not been calculated for the parameter i
1338 auto itr = fMinosErrors.find(i);
1339 return (itr != fMinosErrors.end()) ? itr->second.first : error(i);
1340}
1341
1342double RooMinimizer::FitResult::upperError(unsigned int i) const
1343{
1344 // return upper Minos error for parameter i
1345 // return the parabolic error if Minos error has not been calculated for the parameter i
1346 auto itr = fMinosErrors.find(i);
1347 return (itr != fMinosErrors.end()) ? itr->second.second : error(i);
1348}
1349
1351{
1352 return fFixedParams.find(ipar) != fFixedParams.end();
1353}
1354
1356{
1357 const size_t nParams = fParams.size();
1358 covs.ResizeTo(nParams, nParams);
1359 for (std::size_t ic = 0; ic < nParams; ic++) {
1360 for (std::size_t ii = 0; ii < nParams; ii++) {
1361 covs(ic, ii) = covMatrix(fCovMatrix, ic, ii);
1362 }
1363 }
1364}
ROOT::R::TRInterface & r
Definition Object.C:4
#define coutI(a)
#define coutW(a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
char * ret
Definition Rotated.cxx:221
@ kBlue
Definition Rtypes.h:67
char name[80]
Definition TGX11.cxx:148
TMatrixTSym< Double_t > TMatrixDSym
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
Definition FitConfig.h:49
unsigned int NPar() const
number of parameters settings
Definition FitConfig.h:98
std::string MinimizerName() const
return Minimizer full name (type / algorithm)
const std::string & MinimizerType() const
return type of minimizer package
Definition FitConfig.h:191
const ParameterSettings & ParSettings(unsigned int i) const
get the parameter settings for the i-th parameter (const method)
Definition FitConfig.h:78
Class, describing value, limits and step size of the parameters Provides functionality also to set/re...
bool IsFixed() const
check if is fixed
void SetValue(double val)
set the value
void SetStepSize(double err)
set the step size
double Value() const
return parameter value
double StepSize() const
return step size
static const std::string & DefaultMinimizerType()
Abstract Minimizer class, defining the interface for the various minimizer (like Minuit2,...
Definition Minimizer.h:124
virtual const double * Errors() const
Definition Minimizer.h:263
virtual const double * X() const =0
virtual int CovMatrixStatus() const
Definition Minimizer.h:273
int Status() const
Status code of minimizer.
Definition Minimizer.h:327
virtual double CovMatrix(unsigned int ivar, unsigned int jvar) const
virtual double Edm() const
Definition Minimizer.h:239
virtual double MinValue() const =0
virtual unsigned int NDim() const =0
this is <= Function().NDim() which is the total number of variables (free+ constrained ones)
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:76
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:283
RooAbsCollection * snapshot(bool deepCopy=true) const
Take a snap shot of current collection contents.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
Int_t index(const RooAbsArg *arg) const
Returns index of given arg, or -1 if arg is not in the collection.
void assign(const RooAbsCollection &other) const
Sets the value, cache and constant attribute of any argument in our set that also appears in the othe...
virtual bool addOwned(RooAbsArg &var, bool silent=false)
Add an argument and transfer the ownership to the collection.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
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
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
RooArgSet is a container object that can hold multiple RooAbsArg objects.
Definition RooArgSet.h:24
Object to represent discrete states.
Definition RooCategory.h:28
RooFitResult is a container class to hold the input and output of a PDF fit to a dataset.
void fillCorrMatrix(const std::vector< double > &globalCC, const TMatrixDSym &corrs, const TMatrixDSym &covs)
Function called by RooMinimizer.
static void setDefaultNWorkers(unsigned int N_workers)
Definition Config.cxx:67
static void setTimingAnalysis(bool timingAnalysis)
Definition Config.cxx:78
static void add_metadata(json data)
RooAbsReal that wraps RooAbsL likelihoods for use in RooFit outside of the RooMinimizer context.
Definition RooRealL.h:28
void setRecoverFromNaNStrength(double strength)
Try to recover from invalid function values.
int getPrintLevel()
Get the MINUIT internal printing level.
void optimizeConst(int flag)
void initMinimizerFirstPart()
Initialize the part of the minimizer that is independent of the function to be minimized.
std::ofstream * logfile()
int simplex()
Execute SIMPLEX.
std::unique_ptr< TMatrixDSym > _extV
void setMinimizerType(std::string const &type)
Choose the minimizer algorithm.
RooFit::OwningPtr< RooFitResult > save(const char *name=nullptr, const char *title=nullptr)
Save and return a RooFitResult snapshot of current minimizer status.
std::vector< std::pair< std::string, int > > _statusHistory
void profileStart()
Start profiling timer.
RooPlot * contour(RooRealVar &var1, RooRealVar &var2, double n1=1.0, double n2=2.0, double n3=0.0, double n4=0.0, double n5=0.0, double n6=0.0, unsigned int npoints=50)
Create and draw a TH2 with the error contours in the parameters var1 and var2.
std::unique_ptr< ROOT::Math::Minimizer > _minimizer
! pointer to used minimizer
bool setLogFile(const char *logf=nullptr)
void initMinimizerFcnDependentPart(double defaultErrorLevel)
Initialize the part of the minimizer that is dependent on the function to be minimized.
void fillCorrMatrix(RooFitResult &fitRes)
double & fcnOffset() const
ROOT::Fit::FitConfig _config
fitter configuration (options and parameter settings)
void profileStop()
Stop profiling timer and report results of last session.
int minos()
Execute MINOS.
double & maxFCN()
bool calculateHessErrors()
RooAbsReal & _function
int hesse()
Execute HESSE.
bool calculateMinosErrors()
void setErrorLevel(double level)
Set the level for MINUIT error analysis to the given value.
void determineStatus(bool fitterReturnValue)
int migrad()
Execute MIGRAD.
bool update(bool isValid)
int seek()
Execute SEEK.
bool updateMinimizerOptions(bool canDifferentMinim=true)
void setEps(double eps)
Change MINUIT epsilon.
void setPrintLevel(int newLevel)
Change the MINUIT internal printing level.
void fillResult(bool isValid)
int exec(std::string const &algoName, std::string const &statusName)
int improve()
Execute IMPROVE.
void setOffsetting(bool flag)
Enable internal likelihood offsetting for enhanced numeric precision.
TStopwatch _timer
RooMinimizer::Config _cfg
std::unique_ptr< FitResult > _result
! pointer to the object containing the result of the fit
RooFit::OwningPtr< RooFitResult > lastMinuitFit()
void saveStatus(const char *label, int status)
~RooMinimizer() override
Destructor.
int minimize(const char *type, const char *alg=nullptr)
Minimise the function passed in the constructor.
std::unique_ptr< RooAbsReal::EvalErrorContext > makeEvalErrorContext() const
RooMinimizer(RooAbsReal &function, Config const &cfg={})
Construct MINUIT interface to given function.
void setMaxFunctionCalls(int n)
Change maximum number of likelihood function class from MINUIT (RooMinimizer default 500 * #parameter...
void setStrategy(int istrat)
Change MINUIT strategy to istrat.
int evalCounter() const
TStopwatch _cumulTimer
int getNPar() const
void setMaxIterations(int n)
Change maximum number of MINUIT iterations (RooMinimizer default 500 * #parameters).
void addParamsToProcessTimer()
Add parameters in metadata field to process timer.
std::unique_ptr< RooAbsMinimizerFcn > _fcn
void applyCovarianceMatrix(TMatrixDSym const &V)
Apply results of given external covariance matrix.
static RooMsgService & instance()
Return reference to singleton instance.
Plot frame and a container for graphics objects within that frame.
Definition RooPlot.h:43
void addObject(TObject *obj, Option_t *drawOptions="", bool invisible=false)
Add a generic object to this plot.
Definition RooPlot.cxx:326
Variable that can be changed from the outside.
Definition RooRealVar.h:37
double getError() const
Definition RooRealVar.h:59
virtual void SetLineStyle(Style_t lstyle)
Set the line style.
Definition TAttLine.h:46
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition TAttLine.h:47
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:44
void SetName(const char *name="") override
Set the name of the TNamed.
Manages Markers.
Definition TMarker.h:22
TMatrixTBase< Element > & ResizeTo(Int_t nrows, Int_t ncols, Int_t=-1) override
Set size of the matrix to nrows x ncols New dynamic elements are created, the overlapping part of the...
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:462
Basic string class.
Definition TString.h:138
const Int_t n
Definition legend1.C:16
for(Int_t i=0;i< n;i++)
Definition legend1.C:18
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Definition Config.h:35
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
Definition Config.h:40
bool setAllConstant(const RooAbsCollection &coll, bool constant=true)
set all RooRealVars to constants. return true if at least one changed status
Config argument to RooMinimizer constructor.
std::map< unsigned int, std::pair< double, double > > fMinosErrors
map contains the two Minos errors
double upperError(unsigned int i) const
std::string fMinimType
string indicating type of minimizer
std::vector< double > fErrors
errors
double error(unsigned int i) const
std::vector< double > fParams
parameter values. Size is total number of parameters
void GetCovarianceMatrix(TMatrixDSym &cov) const
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
bool isParameterFixed(unsigned int ipar) const
int fCovStatus
covariance matrix status code
std::vector< double > fCovMatrix
covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
int fStatus
minimizer status code
double lowerError(unsigned int i) const
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4