FairShip
Loading...
Searching...
No Matches
MuonBackGenerator.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
5#include "MuonBackGenerator.h"
6
7#include <algorithm>
8#include <cmath>
9#include <unordered_map>
10#include <utility>
11#include <vector>
12
13#include "BeamSmearingUtils.h"
14#include "FairPrimaryGenerator.h"
15#include "ShipMCTrack.h"
16#include "ShipUnit.h"
17#include "TChain.h"
18#include "TDatabasePDG.h" // for TDatabasePDG
19#include "TFile.h"
20#include "TMCProcess.h"
21#include "TMath.h" // for Sqrt
22#include "TROOT.h"
23#include "TRandom.h"
24#include "TSystem.h"
25#include "TVector.h"
26#include "TVirtualMC.h"
27#include "vetoPoint.h"
28
29using ShipUnit::cm;
30using ShipUnit::mm;
31// read events from Pythia8/Geant4 base simulation (only target + hadron
32// absorber
33
34// ----- Default constructor -------------------------------------------
36 : MCTrack(nullptr),
37 vetoPoints(nullptr),
38 MCTrack_vec(nullptr),
39 vetoPoints_vec(nullptr),
40 fUseSTL(false),
41 fTree(nullptr),
42 fStartFromOrigin(kFALSE) {
43 followMuons = true;
44}
45// -------------------------------------------------------------------------
46// ----- Default constructor -------------------------------------------
47Bool_t MuonBackGenerator::Init(const char* fileName) {
48 return Init(fileName, 0);
49}
50
51Bool_t MuonBackGenerator::Init(const std::vector<std::string>& fileNames) {
52 return Init(fileNames, 0);
53}
54
55Bool_t MuonBackGenerator::Init(const std::vector<std::string>& fileNames,
56 const int startEvent) {
57 if (fileNames.empty()) {
58 LOG(error) << "MuonBackGenerator: no input files provided. "
59 << "Check the -f/--inputFile argument or input file glob.";
60 return kFALSE;
61 }
62 for (const auto& fileName : fileNames) {
63 if (fileName.empty()) {
64 LOG(error) << "MuonBackGenerator: received an empty input file name. "
65 << "Check the -f/--inputFile argument.";
66 return kFALSE;
67 }
68 }
69 if (startEvent < 0) {
70 LOG(error) << "MuonBackGenerator: startEvent must be >= 0, got "
71 << startEvent;
72 return kFALSE;
73 }
74
75 LOG(info) << "Opening input file to find keys " << fileNames.at(0);
76 TFile* testFile = TFile::Open(fileNames.at(0).c_str(), "READ");
77 auto testKeys = testFile ? testFile->GetListOfKeys() : nullptr;
78 if (testKeys == nullptr) {
79 delete testFile;
80 LOG(error) << "MuonBackGenerator: Error opening input file "
81 << fileNames.at(0)
82 << ". Check that the path is correct and the file is a readable "
83 "ROOT file.";
84 return kFALSE;
85 }
86 const bool hasPythia8Geant4 =
87 testKeys->FindObject("pythia8-Geant4") != nullptr;
88 testFile->Close();
89 delete testFile;
90 fn = startEvent;
91 fPaintBeam = 5 * cm; // default value for painting beam
92 fSameSeed = 0;
93 fPhiRandomize = false; // default value for phi randomization
94 fsmearBeam = 8 * mm; // default value for smearing beam
95 fdownScaleDiMuon = kFALSE; // only needed for muflux simulation
96 if (hasPythia8Geant4) {
97 fTree = new TChain("pythia8-Geant4");
98 for (auto& f : fileNames) {
99 LOG(info) << "Opening input file " << f;
100 fTree->Add(f.c_str());
101 }
102 fNevents = fTree->GetEntries();
103 LOG(info) << "Reading " << fNevents << " entries";
104 if (startEvent >= fNevents) {
105 LOG(error) << "MuonBackGenerator: startEvent " << startEvent
106 << " is out of range for " << fNevents << " entries";
107 return kFALSE;
108 }
109 // count only events with muons
110 bool ok = true;
111 ok &= (fTree->SetBranchAddress("id", &id) >= 0);
112 ok &= (fTree->SetBranchAddress("parentid", &parentid) >= 0);
113 ok &= (fTree->SetBranchAddress("pythiaid", &pythiaid) >= 0);
114 ok &= (fTree->SetBranchAddress("ecut", &ecut) >= 0);
115 ok &= (fTree->SetBranchAddress("w", &w) >= 0);
116 // check if ntuple has information of momentum at origin
117 if (fTree->GetListOfLeaves()->GetSize() < 17) {
118 ok &= (fTree->SetBranchAddress("x", &vx) >= 0);
119 ok &= (fTree->SetBranchAddress("y", &vy) >= 0);
120 ok &= (fTree->SetBranchAddress("z", &vz) >= 0);
121 ok &= (fTree->SetBranchAddress("px", &px) >= 0);
122 ok &= (fTree->SetBranchAddress("py", &py) >= 0);
123 ok &= (fTree->SetBranchAddress("pz", &pz) >= 0);
124 } else {
125 ok &= (fTree->SetBranchAddress("ox", &vx) >= 0);
126 ok &= (fTree->SetBranchAddress("oy", &vy) >= 0);
127 ok &= (fTree->SetBranchAddress("oz", &vz) >= 0);
128 ok &= (fTree->SetBranchAddress("opx", &px) >= 0);
129 ok &= (fTree->SetBranchAddress("opy", &py) >= 0);
130 ok &= (fTree->SetBranchAddress("opz", &pz) >= 0);
131 }
132 if (!ok) {
133 LOG(error) << "MuonBackGenerator: failed to bind one or more required "
134 "branches for pythia8-Geant4 input";
135 return kFALSE;
136 }
137 } else {
138 id = -1;
139 fTree = new TChain("cbmsim");
140 for (auto& f : fileNames) {
141 LOG(info) << "Opening input file " << f;
142 fTree->Add(f.c_str());
143 }
144 fNevents = fTree->GetEntries();
145 LOG(info) << "Reading " << fNevents << " entries";
146 if (startEvent >= fNevents) {
147 LOG(error) << "MuonBackGenerator: startEvent " << startEvent
148 << " is out of range for " << fNevents << " entries";
149 return kFALSE;
150 }
151 // Detect format by checking branch name:
152 // STL format uses PlaneHAPoint, TClonesArray uses vetoPoint
153 TBranch* mcBranch = fTree->GetBranch("MCTrack");
154 if (!mcBranch) {
155 LOG(error) << "MuonBackGenerator: MCTrack branch not found in input file";
156 return kFALSE;
157 }
158
159 if (fTree->GetBranch("PlaneHAPoint")) {
160 // New STL format
161 fUseSTL = true;
162 MCTrack_vec = nullptr;
163 vetoPoints_vec = nullptr;
164 auto mcStatus = fTree->SetBranchAddress("MCTrack", &MCTrack_vec);
165 auto vetoStatus =
166 fTree->SetBranchAddress("PlaneHAPoint", &vetoPoints_vec);
167 if (mcStatus < 0 || vetoStatus < 0) {
168 LOG(error) << "MuonBackGenerator: Failed to set branch addresses for "
169 "STL vector format";
170 return kFALSE;
171 }
172 LOG(info) << "Using STL vector format (PlaneHAPoint)";
173 } else if (fTree->GetBranch("vetoPoint")) {
174 // Old TClonesArray format
175 fUseSTL = false;
176 MCTrack = new TClonesArray("ShipMCTrack");
177 vetoPoints = new TClonesArray("vetoPoint");
178 auto mcStatus = fTree->SetBranchAddress("MCTrack", &MCTrack);
179 auto vetoStatus = fTree->SetBranchAddress("vetoPoint", &vetoPoints);
180 if (mcStatus < 0 || vetoStatus < 0) {
181 LOG(error) << "MuonBackGenerator: Failed to set branch addresses for "
182 "TClonesArray format";
183 return kFALSE;
184 }
185 LOG(info) << "Using TClonesArray format (vetoPoint)";
186 } else {
187 LOG(error) << "MuonBackGenerator: Neither PlaneHAPoint nor vetoPoint "
188 "branch found in input file";
189 return kFALSE;
190 }
191 }
192 return kTRUE;
193}
194
195// ----- Default constructor -------------------------------------------
196Bool_t MuonBackGenerator::Init(const char* fileName, const int startEvent) {
197 std::vector<std::string> fileNames = {fileName};
198 return Init(fileNames, startEvent);
199}
200// ----- Destructor ----------------------------------------------------
202 delete MCTrack;
203 MCTrack = nullptr;
204 delete vetoPoints;
205 vetoPoints = nullptr;
206 delete fTree;
207 fTree = nullptr;
208}
209// -------------------------------------------------------------------------
210Bool_t MuonBackGenerator::checkDiMuon(Int_t muIndex) {
211 ShipMCTrack* mu = fUseSTL ? &(*MCTrack_vec)[muIndex]
212 : dynamic_cast<ShipMCTrack*>(MCTrack->At(muIndex));
213 TString pName = mu->GetProcName();
214 if (strncmp("Hadronic inelastic", pName.Data(), 18) == 0 ||
215 strncmp("Positron annihilation", pName.Data(), 21) == 0 ||
216 strncmp("Lepton pair production", pName.Data(), 22) == 0) {
217 return true;
218 }
219 Int_t motherId = mu->GetMotherId();
220 if (motherId < 0) {
221 return false;
222 }
223 ShipMCTrack* mother = fUseSTL
224 ? &(*MCTrack_vec)[motherId]
225 : dynamic_cast<ShipMCTrack*>(MCTrack->At(motherId));
226 Int_t Pcode = TMath::Abs(mother->GetPdgCode());
227 return (Pcode == 221 || Pcode == 223 || Pcode == 333 || Pcode == 113 ||
228 Pcode == 331);
229}
230
231// ----- Passing the event ---------------------------------------------
232Bool_t MuonBackGenerator::ReadEvent(FairPrimaryGenerator* cpg) {
233 auto* pdgBase = TDatabasePDG::Instance();
234 Double_t mass = 0., e = 0., tof = 0.;
235 std::unordered_map<int, int> muList;
236 std::unordered_map<int, std::vector<int>> moList;
237
238 // Helper lambdas to abstract STL vs TClonesArray access
239 auto getVetoSize = [this]() -> int {
240 return fUseSTL ? vetoPoints_vec->size() : vetoPoints->GetEntries();
241 };
242 auto getVetoPoint = [this](int i) -> vetoPoint* {
243 return fUseSTL ? &(*vetoPoints_vec)[i]
244 : dynamic_cast<vetoPoint*>(vetoPoints->At(i));
245 };
246 auto getMCTrack = [this](int i) -> ShipMCTrack* {
247 return fUseSTL ? &(*MCTrack_vec)[i]
248 : dynamic_cast<ShipMCTrack*>(MCTrack->At(i));
249 };
250 auto getMCTrackSize = [this]() -> int {
251 return fUseSTL ? MCTrack_vec->size() : MCTrack->GetEntries();
252 };
253
254 bool found_muon = false;
255 while (fn < fNevents) {
256 fTree->GetEntry(fn);
257 IncrementCounter("scanned_entries");
258 muList.clear();
259 moList.clear();
260 fn++;
261 if (fn % 100000 == 0) {
262 LOGF(info, "Reading event %i", fn);
263 }
264 // test if we have a muon, don't look at neutrinos:
265 if (TMath::Abs(static_cast<int>(id)) == 13) {
266 mass = pdgBase->GetParticle(id)->Mass();
267 e = TMath::Sqrt(px * px + py * py + pz * pz + mass * mass);
268 tof = 0;
269 found_muon = true;
270 break;
271 }
272 if (id == -1) { // use tree as input file
273 Bool_t found = false;
274 for (int i = 0; i < getVetoSize(); i++) {
275 auto* v = getVetoPoint(i);
276 Int_t abspid = TMath::Abs(v->PdgCode());
277 if (abspid == 13 || (!followMuons && abspid != 12 && abspid != 14)) {
278 found = true;
279 Int_t muIndex = v->GetTrackID();
280 if (!fdownScaleDiMuon) {
281 muList.insert({muIndex, i});
282 } else if (abspid == 13) {
283 if (checkDiMuon(muIndex)) {
284 moList[getMCTrack(muIndex)->GetMotherId()].push_back(i);
285 } else {
286 muList.insert({muIndex, i});
287 }
288 }
289 }
290 }
291 // reject muon if comes from boosted channel
292
293 for (auto it = moList.begin(); it != moList.end(); it++) {
294 if (gRandom->Uniform(0., 1.) > 0.99) {
295 std::vector<int> list = it->second;
296 for (unsigned i = 0; i < list.size(); i++) {
297 auto* v = getVetoPoint(list.at(i));
298 Int_t muIndex = v->GetTrackID();
299 muList.insert({muIndex, list.at(i)});
300 }
301 }
302 }
303 if (!found) {
304 LOGF(debug, "No muon found %i", fn - 1);
305 }
306 if (found) {
307 IncrementCounter("accepted_entries");
308 IncrementCounter("selected_muons", muList.size());
309 found_muon = true;
310 break;
311 }
312 }
313 }
314 if (fn >= fNevents && !found_muon) {
315 LOGF(info, "End of tree reached %i", fNevents);
316 gMC->StopRun();
317 return kTRUE;
318 }
319 if (fSameSeed) {
320 Int_t theSeed = fn + fSameSeed * fNevents;
321 LOGF(debug, "Seed: %d", theSeed);
322 gRandom->SetSeed(theSeed);
323 }
324 if (id == -1 && !fStartFromOrigin) {
325 // run_fixedTarget input: the scored tracks crossed the scoring plane once
326 // already, so they continue from where they entered it. Starting them at
327 // their production vertex would simulate the path to the plane a second
328 // time and count the probability of reaching it twice. Beam smearing and
329 // painting were applied in the first stage, and the absorber field breaks
330 // the symmetry a phi rotation would need, so neither is applied here.
331 if (fPhiRandomize) {
332 LOG(fatal) << "MuonBackGenerator: phi randomisation is not supported "
333 "when starting at the scoring plane";
334 }
335 // The input event is kept as it is, untracked, as history.
336 for (int i = 0; i < getMCTrackSize(); i++) {
337 auto* track = getMCTrack(i);
338 IncrementCounter("transported_tracks");
339 cpg->AddTrack(track->GetPdgCode(), track->GetPx(), track->GetPy(),
340 track->GetPz(), track->GetStartX(), track->GetStartY(),
341 track->GetStartZ(), track->GetMotherId(), false,
342 track->GetEnergy(),
343 track->GetStartT() / 1E9, // convert back from ns to sec
344 track->GetWeight(), (TMCProcess)track->GetProcID());
345 }
346 // Each scored track is then added again as it entered the plane, as a
347 // daughter of its origin entry, and only that copy is tracked. Sorted, so
348 // that the output order does not depend on the hash map.
349 std::vector<std::pair<int, int>> scored(muList.begin(), muList.end());
350 std::sort(scored.begin(), scored.end());
351 for (const auto& [i, hit] : scored) {
352 auto* track = getMCTrack(i);
353 auto* v = getVetoPoint(hit);
354 const Double_t m = track->GetMass();
355 e = TMath::Sqrt(v->GetPx() * v->GetPx() + v->GetPy() * v->GetPy() +
356 v->GetPz() * v->GetPz() + m * m);
357 IncrementCounter("transported_tracks");
358 IncrementCounter("plane_copies");
359 cpg->AddTrack(track->GetPdgCode(), v->GetPx(), v->GetPy(), v->GetPz(),
360 v->GetX(), v->GetY(), v->GetZ(), i, true, e,
361 v->GetTime() / 1E9, // convert back from ns to sec
362 track->GetWeight(), kPTransportation);
363 }
364 return kTRUE;
365 }
366 auto [dx, dy] = CalculateBeamOffset(fsmearBeam, fPaintBeam);
367 if (id == -1) {
368 for (int i = 0; i < getMCTrackSize(); i++) {
369 auto* track = getMCTrack(i);
370 Int_t abspid = TMath::Abs(track->GetPdgCode());
371 px = track->GetPx();
372 py = track->GetPy();
373 pz = track->GetPz();
374 if (fPhiRandomize) {
375 double phi_random = gRandom->Uniform(0., 2 * TMath::Pi());
376 Double_t pt = track->GetPt();
377 px = pt * TMath::Cos(phi_random);
378 py = pt * TMath::Sin(phi_random);
379 }
380 vx = track->GetStartX() + dx;
381 vy = track->GetStartY() + dy;
382 vz = track->GetStartZ();
383 tof = track->GetStartT() / 1E9; // convert back from ns to sec;
384 e = track->GetEnergy();
385 Bool_t wanttracking = false; // only transport muons
386 if (auto element = muList.find(i); element != muList.end()) {
387 wanttracking = true;
388 if (!followMuons) {
389 auto* v = getVetoPoint(element->second);
390 TVector3 lpv = v->LastPoint();
391 TVector3 lmv = v->LastMom();
392 if (abspid == 22) {
393 e = lmv.Mag();
394 } else {
395 e = TMath::Sqrt(lmv.Mag2() +
396 (track->GetMass()) * (track->GetMass()));
397 }
398 px = lmv[0];
399 py = lmv[1];
400 pz = lmv[2];
401 vx = lpv[0];
402 vy = lpv[1];
403 vz = lpv[2];
404 tof = v->GetTime() / 1E9; // convert back from ns to sec
405 }
406 }
407 IncrementCounter("transported_tracks");
408 cpg->AddTrack(track->GetPdgCode(), px, py, pz, vx, vy, vz,
409 track->GetMotherId(), wanttracking, e, tof,
410 track->GetWeight(), (TMCProcess)track->GetProcID());
411 }
412 } else {
413 vx += dx / 100.;
414 vy += dy / 100.;
415 if (fPhiRandomize) {
416 double phi_random = gRandom->Uniform(0., 2 * TMath::Pi());
417 Double_t pt = TMath::Sqrt(px * px + py * py);
418 px = pt * TMath::Cos(phi_random);
419 py = pt * TMath::Sin(phi_random);
420 }
421 IncrementCounter("accepted_entries");
422 IncrementCounter("selected_muons");
423 cpg->AddTrack(static_cast<int>(pythiaid), px, py, pz, vx * 100., vy * 100.,
424 vz * 100., -1., false, e, pythiaid, parentid);
425 IncrementCounter("transported_tracks", 2);
426 cpg->AddTrack(static_cast<int>(id), px, py, pz, vx * 100., vy * 100.,
427 vz * 100., -1., true, e, tof, w);
428 }
429 return kTRUE;
430}
431
432// -------------------------------------------------------------------------
std::pair< Double_t, Double_t > CalculateBeamOffset(Double_t smearBeam, Double_t paintBeam)
const Int_t debug
constexpr Double_t cm
constexpr Double_t m
TClonesArray * MCTrack
TChain * fTree
flag to indicate if using STL vectors
TClonesArray * vetoPoints
Bool_t checkDiMuon(Int_t muIndex)
std::vector< vetoPoint > * vetoPoints_vec
Bool_t ReadEvent(FairPrimaryGenerator *) override
std::vector< ShipMCTrack > * MCTrack_vec
Bool_t Init(const char *, int) override
void IncrementCounter(const std::string &name, Long64_t delta=1)
Definition Generator.h:65
Int_t GetPdgCode() const
Definition ShipMCTrack.h:60
constexpr double mm
Definition ShipUnit.h:25
constexpr double cm
Definition ShipUnit.h:23
constexpr double mm
Definition ShipUnit.h:25