ATLAS Offline Software
Loading...
Searching...
No Matches
SeedAnalysisAlg.cxx
Go to the documentation of this file.
1/*
2 Copyright (C) 2002-2024 CERN for the benefit of the ATLAS collaboration
3*/
4
5#include "SeedAnalysisAlg.h"
6
9
12
13#include "Acts/Definitions/Units.hpp"
14#include "Acts/MagneticField/MagneticFieldContext.hpp"
17
18namespace ActsTrk {
19
20 SeedAnalysisAlg::SeedAnalysisAlg(const std::string& name, ISvcLocator* pSvcLocator)
21 : AthMonitorAlgorithm(name, pSvcLocator)
22 {}
23
25 ATH_MSG_INFO("Initializing " << name() << " ...");
26
27 ATH_CHECK( m_beamSpotKey.initialize() );
28 ATH_CHECK( m_fieldCondObjInputKey.initialize() );
29
30 ATH_CHECK( m_inputSeedColletionKey.initialize() );
31
32 ATH_CHECK( m_prdTruth.initialize(not m_prdTruth.empty()));
33 ATH_CHECK( m_detEleCollKey.initialize(not m_detEleCollKey.empty()) );
34
35 ATH_CHECK( m_EventInfoKey.initialize() );
36
37 ATH_CHECK( m_paramEstimationTool.retrieve(EnableTool{!m_prdTruth.empty()}) );
38 ATH_CHECK( m_trackingGeometryTool.retrieve(EnableTool{!m_prdTruth.empty()}) );
39 ATH_CHECK( m_geometryConvTool.retrieve(EnableTool{!m_prdTruth.empty()}) );
40
41 ATH_MSG_DEBUG("Monitoring settings ...");
43
45 }
46
47 StatusCode SeedAnalysisAlg::fillHistograms(const EventContext& ctx) const {
48 ATH_MSG_DEBUG( "Filling Histograms for " << name() << " ... " );
49
50 // CONDS
51 // Read the Beam Spot information
53 ATH_CHECK( beamSpotHandle.isValid() );
54 auto beamSpotData = beamSpotHandle.cptr();
55
56 // Read the b-field information
58 ATH_CHECK( readHandle.isValid() );
59 const AtlasFieldCacheCondObj* fieldCondObj{ *readHandle };
60
61 // Get the magnetic field
62 // Using ACTS classes in order to be sure we are consistent
63 Acts::MagneticFieldContext magFieldContext(fieldCondObj);
64 // Beam Spot Position
65 Acts::Vector2 beamPos( beamSpotData->beamPos()[ Amg::x ] * Acts::UnitConstants::mm,
66 beamSpotData->beamPos()[ Amg::y ] * Acts::UnitConstants::mm );
67
68 // Magnetic Field
69 ATLASMagneticFieldWrapper magneticField;
70 Acts::MagneticFieldProvider::Cache magFieldCache = magneticField.makeCache( magFieldContext );
71 Acts::Vector3 bField = *magneticField.getField( Acts::Vector3(beamPos.x(), beamPos.y(), 0),
72 magFieldCache );
73
74
75 // SEEDS
76 ATH_MSG_DEBUG( "Reading input collection with key " << m_inputSeedColletionKey.key() );
78 ATH_CHECK( handle.isValid() );
79 const ActsTrk::SeedContainer* seed_collection = handle.get();
80 ATH_MSG_DEBUG( "Retrieved " << seed_collection->size() << " input elements from key " << m_inputSeedColletionKey.key() );
81
82 auto monitor_nseed = Monitored::Scalar<int>("Nseed", seed_collection->size());
83 fill(m_monGroupName.value(), monitor_nseed);
84
85 // bottom
86 auto monitor_x1 =
87 Monitored::Collection("x1", *seed_collection,
88 [] (const auto& seed) -> double
89 { return seed.sp()[0]->x(); });
90 auto monitor_y1 =
91 Monitored::Collection("y1", *seed_collection,
92 [] (const auto& seed) -> double
93 { return seed.sp()[0]->y(); });
94 auto monitor_z1 =
95 Monitored::Collection("z1", *seed_collection,
96 [] (const auto& seed) -> double
97 { return seed.sp()[0]->z(); });
98 auto monitor_r1 =
99 Monitored::Collection("r1", *seed_collection,
100 [] (const auto& seed) -> double
101 {
102 const auto* sp = seed.sp()[0];
103 return std::sqrt(sp->x()*sp->x() + sp->y()*sp->y());
104 });
105
106 // middle
107 auto monitor_x2 =
108 Monitored::Collection("x2", *seed_collection,
109 [] (const auto& seed) -> double
110 { return seed.sp()[1]->x(); });
111 auto monitor_y2 =
112 Monitored::Collection("y2", *seed_collection,
113 [] (const auto& seed) -> double
114 { return seed.sp()[1]->y(); });
115 auto monitor_z2 =
116 Monitored::Collection("z2", *seed_collection,
117 [] (const auto& seed) -> double
118 { return seed.sp()[1]->z(); });
119 auto monitor_r2 =
120 Monitored::Collection("r2", *seed_collection,
121 [] (const auto& seed) -> double
122 {
123 const auto* sp = seed.sp()[1];
124 return std::sqrt(sp->x()*sp->x() + sp->y()*sp->y());
125 });
126
127 // top
128 auto monitor_x3 =
129 Monitored::Collection("x3", *seed_collection,
130 [] (const auto& seed) -> double
131 { return seed.sp()[2]->x(); });
132 auto monitor_y3 =
133 Monitored::Collection("y3", *seed_collection,
134 [] (const auto& seed) -> double
135 { return seed.sp()[2]->y(); });
136 auto monitor_z3 =
137 Monitored::Collection("z3", *seed_collection,
138 [] (const auto& seed) -> double
139 { return seed.sp()[2]->z(); });
140 auto monitor_r3 =
141 Monitored::Collection("r3", *seed_collection,
142 [] (const auto& seed) -> double
143 {
144 const auto* sp = seed.sp()[2];
145 return std::sqrt(sp->x()*sp->x() + sp->y()*sp->y());
146 });
147
148 std::vector< std::array<float, 7> > parametersCollection;
149 parametersCollection.reserve(seed_collection->size());
150
151 for (auto seed : *seed_collection) {
152 parametersCollection.push_back( estimateParameters(seed, 300. * bField[2] / 1000.) );
153 }
154
155 auto monitor_param_pt = Monitored::Collection("pt", parametersCollection,
156 [] (const auto& params) -> float
157 { return params[0]; });
158 auto monitor_param_theta = Monitored::Collection("theta", parametersCollection,
159 [] (const auto& params) -> float
160 { return params[1]; });
161 auto monitor_param_eta = Monitored::Collection("eta", parametersCollection,
162 [] (const auto& params) -> float
163 { return params[2]; });
164 auto monitor_param_d0 = Monitored::Collection("d0", parametersCollection,
165 [] (const auto& params) -> float
166 { return params[3]; });
167
168 auto monitor_param_dzdr_b = Monitored::Collection("dzdr_b", parametersCollection,
169 [] (const auto& params) -> float
170 { return params[4]; });
171 auto monitor_param_dzdr_t = Monitored::Collection("dzdr_t", parametersCollection,
172 [] (const auto& params) -> float
173 { return params[5]; });
174
175
176 auto monitor_param_penalty = Monitored::Collection("penalty", parametersCollection,
177 [] (const auto& params) -> float
178 { return params[6]; });
179
180
182 ATH_CHECK(eventInfo.isValid());
183
184 auto monitor_event_number = Monitored::Scalar<long>("event_number", static_cast<long>(eventInfo->eventNumber()));
185 auto monitor_actual_mu = Monitored::Scalar<float>("actual_mu", eventInfo->actualInteractionsPerCrossing());
186
187 std::vector<int> vec_truthBarcode;
188 std::vector<double> vec_truthProb;
189 if (not m_prdTruth.empty())
190 ATH_CHECK( fillTruthHistograms(ctx, *seed_collection, vec_truthBarcode, vec_truthProb) );
191 auto monitor_truth_barcode = Monitored::Collection("truth_barcode", vec_truthBarcode);
192 auto monitor_truth_prob = Monitored::Collection("truth_prob", vec_truthProb);
193
194 fill(m_monGroupName.value(),
195 monitor_x1, monitor_y1, monitor_z1, monitor_r1,
196 monitor_x2, monitor_y2, monitor_z2, monitor_r2,
197 monitor_x3, monitor_y3, monitor_z3, monitor_r3,
198 monitor_param_pt, monitor_param_theta, monitor_param_eta, monitor_param_d0,
199 monitor_param_dzdr_b, monitor_param_dzdr_t,
200 monitor_param_penalty,
201 monitor_event_number, monitor_actual_mu,
202 monitor_truth_barcode, monitor_truth_prob);
203
204 return StatusCode::SUCCESS;
205 }
206
207 StatusCode SeedAnalysisAlg::fillTruthHistograms(const EventContext& ctx,
208 const ActsTrk::SeedContainer& seed_container,
209 std::vector<int>& truthBarCodeVec,
210 std::vector<double>& truthProbVec) const
211 {
212 ATH_MSG_DEBUG( "Filling Truth Histograms for " << name() << " ... " );
213
215 ATH_CHECK(prdTruthHandle.isValid());
216 const PRD_MultiTruthCollection* prdTruth = prdTruthHandle.get();
217
219 ATH_CHECK( detEleHandle.isValid() );
220 const InDetDD::SiDetectorElementCollection& detElements = *detEleHandle.retrieve();
221
222 // Read the b-field information
224 ATH_CHECK( readHandle.isValid() );
225
226 const AtlasFieldCacheCondObj* fieldCondObj{ *readHandle };
227 ATH_CHECK( fieldCondObj != nullptr );
228
229 Acts::MagneticFieldContext magFieldContext(fieldCondObj);
230 auto geo_context = m_trackingGeometryTool->getNominalGeometryContext();
231
232
233 // utilities
234 // Used for param estimation
235 auto retrieveSurfaceFunction =
236 [this, &detElements] (const ActsTrk::Seed& seed, bool useTopSp) -> const Acts::Surface&
237 {
238 const xAOD::SpacePoint* sp = useTopSp ? seed.sp().back() : seed.sp().front();
239 const InDetDD::SiDetectorElement* element = detElements.getDetectorElement(
240 useTopSp ? sp->elementIdList().back() : sp->elementIdList().front());
241 const Trk::Surface& atlas_surface = element->surface();
242 return *m_geometryConvTool->convertSurfaceToActs(atlas_surface);
243 };
244
245
246 // computation
247 std::vector<bool> vec_pass;
248 vec_pass.reserve(seed_container.size());
249
250 std::vector<double> estimated_pt;
251 std::vector<double> estimated_eta;
252 estimated_pt.reserve(seed_container.size());
253 estimated_eta.reserve(seed_container.size());
254
255 for (auto seed : seed_container) {
256 std::optional<Acts::BoundTrackParameters> optTrackParams =
257 m_paramEstimationTool->estimateTrackParameters(
258 seed,
260 geo_context.context(),
261 magFieldContext,
262 retrieveSurfaceFunction);
263
264 if ( not optTrackParams.has_value() ) continue;
265
266 const auto param = optTrackParams.value();
267 estimated_pt.push_back( param.transverseMomentum() );
268 estimated_eta.push_back( -std::log( std::tan(0.5 * param.parameters()[Acts::eBoundTheta]) ) );
269
270 std::map<int, int> truthHits;
271
272 const auto& sps = seed.sp();
273 for (const auto* sp : sps) {
274 int number_of_clusters = m_usePixel ? 1 : 2;
275 for (int cluster_number(0); cluster_number < number_of_clusters; cluster_number++) {
276 const auto& els = sp->measurements();
277 const auto* cluster = els[cluster_number];
278 const xAOD::UncalibMeasType cluster_type = cluster->type();
279 const Identifier id = cluster_type == xAOD::UncalibMeasType::PixelClusterType
280 ? identify(*reinterpret_cast<const xAOD::PixelCluster*>(cluster))
281 : identify(*reinterpret_cast<const xAOD::StripCluster*>(cluster));
282 matchParticleToSeedClusters(prdTruth, id, truthHits);
283 }
284 }
285
286 auto [barcode, prob] = findSeedMajorityTruthParticle(truthHits);
287 truthBarCodeVec.push_back(barcode);
288 truthProbVec.push_back(prob);
289 vec_pass.push_back( barcode != 0 and prob > 0.5 );
290 }
291
292 auto monitor_estimated_pt = Monitored::Collection("estimated_pt", estimated_pt);
293 auto monitor_estimated_eta = Monitored::Collection("estimated_eta", estimated_eta);
294 auto monitor_pass = Monitored::Collection("passed", vec_pass);
295
296 fill(m_monGroupName.value(),
297 monitor_pass,
298 monitor_estimated_pt, monitor_estimated_eta);
299
300 return StatusCode::SUCCESS;
301 }
302
304 {
305 static const SG::ConstAccessor< ElementLink< InDet::PixelClusterCollection > > pixelLinkAcc("pixelClusterLink");
306
307 // TO-DO -- AODs will not have this decoration, we'll need to provide a function for recomputing
308 // the identifier from local position
309 if (not pixelLinkAcc.isAvailable (cluster))
310 return Identifier();
311
312 ElementLink<InDet::PixelClusterCollection> pixelLink = pixelLinkAcc(cluster);
313 return (*pixelLink)->identify();
314 }
315
317 {
318 static const SG::ConstAccessor< ElementLink< InDet::SCT_ClusterCollection > > stripLinkAcc("sctClusterLink");
319
320 // TO-DO -- AODs will not have this decoration, we'll need to provide a function for recomputing
321 // the identifier from local position
322 if (not stripLinkAcc.isAvailable (cluster))
323 return Identifier();
324
325 ElementLink<InDet::SCT_ClusterCollection> stripLink = stripLinkAcc(cluster);
326 return (*stripLink)->identify();
327 }
328
329
331 const Identifier& id,
332 std::map<int, int>& countMap) const {
333 auto n1 = prdTruth->count(id);
334 if (n1 == 0) {
335 int bc = 0;
336 auto nBC = countMap.count(bc);
337 if (nBC == 0) {
338 countMap[bc] = 1;
339 } else {
340 countMap[bc] += 1;
341 }
342 } else {
343 using iprdt = PRD_MultiTruthCollection::const_iterator;
344 std::pair<iprdt, iprdt> range = prdTruth->equal_range(id);
345 for (iprdt itr = range.first; itr != range.second; ++itr) {
346 auto bc = itr->second.barcode();
347 auto nBC = countMap.count(bc);
348 if (nBC == 0) {
349 countMap[bc] = 1;
350 } else {
351 countMap[bc] += 1;
352 }
353 }
354 }
355 }
356
357
358
359 std::pair<int, double> SeedAnalysisAlg::findSeedMajorityTruthParticle(const std::map<int, int>& countMap) const {
360 int bestCount = 0;
361 int bestBarcode = std::numeric_limits<int>::min();
362
363 for (auto const& [barcode, count] : countMap) {
364 if (count > bestCount) {
365 bestCount = count;
366 bestBarcode = barcode;
367 }
368 }
369
370 // 3 spacepoints per seed, 1 (2) clusters per spacepoint for pixel (strip)
371 double nTotal = m_usePixel ? 3. : 6.;
372 double prob = bestCount / nTotal;
373
374 return std::make_pair(bestBarcode, prob);
375 }
376
377 std::array<float, 7> SeedAnalysisAlg::estimateParameters(const ActsTrk::Seed& seed,
378 float pTPerHelixRadius) const
379 {
380 auto extractCoordinates =
381 [] (const xAOD::SpacePoint* sp) -> std::array<float,4>
382 {
383 std::array<float, 4> coordinates {static_cast<float>(sp->x()),
384 static_cast<float>(sp->y()),
385 static_cast<float>(sp->z()),
386 static_cast<float>(std::sqrt(sp->x()*sp->x() + sp->y()*sp->y()))};
387 return coordinates;
388 };
389
390 auto extractQuantities =
391 [] (const std::array<float, 4>& sp,
392 const std::array<float, 4>& spM,
393 bool isBottom) -> std::array<float, 5>
394 {
395 auto& [xM, yM, zM, rM] = spM;
396 auto& [xO, yO, zO, rO] = sp;
397
398 float cosPhiM = xM / rM;
399 float sinPhiM = yM / rM;
400 float deltaX = xO - xM;
401 float deltaY = yO - yM;
402 float deltaZ = zO - zM;
403 float x = deltaX * cosPhiM + deltaY * sinPhiM;
404 float y = deltaY * cosPhiM - deltaX * sinPhiM;
405 float iDeltaR2 = 1.f / (deltaX * deltaX + deltaY * deltaY);
406 float iDeltaR = std::sqrt(iDeltaR2);
407 int bottomFactor = int(not isBottom) - int(isBottom);
408 float cot_theta = deltaZ * iDeltaR * bottomFactor;
409
410 // cotTheta, Zo, iDeltaR, U, V
411 std::array<float, 5> params =
412 {
413 cot_theta,
414 zM - rM * cot_theta,
415 iDeltaR,
416 x * iDeltaR2,
417 y * iDeltaR2
418 };
419
420 return params;
421 };
422
423 const auto& sps = seed.sp();
424 const auto* bottom = sps[0];
425 const auto* medium = sps[1];
426 const auto* top = sps[2];
427
428 auto coo_b = extractCoordinates(bottom);
429 auto coo_m = extractCoordinates(medium);
430 auto coo_t = extractCoordinates(top);
431
432 // Compute the variables we need
433 auto [cotThetaB, Zob, iDeltaRB, Ub, Vb] = extractQuantities(coo_b, coo_m, true);
434 auto [cotThetaT, Zot, iDeltaRT, Ut, Vt] = extractQuantities(coo_t, coo_m, false);
435
436 float squarediDeltaR2B = iDeltaRB*iDeltaRB;
437 float squarediDeltaR2T = iDeltaRB*iDeltaRT;
438 float squarediDeltaR = std::min(squarediDeltaR2B, squarediDeltaR2T);
439
440 auto& [xB, yB, zB, rB] = coo_b;
441 auto& [xM, yM, zM, rM] = coo_m;
442 auto& [xT, yT, zT, rT] = coo_t;
443
444 float ax = xM / rM;
445 float ay = yM/ rM;
446
447 float dxb = xM - xB;
448 float dyb = yM - yB;
449 float dzb = zM - zB;
450 float xb = dxb * ax + dyb *ay;
451 float yb = dyb * ax - dxb * ay;
452 float dxyb = xb * xb + yb * yb;
453 float dxt = xT - xM;
454 float dyt = yT - yM;
455 float dzt = zT - zM;
456 float xt = dxt * ax + dyt *ay;
457 float yt = dyt * ax - dxt * ay;
458 float dxyt = xt * xt + yt * yt;
459
460 float tzb = dzb * std::sqrt( 1.f/dxyb );
461 float tzt = dzt * std::sqrt( 1.f/dxyt );
462
463 float sTzb2 = std::sqrt(1.f + tzb*tzb);
464
465 float dU = Ut - Ub;
466 if (dU == 0.) {
467 return {-1, -1, -1, -1, -1, -1, -1};
468 }
469
470 float A = (Vt - Vb) / dU;
471 float S2 = 1.f + A * A;
472 float B = Vb - A * Ub;
473 float B2 = B * B;
474 if (B2 == 0) B2 = 1e-8;
475
476 // dzdr
477 float dzdr_b = (zM - zB) / (rM - rB);
478 float dzdr_t = (zT - zM) / (rT - rM);
479
480 // eta
481 float cotThetaAvg2 = cotThetaB * cotThetaT;
482 if (cotThetaAvg2 <= 0) {
483 return {-1, -1, -1, -1, -1, -1, -1};
484 }
485 float theta = std::atan(1.f / std::sqrt(cotThetaAvg2));
486 float eta = -std::log(std::tan(0.5f * theta));
487
488 // pt
489 float pt = pTPerHelixRadius * std::sqrt(S2 / B2) / 2.f;
490
491 // d0
492 float d0 = std::abs((A - B * rM) * rM);
493
494 // curvature
495 // not used in current version of the code. We may want to use it later
496 // float curvature = B / std::sqrt(S2);
497 float penalty = std::abs((tzb - tzt) / (squarediDeltaR * sTzb2));
498
499 return {pt, theta, eta, d0, dzdr_b, dzdr_t, penalty};
500 }
501
502}
Scalar eta() const
pseudorapidity method
Scalar theta() const
theta method
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_INFO(x)
#define ATH_MSG_DEBUG(x)
bool isBottom(const T &p)
Definition AtlasPID.h:182
Helper class to provide constant type-safe access to aux data.
static Double_t sp
This is an Identifier helper class for the Pixel subdetector.
struct TBPatternUnitContext S2
@ top
#define y
#define xt
#define yt
#define x
Acts::Result< Acts::Vector3 > getField(const Acts::Vector3 &position, Acts::MagneticFieldProvider::Cache &gcache) const override
MagneticFieldProvider::Cache makeCache(const Acts::MagneticFieldContext &mctx) const override
virtual StatusCode fillHistograms(const EventContext &ctx) const override
adds event to the monitoring histograms
std::pair< int, double > findSeedMajorityTruthParticle(const std::map< int, int > &countMap) const
SeedAnalysisAlg(const std::string &name, ISvcLocator *pSvcLocator)
Gaudi::Property< bool > m_usePixel
StatusCode fillTruthHistograms(const EventContext &ctx, const ActsTrk::SeedContainer &seed_container, std::vector< int > &, std::vector< double > &) const
ToolHandle< ActsTrk::ITrackParamsEstimationTool > m_paramEstimationTool
const Identifier identify(const xAOD::PixelCluster &) const
void matchParticleToSeedClusters(const PRD_MultiTruthCollection *prdTruth, const Identifier &id, std::map< int, int > &countMap) const
std::array< float, 7 > estimateParameters(const ActsTrk::Seed &seed, float pTPerHelixRadius) const
SG::ReadHandleKey< PRD_MultiTruthCollection > m_prdTruth
virtual StatusCode initialize() override
initialize
Gaudi::Property< std::string > m_monGroupName
PublicToolHandle< IGeometryRealmConvTool > m_geometryConvTool
SG::ReadCondHandleKey< AtlasFieldCacheCondObj > m_fieldCondObjInputKey
SG::ReadHandleKey< ActsTrk::SeedContainer > m_inputSeedColletionKey
SG::ReadCondHandleKey< InDet::BeamSpotData > m_beamSpotKey
PublicToolHandle< ActsTrk::ITrackingGeometryTool > m_trackingGeometryTool
SG::ReadCondHandleKey< InDetDD::SiDetectorElementCollection > m_detEleCollKey
Gaudi::Property< bool > m_useTopSp
virtual StatusCode initialize() override
initialize
AthMonitorAlgorithm(const std::string &name, ISvcLocator *pSvcLocator)
Constructor.
SG::ReadHandleKey< xAOD::EventInfo > m_EventInfoKey
Key for retrieving EventInfo from StoreGate.
Class to hold the SiDetectorElement objects to be put in the detector store.
const SiDetectorElement * getDetectorElement(const IdentifierHash &hash) const
Class to hold geometrical description of a silicon detector element.
Trk::Surface & surface()
Element Surface.
Declare a monitored scalar variable.
A PRD is mapped onto all contributing particles.
Helper class to provide constant type-safe access to aux data.
bool isAvailable(const ELT &e) const
Test to see if this variable exists in the store.
const_pointer_type retrieve()
const_pointer_type cptr()
virtual bool isValid() override final
Can the handle be successfully dereferenced?
const_pointer_type get() const
Dereference the pointer, but don't cache anything.
Abstract Base Class for tracking surfaces.
Definition Surface.h:79
void fill(const ToolHandle< GenericMonitoringTool > &groupHandle, std::vector< std::reference_wrapper< Monitored::IMonitoredVariable > > &&variables) const
Fills a vector of variables to a group by reference.
int count(std::string s, const std::string &regx)
count how many occurances of a regx are in a string
Definition hcg.cxx:148
The AlignStoreProviderAlg loads the rigid alignment corrections and pipes them through the readout ge...
ValuesCollection< T > Collection(std::string name, const T &collection)
Declare a monitored (double-convertible) collection.
SG::ReadCondHandle< T > makeHandle(const SG::ReadCondHandleKey< T > &key, const EventContext &ctx=Gaudi::Hive::currentContext())
StripCluster_v1 StripCluster
Define the version of the strip cluster class.
PixelCluster_v1 PixelCluster
Define the version of the pixel cluster class.
UncalibMeasType
Define the type of the uncalibrated measurement.
hold the test vectors and ease the comparison
std::size_t size() const noexcept