PYTHIA  8.312
Weights.h
1 // Weights.h is a part of the PYTHIA event generator.
2 // Copyright (C) 2024 Torbjorn Sjostrand.
3 // PYTHIA is licenced under the GNU GPL v2 or later, see COPYING for details.
4 // Please respect the MCnet Guidelines, see GUIDELINES for details.
5 
6 // This file contains classes that keep track of event weights.
7 
8 #ifndef Pythia8_Weights_H
9 #define Pythia8_Weights_H
10 
11 #include "Pythia8/Basics.h"
12 #include "Pythia8/LHEF3.h"
13 #include "Pythia8/PythiaStdlib.h"
14 #include "Pythia8/SharedPointers.h"
15 
16 namespace Pythia8 {
17 
18 // Forward declare classes which need internal member access.
19 class Info;
20 class History;
21 class PartonLevel;
22 class Merging;
23 class WeightContainer;
24 
25 //==========================================================================
26 
27 // This is a base class to store weight information in a way that allows
28 // unified access in the structure that contains all event generation weights
29 // information (WeightContainer below). The main purpuse of this class is to
30 // supply convenience features to make defining new categories of weights easy.
31 // All weights should inherit from this base class. The specialized classes
32 // may then contain specialized functions, or only act as a glorified
33 // book-keeping structure.
34 
35 class WeightsBase {
36 
37 public:
38 
39  // Friends for internal protected members.
40  friend class History;
41  friend class PartonLevel;
42 
43  // Initialize the weights.
44  virtual void init() {weightValues.resize(0); weightNames.resize(0);
45  bookWeight("Baseline");}
46  virtual void init(bool) {}
47 
48  // Reset all internal values.
49  virtual void clear() {fill(weightValues.begin(), weightValues.end(), 1.);}
50 
51  // Store the current event information (replace whitespace with underscore
52  // for HepMC).
53  virtual void bookVectors(vector<double> weights, vector<string> names) {
54  for (int i = 0; i < (int)weights.size(); ++i) {
55  replace(names[i].begin(), names[i].end(), ' ', '_');
56  bookWeight(names[i], weights[i]);
57  }
58  }
59 
60  // Function to return processed weights to weight container, e.g. if
61  // weights should be combined before proceeding.
62  virtual void collectWeightValues(vector<double>& outputWeights,
63  double norm = 1.);
64 
65  // Similar function to return processed weight names.
66  virtual void collectWeightNames(vector<string>& outputNames);
67 
68  // Get the stored information.
69  // Direcly use storage members here in the base class,
70  // and access those through non-virtual getters.
71  // Note: NOT opting for a map data structure, since information will anyway
72  // have to be serialized in output.
73  // Change weight names for compatibility with Rivet by replacing colons
74  // with full stops.
75  string getWeightsName(int iPos) const {
76  string name = iPos >= 0
77  && iPos < (int)weightNames.size() ? weightNames[iPos] : "";
78  if (name.find(":") != string::npos)
79  replace(name.begin(), name.end(), ':', '.');
80  return name == "" ? to_string(iPos) : name;}
81  virtual double getWeightsValue(int iPos) const { return weightValues[iPos]; }
82  int getWeightsSize() const { return weightValues.size(); }
83 
84  // Function to create a new, synchronized, pair of weight name and value.
85  void bookWeight(string name, double defaultValue = 1.) {
86  // Check if name already exists.
87  if (findIndexOfName(name) != -1) setValueByName(name, defaultValue);
88  else {
89  weightNames.push_back(name);
90  weightValues.push_back(defaultValue);
91  }
92  }
93 
94  // Functions to set values of weights.
95  void setValueByIndex(int iPos, double val) {
96  if (iPos < 0 || iPos >= (int)weightValues.size()) return;
97  weightValues[iPos] = val;
98  }
99  void setValueByName(string name, double val) {
100  setValueByIndex(findIndexOfName(name), val);}
101 
102  // Functions to reweight weight values, by index or by name.
103  virtual void reweightValueByIndex(int iPos, double val) {
104  if (iPos < 0 || iPos >= (int)weightValues.size()) return;
105  weightValues[iPos] *= val;
106  };
107  virtual void reweightValueByName(string name, double val) {
108  // Use existing functions: Find index of name, then set by index.
109  int iPos = findIndexOfName(name);
110  reweightValueByIndex(iPos, val);
111  }
112 
113  // Function to find the index of a given entry in the weightNames vector,
114  // e.g., to be able to synchronize with the weightValues vector.
115  int findIndexOfName(string name) {
116  vector<string>::iterator it
117  = find(weightNames.begin(), weightNames.end(), name);
118  unsigned long int index = distance(weightNames.begin(), it);
119  if (index == weightNames.size()) return -1;
120  return distance(weightNames.begin(), it);
121  }
122 
123  // Set the pointers.
124  void setPtrs(Info* infoPtrIn) { infoPtr = infoPtrIn; }
125 
126 protected:
127 
128  // Parse a WVec of variations into a dictionary.
129  void parse(string wvecKey, map<string, map<string, double> > &dct);
130 
131  // Weight values and names.
132  vector<double> weightValues;
133  vector<string> weightNames;
134 
135  // Pointers necessary for variation initialization
137 
138 };
139 
140 //==========================================================================
141 
142 // Purely virtual base class for shower weights.
143 
144 class WeightsShower : public WeightsBase {
145 
146 public:
147 
148  // Initialize weights (more can be booked at any time)
149  void init(bool) override {}
150 
151  // Weight "groups" (combinations of one or more unique weights).
152  virtual void initWeightGroups(bool = false) {}
153  virtual int nWeightGroups() const {return 0;}
154  virtual string getGroupName( int /*iGroup*/ ) const {return "";}
155  virtual double getGroupWeight( int /*iGroup*/ ) const {return 1.;}
156 
157 };
158 
159 //==========================================================================
160 
161 // This shows a WeightsShower example implementation for SimpleShower.
162 
164 
165 public:
166 
167  // Initialize weights (more can be booked at any time)
168  void init( bool doMerging) override;
169 
170  // Functions to return processed weights to weight container, e.g. if
171  // weights should be combined before proceeding.
172  void collectWeightNames(vector<string>& outputNames) override;
173  void collectWeightValues(vector<double>& outputWeights,
174  double norm = 1.) override;
175 
176  // Initialize the weight groups for automated variations.
177  void initWeightGroups(bool = false) override;
178 
179  // Return group name (want to integrate this in weightNameVector?)
180  string getGroupName(int iGN) const override;
181 
182  // Return group weight (want to integrate this in weightValueVector?)
183  double getGroupWeight(int iGW) const override;
184  int nWeightGroups() const override { return externalVariations.size(); }
185 
186  // Initialise list of atomic weight variations to be performed by shower.
187  bool initUniqueShowerVars();
188 
189  // Memorize enhancement factor and pT of enhanced emission
190  void setEnhancedTrial( double pTIn, double wtIn) { pTEnhanced = pTIn;
191  wtEnhanced = wtIn; }
192  double getEnhancedTrialPT() { return pTEnhanced;}
193  double getEnhancedTrialWeight() { return wtEnhanced;}
194 
195  // Extract full list or subset that matches specific keys (e.g., FSR ones).
196  vector<string> getUniqueShowerVars() { return uniqueShowerVars; }
197  vector<string> getUniqueShowerVars(vector<string> keys);
198 
199  // Initialise map of enhancement factors for shower trial probabilities.
200  bool initEnhanceFactors();
201  unordered_map<string,double> getEnhanceFactors() { return enhanceFactors; }
202 
203  string getInitialName(int iG) const { return initialNameSave[iG]; }
204 
205  // Variations that must be known by TimeShower and Spaceshower.
206  map<int,double> varPDFplus, varPDFminus, varPDFmember;
207 
208  // Vectors for storing shower variatons and enhancement factors.
209  vector<string> uniqueShowerVars;
210  unordered_map<string,double> enhanceFactors;
211 
212  // Vectors for weight group handling
213  vector<string> externalVariations;
214  vector<vector<string> > externalVarNames;
215  vector<string> externalGroupNames;
216  vector<string> initialNameSave;
217  vector<vector<int> > externalMap;
218  int externalVariationsSize{};
219 
220  // Vector for merging requested weight handling
221  vector<double> getMuRWeightVector();
222  vector<vector<string> > mergingVarNames;
223  double pTEnhanced{}, wtEnhanced{};
224 
225 };
226 
227 //==========================================================================
228 
229 // This class collects information on weights generated in the merging
230 // framework. The first weight is always required for CKKW-L, UMEPS and
231 // NLO merging. The additional weights are required for simultaneous
232 // renormalization scale variation in matrix element generation and parton
233 // shower.
234 
235 class WeightsMerging : public WeightsBase {
236 
237 public:
238 
239  // Friends for internal protected members.
240  friend class Merging;
241  friend class WeightContainer;
242 
243  // Initialize weights (more can be booked at any time)
244  void init() override;
245 
246  // Reset all internal values;
247  void clear() override;
248 
249  // Function to create a new, synchronized, pair of weight name and value.
250  void bookWeight(string name, double value, double valueFirst);
251 
252  // Store the current event information.
253  void bookVectors(vector<double> weights, vector<string> names) override;
254  void bookVectors(vector<double> weights, vector<double> weightsFirst,
255  vector<string> names);
256  // Modified weight getter to include first order weight
257  double getWeightsValue(int iPos) const override {
258  return weightValues[iPos] - weightValuesFirst[iPos]; }
259  // Also add getters for UNLOPS-P and -PC schemes
260  double getWeightsValueP(int iPos) const {
261  return weightValuesP[iPos] - weightValuesFirstP[iPos]; }
262  double getWeightsValuePC(int iPos) const {
263  return weightValuesPC[iPos] - weightValuesFirstPC[iPos]; }
264 
265  // Functions to set values of weights.
266  void reweightValueByIndex(int iPos, double val) override;
267  void reweightValueByName(string name, double val) override;
268 
269  // Functions to set values of first order weights.
270  void setValueFirstByIndex(int iPos, double val);
271  void setValueFirstByName(string name, double val);
272 
273  // Functions to set values as whole vector.
274  void setValueVector(vector<double> ValueVector);
275  void setValueFirstVector(vector<double> ValueFirstVector);
276 
277  // Function telling merging which muR variations to perform
278  vector<double> getMuRVarFactors();
279 
280  // Set up mapping between LHEF variations.
281  void setLHEFvariationMapping();
282 
283  // Function to collect weight names.
284  void collectWeightNames(vector<string>& outputNames) override;
285 
286  // Function collecting weight values.
287  void collectWeightValues(vector<double>& outputWeights,
288  double norm = 1.) override;
289 
290 protected:
291 
292  // Corresponding vector with respective LHEF weight indices.
293  map<int,int> muRVarLHEFindex;
294 
295  // Data member for first order weight.
296  vector<double> weightValuesFirst;
297 
298  // Data members for UNLOPS-P and -PC.
299  vector<double> weightValuesP, weightValuesPC,
300  weightValuesFirstP, weightValuesFirstPC;
301 
302  // Boolean to memorize if LHEF weight needs to be applied (only for NLO).
303  bool isNLO;
304 
305 };
306 
307 //==========================================================================
308 
309 // This is a short example class to collect information on Les Houches
310 // Event weights into a container class that can be part of Weight,
311 // which in turn is part of Info.
312 
313 class WeightsLHEF : public WeightsBase {
314 
315 public:
316 
317  // Friends for internal protected members.
318  friend class WeightsMerging;
319 
320  // Central weight, needed for normalization, set from ProcessContainer.cc
322 
323  // Reset all internal values;
324  void clear() override;
325 
326  // Store the current event information.
327  void bookVectors(vector<double> weights, vector<string> names) override;
328 
329  // Function to return processed weights to weight container, e.g. if
330  // weights should be combined before proceeding.
331  void collectWeightValues(vector<double>& outputWeights,
332  double norm = 1.) override;
333  void collectWeightNames(vector<string>& outputNames) override;
334 
335  // Convert weight names in MadGraph5 convention to the convention outlined
336  // in https://arxiv.org/pdf/1405.1067.pdf, page 162ff.
337  vector<string> convertNames(vector<string> names);
338 
339  void identifyVariationsFromLHAinit(map<string,LHAweight>* weights);
340 
341 protected:
342 
343  // Renormalization variations.
344  map<int,double> muRvars;
345 
346 };
347 
348 //==========================================================================
349 
350 // This is class to collect information on fragmentation weighting,
351 // and is in turn part of Info.
352 
354 
355 public:
356 
357  // Initialize the weights.
358  void init() override;
359 
360  int nWeightGroups() const {return externalGroupNames.size();}
361 
362  string getGroupName(int iGN) const {return iGN < 0 || iGN >= nWeightGroups()
363  ? "Null" : externalGroupNames[iGN];}
364 
365  // Return group weight.
366  double getGroupWeight(int iGW) const {
367  if (iGW < 0 || iGW >= nWeightGroups()) return 1.0;
368  double wgt(1.);
369  for (const int &iWgt : externalMap[iGW]) wgt *= getWeightsValue(iWgt);
370  return wgt;}
371 
372  // Functions to return processed weights to weight container, e.g. if
373  // weights should be combined before proceeding.
374  void collectWeightNames(vector<string>& outputNames) override;
375  void collectWeightValues(vector<double>& outputWeights,
376  double norm = 1.) override;
377 
378  // Vectors for weight group handling.
379  vector<map<vector<double>, int> > weightParms{};
380  vector<string> externalGroupNames{};
381  vector<vector<int> > externalMap{};
382 
383  // Factorization indices.
384  enum FactIndex{Z, Flav, PT};
385 
386 };
387 
388 //==========================================================================
389 
390 // This is a container class to collect all event generation weight
391 // information into a wrapper which is in turn is part of Info. In this
392 // way, we could avoid cluttering Info.
393 
395 
396 public:
397 
398  // Default constructor only ensures that members are initialized with
399  // sensible default values.
400  WeightContainer() : weightNominal(1.0), xsecIsInit(false) {}
401 
402  // The nominal Pythia weight, in pb for lha strategy 4 and -4
404  void setWeightNominal( double weightNow );
405  double collectWeightNominal();
406 
407  // First example of a weight subcategory.
408  WeightsLHEF weightsLHEF{};
409 
410  // Shower weights. SimpleShower one hardcoded and made default since
411  // Merging explicitly depends on it, but allow to point to a
412  // different weightsShower-derived object, eg for Vincia (with own
413  // merging).
414  WeightsShower* weightsShowerPtr{};
415  WeightsSimpleShower weightsSimpleShower{};
416 
417  // Merging weights.
418  WeightsMerging weightsMerging{};
419 
420  // Fragmentation weights.
421  WeightsFragmentation weightsFragmentation{};
422 
423  // Userhooks weights.
424  WeightsBase weightsUserHooks{};
425 
426  // Functions to retrieve information stored in the subcategory members.
427  int numberOfWeights();
428  double weightValueByIndex(int key = 0);
429  string weightNameByIndex(int key = 0);
430 
431  // Function to return the vector of weight values, combining all
432  // weights from all subcategories. Currently, only the nominal
433  // weight and LHEF weights are considered. Internal Pythia weights
434  // should also be included eventually.
435  vector<double> weightValueVector();
436 
437  // Function to return the vector of weight names, combining all names from
438  // all subcategories, cf. weightValueVector function.
439  vector<string> weightNameVector();
440 
441  // Reset all members to default stage.
442  void clear();
443 
444  // Reset total cross section estimate.
445  void clearTotal();
446 
447  // Init, for those classes that need it.
448  void init(bool doMerging);
449 
450  // Function to set Pointers in weight classes.
451  void initPtrs(Info* infoPtrIn);
452 
453  // Initialize the cross-section vector.
454  void initXsecVec();
455 
456  // Get cross-section vectors.
457  vector<double> getSampleXsec();
458  vector<double> getTotalXsec();
459  vector<double> getSampleXsecErr();
460  vector<double> getTotalXsecErr();
461 
462  // Accumulate cross section for all weights.
463  void accumulateXsec(double norm = 1.);
464 
465 private:
466 
467  // Pointers necessary for variation initialization.
468  Info* infoPtr{};
469 
470  // Suppress AUX_ weights.
471  bool doSuppressAUXweights{};
472 
473  // Vectors for cross-section.
474  vector<double> sigmaTotal, sigmaSample, errorTotal, errorSample;
475  bool xsecIsInit;
476 
477 };
478 
479 //==========================================================================
480 
481 } // end namespace Pythia8
482 
483 #endif // Pythia8_Weights_H
Z0 Z(f is quark or lepton).*/ void Sigma1ffbar2gmZZprime
Initialize process.
Definition: SigmaNewGaugeBosons.cc:110
double weightNominal
The nominal Pythia weight, in pb for lha strategy 4 and -4.
Definition: Weights.h:403
Purely virtual base class for shower weights.
Definition: Weights.h:144
virtual void bookVectors(vector< double > weights, vector< string > names)
Definition: Weights.h:53
virtual void reweightValueByIndex(int iPos, double val)
Functions to reweight weight values, by index or by name.
Definition: Weights.h:103
FactIndex
Factorization indices.
Definition: Weights.h:384
Definition: Info.h:45
Definition: Weights.h:394
vector< string > externalVariations
Vectors for weight group handling.
Definition: Weights.h:213
vector< double > weightValuesFirst
Data member for first order weight.
Definition: Weights.h:296
virtual void reweightValueByName(string name, double val)
Definition: Weights.h:107
double getWeightsValue(int iPos) const override
Modified weight getter to include first order weight.
Definition: Weights.h:257
Definition: Weights.h:35
virtual void initWeightGroups(bool=false)
Weight "groups" (combinations of one or more unique weights).
Definition: Weights.h:152
map< int, double > muRvars
Renormalization variations.
Definition: Weights.h:344
void bookWeight(string name, double defaultValue=1.)
Function to create a new, synchronized, pair of weight name and value.
Definition: Weights.h:85
void parse(string wvecKey, map< string, map< string, double > > &dct)
Parse a WVec of variations into a dictionary.
Definition: Weights.cc:43
Definition: Merging.h:33
double centralWeight
Central weight, needed for normalization, set from ProcessContainer.cc.
Definition: Weights.h:321
vector< string > getUniqueShowerVars()
Extract full list or subset that matches specific keys (e.g., FSR ones).
Definition: Weights.h:196
vector< string > uniqueShowerVars
Vectors for storing shower variatons and enhancement factors.
Definition: Weights.h:209
Definition: PartonLevel.h:45
double getGroupWeight(int iGW) const
Return group weight.
Definition: Weights.h:366
Definition: Weights.h:235
void setValueByIndex(int iPos, double val)
Functions to set values of weights.
Definition: Weights.h:95
virtual void init()
Initialize the weights.
Definition: Weights.h:44
bool isNLO
Boolean to memorize if LHEF weight needs to be applied (only for NLO).
Definition: Weights.h:303
Info * infoPtr
Pointers necessary for variation initialization.
Definition: Weights.h:136
virtual void collectWeightNames(vector< string > &outputNames)
Similar function to return processed weight names.
Definition: Weights.cc:34
string getWeightsName(int iPos) const
Definition: Weights.h:75
vector< double > weightValues
Weight values and names.
Definition: Weights.h:132
void setEnhancedTrial(double pTIn, double wtIn)
Memorize enhancement factor and pT of enhanced emission.
Definition: Weights.h:190
Definition: Weights.h:353
map< int, double > varPDFplus
Variations that must be known by TimeShower and Spaceshower.
Definition: Weights.h:206
Header for classes to set beam momentum and interaction vertex spread.
Definition: Analysis.h:20
virtual void collectWeightValues(vector< double > &outputWeights, double norm=1.)
WeightsBase class.
Definition: Weights.cc:24
void init(bool) override
Initialize weights (more can be booked at any time)
Definition: Weights.h:149
This shows a WeightsShower example implementation for SimpleShower.
Definition: Weights.h:163
virtual void clear()
Reset all internal values.
Definition: Weights.h:49
int findIndexOfName(string name)
Definition: Weights.h:115
map< int, int > muRVarLHEFindex
Corresponding vector with respective LHEF weight indices.
Definition: Weights.h:293
Definition: Weights.h:313
void setPtrs(Info *infoPtrIn)
Set the pointers.
Definition: Weights.h:124
double getWeightsValueP(int iPos) const
Also add getters for UNLOPS-P and -PC schemes.
Definition: Weights.h:260
Definition: History.h:116
WeightContainer()
Definition: Weights.h:400
vector< double > weightValuesP
Data members for UNLOPS-P and -PC.
Definition: Weights.h:299