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 if (typeid(err) != typeid(std::bad_alloc)) { // only print if the exceptions is different from what is expected
70 LOGP(error, "Exception: {}", err.what());
71 }
72 if (mTrkParams[iteration].DropTFUponFailure) {
73 mMemoryPool->print();
74 mTimeFrame->wipe();
75 ++mNumberOfDroppedTFs;
76 error("...Dropping Timeframe...");
77 } else {
78 throw err;
79 }
80 };
81
82 try {
83 for (iteration = 0; iteration < (int)mTrkParams.size(); ++iteration) {
84 mMemoryPool->setMaxMemory(mTrkParams[iteration].MaxMemory);
85 if (iteration == 3 && mTrkParams[0].DoUPCIteration) {
86 mTimeFrame->swapMasks();
87 }
88 double timeTracklets{0.}, timeCells{0.}, timeNeighbours{0.}, timeRoads{0.};
89 int nTracklets{0}, nCells{0}, nNeighbours{0}, nTracks{-static_cast<int>(mTimeFrame->getNumberOfTracks())};
90 int nROFsIterations = (mTrkParams[iteration].nROFsPerIterations > 0 && !mTimeFrame->mIsGPU) ? mTimeFrame->getNrof() / mTrkParams[iteration].nROFsPerIterations + bool(mTimeFrame->getNrof() % mTrkParams[iteration].nROFsPerIterations) : 1;
91 iVertex = std::min(maxNvertices, 0);
92 logger(std::format("==== ITS {} Tracking iteration {} summary ====", mTraits->getName(), iteration));
93
94 total += evaluateTask(&Tracker::initialiseTimeFrame, StateNames[mCurState = TFInit], iteration, logger, iteration);
95 do {
96 for (iROFs = 0; iROFs < nROFsIterations; ++iROFs) {
97 timeTracklets += evaluateTask(&Tracker::computeTracklets, StateNames[mCurState = Trackleting], iteration, evalLog, iteration, iROFs, iVertex);
98 nTracklets += mTraits->getTFNumberOfTracklets();
99 float trackletsPerCluster = mTraits->getTFNumberOfClusters() > 0 ? float(mTraits->getTFNumberOfTracklets()) / float(mTraits->getTFNumberOfClusters()) : 0.f;
100 if (trackletsPerCluster > mTrkParams[iteration].TrackletsPerClusterLimit) {
101 error(std::format("Too many tracklets per cluster ({}) in iteration {} in ROF span {}-{}:, check the detector status and/or the selections. Current limit is {}",
102 trackletsPerCluster, iteration, iROFs, iROFs + mTrkParams[iteration].nROFsPerIterations, mTrkParams[iteration].TrackletsPerClusterLimit));
103 break;
104 }
105 timeCells += evaluateTask(&Tracker::computeCells, StateNames[mCurState = Celling], iteration, evalLog, iteration);
106 nCells += mTraits->getTFNumberOfCells();
107 float cellsPerCluster = mTraits->getTFNumberOfClusters() > 0 ? float(mTraits->getTFNumberOfCells()) / float(mTraits->getTFNumberOfClusters()) : 0.f;
108 if (cellsPerCluster > mTrkParams[iteration].CellsPerClusterLimit) {
109 error(std::format("Too many cells per cluster ({}) in iteration {} in ROF span {}-{}, check the detector status and/or the selections. Current limit is {}",
110 cellsPerCluster, iteration, iROFs, iROFs + mTrkParams[iteration].nROFsPerIterations, mTrkParams[iteration].CellsPerClusterLimit));
111 break;
112 }
113 timeNeighbours += evaluateTask(&Tracker::findCellsNeighbours, StateNames[mCurState = Neighbouring], iteration, evalLog, iteration);
114 nNeighbours += mTimeFrame->getNumberOfNeighbours();
115 timeRoads += evaluateTask(&Tracker::findRoads, StateNames[mCurState = Roading], iteration, evalLog, iteration);
116 }
117 } while (++iVertex < maxNvertices);
118 logger(std::format(" - Tracklet finding: {} tracklets found in {:.2f} ms", nTracklets, timeTracklets));
119 logger(std::format(" - Cell finding: {} cells found in {:.2f} ms", nCells, timeCells));
120 logger(std::format(" - Neighbours finding: {} neighbours found in {:.2f} ms", nNeighbours, timeNeighbours));
121 logger(std::format(" - Track finding: {} tracks found in {:.2f} ms", nTracks + mTimeFrame->getNumberOfTracks(), timeRoads));
122 total += timeTracklets + timeCells + timeNeighbours + timeRoads;
123 if (mTraits->supportsExtendTracks() && mTrkParams[iteration].UseTrackFollower) {
124 int nExtendedTracks{-mTimeFrame->mNExtendedTracks}, nExtendedClusters{-mTimeFrame->mNExtendedUsedClusters};
125 auto timeExtending = evaluateTask(&Tracker::extendTracks, "Extending tracks", iteration, evalLog, iteration);
126 total += timeExtending;
127 logger(std::format(" - Extending Tracks: {} extended tracks using {} clusters found in {:.2f} ms", nExtendedTracks + mTimeFrame->mNExtendedTracks, nExtendedClusters + mTimeFrame->mNExtendedUsedClusters, timeExtending));
128 }
129 if (mTrkParams[iteration].PrintMemory) {
130 mMemoryPool->print();
131 }
132 }
133 if (mTraits->supportsFindShortPrimaries() && mTrkParams[0].FindShortTracks) {
134 auto nTracksB = mTimeFrame->getNumberOfTracks();
135 total += evaluateTask(&Tracker::findShortPrimaries, "Short primaries finding", 0, logger);
136 auto nTracksA = mTimeFrame->getNumberOfTracks();
137 logger(std::format(" `-> found {} additional tracks", nTracksA - nTracksB));
138 }
139 if constexpr (constants::DoTimeBenchmarks) {
140 logger(std::format("=== TimeFrame {} processing completed in: {:.2f} ms using {} thread(s) ===", mTimeFrameCounter, total, mTraits->getNThreads()));
141 }
142 } catch (const BoundedMemoryResource::MemoryLimitExceeded& err) {
143 handleException(err);
144 return;
145 } catch (const std::bad_alloc& err) {
146 handleException(err);
147 return;
148 } catch (...) {
149 error("Uncaught exception, all bets are off...");
150 }
151
152 if (mTimeFrame->hasMCinformation()) {
153 computeTracksMClabels();
154 }
155 rectifyClusterIndices();
156 ++mTimeFrameCounter;
157 mTotalTime += total;
158
159 if (mTrkParams[0].PrintMemory) {
160 mTimeFrame->printArtefactsMemory();
161 mMemoryPool->print();
162 }
163}
164
165template <int nLayers>
167{
169 if (!mTimeFrame->hasMCinformation()) {
170 return;
171 }
172
173 mTimeFrame->initialiseRoadLabels();
174
175 int roadsNum{static_cast<int>(mTimeFrame->getRoads().size())};
176
177 for (int iRoad{0}; iRoad < roadsNum; ++iRoad) {
178
179 auto& currentRoad{mTimeFrame->getRoads()[iRoad]};
180 std::vector<std::pair<MCCompLabel, size_t>> occurrences;
181 bool isFakeRoad{false};
182 bool isFirstRoadCell{true};
183
184 for (int iCell{0}; iCell < mTrkParams[0].CellsPerRoad(); ++iCell) {
185 const int currentCellIndex{currentRoad[iCell]};
186
187 if (currentCellIndex == constants::UnusedIndex) {
188 if (isFirstRoadCell) {
189 continue;
190 } else {
191 break;
192 }
193 }
194
195 const auto& currentCell{mTimeFrame->getCells()[iCell][currentCellIndex]};
196
197 if (isFirstRoadCell) {
198
199 const int cl0index{mTimeFrame->getClusters()[iCell][currentCell.getFirstClusterIndex()].clusterId};
200 auto cl0labs{mTimeFrame->getClusterLabels(iCell, cl0index)};
201 bool found{false};
202 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
203 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
204 for (const auto& label : cl0labs) {
205 if (label == occurrence.first) {
206 ++occurrence.second;
207 found = true;
208 // break; // uncomment to stop to the first hit
209 }
210 }
211 }
212 if (!found) {
213 for (const auto& label : cl0labs) {
214 occurrences.emplace_back(label, 1);
215 }
216 }
217
218 const int cl1index{mTimeFrame->getClusters()[iCell + 1][currentCell.getSecondClusterIndex()].clusterId};
219
220 const auto& cl1labs{mTimeFrame->getClusterLabels(iCell + 1, cl1index)};
221 found = false;
222 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
223 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
224 for (auto& label : cl1labs) {
225 if (label == occurrence.first) {
226 ++occurrence.second;
227 found = true;
228 // break; // uncomment to stop to the first hit
229 }
230 }
231 }
232 if (!found) {
233 for (auto& label : cl1labs) {
234 occurrences.emplace_back(label, 1);
235 }
236 }
237
238 isFirstRoadCell = false;
239 }
240
241 const int cl2index{mTimeFrame->getClusters()[iCell + 2][currentCell.getThirdClusterIndex()].clusterId};
242 const auto& cl2labs{mTimeFrame->getClusterLabels(iCell + 2, cl2index)};
243 bool found{false};
244 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
245 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
246 for (auto& label : cl2labs) {
247 if (label == occurrence.first) {
248 ++occurrence.second;
249 found = true;
250 // break; // uncomment to stop to the first hit
251 }
252 }
253 }
254 if (!found) {
255 for (auto& label : cl2labs) {
256 occurrences.emplace_back(label, 1);
257 }
258 }
259 }
260
261 std::sort(occurrences.begin(), occurrences.end(), [](auto e1, auto e2) {
262 return e1.second > e2.second;
263 });
264
265 auto maxOccurrencesValue = occurrences[0].first;
266 mTimeFrame->setRoadLabel(iRoad, maxOccurrencesValue.getRawValue(), isFakeRoad);
267 }
268}
269
270template <int nLayers>
271void Tracker<nLayers>::computeTracksMClabels()
272{
273 for (int iROF{0}; iROF < mTimeFrame->getNrof(); ++iROF) {
274 for (auto& track : mTimeFrame->getTracks(iROF)) {
275 std::vector<std::pair<MCCompLabel, size_t>> occurrences;
276 occurrences.clear();
277
278 for (int iCluster = 0; iCluster < TrackITSExt::MaxClusters; ++iCluster) {
279 const int index = track.getClusterIndex(iCluster);
280 if (index == constants::UnusedIndex) {
281 continue;
282 }
283 auto labels = mTimeFrame->getClusterLabels(iCluster, index);
284 bool found{false};
285 for (size_t iOcc{0}; iOcc < occurrences.size(); ++iOcc) {
286 std::pair<o2::MCCompLabel, size_t>& occurrence = occurrences[iOcc];
287 for (const auto& label : labels) {
288 if (label == occurrence.first) {
289 ++occurrence.second;
290 found = true;
291 // break; // uncomment to stop to the first hit
292 }
293 }
294 }
295 if (!found) {
296 for (const auto& label : labels) {
297 occurrences.emplace_back(label, 1);
298 }
299 }
300 }
301 std::sort(std::begin(occurrences), std::end(occurrences), [](auto e1, auto e2) {
302 return e1.second > e2.second;
303 });
304
305 auto maxOccurrencesValue = occurrences[0].first;
306 uint32_t pattern = track.getPattern();
307 // set fake clusters pattern
308 for (int ic{TrackITSExt::MaxClusters}; ic--;) {
309 auto clid = track.getClusterIndex(ic);
310 if (clid != constants::UnusedIndex) {
311 auto labelsSpan = mTimeFrame->getClusterLabels(ic, clid);
312 for (const auto& currentLabel : labelsSpan) {
313 if (currentLabel == maxOccurrencesValue) {
314 pattern |= 0x1 << (16 + ic); // set bit if correct
315 break;
316 }
317 }
318 }
319 }
320 track.setPattern(pattern);
321 if (occurrences[0].second < track.getNumberOfClusters()) {
322 maxOccurrencesValue.setFakeFlag();
323 }
324 mTimeFrame->getTracksLabel(iROF).emplace_back(maxOccurrencesValue);
325 }
326 }
327}
328
329template <int nLayers>
330void Tracker<nLayers>::rectifyClusterIndices()
331{
332 for (int iROF{0}; iROF < mTimeFrame->getNrof(); ++iROF) {
333 for (auto& track : mTimeFrame->getTracks(iROF)) {
334 for (int iCluster = 0; iCluster < TrackITSExt::MaxClusters; ++iCluster) {
335 const int index = track.getClusterIndex(iCluster);
336 if (index != constants::UnusedIndex) {
337 track.setExternalClusterIndex(iCluster, mTimeFrame->getClusterExternalIndex(iCluster, index));
338 }
339 }
340 }
341 }
342}
343
344template <int nLayers>
346{
347 mTimeFrame = &tf;
348 mTraits->adoptTimeFrame(&tf);
349}
350
351template <int nLayers>
353{
354 auto avgTF = mTotalTime * 1.e-3 / ((mTimeFrameCounter > 0) ? (double)mTimeFrameCounter : -1.0);
355 auto avgTFwithDropped = mTotalTime * 1.e-3 / (((mTimeFrameCounter + mNumberOfDroppedTFs) > 0) ? (double)(mTimeFrameCounter + mNumberOfDroppedTFs) : -1.0);
356 LOGP(info, "Tracker summary: Processed {} TFs (dropped {}) in TOT={:.2f} s, AVG/TF={:.2f} ({:.2f}) s", mTimeFrameCounter, mNumberOfDroppedTFs, mTotalTime * 1.e-3, avgTF, avgTFwithDropped);
357}
358
359template class Tracker<7>;
360
361} // 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:352
void adoptTimeFrame(TimeFrame< nLayers > &tf)
Definition Tracker.cxx:345
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