Project
Loading...
Searching...
No Matches
TrackerACTS.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.
11
38
40
43#include "MathUtils/Utils.h"
45
46#include <Acts/Geometry/TrackingGeometry.hpp>
47#include <Acts/Geometry/TrackingVolume.hpp>
48#include <Acts/Geometry/VolumeBounds.hpp>
49#include <Acts/Definitions/Direction.hpp>
50#include <Acts/Definitions/TrackParametrization.hpp>
51#include <Acts/EventData/BoundTrackParameters.hpp>
52#include <Acts/EventData/ParticleHypothesis.hpp>
53#include <Acts/EventData/SeedContainer.hpp>
54#include <Acts/EventData/SourceLink.hpp>
55#include <Acts/EventData/SpacePointContainer.hpp>
56#include <Acts/EventData/TrackContainer.hpp>
57#include <Acts/EventData/VectorMultiTrajectory.hpp>
58#include <Acts/EventData/VectorTrackContainer.hpp>
59#include <Acts/MagneticField/MagneticFieldContext.hpp>
60#include <Acts/Propagator/DirectNavigator.hpp>
61#include <Acts/Propagator/EigenStepper.hpp>
62#include <Acts/Propagator/Propagator.hpp>
63#include <Acts/Seeding/BroadTripletSeedFilter.hpp>
64#include <Acts/Seeding/CylindricalSpacePointGrid.hpp>
65#include <Acts/Seeding/DoubletSeedFinder.hpp>
66#include <Acts/Seeding/EstimateTrackParamsFromSeed.hpp>
67#include <Acts/Seeding/TripletSeedFinder.hpp>
68#include <Acts/Seeding/TripletSeeder.hpp>
69#include <Acts/Surfaces/Surface.hpp>
70#include <Acts/TrackFitting/GainMatrixSmoother.hpp>
71#include <Acts/TrackFitting/GainMatrixUpdater.hpp>
72#include <Acts/TrackFitting/KalmanFitter.hpp>
73#include <Acts/Utilities/CalibrationContext.hpp>
74#include <Acts/Utilities/GridBinFinder.hpp>
75
77
78#include <TFile.h>
79#include <TTree.h>
80#include <nlohmann/json.hpp>
81#include <algorithm>
82#include <array>
83#include <cmath>
84#include <cstdint>
85#include <fstream>
86#include <limits>
87#include <optional>
88#include <memory>
89#include <span>
90#include <stdexcept>
91#include <string>
92#include <utility>
93#include <vector>
94
95namespace o2::trk
96{
97
98namespace
99{
108bool convertTrackParameters(const Acts::BoundTrackParameters& actsTrack,
109 const Acts::GeometryContext& gctx,
111{
112 const auto& state = actsTrack.parameters();
113 if (!state.allFinite() || !actsTrack.covariance().has_value() || !actsTrack.covariance()->allFinite()) {
114 return false;
115 }
116
117 const auto position = actsTrack.position(gctx);
118 if (!position.allFinite()) {
119 return false;
120 }
121 const double alpha = std::atan2(position.y(), position.x());
122 const double ca = std::cos(alpha);
123 const double sa = std::sin(alpha);
124
125 auto toO2 = [&](const Acts::BoundVector& p, Eigen::Matrix<double, 5, 1>& dest) -> bool {
126 const double theta = p[Acts::eBoundTheta];
127 const double sinTheta = std::sin(theta);
128 if (!std::isfinite(sinTheta) || sinTheta <= 1.e-6) {
129 return false;
130 }
131 const auto direction = Acts::makeDirectionFromPhiTheta(p[Acts::eBoundPhi], theta);
132 const Acts::Vector2 local = p.head<2>();
133 const auto xyz = actsTrack.referenceSurface().localToGlobal(gctx, local, direction);
134 if (!xyz.allFinite()) {
135 return false;
136 }
137
138 const double snp = std::sin(p[Acts::eBoundPhi] - alpha);
139 if (!std::isfinite(snp) || std::abs(snp) >= 0.999999) {
140 return false;
141 }
142
143 dest << (-xyz.x() * sa + xyz.y() * ca) / Acts::UnitConstants::cm,
144 xyz.z() / Acts::UnitConstants::cm,
145 snp,
146 std::cos(theta) / sinTheta,
147 p[Acts::eBoundQOverP] * Acts::UnitConstants::GeV / sinTheta;
148 return dest.allFinite();
149 };
150
151 Eigen::Matrix<double, 5, 1> pars;
152 if (!toO2(state, pars)) {
153 return false;
154 }
155
156 const double x = (position.x() * ca + position.y() * sa) / Acts::UnitConstants::cm;
157 if (!std::isfinite(x)) {
158 return false;
159 }
160
161 Eigen::Matrix<double, 5, Acts::eBoundSize> jacobian;
162 jacobian.setZero();
163 for (int i = 0; i < Acts::eBoundSize; ++i) {
164 if (i == Acts::eBoundTime) {
165 continue; // O2 TrackParCov has no time coordinate
166 }
167 const double step = (i == Acts::eBoundLoc0 || i == Acts::eBoundLoc1)
168 ? 1.e-3 * Acts::UnitConstants::mm
169 : (i == Acts::eBoundQOverP)
170 ? std::max(std::abs(state[i]) * 1.e-4, 1.e-6 / Acts::UnitConstants::GeV)
171 : 1.e-5;
172 Acts::BoundVector plus = state;
173 Acts::BoundVector minus = state;
174 plus[i] += step;
175 minus[i] -= step;
176 Eigen::Matrix<double, 5, 1> fPlus, fMinus;
177 if (!toO2(plus, fPlus) || !toO2(minus, fMinus)) {
178 return false;
179 }
180 jacobian.col(i) = (fPlus - fMinus) / (2. * step);
181 }
182
183 const Eigen::Matrix<double, 5, 5> covariance = jacobian * (*actsTrack.covariance()) * jacobian.transpose();
184 if (!covariance.allFinite()) {
185 return false;
186 }
187
188 o2::track::TrackParCov::params_t o2Params{};
189 o2::track::TrackParCov::covMat_t o2Cov{};
190 for (int i = 0; i < 5; ++i) {
191 if (!(covariance(i, i) > 0.) || !std::isfinite(pars[i])) {
192 return false;
193 }
194 o2Params[i] = static_cast<float>(pars[i]);
195 for (int j = 0; j <= i; ++j) {
196 o2Cov[o2::track::CovarMap[i][j]] = static_cast<float>(0.5 * (covariance(i, j) + covariance(j, i)));
197 }
198 }
199 const int charge = state[Acts::eBoundQOverP] >= 0. ? 1 : -1;
200 output = o2::track::TrackParCov{static_cast<float>(x), static_cast<float>(alpha),
201 o2Params, o2Cov, charge, o2::track::PID::Pion};
202 return output.isValid();
203}
204} // namespace
205template <int nLayers>
207{
208 // Initialize space points storage per layer
209 mSpacePointsPerLayer.resize(nLayers);
210 // The debug file and histogram are intentionally not allocated here.
211}
212
213template <int nLayers>
215{
216 if (mDebugFile) {
217 mDebugFile->cd();
218 if (mHistSpacePoints) {
219 mHistSpacePoints->Write("", TObject::kOverwrite);
220 }
221 mDebugFile->Write("", TObject::kOverwrite);
222 mDebugFile->Close();
223 }
224}
225
226template <int nLayers>
228{
229 // A negative limit means unlimited debug output; zero disables it.
230 return mDebugFile && (mConfig.debugMaxTimeFrames < 0 ||
231 mTimeFrameCounter < static_cast<unsigned int>(mConfig.debugMaxTimeFrames));
232}
233
234template <int nLayers>
235void TrackerACTS<nLayers>::initDebugOutput()
236{
237 if (!mConfig.writeDebugTrees || mDebugFile || mConfig.debugMaxTimeFrames == 0) {
238 return;
239 }
240 mDebugFile.reset(TFile::Open(mConfig.debugFileName.c_str(), "RECREATE"));
241 if (!mDebugFile || mDebugFile->IsZombie()) {
242 LOG(error) << "Cannot create ACTS debug ROOT file " << mConfig.debugFileName;
243 mDebugFile.reset();
244 return;
245 }
246 mDebugFile->cd();
247 // The tree branches point into these member records, which are refilled for
248 // each entry. The file owns the trees; the tracker owns the histogram.
249 mClusterTree = new TTree("clusters", "ACTS input clusters and surface mapping; positions in cm; variances in ACTS units");
250 mClusterTree->Branch("tf", &mDebugCluster.tf, "tf/I");
251 mClusterTree->Branch("rof", &mDebugCluster.rof, "rof/I");
252 mClusterTree->Branch("layer", &mDebugCluster.layer, "layer/I");
253 mClusterTree->Branch("clusterId", &mDebugCluster.clusterId, "clusterId/I");
254 mClusterTree->Branch("externalId", &mDebugCluster.externalId, "externalId/I");
255 mClusterTree->Branch("sensorId", &mDebugCluster.sensorId, "sensorId/I");
256 mClusterTree->Branch("mappingStatus", &mDebugCluster.mappingStatus, "mappingStatus/I");
257 mClusterTree->Branch("geometryId", &mDebugCluster.geometryId, "geometryId/l");
258 mClusterTree->Branch("x", &mDebugCluster.x, "x/F");
259 mClusterTree->Branch("y", &mDebugCluster.y, "y/F");
260 mClusterTree->Branch("z", &mDebugCluster.z, "z/F");
261 mClusterTree->Branch("r", &mDebugCluster.r, "r/F");
262 mClusterTree->Branch("phi", &mDebugCluster.phi, "phi/F");
263 mClusterTree->Branch("varianceR", &mDebugCluster.varianceR, "varianceR/F");
264 mClusterTree->Branch("varianceZ", &mDebugCluster.varianceZ, "varianceZ/F");
265
266 mSeedTree = new TTree("seeds", "ACTS output seed triplets; positions in cm; bottom/middle/top order");
267 mSeedTree->Branch("tf", &mDebugSeed.tf, "tf/I");
268 mSeedTree->Branch("rof", &mDebugSeed.rof, "rof/I");
269 mSeedTree->Branch("seedId", &mDebugSeed.seedId, "seedId/I");
270 mSeedTree->Branch("quality", &mDebugSeed.quality, "quality/F");
271 mSeedTree->Branch("layer", mDebugSeed.layer, "layer[3]/I");
272 mSeedTree->Branch("clusterId", mDebugSeed.clusterId, "clusterId[3]/I");
273 mSeedTree->Branch("sensorId", mDebugSeed.sensorId, "sensorId[3]/I");
274 mSeedTree->Branch("geometryId", mDebugSeed.geometryId, "geometryId[3]/l");
275 mSeedTree->Branch("x", mDebugSeed.x, "x[3]/F");
276 mSeedTree->Branch("y", mDebugSeed.y, "y[3]/F");
277 mSeedTree->Branch("z", mDebugSeed.z, "z[3]/F");
278 mSeedTree->Branch("r", mDebugSeed.r, "r[3]/F");
279 mSeedTree->Branch("phi", mDebugSeed.phi, "phi[3]/F");
280
281 mROFTree = new TTree("rofSummary", "ACTS reconstruction counts per time frame and ROF");
282 mROFTree->Branch("tf", &mDebugROF.tf, "tf/I");
283 mROFTree->Branch("rof", &mDebugROF.rof, "rof/I");
284 mROFTree->Branch("nSpacePoints", &mDebugROF.nSpacePoints, "nSpacePoints/I");
285 mROFTree->Branch("nSeeds", &mDebugROF.nSeeds, "nSeeds/I");
286 mROFTree->Branch("nAcceptedTracks", &mDebugROF.nAcceptedTracks, "nAcceptedTracks/I");
287
288 mHistSpacePoints = std::make_unique<TH2F>("hSpacePoints", "Space points; x (cm); y (cm)",
289 200, -100, 100, 200, -100, 100);
290 mHistSpacePoints->SetDirectory(nullptr); // Owned by TrackerACTS, not by TFile.
291 LOG(info) << "ACTS debug trees enabled: " << mConfig.debugFileName;
292}
293
294template <int nLayers>
295void TrackerACTS<nLayers>::dumpGeometryOnce()
296{
297 if (!mConfig.dumpTrackingGeometry || mGeometryDumped) {
298 return;
299 }
300 mGeometryDumped = true; // Even on I/O failure, do not retry on every TF.
302 // get() builds the shared geometry on first access if necessary. Its
303 // nominal context is appropriate because O2 alignment was already applied
304 // to the TGeo matrices from which this ACTS geometry was built.
305 const auto& geometry = manager.get();
306 const auto& gctx = manager.getNominalContext();
307 auto* trkGeometry = o2::trk::GeometryTGeo::Instance();
308 // Build/reuse the sensor-to-surface map. The matrix cache is populated in
309 // clustersToTracks(); the path provider makes matching use the TGeo sensor
310 // path as an identity instead of relying only on transform proximity.
311 const auto& surfaceIndex = manager.getIndex(*trkGeometry, 1.e-3, [trkGeometry](int sensorID) {
312 return std::string(trkGeometry->getMatrixPath(sensorID).Data());
313 });
314
315 std::ofstream out(mConfig.geometryDumpFileName);
316 if (!out) {
317 LOG(error) << "Cannot open ACTS geometry dump: " << mConfig.geometryDumpFileName;
318 return;
319 }
320 out << "{\n \"description\": \"ACTS volumes and sensitive surfaces snapshot, not a complete ACTS geometry serialization\",\n"
321 " \"lengthUnits\": \"mm (angles in rad)\",\n \"volumes\": [\n";
322 bool first = true;
323 int nVolumes = 0;
324 // ACTS visitor callbacks receive non-owning pointers. The snapshot records
325 // global transforms in the nominal context and basic bounds/material
326 // metadata; it is intended for inspection, not for rebuilding the geometry.
327 geometry.visitVolumes([&](const Acts::TrackingVolume* volume) {
328 if (volume == nullptr) {
329 return;
330 }
331 const auto& transform = volume->localToGlobalTransform(gctx);
332 nlohmann::json item;
333 item["geometryId"] = volume->geometryId().value();
334 item["motherGeometryId"] = volume->motherVolume() ? volume->motherVolume()->geometryId().value() : 0;
335 item["name"] = volume->volumeName();
336 item["boundsType"] = static_cast<int>(volume->volumeBounds().type());
337 item["boundsValues"] = volume->volumeBounds().values();
338 item["hasMaterial"] = volume->volumeMaterial() != nullptr;
339 item["translation"] = {transform.translation().x(), transform.translation().y(), transform.translation().z()};
340 item["rotation"] = nlohmann::json::array();
341 for (int row = 0; row < 3; ++row) {
342 item["rotation"].push_back({transform.rotation()(row, 0), transform.rotation()(row, 1), transform.rotation()(row, 2)});
343 }
344 if (!first) {
345 out << ",\n";
346 }
347 out << item.dump();
348 first = false;
349 ++nVolumes;
350 });
351 out << "\n ],\n \"surfaces\": [\n";
352 first = true;
353 int nSurfaces = 0;
354 // The one-argument TrackingGeometry visitor visits sensitive surfaces.
355 // Associate each geometry identifier with the O2 sensor IDs known to the
356 // detector-specific index; a surface can have no matching sensor ID.
357 geometry.visitSurfaces([&](const Acts::Surface* surface) {
358 if (surface == nullptr) {
359 return;
360 }
361 const auto& transform = surface->localToGlobalTransform(gctx);
362 nlohmann::json item;
363 item["geometryId"] = surface->geometryId().value();
364 item["surfaceType"] = static_cast<int>(surface->type());
365 item["boundsType"] = static_cast<int>(surface->bounds().type());
366 item["boundsValues"] = surface->bounds().values();
367 item["hasMaterial"] = surface->hasMaterial();
368 item["translation"] = {transform.translation().x(), transform.translation().y(), transform.translation().z()};
369 item["rotation"] = nlohmann::json::array();
370 for (int row = 0; row < 3; ++row) {
371 item["rotation"].push_back({transform.rotation()(row, 0), transform.rotation()(row, 1), transform.rotation()(row, 2)});
372 }
373 item["sensorIds"] = surfaceIndex.getSensorIDs(surface->geometryId());
374 if (!first) {
375 out << ",\n";
376 }
377 out << item.dump();
378 first = false;
379 ++nSurfaces;
380 });
381 out << "\n ]\n}\n";
382 if (!out.good()) {
383 LOG(error) << "Error while writing ACTS geometry dump " << mConfig.geometryDumpFileName;
384 return;
385 }
386 LOG(info) << "ACTS tracking geometry snapshot: " << nVolumes << " volumes and "
387 << nSurfaces << " surfaces written to " << mConfig.geometryDumpFileName;
388}
389
390template <int nLayers>
391void TrackerACTS<nLayers>::fillDebugSeeds(int rof)
392{
393 if (!isDebugTimeFrame()) {
394 return;
395 }
396 for (size_t iSeed = 0; iSeed < mSeeds.size(); ++iSeed) {
397 const auto& seed = mSeeds[iSeed];
398 mDebugSeed = {};
399 mDebugSeed.tf = static_cast<int>(mTimeFrameCounter);
400 mDebugSeed.rof = rof;
401 mDebugSeed.seedId = static_cast<int>(iSeed);
402 mDebugSeed.quality = seed.quality;
403 const std::array<const SpacePoint*, 3> points{seed.bottom, seed.middle, seed.top};
404 // Keep the output order consistent with the seeder and seed-triplet
405 // convention: innermost (bottom), middle, then outermost (top).
406 for (int i = 0; i < 3; ++i) {
407 const auto& sp = *points[i];
408 mDebugSeed.layer[i] = sp.layer;
409 mDebugSeed.clusterId[i] = sp.clusterId;
410 mDebugSeed.sensorId[i] = sp.sensorId;
411 mDebugSeed.geometryId[i] = sp.surface ? sp.surface->geometryId().value() : 0;
412 mDebugSeed.x[i] = sp.x / Acts::UnitConstants::cm;
413 mDebugSeed.y[i] = sp.y / Acts::UnitConstants::cm;
414 mDebugSeed.z[i] = sp.z / Acts::UnitConstants::cm;
415 mDebugSeed.r[i] = sp.r() / Acts::UnitConstants::cm;
416 mDebugSeed.phi[i] = sp.phi();
417 }
418 mSeedTree->Fill();
419 }
420}
421
422template <int nLayers>
424{
425 // Borrow the TimeFrame; its lifetime must cover all calls that use it.
426 mTimeFrame = &tf;
427}
428
429template <int nLayers>
431{
432 mSpacePoints.clear();
433 for (auto& layerSPs : mSpacePointsPerLayer) {
434 layerSPs.clear();
435 }
436
437 if (!mSensorIDs) {
438 LOG(error) << "Cannot build ACTS space points: Sensor IDs not adopted";
439 return;
440 }
441
442 auto& actsGeometryManager = o2::acts::TrackingGeometryManager::instance();
443 auto* trkGeometry = o2::trk::GeometryTGeo::Instance();
444
445 // Surface matching needs global-to-local transforms from O2's geometry
446 // helper. Build its L2G cache before requesting the manager's detector index.
447 trkGeometry->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::L2G));
448
449 // mSensorIDs is parallel to each layer's cluster ordering. Its sensor ID
450 // selects the corresponding ACTS surface; missing IDs or surfaces cannot be
451 // used by seeding/fitting and are skipped below.
452 const auto& surfaceIndex = actsGeometryManager.getIndex(*trkGeometry, 1.e-3, [trkGeometry](int sensorID) {
453 return std::string(trkGeometry->getMatrixPath(sensorID).Data());
454 });
455
456 int nMapped = 0;
457 int nMissing = 0;
458
459 for (int layer = 0; layer < nLayers; ++layer) {
460 const auto clusters = mTimeFrame->getUnsortedClustersOnLayer(rof, layer);
461 const int firstCluster = mTimeFrame->getSortedStartIndex(rof, layer);
462
463 LOG(debug) << "ACTSTracker: got " << clusters.size() << " clusters on layer " << layer;
464
465 for (size_t iCluster = 0; iCluster < clusters.size(); ++iCluster) {
466 const auto& cluster = clusters[iCluster];
467 const int clusterIndex = firstCluster + static_cast<int>(iCluster);
468
469 const bool hasSensorID = clusterIndex >= 0 && static_cast<size_t>(clusterIndex) < (*mSensorIDs)[layer].size();
470 const int sensorID = hasSensorID ? (*mSensorIDs)[layer][clusterIndex] : -1;
471 const auto* surface = hasSensorID ? surfaceIndex.getSurface(sensorID) : nullptr;
472 if (isDebugTimeFrame()) {
473 mDebugCluster = {};
474 mDebugCluster.tf = static_cast<int>(mTimeFrameCounter);
475 mDebugCluster.rof = rof;
476 mDebugCluster.layer = layer;
477 mDebugCluster.clusterId = clusterIndex;
478 mDebugCluster.externalId = mTimeFrame->getClusterExternalIndex(layer, clusterIndex);
479 mDebugCluster.sensorId = sensorID;
480 // 0: sensor ID missing; 1: ACTS surface missing; 2: mapped.
481 mDebugCluster.mappingStatus = !hasSensorID ? 0 : !surface ? 1
482 : 2;
483 mDebugCluster.geometryId = surface ? surface->geometryId().value() : 0;
484 mDebugCluster.x = cluster.xCoordinate;
485 mDebugCluster.y = cluster.yCoordinate;
486 mDebugCluster.z = cluster.zCoordinate;
487 mDebugCluster.r = std::hypot(mDebugCluster.x, mDebugCluster.y);
488 mDebugCluster.phi = std::atan2(mDebugCluster.y, mDebugCluster.x);
489 mDebugCluster.varianceR = 0.01f;
490 mDebugCluster.varianceZ = 0.01f;
491 mClusterTree->Fill();
492 }
493 if (!hasSensorID) {
494 LOG(error) << "Missing sensor ID for layer " << layer << " cluster " << clusterIndex;
495 ++nMissing;
496 continue;
497 }
498
499 if (!surface) {
500 LOG(error) << "No ACTS surface for sensor " << sensorID << " on layer " << layer;
501 ++nMissing;
502 continue;
503 }
504
505 SpacePoint sp;
506 // SpacePoint and all subsequent ACTS calculations use mm, while the
507 // TimeFrame cluster coordinates are stored in cm.
508 sp.x = cluster.xCoordinate * Acts::UnitConstants::cm;
509 sp.y = cluster.yCoordinate * Acts::UnitConstants::cm;
510 sp.z = cluster.zCoordinate * Acts::UnitConstants::cm;
511
512 if (mHistSpacePoints) {
513 mHistSpacePoints->Fill(sp.x / Acts::UnitConstants::cm, sp.y / Acts::UnitConstants::cm);
514 }
515
516 sp.layer = layer;
517 sp.clusterId = clusterIndex;
518 sp.rof = rof;
519 sp.sensorId = sensorID;
520 sp.surface = surface;
521 sp.varianceR = 0.01f;
522 sp.varianceZ = 0.01f;
523
524 mSpacePoints.push_back(sp);
525 ++nMapped;
526 }
527 }
528
529 for (auto& sp : mSpacePoints) {
530 if (sp.layer >= 0 && sp.layer < nLayers) {
531 mSpacePointsPerLayer[sp.layer].push_back(&sp);
532 }
533 }
534
535 LOG(info) << "ACTS surface mapping: " << nMapped << " clusters mapped, " << nMissing << " clusters missing";
536}
537
538template <int nLayers>
539void TrackerACTS<nLayers>::createSeeds()
540{
541 mSeeds.clear();
542 if (mSpacePoints.empty()) {
543 LOG(info) << "No space points available for seeding";
544 return;
545 }
546
547 o2::acts::MagneticFieldAdapter magneticField;
548 Acts::MagneticFieldContext magneticFieldContext;
549 auto magneticFieldCache = magneticField.makeCache(magneticFieldContext);
550 const auto fieldAtOrigin = magneticField.getField(Acts::Vector3::Zero(), magneticFieldCache);
551 if (!fieldAtOrigin.ok()) {
552 throw std::runtime_error("Failed to query the O2 magnetic field for ACTS seeding");
553 }
554 const float bFieldInZ = fieldAtOrigin.value().z();
555
556 // ACTS seeding consumes cylindrical (phi, z, r) bins in ACTS units. The
557 // bins are populated from the owned space-point vector, whose indices are
558 // retained so ACTS seeds can be translated back to SpacePoint pointers.
559 Acts::CylindricalSpacePointGrid::Config gridConfig;
560 gridConfig.minPt = mConfig.minPt;
561 gridConfig.rMin = 0.f;
562 gridConfig.rMax = 100.f * Acts::UnitConstants::cm;
563 gridConfig.zMin = mConfig.zMin;
564 gridConfig.zMax = mConfig.zMax;
565 gridConfig.deltaRMax = std::max(mConfig.deltaRMaxBottom, mConfig.deltaRMaxTop);
566 gridConfig.cotThetaMax = mConfig.cotThetaMax;
567 gridConfig.impactMax = mConfig.maxImpactParameter;
568 gridConfig.bFieldInZ = bFieldInZ;
569 gridConfig.bottomBinFinder = Acts::GridBinFinder<3ul>{1, std::vector<std::pair<int, int>>{}, 0};
570 gridConfig.topBinFinder = Acts::GridBinFinder<3ul>{1, std::vector<std::pair<int, int>>{}, 0};
571
572 Acts::CylindricalSpacePointGrid grid{gridConfig};
573 for (Acts::SpacePointIndex i = 0; i < mSpacePoints.size(); ++i) {
574 const auto& sp = mSpacePoints[i];
575 grid.insert(i, sp.phi(), sp.z, sp.r());
576 }
577
578 // The doublet finder expects each bin to be sorted in increasing radius.
579 for (size_t i = 0; i < grid.numberOfBins(); ++i) {
580 auto& bin = grid.at(i);
581 std::sort(bin.begin(), bin.end(), [this](Acts::SpacePointIndex a, Acts::SpacePointIndex b) {
582 return mSpacePoints[a].r() < mSpacePoints[b].r();
583 });
584 }
585
586 // ACTS 47 uses a non-templated, column-based space-point container.
587 Acts::SpacePointContainer spacePoints{Acts::SpacePointColumns::CopiedFromIndex |
588 Acts::SpacePointColumns::PackedXY |
589 Acts::SpacePointColumns::PackedZR |
590 Acts::SpacePointColumns::VarianceR |
591 Acts::SpacePointColumns::VarianceZ};
592 spacePoints.reserve(grid.numberOfSpacePoints());
593
594 std::vector<Acts::SpacePointIndexRange> gridRanges;
595 gridRanges.reserve(grid.numberOfBins());
596 for (size_t i = 0; i < grid.numberOfBins(); ++i) {
597 const auto first = static_cast<Acts::SpacePointIndex>(spacePoints.size());
598 for (Acts::SpacePointIndex spIndex : grid.at(i)) {
599 const auto& sp = mSpacePoints[spIndex];
600 auto proxy = spacePoints.createSpacePoint();
601 proxy.copiedFromIndex() = spIndex;
602 proxy.xy() = std::array<float, 2>{sp.x, sp.y};
603 proxy.zr() = std::array<float, 2>{sp.z, sp.r()};
604 proxy.varianceR() = sp.varianceR;
605 proxy.varianceZ() = sp.varianceZ;
606 }
607 const auto last = static_cast<Acts::SpacePointIndex>(spacePoints.size());
608 gridRanges.emplace_back(first, last);
609 }
610
611 Acts::DoubletSeedFinder::Config bottomConfig;
612 bottomConfig.spacePointsSortedByRadius = true;
613 bottomConfig.candidateDirection = Acts::Direction::Backward();
614 bottomConfig.deltaRMin = mConfig.deltaRMinBottom;
615 bottomConfig.deltaRMax = mConfig.deltaRMaxBottom;
616 bottomConfig.collisionRegionMin = mConfig.collisionRegionMin;
617 bottomConfig.collisionRegionMax = mConfig.collisionRegionMax;
618 bottomConfig.cotThetaMax = mConfig.cotThetaMax;
619 bottomConfig.impactMax = mConfig.maxImpactParameter;
620 bottomConfig.minPt = mConfig.minPt;
621 auto bottomFinder = Acts::DoubletSeedFinder::create(Acts::DoubletSeedFinder::DerivedConfig{bottomConfig, bFieldInZ});
622
623 Acts::DoubletSeedFinder::Config topConfig = bottomConfig;
624 topConfig.candidateDirection = Acts::Direction::Forward();
625 topConfig.deltaRMin = mConfig.deltaRMinTop;
626 topConfig.deltaRMax = mConfig.deltaRMaxTop;
627 auto topFinder = Acts::DoubletSeedFinder::create(Acts::DoubletSeedFinder::DerivedConfig{topConfig, bFieldInZ});
628
629 Acts::TripletSeedFinder::Config tripletConfig;
630 tripletConfig.minPt = mConfig.minPt;
631 tripletConfig.impactMax = mConfig.maxImpactParameter;
632 tripletConfig.sigmaScattering = 5.f;
633 tripletConfig.radLengthPerSeed = 0.05f;
634 auto tripletFinder = Acts::TripletSeedFinder::create(Acts::TripletSeedFinder::DerivedConfig{tripletConfig, bFieldInZ});
635
636 Acts::BroadTripletSeedFilter::Config filterConfig;
637 filterConfig.maxSeedsPerSpM = static_cast<unsigned int>(mConfig.maxSeedsPerMiddleSP);
638 filterConfig.deltaRMin = std::min(mConfig.deltaRMinBottom, mConfig.deltaRMinTop);
639 Acts::BroadTripletSeedFilter::State filterState;
640 Acts::BroadTripletSeedFilter::Cache filterCache;
641 Acts::BroadTripletSeedFilter filter{filterConfig, filterState, filterCache, Acts::getDummyLogger()};
642
643 Acts::TripletSeeder seeder;
644 Acts::TripletSeeder::Cache seedingCache;
645 Acts::SeedContainer seeds;
646 seeds.assignSpacePointContainer(spacePoints);
647
648 std::vector<Acts::SpacePointContainer::ConstRange> bottomRanges;
649 std::vector<Acts::SpacePointContainer::ConstRange> topRanges;
650 for (const auto [bottom, middle, top] : grid.binnedGroup()) {
651 bottomRanges.clear();
652 for (const auto bin : bottom) {
653 bottomRanges.push_back(spacePoints.range(gridRanges.at(bin)).asConst());
654 }
655 topRanges.clear();
656 for (const auto bin : top) {
657 topRanges.push_back(spacePoints.range(gridRanges.at(bin)).asConst());
658 }
659 auto middleRange = spacePoints.range(gridRanges.at(middle)).asConst();
660 if (middleRange.empty()) {
661 continue;
662 }
663
664 seeder.createSeedsFromGroups(seedingCache, *bottomFinder, *topFinder,
665 *tripletFinder, filter, spacePoints,
666 bottomRanges, middleRange, topRanges,
667 {gridConfig.rMin, gridConfig.rMax}, seeds);
668 }
669
670 // Restore the existing SeedACTS representation using original SP indices.
671 mSeeds.reserve(seeds.size());
672 for (const auto seed : seeds) {
673 const auto indices = seed.spacePointIndices();
674 SeedACTS output;
675 output.bottom = &mSpacePoints[spacePoints.at(indices[0]).copiedFromIndex()];
676 output.middle = &mSpacePoints[spacePoints.at(indices[1]).copiedFromIndex()];
677 output.top = &mSpacePoints[spacePoints.at(indices[2]).copiedFromIndex()];
678 output.quality = seed.quality();
679 mSeeds.push_back(output);
680 }
681 fillDebugSeeds(mSpacePoints.front().rof);
682
683 LOGF(debug, "Created %zu seeds from %zu space points", mSeeds.size(), mSpacePoints.size());
684}
685
686template <int nLayers>
687void TrackerACTS<nLayers>::findTracks()
688{
689 if (mSeeds.empty()) {
690 return;
691 }
692
693 auto& actsGeometryManager = o2::acts::TrackingGeometryManager::instance();
694 // The same nominal context used to construct/map the geometry must be used
695 // for surface transforms and propagation.
696 const auto& geometryContext = actsGeometryManager.getNominalContext();
697
698 Acts::MagneticFieldContext magneticFieldContext;
699 Acts::CalibrationContext calibrationContext;
700
701 auto magneticField = std::make_shared<o2::acts::MagneticFieldAdapter>();
702 auto magneticFieldCache = magneticField->makeCache(magneticFieldContext);
703
704 using Propagator = Acts::Propagator<Acts::EigenStepper<>, Acts::DirectNavigator>;
705 using Trajectory = Acts::VectorMultiTrajectory;
706 using TrackContainer = Acts::TrackContainer<Acts::VectorTrackContainer, Trajectory>;
707
708 Propagator propagator{Acts::EigenStepper<>{magneticField}, Acts::DirectNavigator{}};
709
710 Acts::KalmanFitter<Propagator, Trajectory> fitter{std::move(propagator)};
711
712 struct HitMeasurement {
713 const Acts::Surface* surface{nullptr};
714 Acts::Vector2 local = Acts::Vector2::Zero();
715 Acts::SquareMatrix<2> covariance = Acts::SquareMatrix<2>::Zero();
716 };
717
718 struct HitSourceLink {
719 const HitMeasurement* hit{nullptr};
720 };
721
722 struct SurfaceAccessor {
723 const Acts::Surface* getSurface(const Acts::SourceLink& sourceLink) const
724 {
725 return sourceLink.get<HitSourceLink>().hit->surface;
726 }
727 };
728
729 struct MeasurementCalibrator {
730 void calibrate(const Acts::GeometryContext&,
731 const Acts::CalibrationContext&,
732 const Acts::SourceLink& sourceLink,
733 Trajectory::TrackStateProxy trackState) const
734 {
735 const auto& hit = *sourceLink.get<HitSourceLink>().hit;
736
737 // The hit was converted to this ACTS surface's local coordinates before
738 // fitting. Calibrate only the two measured local position coordinates.
739 trackState.setUncalibratedSourceLink(Acts::SourceLink{sourceLink});
740 trackState.allocateCalibrated(2);
741 trackState.calibrated<2>() = hit.local;
742 trackState.calibratedCovariance<2>() = hit.covariance;
743
744 trackState.setProjectorSubspaceIndices(std::array<std::uint8_t, 2>{static_cast<std::uint8_t>(Acts::eBoundLoc0),
745 static_cast<std::uint8_t>(Acts::eBoundLoc1)});
746 }
747 };
748
749 SurfaceAccessor surfaceAccessor;
750 MeasurementCalibrator calibrator;
751 Acts::GainMatrixUpdater updater;
752 Acts::GainMatrixSmoother smoother;
753
754 Acts::KalmanFitterExtensions<Trajectory> extensions;
755 extensions.surfaceAccessor.connect<&SurfaceAccessor::getSurface>(&surfaceAccessor);
756 extensions.calibrator.connect<&MeasurementCalibrator::calibrate>(&calibrator);
757 extensions.updater.connect<&Acts::GainMatrixUpdater::operator()<Trajectory>>(&updater);
758 extensions.smoother.connect<&Acts::GainMatrixSmoother::operator()<Trajectory>>(&smoother);
759
760 Acts::PropagatorPlainOptions propagatorOptions{geometryContext, magneticFieldContext};
761
762 Acts::KalmanFitterOptions<Trajectory> fitterOptions{geometryContext,
763 magneticFieldContext,
764 calibrationContext,
765 extensions,
766 propagatorOptions,
767 nullptr,
768 false,
769 false};
770
771 // Mutable TrackContainer uses reference-holder backends, not rvalue shared_ptrs.
772 Acts::VectorTrackContainer trackBackend;
773 Trajectory trajectoryBackend;
774 TrackContainer tracks{trackBackend, trajectoryBackend};
775
776 struct FittedCandidate {
777 Acts::BoundTrackParameters inner;
778 Acts::BoundTrackParameters outer;
779 SeedACTS seed;
780 float chi2;
781 };
782 std::vector<FittedCandidate> candidates;
783 int nFitted = 0;
784 int nFailed = 0;
785 int nInvalid = 0;
786
787 for (const auto& seed : mSeeds) {
788 const std::array<const SpacePoint*, 3> spacePoints{seed.bottom, seed.middle, seed.top};
789
790 if (!spacePoints[0] || !spacePoints[1] || !spacePoints[2]) {
791 ++nInvalid;
792 continue;
793 }
794
795 if (!spacePoints[0]->surface || !spacePoints[1]->surface || !spacePoints[2]->surface) {
796 ++nInvalid;
797 continue;
798 }
799
800 // The direct fitter expects at most one measurement per surface.
801 if (spacePoints[0]->surface == spacePoints[1]->surface ||
802 spacePoints[0]->surface == spacePoints[2]->surface ||
803 spacePoints[1]->surface == spacePoints[2]->surface) {
804 ++nInvalid;
805 continue;
806 }
807
808 Acts::Vector3 pos0{spacePoints[0]->x, spacePoints[0]->y, spacePoints[0]->z};
809 Acts::Vector3 pos1{spacePoints[1]->x, spacePoints[1]->y, spacePoints[1]->z};
810 Acts::Vector3 pos2{spacePoints[2]->x, spacePoints[2]->y, spacePoints[2]->z};
811
812 Acts::FreeVector freeParams;
813 try {
814 const auto localField = magneticField->getField(pos1, magneticFieldCache);
815 if (!localField.ok()) {
816 LOG(error) << "Failed to query the O2 magnetic field for ACTS seed parameters";
817 ++nInvalid;
818 continue;
819 }
820 freeParams = Acts::estimateTrackParamsFromSeed(pos0, 0., pos1, pos2, localField.value());
821 } catch (const std::exception& e) {
822 LOG(debug) << "ACTS seed parameter estimation failed: " << e.what();
823 ++nInvalid;
824 continue;
825 }
826
827 const double qOverP = freeParams[Acts::eFreeQOverP];
828 if (!std::isfinite(qOverP) || std::abs(qOverP) < 1.e-12) {
829 ++nInvalid;
830 continue;
831 }
832
833 Acts::Vector3 direction{freeParams[Acts::eFreeDir0],
834 freeParams[Acts::eFreeDir1],
835 freeParams[Acts::eFreeDir2]};
836
837 if (!direction.allFinite() || direction.norm() < 1.e-12) {
838 ++nInvalid;
839 continue;
840 }
841 direction.normalize();
842
843 std::array<HitMeasurement, 3> measurements;
844 std::vector<Acts::SourceLink> sourceLinks;
845 std::vector<const Acts::Surface*> surfaces;
846 sourceLinks.reserve(3);
847 surfaces.reserve(3);
848
849 bool validMeasurements = true;
850 for (int i = 0; i < 3; ++i) {
851 const auto* sp = spacePoints[i];
852 const auto* surface = sp->surface;
853 Acts::Vector3 position{sp->x, sp->y, sp->z};
854
855 // Convert the cluster's global position to the coordinates expected by
856 // a measurement on this ACTS surface.
857 auto localResult = surface->globalToLocal(geometryContext, position, direction, 1. * Acts::UnitConstants::mm);
858
859 if (!localResult.ok()) {
860 validMeasurements = false;
861 break;
862 }
863
864 auto& measurement = measurements[i];
865 measurement.surface = surface;
866 measurement.local = localResult.value();
867
868 const double sigma = 100. * Acts::UnitConstants::um;
869 // This initial fitter uses a common 100 um diagonal resolution for all
870 // three measurements; detector-specific covariances are not yet passed.
871 measurement.covariance.setZero();
872 measurement.covariance(0, 0) = sigma * sigma;
873 measurement.covariance(1, 1) = sigma * sigma;
874
875 sourceLinks.emplace_back(HitSourceLink{&measurement});
876 surfaces.push_back(surface);
877 }
878
879 if (!validMeasurements) {
880 ++nInvalid;
881 continue;
882 }
883
884 Acts::Vector4 position4;
885 position4 << pos0.x(), pos0.y(), pos0.z(), 0.;
886
887 Acts::BoundMatrix covariance = Acts::BoundMatrix::Zero();
888 auto square = [](const double x) { return x * x; };
889 covariance(Acts::eBoundLoc0, Acts::eBoundLoc0) = square(1. * Acts::UnitConstants::mm);
890 covariance(Acts::eBoundLoc1, Acts::eBoundLoc1) = square(1. * Acts::UnitConstants::mm);
891 covariance(Acts::eBoundPhi, Acts::eBoundPhi) = 0.1 * 0.1;
892 covariance(Acts::eBoundTheta, Acts::eBoundTheta) = 0.1 * 0.1;
893 covariance(Acts::eBoundQOverP, Acts::eBoundQOverP) = square(0.5 * qOverP);
894 covariance(Acts::eBoundTime, Acts::eBoundTime) = square(1. * Acts::UnitConstants::ns);
895
896 auto initialParameters = Acts::BoundTrackParameters::createCurvilinear(position4, direction, qOverP, covariance,
897 Acts::ParticleHypothesis::pion());
898
899 auto result = fitter.fit(sourceLinks.begin(), sourceLinks.end(), initialParameters,
900 fitterOptions, surfaces, tracks);
901
902 if (!result.ok()) {
903 LOG(debug) << "ACTS Kalman fit failed: " << result.error().message();
904 ++nFailed;
905 continue;
906 }
907
908 const auto track = result.value();
909 if (track.nMeasurements() < 3) {
910 ++nFailed;
911 continue;
912 }
913
914 const auto innerState = track.innermostTrackState();
915 if (!innerState.has_value()) {
916 ++nFailed;
917 continue;
918 }
919 const auto outerState = track.outermostTrackState();
920 if (!innerState->hasSmoothed() || !outerState.hasSmoothed() || !std::isfinite(track.chi2()) || track.chi2() < 0.f) {
921 ++nFailed;
922 continue;
923 }
924
925 // Explicitly use the smoothed fit, rather than the original seed estimate.
926 typename Trajectory::ConstTrackStateProxy innerProxy{*innerState};
927 typename Trajectory::ConstTrackStateProxy outerProxy{outerState};
928 candidates.push_back({track.createParametersFromState(innerProxy),
929 track.createParametersFromState(outerProxy),
930 seed, static_cast<float>(track.chi2())});
931 ++nFitted;
932 LOG(debug) << "ACTS fitted seed: "
933 << "nMeasurements=" << track.nMeasurements()
934 << " chi2=" << track.chi2()
935 << " nDoF=" << track.nDoF();
936 }
937
938 // Accept lower-chi2 candidates first: multiple seeds can share clusters.
939 std::sort(candidates.begin(), candidates.end(), [](const auto& a, const auto& b) {
940 return a.chi2 < b.chi2;
941 });
942 int nAccepted = 0;
943 for (const auto& candidate : candidates) {
944 nAccepted += acceptTrack(candidate.inner, candidate.outer, candidate.seed, candidate.chi2);
945 }
946 LOG(debug) << "ACTS fitting: " << nFitted << " fitted, "
947 << nAccepted << " accepted, " << nFailed << " failed, "
948 << nInvalid << " invalid from " << mSeeds.size() << " seeds";
949}
950
951template <int nLayers>
952bool TrackerACTS<nLayers>::acceptTrack(const Acts::BoundTrackParameters& inner,
953 const Acts::BoundTrackParameters& outer,
954 const SeedACTS& seed, float chi2)
955{
956 if (!mTimeFrame || !std::isfinite(chi2) || chi2 < 0.f) {
957 return false;
958 }
959
960 const std::array<const SpacePoint*, 3> hits{seed.bottom, seed.middle, seed.top};
961 std::array<int, o2::its::TrackITSExt::MaxClusters> clusterIndices;
962 clusterIndices.fill(-1);
963 std::array<int, nLayers> internalIndices;
964 internalIndices.fill(-1);
965 uint32_t pattern = 0;
966 std::array<uint64_t, 3> keys{};
967
968 // TrackITSExt has one cluster slot per detector layer. Retain the internal
969 // TimeFrame cluster index for MC lookup, but publish its external index in
970 // the O2 track.
971 for (int i = 0; i < 3; ++i) {
972 const auto* hit = hits[i];
973 if (!hit || hit->layer < 0 || hit->layer >= nLayers || hit->clusterId < 0 ||
974 hit->rof < 0 || hit->rof >= mTimeFrame->getNrof(hit->layer)) {
975 return false;
976 }
977 const uint32_t mask = 1u << hit->layer;
978 if (pattern & mask) { // the TrackITSExt index array has one slot per layer
979 return false;
980 }
981 pattern |= mask;
982 keys[i] = (uint64_t(static_cast<uint32_t>(hit->layer)) << 32) | static_cast<uint32_t>(hit->clusterId);
983 if (mAcceptedClusters.contains(keys[i])) {
984 return false;
985 }
986 // Keep the internal index for later MC lookup; publish the external one.
987 internalIndices[hit->layer] = hit->clusterId;
988 clusterIndices[hit->layer] = mTimeFrame->getClusterExternalIndex(hit->layer, hit->clusterId);
989 if (clusterIndices[hit->layer] < 0) {
990 return false;
991 }
992 }
993
994 o2::track::TrackParCov innerO2, outerO2;
995 // Convert the smoothed ACTS parameters at both ends of the fitted
996 // trajectory. Conversion uses the nominal geometry context so that bound
997 // local parameters are interpreted on their associated surfaces.
999 if (!convertTrackParameters(inner, gctx, innerO2) || !convertTrackParameters(outer, gctx, outerO2)) {
1000 return false;
1001 }
1002
1003 // Require the three source clusters to have compatible readout timing. Use
1004 // the nominal overlap when possible, otherwise the widened overlap, exactly
1005 // as in ITS track acceptance.
1006 const auto& timing = mTimeFrame->getROFOverlapTableView();
1007 auto nominal = timing.getLayer(hits[0]->layer).getROFTimeBounds(hits[0]->rof);
1008 auto expanded = timing.getLayer(hits[0]->layer).getROFTimeBounds(hits[0]->rof, true);
1009 bool nominalCompatible = true;
1010 for (int i = 1; i < 3; ++i) {
1011 const auto other = timing.getLayer(hits[i]->layer).getROFTimeBounds(hits[i]->rof);
1012 const auto otherExpanded = timing.getLayer(hits[i]->layer).getROFTimeBounds(hits[i]->rof, true);
1013 if (nominalCompatible) {
1014 if (nominal.isCompatible(other)) {
1015 nominal += other;
1016 } else {
1017 nominalCompatible = false;
1018 }
1019 }
1020 if (!expanded.isCompatible(otherExpanded)) {
1021 return false;
1022 }
1023 expanded += otherExpanded;
1024 }
1025
1026 o2::its::TrackITSExt o2Track{std::move(innerO2), static_cast<short>(hits.size()), chi2, std::move(outerO2), clusterIndices};
1027 o2Track.setPattern(pattern);
1028 o2Track.getTimeStamp() = (nominalCompatible ? nominal : expanded).makeSymmetrical();
1029 const float maxHalfROF = timing.getClockLayer().mROFLength * 0.5f;
1030 if (o2Track.getTimeStamp().getTimeStampError() > maxHalfROF) {
1031 o2Track.getTimeStamp().setTimeStampError(maxHalfROF);
1032 }
1033
1034 // Labels are computed once, after all ROFs, from the internal indices.
1035 mTimeFrame->getTracks().emplace_back(std::move(o2Track));
1036 mAcceptedTrackClusterIndices.push_back(internalIndices);
1037 for (const auto key : keys) {
1038 mAcceptedClusters.insert(key);
1039 }
1040 return true;
1041}
1042
1043template <int nLayers>
1044void TrackerACTS<nLayers>::computeTracksMClabels()
1045{
1046 if (!mTimeFrame || !mTimeFrame->hasMCinformation()) {
1047 return;
1048 }
1049
1050 auto& tracks = mTimeFrame->getTracks();
1051 auto& labels = mTimeFrame->getTracksLabel();
1052
1053 if (tracks.size() != mAcceptedTrackClusterIndices.size()) {
1054 LOGP(fatal, "ACTS MC labeling: {} tracks but {} internal cluster reference sets", tracks.size(), mAcceptedTrackClusterIndices.size());
1055 return;
1056 }
1057
1058 // There must be exactly one label for each accepted track, in track order.
1059 labels.clear();
1060 labels.reserve(tracks.size());
1061
1062 struct LabelCount {
1064 int count;
1065 int lastHit;
1066 };
1067
1068 for (size_t iTrack = 0; iTrack < tracks.size(); ++iTrack) {
1069 auto& track = tracks[iTrack];
1070 const auto& indices = mAcceptedTrackClusterIndices[iTrack];
1071 std::vector<LabelCount> counts;
1072 int nHits = 0;
1073
1074 for (int layer = 0; layer < nLayers; ++layer) {
1075 if (indices[layer] < 0) {
1076 continue;
1077 }
1078 ++nHits;
1079 for (const auto& candidate : mTimeFrame->getClusterLabels(layer, indices[layer])) {
1080 if (!candidate.isValid()) {
1081 continue;
1082 }
1083
1084 auto it = std::find_if(counts.begin(), counts.end(), [&candidate](const auto& entry) {
1085 return entry.label == candidate;
1086 });
1087 if (it == counts.end()) {
1088 counts.push_back({candidate, 1, nHits});
1089 } else if (it->lastHit != nHits) {
1090 // Count a given truth label at most once per attached cluster.
1091 ++it->count;
1092 it->lastHit = nHits;
1093 }
1094 }
1095 }
1096 // Choose the truth label occurring in the largest number of attached
1097 // clusters. Mark it fake unless it is represented on every hit.
1098 o2::MCCompLabel winner;
1099 uint32_t pattern = track.getPattern() & 0x0000ffffu;
1100 if (counts.empty()) {
1101 winner.setFakeFlag();
1102 } else {
1103 const auto best = std::max_element(counts.begin(), counts.end(), [](const auto& a, const auto& b) {
1104 return a.count < b.count;
1105 });
1106 winner = best->label;
1107 if (best->count != nHits) {
1108 winner.setFakeFlag();
1109 }
1110 // Preserve the standard TrackITS pattern convention: bits [16, 31]
1111 // indicate clusters compatible with the representative MC label.
1112 for (int layer = 0; layer < nLayers; ++layer) {
1113 if (indices[layer] < 0) {
1114 continue;
1115 }
1116 for (const auto& candidate : mTimeFrame->getClusterLabels(layer, indices[layer])) {
1117 if (candidate.isValid() && candidate == best->label) {
1118 pattern |= (1u << (16 + layer));
1119 break;
1120 }
1121 }
1122 }
1123 }
1124 track.setPattern(pattern);
1125 labels.emplace_back(winner);
1126 }
1127 LOGP(info, "ACTS MC labeling: {} tracks, {} labels", tracks.size(), labels.size());
1128}
1129
1130template <int nLayers>
1132{
1133 if (!mTimeFrame) {
1134 LOG(error) << "Cannot run TrackerACTS: No TimeFrame adopted";
1135 return;
1136 }
1137
1138 double totalTime = 0.;
1139 mAcceptedClusters.clear();
1140 mAcceptedTrackClusterIndices.clear();
1141 LOG(info) << "==== TRK ACTS Tracking ====";
1142
1143 // Trigger (or retrieve) the process-wide immutable ACTS geometry. A builder
1144 // must already have been installed and the aligned O2 geometry must be
1145 // available before this first access.
1146 auto& actsGeometryManager = o2::acts::TrackingGeometryManager::instance();
1147 const auto& trackingGeometry = actsGeometryManager.get();
1148
1149 // Keep the geometry alive and make the explicit initialization step clear;
1150 // detailed lookups are done through the detector-specific surface index.
1151 (void)trackingGeometry;
1152
1153 auto* trkGeometry = o2::trk::GeometryTGeo::Instance();
1154 // The index uses this L2G cache and an exact TGeo path provider to map each
1155 // TRK sensor ID to the ACTS surface built for that sensor. It is cached by
1156 // TrackingGeometryManager and reused by the ROF processing below.
1157 trkGeometry->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::L2G));
1158 const auto& surfaceIndex = actsGeometryManager.getIndex(*trkGeometry, 1.e-3, [trkGeometry](int sensorID) {
1159 return std::string(trkGeometry->getMatrixPath(sensorID).Data());
1160 });
1161
1162 LOG(info) << "ACTS tracking geometry initialized with " << surfaceIndex.size()
1163 << " mapped sensors on " << surfaceIndex.getNSurfaces() << " surfaces";
1164 try {
1165 dumpGeometryOnce();
1166 } catch (const std::exception& e) {
1167 LOG(error) << "ACTS geometry debug dump failed: " << e.what();
1168 }
1169 if (mConfig.writeDebugTrees && mTimeFrameCounter == 0) {
1170 initDebugOutput();
1171 }
1172
1173 // Each ROF is processed independently for space-point creation, seeding,
1174 // and fitting. Accepted tracks accumulate in the TimeFrame across ROFs.
1175 for (int iROF = 0; iROF < mTimeFrame->getNrof(0); ++iROF) {
1176 LOG(info) << "Processing ROF " << iROF;
1177
1178 mCurState = SpacePointBuilding;
1179 totalTime += evaluateTask([this, iROF]() { buildSpacePoints(iROF); }, StateNames[mCurState]);
1180
1181 mCurState = Seeding;
1182 totalTime += evaluateTask([this]() { createSeeds(); }, StateNames[mCurState]);
1183
1184 const auto nTracksBefore = mTimeFrame->getTracks().size();
1185 mCurState = TrackFinding;
1186 totalTime += evaluateTask([this]() { findTracks(); }, StateNames[mCurState]);
1187 if (isDebugTimeFrame()) {
1188 mDebugROF.tf = static_cast<int>(mTimeFrameCounter);
1189 mDebugROF.rof = iROF;
1190 mDebugROF.nSpacePoints = static_cast<int>(mSpacePoints.size());
1191 mDebugROF.nSeeds = static_cast<int>(mSeeds.size());
1192 mDebugROF.nAcceptedTracks = static_cast<int>(mTimeFrame->getTracks().size() - nTracksBefore);
1193 mROFTree->Fill();
1194 }
1195 }
1196
1197 // Run MC labeling once, after every accepted track has been published.
1198 if (mTimeFrame->hasMCinformation()) {
1199 computeTracksMClabels();
1200 }
1201
1202 LOG(info) << "=== TimeFrame " << mTimeFrameCounter << " completed in: " << totalTime << " ms ===";
1203 if (isDebugTimeFrame()) {
1204 mDebugFile->cd();
1205 if (mHistSpacePoints) {
1206 mHistSpacePoints->Write("", TObject::kOverwrite);
1207 }
1208 mDebugFile->Write("", TObject::kOverwrite);
1209 mDebugFile->Flush();
1210 }
1211 ++mTimeFrameCounter;
1212 mTotalTime += totalTime;
1213}
1214
1215template <int nLayers>
1217{
1218 float avgTF = mTimeFrameCounter > 0 ? static_cast<float>(mTotalTime) / mTimeFrameCounter : 0.f;
1219 LOGP(info, "TrackerACTS summary: Processed {} TFs in TOT={:.2f} ms, AVG/TF={:.2f} ms", mTimeFrameCounter, mTotalTime, avgTF);
1220}
1221
1222// Explicit template instantiations
1223template class TrackerACTS<11>;
1224} // namespace o2::trk
General auxilliary methods.
std::ostringstream debug
int16_t charge
Definition RawEventData.h:5
unsigned int uint32_t
std::vector< std::string > keys
int32_t i
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char Directory with events to Events directory is and not inside events Show standalone event Run event generator maximum time bin of continuous for triggered for automatic continuous for automatic continuous triggered uint64_t
Timeframe settings Average distance in cm of events merged into Randomize distance around average distance of merged events Simulate correct bunch interactions instead of placing only the average number of events A value[n] sets TFlen for[n] collisions in Number of bunches per trainsort Number of bunch trains Instantaneous interaction rate Do not simulate border Total number of collisions to be placed in the interior of all time Do not select random but walk over array of events in stride steps h Event generator settings h configStandalone Use CPU for GPU Force usage of the specified GPU device no CPU fallback Continue processing after an error First event to Number of events to Number of iterations to Number of iterations to Number of initial iterations excluded from const char e
char error[CURL_ERROR_SIZE]
SurfaceTrackState state
float chi2
std::vector< int > clusterIndices
std::vector< o2::MCCompLabel > labels
std::vector< o2::its::TrackITS > tracks
void output(const std::map< std::string, ChannelStat > &channels)
Definition rawdump.cxx:197
Acts::MagneticFieldProvider backed by the O2 field.
uint32_t j
Definition RawData.h:0
Acts::Vector3 position
const Acts::Surface * surface
TRK tracker using ACTS seeding algorithm.
Process-wide provider of the ACTS tracking geometry.
std::vector< std::shared_ptr< Surface > > surfaces
StringRef key
void setFakeFlag(bool v=true)
Cache makeCache(const Acts::MagneticFieldContext &mctx) const final
Acts::Result< Acts::Vector3 > getField(const Acts::Vector3 &position, Cache &cache) const final
const Acts::GeometryContext & getNominalContext() const
static TrackingGeometryManager & instance()
static GeometryTGeo * Instance()
void clustersToTracks()
Build space points, find tracks, and publish accepted tracks in the TimeFrame.
void adoptTimeFrame(o2::its::TimeFrame< nLayers > &tf)
void printSummary() const
Print the accumulated tracking timing and processing summary.
GLfloat GLfloat GLfloat alpha
Definition glcorearb.h:279
GLint GLenum GLint x
Definition glcorearb.h:403
GLint GLsizei count
Definition glcorearb.h:399
GLuint64EXT * result
Definition glcorearb.h:5662
GLdouble GLdouble GLdouble GLdouble top
Definition glcorearb.h:4077
GLint first
Definition glcorearb.h:399
GLboolean GLboolean GLboolean b
Definition glcorearb.h:1233
GLsizei const GLfloat * value
Definition glcorearb.h:819
GLuint GLsizei const GLchar * label
Definition glcorearb.h:2519
GLsizei GLenum const void * indices
Definition glcorearb.h:400
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLint GLint bottom
Definition glcorearb.h:1979
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
Definition glcorearb.h:1308
GLenum GLuint GLint GLint layer
Definition glcorearb.h:1310
GLboolean GLboolean GLboolean GLboolean a
Definition glcorearb.h:1233
GLint GLuint mask
Definition glcorearb.h:291
PropagatorF Propagator
Definition Propagator.h:225
int const float const TrackSeed< NLayers > & seed
const bool const int nLayers
const bool const bool const int FollowDirection BestTrial TrackITSInternal< NLayers > & best
const bool const int TrackITSInternal< NLayers > & track
const float const float const float const float std::array< float, 3 > std::array< float, 3 > & direction
TrackParCovF TrackParCov
Definition Track.h:33
value_T step
Definition TrackUtils.h:42
std::unique_ptr< GPUReconstructionTimeframe > tf
constexpr size_t max
VectorOfTObjectPtrs other
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::vector< Cluster > clusters
std::vector< int > row
std::array< uint16_t, 5 > pattern