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