FairShip
Loading...
Searching...
No Matches
ActsStrawTracker.cxx
Go to the documentation of this file.
1// SPDX-License-Identifier: LGPL-3.0-or-later
2// SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP
3// Collaboration
4
5#include "ActsStrawTracker.h"
6
7#include <algorithm>
8#include <array>
9#include <cmath>
10#include <limits>
11#include <numeric>
12#include <optional>
13#include <stdexcept>
14#include <utility>
15
16#include "Acts/Definitions/TrackParametrization.hpp"
17#include "Acts/Definitions/Units.hpp"
18#include "Acts/EventData/BoundTrackParameters.hpp"
19#include "Acts/EventData/ParticleHypothesis.hpp"
20#include "Acts/EventData/SourceLink.hpp"
21#include "Acts/EventData/TrackContainer.hpp"
22#include "Acts/EventData/TransformationHelpers.hpp"
23#include "Acts/EventData/VectorMultiTrajectory.hpp"
24#include "Acts/EventData/VectorTrackContainer.hpp"
25#include "Acts/Geometry/GeometryContext.hpp"
26#include "Acts/MagneticField/MagneticFieldContext.hpp"
27#include "Acts/Propagator/DirectNavigator.hpp"
28#include "Acts/Propagator/EigenStepper.hpp"
29#include "Acts/Propagator/Propagator.hpp"
30#include "Acts/Propagator/VoidNavigator.hpp"
31#include "Acts/Surfaces/PlaneSurface.hpp"
32#include "Acts/TrackFitting/GainMatrixSmoother.hpp"
33#include "Acts/TrackFitting/GainMatrixUpdater.hpp"
34#include "Acts/TrackFitting/KalmanFitter.hpp"
35#include "Acts/Utilities/CalibrationContext.hpp"
36#include "Acts/Utilities/Logger.hpp"
37#include "Acts/Utilities/UnitVectors.hpp"
38#include "ActsFrame.hpp"
39#include "ActsShipField.hpp"
40#include "ActsStrawGeometry.hpp"
41#include "StrawPatRec.hpp"
42#include "TGeoManager.h"
43#include "TVirtualMagField.h"
44
45namespace SHiP {
46
47namespace {
48
49namespace u = Acts::UnitConstants;
50
51using Trajectory = Acts::VectorMultiTrajectory;
52using TrackContainer = Acts::TrackContainer<Acts::VectorTrackContainer,
53 Trajectory, std::shared_ptr>;
54using Stepper = Acts::EigenStepper<>;
55using DirectPropagator = Acts::Propagator<Stepper, Acts::DirectNavigator>;
56using KalmanFitter = Acts::KalmanFitter<DirectPropagator, Trajectory>;
57using Extrapolator = Acts::Propagator<Stepper, Acts::VoidNavigator>;
58
61constexpr double kSeedSigmaLoc0 = 1 * u::mm;
62constexpr double kSeedSigmaLoc1 = 20 * u::mm;
63constexpr double kSeedSigmaAngle = 5e-3;
64constexpr double kSeedRelativeSigmaP = 0.3;
66constexpr int kMaxRefits = 3;
68constexpr double kOutlierPull = 5.;
70constexpr double kFieldStep = 5.;
72constexpr double kKick = 0.299792458;
74constexpr double kMaxSeedMomentum = 1000.;
76constexpr int kMinFitMeasurements = 10;
81constexpr double kTrackHitWeight = 0.5;
82constexpr double kMaxTrackChi2PerNdf = 5.;
83constexpr double kMaxSharedFraction = 0.25;
86constexpr std::size_t kMinTrackHits = 20;
87// The time is not measured, so it is effectively left free
88constexpr double kSeedSigmaTime = 1e9;
89
91constexpr double kVertexSeedMinX = 20 * u::m;
92constexpr double kVertexSeedMaxX = 90 * u::m;
94constexpr int kVertexIterations = 10;
95constexpr double kVertexTolerance = 0.1 * u::mm;
96
97constexpr double kPathLimit = 100 * u::m;
98
99struct StrawMeasurement {
100 const Acts::Surface* surface;
101 const StrawWire* wire;
103 double driftRadius;
104 double variance;
106 int sign{1};
107};
108
110template <int N, std::size_t M = N * (N + 1) / 2>
111std::array<Double_t, M> upperTriangle(const Acts::SquareMatrix<N>& matrix) {
112 std::array<Double_t, M> elements{};
113 std::size_t k = 0;
114 for (int row = 0; row < N; ++row) {
115 for (int col = row; col < N; ++col) {
116 elements[k++] = matrix(row, col);
117 }
118 }
119 return elements;
120}
121
123Acts::Matrix<3, 3> momentumJacobianDirection(double qOverP) {
124 return Acts::SquareMatrix3::Identity() / std::abs(qOverP);
125}
126
127Acts::Vector3 momentumJacobianQOverP(const Acts::Vector3& direction,
128 double qOverP) {
129 return -direction / (qOverP * std::abs(qOverP));
130}
131
133Acts::SquareMatrix<6> shipCovariance(const Acts::BoundTrackParameters& params,
134 const Acts::GeometryContext& gctx) {
135 const auto& surface = params.referenceSurface();
136 const Acts::FreeVector free =
137 Acts::transformBoundToFreeParameters(surface, gctx, params.parameters());
138 const Acts::Vector3 direction = free.segment<3>(Acts::eFreeDir0);
139 const Acts::BoundToFreeMatrix boundToFree = surface.boundToFreeJacobian(
140 gctx, free.segment<3>(Acts::eFreePos0), direction);
141 const Acts::FreeMatrix freeCovariance =
142 boundToFree * params.covariance().value() * boundToFree.transpose();
143
144 const double qOverP = free[Acts::eFreeQOverP];
145 const Acts::RotationMatrix3 rotation = ActsFrame::toShipRotation();
146 Acts::Matrix<6, Acts::eFreeSize> freeToShip =
147 Acts::Matrix<6, Acts::eFreeSize>::Zero();
148 freeToShip.block<3, 3>(0, Acts::eFreePos0) =
149 rotation / ActsFrame::kShipLength;
150 freeToShip.block<3, 3>(3, Acts::eFreeDir0) =
151 rotation * momentumJacobianDirection(qOverP) / u::GeV;
152 freeToShip.block<3, 1>(3, Acts::eFreeQOverP) =
153 rotation * momentumJacobianQOverP(direction, qOverP) / u::GeV;
154 return freeToShip * freeCovariance * freeToShip.transpose();
155}
156
158Acts::SquareMatrix3 shipMomentumCovariance(
159 const Acts::BoundTrackParameters& params) {
160 const double phi = params.parameters()[Acts::eBoundPhi];
161 const double theta = params.parameters()[Acts::eBoundTheta];
162 const double qOverP = params.parameters()[Acts::eBoundQOverP];
163 const double p = 1. / std::abs(qOverP);
164 const Acts::Vector3 direction = params.direction();
165 Acts::Matrix<3, Acts::eBoundSize> boundToMomentum =
166 Acts::Matrix<3, Acts::eBoundSize>::Zero();
167 boundToMomentum.col(Acts::eBoundPhi) =
168 Acts::Vector3(-std::sin(phi) * std::sin(theta),
169 std::cos(phi) * std::sin(theta), 0.) *
170 p;
171 boundToMomentum.col(Acts::eBoundTheta) =
172 Acts::Vector3(std::cos(phi) * std::cos(theta),
173 std::sin(phi) * std::cos(theta), -std::sin(theta)) *
174 p;
175 boundToMomentum.col(Acts::eBoundQOverP) =
176 momentumJacobianQOverP(direction, qOverP);
177 const Acts::Matrix<3, Acts::eBoundSize> jacobian =
178 ActsFrame::toShipRotation() * boundToMomentum / u::GeV;
179 return jacobian * params.covariance().value() * jacobian.transpose();
180}
181
183using Tangent = std::pair<Acts::Vector3, Acts::Vector3>;
184
186Tangent tangent(const Acts::Surface& surface, const Acts::BoundVector& params,
187 const Acts::GeometryContext& gctx) {
188 const Acts::Vector3 direction = Acts::makeDirectionFromPhiTheta(
189 params[Acts::eBoundPhi], params[Acts::eBoundTheta]);
190 return {surface.localToGlobal(
191 gctx,
192 Acts::Vector2(params[Acts::eBoundLoc0], params[Acts::eBoundLoc1]),
193 direction),
194 direction};
195}
196
197std::vector<Tangent> tangents(
198 const std::vector<Acts::BoundTrackParameters>& tracks,
199 const Acts::GeometryContext& gctx) {
200 std::vector<Tangent> lines;
201 for (const auto& track : tracks) {
202 lines.push_back(
203 tangent(track.referenceSurface(), track.parameters(), gctx));
204 }
205 return lines;
206}
207
209Acts::Vector3 closestPoint(const std::vector<Tangent>& lines) {
210 Acts::SquareMatrix3 a = Acts::SquareMatrix3::Zero();
211 Acts::Vector3 b = Acts::Vector3::Zero();
212 for (const auto& [position, direction] : lines) {
213 const Acts::SquareMatrix3 projection =
214 Acts::SquareMatrix3::Identity() - direction * direction.transpose();
215 a += projection;
216 b += projection * position;
217 }
218 return a.colPivHouseholderQr().solve(b);
219}
220
223Acts::Vector3 vertexSeed(const std::vector<Acts::BoundTrackParameters>& tracks,
224 const Acts::GeometryContext& gctx) {
225 Acts::Vector3 seed = closestPoint(tangents(tracks, gctx));
226 if (!seed.allFinite()) {
227 seed = Acts::Vector3(0.5 * (kVertexSeedMinX + kVertexSeedMaxX), 0., 0.);
228 }
229 seed.x() = std::clamp(seed.x(), kVertexSeedMinX, kVertexSeedMaxX);
230 return seed;
231}
232
234std::shared_ptr<Acts::PlaneSurface> constantZPlane(const Acts::Vector3& point) {
235 Acts::Transform3 transform = Acts::Transform3::Identity();
236 transform.linear().col(0) = Acts::Vector3::UnitY();
237 transform.linear().col(1) = Acts::Vector3::UnitZ();
238 transform.linear().col(2) = Acts::Vector3::UnitX();
239 transform.translation() = point;
240 return Acts::Surface::makeShared<Acts::PlaneSurface>(transform);
241}
242
244double lineDistance(const Acts::Vector3& p1, const Acts::Vector3& d1,
245 const Acts::Vector3& p2, const Acts::Vector3& d2) {
246 const Acts::Vector3 delta = p1 - p2;
247 const Acts::Vector3 normal = d1.cross(d2);
248 if (normal.norm() > 1e-12) {
249 return std::abs(delta.dot(normal)) / normal.norm();
250 }
251 return delta.cross(d1.normalized()).norm();
252}
253
254} // namespace
255
257 Impl(const TGeoManager& geometry, TVirtualMagField* magField)
258 : straws(geometry),
259 shipField(magField),
260 field(std::make_shared<ActsShipField>(magField)),
261 fitter(DirectPropagator(Stepper(field), Acts::DirectNavigator(),
262 Acts::getDefaultLogger("Propagator",
263 Acts::Logging::WARNING)),
264 Acts::getDefaultLogger("KalmanFitter", Acts::Logging::WARNING)),
266 Stepper(field), Acts::VoidNavigator(),
267 Acts::getDefaultLogger("Extrapolator", Acts::Logging::WARNING)),
268 tracks(std::make_shared<Acts::VectorTrackContainer>(),
269 std::make_shared<Trajectory>()) {
270 extensions.surfaceAccessor.connect<&Impl::surfaceOf>(this);
271 extensions.calibrator.connect<&Impl::calibrate>(this);
272 extensions.updater
273 .connect<&Acts::GainMatrixUpdater::operator()<Trajectory>>(&updater);
274 extensions.smoother
275 .connect<&Acts::GainMatrixSmoother::operator()<Trajectory>>(&smoother);
276
277 // The magnet sits between stations 2 and 3
278 for (const auto& [id, wire] : straws.wires()) {
279 if (wire.station == 2) {
280 magnetStart = std::max(magnetStart, wire.z);
281 } else if (wire.station == 3) {
282 magnetEnd = std::min(magnetEnd, wire.z);
283 }
284 }
285 LineSegment axis;
286 const auto [integral, centre] = fieldIntegral(axis);
287 patRec.emplace(StrawPatRec::Config{}, centre, integral);
288 }
289
291 std::vector<PatRecHit> patRecHits(const std::vector<Int_t>& indices) const;
293 Acts::BoundTrackParameters seed(const TrackCandidate& candidate,
294 const StrawMeasurement& first) const;
297 Int_t fit(const TrackCandidate& candidate,
298 const std::vector<PatRecHit>& hits);
300 std::optional<std::size_t> fitOnce(const std::vector<Int_t>& indices,
301 const Acts::BoundTrackParameters& start);
302
305 std::pair<double, double> fieldIntegral(const LineSegment& line) const {
306 double integral = 0.;
307 double moment = 0.;
308 for (double z = magnetStart; z < magnetEnd; z += kFieldStep) {
309 const double zMid = z + kFieldStep / 2.;
310 const double x[3] = {line.x(zMid), line.y(zMid), zMid};
311 double b[3] = {0., 0., 0.};
312 shipField->Field(x, b);
313 // kGauss to T, cm to m
314 const double bx = 0.1 * b[0] * 0.01 * kFieldStep;
315 integral += bx;
316 moment += bx * zMid;
317 }
318 return {integral, integral != 0. ? moment / integral
319 : 0.5 * (magnetStart + magnetEnd)};
320 }
321
322 const Acts::Surface* surfaceOf(const Acts::SourceLink& sourceLink) const {
323 return measurements.at(sourceLink.get<std::size_t>()).surface;
324 }
325
326 void calibrate(const Acts::GeometryContext& /*gctx*/,
327 const Acts::CalibrationContext& /*cctx*/,
328 const Acts::SourceLink& sourceLink,
329 Trajectory::TrackStateProxy state) const {
330 const auto& measurement = measurements.at(sourceLink.get<std::size_t>());
331 state.allocateCalibrated(1);
332 state.template calibrated<1>()(0) =
333 measurement.sign * measurement.driftRadius;
334 state.template calibratedCovariance<1>()(0, 0) = measurement.variance;
335 state.setProjectorSubspaceIndices(std::array{Acts::eBoundLoc0});
336 state.setUncalibratedSourceLink(Acts::SourceLink(sourceLink));
337 }
338
339 Acts::BoundTrackParameters trackParameters(Int_t track) const {
340 if (track < 0 || static_cast<std::size_t>(track) >= tracks.size()) {
341 throw std::out_of_range("ActsStrawTracker: track index out of range");
342 }
343 return tracks.getTrack(track).createParametersAtReference();
344 }
345
347 std::optional<Acts::BoundTrackParameters> extrapolate(
348 const Extrapolator& propagator, const Acts::BoundTrackParameters& start,
349 const Acts::Surface& target) const {
350 for (const auto direction :
351 {Acts::Direction::Forward(), Acts::Direction::Backward()}) {
352 Extrapolator::Options<> options(gctx, mctx);
353 options.pathLimit = kPathLimit;
354 options.direction = direction;
355 auto result = propagator.propagate(start, target, options);
356 if (result.ok() && result.value().endParameters.has_value()) {
357 return result.value().endParameters.value();
358 }
359 }
360 return std::nullopt;
361 }
362
364 TVirtualMagField* shipField;
365 std::shared_ptr<const ActsShipField> field;
366 double magnetStart = -std::numeric_limits<double>::infinity();
367 double magnetEnd = std::numeric_limits<double>::infinity();
368 std::optional<StrawPatRec> patRec;
369 KalmanFitter fitter;
370 Extrapolator extrapolator;
371 Acts::GainMatrixUpdater updater;
372 Acts::GainMatrixSmoother smoother;
373 Acts::KalmanFitterExtensions<Trajectory> extensions;
374 Acts::GeometryContext gctx =
375 Acts::GeometryContext::dangerouslyDefaultConstruct();
376 Acts::MagneticFieldContext mctx;
377 Acts::CalibrationContext cctx;
378 std::vector<StrawMeasurement> measurements;
379 TrackContainer tracks;
381 std::vector<std::vector<Int_t>> trackMeasurements;
382};
383
384ActsStrawTracker::ActsStrawTracker(const TGeoManager* geometry,
385 TVirtualMagField* field) {
386 if (geometry == nullptr) {
387 throw std::invalid_argument("ActsStrawTracker: geometry is null");
388 }
389 fImpl = std::make_unique<Impl>(*geometry, field);
390}
391
393
395 fImpl->measurements.clear();
396 fImpl->tracks.clear();
397 fImpl->trackMeasurements.clear();
398}
399
400Int_t ActsStrawTracker::AddMeasurement(Int_t detectorId, Double_t driftRadius,
401 Double_t resolution) {
402 const Acts::Surface* surface = fImpl->straws.surface(detectorId);
403 const StrawWire* wire = fImpl->straws.wire(detectorId);
404 if (surface == nullptr || wire == nullptr) {
405 return -1;
406 }
407 const double sigma = resolution * ActsFrame::kShipLength;
408 fImpl->measurements.push_back({surface, wire,
409 std::abs(driftRadius) * ActsFrame::kShipLength,
410 sigma * sigma});
411 return static_cast<Int_t>(fImpl->measurements.size() - 1);
412}
413
415 const std::vector<Int_t>& indices) const {
416 std::vector<PatRecHit> hits;
417 hits.reserve(indices.size());
418 for (const Int_t index : indices) {
419 if (index < 0 || static_cast<std::size_t>(index) >= measurements.size()) {
420 throw std::out_of_range("ActsStrawTracker: measurement out of range");
421 }
422 const auto& m = measurements[index];
423 hits.push_back({index, m.wire, m.driftRadius / ActsFrame::kShipLength,
424 std::sqrt(m.variance) / ActsFrame::kShipLength});
425 }
426 return hits;
427}
428
429Acts::BoundTrackParameters ActsStrawTracker::Impl::seed(
430 const TrackCandidate& candidate, const StrawMeasurement& first) const {
431 const LineSegment& line = candidate.upstream;
432 const double z = first.wire->z;
433 const Acts::Vector3 position =
434 ActsFrame::positionToActs(line.x(z), line.y(z), z);
435 const Acts::Vector3 direction =
436 (ActsFrame::toActsRotation() * Acts::Vector3(line.tx, line.ty, 1.))
437 .normalized();
438 const auto hypothesis = Acts::ParticleHypothesis::muon();
439 const double qOverP = hypothesis.qOverP(
440 candidate.momentum * u::GeV, static_cast<double>(candidate.charge));
441
442 // Local coordinates at the point of closest approach to the first straw
443 const Acts::Surface& surface = *first.surface;
444 const auto intersection =
445 surface.intersect(gctx, position, direction).closest();
446 const Acts::Vector3 onSurface =
447 intersection.isValid() ? intersection.position() : position;
448 auto local = surface.globalToLocal(gctx, onSurface, direction);
449 const Acts::Vector2 localPosition =
450 local.ok() ? local.value() : Acts::Vector2::Zero();
451
452 Acts::BoundVector parameters = Acts::BoundVector::Zero();
453 parameters[Acts::eBoundLoc0] = localPosition[0];
454 parameters[Acts::eBoundLoc1] = localPosition[1];
455 parameters[Acts::eBoundPhi] = Acts::VectorHelpers::phi(direction);
456 parameters[Acts::eBoundTheta] = Acts::VectorHelpers::theta(direction);
457 parameters[Acts::eBoundQOverP] = qOverP;
458 Acts::BoundVector sigmas;
459 sigmas << kSeedSigmaLoc0, kSeedSigmaLoc1, kSeedSigmaAngle, kSeedSigmaAngle,
460 kSeedRelativeSigmaP * std::abs(qOverP), kSeedSigmaTime;
461 const Acts::BoundMatrix covariance = sigmas.cwiseProduct(sigmas).asDiagonal();
462 return Acts::BoundTrackParameters(surface.getSharedPtr(), parameters,
463 covariance, hypothesis);
464}
465
466std::optional<std::size_t> ActsStrawTracker::Impl::fitOnce(
467 const std::vector<Int_t>& indices,
468 const Acts::BoundTrackParameters& start) {
469 std::vector<Acts::SourceLink> sourceLinks;
470 std::vector<const Acts::Surface*> surfaces;
471 for (const Int_t index : indices) {
472 sourceLinks.emplace_back(static_cast<std::size_t>(index));
473 surfaces.push_back(measurements[index].surface);
474 }
475 Acts::PropagatorPlainOptions propagatorOptions(gctx, mctx);
476 Acts::KalmanFitterOptions<Trajectory> options(gctx, mctx, std::cref(cctx),
477 extensions, propagatorOptions,
478 surfaces.front());
479 options.referenceSurfaceStrategy = Acts::TrackExtrapolationStrategy::first;
480
481 const std::size_t nTracksBefore = tracks.size();
482 auto result = fitter.fit(sourceLinks.begin(), sourceLinks.end(), start,
483 options, surfaces, tracks);
484 if (!result.ok() || !result.value().hasReferenceSurface()) {
485 // A failed fit may leave a partial track behind. Drop it, so that track
486 // indices stay contiguous.
487 while (tracks.size() > nTracksBefore) {
488 tracks.removeTrack(tracks.size() - 1);
489 }
490 return std::nullopt;
491 }
492 return result.value().index();
493}
494
496 const std::vector<PatRecHit>& hits) {
497 // The measurements, ordered in z, with the sides of the wires from the
498 // segment fits
499 std::vector<std::pair<double, Int_t>> ordered;
500 for (const LineSegment* segment :
501 {&candidate.upstream, &candidate.downstream}) {
502 for (std::size_t k = 0; k < segment->hits.size(); ++k) {
503 const PatRecHit& hit = hits[segment->hits[k]];
504 measurements[hit.index].sign = segment->signs[k];
505 ordered.emplace_back(hit.wire->z, hit.index);
506 }
507 }
508 std::sort(ordered.begin(), ordered.end());
509 std::vector<Int_t> indices;
510 for (const auto& [z, index] : ordered) {
511 indices.push_back(index);
512 }
513
514 // Momentum from the kink, with the field integral along this track
515 TrackCandidate refined = candidate;
516 const auto [integral, centre] = fieldIntegral(candidate.upstream);
517 const double kink = candidate.downstream.ty - candidate.upstream.ty;
518 if (integral != 0. && kink != 0.) {
519 const LineSegment& up = candidate.upstream;
520 const double pz =
521 std::min(std::abs(kKick * integral / kink), kMaxSeedMomentum);
522 refined.momentum = pz * std::sqrt(1. + up.tx * up.tx + up.ty * up.ty);
523 refined.charge = kink / integral > 0. ? 1 : -1;
524 }
525 Acts::BoundTrackParameters start =
526 seed(refined, measurements[indices.front()]);
527
528 for (int refit = 0;; ++refit) {
529 if (static_cast<int>(indices.size()) < kMinFitMeasurements) {
530 return -1;
531 }
532 const auto track = fitOnce(indices, start);
533 if (!track) {
534 return -1;
535 }
536 // Check each hit against the fitted track: take the side of the wire it
537 // passes on, and drop hits that are too far from it
538 bool changed = false;
539 std::vector<std::pair<double, Int_t>> kept;
540 const auto proxy = tracks.getTrack(*track);
541 for (const auto state : proxy.trackStatesReversed()) {
542 if (!state.hasUncalibratedSourceLink() || !state.hasSmoothed()) {
543 continue;
544 }
545 const auto index = static_cast<Int_t>(
546 state.getUncalibratedSourceLink().template get<std::size_t>());
547 auto& m = measurements[index];
548 const double predicted = state.smoothed()[Acts::eBoundLoc0];
549 const double sigma =
550 std::sqrt(m.variance + state.smoothedCovariance()(Acts::eBoundLoc0,
551 Acts::eBoundLoc0));
552 if (std::abs(std::abs(predicted) - m.driftRadius) >
553 kOutlierPull * sigma) {
554 changed = true;
555 continue;
556 }
557 const int side = predicted >= 0. ? 1 : -1;
558 if (side != m.sign && std::abs(predicted) > std::sqrt(m.variance)) {
559 m.sign = side;
560 changed = true;
561 }
562 kept.emplace_back(m.wire->z, index);
563 }
564 if (!changed || refit == kMaxRefits) {
565 trackMeasurements.push_back(indices);
566 return static_cast<Int_t>(*track);
567 }
568 // Refit from the fitted parameters, with the seed uncertainties so the
569 // previous fit does not bias the next
570 auto params = proxy.createParametersAtReference();
571 start = Acts::BoundTrackParameters(
572 params.referenceSurface().getSharedPtr(), params.parameters(),
573 seed(refined, measurements[indices.front()]).covariance(),
574 params.particleHypothesis());
575 tracks.removeTrack(*track);
576 std::sort(kept.begin(), kept.end());
577 indices.clear();
578 for (const auto& [z, index] : kept) {
579 indices.push_back(index);
580 }
581 }
582}
583
585 auto& impl = *fImpl;
586 std::vector<Int_t> all(impl.measurements.size());
587 std::iota(all.begin(), all.end(), 0);
588 const auto hits = impl.patRecHits(all);
589 const auto candidates = impl.patRec->findTracks(hits);
590
591 // Fit every candidate, then resolve the ambiguities between the fitted
592 // tracks: best first, rejecting tracks that share too many hits with an
593 // accepted one or fit badly
594 struct Fitted {
595 std::size_t candidate;
596 double chi2PerNdf;
597 std::vector<Int_t> measurements;
598 };
599 std::vector<Fitted> fitted;
600 for (std::size_t i = 0; i < candidates.size(); ++i) {
601 const Int_t track = impl.fit(candidates[i], hits);
602 if (track < 0) {
603 continue;
604 }
605 const auto proxy = impl.tracks.getTrack(track);
606 if (proxy.nDoF() > 0) {
607 fitted.push_back(
608 {i, proxy.chi2() / proxy.nDoF(), impl.trackMeasurements[track]});
609 }
610 }
611 const auto rank = [](const Fitted& f) {
612 return f.chi2PerNdf -
613 kTrackHitWeight * static_cast<double>(f.measurements.size());
614 };
615 std::sort(fitted.begin(), fitted.end(),
616 [&](const auto& a, const auto& b) { return rank(a) < rank(b); });
617 std::vector<const Fitted*> accepted;
618 for (const auto& f : fitted) {
619 if (f.chi2PerNdf > kMaxTrackChi2PerNdf ||
620 f.measurements.size() < kMinTrackHits) {
621 continue;
622 }
623 const bool conflict =
624 std::any_of(accepted.begin(), accepted.end(), [&](const Fitted* a) {
625 int shared = 0;
626 for (const Int_t m : f.measurements) {
627 shared +=
628 std::count(a->measurements.begin(), a->measurements.end(), m);
629 }
630 const auto shorter =
631 std::min(f.measurements.size(), a->measurements.size());
632 return shared > kMaxSharedFraction * static_cast<double>(shorter);
633 });
634 if (!conflict) {
635 accepted.push_back(&f);
636 }
637 }
638 // Refit the accepted tracks into an empty container, in candidate order,
639 // so the track indices are contiguous
640 std::sort(accepted.begin(), accepted.end(),
641 [](const Fitted* a, const Fitted* b) {
642 return a->candidate < b->candidate;
643 });
644 impl.tracks.clear();
645 impl.trackMeasurements.clear();
646 for (const Fitted* f : accepted) {
647 impl.fit(candidates[f->candidate], hits);
648 }
649 return GetNTracks();
650}
651
652Int_t ActsStrawTracker::FitCandidate(const std::vector<Int_t>& measurements) {
653 auto& impl = *fImpl;
654 const auto hits = impl.patRecHits(measurements);
655 const auto candidate = impl.patRec->fitCandidate(hits);
656 return candidate ? impl.fit(*candidate, hits) : -1;
657}
658
659std::vector<Int_t> ActsStrawTracker::GetTrackMeasurements(Int_t track) const {
660 if (track < 0 ||
661 static_cast<std::size_t>(track) >= fImpl->trackMeasurements.size()) {
662 throw std::out_of_range("ActsStrawTracker: track index out of range");
663 }
664 return fImpl->trackMeasurements[track];
665}
666
668 return static_cast<Int_t>(fImpl->tracks.size());
669}
670
672 const auto& impl = *fImpl;
673 const auto params = impl.trackParameters(track);
674 const auto proxy = impl.tracks.getTrack(track);
675
676 std::vector<Double_t> residuals;
677 std::vector<Double_t> pulls;
678 for (const auto state : proxy.trackStatesReversed()) {
679 if (!state.hasCalibrated() || !state.hasSmoothed()) {
680 continue;
681 }
682 const double measured = state.template calibrated<1>()(0);
683 const double variance = state.template calibratedCovariance<1>()(0, 0);
684 const double smoothed = state.smoothed()[Acts::eBoundLoc0];
685 const double smoothedVariance =
686 state.smoothedCovariance()(Acts::eBoundLoc0, Acts::eBoundLoc0);
687 const double residual = measured - smoothed;
688 // Residuals of smoothed states have variance V - HCH^T
689 const double residualVariance = variance - smoothedVariance;
690 residuals.push_back(residual / ActsFrame::kShipLength);
691 pulls.push_back(
692 residualVariance > 0. ? residual / std::sqrt(residualVariance) : 0.);
693 }
694 std::reverse(residuals.begin(), residuals.end());
695 std::reverse(pulls.begin(), pulls.end());
696
697 const Acts::Vector3 position =
698 ActsFrame::positionToShip(params.position(impl.gctx));
699 const Acts::Vector3 momentum = ActsFrame::momentumToShip(params.momentum());
700 return RecoTrack(TVector3(position.x(), position.y(), position.z()),
701 TVector3(momentum.x(), momentum.y(), momentum.z()),
702 static_cast<Int_t>(std::lround(params.charge())),
703 upperTriangle<6>(shipCovariance(params, impl.gctx)),
704 proxy.chi2(), proxy.nDoF(), proxy.nMeasurements(),
705 std::move(residuals), std::move(pulls));
706}
707
708Bool_t ActsStrawTracker::FitVertex(const std::vector<Int_t>& tracks,
709 RecoVertex& vertex) const {
710 const auto& impl = *fImpl;
711 if (tracks.size() < 2) {
712 return false;
713 }
714 std::vector<Acts::BoundTrackParameters> fitted;
715 for (const Int_t track : tracks) {
716 fitted.push_back(impl.trackParameters(track));
717 }
718
719 // As in the GenFit vertexing: start from the closest approach of the
720 // straight tracks, then extrapolate them through the field to the plane of
721 // constant z through the current estimate, and take the closest approach
722 // of their tangents there, until it no longer moves
723 Acts::Vector3 point = vertexSeed(fitted, impl.gctx);
724 std::vector<Acts::BoundTrackParameters> atPlane;
725 for (int iteration = 0; iteration < kVertexIterations; ++iteration) {
726 const auto plane = constantZPlane(point);
727 atPlane.clear();
728 for (const auto& params : fitted) {
729 auto extrapolated = impl.extrapolate(impl.extrapolator, params, *plane);
730 if (!extrapolated) {
731 return false;
732 }
733 atPlane.push_back(std::move(*extrapolated));
734 }
735 const Acts::Vector3 next = closestPoint(tangents(atPlane, impl.gctx));
736 if (!next.allFinite()) {
737 return false;
738 }
739 const double step = (next - point).norm();
740 point = next;
741 if (step < kVertexTolerance) {
742 break;
743 }
744 }
745
746 // Covariance of the vertex (and of the DOCA) from the covariances of the
747 // tangents' positions and directions on the plane, by linear propagation
748 // with numerical derivatives
749 const auto base = tangents(atPlane, impl.gctx);
750 const int nPar = 4; // loc0, loc1, phi, theta
751 const int n = static_cast<int>(atPlane.size());
752 Eigen::MatrixXd jacobian = Eigen::MatrixXd::Zero(4, nPar * n);
753 Eigen::MatrixXd covariance = Eigen::MatrixXd::Zero(nPar * n, nPar * n);
754 const bool twoTracks = n == 2;
755 const double baseDoca = twoTracks
756 ? lineDistance(base[0].first, base[0].second,
757 base[1].first, base[1].second)
758 : 0.;
759 for (int i = 0; i < n; ++i) {
760 const auto& cov = atPlane[i].covariance().value();
761 covariance.block(nPar * i, nPar * i, nPar, nPar) =
762 cov.topLeftCorner(nPar, nPar);
763 for (int k = 0; k < nPar; ++k) {
764 const double epsilon = std::max(1e-3 * std::sqrt(cov(k, k)), 1e-12);
765 Acts::BoundVector shifted = atPlane[i].parameters();
766 shifted[k] += epsilon;
767 auto lines = base;
768 lines[i] = tangent(atPlane[i].referenceSurface(), shifted, impl.gctx);
769 jacobian.block(0, nPar * i + k, 3, 1) =
770 (closestPoint(lines) - point) / epsilon;
771 if (twoTracks) {
772 jacobian(3, nPar * i + k) =
773 (lineDistance(lines[0].first, lines[0].second, lines[1].first,
774 lines[1].second) -
775 baseDoca) /
776 epsilon;
777 }
778 }
779 }
780 const Eigen::MatrixXd propagated =
781 jacobian * covariance * jacobian.transpose();
782 const Acts::SquareMatrix3 actsCovariance = propagated.topLeftCorner(3, 3);
783
784 const Acts::RotationMatrix3 rotation = ActsFrame::toShipRotation();
785 const Acts::Vector3 position = ActsFrame::positionToShip(point);
786 const Acts::SquareMatrix3 positionCovariance =
787 rotation * actsCovariance * rotation.transpose() /
789 // Fit quality: the DOCA against its uncertainty for two tracks
790 const double docaVariance = propagated(3, 3);
791 const double chi2 =
792 twoTracks && docaVariance > 0. ? baseDoca * baseDoca / docaVariance : 0.;
793 vertex = RecoVertex(TVector3(position.x(), position.y(), position.z()),
794 upperTriangle<3>(positionCovariance), chi2,
795 twoTracks ? 1. : 2. * n - 3.);
796
797 for (int i = 0; i < n; ++i) {
798 const Acts::Vector3 momentum =
799 ActsFrame::momentumToShip(atPlane[i].momentum());
800 vertex.AddTrack(tracks[i],
801 TVector3(momentum.x(), momentum.y(), momentum.z()),
802 upperTriangle<3>(shipMomentumCovariance(atPlane[i])));
803 }
804 if (twoTracks) {
805 vertex.SetDoca(baseDoca / ActsFrame::kShipLength);
806 }
807 return true;
808}
809
811 const TVector3& hit) const {
812 const auto& impl = *fImpl;
813 // Plane of constant z centred on the hit
814 const auto plane =
815 constantZPlane(ActsFrame::positionToActs(hit.X(), hit.Y(), hit.Z()));
816
817 const auto result =
818 impl.extrapolate(impl.extrapolator, impl.trackParameters(track), *plane);
819 if (!result) {
820 return -1.;
821 }
822 const auto& local = result->parameters();
823 return std::hypot(local[Acts::eBoundLoc0], local[Acts::eBoundLoc1]) /
825}
826
828 return static_cast<Int_t>(fImpl->straws.size());
829}
830
831} // namespace SHiP
constexpr Double_t m
Int_t FitCandidate(const std::vector< Int_t > &measurements)
std::vector< Int_t > GetTrackMeasurements(Int_t track) const
Measurements used in the fit of a track.
std::unique_ptr< Impl > fImpl
Int_t FindTracks()
Find and fit all tracks among the measurements; returns their number.
Int_t AddMeasurement(Int_t detectorId, Double_t driftRadius, Double_t resolution)
RecoTrack GetTrack(Int_t track) const
Double_t DistanceToHit(Int_t track, const TVector3 &hit) const
ActsStrawTracker(const TGeoManager *geometry, TVirtualMagField *field)
Int_t GetNStraws() const
Number of straws found in the geometry.
void ClearEvent()
Forget the measurements and tracks of the previous event.
Bool_t FitVertex(const std::vector< Int_t > &tracks, RecoVertex &vertex) const
void AddTrack(Int_t trackId, const TVector3 &momentum, const std::array< Double_t, 6 > &momentumCovariance)
void SetDoca(Double_t doca)
Distance of closest approach of the two tracks, before the vertex fit.
Definition RecoVertex.h:40
Acts::Vector3 momentumToShip(const Acts::Vector3 &momentum)
Definition ActsFrame.hpp:51
Acts::RotationMatrix3 toShipRotation()
Rotation taking ACTS-frame vectors to the SHiP frame.
Definition ActsFrame.hpp:22
Acts::RotationMatrix3 toActsRotation()
Rotation taking SHiP-frame vectors to the ACTS frame.
Definition ActsFrame.hpp:31
Acts::Vector3 positionToShip(const Acts::Vector3 &position)
Definition ActsFrame.hpp:42
Acts::Vector3 positionToActs(double x, double y, double z)
Definition ActsFrame.hpp:38
constexpr double kShipLength
Length unit of the SHiP frame, in ACTS units.
Definition ActsFrame.hpp:36
None projection()
Acts::GainMatrixSmoother smoother
std::vector< std::vector< Int_t > > trackMeasurements
Measurements used in each track.
std::pair< double, double > fieldIntegral(const LineSegment &line) const
Impl(const TGeoManager &geometry, TVirtualMagField *magField)
std::optional< Acts::BoundTrackParameters > extrapolate(const Extrapolator &propagator, const Acts::BoundTrackParameters &start, const Acts::Surface &target) const
Propagate to target in whichever direction reaches it.
Acts::CalibrationContext cctx
std::vector< PatRecHit > patRecHits(const std::vector< Int_t > &indices) const
Hits for the pattern recognition, from measurement indices.
std::shared_ptr< const ActsShipField > field
void calibrate(const Acts::GeometryContext &, const Acts::CalibrationContext &, const Acts::SourceLink &sourceLink, Trajectory::TrackStateProxy state) const
std::optional< std::size_t > fitOnce(const std::vector< Int_t > &indices, const Acts::BoundTrackParameters &start)
One Kalman fit of the given measurements, appended to the tracks.
const Acts::Surface * surfaceOf(const Acts::SourceLink &sourceLink) const
Int_t fit(const TrackCandidate &candidate, const std::vector< PatRecHit > &hits)
std::optional< StrawPatRec > patRec
Acts::BoundTrackParameters trackParameters(Int_t track) const
Acts::KalmanFitterExtensions< Trajectory > extensions
Acts::BoundTrackParameters seed(const TrackCandidate &candidate, const StrawMeasurement &first) const
Seed for the fit of a candidate, on the surface of its first hit.
Acts::MagneticFieldContext mctx
std::vector< StrawMeasurement > measurements
Acts::GainMatrixUpdater updater
double y(double z) const
double x(double z) const
const StrawWire * wire
A straw wire in the SHiP frame (cm), for pattern recognition.