ATLAS Offline Software
Loading...
Searching...
No Matches
RecoToTruthAssociationAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
4
6
11#include "TrkTrack/Track.h"
18using namespace xAOD::P4Helpers;
19namespace {
20 constexpr unsigned int dummy_unsigned = 999;
21 void increment_unsigned(unsigned& val) {
22 if (val == dummy_unsigned)
23 val = 1;
24 else
25 ++val;
26 }
28 const SG::ConstAccessor<int> acc_origin("truthOrigin");
29 const SG::ConstAccessor<int> acc_type("truthType");
30 const SG::ConstAccessor<unsigned int> acc_classification("truthClassification");
31 const SG::ConstAccessor<TruthLink_t> acc_link("truthParticleLink");
32 //
33 const SG::Decorator<int> dec_origin("truthOrigin");
34 const SG::Decorator<unsigned int> dec_classification("truthClassification");
35 const SG::Decorator<int> dec_type ("truthType");
36 const SG::Decorator<TruthLink_t> dec_link("truthParticleLink");
37
38 static const SG::ConstAccessor<std::vector<unsigned long long>> truthMdtHitsAcc("truthMdtHits");
39 static const SG::ConstAccessor<std::vector<unsigned long long>> truthCscHitsAcc("truthCscHits");
40 static const SG::ConstAccessor<std::vector<unsigned long long>> truthRpcHitsAcc("truthRpcHits");
41 static const SG::ConstAccessor<std::vector<unsigned long long>> truthTgcHitsAcc("truthTgcHits");
42
43} // namespace
44
45namespace Muon {
46using namespace MuonStationIndex;
47// Initialize method:
49 ATH_CHECK(m_idHelperSvc.retrieve());
50 ATH_CHECK(m_truthMuKey.initialize());
51 ATH_CHECK(m_recoMuKey.initialize());
52
53 if (m_recoLink.empty()){
55 } else {
57 }
58
59 ATH_CHECK(m_muonTruthRecoLink.initialize(!m_recoLink.empty()));
67 for (const std::string& trk_coll : m_assocTrkContainers.value()){
68 m_inputDecorKey.emplace_back(trk_coll + ".truthParticleLink");
69 }
70
71 m_inputDecorKey.emplace_back(m_truthMuKey, SG::AuxTypeRegistry::instance().getName(acc_origin.auxid()));
72 m_inputDecorKey.emplace_back(m_truthMuKey, SG::AuxTypeRegistry::instance().getName(acc_type.auxid()));
73 if (m_idHelperSvc->hasMDT()) {
74 m_inputDecorKey.emplace_back(m_truthMuKey, SG::AuxTypeRegistry::instance().getName(truthMdtHitsAcc.auxid()));
75 }
76 if (m_idHelperSvc->hasRPC()) {
77 m_inputDecorKey.emplace_back(m_truthMuKey, SG::AuxTypeRegistry::instance().getName(truthRpcHitsAcc.auxid()));
78 }
79 if (m_idHelperSvc->hasTGC()) {
80 m_inputDecorKey.emplace_back(m_truthMuKey, SG::AuxTypeRegistry::instance().getName(truthTgcHitsAcc.auxid()));
81 }
82 if (m_idHelperSvc->hasCSC()) {
83 m_inputDecorKey.emplace_back(m_truthMuKey, SG::AuxTypeRegistry::instance().getName(truthCscHitsAcc.auxid()));
84 }
85
86 ATH_CHECK(m_inputDecorKey.initialize());
87 return StatusCode::SUCCESS;
88}
89
90// Execute method:
91StatusCode RecoToTruthAssociationAlg::execute(const EventContext& ctx) const {
92 const xAOD::TruthParticleContainer* muonTruthContainer{nullptr};
93 ATH_CHECK(SG::get(muonTruthContainer, m_truthMuKey , ctx));
94 std::unique_ptr<SG::WriteDecorHandle<xAOD::TruthParticleContainer, ElementLink<xAOD::MuonContainer>>> muonTruthParticleRecoLink{};
95 if (!m_muonTruthRecoLink.empty()) {
96 muonTruthParticleRecoLink = std::make_unique<SG::WriteDecorHandle<xAOD::TruthParticleContainer, ElementLink<xAOD::MuonContainer>>>(m_muonTruthRecoLink, ctx);
97 }
98
100 ctx);
101 if (!muonTruthParticleLink.isValid()) {
102 ATH_MSG_WARNING("muon particle container not valid");
103 return StatusCode::FAILURE;
104 }
109 ctx);
112
113 // add link to reco muons and viceversa
114 bool saw_staco = false;
115 bool decor_staco = false;
116
117 // loop over muons
118 for (const xAOD::Muon* muon : *muonTruthParticleLink) {
119 // use primary track particle to get the truth link (except for the case of STACO, where we must use the ID track particle, as the
120 // combined is not truth-matched)
121 ATH_MSG_DEBUG("muon with pT " << muon->pt() << " MeV, eta: " << muon->eta() << ", phi " << muon->phi() << " and author "
122 << muon->author());
123 const xAOD::TrackParticle* tp = nullptr;
124 if (m_associateWithInDetTP || muon->author() == xAOD::Muon::STACO || muon->author() == xAOD::Muon::MuGirl) {
125 tp = muon->trackParticle(xAOD::Muon::InnerDetectorTrackParticle);
126 } else {
127 tp = muon->primaryTrackParticle();
128 }
129
130 bool foundTruth{false}, setOrigin{false};
131 if (tp) {
132 // Associate reco with truth muon. Loop over reconstructed muons, get track particle for each one.
133 // Each track particle should carry a link to the corresponding truth particle. Then compare this truth particle link with the
134 // given truth muon particle
135 if (acc_origin.isAvailable(*tp) && acc_origin(*tp) != 0) {
136 muonTruthParticleOrigin(*muon) = acc_origin(*tp);
137 muonTruthParticleType(*muon) = acc_type(*tp);
138 muonTruthParticleClassification(*muon) = acc_classification(*tp);
139 setOrigin = true;
140 }
141
143 if (acc_link.isAvailable(*tp)) {
144 truthLink = acc_link(*tp);
145 } else {
146 ATH_MSG_DEBUG("Could not find any truth link associated with track having pt:"<<tp->pt()<<" MeV, eta: "<<tp->eta()<<", phi: "<<tp->phi()<<", charge: "<<tp->charge()<<". d0:"<<tp->d0()<<", z0: "<<tp->z0());
147 }
148
149 if (truthLink.isValid()) {
150 ATH_MSG_VERBOSE(" Got valid truth link for muon author " << muon->author() << " uniqueID " << HepMC::uniqueID(*truthLink));
151 // loop over truth particles
152 for (const xAOD::TruthParticle* truthParticle : *muonTruthContainer) {
153 if (!MC::isStable(truthParticle)) continue;
154 ATH_MSG_DEBUG("Got truth muon with uniqueID " << HepMC::uniqueID(truthParticle) << " pt " << truthParticle->pt());
155 if ( !HepMC::is_sim_descendant(*truthLink, truthParticle)) {
156 ATH_MSG_VERBOSE("UniqueID truth link: " << HepMC::uniqueID(*truthLink)
157 << " is not decendant of " << HepMC::uniqueID(truthParticle));
158 continue;
159 }
160 ATH_MSG_VERBOSE("Truth muon uniqueID matches -> creating link with truth particle " << HepMC::uniqueID(*truthLink));
161 foundTruth = true;
163 ElementLink<xAOD::TruthParticleContainer> muonTruthLink{*muonTruthContainer,
164 truthParticle->index(),
165 ctx};
166 muonTruthLink.toPersistent();
167 muonTruthParticleLink(*muon) = muonTruthLink;
168 if (!setOrigin) {
169 muonTruthParticleOrigin(*muon) = acc_origin(*tp);
170 muonTruthParticleType(*muon) = acc_type(*tp);
171 muonTruthParticleClassification(*muon) = acc_classification(*tp);
172 setOrigin = true;
173 }
175 if (muonTruthParticleRecoLink && muonTruthParticleRecoLink->operator()(*truthParticle).isValid()){
176 const xAOD::Muon* decor_muon = *muonTruthParticleRecoLink->operator()(*truthParticle);
177 ATH_MSG_VERBOSE("Truth particle is already decorated with reco muon "<<decor_muon->pt()*1.e-3
178 <<" eta: "<<decor_muon->eta()<<" phi: "<<decor_muon->phi()<<" charge: "<<
179 decor_muon->charge()<<" author: "<<decor_muon->author()<<" all authors: "<<
180 decor_muon->allAuthors());
181
182 // Check first if the exiting muon has a better author
183 if (MuonCombined::authorRank(decor_muon->author()) < MuonCombined::authorRank(muon->author())){
184 ATH_MSG_DEBUG("Author of the decorated muon is better than the one of the new candidate");
185 continue;
186 }
188 if (deltaR2(muon,truthParticle) >= deltaR2(muon, decor_muon)) continue;
189 }
190
191
192 ElementLink<xAOD::MuonContainer> muonLink{muon, *muonTruthParticleLink, ctx};
193
195 std::vector<unsigned int> nprecHitsPerChamberLayer(toInt(ChIndex::ChIndexMax), dummy_unsigned);
196 std::vector<unsigned int> nphiHitsPerChamberLayer(toInt(PhiIndex::PhiIndexMax), dummy_unsigned);
197 std::vector<unsigned int> ntrigEtaHitsPerChamberLayer(toInt(PhiIndex::PhiIndexMax), dummy_unsigned);
198
199 constexpr int author_sel = (1<<xAOD::Muon::MuidCo) | (1<<xAOD::Muon::MuidSA) | (1<<xAOD::Muon::MuGirl);
200 count_chamber_layers(muon->allAuthors() & author_sel
201 ? truthParticle
202 : nullptr,
203 tp->track(), nprecHitsPerChamberLayer, nphiHitsPerChamberLayer, ntrigEtaHitsPerChamberLayer);
205 muonTruthParticleNPrecMatched(*muon) = nprecHitsPerChamberLayer;
206 muonTruthParticleNPhiMatched(*muon) = nphiHitsPerChamberLayer;
207 muonTruthParticleNTrigEtaMatched(*muon) = ntrigEtaHitsPerChamberLayer;
208
209 if (muonTruthParticleRecoLink) (*muonTruthParticleRecoLink)(*truthParticle) = muonLink;
210 break;
211 }
212 } else {
213 ATH_MSG_DEBUG("Invalid truth link");
214 }
215 } else {
216 ATH_MSG_WARNING("Could not find the appropiate track particle for muon with pT: " << muon->pt() * 1.e-3 << " GeV, eta: "
217 << muon->eta() << ", phi: " << muon->phi()
218 << " author: " << muon->author());
219 }
220
221 if (!setOrigin) {
222 muonTruthParticleOrigin(*muon) = 0;
223 muonTruthParticleType(*muon) = 0;
224 muonTruthParticleClassification(*muon) = 0;
225 }
226 if (!foundTruth) {
227 muonTruthParticleLink(*muon) = ElementLink<xAOD::TruthParticleContainer>();
228 // add these empty vectors
229 muonTruthParticleNPrecMatched(*muon) = std::vector<unsigned int>{};
230 muonTruthParticleNPhiMatched(*muon) = std::vector<unsigned int>{};
231 muonTruthParticleNTrigEtaMatched(*muon) = std::vector<unsigned int>{};
232 }
235 if (muon->author() == xAOD::Muon::STACO) {
236 const xAOD::TrackParticle* cmb_trk = muon->trackParticle(xAOD::Muon::CombinedTrackParticle);
237 if (!cmb_trk){
238 ATH_MSG_WARNING("Even a STACO muon should have a combined track");
239 continue;
240 } else {
241 if (!saw_staco) {
242 saw_staco = true;
243 decor_staco = !dec_origin.isAvailable (*cmb_trk);
244 }
245 if (decor_staco) {
246 dec_origin(*cmb_trk) = acc_origin(*muon);
247 dec_classification(*cmb_trk) = acc_classification(*muon);
248 dec_type(*cmb_trk) = acc_type(*muon);
249 dec_link(*cmb_trk) = acc_link(*muon);
250 }
251 }
252 }
253 }
255 if (muonTruthParticleRecoLink && !muonTruthParticleRecoLink->isAvailable()) {
256 for (const xAOD::TruthParticle* truthParticle : **muonTruthParticleRecoLink) {
257 ATH_MSG_DEBUG("no reco muon link set, add an empty one");
258 (*muonTruthParticleRecoLink)(*truthParticle) = ElementLink<xAOD::MuonContainer>();
259 }
260 }
261
262 return StatusCode::SUCCESS;
263}
264
266 std::vector<unsigned int>& nprecHitsPerChamberLayer,
267 std::vector<unsigned int>& nphiHitsPerChamberLayer,
268 std::vector<unsigned int>& ntrigEtaHitsPerChamberLayer) const {
269
270 if (!truthParticle || !truthMdtHitsAcc.isAvailable(*truthParticle)) {
271 ATH_MSG_DEBUG("muon has no truth hits vector in the truth association alg");
272 nprecHitsPerChamberLayer.clear();
273 nphiHitsPerChamberLayer.clear();
274 ntrigEtaHitsPerChamberLayer.clear();
275 return;
276 }
277 const std::vector<unsigned long long>& mdtTruth = truthMdtHitsAcc(*truthParticle);
278 std::vector<unsigned long long> cscTruth;
279
280 if (m_idHelperSvc->hasCSC()) cscTruth = truthCscHitsAcc(*truthParticle);
281 const std::vector<unsigned long long>& rpcTruth = truthRpcHitsAcc(*truthParticle);
282 const std::vector<unsigned long long>& tgcTruth = truthTgcHitsAcc(*truthParticle);
283
284 for (const Trk::TrackStateOnSurface* tsit : *ptrk->trackStateOnSurfaces()) {
285 if (!tsit || !tsit->trackParameters() || !tsit->measurementOnTrack()) continue;
286 const Trk::MeasurementBase* meas = tsit->measurementOnTrack();
287 Identifier id;
288 const Trk::RIO_OnTrack* rot = dynamic_cast<const Trk::RIO_OnTrack*>(meas);
289 if (rot)
290 id = rot->identify();
291 else {
292 const Muon::CompetingMuonClustersOnTrack* crot = dynamic_cast<const Muon::CompetingMuonClustersOnTrack*>(meas);
293 if (crot && !crot->containedROTs().empty() && crot->containedROTs().front()) id = crot->containedROTs().front()->identify();
294 }
295 if (!m_idHelperSvc->isMuon(id)) continue;
296
297 bool measPhi = m_idHelperSvc->measuresPhi(id);
298 bool isTgc = m_idHelperSvc->isTgc(id);
299 ChIndex chIndex = !isTgc ? m_idHelperSvc->chamberIndex(id) : ChIndex::ChUnknown;
300 if (m_idHelperSvc->isMdt(id)) {
301 for (unsigned int i = 0; i < mdtTruth.size(); ++i) {
302 if (id == mdtTruth[i]) {
303 if (chIndex != ChIndex::ChUnknown) {
304 increment_unsigned(nprecHitsPerChamberLayer.at(toInt(chIndex)));
305 }
306 break;
307 }
308 }
309 } else if (m_idHelperSvc->hasCSC() && m_idHelperSvc->isCsc(id)) {
310 for (unsigned int i = 0; i < cscTruth.size(); ++i) {
311 if (id != cscTruth[i]) continue;
312 if (measPhi) {
313 PhiIndex index = m_idHelperSvc->phiIndex(id);
314 if (index != PhiIndex::PhiUnknown) {
315 increment_unsigned(nphiHitsPerChamberLayer.at(toInt(index)));
316 }
317 } else {
318 if (chIndex != ChIndex::ChUnknown) {
319 increment_unsigned(nprecHitsPerChamberLayer.at(toInt(chIndex)));
320 }
321 }
322 break;
323 }
324 } else if (m_idHelperSvc->isRpc(id)) {
325 for (unsigned int i = 0; i < rpcTruth.size(); ++i) {
326 if (id != rpcTruth[i]) { continue; }
327 PhiIndex index = m_idHelperSvc->phiIndex(id);
328 if (index != PhiIndex::PhiUnknown) {
329 if (measPhi) {
330 increment_unsigned(nphiHitsPerChamberLayer.at(toInt(index)));
331 } else {
332 increment_unsigned(ntrigEtaHitsPerChamberLayer.at(toInt(index)));
333 }
334 }
335 break;
336 }
337 } else if (m_idHelperSvc->isTgc(id)) {
338 for (unsigned int i = 0; i < tgcTruth.size(); ++i) {
339 if (id != tgcTruth[i]) { continue; }
340 PhiIndex index = m_idHelperSvc->phiIndex(id);
341 if (index != PhiIndex::PhiUnknown) {
342 if (measPhi) {
343 increment_unsigned(nphiHitsPerChamberLayer.at(toInt(index)));
344 } else {
345 increment_unsigned(ntrigEtaHitsPerChamberLayer.at(toInt(index)));
346 }
347 }
348 break;
349 }
350 }
351 } // end loop over TSOS
352 ATH_MSG_DEBUG("finished loop over TSOS");
353
354 // now, have to check if there are non-zero truth hits in indices without reco hits
355 clear_dummys(mdtTruth, nprecHitsPerChamberLayer);
356 clear_dummys(cscTruth, nprecHitsPerChamberLayer);
357
358 clear_dummys(cscTruth, nphiHitsPerChamberLayer);
359 clear_dummys(rpcTruth, nphiHitsPerChamberLayer);
360 clear_dummys(tgcTruth, nphiHitsPerChamberLayer);
361
362 clear_dummys(rpcTruth, ntrigEtaHitsPerChamberLayer);
363 clear_dummys(tgcTruth, ntrigEtaHitsPerChamberLayer);
364}
365void RecoToTruthAssociationAlg::clear_dummys(const std::vector<unsigned long long>& identifiers, std::vector<unsigned int>& vec) const {
368 if (identifiers.empty()) { return; }
369 for (unsigned int i = 0; i < vec.size(); ++i) {
370 if (vec[i] != dummy_unsigned) continue;
371 for (unsigned j = 0; j < identifiers.size(); ++j) {
372 const Identifier id{identifiers[j]};
373 if (m_idHelperSvc->measuresPhi(id)) {
374 const auto phiIdx = static_cast<PhiIndex>(i);
375 if (m_idHelperSvc->phiIndex(id) == phiIdx) {
376 vec[i] = 0;
377 break;
378 }
379 } else {
380 const auto chIdx = static_cast<ChIndex>(i);
381 if (m_idHelperSvc->chamberIndex(id) == chIdx) {
382 vec[i] = 0;
383 break;
384 }
385 }
386 }
387 }
388}
389}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_VERBOSE(x)
#define ATH_MSG_WARNING(x)
#define ATH_MSG_DEBUG(x)
std::vector< size_t > vec
Helper class to provide constant type-safe access to aux data.
ATLAS-specific HepMC functions.
Handle class for adding a decoration to an object.
ElementLink< xAOD::TruthParticleContainer > TruthLink_t
Class for competing MuonClusters, it extends the Trk::CompetingRIOsOnTrack base class.
const std::vector< std::unique_ptr< const MuonClusterOnTrack > > & containedROTs() const
returns the vector of SCT_ClusterOnTrack objects .
SG::ReadHandleKey< xAOD::MuonContainer > m_recoMuKey
SG::ReadDecorHandleKeyArray< xAOD::IParticleContainer > m_inputDecorKey
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleOrigin
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleNPhiMatched
Gaudi::Property< bool > m_associateWithInDetTP
SG::WriteDecorHandleKey< xAOD::TruthParticleContainer > m_muonTruthRecoLink
Decorations for the filtered muon truth particles.
Gaudi::Property< std::vector< std::string > > m_assocTrkContainers
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleClassification
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleType
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleLink
Decorations for the reconstructed muon particles.
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleNTrigEtaMatched
void count_chamber_layers(const xAOD::IParticle *truth_particle, const Trk::Track *ptrk, std::vector< unsigned int > &nprecHitsPerChamberLayer, std::vector< unsigned int > &nphiHitsPerChamberLayer, std::vector< unsigned int > &ntrigEtaHitsPerChamberLayer) const
void clear_dummys(const std::vector< unsigned long long > &identifiers, std::vector< unsigned int > &vec) const
ServiceHandle< Muon::IMuonIdHelperSvc > m_idHelperSvc
Gaudi::Property< std::string > m_recoLink
SG::ReadHandleKey< xAOD::TruthParticleContainer > m_truthMuKey
Key to the filtered muon truth particles.
StatusCode execute(const EventContext &ctx) const override
SG::WriteDecorHandleKey< xAOD::MuonContainer > m_muonTruthParticleNPrecMatched
static AuxTypeRegistry & instance()
Return the singleton registry instance.
Helper class to provide constant type-safe access to aux data.
Handle class for adding a decoration to an object.
This class is the pure abstract base class for all fittable tracking measurements.
Class to handle RIO On Tracks ROT) for InDet and Muons, it inherits from the common MeasurementBase.
Definition RIO_OnTrack.h:70
Identifier identify() const
return the identifier -extends MeasurementBase
represents the track state (measurement, material, fit parameters and quality) at a surface.
const Trk::TrackStates * trackStateOnSurfaces() const
return a pointer to a const DataVector of const TrackStateOnSurfaces.
Class providing the definition of the 4-vector interface.
XAOD_AUXDATA_DEPRECATED bool isAvailable(const std::string &name, const std::string &clsname="") const
Check if a user property is available for reading or not.
virtual double eta() const
The pseudorapidity ( ) of the particle.
virtual double phi() const
The azimuthal angle ( ) of the particle.
virtual double pt() const
The transverse momentum ( ) of the particle.
float charge() const
uint16_t allAuthors() const
Get all the authors of this Muon.
Author author() const
float z0() const
Returns the parameter.
const Trk::Track * track() const
Returns a pointer (which can be NULL) to the Trk::Track which was used to make this TrackParticle.
virtual double phi() const override final
The azimuthal angle ( ) of the particle (has range to .).
float d0() const
Returns the parameter.
virtual double pt() const override final
The transverse momentum ( ) of the particle.
virtual double eta() const override final
The pseudorapidity ( ) of the particle.
float charge() const
Returns the charge.
int uniqueID(const T &p)
bool is_sim_descendant(const T1 &p1, const T2 &p2)
Method to check if the first particle is a descendant of the second in the simulation,...
bool isStable(const T &p)
Identify if the particle is stable, i.e. has not decayed.
int authorRank(const xAOD::Muon::Author a)
Definition TagBase.h:24
ChIndex chIndex(const std::string &index)
convert ChIndex name string to enum
PhiIndex
enum to classify the different phi layers in the muon spectrometer
constexpr int toInt(const EnumType enumVal)
ChIndex
enum to classify the different chamber layers in the muon spectrometer
NRpcCablingAlg reads raw condition data and writes derived condition data to the condition store.
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.
Definition index.py:1
double deltaR2(double rapidity1, double phi1, double rapidity2, double phi2)
from bare rapidity,phi
TrackParticle_v1 TrackParticle
Reference the current persistent version:
TruthParticle_v1 TruthParticle
Typedef to implementation.
Muon_v1 Muon
Reference the current persistent version:
TruthParticleContainer_v1 TruthParticleContainer
Declare the latest version of the truth particle container.