Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2025-09-18 09:25:43

0001 // Weights.h is a part of the PYTHIA event generator.
0002 // Copyright (C) 2025 Torbjorn Sjostrand.
0003 // PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details.
0004 // Please respect the MCnet Guidelines, see GUIDELINES for details.
0005 
0006 // This file contains classes that keep track of event weights.
0007 
0008 #ifndef Pythia8_Weights_H
0009 #define Pythia8_Weights_H
0010 
0011 #include "Pythia8/Basics.h"
0012 #include "Pythia8/LHEF3.h"
0013 #include "Pythia8/PythiaStdlib.h"
0014 #include "Pythia8/SharedPointers.h"
0015 
0016 namespace Pythia8 {
0017 
0018 // Forward declare classes which need internal member access.
0019 class History;
0020 class Info;
0021 class PartonLevel;
0022 class Merging;
0023 class WeightContainer;
0024 class StringFlav;
0025 
0026 //==========================================================================
0027 
0028 // This is a base class to store weight information in a way that allows
0029 // unified access in the structure that contains all event generation weights
0030 // information (WeightContainer below). The main purpuse of this class is to
0031 // supply convenience features to make defining new categories of weights easy.
0032 // All weights should inherit from this base class. The specialized classes
0033 // may then contain specialized functions, or only act as a glorified
0034 // book-keeping structure.
0035 
0036 class WeightsBase {
0037 
0038 public:
0039 
0040   // Friends for internal protected members.
0041   friend class History;
0042   friend class PartonLevel;
0043 
0044   // Initialize the weights.
0045   virtual void init() {weightValues.resize(0); weightNames.resize(0);
0046     bookWeight("Baseline");}
0047   virtual void init(bool) {}
0048 
0049   // Reset all internal values.
0050   virtual void clear() {fill(weightValues.begin(), weightValues.end(), 1.);}
0051 
0052   // Store the current event information (replace whitespace with underscore
0053   // for HepMC).
0054   virtual void bookVectors(vector<double> weights, vector<string> names) {
0055     for (int i = 0; i < (int)weights.size(); ++i) {
0056       replace(names[i].begin(), names[i].end(), ' ', '_');
0057       bookWeight(names[i], weights[i]);
0058     }
0059   }
0060 
0061   // Function to return processed weights to weight container, e.g. if
0062   // weights should be combined before proceeding.
0063   virtual void collectWeightValues(vector<double>& outputWeights,
0064     double norm = 1.);
0065 
0066   // Similar function to return processed weight names.
0067   virtual void collectWeightNames(vector<string>& outputNames);
0068 
0069   // Get the stored information.
0070   // Direcly use storage members here in the base class,
0071   // and access those through non-virtual getters.
0072   // Note: NOT opting for a map data structure, since information will anyway
0073   // have to be serialized in output.
0074   // Change weight names for compatibility with Rivet by replacing colons
0075   // with full stops.
0076   string getWeightsName(int iPos) const  {
0077     string name = iPos >= 0
0078       && iPos < (int)weightNames.size() ? weightNames[iPos] : "";
0079     if (name.find(":") != string::npos)
0080       replace(name.begin(), name.end(), ':', '.');
0081     return name == "" ? to_string(iPos) : name;}
0082   virtual double getWeightsValue(int iPos) const { return weightValues[iPos]; }
0083   int getWeightsSize() const { return weightValues.size(); }
0084 
0085   // Function to create a new, synchronized, pair of weight name and value.
0086   void bookWeight(string name, double defaultValue = 1.)  {
0087     // Check if name already exists.
0088     if (findIndexOfName(name) != -1) setValueByName(name, defaultValue);
0089     else {
0090       weightNames.push_back(name);
0091       weightValues.push_back(defaultValue);
0092     }
0093   }
0094 
0095   // Functions to set values of weights.
0096   void setValueByIndex(int iPos, double val) {
0097     if (iPos < 0 || iPos >= (int)weightValues.size()) return;
0098     weightValues[iPos] = val;
0099   }
0100   void setValueByName(string name, double val) {
0101     setValueByIndex(findIndexOfName(name), val);}
0102 
0103   // Functions to reweight weight values, by index or by name.
0104   virtual void reweightValueByIndex(int iPos, double val) {
0105     if (iPos < 0 || iPos >= (int)weightValues.size()) return;
0106     weightValues[iPos] *= val;
0107   };
0108   virtual void reweightValueByName(string name, double val) {
0109     // Use existing functions: Find index of name, then set by index.
0110     int iPos = findIndexOfName(name);
0111     reweightValueByIndex(iPos, val);
0112   }
0113 
0114   // Function to find the index of a given entry in the weightNames vector,
0115   // e.g., to be able to synchronize with the weightValues vector.
0116   int findIndexOfName(string name) {
0117     vector<string>::iterator it
0118       = find(weightNames.begin(), weightNames.end(), name);
0119     unsigned long int index = distance(weightNames.begin(), it);
0120     if (index == weightNames.size()) return -1;
0121     return distance(weightNames.begin(), it);
0122   }
0123 
0124   // Set the pointers.
0125   void setPtrs(Info* infoPtrIn) { infoPtr = infoPtrIn; }
0126 
0127 protected:
0128 
0129   // Parse a WVec of variations into a dictionary.
0130   void parse(string wvecKey, map<string, map<string, double> > &dct);
0131 
0132   // Weight values and names.
0133   vector<double> weightValues;
0134   vector<string> weightNames;
0135 
0136   // Pointers necessary for variation initialization
0137   Info* infoPtr{};
0138 
0139 };
0140 
0141 //==========================================================================
0142 
0143 // Purely virtual base class for shower weights.
0144 
0145 class WeightsShower : public WeightsBase {
0146 
0147 public:
0148 
0149   // Initialize weights (more can be booked at any time)
0150   void init(bool) override {}
0151 
0152   // Weight "groups" (combinations of one or more unique weights).
0153   virtual void initWeightGroups(bool = false) {}
0154   virtual int nWeightGroups() const {return 0;}
0155   virtual string getGroupName( int /*iGroup*/ ) const {return "";}
0156   virtual double getGroupWeight( int /*iGroup*/ ) const {return 1.;}
0157 
0158 };
0159 
0160 //==========================================================================
0161 
0162 // This shows a WeightsShower example implementation for SimpleShower.
0163 
0164 class WeightsSimpleShower : public WeightsShower {
0165 
0166 public:
0167 
0168   // Initialize weights (more can be booked at any time)
0169   void init( bool doMerging) override;
0170 
0171   // Functions to return processed weights to weight container, e.g. if
0172   // weights should be combined before proceeding.
0173   void collectWeightNames(vector<string>& outputNames) override;
0174   void collectWeightValues(vector<double>& outputWeights,
0175     double norm = 1.) override;
0176 
0177   // Initialize the weight groups for automated variations.
0178   void initWeightGroups(bool = false) override;
0179 
0180   // Return group name (want to integrate this in weightNameVector?)
0181   string getGroupName(int iGN) const override;
0182 
0183   // Return group weight (want to integrate this in weightValueVector?)
0184   double getGroupWeight(int iGW) const override;
0185   int    nWeightGroups() const override { return externalVariations.size(); }
0186 
0187   // Initialise list of atomic weight variations to be performed by shower.
0188   bool initUniqueShowerVars();
0189 
0190   // Memorize enhancement factor and pT of enhanced emission
0191   void setEnhancedTrial( double pTIn, double wtIn) { pTEnhanced = pTIn;
0192     wtEnhanced = wtIn; }
0193   double getEnhancedTrialPT() { return pTEnhanced;}
0194   double getEnhancedTrialWeight() { return wtEnhanced;}
0195 
0196   // Extract full list or subset that matches specific keys (e.g., FSR ones).
0197   vector<string> getUniqueShowerVars() { return uniqueShowerVars; }
0198   vector<string> getUniqueShowerVars(vector<string> keys);
0199 
0200   // Initialise map of enhancement factors for shower trial probabilities.
0201   bool initEnhanceFactors();
0202   unordered_map<string,double> getEnhanceFactors() { return enhanceFactors; }
0203 
0204   string getInitialName(int iG) const { return initialNameSave[iG]; }
0205 
0206   // Variations that must be known by TimeShower and Spaceshower.
0207   map<int,double> varPDFplus, varPDFminus, varPDFmember;
0208 
0209   // Vectors for storing shower variatons and enhancement factors.
0210   vector<string> uniqueShowerVars;
0211   unordered_map<string,double> enhanceFactors;
0212 
0213   // Vectors for weight group handling
0214   vector<string>          externalVariations;
0215   vector<vector<string> > externalVarNames;
0216   vector<string>          externalGroupNames;
0217   vector<string>          initialNameSave;
0218   vector<vector<int> >    externalMap;
0219   int                     externalVariationsSize{};
0220 
0221   // Vector for merging requested weight handling
0222   vector<double> getMuRWeightVector();
0223   vector<vector<string> > mergingVarNames;
0224   double pTEnhanced{}, wtEnhanced{};
0225 
0226 };
0227 
0228 //==========================================================================
0229 
0230 // This class collects information on weights generated in the merging
0231 // framework. The first weight is always required for CKKW-L, UMEPS and
0232 // NLO merging. The additional weights are required for simultaneous
0233 // renormalization scale variation in matrix element generation and parton
0234 // shower.
0235 
0236 class WeightsMerging : public WeightsBase {
0237 
0238 public:
0239 
0240   // Friends for internal protected members.
0241   friend class Merging;
0242   friend class WeightContainer;
0243 
0244   // Initialize weights (more can be booked at any time)
0245   void init() override;
0246 
0247   // Reset all internal values;
0248   void clear() override;
0249 
0250   // Function to create a new, synchronized, pair of weight name and value.
0251   void bookWeight(string name, double value, double valueFirst);
0252 
0253   // Store the current event information.
0254   void bookVectors(vector<double> weights, vector<string> names) override;
0255   void bookVectors(vector<double> weights, vector<double> weightsFirst,
0256             vector<string> names);
0257   // Modified weight getter to include first order weight
0258   double getWeightsValue(int iPos) const override {
0259     return weightValues[iPos] - weightValuesFirst[iPos]; }
0260   // Also add getters for UNLOPS-P and -PC schemes
0261   double getWeightsValueP(int iPos) const {
0262     return weightValuesP[iPos] - weightValuesFirstP[iPos]; }
0263   double getWeightsValuePC(int iPos) const {
0264     return weightValuesPC[iPos] - weightValuesFirstPC[iPos]; }
0265 
0266   // Functions to set values of weights.
0267   void reweightValueByIndex(int iPos, double val) override;
0268   void reweightValueByName(string name, double val) override;
0269 
0270   // Functions to set values of first order weights.
0271   void setValueFirstByIndex(int iPos, double val);
0272   void setValueFirstByName(string name, double val);
0273 
0274   // Functions to set values as whole vector.
0275   void setValueVector(vector<double> ValueVector);
0276   void setValueFirstVector(vector<double> ValueFirstVector);
0277 
0278   // Function telling merging which muR variations to perform
0279   vector<double> getMuRVarFactors();
0280 
0281   // Set up mapping between LHEF variations.
0282   void setLHEFvariationMapping();
0283 
0284   // Function to collect weight names.
0285   void collectWeightNames(vector<string>& outputNames) override;
0286 
0287   // Function collecting weight values.
0288   void collectWeightValues(vector<double>& outputWeights,
0289      double norm = 1.) override;
0290 
0291 protected:
0292 
0293   // Corresponding vector with respective LHEF weight indices.
0294   map<int,int> muRVarLHEFindex;
0295 
0296   // Data member for first order weight.
0297   vector<double> weightValuesFirst;
0298 
0299   // Data members for UNLOPS-P and -PC.
0300   vector<double> weightValuesP, weightValuesPC,
0301     weightValuesFirstP, weightValuesFirstPC;
0302 
0303   // Boolean to memorize if LHEF weight needs to be applied (only for NLO).
0304   bool isNLO;
0305 
0306 };
0307 
0308 //==========================================================================
0309 
0310 // This is a short example class to collect information on Les Houches
0311 // Event weights into a container class that can be part of Weight,
0312 // which in turn is part of Info.
0313 
0314 class WeightsLHEF : public WeightsBase {
0315 
0316 public:
0317 
0318   // Friends for internal protected members.
0319   friend class WeightsMerging;
0320 
0321   // Central weight, needed for normalization, set from ProcessContainer.cc
0322   double centralWeight;
0323 
0324   // Reset all internal values;
0325   void clear() override;
0326 
0327   // Store the current event information.
0328   void bookVectors(vector<double> weights, vector<string> names) override;
0329 
0330   // Function to return processed weights to weight container, e.g. if
0331   // weights should be combined before proceeding.
0332   void collectWeightValues(vector<double>& outputWeights,
0333      double norm = 1.) override;
0334   void collectWeightNames(vector<string>& outputNames) override;
0335 
0336   // Convert weight names in MadGraph5 convention to the convention outlined
0337   // in https://arxiv.org/pdf/1405.1067.pdf, page 162ff.
0338   vector<string> convertNames(vector<string> names);
0339 
0340   void identifyVariationsFromLHAinit(map<string,LHAweight>* weights);
0341 
0342 protected:
0343 
0344   // Renormalization variations.
0345   map<int,double> muRvars;
0346 
0347 };
0348 
0349 //==========================================================================
0350 
0351 // This is class to collect information on fragmentation weighting,
0352 // and is in turn part of Info.
0353 
0354 class WeightsFragmentation : public WeightsBase {
0355 
0356 public:
0357 
0358   // Friends for fragmentation reweighitng.
0359   friend class StringFlav;
0360 
0361   // Initialize the weights.
0362   void init() override;
0363 
0364   // Clear the weights.
0365   void clear() override {
0366     WeightsBase::clear(); fill(flavBreaks.begin(), flavBreaks.end(), 0);}
0367 
0368   int nWeightGroups() const {return externalGroupNames.size();}
0369 
0370   string getGroupName(int iGN) const {return iGN < 0 || iGN >= nWeightGroups()
0371       ? "Null" : externalGroupNames[iGN];}
0372 
0373   // Return group weight.
0374   double getGroupWeight(int iGW) const {
0375     if (iGW < 0 || iGW >= nWeightGroups()) return 1.0;
0376     double wgt(1.);
0377     for (const int &iWgt : externalMap[iGW]) wgt *= getWeightsValue(iWgt);
0378     return wgt;}
0379 
0380   // Functions to return processed weights to weight container, e.g. if
0381   // weights should be combined before proceeding.
0382   void collectWeightNames(vector<string>& outputNames) override;
0383   void collectWeightValues(vector<double>& outputWeights,
0384     double norm = 1.) override;
0385 
0386   // Calculate the derived flavor parameters.
0387   vector<double> flavParms(double xi, double rho, double x, double y);
0388 
0389   // Calculate a flavor weight.
0390   double flavWeight(const vector<double>& parms) {
0391     return flavWeight(parms, flavBreaks);}
0392   double flavWeight(const vector<double>& parms, const vector<int>& breaks);
0393 
0394   // Vectors for weight group handling.
0395   vector<map<vector<double>, int> > weightParms{};
0396   vector<string>       externalGroupNames{};
0397   vector<vector<int> > externalMap{};
0398 
0399   // Track the breaks needed for reweighting.
0400   vector<int> flavBreaks;
0401 
0402   // Factorization indices.
0403   enum FactIndex{Z, Flav, PT};
0404 
0405 private:
0406 
0407   // Ordering of the fragmentation weight keys.
0408   const vector<vector< pair<string, string> > > keyOrder{
0409     {{"frag:alund", "StringZ:aLund"}, {"frag:blund", "StringZ:bLund"},
0410      {"frag:rfactc", "StringZ:rFactC"}, {"frag:rfactb", "StringZ:rFactB"}},
0411     {{"frag:xi", "StringFlav:ProbQQtoQ"}, {"frag:rho", "StringFlav:ProbStoUD"},
0412      {"frag:x", "StringFlav:ProbSQtoQQ"},
0413      {"frag:y", "StringFlav:ProbQQ1toQQ0"}},
0414     {{"frag:ptsigma", "StringPT:sigma"}}};
0415 
0416   // Flavor spin ratios to store in derived.
0417   const vector<int> flavIdxs{0, 1, 2, 3, 6};
0418 
0419   // Stored parameters for flavor reweighting.
0420   vector<double> flavBase;
0421 
0422   // Count the flavor breaks for variations.
0423   void flavCount(int idIn, bool early, bool noChoice);
0424 
0425 };
0426 
0427 //==========================================================================
0428 
0429 // This is a container class to collect all event generation weight
0430 // information into a wrapper which is in turn is part of Info. In this
0431 // way, we could avoid cluttering Info.
0432 
0433 class WeightContainer {
0434 
0435 public:
0436 
0437   // Default constructor only ensures that members are initialized with
0438   // sensible default values.
0439   WeightContainer() : weightNominal(1.0), xsecIsInit(false) {}
0440 
0441   // The nominal Pythia weight, in pb for lha strategy 4 and -4
0442   double weightNominal;
0443   void setWeightNominal( double weightNow );
0444   double collectWeightNominal();
0445 
0446   // First example of a weight subcategory.
0447   WeightsLHEF          weightsLHEF{};
0448 
0449   // Shower weights. SimpleShower one hardcoded and made default since
0450   // Merging explicitly depends on it, but allow to point to a
0451   // different weightsShower-derived object, eg for Vincia (with own
0452   // merging).
0453   WeightsShower*       weightsShowerPtr{};
0454   WeightsSimpleShower  weightsSimpleShower{};
0455 
0456   // Merging weights.
0457   WeightsMerging       weightsMerging{};
0458 
0459   // Fragmentation weights.
0460   WeightsFragmentation weightsFragmentation{};
0461 
0462   // Userhooks weights.
0463   WeightsBase          weightsUserHooks{};
0464 
0465   // Functions to retrieve information stored in the subcategory members.
0466   int numberOfWeights();
0467   double weightValueByIndex(int key = 0);
0468   string weightNameByIndex(int key = 0);
0469 
0470   // Function to return the vector of weight values, combining all
0471   // weights from all subcategories. Currently, only the nominal
0472   // weight and LHEF weights are considered. Internal Pythia weights
0473   // should also be included eventually.
0474   vector<double> weightValueVector();
0475 
0476   // Function to return the vector of weight names, combining all names from
0477   // all subcategories, cf. weightValueVector function.
0478   vector<string> weightNameVector();
0479 
0480   // Reset all members to default stage.
0481   void clear();
0482 
0483   // Reset total cross section estimate.
0484   void clearTotal();
0485 
0486   // Init, for those classes that need it.
0487   void init(bool doMerging);
0488 
0489   // Function to set Pointers in weight classes.
0490   void initPtrs(Info* infoPtrIn);
0491 
0492   // Initialize the cross-section vector.
0493   void initXsecVec();
0494 
0495   // Get cross-section vectors.
0496   vector<double> getSampleXsec();
0497   vector<double> getTotalXsec();
0498   vector<double> getSampleXsecErr();
0499   vector<double> getTotalXsecErr();
0500 
0501   // Accumulate cross section for all weights.
0502   void accumulateXsec(double norm = 1.);
0503 
0504 private:
0505 
0506   // Pointers necessary for variation initialization.
0507   Info* infoPtr{};
0508 
0509   // Suppress AUX_ weights.
0510   bool doSuppressAUXweights{};
0511 
0512   // Vectors for cross-section.
0513   vector<double> sigmaTotal, sigmaSample, errorTotal, errorSample;
0514   bool xsecIsInit;
0515 
0516 };
0517 
0518 //==========================================================================
0519 
0520 } // end namespace Pythia8
0521 
0522 #endif // Pythia8_Weights_H