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