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>
80#include <nlohmann/json.hpp>
108bool convertTrackParameters(
const Acts::BoundTrackParameters& actsTrack,
109 const Acts::GeometryContext& gctx,
112 const auto&
state = actsTrack.parameters();
113 if (!
state.allFinite() || !actsTrack.covariance().has_value() || !actsTrack.covariance()->allFinite()) {
117 const auto position = actsTrack.position(gctx);
122 const double ca = std::cos(
alpha);
123 const double sa = std::sin(
alpha);
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) {
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()) {
138 const double snp = std::sin(p[Acts::eBoundPhi] -
alpha);
139 if (!std::isfinite(snp) || std::abs(snp) >= 0.999999) {
143 dest << (-xyz.x() * sa + xyz.y() * ca) / Acts::UnitConstants::cm,
144 xyz.z() / Acts::UnitConstants::cm,
147 p[Acts::eBoundQOverP] * Acts::UnitConstants::GeV /
sinTheta;
148 return dest.allFinite();
151 Eigen::Matrix<double, 5, 1> pars;
152 if (!toO2(
state, pars)) {
156 const double x = (
position.x() * ca +
position.y() * sa) / Acts::UnitConstants::cm;
157 if (!std::isfinite(
x)) {
161 Eigen::Matrix<double, 5, Acts::eBoundSize> jacobian;
163 for (
int i = 0;
i < Acts::eBoundSize; ++
i) {
164 if (
i == Acts::eBoundTime) {
167 const double step = (
i == Acts::eBoundLoc0 ||
i == Acts::eBoundLoc1)
168 ? 1.e-3 * Acts::UnitConstants::mm
169 : (
i ==
Acts::eBoundQOverP)
172 Acts::BoundVector plus =
state;
173 Acts::BoundVector minus =
state;
176 Eigen::Matrix<double, 5, 1> fPlus, fMinus;
177 if (!toO2(plus, fPlus) || !toO2(minus, fMinus)) {
180 jacobian.col(
i) = (fPlus - fMinus) / (2. * step);
183 const Eigen::Matrix<double, 5, 5> covariance = jacobian * (*actsTrack.covariance()) * jacobian.transpose();
184 if (!covariance.allFinite()) {
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])) {
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)));
199 const int charge =
state[Acts::eBoundQOverP] >= 0. ? 1 : -1;
201 o2Params, o2Cov,
charge, o2::track::PID::Pion};
205template <
int nLayers>
209 mSpacePointsPerLayer.resize(nLayers);
213template <
int nLayers>
218 if (mHistSpacePoints) {
219 mHistSpacePoints->Write(
"", TObject::kOverwrite);
221 mDebugFile->Write(
"", TObject::kOverwrite);
226template <
int nLayers>
230 return mDebugFile && (mConfig.debugMaxTimeFrames < 0 ||
231 mTimeFrameCounter < static_cast<unsigned int>(mConfig.debugMaxTimeFrames));
234template <
int nLayers>
235void TrackerACTS<nLayers>::initDebugOutput()
237 if (!mConfig.writeDebugTrees || mDebugFile || mConfig.debugMaxTimeFrames == 0) {
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;
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");
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");
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");
288 mHistSpacePoints = std::make_unique<TH2F>(
"hSpacePoints",
"Space points; x (cm); y (cm)",
289 200, -100, 100, 200, -100, 100);
290 mHistSpacePoints->SetDirectory(
nullptr);
291 LOG(info) <<
"ACTS debug trees enabled: " << mConfig.debugFileName;
294template <
int nLayers>
295void TrackerACTS<nLayers>::dumpGeometryOnce()
297 if (!mConfig.dumpTrackingGeometry || mGeometryDumped) {
300 mGeometryDumped =
true;
305 const auto& geometry = manager.get();
306 const auto& gctx = manager.getNominalContext();
311 const auto& surfaceIndex = manager.getIndex(*trkGeometry, 1.e-3, [trkGeometry](
int sensorID) {
312 return std::string(trkGeometry->getMatrixPath(sensorID).Data());
315 std::ofstream out(mConfig.geometryDumpFileName);
317 LOG(
error) <<
"Cannot open ACTS geometry dump: " << mConfig.geometryDumpFileName;
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";
327 geometry.visitVolumes([&](
const Acts::TrackingVolume* volume) {
328 if (volume ==
nullptr) {
331 const auto& transform = volume->localToGlobalTransform(gctx);
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();
342 item[
"rotation"].push_back({transform.rotation()(
row, 0), transform.rotation()(
row, 1), transform.rotation()(
row, 2)});
351 out <<
"\n ],\n \"surfaces\": [\n";
357 geometry.visitSurfaces([&](
const Acts::Surface*
surface) {
361 const auto& transform =
surface->localToGlobalTransform(gctx);
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();
371 item[
"rotation"].push_back({transform.rotation()(
row, 0), transform.rotation()(
row, 1), transform.rotation()(
row, 2)});
373 item[
"sensorIds"] = surfaceIndex.getSensorIDs(
surface->geometryId());
383 LOG(
error) <<
"Error while writing ACTS geometry dump " << mConfig.geometryDumpFileName;
386 LOG(info) <<
"ACTS tracking geometry snapshot: " << nVolumes <<
" volumes and "
387 << nSurfaces <<
" surfaces written to " << mConfig.geometryDumpFileName;
390template <
int nLayers>
391void TrackerACTS<nLayers>::fillDebugSeeds(
int rof)
393 if (!isDebugTimeFrame()) {
396 for (
size_t iSeed = 0; iSeed < mSeeds.size(); ++iSeed) {
397 const auto&
seed = mSeeds[iSeed];
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};
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();
422template <
int nLayers>
429template <
int nLayers>
432 mSpacePoints.clear();
433 for (
auto& layerSPs : mSpacePointsPerLayer) {
438 LOG(
error) <<
"Cannot build ACTS space points: Sensor IDs not adopted";
447 trkGeometry->fillMatrixCache(o2::math_utils::bit2Mask(o2::math_utils::TransformType::L2G));
452 const auto& surfaceIndex = actsGeometryManager.getIndex(*trkGeometry, 1.e-3, [trkGeometry](
int sensorID) {
453 return std::string(trkGeometry->getMatrixPath(sensorID).Data());
460 const auto clusters = mTimeFrame->getUnsortedClustersOnLayer(rof,
layer);
461 const int firstCluster = mTimeFrame->getSortedStartIndex(rof,
layer);
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);
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()) {
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;
481 mDebugCluster.mappingStatus = !hasSensorID ? 0 : !
surface ? 1
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();
494 LOG(
error) <<
"Missing sensor ID for layer " <<
layer <<
" cluster " << clusterIndex;
500 LOG(
error) <<
"No ACTS surface for sensor " << sensorID <<
" on layer " <<
layer;
508 sp.x = cluster.xCoordinate * Acts::UnitConstants::cm;
509 sp.y = cluster.yCoordinate * Acts::UnitConstants::cm;
510 sp.z = cluster.zCoordinate * Acts::UnitConstants::cm;
512 if (mHistSpacePoints) {
513 mHistSpacePoints->Fill(sp.x / Acts::UnitConstants::cm, sp.y / Acts::UnitConstants::cm);
517 sp.clusterId = clusterIndex;
519 sp.sensorId = sensorID;
521 sp.varianceR = 0.01f;
522 sp.varianceZ = 0.01f;
524 mSpacePoints.push_back(sp);
529 for (
auto& sp : mSpacePoints) {
530 if (sp.layer >= 0 && sp.layer < nLayers) {
531 mSpacePointsPerLayer[sp.layer].push_back(&sp);
535 LOG(info) <<
"ACTS surface mapping: " << nMapped <<
" clusters mapped, " << nMissing <<
" clusters missing";
538template <
int nLayers>
539void TrackerACTS<nLayers>::createSeeds()
542 if (mSpacePoints.empty()) {
543 LOG(info) <<
"No space points available for seeding";
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");
554 const float bFieldInZ = fieldAtOrigin.value().z();
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};
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());
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();
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());
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;
607 const auto last =
static_cast<Acts::SpacePointIndex
>(spacePoints.size());
608 gridRanges.emplace_back(
first, last);
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});
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});
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});
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()};
643 Acts::TripletSeeder seeder;
644 Acts::TripletSeeder::Cache seedingCache;
645 Acts::SeedContainer seeds;
646 seeds.assignSpacePointContainer(spacePoints);
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());
656 for (
const auto bin :
top) {
657 topRanges.push_back(spacePoints.range(gridRanges.at(bin)).asConst());
659 auto middleRange = spacePoints.range(gridRanges.at(middle)).asConst();
660 if (middleRange.empty()) {
664 seeder.createSeedsFromGroups(seedingCache, *bottomFinder, *topFinder,
665 *tripletFinder,
filter, spacePoints,
666 bottomRanges, middleRange, topRanges,
667 {gridConfig.rMin, gridConfig.rMax}, seeds);
671 mSeeds.reserve(seeds.size());
672 for (
const auto seed : seeds) {
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()];
681 fillDebugSeeds(mSpacePoints.front().rof);
683 LOGF(
debug,
"Created %zu seeds from %zu space points", mSeeds.size(), mSpacePoints.size());
686template <
int nLayers>
687void TrackerACTS<nLayers>::findTracks()
689 if (mSeeds.empty()) {
696 const auto& geometryContext = actsGeometryManager.getNominalContext();
698 Acts::MagneticFieldContext magneticFieldContext;
699 Acts::CalibrationContext calibrationContext;
701 auto magneticField = std::make_shared<o2::acts::MagneticFieldAdapter>();
702 auto magneticFieldCache = magneticField->
makeCache(magneticFieldContext);
704 using Propagator = Acts::Propagator<Acts::EigenStepper<>, Acts::DirectNavigator>;
705 using Trajectory = Acts::VectorMultiTrajectory;
706 using TrackContainer = Acts::TrackContainer<Acts::VectorTrackContainer, Trajectory>;
708 Propagator propagator{Acts::EigenStepper<>{magneticField}, Acts::DirectNavigator{}};
710 Acts::KalmanFitter<Propagator, Trajectory> fitter{std::move(propagator)};
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();
718 struct HitSourceLink {
719 const HitMeasurement* hit{
nullptr};
722 struct SurfaceAccessor {
723 const Acts::Surface* getSurface(
const Acts::SourceLink& sourceLink)
const
725 return sourceLink.get<HitSourceLink>().hit->surface;
729 struct MeasurementCalibrator {
730 void calibrate(
const Acts::GeometryContext&,
731 const Acts::CalibrationContext&,
732 const Acts::SourceLink& sourceLink,
733 Trajectory::TrackStateProxy trackState)
const
735 const auto& hit = *sourceLink.get<HitSourceLink>().hit;
739 trackState.setUncalibratedSourceLink(Acts::SourceLink{sourceLink});
740 trackState.allocateCalibrated(2);
741 trackState.calibrated<2>() = hit.local;
742 trackState.calibratedCovariance<2>() = hit.covariance;
744 trackState.setProjectorSubspaceIndices(std::array<std::uint8_t, 2>{
static_cast<std::uint8_t
>(Acts::eBoundLoc0),
745 static_cast<std::uint8_t
>(Acts::eBoundLoc1)});
749 SurfaceAccessor surfaceAccessor;
750 MeasurementCalibrator calibrator;
751 Acts::GainMatrixUpdater updater;
752 Acts::GainMatrixSmoother smoother;
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);
760 Acts::PropagatorPlainOptions propagatorOptions{geometryContext, magneticFieldContext};
762 Acts::KalmanFitterOptions<Trajectory> fitterOptions{geometryContext,
763 magneticFieldContext,
772 Acts::VectorTrackContainer trackBackend;
773 Trajectory trajectoryBackend;
774 TrackContainer
tracks{trackBackend, trajectoryBackend};
776 struct FittedCandidate {
777 Acts::BoundTrackParameters inner;
778 Acts::BoundTrackParameters outer;
782 std::vector<FittedCandidate> candidates;
787 for (
const auto& seed : mSeeds) {
788 const std::array<const SpacePoint*, 3> spacePoints{
seed.bottom,
seed.middle,
seed.top};
790 if (!spacePoints[0] || !spacePoints[1] || !spacePoints[2]) {
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};
812 Acts::FreeVector freeParams;
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";
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();
827 const double qOverP = freeParams[Acts::eFreeQOverP];
828 if (!std::isfinite(qOverP) || std::abs(qOverP) < 1.e-12) {
833 Acts::Vector3
direction{freeParams[Acts::eFreeDir0],
834 freeParams[Acts::eFreeDir1],
835 freeParams[Acts::eFreeDir2]};
843 std::array<HitMeasurement, 3> measurements;
844 std::vector<Acts::SourceLink> sourceLinks;
845 std::vector<const Acts::Surface*>
surfaces;
846 sourceLinks.reserve(3);
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};
857 auto localResult =
surface->globalToLocal(geometryContext,
position, direction, 1. * Acts::UnitConstants::mm);
859 if (!localResult.ok()) {
860 validMeasurements =
false;
864 auto& measurement = measurements[
i];
866 measurement.local = localResult.value();
868 const double sigma = 100. * Acts::UnitConstants::um;
871 measurement.covariance.setZero();
872 measurement.covariance(0, 0) = sigma * sigma;
873 measurement.covariance(1, 1) = sigma * sigma;
875 sourceLinks.emplace_back(HitSourceLink{&measurement});
879 if (!validMeasurements) {
884 Acts::Vector4 position4;
885 position4 << pos0.x(), pos0.y(), pos0.z(), 0.;
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);
896 auto initialParameters = Acts::BoundTrackParameters::createCurvilinear(position4, direction, qOverP, covariance,
897 Acts::ParticleHypothesis::pion());
899 auto result = fitter.fit(sourceLinks.begin(), sourceLinks.end(), initialParameters,
903 LOG(
debug) <<
"ACTS Kalman fit failed: " <<
result.error().message();
909 if (
track.nMeasurements() < 3) {
914 const auto innerState =
track.innermostTrackState();
915 if (!innerState.has_value()) {
919 const auto outerState =
track.outermostTrackState();
920 if (!innerState->hasSmoothed() || !outerState.hasSmoothed() || !std::isfinite(
track.chi2()) ||
track.chi2() < 0.f) {
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())});
933 <<
"nMeasurements=" <<
track.nMeasurements()
934 <<
" chi2=" <<
track.chi2()
935 <<
" nDoF=" <<
track.nDoF();
939 std::sort(candidates.begin(), candidates.end(), [](
const auto&
a,
const auto&
b) {
940 return a.chi2 < b.chi2;
943 for (
const auto& candidate : candidates) {
944 nAccepted += acceptTrack(candidate.inner, candidate.outer, candidate.seed, candidate.chi2);
946 LOG(
debug) <<
"ACTS fitting: " << nFitted <<
" fitted, "
947 << nAccepted <<
" accepted, " << nFailed <<
" failed, "
948 << nInvalid <<
" invalid from " << mSeeds.size() <<
" seeds";
951template <
int nLayers>
952bool TrackerACTS<nLayers>::acceptTrack(
const Acts::BoundTrackParameters& inner,
953 const Acts::BoundTrackParameters& outer,
954 const SeedACTS& seed,
float chi2)
956 if (!mTimeFrame || !std::isfinite(
chi2) ||
chi2 < 0.f) {
960 const std::array<const SpacePoint*, 3> hits{
seed.bottom,
seed.middle,
seed.top};
961 std::array<int, o2::its::TrackITSExt::MaxClusters>
clusterIndices;
963 std::array<int, nLayers> internalIndices;
964 internalIndices.fill(-1);
966 std::array<uint64_t, 3>
keys{};
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)) {
983 if (mAcceptedClusters.contains(
keys[
i])) {
987 internalIndices[hit->layer] = hit->clusterId;
988 clusterIndices[hit->layer] = mTimeFrame->getClusterExternalIndex(hit->layer, hit->clusterId);
999 if (!convertTrackParameters(inner, gctx, innerO2) || !convertTrackParameters(outer, gctx, outerO2)) {
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)) {
1017 nominalCompatible =
false;
1020 if (!expanded.isCompatible(otherExpanded)) {
1023 expanded += otherExpanded;
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);
1035 mTimeFrame->getTracks().emplace_back(std::move(o2Track));
1036 mAcceptedTrackClusterIndices.push_back(internalIndices);
1038 mAcceptedClusters.insert(
key);
1043template <
int nLayers>
1044void TrackerACTS<nLayers>::computeTracksMClabels()
1046 if (!mTimeFrame || !mTimeFrame->hasMCinformation()) {
1050 auto&
tracks = mTimeFrame->getTracks();
1051 auto&
labels = mTimeFrame->getTracksLabel();
1053 if (
tracks.size() != mAcceptedTrackClusterIndices.size()) {
1054 LOGP(fatal,
"ACTS MC labeling: {} tracks but {} internal cluster reference sets",
tracks.size(), mAcceptedTrackClusterIndices.size());
1068 for (
size_t iTrack = 0; iTrack <
tracks.size(); ++iTrack) {
1070 const auto&
indices = mAcceptedTrackClusterIndices[iTrack];
1071 std::vector<LabelCount> counts;
1079 for (
const auto& candidate : mTimeFrame->getClusterLabels(
layer,
indices[
layer])) {
1080 if (!candidate.isValid()) {
1084 auto it = std::find_if(counts.begin(), counts.end(), [&candidate](
const auto&
entry) {
1085 return entry.label == candidate;
1087 if (it == counts.end()) {
1088 counts.push_back({candidate, 1, nHits});
1089 }
else if (it->lastHit != nHits) {
1092 it->lastHit = nHits;
1100 if (counts.empty()) {
1103 const auto best = std::max_element(counts.begin(), counts.end(), [](
const auto&
a,
const auto&
b) {
1104 return a.count < b.count;
1106 winner =
best->label;
1107 if (
best->count != nHits) {
1116 for (
const auto& candidate : mTimeFrame->getClusterLabels(
layer,
indices[
layer])) {
1117 if (candidate.isValid() && candidate ==
best->label) {
1125 labels.emplace_back(winner);
1127 LOGP(info,
"ACTS MC labeling: {} tracks, {} labels",
tracks.size(),
labels.size());
1130template <
int nLayers>
1134 LOG(
error) <<
"Cannot run TrackerACTS: No TimeFrame adopted";
1138 double totalTime = 0.;
1139 mAcceptedClusters.clear();
1140 mAcceptedTrackClusterIndices.clear();
1141 LOG(info) <<
"==== TRK ACTS Tracking ====";
1147 const auto& trackingGeometry = actsGeometryManager.get();
1151 (
void)trackingGeometry;
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());
1162 LOG(info) <<
"ACTS tracking geometry initialized with " << surfaceIndex.size()
1163 <<
" mapped sensors on " << surfaceIndex.getNSurfaces() <<
" surfaces";
1166 }
catch (
const std::exception&
e) {
1167 LOG(
error) <<
"ACTS geometry debug dump failed: " <<
e.what();
1169 if (mConfig.writeDebugTrees && mTimeFrameCounter == 0) {
1175 for (
int iROF = 0; iROF < mTimeFrame->getNrof(0); ++iROF) {
1176 LOG(info) <<
"Processing ROF " << iROF;
1178 mCurState = SpacePointBuilding;
1179 totalTime += evaluateTask([
this, iROF]() { buildSpacePoints(iROF); }, StateNames[mCurState]);
1181 mCurState = Seeding;
1182 totalTime += evaluateTask([
this]() { createSeeds(); }, StateNames[mCurState]);
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);
1198 if (mTimeFrame->hasMCinformation()) {
1199 computeTracksMClabels();
1202 LOG(info) <<
"=== TimeFrame " << mTimeFrameCounter <<
" completed in: " << totalTime <<
" ms ===";
1203 if (isDebugTimeFrame()) {
1205 if (mHistSpacePoints) {
1206 mHistSpacePoints->Write(
"", TObject::kOverwrite);
1208 mDebugFile->Write(
"", TObject::kOverwrite);
1209 mDebugFile->Flush();
1211 ++mTimeFrameCounter;
1212 mTotalTime += totalTime;
1215template <
int nLayers>
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);
General auxilliary methods.
std::vector< std::string > keys
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]
std::vector< int > clusterIndices
std::vector< o2::MCCompLabel > labels
std::vector< o2::its::TrackITS > tracks
Acts::MagneticFieldProvider backed by the O2 field.
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
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
GLdouble GLdouble GLdouble GLdouble top
GLboolean GLboolean GLboolean b
GLsizei const GLfloat * value
GLuint GLsizei const GLchar * label
GLsizei GLenum const void * indices
typedef void(APIENTRYP PFNGLCULLFACEPROC)(GLenum mode)
GLint GLint GLint GLint GLint GLint GLint GLbitfield GLenum filter
GLenum GLuint GLint GLint layer
GLboolean GLboolean GLboolean GLboolean a
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
std::unique_ptr< GPUReconstructionTimeframe > tf
VectorOfTObjectPtrs other
LOG(info)<< "Compressed in "<< sw.CpuTime()<< " s"
std::vector< Cluster > clusters
std::array< uint16_t, 5 > pattern