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