FairShip
Loading...
Searching...
No Matches
split_provenance.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"""Provenance of split kaon/pion tracks: which tracks can exist together.
5
6Splitting (exitHadronAbsorber, --kaon-pion-splits) replaces the decay of a
7kaon or pion by weighted alternatives. They are mutually exclusive histories,
8not particles that exist together, but in the MC track tree they look like
9siblings of the split track. ShipMCTrack records them in split sets:
10
11* every track created for one split track shares its split set
12 (GetSplitSet(), -1 if none);
13* the split track and its continuations are the survivor line
14 (kSplitSurvivor), the clones each stand for one of its decays
15 (kSplitDecay), with probability weight / GetSplitWeight();
16* GetSplitWeight() is the weight of the split track before splitting.
17
18Single-particle quantities need none of this: sum weights as usual. Anything
19that combines several tracks of an event does:
20
21* compatible(i, j): can tracks i and j exist in the same real event? Two
22 different decay alternatives of one set cannot. A decay at time t and a
23 track that left the survivor line at time t' can only if t' < t.
24* pair_weight(i, j): the weight that makes pair observables unbiased,
25 w_i w_j / w_a, where w_a is the weight of the line at the point where the
26 two tracks part. It is 0 for incompatible pairs.
27* desplit(rng): draw one outcome per split set with the right probabilities
28 and return which tracks exist in that analog-like event. Each kept track
29 then stands for the event with the weight of its primary. Useful for
30 multiplicities, coincidences, triggers and occupancy, which weights cannot
31 describe.
32
33The weights of a survivor line's secondaries must be the line's weight when
34they were created. Times are the start times of the tracks (ns).
35
36A minimal example::
37
38 prov = SplitProvenance.from_tracks(event.MCTrack)
39 w = prov.pair_weight(mu1, mu2) # 0 if the muons are alternatives
40 keep = prov.desplit(rng).keeps_track # analog-like selection of tracks
41"""
42
43import math
44from dataclasses import dataclass
45
46import numpy as np
47
48NOT_SPLIT, SURVIVOR, DECAY = 0, 1, 2
49K_NO_PROCESS = 44 # TMCProcess kPNoProcess: clones and continuations
50
51
52@dataclass(frozen=True)
53class _Link:
54 """How a lineage passes through one split set."""
55
56 split_set: int
57 role: int
58 member: int # the set member on the lineage
59 branch_time: float # decay: start of the clone; survivor: where the lineage leaves the line
60 branch_weight: float # weight of the line at branch_time (survivor) or of the clone (decay)
61
62
64 """Split-set structure of one event; see the module docstring."""
65
66 def __init__(self, mother, split_set, split_role, split_weight, start_t, weight, proc_id=None):
67 self.mother = np.asarray(mother, dtype=int)
68 self.split_set = np.asarray(split_set, dtype=int)
69 self.split_role = np.asarray(split_role, dtype=int)
70 self.split_weight = np.asarray(split_weight, dtype=float)
71 self.start_t = np.asarray(start_t, dtype=float)
72 self.weight = np.asarray(weight, dtype=float)
73 # Continuations are pushed by the splitting code (no process); the
74 # original split track was made by Geant4.
75 self.continuation = (
76 np.zeros(len(self.mother), dtype=bool)
77 if proc_id is None
78 else (np.asarray(proc_id, dtype=int) == K_NO_PROCESS) & (self.split_role == SURVIVOR)
79 )
80 self.sets = {}
81 for i in np.flatnonzero(self.split_set >= 0):
82 entry = self.sets.setdefault(
83 int(self.split_set[i]), {"W": float(self.split_weight[i]), "decays": [], "survivors": []}
84 )
85 entry["decays" if self.split_role[i] == DECAY else "survivors"].append(int(i))
86 for entry in self.sets.values():
87 entry["decays"].sort(key=lambda c: self.start_t[c])
88 entry["survivors"].sort(key=lambda c: self.start_t[c])
89 entry["stored"] = float(sum(self.weight[c] for c in entry["decays"]))
90 self._lineages = {}
91
92 @classmethod
93 def from_tracks(cls, tracks):
94 """From a sequence of ShipMCTrack (e.g. event.MCTrack)."""
95 rows = [
96 (
97 t.GetMotherId(),
98 t.GetSplitSet(),
99 t.GetSplitRole(),
100 t.GetSplitWeight(),
101 t.GetStartT(),
102 t.GetWeight(),
103 t.GetProcID(),
104 )
105 for t in tracks
106 ]
107 if not rows:
108 return cls([], [], [], [], [], [], [])
109 return cls(*zip(*rows))
110
111 def __len__(self):
112 return len(self.mother)
113
114 # --- structure -------------------------------------------------------------
115
116 def lineage(self, i):
117 """Track i and its ancestors, nearest first."""
118 if i not in self._lineages:
119 line = [i]
120 while self.mother[line[-1]] >= 0 and len(line) <= len(self):
121 line.append(int(self.mother[line[-1]]))
122 self._lineages[i] = line
123 return self._lineages[i]
124
125 def initial_weight(self, i):
126 """Weight of track i when it was created (before any split of its own)."""
127 return self.split_weight[i] if self.split_set[i] >= 0 else self.weight[i]
128
130 """Weight of the survivor line where survivor track a starts."""
131 if not self.continuation[a]:
132 return self.split_weight[a]
133 # A continuation starts where the track it continues ended, with that
134 # track's final weight. If that track was not stored, a's own final
135 # weight is the closest lower bound.
136 earlier = [b for b in self.sets[int(self.split_set[a])]["survivors"] if self.start_t[b] < self.start_t[a]]
137 return self.weight[earlier[-1]] if earlier else self.weight[a]
138
139 def _links(self, i, t_obs, at_start=False):
140 """Split sets on the lineage of i (at most one member each, since members are siblings).
141
142 If i is itself on a survivor line, it is observed at t_obs with its
143 stored weight (the weight at the end of its path, e.g. at the scoring
144 plane where tracks stop), or with at_start at its own start.
145 """
146 line = self.lineage(i)
147 links = {}
148 for k, a in enumerate(line):
149 s = self.split_set[a]
150 if s < 0:
151 continue
152 if self.split_role[a] == DECAY:
153 links[int(s)] = _Link(int(s), DECAY, a, self.start_t[a], self.weight[a])
154 elif k == 0 and at_start:
155 links[int(s)] = _Link(int(s), SURVIVOR, a, self.start_t[a], self._line_weight_at_start(a))
156 elif k == 0:
157 links[int(s)] = _Link(int(s), SURVIVOR, a, t_obs, self.weight[a])
158 else:
159 child = line[k - 1]
160 links[int(s)] = _Link(int(s), SURVIVOR, a, self.start_t[child], self.initial_weight(child))
161 return links
162
163 # --- pairs -------------------------------------------------------------------
164
165 def compatible(self, i, j, t_i=math.inf, t_j=math.inf):
166 """Whether tracks i and j can exist in the same real event.
167
168 t_i, t_j: when a survivor-line track is itself the observed object (e.g.
169 a hit of the split kaon), the time of that observation.
170 """
171 li, lj = self._links(i, t_i), self._links(j, t_j)
172 for s in li.keys() & lj.keys():
173 a, b = li[s], lj[s]
174 if a.member == b.member:
175 continue
176 if a.role == DECAY and b.role == DECAY:
177 return False
178 if a.role == DECAY and not b.branch_time < a.branch_time:
179 return False
180 if b.role == DECAY and not a.branch_time < b.branch_time:
181 return False
182 return True
183
184 def pair_weight(self, i, j, t_i=math.inf, t_j=math.inf):
185 """Weight of the pair (i, j) for unbiased pair observables; 0 if incompatible."""
186 if i == j or not self.compatible(i, j, t_i, t_j):
187 return 0.0
188 line_i, line_j = self.lineage(i), self.lineage(j)
189 on_j = set(line_j)
190 m = next((a for a in line_i if a in on_j), None)
191 if m is None:
192 # No common ancestor: two primaries of the same event.
193 w_a = max(self.initial_weight(line_i[-1]), self.initial_weight(line_j[-1]))
194 return self.weight[i] * self.weight[j] / w_a
195 if m in (i, j):
196 # One is an ancestor of the other: the pair stands for the descendant.
197 return self.weight[j] if m == i else self.weight[i]
198 ci = line_i[line_i.index(m) - 1]
199 cj = line_j[line_j.index(m) - 1]
200 s = self.split_set[ci]
201 if s >= 0 and s == self.split_set[cj]:
202 # The lineages part inside one split set: at a decay on the survivor
203 # line, or where each leaves the survivor line.
204 a, b = self._links(i, t_i)[int(s)], self._links(j, t_j)[int(s)]
205 if a.role == DECAY:
206 w_a = b.branch_weight
207 elif b.role == DECAY:
208 w_a = a.branch_weight
209 else:
210 w_a = max(a.branch_weight, b.branch_weight)
211 else:
212 # The lineages part at m; its weight there is that of the earlier child.
213 w_a = max(self.initial_weight(ci), self.initial_weight(cj))
214 return self.weight[i] * self.weight[j] / w_a
215
216 # --- de-splitting --------------------------------------------------------------
217
218 def desplit(self, rng):
219 """Draw one outcome per split set; see Desplit."""
220 return Desplit(self, rng)
221
222
224 """One analog-like realisation of a split event.
225
226 For every split set one outcome is drawn with probability proportional to
227 its weight: one of the stored decay alternatives, or "something else" (a
228 decay whose clones were pruned, or no decay at all). In the latter case a
229 second number decides how far along the survivor line the track got, so
230 that survivor-line tracks are kept consistently. A kept track stands for
231 the event with the weight of its primary, analog_weight(i).
232 """
233
234 def __init__(self, prov, rng):
235 self.prov = prov
236 self.choice = {}
237 for s, e in prov.sets.items():
238 u = rng.random() * e["W"]
239 chosen, cum = None, 0.0
240 for c in e["decays"]:
241 if u < cum + prov.weight[c]:
242 chosen = c
243 break
244 cum += prov.weight[c]
245 # Given no stored alternative, u - stored is uniform on [0, W - stored).
246 self.choice[s] = (chosen, u - e["stored"])
247 self.keeps_track = np.array([self.keeps(i) for i in range(len(prov))], dtype=bool)
248
249 def _survives_to(self, s, branch_time, branch_weight):
250 prov = self.prov
251 chosen, v = self.choice[s]
252 if chosen is not None:
253 return branch_time < prov.start_t[chosen]
254 later = sum(prov.weight[c] for c in prov.sets[s]["decays"] if prov.start_t[c] > branch_time)
255 return v < branch_weight - later
256
257 def keeps(self, i, t_obs=None):
258 """Whether track i exists, or for t_obs its observation at that time."""
259 links = self.prov._links(i, math.inf, at_start=True) if t_obs is None else self.prov._links(i, t_obs)
260 for s, link in links.items():
261 if link.role == DECAY:
262 if self.choice[s][0] != link.member:
263 return False
264 elif not self._survives_to(s, link.branch_time, link.branch_weight):
265 return False
266 return True
267
268 def keeps_point(self, i, t):
269 """Whether a hit of track i at time t exists (matters for survivor-line tracks)."""
270 return self.keeps(i, t_obs=t)
271
272 def analog_weight(self, i):
273 """Weight a kept track carries in the de-split event: that of its primary."""
274 return self.prov.initial_weight(self.prov.lineage(i)[-1])
_survives_to(self, s, branch_time, branch_weight)
keeps(self, i, t_obs=None)
compatible(self, i, j, t_i=math.inf, t_j=math.inf)
__init__(self, mother, split_set, split_role, split_weight, start_t, weight, proc_id=None)
pair_weight(self, i, j, t_i=math.inf, t_j=math.inf)
_links(self, i, t_obs, at_start=False)