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 }
87 ~FreezeDisconnectedParametersRAII()
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) or a chi^2 as returned by
146/// RooAbsPdf::createNLL() or RooAbsReal::createChi2(). This class propagates
147/// all RooFit information (floating parameters, their values and errors)
148/// to MINUIT before each MINUIT call and propagates all MINUIT information
149/// back to the RooFit object at the end of each call (updated parameter
150/// values, their (asymmetric errors) etc. The default MINUIT error level
151/// for HESSE and MINOS error analysis is taken from the defaultErrorLevel()
152/// value of the input function.
153
154/// Constructor that accepts all configuration in struct with RooAbsReal likelihood
155RooMinimizer::RooMinimizer(RooAbsReal &function, Config const &cfg) : _function{function}, _cfg(cfg)
156{
158 auto nll_real = dynamic_cast<RooFit::TestStatistics::RooRealL *>(&function);
159 if (nll_real != nullptr) {
160 if (_cfg.parallelize != 0) { // new test statistic with multiprocessing library with
161 // parallel likelihood or parallel gradient
162#ifdef ROOFIT_MULTIPROCESS
164 // Note that this is necessary because there is currently no serial-mode LikelihoodGradientWrapper.
165 // We intend to repurpose RooGradMinimizerFcn to build such a LikelihoodGradientSerial class.
166 coutI(InputArguments) << "Modular likelihood detected and likelihood parallelization requested, "
167 << "also setting parallel gradient calculation mode." << std::endl;
169 }
170 // If _cfg.parallelize is larger than zero set the number of workers to that value. Otherwise do not do
171 // anything and let RooFit::MultiProcess handle the number of workers
172 if (_cfg.parallelize > 0)
175
176 _fcn = std::make_unique<RooFit::TestStatistics::MinuitFcnGrad>(
177 nll_real->getRooAbsL(), this, _config.ParamsSettings(),
179 static_cast<RooFit::TestStatistics::LikelihoodMode>(int(_cfg.enableParallelDescent))},
181#else
182 throw std::logic_error(
183 "Parallel minimization requested, but multiprocessing is not supported on this platform");
184#endif
185 } else { // modular test statistic non parallel
186 coutW(InputArguments)
187 << "Requested modular likelihood without gradient parallelization, some features such as offsetting "
188 << "may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl;
189 // The RooRealL that is used in the case where the modular likelihood is being passed to a RooMinimizerFcn does
190 // not have offsetting implemented. Therefore, offsetting will not work in this case. Other features might also
191 // not work since the RooRealL was not intended for minimization. Further development is required to make the
192 // MinuitFcnGrad also handle serial gradient minimization. The MinuitFcnGrad accepts a RooAbsL and has
193 // offsetting implemented, thus omitting the need for RooRealL minimization altogether.
194 _fcn = std::make_unique<RooMinimizerFcn>(&function, this);
195 }
196 } else {
197 if (_cfg.parallelize != 0) { // Old test statistic with parallel likelihood or gradient
198 throw std::logic_error("In RooMinimizer constructor: Selected likelihood evaluation but a "
199 "non-modular likelihood was given. Please supply ModularL(true) as an "
200 "argument to createNLL for modular likelihoods to use likelihood "
201 "or gradient parallelization.");
202 }
203 _fcn = std::make_unique<RooMinimizerFcn>(&function, this);
204 }
206}
207
208/// Initialize the part of the minimizer that is independent of the function to be minimized
210{
211 RooSentinel::activate();
213
215 setEps(1.0); // default tolerance
216}
217
218/// Initialize the part of the minimizer that is dependent on the function to be minimized
220{
221 // default max number of calls
222 _config.MinimizerOptions().SetMaxIterations(500 * _fcn->getNDim());
224
225 // Shut up for now
226 setPrintLevel(-1);
227
228 // Use +0.5 for 1-sigma errors
229 setErrorLevel(defaultErrorLevel);
230
231 // Declare our parameters to MINUIT
232 _fcn->Synchronize(_config.ParamsSettings());
233
234 // Now set default verbosity
235 setPrintLevel(RooMsgService::instance().silentMode() ? -1 : 1);
236
237 // Set user defined and default _fcn config
239
240 // Likelihood holds information on offsetting in old style, so do not set here unless explicitly set by user
241 if (_cfg.offsetting != -1) {
243 }
244}
245
246////////////////////////////////////////////////////////////////////////////////
247/// Destructor
248
250
251////////////////////////////////////////////////////////////////////////////////
252/// Change MINUIT strategy to istrat. Accepted codes
253/// are 0,1,2 and represent MINUIT strategies for dealing
254/// most efficiently with fast FCNs (0), expensive FCNs (2)
255/// and 'intermediate' FCNs (1)
256
258{
260}
261
262////////////////////////////////////////////////////////////////////////////////
263/// Change maximum number of MINUIT iterations
264/// (RooMinimizer default 500 * #%parameters)
265
270
271////////////////////////////////////////////////////////////////////////////////
272/// Change maximum number of likelihood function class from MINUIT
273/// (RooMinimizer default 500 * #%parameters)
274
279
280////////////////////////////////////////////////////////////////////////////////
281/// Set the level for MINUIT error analysis to the given
282/// value. This function overrides the default value
283/// that is taken in the RooMinimizer constructor from
284/// the defaultErrorLevel() method of the input function
285
287{
289}
290
291////////////////////////////////////////////////////////////////////////////////
292/// Change MINUIT epsilon
293
294void RooMinimizer::setEps(double eps)
295{
297}
298
299////////////////////////////////////////////////////////////////////////////////
300/// Enable internal likelihood offsetting for enhanced numeric precision
301
303{
304 _cfg.offsetting = flag;
305 _fcn->setOffsetting(_cfg.offsetting);
306}
307
308////////////////////////////////////////////////////////////////////////////////
309/// Choose the minimizer algorithm.
310///
311/// Passing an empty string selects the default minimizer type returned by
312/// ROOT::Math::MinimizerOptions::DefaultMinimizerType().
313
314void RooMinimizer::setMinimizerType(std::string const &type)
315{
317
318 if ((_cfg.parallelize != 0) && _cfg.minimizerType != "Minuit2") {
319 std::stringstream ss;
320 ss << "In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!";
321 if (type.empty()) {
322 ss << "\nPlease set it as your default minimizer via "
323 "ROOT::Math::MinimizerOptions::SetDefaultMinimizer(\"Minuit2\").";
324 }
325 throw std::invalid_argument(ss.str());
326 }
327}
328
329void RooMinimizer::determineStatus(bool fitterReturnValue)
330{
331 // Minuit-given status:
332 _status = fitterReturnValue ? _result->fStatus : -1;
333
334 // RooFit-based additional failed state information:
335 if (evalCounter() <= _fcn->GetNumInvalidNLL()) {
336 coutE(Minimization) << "RooMinimizer: all function calls during minimization gave invalid NLL values!"
337 << std::endl;
338 }
339}
340
341////////////////////////////////////////////////////////////////////////////////
342/// Minimise the function passed in the constructor.
343/// \param[in] type Type of fitter to use, e.g. "Minuit" "Minuit2". Passing an
344/// empty string will select the default minimizer type of the
345/// RooMinimizer, as returned by
346/// ROOT::Math::MinimizerOptions::DefaultMinimizerType().
347/// \attention This overrides the default fitter of this RooMinimizer.
348/// \param[in] alg Fit algorithm to use. (Optional)
349int RooMinimizer::minimize(const char *type, const char *alg)
350{
351
352 if (_cfg.timingAnalysis) {
353#ifdef ROOFIT_MULTIPROCESS
355#else
356 throw std::logic_error("ProcessTimer requested, but multiprocessing is not supported on this platform.");
357#endif
358 }
359 _fcn->Synchronize(_config.ParamsSettings());
360
363
364 profileStart();
365 {
366 auto ctx = makeEvalErrorContext();
367
368 bool ret = fitFCN();
369 determineStatus(ret);
370 }
371 profileStop();
372 _fcn->BackProp();
373
374 saveStatus("MINIMIZE", _status);
375
376 return _status;
377}
378
379////////////////////////////////////////////////////////////////////////////////
380/// Execute MIGRAD. Changes in parameter values
381/// and calculated errors are automatically
382/// propagated back the RooRealVars representing
383/// the floating parameters in the MINUIT operation.
384
386{
387 return exec("migrad", "MIGRAD");
388}
389
390int RooMinimizer::exec(std::string const &algoName, std::string const &statusName)
391{
392 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
393
394 _fcn->Synchronize(_config.ParamsSettings());
395 profileStart();
396 {
397 auto ctx = makeEvalErrorContext();
398
399 bool ret = false;
400 if (algoName == "hesse") {
401 // HESSE has a special entry point in the ROOT::Math::Fitter
403 ret = calculateHessErrors();
404 } else if (algoName == "minos") {
405 // MINOS has a special entry point in the ROOT::Math::Fitter
407 ret = calculateMinosErrors();
408 } else {
409 _config.SetMinimizer(_cfg.minimizerType.c_str(), algoName.c_str());
410 ret = fitFCN();
411 }
412 determineStatus(ret);
413 }
414 profileStop();
415 _fcn->BackProp();
416
417 saveStatus(statusName.c_str(), _status);
418
419 return _status;
420}
421
422////////////////////////////////////////////////////////////////////////////////
423/// Execute HESSE. Changes in parameter values
424/// and calculated errors are automatically
425/// propagated back the RooRealVars representing
426/// the floating parameters in the MINUIT operation.
427
429{
430 if (_minimizer == nullptr) {
431 coutW(Minimization) << "RooMinimizer::hesse: Error, run Migrad before Hesse!" << std::endl;
432 _status = -1;
433 return _status;
434 }
435
436 return exec("hesse", "HESSE");
437}
438
439////////////////////////////////////////////////////////////////////////////////
440/// Execute MINOS. Changes in parameter values
441/// and calculated errors are automatically
442/// propagated back the RooRealVars representing
443/// the floating parameters in the MINUIT operation.
444
446{
447 if (_minimizer == nullptr) {
448 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
449 _status = -1;
450 return _status;
451 }
452
453 return exec("minos", "MINOS");
454}
455
456////////////////////////////////////////////////////////////////////////////////
457/// Execute MINOS for given list of parameters. Changes in parameter values
458/// and calculated errors are automatically
459/// propagated back the RooRealVars representing
460/// the floating parameters in the MINUIT operation.
461
462int RooMinimizer::minos(const RooArgSet &minosParamList)
463{
464 if (_minimizer == nullptr) {
465 coutW(Minimization) << "RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
466 _status = -1;
467 } else if (!minosParamList.empty()) {
468 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
469
470 _fcn->Synchronize(_config.ParamsSettings());
471 profileStart();
472 {
473 auto ctx = makeEvalErrorContext();
474
475 // get list of parameters for Minos
476 std::vector<unsigned int> paramInd;
477 RooArgList floatParams = _fcn->floatParams();
478 for (RooAbsArg *arg : minosParamList) {
479 RooAbsArg *par = floatParams.find(arg->GetName());
480 if (par && !par->isConstant()) {
481 int index = floatParams.index(par);
482 paramInd.push_back(index);
483 }
484 }
485
486 if (!paramInd.empty()) {
487 // set the parameter indices
488 _config.SetMinosErrors(paramInd);
489
491 bool ret = calculateMinosErrors();
492 determineStatus(ret);
493 // to avoid that following minimization computes automatically the Minos errors
494 _config.SetMinosErrors(false);
495 }
496 }
497 profileStop();
498 _fcn->BackProp();
499
500 saveStatus("MINOS", _status);
501 }
502
503 return _status;
504}
505
506////////////////////////////////////////////////////////////////////////////////
507/// Execute SEEK. Changes in parameter values
508/// and calculated errors are automatically
509/// propagated back the RooRealVars representing
510/// the floating parameters in the MINUIT operation.
511
513{
514 return exec("seek", "SEEK");
515}
516
517////////////////////////////////////////////////////////////////////////////////
518/// Execute SIMPLEX. Changes in parameter values
519/// and calculated errors are automatically
520/// propagated back the RooRealVars representing
521/// the floating parameters in the MINUIT operation.
522
524{
525 return exec("simplex", "SIMPLEX");
526}
527
528////////////////////////////////////////////////////////////////////////////////
529/// Execute IMPROVE. Changes in parameter values
530/// and calculated errors are automatically
531/// propagated back the RooRealVars representing
532/// the floating parameters in the MINUIT operation.
533
535{
536 return exec("migradimproved", "IMPROVE");
537}
538
539////////////////////////////////////////////////////////////////////////////////
540/// Change the MINUIT internal printing level
541
543{
544 _config.MinimizerOptions().SetPrintLevel(newLevel + 1);
545}
546
547////////////////////////////////////////////////////////////////////////////////
548/// Get the MINUIT internal printing level
549
554
555////////////////////////////////////////////////////////////////////////////////
556/// \deprecated Has no effect anymore. Functionality was removed in ROOT 6.42,
557/// and this function is kept as an empty shell that does nothing (for API
558/// compatibility between different ROOT versions).
559
560void RooMinimizer::optimizeConst(int /*flag*/) {}
561
562////////////////////////////////////////////////////////////////////////////////
563/// Save and return a RooFitResult snapshot of current minimizer status.
564/// This snapshot contains the values of all constant parameters,
565/// the value of all floating parameters at RooMinimizer construction and
566/// after the last MINUIT operation, the MINUIT status, variance quality,
567/// EDM setting, number of calls with evaluation problems, the minimized
568/// function value and the full correlation matrix.
569
570RooFit::OwningPtr<RooFitResult> RooMinimizer::save(const char *userName, const char *userTitle)
571{
572 if (_minimizer == nullptr) {
573 coutW(Minimization) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
574 return nullptr;
575 }
576
577 std::string name = userName ? std::string{userName} : _fcn->getFunctionName();
578 std::string title = userTitle ? std::string{userTitle} : _fcn->getFunctionTitle();
579 auto fitRes = std::make_unique<RooFitResult>(name.c_str(), title.c_str());
580
581 fitRes->setConstParList(_fcn->constParams());
582
583 fitRes->setNumInvalidNLL(_fcn->GetNumInvalidNLL());
584
585 fitRes->setStatus(_status);
586 fitRes->setCovQual(_minimizer->CovMatrixStatus());
587 fitRes->setMinNLL(_result->fVal - _fcn->getOffset());
588 fitRes->setEDM(_result->fEdm);
589
590 fitRes->setInitParList(_fcn->initFloatParams());
591 fitRes->setFinalParList(_fcn->floatParams());
592
593 if (!_extV) {
594 fillCorrMatrix(*fitRes);
595 } else {
596 fitRes->setCovarianceMatrix(*_extV);
597 }
598
599 fitRes->setStatusHistory(_statusHistory);
600
601 return RooFit::makeOwningPtr(std::move(fitRes));
602}
603
604namespace {
605
606/// retrieve covariance matrix element
607double covMatrix(std::vector<double> const &covMat, unsigned int i, unsigned int j)
608{
609 if (covMat.empty())
610 return 0; // no matrix is available in case of non-valid fits
611 return j < i ? covMat[j + i * (i + 1) / 2] : covMat[i + j * (j + 1) / 2];
612}
613
614/// retrieve correlation elements
615double correlation(std::vector<double> const &covMat, unsigned int i, unsigned int j)
616{
617 if (covMat.empty())
618 return 0; // no matrix is available in case of non-valid fits
619 double tmp = covMatrix(covMat, i, i) * covMatrix(covMat, j, j);
620 return tmp > 0 ? covMatrix(covMat, i, j) / std::sqrt(tmp) : 0;
621}
622
623} // namespace
624
626{
627 const std::size_t nParams = _fcn->getNDim();
628 TMatrixDSym corrs(nParams);
629 TMatrixDSym covs(nParams);
630 std::vector<double> globalCC = _minimizer->GlobalCC();
631 globalCC.resize(nParams); // pad with zeros
632 for (std::size_t ic = 0; ic < nParams; ic++) {
633 for (std::size_t ii = 0; ii < nParams; ii++) {
634 corrs(ic, ii) = correlation(_result->fCovMatrix, ic, ii);
635 covs(ic, ii) = covMatrix(_result->fCovMatrix, ic, ii);
636 }
637 }
638 fitRes.fillCorrMatrix(globalCC, corrs, covs);
639}
640
641////////////////////////////////////////////////////////////////////////////////
642/// Create and draw a TH2 with the error contours in the parameters `var1` and `var2`.
643/// \param[in] var1 The first parameter (x axis).
644/// \param[in] var2 The second parameter (y axis).
645/// \param[in] n1 First contour.
646/// \param[in] n2 Optional contour. 0 means don't draw.
647/// \param[in] n3 Optional contour. 0 means don't draw.
648/// \param[in] n4 Optional contour. 0 means don't draw.
649/// \param[in] n5 Optional contour. 0 means don't draw.
650/// \param[in] n6 Optional contour. 0 means don't draw.
651/// \param[in] npoints Number of points for evaluating the contour.
652///
653/// Up to six contours can be drawn using the arguments `n1` to `n6` to request the desired
654/// coverage in units of \f$ \sigma = n^2 \cdot \mathrm{ErrorDef} \f$.
655/// See ROOT::Math::Minimizer::ErrorDef().
656
657RooPlot *RooMinimizer::contour(RooRealVar &var1, RooRealVar &var2, double n1, double n2, double n3, double n4,
658 double n5, double n6, unsigned int npoints)
659{
660 RooArgList params = _fcn->floatParams();
661 RooArgList paramSave;
662 params.snapshot(paramSave);
663
664 // Verify that both variables are floating parameters of PDF
665 int index1 = params.index(&var1);
666 if (index1 < 0) {
667 coutE(Minimization) << "RooMinimizer::contour(" << GetName() << ") ERROR: " << var1.GetName()
668 << " is not a floating parameter of " << _fcn->getFunctionName() << std::endl;
669 return nullptr;
670 }
671
672 int index2 = params.index(&var2);
673 if (index2 < 0) {
674 coutE(Minimization) << "RooMinimizer::contour(" << GetName() << ") ERROR: " << var2.GetName()
675 << " is not a floating parameter of PDF " << _fcn->getFunctionName() << std::endl;
676 return nullptr;
677 }
678
679 // create and draw a frame
680 RooPlot *frame = new RooPlot(var1, var2);
681
682 // draw a point at the current parameter values
683 TMarker *point = new TMarker(var1.getVal(), var2.getVal(), 8);
684 frame->addObject(point);
685
686 // check first if a inimizer is available. If not means
687 // the minimization is not done , so do it
688 if (_minimizer == nullptr) {
689 coutW(Minimization) << "RooMinimizer::contour: Error, run Migrad before contours!" << std::endl;
690 return frame;
691 }
692
693 // remember our original value of ERRDEF
694 double errdef = _minimizer->ErrorDef();
695
696 double n[6];
697 n[0] = n1;
698 n[1] = n2;
699 n[2] = n3;
700 n[3] = n4;
701 n[4] = n5;
702 n[5] = n6;
703
704 auto operModeRAII = setOperModesDirty(_function);
705 for (int ic = 0; ic < 6; ic++) {
706 if (n[ic] > 0) {
707
708 // set the value corresponding to an n1-sigma contour
709 _minimizer->SetErrorDef(n[ic] * n[ic] * errdef);
710
711 // calculate and draw the contour
712 std::vector<double> xcoor(npoints + 1);
713 std::vector<double> ycoor(npoints + 1);
714 bool ret = _minimizer->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
715
716 if (!ret) {
717 coutE(Minimization) << "RooMinimizer::contour(" << GetName()
718 << ") ERROR: MINUIT did not return a contour graph for n=" << n[ic] << std::endl;
719 } else {
720 xcoor[npoints] = xcoor[0];
721 ycoor[npoints] = ycoor[0];
722 TGraph *graph = new TGraph(npoints + 1, xcoor.data(), ycoor.data());
723
724 std::stringstream name;
725 name << "contour_" << _fcn->getFunctionName() << "_n" << n[ic];
726 graph->SetName(name.str().c_str());
727 graph->SetLineStyle(ic + 1);
728 graph->SetLineWidth(2);
729 graph->SetLineColor(kBlue);
730 frame->addObject(graph, "L");
731 }
732 }
733 }
734
735 // restore the original ERRDEF
736 _minimizer->SetErrorDef(errdef);
737
738 // restore parameter values
739 params.assign(paramSave);
740
741 return frame;
742}
743
744////////////////////////////////////////////////////////////////////////////////
745/// Add parameters in metadata field to process timer
746
748{
749#ifdef ROOFIT_MULTIPROCESS
750 // parameter indices for use in timing heat matrix
751 std::vector<std::string> parameter_names;
752 for (RooAbsArg *parameter : _fcn->floatParams()) {
753 parameter_names.push_back(parameter->GetName());
754 if (_cfg.verbose) {
755 coutI(Minimization) << "parameter name: " << parameter_names.back() << std::endl;
756 }
757 }
759#else
760 coutI(Minimization) << "Not adding parameters to processtimer because multiprocessing is not enabled." << std::endl;
761#endif
762}
763
764////////////////////////////////////////////////////////////////////////////////
765/// Start profiling timer
766
768{
769 if (_cfg.profile) {
770 _timer.Start();
771 _cumulTimer.Start(_profileStart ? false : true);
772 _profileStart = true;
773 }
774}
775
776////////////////////////////////////////////////////////////////////////////////
777/// Stop profiling timer and report results of last session
778
780{
781 if (_cfg.profile) {
782 _timer.Stop();
784 coutI(Minimization) << "Command timer: ";
785 _timer.Print();
786 coutI(Minimization) << "Session timer: ";
788 }
789}
790
791////////////////////////////////////////////////////////////////////////////////
792/// Apply results of given external covariance matrix. i.e. propagate its errors
793/// to all RRV parameter representations and give this matrix instead of the
794/// HESSE matrix at the next save() call
795
797{
798 _extV.reset(static_cast<TMatrixDSym *>(V.Clone()));
799 _fcn->ApplyCovarianceMatrix(*_extV);
800}
801
803{
804 // Import the results of the last fit performed, interpreting
805 // the fit parameters as the given varList of parameters.
806
807 if (_minimizer == nullptr) {
808 oocoutE(nullptr, InputArguments) << "RooMinimizer::save: Error, run minimization before!" << std::endl;
809 return nullptr;
810 }
811
812 auto res = std::make_unique<RooFitResult>("lastMinuitFit", "Last MINUIT fit");
813
814 // Extract names of fit parameters
815 // and construct corresponding RooRealVars
816 RooArgList constPars("constPars");
817 RooArgList floatPars("floatPars");
818
819 const RooArgList floatParsFromFcn = _fcn->floatParams();
820
821 for (unsigned int i = 0; i < _fcn->getNDim(); ++i) {
822
823 TString varName(floatParsFromFcn.at(i)->GetName());
824 bool isConst(_result->isParameterFixed(i));
825
826 double xlo = _config.ParSettings(i).LowerLimit();
827 double xhi = _config.ParSettings(i).UpperLimit();
828 double xerr = _result->error(i);
829 double xval = _result->fParams[i];
830
831 std::unique_ptr<RooRealVar> var;
832
833 if ((xlo < xhi) && !isConst) {
834 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
835 } else {
836 var = std::make_unique<RooRealVar>(varName, varName, xval);
837 }
838 var->setConstant(isConst);
839
840 if (isConst) {
841 constPars.addOwned(std::move(var));
842 } else {
843 var->setError(xerr);
844 floatPars.addOwned(std::move(var));
845 }
846 }
847
848 res->setConstParList(constPars);
849 res->setInitParList(floatPars);
850 res->setFinalParList(floatPars);
851 res->setMinNLL(_result->fVal);
852 res->setEDM(_result->fEdm);
853 res->setCovQual(_minimizer->CovMatrixStatus());
854 res->setStatus(_result->fStatus);
855 fillCorrMatrix(*res);
856
857 return RooFit::makeOwningPtr(std::move(res));
858}
859
860/// Try to recover from invalid function values. When invalid function values
861/// are encountered, a penalty term is returned to the minimiser to make it
862/// back off. This sets the strength of this penalty. \note A strength of zero
863/// is equivalent to a constant penalty (= the gradient vanishes, ROOT < 6.24).
864/// Positive values lead to a gradient pointing away from the undefined
865/// regions. Use ~10 to force the minimiser away from invalid function values.
867{
868 _cfg.recoverFromNaN = strength;
869}
870
871bool RooMinimizer::setLogFile(const char *logf)
872{
873 _cfg.logf = logf;
874 return _cfg.logf ? _fcn->SetLogFile(_cfg.logf) : false;
875}
876
878{
879 return _fcn->evalCounter();
880}
882{
883 _fcn->zeroEvalCount();
884}
885
887{
888 return _fcn->getNDim();
889}
890
891std::ofstream *RooMinimizer::logfile()
892{
893 return _fcn->GetLogFile();
894}
896{
897 return _fcn->GetMaxFCN();
898}
900{
901 return _fcn->getOffset();
902}
903
904std::unique_ptr<RooAbsReal::EvalErrorContext> RooMinimizer::makeEvalErrorContext() const
905{
907 // If evaluation error printing is disabled, we don't need to collect the
908 // errors and only need to count them. This significantly reduces the
909 // performance overhead when having evaluation errors.
911 return std::make_unique<RooAbsReal::EvalErrorContext>(m);
912}
913
915{
916 // fit a user provided FCN function
917 // create fit parameter settings
918
919 auto operModeRAII = setOperModesDirty(_function);
920
921 // Check number of parameters
922 unsigned int npar = getNPar();
923 if (npar == 0) {
924 coutE(Minimization) << "RooMinimizer::fitFCN(): FCN function has zero parameters" << std::endl;
925 return false;
926 }
927
928 // initiate the minimizer
930
931 // Identify floating RooCategory parameters
932 RooArgSet floatingCats;
933 for (auto arg : _fcn->allParams()) {
934 if (arg->isCategory() && !arg->isConstant())
935 floatingCats.add(*arg);
936 }
937
938 std::vector<RooCategory *> pdfIndices;
939 for (auto *arg : floatingCats) {
940 if (auto *cat = dynamic_cast<RooCategory *>(arg))
941 pdfIndices.push_back(cat);
942 }
943
944 const size_t nPdfs = pdfIndices.size();
945
946 // Identify floating continuous parameters (RooRealVar)
947 RooArgSet floatReals;
948 for (auto arg : _fcn->allParams()) {
949 if (!arg->isCategory() && !arg->isConstant())
950 floatReals.add(*arg);
951 }
952
953 if (nPdfs == 0) {
954 coutI(Minimization) << "[fitFCN] No discrete parameters, performing continuous minimization only" << std::endl;
955 FreezeDisconnectedParametersRAII freeze(this, *_fcn);
956 bool isValid = _minimizer->Minimize();
957 if (!_result)
958 _result = std::make_unique<FitResult>();
959 fillResult(isValid);
960 if (isValid)
962 return isValid;
963 }
964
965 // set also new parameter values and errors in FitConfig
966 // Prepare discrete indices
967 std::vector<int> maxIndices;
968 maxIndices.reserve(pdfIndices.size());
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;
980 auto combos = generateOrthogonalCombinations(maxIndices);
981 reorderCombinations(combos, maxIndices, bestIndices);
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;
1008 bestIndices = combo;
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
1061 auto operModeRAII = setOperModesDirty(_function);
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
1097 auto operModeRAII = setOperModesDirty(_function);
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 }
1119 iparNewMin = 0;
1120 for (int i = 0; i < iparMax; ++i) {
1121 double elow;
1122 double eup;
1123 unsigned int index = (!ipars.empty()) ? ipars[i] : i;
1124 bool ret = _minimizer->GetMinosError(index, elow, eup);
1125 // flags case when a new minimum has been found
1126 if ((_minimizer->MinosStatus() & 8) != 0) {
1127 iparNewMin = i;
1128 }
1129 if (ret)
1130 _result->fMinosErrors.emplace(index, std::make_pair(elow, eup));
1131 ok |= ret;
1132 }
1133
1134 iparMax = iparNewMin;
1135 iter++; // to avoid infinite looping
1136 } while (iparNewMin > 0 && iter < 10);
1137 if (!ok) {
1138 coutE(Minimization)
1139 << "RooMinimizer::calculateMinosErrors() Minos error calculation failed for all the selected parameters"
1140 << std::endl;
1141 }
1142
1143 // re-give a minimizer instance in case it has been changed
1144 // but maintain previous valid status. Do not set result to false if minos failed
1145 ok &= update(_result->fValid);
1146
1147 return ok;
1148}
1149
1151{
1152 _minimizer = std::unique_ptr<ROOT::Math::Minimizer>(_config.CreateMinimizer());
1153 _fcn->initMinimizer(*_minimizer, this);
1154 _minimizer->SetVariables(_config.ParamsSettings().begin(), _config.ParamsSettings().end());
1155
1157 std::vector<double> v;
1158 for (std::size_t i = 0; i < _fcn->getNDim(); ++i) {
1159 RooRealVar &param = _fcn->floatableParam(i);
1160 v.push_back(param.getError() * param.getError());
1161 }
1162 _minimizer->SetCovarianceDiag(v, v.size());
1163 }
1164}
1165
1166bool RooMinimizer::updateMinimizerOptions(bool canDifferentMinim)
1167{
1168 // update minimizer options when re-doing a Fit or computing Hesse or Minos errors
1169
1170 // create a new minimizer if it is different type
1171 // minimizer type string stored in FitResult is "minimizer name" + " / " + minimizer algo
1172 std::string newMinimType = _config.MinimizerName();
1173 if (_minimizer && _result && newMinimType != _result->fMinimType) {
1174 // if a different minimizer is allowed (e.g. when calling Hesse)
1175 if (canDifferentMinim) {
1176 std::string msg = "Using now " + newMinimType;
1177 coutI(Minimization) << "RooMinimizer::updateMinimizerOptions(): " << msg << std::endl;
1178 initMinimizer();
1179 } else {
1180 std::string msg = "Cannot change minimizer. Continue using " + _result->fMinimType;
1181 coutW(Minimization) << "RooMinimizer::updateMinimizerOptions() " << msg << std::endl;
1182 }
1183 }
1184
1185 // create minimizer if it was not done before
1186 if (!_minimizer) {
1187 initMinimizer();
1188 }
1189
1190 // set new minimizer options (but not functions and parameters)
1191 _minimizer->SetOptions(_config.MinimizerOptions());
1192 return true;
1193}
1194
1196{
1197 // update the fit configuration after a fit using the obtained result
1198 if (_result->fParams.empty() || !_result->fValid)
1199 return;
1200 for (unsigned int i = 0; i < _config.NPar(); ++i) {
1202 par.SetValue(_result->fParams[i]);
1203 if (_result->error(i) > 0)
1204 par.SetStepSize(_result->error(i));
1205 }
1206}
1207
1209 : fStatus(-99), // use this special convention to flag it when printing result
1210 fCovStatus(0),
1211 fParams(fconfig.NPar()),
1212 fErrors(fconfig.NPar()),
1213 fMinimType(fconfig.MinimizerType())
1214{
1215 // create a Fit result from a fit config (i.e. with initial parameter values
1216 // and errors equal to step values
1217 // The model function is NULL in this case
1218
1219 // set minimizer type and algorithm
1220 // append algorithm name for minimizer that support it
1221 if ((fMinimType.find("Fumili") == std::string::npos) && (fMinimType.find("GSLMultiFit") == std::string::npos)) {
1222 if (!fconfig.MinimizerAlgoType().empty())
1223 fMinimType += " / " + fconfig.MinimizerAlgoType();
1224 }
1225
1226 // get parameter values and errors (step sizes)
1227 for (unsigned int i = 0; i < fconfig.NPar(); ++i) {
1228 const ROOT::Fit::ParameterSettings &par = fconfig.ParSettings(i);
1229 fParams[i] = par.Value();
1230 fErrors[i] = par.StepSize();
1231 if (par.IsFixed())
1232 fFixedParams[i] = true;
1233 }
1234}
1235
1237{
1239 ROOT::Fit::FitConfig const &fconfig = _config;
1240
1241 // Fill the FitResult after minimization using result from Minimizers
1242
1243 _result->fValid = isValid;
1244 _result->fStatus = min.Status();
1245 _result->fCovStatus = min.CovMatrixStatus();
1246 _result->fVal = min.MinValue();
1247 _result->fEdm = min.Edm();
1248
1249 _result->fMinimType = fconfig.MinimizerName();
1250
1251 const unsigned int npar = min.NDim();
1252 if (npar == 0)
1253 return;
1254
1255 if (min.X()) {
1256 _result->fParams = std::vector<double>(min.X(), min.X() + npar);
1257 } else {
1258 // case minimizer does not provide minimum values (it failed) take from configuration
1259 _result->fParams.resize(npar);
1260 for (unsigned int i = 0; i < npar; ++i) {
1261 _result->fParams[i] = (fconfig.ParSettings(i).Value());
1262 }
1263 }
1264
1265 // check for fixed or limited parameters
1266 for (unsigned int ipar = 0; ipar < npar; ++ipar) {
1267 if (fconfig.ParSettings(ipar).IsFixed())
1268 _result->fFixedParams[ipar] = true;
1269 }
1270
1271 // fill error matrix
1272 // if minimizer provides error provides also error matrix
1273 // clear in case of re-filling an existing result
1274 _result->fCovMatrix.clear();
1275
1276 if (min.Errors() != nullptr) {
1277 updateErrors();
1278 }
1279}
1280
1281bool RooMinimizer::update(bool isValid)
1282{
1284 ROOT::Fit::FitConfig const &fconfig = _config;
1285
1286 // update fit result with new status from minimizer
1287 // ncalls if it is not zero is used instead of value from minimizer
1288
1289 // in case minimizer changes
1290 _result->fMinimType = fconfig.MinimizerName();
1291
1292 const std::size_t npar = _result->fParams.size();
1293
1294 _result->fValid = isValid;
1295 // update minimum value
1296 _result->fVal = min.MinValue();
1297 _result->fEdm = min.Edm();
1298 _result->fStatus = min.Status();
1299 _result->fCovStatus = min.CovMatrixStatus();
1300
1301 // copy parameter value and errors
1302 std::copy(min.X(), min.X() + npar, _result->fParams.begin());
1303
1304 if (min.Errors() != nullptr) {
1305 updateErrors();
1306 }
1307 return true;
1308}
1309
1311{
1313 const std::size_t npar = _result->fParams.size();
1314
1315 _result->fErrors.resize(npar);
1316 std::copy(min.Errors(), min.Errors() + npar, _result->fErrors.begin());
1317
1318 if (_result->fCovStatus != 0) {
1319
1320 // update error matrix
1321 unsigned int r = npar * (npar + 1) / 2;
1322 _result->fCovMatrix.resize(r);
1323 unsigned int l = 0;
1324 for (unsigned int i = 0; i < npar; ++i) {
1325 for (unsigned int j = 0; j <= i; ++j)
1326 _result->fCovMatrix[l++] = min.CovMatrix(i, j);
1327 }
1328 }
1329 // minos errors are set separately when calling Fitter::CalculateMinosErrors()
1330}
1331
1332double RooMinimizer::FitResult::lowerError(unsigned int i) const
1333{
1334 // return lower Minos error for parameter i
1335 // return the parabolic error if Minos error has not been calculated for the parameter i
1336 auto itr = fMinosErrors.find(i);
1337 return (itr != fMinosErrors.end()) ? itr->second.first : error(i);
1338}
1339
1340double RooMinimizer::FitResult::upperError(unsigned int i) const
1341{
1342 // return upper Minos error for parameter i
1343 // return the parabolic error if Minos error has not been calculated for the parameter i
1344 auto itr = fMinosErrors.find(i);
1345 return (itr != fMinosErrors.end()) ? itr->second.second : error(i);
1346}
1347
1349{
1350 return fFixedParams.find(ipar) != fFixedParams.end();
1351}
1352
1354{
1355 const size_t nParams = fParams.size();
1356 covs.ResizeTo(nParams, nParams);
1357 for (std::size_t ic = 0; ic < nParams; ic++) {
1358 for (std::size_t ii = 0; ii < nParams; ii++) {
1359 covs(ic, ii) = covMatrix(fCovMatrix, ic, ii);
1360 }
1361 }
1362}
#define coutI(a)
#define coutW(a)
#define oocoutE(o, a)
#define oocoutI(o, a)
#define coutE(a)
@ kBlue
Definition Rtypes.h:66
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
const std::string & MinimizerAlgoType() const
return type of minimizer algorithms
Definition FitConfig.h:196
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
double LowerLimit() const
return lower limit value
void SetStepSize(double err)
set the step size
double Value() const
return parameter value
double StepSize() const
return step size
double UpperLimit() const
return upper limit value
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
Common abstract base class for objects that represent a value and a "shape" in RooFit.
Definition RooAbsArg.h:77
bool isConstant() const
Check if the "Constant" attribute is set.
Definition RooAbsArg.h:284
RooAbsCollection * snapshot(bool deepCopy=true) const
Take a snap shot of current collection contents.
virtual bool add(const RooAbsArg &var, bool silent=false)
Add the specified argument to list.
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.
RooAbsArg * find(const char *name) const
Find object with given name in list.
Abstract base class for objects that represent a real value and implements functionality common to al...
Definition RooAbsReal.h:63
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
Definition RooAbsReal.h:107
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
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
Definition RooArgList.h:110
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.
void fillCorrMatrix(const std::vector< double > &globalCC, const TMatrixDSym &corrs, const TMatrixDSym &covs)
Function called by RooMinimizer.
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
TMatrixTBase< Element > & ResizeTo(Int_t nrows, Int_t ncols, Int_t=-1) override
Set size of the matrix to nrows x ncols New dynamic elements are created, the overlapping part of the...
const char * GetName() const override
Returns name of object.
Definition TNamed.h:49
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