Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-12-18 10:36:26

0001 /*****************************************************************************
0002  * Project: RooFit                                                           *
0003  * Package: RooFitCore                                                       *
0004  *    File: $Id$
0005  * Authors:                                                                  *
0006  *   WV, Wouter Verkerke, UC Santa Barbara, verkerke@slac.stanford.edu       *
0007  *   DK, David Kirkby,    UC Irvine,         dkirkby@uci.edu                 *
0008  *   AL, Alfio Lazzaro,   INFN Milan,        alfio.lazzaro@mi.infn.it        *
0009  *   PB, Patrick Bos,     NL eScience Center, p.bos@esciencecenter.nl        *
0010  *                                                                           *
0011  *                                                                           *
0012  * Redistribution and use in source and binary forms,                        *
0013  * with or without modification, are permitted according to the terms        *
0014  * listed in LICENSE (http://roofit.sourceforge.net/license.txt)             *
0015  *****************************************************************************/
0016 
0017 #ifndef ROO_MINIMIZER
0018 #define ROO_MINIMIZER
0019 
0020 #include <RooAbsReal.h>
0021 
0022 #include <TStopwatch.h>
0023 #include <TMatrixDSymfwd.h>
0024 
0025 #include <Fit/FitConfig.h>
0026 
0027 #include <fstream>
0028 #include <map>
0029 #include <memory>
0030 #include <string>
0031 #include <utility>
0032 #include <vector>
0033 
0034 class RooAbsMinimizerFcn;
0035 class RooFitResult;
0036 class RooArgList;
0037 class RooRealVar;
0038 class RooArgSet;
0039 class RooPlot;
0040 namespace RooFit {
0041 namespace TestStatistics {
0042 class LikelihoodGradientJob;
0043 }
0044 } // namespace RooFit
0045 
0046 class RooMinimizer : public TObject {
0047 public:
0048    // Internal struct for the temporary fit result.
0049    struct FitResult {
0050 
0051       FitResult() = default;
0052       FitResult(const ROOT::Fit::FitConfig &fconfig);
0053 
0054       double error(unsigned int i) const { return (i < fErrors.size()) ? fErrors[i] : 0; }
0055       double lowerError(unsigned int i) const;
0056       double upperError(unsigned int i) const;
0057 
0058       double Edm() const { return fEdm; }
0059       bool IsValid() const { return fValid; }
0060       int Status() const { return fStatus; }
0061       void GetCovarianceMatrix(TMatrixDSym &cov) const;
0062 
0063       bool isParameterFixed(unsigned int ipar) const;
0064 
0065       bool fValid = false;                       ///< flag for indicating valid fit
0066       int fStatus = -1;                          ///< minimizer status code
0067       int fCovStatus = -1;                       ///< covariance matrix status code
0068       double fVal = 0;                           ///< minimum function value
0069       double fEdm = -1;                          ///< expected distance from minimum
0070       std::map<unsigned int, bool> fFixedParams; ///< list of fixed parameters
0071       std::vector<double> fParams;               ///< parameter values. Size is total number of parameters
0072       std::vector<double> fErrors;               ///< errors
0073       std::vector<double> fCovMatrix; ///< covariance matrix (size is npar*(npar+1)/2) where npar is total parameters
0074       std::vector<double> fGlobalCC;  ///< global Correlation coefficient
0075       std::map<unsigned int, std::pair<double, double>> fMinosErrors; ///< map contains the two Minos errors
0076       std::string fMinimType;                                         ///< string indicating type of minimizer
0077    };
0078 
0079    /// Config argument to RooMinimizer constructor.
0080    struct Config {
0081 
0082       Config() {}
0083 
0084       bool useGradient = true; // Use the gradient provided by the RooAbsReal, if there is one.
0085 
0086       double recoverFromNaN = 10.; // RooAbsMinimizerFcn config
0087       int printEvalErrors = 10;    // RooAbsMinimizerFcn config
0088       int doEEWall = 1;            // RooAbsMinimizerFcn config
0089       int offsetting = -1;         // RooAbsMinimizerFcn config
0090       const char *logf = nullptr;  // RooAbsMinimizerFcn config
0091 
0092       // RooAbsMinimizerFcn config that can only be set in constructor, 0 means no parallelization (default),
0093       // -1 is parallelization with the number of workers controlled by RooFit::MultiProcess which
0094       // defaults to the number of available processors, n means parallelization with n CPU's
0095       int parallelize = 0;
0096 
0097       // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
0098       // argument is ignored when parallelize is 0
0099       bool enableParallelGradient = true;
0100 
0101       // Experimental: RooAbsMinimizerFcn config that can only be set in constructor
0102       // argument is ignored when parallelize is 0
0103       bool enableParallelDescent = false;
0104 
0105       bool verbose = false;        // local config
0106       bool profile = false;        // local config
0107       bool timingAnalysis = false; // local config
0108       std::string minimizerType;   // local config
0109 
0110       bool setInitialCovariance = false; // Use covariance matrix provided by user
0111    };
0112 
0113    // For backwards compatibility with when the RooMinimizer used the ROOT::Math::Fitter.
0114    class FitterInterface {
0115    public:
0116       FitterInterface(ROOT::Fit::FitConfig *config, ROOT::Math::Minimizer *minimizer, FitResult const *result)
0117          : _config{config}, _minimizer{minimizer}, _result{result}
0118       {
0119       }
0120 
0121       ROOT::Fit::FitConfig &Config() const { return *_config; }
0122       ROOT::Math::Minimizer *GetMinimizer() const { return _minimizer; }
0123       const FitResult &Result() const { return *_result; }
0124 
0125    private:
0126       ROOT::Fit::FitConfig *_config = nullptr;
0127       ROOT::Math::Minimizer *_minimizer = nullptr;
0128       FitResult const *_result = nullptr;
0129    };
0130 
0131    explicit RooMinimizer(RooAbsReal &function, Config const &cfg = {});
0132 
0133    ~RooMinimizer() override;
0134 
0135    enum Strategy { Speed = 0, Balance = 1, Robustness = 2 };
0136    enum PrintLevel { None = -1, Reduced = 0, Normal = 1, ExtraForProblem = 2, Maximum = 3 };
0137 
0138    // Setters on _theFitter
0139    void setStrategy(int istrat);
0140    void setErrorLevel(double level);
0141    void setEps(double eps);
0142    void setMaxIterations(int n);
0143    void setMaxFunctionCalls(int n);
0144    void setPrintLevel(int newLevel);
0145 
0146    // Setters on _fcn
0147    void optimizeConst(int flag);
0148    void setEvalErrorWall(bool flag) { _cfg.doEEWall = flag; }
0149    void setRecoverFromNaNStrength(double strength);
0150    void setOffsetting(bool flag);
0151    void setPrintEvalErrors(int numEvalErrors) { _cfg.printEvalErrors = numEvalErrors; }
0152    void setVerbose(bool flag = true) { _cfg.verbose = flag; }
0153    bool setLogFile(const char *logf = nullptr);
0154 
0155    int migrad();
0156    int hesse();
0157    int minos();
0158    int minos(const RooArgSet &minosParamList);
0159    int seek();
0160    int simplex();
0161    int improve();
0162 
0163    int minimize(const char *type, const char *alg = nullptr);
0164 
0165    RooFit::OwningPtr<RooFitResult> save(const char *name = nullptr, const char *title = nullptr);
0166    RooPlot *contour(RooRealVar &var1, RooRealVar &var2, double n1 = 1.0, double n2 = 2.0, double n3 = 0.0,
0167                     double n4 = 0.0, double n5 = 0.0, double n6 = 0.0, unsigned int npoints = 50);
0168 
0169    void setProfile(bool flag = true) { _cfg.profile = flag; }
0170 
0171    int getPrintLevel();
0172 
0173    void setMinimizerType(std::string const &type);
0174    std::string const &minimizerType() const { return _cfg.minimizerType; }
0175 
0176    RooFit::OwningPtr<RooFitResult> lastMinuitFit();
0177 
0178    void saveStatus(const char *label, int status) { _statusHistory.emplace_back(label, status); }
0179 
0180    /// Clears the Minuit status history.
0181    void clearStatusHistory() { _statusHistory.clear(); }
0182 
0183    int evalCounter() const;
0184    void zeroEvalCount();
0185 
0186    /// Return underlying ROOT fitter object
0187    inline auto fitter() { return std::make_unique<FitterInterface>(&_config, _minimizer.get(), _result.get()); }
0188 
0189    int getNPar() const;
0190 
0191    void applyCovarianceMatrix(TMatrixDSym const &V);
0192 
0193 private:
0194    friend class RooAbsMinimizerFcn;
0195    friend class RooMinimizerFcn;
0196    friend class RooFit::TestStatistics::LikelihoodGradientJob;
0197 
0198    std::unique_ptr<RooAbsReal::EvalErrorContext> makeEvalErrorContext() const;
0199 
0200    void addParamsToProcessTimer();
0201 
0202    void profileStart();
0203    void profileStop();
0204 
0205    std::ofstream *logfile();
0206    double &maxFCN();
0207    double &fcnOffset() const;
0208 
0209    // constructor helper functions
0210    void initMinimizerFirstPart();
0211    void initMinimizerFcnDependentPart(double defaultErrorLevel);
0212 
0213    void determineStatus(bool fitterReturnValue);
0214 
0215    int exec(std::string const &algoName, std::string const &statusName);
0216 
0217    bool fitFCN();
0218 
0219    bool calculateHessErrors();
0220    bool calculateMinosErrors();
0221 
0222    void initMinimizer();
0223    void updateFitConfig();
0224    bool updateMinimizerOptions(bool canDifferentMinim = true);
0225 
0226    void fillResult(bool isValid);
0227    bool update(bool isValid);
0228 
0229    void fillCorrMatrix(RooFitResult &fitRes);
0230    void updateErrors();
0231 
0232    ROOT::Fit::FitConfig _config;                      ///< fitter configuration (options and parameter settings)
0233    std::unique_ptr<FitResult> _result;                ///<! pointer to the object containing the result of the fit
0234    std::unique_ptr<ROOT::Math::Minimizer> _minimizer; ///<! pointer to used minimizer
0235    int _status = -99;
0236    bool _profileStart = false;
0237    TStopwatch _timer;
0238    TStopwatch _cumulTimer;
0239    std::unique_ptr<TMatrixDSym> _extV;
0240    std::unique_ptr<RooAbsMinimizerFcn> _fcn;
0241    std::vector<std::pair<std::string, int>> _statusHistory;
0242    RooMinimizer::Config _cfg; // local config object
0243 
0244    ClassDefOverride(RooMinimizer, 0) // RooFit interface to ROOT::Math::Minimizer
0245 };
0246 
0247 #endif