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/// 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();
618 std::vector<double> globalCC = _minimizer->GlobalCC();
619 globalCC.resize(nParams); // pad with zeros
620 for (std::size_t ic = 0; ic < nParams; 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
778////////////////////////////////////////////////////////////////////////////////
779/// Apply results of given external covariance matrix. i.e. propagate its errors
780/// to all RRV parameter representations and give this matrix instead of the
781/// HESSE matrix at the next save() call
782
784{
785 _extV.reset(static_cast<TMatrixDSym *>(V.Clone()));
786 _fcn->ApplyCovarianceMatrix(*_extV);
787}
788
790{
791 // Import the results of the last fit performed, interpreting
792 // the fit parameters as the given varList of parameters.
793
794 if (_minimizer == nullptr) {
795 oocoutE(nullptr, InputArguments) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
796 return nullptr;
797 }
798
799 auto res = std::make_unique<RooFitResult>("lastMinuitFit", "Last MINUIT fit");
800
801 // Extract names of fit parameters
802 // and construct corresponding RooRealVars
803 RooArgList constPars("constPars");
804 RooArgList floatPars("floatPars");
805
806 const RooArgList floatParsFromFcn = _fcn->floatParams();
807
808 for (unsigned int i = 0; i < _fcn->getNDim(); ++i) {
809
810 TString varName(floatParsFromFcn.at(i)->GetName());
811 bool isConst(_result->isParameterFixed(i));
812
813 double xlo = _config.ParSettings(i).LowerLimit();
814 double xhi = _config.ParSettings(i).UpperLimit();
815 double xerr = _result->error(i);
816 double xval = _result->fParams[i];
817
818 std::unique_ptr<RooRealVar> var;
819
820 if ((xlo < xhi) && !isConst) {
821 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
822 } else {
823 var = std::make_unique<RooRealVar>(varName, varName, xval);
824 }
825 var->setConstant(isConst);
826
827 if (isConst) {
828 constPars.addOwned(std::move(var));
829 } else {
830 var->setError(xerr);
831 floatPars.addOwned(std::move(var));
832 }
833 }
834
835 res->setConstParList(constPars);
836 res->setInitParList(floatPars);
837 res->setFinalParList(floatPars);
838 res->setMinNLL(_result->fVal);
839 res->setEDM(_result->fEdm);
840 res->setCovQual(_minimizer->CovMatrixStatus());
841 res->setStatus(_result->fStatus);
842 fillCorrMatrix(*res);
843
844 return RooFit::makeOwningPtr(std::move(res));
845}
846
847/// Try to recover from invalid function values. When invalid function values
848/// are encountered, a penalty term is returned to the minimiser to make it
849/// back off. This sets the strength of this penalty. \note A strength of zero
850/// is equivalent to a constant penalty (= the gradient vanishes, ROOT < 6.24).
851/// Positive values lead to a gradient pointing away from the undefined
852/// regions. Use ~10 to force the minimiser away from invalid function values.
857
858bool RooMinimizer::setLogFile(const char *logf)
859{
860 _cfg.logf = logf;
861 return _cfg.logf ? _fcn->SetLogFile(_cfg.logf) : false;
862}
863
865{
866 return _fcn->evalCounter();
867}
869{
870 _fcn->zeroEvalCount();
871}
872
874{
875 return _fcn->getNDim();
876}
877
878std::ofstream *RooMinimizer::logfile()
879{
880 return _fcn->GetLogFile();
881}
883{
884 return _fcn->GetMaxFCN();
885}
887{
888 return _fcn->getOffset();
889}
890
891std::unique_ptr<RooAbsReal::EvalErrorContext> RooMinimizer::makeEvalErrorContext() const
892{
894 // If evaluation error printing is disabled, we don't need to collect the
895 // errors and only need to count them. This significantly reduces the
896 // performance overhead when having evaluation errors.
898 return std::make_unique<RooAbsReal::EvalErrorContext>(m);
899}
900
902{
903 // fit a user provided FCN function
904 // create fit parameter settings
905
906 // Check number of parameters
907 unsigned int npar = getNPar();
908 if (npar == 0) {
909 coutE(Minimization) << "RooMinimizer::fitFCN(): FCN function has zero parameters" << std::endl;
910 return false;
911 }
912
913 // initiate the minimizer
915
916 // Identify floating RooCategory parameters
918 for (auto arg : _fcn->allParams()) {
919 if (arg->isCategory() && !arg->isConstant())
920 floatingCats.add(*arg);
921 }
922
923 std::vector<RooCategory *> pdfIndices;
924 for (auto *arg : floatingCats) {
925 if (auto *cat = dynamic_cast<RooCategory *>(arg))
926 pdfIndices.push_back(cat);
927 }
928
929 const size_t nPdfs = pdfIndices.size();
930
931 // Identify floating continuous parameters (RooRealVar)
933 for (auto arg : _fcn->allParams()) {
934 if (!arg->isCategory() && !arg->isConstant())
935 floatReals.add(*arg);
936 }
937
938 if (nPdfs == 0) {
939 coutI(Minimization) << "[fitFCN] No discrete parameters, performing continuous minimization only" << std::endl;
940 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
941 bool isValid = _minimizer->Minimize();
942 if (!_result)
943 _result = std::make_unique<FitResult>();
944 fillResult(isValid);
945 if (isValid)
947 return isValid;
948 }
949
950 // set also new parameter values and errors in FitConfig
951 // Prepare discrete indices
952 std::vector<int> maxIndices;
953 for (auto *cat : pdfIndices)
954 maxIndices.push_back(cat->size());
955
956 std::set<std::vector<int>> tried;
957 std::map<std::vector<int>, double> nllMap;
958 std::vector<int> bestIndices(nPdfs, 0);
959 double bestNLL = 1e30;
960
961 bool improved = true;
962 while (improved) {
963 improved = false;
966
967 for (const auto &combo : combos) {
968 if (tried.count(combo))
969 continue;
970
971 for (size_t i = 0; i < nPdfs; ++i)
972 pdfIndices[i]->setIndex(combo[i]);
973
974 // Freeze categories during continuous minimization
975 std::vector<bool> wasConst(nPdfs);
976 for (size_t i = 0; i < nPdfs; ++i) {
977 wasConst[i] = pdfIndices[i]->isConstant();
978 pdfIndices[i]->setConstant(true);
979 }
980 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
981 _minimizer->Minimize();
982
983 for (size_t i = 0; i < nPdfs; ++i)
984 pdfIndices[i]->setConstant(wasConst[i]);
985
986 double val = _minimizer->MinValue();
987 tried.insert(combo);
988 nllMap[combo] = val;
989
990 if (val < bestNLL) {
991 bestNLL = val;
993 improved = true;
994 }
995 }
996 }
997
998 for (size_t i = 0; i < nPdfs; ++i) {
999 pdfIndices[i]->setIndex(bestIndices[i]);
1000 }
1001
1002 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
1003 _minimizer->Minimize();
1004
1005 coutI(Minimization) << "All NLL Values per Combination:" << std::endl;
1006 for (const auto &entry : nllMap) {
1007 const auto &combo = entry.first;
1008 double val = entry.second;
1009
1010 std::stringstream ss;
1011 ss << "Combo: [";
1012 for (size_t i = 0; i < combo.size(); ++i) {
1013 ss << combo[i];
1014 if (i + 1 < combo.size())
1015 ss << ", ";
1016 }
1017 ss << "], NLL: " << val;
1018
1019 coutI(Minimization) << ss.str() << std::endl;
1020 }
1021
1022 std::stringstream ssBest;
1023 ssBest << "DP Best Indices: [";
1024 for (size_t i = 0; i < bestIndices.size(); ++i) {
1025 ssBest << bestIndices[i];
1026 if (i + 1 < bestIndices.size())
1027 ssBest << ", ";
1028 }
1029 ssBest << "], NLL = " << bestNLL;
1030
1031 coutI(Minimization) << ssBest.str() << std::endl;
1032
1033 if (!_result)
1034 _result = std::make_unique<FitResult>();
1035 fillResult(true);
1037
1038 return true;
1039}
1041{
1042 // compute the Hesse errors according to configuration
1043 // set in the parameters and append value in fit result
1044
1045 // update minimizer (recreate if not done or if name has changed
1046 if (!updateMinimizerOptions()) {
1047 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
1048 return false;
1049 }
1050
1051 // run Hesse
1052 bool ret = _minimizer->Hesse();
1053 if (!ret)
1054 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error when calculating Hessian" << std::endl;
1055
1056 // update minimizer results with what comes out from Hesse
1057 // in case is empty - create from a FitConfig
1058 if (_result->fParams.empty())
1059 _result = std::make_unique<FitResult>(_config);
1060
1061 // re-give a minimizer instance in case it has been changed
1062 ret |= update(ret);
1063
1064 // set also new errors in FitConfig
1065 if (ret)
1067
1068 return ret;
1069}
1070
1072{
1073 // compute the Minos errors according to configuration
1074 // set in the parameters and append value in fit result
1075 // normally Minos errors are computed just after the minimization
1076 // (in DoMinimization) aftewr minimizing if the
1077 // FitConfig::MinosErrors() flag is set
1078
1079 // update minimizer (but cannot re-create in this case). Must use an existing one
1080 if (!updateMinimizerOptions(false)) {
1081 coutE(Minimization) << "RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
1082 return false;
1083 }
1084
1085 const std::vector<unsigned int> &ipars = _config.MinosParams();
1086 unsigned int n = (!ipars.empty()) ? ipars.size() : _fcn->getNDim();
1087 bool ok = false;
1088
1089 int iparNewMin = 0;
1090 int iparMax = n;
1091 int iter = 0;
1092 // rerun minos for the parameters run before a new Minimum has been found
1093 do {
1094 if (iparNewMin > 0)
1095 coutI(Minimization) << "RooMinimizer::calculateMinosErrors() Run again Minos for some parameters because a "
1096 "new Minimum has been found"
1097 << std::endl;
1098 iparNewMin = 0;
1099 for (int i = 0; i < iparMax; ++i) {
1100 double elow, eup;
1101 unsigned int index = (!ipars.empty()) ? ipars[i] : i;
1102 bool ret = _minimizer->GetMinosError(index, elow, eup);
1103 // flags case when a new minimum has been found
1104 if ((_minimizer->MinosStatus() & 8) != 0) {
1105 iparNewMin = i;
1106 }
1107 if (ret)
1108 _result->fMinosErrors.emplace(index, std::make_pair(elow, eup));
1109 ok |= ret;
1110 }
1111
1113 iter++; // to avoid infinite looping
1114 } while (iparNewMin > 0 && iter < 10);
1115 if (!ok) {
1116 coutE(Minimization)
1117 << "RooMinimizer::calculateMinosErrors() Minos error calculation failed for all the selected parameters"
1118 << std::endl;
1119 }
1120
1121 // re-give a minimizer instance in case it has been changed
1122 // but maintain previous valid status. Do not set result to false if minos failed
1123 ok &= update(_result->fValid);
1124
1125 return ok;
1126}
1127
1129{
1130 _minimizer = std::unique_ptr<ROOT::Math::Minimizer>(_config.CreateMinimizer());
1131 _fcn->initMinimizer(*_minimizer);
1133
1135 std::vector<double> v;
1136 for (std::size_t i = 0; i < _fcn->getNDim(); ++i) {
1137 RooRealVar &param = _fcn->floatableParam(i);
1138 v.push_back(param.getError() * param.getError());
1139 }
1140 _minimizer->SetCovarianceDiag(v, v.size());
1141 }
1142}
1143
1145{
1146 // update minimizer options when re-doing a Fit or computing Hesse or Minos errors
1147
1148 // create a new minimizer if it is different type
1149 // minimizer type string stored in FitResult is "minimizer name" + " / " + minimizer algo
1150 std::string newMinimType = _config.MinimizerName();
1151 if (_minimizer && _result && newMinimType != _result->fMinimType) {
1152 // if a different minimizer is allowed (e.g. when calling Hesse)
1153 if (canDifferentMinim) {
1154 std::string msg = "Using now " + newMinimType;
1155 coutI(Minimization) << "RooMinimizer::updateMinimizerOptions(): " << msg << std::endl;
1156 initMinimizer();
1157 } else {
1158 std::string msg = "Cannot change minimizer. Continue using " + _result->fMinimType;
1159 coutW(Minimization) << "RooMinimizer::updateMinimizerOptions() " << msg << std::endl;
1160 }
1161 }
1162
1163 // create minimizer if it was not done before
1164 if (!_minimizer) {
1165 initMinimizer();
1166 }
1167
1168 // set new minimizer options (but not functions and parameters)
1169 _minimizer->SetOptions(_config.MinimizerOptions());
1170 return true;
1171}
1172
1174{
1175 // update the fit configuration after a fit using the obtained result
1176 if (_result->fParams.empty() || !_result->fValid)
1177 return;
1178 for (unsigned int i = 0; i < _config.NPar(); ++i) {
1180 par.SetValue(_result->fParams[i]);
1181 if (_result->error(i) > 0)
1182 par.SetStepSize(_result->error(i));
1183 }
1184}
1185
1187 : fStatus(-99), // use this special convention to flag it when printing result
1188 fCovStatus(0),
1189 fParams(fconfig.NPar()),
1190 fErrors(fconfig.NPar())
1191{
1192 // create a Fit result from a fit config (i.e. with initial parameter values
1193 // and errors equal to step values
1194 // The model function is NULL in this case
1195
1196 // set minimizer type and algorithm
1197 fMinimType = fconfig.MinimizerType();
1198 // append algorithm name for minimizer that support it
1199 if ((fMinimType.find("Fumili") == std::string::npos) && (fMinimType.find("GSLMultiFit") == std::string::npos)) {
1200 if (!fconfig.MinimizerAlgoType().empty())
1201 fMinimType += " / " + fconfig.MinimizerAlgoType();
1202 }
1203
1204 // get parameter values and errors (step sizes)
1205 for (unsigned int i = 0; i < fconfig.NPar(); ++i) {
1206 const ROOT::Fit::ParameterSettings &par = fconfig.ParSettings(i);
1207 fParams[i] = par.Value();
1208 fErrors[i] = par.StepSize();
1209 if (par.IsFixed())
1210 fFixedParams[i] = true;
1211 }
1212}
1213
1215{
1218
1219 // Fill the FitResult after minimization using result from Minimizers
1220
1221 _result->fValid = isValid;
1222 _result->fStatus = min.Status();
1223 _result->fCovStatus = min.CovMatrixStatus();
1224 _result->fVal = min.MinValue();
1225 _result->fEdm = min.Edm();
1226
1227 _result->fMinimType = fconfig.MinimizerName();
1228
1229 const unsigned int npar = min.NDim();
1230 if (npar == 0)
1231 return;
1232
1233 if (min.X())
1234 _result->fParams = std::vector<double>(min.X(), min.X() + npar);
1235 else {
1236 // case minimizer does not provide minimum values (it failed) take from configuration
1237 _result->fParams.resize(npar);
1238 for (unsigned int i = 0; i < npar; ++i) {
1239 _result->fParams[i] = (fconfig.ParSettings(i).Value());
1240 }
1241 }
1242
1243 // check for fixed or limited parameters
1244 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
1245 if (fconfig.ParSettings(ipar).IsFixed())
1246 _result->fFixedParams[ipar] = true;
1247 }
1248
1249 // fill error matrix
1250 // if minimizer provides error provides also error matrix
1251 // clear in case of re-filling an existing result
1252 _result->fCovMatrix.clear();
1253
1254 if (min.Errors() != nullptr) {
1255 updateErrors();
1256 }
1257}
1258
1259bool RooMinimizer::update(bool isValid)
1260{
1263
1264 // update fit result with new status from minimizer
1265 // ncalls if it is not zero is used instead of value from minimizer
1266
1267 // in case minimizer changes
1268 _result->fMinimType = fconfig.MinimizerName();
1269
1270 const std::size_t npar = _result->fParams.size();
1271
1272 _result->fValid = isValid;
1273 // update minimum value
1274 _result->fVal = min.MinValue();
1275 _result->fEdm = min.Edm();
1276 _result->fStatus = min.Status();
1277 _result->fCovStatus = min.CovMatrixStatus();
1278
1279 // copy parameter value and errors
1280 std::copy(min.X(), min.X() + npar, _result->fParams.begin());
1281
1282 if (min.Errors() != nullptr) {
1283 updateErrors();
1284 }
1285 return true;
1286}
1287
1289{
1291 const std::size_t npar = _result->fParams.size();
1292
1293 _result->fErrors.resize(npar);
1294 std::copy(min.Errors(), min.Errors() + npar, _result->fErrors.begin());
1295
1296 if (_result->fCovStatus != 0) {
1297
1298 // update error matrix
1299 unsigned int r = npar * (npar + 1) / 2;
1300 _result->fCovMatrix.resize(r);
1301 unsigned int l = 0;
1302 for (unsigned int i = 0; i < npar; ++i) {
1303 for (unsigned int j = 0; j <= i; ++j)
1304 _result->fCovMatrix[l++] = min.CovMatrix(i, j);
1305 }
1306 }
1307 // minos errors are set separately when calling Fitter::CalculateMinosErrors()
1308}
1309
1310double RooMinimizer::FitResult::lowerError(unsigned int i) const
1311{
1312 // return lower Minos error for parameter i
1313 // return the parabolic error if Minos error has not been calculated for the parameter i
1314 auto itr = fMinosErrors.find(i);
1315 return (itr != fMinosErrors.end()) ? itr->second.first : error(i);
1316}
1317
1318double RooMinimizer::FitResult::upperError(unsigned int i) const
1319{
1320 // return upper Minos error for parameter i
1321 // return the parabolic error if Minos error has not been calculated for the parameter i
1322 auto itr = fMinosErrors.find(i);
1323 return (itr != fMinosErrors.end()) ? itr->second.second : error(i);
1324}
1325
1327{
1328 return fFixedParams.find(ipar) != fFixedParams.end();
1329}
1330
1332{
1333 const size_t nParams = fParams.size();
1334 covs.ResizeTo(nParams, nParams);
1335 for (std::size_t ic = 0; ic < nParams; ic++) {
1336 for (std::size_t ii = 0; ii < nParams; ii++) {
1337 covs(ic, ii) = covMatrix(fCovMatrix, ic, ii);
1338 }
1339 }
1340}
#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
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
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: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