Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
Minuit2Minimizer.cxx
Go to the documentation of this file.
1// @(#)root/minuit2:$Id$
2// Author: L. Moneta Wed Oct 18 11:48:00 2006
3
4/**********************************************************************
5 * *
6 * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7 * *
8 * *
9 **********************************************************************/
10
11// Implementation file for class Minuit2Minimizer
12
14
15#include "Math/IFunction.h"
16#include "Math/IOptions.h"
17
19
20#include "Minuit2/FCNAdapter.h"
23#include "Minuit2/MnMigrad.h"
24#include "Minuit2/MnMinos.h"
25#include "Minuit2/MinosError.h"
26#include "Minuit2/MnHesse.h"
28#include "Minuit2/MnPrint.h"
35#include "Minuit2/MnContours.h"
38
39#include <cassert>
40#include <iostream>
41#include <algorithm>
42#include <functional>
43
44#ifdef USE_ROOT_ERROR
45#include "TError.h"
46#include "TROOT.h"
47#include "TMinuit2TraceObject.h"
48#endif
49
50namespace ROOT {
51
52namespace Minuit2 {
53
54// functions needed to control siwthc off of Minuit2 printing level
55#ifdef USE_ROOT_ERROR
57{
58 // switch off Minuit2 printing of INFO message (cut off is 1001)
60 if (prevErrorIgnoreLevel < 1001) {
61 gErrorIgnoreLevel = 1001;
63 }
64 return -2; // no op in this case
65}
66
68{
70}
71#else
72// dummy functions
74{
75 return -1;
76}
78{
79 return -1;
80}
82#endif
83
85{
86 // Default constructor implementation depending on minimizer type
88}
89
91{
92 // constructor from a string
93
94 std::string algoname(type);
95 // tolower() is not an std function (Windows)
96 std::transform(algoname.begin(), algoname.end(), algoname.begin(), (int (*)(int))tolower);
97
99 if (algoname == "simplex")
101 if (algoname == "minimize")
103 if (algoname == "scan")
104 algoType = kScan;
105 if (algoname == "fumili" || algoname == "fumili2")
107 if (algoname == "bfgs")
109
111}
112
114{
115 // Set minimizer algorithm type
116 fUseFumili = false;
117 switch (type) {
118 case ROOT::Minuit2::kMigrad: fMinimizer = std::make_unique<ROOT::Minuit2::VariableMetricMinimizer>(); return;
120 fMinimizer = std::make_unique<ROOT::Minuit2::VariableMetricMinimizer>(VariableMetricMinimizer::BFGSType());
121 return;
122 case ROOT::Minuit2::kSimplex: fMinimizer = std::make_unique<ROOT::Minuit2::SimplexMinimizer>(); return;
123 case ROOT::Minuit2::kCombined: fMinimizer = std::make_unique<ROOT::Minuit2::CombinedMinimizer>(); return;
124 case ROOT::Minuit2::kScan: fMinimizer = std::make_unique<ROOT::Minuit2::ScanMinimizer>(); return;
126 fMinimizer = std::make_unique<ROOT::Minuit2::FumiliMinimizer>();
127 fUseFumili = true;
128 return;
129 default:
130 // migrad minimizer
131 fMinimizer = std::make_unique<ROOT::Minuit2::VariableMetricMinimizer>();
132 }
133}
134
136
138{
139 // delete the state in case of consecutive minimizations
141 // clear also the function minimum
142 fMinimum.reset();
143}
144
145// set variables
146
147bool Minuit2Minimizer::SetVariable(unsigned int ivar, const std::string &name, double val, double step)
148{
149 // set a free variable.
150 // Add the variable if not existing otherwise set value if exists already
151 // this is implemented in MnUserParameterState::Add
152 // if index is wrong (i.e. variable already exists but with a different index return false) but
153 // value is set for corresponding variable name
154
155 // std::cout << " add parameter " << name << " " << val << " step " << step << std::endl;
156 MnPrint print("Minuit2Minimizer::SetVariable", PrintLevel());
157
158 if (step <= 0) {
159 print.Info("Parameter", name, "has zero or invalid step size - consider it as constant");
160 fState.Add(name, val);
161 } else
162 fState.Add(name, val, step);
163
164 unsigned int minuit2Index = fState.Index(name);
165 if (minuit2Index != ivar) {
166 print.Warn("Wrong index", minuit2Index, "used for the variable", name);
168 return false;
169 }
171
172 return true;
173}
174
175/** set initial second derivatives
176 */
177bool Minuit2Minimizer::SetCovarianceDiag(std::span<const double> d2, unsigned int n)
178{
179 MnPrint print("Minuit2Minimizer::SetCovarianceDiag", PrintLevel());
180
181 std::vector<double> cov(n * (n + 1) / 2);
182
183 for (unsigned int i = 0; i < n; i++) {
184 for (unsigned int j = i; j < n; j++)
185 cov[i + j * (j + 1) / 2] = (i == j) ? d2[i] : 0.;
186 }
187
189}
190
191bool Minuit2Minimizer::SetCovariance(std::span<const double> cov, unsigned int nrow)
192{
193 MnPrint print("Minuit2Minimizer::SetCovariance", PrintLevel());
194
196
197 return true;
198}
199
200bool Minuit2Minimizer::SetLowerLimitedVariable(unsigned int ivar, const std::string &name, double val, double step,
201 double lower)
202{
203 // add a lower bounded variable
204 if (!SetVariable(ivar, name, val, step))
205 return false;
207 return true;
208}
209
210bool Minuit2Minimizer::SetUpperLimitedVariable(unsigned int ivar, const std::string &name, double val, double step,
211 double upper)
212{
213 // add a upper bounded variable
214 if (!SetVariable(ivar, name, val, step))
215 return false;
217 return true;
218}
219
220bool Minuit2Minimizer::SetLimitedVariable(unsigned int ivar, const std::string &name, double val, double step,
221 double lower, double upper)
222{
223 // add a double bound variable
224 if (!SetVariable(ivar, name, val, step))
225 return false;
227 return true;
228}
229
230bool Minuit2Minimizer::SetFixedVariable(unsigned int ivar, const std::string &name, double val)
231{
232 // add a fixed variable
233 // need a step size otherwise treated as a constant
234 // use 10%
235 double step = (val != 0) ? 0.1 * std::abs(val) : 0.1;
236 if (!SetVariable(ivar, name, val, step)) {
238 }
239 fState.Fix(ivar);
240 return true;
241}
242
243std::string Minuit2Minimizer::VariableName(unsigned int ivar) const
244{
245 // return the variable name
246 if (ivar >= fState.MinuitParameters().size())
247 return std::string();
248 return fState.GetName(ivar);
249}
250
251int Minuit2Minimizer::VariableIndex(const std::string &name) const
252{
253 // return the variable index
254 // check if variable exist
255 return fState.Trafo().FindIndex(name);
256}
257
258bool Minuit2Minimizer::SetVariableValue(unsigned int ivar, double val)
259{
260 // set value for variable ivar (only for existing parameters)
261 if (ivar >= fState.MinuitParameters().size())
262 return false;
263 fState.SetValue(ivar, val);
264 return true;
265}
266
268{
269 // set value for variable ivar (only for existing parameters)
270 unsigned int n = fState.MinuitParameters().size();
271 if (n == 0)
272 return false;
273 for (unsigned int ivar = 0; ivar < n; ++ivar)
275 return true;
276}
277
278bool Minuit2Minimizer::SetVariableStepSize(unsigned int ivar, double step)
279{
280 // set the step-size of an existing variable
281 // parameter must exist or return false
282 if (ivar >= fState.MinuitParameters().size())
283 return false;
284 fState.SetError(ivar, step);
285 return true;
286}
287
289{
290 // set the limits of an existing variable
291 // parameter must exist or return false
292 if (ivar >= fState.MinuitParameters().size())
293 return false;
295 return true;
296}
298{
299 // set the limits of an existing variable
300 // parameter must exist or return false
301 if (ivar >= fState.MinuitParameters().size())
302 return false;
304 return true;
305}
306
307bool Minuit2Minimizer::SetVariableLimits(unsigned int ivar, double lower, double upper)
308{
309 // set the limits of an existing variable
310 // parameter must exist or return false
311 if (ivar >= fState.MinuitParameters().size())
312 return false;
314 return true;
315}
316
318{
319 // Fix an existing variable
320 if (ivar >= fState.MinuitParameters().size())
321 return false;
322 fState.Fix(ivar);
323 return true;
324}
325
327{
328 // Release an existing variable
329 if (ivar >= fState.MinuitParameters().size())
330 return false;
332 return true;
333}
334
336{
337 // query if variable is fixed
338 if (ivar >= fState.MinuitParameters().size()) {
339 MnPrint print("Minuit2Minimizer", PrintLevel());
340 print.Error("Wrong variable index");
341 return false;
342 }
343 return (fState.Parameter(ivar).IsFixed() || fState.Parameter(ivar).IsConst());
344}
345
347{
348 // retrieve variable settings (all set info on the variable)
349 if (ivar >= fState.MinuitParameters().size()) {
350 MnPrint print("Minuit2Minimizer", PrintLevel());
351 print.Error("Wrong variable index");
352 return false;
353 }
354 const MinuitParameter &par = fState.Parameter(ivar);
355 varObj.Set(par.Name(), par.Value(), par.Error());
356 if (par.HasLowerLimit()) {
357 if (par.HasUpperLimit()) {
358 varObj.SetLimits(par.LowerLimit(), par.UpperLimit());
359 } else {
360 varObj.SetLowerLimit(par.LowerLimit());
361 }
362 } else if (par.HasUpperLimit()) {
363 varObj.SetUpperLimit(par.UpperLimit());
364 }
365 if (par.IsConst() || par.IsFixed())
366 varObj.Fix();
367 return true;
368}
369
371{
372 // set function to be minimized
373 fMinuitFCN.reset();
374 fDim = func.NDim();
375 const bool hasGrad = func.HasGradient();
376 if (!fUseFumili) {
377 auto lambdaFunc = [&func](double const *params) { return func(params); };
378 auto adapter = std::make_unique<ROOT::Minuit2::FCNAdapter>(lambdaFunc, ErrorDef());
379 if (hasGrad) {
380 auto const &gradFunc = dynamic_cast<ROOT::Math::IMultiGradFunction const &>(func);
381 auto lambdaGrad = [&gradFunc](double const *params, double *grad) { return gradFunc.Gradient(params, grad); };
382 adapter->SetGradientFunction(lambdaGrad);
383 }
384 fMinuitFCN = std::move(adapter);
385 return;
386 }
387 if (hasGrad) {
388 // for Fumili the fit method function interface is required
389 auto fcnfunc = dynamic_cast<const ROOT::Math::FitMethodGradFunction *>(&func);
390 if (!fcnfunc) {
391 MnPrint print("Minuit2Minimizer", PrintLevel());
392 print.Error("Wrong Fit method function for Fumili");
393 return;
394 }
395 fMinuitFCN = std::make_unique<ROOT::Minuit2::FumiliFCNAdapter<ROOT::Math::FitMethodGradFunction>>(*fcnfunc, fDim,
396 ErrorDef());
397 } else {
398 // for Fumili the fit method function interface is required
399 auto fcnfunc = dynamic_cast<const ROOT::Math::FitMethodFunction *>(&func);
400 if (!fcnfunc) {
401 MnPrint print("Minuit2Minimizer", PrintLevel());
402 print.Error("Wrong Fit method function for Fumili");
403 return;
404 }
405 fMinuitFCN =
406 std::make_unique<ROOT::Minuit2::FumiliFCNAdapter<ROOT::Math::FitMethodFunction>>(*fcnfunc, fDim, ErrorDef());
407 }
408}
409
410void Minuit2Minimizer::SetHessianFunction(std::function<bool(std::span<const double>, double *)> hfunc)
411{
412 // for Fumili not supported for the time being
413 if (fUseFumili) return;
414 auto fcn = static_cast<ROOT::Minuit2::FCNAdapter *>(fMinuitFCN.get());
415 if (!fcn) return;
416 fcn->SetHessianFunction(hfunc);
417}
418
419namespace {
420
422{
424 // set strategy and add extra options if needed
426 if (!minuit2Opt) {
428 }
429 if (!minuit2Opt) {
430 return st;
431 }
432 auto customize = [&minuit2Opt](const char *name, auto val) {
433 minuit2Opt->GetValue(name, val);
434 return val;
435 };
436 // set extra options
437 st.SetGradientNCycles(customize("GradientNCycles", int(st.GradientNCycles())));
438 st.SetHessianNCycles(customize("HessianNCycles", int(st.HessianNCycles())));
439 st.SetHessianGradientNCycles(customize("HessianGradientNCycles", int(st.HessianGradientNCycles())));
440
441 st.SetGradientTolerance(customize("GradientTolerance", st.GradientTolerance()));
442 st.SetGradientStepTolerance(customize("GradientStepTolerance", st.GradientStepTolerance()));
443 st.SetHessianStepTolerance(customize("HessianStepTolerance", st.HessianStepTolerance()));
444 st.SetHessianG2Tolerance(customize("HessianG2Tolerance", st.HessianG2Tolerance()));
445
446 // These two are the parts of strategy 3 that matter most for ill-conditioned problems
447 st.SetHessianCentralFDMixedDerivatives(
448 customize("HessianCentralFDMixedDerivatives", int(st.HessianCentralFDMixedDerivatives())));
449 st.SetHessianForcePosDef(customize("HessianForcePosDef", int(st.HessianForcePosDef())));
450
451 return st;
452}
453
454} // namespace
455
456/// Perform the minimization and store a copy of FunctionMinimum.
457/// The maximum number of function calls used can be checked via `this->MaxFunctionCalls()`,
458/// if this value is 0 (the default), then it is replaced with
459/// `2 * (nvar + 1) * (200 + 100 * nvar + 5 * nvar * nvar` where `nvar` is number of variable parameters.
460/// \see MnMinos::FindCrossValue
461/// Other minimization settings can be retrieved via `Tolerance()`, `Strategy()`, `ErrorDef()`, `Precision()`
462/// \see ROOT::Math::MinimizerOptions::PrintDefault()
464{
465
466
467 MnPrint print("Minuit2Minimizer::Minimize", PrintLevel());
468
469 if (!fMinuitFCN) {
470 print.Error("FCN function has not been set");
471 return false;
472 }
473
474 assert(GetMinimizer() != nullptr);
475
476 // delete result of previous minimization
477 fMinimum.reset();
478
479 const int maxfcn = MaxFunctionCalls();
480 const double tol = Tolerance();
481 const int strategyLevel = Strategy();
482 fMinuitFCN->SetErrorDef(ErrorDef());
483
484 const int printLevel = PrintLevel();
485 print.Debug("Minuit print level is", printLevel);
486 if (PrintLevel() >= 1) {
487 // print the real number of maxfcn used (defined in ModularFunctionMinimizer)
488 int maxfcn_used = maxfcn;
489 if (maxfcn_used == 0) {
490 int nvar = fState.VariableParameters();
491 maxfcn_used = 200 + 100 * nvar + 5 * nvar * nvar;
492 }
493 std::cout << "Minuit2Minimizer: Minimize with max-calls " << maxfcn_used << " convergence for edm < " << tol
494 << " strategy " << strategyLevel << std::endl;
495 }
496
497 // internal minuit messages
498 fMinimizer->Builder().SetPrintLevel(printLevel);
499
500 // switch off Minuit2 printing
501 const int prev_level = (printLevel <= 0) ? TurnOffPrintInfoLevel() : -2;
503
504 // set the precision if needed
505 if (Precision() > 0)
507
508 // add extra options if needed
510 if (!minuit2Opt) {
512 }
513 if (minuit2Opt) {
514 // set extra options
515 int storageLevel = 1;
516 bool ret = minuit2Opt->GetValue("StorageLevel", storageLevel);
517 if (ret)
519
520 // fumili options
521 if (fUseFumili) {
522 std::string fumiliMethod;
523 ret = minuit2Opt->GetValue("FumiliMethod", fumiliMethod);
524 if (ret) {
525 auto fumiliMinimizer = dynamic_cast<ROOT::Minuit2::FumiliMinimizer *>(fMinimizer.get());
526 if (fumiliMinimizer)
527 fumiliMinimizer->SetMethod(fumiliMethod);
528 }
529 }
530
531 if (printLevel > 0) {
532 std::cout << "Minuit2Minimizer::Minuit - Changing default options" << std::endl;
533 minuit2Opt->Print();
534 }
535 }
536
537 // set a minimizer tracer object (default for printlevel=10, from gROOT for printLevel=11)
538 // use some special print levels
539 MnTraceObject *traceObj = nullptr;
540#ifdef USE_ROOT_ERROR
541 if (printLevel == 10 && gROOT) {
542 TObject *obj = gROOT->FindObject("Minuit2TraceObject");
543 traceObj = dynamic_cast<ROOT::Minuit2::MnTraceObject *>(obj);
544 if (traceObj) {
545 // need to remove from the list
546 gROOT->Remove(obj);
547 }
548 }
549 if (printLevel == 20 || printLevel == 30 || printLevel == 40 || (printLevel >= 20000 && printLevel < 30000)) {
550 int parNumber = printLevel - 20000;
551 if (printLevel == 20)
552 parNumber = -1;
553 if (printLevel == 30)
554 parNumber = -2;
555 if (printLevel == 40)
556 parNumber = 0;
558 }
559#endif
560 if (printLevel == 100 || (printLevel >= 10000 && printLevel < 20000)) {
561 int parNumber = printLevel - 10000;
563 }
564 if (traceObj) {
565 traceObj->Init(fState);
567 }
568
570
572 fMinimum = std::make_unique<ROOT::Minuit2::FunctionMinimum>(min);
573
574 // check if Hesse needs to be run. We do it when is requested (IsValidError() == true , set by SetParabError(true) in fitConfig)
575 // (IsValidError() means the flag to get correct error from the Minimizer is set (Minimizer::SetValidError())
576 // AND when we have a valid minimum,
577 // AND when the the current covariance matrix is estimated using the iterative approximation (Dcovar != 0 , i.e. Hesse has not computed before)
578 if (fMinimum->IsValid() && IsValidError() && fMinimum->State().Error().Dcovar() != 0) {
579 // run Hesse (Hesse will add results in the last state of fMinimum
581 hesse(*fMinuitFCN, *fMinimum, maxfcn);
582 }
583
584 // -2 is the highest low invalid value for gErrorIgnoreLevel
585 if (prev_level > -2)
588
589 // copy minimum state (parameter values and errors)
590 fState = fMinimum->UserState();
591 bool ok = ExamineMinimum(*fMinimum);
592 // fMinimum = 0;
593
594 // delete trace object if it was constructed
595 if (traceObj) {
596 delete traceObj;
597 }
598 return ok;
599}
600
602{
603 /// study the function minimum
604
605 // debug ( print all the states)
606 int debugLevel = PrintLevel();
607 if (debugLevel >= 3) {
608
609 std::span<const ROOT::Minuit2::MinimumState> iterationStates = min.States();
610 std::cout << "Number of iterations " << iterationStates.size() << std::endl;
611 for (unsigned int i = 0; i < iterationStates.size(); ++i) {
612 // std::cout << iterationStates[i] << std::endl;
614 std::cout << "----------> Iteration " << i << std::endl;
615 int pr = std::cout.precision(12);
616 std::cout << " FVAL = " << st.Fval() << " Edm = " << st.Edm() << " Nfcn = " << st.NFcn()
617 << std::endl;
618 std::cout.precision(pr);
619 if (st.HasCovariance())
620 std::cout << " Error matrix change = " << st.Error().Dcovar() << std::endl;
621 if (st.HasParameters()) {
622 std::cout << " Parameters : ";
623 // need to transform from internal to external
624 for (int j = 0; j < st.size(); ++j)
625 std::cout << " p" << j << " = " << fState.Int2ext(j, st.Vec()(j));
626 std::cout << std::endl;
627 }
628 }
629 }
630
631 fStatus = 0;
632 std::string txt;
633 if (!min.HasPosDefCovar()) {
634 // this happens normally when Hesse failed
635 // it can happen in case MnSeed failed (see ROOT-9522)
636 txt = "Covar is not pos def";
637 fStatus = 5;
638 }
639 if (min.HasMadePosDefCovar()) {
640 txt = "Covar was made pos def";
641 fStatus = 1;
642 }
643 if (min.HesseFailed()) {
644 txt = "Hesse is not valid";
645 fStatus = 2;
646 }
647 if (min.IsAboveMaxEdm()) {
648 txt = "Edm is above max";
649 fStatus = 3;
650 }
651 if (min.HasReachedCallLimit()) {
652 txt = "Reached call limit";
653 fStatus = 4;
654 }
655
656 MnPrint print("Minuit2Minimizer::Minimize", debugLevel);
657 bool validMinimum = min.IsValid();
658 if (validMinimum) {
659 // print a warning message in case something is not ok
660 // this for example is case when Covar was made posdef and fStatus=3
661 if (fStatus != 0 && debugLevel > 0)
662 print.Warn(txt);
663 } else {
664 // minimum is not valid when state is not valid and edm is over max or has passed call limits
665 if (fStatus == 0) {
666 // this should not happen
667 txt = "unknown failure";
668 fStatus = 6;
669 }
670 print.Warn("Minimization did NOT converge,", txt);
671 }
672
673 if (debugLevel >= 1)
674 PrintResults();
675
676 // set the minimum values in the fValues vector
677 std::span<const MinuitParameter> paramsObj = fState.MinuitParameters();
678 if (paramsObj.empty())
679 return false;
680 assert(fDim == paramsObj.size());
681 // re-size vector if it has changed after a new minimization
682 if (fValues.size() != fDim)
683 fValues.resize(fDim);
684 for (unsigned int i = 0; i < fDim; ++i) {
685 fValues[i] = paramsObj[i].Value();
686 }
687
688 return validMinimum;
689}
690
692{
693 // print results of minimization
694 if (!fMinimum)
695 return;
696 if (fMinimum->IsValid()) {
697 // valid minimum
698 std::cout << "Minuit2Minimizer : Valid minimum - status = " << fStatus << std::endl;
699 int pr = std::cout.precision(18);
700 std::cout << "FVAL = " << fState.Fval() << std::endl;
701 std::cout << "Edm = " << fState.Edm() << std::endl;
702 std::cout.precision(pr);
703 std::cout << "Nfcn = " << fState.NFcn() << std::endl;
704 for (unsigned int i = 0; i < fState.MinuitParameters().size(); ++i) {
705 const MinuitParameter &par = fState.Parameter(i);
706 std::cout << par.Name() << "\t = " << par.Value() << "\t ";
707 if (par.IsFixed())
708 std::cout << "(fixed)" << std::endl;
709 else if (par.IsConst())
710 std::cout << "(const)" << std::endl;
711 else if (par.HasLimits())
712 std::cout << "+/- " << par.Error() << "\t(limited)" << std::endl;
713 else
714 std::cout << "+/- " << par.Error() << std::endl;
715 }
716 } else {
717 std::cout << "Minuit2Minimizer : Invalid minimum - status = " << fStatus << std::endl;
718 std::cout << "FVAL = " << fState.Fval() << std::endl;
719 std::cout << "Edm = " << fState.Edm() << std::endl;
720 std::cout << "Nfcn = " << fState.NFcn() << std::endl;
721 }
722}
723
724const double *Minuit2Minimizer::Errors() const
725{
726 // return error at minimum (set to zero for fixed and constant params)
727 std::span<const MinuitParameter> paramsObj = fState.MinuitParameters();
728 if (paramsObj.empty())
729 return nullptr;
730 assert(fDim == paramsObj.size());
731 // be careful for multiple calls of this function. I will redo an allocation here
732 // only when size of vectors has changed (e.g. after a new minimization)
733 if (fErrors.size() != fDim)
734 fErrors.resize(fDim);
735 for (unsigned int i = 0; i < fDim; ++i) {
736 const MinuitParameter &par = paramsObj[i];
737 if (par.IsFixed() || par.IsConst())
738 fErrors[i] = 0;
739 else
740 fErrors[i] = par.Error();
741 }
742
743 return &fErrors.front();
744}
745
746double Minuit2Minimizer::CovMatrix(unsigned int i, unsigned int j) const
747{
748 // get value of covariance matrices (transform from external to internal indices)
749 if (i >= fDim || j >= fDim)
750 return 0;
751 if (!fState.HasCovariance())
752 return 0; // no info available when minimization has failed
753 if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst())
754 return 0;
755 if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst())
756 return 0;
757 unsigned int k = fState.IntOfExt(i);
758 unsigned int l = fState.IntOfExt(j);
759 return fState.Covariance()(k, l);
760}
761
763{
764 // get value of covariance matrices
765 if (!fState.HasCovariance())
766 return false; // no info available when minimization has failed
767 for (unsigned int i = 0; i < fDim; ++i) {
768 if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst()) {
769 for (unsigned int j = 0; j < fDim; ++j) {
770 cov[i * fDim + j] = 0;
771 }
772 } else {
773 unsigned int l = fState.IntOfExt(i);
774 for (unsigned int j = 0; j < fDim; ++j) {
775 // could probably speed up this loop (if needed)
776 int k = i * fDim + j;
777 if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst())
778 cov[k] = 0;
779 else {
780 // need to transform from external to internal indices)
781 // for taking care of the removed fixed row/columns in the Minuit2 representation
782 unsigned int m = fState.IntOfExt(j);
783 cov[k] = fState.Covariance()(l, m);
784 }
785 }
786 }
787 }
788 return true;
789}
790
792{
793 // get value of Hessian matrix
794 // this is the second derivative matrices
795 //
796 // Note: for parameters with limits, the returned external Hessian is obtained by inverting the
797 // external covariance matrix, which is transformed from the internal one with the Jacobian of the
798 // int<->ext transformation only (see MnUserTransformation::Int2extCovariance). This is correct only
799 // at the minimum, where the external gradient vanishes. Away from the minimum the transformation
800 // would need an additional second-derivative term and the result would be inaccurate.
801 if (!fState.HasCovariance())
802 return false; // no info available when minimization has failed
803 for (unsigned int i = 0; i < fDim; ++i) {
804 if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst()) {
805 for (unsigned int j = 0; j < fDim; ++j) {
806 hess[i * fDim + j] = 0;
807 }
808 } else {
809 unsigned int l = fState.IntOfExt(i);
810 for (unsigned int j = 0; j < fDim; ++j) {
811 // could probably speed up this loop (if needed)
812 int k = i * fDim + j;
813 if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst())
814 hess[k] = 0;
815 else {
816 // need to transform from external to internal indices)
817 // for taking care of the removed fixed row/columns in the Minuit2 representation
818 unsigned int m = fState.IntOfExt(j);
819 hess[k] = fState.Hessian()(l, m);
820 }
821 }
822 }
823 }
824
825 return true;
826}
827
828double Minuit2Minimizer::Correlation(unsigned int i, unsigned int j) const
829{
830 // get correlation between parameter i and j
831 if (i >= fDim || j >= fDim)
832 return 0;
833 if (!fState.HasCovariance())
834 return 0; // no info available when minimization has failed
835 if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst())
836 return 0;
837 if (fState.Parameter(j).IsFixed() || fState.Parameter(j).IsConst())
838 return 0;
839 unsigned int k = fState.IntOfExt(i);
840 unsigned int l = fState.IntOfExt(j);
841 double cij = fState.IntCovariance()(k, l);
842 double tmp = std::sqrt(std::abs(fState.IntCovariance()(k, k) * fState.IntCovariance()(l, l)));
843 if (tmp > 0)
844 return cij / tmp;
845 return 0;
846}
847
848std::vector<double> Minuit2Minimizer::GlobalCC() const
849{
850 // get global correlation coefficient for the parameter i. This is a number between zero and one which gives
851 // the correlation between the i-th parameter and that linear combination of all other parameters which
852 // is most strongly correlated with i.
853
854 std::vector<double> out;
856 // no info available when minimization has failed or has some problems
857 if (!globalCC.IsValid())
858 return out;
859 out.resize(fDim);
860 for (unsigned int i = 0; i < fDim; ++i) {
861 if (fState.Parameter(i).IsFixed() || fState.Parameter(i).IsConst())
862 out[i] = 0;
863 else {
864 unsigned int k = fState.IntOfExt(i);
865 out[i] = globalCC.GlobalCC()[k];
866 }
867 }
868 return out;
869}
870
871bool Minuit2Minimizer::GetMinosError(unsigned int i, double &errLow, double &errUp, int runopt)
872{
873 // return the minos error for parameter i
874 // if a minimum does not exist an error is returned
875 // runopt is a flag which specifies if only lower or upper error needs to be run
876 // if runopt = 0 both, = 1 only lower, + 2 only upper errors
877 errLow = 0;
878 errUp = 0;
879
881
882 // need to know if parameter is const or fixed
883 if (fState.Parameter(i).IsConst() || fState.Parameter(i).IsFixed()) {
884 return false;
885 }
886
887 MnPrint print("Minuit2Minimizer::GetMinosError", PrintLevel());
888
889 // to run minos I need function minimum class
890 // redo minimization from current state
891 // ROOT::Minuit2::FunctionMinimum min =
892 // GetMinimizer()->Minimize(*GetFCN(),fState, ROOT::Minuit2::MnStrategy(strategy), MaxFunctionCalls(),
893 // Tolerance());
894 // fState = min.UserState();
895 if (fMinimum == nullptr) {
896 print.Error("Failed - no function minimum existing");
897 return false;
898 }
899
900 if (!fMinimum->IsValid()) {
901 print.Error("Failed - invalid function minimum");
902 return false;
903 }
904
905 fMinuitFCN->SetErrorDef(ErrorDef());
906 // if error def has been changed update it in FunctionMinimum
907 if (ErrorDef() != fMinimum->Up())
908 fMinimum->SetErrorDef(ErrorDef());
909
911
912 // run again the Minimization in case of a new minimum
913 // bit 8 is set
914 if ((mstatus & 8) != 0) {
915 print.Info([&](std::ostream &os) {
916 os << "Found a new minimum: run again the Minimization starting from the new point";
917 os << "\nFVAL = " << fState.Fval();
918 for (auto &par : fState.MinuitParameters()) {
919 os << '\n' << par.Name() << "\t = " << par.Value();
920 }
921 });
922 // release parameter that was fixed in the returned state from Minos
924 bool ok = Minimize();
925 if (!ok)
926 return false;
927 // run again Minos from new Minimum (also lower error needs to be re-computed)
928 print.Info("Run now again Minos from the new found Minimum");
930
931 // do not reset new minimum bit to flag for other parameters
932 mstatus |= 8;
933 }
934
935 fStatus += 10 * mstatus;
937
938 bool isValid = ((mstatus & 1) == 0) && ((mstatus & 2) == 0);
939 return isValid;
940}
941
942int Minuit2Minimizer::RunMinosError(unsigned int i, double &errLow, double &errUp, int runopt)
943{
944
945 bool runLower = runopt != 2;
946 bool runUpper = runopt != 1;
947
948 const int debugLevel = PrintLevel();
949 // switch off Minuit2 printing
950 const int prev_level = (debugLevel <= 0) ? TurnOffPrintInfoLevel() : -2;
952
953 // set the precision if needed
954 if (Precision() > 0)
956
958
959 // run MnCross
960 MnCross low;
961 MnCross up;
962 int maxfcn = MaxFunctionCalls();
963 double tol = Tolerance();
964
965 const char *par_name = fState.Name(i);
966
967 // now input tolerance for migrad calls inside Minos (MnFunctionCross)
968 // before it was fixed to 0.05
969 // cut off too small tolerance (they are not needed)
970 tol = std::max(tol, 0.01);
971
972 // get the real number of maxfcn used (defined in MnMinos) to be printed
973 int maxfcn_used = maxfcn;
974 if (maxfcn_used == 0) {
975 int nvar = fState.VariableParameters();
976 maxfcn_used = 2 * (nvar + 1) * (200 + 100 * nvar + 5 * nvar * nvar);
977 }
978
979 if (runLower) {
980 if (debugLevel >= 1) {
981 std::cout << "************************************************************************************************"
982 "******\n";
983 std::cout << "Minuit2Minimizer::GetMinosError - Run MINOS LOWER error for parameter #" << i << " : "
984 << par_name << " using max-calls " << maxfcn_used << ", tolerance " << tol << std::endl;
985 }
986 low = minos.Loval(i, maxfcn, tol);
987 }
988 if (runUpper) {
989 if (debugLevel >= 1) {
990 std::cout << "************************************************************************************************"
991 "******\n";
992 std::cout << "Minuit2Minimizer::GetMinosError - Run MINOS UPPER error for parameter #" << i << " : "
993 << par_name << " using max-calls " << maxfcn_used << ", tolerance " << tol << std::endl;
994 }
995 up = minos.Upval(i, maxfcn, tol);
996 }
997
998 ROOT::Minuit2::MinosError me(i, fMinimum->UserState().Value(i), low, up);
999
1000 // restore global print level
1001 if (prev_level > -2)
1004
1005 // debug result of Minos
1006 // print error message in Minos
1007 // Note that the only invalid condition can happen when the (npar-1) minimization fails
1008 // The error is also invalid when the maximum number of calls is reached or a new function minimum is found
1009 // in case of the parameter at the limit the error is not invalid.
1010 // When the error is invalid the returned error is the Hessian error.
1011
1012 if (debugLevel > 0) {
1013 if (runLower) {
1014 if (!me.LowerValid())
1015 std::cout << "Minos: Invalid lower error for parameter " << par_name << std::endl;
1016 if (me.AtLowerLimit())
1017 std::cout << "Minos: Parameter : " << par_name << " is at Lower limit; error is " << me.Lower()
1018 << std::endl;
1019 if (me.AtLowerMaxFcn())
1020 std::cout << "Minos: Maximum number of function calls exceeded when running for lower error for parameter "
1021 << par_name << std::endl;
1022 if (me.LowerNewMin())
1023 std::cout << "Minos: New Minimum found while running Minos for lower error for parameter " << par_name
1024 << std::endl;
1025
1026 if (debugLevel >= 1 && me.LowerValid())
1027 std::cout << "Minos: Lower error for parameter " << par_name << " : " << me.Lower() << std::endl;
1028 }
1029 if (runUpper) {
1030 if (!me.UpperValid())
1031 std::cout << "Minos: Invalid upper error for parameter " << par_name << std::endl;
1032 if (me.AtUpperLimit())
1033 std::cout << "Minos: Parameter " << par_name << " is at Upper limit; error is " << me.Upper() << std::endl;
1034 if (me.AtUpperMaxFcn())
1035 std::cout << "Minos: Maximum number of function calls exceeded when running for upper error for parameter "
1036 << par_name << std::endl;
1037 if (me.UpperNewMin())
1038 std::cout << "Minos: New Minimum found while running Minos for upper error for parameter " << par_name
1039 << std::endl;
1040
1041 if (debugLevel >= 1 && me.UpperValid())
1042 std::cout << "Minos: Upper error for parameter " << par_name << " : " << me.Upper() << std::endl;
1043 }
1044 }
1045
1046 MnPrint print("RunMinosError", PrintLevel());
1047 bool lowerInvalid = (runLower && !me.LowerValid());
1048 bool upperInvalid = (runUpper && !me.UpperValid());
1049 // print message in case of invalid error also in printLevel0
1050 if (lowerInvalid) {
1051 print.Warn("Invalid lower error for parameter", fMinimum->UserState().Name(i));
1052 }
1053 if (upperInvalid) {
1054 print.Warn("Invalid upper error for parameter", fMinimum->UserState().Name(i));
1055 }
1056 // print also case it is lower/upper limit
1057 if (me.AtLowerLimit()) {
1058 print.Warn("Lower error for parameter", fMinimum->UserState().Name(i), "is at the Lower limit!");
1059 }
1060 if (me.AtUpperLimit()) {
1061 print.Warn("Upper error for parameter", fMinimum->UserState().Name(i), "is at the Upper limit!");
1062 }
1063
1064 int mstatus = 0;
1065 if (lowerInvalid || upperInvalid) {
1066 // set status according to bit
1067 // bit 1: lower invalid Minos errors
1068 // bit 2: upper invalid Minos error
1069 // bit 3: invalid because max FCN
1070 // bit 4 : invalid because a new minimum has been found
1071 if (lowerInvalid) {
1072 mstatus |= 1;
1073 if (me.AtLowerMaxFcn())
1074 mstatus |= 4;
1075 if (me.LowerNewMin())
1076 mstatus |= 8;
1077 }
1078 if (upperInvalid) {
1079 mstatus |= 2;
1080 if (me.AtUpperMaxFcn())
1081 mstatus |= 4;
1082 if (me.UpperNewMin())
1083 mstatus |= 8;
1084 }
1085 }
1086 // case upper/lower limit
1087 if (me.AtUpperLimit() || me.AtLowerLimit())
1088 mstatus |= 16;
1089
1090 if (runLower)
1091 errLow = me.Lower();
1092 if (runUpper)
1093 errUp = me.Upper();
1094
1095 // in case of new minimum found update also the minimum state
1096 if ((runLower && me.LowerNewMin()) && (runUpper && me.UpperNewMin())) {
1097 // take state with lower function value
1098 fState = (low.State().Fval() < up.State().Fval()) ? low.State() : up.State();
1099 } else if (runLower && me.LowerNewMin()) {
1100 fState = low.State();
1101 } else if (runUpper && me.UpperNewMin()) {
1102 fState = up.State();
1103 }
1104
1105 return mstatus;
1106}
1107
1108bool Minuit2Minimizer::Scan(unsigned int ipar, unsigned int &nstep, double *x, double *y, double xmin, double xmax)
1109{
1110 // scan a parameter (variable) around the minimum value
1111 // the parameters must have been set before
1112 // if xmin=0 && xmax == 0 by default scan around 2 sigma of the error
1113 // if the errors are also zero then scan from min and max of parameter range
1114
1115 MnPrint print("Minuit2Minimizer::Scan", PrintLevel());
1116 if (!fMinuitFCN) {
1117 print.Error("Function must be set before using Scan");
1118 return false;
1119 }
1120
1121 if (ipar > fState.MinuitParameters().size()) {
1122 print.Error("Invalid number; minimizer variables must be set before using Scan");
1123 return false;
1124 }
1125
1126 // switch off Minuit2 printing
1127 const int prev_level = (PrintLevel() <= 0) ? TurnOffPrintInfoLevel() : -2;
1129
1130 // set the precision if needed
1131 if (Precision() > 0)
1133
1135 double amin = scan.Fval(); // fcn value of the function before scan
1136
1137 // first value is param value
1138 std::vector<std::pair<double, double>> result = scan(ipar, nstep - 1, xmin, xmax);
1139
1140 // restore global print level
1141 if (prev_level > -2)
1144
1145 if (result.size() != nstep) {
1146 print.Error("Invalid result from MnParameterScan");
1147 return false;
1148 }
1149 // sort also the returned points in x
1150 std::sort(result.begin(), result.end());
1151
1152 for (unsigned int i = 0; i < nstep; ++i) {
1153 x[i] = result[i].first;
1154 y[i] = result[i].second;
1155 }
1156
1157 // what to do if a new minimum has been found ?
1158 // use that as new minimum
1159 if (scan.Fval() < amin) {
1160 print.Info("A new minimum has been found");
1161 fState.SetValue(ipar, scan.Parameters().Value(ipar));
1162 }
1163
1164 return true;
1165}
1166
1167bool Minuit2Minimizer::Contour(unsigned int ipar, unsigned int jpar, unsigned int &npoints, double *x, double *y)
1168{
1169 // contour plot for parameter i and j
1170 // need a valid FunctionMinimum otherwise exits
1171
1172 MnPrint print("Minuit2Minimizer::Contour", PrintLevel());
1173
1174 if (fMinimum == nullptr) {
1175 print.Error("No function minimum existing; must minimize function before");
1176 return false;
1177 }
1178
1179 if (!fMinimum->IsValid()) {
1180 print.Error("Invalid function minimum");
1181 return false;
1182 }
1184
1185 fMinuitFCN->SetErrorDef(ErrorDef());
1186 // if error def has been changed update it in FunctionMinimum
1187 if (ErrorDef() != fMinimum->Up()) {
1188 fMinimum->SetErrorDef(ErrorDef());
1189 }
1190
1191 print.Info("Computing contours at level -", ErrorDef());
1192
1193 // switch off Minuit2 printing (for level of 0,1)
1194 const int prev_level = (PrintLevel() <= 1) ? TurnOffPrintInfoLevel() : -2;
1196
1197 // set the precision if needed
1198 if (Precision() > 0)
1200
1201 // eventually one should specify tolerance in contours
1202 MnContours contour(*fMinuitFCN, *fMinimum, Strategy());
1203
1204 // restore global print level
1205 if (prev_level > -2)
1208
1209 // compute the contour
1210 std::vector<std::pair<double, double>> result = contour(ipar, jpar, npoints);
1211 if (result.size() != npoints) {
1212 print.Error("Invalid result from MnContours");
1213 return false;
1214 }
1215 for (unsigned int i = 0; i < npoints; ++i) {
1216 x[i] = result[i].first;
1217 y[i] = result[i].second;
1218 }
1219 print.Info([&](std::ostream &os) {
1220 os << " Computed " << npoints << " points at level " << ErrorDef();
1221 for (unsigned int i = 0; i < npoints; i++) {
1222 if (i %5 == 0) os << std::endl;
1223 os << "( " << x[i] << ", " << y[i] << ") ";
1224 }
1225 os << std::endl << std::endl;
1226 });
1227
1228 return true;
1229}
1230
1232{
1233 // find Hessian (full second derivative calculations)
1234 // the contained state will be updated with the Hessian result
1235 // in case a function minimum exists and is valid the result will be
1236 // appended in the function minimum
1237
1238 MnPrint print("Minuit2Minimizer::Hesse", PrintLevel());
1239
1240 if (!fMinuitFCN) {
1241 print.Error("FCN function has not been set");
1242 return false;
1243 }
1244
1245 const int maxfcn = MaxFunctionCalls();
1246 print.Info("Using max-calls", maxfcn);
1247
1248 // switch off Minuit2 printing
1249 const int prev_level = (PrintLevel() <= 0) ? TurnOffPrintInfoLevel() : -2;
1251
1252 // set the precision if needed
1253 if (Precision() > 0)
1255
1257
1258 // case when function minimum exists
1259 if (fMinimum) {
1260
1261 // if (PrintLevel() >= 3) {
1262 // std::cout << "Minuit2Minimizer::Hesse - State before running Hesse " << std::endl;
1263 // std::cout << fState << std::endl;
1264 // }
1265
1266 // run hesse and function minimum will be updated with Hesse result
1267 hesse(*fMinuitFCN, *fMinimum, maxfcn);
1268 // update user state
1269 fState = fMinimum->UserState();
1270 }
1271
1272 else {
1273 // run Hesse on point stored in current state (independent of function minimum validity)
1274 // (x == 0)
1275 fState = hesse(*fMinuitFCN, fState, maxfcn);
1276 }
1277
1278 // restore global print level
1279 if (prev_level > -2)
1282
1283 if (PrintLevel() >= 3) {
1284 std::cout << "Minuit2Minimizer::Hesse - State returned from Hesse " << std::endl;
1285 std::cout << fState << std::endl;
1286 }
1287
1289 std::string covStatusType = "not valid";
1290 if (covStatus == 1)
1291 covStatusType = "approximate";
1292 if (covStatus == 2)
1293 covStatusType = "full but made positive defined";
1294 if (covStatus == 3)
1295 covStatusType = "accurate";
1296 if (covStatus == 0)
1297 covStatusType = "full but not positive defined";
1298
1299 if (!fState.HasCovariance()) {
1300 // if false means error is not valid and this is due to a failure in Hesse
1301 // update minimizer error status
1302 int hstatus = 4;
1303 // information on error state can be retrieved only if fMinimum is available
1304 if (fMinimum) {
1305 if (fMinimum->Error().HesseFailed())
1306 hstatus = 1;
1307 if (fMinimum->Error().InvertFailed())
1308 hstatus = 2;
1309 else if (!(fMinimum->Error().IsPosDef()))
1310 hstatus = 3;
1311 }
1312
1313 print.Warn("Hesse failed - matrix is", covStatusType);
1314 print.Warn(hstatus);
1315
1316 fStatus += 100 * hstatus;
1317 return false;
1318 }
1319
1320 print.Info("Hesse is valid - matrix is", covStatusType);
1321
1322 return true;
1323}
1324
1326{
1327 // return status of covariance matrix
1328 //-1 - not available (inversion failed or Hesse failed)
1329 // 0 - available but not positive defined
1330 // 1 - covariance only approximate
1331 // 2 full matrix but forced pos def
1332 // 3 full accurate matrix
1333
1334 if (fMinimum) {
1335 // case a function minimum is available
1336 if (fMinimum->HasAccurateCovar())
1337 return 3;
1338 else if (fMinimum->HasMadePosDefCovar())
1339 return 2;
1340 else if (fMinimum->HasValidCovariance())
1341 return 1;
1342 else if (fMinimum->HasCovariance())
1343 return 0;
1344 return -1;
1345 } else {
1346 // case fMinimum is not available - use state information
1347 return fState.CovarianceStatus();
1348 }
1349 return 0;
1350}
1351
1353{
1354 // set trace object
1355 if (fMinimizer)
1356 fMinimizer->Builder().SetTraceObject(obj);
1357}
1358
1360{
1361 // set storage level
1362 if (fMinimizer)
1363 fMinimizer->Builder().SetStorageLevel(level);
1364}
1365
1366void Minuit2Minimizer::SetFCN(unsigned int nDim, std::unique_ptr<ROOT::Minuit2::FCNBase> fcn)
1367{
1368 fDim = nDim;
1369 fMinuitFCN = std::move(fcn);
1370}
1371
1372} // end namespace Minuit2
1373
1374} // end namespace ROOT
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
Int_t gErrorIgnoreLevel
errors with level below this value will be ignored. Default is kUnset.
Definition TError.cxx:33
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 result
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
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:131
float xmin
float xmax
#define gROOT
Definition TROOT.h:417
Class, describing value, limits and step size of the parameters Provides functionality also to set/re...
FitMethodFunction class Interface for objective functions (like chi2 and likelihood used in the fit) ...
Documentation for the abstract class IBaseFunctionMultiDim.
Definition IFunction.h:63
virtual unsigned int NDim() const =0
Retrieve the dimension of the function.
Interface (abstract class) for multi-dimensional functions providing a gradient calculation.
Definition IFunction.h:239
Generic interface for defining configuration options of a numerical algorithm.
Definition IOptions.h:28
const IOptions * ExtraOptions() const
return extra options (NULL pointer if they are not present)
static ROOT::Math::IOptions * FindDefault(const char *name)
Find an extra options and return a nullptr if it is not existing.
double Tolerance() const
Absolute tolerance.
Definition Minimizer.h:317
unsigned int MaxFunctionCalls() const
Max number of function calls.
Definition Minimizer.h:311
double Precision() const
Precision of minimizer in the evaluation of the objective function.
Definition Minimizer.h:321
int fStatus
status of minimizer
Definition Minimizer.h:388
int Strategy() const
Strategy.
Definition Minimizer.h:324
double ErrorDef() const
Definition Minimizer.h:334
MinimizerOptions fOptions
minimizer options
Definition Minimizer.h:387
bool IsValidError() const
Definition Minimizer.h:337
int PrintLevel() const
Set print level.
Definition Minimizer.h:308
Adapter class to wrap user-provided functions into the FCNBase interface.
Definition FCNAdapter.h:37
Instantiates the seed generator and Minimum builder for the Fumili minimization method.
class holding the full result of the minimization; both internal and external (MnUserParameterState) ...
MinimumState keeps the information (position, Gradient, 2nd deriv, etc) after one minimization step (...
Class holding the result of Minos (lower and upper values) for a specific parameter.
Definition MinosError.h:25
bool AtUpperLimit() const
Definition MinosError.h:87
bool AtLowerMaxFcn() const
Definition MinosError.h:88
bool AtUpperMaxFcn() const
Definition MinosError.h:89
bool AtLowerLimit() const
Definition MinosError.h:86
bool ExamineMinimum(const ROOT::Minuit2::FunctionMinimum &min)
examine the minimum result
Minuit2Minimizer(ROOT::Minuit2::EMinimizerType type=ROOT::Minuit2::kMigrad)
Default constructor.
void SetStorageLevel(int level)
set storage level = 1 : store all iteration states (default) = 0 : store only first and last state to...
bool SetCovariance(std::span< const double > cov, unsigned int nrow) override
set initial covariance matrix
bool SetLimitedVariable(unsigned int ivar, const std::string &name, double val, double step, double, double) override
set upper/lower limited variable (override if minimizer supports them )
bool Contour(unsigned int i, unsigned int j, unsigned int &npoints, double *xi, double *xj) override
find the contour points (xi,xj) of the function for parameter i and j around the minimum The contour ...
virtual bool SetCovarianceDiag(std::span< const double > d2, unsigned int n) override
set initial second derivatives
bool IsFixedVariable(unsigned int ivar) const override
query if an existing variable is fixed (i.e.
bool SetVariableUpperLimit(unsigned int ivar, double upper) override
set the upper-limit of an already existing variable
bool SetVariableValues(const double *val) override
Set the values of all existing variables (array must be dimensioned to the size of the existing param...
bool SetVariable(unsigned int ivar, const std::string &name, double val, double step) override
set free variable
const double * Errors() const override
return errors at the minimum
void SetFunction(const ROOT::Math::IMultiGenFunction &func) override
set the function to minimize
bool SetVariableStepSize(unsigned int ivar, double step) override
set the step size of an already existing variable
bool GetCovMatrix(double *cov) const override
Fill the passed array with the covariance matrix elements if the variable is fixed or const the value...
bool ReleaseVariable(unsigned int ivar) override
release an existing variable
bool GetVariableSettings(unsigned int ivar, ROOT::Fit::ParameterSettings &varObj) const override
get variable settings in a variable object (like ROOT::Fit::ParamsSettings)
bool Hesse() override
perform a full calculation of the Hessian matrix for error calculation If a valid minimum exists the ...
bool GetMinosError(unsigned int i, double &errLow, double &errUp, int=0) override
get the minos error for parameter i, return false if Minos failed A minimizaiton must be performed be...
std::string VariableName(unsigned int ivar) const override
get name of variables (override if minimizer support storing of variable names)
int RunMinosError(unsigned int i, double &errLow, double &errUp, int runopt)
bool SetVariableLimits(unsigned int ivar, double lower, double upper) override
set the limits of an already existing variable
double Correlation(unsigned int i, unsigned int j) const override
return correlation coefficient between variable i and j.
bool SetLowerLimitedVariable(unsigned int ivar, const std::string &name, double val, double step, double lower) override
set lower limit variable (override if minimizer supports them )
void SetTraceObject(MnTraceObject &obj)
set an object to trace operation for each iteration The object must be a (or inherit from) ROOT::Minu...
virtual const ROOT::Minuit2::ModularFunctionMinimizer * GetMinimizer() const
double CovMatrix(unsigned int i, unsigned int j) const override
return covariance matrix elements if the variable is fixed or const the value is zero The ordering of...
void SetMinimizerType(ROOT::Minuit2::EMinimizerType type)
std::unique_ptr< ROOT::Minuit2::ModularFunctionMinimizer > fMinimizer
bool SetVariableValue(unsigned int ivar, double val) override
set variable
bool Scan(unsigned int i, unsigned int &nstep, double *x, double *y, double xmin=0, double xmax=0) override
scan a parameter i around the minimum.
int VariableIndex(const std::string &name) const override
get index of variable given a variable given a name return -1 if variable is not found
bool SetUpperLimitedVariable(unsigned int ivar, const std::string &name, double val, double step, double upper) override
set upper limit variable (override if minimizer supports them )
ROOT::Minuit2::MnUserParameterState fState
bool SetVariableLowerLimit(unsigned int ivar, double lower) override
set the lower-limit of an already existing variable
bool FixVariable(unsigned int ivar) override
fix an existing variable
void SetHessianFunction(std::function< bool(std::span< const double >, double *)> hfunc) override
set the function implementing Hessian computation
bool Minimize() override
method to perform the minimization.
bool SetFixedVariable(unsigned int, const std::string &, double) override
set fixed variable (override if minimizer supports them )
bool GetHessianMatrix(double *h) const override
Fill the passed array with the Hessian matrix elements The Hessian matrix is the matrix of the second...
void PrintResults() override
return reference to the objective function virtual const ROOT::Math::IGenFunction & Function() const;
void Clear() override
Reset for consecutive minimization - implement if needed.
~Minuit2Minimizer() override
Destructor (no operations)
std::vector< double > GlobalCC() const override
get global correlation coefficient for the variable i.
void SetFCN(unsigned int nDim, std::unique_ptr< ROOT::Minuit2::FCNBase > fcn)
To set the function directly to a Minuit 2 function.
int CovMatrixStatus() const override
return the status of the covariance matrix status = -1 : not available (inversion failed or Hesse fai...
std::unique_ptr< ROOT::Minuit2::FCNBase > fMinuitFCN
std::unique_ptr< ROOT::Minuit2::FunctionMinimum > fMinimum
class for the individual Minuit Parameter with Name and number; contains the input numbers for the mi...
API class for Contours Error analysis (2-dim errors); minimization has to be done before and Minimum ...
Definition MnContours.h:35
const MnUserParameterState & State() const
Definition MnCross.h:84
class for global correlation coefficient
API class for calculating the numerical covariance matrix (== 2x Inverse Hessian == 2x Inverse 2nd de...
Definition MnHesse.h:41
API class for Minos Error analysis (asymmetric errors); minimization has to be done before and Minimu...
Definition MnMinos.h:33
MnCross Loval(unsigned int, unsigned int maxcalls=0, double toler=0.1) const
Definition MnMinos.cxx:206
MnCross Upval(unsigned int, unsigned int maxcalls=0, double toler=0.1) const
Definition MnMinos.cxx:200
Scans the values of FCN as a function of one Parameter and retains the best function and Parameter va...
const MnUserParameters & Parameters() const
void Debug(const Ts &... args)
Definition MnPrint.h:135
void Error(const Ts &... args)
Definition MnPrint.h:117
void Info(const Ts &... args)
Definition MnPrint.h:129
static int SetGlobalLevel(int level)
Definition MnPrint.cxx:111
void Warn(const Ts &... args)
Definition MnPrint.h:123
API class for defining four levels of strategies: low (0), medium (1), high (2), very high (>=3); act...
Definition MnStrategy.h:255
class which holds the external user and/or internal Minuit representation of the parameters and error...
void SetLimits(unsigned int, double, double)
const MnUserParameters & Parameters() const
unsigned int Index(const std::string &) const
const std::string & GetName(unsigned int) const
double Int2ext(unsigned int, double) const
MnGlobalCorrelationCoeff GlobalCC() const
const MinuitParameter & Parameter(unsigned int i) const
void Add(const std::string &name, double val, double err)
const char * Name(unsigned int) const
void AddCovariance(const MnUserCovariance &)
const std::vector< ROOT::Minuit2::MinuitParameter > & MinuitParameters() const
facade: forward interface of MnUserParameters and MnUserTransformation
unsigned int IntOfExt(unsigned int) const
const MnUserTransformation & Trafo() const
const MnUserCovariance & IntCovariance() const
const MnUserCovariance & Covariance() const
const_iterator begin() const
const_iterator end() const
Mother of all ROOT objects.
Definition TObject.h:42
virtual TObject * FindObject(const char *name) const
Must be redefined in derived classes.
Definition TObject.cxx:424
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
void RestoreGlobalPrintLevel(int)
TMarker m
Definition textangle.C:8
TLine l
Definition textangle.C:4