56#ifdef ROOFIT_MULTIPROCESS
90 if (nll_real !=
nullptr) {
93#ifdef ROOFIT_MULTIPROCESS
97 coutI(InputArguments) <<
"Modular likelihood detected and likelihood parallelization requested, "
98 <<
"also setting parallel gradient calculation mode." << std::endl;
107 _fcn = std::make_unique<RooFit::TestStatistics::MinuitFcnGrad>(
110 static_cast<RooFit::TestStatistics::LikelihoodMode>(int(_cfg.enableParallelDescent))},
113 throw std::logic_error(
114 "Parallel minimization requested, but ROOT was not compiled with multiprocessing enabled, "
115 "please recompile with -Droofit_multiprocess=ON for parallel evaluation");
118 coutW(InputArguments)
119 <<
"Requested modular likelihood without gradient parallelization, some features such as offsetting "
120 <<
"may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl;
126 _fcn = std::make_unique<RooMinimizerFcn>(&function,
this);
130 throw std::logic_error(
"In RooMinimizer constructor: Selected likelihood evaluation but a "
131 "non-modular likelihood was given. Please supply ModularL(true) as an "
132 "argument to createNLL for modular likelihoods to use likelihood "
133 "or gradient parallelization.");
135 _fcn = std::make_unique<RooMinimizerFcn>(&function,
this);
143 RooSentinel::activate();
251 std::stringstream ss;
252 ss <<
"In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!";
254 ss <<
"\nPlease set it as your default minimizer via "
255 "ROOT::Math::MinimizerOptions::SetDefaultMinimizer(\"Minuit2\").";
257 throw std::invalid_argument(ss.str());
268 coutE(Minimization) <<
"RooMinimizer: all function calls during minimization gave invalid NLL values!"
284#ifdef ROOFIT_MULTIPROCESS
287 throw std::logic_error(
"ProcessTimer, but ROOT was not compiled with multiprocessing enabled, "
288 "please recompile with -Droofit_multiprocess=ON for logging with the "
320 return exec(
"migrad",
"MIGRAD");
331 if (algoName ==
"hesse") {
335 }
else if (algoName ==
"minos") {
362 coutW(Minimization) <<
"RooMinimizer::hesse: Error, run Migrad before Hesse!" << std::endl;
367 return exec(
"hesse",
"HESSE");
379 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
384 return exec(
"minos",
"MINOS");
396 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
398 }
else if (!minosParamList.
empty()) {
406 std::vector<unsigned int> paramInd;
408 RooAbsArg *par =
_fcn->GetFloatParamList()->find(arg->GetName());
410 int index =
_fcn->GetFloatParamList()->index(par);
411 paramInd.push_back(
index);
415 if (!paramInd.empty()) {
443 return exec(
"seek",
"SEEK");
454 return exec(
"simplex",
"SIMPLEX");
465 return exec(
"migradimproved",
"IMPROVE");
490 _fcn->setOptimizeConst(flag);
504 coutW(Minimization) <<
"RooMinimizer::save: Error, run minimization before!" << std::endl;
509 TString title = userTitle ? userTitle :
Form(
"%s",
_fcn->getFunctionTitle().c_str());
510 auto fitRes = std::make_unique<RooFitResult>(
name, title);
516 for (std::size_t i = 0; i <
_fcn->GetFloatParamList()->
size(); i++) {
520 saveFloatFinalList.
remove(*par);
521 saveConstList.
add(*par);
524 saveConstList.
sort();
526 fitRes->setConstParList(saveConstList);
527 fitRes->setInitParList(saveFloatInitList);
529 double removeOffset = 0.;
530 fitRes->setNumInvalidNLL(
_fcn->GetNumInvalidNLL());
531 removeOffset = -
_fcn->getOffset();
534 fitRes->setCovQual(
_minimizer->CovMatrixStatus());
535 fitRes->setMinNLL(
_result->fVal + removeOffset);
537 fitRes->setFinalParList(saveFloatFinalList);
541 fitRes->setCovarianceMatrix(*
_extV);
552double covMatrix(std::vector<double>
const &covMat,
unsigned int i,
unsigned int j)
556 return j < i ? covMat[j + i * (i + 1) / 2] : covMat[i + j * (j + 1) / 2];
560double correlation(std::vector<double>
const &covMat,
unsigned int i,
unsigned int j)
564 double tmp = covMatrix(covMat, i, i) * covMatrix(covMat, j, j);
565 return tmp > 0 ? covMatrix(covMat, i, j) / std::sqrt(tmp) : 0;
572 const std::size_t nParams =
_fcn->getNDim();
573 std::vector<double> globalCC;
576 for (std::size_t ic = 0; ic < nParams; ic++) {
577 globalCC.push_back(
_result->fGlobalCC[ic]);
578 for (std::size_t ii = 0; ii < nParams; ii++) {
579 corrs(ic, ii) = correlation(
_result->fCovMatrix, ic, ii);
580 covs(ic, ii) = covMatrix(
_result->fCovMatrix, ic, ii);
603 double n5,
double n6,
unsigned int npoints)
610 int index1 =
_fcn->GetFloatParamList()->
index(&var1);
612 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var1.
GetName()
613 <<
" is not a floating parameter of " <<
_fcn->getFunctionName() << std::endl;
617 int index2 =
_fcn->GetFloatParamList()->index(&var2);
619 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var2.
GetName()
620 <<
" is not a floating parameter of PDF " <<
_fcn->getFunctionName() << std::endl;
634 coutW(Minimization) <<
"RooMinimizer::contour: Error, run Migrad before contours!" << std::endl;
649 for (
int ic = 0; ic < 6; ic++) {
656 std::vector<double> xcoor(npoints + 1);
657 std::vector<double> ycoor(npoints + 1);
658 bool ret =
_minimizer->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
661 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName()
662 <<
") ERROR: MINUIT did not return a contour graph for n=" <<
n[ic] << std::endl;
664 xcoor[npoints] = xcoor[0];
665 ycoor[npoints] = ycoor[0];
668 graph->SetName(
Form(
"contour_%s_n%f",
_fcn->getFunctionName().c_str(),
n[ic]));
669 graph->SetLineStyle(ic + 1);
670 graph->SetLineWidth(2);
681 params->
assign(paramSave);
691#ifdef ROOFIT_MULTIPROCESS
693 std::vector<std::string> parameter_names;
694 for (
auto &¶meter : *
_fcn->GetFloatParamList()) {
695 parameter_names.push_back(parameter->GetName());
697 coutI(Minimization) <<
"parameter name: " << parameter_names.back() << std::endl;
702 coutI(Minimization) <<
"Not adding parameters to processtimer because multiprocessing is not enabled." << std::endl;
726 coutI(Minimization) <<
"Command timer: ";
728 coutI(Minimization) <<
"Session timer: ";
735 return _fcn->getMultiGenFcn();
755 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::save: Error, run minimization before!" << std::endl;
759 auto res = std::make_unique<RooFitResult>(
"lastMinuitFit",
"Last MINUIT fit");
766 for (
unsigned int i = 0; i <
_fcn->getNDim(); ++i) {
768 TString varName(
_fcn->GetFloatParamList()->at(i)->GetName());
769 bool isConst(
_result->isParameterFixed(i));
773 double xerr =
_result->error(i);
774 double xval =
_result->fParams[i];
776 std::unique_ptr<RooRealVar> var;
778 if ((xlo < xhi) && !isConst) {
779 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
781 var = std::make_unique<RooRealVar>(varName, varName, xval);
783 var->setConstant(isConst);
793 res->setConstParList(constPars);
794 res->setInitParList(floatPars);
795 res->setFinalParList(floatPars);
798 res->setCovQual(
_minimizer->CovMatrixStatus());
799 res->setStatus(
_result->fStatus);
824 return _fcn->evalCounter();
828 _fcn->zeroEvalCount();
833 return _fcn->getNDim();
838 return _fcn->GetLogFile();
842 return _fcn->GetMaxFCN();
846 return _fcn->getOffset();
856 return std::make_unique<RooAbsReal::EvalErrorContext>(
m);
863 unsigned int npar = fcn.
NDim();
865 coutE(Minimization) <<
"RooMinimizer::fitFCN(): FCN function has zero parameters" << std::endl;
878 _result = std::make_unique<FitResult>();
896 coutE(Minimization) <<
"RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
903 coutE(Minimization) <<
"RooMinimizer::calculateHessErrors() Error when calculating Hessian" << std::endl;
930 coutE(Minimization) <<
"RooMinimizer::calculateHessErrors() Error re-initializing the minimizer" << std::endl;
935 unsigned int n = (!ipars.empty()) ? ipars.size() :
_fcn->getNDim();
944 coutI(Minimization) <<
"RooMinimizer::calculateMinosErrors() Run again Minos for some parameters because a "
945 "new Minimum has been found"
948 for (
int i = 0; i < iparMax; ++i) {
950 unsigned int index = (!ipars.empty()) ? ipars[i] : i;
957 _result->fMinosErrors.emplace(
index, std::make_pair(elow, eup));
961 iparMax = iparNewMin;
963 }
while (iparNewMin > 0 && iter < 10);
966 <<
"RooMinimizer::calculateMinosErrors() Minos error calculation failed for all the selected parameters"
993 if (canDifferentMinim) {
994 std::string msg =
"Using now " + newMinimType;
995 coutI(Minimization) <<
"RooMinimizer::updateMinimizerOptions(): " << msg << std::endl;
998 std::string msg =
"Cannot change minimizer. Continue using " +
_result->fMinimType;
999 coutW(Minimization) <<
"RooMinimizer::updateMinimizerOptions() " << msg << std::endl;
1018 for (
unsigned int i = 0; i <
_config.
NPar(); ++i) {
1029 fParams(fconfig.NPar()),
1030 fErrors(fconfig.NPar())
1039 if ((
fMinimType.find(
"Fumili") == std::string::npos) && (
fMinimType.find(
"GSLMultiFit") == std::string::npos)) {
1045 for (
unsigned int i = 0; i < fconfig.
NPar(); ++i) {
1069 const unsigned int npar = min.
NDim();
1074 _result->fParams = std::vector<double>(min.
X(), min.
X() + npar);
1077 _result->fParams.resize(npar);
1078 for (
unsigned int i = 0; i < npar; ++i) {
1084 for (
unsigned int ipar = 0; ipar < npar; ++ipar) {
1086 _result->fFixedParams[ipar] =
true;
1095 if (min.
Errors() !=
nullptr) {
1111 const std::size_t npar =
_result->fParams.size();
1121 std::copy(min.
X(), min.
X() + npar,
_result->fParams.begin());
1123 if (min.
Errors() !=
nullptr) {
1132 const std::size_t npar =
_result->fParams.size();
1134 _result->fErrors.resize(npar);
1137 if (
_result->fCovStatus != 0) {
1140 unsigned int r = npar * (npar + 1) / 2;
1143 for (
unsigned int i = 0; i < npar; ++i) {
1144 for (
unsigned int j = 0; j <= i; ++j)
1151 _result->fGlobalCC.resize(npar);
1152 for (
unsigned int i = 0; i < npar; ++i) {
1158 _result->fGlobalCC[i] = globcc;
1166 auto itr = fMinosErrors.find(i);
1167 return (itr != fMinosErrors.end()) ? itr->second.first : error(i);
1174 auto itr = fMinosErrors.find(i);
1175 return (itr != fMinosErrors.end()) ? itr->second.second : error(i);
1180 return fFixedParams.find(ipar) != fFixedParams.end();
size_t size(const MatrixT &matrix)
retrieve the size of a square matrix
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 * Form(const char *fmt,...)
Formats a string in a circular formatting buffer.
Class describing the configuration of the fit, options and parameter settings using the ROOT::Fit::Pa...
const std::vector< unsigned int > & MinosParams() const
return vector of parameter indices for which the Minos Error will be computed
void SetMinimizer(const char *type, const char *algo=nullptr)
set minimizer type
void SetMinosErrors(bool on=true)
set Minos errors computation to be performed after fitting
const std::string & MinimizerAlgoType() const
return type of minimizer algorithms
unsigned int NPar() const
number of parameters settings
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)
ROOT::Math::Minimizer * CreateMinimizer()
create a new minimizer according to chosen configuration
const std::string & MinimizerType() const
return type of minimizer package
const ParameterSettings & ParSettings(unsigned int i) const
get the parameter settings for the i-th parameter (const method)
ROOT::Math::MinimizerOptions & MinimizerOptions()
access to the minimizer control parameter (non const method)
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
copy constructor and assignment operators (leave them to the compiler)
double StepSize() const
return step size
double UpperLimit() const
return upper limit value
Documentation for the abstract class IBaseFunctionMultiDim.
virtual unsigned int NDim() const =0
Retrieve the dimension of the function.
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,...
virtual const double * Errors() const
return errors at the minimum
virtual const double * X() const =0
return pointer to X values at the minimum
virtual double GlobalCC(unsigned int ivar) const
return global correlation coefficient for variable i This is a number between zero and one which give...
virtual int CovMatrixStatus() const
return status of covariance matrix using Minuit convention {0 not calculated 1 approximated 2 made po...
int Status() const
status code of minimizer
virtual double CovMatrix(unsigned int ivar, unsigned int jvar) const
return covariance matrices element for variables ivar,jvar if the variable is fixed the return value ...
virtual double Edm() const
return expected distance reached from the minimum (re-implement if minimizer provides it
virtual double MinValue() const =0
return minimum function value
virtual unsigned int NDim() const =0
this is <= Function().NDim() which is the total number of variables (free+ constrained ones)
Common abstract base class for objects that represent a value and a "shape" in RooFit.
bool isConstant() const
Check if the "Constant" attribute is set.
virtual bool remove(const RooAbsArg &var, bool silent=false, bool matchByNameOnly=false)
Remove the specified argument from our list.
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.
void sort(bool reverse=false)
Sort collection using std::sort and name comparison.
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...
double getVal(const RooArgSet *normalisationSet=nullptr) const
Evaluate object.
static void clearEvalErrorLog()
Clear the stack of evaluation error messages.
RooArgList is a container object that can hold multiple RooAbsArg objects.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
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)
static void setTimingAnalysis(bool timingAnalysis)
static void add_metadata(json data)
RooAbsReal that wraps RooAbsL likelihoods for use in RooFit outside of the RooMinimizer context.
Wrapper class around ROOT::Math::Minimizer that provides a seamless interface between the minimizer f...
void setRecoverFromNaNStrength(double strength)
Try to recover from invalid function values.
int getPrintLevel()
Get the MINUIT internal printing level.
void optimizeConst(int flag)
If flag is true, perform constant term optimization on function being minimized.
void initMinimizerFirstPart()
Initialize the part of the minimizer that is independent of the function to be minimized.
std::ofstream * logfile()
int simplex()
Execute SIMPLEX.
std::unique_ptr< TMatrixDSym > _extV
void setMinimizerType(std::string const &type)
Choose the minimizer algorithm.
RooFit::OwningPtr< RooFitResult > save(const char *name=nullptr, const char *title=nullptr)
Save and return a RooFitResult snapshot of current minimizer status.
std::vector< std::pair< std::string, int > > _statusHistory
void profileStart()
Start profiling timer.
RooPlot * contour(RooRealVar &var1, RooRealVar &var2, double n1=1.0, double n2=2.0, double n3=0.0, double n4=0.0, double n5=0.0, double n6=0.0, unsigned int npoints=50)
Create and draw a TH2 with the error contours in the parameters var1 and var2.
std::unique_ptr< ROOT::Math::Minimizer > _minimizer
! pointer to used minimizer
bool setLogFile(const char *logf=nullptr)
void initMinimizerFcnDependentPart(double defaultErrorLevel)
Initialize the part of the minimizer that is dependent on the function to be minimized.
void fillCorrMatrix(RooFitResult &fitRes)
double & fcnOffset() const
ROOT::Fit::FitConfig _config
fitter configuration (options and parameter settings)
void profileStop()
Stop profiling timer and report results of last session.
int minos()
Execute MINOS.
bool calculateHessErrors()
int hesse()
Execute HESSE.
bool calculateMinosErrors()
void setErrorLevel(double level)
Set the level for MINUIT error analysis to the given value.
void determineStatus(bool fitterReturnValue)
int migrad()
Execute MIGRAD.
bool update(bool isValid)
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.
RooMinimizer::Config _cfg
bool fitFCN(const ROOT::Math::IMultiGenFunction &fcn)
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.
ROOT::Math::IMultiGenFunction * getMultiGenFcn() const
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.
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.
void addObject(TObject *obj, Option_t *drawOptions="", bool invisible=false)
Add a generic object to this plot.
Variable that can be changed from the outside.
A TGraph is an object made of two arrays X and Y with npoints each.
const char * GetName() const override
Returns name of object.
virtual const char * GetName() const
Returns name of object.
virtual TObject * Clone(const char *newname="") const
Make a clone of an object using the Streamer facility.
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.
OwningPtr< T > makeOwningPtr(std::unique_ptr< T > &&ptr)
Internal helper to turn a std::unique_ptr<T> into an OwningPtr.
T * OwningPtr
An alias for raw pointers for indicating that the return type of a RooFit function is an owning point...
Config argument to RooMinimizer constructor.
std::string minimizerType
bool enableParallelGradient
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
std::map< unsigned int, bool > fFixedParams
list of fixed parameters
bool isParameterFixed(unsigned int ipar) const
double lowerError(unsigned int i) const