ATLAS Offline Software
Loading...
Searching...
No Matches
TruthSegToTruthPartAssocAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2026 CERN for the benefit of the ATLAS collaboration
3*/
5
8#include "AthLinks/ElementLink.h"
9#include "Identifier/Identifier.h"
15#include "Acts/Surfaces/PlaneSurface.hpp"
17
18#include <unordered_set>
19
20
21using namespace Acts::UnitLiterals;
22using namespace MuonR4::SegmentFit;
23namespace {
24 using IdSet_t = std::unordered_set<Identifier>;
25 unsigned int countMatched(const std::vector<const xAOD::MuonSimHit*>& simHits,
26 const IdSet_t& matchIds) {
27 return std::ranges::count_if(simHits, [&matchIds](const xAOD::MuonSimHit* hit) {
28 return matchIds.count(hit->identify());
29 });
30 }
31
32 Acts::Vector4 vertexPos(const xAOD::TruthParticle& truthPart) {
33 if (truthPart.hasProdVtx()){
34 const xAOD::TruthVertex* vtx = truthPart.prodVtx();
35 return ActsTrk::convertPosToActs(Amg::Vector3D{vtx->x(), vtx->y(), vtx->z()}, vtx->t());
36 }
37 return Acts::Vector4::Zero();
38 }
39
40 static const SG::ConstAccessor<float> acc_q{"charge"};
41 static const SG::ConstAccessor<float> acc_pt{"pt"};
42}
43namespace MuonR4{
45 ATH_CHECK(m_truthKey.initialize());
46 for (const std::string& hitIds : m_simHitIds) {
47 m_simHitKeys.emplace_back(m_truthKey, hitIds);
48 }
49 ATH_CHECK(m_simHitKeys.initialize());
50 ATH_CHECK(m_segLinkKey.initialize());
51 ATH_CHECK(m_segmentKey.initialize());
52 ATH_CHECK(m_truthLinkKey.initialize());
53 ATH_CHECK(m_idHelperSvc.retrieve());
54 ATH_CHECK(m_ctxProvider.initialize());
55 ATH_CHECK(m_extrapolationTool.retrieve(EnableTool{m_includePileUpObjs}));
56 ATH_CHECK(detStore()->retrieve(m_detMgr));
57 return StatusCode::SUCCESS;
58 }
59 StatusCode TruthSegToTruthPartAssocAlg::execute(const EventContext& ctx) const {
60
61 const xAOD::TruthParticleContainer* truthParticles{nullptr};
62 ATH_CHECK(SG::get(truthParticles, m_truthKey, ctx));
63
66 using SegLinkVec_t = std::vector<SegLink_t>;
68
70 std::vector<IdDecorHandle_t> idDecorHandles{};
72 idDecorHandles.emplace_back(hitKey, ctx);
73 }
75 using IdSet_t = std::unordered_set<Identifier>;
76 using TruthTuple_t = std::tuple<const xAOD::TruthParticle*, IdSet_t>;
77 std::vector<TruthTuple_t> truthPartWithIds{};
79 std::vector<const xAOD::TruthParticle*> bkgMuons{};
80 truthPartWithIds.reserve(truthParticles->size());
81 for (const xAOD::TruthParticle* truthMuon : *truthParticles){
82 segLinkDecor(*truthMuon).clear();
83 IdSet_t assocIds{};
84 ATH_MSG_DEBUG(__func__<<"() "<<__LINE__<<" - Truth muon "<<truthMuon->pt()<<", eta: "<<truthMuon->eta()
85 <<", phi: "<<(truthMuon->phi() / 1._degree)<<", id: "<< HepMC::uniqueID(truthMuon));
86 for (const IdDecorHandle_t& hitDecor : idDecorHandles) {
87 std::ranges::transform(hitDecor(*truthMuon), std::inserter(assocIds, assocIds.begin()),
88 [this](unsigned long long rawId){
89 const Identifier id{rawId};
90 ATH_MSG_VERBOSE(" --- associated hit id: "<<m_idHelperSvc->toString(id));
91 return id;
92 });
93 }
94 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Truth muon with pt: "<<(truthMuon->pt() / 1_GeV)
95 <<", eta: "<<truthMuon->eta()<<", phi: "<<truthMuon->phi()
96 <<", uniqueID: "<<HepMC::uniqueID(truthMuon)<<", associated hits: "<<assocIds.size());
97 if (assocIds.empty()) {
98 bkgMuons.push_back(truthMuon);
99 } else {
100 truthPartWithIds.emplace_back(std::make_tuple(truthMuon, std::move(assocIds)));
101 }
102 }
104 const xAOD::MuonSegmentContainer* segments{nullptr};
105 ATH_CHECK(SG::get(segments, m_segmentKey, ctx));
106
108 TruthPartDecor_t truthLinkDecor{m_truthLinkKey, ctx};
110 std::vector<const xAOD::MuonSegment*> bkgSegments{};
111
112 for (const xAOD::MuonSegment* segment : *segments){
113 std::vector<const xAOD::MuonSimHit*> simHits = getMatchingSimHits(*segment);
114 ATH_MSG_DEBUG(__func__<<"() "<<__LINE__<<" - Reconstructed truth segment "
116 <<", chamberId: "<<Muon::MuonStationIndex::chName(segment->chamberIndex())
117 <<", phi: "<<segment->sector()<<", nPrecHits: "<<segment->nPrecisionHits()
118 <<", nDoF: "<<segment->numberDoF()<<" sim hits: "<<simHits.size());
119 if (msgLvl(MSG::VERBOSE)){
120 for (const xAOD::MuonSimHit* hit: simHits) {
121 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Associated sim hit: "<<m_idHelperSvc->toString(hit->identify())
122 <<", locPos: "<<Amg::toString(xAOD::toEigen(hit->localPosition()))
123 <<", locDir: "<<Amg::toString(xAOD::toEigen(hit->localDirection()))
124 <<", "<<hit->genParticleLink());
125 }
126 }
128 if (!(*simHits.begin())->genParticleLink().isValid()) {
129 bkgSegments.push_back(segment);
130 truthLinkDecor(*segment) = TruthPartLink_t{};
131 continue;
132 }
133 /* now find the truth particle with all associated hits */
134 const auto best_itr = std::ranges::max_element(truthPartWithIds,
135 [&simHits](const TruthTuple_t& truthTupleA,
136 const TruthTuple_t& truthTupleB) {
137 return countMatched(simHits, std::get<1>(truthTupleA)) <
138 countMatched(simHits, std::get<1>(truthTupleB));
139 });
140 if (best_itr == truthPartWithIds.end()) {
141 ATH_MSG_WARNING(__func__<<"() "<<__LINE__<<" - No truth particle matched the truth hits of the segment");
142 continue;
143 }
144 if (1.*countMatched(simHits, std::get<1>(*best_itr)) < 0.5* simHits.size()) {
145 if (msgLvl(MSG::VERBOSE)) {
146 for (const auto& [truthMuon, assocIds]: truthPartWithIds){
147 std::stringstream unMatchedStr{};
148 unsigned int counts{0};
149 for (const xAOD::MuonSimHit* hit: simHits) {
150 if (!assocIds.count(hit->identify())){
151 unMatchedStr<<" *** "<<m_idHelperSvc->toString(hit->identify())<<std::endl;
152 } else {
153 ++counts;
154 }
155 }
156 if (!counts) {
157 continue;
158 }
159 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Truth muon "<<truthMuon->pt()<<", eta: "<<truthMuon->eta()
160 <<", "<<truthMuon->phi()<<", barcode: "<<HepMC::uniqueID(truthMuon)<<", matched hits: "
161 <<counts<<", unmatched: "<<std::endl<<unMatchedStr.str());
162 }
163 }
164 continue;
165 }
166 const xAOD::TruthParticle* truthPart{std::get<0>(*best_itr)};
167 segLinkDecor(*truthPart).emplace_back(m_segmentKey.key(), segment->index(), ctx);
168 truthLinkDecor(*segment) = TruthPartLink_t{m_truthKey.key(), truthPart->index(), ctx};
169
170 }
171 matchPileupSegments(ctx, bkgMuons, bkgSegments, truthLinkDecor, segLinkDecor);
173 for (const xAOD::TruthParticle* truthMuon : *truthParticles){
174 const Amg::Vector3D dir = Amg::Vector3D{truthMuon->px(), truthMuon->py(), truthMuon->pz()}.normalized();
175 const xAOD::TruthVertex* vtx{truthMuon->prodVtx()};
176 const Amg::Vector3D pos = (vtx? Amg::Vector3D{vtx->x(), vtx->y(), vtx->z()} : Amg::Vector3D::Zero());
177 SegLinkVec_t& linkedSegs{segLinkDecor(*truthMuon)};
178 std::ranges::sort(linkedSegs,[&pos, &dir](const SegLink_t& linkA, const SegLink_t& linkB){
179 return dir.dot((*linkA)->position() - pos) <
180 dir.dot((*linkB)->position() - pos);
181 });
182 }
183 return StatusCode::SUCCESS;
184 }
186 const std::vector<const xAOD::TruthParticle*>& pileUpMuons,
187 const std::vector<const xAOD::MuonSegment*>& pileUpSegments,
188 TruthPartDecor_t& truthPartDecor,
189 TruthSegLinkDecor_t& truthSegDecor) const {
190
191 if (!m_includePileUpObjs) {
192 ATH_MSG_DEBUG(__func__<<"() "<<__LINE__<<" - Matching between pile-up segments & muons is disabled");
193 return;
194 }
195 if (pileUpMuons.empty() || pileUpSegments.empty()) {
196 ATH_MSG_DEBUG(__func__<<"() "<<__LINE__<<" - Segments ("<<pileUpSegments.size()<<") or muons ("
197 <<pileUpMuons.size()<<") are empty -> nothing to do");
198 return;
199 }
200 if (msgLvl(MSG::DEBUG)) {
201 std::stringstream sstr{};
202 for (const xAOD::TruthParticle* bkgMuon : pileUpMuons) {
203 sstr<<" *** pT: "<<(bkgMuon->pt() / 1_GeV)<<", eta: "<<bkgMuon->eta()
204 <<", phi: "<<(bkgMuon->phi() / 1_degree)<<", pdgId: "<<bkgMuon->pdgId()
205 <<", pos: "<<Amg::toString(vertexPos(*bkgMuon))
206 <<", uid: "<<bkgMuon->uid() <<std::endl;
207 }
208 sstr<<"\n To these segments: "<<std::endl;
209 unsigned int counter{0};
210 for (const xAOD::MuonSegment* bkgSeg : pileUpSegments) {
211 sstr<<" "<<(counter++)<<") "<<Amg::toString(bkgSeg->position())
212 <<", phi: "<<(bkgSeg->position().phi() / 1_degree)<<", eta: "<<(bkgSeg->position().eta())
213 <<", pT: "<< (acc_pt(*bkgSeg) / 1_GeV)
214 <<" chamberId: "<<Muon::MuonStationIndex::chName(bkgSeg->chamberIndex())
215 <<", sector: "<<bkgSeg->sector()<<", nPrecHits: "<<bkgSeg->nPrecisionHits()
216 <<", chi2: "<<(bkgSeg->chiSquared() / std::max(bkgSeg->numberDoF(), 1.f))
217 <<", nDoF: "<<bkgSeg->numberDoF()<<std::endl;
218 }
219 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - \nMatch the following muons "<<std::endl<<sstr.str());
220 }
221 std::vector<char> segmentMatched(pileUpSegments.size(), 0);
222
223 const Acts::GeometryContext tgContext = m_ctxProvider.getGeometryContext(ctx);
224
225 for (const xAOD::TruthParticle* bkgMuon : pileUpMuons) {
226 const Acts::Vector4 fourPos = vertexPos(*bkgMuon);
227 const Acts::Vector4 fourMom = ActsTrk::convertMomToActs(Amg::Vector3D{bkgMuon->px(), bkgMuon->py(), bkgMuon->pz()},
228 bkgMuon->m());
229 const Amg::Vector3D threeMom = fourMom.block<3,1>(0,0);
230 const Amg::Vector3D start = ActsTrk::convertPosFromActs(fourPos).first;
231 auto startSurf = Acts::Surface::makeShared<Acts::PlaneSurface>(Amg::getTranslate3D(start));
232
233
234 Acts::BoundMatrix initialCov{Acts::BoundMatrix::Identity()};
235
236 auto initialPars = Acts::BoundTrackParameters::create(tgContext, startSurf, fourPos, threeMom.unit(),
237 bkgMuon->charge() / threeMom.mag(),
238 initialCov, Acts::ParticleHypothesis::muon());
239 if(!initialPars.ok()) {
240 ATH_MSG_WARNING(__func__<<"() "<<__LINE__<<" - Failed to create start parameters");
241 continue;
242 }
243 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Created new start parameters "<<Amg::toString(fourPos)<<", "
244 <<Amg::toString(threeMom) <<", pT: "<<(threeMom.perp() / 1_GeV)
245 <<" GeV, eta: "<<threeMom.eta()<<", phi: "<<(threeMom.phi() / 1_degree)<<", q: "<<bkgMuon->charge());
246
247 for (std::size_t sIdx =0 ; sIdx < pileUpSegments.size(); ++sIdx) {
248 // Skip already matched segments
249 if (segmentMatched[sIdx]) {
250 continue;
251 }
252 const xAOD::MuonSegment* bkgSeg = pileUpSegments[sIdx];
253 if (acc_q(*bkgSeg) != bkgMuon->charge()) {
254 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Segment charge does not match");
255 continue;
256 }
257 const Amg::Vector3D segPos = bkgSeg->position();
258 const Amg::Vector3D segDir = bkgSeg->direction();
260 const double lDist = std::abs(Amg::lineDistance(segPos, segDir, start, threeMom.unit()));
261 const double dPhi = std::abs(segPos.deltaPhi(threeMom));
262 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Segment "<<sIdx<<", "<<Amg::toString(segPos)
263 <<", "<<Amg::toString(segDir) <<", lDist: "<<lDist<<", dPhi: "<<(dPhi / 1_degree));
264 if (dPhi > m_pileUpObjDPhiCut) {
265 continue;
266 }
267 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Start extrapolation");
268 const auto* sector = m_detMgr->getSectorEnvelope(bkgSeg->chamberIndex(), bkgSeg->sector(), bkgSeg->etaIndex());
269 auto propPars = m_extrapolationTool->propagate(ctx, *initialPars, sector->surface());
270 if (!propPars.ok()) {
271 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Extrapolation failed.");
272 continue;
273 }
275 const Amg::Vector2D dPosExtp = propPars->localPosition() - (sector->globalToLocalTransform(tgContext) * segPos).segment<2>(0);
276 const double dThetaExtp = std::abs(segDir.theta() - propPars->theta());
277 const double dPhiExtp = std::abs(segDir.phi() - propPars->phi());
278 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Parameter difference: "<<Amg::toString(dPosExtp)
279 <<", dTheta:"<<(dThetaExtp / 1._degree)<<", dPhi: "<<(dPhiExtp / 1._degree));
280
281
282 if (std::abs(dPosExtp.x()) > m_pileUpObjExtpDxCut || std::abs(dPosExtp.y()) > m_pileUpObjExtpDyCut ||
283 dThetaExtp > m_pileUpObjExtpDthetaCut || dPhiExtp > m_pileUpObjExtpDphiCut) {
284 ATH_MSG_VERBOSE(__func__<<"() "<<__LINE__<<" - Parameters differ too much. Cut values"
286 continue;
287 }
288 truthPartDecor(*bkgSeg) = TruthPartLink_t{*truthSegDecor.container(), bkgMuon->index(), ctx};
289 truthSegDecor(*bkgMuon).emplace_back(*truthPartDecor.container(), bkgSeg->index(), ctx);
290 segmentMatched[sIdx] = true;
291 }
292 }
293 }
294}
Scalar eta() const
pseudorapidity method
Scalar phi() const
phi method
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_DEBUG(x,...)
#define ATH_MSG_WARNING(x,...)
#define ATH_MSG_VERBOSE(x,...)
ATLAS-specific HepMC functions.
bool hit(const Container &ids, int pdgId)
Handle class for reading a decoration on an object.
Handle class for adding a decoration to an object.
const ServiceHandle< StoreGateSvc > & detStore() const
bool msgLvl(const MSG::Level lvl) const
size_type size() const noexcept
Returns the number of elements in the collection.
Gaudi::Property< std::vector< std::string > > m_simHitIds
List of simHit id decorations to read from the truth particle.
Gaudi::Property< bool > m_includePileUpObjs
Property checking whether a pile-up muons shall be matched to pile-up segments.
const MuonGMR4::MuonDetectorManager * m_detMgr
Pointer to the muon detector manager.
xAOD::ContainerDecorator< xAOD::TruthParticleContainer, TruthSegLinkVec_t > TruthSegLinkDecor_t
SG::WriteDecorHandleKey< xAOD::MuonSegmentContainer > m_truthLinkKey
Key of the truthParticleLink decorated onto the segment.
ActsTrk::ContextUtility m_ctxProvider
Context provider for geometry, magnetic field and calibration contexts.
ElementLink< xAOD::TruthParticleContainer > TruthPartLink_t
virtual StatusCode initialize() override final
Gaudi::Property< double > m_pileUpObjExtpDthetaCut
Cut on the delta theta between the bkg segment and the extrapolated parameters.
SG::ReadHandleKey< xAOD::TruthParticleContainer > m_truthKey
Key to the truth particle container to associate.
ServiceHandle< Muon::IMuonIdHelperSvc > m_idHelperSvc
IdHelperSvc to decode the Identifiers.
SG::WriteDecorHandleKey< xAOD::TruthParticleContainer > m_segLinkKey
Declaration of the segmentLink to the truth particle.
Gaudi::Property< double > m_pileUpObjDPhiCut
Delta phi cut between particle momentum & segment position to start the extrapolation.
Gaudi::Property< double > m_pileUpObjExtpDyCut
Cut on the delta y0 between the bkg segment and the extrapolated parameters.
xAOD::ContainerDecorator< xAOD::MuonSegmentContainer, TruthPartLink_t > TruthPartDecor_t
void matchPileupSegments(const EventContext &ctx, const std::vector< const xAOD::TruthParticle * > &pileUpMuons, const std::vector< const xAOD::MuonSegment * > &pileUpSegments, TruthPartDecor_t &truthPartDecor, TruthSegLinkDecor_t &truthSegDecor) const
Match truth muons without any HEPMC link with truth segments reconstructed in the MS.
virtual StatusCode execute(const EventContext &ctx) const override final
Gaudi::Property< double > m_pileUpObjExtpDphiCut
Cut on the delta phi between the bkg segment and the extrapolated parameters.
SG::ReadHandleKey< xAOD::MuonSegmentContainer > m_segmentKey
Key to the truth segment container to associate.
SG::ReadDecorHandleKeyArray< xAOD::TruthParticleContainer > m_simHitKeys
Declaration of the dependency on the simHit decorations.
ToolHandle< ActsTrk::IExtrapolationTool > m_extrapolationTool
Track extrapolation tool.
Gaudi::Property< double > m_pileUpObjExtpDxCut
Cut on the delta x0 between the bkg segment and the extrapolated parameters.
Helper class to provide constant type-safe access to aux data.
Property holding a SG store/key/clid/attr name from which a ReadDecorHandle is made.
Handle class for reading a decoration on an object.
Auxiliary class to instantiate WriteDecorHandles.The handles can be created in an empty state.
const Cont_t * container() const
Returns the underlying container.
Amg::Vector3D direction() const
Returns the direction as Amg::Vector.
::Muon::MuonStationIndex::ChIndex chamberIndex() const
Returns the chamber index.
Amg::Vector3D position() const
Returns the position as Amg::Vector.
int etaIndex() const
Returns the eta index, which corresponds to stationEta in the offline identifiers (and the ).
bool hasProdVtx() const
Check for a production vertex on this particle.
const TruthVertex_v1 * prodVtx() const
The production vertex of this particle.
float z() const
Vertex longitudinal distance along the beam line form the origin.
float y() const
Vertex y displacement.
float t() const
Vertex time.
float x() const
Vertex x displacement.
std::pair< Amg::Vector3D, double > convertPosFromActs(const Acts::Vector4 &actsPos)
Converts an Acts 4-vector into a pair of an Athena spatial vector and the passed time.
Acts::Vector4 convertMomToActs(const Amg::Vector3D &threeMom, const double mass=0.)
Converts a three momentum vector from Athena together with the associated particle mass into an Acts ...
Acts::Vector4 convertPosToActs(const Amg::Vector3D &athenaPos, const double athenaTime=0.)
Converts a position vector & time from Athena units into Acts units.
std::string toString(const Translation3D &translation, int precision=4)
GeoPrimitvesToStringConverter.
double lineDistance(const AmgVector(N)&posA, const AmgVector(N)&dirA, const AmgVector(N)&posB, const AmgVector(N)&dirB)
: Calculates the shortest distance between two lines
Amg::Isometry3D getTranslate3D(const double X, const double Y, const double Z)
: Returns a shift transformation along an arbitrary axis
Eigen::Matrix< double, 2, 1 > Vector2D
Eigen::Matrix< double, 3, 1 > Vector3D
int uniqueID(const T &p)
Parameters localSegmentPars(const xAOD::MuonSegment &seg)
Returns the localSegPars decoration from a xAODMuon::Segment.
std::string toString(const Parameters &pars)
Dumps the parameters into a string with labels in front of each number.
This header ties the generic definitions in this package.
std::vector< const xAOD::MuonSimHit * > getMatchingSimHits(const xAOD::MuonSegment &segment)
: Returns all sim hits matched to a xAOD::MuonSegment
std::vector< SegLink_t > SegLinkVec_t
ElementLink< xAOD::MuonSegmentContainer > SegLink_t
const std::string & chName(ChIndex index)
convert ChIndex into a string
const T * get(const ReadCondHandleKey< T > &key, const EventContext &ctx)
Convenience function to retrieve an object given a ReadCondHandleKey.
MuonSegmentContainer_v1 MuonSegmentContainer
Definition of the current "MuonSegment container version".
TruthVertex_v1 TruthVertex
Typedef to implementation.
Definition TruthVertex.h:15
MuonSimHit_v1 MuonSimHit
Defined the version of the MuonSimHit.
Definition MuonSimHit.h:12
TruthParticle_v1 TruthParticle
Typedef to implementation.
MuonSegment_v1 MuonSegment
Reference the current persistent version:
TruthParticleContainer_v1 TruthParticleContainer
Declare the latest version of the truth particle container.