PYTHIA  8.311
Basics.h
1 // Basics.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 // Header file for basic, often-used helper classes.
7 // RndmEngine: base class for external random number generators.
8 // Rndm: random number generator.
9 // Vec4: simple four-vectors.
10 // RotBstMatrix: matrices encoding rotations and boosts of Vec4 objects.
11 // Hist: simple one-dimensional histograms.
12 
13 #ifndef Pythia8_Basics_H
14 #define Pythia8_Basics_H
15 
16 #include "Pythia8/PythiaStdlib.h"
17 #include "Pythia8/SharedPointers.h"
18 
19 namespace Pythia8 {
20 
21 //==========================================================================
22 
23 // Forward reference to RotBstMatrix class; needed in Vec4 class.
24 class RotBstMatrix;
25 
26 //--------------------------------------------------------------------------
27 
28 // Vec4 class.
29 // This class implements four-vectors, in energy-momentum space.
30 // (But can equally well be used to hold space-time four-vectors.)
31 
32 class Vec4 {
33 
34 public:
35 
36  // Constructors.
37  Vec4(double xIn = 0., double yIn = 0., double zIn = 0., double tIn = 0.)
38  : xx(xIn), yy(yIn), zz(zIn), tt(tIn) { }
39  Vec4(const Vec4& v) : xx(v.xx), yy(v.yy), zz(v.zz), tt(v.tt) { }
40  Vec4& operator=(const Vec4& v) { if (this != &v) { xx = v.xx; yy = v.yy;
41  zz = v.zz; tt = v.tt; } return *this; }
42  Vec4& operator=(double value) { xx = value; yy = value; zz = value;
43  tt = value; return *this; }
44 
45  // Member functions for input.
46  void reset() {xx = 0.; yy = 0.; zz = 0.; tt = 0.;}
47  void p(double xIn, double yIn, double zIn, double tIn)
48  {xx = xIn; yy = yIn; zz = zIn; tt = tIn;}
49  void p(Vec4 pIn) {xx = pIn.xx; yy = pIn.yy; zz = pIn.zz; tt = pIn.tt;}
50  void px(double xIn) {xx = xIn;}
51  void py(double yIn) {yy = yIn;}
52  void pz(double zIn) {zz = zIn;}
53  void e(double tIn) {tt = tIn;}
54 
55  // Member functions for output.
56  double px() const {return xx;}
57  double py() const {return yy;}
58  double pz() const {return zz;}
59  double e() const {return tt;}
60  double& operator[](int i) {
61  switch(i) {
62  case 1: return xx;
63  case 2: return yy;
64  case 3: return zz;
65  default: return tt;
66  }
67  }
68  double mCalc() const {double temp = tt*tt - xx*xx - yy*yy - zz*zz;
69  return (temp >= 0.) ? sqrt(temp) : -sqrt(-temp);}
70  double m2Calc() const {return tt*tt - xx*xx - yy*yy - zz*zz;}
71  double pT() const {return sqrt(xx*xx + yy*yy);}
72  double pT2() const {return xx*xx + yy*yy;}
73  double pAbs() const {return sqrt(xx*xx + yy*yy + zz*zz);}
74  double pAbs2() const {return xx*xx + yy*yy + zz*zz;}
75  double eT() const {double temp = xx*xx + yy*yy;
76  return tt * sqrt( temp / (temp + zz*zz) );}
77  double eT2() const {double temp = xx*xx + yy*yy;
78  return tt*tt * temp / (temp + zz*zz);}
79  double theta() const {return atan2(sqrt(xx*xx + yy*yy), zz);}
80  double phi() const {return atan2(yy,xx);}
81  double thetaXZ() const {return atan2(xx,zz);}
82  double pPos() const {return tt + zz;}
83  double pNeg() const {return tt - zz;}
84  double rap() const {
85  double txyz = (tt > 0.) ? tt : sqrt(xx*xx + yy*yy + zz*zz);
86  if (zz >= txyz) return 20.;
87  if (zz <= -txyz) return -20.;
88  return 0.5 * log( (txyz + zz) / (txyz - zz) );}
89  double eta() const {double xyz = sqrt(xx*xx + yy*yy + zz*zz);
90  if (zz >= xyz) return 20.;
91  if (zz <= -xyz) return -20.;
92  return 0.5 * log( (xyz + zz) / (xyz - zz) );}
93 
94  // Member functions that perform operations.
95  void rescale3(double fac) {xx *= fac; yy *= fac; zz *= fac;}
96  void rescale4(double fac) {xx *= fac; yy *= fac; zz *= fac; tt *= fac;}
97  void flip3() {xx = -xx; yy = -yy; zz = -zz;}
98  void flip4() {xx = -xx; yy = -yy; zz = -zz; tt = -tt;}
99  void rot(double thetaIn, double phiIn);
100  void rotaxis(double phiIn, double nx, double ny, double nz);
101  void rotaxis(double phiIn, const Vec4& n);
102  void bst(double betaX, double betaY, double betaZ);
103  void bst(double betaX, double betaY, double betaZ, double gamma);
104  void bst(const Vec4& pIn);
105  void bst(const Vec4& pIn, double mIn);
106  void bstback(const Vec4& pIn);
107  void bstback(const Vec4& pIn, double mIn);
108  void rotbst(const RotBstMatrix& M);
109 
110  // Operator overloading with member functions
111  inline Vec4 operator-() const {Vec4 tmp; tmp.xx = -xx; tmp.yy = -yy;
112  tmp.zz = -zz; tmp.tt = -tt; return tmp;}
113  inline Vec4& operator+=(const Vec4& v) {xx += v.xx; yy += v.yy; zz += v.zz;
114  tt += v.tt; return *this;}
115  inline Vec4& operator-=(const Vec4& v) {xx -= v.xx; yy -= v.yy; zz -= v.zz;
116  tt -= v.tt; return *this;}
117  inline Vec4& operator*=(double f) {xx *= f; yy *= f; zz *= f;
118  tt *= f; return *this;}
119  inline Vec4& operator/=(double f) {xx /= f; yy /= f; zz /= f;
120  tt /= f; return *this;}
121  inline Vec4 operator+(const Vec4& v) const {
122  Vec4 tmp = *this; return tmp += v;}
123  inline Vec4 operator-(const Vec4& v) const {
124  Vec4 tmp = *this; return tmp -= v;}
125  inline Vec4 operator*(double f) const {
126  Vec4 tmp = *this; return tmp *= f;}
127  inline Vec4 operator/(double f) const {
128  Vec4 tmp = *this; return tmp /= f;}
129  inline double operator*(const Vec4& v) const {
130  return tt*v.tt - xx*v.xx - yy*v.yy - zz*v.zz;}
131 
132  // Operator overloading with friends.
133  friend Vec4 operator*(double f, const Vec4& v1);
134 
135  // Print a four-vector.
136  friend ostream& operator<<(ostream&, const Vec4& v) ;
137 
138  // Check if NaN, INF, or finite.
139  friend inline bool isnan(const Vec4 &v) {
140  return isnan(v.tt) || isnan(v.xx) || isnan(v.yy) || isnan(v.zz);}
141  friend inline bool isinf(const Vec4 &v) {
142  return isinf(v.tt) || isinf(v.xx) || isinf(v.yy) || isinf(v.zz);}
143  friend inline bool isfinite(const Vec4 &v) {
144  return isfinite(v.tt) && isfinite(v.xx) && isfinite(v.yy)
145  && isfinite(v.zz);}
146 
147  // Invariant mass and its square.
148  friend double m(const Vec4& v1);
149  friend double m(const Vec4& v1, const Vec4& v2);
150  friend double m2(const Vec4& v1);
151  friend double m2(const Vec4& v1, const Vec4& v2);
152  friend double m2(const Vec4& v1, const Vec4& v2, const Vec4& v3);
153  friend double m2(const Vec4& v1, const Vec4& v2, const Vec4& v3,
154  const Vec4& v4);
155 
156  // Scalar and cross product of 3-vector parts.
157  friend double dot3(const Vec4& v1, const Vec4& v2);
158  friend Vec4 cross3(const Vec4& v1, const Vec4& v2);
159 
160  // Cross-product of three 4-vectors ( p_i = epsilon_{iabc} p_a p_b p_c).
161  friend Vec4 cross4(const Vec4& a, const Vec4& b, const Vec4& c);
162 
163  // theta is polar angle between v1 and v2.
164  friend double theta(const Vec4& v1, const Vec4& v2);
165  friend double costheta(const Vec4& v1, const Vec4& v2);
166 
167  // phi is azimuthal angle between v1 and v2 around z axis.
168  friend double phi(const Vec4& v1, const Vec4& v2);
169  friend double cosphi(const Vec4& v1, const Vec4& v2);
170 
171  // phi is azimuthal angle between v1 and v2 around n axis.
172  friend double phi(const Vec4& v1, const Vec4& v2, const Vec4& n);
173  friend double cosphi(const Vec4& v1, const Vec4& v2, const Vec4& n);
174 
175  // R is distance in cylindrical (y/eta, phi) coordinates.
176  friend double RRapPhi(const Vec4& v1, const Vec4& v2);
177  friend double REtaPhi(const Vec4& v1, const Vec4& v2);
178 
179  // Shift four-momenta within pair from old to new masses.
180  friend bool pShift( Vec4& p1Move, Vec4& p2Move, double m1New, double m2New);
181 
182  // Create two vectors that are perpendicular to both input vectors.
183  friend pair<Vec4,Vec4> getTwoPerpendicular(const Vec4& v1, const Vec4& v2);
184 
185 private:
186 
187  // Constants: could only be changed in the code itself.
188  static const double TINY;
189 
190  // The four-vector data members.
191  double xx, yy, zz, tt;
192 
193 };
194 
195 //--------------------------------------------------------------------------
196 
197 // Namespace function declarations; friends of Vec4 class.
198 
199 // Implementation of operator overloading with friends.
200 inline Vec4 operator*(double f, const Vec4& v1)
201  {Vec4 v = v1; return v *= f;}
202 
203 // Invariant mass and its square.
204 double m(const Vec4& v1);
205 double m(const Vec4& v1, const Vec4& v2);
206 double m2(const Vec4& v1);
207 double m2(const Vec4& v1, const Vec4& v2);
208 double m2(const Vec4& v1, const Vec4& v2, const Vec4& v3);
209 double m2(const Vec4& v1, const Vec4& v2, const Vec4& v3,
210  const Vec4& v4);
211 
212 // Scalar and cross product of 3-vector parts.
213 double dot3(const Vec4& v1, const Vec4& v2);
214 Vec4 cross3(const Vec4& v1, const Vec4& v2);
215 
216 // Cross-product of three 4-vectors ( p_i = epsilon_{iabc} p_a p_b p_c).
217 Vec4 cross4(const Vec4& a, const Vec4& b, const Vec4& c);
218 
219 // theta is polar angle between v1 and v2.
220 double theta(const Vec4& v1, const Vec4& v2);
221 double costheta(const Vec4& v1, const Vec4& v2);
222 double costheta(double e1, double e2, double m1, double m2, double s12);
223 
224 // phi is azimuthal angle between v1 and v2 around z axis.
225 double phi(const Vec4& v1, const Vec4& v2);
226 double cosphi(const Vec4& v1, const Vec4& v2);
227 
228 // phi is azimuthal angle between v1 and v2 around n axis.
229 double phi(const Vec4& v1, const Vec4& v2, const Vec4& n);
230 double cosphi(const Vec4& v1, const Vec4& v2, const Vec4& n);
231 
232 // R is distance in cylindrical (y/eta, phi) coordinates.
233 double RRapPhi(const Vec4& v1, const Vec4& v2);
234 double REtaPhi(const Vec4& v1, const Vec4& v2);
235 
236 // Print a four-vector.
237 ostream& operator<<(ostream&, const Vec4& v) ;
238 
239 // Shift four-momenta within pair from old to new masses.
240 bool pShift( Vec4& p1Move, Vec4& p2Move, double m1New, double m2New);
241 
242 // Create two vectors that are perpendicular to both input vectors.
243 pair<Vec4,Vec4> getTwoPerpendicular(const Vec4& v1, const Vec4& v2);
244 
245 //==========================================================================
246 
247 // RotBstMatrix class.
248 // This class implements 4 * 4 matrices that encode an arbitrary combination
249 // of rotations and boosts, that can be applied to Vec4 four-vectors.
250 
252 
253 public:
254 
255  // Constructors.
256  RotBstMatrix() : M() {for (int i = 0; i < 4; ++i) {
257  for (int j = 0; j < 4; ++j) { M[i][j] = (i==j) ? 1. : 0.; } } }
258  RotBstMatrix(const RotBstMatrix& Min) : M() {
259  for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) {
260  M[i][j] = Min.M[i][j]; } } }
261  RotBstMatrix& operator=(const RotBstMatrix& Min) {if (this != &Min) {
262  for (int i = 0; i < 4; ++i) { for (int j = 0; j < 4; ++j) {
263  M[i][j] = Min.M[i][j]; } } } return *this; }
264 
265  // Member functions.
266  void rot(double = 0., double = 0.);
267  void rot(const Vec4& p);
268  void bst(double = 0., double = 0., double = 0.);
269  void bst(const Vec4&);
270  void bstback(const Vec4&);
271  void bst(const Vec4&, const Vec4&);
272  void toCMframe(const Vec4&, const Vec4&);
273  void fromCMframe(const Vec4&, const Vec4&, bool flip = false);
274  void toSameVframe(const Vec4&, const Vec4&);
275  void fromSameVframe(const Vec4&, const Vec4&);
276  void rotbst(const RotBstMatrix&);
277  void invert();
278  RotBstMatrix inverse() const { RotBstMatrix tmp = *this;
279  tmp.invert(); return tmp; }
280  void reset();
281 
282  // Return value of matrix element.
283  double value(int i, int j) { return M[i][j];}
284 
285  // Crude estimate deviation from unit matrix.
286  double deviation() const;
287 
288  // Print a transformation matrix.
289  friend ostream& operator<<(ostream&, const RotBstMatrix&) ;
290 
291  // Private members to be accessible from Vec4.
292  friend class Vec4;
293 
294  // Multiplication.
295  Vec4 operator*(Vec4 p) const { p.rotbst(*this); return p; }
296  RotBstMatrix operator*(RotBstMatrix R) const { R.rotbst(*this); return R; }
297 
298 private:
299 
300  // Constants: could only be changed in the code itself.
301  static const double TINY;
302 
303  // The rotation-and-boost matrix data members.
304  double M[4][4];
305 
306 };
307 
308 //--------------------------------------------------------------------------
309 
310 // Namespace function declaration; friend of RotBstMatrix class.
311 
312 // Print a transformation matrix.
313 ostream& operator<<(ostream&, const RotBstMatrix&) ;
314 
315 // Get a RotBstMatrix to rest frame of p.
316 inline RotBstMatrix toCMframe(const Vec4& p) {
317  RotBstMatrix tmp; tmp.bstback(p); return tmp; }
318 
319 // Get a RotBstMatrix from rest frame of p.
320 inline RotBstMatrix fromCMframe(const Vec4& p) {
321  RotBstMatrix tmp; tmp.bst(p); return tmp; }
322 
323 // Get a RotBstMatrix to rest frame of p1 and p2, where p1 is along
324 // the z-axis.
325 inline RotBstMatrix toCMframe(const Vec4& p1, const Vec4& p2) {
326  RotBstMatrix tmp; tmp.toCMframe(p1, p2); return tmp; }
327 
328 // Get a RotBstMatrix from rest frame of p1 and p2, where p1 is
329 // assumed by default to be along the z-axis. The flip option
330 // handles the case when p1 is along the negative z-axis.
331 inline RotBstMatrix fromCMframe(const Vec4& p1, const Vec4& p2,
332  bool flip = false) {
333  RotBstMatrix tmp; tmp.fromCMframe(p1, p2, flip); return tmp; }
334 
335 // Get a RotBstMatrix to rest frame of ptot where pz is along the
336 // z-axis and pxz is in the xz-plane with positive x.
337 inline RotBstMatrix toCMframe(const Vec4& ptot, const Vec4& pz,
338  const Vec4 & pxz) { RotBstMatrix tmp = toCMframe(ptot);
339  Vec4 pzp = tmp*pz; tmp.rot(0.0, -pzp.phi()); tmp.rot(-pzp.theta());
340  tmp.rot(0.0, -(tmp*pxz).phi()); return tmp; }
341 
342 // Get a RotBstMatrix from rest frame of ptot where pz is along the
343 // z-axis and pxz is in the xz-plane with positive x.
344 inline RotBstMatrix fromCMframe(const Vec4& ptot, const Vec4& pz,
345  const Vec4 & pxz) { return toCMframe(ptot, pz, pxz).inverse(); }
346 
347 //==========================================================================
348 
349 // RndmEngine is the base class for external random number generators.
350 // There is only one pure virtual method, that should do the generation.
351 
352 class RndmEngine {
353 
354 public:
355 
356  // Destructor.
357  virtual ~RndmEngine() {}
358 
359  // A virtual method, wherein the derived class method
360  // generates a random number uniformly distributed between 0 and 1.
361  virtual double flat() {return 1;}
362 
363 };
364 
365 //==========================================================================
366 
367 // RndmState class.
368 // This class describes the configuration of a Rndm object.
369 
370 struct RndmState {
371  int i97{}, j97{}, seed{0};
372  long sequence{0};
373  double u[97]{}, c{}, cd{}, cm{};
374 
375  // Test whether two random states would generate the same random sequence.
376  bool operator==(const RndmState& other) const;
377 };
378 
379 //==========================================================================
380 
381 // Rndm class.
382 // This class handles random number generation according to the
383 // Marsaglia-Zaman-Tsang algorithm.
384 
385 class Rndm {
386 
387 public:
388 
389  // Constructors.
390  Rndm() : initRndm(false), stateSave(), useExternalRndm(false) { }
391  Rndm(int seedIn) : initRndm(false), stateSave(), useExternalRndm(false) {
392  init(seedIn);}
393 
394  // Possibility to pass in pointer for external random number generation.
395  bool rndmEnginePtr( RndmEnginePtr rndmEngPtrIn);
396 
397  // Initialize, normally at construction or in first call.
398  void init(int seedIn = 0) ;
399 
400  // Generate next random number uniformly between 0 and 1.
401  double flat() ;
402 
403  // Generate random numbers according to exp(-x).
404  double exp() ;
405 
406  // Generate random numbers according to x * exp(-x).
407  double xexp() { return -log(flat() * flat()) ;}
408 
409  // Generate random numbers according to exp(-x^2/2).
410  double gauss() {return sqrt(-2. * log(flat())) * cos(M_PI * flat());}
411 
412  // Generate two random numbers according to exp(-x^2/2-y^2/2).
413  pair<double, double> gauss2() {double r = sqrt(-2. * log(flat()));
414  double phi = 2. * M_PI * flat();
415  return { r * sin(phi), r * cos(phi) };}
416 
417  // Generate a random number according to a Gamma-distribution.
418  double gamma(double k0, double r0);
419 
420  // Generate two random vectors according to the phase space distribution
421  pair<Vec4, Vec4> phaseSpace2(double eCM, double m1, double m2);
422 
423  // Pick one option among vector of (positive) probabilities.
424  int pick(const vector<double>& prob) ;
425 
426  // Randomly shuffle a vector, standard Fisher-Yates algorithm.
427  template<typename T> void shuffle(vector<T>& vec);
428 
429  // Save or read current state to or from a binary file.
430  bool dumpState(string fileName);
431  bool readState(string fileName);
432 
433  // Get or set the state of the random number generator.
434  RndmState getState() const {return stateSave;}
435  void setState(const RndmState& state) {stateSave = state;}
436 
437  // The default seed, i.e. the Marsaglia-Zaman random number sequence.
438  static constexpr int DEFAULTSEED = 19780503;
439 
440 #ifdef RNGDEBUG
441  // Random number methods used for debugging only.
442  double flatDebug(string loc, string file, int line);
443  double xexpDebug(string loc, string file, int line);
444  double gaussDebug(string loc, string file, int line);
445  pair<double, double> gauss2Debug(string loc, string file, int line);
446  double gammaDebug(string loc, string file, int line, double k0, double r0);
447  pair<Vec4, Vec4> phaseSpace2Debug(string loc, string file, int line,
448  double eCM, double m1, double m2);
449 
450  // Static members for debugging to print call file location or filter.
451  static bool debugNow, debugLocation, debugIndex;
452  static int debugPrecision, debugCall;
453  static set<string> debugStarts, debugEnds, debugContains, debugMatches;
454 #endif
455 
456 private:
457 
458  // State of the random number generator.
459  bool initRndm;
460  RndmState stateSave;
461 
462  // Pointer for external random number generation.
463  bool useExternalRndm;
464  RndmEnginePtr rndmEngPtr{};
465 
466 };
467 
468 //==========================================================================
469 
470 // Hist class.
471 // This class handles a single histogram at a time.
472 
473 class Hist {
474 
475 public:
476 
477  // Constructors, including copy constructors.
478  Hist() : titleSave(""), nBin(), nFill(), nNonFinite(), xMin(),
479  xMax(), linX(), doStats(), dx(), under(), inside(), over(), sumxNw()
480  { }
481  Hist(string titleIn, int nBinIn = 100, double xMinIn = 0.,
482  double xMaxIn = 1., bool logXIn = false, bool doStatsIn = false) :
483  nBin(), nFill(), nNonFinite(), xMin(), xMax(), linX(), doStats(), dx(),
484  under(), inside(), over(), sumxNw()
485  { book(titleIn, nBinIn, xMinIn, xMaxIn, logXIn, doStatsIn); }
486  Hist(const Hist& h)
487  : titleSave(h.titleSave), nBin(h.nBin), nFill(h.nFill),
488  nNonFinite(h.nNonFinite), xMin(h.xMin), xMax(h.xMax), linX(h.linX),
489  doStats(h.doStats), dx(h.dx), under(h.under), inside(h.inside),
490  over(h.over), res(h.res), res2(h.res2), sumxNw() {
491  for (int i = 0; i < nMoments; ++i) sumxNw[i] = h.sumxNw[i];
492  }
493  Hist(string titleIn, const Hist& h)
494  : titleSave(titleIn), nBin(h.nBin), nFill(h.nFill),
495  nNonFinite(h.nNonFinite), xMin(h.xMin), xMax(h.xMax), linX(h.linX),
496  doStats(h.doStats), dx(h.dx), under(h.under), inside(h.inside),
497  over(h.over), res(h.res), res2(h.res2), sumxNw() {
498  for (int i = 0; i < nMoments; ++i) sumxNw[i] = h.sumxNw[i];
499  }
500  Hist& operator=(const Hist& h) { if(this != &h) {
501  nBin = h.nBin; nFill = h.nFill; nNonFinite = h.nNonFinite; xMin = h.xMin;
502  xMax = h.xMax; linX = h.linX; doStats = h.doStats; dx = h.dx;
503  under = h.under; inside = h.inside; over = h.over;
504  for (int i = 0; i < nMoments; ++i) sumxNw[i] = h.sumxNw[i];
505  res = h.res; res2 = h.res2; } return *this; }
506 
507  // Create a histogram that is the plot of the given function.
508  static Hist plotFunc(function<double(double)> f, string titleIn,
509  int nBinIn, double xMinIn, double xMaxIn, bool logXIn = false);
510 
511  // Book a histogram.
512  void book(string titleIn = " ", int nBinIn = 100, double xMinIn = 0.,
513  double xMaxIn = 1., bool logXIn = false, bool doStatsIn = false) ;
514 
515  // Set title of a histogram.
516  void title(string titleIn = " ") {titleSave = titleIn; }
517 
518  // Reset bin contents.
519  void null() ;
520 
521  // Fill bin with weight.
522  void fill(double x, double w = 1.) ;
523 
524  // Print a histogram with overloaded << operator.
525  friend ostream& operator<<(ostream& os, const Hist& h) ;
526 
527  // Print histogram contents as a table (e.g. for Gnuplot, Rivet or Pyplot),
528  // optionally with statistical errors.
529  void table(ostream& os = cout, bool printOverUnder = false,
530  bool xMidBin = true, bool printError = false) const ;
531  void table(string fileName, bool printOverUnder = false,
532  bool xMidBin = true, bool printError = false) const {
533  ofstream streamName(fileName.c_str());
534  table(streamName, printOverUnder, xMidBin, printError);}
535  void rivetTable(ostream& os = cout, bool printError = true) const ;
536  void rivetTable(string fileName, bool printError = true) const {
537  ofstream streamName(fileName.c_str()); rivetTable(streamName, printError);}
538  void pyplotTable(ostream& os = cout, bool isHist = true,
539  bool printError = false) const ;
540  void pyplotTable(string fileName, bool isHist = true,
541  bool printError = false) const {ofstream streamName(fileName.c_str());
542  pyplotTable(streamName, isHist, printError);}
543 
544  // Fill contents of a two-column (x,y) table, e.g. written by table() above.
545  void fillTable(istream& is = cin);
546  void fillTable(string fileName) { ifstream streamName(fileName.c_str());
547  fillTable(streamName);}
548 
549  // Print a table out of two histograms with same x axis (no errors printed).
550  friend void table(const Hist& h1, const Hist& h2, ostream& os,
551  bool printOverUnder, bool xMidBin) ;
552  friend void table(const Hist& h1, const Hist& h2, string fileName,
553  bool printOverUnder, bool xMidBin) ;
554 
555  // Return title and size of histogram. Also if logarithmic x scale.
556  string getTitle() const {return titleSave;}
557  int getBinNumber() const {return nBin;}
558  int getNonFinite() const {return nNonFinite;}
559  bool getLinX() const {return linX;}
560 
561  // Return min and max in x and y directions.
562  double getXMin() const {return xMin;}
563  double getXMax() const {return xMax;}
564  double getYMin() const { if (nBin == 0) return 0.;
565  double yMin = res[0];
566  for (int ix = 1; ix < nBin; ++ix)
567  if (res[ix] < yMin ) yMin = res[ix];
568  return yMin;}
569  double getYMax() const { if (nBin == 0) return 0.;
570  double yMax = res[0];
571  for (int ix = 1; ix < nBin; ++ix)
572  if (res[ix] > yMax ) yMax = res[ix];
573  return yMax;}
574  double getYAbsMin() const { double yAbsMin = 1e20; double yAbs;
575  for (int ix = 0; ix < nBin; ++ix) { yAbs = abs(res[ix]);
576  if (yAbs > 1e-20 && yAbs < yAbsMin) yAbsMin = yAbs; }
577  return yAbsMin;}
578 
579  // Return <X> and error on <X>, unbinned from saved weight sums (default)
580  // or directly from the histogram bins (unbinned = false). In the latter
581  // case, the error estimate includes the difference between the binned and
582  // unbinned value summed in quadrature with the statistical error, as a
583  // measure of bin granularity error.
584  double getXMean(bool unbinned=true) const;
585  double getXMeanErr(bool unbinned=true) const;
586 
587  // Return Median in X and its statistical error, ignoring underflow and
588  // overflow (default) or including them (includeOverUnder = true). By
589  // default, error includes granularity estimate obtained by comparing binned
590  // vs unbinned mean value, but this can be switched off (unbinned = false).
591  double getXMedian(bool includeOverUnder=false) const;
592  double getXMedianErr(bool unbinned=true) const;
593 
594  // Return average <Y> value.
595  double getYMean() const { return inside / nFill; }
596 
597  // Return RMS and equivalent n'th roots of n'th moments about the mean,
598  // and their error estimates. Up to n = 6, both unbinned and binned moments
599  // can be calculated. For n >= 7, and for all error estimates, only
600  // binned values are available. Note that (unlike ROOT), the error estimates
601  // do not assume normal distributions.
602  // RMN(2) = RMS is the standard root-mean-square deviation from the mean.
603  // RMN(3) is the cube root of the mean-cube deviation,
604  // cbrt(<(x - <x>)^3>). It is sensitive to single-sided tails,
605  // as are characteristic of many particle-physics distributions.
606  // RMN(4) adds sensitivity to double-sided long tails (eg BW vs
607  // Gaussian), and further sensitivity to long single-sided ones.
608  // Etc.
609  double getXRMN(int n=2, bool unbinned=true) const;
610  double getXRMS(bool unbinned=true) const {return getXRMN(2, unbinned);}
611 
612  double getXRMNErr(int n=2, bool unbinned=true) const;
613  double getXRMSErr(bool unbinned=true) const {
614  return getXRMNErr(2, unbinned);}
615 
616  // Return content of specific bin: 0 gives underflow and nBin+1 overflow.
617  double getBinContent(int iBin) const;
618 
619  // Return the lower edge of the bin.
620  double getBinEdge(int iBin) const;
621 
622  // Return the width of the bin.
623  double getBinWidth(int iBin=1) const;
624 
625  // Return bin contents.
626  vector<double> getBinContents() const;
627 
628  // Return bin edges.
629  vector<double> getBinEdges() const;
630 
631  // Return number of entries.
632  int getEntries(bool alsoNonFinite = true) const {
633  return alsoNonFinite ? nNonFinite + nFill : nFill; }
634 
635  // Return sum of weights.
636  double getWeightSum(bool alsoOverUnder = true) const {
637  return alsoOverUnder ? inside + over + under : inside; }
638 
639  // Return effective entries (for weighted histograms = number
640  // of equivalent unweighted events for same statistical power).
641  double getNEffective() const {
642  double sumw2 = 0.;
643  for (int ix = 0; ix < nBin; ++ix) sumw2 += res2[ix];
644  if (sumw2 <= Hist::TINY) return 0.;
645  else return pow2(sumxNw[0]) / sumw2;
646  }
647 
648  // Check whether another histogram has same size and limits.
649  bool sameSize(const Hist& h) const ;
650 
651  // Take an arbitrary function of bin contents.
652  void takeFunc(function<double(double)> func);
653 
654  // Take logarithm (base 10 or e) of bin contents.
655  void takeLog(bool tenLog = true);
656 
657  // Take square root of bin contents.
658  void takeSqrt();
659 
660  // Normalize sum of bin contents to value, with or without overflow bins.
661  void normalize(double f = 1, bool overflow = true) ;
662 
663  // Normalize sum of bin areas to value, with or without overflow bins.
664  void normalizeIntegral(double f = 1, bool overflow = true);
665 
666  // Scale each bin content by 1 / (wtSum * bin width).
667  void normalizeSpectrum(double wtSum);
668 
669  // Operator overloading with member functions
670  Hist& operator+=(const Hist& h) ;
671  Hist& operator-=(const Hist& h) ;
672  Hist& operator*=(const Hist& h) ;
673  Hist& operator/=(const Hist& h) ;
674  Hist& operator+=(double f) ;
675  Hist& operator-=(double f) ;
676  Hist& operator*=(double f) ;
677  Hist& operator/=(double f) ;
678  Hist operator+(double f) const;
679  Hist operator+(const Hist& h2) const;
680  Hist operator-(double f) const;
681  Hist operator-(const Hist& h2) const;
682  Hist operator*(double f) const;
683  Hist operator*(const Hist& h2) const;
684  Hist operator/(double f) const;
685  Hist operator/(const Hist& h2) const;
686 
687  // Operator overloading with friends
688  friend Hist operator+(double f, const Hist& h1);
689  friend Hist operator-(double f, const Hist& h1);
690  friend Hist operator*(double f, const Hist& h1);
691  friend Hist operator/(double f, const Hist& h1);
692 
693 private:
694 
695  // Constants: could only be changed in the code itself.
696  static const int NBINMAX, NCOLMAX, NLINES;
697  static const double TOLERANCE, TINY, LARGE, SMALLFRAC, DYAC[];
698  static const char NUMBER[];
699 
700  // Properties and contents of a histogram.
701  string titleSave;
702  int nBin, nFill, nNonFinite;
703  double xMin, xMax;
704  bool linX, doStats;
705  double dx, under, inside, over;
706  vector<double> res, res2;
707 
708  // Sum x^N w, for different powers N, for calculation of unbinned moments.
709  static constexpr int nMoments = 7;
710  double sumxNw[nMoments];
711 
712 };
713 
714 //--------------------------------------------------------------------------
715 
716 // Namespace function declarations; friends of Hist class.
717 
718 // Print a histogram with overloaded << operator.
719 ostream& operator<<(ostream& os, const Hist& h) ;
720 
721 // Print a table out of two histograms with same x axis.
722 void table(const Hist& h1, const Hist& h2, ostream& os = cout,
723  bool printOverUnder = false, bool xMidBin = true) ;
724 void table(const Hist& h1, const Hist& h2, string fileName,
725  bool printOverUnder = false, bool xMidBin = true) ;
726 
727 // Operator overloading with friends
728 Hist operator+(double f, const Hist& h1);
729 Hist operator-(double f, const Hist& h1);
730 Hist operator*(double f, const Hist& h1);
731 Hist operator/(double f, const Hist& h1);
732 
733 //==========================================================================
734 
735 // HistPlot class.
736 // Writes a Python program that can generate PDF plots from Hist histograms.
737 
738 class HistPlot {
739 
740 public:
741 
742  // Constructor requires name of Python program (and adds .py).
743  HistPlot(string pythonName, bool useLegacyIn = false)
744  : nFrame(), nTable(), useLegacy(useLegacyIn) {
745  toPython.open( (pythonName + ".py").c_str() );
746  toPython << "from matplotlib import pyplot as plt" << endl
747  << "from matplotlib.backends.backend_pdf import PdfPages" << endl;
748  nPDF = 0; }
749 
750  // Destructor should do final close.
751  ~HistPlot() { toPython << "pp.close()" << endl; }
752 
753  // New plot frame, with title, x and y labels, x and y sizes..
754  void frame( string frameIn, string titleIn = "", string xLabIn = "",
755  string yLabIn = "", double xSizeIn = 8., double ySizeIn = 6.) {
756  framePrevious = frameName; frameName = frameIn; title = titleIn;
757  xLabel = xLabIn; yLabel = yLabIn; xSize = xSizeIn; ySize = ySizeIn;
758  histos.clear(); styles.clear(); legends.clear(); files.clear();
759  fileStyles.clear(); fileLegends.clear(); filexyerr.clear();}
760 
761  // Add a histogram to the current plot, with optional style and legend.
762  void add( const Hist& histIn, string styleIn = "h",
763  string legendIn = "void") {
764  if (histIn.getBinNumber() == 0) {
765  cout << " Error: histogram is not booked" << endl;
766  return;
767  }
768  histos.push_back(histIn);
769  styles.push_back(styleIn); legends.push_back(legendIn); }
770 
771  // Add a file of (x, y) values not from a histogram, e.g. data points.
772  void addFile( string fileIn, string styleIn = "o",
773  string legendIn = "void", string xyerrIn="") { files.push_back(fileIn);
774  fileStyles.push_back(styleIn); fileLegends.push_back(legendIn);
775  filexyerr.push_back(xyerrIn);}
776 
777  // Plot a frame given the information from the new and add calls.
778  void plot( bool logY = false, bool logX = false, bool userBorders = false);
779  void plot( double xMinUserIn, double xMaxUserIn, double yMinUserIn,
780  double yMaxUserIn, bool logY = false, bool logX = false) {
781  xMinUser = xMinUserIn; xMaxUser = xMaxUserIn; yMinUser = yMinUserIn;
782  yMaxUser = yMaxUserIn; plot( logY, logX, true);}
783 
784  // Omnibus single call when only one histogram in the frame.
785  void plotFrame( string frameIn, const Hist& histIn, string titleIn = "",
786  string xLabIn = "", string yLabIn = "", string styleIn = "h",
787  string legendIn = "void", bool logY = false) {
788  frame( frameIn, titleIn, xLabIn, yLabIn);
789  add( histIn, styleIn, legendIn); plot( logY); }
790 
791 private:
792 
793  // Initialization code.
794  void init( string pythonName);
795 
796  // Stored quantities.
797  ofstream toPython;
798  int nPDF, nFrame, nTable;
799  double xSize, ySize, xMinUser, xMaxUser, yMinUser, yMaxUser;
800  string frameName, framePrevious, title, xLabel, yLabel, fileName, tmpFig;
801  vector<Hist> histos;
802  vector<string> styles, legends, files, fileStyles, fileLegends, filexyerr;
803 
804  // If true, use old linthreshy matplotlib parameter (removed in 3.5.0)
805  bool useLegacy;
806 
807 };
808 
809 //==========================================================================
810 
811 // Methods used for debugging random number sequences.
812 
813 #ifdef RNGDEBUG
814 #define flat() flatDebug(__METHOD_NAME__, __FILE__, __LINE__)
815 #define xexp() xexpDebug(__METHOD_NAME__, __FILE__, __LINE__)
816 #define gauss() gaussDebug(__METHOD_NAME__, __FILE__, __LINE__)
817 #define gamma(...) gammaDebug(__METHOD_NAME__, __FILE__, __LINE__, __VA_ARGS__)
818 #define phaseSpace2(...) phaseSpace2Debug(__METHOD_NAME__, __FILE__, __LINE__,\
819  __VA_ARGS__)
820 #endif
821 
822 //==========================================================================
823 
824 // Randomly shuffle a vector, standard Fisher-Yates algorithm.
825 // This must be defined after possible RNG debugging.
826 
827 template<typename T> void Rndm::shuffle(vector<T>& vec) {
828  for (int i = vec.size() - 1; i > 0; --i)
829  swap(vec[i], vec[floor(flat() * (i + 1))]);
830 }
831 
832 //==========================================================================
833 
834 } // end namespace Pythia8
835 
836 #endif // Pythia8_Basics_H
RndmState getState() const
Get or set the state of the random number generator.
Definition: Basics.h:434
double px() const
Member functions for output.
Definition: Basics.h:56
constexpr double pow2(const double &x)
Powers of small integers - for balance speed/code clarity.
Definition: PythiaStdlib.h:182
double value(int i, int j)
Return value of matrix element.
Definition: Basics.h:283
pair< double, double > gauss2()
Generate two random numbers according to exp(-x^2/2-y^2/2).
Definition: Basics.h:413
friend double m2(const Vec4 &v1)
The squared invariant mass of one or more four-vectors.
Definition: Basics.cc:586
void rot(double=0., double=0.)
Member functions.
Definition: Basics.cc:823
Hist()
Constructors, including copy constructors.
Definition: Basics.h:478
void bstback(const Vec4 &pIn)
Boost given by a Vec4 p; boost in opposite direction.
Definition: Basics.cc:509
void invert()
Invert the rotation and boost.
Definition: Basics.cc:1042
void rotbst(const RotBstMatrix &)
Combine existing rotation/boost matrix with another one.
Definition: Basics.cc:1027
void rescale3(double fac)
Member functions that perform operations.
Definition: Basics.h:95
void frame(string frameIn, string titleIn="", string xLabIn="", string yLabIn="", double xSizeIn=8., double ySizeIn=6.)
New plot frame, with title, x and y labels, x and y sizes..
Definition: Basics.h:754
friend bool isnan(const Vec4 &v)
Check if NaN, INF, or finite.
Definition: Basics.h:139
Vec4 operator*(double f, const Vec4 &v1)
Namespace function declarations; friends of Vec4 class.
Definition: Basics.h:200
void rotaxis(double phiIn, double nx, double ny, double nz)
Azimuthal rotation phi around an arbitrary axis (nz, ny, nz).
Definition: Basics.cc:387
RotBstMatrix()
Constructors.
Definition: Basics.h:256
RotBstMatrix toCMframe(const Vec4 &p)
Get a RotBstMatrix to rest frame of p.
Definition: Basics.h:316
void title(string titleIn=" ")
Set title of a histogram.
Definition: Basics.h:516
void addFile(string fileIn, string styleIn="o", string legendIn="void", string xyerrIn="")
Add a file of (x, y) values not from a histogram, e.g. data points.
Definition: Basics.h:772
Vec4 operator*(Vec4 p) const
Multiplication.
Definition: Basics.h:295
void rotbst(const RotBstMatrix &M)
Arbitrary combination of rotations and boosts defined by 4 * 4 matrix.
Definition: Basics.cc:551
virtual ~RndmEngine()
Destructor.
Definition: Basics.h:357
RotBstMatrix fromCMframe(const Vec4 &p)
Get a RotBstMatrix from rest frame of p.
Definition: Basics.h:320
void bst(double=0., double=0., double=0.)
Boost with velocity vector (betaX, betaY, betaZ).
Definition: Basics.cc:865
void plotFrame(string frameIn, const Hist &histIn, string titleIn="", string xLabIn="", string yLabIn="", string styleIn="h", string legendIn="void", bool logY=false)
Omnibus single call when only one histogram in the frame.
Definition: Basics.h:785
const double DYAC[]
Constants for printout: fixed steps on y scale; filling characters.
Definition: Basics.cc:1118
friend double costheta(const Vec4 &v1, const Vec4 &v2)
Cosine of the opening angle between two three-vectors.
Definition: Basics.cc:655
void bstback(const Vec4 &)
Boost so vector originally with same velocity as p is brought to rest.
Definition: Basics.cc:904
Rndm()
Constructors.
Definition: Basics.h:390
Definition: Basics.h:385
void rot(double thetaIn, double phiIn)
Rotation (simple).
Definition: Basics.cc:368
double getNEffective() const
Definition: Basics.h:641
friend ostream & operator<<(ostream &, const Vec4 &v)
Print a four-vector.
Definition: Basics.cc:565
bool operator==(const DireTimesEnd &dip1, const DireTimesEnd &dip2)
The DireTimesEnd class.
Definition: DireTimes.cc:19
friend double m(const Vec4 &v1)
Invariant mass and its square.
Definition: Basics.cc:576
friend Vec4 cross3(const Vec4 &v1, const Vec4 &v2)
The cross product of two three-vectors.
Definition: Basics.cc:614
string getTitle() const
Return title and size of histogram. Also if logarithmic x scale.
Definition: Basics.h:556
A derived class for nuclear PDFs. Needs a pointer for (free) proton PDFs.
Definition: PartonDistributions.h:1060
Vec4(double xIn=0., double yIn=0., double zIn=0., double tIn=0.)
Constructors.
Definition: Basics.h:37
friend bool pShift(Vec4 &p1Move, Vec4 &p2Move, double m1New, double m2New)
Shift four-momenta within pair from old to new masses.
Definition: Basics.cc:757
double getYMean() const
Return average <Y> value.
Definition: Basics.h:595
friend double dot3(const Vec4 &v1, const Vec4 &v2)
Scalar and cross product of 3-vector parts.
Definition: Basics.cc:606
~HistPlot()
Destructor should do final close.
Definition: Basics.h:751
int getEntries(bool alsoNonFinite=true) const
Return number of entries.
Definition: Basics.h:632
friend Vec4 cross4(const Vec4 &a, const Vec4 &b, const Vec4 &c)
Cross-product of three 4-vectors ( p_i = epsilon_{iabc} p_a p_b p_c).
Definition: Basics.cc:626
void table(const Hist &h1, const Hist &h2, ostream &os=cout, bool printOverUnder=false, bool xMidBin=true)
Print a table out of two histograms with same x axis.
Definition: Basics.cc:1581
void bst(double betaX, double betaY, double betaZ)
Boost (simple).
Definition: Basics.cc:434
Definition: Basics.h:352
Definition: Basics.h:473
void add(const Hist &histIn, string styleIn="h", string legendIn="void")
Add a histogram to the current plot, with optional style and legend.
Definition: Basics.h:762
Definition: Basics.h:251
Definition: Basics.h:738
Definition: Basics.h:370
friend double cosphi(const Vec4 &v1, const Vec4 &v2)
Cosine of the azimuthal angle between two three-vectors.
Definition: Basics.cc:685
virtual double flat()
Definition: Basics.h:361
double gauss()
Generate random numbers according to exp(-x^2/2).
Definition: Basics.h:410
friend double RRapPhi(const Vec4 &v1, const Vec4 &v2)
R is distance in cylindrical (y/eta, phi) coordinates.
Definition: Basics.cc:734
friend pair< Vec4, Vec4 > getTwoPerpendicular(const Vec4 &v1, const Vec4 &v2)
Create two vectors that are perpendicular to both input vectors.
Definition: Basics.cc:785
HistPlot(string pythonName, bool useLegacyIn=false)
Constructor requires name of Python program (and adds .py).
Definition: Basics.h:743
void shuffle(vector< T > &vec)
Randomly shuffle a vector, standard Fisher-Yates algorithm.
Definition: Basics.h:827
Header for classes to set beam momentum and interaction vertex spread.
Definition: Analysis.h:20
void toCMframe(const Vec4 &, const Vec4 &)
Definition: Basics.cc:930
friend double REtaPhi(const Vec4 &v1, const Vec4 &v2)
Distance in cylindrical (eta, phi) coordinates.
Definition: Basics.cc:745
Hist operator+(double f, const Hist &h1)
Operator overloading with friends.
Definition: Basics.cc:2213
void reset()
Member functions for input.
Definition: Basics.h:46
Vec4 operator-() const
Operator overloading with member functions.
Definition: Basics.h:111
Definition: Basics.h:32
double getWeightSum(bool alsoOverUnder=true) const
Return sum of weights.
Definition: Basics.h:636
double xexp()
Generate random numbers according to x * exp(-x).
Definition: Basics.h:407
double getXMin() const
Return min and max in x and y directions.
Definition: Basics.h:562
void fromCMframe(const Vec4 &, const Vec4 &, bool flip=false)
Definition: Basics.cc:949