delphi-edm4hep
DELPHI SDST/FDST -> EDM4hep converter
Loading...
Searching...
No Matches
Tracking.cpp
Go to the documentation of this file.
1// Tracking domain — implementation S3 (pass-1).
2//
3// Walks the PA chain (LDTOP-1 -> per-PV -> per-PA), emitting:
4// <prefix>_TRAC_Tracks (Track + TrackState[AtIP] + 5x5 helix-basis cov)
5// <prefix>_MAIN_Particles (charged + neutral; 4-mom from sk::VECP)
6// <prefix>_VECP_Particles_SelectionFlag (UserData int32)
7// <prefix>_MAIN_Particles_ReconstructionCode (UserData int32)
8// <prefix>_MAIN_Particles_DetectorMask (UserData int32)
9//
10// Each Track links to the track elements from its PA (see TrackElements).
11// <prefix>_MAIN_Particles_TrackLength (UserData float, cm)
12// <prefix>_QTRAC_Tracks_d0PV / _z0PV / _d0BS (UserData float; QTRAC 38..40)
13//
14// No shape moments, no sigma calibration, no perigee-momentum fallback —
15// bank-truth values only (those custom operations are intentionally
16// dropped).
17
19
22
23#include "skelana/pscbsp.hpp"
24
27#include "skelana/pscvec.hpp"
28#include "skelana/psctra.hpp"
29
30#include <edm4hep/ReconstructedParticleCollection.h>
31#include <edm4hep/TrackCollection.h>
32#include <edm4hep/TrackState.h>
33#include <podio/Frame.h>
34#include <podio/UserDataCollection.h>
35
36#include <array>
37#include <cmath>
38#include <cstdint>
39#include <limits>
40#include <algorithm>
41#include <unordered_map>
42#include <iostream>
43#include <string>
44
45namespace ph = phdst;
46namespace sk = skelana;
47namespace aa = delphi_edm4hep::aabtag;
48
49namespace {
50constexpr double kCm2Mm = 10.0;
51constexpr float kNotMeasured = std::numeric_limits<float>::quiet_NaN();
52} // namespace
53
55
56namespace {
57
58// The DELPHI perigee -> EDM4hep helix conversion (Jacobian push-forward,
59// weight-matrix inversion, TrackState emit) lives in the shared
60// delphi_edm4hep::Helix class (Helix.h) so PA.TRAC and PA.ELTR use one
61// definition.
62
63// Look up the SKELANA VECP index for a given PA's lpa, using the LVECP
64// back-link. The `want_charged` flag gates: a charged-track PA wants
65// VECP(7,*) != 0; a neutral PA wants VECP(7,*) == 0. (PSHCTRECOVER
66// can reclassify mid-PSCEVT; the gate defends against that.)
67// Returns 0 if no match.
68int find_vecp_index(int lpa, bool want_charged)
69{
70 for (int i = sk::LVPART; i <= sk::NVECP; ++i) {
71 if (sk::LVECP(i) != lpa) continue;
72 const int q = static_cast<int>(std::lround(sk::VECP(7, i)));
73 if (want_charged && q != 0) return i;
74 if (!want_charged && q == 0) return i;
75 }
76 return 0;
77}
78
79} // namespace
80
82{
83 // Storage that will be moved into the Frame at the end. Handles taken
84 // before the move remain valid (podio guarantees handle stability
85 // across the collection move).
86 edm4hep::TrackCollection trkCol;
87 edm4hep::ReconstructedParticleCollection pfoCol;
88 podio::UserDataCollection<std::int32_t> lvlockCol;
89 podio::UserDataCollection<std::int32_t> codeCol;
90 podio::UserDataCollection<std::int32_t> detCol;
91 podio::UserDataCollection<float> lengthCol;
92 podio::UserDataCollection<float> d0PvCol;
93 podio::UserDataCollection<float> z0PvCol;
94 podio::UserDataCollection<float> d0BsCol;
95
96 Output result;
97 result.particle_handles.reserve(static_cast<std::size_t>(sk::NVECP + 1));
98 // VECP-index map: size sk::NVECP + 1, all -1 initially. Index 0 unused.
99 result.vecp_to_particle.assign(static_cast<std::size_t>(sk::NVECP + 1), -1);
100 // PA-index map: sized lazily as we walk; -1 entries for PAs we skip.
101 // Reserve a reasonable upper bound to avoid mid-walk reallocation.
102 result.pa_to_particle.reserve(static_cast<std::size_t>(sk::NVECP + 16));
103
104 // Helper: register a freshly-created particle handle in the output
105 // metadata. vecp_i = 0 means "no VECP match" (the handle still goes
106 // into particle_handles, but vecp_to_particle is not updated).
107 // The current paIdx is taken from the surrounding forEachPA scope.
108 auto record_particle = [&](edm4hep::MutableReconstructedParticle pfo,
109 int vecp_i, int paIdx) {
110 const int new_idx = static_cast<int>(result.particle_handles.size());
111 result.particle_handles.push_back(pfo);
112 if (vecp_i >= 1 && vecp_i < static_cast<int>(result.vecp_to_particle.size())) {
113 result.vecp_to_particle[vecp_i] = new_idx;
114 }
115 if (paIdx >= static_cast<int>(result.pa_to_particle.size())) {
116 result.pa_to_particle.resize(static_cast<std::size_t>(paIdx + 1), -1);
117 }
118 result.pa_to_particle[paIdx] = new_idx;
119 };
120
121 // Helper: push the BS/PV-corrected impact-parameter triplet for a
122 // VECP-matched track, or NaN sentinels if vecp_i is 0.
123 //
124 // CONVENTION / FOOTGUN (QTRAC_Tracks_d0PV / _z0PV / _d0BS): sk::QTRAC values
125 // converted cm -> **mm**, DELPHI sign (rho = Vx sinphi - Vy cosphi), parallel
126 // to TRAC_Tracks (charged-only). These are EMPTY (0 / -999) in real DATA --
127 // the SKELANA QTRAC common is only filled in MC. For a data-usable impact
128 // parameter use PV_Tracks_d0PV (Vertex.cpp): geometric, also **mm** but LCIO
129 // sign. Both are filled on MC, where d0 differs by a factor -1 while z0
130 // agrees -- do not mix them.
131 static constexpr float kNaN = std::numeric_limits<float>::quiet_NaN();
132 auto push_qtrac_or_nan = [&](int vecp_i) {
133 if (vecp_i >= 1) {
134 d0PvCol.push_back(sk::QTRAC(38, vecp_i) * 10.f); // cm -> mm
135 z0PvCol.push_back(sk::QTRAC(39, vecp_i) * 10.f); // cm -> mm
136 d0BsCol.push_back(delphi_edm4hep::beamspot::positionUsable(sk::IERRBS)
137 ? sk::QTRAC(40, vecp_i) * 10.f // cm -> mm
138 : kNaN);
139 } else {
140 d0PvCol.push_back(kNaN);
141 z0PvCol.push_back(kNaN);
142 d0BsCol.push_back(kNaN);
143 }
144 };
145
146 using namespace delphi_edm4hep::pawalk;
147
148 // Helper: extend pa_to_particle with -1 so the map stays parallel to
149 // the PA-walk index even when we return early for a skipped PA.
150 auto mark_pa_skipped = [&](int paIdx) {
151 if (paIdx >= static_cast<int>(result.pa_to_particle.size())) {
152 result.pa_to_particle.resize(static_cast<std::size_t>(paIdx + 1), -1);
153 }
154 };
155
156 // Charged PAs whose VECP momentum lookup failed (emitted with zero
157 // 4-momentum). Logged once per event below so the degradation is loud.
158 int n_zero_mom_charged = 0;
159
160 // Per-particle words running parallel to <tag>_MAIN_Particles.
161 //
162 // LVLOCK selection verdict; 0 = selected. Neutrals are selected too
163 // (PSHSNT, with the per-table calorimeter thresholds), so they
164 // carry a real verdict rather than a sentinel.
165 // code PXPHOT reconstruction code, IQ(LPA+3) bits 19-25. SKELANA reads
166 // it to reject VD-only tracks (75 with z, 77 without z, VFT-only
167 // from ISVER 107) and ID+VD-only tracks without z (72).
168 // length track length in cm, the one selection quantity that cannot be
169 // reconstructed from the other emitted collections.
170 auto push_particle_words = [&](int vecp_i, int lpa, int lmain) {
171 lvlockCol.push_back(vecp_i >= 1 ? sk::LVLOCK(vecp_i) : -1);
172 codeCol.push_back((ph::IQ(lpa + 3) >> 18) & 0x7F);
173 detCol.push_back(ph::IQ(lpa + 2));
174 lengthCol.push_back(lmain > 0 ? ph::Q(lmain + 9) : 0.f);
175 };
176
177 // AABTAG's impact parameters, keyed by the PA they belong to. Empty when
178 // AABTAG produced nothing usable for this event.
179 const auto lpa_to_btag = aabtag::lpaToTrack();
180
181 forEachPA([&](int lpa, int paIdx) {
182 // PA.MAIN: per-track summary. Charge code at Q(LMAIN+8):
183 // 0 = neutral, 1 = positive, 2 = negative, 3 = undefined.
184 const int lmain = lphpa("MAIN", lpa);
185 if (lmain <= 0) { mark_pa_skipped(paIdx); return; }
186 const int charge_code = static_cast<int>(std::lround(ph::Q(lmain + 8)));
187
188 if (charge_code == 0) {
189 // ------- Neutral path -------
190 // No PA.TRAC. 4-momentum from VECP. Emit only the Particle.
191 const int vecp_i = find_vecp_index(lpa, /*want_charged=*/false);
192 if (vecp_i < 1) { mark_pa_skipped(paIdx); return; }
193
194 auto npfo = pfoCol.create();
195 npfo.setMomentum({sk::VECP(1, vecp_i),
196 sk::VECP(2, vecp_i),
197 sk::VECP(3, vecp_i)});
198 npfo.setEnergy(sk::VECP(4, vecp_i));
199 npfo.setMass (sk::VECP(5, vecp_i));
200 npfo.setCharge(0.f);
201 record_particle(npfo, vecp_i, paIdx);
202 // d0PV/z0PV/d0BS are parallel to Tracks (charged-only) and so are not
203 // pushed for neutrals; the per-particle words are.
204 push_particle_words(vecp_i, lpa, lmain);
205 return;
206 }
207
208 // ------- Charged path -------
209 // PA.TRAC: perigee (d0, z0, theta, phi, 1/R) at +2..+6;
210 // 15-element lower-tri weight matrix at +7..+21.
211 const int ltrac = lphpa("TRAC", lpa);
212 if (ltrac <= 0) { mark_pa_skipped(paIdx); return; }
213 const float D0_dp = ph::Q(ltrac + 2); // cm
214 const float Z0_dp = ph::Q(ltrac + 3); // cm
215 const float theta_dp = ph::Q(ltrac + 4); // rad
216 const float phi_dp = ph::Q(ltrac + 5); // rad
217 const float invR_dp = ph::Q(ltrac + 6); // 1/cm (signed)
218 std::array<float, 15> Wraw{};
219 for (int k = 0; k < 15; ++k) Wraw[k] = ph::Q(ltrac + 7 + k);
220
221 const auto helix = Helix::fromPerigee(D0_dp, Z0_dp, theta_dp, phi_dp,
222 invR_dp, &Wraw);
223 if (!helix.valid()) {
224 mark_pa_skipped(paIdx);
225 return; // degenerate sin(theta) -> skip
226 }
227
228 auto trk = trkCol.create();
229 trk.addToTrackStates(helix.toTrackState(edm4hep::TrackState::AtIP));
230
231 // AABTAG measures an impact parameter for the subset of tracks it can
232 // use, against its own primary vertex. That is a property of the track,
233 // so it rides here as a state at that vertex rather than in a parallel
234 // array; a track AABTAG skipped simply has no AtVertex state.
235 // Only D0 and Z0 are measured; the rest stay NaN rather than zero, which
236 // would claim a measurement that was never made.
237 if (auto it = lpa_to_btag.find(lpa); it != lpa_to_btag.end()) {
238 trk.addToTrackStates(
239 aabtag::vertexState(it->second, pawalk::trueCharge(lpa)));
240 }
241
242 // Track elements reconstructed from this PA, decoded by
243 // TrackElementsWriter. Linked here, while the track is still mutable.
244 if (ctx_.track_elements) {
245 const auto& te = *ctx_.track_elements;
246 if (paIdx < static_cast<int>(te.pa_to_segments.size())) {
247 for (const auto& seg : te.pa_to_segments[paIdx]) trk.addToTracks(seg);
248 }
249 if (paIdx < static_cast<int>(te.pa_to_plane_hits.size())) {
250 for (const auto& hit : te.pa_to_plane_hits[paIdx]) {
251 trk.addToTrackerHits(hit);
252 }
253 }
254 }
255
256 // Extrapolation states for this PA, decoded by TraxWriter.
257 if (ctx_.trax && paIdx < static_cast<int>(ctx_.trax->pa_to_states.size())) {
258 for (const auto& st : ctx_.trax->pa_to_states[paIdx]) {
259 trk.addToTrackStates(st);
260 }
261 }
262
263 // chi2 / ndf from PA.MAIN. +26/+27 (with VD) preferred, fallback to
264 // +16/+17 (without VD). SKELANA sanitises ndf to [0, 1000].
265 float chi2_vd = ph::Q(lmain + 26);
266 int ndf_vd = static_cast<int>(std::lround(ph::Q(lmain + 27)));
267 if (ndf_vd < 0 || ndf_vd > 1000) ndf_vd = 0;
268 if (ndf_vd > 0 && chi2_vd > 0.f) {
269 trk.setChi2(chi2_vd);
270 trk.setNdf(ndf_vd);
271 } else {
272 float chi2_no_vd = ph::Q(lmain + 16);
273 int ndf_no_vd = static_cast<int>(std::lround(ph::Q(lmain + 17)));
274 if (ndf_no_vd < 0 || ndf_no_vd > 1000) ndf_no_vd = 0;
275 if (ndf_no_vd > 0) {
276 trk.setChi2(chi2_no_vd);
277 trk.setNdf(ndf_no_vd);
278 }
279 }
280
281 // VECP-matched index: required for VECP 4-momentum, LVLOCK, and
282 // QTRAC reads. If no match, fall back to perigee-derived momentum
283 // (with pion mass) — same fallback the current converter uses.
284 const int vecp_i = find_vecp_index(lpa, /*want_charged=*/true);
285
286 // Vertex-Detector hits SKELANA assigned to this track, decoded by
287 // VdHitsWriter and grouped by the same charged-track ordinal. Linked
288 // here, while the track is still mutable.
289 if (ctx_.vd_hits && vecp_i >= 1) {
290 const auto& vd = ctx_.vd_hits->vecp_to_hits;
291 if (vecp_i < static_cast<int>(vd.size())) {
292 for (const auto& hit : vd[static_cast<std::size_t>(vecp_i)]) {
293 trk.addToTrackerHits(hit);
294 }
295 }
296 }
297
298 // Charge from PA.MAIN: 1 positive, 2 negative. Code 3 is DELPHI's "charged,
299 // sign unknown" (the small-angle tracker); DELPHI never assigns it a sign,
300 // so it is NaN here -- never 0, which would read as neutral.
301 float charge = 0.f;
302 if (charge_code == 1) charge = +1.f;
303 else if (charge_code == 2) charge = -1.f;
304 else if (charge_code == 3) charge = kNotMeasured;
305
306 float px = 0.f, py = 0.f, pz = 0.f, E = 0.f, mass = 0.f;
307 if (vecp_i >= 1) {
308 px = sk::VECP(1, vecp_i);
309 py = sk::VECP(2, vecp_i);
310 pz = sk::VECP(3, vecp_i);
311 E = sk::VECP(4, vecp_i);
312 mass = sk::VECP(5, vecp_i);
313 } else {
314 // No VECP match -> this charged Particle keeps zero 4-momentum (the
315 // perigee-momentum fallback is intentionally not implemented; VECP is
316 // authoritative). Count it so the job degrades loudly (logged per event
317 // below) instead of silently emitting an unphysical zero-momentum track.
318 ++n_zero_mom_charged;
319 }
320
321 auto pfo = pfoCol.create();
322 pfo.setMomentum({px, py, pz});
323 pfo.setEnergy(E);
324 pfo.setMass(mass);
325 pfo.setCharge(charge);
326 pfo.addToTracks(trk);
327 record_particle(pfo, vecp_i, paIdx);
328
329 // LVLOCK: per-VECP track-quality bitmask. -1 sentinel if no VECP
330 // match. Stored as int32 so bit 32 (REMCLU overlap) is preserved.
331 push_particle_words(vecp_i, lpa, lmain);
332
333 // BS/PV-corrected impact parameters from sk::QTRAC(38..40, vecp_i).
334 // PSCTRA indexes by the charged-VECP ordinal which matches vecp_i
335 // when IFLODR=1 (charged-first ordering).
336 push_qtrac_or_nan(vecp_i);
337 });
338
339 if (n_zero_mom_charged > 0) {
340 std::cerr << "delphi_edm4hep::tracking: WARNING: " << n_zero_mom_charged
341 << " charged PFO(s) had no VECP momentum match and were emitted"
342 << " with zero 4-momentum in this event\n";
343 }
344
345 // Push all collections into the Frame via the base class's put().
346 // Handles in `result` remain valid afterwards.
347 put(std::move(trkCol), "TRAC", "Tracks", Provenance::Derived);
348 put(std::move(pfoCol), "MAIN", "Particles", Provenance::Derived);
349 put(std::move(lvlockCol), "VECP", "Particles_SelectionFlag", Provenance::Derived);
350 put(std::move(codeCol), "MAIN", "Particles_ReconstructionCode", Provenance::Transcribed);
351 put(std::move(detCol), "MAIN", "Particles_DetectorMask", Provenance::Transcribed);
352 put(std::move(lengthCol), "MAIN", "Particles_TrackLength", Provenance::Transcribed);
353 put(std::move(d0PvCol), "QTRAC", "Tracks_d0PV", Provenance::Derived);
354 put(std::move(z0PvCol), "QTRAC", "Tracks_z0PV", Provenance::Derived);
355 put(std::move(d0BsCol), "QTRAC", "Tracks_d0BS", Provenance::Derived);
356
357 // Hand off to downstream writers via the shared context.
358 ctx_.tracking = std::move(result);
359}
360
361} // namespace delphi_edm4hep::tracking
const Coll & put(Coll &&coll, std::string_view bank, std::string_view readable, Provenance prov)
static Helix fromPerigee(float d0, float z0, float theta, float phi, float invR, const std::array< float, 15 > *W=nullptr)
Definition Helix.cpp:109
std::unordered_map< int, int > lpaToTrack()
edm4hep::TrackState vertexState(int i, int charge)
constexpr bool positionUsable(int errorCode)
void forEachPA(F &&fn)
Definition PaWalk.h:67
int trueCharge(int lpa)
Definition PaWalk.h:50
int lphpa(const char *iddp, int lpa, int nump=0)
Definition PaWalk.h:34
Definition PaWalk.h:21
std::vector< int > pa_to_particle
std::vector< edm4hep::MutableReconstructedParticle > particle_handles
std::vector< int > vecp_to_particle