FairShip
Loading...
Searching...
No Matches
strawReco.py
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 Collaboration
3
4"""ACTS-based straw tracker reconstruction utilities.
5
6Fit straw-tube track candidates and vertices with ACTS, and extrapolate
7fitted tracks to SBT hits for veto matching. The fitting itself is done by
8the C++ ``SHiP::ActsStrawTracker``; everything here is in the SHiP frame
9(cm, GeV).
10"""
11
12import logging
13from dataclasses import dataclass
14from itertools import combinations
15
16import ROOT
17from recoConstants import MIN_HITS_PER_TRACK
18
19logger = logging.getLogger(__name__)
20
21# Track-quality cut for the tracks handed to the vertex fit.
22MAX_CHI2_NDF = 25.0
23
24# Distance reported for tracks with no SBT match, as in the GenFit path
25NO_VETO_MATCH = (-1, 99999.0)
26
27
28@dataclass(frozen=True)
30 """A smeared straw hit.
31
32 The drift distance is unsigned: which side of the wire the track passed
33 on is resolved in the fit. The MC track ID is only used for the MC link
34 and for truth seeding.
35 """
36
37 detector_id: int
38 station: int
39 view: int
40 layer: int
41 track_id: int
42 # z of the hit (cm)
43 z: float
44 # Smeared drift distance (cm)
45 drift: float
46
47 @property
48 def layer_key(self) -> tuple[int, int, int]:
49 """The straw layer, which can hold at most one hit of a track."""
50 return (self.station, self.view, self.layer)
51
52
53def make_tracker(geometry, field):
54 """Create the ACTS straw tracker for the loaded geometry and field."""
55 if not hasattr(ROOT.SHiP, "ActsStrawTracker"):
56 raise RuntimeError("FairShip was built without ACTS, so the ACTS track fitter is not available")
57 tracker = ROOT.SHiP.ActsStrawTracker(geometry, field)
58 logger.info("ACTS straw tracker built with %d straws", tracker.GetNStraws())
59 return tracker
60
61
62def runTracking(tracker, candidates, hits, resolution, fit_vertex=True):
63 """Find or fit tracks and, if the event qualifies, fit their vertex.
64
65 With ``candidates`` None, the tracker's own pattern recognition finds
66 the tracks. Otherwise ``candidates`` are dicts with ``indices`` into
67 ``hits`` (sorted by hit z in place), and each is fitted on its own.
68
69 Returns the fitted tracks (``SHiP::RecoTrack``, in the order of the
70 tracker's track indices), the fitted vertices (``SHiP::RecoVertex``) and,
71 per fitted track, the indices into ``hits`` that were used in the fit.
72 """
73 tracker.ClearEvent()
74 measurements = [tracker.AddMeasurement(h.detector_id, h.drift, resolution) for h in hits]
75 hit_of_measurement = {m: i for i, m in enumerate(measurements) if m >= 0}
76
77 if candidates is None:
78 tracker.FindTracks()
79 candidates = []
80 for cand in candidates:
81 cand["indices"].sort(key=lambda i: hits[i].z)
82
83 # The Kalman filter takes at most one measurement per straw layer
84 used = []
85 seen_layers = set()
86 for idx in cand["indices"]:
87 if measurements[idx] < 0:
88 logger.warning("No ACTS surface for straw %d", hits[idx].detector_id)
89 continue
90 if hits[idx].layer_key not in seen_layers:
91 used.append(idx)
92 seen_layers.add(hits[idx].layer_key)
93
94 if len(used) < MIN_HITS_PER_TRACK:
95 logger.debug("Skipping track with too few hits: %d", len(used))
96 continue
97
98 tracker.FitCandidate(ROOT.std.vector("int")([measurements[i] for i in used]))
99
100 tracks = [tracker.GetTrack(i) for i in range(tracker.GetNTracks())]
101 track_hit_indices = [
102 [hit_of_measurement[m] for m in tracker.GetTrackMeasurements(i)] for i in range(tracker.GetNTracks())
103 ]
104
105 good = [
106 i
107 for i, track in enumerate(tracks)
108 if track.nMeasurements() >= MIN_HITS_PER_TRACK
109 and track.nDoF() > 0
110 and track.chi2() / track.nDoF() <= MAX_CHI2_NDF
111 ]
112 # A two-track vertex for every opposite-charge pair of good tracks, as in
113 # the GenFit vertexing
114 vertices = []
115 if fit_vertex:
116 for i, j in combinations(good, 2):
117 if tracks[i].charge() * tracks[j].charge() >= 0:
118 continue
119 vertex = ROOT.SHiP.RecoVertex()
120 if tracker.FitVertex(ROOT.std.vector("int")([i, j]), vertex):
121 vertices.append(vertex)
122 else:
123 logger.debug("Vertex fit failed for tracks %d and %d", i, j)
124
125 return tracks, vertices, track_hit_indices
126
127
128def calculateSBTDOCA(tracker, sbt_digis, selected_indices):
129 """Match fitted tracks to SBT hits.
130
131 Each track is extrapolated to the plane of constant z through every SBT
132 hit. Returns one ``(hitID, distMin)`` per entry of ``selected_indices``,
133 with the distance in cm, to match the GenFit
134 ShipDigiReco.findVetoHitOnTrack; tracks with no match get
135 ``NO_VETO_MATCH``.
136 """
137 hits = [ROOT.TVector3(hit.GetX(), hit.GetY(), hit.GetZ()) for hit in sbt_digis]
138 veto_results = []
139 for track in selected_indices:
140 hitID, distMin = NO_VETO_MATCH
141 for s_idx, hit in enumerate(hits):
142 doca = tracker.DistanceToHit(int(track), hit)
143 if 0 <= doca < distMin:
144 hitID, distMin = s_idx, doca
145 veto_results.append((hitID, distMin))
146 return veto_results
tuple[int, int, int] layer_key(self)
Definition strawReco.py:48
make_tracker(geometry, field)
Definition strawReco.py:53
runTracking(tracker, candidates, hits, resolution, fit_vertex=True)
Definition strawReco.py:62
calculateSBTDOCA(tracker, sbt_digis, selected_indices)
Definition strawReco.py:128