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