15def find_signal_track(mc_tracks, pdg=None):
16 """Return the index of the signal particle in ``mc_tracks``, or ``None``.
17
18 The signal (HNL, dark photon, dark scalar, ...) does not sit at a fixed
19 position: the generators store a variable amount of the production chain
20 ahead of it, so it can be track 0, 1 or 2 depending on the configuration.
21 Its PDG code is not a reliable handle either, since external-input
22 generators use placeholders. Hence this lookup.
23
24 Parameters
25 ----------
26 mc_tracks : sequence
27 The ``MCTrack`` branch. Indexing and ``len()`` are used rather than
28 ``At()``/``GetEntriesFast()`` so that both ``std::vector<ShipMCTrack>``
29 and ``TClonesArray`` work.
30 pdg : int, optional
31 The signal PDG code, when the caller knows it. Otherwise the signal is
32 inferred from the shape of the generator record, as described below.
33 Pass ``pdg`` where it is available.
34
35 Notes
36 -----
37 A signal event is generated as a single production chain -- optionally a
38 grandmother and a mother, then the signal -- followed by the signal's decay
39 products. So among the tracks the generator put on the stack there is
40 exactly one root, and the signal is the deepest one that has a daughter
41 also on the stack.
42
43 Requiring a single root is what keeps this honest on background samples,
44 where the generator stack is a branching cascade with several roots: those
45 give ``None`` rather than an arbitrary resonance decay.
46 """
47 if pdg is not None:
48 for i in range(len(mc_tracks)):
49 if abs(mc_tracks[i].GetPdgCode()) == abs(pdg):
50 return i
51 return None
52
53 n_tracks = len(mc_tracks)
54 stack = {i for i in range(n_tracks) if mc_tracks[i].GetProcName() == PRIMARY_PROCESS}
55 mothers = {i: mc_tracks[i].GetMotherId() for i in stack}
56
57 roots = [i for i in stack if mothers[i] not in stack]
58 if len(roots) != 1:
59 return None
60
61 with_daughters = {mothers[i] for i in stack if mothers[i] in stack}
62 return max(with_daughters) if with_daughters else None
63
64