delphi-edm4hep
DELPHI SDST/FDST -> EDM4hep converter
Loading...
Searching...
No Matches
Vertex.cpp
Go to the documentation of this file.
1// Vertex domain — implementation S4.
2//
3// Reads PSCVTX (reco PV chain + simulation PV chain), PSCBSP (beam spot),
4// PSCRV0 (Delphi-official V0), PSCPHC (photon conversions). All positions
5// converted from DELPHI cm to EDM4hep mm. Vertex-to-Particle relations are
6// collection-specific: the reco PV chain carries DELPHI's outgoing PA
7// assignment, while V0 and photon-conversion vertices carry their fitted
8// daughters.
9
12
13#include "skelana/pscbsp.hpp"
14#include "skelana/pscphc.hpp"
15#include "skelana/pscrv0.hpp"
16#include "skelana/pscvtx.hpp"
17
18#include "phdst/uxcom.hpp" // ph::LQ, ph::IQ, ph::Q (raw ZEBRA store)
19#include "phdst/uxlink.hpp" // ph::LDTOP
20
21#include <edm4hep/MutableVertex.h>
22#include <edm4hep/VertexCollection.h>
23#include <edm4hep/TrackCollection.h>
24#include <edm4hep/TrackState.h>
25#include <podio/Frame.h>
26#include <podio/UserDataCollection.h>
27
28#include <cmath>
29#include <numbers>
30#include <cstdint>
31#include <limits>
32#include <stdexcept>
33#include <string>
34#include <vector>
35
36namespace sk = skelana;
37namespace ph = phdst;
38
39namespace delphi_edm4hep::vertex {
40
41namespace {
42
43// DELPHI cm -> EDM4hep mm conversion. cm^2 -> mm^2 picks up an x100
44// factor; we precompute it once.
45constexpr double kCm2Mm = 10.0;
46constexpr float kCm2Mm2_f = static_cast<float>(kCm2Mm * kCm2Mm);
47
48// Algorithm-type tags on edm4hep::Vertex. Arbitrary but stable across
49// the library; downstream consumers can branch on these.
50constexpr int kAlgoPrimary = 0;
51// Any reconstructed-chain entry that is not the event primary, including a
52// dummy beamspot bucket. The raw status bits distinguish dummy/secondary
53// semantics; algorithmType intentionally makes only the primary/non-primary
54// distinction.
55constexpr int kAlgoNonPrimaryReco = 1;
56constexpr int kAlgoBeamSpot = 2;
57constexpr int kAlgoSimulation = 4;
58constexpr int kAlgoV0 = 10;
59constexpr int kAlgoPhotonConv = 11;
60
61// DELPHI PSCVTX/LPV status bits (KVTX(17,j) / IQ(lpv)). Bit 1 marks a
62// dummy vertex and bit 2 a secondary vertex. A dummy first slot is the
63// unfitted beam-spot bucket and must never be published as the event PV.
64constexpr std::int32_t kStatusDummy = 0x01;
65constexpr std::int32_t kStatusSecondary = 0x02;
66constexpr int kMaxRecoVertices = 150; // DELPHI NVTXMX cap
67
68constexpr bool isPrimaryRecoVertex(bool first, std::int32_t status) {
69 return first &&
70 (status & (kStatusDummy | kStatusSecondary)) == 0;
71}
72
73static_assert(isPrimaryRecoVertex(true, 0));
74static_assert(!isPrimaryRecoVertex(true, kStatusDummy));
75static_assert(!isPrimaryRecoVertex(true, kStatusSecondary));
76static_assert(!isPrimaryRecoVertex(false, 0));
77
78// Fill the geometric content of a Vertex from PSCVTX entry j. Pulls
79// position (cm->mm), covariance (cm^2 -> mm^2), chi^2, and ndf.
80void fillFromPSCVTX(edm4hep::MutableVertex vtx, int j) {
81 vtx.setPosition({
82 static_cast<float>(sk::QVTX(6, j) * kCm2Mm),
83 static_cast<float>(sk::QVTX(7, j) * kCm2Mm),
84 static_cast<float>(sk::QVTX(8, j) * kCm2Mm),
85 });
86 vtx.setChi2(sk::QVTX(9, j));
87 vtx.setNdf (sk::KVTX(4, j));
88 vtx.setCovMatrix({
89 sk::QVTX(10, j) * kCm2Mm2_f, // XX
90 sk::QVTX(11, j) * kCm2Mm2_f, // XY
91 sk::QVTX(12, j) * kCm2Mm2_f, // YY
92 sk::QVTX(13, j) * kCm2Mm2_f, // XZ
93 sk::QVTX(14, j) * kCm2Mm2_f, // YZ
94 sk::QVTX(15, j) * kCm2Mm2_f, // ZZ
95 });
96}
97
98// Fill a Vertex from the raw ZEBRA vertex bank at offset lpv (the
99// LQ(LDTOP-1) chain). This is the DELANA reco PV chain used whenever the
100// SKELANA PSCVTX primary slot is unavailable. Layout mirrors
101// delphi-raw-nanoaod's fillVtx: Q(lpv+5..7) = position cm,
102// Q(lpv+8) = chi2, IQ(lpv+3) = ndf, Q(lpv+9..14) = error matrix.
103void fillFromLDTOP(edm4hep::MutableVertex vtx, int lpv) {
104 vtx.setPosition({
105 static_cast<float>(ph::Q(lpv + 5) * kCm2Mm),
106 static_cast<float>(ph::Q(lpv + 6) * kCm2Mm),
107 static_cast<float>(ph::Q(lpv + 7) * kCm2Mm),
108 });
109 vtx.setChi2(ph::Q(lpv + 8));
110 vtx.setNdf (ph::IQ(lpv + 3));
111 vtx.setCovMatrix({
112 ph::Q(lpv + 9) * kCm2Mm2_f, // XX
113 ph::Q(lpv + 10) * kCm2Mm2_f, // XY
114 ph::Q(lpv + 11) * kCm2Mm2_f, // YY
115 ph::Q(lpv + 12) * kCm2Mm2_f, // XZ
116 ph::Q(lpv + 13) * kCm2Mm2_f, // YZ
117 ph::Q(lpv + 14) * kCm2Mm2_f, // ZZ
118 });
119}
120
121// Does PSCVTX carry a geometrically usable first slot? SKELANA can populate
122// this common for both data and MC; the -999 cm sentinel selects the raw
123// ZEBRA-chain fallback. Dummy status is handled separately below.
124bool pscvtxPrimaryUsable() {
125 return sk::NVTX >= 1 && sk::QVTX(6, 1) > -990.0f;
126}
127
128} // namespace
129
131{
132 // Need tracking output for V0 / PhotonConv -> Particle relations.
133 if (!ctx_.tracking) {
134 // Still emit empty collections so downstream schema is stable.
135 put(edm4hep::VertexCollection{}, "PV", "PrimaryVertex",
137 put(edm4hep::VertexCollection{}, "PV", "Vertices",
139 put(podio::UserDataCollection<std::int32_t>{}, "PV", "Vertices_StatusBits",
141 put(edm4hep::VertexCollection{}, "BSP", "BeamSpot", Provenance::Derived);
142 put(edm4hep::VertexCollection{}, "V0", "V0Candidates",
144 put(edm4hep::VertexCollection{}, "PHC", "PhotonConversions",
146 return;
147 }
148 const auto& tracking = *ctx_.tracking;
149
150 edm4hep::VertexCollection pvCol;
151 edm4hep::VertexCollection vtxCol;
152 podio::UserDataCollection<std::int32_t> statusBits;
153 edm4hep::VertexCollection bspCol;
154 edm4hep::VertexCollection v0Col;
155 edm4hep::VertexCollection phcCol;
156
157 // Helper: attach a VECP-indexed Particle to a Vertex via addToParticles.
158 // Silently no-ops if the VECP entry is out of range or has no matching
159 // emitted Particle.
160 auto add_particle_by_vecp = [&](edm4hep::MutableVertex vtx, int vecp_idx) {
161 const auto& map = tracking.vecp_to_particle;
162 if (vecp_idx < 1 || vecp_idx >= static_cast<int>(map.size())) return;
163 const int p_idx = map[vecp_idx];
164 if (p_idx < 0) return;
165 vtx.addToParticles(tracking.particle_handles[p_idx]);
166 };
167
168 // Reco vertices captured in creation order (== LPV-chain order on both the
169 // PSCVTX and LDTOP paths) + a handle to the standalone PrimaryVertex copy,
170 // so the per-vertex outgoing-particle assignments can be wired in after
171 // creation.
172 std::vector<edm4hep::MutableVertex> recoVtx;
173 edm4hep::MutableVertex pvHandle{};
174 bool havePvHandle = false;
175
176 // ----- Reconstructed PV chain (PSCVTX entries 1..NVTX) -----
177 // Convention: entry j=1 is the primary vertex unless status bit 1 (dummy)
178 // or bit 2 (secondary) is set. The full chain, including dummy entries, is
179 // also emitted into `Vertices` with the raw per-entry status bits.
180 //
181 // PXTAG D⁰/D±/Dₛ-candidate bits (5+) in IQ(LPV) per dst_content.txt
182 // p.3 are preserved verbatim in the `Vertices_StatusBits` UserData
183 // — no semantic interpretation done here. Consumers needing the
184 // per-vertex flavour-tag flags read them off the raw int32.
185 // Primary-vertex position in DELPHI cm, captured for the d0PV/z0PV
186 // impact computation below. Stays sentinel if no usable PV is found.
187 double pv_x_cm = -999.0, pv_y_cm = -999.0, pv_z_cm = -999.0;
188 bool have_pv = false;
189
190 if (pscvtxPrimaryUsable()) {
191 // Use the SKELANA common when its first slot is geometrically available.
192 for (int j = 1; j <= sk::NVTX; ++j) {
193 const std::int32_t status = sk::KVTX(17, j);
194 const bool is_primary = isPrimaryRecoVertex(j == 1, status);
195
196 auto vtx = vtxCol.create();
197 vtx.setPrimary(is_primary);
198 vtx.setAlgorithmType(is_primary ? kAlgoPrimary : kAlgoNonPrimaryReco);
199 fillFromPSCVTX(vtx, j);
200 statusBits.push_back(status);
201 recoVtx.push_back(vtx);
202
203 if (is_primary) {
204 auto pv = pvCol.create();
205 pv.setPrimary(true);
206 pv.setAlgorithmType(kAlgoPrimary);
207 fillFromPSCVTX(pv, j);
208 pv_x_cm = sk::QVTX(6, j); pv_y_cm = sk::QVTX(7, j); pv_z_cm = sk::QVTX(8, j);
209 have_pv = true;
210 pvHandle = pv; havePvHandle = true;
211 }
212 }
213 } else {
214 // PSCVTX is unavailable: read the DELANA reco vertex chain straight from
215 // the raw ZEBRA store at LQ(LDTOP-1).
216 int lpv = (ph::LDTOP > 0) ? ph::LQ(ph::LDTOP - 1) : 0;
217 int count = 0;
218 while (lpv > 0 && count < kMaxRecoVertices) {
219 const std::int32_t status = ph::IQ(lpv);
220 const bool is_primary = isPrimaryRecoVertex(count == 0, status);
221
222 auto vtx = vtxCol.create();
223 vtx.setPrimary(is_primary);
224 vtx.setAlgorithmType(is_primary ? kAlgoPrimary : kAlgoNonPrimaryReco);
225 fillFromLDTOP(vtx, lpv);
226 statusBits.push_back(status);
227 recoVtx.push_back(vtx);
228
229 if (is_primary) {
230 auto pv = pvCol.create();
231 pv.setPrimary(true);
232 pv.setAlgorithmType(kAlgoPrimary);
233 fillFromLDTOP(pv, lpv);
234 pv_x_cm = ph::Q(lpv + 5); pv_y_cm = ph::Q(lpv + 6); pv_z_cm = ph::Q(lpv + 7);
235 have_pv = true;
236 pvHandle = pv; havePvHandle = true;
237 }
238 ++count;
239 lpv = ph::LQ(lpv);
240 }
241 }
242
243 // ----- Wire each reco vertex -> its outgoing-particle assignment -----
244 // DELPHI documents the PA sub-chain at LQ(lpv-1) as outgoing particles,
245 // not as the tracks used by the vertex fit. Keep that faithful meaning here;
246 // AABTAG fit membership is published separately by the Btag writer. The
247 // running pa_idx matches tracking.pa_to_particle (built by the same
248 // forEachPA walk), so each PA maps to its emitted Particle.
249 {
250 const auto& pa2p = tracking.pa_to_particle;
251 int pa_idx = 0;
252 const int ldtop = ph::LDTOP;
253 std::vector<int> lpvChain;
254 for (int lpv = (ldtop > 0) ? ph::LQ(ldtop - 1) : 0;
255 lpv > 0 && lpvChain.size() < static_cast<std::size_t>(kMaxRecoVertices);
256 lpv = ph::LQ(lpv)) {
257 lpvChain.push_back(lpv);
258 }
259 if (lpvChain.size() != recoVtx.size()) {
260 throw std::runtime_error(
261 "PSCVTX/reco vertex count does not match the raw LPV chain; "
262 "refusing to attach outgoing particles by ordinal");
263 }
264 for (std::size_t vi = 0; vi < lpvChain.size(); ++vi) {
265 const int lpv = lpvChain[vi];
266 auto vtx = recoVtx[vi];
267 for (int lpa = ph::LQ(lpv - 1); lpa > 0; lpa = ph::LQ(lpa), ++pa_idx) {
268 if (pa_idx < static_cast<int>(pa2p.size()) && pa2p[pa_idx] >= 0)
269 vtx.addToParticles(tracking.particle_handles[pa2p[pa_idx]]);
270 }
271 if (vtx.isPrimary() && havePvHandle)
272 for (const auto& p : vtx.getParticles()) pvHandle.addToParticles(p);
273 }
274 }
275
276 // ----- Simulation PV (PSCVTX sim region: first entry only) -----
277 // PSCVTX stores reco at 1..NVTXMX and simulation at NVTXMX+1..2*NVTXMX.
278 // The first simulated slot (NVTXMX+1) is the true interaction point. The
279 // others are DELSIM's decay and interaction vertices; they are not emitted
280 // here but give the vertices and endpoints of sDST_STSH_MCParticles
281 // (Truth.cpp).
282 if (sk::NVTXMC >= 1) {
283 const int j = sk::NVTXMX + 1;
284 auto vtx = vtxCol.create();
285 vtx.setPrimary(false);
286 vtx.setAlgorithmType(kAlgoSimulation);
287 fillFromPSCVTX(vtx, j);
288 statusBits.push_back(sk::KVTX(17, j));
289 }
290
291 // ----- Beam spot (PSCBSP) -----
292 // Always one entry. NaN position and covariance when there is no usable
293 // database entry (see internal/BeamSpotStatus.h).
294 {
295 const bool usable = beamspot::positionUsable(sk::IERRBS);
296 const float nan = std::numeric_limits<float>::quiet_NaN();
297 auto pos = [&](int i) {
298 return usable ? sk::XYZBS(i) * static_cast<float>(kCm2Mm) : nan;
299 };
300 auto var = [&](int i) {
301 return usable ? sk::DXYZBS(i) * sk::DXYZBS(i) * kCm2Mm2_f : nan;
302 };
303 auto bs = bspCol.create();
304 bs.setPrimary(false);
305 bs.setAlgorithmType(kAlgoBeamSpot);
306 bs.setPosition({pos(1), pos(2), pos(3)});
307 // PSCBSP stores per-axis sigmas; we diagonalise (no off-diag info).
308 bs.setCovMatrix({var(1), 0.f, var(2), 0.f, 0.f, var(3)});
309 }
310
311 // ----- Delphi-official V0 candidates (PSCRV0) -----
312 // QRV0(8..10) = vertex (X, Y, Z) in cm; KRV0(1..2) = VECP indices of
313 // the two daughters. Surface DELPHI's own V0 classification + the
314 // fitted V0 quantities via Vertex.parameters so analyses can select
315 // K0/Λ without re-deriving them — without these the collection is
316 // just the LOOSE candidate list (S/B ~ 0.9; cutting tag→K0/Λ gives
317 // the clean peaks). parameters layout:
318 // [0] tag KRV0(5): categorical — 0 loose, 1 tight, 2 K0-bkg,
319 // 3 Λ-bkg, 22 K0, 33 Λ (compare by equality, not bitmask)
320 // [1] suggested V0 mass QRV0(19), SIGNED: <0 for antiparticle
321 // (e.g. Λ̄). Take std::abs() for the mass peak; the sign
322 // distinguishes Λ from Λ̄.
323 // [2] V0 momentum |p| QRV0(6) (GeV)
324 // [3] chi2 probability QRV0(7) (PXFVTX fit)
325 // [4] xy flight distance / error QRV0(11)
326 // [5] xy pointing angle to PV QRV0(12) (rad)
327 for (int i = 1; i <= sk::NRV0; ++i) {
328 auto v0 = v0Col.create();
329 v0.setPrimary(false);
330 v0.setAlgorithmType(kAlgoV0);
331 v0.setPosition({
332 sk::QRV0(8, i) * static_cast<float>(kCm2Mm),
333 sk::QRV0(9, i) * static_cast<float>(kCm2Mm),
334 sk::QRV0(10, i) * static_cast<float>(kCm2Mm),
335 });
336 v0.addToParameters(static_cast<float>(sk::KRV0(5, i))); // tag
337 v0.addToParameters(sk::QRV0(19, i)); // suggested mass
338 v0.addToParameters(sk::QRV0(6, i)); // |p|
339 v0.addToParameters(sk::QRV0(7, i)); // chi2 prob
340 v0.addToParameters(sk::QRV0(11, i)); // flight/err
341 v0.addToParameters(sk::QRV0(12, i)); // pointing angle
342 // PSCRV0 doesn't carry a per-V0 cov matrix in the same docs-aligned
343 // slots that PSCVTX does (QRV0(24..33) is the V0 weight matrix in a
344 // different basis — flagged for follow-up).
345 add_particle_by_vecp(v0, sk::KRV0(1, i));
346 add_particle_by_vecp(v0, sk::KRV0(2, i));
347 }
348
349 // ----- Photon conversions (PSCPHC) -----
350 // QPHOC(10..12) = conversion (X, Y, Z) in cm; KPHOC(1..2) = VECP
351 // indices of the e+/e- daughters.
352 for (int i = 1; i <= sk::NPHOC; ++i) {
353 auto phc = phcCol.create();
354 phc.setPrimary(false);
355 phc.setAlgorithmType(kAlgoPhotonConv);
356 phc.setPosition({
357 sk::QPHOC(10, i) * static_cast<float>(kCm2Mm),
358 sk::QPHOC(11, i) * static_cast<float>(kCm2Mm),
359 sk::QPHOC(12, i) * static_cast<float>(kCm2Mm),
360 });
361 add_particle_by_vecp(phc, sk::KPHOC(1, i));
362 add_particle_by_vecp(phc, sk::KPHOC(2, i));
363 }
364
365 // ----- Per-track impact parameters w.r.t. the primary vertex -----
366 // d0PV/z0PV from SKELANA QTRAC(38,39) read 0/-999 in real DATA (the
367 // common is unfilled there), so compute them geometrically from each
368 // track's AtIP perigee and the PV found above. Emitted parallel to
369 // sDST_TRAC_Tracks (same order), in **mm**, LCIO sign convention
370 // (consistent with the TrackState the tracks carry). The track is followed
371 // along its circle to the point closest to the PV; flag is 1 when a PV was
372 // available, 0 otherwise (value -999).
373 // NOTE the dual convention: this <tag>_PV_trackD0PV is the DATA-usable one
374 // (mm, LCIO, parallel to TRAC_Tracks); the Tracking.cpp <tag>_TRAC_d0PV is
375 // QTRAC converted cm->mm, DELPHI sign, also parallel to TRAC_Tracks
376 // (charged-only) but MC-only (QTRAC unfilled on data), so PV_trackD0PV
377 // ~= -1 * TRAC_d0PV on MC (same units now, opposite sign). Do not mix them.
378 podio::UserDataCollection<float> d0pvCol;
379 podio::UserDataCollection<float> z0pvCol;
380 podio::UserDataCollection<std::int32_t> d0pvFlag;
381 {
382 const double px = pv_x_cm * kCm2Mm, py = pv_y_cm * kCm2Mm, pz = pv_z_cm * kCm2Mm;
383 const auto& tracks = frame_.get<edm4hep::TrackCollection>(
384 makeName("TRAC", "Tracks"));
385 for (const auto& trk : tracks) {
386 float d0pv = -999.f, z0pv = -999.f;
387 std::int32_t flag = kImpactMissing;
388 if (have_pv) {
389 // AtIP track state (referencePoint = origin by construction).
390 for (const auto& ts : trk.getTrackStates()) {
391 if (ts.location != edm4hep::TrackState::AtIP) continue;
392 const double s = std::sin(ts.phi), c = std::cos(ts.phi);
393 if (ts.omega == 0.f) { // straight track
394 d0pv = static_cast<float>(ts.D0 + (px * s - py * c));
395 z0pv = static_cast<float>(ts.Z0 - pz + ts.tanLambda * (px * c + py * s));
396 } else {
397 // A straight-line shift is wrong by up to ~1 mm in z0 for tracks
398 // passing far from the origin. Circle centre for the EDM4hep
399 // convention (omega > 0 turns clockwise seen from +z).
400 const double R = 1.0 / ts.omega;
401 const double sgn = std::copysign(1.0, R);
402 const double dx = px - (R - ts.D0) * s;
403 const double dy = py + (R - ts.D0) * c;
404 d0pv = static_cast<float>(R - sgn * std::hypot(dx, dy));
405 const double phiPV = std::atan2(-sgn * dx, sgn * dy);
406 const double dphi = std::remainder(phiPV - ts.phi, 2.0 * std::numbers::pi);
407 z0pv = static_cast<float>(ts.Z0 - ts.tanLambda * R * dphi - pz);
408 }
409 flag = 1;
410 break;
411 }
412 }
413 d0pvCol.push_back(d0pv);
414 z0pvCol.push_back(z0pv);
415 d0pvFlag.push_back(flag);
416 }
417 }
418
419 // ----- Push everything into the frame via the base put() -----
420 put(std::move(d0pvCol), "PV", "Tracks_d0PV", Provenance::Custom);
421 put(std::move(z0pvCol), "PV", "Tracks_z0PV", Provenance::Custom);
422 put(std::move(d0pvFlag), "PV", "Tracks_ImpactFlag", Provenance::Custom);
423 put(std::move(pvCol), "PV", "PrimaryVertex", Provenance::Transcribed);
424 put(std::move(vtxCol), "PV", "Vertices", Provenance::Transcribed);
425 put(std::move(statusBits), "PV", "Vertices_StatusBits", Provenance::Transcribed);
426 put(std::move(bspCol), "BSP", "BeamSpot", Provenance::Derived);
427 put(std::move(v0Col), "V0", "V0Candidates", Provenance::Transcribed);
428 put(std::move(phcCol), "PHC", "PhotonConversions", Provenance::Transcribed);
429}
430
431} // namespace delphi_edm4hep::vertex
std::string makeName(std::string_view bank, std::string_view readable) const
const Coll & put(Coll &&coll, std::string_view bank, std::string_view readable, Provenance prov)
constexpr bool positionUsable(int errorCode)
Definition PaWalk.h:21