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