59#ifdef R__HAS_ROOFIT_MULTIPROCESS
107 if (nll_real !=
nullptr) {
110#ifdef R__HAS_ROOFIT_MULTIPROCESS
114 coutI(InputArguments) <<
"Modular likelihood detected and likelihood parallelization requested, "
115 <<
"also setting parallel gradient calculation mode." << std::endl;
124 _fcn = std::make_unique<RooFit::TestStatistics::MinuitFcnGrad>(
125 nll_real->getRooAbsL(),
this,
_theFitter->Config().ParamsSettings(),
127 static_cast<RooFit::TestStatistics::LikelihoodMode>(int(_cfg.enableParallelDescent))},
130 throw std::logic_error(
131 "Parallel minimization requested, but ROOT was not compiled with multiprocessing enabled, "
132 "please recompile with -Droofit_multiprocess=ON for parallel evaluation");
135 coutW(InputArguments)
136 <<
"Requested modular likelihood without gradient parallelization, some features such as offsetting "
137 <<
"may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl;
143 _fcn = std::make_unique<RooMinimizerFcn>(&function,
this);
147 throw std::logic_error(
"In RooMinimizer constructor: Selected likelihood evaluation but a "
148 "non-modular likelihood was given. Please supply ModularL(true) as an "
149 "argument to createNLL for modular likelihoods to use likelihood "
150 "or gradient parallelization.");
152 _fcn = std::make_unique<RooMinimizerFcn>(&function,
this);
163 _theFitter = std::make_unique<ROOT::Fit::Fitter>();
172 _theFitter->Config().MinimizerOptions().SetMaxIterations(500 *
_fcn->getNDim());
173 _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(500 *
_fcn->getNDim());
213 _theFitter->Config().MinimizerOptions().SetStrategy(istrat);
222 _theFitter->Config().MinimizerOptions().SetMaxIterations(
n);
231 _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(
n);
242 _theFitter->Config().MinimizerOptions().SetErrorDef(level);
250 _theFitter->Config().MinimizerOptions().SetTolerance(eps);
273 std::stringstream ss;
274 ss <<
"In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!";
276 ss <<
"\nPlease set it as your default minimizer via "
277 "ROOT::Math::MinimizerOptions::SetDefaultMinimizer(\"Minuit2\").";
279 throw std::invalid_argument(ss.str());
315#ifdef R__HAS_ROOFIT_MULTIPROCESS
318 throw std::logic_error(
"ProcessTimer, but ROOT was not compiled with multiprocessing enabled, "
319 "please recompile with -Droofit_multiprocess=ON for logging with the "
376 coutW(Minimization) <<
"RooMinimizer::hesse: Error, run Migrad before Hesse!" << endl;
407 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << endl;
417 bool ret =
_theFitter->CalculateMinosErrors();
439 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << endl;
441 }
else if (!minosParamList.
empty()) {
449 std::vector<unsigned int> paramInd;
451 RooAbsArg *par =
_fcn->GetFloatParamList()->find(arg->GetName());
453 int index =
_fcn->GetFloatParamList()->index(par);
454 paramInd.push_back(
index);
458 if (paramInd.size()) {
460 _theFitter->Config().SetMinosErrors(paramInd);
463 bool ret =
_theFitter->CalculateMinosErrors();
558 _theFitter->Config().MinimizerOptions().SetPrintLevel(newLevel + 1);
566 return _theFitter->Config().MinimizerOptions().PrintLevel() + 1;
575 _fcn->setOptimizeConst(flag);
589 coutW(Minimization) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
594 name = userName ? userName :
Form(
"%s",
_fcn->getFunctionName().c_str());
595 title = userTitle ? userTitle :
Form(
"%s",
_fcn->getFunctionTitle().c_str());
596 auto fitRes = std::make_unique<RooFitResult>(
name, title);
602 for (std::size_t i = 0; i <
_fcn->GetFloatParamList()->
size(); i++) {
606 saveFloatFinalList.
remove(*par);
607 saveConstList.
add(*par);
610 saveConstList.
sort();
612 fitRes->setConstParList(saveConstList);
613 fitRes->setInitParList(saveFloatInitList);
617 double removeOffset = 0.;
619 fitRes->setNumInvalidNLL(
fitFcn->GetNumInvalidNLL());
620 removeOffset = -
fitFcn->getOffset();
624 fitRes->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
625 fitRes->setMinNLL(
_theFitter->Result().MinFcnValue() + removeOffset);
627 fitRes->setFinalParList(saveFloatFinalList);
629 std::vector<double> globalCC;
632 for (std::size_t ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
633 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
634 for (std::size_t ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
635 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
636 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
639 fitRes->fillCorrMatrix(globalCC, corrs, covs);
641 fitRes->setCovarianceMatrix(*
_extV);
666 double n5,
double n6,
unsigned int npoints)
672 int index1 =
_fcn->GetFloatParamList()->
index(&var1);
674 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var1.
GetName()
675 <<
" is not a floating parameter of " <<
_fcn->getFunctionName() << endl;
679 int index2 =
_fcn->GetFloatParamList()->index(&var2);
681 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var2.
GetName()
682 <<
" is not a floating parameter of PDF " <<
_fcn->getFunctionName() << endl;
696 coutW(Minimization) <<
"RooMinimizer::contour: Error, run Migrad before contours!" << endl;
701 double errdef =
_theFitter->GetMinimizer()->ErrorDef();
711 for (
int ic = 0; ic < 6; ic++) {
715 _theFitter->GetMinimizer()->SetErrorDef(
n[ic] *
n[ic] * errdef);
718 std::vector<double> xcoor(npoints + 1);
719 std::vector<double> ycoor(npoints + 1);
720 bool ret =
_theFitter->GetMinimizer()->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
723 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName()
724 <<
") ERROR: MINUIT did not return a contour graph for n=" <<
n[ic] << endl;
726 xcoor[npoints] = xcoor[0];
727 ycoor[npoints] = ycoor[0];
730 graph->SetName(
Form(
"contour_%s_n%f",
_fcn->getFunctionName().c_str(),
n[ic]));
731 graph->SetLineStyle(ic + 1);
732 graph->SetLineWidth(2);
740 _theFitter->GetMinimizer()->SetErrorDef(errdef);
743 params->
assign(*paramSave);
753#ifdef R__HAS_ROOFIT_MULTIPROCESS
755 std::vector<std::string> parameter_names;
756 for (
auto &¶meter : *
_fcn->GetFloatParamList()) {
757 parameter_names.push_back(parameter->GetName());
759 coutI(Minimization) <<
"parameter name: " << parameter_names.back() << std::endl;
764 coutI(Minimization) <<
"Not adding parameters to processtimer because multiprocessing "
765 <<
"is not enabled." << std::endl;
789 coutI(Minimization) <<
"Command timer: ";
791 coutI(Minimization) <<
"Session timer: ";
799 return fitterFcn ? fitterFcn :
_fcn->getMultiGenFcn();
824 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
830 oocoutE(
nullptr, InputArguments)
831 <<
"RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
832 <<
" or match the number of variables of the last fit ("
833 <<
_theFitter->Result().NTotalParameters() <<
")" << endl;
840 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::lastMinuitFit: ERROR: variable '" << arg->GetName()
841 <<
"' is not of type RooRealVar" << endl;
846 auto res = std::make_unique<RooFitResult>(
"lastMinuitFit",
"Last MINUIT fit");
854 for (i = 0; i <
_theFitter->Result().NTotalParameters(); ++i) {
857 bool isConst(
_theFitter->Result().IsParameterFixed(i));
859 double xlo =
_theFitter->Config().ParSettings(i).LowerLimit();
860 double xhi =
_theFitter->Config().ParSettings(i).UpperLimit();
864 std::unique_ptr<RooRealVar> var;
865 if (varList.
empty()) {
867 if ((xlo < xhi) && !isConst) {
868 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
870 var = std::make_unique<RooRealVar>(varName, varName, xval);
872 var->setConstant(isConst);
876 var->setConstant(isConst);
879 var->setRange(xlo, xhi);
883 oocoutI(
nullptr, Eval) <<
"RooMinimizer::lastMinuitFit: fit parameter '" << varName
884 <<
"' stored in variable '" << var->GetName() <<
"'" << endl;
896 res->setConstParList(constPars);
897 res->setInitParList(floatPars);
898 res->setFinalParList(floatPars);
899 res->setMinNLL(
_theFitter->Result().MinFcnValue());
901 res->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
902 res->setStatus(
_theFitter->Result().Status());
903 std::vector<double> globalCC;
906 for (
unsigned int ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
907 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
908 for (
unsigned int ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
909 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
910 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
913 res->fillCorrMatrix(globalCC, corrs, covs);
940 return _fcn->evalCounter();
944 _fcn->zeroEvalCount();
949 return _fcn->getNDim();
954 return _fcn->GetLogFile();
958 return _fcn->GetMaxFCN();
963#ifdef R__HAS_ROOFIT_MULTIPROCESS
977 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.
Fitter class, entry point for performing all type of fits.
ROOT::Math::IMultiGenFunction * GetFCN() const
return pointer to last used objective function (is NULL in case fit is not yet done) This pointer wil...
Documentation for the abstract class IBaseFunctionMultiDim.
static const std::string & DefaultMinimizerType()
RooAbsArg is the common abstract base class for objects that represent a value and a "shape" in RooFi...
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.
RooAbsReal is the common abstract base class for objects that represent a real value and implements f...
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.
RooMinimizer is a wrapper class around ROOT::Fit:Fitter that provides a seamless interface between th...
void setRecoverFromNaNStrength(double strength)
Try to recover from invalid function values.
static 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.
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 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.
static std::unique_ptr< ROOT::Fit::Fitter > _theFitter
int migrad()
Execute MIGRAD.
void setEps(double eps)
Change MINUIT epsilon.
void setPrintLevel(int newLevel)
Change the MINUIT internal printing level.
int improve()
Execute IMPROVE.
static void cleanup()
Cleanup method called by atexit handler installed by RooSentinel to delete all global heap objects wh...
void setOffsetting(bool flag)
Enable internal likelihood offsetting for enhanced numeric precision.
RooMinimizer::Config _cfg
static 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
void setStrategy(int strat)
Change MINUIT strategy to istrat.
std::unique_ptr< RooAbsReal::EvalErrorContext > makeEvalErrorContext() const
RooMinimizer(RooAbsReal &function, Config const &cfg={})
Construct MINUIT interface to given function.
ROOT::Fit::Fitter * fitter()
Return underlying ROOT fitter object.
void setMaxFunctionCalls(int n)
Change maximum number of likelihood function calss from MINUIT (RooMinimizer default 500 * #parameter...
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.
A RooPlot is a 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.
RooRealVar represents a variable that can be changed from the outside.
static void activate()
Install atexit handler that calls CleanupRooFitAtExit() on program termination.
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 > owningPtr(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 ctor.
std::string minimizerType
bool enableParallelGradient