FairShip
Loading...
Searching...
No Matches
ParticleGunGenerator.cxx
Go to the documentation of this file.
1
3
4#include <TDatabasePDG.h>
5#include <TMath.h>
6#include <TNamed.h>
7#include <TParticlePDG.h>
8#include <TRandom.h>
9
10#include <cmath> // for cos, acos
11#include <cstdio> // for printf
12#include <optional>
13#include <stdexcept>
14
15#include "FairLogger.h"
16#include "FairPrimaryGenerator.h"
17#include "TFile.h"
18#include "TH2.h"
19#include "TH3.h"
20
21// Function-local static maps so std::map's allocations happen lazily on
22// first use rather than during dynamic initialisation, where the bad_alloc
23// would propagate out as an uncatchable exception
24// (bugprone-throwing-static-initialization).
25static const std::map<std::string, ModelSpec>& kVertexModels() {
26 static const std::map<std::string, ModelSpec> models = {
27 {"gaussian",
28 {5, "Gaus(X), Gaus(Y), Point(Z)",
29 [](ParticleGunParticle& p, const std::vector<Double32_t>& pars) {
30 p.X = (pars[1] > 0) ? gRandom->Gaus(pars[0], pars[1]) : pars[0];
31 p.Y = (pars[3] > 0) ? gRandom->Gaus(pars[2], pars[3]) : pars[2];
32 p.Z = pars[4];
33 }}},
34 {"exponential",
35 {5, "Exp(X), Exp(Y), Point(Z)",
36 [](ParticleGunParticle& p, const std::vector<Double32_t>& pars) {
37 p.X =
38 (gRandom->Uniform() > 0.5)
39 ? gRandom->Exp(pars[1]) + pars[0]
40 : -gRandom->Exp(pars[1]) +
41 pars[0]; // Make this symmetric about a specified point
42 p.Y = (gRandom->Uniform() > 0.5) ? gRandom->Exp(pars[3]) + pars[2]
43 : -gRandom->Exp(pars[3]) + pars[2];
44 p.Z = pars[4];
45 }}},
46 {"uniform",
47 {5, "Uniform(X), Uniform(Y), Point(Z)",
48 [](ParticleGunParticle& p, const std::vector<Double32_t>& pars) {
49 p.X = (pars[1] > 0) ? gRandom->Uniform(pars[0] - pars[1] / 2.,
50 pars[0] + pars[1] / 2.)
51 : pars[0];
52 p.Y = (pars[3] > 0) ? gRandom->Uniform(pars[2] - pars[3] / 2.,
53 pars[2] + pars[3] / 2.)
54 : pars[2];
55 p.Z = pars[4];
56 }}},
57 {"uniform3d",
58 {6, "Uniform(X), Uniform(Y), Uniform(Z)",
59 [](ParticleGunParticle& p, const std::vector<Double32_t>& pars) {
60 auto uniform = [](Double32_t centre, Double32_t width) {
61 return (width > 0) ? gRandom->Uniform(centre - width / 2.,
62 centre + width / 2.)
63 : centre;
64 };
65 p.X = uniform(pars[0], pars[1]);
66 p.Y = uniform(pars[2], pars[3]);
67 p.Z = uniform(pars[4], pars[5]);
68 }}},
69 };
70 return models;
71}
72
73static const std::map<int, ModelSpec>& kMomentumModels() {
74 static const std::map<int, ModelSpec> models = {
75 {1,
76 {6, "Gaus(Px), Gaus(Py), Landau(Pz)",
77 [](ParticleGunParticle& p, const std::vector<Double32_t>& pars) {
78 p.Px = (pars[1] > 0) ? gRandom->Gaus(pars[0], pars[1]) : pars[0];
79 p.Py = (pars[3] > 0) ? gRandom->Gaus(pars[2], pars[3]) : pars[2];
80 p.Pz = (pars[5] > 0) ? gRandom->Landau(pars[4], pars[5]) : pars[4];
81 }}},
82 };
83 return models;
84}
85
89
91 : SHiP::Generator() {
92 // Constructor. Set default kinematics limits
93 SetPDGType(pdgid);
94 SetMultiplicity(mult);
96}
97
99
101 const std::string& inFile, const std::string& inHisto,
102 std::vector<std::string> varNames) {
103 TFile* loadFile = TFile::Open(inFile.c_str(), "READ");
104 if (!loadFile) {
105 delete loadFile;
106 LOG(fatal) << "ParticleGunGenerator: Cannot open file " << inFile;
107 throw std::runtime_error("ParticleGunGenerator: Cannot open file " +
108 inFile);
109 }
110
111 auto* raw = dynamic_cast<TH1*>(loadFile->Get(inHisto.c_str()));
112 if (!raw) {
113 loadFile->Close();
114 delete loadFile;
115 LOG(fatal) << "ParticleGunGenerator: Histogram " << inHisto
116 << " not found in file " << inFile;
117 throw std::runtime_error("ParticleGunGenerator: Histogram " + inHisto +
118 " not found in file " + inFile);
119 }
120 raw = static_cast<TH1*>(raw->Clone());
121 raw->SetDirectory(nullptr); // detach from ROOT's directory ownership
122 loadFile->Close();
123 delete loadFile;
124
125 const int dims = raw->GetDimension();
126 if (static_cast<int>(varNames.size()) != dims) {
127 LOG(fatal) << "ParticleGunGenerator: " << varNames.size()
128 << " variables given for a " << dims << "-D histogram";
129 throw std::runtime_error(
130 "ParticleGunGenerator: " + std::to_string(varNames.size()) +
131 " variables given for a " + std::to_string(dims) + "-D histogram");
132 } else {
134 for (const auto& name : varNames) {
135 static_cast<void>(GetVar(probe, name));
136 }
137 }
138
139 // Check for variable name conflicts with already-loaded histograms
140 for (const auto& name : varNames) {
141 for (const auto& entry : fHistoEntries) {
142 for (const auto& existing : entry.varNames) {
143 if (existing == name) {
144 LOG(fatal)
145 << "ParticleGunGenerator: variable \"" << name
146 << "\" is already controlled by a previously loaded histogram";
147 throw std::runtime_error(
148 "ParticleGunGenerator: variable \"" + name +
149 "\" is already controlled by a previously loaded histogram");
150 }
151 }
152 }
153 }
154
155 fHistoEntries.push_back(
156 {std::shared_ptr<TH1>(raw), dims, std::move(varNames)});
157
158 LOG(info) << "ParticleGunGenerator: loaded " << dims << "-D histogram \""
159 << inHisto << "\" from " << inFile << " (" << fHistoEntries.size()
160 << " total)";
161}
162
164 const auto& vertexSpec = kVertexModels().at(fVertexModel);
165
166 if (static_cast<int>(fVertexPars.size()) != vertexSpec.expectedPars) {
167 throw std::runtime_error(
168 "ParticleGunGenerator: vertex model " + fVertexModel + " requires " +
169 std::to_string(vertexSpec.expectedPars) + " parameters, got " +
170 std::to_string(fVertexPars.size()));
171 }
172
173 // Check for particle type
174 TDatabasePDG* pdgBase = TDatabasePDG::Instance();
175 TParticlePDG* particle = pdgBase->GetParticle(m_pdgid);
176
177 if (!particle) {
178 LOG(fatal) << "ParticleGunGenerator: PDG " << m_pdgid << " not defined";
179 return kFALSE;
180 }
181 LOG(info) << this->ClassName() << ": particle with PDG =" << m_pdgid
182 << " Found";
183 fPDGMass = particle->Mass();
184
185 if (fPhiMax - fPhiMin > 360) {
186 LOG(fatal) << "ParticleGunGenerator:Init(): phi range is too wide: "
187 << fPhiMin << "<phi<" << fPhiMax;
188 return kFALSE;
189 }
190 if (fEkinRangeIsSet) {
191 if (fPRangeIsSet) {
192 LOG(fatal) << "ParticleGunGenerator:Init(): Cannot set P and Ekin ranges "
193 "simultaneously";
194 return kFALSE;
195 } else {
196 fPMin = TMath::Sqrt(fEkinMin * (fEkinMin + 2 * fPDGMass));
197 fPMax = TMath::Sqrt(fEkinMax * (fEkinMax + 2 * fPDGMass));
198 fPRangeIsSet = kTRUE;
199 fEkinRangeIsSet = kFALSE;
200 }
201 }
203 LOG(fatal) << "ParticleGunGenerator:Init(): Cannot set P and Pt ranges "
204 "simultaneously";
205 return kFALSE;
206 }
207 if (fPRangeIsSet && fYRangeIsSet) {
208 LOG(fatal) << "ParticleGunGenerator:Init(): Cannot set P and Y ranges "
209 "simultaneously";
210 return kFALSE;
211 }
215 LOG(fatal) << "ParticleGunGenerator:Init(): Cannot set Y, Theta or Eta "
216 "ranges simultaneously";
217 return kFALSE;
218 }
219 return kTRUE;
220}
221
222void ParticleGunGenerator::SetBothCharges(bool flag, Double32_t fraction) {
223 if (flag && (!std::isfinite(fraction) || fraction < 0. || fraction > 1.)) {
224 LOG(fatal)
225 << "ParticleGunGenerator: charge fraction must be finite and in [0, 1]";
226 throw std::runtime_error(
227 "ParticleGunGenerator: charge fraction must be finite and in [0, 1]");
228 }
229 m_bothCharges = flag;
230 m_chargeFraction = flag ? fraction : 1.;
231 if (m_bothCharges) {
232 // Check for particle type
233 TDatabasePDG* pdgBase = TDatabasePDG::Instance();
234 TParticlePDG* particle = pdgBase->GetParticle(-m_pdgid);
235 if (!particle) {
236 LOG(warning) << "ParticleGunGenerator: PDG " << -m_pdgid
237 << " not defined. Only generating " << m_pdgid;
238 m_bothCharges = false;
239 m_chargeFraction = 1.;
240 } else
241 LOG(info)
242 << "ParticleGunGenerator: Setting to generate both charges, with "
243 "fraction of "
244 << m_pdgid << " set to " << m_chargeFraction;
245 } else
246 LOG(info) << "ParticleGunGenerator: Setting to only generate one charge "
247 "for PDG id"
248 << m_pdgid;
249}
250
252 if (m_bothCharges) {
253 float tPDG = gRandom->Uniform();
254 return (tPDG > m_chargeFraction) ? -m_pdgid : m_pdgid;
255 } else
256 return m_pdgid;
257}
258
259Bool_t ParticleGunGenerator::ReadEvent(FairPrimaryGenerator* primGen) {
260 int pdg_type;
261 // With a common vertex, all particles of the event share the first one's
262 std::optional<ParticleGunParticle> vertex;
263 for (Int_t k = 0; k < GetMultiplicity(); k++) {
264 pdg_type = GenPDGType();
266 if (m_commonVertex) {
267 if (!vertex) {
268 vertex = p;
269 }
270 p.X = vertex->X;
271 p.Y = vertex->Y;
272 p.Z = vertex->Z;
273 }
275 primGen->AddTrack(pdg_type, p.Px, p.Py, p.Pz, p.X, p.Y, p.Z);
276 }
277 return kTRUE;
278}
279
282 // --- Vertex smearing ---
284 if (fMomentumModel > 0)
286 else {
287 Double32_t pabs = 0, pt = 0, theta = 0, eta, y, mt, pz = 0;
288 // Generate particles
289 const Double32_t phi =
290 gRandom->Uniform(fPhiMin, fPhiMax) * TMath::DegToRad();
291
292 if (fPRangeIsSet) {
293 pabs = gRandom->Uniform(fPMin, fPMax);
294 } else if (fPtRangeIsSet) {
295 pt = gRandom->Uniform(fPtMin, fPtMax);
296 }
297
298 if (fThetaRangeIsSet) {
299 if (fCosThetaIsSet)
300 theta = acos(gRandom->Uniform(cos(fThetaMax * TMath::DegToRad()),
301 cos(fThetaMin * TMath::DegToRad())));
302 else {
303 theta = gRandom->Uniform(fThetaMin, fThetaMax) * TMath::DegToRad();
304 }
305 } else if (fEtaRangeIsSet) {
306 eta = gRandom->Uniform(fEtaMin, fEtaMax);
307 theta = 2 * TMath::ATan(TMath::Exp(-eta));
308 } else if (fYRangeIsSet) {
309 y = gRandom->Uniform(fYMin, fYMax);
310 mt = TMath::Sqrt(GetPDGMass() * GetPDGMass() + pt * pt);
311 pz = mt * TMath::SinH(y);
312 }
313
315 if (fPRangeIsSet) {
316 pz = pabs * TMath::Cos(theta);
317 pt = pabs * TMath::Sin(theta);
318 } else if (fPtRangeIsSet) {
319 pz = pt / TMath::Tan(theta);
320 }
321 } else if (fPRangeIsSet) {
322 pz = pabs;
323 }
324 p.Px = pt * TMath::Cos(phi);
325 p.Py = pt * TMath::Sin(phi);
326 p.Pz = pz;
327 }
328 return p;
329}
330
332 for (const auto& entry : fHistoEntries) {
333 switch (entry.dims) {
334 case 1:
335 SetVar(p, entry.varNames[0],
336 static_cast<TH1*>(entry.hist.get())->GetRandom());
337 break;
338 case 2:
339 static_cast<TH2*>(entry.hist.get())
340 ->GetRandom2(GetVar(p, entry.varNames[0]),
341 GetVar(p, entry.varNames[1]));
342 break;
343 case 3:
344 static_cast<TH3*>(entry.hist.get())
345 ->GetRandom3(GetVar(p, entry.varNames[0]),
346 GetVar(p, entry.varNames[1]),
347 GetVar(p, entry.varNames[2]));
348 break;
349 default:
350 LOG(error) << "ParticleGunGenerator: unsupported histogram dimension "
351 << entry.dims;
352 }
353 }
354}
355
357 std::vector<Double32_t> pars) {
358 auto it = kMomentumModels().find(modelNo);
359 if (it == kMomentumModels().end()) {
360 LOG(fatal) << "ParticleGunGenerator: unknown momentum model " << modelNo;
361 throw std::runtime_error("ParticleGunGenerator: unknown momentum model " +
362 std::to_string(modelNo));
363 }
364
365 const auto& spec = it->second;
366 if (static_cast<int>(pars.size()) != spec.expectedPars) {
367 LOG(fatal) << "ParticleGunGenerator: momentum model " << modelNo << " ("
368 << spec.description << ") requires " << spec.expectedPars
369 << " parameters, got " << pars.size();
370 throw std::runtime_error("ParticleGunGenerator: momentum model " +
371 std::to_string(modelNo) + " (" + spec.description +
372 ") requires " + std::to_string(spec.expectedPars) +
373 " parameters, got " + std::to_string(pars.size()));
374 }
375
376 fMomentumModel = modelNo;
377 fMomentumPars = std::move(pars);
378 LOG(info) << "ParticleGunGenerator: momentum model " << modelNo << " ("
379 << spec.description << ")";
380}
381
382void ParticleGunGenerator::SetVertexModel(const std::string& model,
383 std::vector<Double32_t> pars) {
384 // Normalise to lowercase so "Gaussian", "GAUSSIAN" etc. all work
385 std::string lower = model;
386 std::transform(lower.begin(), lower.end(), lower.begin(), ::tolower);
387
388 auto it = kVertexModels().find(lower);
389 if (it == kVertexModels().end()) {
390 LOG(fatal) << "ParticleGunGenerator: unknown vertex model " << model;
391 throw std::runtime_error("ParticleGunGenerator: unknown vertex model " +
392 model);
393 }
394
395 const auto& spec = it->second;
396 if (static_cast<int>(pars.size()) != spec.expectedPars) {
397 LOG(fatal) << "ParticleGunGenerator: vertex model " << model << " ("
398 << spec.description << ") requires " << spec.expectedPars
399 << " parameters, got " << pars.size();
400 throw std::runtime_error("ParticleGunGenerator: vertex model " + model +
401 " (" + spec.description + ") requires " +
402 std::to_string(spec.expectedPars) +
403 " parameters, got " + std::to_string(pars.size()));
404 }
405
406 fVertexModel = lower;
407 fVertexPars = std::move(pars);
408 LOG(info) << "ParticleGunGenerator: vertex model " << lower << " ("
409 << spec.description << ")";
410}
411
413 kVertexModels().at(fVertexModel).generate(p, fVertexPars);
414}
415
417 kMomentumModels().at(fMomentumModel).generate(p, fMomentumPars);
418}
419
421 LOG(info) << "Available vertex models:";
422 for (const auto& [id, spec] : kVertexModels())
423 LOG(info) << " Model " << id << " (" << spec.expectedPars
424 << " pars): " << spec.description;
425}
426
428 LOG(info) << "Available momentum models:";
429 for (const auto& [id, spec] : kMomentumModels())
430 LOG(info) << " Model " << id << " (" << spec.expectedPars
431 << " pars): " << spec.description;
432}
433
435 const std::string& name) {
436 if (name == "X") return p.X;
437 if (name == "Y") return p.Y;
438 if (name == "Z") return p.Z;
439 if (name == "Px") return p.Px;
440 if (name == "Py") return p.Py;
441 if (name == "Pz") return p.Pz;
442 LOG(fatal) << "ParticleGunGenerator: unknown variable name '" << name << "'";
443 throw std::runtime_error("ParticleGunGenerator: unknown variable name '" +
444 name + "'");
445 return p.X; // unreachable, silences compiler warning
446}
447
449 const std::string& name, Double32_t value) {
450 GetVar(p, name) = value;
451}
452
454 auto* clone = new ParticleGunGenerator(*this);
455 for (auto& entry : clone->fHistoEntries) {
456 entry.hist.reset(static_cast<TH1*>(entry.hist->Clone()));
457 entry.hist->SetDirectory(nullptr);
458 }
459 return clone;
460}
void OverrideFromHistogram(ParticleGunParticle &p)
~ParticleGunGenerator() override
void SetVertexModel(const std::string &model, std::vector< Double32_t > pars)
std::vector< HistoEntry > fHistoEntries
Bool_t ReadEvent(FairPrimaryGenerator *primGen) override
void GenVertexModel(ParticleGunParticle &p)
void GenMomentumModel(ParticleGunParticle &p)
void SetBothCharges(bool flag, Double32_t fraction=0.5)
Double32_t & GetVar(ParticleGunParticle &p, const std::string &name)
void SetVar(ParticleGunParticle &p, const std::string &name, Double32_t value)
ParticleGunParticle GenerateKinematics()
std::vector< Double32_t > fMomentumPars
FairGenerator * CloneGenerator() const override
void SetMomentumModel(const int modelNo, std::vector< Double32_t > pars)
void LoadHistoFromFile(const std::string &inFile, const std::string &inHisto, std::vector< std::string > varNames)
std::vector< Double32_t > fVertexPars
void SetPhiRange(Double32_t phimin=0, Double32_t phimax=360)
Generator()=default
width(particle)
Definition rpvsusy.py:91