ATLAS Offline Software
Loading...
Searching...
No Matches
MuonSensitiveDetector.cxx
Go to the documentation of this file.
1
2/*
3 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
4*/
5
7
10#include <GeoModelKernel/throwExcept.h>
13
14#include <G4Geantino.hh>
15#include <G4ChargedGeantino.hh>
16
17#include <MCTruth/TrackHelper.h>
20
21using namespace ActsTrk;
22
23namespace {
24 static const SG::Decorator<int> dec_G4TrkId{"MuonSim_G4TrkId"};
25}
26
27namespace MuonG4R4 {
29 const std::string& output_key,
30 const std::string& trfStore_key,
31 const MuonGMR4::MuonDetectorManager* detMgr):
32 G4VSensitiveDetector{name},
33 AthMessaging{name},
34 m_writeKey{output_key},
35 m_trfCacheKey{trfStore_key},
36 m_detMgr{detMgr} {
37 m_trfCacheKey.initialize().ignore();
38 }
39 void MuonSensitiveDetector::Initialize(G4HCofThisEvent*) {
42 auto* hitVec = m_g4UserEventInfo->GetHitCollectionMap()->Find<MuonSimHitsVec>(m_writeKey);
43 if (!hitVec) {
44 THROW_EXCEPTION("The event does not contain a MuonSimHit container called '"<<m_writeKey<<"'");
45 }
46 m_outContainer = hitVec->container.get();
47 ATH_MSG_DEBUG(__func__<<"() "<<__LINE__<<" - Retrieved '"<<m_writeKey<<"'.");
48 } else {
49 m_outContainer = nullptr;
50 }
51 }
55 const EventContext& MuonSensitiveDetector::eventContext() const {
56 AtlasG4EventUserInfo* g4EventInfo = eventInfo();
57 if (!g4EventInfo) {
58 THROW_EXCEPTION("No AtlasG4EventUserInfo available");
59 }
60 return g4EventInfo->GetEventContext();
61 }
64 const ActsTrk::DetectorAlignStore* alignment{nullptr};
65 if (!SG::get(alignment, m_trfCacheKey, eventContext()).isSuccess()) {
66 THROW_EXCEPTION("Failed to retrieve "<<m_trfCacheKey.fullKey()<<".");
67 }
68 gctx.setStore(std::make_unique<DetectorAlignStore>(*alignment));
69 return gctx;
70 }
71 bool MuonSensitiveDetector::processStep(const G4Step* aStep) const {
72 const G4Track* currentTrack = aStep->GetTrack();
73 ATH_MSG_VERBOSE("Check whether step pdgId: "<<(*currentTrack)<<" will be processed.");
75 constexpr double velCutOff = 10.*Gaudi::Units::micrometer / Gaudi::Units::second;
76 if (aStep->GetStepLength() < std::numeric_limits<float>::epsilon() || currentTrack->GetVelocity() < velCutOff) {
77 ATH_MSG_VERBOSE("Step length is too short ");
78 return false;
79 }
81 if (currentTrack->GetDefinition()->GetPDGCharge() == 0.0) {
82 ATH_MSG_VERBOSE("Particle is neutral");
83 return currentTrack->GetDefinition() == G4Geantino::GeantinoDefinition() ||
84 currentTrack->GetDefinition() == G4ChargedGeantino::ChargedGeantinoDefinition();
85 }
86 return true;
87 }
89 TrackHelper trHelper{track};
90 AtlasG4EventUserInfo* g4EventInfo = eventInfo();
91 return trHelper.GenerateParticleLink(g4EventInfo ? g4EventInfo->GetEventStore() : nullptr);
92 }
94 const Amg::Transform3D& toGasGap,
95 const G4Step* aStep) {
96
97 const G4Track* currentTrack = aStep->GetTrack();
99 const Amg::Vector3D locPostStep{toGasGap*Amg::Hep3VectorToEigen(aStep->GetPostStepPoint()->GetPosition())};
100 Amg::Vector3D locPreStep{toGasGap*Amg::Hep3VectorToEigen(aStep->GetPreStepPoint()->GetPosition())};
101
103 Amg::Vector3D locHitDir = toGasGap.linear() * Amg::Hep3VectorToEigen(currentTrack->GetMomentumDirection());
104
107 xAOD::MuonSimHit* prevHit = lastSnapShot(hitID, aStep);
108 if (std::abs(currentTrack->GetParticleDefinition()->GetPDGEncoding()) == 11 && prevHit) {
109 locPreStep = xAOD::toEigen(prevHit->localPosition()) - 0.5* prevHit->stepLength() *
110 xAOD::toEigen(prevHit->localDirection());
111
112 locHitDir = (locPostStep - locPreStep).unit();
113 }
114 const Amg::Vector3D locHitPos = 0.5* (locPreStep + locPostStep);
115 ATH_MSG_VERBOSE( m_detMgr->idHelperSvc()->toStringGasGap(hitID)<<" - track: "<<(*currentTrack)
116 <<", deposit: "<<aStep->GetTotalEnergyDeposit()<<", -- local coords: "
117 <<"prestep: "<<Amg::toString(locPreStep)<<", post step: "<<Amg::toString(locPostStep)
118 <<" mid point: "<< Amg::toString(locHitPos)<<", direction: "<<Amg::toString(locHitDir)
119 <<", deposit: "<<aStep->GetTotalEnergyDeposit());
120
121 const double globalTime = currentTrack->GetGlobalTime() + locHitDir.dot(locPostStep - locHitPos) / currentTrack->GetVelocity();
122
123 xAOD::MuonSimHit* newHit = saveHit(hitID, locHitPos, locHitDir, globalTime, aStep);
124 if (prevHit) {
125 newHit->setStepLength((locPostStep - locPreStep).mag());
126 }
127 return newHit;
128 }
130 const Amg::Vector3D& hitPos,
131 const Amg::Vector3D& hitDir,
132 const double globTime,
133 const G4Step* aStep) {
134 const G4Track* currentTrack = aStep->GetTrack();
135 const HepMcParticleLink particleLink{genParticleLink(currentTrack)};
136 // If Geant4 propagates the same track through the same volume just update the last hit and don't write a new one
137 xAOD::MuonSimHit* hit = lastSnapShot(hitId, aStep, particleLink);
138 bool newHit{false};
139 if (!hit) {
140 if (!m_outContainer) {
141 THROW_EXCEPTION("Cannot find container '"<<m_writeKey<<"'.");
142 }
143 hit = m_outContainer->push_back(std::make_unique<xAOD::MuonSimHit>());
144 newHit = true;
145 }
146 dec_G4TrkId(*hit) = currentTrack->GetTrackID();
147 hit->setIdentifier(hitId);
148 hit->setLocalPosition(xAOD::toStorage(hitPos));
149 hit->setLocalDirection(xAOD::toStorage(hitDir));
150 hit->setMass(currentTrack->GetDefinition()->GetPDGMass());
151 hit->setGlobalTime(globTime);
152 hit->setPdgId(currentTrack->GetDefinition()->GetPDGEncoding());
153 hit->setEnergyDeposit(aStep->GetTotalEnergyDeposit() + (newHit ? 0. : hit->energyDeposit()));
154 hit->setKineticEnergy(currentTrack->GetKineticEnergy());
155 hit->setGenParticleLink(particleLink);
156 hit->setStepLength(aStep->GetStepLength());
157
158 ATH_MSG_VERBOSE("Save new hit "<<m_detMgr->idHelperSvc()->toString(hitId)
159 <<", pdgId: "<<hit->pdgId()
160 <<", "<<particleLink
161 <<", trackId: "<<currentTrack->GetTrackID()<<", "
162 <<", "<<particleLink.cptr()<<std::endl
163 <<"pos: "<<Amg::toString(hitPos)<<", dir: "<<Amg::toString(hitDir)<<", time: "<<globTime
164 <<", energy: "<<hit->kineticEnergy()<<", stepLength: "<<hit->stepLength()<<", "
165 <<", deposit energy: "<<hit->energyDeposit());
166 return hit;
167 }
169 const G4Step* hitStep) {
170 const HepMcParticleLink particleLink{genParticleLink(hitStep->GetTrack())};
171 return lastSnapShot(hitId, hitStep, particleLink);
172 }
174 const G4Step* hitStep,
175 const HepMcParticleLink& particleLink) {
178 if (m_outContainer->empty() ||
179 m_outContainer->back()->identify() != hitId ||
180 particleLink != m_outContainer->back()->genParticleLink() ||
181 dec_G4TrkId(*m_outContainer->back()) != hitStep->GetTrack()->GetTrackID()) {
182 return nullptr;
183 }
184 return m_outContainer->back();
185 }
186}
Scalar mag() const
mag method
#define ATH_MSG_DEBUG(x,...)
#define ATH_MSG_VERBOSE(x,...)
detray::unit< scalar_t > unit
bool hit(const Container &ids, int pdgId)
Utility helpers used by Run-4 muon sensitive detector implementations.
Handle class for reading from StoreGate.
void setStore(AlignmentStorePtr store)
Adds the store to the Geometry context.
AthMessaging(IMessageSvc *msgSvc, const std::string &name)
Constructor.
This class is attached to G4Event objects as UserInformation.
static AtlasG4EventUserInfo * GetEventUserInfo()
const EventContext & GetEventContext() const
const T * get(size_type n) const
Access an element, as an rvalue.
const MuonGMR4::MuonDetectorManager * m_detMgr
Pointer to the underlying detector manager.
AtlasG4EventUserInfo * eventInfo() const
Returns the event user info for the current G4 event, if available.
const EventContext & eventContext() const
Returns the current event context recorded in the G4 event info.
virtual void Initialize(G4HCofThisEvent *HCE) override final
Create the output container at the beginning of the event.
MuonSensitiveDetector(const std::string &name, const std::string &output_key, const std::string &trf_storeKey, const MuonGMR4::MuonDetectorManager *detMgr)
Constructor.
SG::ReadHandleKey< ActsTrk::DetectorAlignStore > m_trfCacheKey
ReadHandleKey to the DetectorAlignmentStore caching the relevant transformations needed in this event...
HepMcParticleLink genParticleLink(const G4Track *track) const
Generates a HepMcParticleLink for the Geant4 track using the current event store.
xAOD::MuonSimHit * propagateAndSaveStrip(const Identifier &hitId, const Amg::Transform3D &toGasGap, const G4Step *hitStep)
Records the G4Step in the sim hit.
bool processStep(const G4Step *step) const
Checks whether the current step shall be processed at all.
AtlasG4EventUserInfo * m_g4UserEventInfo
G4 event user information holding the current event store/context.
std::string m_writeKey
Key under which the output container is stored in the G4 event.
xAOD::MuonSimHit * saveHit(const Identifier &hitId, const Amg::Vector3D &hitPos, const Amg::Vector3D &hitDir, const double globTime, const G4Step *hitStep)
Saves the current Step as a xAOD::MuonSimHit snapshot.
ActsTrk::GeometryContext getGeoContext() const
Returns the current geometry context in the event.
xAOD::MuonSimHitContainer * m_outContainer
Pointer to the MuonSimHit output container.
xAOD::MuonSimHit * lastSnapShot(const Identifier &gasGapId, const G4Step *hitStep, const HepMcParticleLink &particleLink)
Returns the last snap shot matching an already generated HepMcParticleLink.
HepMcParticleLink GenerateParticleLink()
Generates a new HepMcParticleLink object on the stack based on the generation-zero unique id,...
Definition TrackHelper.h:75
ConstVectorMap< 3 > localDirection() const
Returns the local direction of the traversing particle.
float stepLength() const
Returns the path length of the G4 step.
void setStepLength(const float length)
Set the path length of the G4 step.
ConstVectorMap< 3 > localPosition() const
Returns the local postion of the traversing particle.
The AlignStoreProviderAlg loads the rigid alignment corrections and pipes them through the readout ge...
std::string toString(const Translation3D &translation, int precision=4)
GeoPrimitvesToStringConverter.
Amg::Vector3D Hep3VectorToEigen(const CLHEP::Hep3Vector &CLHEPvector)
Converts a CLHEP-based CLHEP::Hep3Vector into an Eigen-based Amg::Vector3D.
Eigen::Affine3d Transform3D
Eigen::Matrix< double, 3, 1 > Vector3D
Include the common definitions from the MuonReadoutGeometry.
AthHitVec::AuxStoreHitCollection< xAOD::MuonSimHitContainer, xAOD::MuonSimHitAuxContainer > MuonSimHitsVec
Helper type which can be filled into the HitCollectionMap storing the event content in the event.
SG::Decorator< T, ALLOC > Decorator
Helper class to provide type-safe access to aux data, specialized for JaggedVecElt.
Definition AuxElement.h:576
const T * get(const ReadCondHandleKey< T > &key, const EventContext &ctx)
Convenience function to retrieve an object given a ReadCondHandleKey.
MuonSimHit_v1 MuonSimHit
Defined the version of the MuonSimHit.
Definition MuonSimHit.h:12
MeasVector< N > toStorage(const AmgVector(N)&amgVec)
Converts the double precision of the AmgVector into the floating point storage precision of the MeasV...
#define THROW_EXCEPTION(MESSAGE)
Definition throwExcept.h:10