FairShip
Loading...
Searching...
No Matches
exitHadronAbsorber.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 <algorithm>
8#include <cmath>
9#include <cstddef>
10#include <iostream>
11#include <iterator>
12#include <limits>
13
14#include "CLHEP/Units/SystemOfUnits.h"
15#include "FairGeoBuilder.h"
16#include "FairGeoInterface.h"
17#include "FairGeoLoader.h"
18#include "FairGeoMedia.h"
19#include "FairGeoNode.h"
20#include "FairGeoVolume.h"
21#include "FairLogger.h"
22#include "FairRootManager.h"
23#include "FairVolume.h"
24#include "G4LogicalVolume.hh"
25#include "G4ParticleDefinition.hh"
26#include "G4Step.hh"
27#include "G4StepPoint.hh"
28#include "G4Track.hh"
29#include "G4VPhysicalVolume.hh"
30#include "Randomize.hh"
31#include "ShipDetectorList.h"
32#include "ShipMCTrack.h"
33#include "ShipStack.h"
34#include "ShipUnit.h"
35#include "TArrayI.h"
36#include "TDatabasePDG.h"
37#include "TGeoBBox.h"
38#include "TGeoBoolNode.h"
39#include "TGeoEltu.h"
40#include "TGeoManager.h"
41#include "TGeoMaterial.h"
42#include "TH1D.h"
43#include "TH2D.h"
44#include "TLorentzVector.h"
45#include "TMCProcess.h"
46#include "TParticle.h"
47#include "TROOT.h"
48#include "TVirtualMC.h"
49#include "vetoPoint.h"
50
51using std::cout;
52using std::endl;
53
54using ShipUnit::cm;
55using ShipUnit::m;
56using ShipUnit::mm;
57
58namespace {
59
63struct HistogrammedParticle {
64 Int_t pdg;
65 bool withAntiparticle;
66};
67constexpr HistogrammedParticle kHistogrammed[] = {
68 {11, true}, {12, true}, {13, true}, {14, true}, {15, true},
69 {16, true}, {17, true}, {22, false}, {111, false}, {221, false},
70 {223, false}, {331, false}, {211, true}, {321, true}, {2212, true}};
71
74Int_t HistogramId(Int_t pdg) {
75 return 10000 + TMath::Abs(pdg) + (pdg < 0 ? 10000 : 0);
76}
77
78// ShipStack::PushTrack multiplies the weight of a pushed track by that of the
79// track it names as parent, and leaves it alone for a primary. A clone that
80// should end up with weight w is therefore pushed with w divided by this.
81Double_t PushedWeightScale(Int_t parentId) {
82 if (parentId < 0) {
83 return 1.;
84 }
85 auto* stack = dynamic_cast<ShipStack*>(gMC->GetStack());
86 TParticle* parent = stack->GetParticle(parentId);
87 if (!parent || parent->GetWeight() <= 0.) {
88 return 1.;
89 }
90 return parent->GetWeight();
91}
92
93} // namespace
94
99std::map<Int_t, exitHadronAbsorber::WeightHistory>
102
104 // A secondary made at the end of a step and the split on that step share
105 // the Geant4 post-step time, but geant4_vmc converts it to seconds by
106 // division for the split (TrackPosition) and by multiplication with the
107 // inverse unit for the secondary (stack push), so the two can differ by an
108 // ulp or two. A few ulp of tolerance covers that and stays far below the
109 // time of any real step. Split times increase strictly (a split needs a
110 // step of non-zero length), so the lookup is a binary search.
111 const Double_t tMax =
112 t + 4 * std::numeric_limits<Double_t>::epsilon() * std::abs(t);
113 const auto after = std::upper_bound(
114 splits.begin(), splits.end(), tMax,
115 [](Double_t time, const auto& split) { return time < split.first; });
116 return after == splits.begin() ? initial : std::prev(after)->second;
117}
118
119exitHadronAbsorber::exitHadronAbsorber(const char* Name, Bool_t Active)
120 : Detector(Name, Active, kVETO),
121 fOnlyMuons(kFALSE),
122 fSkipNeutrinos(kFALSE),
123 fVetoName("veto"),
124 fzPos(3E8),
125 withNtuple(kFALSE),
126 fCylindricalPlane(kFALSE),
127 fUseCaveCoordinates(kFALSE),
128 fNsplits(0),
130
132 : Detector("exitHadronAbsorber", kTRUE, kVETO),
133 fUniqueID(-1),
134 fOnlyMuons(kFALSE),
135 fSkipNeutrinos(kFALSE),
136 fVetoName("veto"),
137 fzPos(3E8),
138 withNtuple(kFALSE),
139 fCylindricalPlane(kFALSE),
140 fUseCaveCoordinates(kFALSE),
141 fNsplits(0),
143
145 // Guard the conversion: a negative value would become a huge std::size_t and
146 // silently disable the safety valve.
147 if (n < 1) {
148 LOG(error) << "exitHadronAbsorber: max split buffer must be >= 1, ignoring "
149 << n;
150 return;
151 }
152 fMaxSplitBuffer = static_cast<std::size_t>(n);
153}
154
156 if (n < 1) {
157 LOG(error) << "exitHadronAbsorber: max event size must be >= 1, ignoring "
158 << n;
159 return;
160 }
161 fMaxEventSize = static_cast<std::size_t>(n);
162}
163
164Bool_t exitHadronAbsorber::ProcessHits(FairVolume* vol) {
166 TString volName = gMC->CurrentVolName();
167
168 // Only this detector's own plane: other exitHadronAbsorber planes share the
169 // name prefix.
170 if (volName == fPlaneVolName) {
171 if (gMC->IsTrackEntering()) {
172 fTrackID = gMC->GetStack()->GetCurrentTrackNumber();
173 fEventID = gMC->CurrentEvent();
174 TParticle* p = gMC->GetStack()->GetCurrentTrack();
175 fUniqueID = p->GetUniqueID();
176 Int_t pdgCode = p->GetPdgCode();
177 gMC->TrackMomentum(fMom);
178 if (!fOnlyMuons || TMath::Abs(pdgCode) == 13) {
179 fTime = gMC->TrackTime() * 1.0e09;
180 fLength = gMC->TrackLength();
181 gMC->TrackPosition(fPos);
182 if (((fMom.E() - fMom.M()) > EMax) &&
183 (fgReplacedTracks.count(fTrackID) == 0)) {
185 TVector3(fPos.X(), fPos.Y(), fPos.Z()),
186 TVector3(fMom.Px(), fMom.Py(), fMom.Pz()), fTime, fLength, 0,
187 pdgCode, TVector3(p->Vx(), p->Vy(), p->Vz()),
188 TVector3(p->Px(), p->Py(), p->Pz()));
189 auto* stack = dynamic_cast<ShipStack*>(gMC->GetStack());
190 stack->AddPoint(kVETO);
191 }
192 }
193 }
194
195 if ((!fCylindricalPlane) && fzPos > 1E8) {
196 gMC->StopTrack();
197 }
198 }
199
200 return kTRUE;
201}
202
203void exitHadronAbsorber::SplitStepHook(const G4Step* step) {
204 if (fgSplitter) {
205 fgSplitter->SplitStep(step);
206 }
207}
208
209void exitHadronAbsorber::SplitStep(const G4Step* step) {
210 const G4Track* track = step->GetTrack();
211 const G4ParticleDefinition* def = track->GetDefinition();
212 const Int_t track_pid = def->GetPDGEncoding();
213 if (std::abs(track_pid) != 211 && std::abs(track_pid) != 321) {
214 return;
215 }
216 ++fHookSteps;
217 const Int_t currentTrackId = gMC->GetStack()->GetCurrentTrackNumber();
218 if (fCloneTracks.count(currentTrackId) > 0 ||
219 fgReplacedTracks.count(currentTrackId) > 0) {
220 return;
221 }
222
223 // Whether this step is split is decided from the pre-step point only: its
224 // volume, its kinetic energy and the decay length there. None of them depends
225 // on how the step ends. If the decision depended on it, as it did when the
226 // split ran in ProcessHits() for the steps FairRoot attributes to a splitting
227 // volume, steps ending in a decay would be split more often than steps ending
228 // on a volume boundary, and the decay weight would no longer add up to the
229 // decay probability.
230 const G4StepPoint* pre = step->GetPreStepPoint();
231 const G4StepPoint* post = step->GetPostStepPoint();
232 const G4VPhysicalVolume* preVolume = pre->GetPhysicalVolume();
233 if (!preVolume ||
234 fSplitVolumes.count(preVolume->GetLogicalVolume()->GetName()) == 0) {
235 return;
236 }
237 const Double_t mass = def->GetPDGMass() / CLHEP::GeV;
238 if (pre->GetKineticEnergy() / CLHEP::GeV <= EMax) {
239 return;
240 }
241 const Double_t delta_s = step->GetStepLength() / CLHEP::cm;
242 if (delta_s <= 0) {
243 return;
244 }
245 TParticle* part = gMC->GetStack()->GetCurrentTrack();
246 if (!part) {
247 return;
248 }
249
250 // Decay length beta gamma c tau at the pre-step momentum, as G4Decay
251 // computes it for the step.
252 const Double_t c_tau = def->GetPDGLifeTime() / CLHEP::cm * CLHEP::c_light;
253 if (c_tau <= 0) {
254 return;
255 }
256 const G4ThreeVector pPre = pre->GetMomentum() / CLHEP::GeV;
257 const G4ThreeVector pPost = post->GetMomentum() / CLHEP::GeV;
258 const Double_t lambda_decay = pPre.mag() / mass * c_tau;
259 const Double_t P_decay = 1.0 - std::exp(-delta_s / lambda_decay);
260 if (!(P_decay > 0.0)) {
261 return;
262 }
263
264 double polX = 0, polY = 0, polZ = 0;
265 TVector3 polVector;
266 part->GetPolarisation(polVector);
267 polX = polVector.X();
268 polY = polVector.Y();
269 polZ = polVector.Z();
270 Int_t trueParentId = part->GetFirstMother();
271
272 // Reserve room for the fNsplits endpoint clones PostTrack() appends
273 // when the parent finally decays, so the buffer never exceeds
274 // fMaxSplitBuffer. All terms are on the left to keep the unsigned
275 // arithmetic from wrapping.
276 const std::size_t secondaryBufferSize = fSecondaryBuffer.size();
277 const std::size_t event_size = gMC->GetStack()->GetNtrack();
278
279 const std::size_t pending = secondaryBufferSize +
280 static_cast<std::size_t>(fIntermediateNsplits) +
281 static_cast<std::size_t>(fNsplits);
282 const bool bufferFull = pending > fMaxSplitBuffer;
283 const std::size_t projected_size = event_size + pending * kShowerSafetyFactor;
284 const bool eventFull = projected_size > fMaxEventSize;
285 if (bufferFull || eventFull) {
286 // Skip the split for this step instead of truncating the buffer. The
287 // track weight is the ledger: leaving it untouched means the weight we
288 // did not split off is still carried by the track, and reaches the
289 // natural-decay clones in PostTrack() if the track ends in a decay. The
290 // total weight the track contributes is unchanged, only the statistical
291 // boost is reduced. The caps depend on the buffer, not on how this step
292 // ends, so skipping keeps the split decision independent of the decay.
293 if (bufferFull && !fSplitBufferLimitWarned) {
294 LOG(warning) << "exitHadronAbsorber: intermediate split buffer "
295 "reached "
296 << secondaryBufferSize
297 << " entries; skipping further per-step splitting "
298 "(reported once per event). Consider lowering "
299 "--intermediate-kaon-pion-splits or raising "
300 "--max-split-buffer.";
302 }
303 if (eventFull && !fEventSizeLimitWarned) {
304 LOG(warning) << "exitHadronAbsorber: event size reached " << event_size
305 << " entries, projected size " << projected_size
306 << " with the pending split clones; skipping "
307 "further per-step splitting (reported once per "
308 "event). Consider lowering "
309 "--intermediate-kaon-pion-splits or raising "
310 "--max-event-size.";
311 fEventSizeLimitWarned = kTRUE;
312 }
313 return;
314 }
315
316 // The track's own weight is the ledger: it starts at whatever the track was
317 // pushed with and loses the decay branch at every split. The clones get
318 // exactly what the track loses, so track + clones keep the weight the track
319 // started with at every step, whatever that weight is, even if it differs
320 // from that of the track ShipStack scales the clones by (see
321 // PushedWeightScale). Lowering the track's weight also keeps everything it
322 // goes on to do in step: its hit at the sensitive plane, and the
323 // secondaries it makes if it ends by interacting rather than decaying.
324 // Geant4 pushes a secondary onto the VMC stack when that secondary starts
325 // tracking, which is after the parent is done, so the secondaries pick this
326 // up on their own. This relies on /mcTracking/saveSecondariesInStep staying
327 // off (see gconfig/g4config.in); turning it on pushes secondaries during the
328 // step that makes them. Secondaries made mid-track by processes that do not
329 // end it (delta rays, elastic recoils) are pushed with the parent's final
330 // weight as well; PreTrack() rescales them to its weight at the step that
331 // made them, from the history recorded below.
332 const Double_t trackWeight = part->GetWeight();
333 const Double_t cloneWeight = trackWeight * P_decay / fIntermediateNsplits /
334 PushedWeightScale(trueParentId);
335 const Int_t splitSet = SplitSetOf(currentTrackId, trackWeight);
336
337 // Each clone decays where the track would have: at a distance along the
338 // step drawn from the decay distribution restricted to the step,
339 // s = -lambda ln(1 - u P_decay), u uniform in [0, 1),
340 // interpolated between the pre- and post-step points. Putting every clone at
341 // the post-step point instead piles the decays of a long step (e.g. through
342 // the helium between target slabs) up at the next volume boundary.
343 //
344 // The momentum is only interpolated if the track survives the step. A step
345 // that ends the track (an inelastic interaction, its own decay) leaves the
346 // post-step point with the momentum after that process, zero for a killed
347 // track, so interpolating towards it would give the clones of every track's
348 // last step too little momentum. Up to the interaction the track only loses
349 // energy continuously, which is negligible over one step, so those clones get
350 // the pre-step momentum.
351 const G4ThreeVector pEnd = track->GetTrackStatus() == fAlive ? pPost : pPre;
352 const G4ThreeVector xPre = pre->GetPosition() / CLHEP::cm;
353 const G4ThreeVector xPost = post->GetPosition() / CLHEP::cm;
354 const Double_t tPre = pre->GetGlobalTime() / CLHEP::s;
355 const Double_t tPost = post->GetGlobalTime() / CLHEP::s;
356 for (int i = 0; i < fIntermediateNsplits; ++i) {
357 const Double_t s =
358 -lambda_decay * std::log(1.0 - G4UniformRand() * P_decay);
359 const Double_t f = std::clamp(s / delta_s, 0.0, 1.0);
360 const G4ThreeVector x = xPre + f * (xPost - xPre);
361 const G4ThreeVector p = pPre + f * (pEnd - pPre);
362 TrackBuffer clone;
363 clone.pdg = track_pid;
364 clone.px = p.x();
365 clone.py = p.y();
366 clone.pz = p.z();
367 clone.e = std::sqrt(p.mag2() + mass * mass);
368 clone.x = x.x();
369 clone.y = x.y();
370 clone.z = x.z();
371 clone.t = tPre + f * (tPost - tPre);
372 clone.polx = polX;
373 clone.poly = polY;
374 clone.polz = polZ;
375 clone.weight = cloneWeight;
376 clone.parentID = trueParentId;
377 clone.splitSet = splitSet;
378 clone.splitRole = ShipMCTrack::kSplitDecay;
379 fSecondaryBuffer.push_back(clone);
380 }
381 part->SetWeight(trackWeight * (1.0 - P_decay));
382 auto [history, isNew] = fgWeightHistory.try_emplace(currentTrackId);
383 if (isNew) {
384 history->second.initial = trackWeight;
385 }
386 // Post-step time in seconds, converted by division as TrackPosition() does;
387 // WeightHistory::WeightAt() allows for the ulp it can differ by from the
388 // time of a secondary pushed at the same point.
389 history->second.splits.emplace_back(tPost, trackWeight * (1.0 - P_decay));
390 fSplitDecays++;
392 fLastSplitTrackID = currentTrackId;
393 fLastSplitStep = track->GetCurrentStepNumber();
395}
396
399 // PostTrack() buffers fNsplits endpoint clones for every splitting decay in
400 // both modes, without consulting the cap, so a cap below fNsplits breaks the
401 // hard bound. With per-step splitting it also makes the SplitStep()
402 // reservation permanently unsatisfiable, disabling per-step splitting.
403 if (fNsplits > 0 && static_cast<std::size_t>(fNsplits) > fMaxSplitBuffer) {
404 LOG(fatal) << "exitHadronAbsorber: max split buffer (" << fMaxSplitBuffer
405 << ") must be at least the endpoint split count (" << fNsplits
406 << ")";
407 }
408 if (fNsplits > 0 && fIntermediateNsplits > 0 && !fSplitOnce) {
409 if (fgSplitter && fgSplitter != this) {
410 LOG(fatal) << "exitHadronAbsorber: only one instance can split per step";
411 }
412 fgSplitter = this;
413 }
414 TSeqCollection* fileList = gROOT->GetListOfFiles();
415 fout = dynamic_cast<TFile*>(fileList->At(0));
416 // book hists for Genie neutrino momentum distribution, and for the other
417 // particles in kHistogrammed
418 TDatabasePDG* PDG = TDatabasePDG::Instance();
419 for (const auto& particle : kHistogrammed) {
420 for (Int_t sign : {1, -1}) {
421 if (sign < 0 && !particle.withAntiparticle) {
422 continue;
423 }
424 const Int_t idw = sign * particle.pdg;
425 const Int_t idhnu = HistogramId(idw);
426 TString name = PDG->GetParticle(idw)->GetName();
427 TString title = name;
428 title += " momentum (GeV)";
429 TString key = fVetoName;
430 key += idhnu;
431 [[maybe_unused]] TH1D* Hidhnu = new TH1D(key, title, 400, 0., 400.);
432 title = name;
433 title += " log10-p vs log10-pt";
434 key = fVetoName;
435 key += idhnu + 1000;
436 [[maybe_unused]] TH2D* Hidhnu100 =
437 new TH2D(key, title, 100, -0.3, 1.7, 100, -2., 0.5);
438 title = name;
439 title += " log10-p vs log10-pt";
440 key = fVetoName;
441 key += idhnu + 2000;
442 [[maybe_unused]] TH2D* Hidhnu200 =
443 new TH2D(key, title, 25, -0.3, 1.7, 100, -2., 0.5);
444 }
445 }
446 if (withNtuple) {
447 fNtuple = new TNtuple("4DP", "4DP", "id:px:py:pz:x:y:z");
448 }
449}
450
453 fCloneTracks.clear();
454 fgReplacedDecays.clear();
455 fgReplacedTracks.clear();
456 fgWeightHistory.clear();
457 fgWeightCorrected.clear();
459 fLastSplitStep = -1;
460 fSplitSetOfTrack.clear();
461 fSplitSetWeight.clear();
462 fNextSplitSet = 0;
464 fEventSizeLimitWarned = kFALSE;
465}
466
468 // Checked here rather than at the start of the next event so that the last
469 // event of a run is covered too.
471}
472
474 if (fSecondaryBuffer.empty()) {
475 return;
476 }
477 // No track carried these clones to the stack popper before the event
478 // ended, so their weight never made it into the simulation.
479 Double_t lostWeight = 0;
480 for (const auto& trk : fSecondaryBuffer) {
481 lostWeight += trk.weight;
482 }
484 fLostCloneTracks += static_cast<Int_t>(fSecondaryBuffer.size());
485 fLostCloneWeight += lostWeight;
486 LOG(warning) << "exitHadronAbsorber: discarding " << fSecondaryBuffer.size()
487 << " buffered split clones (summed weight " << lostWeight
488 << ") which no track handed to the stack popper";
489 fSecondaryBuffer.clear();
490}
491
492Int_t exitHadronAbsorber::SplitSetOf(Int_t trackId, Double_t weight) {
493 const auto it = fSplitSetOfTrack.find(trackId);
494 if (it != fSplitSetOfTrack.end()) {
495 return it->second;
496 }
497 const Int_t splitSet = fNextSplitSet++;
498 fSplitSetOfTrack.emplace(trackId, splitSet);
499 fSplitSetWeight.push_back(weight);
500 if (auto* stack = dynamic_cast<ShipStack*>(gMC->GetStack())) {
501 stack->SetSplitSet(trackId, splitSet, ShipMCTrack::kSplitSurvivor, weight);
502 }
503 return splitSet;
504}
505
507 Int_t currentTrackId = gMC->GetStack()->GetCurrentTrackNumber();
508
509 // A replaced track can only get here as a carrier. Its decay is either part
510 // of one that the clones already re-sample, or one an unsplit run would not
511 // have, so it must not be split: its clones would be exempt from the cut.
512 if (fCloneTracks.count(currentTrackId) > 0 ||
513 fgReplacedTracks.count(currentTrackId) > 0) {
514 return;
515 }
516
517 Int_t track_pid = gMC->TrackPid();
518 bool kaon_or_pion =
519 (TMath::Abs(track_pid) == 211 || TMath::Abs(track_pid) == 321);
520
521 if (fNsplits > 0 && kaon_or_pion) {
522 bool isNaturalDecay = false;
523 TArrayI processes;
524 gMC->StepProcesses(processes);
525 for (int i = 0; i < processes.GetSize(); i++) {
526 if (processes[i] == kPDecay) {
527 isNaturalDecay = true;
528 break;
529 }
530 }
531
532 TParticle* part = gMC->GetStack()->GetCurrentTrack();
533 if (!part) return;
534
535 TLorentzVector finalPos, finalMom;
536 gMC->TrackPosition(finalPos);
537 gMC->TrackMomentum(finalMom);
538
539 double polX = 0, polY = 0, polZ = 0;
540 TVector3 polVector;
541 part->GetPolarisation(polVector);
542 polX = polVector.X();
543 polY = polVector.Y();
544 polZ = polVector.Z();
545 Int_t trueParentId = part->GetFirstMother();
546
547 // A track that decays hands all of its remaining weight to the endpoint
548 // clones. With per-step splitting its weight has already been lowered by
549 // every split along the way.
550 //
551 // Except where the per-step split already covered the step. There, the
552 // clones of every step are the track's decays, and its weight e^(-tau) is
553 // what survives them. Letting Geant4 decay the track as well would apply
554 // the decay probability twice: the track would be both removed with
555 // probability 1 - e^(-tau) and down-weighted by e^(-tau), which roughly
556 // doubles the decay yield when interactions dominate. So a natural decay
557 // on a split step is not a decay: the track is pushed again at the decay
558 // point as a continuation with its current weight. The decay length is
559 // exponential, so this is the same as switching the decay off while the
560 // track is being split. Off the split steps (outside the volumes
561 // registered for splitting, below the energy cut, or with the buffer
562 // full) the natural decay stands and goes to the endpoint clones.
563 const Bool_t splitThisStep = !fSplitOnce &&
564 fLastSplitTrackID == currentTrackId &&
565 fLastSplitStep == gMC->StepNumber();
566 if (isNaturalDecay) {
567 TrackBuffer endpoint;
568 endpoint.pdg = track_pid;
569 endpoint.px = finalMom.Px();
570 endpoint.py = finalMom.Py();
571 endpoint.pz = finalMom.Pz();
572 endpoint.e = finalMom.E();
573 endpoint.x = finalPos.X();
574 endpoint.y = finalPos.Y();
575 endpoint.z = finalPos.Z();
576 endpoint.t = finalPos.T();
577 endpoint.polx = polX;
578 endpoint.poly = polY;
579 endpoint.polz = polZ;
580 endpoint.parentID = trueParentId;
581 // The continuation stays on the survivor side of the set; endpoint
582 // clones are its decay alternatives.
583 endpoint.splitSet = SplitSetOf(currentTrackId, part->GetWeight());
584 endpoint.splitRole = splitThisStep ? ShipMCTrack::kSplitSurvivor
586 if (splitThisStep) {
587 endpoint.weight = part->GetWeight() / PushedWeightScale(trueParentId);
588 endpoint.continuation = kTRUE;
589 fSecondaryBuffer.push_back(endpoint);
591 } else {
592 endpoint.weight =
593 part->GetWeight() / fNsplits / PushedWeightScale(trueParentId);
594 for (int i = 0; i < fNsplits; ++i) {
595 fSecondaryBuffer.push_back(endpoint);
596 }
597 fSplitDecays++;
599 }
600 // Either way the products of this decay are replaced.
601 fgReplacedDecays.insert(currentTrackId);
603 }
604
605 // A track that ends any other way keeps the remaining weight itself, so
606 // there is nothing to hand on. Geant4 never gives us a track that is
607 // still going: G4TrackingManager steps while the status is fAlive or
608 // fStopButAlive, TG4TrackingAction::PostUserTrackingAction skips
609 // PostTrack for fSuspend, and IsTrackStop() covers every status that is
610 // left. StopTrack() stays because it is the one call here that can still
611 // matter for a status other than fStopAndKill.
612 gMC->StopTrack();
613 }
614}
615
617 // Invariant for this whole method: the clone buffer may only be handed to a
618 // carrier that is guaranteed to step. TG4StackPopper converts pushed tracks
619 // into Geant4 secondaries from PostStepDoIt only, and its Reset() at the
620 // start of the next track writes off everything still pending, so a carrier
621 // stopped before its first step swallows the entire set. Every reason to stop
622 // this track is therefore settled before the flush at the end.
623 gMC->TrackMomentum(fMom);
624 TParticle* p = gMC->GetStack()->GetCurrentTrack();
625 Int_t currentID = gMC->GetStack()->GetCurrentTrackNumber();
626 Bool_t isClone = (fCloneTracks.find(currentID) != fCloneTracks.end());
627
628 // Claim the carrier for the clones buffered by the last splitting decay. A
629 // decay always puts its daughters on the stack, so some track always follows
630 // it; only the cuts below can strand the buffer until the event ends.
631 Bool_t isCarrier =
634 fgCarrierTrackID = currentID;
635 }
636
637 Int_t pdgCode = p->GetPdgCode();
638 Int_t idabs = TMath::Abs(pdgCode);
639 Bool_t belowCut = (fMom.E() - fMom.M()) < EMax;
640 Bool_t skippedNeutrino =
641 fSkipNeutrinos && (idabs == 12 || idabs == 14 || idabs == 16);
642
643 // Products of a replaced decay, and their descendants, are replaced too.
644 // Every instance runs this, so the set is complete before any track steps.
645 // A replaced track's secondaries can pass the cut even if it does not,
646 // because a decay turns rest mass into kinetic energy (a slow pi0 can give a
647 // photon above it), so they have to be stopped by ancestry, not by energy.
648 const Int_t motherId = p->GetFirstMother();
649
650 // A Geant4 secondary of a per-step split track was pushed with the track's
651 // final weight; give it the weight the track had when it made it. This
652 // precedes every stop below, so stopped secondaries are stored with the
653 // right weight too, and their own secondaries inherit it. Clones and
654 // continuations (kPNoProcess) already carry exact weights.
655 const auto history = fgWeightHistory.find(motherId);
656 if (history != fgWeightHistory.end() && p->GetUniqueID() != kPNoProcess &&
657 fgWeightCorrected.insert(currentID).second) {
658 auto* shipStack = dynamic_cast<ShipStack*>(gMC->GetStack());
659 const TParticle* mother =
660 shipStack ? shipStack->GetParticle(motherId) : nullptr;
661 const Double_t finalWeight = mother ? mother->GetWeight() : 0.;
662 if (finalWeight > 0.) {
663 p->SetWeight(p->GetWeight() * history->second.WeightAt(p->T()) /
664 finalWeight);
665 }
666 }
667 if (fgReplacedDecays.count(motherId) > 0 ||
668 fgReplacedTracks.count(motherId) > 0) {
669 fgReplacedTracks.insert(currentID);
670 }
671 const Bool_t isReplaced = fgReplacedTracks.count(currentID) > 0;
672
673 if (!isClone && !isCarrier && (belowCut || isReplaced)) {
674 // Do NOT flush the clone buffer into this track: it is stopped before its
675 // first step, so the stack popper would never run for it and the pending
676 // clones would be silently discarded at the next track's popper reset.
677 // The designated carrier is exempt so that it does step, and is replaced
678 // below instead.
679 //
680 // Clones are exempt from the cut. They are a bookkeeping device that has
681 // to decay immediately (ForceDecayTime(0)) so that the decay can be
682 // re-sampled, and their parent already passed the cut at the start of its
683 // own track. Applying the cut again at the decay point would drop decay
684 // products which an unsplit run keeps, because there the cut acts on the
685 // (possibly much harder) decay muon rather than on the parent. The decay
686 // products of the clones are cut as usual.
687 gMC->StopTrack();
688 return;
689 }
690
691 // A carrier that an unsplit run would have stopped, below the cut or as a
692 // skipped neutrino, is replaced: it steps, but ProcessHits does not score
693 // it, it is not split, and its descendants are stopped above. Clones are
694 // never replaced this way: their parent is the split track, not the carrier.
695 const Bool_t isCarrierOnly = isCarrier && !isClone;
696 if (isCarrierOnly && (belowCut || skippedNeutrino)) {
697 fgReplacedTracks.insert(currentID);
698 }
699
700 // A carrier that is below the cut or replaced by ancestry only has to step
701 // so that the stack popper hands the clones over. An unsplit run would not
702 // have it, so it must not reach the histograms or the ntuple. The exception
703 // is a neutrino above the cut, which an unsplit run records before stopping
704 // it.
705 const Bool_t recordStatistics = !(isCarrierOnly && (belowCut || isReplaced));
706
707 // record statistics for neutrinos, electrons and photons
708 // add pi0 111 eta 221 eta' 331 omega 223
709 if (recordStatistics && (idabs < 18 || idabs == 22 || idabs == 111 ||
710 idabs == 221 || idabs == 223 || idabs == 331 ||
711 idabs == 211 || idabs == 321 || idabs == 2212)) {
712 Double_t wspill = p->GetWeight();
713 Int_t idhnu = idabs + 10000;
714 if (pdgCode < 0) {
715 idhnu += 10000;
716 }
717 Double_t l10ptot =
718 TMath::Min(TMath::Max(TMath::Log10(fMom.P()), -0.3), 1.69999);
719 Double_t l10pt =
720 TMath::Min(TMath::Max(TMath::Log10(fMom.Pt()), -2.), 0.4999);
721 TString key = fVetoName;
722 key += idhnu;
723 TH1D* h1 = dynamic_cast<TH1D*>(fout->Get(key));
724 if (h1) {
725 h1->Fill(fMom.P(), wspill);
726 }
727 key = fVetoName;
728 key += idhnu + 1000;
729 TH2D* h2 = dynamic_cast<TH2D*>(fout->Get(key));
730 if (h2) {
731 h2->Fill(l10ptot, l10pt, wspill);
732 }
733 key = fVetoName;
734 key += idhnu + 2000;
735 h2 = dynamic_cast<TH2D*>(fout->Get(key));
736 if (h2) {
737 h2->Fill(l10ptot, l10pt, wspill);
738 }
739 if (withNtuple) {
740 fNtuple->Fill(pdgCode, fMom.Px(), fMom.Py(), fMom.Pz(), fPos.X(),
741 fPos.Y(), fPos.Z());
742 }
743 if (skippedNeutrino && !isCarrier) {
744 // The statistics above are still recorded, but the track is stopped
745 // before its first step, so it must not receive the clone buffer.
746 gMC->StopTrack();
747 return;
748 }
749 }
750
751 // A module whose PreTrack() ran before ours may already have stopped the
752 // track: FairMCApplication calls the detectors in registration order, and
753 // run_fixedTarget.py registers the other exitHadronAbsorber planes ahead of
754 // the one that owns the split buffer. A module registered after this one is
755 // not covered: if it stops the track, the clones flushed below are lost.
756 if (!gMC->IsTrackAlive()) {
757 return;
758 }
759
760 if (!fSecondaryBuffer.empty()) {
761 auto* stack = dynamic_cast<ShipStack*>(gMC->GetStack());
762 Int_t ntr;
763 for (const auto& trk : fSecondaryBuffer) {
764 stack->PushTrack(1, trk.parentID, trk.pdg, trk.px, trk.py, trk.pz, trk.e,
765 trk.x, trk.y, trk.z, trk.t, trk.polx, trk.poly, trk.polz,
766 kPNoProcess, ntr, trk.weight, 999);
767 if (!trk.continuation) {
768 fCloneTracks.insert(ntr);
769 }
770 if (trk.splitSet >= 0) {
771 stack->SetSplitSet(ntr, trk.splitSet, trk.splitRole,
772 fSplitSetWeight[trk.splitSet]);
773 if (trk.splitRole == ShipMCTrack::kSplitSurvivor) {
774 fSplitSetOfTrack[ntr] = trk.splitSet;
775 }
776 }
777 }
778 // Clear the buffer so we don't duplicate them for the next track
779 fSecondaryBuffer.clear();
780 }
781
782 if (isClone) {
783 // Force the decay time to 0
784 gMC->ForceDecayTime(0);
785 }
786}
787
789 if (fgSplitter == this && fHookSteps == 0) {
790 LOG(error) << "exitHadronAbsorber: per-step splitting is enabled but no "
791 "kaon or pion step reached SplitStep(); the Geant4 run "
792 "configuration must use ShipRunConfiguration (see "
793 "gconfig/g4Config.C)";
794 }
795 // BeginEvent only sees the buffer of the previous event, so the last event
796 // of the run has to be checked here.
798 if (fNsplits > 0) {
799 LOG(info) << "exitHadronAbsorber: split " << fSplitDecays
800 << " times, creating " << fClonesBuffered << " clones";
801 if (!fSplitOnce) {
802 LOG(info) << "exitHadronAbsorber: " << fContinuedDecays
803 << " natural decays on split steps continued instead";
804 }
805 if (fLostBufferEvents > 0) {
806 LOG(warning) << "exitHadronAbsorber: " << fLostBufferEvents
807 << " event(s) ended with buffered split clones, losing "
808 << fLostCloneTracks << " clones of summed weight "
810 } else {
811 LOG(info) << "exitHadronAbsorber: every buffered split clone was tracked";
812 }
813 }
814 for (const auto& particle : kHistogrammed) {
815 for (Int_t sign : {1, -1}) {
816 if (sign < 0 && !particle.withAntiparticle) {
817 continue;
818 }
819 const Int_t idhnu = HistogramId(sign * particle.pdg);
820 TString key = fVetoName;
821 key += idhnu;
822 TSeqCollection* fileList = gROOT->GetListOfFiles();
823 dynamic_cast<TFile*>(fileList->At(0))->cd();
824 TH1D* Hidhnu = dynamic_cast<TH1D*>(fout->Get(key));
825 Hidhnu->Write();
826 key = fVetoName;
827 key += idhnu + 1000;
828 TH2D* Hidhnu100 = dynamic_cast<TH2D*>(fout->Get(key));
829 Hidhnu100->Write();
830 key = fVetoName;
831 key += idhnu + 2000;
832 TH2D* Hidhnu200 = dynamic_cast<TH2D*>(fout->Get(key));
833 Hidhnu200->Write();
834 }
835 }
836 if (withNtuple) {
837 fNtuple->Write();
838 }
839}
840
841namespace {
842
843// Names of a volume and of all volumes below it.
844void CollectVolumeNames(TGeoVolume* volume, std::set<std::string>& names) {
845 if (!volume || !names.insert(volume->GetName()).second) {
846 return;
847 }
848 for (Int_t i = 0; i < volume->GetNdaughters(); ++i) {
849 TGeoNode* node = volume->GetNode(i);
850 if (node) {
851 CollectVolumeNames(node->GetVolume(), names);
852 }
853 }
854}
855
856} // namespace
857
859 static FairGeoLoader* geoLoad = FairGeoLoader::Instance();
860 static FairGeoInterface* geoFace = geoLoad->getGeoInterface();
861 static FairGeoMedia* media = geoFace->getMedia();
862 static FairGeoBuilder* geoBuild = geoLoad->getGeoBuilder();
863
864 FairGeoMedium* ShipMedium = media->getMedium("vacuums");
865 TGeoMedium* vac = gGeoManager->GetMedium("vacuums");
866 if (vac == nullptr) geoBuild->createMedium(ShipMedium);
867 vac = gGeoManager->GetMedium("vacuums");
868 gGeoManager->GetTopVolume();
869 TGeoNavigator* nav = gGeoManager->GetCurrentNavigator();
870 Double_t zLoc;
871 if (fzPos > 1E8) {
872 // Add thin sensitive plane after hadron absorber
873 Double_t local[3] = {0, 0, 0};
874 if (!nav->cd("/MuonShieldArea_1/AbsorberVol_1")) {
875 LOG(fatal) << "exitHadronAbsorber: no hadron absorber in the geometry, "
876 "add the muon shield or set the plane position explicitly";
877 }
878 TGeoBBox* tmp =
879 dynamic_cast<TGeoBBox*>(nav->GetCurrentNode()->GetVolume()->GetShape());
880 local[2] = tmp->GetDZ();
881 Double_t global[3] = {0, 0, 0};
882 nav->LocalToMaster(local, global);
883 zLoc = global[2] + 1. * cm;
884 } else {
885 zLoc = fzPos;
886 } // use external input
887
888 TString myname(this->GetName());
889 TString shapename_prefix(myname); // Use a prefix for shapenames
890
891 Double_t xLocPlane = 0.0;
892 Double_t yLocPlane = 0.0;
893 Double_t zLocPlane = zLoc;
894
895 if (!fCylindricalPlane) {
896 TGeoVolume* sensPlane =
897 gGeoManager->MakeBox(shapename_prefix + fVetoName + "_box", vac,
898 3.56 * m - 1. * mm, 1.7 * m - 1. * mm, 1. * mm);
899 std::cout << this->GetName()
900 << ", ConstructGeometry(): Created Box with dimensions: "
901 "3.56*m-1.*mm,1.7*m-1.*mm,1.*mm"
902 << std::endl;
903
904 if (!fUseCaveCoordinates) {
905 nav->cd("/MuonShieldArea_1/");
906 } else {
907 Double_t local[3] = {0, 0, zLoc};
908 Double_t global[3];
909 nav->cd("/target_vacuum_box_1/TargetArea_1");
910 nav->LocalToMaster(local, global);
911 nav->cd("/cave_1");
912 yLocPlane = global[1];
913 zLocPlane = global[2];
914 xLocPlane = global[0];
915 }
916 sensPlane->SetLineColor(kBlue - 10);
917 nav->GetCurrentNode()->GetVolume()->AddNode(
918 sensPlane, 1, new TGeoTranslation(xLocPlane, yLocPlane, zLocPlane));
919 fPlaneVolName = sensPlane->GetName();
920 AddSensitiveVolume(sensPlane);
921 } else { // add cylindrical sensPlane
922 TGeoVolume* sensPlaneCyl =
923 gGeoManager->MakeTube(shapename_prefix + fVetoName + "_tube", vac,
924 12.51 * cm, 12.52 * cm, zLoc / 2.);
925 std::cout << this->GetName()
926 << ", ConstructGeometry(): Created Tube with dimensions: "
927 "12.51*cm,12.52*cm,zLoc/2."
928 << std::endl;
929 nav->cd("/target_vacuum_box_1/TargetArea_1/HeVolume_1");
930 nav->GetCurrentNode()->GetVolume()->AddNode(sensPlaneCyl, 1,
931 new TGeoTranslation(0, 0, 0));
932 fPlaneVolName = sensPlaneCyl->GetName();
933 AddSensitiveVolume(sensPlaneCyl);
934 }
935 // Splitting region of SplitStep(): the target box and everything in it.
936 // These are not made sensitive: SplitStep() sees every step through
937 // ShipSteppingAction and checks the volume of the pre-step point.
938 if ((fNsplits > 0) && (fIntermediateNsplits > 0) && (!fSplitOnce)) {
939 nav->cd("/target_vacuum_box_1");
940 CollectVolumeNames(nav->GetCurrentNode()->GetVolume(), fSplitVolumes);
941 LOG(info) << "exitHadronAbsorber: per-step splitting in "
942 << fSplitVolumes.size() << " volumes below target_vacuum_box";
943 }
944}
945
947 fDetPoints = new std::vector<vetoPoint>();
948 TString name = fVetoName + "Point";
949 FairRootManager::Instance()->RegisterAny(name.Data(), fDetPoints, kTRUE);
950}
constexpr Double_t cm
constexpr Double_t m
@ kVETO
std::vector< vetoPoint > * fDetPoints
Definition Detector.h:90
vetoPoint * AddHit(Args &&... args)
Definition Detector.h:38
void Initialize() override
Definition Detector.h:46
@ kSplitDecay
a clone standing for one decay of the split track
Definition ShipMCTrack.h:34
@ kSplitSurvivor
the split track itself, or its continuation
Definition ShipMCTrack.h:33
TParticle * GetParticle(Int_t trackId) const
static constexpr Int_t kCarrierRequested
static constexpr Int_t kNoCarrier
void DiscardBufferedClones()
secondaries already rescaled
std::vector< Double_t > fSplitSetWeight
Int_t fContinuedDecays
clones created for those decays
static Int_t fgCarrierTrackID
std::map< Int_t, Int_t > fSplitSetOfTrack
static std::map< Int_t, WeightHistory > fgWeightHistory
void ConstructGeometry() override
void SetMaxSplitBuffer(Int_t n)
Int_t fNextSplitSet
indexed by set ID
Bool_t fUseCaveCoordinates
cylindrical sensPlane flag
static std::set< Int_t > fgReplacedDecays
Int_t SplitSetOf(Int_t trackId, Double_t weight)
Bool_t ProcessHits(FairVolume *v=nullptr) override
static void SplitStepHook(const G4Step *step)
Bool_t fCylindricalPlane
max energy to transport
Double_t fzPos
name of the sensitive plane volume
void FinishEvent() override
Double_t fLostCloneWeight
clones which were never tracked
static constexpr std::size_t kShowerSafetyFactor
int32_t fNsplits
set position from cave
std::vector< TrackBuffer > fSecondaryBuffer
Bool_t withNtuple
zPos, optional
Int_t fClonesBuffered
decays replaced by clones
static void RequestCloneCarrier()
static std::set< Int_t > fgReplacedTracks
Int_t fLostBufferEvents
natural decays replaced by a continuation
TString fVetoName
flag if neutrinos should be ignored
TFile * fout
summed weight of those clones
TNtuple * fNtuple
special option for Dark Photon physics studies
Bool_t fSkipNeutrinos
flag if only muons should be stored
static std::set< Int_t > fgWeightCorrected
void SplitStep(const G4Step *step)
Int_t fLostCloneTracks
events ending with unflushed clones
std::set< std::string > fSplitVolumes
static exitHadronAbsorber * fgSplitter
std::set< Int_t > fCloneTracks
constexpr double mm
Definition ShipUnit.h:25
int i
Definition ShipAna.py:108
constexpr double cm
Definition ShipUnit.h:23
constexpr double mm
Definition ShipUnit.h:25
constexpr double m
Definition ShipUnit.h:24
Double_t WeightAt(Double_t t) const
std::vector< std::pair< Double_t, Double_t > > splits