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"
59#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(*_fcn->getMultiGenFcn());
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(*_fcn->getMultiGenFcn());
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/// If flag is true, perform constant term optimization on
543/// function being minimized.
544
546{
547 _fcn->setOptimizeConst(flag);
548}
549
550////////////////////////////////////////////////////////////////////////////////
551/// Save and return a RooFitResult snapshot of current minimizer status.
552/// This snapshot contains the values of all constant parameters,
553/// the value of all floating parameters at RooMinimizer construction and
554/// after the last MINUIT operation, the MINUIT status, variance quality,
555/// EDM setting, number of calls with evaluation problems, the minimized
556/// function value and the full correlation matrix.
557
559{
560 if (_minimizer == nullptr) {
561 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
562 return nullptr;
563 }
564
565 std::string name = userName ? std::string{userName} : _fcn->getFunctionName();
566 std::string title = userTitle ? std::string{userTitle} : _fcn->getFunctionTitle();
567 auto fitRes = std::make_unique<RooFitResult>(name.c_str(), title.c_str());
568
569 fitRes->setConstParList(_fcn->constParams());
570
571 fitRes->setNumInvalidNLL(_fcn->GetNumInvalidNLL());
572
573 fitRes->setStatus(_status);
574 fitRes->setCovQual(_minimizer->CovMatrixStatus());
575 fitRes->setMinNLL(_result->fVal - _fcn->getOffset());
576 fitRes->setEDM(_result->fEdm);
577
578 fitRes->setInitParList(_fcn->initFloatParams());
579 fitRes->setFinalParList(_fcn->floatParams());
580
581 if (!_extV) {
583 } else {
584 fitRes->setCovarianceMatrix(*_extV);
585 }
586
587 fitRes->setStatusHistory(_statusHistory);
588
589 return RooFit::makeOwningPtr(std::move(fitRes));
590}
591
592namespace {
593
594/// retrieve covariance matrix element
595double covMatrix(std::vector<double> const &covMat, unsigned int i, unsigned int j)
596{
597 if (covMat.empty())
598 return 0; // no matrix is available in case of non-valid fits
599 return j < i ? covMat[j + i * (i + 1) / 2] : covMat[i + j * (j + 1) / 2];
600}
601
602/// retrieve correlation elements
603double correlation(std::vector<double> const &covMat, unsigned int i, unsigned int j)
604{
605 if (covMat.empty())
606 return 0; // no matrix is available in case of non-valid fits
607 double tmp = covMatrix(covMat, i, i) * covMatrix(covMat, j, j);
608 return tmp > 0 ? covMatrix(covMat, i, j) / std::sqrt(tmp) : 0;
609}
610
611} // namespace
612
614{
615 const std::size_t nParams = _fcn->getNDim();
616 std::vector<double> globalCC;
619 for (std::size_t ic = 0; ic < nParams; ic++) {
620 globalCC.push_back(_result->fGlobalCC[ic]);
621 for (std::size_t ii = 0; ii < nParams; ii++) {
622 corrs(ic, ii) = correlation(_result->fCovMatrix, ic, ii);
623 covs(ic, ii) = covMatrix(_result->fCovMatrix, ic, ii);
624 }
625 }
626 fitRes.fillCorrMatrix(globalCC, corrs, covs);
627}
628
629////////////////////////////////////////////////////////////////////////////////
630/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
631/// \param[in] var1 The first parameter (x axis).
632/// \param[in] var2 The second parameter (y axis).
633/// \param[in] n1 First contour.
634/// \param[in] n2 Optional contour. 0 means don't draw.
635/// \param[in] n3 Optional contour. 0 means don't draw.
636/// \param[in] n4 Optional contour. 0 means don't draw.
637/// \param[in] n5 Optional contour. 0 means don't draw.
638/// \param[in] n6 Optional contour. 0 means don't draw.
639/// \param[in] npoints Number of points for evaluating the contour.
640///
641/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
642/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
643/// See ROOT::Math::Minimizer::ErrorDef().
644
645RooPlot *RooMinimizer::contour(RooRealVar &var1, RooRealVar &var2, double n1, double n2, double n3, double n4,
646 double n5, double n6, unsigned int npoints)
647{
648 RooArgList params = _fcn->floatParams();
650 params.snapshot(paramSave);
651
652 // Verify that both variables are floating parameters of PDF
653 int index1 = params.index(&var1);
654 if (index1 < 0) {
655 coutE(Minimization) << "RooMinimizer::contour(" << GetName() << ") ERROR: " << var1.GetName()
656 << " is not a floating parameter of " << _fcn->getFunctionName() << std::endl;
657 return nullptr;
658 }
659
660 int index2 = params.index(&var2);
661 if (index2 < 0) {
662 coutE(Minimization) << "RooMinimizer::contour(" << GetName() << ") ERROR: " << var2.GetName()
663 << " is not a floating parameter of PDF " << _fcn->getFunctionName() << std::endl;
664 return nullptr;
665 }
666
667 // create and draw a frame
668 RooPlot *frame = new RooPlot(var1, var2);
669
670 // draw a point at the current parameter values
671 TMarker *point = new TMarker(var1.getVal(), var2.getVal(), 8);
672 frame->addObject(point);
673
674 // check first if a inimizer is available. If not means
675 // the minimization is not done , so do it
676 if (_minimizer == nullptr) {
677 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!" << std::endl;
678 return frame;
679 }
680
681 // remember our original value of ERRDEF
682 double errdef = _minimizer->ErrorDef();
683
684 double n[6];
685 n[0] = n1;
686 n[1] = n2;
687 n[2] = n3;
688 n[3] = n4;
689 n[4] = n5;
690 n[5] = n6;
691
692 for (int ic = 0; ic < 6; ic++) {
693 if (n[ic] > 0) {
694
695 // set the value corresponding to an n1-sigma contour
696 _minimizer->SetErrorDef(n[ic] * n[ic] * errdef);
697
698 // calculate and draw the contour
699 std::vector<double> xcoor(npoints + 1);
700 std::vector<double> ycoor(npoints + 1);
701 bool ret = _minimizer->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
702
703 if (!ret) {
704 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
705 << ") ERROR: MINUIT did not return a contour graph for n=" << n[ic] << std::endl;
706 } else {
707 xcoor[npoints] = xcoor[0];
708 ycoor[npoints] = ycoor[0];
709 TGraph *graph = new TGraph(npoints + 1, xcoor.data(), ycoor.data());
710
711 std::stringstream name;
712 name << "contour_" << _fcn->getFunctionName() << "_n" << n[ic];
713 graph->SetName(name.str().c_str());
714 graph->SetLineStyle(ic + 1);
715 graph->SetLineWidth(2);
716 graph->SetLineColor(kBlue);
717 frame->addObject(graph, "L");
718 }
719 }
720 }
721
722 // restore the original ERRDEF
723 _minimizer->SetErrorDef(errdef);
724
725 // restore parameter values
726 params.assign(paramSave);
727
728 return frame;
729}
730
731////////////////////////////////////////////////////////////////////////////////
732/// Add parameters in metadata field to process timer
733
735{
736#ifdef ROOFIT_MULTIPROCESS
737 // parameter indices for use in timing heat matrix
738 std::vector<std::string> parameter_names;
739 for (RooAbsArg *parameter : _fcn->floatParams()) {
740 parameter_names.push_back(parameter->GetName());
741 if (_cfg.verbose) {
742 coutI(Minimization) << "parameter name: " << parameter_names.back() << std::endl;
743 }
744 }
746#else
747 coutI(Minimization) << "Not adding parameters to processtimer because multiprocessing is not enabled." << std::endl;
748#endif
749}
750
751////////////////////////////////////////////////////////////////////////////////
752/// Start profiling timer
753
755{
756 if (_cfg.profile) {
757 _timer.Start();
758 _cumulTimer.Start(_profileStart ? false : true);
759 _profileStart = true;
760 }
761}
762
763////////////////////////////////////////////////////////////////////////////////
764/// Stop profiling timer and report results of last session
765
767{
768 if (_cfg.profile) {
769 _timer.Stop();
771 coutI(Minimization) << "Command timer: ";
772 _timer.Print();
773 coutI(Minimization) << "Session timer: ";
775 }
776}
777
779{
780
781 return _fcn->getMultiGenFcn();
782}
783
784////////////////////////////////////////////////////////////////////////////////
785/// Apply results of given external covariance matrix. i.e. propagate its errors
786/// to all RRV parameter representations and give this matrix instead of the
787/// HESSE matrix at the next save() call
788
790{
791 _extV.reset(static_cast<TMatrixDSym *>(V.Clone()));
792 _fcn->ApplyCovarianceMatrix(*_extV);
793}
794
796{
797 // Import the results of the last fit performed, interpreting
798 // the fit parameters as the given varList of parameters.
799
800 if (_minimizer == nullptr) {
801 oocoutE(nullptr, InputArguments) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
802 return nullptr;
803 }
804
805 auto res = std::make_unique<RooFitResult>("lastMinuitFit", "Last MINUIT fit");
806
807 // Extract names of fit parameters
808 // and construct corresponding RooRealVars
809 RooArgList constPars("constPars");
810 RooArgList floatPars("floatPars");
811
812 const RooArgList floatParsFromFcn = _fcn->floatParams();
813
814 for (unsigned int i = 0; i < _fcn->getNDim(); ++i) {
815
816 TString varName(floatParsFromFcn.at(i)->GetName());
817 bool isConst(_result->isParameterFixed(i));
818
819 double xlo = _config.ParSettings(i).LowerLimit();
820 double xhi = _config.ParSettings(i).UpperLimit();
821 double xerr = _result->error(i);
822 double xval = _result->fParams[i];
823
824 std::unique_ptr<RooRealVar> var;
825
826 if ((xlo < xhi) && !isConst) {
827 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
828 } else {
829 var = std::make_unique<RooRealVar>(varName, varName, xval);
830 }
831 var->setConstant(isConst);
832
833 if (isConst) {
834 constPars.addOwned(std::move(var));
835 } else {
836 var->setError(xerr);
837 floatPars.addOwned(std::move(var));
838 }
839 }
840
841 res->setConstParList(constPars);
842 res->setInitParList(floatPars);
843 res->setFinalParList(floatPars);
844 res->setMinNLL(_result->fVal);
845 res->setEDM(_result->fEdm);
846 res->setCovQual(_minimizer->CovMatrixStatus());
847 res->setStatus(_result->fStatus);
848 fillCorrMatrix(*res);
849
850 return RooFit::makeOwningPtr(std::move(res));
851}
852
853/// Try to recover from invalid function values. When invalid function values
854/// are encountered, a penalty term is returned to the minimiser to make it
855/// back off. This sets the strength of this penalty. \note A strength of zero
856/// is equivalent to a constant penalty (= the gradient vanishes, ROOT < 6.24).
857/// Positive values lead to a gradient pointing away from the undefined
858/// regions. Use ~10 to force the minimiser away from invalid function values.
863
864bool RooMinimizer::setLogFile(const char *logf)
865{
866 _cfg.logf = logf;
867 return _cfg.logf ? _fcn->SetLogFile(_cfg.logf) : false;
868}
869
871{
872 return _fcn->evalCounter();
873}
875{
876 _fcn->zeroEvalCount();
877}
878
880{
881 return _fcn->getNDim();
882}
883
884std::ofstream *RooMinimizer::logfile()
885{
886 return _fcn->GetLogFile();
887}
889{
890 return _fcn->GetMaxFCN();
891}
893{
894 return _fcn->getOffset();
895}
896
897std::unique_ptr<RooAbsReal::EvalErrorContext> RooMinimizer::makeEvalErrorContext() const
898{
900 // If evaluation error printing is disabled, we don't need to collect the
901 // errors and only need to count them. This significantly reduces the
902 // performance overhead when having evaluation errors.
904 return std::make_unique<RooAbsReal::EvalErrorContext>(m);
905}
906
908{
909 // fit a user provided FCN function
910 // create fit parameter settings
911
912 // Check number of parameters
913 unsigned int npar = fcn.NDim();
914 if (npar == 0) {
915 coutE(Minimization) << "RooMinimizer::fitFCN(): FCN function has zero parameters" << std::endl;
916 return false;
917 }
918
919 // initiate the minimizer
921
922 // Identify floating RooCategory parameters
924 for (auto arg : _fcn->allParams()) {
925 if (arg->isCategory() && !arg->isConstant())
926 floatingCats.add(*arg);
927 }
928
929 std::vector<RooCategory *> pdfIndices;
930 for (auto *arg : floatingCats) {
931 if (auto *cat = dynamic_cast<RooCategory *>(arg))
932 pdfIndices.push_back(cat);
933 }
934
935 const size_t nPdfs = pdfIndices.size();
936
937 // Identify floating continuous parameters (RooRealVar)
939 for (auto arg : _fcn->allParams()) {
940 if (!arg->isCategory() && !arg->isConstant())
941 floatReals.add(*arg);
942 }
943
944 if (nPdfs == 0) {
945 coutI(Minimization) << "[fitFCN] No discrete parameters, performing continuous minimization only" << std::endl;
946 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
947 bool isValid = _minimizer->Minimize();
948 if (!_result)
949 _result = std::make_unique<FitResult>();
950 fillResult(isValid);
951 if (isValid)
953 return isValid;
954 }
955
956 // set also new parameter values and errors in FitConfig
957 // Prepare discrete indices
958 std::vector<int> maxIndices;
959 for (auto *cat : pdfIndices)
960 maxIndices.push_back(cat->size());
961
962 std::set<std::vector<int>> tried;
963 std::map<std::vector<int>, double> nllMap;
964 std::vector<int> bestIndices(nPdfs, 0);
965 double bestNLL = 1e30;
966
967 bool improved = true;
968 while (improved) {
969 improved = false;
972
973 for (const auto &combo : combos) {
974 if (tried.count(combo))
975 continue;
976
977 for (size_t i = 0; i < nPdfs; ++i)
978 pdfIndices[i]->setIndex(combo[i]);
979
980 // Freeze categories during continuous minimization
981 std::vector<bool> wasConst(nPdfs);
982 for (size_t i = 0; i < nPdfs; ++i) {
983 wasConst[i] = pdfIndices[i]->isConstant();
984 pdfIndices[i]->setConstant(true);
985 }
986 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
987 _minimizer->Minimize();
988
989 for (size_t i = 0; i < nPdfs; ++i)
990 pdfIndices[i]->setConstant(wasConst[i]);
991
992 double val = _minimizer->MinValue();
993 tried.insert(combo);
994 nllMap[combo] = val;
995
996 if (val < bestNLL) {
997 bestNLL = val;
999 improved = true;
1000 }
1001 }
1002 }
1003
1004 for (size_t i = 0; i < nPdfs; ++i) {
1005 pdfIndices[i]->setIndex(bestIndices[i]);
1006 }
1007
1008 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
1009 _minimizer->Minimize();
1010
1011 coutI(Minimization) << "All NLL Values per Combination:" << std::endl;
1012 for (const auto &entry : nllMap) {
1013 const auto &combo = entry.first;
1014 double val = entry.second;
1015
1016 std::stringstream ss;
1017 ss << "Combo: [";
1018 for (size_t i = 0; i < combo.size(); ++i) {
1019 ss << combo[i];
1020 if (i + 1 < combo.size())
1021 ss << ", ";
1022 }
1023 ss << "], NLL: " << val;
1024
1025 coutI(Minimization) << ss.str() << std::endl;
1026 }
1027
1028 std::stringstream ssBest;
1029 ssBest << "DP Best Indices: [";
1030 for (size_t i = 0; i < bestIndices.size(); ++i) {
1031 ssBest << bestIndices[i];
1032 if (i + 1 < bestIndices.size())
1033 ssBest << ", ";
1034 }
1035 ssBest << "], NLL = " << bestNLL;
1036
1037 coutI(Minimization) << ssBest.str() << std::endl;
1038
1039 if (!_result)
1040 _result = std::make_unique<FitResult>();
1041 fillResult(true);
1043
1044 return true;
1045}
1047{
1048 // compute the Hesse errors according to configuration
1049 // set in the parameters and append value in fit result
1050
1051 // update minimizer (recreate if not done or if name has changed
1052 if (!updateMinimizerOptions()) {
1053 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
1054 return false;
1055 }
1056
1057 // run Hesse
1058 bool ret = _minimizer->Hesse();
1059 if (!ret)
1060 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error when calculating Hessian" << std::endl;
1061
1062 // update minimizer results with what comes out from Hesse
1063 // in case is empty - create from a FitConfig
1064 if (_result->fParams.empty())
1065 _result = std::make_unique<FitResult>(_config);
1066
1067 // re-give a minimizer instance in case it has been changed
1068 ret |= update(ret);
1069
1070 // set also new errors in FitConfig
1071 if (ret)
1073
1074 return ret;
1075}
1076
1078{
1079 // compute the Minos errors according to configuration
1080 // set in the parameters and append value in fit result
1081 // normally Minos errors are computed just after the minimization
1082 // (in DoMinimization) aftewr minimizing if the
1083 // FitConfig::MinosErrors() flag is set
1084
1085 // update minimizer (but cannot re-create in this case). Must use an existing one
1086 if (!updateMinimizerOptions(false)) {
1087 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
1088 return false;
1089 }
1090
1091 const std::vector<unsigned int> &ipars = _config.MinosParams();
1092 unsigned int n = (!ipars.empty()) ? ipars.size() : _fcn->getNDim();
1093 bool ok = false;
1094
1095 int iparNewMin = 0;
1096 int iparMax = n;
1097 int iter = 0;
1098 // rerun minos for the parameters run before a new Minimum has been found
1099 do {
1100 if (iparNewMin > 0)
1101 coutI(Minimization) << "RooMinimizer::calculateMinosErrors() Run again Minos for some parameters because a "
1102 "new Minimum has been found"
1103 << std::endl;
1104 iparNewMin = 0;
1105 for (int i = 0; i < iparMax; ++i) {
1106 double elow, eup;
1107 unsigned int index = (!ipars.empty()) ? ipars[i] : i;
1108 bool ret = _minimizer->GetMinosError(index, elow, eup);
1109 // flags case when a new minimum has been found
1110 if ((_minimizer->MinosStatus() & 8) != 0) {
1111 iparNewMin = i;
1112 }
1113 if (ret)
1114 _result->fMinosErrors.emplace(index, std::make_pair(elow, eup));
1115 ok |= ret;
1116 }
1117
1119 iter++; // to avoid infinite looping
1120 } while (iparNewMin > 0 && iter < 10);
1121 if (!ok) {
1122 coutE(Minimization)
1123 << "RooMinimizer::calculateMinosErrors() Minos error calculation failed for all the selected parameters"
1124 << std::endl;
1125 }
1126
1127 // re-give a minimizer instance in case it has been changed
1128 // but maintain previous valid status. Do not set result to false if minos failed
1129 ok &= update(_result->fValid);
1130
1131 return ok;
1132}
1133
1135{
1136 _minimizer = std::unique_ptr<ROOT::Math::Minimizer>(_config.CreateMinimizer());
1137 _minimizer->SetFunction(*getMultiGenFcn());
1139
1141 std::vector<double> v;
1142 for (std::size_t i = 0; i < _fcn->getNDim(); ++i) {
1143 RooRealVar &param = _fcn->floatableParam(i);
1144 v.push_back(param.getError() * param.getError());
1145 }
1146 _minimizer->SetCovarianceDiag(v, v.size());
1147 }
1148}
1149
1151{
1152 // update minimizer options when re-doing a Fit or computing Hesse or Minos errors
1153
1154 // create a new minimizer if it is different type
1155 // minimizer type string stored in FitResult is "minimizer name" + " / " + minimizer algo
1156 std::string newMinimType = _config.MinimizerName();
1157 if (_minimizer && _result && newMinimType != _result->fMinimType) {
1158 // if a different minimizer is allowed (e.g. when calling Hesse)
1159 if (canDifferentMinim) {
1160 std::string msg = "Using now " + newMinimType;
1161 coutI(Minimization) << "RooMinimizer::updateMinimizerOptions(): " << msg << std::endl;
1162 initMinimizer();
1163 } else {
1164 std::string msg = "Cannot change minimizer. Continue using " + _result->fMinimType;
1165 coutW(Minimization) << "RooMinimizer::updateMinimizerOptions() " << msg << std::endl;
1166 }
1167 }
1168
1169 // create minimizer if it was not done before
1170 if (!_minimizer) {
1171 initMinimizer();
1172 }
1173
1174 // set new minimizer options (but not functions and parameters)
1175 _minimizer->SetOptions(_config.MinimizerOptions());
1176 return true;
1177}
1178
1180{
1181 // update the fit configuration after a fit using the obtained result
1182 if (_result->fParams.empty() || !_result->fValid)
1183 return;
1184 for (unsigned int i = 0; i < _config.NPar(); ++i) {
1186 par.SetValue(_result->fParams[i]);
1187 if (_result->error(i) > 0)
1188 par.SetStepSize(_result->error(i));
1189 }
1190}
1191
1193 : fStatus(-99), // use this special convention to flag it when printing result
1194 fCovStatus(0),
1195 fParams(fconfig.NPar()),
1196 fErrors(fconfig.NPar())
1197{
1198 // create a Fit result from a fit config (i.e. with initial parameter values
1199 // and errors equal to step values
1200 // The model function is NULL in this case
1201
1202 // set minimizer type and algorithm
1203 fMinimType = fconfig.MinimizerType();
1204 // append algorithm name for minimizer that support it
1205 if ((fMinimType.find("Fumili") == std::string::npos) && (fMinimType.find("GSLMultiFit") == std::string::npos)) {
1206 if (!fconfig.MinimizerAlgoType().empty())
1207 fMinimType += " / " + fconfig.MinimizerAlgoType();
1208 }
1209
1210 // get parameter values and errors (step sizes)
1211 for (unsigned int i = 0; i < fconfig.NPar(); ++i) {
1212 const ROOT::Fit::ParameterSettings &par = fconfig.ParSettings(i);
1213 fParams[i] = par.Value();
1214 fErrors[i] = par.StepSize();
1215 if (par.IsFixed())
1216 fFixedParams[i] = true;
1217 }
1218}
1219
1221{
1224
1225 // Fill the FitResult after minimization using result from Minimizers
1226
1227 _result->fValid = isValid;
1228 _result->fStatus = min.Status();
1229 _result->fCovStatus = min.CovMatrixStatus();
1230 _result->fVal = min.MinValue();
1231 _result->fEdm = min.Edm();
1232
1233 _result->fMinimType = fconfig.MinimizerName();
1234
1235 const unsigned int npar = min.NDim();
1236 if (npar == 0)
1237 return;
1238
1239 if (min.X())
1240 _result->fParams = std::vector<double>(min.X(), min.X() + npar);
1241 else {
1242 // case minimizer does not provide minimum values (it failed) take from configuration
1243 _result->fParams.resize(npar);
1244 for (unsigned int i = 0; i < npar; ++i) {
1245 _result->fParams[i] = (fconfig.ParSettings(i).Value());
1246 }
1247 }
1248
1249 // check for fixed or limited parameters
1250 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
1251 if (fconfig.ParSettings(ipar).IsFixed())
1252 _result->fFixedParams[ipar] = true;
1253 }
1254
1255 // fill error matrix
1256 // if minimizer provides error provides also error matrix
1257 // clear in case of re-filling an existing result
1258 _result->fCovMatrix.clear();
1259 _result->fGlobalCC.clear();
1260
1261 if (min.Errors() != nullptr) {
1262 updateErrors();
1263 }
1264}
1265
1266bool RooMinimizer::update(bool isValid)
1267{
1270
1271 // update fit result with new status from minimizer
1272 // ncalls if it is not zero is used instead of value from minimizer
1273
1274 // in case minimizer changes
1275 _result->fMinimType = fconfig.MinimizerName();
1276
1277 const std::size_t npar = _result->fParams.size();
1278
1279 _result->fValid = isValid;
1280 // update minimum value
1281 _result->fVal = min.MinValue();
1282 _result->fEdm = min.Edm();
1283 _result->fStatus = min.Status();
1284 _result->fCovStatus = min.CovMatrixStatus();
1285
1286 // copy parameter value and errors
1287 std::copy(min.X(), min.X() + npar, _result->fParams.begin());
1288
1289 if (min.Errors() != nullptr) {
1290 updateErrors();
1291 }
1292 return true;
1293}
1294
1296{
1298 const std::size_t npar = _result->fParams.size();
1299
1300 _result->fErrors.resize(npar);
1301 std::copy(min.Errors(), min.Errors() + npar, _result->fErrors.begin());
1302
1303 if (_result->fCovStatus != 0) {
1304
1305 // update error matrix
1306 unsigned int r = npar * (npar + 1) / 2;
1307 _result->fCovMatrix.resize(r);
1308 unsigned int l = 0;
1309 for (unsigned int i = 0; i < npar; ++i) {
1310 for (unsigned int j = 0; j <= i; ++j)
1311 _result->fCovMatrix[l++] = min.CovMatrix(i, j);
1312 }
1313 }
1314 // minos errors are set separately when calling Fitter::CalculateMinosErrors()
1315
1316 // update global CC
1317 _result->fGlobalCC.resize(npar);
1318 for (unsigned int i = 0; i < npar; ++i) {
1319 double globcc = min.GlobalCC(i);
1320 if (globcc < 0) {
1321 _result->fGlobalCC.clear();
1322 break; // it is not supported by that minimizer
1323 }
1324 _result->fGlobalCC[i] = globcc;
1325 }
1326}
1327
1328double RooMinimizer::FitResult::lowerError(unsigned int i) const
1329{
1330 // return lower Minos error for parameter i
1331 // return the parabolic error if Minos error has not been calculated for the parameter i
1332 auto itr = fMinosErrors.find(i);
1333 return (itr != fMinosErrors.end()) ? itr->second.first : error(i);
1334}
1335
1336double RooMinimizer::FitResult::upperError(unsigned int i) const
1337{
1338 // return upper Minos error for parameter i
1339 // return the parabolic error if Minos error has not been calculated for the parameter i
1340 auto itr = fMinosErrors.find(i);
1341 return (itr != fMinosErrors.end()) ? itr->second.second : error(i);
1342}
1343
1345{
1346 return fFixedParams.find(ipar) != fFixedParams.end();
1347}
1348
1350{
1351 const size_t nParams = fParams.size();
1352 covs.ResizeTo(nParams, nParams);
1353 for (std::size_t ic = 0; ic < nParams; ic++) {
1354 for (std::size_t ii = 0; ii < nParams; ii++) {
1355 covs(ic, ii) = covMatrix(fCovMatrix, ic, ii);
1356 }
1357 }
1358}
#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:110
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
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:63
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)
If flag is true, perform constant term optimization on function being minimized.
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
bool fitFCN(const ROOT::Math::IMultiGenFunction &fcn)
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.
ROOT::Math::IMultiGenFunction * getMultiGenFcn() const
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:325
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:44
virtual void SetLineWidth(Width_t lwidth)
Set the line width.
Definition TAttLine.h:45
virtual void SetLineColor(Color_t lcolor)
Set the line color.
Definition TAttLine.h:42
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:2329
Manages Markers.
Definition TMarker.h:22
virtual const char * GetName() const
Returns name of object.
Definition TObject.cxx:457
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