59#ifdef ROOFIT_MULTIPROCESS
107 if (nll_real !=
nullptr) {
110#ifdef 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);
160 RooSentinel::activate();
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 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 "
377 coutW(Minimization) <<
"RooMinimizer::hesse: Error, run Migrad before Hesse!" << endl;
408 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << endl;
418 bool ret =
_theFitter->CalculateMinosErrors();
440 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << endl;
442 }
else if (!minosParamList.
empty()) {
450 std::vector<unsigned int> paramInd;
452 RooAbsArg *par =
_fcn->GetFloatParamList()->find(arg->GetName());
454 int index =
_fcn->GetFloatParamList()->index(par);
455 paramInd.push_back(
index);
459 if (paramInd.size()) {
461 _theFitter->Config().SetMinosErrors(paramInd);
464 bool ret =
_theFitter->CalculateMinosErrors();
559 _theFitter->Config().MinimizerOptions().SetPrintLevel(newLevel + 1);
567 return _theFitter->Config().MinimizerOptions().PrintLevel() + 1;
576 _fcn->setOptimizeConst(flag);
590 coutW(Minimization) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
595 name = userName ? userName :
Form(
"%s",
_fcn->getFunctionName().c_str());
596 title = userTitle ? userTitle :
Form(
"%s",
_fcn->getFunctionTitle().c_str());
597 auto fitRes = std::make_unique<RooFitResult>(
name, title);
603 for (std::size_t i = 0; i <
_fcn->GetFloatParamList()->
size(); i++) {
607 saveFloatFinalList.
remove(*par);
608 saveConstList.
add(*par);
611 saveConstList.
sort();
613 fitRes->setConstParList(saveConstList);
614 fitRes->setInitParList(saveFloatInitList);
616 double removeOffset = 0.;
617 fitRes->setNumInvalidNLL(
_fcn->GetNumInvalidNLL());
618 removeOffset = -
_fcn->getOffset();
621 fitRes->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
622 fitRes->setMinNLL(
_theFitter->Result().MinFcnValue() + removeOffset);
624 fitRes->setFinalParList(saveFloatFinalList);
626 std::vector<double> globalCC;
629 for (std::size_t ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
630 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
631 for (std::size_t ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
632 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
633 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
636 fitRes->fillCorrMatrix(globalCC, corrs, covs);
638 fitRes->setCovarianceMatrix(*
_extV);
663 double n5,
double n6,
unsigned int npoints)
670 int index1 =
_fcn->GetFloatParamList()->
index(&var1);
672 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var1.
GetName()
673 <<
" is not a floating parameter of " <<
_fcn->getFunctionName() << endl;
677 int index2 =
_fcn->GetFloatParamList()->index(&var2);
679 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var2.
GetName()
680 <<
" is not a floating parameter of PDF " <<
_fcn->getFunctionName() << endl;
694 coutW(Minimization) <<
"RooMinimizer::contour: Error, run Migrad before contours!" << endl;
699 double errdef =
_theFitter->GetMinimizer()->ErrorDef();
709 for (
int ic = 0; ic < 6; ic++) {
713 _theFitter->GetMinimizer()->SetErrorDef(
n[ic] *
n[ic] * errdef);
716 std::vector<double> xcoor(npoints + 1);
717 std::vector<double> ycoor(npoints + 1);
718 bool ret =
_theFitter->GetMinimizer()->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
721 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName()
722 <<
") ERROR: MINUIT did not return a contour graph for n=" <<
n[ic] << endl;
724 xcoor[npoints] = xcoor[0];
725 ycoor[npoints] = ycoor[0];
728 graph->SetName(
Form(
"contour_%s_n%f",
_fcn->getFunctionName().c_str(),
n[ic]));
729 graph->SetLineStyle(ic + 1);
730 graph->SetLineWidth(2);
738 _theFitter->GetMinimizer()->SetErrorDef(errdef);
741 params->
assign(paramSave);
751#ifdef ROOFIT_MULTIPROCESS
753 std::vector<std::string> parameter_names;
754 for (
auto &¶meter : *
_fcn->GetFloatParamList()) {
755 parameter_names.push_back(parameter->GetName());
757 coutI(Minimization) <<
"parameter name: " << parameter_names.back() << std::endl;
762 coutI(Minimization) <<
"Not adding parameters to processtimer because multiprocessing "
763 <<
"is not enabled." << std::endl;
787 coutI(Minimization) <<
"Command timer: ";
789 coutI(Minimization) <<
"Session timer: ";
797 return fitterFcn ? fitterFcn :
_fcn->getMultiGenFcn();
822 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
828 oocoutE(
nullptr, InputArguments)
829 <<
"RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
830 <<
" or match the number of variables of the last fit ("
831 <<
_theFitter->Result().NTotalParameters() <<
")" << endl;
838 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::lastMinuitFit: ERROR: variable '" << arg->GetName()
839 <<
"' is not of type RooRealVar" << endl;
844 auto res = std::make_unique<RooFitResult>(
"lastMinuitFit",
"Last MINUIT fit");
852 for (i = 0; i <
_theFitter->Result().NTotalParameters(); ++i) {
855 bool isConst(
_theFitter->Result().IsParameterFixed(i));
857 double xlo =
_theFitter->Config().ParSettings(i).LowerLimit();
858 double xhi =
_theFitter->Config().ParSettings(i).UpperLimit();
862 std::unique_ptr<RooRealVar> var;
863 if (varList.
empty()) {
865 if ((xlo < xhi) && !isConst) {
866 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
868 var = std::make_unique<RooRealVar>(varName, varName, xval);
870 var->setConstant(isConst);
874 var->setConstant(isConst);
877 var->setRange(xlo, xhi);
881 oocoutI(
nullptr, Eval) <<
"RooMinimizer::lastMinuitFit: fit parameter '" << varName
882 <<
"' stored in variable '" << var->GetName() <<
"'" << endl;
894 res->setConstParList(constPars);
895 res->setInitParList(floatPars);
896 res->setFinalParList(floatPars);
897 res->setMinNLL(
_theFitter->Result().MinFcnValue());
899 res->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
900 res->setStatus(
_theFitter->Result().Status());
901 std::vector<double> globalCC;
904 for (
unsigned int ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
905 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
906 for (
unsigned int ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
907 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
908 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
911 res->fillCorrMatrix(globalCC, corrs, covs);
938 return _fcn->evalCounter();
942 _fcn->zeroEvalCount();
947 return _fcn->getNDim();
952 return _fcn->GetLogFile();
956 return _fcn->GetMaxFCN();
961#ifdef ROOFIT_MULTIPROCESS
975 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()
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.
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
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 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.
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.
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