delphi-edm4hep
DELPHI SDST/FDST -> EDM4hep converter
Loading...
Searching...
No Matches
Truth.cpp
Go to the documentation of this file.
1// Truth domain — TruthGenWriter + TruthRecoLinkWriter.
2//
3// TruthGenWriter emits the simulation record of the STSH bank: the generator
4// event (PSCLUJ, filled by PSHLUJ on sDST or PSFLUJ on fDST per bank-presence
5// gating) and the particles the detector simulation added (the simulated
6// tracks of PSCVEC / PSCTBL without a generator line). TruthRecoLinkWriter
7// links reconstructed particles to them through the exact PSCTBL tables.
8
11
12#include "phdst/uxcom.hpp"
13#include "phdst/uxlink.hpp"
14#include "skelana/mtrack.hpp"
15#include "skelana/pscluj.hpp"
16#include "skelana/psctbl.hpp"
17#include "skelana/pscvec.hpp"
18#include "skelana/pscvtx.hpp"
19
20#include <edm4hep/MCParticleCollection.h>
21#include <edm4hep/RecoMCParticleLinkCollection.h>
22
23#include <algorithm>
24#include <array>
25#include <cmath>
26#include <iostream>
27#include <optional>
28#include <set>
29#include <vector>
30
31// JETSET helpers. Charges via LUCHGE in units of e/3 (exhaustive PDG
32// coverage; replaces the 16-entry whitelist of the legacy code).
33extern "C" {
34 void pshluj_();
35 void psfluj_();
36 int luchge_(int* kf);
37}
38
39namespace ph = phdst;
40namespace sk = skelana;
41
42namespace delphi_edm4hep::truth {
43
44namespace {
45
46inline float charge_from_pdg(int pdg) {
47 return static_cast<float>(luchge_(&pdg)) / 3.0f;
48}
49
50// Gate the PSCLUJ unpacker on bank presence in the LDTOP chain, invoke
51// the sDST or fDST routine, return sk::NP. (full-DST SH chain at
52// LDTOP-3, sDST condensed LU at LDTOP-28/-29.)
53int unpack_lujets() {
54 sk::NP = 0;
55 if (ph::LDTOP <= 0) return 0;
56 const bool short_sim = (ph::IQ(ph::LDTOP - 2) > 28)
57 && (ph::LQ(ph::LDTOP - 28) != 0)
58 && (ph::LQ(ph::LDTOP - 29) != 0);
59 const bool full_sim = (ph::LQ(ph::LDTOP - 3) != 0);
60 if (short_sim) pshluj_();
61 else if (full_sim) psfluj_();
62 return sk::NP;
63}
64
65constexpr double kCm2Mm = 10.0;
66
67// Per-event MC truth interaction point (sim-PV), in mm. Handles BOTH sim
68// layouts: shortDST (LPVS at LDTOP-28, first sim-PV x/y/z at Q(ip+4..6) cm) and
69// fullDST (LDTOP-3 -> LSH -> LST -> LPV, x/y/z at Q(lpv+5..7) cm); same decode
70// as delphi-raw-nanoaod fillSimPV. Returns nullopt when no sim banks are present
71// (real data / missing bank). Used as the production vertex of generator-only
72// entries, which DELSIM gives no vertex of their own.
73std::optional<std::array<double, 3>> read_sim_pv_mm() {
74 if (ph::LDTOP <= 0) return std::nullopt;
75 // shortDST sim layout: LPVS at LDTOP-28, x/y/z at +4/+5/+6 (cm). Guard the
76 // down-link index exactly as unpack_lujets() does -- LDTOP-28 is only a valid
77 // link when the LDTOP bank has >28 down-links -- so this is safe on real data
78 // (and on fullDST, where it falls through to the LSH-chain walk below).
79 if (ph::IQ(ph::LDTOP - 2) > 28) {
80 const int lpvs = ph::LQ(ph::LDTOP - 28);
81 if (lpvs > 0) {
82 const int npvs = ph::IQ(lpvs + 1);
83 if (npvs >= 1) {
84 const int ip = lpvs + 1 + npvs;
85 return std::array<double, 3>{ph::Q(ip + 4) * kCm2Mm,
86 ph::Q(ip + 5) * kCm2Mm,
87 ph::Q(ip + 6) * kCm2Mm};
88 }
89 }
90 }
91 // fullDST sim layout (our DELSIM SDST takes this path): walk the LSH chain at
92 // LDTOP-3, first SH with Q(lsh+1)!=0 -> LST at LSH-4 -> LPV at LST+1; x/y/z at
93 // LPV+5/+6/+7 (cm). Same decode as raw-nanoaod fillSimPV (PSFLUJ, skelana.car ~L7088).
94 for (int lsh = ph::LQ(ph::LDTOP - 3); lsh > 0; lsh = ph::LQ(lsh)) {
95 if (std::lround(ph::Q(lsh + 1)) == 0) continue;
96 const int lst = ph::LQ(lsh - 4);
97 if (lst <= 0) continue;
98 const int lpv = ph::LQ(lst + 1);
99 if (lpv <= 0) continue;
100 return std::array<double, 3>{ph::Q(lpv + 5) * kCm2Mm,
101 ph::Q(lpv + 6) * kCm2Mm,
102 ph::Q(lpv + 7) * kCm2Mm};
103 }
104 return std::nullopt;
105}
106
107// The simulated tracks (ST) SKELANA unpacks from STSH: track number 1..NST.
108// Their momenta sit in the second half of VECP, their vertices in the
109// simulated half of QVTX, and PSCTBL relates them to the generator lines.
110struct SimulatedTrack {
111 int number;
112 float vec(int word) const { return sk::VECP(word, sk::MTRACK + number); }
113 int generatorLine() const { return sk::ISTLU(number); } // 0: made by DELSIM
114 int originVertex() const { return sk::ISTVX(1, number); }
115 int endVertex() const { return sk::ISTVX(2, number); } // 0: none
116};
117
118// The second half of VECP holds MTRACK simulated tracks.
119int simulatedTrackCount() {
120 if (sk::NST() > sk::MTRACK) {
121 static bool warned = false;
122 if (!warned) {
123 std::cerr << "delphi_edm4hep::truth: " << sk::NST()
124 << " simulated tracks, only the first " << sk::MTRACK
125 << " fit SKELANA's track vector\n";
126 warned = true;
127 }
128 return sk::MTRACK;
129 }
130 return sk::NST();
131}
132
133// Position (mm) of simulated vertex k; empty when k is not a vertex.
134std::optional<edm4hep::Vector3d> simulatedVertexPosition(int k) {
135 if (k < 1 || k > sk::NVTXMX) return std::nullopt;
136 const int column = sk::NVTXMX + k;
137 return edm4hep::Vector3d{sk::QVTX(6, column) * kCm2Mm,
138 sk::QVTX(7, column) * kCm2Mm,
139 sk::QVTX(8, column) * kCm2Mm};
140}
141
142// The simulated track entering simulated vertex k; 0 when none.
143int trackEnteringVertex(int k) {
144 if (k < 1 || k > sk::NVTXMX) return 0;
145 return sk::KVTX(2, sk::NVTXMX + k);
146}
147
148// PDG code of a simulated track's DELPHI particle code. A code outside the
149// table gives 0 and is reported once.
150int pdgOfSimulatedTrack(const SimulatedTrack& track) {
151 const int delphiCode = static_cast<int>(std::lround(track.vec(8)));
152 const int pdg = pdgFromDelphiCode(delphiCode);
153 static std::set<int> reported;
154 if (pdg == 0 && reported.insert(delphiCode).second) {
155 std::cerr << "delphi_edm4hep::truth: DELPHI particle code " << delphiCode
156 << " has no PDG code; written as 0\n";
157 }
158 return pdg;
159}
160
161} // namespace
162
163// ---------------------------------------------------------------------------
165 GenParticleResult result;
166
167 const int nGen = unpack_lujets();
168 edm4hep::MCParticleCollection mc;
169 result.handles.reserve(static_cast<std::size_t>(nGen));
170
171 // Gated on nGen>=1 so real data (no LUJETS) never reads sim banks.
172 const auto spv = nGen >= 1 ? read_sim_pv_mm() : std::nullopt;
173
174 // DELSIM records a production vertex (cm, in the frame of the
175 // reconstruction; PSFLUJ, skelana.car:7125-7127; PSHLUJ, skelana.car:
176 // 5390-5392) only for the particles it tracked through the detector.
177 // Generator-only entries -- partons, resonances and the products of decays
178 // done by the generator -- have VP = 0; they are placed from the decay chain
179 // below. LUJETS lists every parent before its daughters.
180 using Position = std::optional<std::array<double, 3>>;
181 std::vector<Position> productionPoint(nGen + 1), decayPoint(nGen + 1);
182 for (int i = 1; i <= nGen; ++i) {
183 const bool trackedByDelsim =
184 sk::VP(i, 1) != 0.f || sk::VP(i, 2) != 0.f || sk::VP(i, 3) != 0.f;
185 if (trackedByDelsim)
186 productionPoint[i] = {sk::VP(i, 1) * kCm2Mm, sk::VP(i, 2) * kCm2Mm,
187 sk::VP(i, 3) * kCm2Mm};
188 }
189
190 // Decay point of each particle: where one of its tracked daughters starts.
191 // A generator-only daughter is a resonance that decays where it is made, so
192 // its own decay point stands in when no daughter was tracked. Walking the
193 // record backwards visits every daughter before its parent.
194 for (int daughter = nGen; daughter >= 1; --daughter) {
195 const int parent = sk::KP(daughter, 3);
196 if (parent < 1 || parent >= daughter) continue;
197 if (productionPoint[daughter]) decayPoint[parent] = productionPoint[daughter];
198 else if (!decayPoint[parent]) decayPoint[parent] = decayPoint[daughter];
199 }
200
201 // A generator-only particle starts where its parent decayed; failing that,
202 // where its parent started; with no parent, at the simulated primary vertex.
203 for (int particle = 1; particle <= nGen; ++particle) {
204 if (productionPoint[particle]) continue;
205 const int parent = sk::KP(particle, 3);
206 if (parent < 1 || parent >= particle) productionPoint[particle] = spv;
207 else if (decayPoint[parent]) productionPoint[particle] = decayPoint[parent];
208 else productionPoint[particle] = productionPoint[parent];
209 }
210
211 // First pass: per-LU-index handle creation. KP(i,1)=status, KP(i,2)=PDG,
212 // PP(i,1..3)=p, PP(i,5)=mass, VP(i,1..3)=production vertex (cm).
213 for (int i = 1; i <= nGen; ++i) {
214 auto mp = mc.create();
215 mp.setPDG(sk::KP(i, 2));
216 mp.setGeneratorStatus(static_cast<std::int16_t>(sk::KP(i, 1)));
217 mp.setMomentum({sk::PP(i, 1), sk::PP(i, 2), sk::PP(i, 3)});
218 mp.setMass(sk::PP(i, 5));
219 if (const auto& v = productionPoint[i]) mp.setVertex({(*v)[0], (*v)[1], (*v)[2]});
220 mp.setCharge(charge_from_pdg(sk::KP(i, 2)));
221 result.handles.push_back(mp);
222 }
223
224 // Second pass: parent/daughter graph (parent edges only; daughters
225 // are recoverable by reverse traversal).
226 // Endpoint (decay vertex): a decay's real daughters sit at the (possibly
227 // displaced) decay vertex, but LUJETS documentation-copy daughters (status 21)
228 // sit at the PARENT's production vertex. Pick the MOST-displaced daughter so a
229 // coincident doc-copy can't clobber a real displaced vertex -- the previous
230 // "last-daughter-wins" silently dropped ~40% of displaced B/D endpoints. A
231 // particle whose only daughters are coincident gets a zero-flight endpoint at
232 // its own vertex (correct); stable particles (no daughters) keep the default.
233 std::vector<double> best_disp2(static_cast<std::size_t>(nGen), -1.0);
234 for (int i = 1; i <= nGen; ++i) {
235 const int parent_lu = sk::KP(i, 3);
236 if (parent_lu >= 1 && parent_lu <= nGen) {
237 const std::size_t child = static_cast<std::size_t>(i - 1);
238 const std::size_t pidx = static_cast<std::size_t>(parent_lu - 1);
239 result.handles[child].addToParents(result.handles[pidx]);
240 result.handles[pidx].addToDaughters(result.handles[child]);
241 const auto pv = result.handles[pidx].getVertex();
242 const auto cv = result.handles[child].getVertex();
243 const double dx = cv.x - pv.x, dy = cv.y - pv.y, dz = cv.z - pv.z;
244 const double d2 = dx * dx + dy * dy + dz * dz;
245 if (d2 > best_disp2[pidx]) {
246 result.handles[pidx].setEndpoint(cv);
247 best_disp2[pidx] = d2;
248 }
249 }
250 }
251
252 // MCParticle of each simulated track, by track number (entry 0 unused).
253 // A track with a generator line is that line's particle; a track made by
254 // DELSIM (decay products, interactions in the detector) gets a new one.
255 std::vector<edm4hep::MutableMCParticle> particleOfTrack(simulatedTrackCount() + 1);
256 for (int number = 1; number <= simulatedTrackCount(); ++number) {
257 const SimulatedTrack track{number};
258 const int line = track.generatorLine();
259 if (line >= 1 && line <= nGen) {
260 particleOfTrack[number] = result.handles[line - 1];
261 continue;
262 }
263 auto particle = mc.create();
264 particle.setPDG(pdgOfSimulatedTrack(track));
265 particle.setGeneratorStatus(0);
266 particle.setCreatedInSimulation(true);
267 particle.setMomentum({track.vec(1), track.vec(2), track.vec(3)});
268 particle.setMass(track.vec(5));
269 particle.setCharge(track.vec(7));
270 const auto origin = simulatedVertexPosition(track.originVertex());
271 if (origin) {
272 particle.setVertex(*origin);
273 }
274 particleOfTrack[number] = particle;
275 }
276
277 // Where DELSIM ended a track (decay or interaction), which replaces the
278 // estimate from generator daughters above and is the only one for the
279 // particles DELSIM decays (K0S, Lambda, ...). Who made each DELSIM
280 // particle: the track entering its origin vertex.
281 for (int number = 1; number <= simulatedTrackCount(); ++number) {
282 const SimulatedTrack track{number};
283 auto& particle = particleOfTrack[number];
284 const auto end = simulatedVertexPosition(track.endVertex());
285 if (end) {
286 particle.setEndpoint(*end);
287 }
288 if (track.generatorLine() >= 1) continue;
289 const int parentTrack = trackEnteringVertex(track.originVertex());
290 if (parentTrack < 1 || parentTrack > simulatedTrackCount()) continue;
291 particle.addToParents(particleOfTrack[parentTrack]);
292 particleOfTrack[parentTrack].addToDaughters(particle);
293 }
294 result.particleOfSimulatedTrack = std::move(particleOfTrack);
295
296 put(std::move(mc), "STSH", "MCParticles", Provenance::Derived);
297 ctx_.gen_truth = std::move(result);
298}
299
300// ---------------------------------------------------------------------------
302 edm4hep::RecoMCParticleLinkCollection links;
303
304 // Need both upstream writers' outputs.
305 if (!ctx_.gen_truth || !ctx_.tracking) {
306 put(std::move(links), "TBL", "RecoToMC", Provenance::Transcribed); // emit empty + return
307 return;
308 }
309 const auto& gen = *ctx_.gen_truth;
310 const auto& tracking = *ctx_.tracking;
311
312 // PSCTBL.NPA = # PA particles = VECP entries. For each VECP index j:
313 // simulatedTrack = IPAST(j) (0 if no simulated track)
314 // particle_idx = vecp_to_particle[j] (-1 if Tracking dropped it)
315 // The simulated track's MCParticle is its generator particle, or the one
316 // DELSIM created (e.g. a Lambda decay product).
317 const int nPA = sk::NPA();
318 const auto& v2p = tracking.vecp_to_particle;
319 const auto& particleOfTrack = gen.particleOfSimulatedTrack;
320
321 for (int j = 1; j <= nPA; ++j) {
322 if (j >= static_cast<int>(v2p.size())) break;
323 const int particle_idx = v2p[j];
324 if (particle_idx < 0) continue;
325 const int simulatedTrack = sk::IPAST(j);
326 if (simulatedTrack < 1) continue;
327 if (simulatedTrack >= static_cast<int>(particleOfTrack.size())) continue;
328
329 auto link = links.create();
330 link.setFrom(tracking.particle_handles[particle_idx]);
331 link.setTo (particleOfTrack[simulatedTrack]);
332 link.setWeight(1.0f);
333 }
334
335 put(std::move(links), "TBL", "RecoToMC", Provenance::Transcribed);
336}
337
338} // namespace delphi_edm4hep::truth
int luchge_(int *kf)
void pshluj_()
void psfluj_()
const Coll & put(Coll &&coll, std::string_view bank, std::string_view readable, Provenance prov)
int pdgFromDelphiCode(int delphiCode)
Definition PaWalk.h:21
std::vector< edm4hep::MutableMCParticle > handles
Definition TruthData.h:21
std::vector< edm4hep::MutableMCParticle > particleOfSimulatedTrack
Definition TruthData.h:24