59#ifdef ROOFIT_MULTIPROCESS
106 if (nll_real !=
nullptr) {
109#ifdef ROOFIT_MULTIPROCESS
113 coutI(InputArguments) <<
"Modular likelihood detected and likelihood parallelization requested, "
114 <<
"also setting parallel gradient calculation mode." << std::endl;
123 _fcn = std::make_unique<RooFit::TestStatistics::MinuitFcnGrad>(
124 nll_real->getRooAbsL(),
this,
_theFitter->Config().ParamsSettings(),
126 static_cast<RooFit::TestStatistics::LikelihoodMode>(int(_cfg.enableParallelDescent))},
129 throw std::logic_error(
130 "Parallel minimization requested, but ROOT was not compiled with multiprocessing enabled, "
131 "please recompile with -Droofit_multiprocess=ON for parallel evaluation");
134 coutW(InputArguments)
135 <<
"Requested modular likelihood without gradient parallelization, some features such as offsetting "
136 <<
"may not work yet. Non-modular likelihoods are more reliable without parallelization." << std::endl;
142 _fcn = std::make_unique<RooMinimizerFcn>(&
function,
this);
146 throw std::logic_error(
"In RooMinimizer constructor: Selected likelihood evaluation but a "
147 "non-modular likelihood was given. Please supply ModularL(true) as an "
148 "argument to createNLL for modular likelihoods to use likelihood "
149 "or gradient parallelization.");
151 _fcn = std::make_unique<RooMinimizerFcn>(&
function,
this);
159 RooSentinel::activate();
162 _theFitter = std::make_unique<ROOT::Fit::Fitter>();
171 _theFitter->Config().MinimizerOptions().SetMaxIterations(500 *
_fcn->getNDim());
172 _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(500 *
_fcn->getNDim());
212 _theFitter->Config().MinimizerOptions().SetStrategy(istrat);
221 _theFitter->Config().MinimizerOptions().SetMaxIterations(
n);
230 _theFitter->Config().MinimizerOptions().SetMaxFunctionCalls(
n);
241 _theFitter->Config().MinimizerOptions().SetErrorDef(level);
249 _theFitter->Config().MinimizerOptions().SetTolerance(eps);
272 std::stringstream ss;
273 ss <<
"In RooMinimizer::setMinimizerType: only Minuit2 is supported when not using classic function mode!";
275 ss <<
"\nPlease set it as your default minimizer via "
276 "ROOT::Math::MinimizerOptions::SetDefaultMinimizer(\"Minuit2\").";
278 throw std::invalid_argument(ss.str());
310 coutE(Minimization) <<
"RooMinimizer: all function calls during minimization gave invalid NLL values!"
326#ifdef ROOFIT_MULTIPROCESS
329 throw std::logic_error(
"ProcessTimer, but ROOT was not compiled with multiprocessing enabled, "
330 "please recompile with -Droofit_multiprocess=ON for logging with the "
388 coutW(Minimization) <<
"RooMinimizer::hesse: Error, run Migrad before Hesse!" << endl;
419 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << endl;
429 bool ret =
_theFitter->CalculateMinosErrors();
451 coutW(Minimization) <<
"RooMinimizer::minos: Error, run Migrad before Minos!" << endl;
453 }
else if (!minosParamList.
empty()) {
461 std::vector<unsigned int> paramInd;
463 RooAbsArg *par =
_fcn->GetFloatParamList()->find(arg->GetName());
465 int index =
_fcn->GetFloatParamList()->index(par);
466 paramInd.push_back(
index);
470 if (!paramInd.empty()) {
472 _theFitter->Config().SetMinosErrors(paramInd);
475 bool ret =
_theFitter->CalculateMinosErrors();
570 _theFitter->Config().MinimizerOptions().SetPrintLevel(newLevel + 1);
578 return _theFitter->Config().MinimizerOptions().PrintLevel() + 1;
587 _fcn->setOptimizeConst(flag);
601 coutW(Minimization) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
607 name = userName ? userName :
Form(
"%s",
_fcn->getFunctionName().c_str());
608 title = userTitle ? userTitle :
Form(
"%s",
_fcn->getFunctionTitle().c_str());
609 auto fitRes = std::make_unique<RooFitResult>(
name, title);
615 for (std::size_t i = 0; i <
_fcn->GetFloatParamList()->
size(); i++) {
619 saveFloatFinalList.
remove(*par);
620 saveConstList.
add(*par);
623 saveConstList.
sort();
625 fitRes->setConstParList(saveConstList);
626 fitRes->setInitParList(saveFloatInitList);
628 double removeOffset = 0.;
629 fitRes->setNumInvalidNLL(
_fcn->GetNumInvalidNLL());
630 removeOffset = -
_fcn->getOffset();
633 fitRes->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
634 fitRes->setMinNLL(
_theFitter->Result().MinFcnValue() + removeOffset);
636 fitRes->setFinalParList(saveFloatFinalList);
638 std::vector<double> globalCC;
641 for (std::size_t ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
642 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
643 for (std::size_t ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
644 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
645 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
648 fitRes->fillCorrMatrix(globalCC, corrs, covs);
650 fitRes->setCovarianceMatrix(*
_extV);
675 double n5,
double n6,
unsigned int npoints)
682 int index1 =
_fcn->GetFloatParamList()->
index(&var1);
684 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var1.
GetName()
685 <<
" is not a floating parameter of " <<
_fcn->getFunctionName() << endl;
689 int index2 =
_fcn->GetFloatParamList()->index(&var2);
691 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName() <<
") ERROR: " << var2.
GetName()
692 <<
" is not a floating parameter of PDF " <<
_fcn->getFunctionName() << endl;
706 coutW(Minimization) <<
"RooMinimizer::contour: Error, run Migrad before contours!" << endl;
711 double errdef =
_theFitter->GetMinimizer()->ErrorDef();
721 for (
int ic = 0; ic < 6; ic++) {
725 _theFitter->GetMinimizer()->SetErrorDef(
n[ic] *
n[ic] * errdef);
728 std::vector<double> xcoor(npoints + 1);
729 std::vector<double> ycoor(npoints + 1);
730 bool ret =
_theFitter->GetMinimizer()->Contour(index1, index2, npoints, xcoor.data(), ycoor.data());
733 coutE(Minimization) <<
"RooMinimizer::contour(" <<
GetName()
734 <<
") ERROR: MINUIT did not return a contour graph for n=" <<
n[ic] << endl;
736 xcoor[npoints] = xcoor[0];
737 ycoor[npoints] = ycoor[0];
740 graph->SetName(
Form(
"contour_%s_n%f",
_fcn->getFunctionName().c_str(),
n[ic]));
741 graph->SetLineStyle(ic + 1);
742 graph->SetLineWidth(2);
750 _theFitter->GetMinimizer()->SetErrorDef(errdef);
753 params->
assign(paramSave);
763#ifdef ROOFIT_MULTIPROCESS
765 std::vector<std::string> parameter_names;
766 for (
auto &¶meter : *
_fcn->GetFloatParamList()) {
767 parameter_names.push_back(parameter->GetName());
769 coutI(Minimization) <<
"parameter name: " << parameter_names.back() << std::endl;
774 coutI(Minimization) <<
"Not adding parameters to processtimer because multiprocessing is not enabled." << std::endl;
798 coutI(Minimization) <<
"Command timer: ";
800 coutI(Minimization) <<
"Session timer: ";
808 return fitterFcn ? fitterFcn :
_fcn->getMultiGenFcn();
833 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::save: Error, run minimization before!" << endl;
839 oocoutE(
nullptr, InputArguments)
840 <<
"RooMinimizer::lastMinuitFit: ERROR: supplied variable list must be either empty " << endl
841 <<
" or match the number of variables of the last fit ("
842 <<
_theFitter->Result().NTotalParameters() <<
")" << endl;
849 oocoutE(
nullptr, InputArguments) <<
"RooMinimizer::lastMinuitFit: ERROR: variable '" << arg->GetName()
850 <<
"' is not of type RooRealVar" << endl;
855 auto res = std::make_unique<RooFitResult>(
"lastMinuitFit",
"Last MINUIT fit");
863 for (i = 0; i <
_theFitter->Result().NTotalParameters(); ++i) {
866 bool isConst(
_theFitter->Result().IsParameterFixed(i));
868 double xlo =
_theFitter->Config().ParSettings(i).LowerLimit();
869 double xhi =
_theFitter->Config().ParSettings(i).UpperLimit();
873 std::unique_ptr<RooRealVar> var;
874 if (varList.
empty()) {
876 if ((xlo < xhi) && !isConst) {
877 var = std::make_unique<RooRealVar>(varName, varName, xval, xlo, xhi);
879 var = std::make_unique<RooRealVar>(varName, varName, xval);
881 var->setConstant(isConst);
885 var->setConstant(isConst);
888 var->setRange(xlo, xhi);
892 oocoutI(
nullptr, Eval) <<
"RooMinimizer::lastMinuitFit: fit parameter '" << varName
893 <<
"' stored in variable '" << var->GetName() <<
"'" << endl;
905 res->setConstParList(constPars);
906 res->setInitParList(floatPars);
907 res->setFinalParList(floatPars);
908 res->setMinNLL(
_theFitter->Result().MinFcnValue());
910 res->setCovQual(
_theFitter->GetMinimizer()->CovMatrixStatus());
911 res->setStatus(
_theFitter->Result().Status());
912 std::vector<double> globalCC;
915 for (
unsigned int ic = 0; ic <
_theFitter->Result().Parameters().
size(); ic++) {
916 globalCC.push_back(
_theFitter->Result().GlobalCC(ic));
917 for (
unsigned int ii = 0; ii <
_theFitter->Result().Parameters().
size(); ii++) {
918 corrs(ic, ii) =
_theFitter->Result().Correlation(ic, ii);
919 covs(ic, ii) =
_theFitter->Result().CovMatrix(ic, ii);
922 res->fillCorrMatrix(globalCC, corrs, covs);
950 return _fcn->evalCounter();
954 _fcn->zeroEvalCount();
959 return _fcn->getNDim();
964 return _fcn->GetLogFile();
968 return _fcn->GetMaxFCN();
972 return _fcn->getOffset();
977#ifdef ROOFIT_MULTIPROCESS
991 return std::make_unique<RooAbsReal::EvalErrorContext>(
m);
double defaultErrorLevel() const override
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.
virtual double defaultErrorLevel() const
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.
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.
static std::unique_ptr< ROOT::Fit::Fitter > _theFitter
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 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 > 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