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.empty()) {
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;
596 name = userName ? userName :
Form(
"%s",
_fcn->getFunctionName().c_str());
597 title = userTitle ? userTitle :
Form(
"%s",
_fcn->getFunctionTitle().c_str());
598 auto fitRes = std::make_unique<RooFitResult>(
name, title);
604 for (std::size_t i = 0; i <
_fcn->GetFloatParamList()->
size(); i++) {
608 saveFloatFinalList.
remove(*par);
609 saveConstList.
add(*par);
612 saveConstList.
sort();
614 fitRes->setConstParList(saveConstList);
615 fitRes->setInitParList(saveFloatInitList);
617 double removeOffset = 0.;
618 fitRes->setNumInvalidNLL(
_fcn->GetNumInvalidNLL());
619 removeOffset = -
_fcn->getOffset();
622 fitRes->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
623 fitRes->setMinNLL(
_theFitter->Result().MinFcnValue() + removeOffset);
625 fitRes->setFinalParList(saveFloatFinalList);
627 std::vector<double> globalCC;
630 for (std::size_t ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
631 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
632 for (std::size_t ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
633 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
634 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
637 fitRes->fillCorrMatrix(globalCC, corrs, covs);
639 fitRes->setCovarianceMatrix(*
_extV);
664 double n5,
double n6,
unsigned int npoints)
671 int index1 =
_fcn->GetFloatParamList()->
index(&var1);
673 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var1.
GetName()
674 <<
" is not a floating parameter of " <<
_fcn->getFunctionName() << endl;
678 int index2 =
_fcn->GetFloatParamList()->index(&var2);
680 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var2.
GetName()
681 <<
" is not a floating parameter of PDF " <<
_fcn->getFunctionName() << endl;
695 coutW(Minimization) <<
"RooMinimizer::contour: Error, run Migrad before contours!" << endl;
700 double errdef =
_theFitter->GetMinimizer()->ErrorDef();
710 for (
int ic = 0; ic < 6; ic++) {
714 _theFitter->GetMinimizer()->SetErrorDef(
n[ic] *
n[ic] * errdef);
717 std::vector<double> xcoor(npoints + 1);
718 std::vector<double> ycoor(npoints + 1);
719 bool ret =
_theFitter->GetMinimizer()->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
722 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName()
723 <<
") ERROR: MINUIT did not return a contour graph for n=" <<
n[ic] << endl;
725 xcoor[npoints] = xcoor[0];
726 ycoor[npoints] = ycoor[0];
729 graph->SetName(
Form(
"contour_%s_n%f",
_fcn->getFunctionName().c_str(),
n[ic]));
730 graph->SetLineStyle(ic + 1);
731 graph->SetLineWidth(2);
739 _theFitter->GetMinimizer()->SetErrorDef(errdef);
742 params->
assign(paramSave);
752#ifdef ROOFIT_MULTIPROCESS
754 std::vector<std::string> parameter_names;
755 for (
auto &¶meter : *
_fcn->GetFloatParamList()) {
756 parameter_names.push_back(parameter->GetName());
758 coutI(Minimization) <<
"parameter name: " << parameter_names.back() << std::endl;
763 coutI(Minimization) <<
"Not adding parameters to processtimer because multiprocessing "
764 <<
"is not enabled." << std::endl;
788 coutI(Minimization) <<
"Command timer: ";
790 coutI(Minimization) <<
"Session timer: ";
798 return fitterFcn ? fitterFcn :
_fcn->getMultiGenFcn();
823 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
829 oocoutE(
nullptr, InputArguments)
830 <<
"RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
831 <<
" or match the number of variables of the last fit ("
832 <<
_theFitter->Result().NTotalParameters() <<
")" << endl;
839 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::lastMinuitFit: ERROR: variable '" << arg->GetName()
840 <<
"' is not of type RooRealVar" << endl;
845 auto res = std::make_unique<RooFitResult>(
"lastMinuitFit",
"Last MINUIT fit");
853 for (i = 0; i <
_theFitter->Result().NTotalParameters(); ++i) {
856 bool isConst(
_theFitter->Result().IsParameterFixed(i));
858 double xlo =
_theFitter->Config().ParSettings(i).LowerLimit();
859 double xhi =
_theFitter->Config().ParSettings(i).UpperLimit();
863 std::unique_ptr<RooRealVar> var;
864 if (varList.
empty()) {
866 if ((xlo < xhi) && !isConst) {
867 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
869 var = std::make_unique<RooRealVar>(varName, varName, xval);
871 var->setConstant(isConst);
875 var->setConstant(isConst);
878 var->setRange(xlo, xhi);
882 oocoutI(
nullptr, Eval) <<
"RooMinimizer::lastMinuitFit: fit parameter '" << varName
883 <<
"' stored in variable '" << var->GetName() <<
"'" << endl;
895 res->setConstParList(constPars);
896 res->setInitParList(floatPars);
897 res->setFinalParList(floatPars);
898 res->setMinNLL(
_theFitter->Result().MinFcnValue());
900 res->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
901 res->setStatus(
_theFitter->Result().Status());
902 std::vector<double> globalCC;
905 for (
unsigned int ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
906 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
907 for (
unsigned int ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
908 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
909 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
912 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 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()
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.
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.
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 > 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