FairShip
Loading...
Searching...
No Matches
HNLPythia8Generator.cxx
Go to the documentation of this file.
1// SPDX-License-Identifier: LGPL-3.0-or-later
2// SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP
3// Collaboration
4
6
7#include <cmath>
8
9#include "BeamSmearingUtils.h"
10#include "FairPrimaryGenerator.h"
11#include "PythiaUnits.h"
12#include "TDatabasePDG.h" // for TDatabasePDG
13#include "TMath.h"
14#include "TROOT.h"
15#include "TSystem.h"
18// Lengths inside this generator are in Pythia8 units (mm); the setters convert
19// from cm and AddTrack gets cm.
20constexpr Double_t kPythiaMm = 1.;
22const Bool_t debug = false;
23// using namespace Pythia8;
24
25// ----- Default constructor -------------------------------------------
27 fId = 2212; // proton
28 fMom = 400; // proton
29 fHNL = 9900015; // HNL pdg code
30 fLmin = 5000. * kPythiaCm; // min decay length along the HNL flight direction
31 // (50 m, stored in Pythia units, mm)
32 fLmax = 12000. * kPythiaCm; // max decay length along the HNL flight
33 // direction (120 m, stored in Pythia units, mm)
34 fFDs = 7.7 / 10.4; // correction for Pythia6 to match measured Ds
35 // production.
36 // TODO(olantwin, 2026-08-12): cite source of 7.7/10.4
37 fsmearBeam = 8 * kPythiaMm; // default value for smearing beam (8 mm)
38 fPaintBeam = 5 * kPythiaCm; // default value for painting beam (5 cm)
39 fInputFile = nullptr;
40 fnRetries = 0;
41 fShipEventNr = 0;
42 fPythia = new Pythia8::Pythia();
43}
44// -------------------------------------------------------------------------
45
46// ----- Default constructor -------------------------------------------
48 if (debug) {
49 List(9900015);
50 }
51 if (fUseRandom1) fRandomEngine = std::make_shared<PyTr1Rng>();
52 if (fUseRandom3) fRandomEngine = std::make_shared<PyTr3Rng>();
53 fPythia->setRndmEnginePtr(fRandomEngine);
54 fn = 0;
55 if (fextFile) {
56 if (firstEvent < 0) {
57 LOG(error) << "HNLPythia8Generator: firstEvent must be >= 0, got "
58 << firstEvent;
59 return kFALSE;
60 }
61 fInputFile = TFile::Open(fextFile->c_str(), "READ");
62 LOG(info) << "Open external file with charm or beauty hadrons: "
63 << *fextFile;
64 if (!fInputFile) {
65 LOG(error) << "HNLPythia8Generator: error opening input file "
66 << *fextFile;
67 delete fInputFile;
68 fInputFile = nullptr;
69 return kFALSE;
70 }
71
72 fTree = fInputFile->Get<TTree>("pythia6");
73 if (!fTree) {
74 LOG(error) << "HNLPythia8Generator: cannot find tree pythia6 in file "
75 << *fextFile;
76 fInputFile->Close();
77 delete fInputFile;
78 fInputFile = nullptr;
79 return kFALSE;
80 }
81 fNevents = fTree->GetEntries();
82 if (firstEvent >= fNevents) {
83 LOG(error) << "HNLPythia8Generator: firstEvent " << firstEvent
84 << " is out of range for " << fNevents << " entries";
85 fInputFile->Close();
86 delete fInputFile;
87 fInputFile = nullptr;
88 fTree = nullptr;
89 return kFALSE;
90 }
91 fn = firstEvent;
92 bool ok = true;
93 ok &= (fTree->SetBranchAddress("id", &hid) >= 0);
94 ok &= (fTree->SetBranchAddress("px", &hpx) >= 0);
95 ok &= (fTree->SetBranchAddress("py", &hpy) >= 0);
96 ok &= (fTree->SetBranchAddress("pz", &hpz) >= 0);
97 ok &= (fTree->SetBranchAddress("E", &hE) >= 0);
98 ok &= (fTree->SetBranchAddress("M", &hM) >= 0);
99 ok &= (fTree->SetBranchAddress("mid", &mid) >= 0);
100 ok &= (fTree->SetBranchAddress("mpx", &mpx) >= 0);
101 ok &= (fTree->SetBranchAddress("mpy", &mpy) >= 0);
102 ok &= (fTree->SetBranchAddress("mpz", &mpz) >= 0);
103 ok &= (fTree->SetBranchAddress("mE", &mE) >= 0);
104 if (!ok) {
105 LOG(error) << "HNLPythia8Generator: failed to bind one or more required "
106 "branches";
107 fInputFile->Close();
108 delete fInputFile;
109 fInputFile = nullptr;
110 fTree = nullptr;
111 return kFALSE;
112 }
113 } else {
114 LOG(debug) << "Beam Momentum " << fMom;
115 fPythia->settings.mode("Beams:idA", fId);
116 fPythia->settings.mode("Beams:idB", 2212);
117 fPythia->settings.mode("Beams:frameType", 2);
118 fPythia->settings.parm("Beams:eA", fMom); // codespell:ignore parm
119 fPythia->settings.parm("Beams:eB", 0.); // codespell:ignore parm
120 }
121 TDatabasePDG* pdgBase = TDatabasePDG::Instance();
122 auto* hnl = pdgBase->GetParticle(fHNL);
123 if (!hnl) {
124 LOG(error) << "HNLPythia8Generator: PDG " << fHNL
125 << " not found in ROOT database";
126 if (fInputFile) {
127 fInputFile->Close();
128 delete fInputFile;
129 fInputFile = nullptr;
130 fTree = nullptr;
131 }
132 return kFALSE;
133 }
134 Double_t root_ctau = hnl->Lifetime();
135 fctau = fPythia->particleData.tau0(fHNL); //* 3.3333e-12
136 LOG(debug) << "tau root " << root_ctau << "[s] ctau root = "
137 << root_ctau * ShipUnit::s * ShipUnit::c_light << "[cm]";
138 LOG(debug) << "ctau pythia " << fctau << "[mm]";
139 if (debug) {
140 List(9900015);
141 }
142 fPythia->init();
143 return kTRUE;
144}
145// -------------------------------------------------------------------------
146
147// ----- Destructor ----------------------------------------------------
149 if (fInputFile) {
150 fInputFile->Close();
151 delete fInputFile;
152 fInputFile = nullptr;
153 fTree = nullptr;
154 }
155 delete fPythia;
156 fPythia = nullptr;
157}
158// -------------------------------------------------------------------------
159
160// ----- Passing the event ---------------------------------------------
161Bool_t HNLPythia8Generator::ReadEvent(FairPrimaryGenerator* cpg) {
162 Double_t tp, tS, zp, xp, yp, zS, xS, yS, pz, px, py, e, w;
163 Double_t tm, zm, xm, ym, pmz, pmx, pmy, em;
164 Int_t im;
165 // take HNL decay of Pythia, move it to the SHiP decay region
166 // recalculate decay time
167 // weight event with exp(-t_ship/tau_HNL) / exp(-t_pythia/tau_HNL)
168
169 int iHNL = 0; // index of the chosen HNL (the 1st one), also ensures that at
170 // least 1 HNL is produced
171 std::vector<int>
172 dec_chain; // pythia indices of the particles to be stored on the stack
173 std::vector<int> hnls; // pythia indices of HNL particles
174 do {
175 if (fextFile) {
176 // take charm or beauty hadron from external file
177 // correct for too much Ds produced by pythia6
178 bool x = true;
179 while (x) {
180 if (fn == fNevents) {
181 LOG(warning) << "End of input file. Rewind.";
182 }
183 fTree->GetEntry(fn % fNevents);
184 fn++;
185 if (static_cast<int>(fabs(hid[0])) != 431) {
186 x = false;
187 } else {
188 Double_t rnr = gRandom->Uniform(0, 1);
189 if (rnr < fFDs) {
190 x = false;
191 };
192 // cout<<"what is x "<<x<<" id "<<int(fabs(hid[0]))<<" rnr " << rnr
193 // <<" "<< fFDs <<std::endl ;
194 }
195 }
196 fPythia->event.reset();
197 fPythia->event.append((Int_t)hid[0], 1, 0, 0, hpx[0], hpy[0], hpz[0],
198 hE[0], hM[0], 0., 9.);
199 }
200 fPythia->next();
201 for (int i = 0; i < fPythia->event.size(); i++) {
202 // find first HNL
203 if (abs(fPythia->event[i].id()) == fHNL) {
204 hnls.push_back(i);
205 }
206 }
207 IncrementCounter("hnl_candidates", hnls.size());
208 if (hnls.size() > 1) {
209 IncrementCounter("hnl_multi_candidate_tries");
210 }
211 iHNL = hnls.size();
212 if (iHNL == 0) {
213 fnRetries += 1;
214 } else {
215 // filter HNLs by vessel acceptance
216 std::vector<int> accepted;
217 for (int idx : hnls) {
218 if (IsInVesselAcceptance(fPythia->event[idx].px(),
219 fPythia->event[idx].py(),
220 fPythia->event[idx].pz())) {
221 accepted.push_back(idx);
222 }
223 }
224 IncrementCounter("hnl_accepted_candidates", accepted.size());
225 if (accepted.empty()) {
226 iHNL = 0;
227 hnls.clear();
228 fnGeoRejects += 1;
229 continue;
230 }
231 int r = static_cast<int>(gRandom->Uniform(0, accepted.size()));
232 int i = accepted[r];
233 // production vertex
234 zp = fPythia->event[i].zProd();
235 xp = fPythia->event[i].xProd();
236 yp = fPythia->event[i].yProd();
237 tp = fPythia->event[i].tProd();
238 // momentum
239 pz = fPythia->event[i].pz();
240 px = fPythia->event[i].px();
241 py = fPythia->event[i].py();
242 e = fPythia->event[i].e();
243 // new decay vertex
244 Double_t LS = gRandom->Uniform(fLmin, fLmax); // mm, G4 and Pythia8 units
245 Double_t p = TMath::Sqrt(px * px + py * py + pz * pz);
246 Double_t lam = LS / p;
247 xS = xp + lam * px;
248 yS = yp + lam * py;
249 zS = zp + lam * pz;
250 Double_t gam = e / TMath::Sqrt(e * e - p * p);
251 Double_t beta = p / e;
252 tS = tp + LS / beta; // decay time in Pythia units (mm/c): flight
253 // distance over dimensionless beta
254 // decay probability density at LS, normalised for the uniform sampling
255 // of LS over [fLmin, fLmax]
256 w = TMath::Exp(-LS / (beta * gam * fctau)) *
257 ((fLmax - fLmin) / (beta * gam * fctau));
258 im = (Int_t)fPythia->event[i].mother1();
259 zm = fPythia->event[im].zProd();
260 xm = fPythia->event[im].xProd();
261 ym = fPythia->event[im].yProd();
262 pmz = fPythia->event[im].pz();
263 pmx = fPythia->event[im].px();
264 pmy = fPythia->event[im].py();
265 em = fPythia->event[im].e();
266 tm = fPythia->event[im].tProd();
267 // foresee finite beam size
268 auto [dx, dy] = CalculateBeamOffset(fsmearBeam, fPaintBeam);
269 if (fextFile) {
270 // take grand mother particle from input file, to know if primary or
271 // secondary production
272 cpg->AddTrack((Int_t)mid[0], mpx[0], mpy[0], mpz[0],
275 PythiaLengthToCm(zm), -1, false, mE[0], 0., 1.);
276 cpg->AddTrack(
277 (Int_t)fPythia->event[im].id(), pmx, pmy, pmz,
280 0, false, em, PythiaTimeToS(tm),
281 w); // convert pythia's (x,y,z[mm], t[mm/c]) to ([cm], [s])
282 cpg->AddTrack(fHNL, px, py, pz,
285 PythiaLengthToCm(zp), 1, false, e, PythiaTimeToS(tp), w);
286 } else {
287 cpg->AddTrack(
288 (Int_t)fPythia->event[im].id(), pmx, pmy, pmz,
291 -1, false, em, PythiaTimeToS(tm),
292 w); // convert pythia's (x,y,z[mm], t[mm/c]) to ([cm], [s])
293 cpg->AddTrack(fHNL, px, py, pz,
296 PythiaLengthToCm(zp), 0, false, e, PythiaTimeToS(tp), w);
297 }
298 // bookkeep the indices of stored particles
299 dec_chain.push_back(im);
300 dec_chain.push_back(i);
301 // cout << endl << " insert mother pdg=" <<fPythia->event[im].id() << "
302 // pmz = " << pmz << " [GeV], zm = " << zm << " [mm] tm = " << tm << "
303 // [mm/c]" << endl; cout << " ----> insert HNL =" << fHNL << " pz = " <<
304 // pz << " [GeV] zp = " << zp << " [mm] tp = " << tp << " [mm/c]" << endl;
305 iHNL = i;
306 }
307 } while (iHNL ==
308 0); // ----------- avoid rare empty events w/o any HNL's produced
309
310 if (fShipEventNr % 100 == 0) {
311 LOGF(info, "ship event %i / pythia event-nr %i", fShipEventNr, fn);
312 }
313 fShipEventNr += 1;
314 // fill a container with pythia indices of the HNL decay chain
315 for (int k = 0; k < fPythia->event.size(); k++) {
316 // if daughter of HNL, copy
317 im = fPythia->event[k].mother1();
318 while (im > 0) {
319 if (im == iHNL) {
320 break;
321 } // pick the decay products of only 1 chosen HNL
322 // if ( abs(fPythia->event[im].id())==fHNL && im == iHNL ){break;}
323 else {
324 im = fPythia->event[im].mother1();
325 }
326 }
327 if (im < 1) {
328 continue;
329 }
330 dec_chain.push_back(k);
331 }
332
333 // go over daughters and store them on the stack, starting from 2 to account
334 // for HNL and its mother
335 for (std::vector<int>::iterator it = dec_chain.begin() + 2;
336 it != dec_chain.end(); ++it) {
337 // pythia index of the particle to store
338 int k = *it;
339 // find mother position on the output stack: impy -> im
340 int impy = fPythia->event[k].mother1();
341 std::vector<int>::iterator itm =
342 std::find(dec_chain.begin(), dec_chain.end(), impy);
343 im = -1; // safety
344 if (itm != dec_chain.end())
345 im = itm - dec_chain.begin(); // convert iterator into sequence number
346
347 Bool_t wanttracking = false;
348 if (fPythia->event[k].isFinal()) {
349 wanttracking = true;
350 }
351 pz = fPythia->event[k].pz();
352 px = fPythia->event[k].px();
353 py = fPythia->event[k].py();
354 e = fPythia->event[k].e();
355 if (fextFile) {
356 im += 1;
357 }
358 IncrementCounter("hnl_stored_decay_products");
359 cpg->AddTrack((Int_t)fPythia->event[k].id(), px, py, pz,
361 PythiaLengthToCm(zS), im, wanttracking, e, PythiaTimeToS(tS),
362 w);
363 // std::cout <<k<< " insert pdg =" <<fPythia->event[k].id() << " pz = " <<
364 // pz << " [GeV] zS = " << zS << " [mm] tS = " << tS << "[mm/c]" << endl;
365 }
366 return kTRUE;
367}
368// -------------------------------------------------------------------------
370 // Set Parameters
371 fPythia->readString(par);
372 LOG(debug) << "fPythia->readString(\"" << par << "\")";
373}
374
375// -------------------------------------------------------------------------
std::pair< Double_t, Double_t > CalculateBeamOffset(Double_t smearBeam, Double_t paintBeam)
const Int_t debug
constexpr double PythiaTimeToS(double t)
A Pythia8 time (mm/c) in VMC units (s).
Definition PythiaUnits.h:20
constexpr Double_t kPythiaMm
constexpr Double_t kPythiaCm
constexpr double PythiaLengthToCm(double x)
A Pythia8 position (mm) in FairShip units (cm).
Definition PythiaUnits.h:18
TTree * fTree
pointer to a file
Bool_t ReadEvent(FairPrimaryGenerator *) override
std::shared_ptr< Pythia8::RndmEngine > fRandomEngine
Pythia8::Pythia * fPythia
void IncrementCounter(const std::string &name, Long64_t delta=1)
Definition Generator.h:65
bool IsInVesselAcceptance(Double_t px, Double_t py, Double_t pz) const
Definition Generator.h:70
Int_t fnGeoRejects
Definition Generator.h:81
std::optional< std::string > fextFile
Definition Generator.h:76
constexpr double c_light
Definition ShipUnit.h:44
constexpr double s
Definition ShipUnit.h:31
Definition hnl.py:1
constexpr double PythiaTimeToS(double t)
A Pythia8 time (mm/c) in VMC units (s).
Definition PythiaUnits.h:20
constexpr double PythiaLengthToCm(double x)
A Pythia8 position (mm) in FairShip units (cm).
Definition PythiaUnits.h:18
constexpr double kPythiaLengthPerCm
Pythia8 lengths are in mm, FairShip lengths in cm.
Definition PythiaUnits.h:13