59#ifdef ROOFIT_MULTIPROCESS
93 if (nll_real !=
nullptr) {
96#ifdef ROOFIT_MULTIPROCESS
100 coutI(InputArguments) <<
"Modular likelihood detected and likelihood parallelization requested, "
101 <<
"also setting parallel gradient calculation mode." << std::endl;
110 _fcn = std::make_unique<RooFit::TestStatistics::MinuitFcnGrad>(
111 nll_real->getRooAbsL(),
this,
getConfig().ParamsSettings(),
116 throw std::logic_error(
117 "Parallel minimization requested, but ROOT was not compiled with multiprocessing enabled, "
118 "please recompile with -Droofit_multiprocess=ON for parallel evaluation");
121 coutW(InputArguments)
122 <<
"Requested modular likelihood without gradient parallelization, some features such as offsetting "
123 <<
"may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl;
129 _fcn = std::make_unique<RooMinimizerFcn>(&function,
this);
133 throw std::logic_error(
"In RooMinimizer constructor: Selected likelihood evaluation but a "
134 "non-modular likelihood was given. Please supply ModularL(true) as an "
135 "argument to createNLL for modular likelihoods to use likelihood "
136 "or gradient parallelization.");
138 _fcn = std::make_unique<RooMinimizerFcn>(&function,
this);
146 RooSentinel::activate();
149 _theFitter = std::make_unique<ROOT::Fit::Fitter>();
255 std::stringstream ss;
256 ss <<
"In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!";
258 ss <<
"\nPlease set it as your default minimizer via "
259 "ROOT::Math::MinimizerOptions::SetDefaultMinimizer(\"Minuit2\").";
261 throw std::invalid_argument(ss.str());
272 coutE(Minimization) <<
"RooMinimizer: all function calls during minimization gave invalid NLL values!"
288#ifdef ROOFIT_MULTIPROCESS
291 throw std::logic_error(
"ProcessTimer, but ROOT was not compiled with multiprocessing enabled, "
292 "please recompile with -Droofit_multiprocess=ON for logging with the "
324 return exec(
"migrad",
"MIGRAD");
335 if (algoName ==
"hesse") {
339 }
else if (algoName ==
"minos") {
366 coutW(Minimization) <<
"RooMinimizer::hesse: Error, run Migrad before Hesse!" << std::endl;
371 return exec(
"hesse",
"HESSE");
383 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
388 return exec(
"minos",
"MINOS");
400 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << std::endl;
402 }
else if (!minosParamList.
empty()) {
410 std::vector<unsigned int> paramInd;
412 RooAbsArg *par =
_fcn->GetFloatParamList()->find(arg->GetName());
414 int index =
_fcn->GetFloatParamList()->index(par);
415 paramInd.push_back(
index);
419 if (!paramInd.empty()) {
424 bool ret =
_theFitter->CalculateMinosErrors();
447 return exec(
"seek",
"SEEK");
458 return exec(
"simplex",
"SIMPLEX");
469 return exec(
"migradimproved",
"IMPROVE");
494 _fcn->setOptimizeConst(flag);
508 coutW(Minimization) <<
"RooMinimizer::save: Error, run minimization before!" << std::endl;
514 name = userName ? userName :
Form(
"%s",
_fcn->getFunctionName().c_str());
515 title = userTitle ? userTitle :
Form(
"%s",
_fcn->getFunctionTitle().c_str());
516 auto fitRes = std::make_unique<RooFitResult>(
name, title);
522 for (std::size_t i = 0; i <
_fcn->GetFloatParamList()->
size(); i++) {
526 saveFloatFinalList.
remove(*par);
527 saveConstList.
add(*par);
530 saveConstList.
sort();
532 fitRes->setConstParList(saveConstList);
533 fitRes->setInitParList(saveFloatInitList);
535 double removeOffset = 0.;
536 fitRes->setNumInvalidNLL(
_fcn->GetNumInvalidNLL());
537 removeOffset = -
_fcn->getOffset();
541 fitRes->setMinNLL(
getResult().MinFcnValue() + removeOffset);
543 fitRes->setFinalParList(saveFloatFinalList);
546 std::vector<double> globalCC;
549 for (std::size_t ic = 0; ic < nParams; ic++) {
550 globalCC.push_back(
getResult().GlobalCC(ic));
551 for (std::size_t ii = 0; ii < nParams; ii++) {
556 fitRes->fillCorrMatrix(globalCC, corrs, covs);
558 fitRes->setCovarianceMatrix(*
_extV);
583 double n5,
double n6,
unsigned int npoints)
590 int index1 =
_fcn->GetFloatParamList()->
index(&var1);
592 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var1.
GetName()
593 <<
" is not a floating parameter of " <<
_fcn->getFunctionName() << std::endl;
597 int index2 =
_fcn->GetFloatParamList()->index(&var2);
599 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var2.
GetName()
600 <<
" is not a floating parameter of PDF " <<
_fcn->getFunctionName() << std::endl;
614 coutW(Minimization) <<
"RooMinimizer::contour: Error, run Migrad before contours!" << std::endl;
629 for (
int ic = 0; ic < 6; ic++) {
636 std::vector<double> xcoor(npoints + 1);
637 std::vector<double> ycoor(npoints + 1);
641 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName()
642 <<
") ERROR: MINUIT did not return a contour graph for n=" <<
n[ic] << std::endl;
644 xcoor[npoints] = xcoor[0];
645 ycoor[npoints] = ycoor[0];
648 graph->SetName(
Form(
"contour_%s_n%f",
_fcn->getFunctionName().c_str(),
n[ic]));
649 graph->SetLineStyle(ic + 1);
650 graph->SetLineWidth(2);
661 params->
assign(paramSave);
671#ifdef ROOFIT_MULTIPROCESS
673 std::vector<std::string> parameter_names;
674 for (
auto &¶meter : *
_fcn->GetFloatParamList()) {
675 parameter_names.push_back(parameter->GetName());
677 coutI(Minimization) <<
"parameter name: " << parameter_names.back() << std::endl;
682 coutI(Minimization) <<
"Not adding parameters to processtimer because multiprocessing is not enabled." << std::endl;
706 coutI(Minimization) <<
"Command timer: ";
708 coutI(Minimization) <<
"Session timer: ";
716 return fitterFcn ? fitterFcn :
_fcn->getMultiGenFcn();
741 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::save: Error, run minimization before!" << std::endl;
747 oocoutE(
nullptr, InputArguments)
748 <<
"RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << std::endl
749 <<
" or match the number of variables of the last fit ("
757 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::lastMinuitFit: ERROR: variable '" << arg->GetName()
758 <<
"' is not of type RooRealVar" << std::endl;
763 auto res = std::make_unique<RooFitResult>(
"lastMinuitFit",
"Last MINUIT fit");
774 bool isConst(
getResult().IsParameterFixed(i));
781 std::unique_ptr<RooRealVar> var;
782 if (varList.
empty()) {
784 if ((xlo < xhi) && !isConst) {
785 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
787 var = std::make_unique<RooRealVar>(varName, varName, xval);
789 var->setConstant(isConst);
793 var->setConstant(isConst);
796 var->setRange(xlo, xhi);
800 oocoutI(
nullptr, Eval) <<
"RooMinimizer::lastMinuitFit: fit parameter '" << varName
801 <<
"' stored in variable '" << var->GetName() <<
"'" << std::endl;
813 res->setConstParList(constPars);
814 res->setInitParList(floatPars);
815 res->setFinalParList(floatPars);
816 res->setMinNLL(
getResult().MinFcnValue());
820 std::vector<double> globalCC;
824 for (
unsigned int ic = 0; ic < nParams; ic++) {
825 globalCC.push_back(
getResult().GlobalCC(ic));
826 for (
unsigned int ii = 0; ii < nParams; ii++) {
831 res->fillCorrMatrix(globalCC, corrs, covs);
859 return _fcn->evalCounter();
863 _fcn->zeroEvalCount();
868 return _fcn->getNDim();
873 return _fcn->GetLogFile();
877 return _fcn->GetMaxFCN();
881 return _fcn->getOffset();
886#ifdef ROOFIT_MULTIPROCESS
900 return std::make_unique<RooAbsReal::EvalErrorContext>(
m);
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 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.
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 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)
double Error(unsigned int i) const
parameter error by index
double CovMatrix(unsigned int i, unsigned int j) const
retrieve covariance matrix element
double Value(unsigned int i) const
parameter value by index
const std::vector< double > & Parameters() const
parameter values (return std::vector)
double Correlation(unsigned int i, unsigned int j) const
retrieve correlation elements
unsigned int NTotalParameters() const
get total number of parameters
int Status() const
minimizer status code
double LowerLimit() const
return lower limit value
double UpperLimit() const
return upper limit value
Documentation for the abstract class IBaseFunctionMultiDim.
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
void SetErrorDef(double up)
set scale for calculating the errors
double ErrorDef() const
return the statistical scale used for calculate the error is typically 1 for Chi2 and 0....
virtual bool Contour(unsigned int ivar, unsigned int jvar, unsigned int &npoints, double *xi, double *xj)
find the contour points (xi, xj) of the function for parameter ivar and jvar around the minimum The c...
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.
TObject * Clone(const char *newname=nullptr) const override
Make a clone of an object using the Streamer facility.
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...
Storage_t::size_type size() const
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.
RooAbsArg * at(Int_t idx) const
Return object at given index, or nullptr if index is out of range.
RooArgSet is a container object that can hold multiple RooAbsArg objects.
static void setDefaultNWorkers(unsigned int N_workers)
static unsigned int getDefaultNWorkers()
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::Fit:Fitter that provides a seamless interface between the minimizer functi...
void setRecoverFromNaNStrength(double strength)
Try to recover from invalid function values.
int getPrintLevel()
Get the MINUIT internal printing level.
const ROOT::Fit::FitResult & getResult() const
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
ROOT::Fit::FitConfig & getConfig() const
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.
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.
double & fcnOffset() const
void profileStop()
Stop profiling timer and report results of last session.
int minos()
Execute MINOS.
int hesse()
Execute HESSE.
void setErrorLevel(double level)
Set the level for MINUIT error analysis to the given value.
void determineStatus(bool fitterReturnValue)
int migrad()
Execute MIGRAD.
void setEps(double eps)
Change MINUIT epsilon.
void setPrintLevel(int newLevel)
Change the MINUIT internal printing level.
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.
std::unique_ptr< ROOT::Fit::Fitter > _theFitter
RooMinimizer::Config _cfg
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.
ROOT::Math::Minimizer * getMinimizer() 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.
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.
int CompareTo(const char *cs, ECaseCompare cmp=kExact) const
Compare a string to char *cs2.
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.
bool enableParallelDescent
std::string minimizerType
bool enableParallelGradient