ATLAS Offline Software
Loading...
Searching...
No Matches
FPGATrackSimDataPrepAlg.cxx
Go to the documentation of this file.
1
2
3// Copyright (C) 2002-2025 CERN for the benefit of the ATLAS collaboration
4
6
14
18
20
23
25
26#include "GaudiKernel/IEventProcessor.h"
28
29constexpr bool enableBenchmark =
30#ifdef BENCHMARK_FPGATRACKSIM
31 true;
32#else
33 false;
34#endif
35
37// Initialize
38
39FPGATrackSimDataPrepAlg::FPGATrackSimDataPrepAlg (const std::string& name, ISvcLocator* pSvcLocator) :
40 AthReentrantAlgorithm(name, pSvcLocator)
41{
42}
43
44
46{
47 std::stringstream ss(m_description);
48 std::string line;
49 ATH_MSG_INFO("Tag config:");
50 if (!m_description.empty()) {
51 while (std::getline(ss, line, '\n')) {
52 ATH_MSG_INFO('\t' << line);
53 }
54 }
55
56 // Dump the configuration to make sure it propagated through right
57 const std::vector<Gaudi::Details::PropertyBase*> props = this->getProperties();
58 for( Gaudi::Details::PropertyBase* prop : props ) {
59 if (prop->ownerTypeName()==this->type()) {
60 ATH_MSG_DEBUG("Property:\t" << prop->name() << "\t : \t" << prop->toString());
61 }
62 }
63
64
65 ATH_CHECK(m_hitSGInputTool.retrieve(EnableTool{!m_hitSGInputTool.empty()}));
66
67 ATH_CHECK(m_hitInputTool.retrieve(EnableTool{!m_hitInputTool.empty()}));
68 ATH_CHECK(m_hitInputTool2.retrieve(EnableTool{m_secondInputToolN > 0 && !m_hitInputTool2.empty()}));
69 ATH_CHECK(m_hitMapTools.retrieve());
70 ATH_CHECK(m_hitFilteringTool.retrieve(EnableTool{m_doHitFiltering}));
71 ATH_CHECK(m_clusteringTool.retrieve(EnableTool{m_clustering > 0}));
72
73 ATH_CHECK(m_writeOutputTool.retrieve());
75
76
77 ATH_MSG_DEBUG("initialize() Instantiating root objects");
79 m_logicEventHeader = m_writeOutputTool->addInputBranch(m_postClusterBranch.value(), true);
80
81 ATH_MSG_DEBUG("initialize() Setting branch");
82
83 if (!m_monTool.empty())
84 ATH_CHECK(m_monTool.retrieve());
85
86 ATH_CHECK( m_FPGAClusterKey.initialize() );
87 ATH_CHECK( m_FPGAHitKey.initialize() );
88 ATH_CHECK( m_FPGAHitUnmappedKey.initialize() );
90 ATH_CHECK( m_truthLinkContainerKey.initialize() );
91 ATH_CHECK( m_FPGATruthTrackKey.initialize() );
92 ATH_CHECK( m_FPGAOfflineTrackKey.initialize() );
93 ATH_CHECK( m_FPGAEventInfoKey.initialize() );
94
95 ATH_CHECK( m_chrono.retrieve() );
96 ATH_MSG_DEBUG("initialize() Finished");
97
98
99 return StatusCode::SUCCESS;
100}
101
102
104// MAIN EXECUTE ROUTINE //
106
107StatusCode FPGATrackSimDataPrepAlg::execute(const EventContext& ctx) const
108{
109 // Local event headers (thread-safe)
111 FPGATrackSimEventInputHeader firstInputHeader;
112
113 FPGATrackSimLogicalEventInputHeader logicEventHeader_precluster;
115
116 // Local storage for clusters and unmapped hits
118 std::vector<std::unique_ptr<FPGATrackSimHit>> hits_miss;
119
120 // Read inputs
121 bool done = false;
122 ATH_CHECK(readInputs(ctx, eventHeader, firstInputHeader, done));
123
124 if (done) {
125 SmartIF<IEventProcessor> appMgr{service("ApplicationMgr")};
126 if (!appMgr) {
127 ATH_MSG_ERROR("Failed to retrieve ApplicationMgr as IEventProcessor");
128 return StatusCode::FAILURE;
129 }
130 return appMgr->stopRun();
131 }
132
135
137 ATH_CHECK( FPGAHitUnmapped.record (std::make_unique<FPGATrackSimHitCollection>()));
138
140 ATH_CHECK( FPGAClusters.record (std::make_unique<FPGATrackSimClusterCollection>()));
141
143 ATH_CHECK(truthLinkVec.record(std::make_unique<xAODTruthParticleLinkVector>()));
144
146 ATH_CHECK(FPGATruthTracks.record(std::make_unique<FPGATrackSimTruthTrackCollection>()));
147
149 ATH_CHECK(FPGAOfflineTracks.record(std::make_unique<FPGATrackSimOfflineTrackCollection>()));
150 // Apply event selection based on truth tracks
151 if (m_doEvtSel) {
152 bool acceptEvent = false;
153 if constexpr (enableBenchmark) m_chrono->chronoStart("DataPrep: EventSelection");
154 for (auto eventSelector : m_eventSelectionTools)
155 {
156 if (eventSelector->selectEvent(eventHeader)) {
157 ATH_MSG_DEBUG("Event accepted by: " << eventSelector->name());
158 acceptEvent = true;
159 if ((m_writeRegion>=0)&&(m_writeRegion==eventSelector->getRegionID())) {
160 m_writeOutputTool->activateEventOutput();
161 }
162 }
163 }
164 if constexpr (enableBenchmark) m_chrono->chronoStop("DataPrep: EventSelection");
165 if (m_useInternalTruthTracks && acceptEvent) {
166 if constexpr (enableBenchmark) m_chrono->chronoStart("DataPrep: TruthMatching");
167 SG::ReadHandle<xAOD::TruthParticleContainer> truthParticleContainer(m_inputTruthParticleContainerKey, ctx); // Read offline TruthParticles
168 if (!truthParticleContainer.isValid()) {
169 ATH_MSG_ERROR("No valid truth particle container with key " << truthParticleContainer.key());
170 return StatusCode::FAILURE;
171 }
172 ATH_MSG_DEBUG("making mp of truth particles");
173 std::unordered_map<HepMcParticleLink::barcode_type, std::pair<const xAOD::TruthParticle*, size_t>> truthParticlesMap;
174 size_t truthParticleIndex = 0;
175 for (const xAOD::TruthParticle* truthParticle : *truthParticleContainer) {
176 truthParticlesMap.insert(std::make_pair(HepMC::uniqueID(truthParticle), std::make_pair(truthParticle,truthParticleIndex)));
177 truthParticleIndex++;
178 }
179 const FPGATrackSimTruthTrackCollection& fpgaTruthTracks = eventHeader.optional().getTruthTracks();
180 truthLinkVec->reserve(fpgaTruthTracks.size());
181 ATH_MSG_DEBUG("begin truth matching for " << fpgaTruthTracks.size() << " FPGA truth tracks");
182 for (const FPGATrackSimTruthTrack& fpgaTruthTrack : fpgaTruthTracks) {
183 auto it = truthParticlesMap.find(fpgaTruthTrack.getUniqueID()); // TODO FIXME need to check FPGATrackSimTruthTrack uniqueIDs are properly filled
184 if (it != truthParticlesMap.end()) {
185 ElementLink<xAOD::TruthParticleContainer> truthParticleLink(*truthParticleContainer, it->second.second);
186 // TODO: check if we can avoid using the previously-created map and look directly for the unique ID in the link vector container
187 truthLinkVec->push_back(new xAODTruthParticleLink(HepMcParticleLink(HepMC::uniqueID(it->second.first), 0,
189 ATH_MSG_DEBUG("Truth link added");
190 }
191 }
192 if (truthLinkVec->empty()) {
193 ATH_MSG_DEBUG("No truth particles selected. Skipping event...");
194 return StatusCode::SUCCESS;
195 }
196 std::stable_sort(truthLinkVec->begin(), truthLinkVec->end(), SortTruthParticleLink());
197 if constexpr (enableBenchmark) m_chrono->chronoStop("DataPrep: TruthMatching");
198 }
199 }
200 else {
201 ATH_MSG_DEBUG("No Event Selection applied");
202 for (auto eventSelector : m_eventSelectionTools) {
203 eventSelector->setSelectedEvent(true);
204 }
205 }
206
207 // Event passes cuts, count it
208 m_evt++;
209
210 // Map, cluster, and filter hits
211 ATH_CHECK(processInputs(eventHeader, logicEventHeader, logicEventHeader_precluster,
212 hits_miss, clusters, FPGAHitUnmapped, FPGAClusters));
213
214 if constexpr (enableBenchmark) m_chrono->chronoStart("DataPrep: get truth/offline tracks");
215 for (const auto& truthtrack : logicEventHeader.optional().getTruthTracks()) {
216 FPGATruthTracks->push_back(truthtrack);
217 }
218
219 // Need to do the same for offline tracks.
220 for (const auto& offlineTrack : logicEventHeader.optional().getOfflineTracks()) {
221 FPGAOfflineTracks->push_back(offlineTrack);
222 }
223
224 if constexpr (enableBenchmark) m_chrono->chronoStop("DataPrep: get truth/offline tracks");
225
226 // Get reference to hits
227
228 // Recording Data
229 for (auto eventSelector : m_eventSelectionTools)
230 {
231 // Get reference to hits
232 const unsigned& regionID = eventSelector->getRegionID();
233
234 auto mon_regionID = Monitored::Scalar<unsigned>("regionID", regionID);
235 Monitored::Group(m_monTool, mon_regionID);
236 }
237
238 std::vector<FPGATrackSimHit> const& hits = logicEventHeader.towers().at(0).hits();
239 if (m_recordHits) {
240 if constexpr (enableBenchmark) m_chrono->chronoStart("DataPrep: record hits");
241 // If and when we set up code to run over more than one region/tower at a time this will need to be updated
242 auto *FPGAHits_cdv = FPGAHits.ptr();
243 for (const FPGATrackSimCluster& cluster : *FPGAClusters) {
244 const FPGATrackSimHit* hit = &cluster.getClusterEquiv();
245 if (hit->isReal()) FPGAHits_cdv->push_back(hit);
246 }
247 if constexpr (enableBenchmark) m_chrono->chronoStop("DataPrep: record hits");
248 }
249
250 auto mon_nhits = Monitored::Scalar<unsigned>("nHits", hits.size());
251 auto mon_nhits_unmapped = Monitored::Scalar<unsigned>("nHits_unmapped", hits_miss.size());
252 Monitored::Group(m_monTool, mon_nhits, mon_nhits_unmapped);
253
255 // Put the FPGATrackSim event info on storegate so later algorithms can access it easily.
257 ATH_CHECK(FPGAEventInfo.record(std::make_unique<FPGATrackSimEventInfo>(eventHeader.event())));
258 }
259
260 // Write the output and reset
261 if (m_writeOutputData) {
262 // Lock and transfer to ROOT-managed pointers
263 std::lock_guard<std::mutex> lock(m_rootWriteMutex);
264
265 *m_logicEventHeader = std::move(logicEventHeader);
267 *m_logicEventHeader_precluster = std::move(logicEventHeader_precluster);
268 }
269
270 ATH_CHECK(m_writeOutputTool->writeData());
271 }
272
273 return StatusCode::SUCCESS;
274}
275
276
278// INPUT PASSING, READING AND PROCESSING //
280
282 const EventContext& ctx,
283 FPGATrackSimEventInputHeader& eventHeader,
284 FPGATrackSimEventInputHeader& firstInputHeader,
285 bool& done) const
286{
287
288 if (!m_hitSGInputTool.empty()) {
289 ATH_CHECK(m_hitSGInputTool->readData(&eventHeader, ctx));
290 ATH_MSG_DEBUG("Loaded " << eventHeader.nHits() << " hits in event header from SG");
291 return StatusCode::SUCCESS;
292 }
293
294 if (m_ev % m_firstInputToolN == 0)
295 {
296 // Read primary input
297 ATH_CHECK(m_hitInputTool->readData(&firstInputHeader, done));
298 if (done)
299 {
300 ATH_MSG_DEBUG("Cannot read more events from file, returning");
301 return StatusCode::SUCCESS;
302 }
303 }
304
305 eventHeader = firstInputHeader;
306
307 // Read secondary input
308 for (int i = 0; i < m_secondInputToolN; i++)
309 {
310 ATH_CHECK(m_hitInputTool2->readData(&eventHeader, done, false));
311 if (done)
312 {
313 ATH_MSG_INFO("Cannot read more events from file, returning");
314 return StatusCode::SUCCESS;
315 }
316 }
317
318 m_ev++;
319
320 return StatusCode::SUCCESS;
321}
322
323
324// Applies clustering, mapping, hit filtering, and space points
326 const FPGATrackSimEventInputHeader& eventHeader,
327 FPGATrackSimLogicalEventInputHeader& logicEventHeader,
328 FPGATrackSimLogicalEventInputHeader& logicEventHeader_precluster,
329 std::vector<std::unique_ptr<FPGATrackSimHit>>& hits_miss,
333{
334 // Map hits
335 ATH_MSG_DEBUG("Running hits conversion");
336 logicEventHeader.reset();
337 logicEventHeader_precluster.reset();
338
339 if constexpr (enableBenchmark) m_chrono->chronoStart("DataPrep: RawToLogical");
340 for (auto hitMapTool : m_hitMapTools){
341 ATH_CHECK(hitMapTool->convert(1, eventHeader, logicEventHeader));
342 }
343 if constexpr (enableBenchmark) m_chrono->chronoStop("DataPrep: RawToLogical");
344
345
346 for (auto& hit : hits_miss) FPGAHitUnmapped->push_back(std::move(hit));
347 hits_miss.clear();
348
349
350 ATH_MSG_DEBUG("Hits conversion done, #unmapped hists = " << FPGAHitUnmapped->size());
351
352 // At this stage, copy the logicEventHeader.
354 logicEventHeader_precluster = logicEventHeader;
355 }
356
357 if constexpr (enableBenchmark) m_chrono->chronoStart("DataPrep: Clustering");
358 // Clustering
359 for (int ic = 0; ic < m_clustering; ic++) {
360 ATH_MSG_DEBUG("Running clustering");
361 ATH_CHECK(m_clusteringTool->DoClustering(logicEventHeader, clusters));
362 // I think I also want to pass clusters to random removal (but won't work currently)
363 if (m_doHitFiltering) ATH_CHECK(m_hitFilteringTool->DoRandomRemoval(logicEventHeader, false));
364 unsigned npix(0), nstrip(0);
365 for (const FPGATrackSimCluster& cluster : clusters) {
366 if (cluster.getClusterEquiv().isPixel()) npix++;
367 else nstrip++;
368 }
369
370 m_nPixClusters += npix;
371 m_nStripClusters += nstrip;
372
373
374 // The following is hopefully a thread-safe approach to update nMaximum clusters
375 // using compare-exchange loop to prevent race conditions.
376 // Logic: Without atomics, two threads could both read e.g. max=100, calculate new values (150, 200),
377 // and the last write would win, potentially losing the true maximum (200 vs 150).
378 // compare_exchange_weak atomically checks if the value is unchanged before updating,
379 // and retries if another thread modified it concurrently, ensuring correctness.
380
381 // max update for m_nMaxPixClusters
382 unsigned current_max_pix = m_nMaxPixClusters;
383 while (npix > current_max_pix &&
384 !m_nMaxPixClusters.compare_exchange_weak(current_max_pix, npix));
385
386 // max update for m_nMaxStripClusters
387 unsigned current_max_strip = m_nMaxStripClusters;
388 while (nstrip > current_max_strip &&
389 !m_nMaxStripClusters.compare_exchange_weak(current_max_strip, nstrip));
390
391 // max update for m_nMaxClusters
392 unsigned current_max_clusters = m_nMaxClusters;
393 unsigned clusters_size = clusters.size();
394 while (clusters_size > current_max_clusters &&
395 !m_nMaxClusters.compare_exchange_weak(current_max_clusters, clusters_size));
396 }
397 // Record clusters
398 FPGAClusters->insert(
399 FPGAClusters->end(),
400 std::make_move_iterator(clusters.begin()),
401 std::make_move_iterator(clusters.end()));
402
403 if constexpr (enableBenchmark) m_chrono->chronoStop("DataPrep: Clustering");
404
405 return StatusCode::SUCCESS;
406}
407
409// Finalize
410
412{
413 ATH_MSG_INFO("PRINTING FPGATRACKSIM SIMPLE DATAPREP STATS");
414 ATH_MSG_INFO("========================================================================================");
415 ATH_MSG_INFO("Number of pixel clusters/event = " << m_nPixClusters/m_evt);
416 ATH_MSG_INFO("Number of strip clusters/event = " << m_nStripClusters/m_evt);
417 ATH_MSG_INFO("Max number of pixel clusters in an event = " << m_nMaxPixClusters);
418 ATH_MSG_INFO("Max number of strip clusters in an event = " << m_nMaxStripClusters);
419 ATH_MSG_INFO("Max number of clusters in an event = " << m_nMaxClusters);
420
421 return StatusCode::SUCCESS;
422}
#define ATH_CHECK
Evaluate an expression and check for errors.
#define ATH_MSG_ERROR(x)
#define ATH_MSG_INFO(x)
#define ATH_MSG_DEBUG(x)
DataVector adapter that acts like it holds const pointers.
std::vector< FPGATrackSimCluster > FPGATrackSimClusterCollection
: FPGATrackSim-specific class to represent an hit in the detector.
Utilize NN score to build track candidates.
Overlap removal tool for FPGATrackSimTrack.
Maps ITK module indices to FPGATrackSim regions.
Stores slice definitions for FPGATrackSim regions.
Defines a class for roads.
Structs that store the 5 track parameters.
std::vector< FPGATrackSimTruthTrack > FPGATrackSimTruthTrackCollection
static Double_t ss
An algorithm that can be simultaneously executed in multiple threads.
DataVector adapter that acts like it holds const pointers.
ToolHandleArray< FPGATrackSimRawToLogicalHitsTool > m_hitMapTools
SG::WriteHandleKey< FPGATrackSimOfflineTrackCollection > m_FPGAOfflineTrackKey
virtual StatusCode execute(const EventContext &ctx) const override final
SG::WriteHandleKey< FPGATrackSimHitCollection > m_FPGAHitUnmappedKey
Gaudi::Property< std::string > m_preClusterBranch
Gaudi::Property< bool > m_isDataPrepPipeline
Gaudi::Property< std::string > m_postClusterBranch
virtual StatusCode finalize() override
Gaudi::Property< bool > m_doEvtSel
SG::WriteHandleKey< FPGATrackSimTruthTrackCollection > m_FPGATruthTrackKey
FPGATrackSimLogicalEventInputHeader * m_logicEventHeader_precluster
ToolHandle< IFPGATrackSimInputTool > m_hitSGInputTool
Gaudi::Property< int > m_firstInputToolN
ToolHandle< FPGATrackSimOutputHeaderTool > m_writeOutputTool
StatusCode processInputs(const FPGATrackSimEventInputHeader &eventHeader, FPGATrackSimLogicalEventInputHeader &logicEventHeader, FPGATrackSimLogicalEventInputHeader &logicEventHeader_precluster, std::vector< std::unique_ptr< FPGATrackSimHit > > &hits_miss, FPGATrackSimClusterCollection &clusters, SG::WriteHandle< FPGATrackSimHitCollection > &FPGAHitUnmapped, SG::WriteHandle< FPGATrackSimClusterCollection > &FPGAClusters) const
SG::WriteHandleKey< ConstDataVector< FPGATrackSimHitCollection > > m_FPGAHitKey
virtual StatusCode initialize() override
Gaudi::Property< int > m_secondInputToolN
std::atomic< unsigned > m_nMaxStripClusters
ToolHandleArray< FPGATrackSim::FPGATrackSimEventSelectionTool > m_eventSelectionTools
std::atomic< unsigned > m_nMaxClusters
ToolHandle< FPGATrackSimReadRawRandomHitsTool > m_hitInputTool2
Gaudi::Property< bool > m_writePreClusterBranch
SG::ReadHandleKey< xAOD::TruthParticleContainer > m_inputTruthParticleContainerKey
ToolHandle< GenericMonitoringTool > m_monTool
Gaudi::Property< bool > m_useInternalTruthTracks
std::atomic< unsigned long > m_nPixClusters
ToolHandle< IFPGATrackSimEventInputHeaderTool > m_hitInputTool
FPGATrackSimLogicalEventInputHeader * m_logicEventHeader
std::atomic< unsigned > m_nMaxPixClusters
Gaudi::Property< int > m_writeRegion
Gaudi::Property< int > m_clustering
std::atomic< unsigned long > m_nStripClusters
SG::WriteHandleKey< FPGATrackSimEventInfo > m_FPGAEventInfoKey
Gaudi::Property< bool > m_writeOutputData
SG::WriteHandleKeyArray< FPGATrackSimClusterCollection > m_FPGAClusterKey
ServiceHandle< IChronoStatSvc > m_chrono
ToolHandle< FPGATrackSimClusteringToolI > m_clusteringTool
FPGATrackSimDataPrepAlg(const std::string &name, ISvcLocator *pSvcLocator)
Gaudi::Property< bool > m_doHitFiltering
Gaudi::Property< bool > m_recordHits
std::atomic< unsigned > m_ev
ToolHandle< IFPGATrackSimHitFilteringTool > m_hitFilteringTool
SG::WriteHandleKey< xAODTruthParticleLinkVector > m_truthLinkContainerKey
StatusCode readInputs(const EventContext &ctx, FPGATrackSimEventInputHeader &eventHeader, FPGATrackSimEventInputHeader &firstInputHeader, bool &done) const
FPGATrackSimEventInfo const & event() const
FPGATrackSimOptionalEventInfo const & optional() const
bool isReal() const
const std::vector< FPGATrackSimTowerInputHeader > & towers() const
FPGATrackSimOptionalEventInfo const & optional() const
const std::vector< FPGATrackSimTruthTrack > & getTruthTracks() const
const std::vector< FPGATrackSimOfflineTrack > & getOfflineTracks() const
Group of local monitoring quantities and retain correlation when filling histograms
Declare a monitored scalar variable.
virtual bool isValid() override final
Can the handle be successfully dereferenced?
virtual const std::string & key() const override final
Return the StoreGate ID for the referenced object.
StatusCode record(std::unique_ptr< T > data)
Record a const object to the store.
pointer_type ptr()
Dereference the pointer.
int uniqueID(const T &p)
@ VIEW_ELEMENTS
this data object is a view, it does not own its elmts
void stable_sort(DataModel_detail::iterator< DVL > beg, DataModel_detail::iterator< DVL > end)
Specialization of stable_sort for DataVector/List.
TruthParticle_v1 TruthParticle
Typedef to implementation.
constexpr bool enableBenchmark