Project
Loading...
Searching...
No Matches
Tracker.cxx
Go to the documentation of this file.
1// Copyright 2019-2020 CERN and copyright holders of ALICE O2.
2// See https://alice-o2.web.cern.ch/copyright for details of the copyright holders.
3// All rights not expressly granted are reserved.
4//
5// This software is distributed under the terms of the GNU General Public
6// License v3 (GPL Version 3), copied verbatim in the file "COPYING".
7//
8// In applying this license CERN does not waive the privileges and immunities
9// granted to it by virtue of its status as an Intergovernmental Organization
10// or submit itself to any jurisdiction.
15
16#include "ITStracking/Tracker.h"
17
19#include "ITStracking/Cell.h"
25
27#include <cassert>
28#include <format>
29#include <cstdlib>
30#include <string>
31#include <climits>
32
33namespace o2::its
34{
36
37template <int nLayers>
39{
41 mTrkParams.resize(1);
42 if (traits->isGPU()) {
44 ITSGpuTrackingParamConfig::Instance().printKeyValues(true, true);
45 }
46}
47
48template <int nLayers>
49void Tracker<nLayers>::clustersToTracks(const LogFunc& logger, const LogFunc& error)
50{
51 LogFunc evalLog = [](const std::string&) {};
52
53 double total{0};
54 mTraits->updateTrackingParameters(mTrkParams);
55 int maxNvertices{-1};
56 if (mTrkParams[0].PerPrimaryVertexProcessing) {
57 for (int iROF{0}; iROF < mTimeFrame->getNrof(); ++iROF) {
58 int minRof = o2::gpu::CAMath::Max(0, iROF - mTrkParams[0].DeltaROF);
59 int maxRof = o2::gpu::CAMath::Min(mTimeFrame->getNrof(), iROF + mTrkParams[0].DeltaROF);
60 maxNvertices = std::max(maxNvertices, (int)mTimeFrame->getPrimaryVertices(minRof, maxRof).size());
61 }
62 }
63
64 int iteration{0}, iROFs{0}, iVertex{0};
65 auto handleException = [&](const auto& err) {
66 LOGP(error, "Too much memory used during {} in iteration {} in ROF span {}-{} iVtx={}: {:.2f} GB. Current limit is {:.2f} GB, check the detector status and/or the selections.",
67 StateNames[mCurState], iteration, iROFs, iROFs + mTrkParams[iteration].nROFsPerIterations, iVertex,
68 (double)mTimeFrame->getArtefactsMemory() / GB, (double)mTrkParams[iteration].MaxMemory / GB);
69 LOGP(error, "Exception: {}", err.what());
70 if (mTrkParams[iteration].DropTFUponFailure) {
71 mMemoryPool->print();
72 mTimeFrame->wipe();
73 ++mNumberOfDroppedTFs;
74 error("...Dropping Timeframe...");
75 } else {
76 throw err;
77 }
78 };
79
80 try {
81 for (iteration = 0; iteration < (int)mTrkParams.size(); ++iteration) {
82 mMemoryPool->setMaxMemory(mTrkParams[iteration].MaxMemory);
83 if (iteration == 3 && mTrkParams[0].DoUPCIteration) {
84 mTimeFrame->swapMasks();
85 }
86 double timeTracklets{0.}, timeCells{0.}, timeNeighbours{0.}, timeRoads{0.};
87 int nTracklets{0}, nCells{0}, nNeighbours{0}, nTracks{-static_cast<int>(mTimeFrame->getNumberOfTracks())};
88 int nROFsIterations = mTrkParams[iteration].nROFsPerIterations > 0 ? mTimeFrame->getNrof() / mTrkParams[iteration].nROFsPerIterations + bool(mTimeFrame->getNrof() % mTrkParams[iteration].nROFsPerIterations) : 1;
89 iVertex = std::min(maxNvertices, 0);
90 logger(std::format("==== ITS {} Tracking iteration {} summary ====", mTraits->getName(), iteration));
91
92 total += evaluateTask(&Tracker::initialiseTimeFrame, StateNames[mCurState = TFInit], iteration, logger, iteration);
93 do {
94 for (iROFs = 0; iROFs < nROFsIterations; ++iROFs) {
95 timeTracklets += evaluateTask(&Tracker::computeTracklets, StateNames[mCurState = Trackleting], iteration, evalLog, iteration, iROFs, iVertex);
96 nTracklets += mTraits->getTFNumberOfTracklets();
97 float trackletsPerCluster = mTraits->getTFNumberOfClusters() > 0 ? float(mTraits->getTFNumberOfTracklets()) / float(mTraits->getTFNumberOfClusters()) : 0.f;
98 if (trackletsPerCluster > mTrkParams[iteration].TrackletsPerClusterLimit) {
99 error(std::format("Too many tracklets per cluster ({}) in iteration {} in ROF span {}-{}:, check the detector status and/or the selections. Current limit is {}",
100 trackletsPerCluster, iteration, iROFs, iROFs + mTrkParams[iteration].nROFsPerIterations, mTrkParams[iteration].TrackletsPerClusterLimit));
101 break;
102 }
103 timeCells += evaluateTask(&Tracker::computeCells, StateNames[mCurState = Celling], iteration, evalLog, iteration);
104 nCells += mTraits->getTFNumberOfCells();
105 float cellsPerCluster = mTraits->getTFNumberOfClusters() > 0 ? float(mTraits->getTFNumberOfCells()) / float(mTraits->getTFNumberOfClusters()) : 0.f;
106 if (cellsPerCluster > mTrkParams[iteration].CellsPerClusterLimit) {
107 error(std::format("Too many cells per cluster ({}) in iteration {} in ROF span {}-{}, check the detector status and/or the selections. Current limit is {}",
108 cellsPerCluster, iteration, iROFs, iROFs + mTrkParams[iteration].nROFsPerIterations, mTrkParams[iteration].CellsPerClusterLimit));
109 break;
110 }
111 timeNeighbours += evaluateTask(&Tracker::findCellsNeighbours, StateNames[mCurState = Neighbouring], iteration, evalLog, iteration);
112 nNeighbours += mTimeFrame->getNumberOfNeighbours();
113 timeRoads += evaluateTask(&Tracker::findRoads, StateNames[mCurState = Roading], iteration, evalLog, iteration);
114 }
115 } while (++iVertex < maxNvertices);
116 logger(std::format(" - Tracklet finding: {} tracklets found in {:.2f} ms", nTracklets, timeTracklets));
117 logger(std::format(" - Cell finding: {} cells found in {:.2f} ms", nCells, timeCells));
118 logger(std::format(" - Neighbours finding: {} neighbours found in {:.2f} ms", nNeighbours, timeNeighbours));
119 logger(std::format(" - Track finding: {} tracks found in {:.2f} ms", nTracks + mTimeFrame->getNumberOfTracks(), timeRoads));
120 total += timeTracklets + timeCells + timeNeighbours + timeRoads;
121 if (mTraits->supportsExtendTracks() && mTrkParams[iteration].UseTrackFollower) {
122 int nExtendedTracks{-mTimeFrame->mNExtendedTracks}, nExtendedClusters{-mTimeFrame->mNExtendedUsedClusters};
123 auto timeExtending = evaluateTask(&Tracker::extendTracks, "Extending tracks", iteration, evalLog, iteration);
124 total += timeExtending;
125 logger(std::format(" - Extending Tracks: {} extended tracks using {} clusters found in {:.2f} ms", nExtendedTracks + mTimeFrame->mNExtendedTracks, nExtendedClusters + mTimeFrame->mNExtendedUsedClusters, timeExtending));
126 }
127 if (mTrkParams[iteration].PrintMemory) {
128 mMemoryPool->print();
129 }
130 }
131 if (mTraits->supportsFindShortPrimaries() && mTrkParams[0].FindShortTracks) {
132 auto nTracksB = mTimeFrame->getNumberOfTracks();
133 total += evaluateTask(&Tracker::findShortPrimaries, "Short primaries finding", 0, logger);
134 auto nTracksA = mTimeFrame->getNumberOfTracks();
135 logger(std::format(" `-> found {} additional tracks", nTracksA - nTracksB));
136 }
137 if constexpr (constants::DoTimeBenchmarks) {
138 logger(std::format("=== TimeFrame {} processing completed in: {:.2f} ms using {} thread(s) ===", mTimeFrameCounter, total, mTraits->getNThreads()));
139 }
140 } catch (const BoundedMemoryResource::MemoryLimitExceeded& err) {
141 handleException(err);
142 return;
143 } catch (const std::bad_alloc& err) {
144 handleException(err);
145 return;
146 } catch (...) {
147 error("Uncaught exception, all bets are off...");
148 }
149
150 if (mTimeFrame->hasMCinformation()) {
151 computeTracksMClabels();
152 }
153 rectifyClusterIndices();
154 ++mTimeFrameCounter;
155 mTotalTime += total;
156
157 if (mTrkParams[0].PrintMemory) {
158 mTimeFrame->printArtefactsMemory();
159 mMemoryPool->print();
160 }
161}
162
163template <int nLayers>
165{
167 if (!mTimeFrame->hasMCinformation()) {
168 return;
169 }
170
171 mTimeFrame->initialiseRoadLabels();
172
173 int roadsNum{static_cast<int>(mTimeFrame->getRoads().size())};
174
175 for (int iRoad{0}; iRoad < roadsNum; ++iRoad) {
176
177 auto& currentRoad{mTimeFrame->getRoads()[iRoad]};
178 std::vector<std::pair<MCCompLabel, size_t>> occurrences;
179 bool isFakeRoad{false};
180 bool isFirstRoadCell{true};
181
182 for (int iCell{0}; iCell < mTrkParams[0].CellsPerRoad(); ++iCell) {
183 const int currentCellIndex{currentRoad[iCell]};
184
185 if (currentCellIndex == constants::UnusedIndex) {
186 if (isFirstRoadCell) {
187 continue;
188 } else {
189 break;
190 }
191 }
192
193 const auto& currentCell{mTimeFrame->getCells()[iCell][currentCellIndex]};
194
195 if (isFirstRoadCell) {
196
197 const int cl0index{mTimeFrame->getClusters()[iCell][currentCell.getFirstClusterIndex()].clusterId};
198 auto cl0labs{mTimeFrame->getClusterLabels(iCell, cl0index)};
199 bool found{false};
200 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
201 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
202 for (const auto& label : cl0labs) {
203 if (label == occurrence.first) {
204 ++occurrence.second;
205 found = true;
206 // break; // uncomment to stop to the first hit
207 }
208 }
209 }
210 if (!found) {
211 for (const auto& label : cl0labs) {
212 occurrences.emplace_back(label, 1);
213 }
214 }
215
216 const int cl1index{mTimeFrame->getClusters()[iCell + 1][currentCell.getSecondClusterIndex()].clusterId};
217
218 const auto& cl1labs{mTimeFrame->getClusterLabels(iCell + 1, cl1index)};
219 found = false;
220 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
221 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
222 for (auto& label : cl1labs) {
223 if (label == occurrence.first) {
224 ++occurrence.second;
225 found = true;
226 // break; // uncomment to stop to the first hit
227 }
228 }
229 }
230 if (!found) {
231 for (auto& label : cl1labs) {
232 occurrences.emplace_back(label, 1);
233 }
234 }
235
236 isFirstRoadCell = false;
237 }
238
239 const int cl2index{mTimeFrame->getClusters()[iCell + 2][currentCell.getThirdClusterIndex()].clusterId};
240 const auto& cl2labs{mTimeFrame->getClusterLabels(iCell + 2, cl2index)};
241 bool found{false};
242 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
243 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
244 for (auto& label : cl2labs) {
245 if (label == occurrence.first) {
246 ++occurrence.second;
247 found = true;
248 // break; // uncomment to stop to the first hit
249 }
250 }
251 }
252 if (!found) {
253 for (auto& label : cl2labs) {
254 occurrences.emplace_back(label, 1);
255 }
256 }
257 }
258
259 std::sort(occurrences.begin(), occurrences.end(), [](auto e1, auto e2) {
260 return e1.second > e2.second;
261 });
262
263 auto maxOccurrencesValue = occurrences[0].first;
264 mTimeFrame->setRoadLabel(iRoad, maxOccurrencesValue.getRawValue(), isFakeRoad);
265 }
266}
267
268template <int nLayers>
269void Tracker<nLayers>::computeTracksMClabels()
270{
271 for (int iROF{0}; iROF < mTimeFrame->getNrof(); ++iROF) {
272 for (auto& track : mTimeFrame->getTracks(iROF)) {
273 std::vector<std::pair<MCCompLabel, size_t>> occurrences;
274 occurrences.clear();
275
276 for (int iCluster = 0; iCluster < TrackITSExt::MaxClusters; ++iCluster) {
277 const int index = track.getClusterIndex(iCluster);
278 if (index == constants::UnusedIndex) {
279 continue;
280 }
281 auto labels = mTimeFrame->getClusterLabels(iCluster, index);
282 bool found{false};
283 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
284 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
285 for (const auto& label : labels) {
286 if (label == occurrence.first) {
287 ++occurrence.second;
288 found = true;
289 // break; // uncomment to stop to the first hit
290 }
291 }
292 }
293 if (!found) {
294 for (const auto& label : labels) {
295 occurrences.emplace_back(label, 1);
296 }
297 }
298 }
299 std::sort(std::begin(occurrences), std::end(occurrences), [](auto e1, auto e2) {
300 return e1.second > e2.second;
301 });
302
303 auto maxOccurrencesValue = occurrences[0].first;
304 uint32_t pattern = track.getPattern();
305 // set fake clusters pattern
306 for (int ic{TrackITSExt::MaxClusters}; ic--;) {
307 auto clid = track.getClusterIndex(ic);
308 if (clid != constants::UnusedIndex) {
309 auto labelsSpan = mTimeFrame->getClusterLabels(ic, clid);
310 for (const auto& currentLabel : labelsSpan) {
311 if (currentLabel == maxOccurrencesValue) {
312 pattern |= 0x1 << (16 + ic); // set bit if correct
313 break;
314 }
315 }
316 }
317 }
318 track.setPattern(pattern);
319 if (occurrences[0].second < track.getNumberOfClusters()) {
320 maxOccurrencesValue.setFakeFlag();
321 }
322 mTimeFrame->getTracksLabel(iROF).emplace_back(maxOccurrencesValue);
323 }
324 }
325}
326
327template <int nLayers>
328void Tracker<nLayers>::rectifyClusterIndices()
329{
330 for (int iROF{0}; iROF < mTimeFrame->getNrof(); ++iROF) {
331 for (auto& track : mTimeFrame->getTracks(iROF)) {
332 for (int iCluster = 0; iCluster < TrackITSExt::MaxClusters; ++iCluster) {
333 const int index = track.getClusterIndex(iCluster);
334 if (index != constants::UnusedIndex) {
335 track.setExternalClusterIndex(iCluster, mTimeFrame->getClusterExternalIndex(iCluster, index));
336 }
337 }
338 }
339 }
340}
341
342template <int nLayers>
344{
345 mTimeFrame = &tf;
346 mTraits->adoptTimeFrame(&tf);
347}
348
349template <int nLayers>
351{
352 auto avgTF = mTotalTime * 1.e-3 / ((mTimeFrameCounter > 0) ? (double)mTimeFrameCounter : -1.0);
353 auto avgTFwithDropped = mTotalTime * 1.e-3 / (((mTimeFrameCounter + mNumberOfDroppedTFs) > 0) ? (double)(mTimeFrameCounter + mNumberOfDroppedTFs) : -1.0);
354 LOGP(info, "Tracker summary: Processed {} TFs (dropped {}) in TOT={:.2f} s, AVG/TF={:.2f} ({:.2f}) s", mTimeFrameCounter, mNumberOfDroppedTFs, mTotalTime * 1.e-3, avgTF, avgTFwithDropped);
355}
356
357template class Tracker<7>;
358
359} // namespace o2::its
Base track model for the Barrel, params only, w/o covariance.
#define GB
Definition Utils.h:40
static constexpr int MaxClusters
< heavy version of TrackITS, with clusters embedded
Definition TrackITS.h:169
virtual bool isGPU() const noexcept
void printSummary() const
Definition Tracker.cxx:350
void adoptTimeFrame(TimeFrame< nLayers > &tf)
Definition Tracker.cxx:343
void clustersToTracks(const LogFunc &=[](const std::string &s) { std::cout<< s<< '\n';}, const LogFunc &=[](const std::string &s) { std::cerr<< s<< '\n';})
Definition Tracker.cxx:49
Tracker(TrackerTraits< nLayers > *traits)
Definition Tracker.cxx:38
GLuint index
Definition glcorearb.h:781
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
constexpr float GB
Definition Constants.h:30
constexpr bool DoTimeBenchmarks
Definition Constants.h:31
std::unique_ptr< GPUReconstructionTimeframe > tf
std::array< uint16_t, 5 > pattern