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