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