FairShip
Loading...
Searching...
No Matches
analysis_toolkit.py
Go to the documentation of this file.
1#!/usr/bin/env python
2# SPDX-License-Identifier: LGPL-3.0-or-later
3# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
4
5"""Toolkit for Analysis."""
6
7import numpy as np
8import pythia8_conf
9import ROOT
10import shipunit as u
11from ShipGeoConfig import load_from_root_file
12from shipTrackAccess import get_tracks, track_info, uses_acts
13from tabulate import tabulate
14
15
17 """Class to perform various selection checks on the candidate."""
18
19 def __init__(self, geo_file) -> None:
20 """Initialize the selection_check class with geometry and configuration."""
21 self.geometry_manager = geo_file.Get("FAIRGeom")
22 self.ship_geo = load_from_root_file(geo_file, "ShipGeo")
23
24 # Decay vessel entrance, from the configuration stored with the geometry
25 # Includes fallback for older geometries
26 dv = self.ship_geo.decayVolume
27 if "z0" in dv: # Newer geometries
28 self.decay_vessel_z0 = dv.z0
29 else: # Geometries written before decayVolume.z0 existed: the vessel starts at the upstream end of Tub1
30 self.decay_vessel_z0 = self.ship_geo.Chamber1.z - self.ship_geo.chambers.Tub1length
31
32 def access_event(self, tree) -> None:
33 """Access event data."""
34 self.tree = tree
35 self.acts_tracks = uses_acts(tree)
36
37 def define_candidate_time(self, candidate):
38 """Calculate time associated with the candidate decay vertex using strawtubes MCPoint info."""
39 t0 = self.tree.ShipEventHeader.GetEventTime()
40 candidate_pos = ROOT.TVector3()
41 candidate.GetVertex(candidate_pos)
42
43 d1, d2 = candidate.GetDaughter(0), candidate.GetDaughter(1)
44 d1_mc, d2_mc = self.tree.fitTrack2MC[d1], self.tree.fitTrack2MC[d2]
45
46 time_vtx_from_strawhits = []
47
48 for hit in self.tree.strawtubesPoint:
49 if not (int(str(hit.GetDetectorID())[:1]) == 1 or int(str(hit.GetDetectorID())[:1]) == 2):
50 continue
51
52 if not (hit.GetTrackID() == d1_mc or hit.GetTrackID() == d2_mc):
53 continue
54
55 t_straw = hit.GetTime()
56
57 dist = np.sqrt(
58 (candidate_pos.X() - hit.GetX()) ** 2
59 + (candidate_pos.Y() - hit.GetY()) ** 2
60 + (candidate_pos.Z() - hit.GetZ()) ** 2
61 ) # distance to the vertex in cm
62
63 d_mom = self.tree.MCTrack[hit.GetTrackID()].GetP() / u.GeV
64 mass = self.tree.MCTrack[hit.GetTrackID()].GetMass()
65 v = u.c_light * d_mom / np.sqrt(d_mom**2 + (mass) ** 2)
66
67 t_vertex = t_straw - (dist / v)
68
69 time_vtx_from_strawhits.append(t_vertex)
70
71 if not time_vtx_from_strawhits:
72 return float("nan") # no matching straw hits, vertex time cannot be computed
73
74 t_vtx = np.average(time_vtx_from_strawhits) + t0
75
76 return t_vtx # units in ns
77
78 def impact_parameter(self, candidate):
79 """Calculate the impact parameter of the candidate relative to (0,0,target.z0)."""
80 candidate_pos = ROOT.TVector3()
81 candidate.GetVertex(candidate_pos)
82
83 candidate_mom = ROOT.TLorentzVector()
84 candidate.Momentum(candidate_mom)
85 target_point = ROOT.TVector3(0, 0, self.ship_geo.target.z0)
86
87 projection_factor = 0
88 if hasattr(candidate_mom, "P"):
89 P = candidate_mom.P()
90 else:
91 P = candidate_mom.Mag()
92 for i in range(3):
93 projection_factor += candidate_mom(i) / P * (target_point(i) - candidate_pos(i))
94
95 dist = 0
96 for i in range(3):
97 dist += (target_point(i) - candidate_pos(i) - projection_factor * candidate_mom(i) / P) ** 2
98 dist = ROOT.TMath.Sqrt(dist)
99
100 return dist # in cm
101
102 def dist_to_innerwall(self, candidate) -> float | int:
103 """Calculate the minimum distance(in XY plane) of the candidate decay vertex to the inner wall of the decay vessel. If outside the decay volume, return 0."""
104 candidate_pos = ROOT.TVector3()
105 candidate.GetVertex(candidate_pos)
106 position = (candidate_pos.X(), candidate_pos.Y(), candidate_pos.Z())
107
108 nsteps = 8
109 dalpha = 2 * ROOT.TMath.Pi() / nsteps
110 min_distance = float("inf")
111
112 node = self.geometry_manager.FindNode(*position)
113 if not node:
114 return 0 # is outside the decay volume
115
116 # Loop over directions in the XY plane
117 for n in range(nsteps):
118 alpha = n * dalpha
119 direction = (
120 ROOT.TMath.Sin(alpha),
121 ROOT.TMath.Cos(alpha),
122 0.0,
123 ) # Direction vector in XY plane
124 self.geometry_manager.InitTrack(*position, *direction)
125 if not self.geometry_manager.FindNextBoundary():
126 continue
127 # Get the distance to the boundary and update the minimum distance
128 distance = self.geometry_manager.GetStep()
129 min_distance = min(min_distance, distance)
130
131 return min_distance
132
133 def dist_to_vesselentrance(self, candidate):
134 """Calculate the distance of the candidate decay vertex to the entrance of the decay vessel."""
135 candidate_pos = ROOT.TVector3()
136 candidate.GetVertex(candidate_pos)
137 return candidate_pos.Z() - self.decay_vessel_z0
138
139 def nDOF(self, candidate):
140 """Return the number of degrees of freedom (nDOF) for the particle's daughter tracks."""
141 nmeas = []
142 t1, t2 = candidate.GetDaughter(0), candidate.GetDaughter(1)
143
144 tracks = get_tracks(self.tree)
145 for tr in [t1, t2]:
146 nmeas.append(round(track_info(tracks[tr], self.acts_tracks).ndf))
147
148 return np.array(nmeas)
149
150 def daughtermomentum(self, candidate):
151 """Return the momentum(Mag) of the particle's daughter tracks.
152
153 Tracks without a usable fit yield -1, which fails the preselection
154 momentum cut.
155 """
156 daughter_mom = []
157 t1, t2 = candidate.GetDaughter(0), candidate.GetDaughter(1)
158 tracks = get_tracks(self.tree)
159 for trD in [t1, t2]:
160 info = track_info(tracks[trD], self.acts_tracks)
161 if not info.converged or info.mom is None or info.ndf <= 0:
162 daughter_mom.append(-1.0)
163 continue
164 daughter_mom.append(info.mom.Mag())
165
166 return np.array(daughter_mom)
167
168 def invariant_mass(self, candidate):
169 """Invariant mass of the candidate."""
170 return candidate.GetMass()
171
172 def DOCA(self, candidate):
173 """Distance of Closest Approach."""
174 return candidate.GetDoca()
175
176 def is_in_fiducial(self, candidate) -> bool:
177 """Check if the candidate decay vertex is within the Fiducial Volume."""
178 candidate_pos = ROOT.TVector3()
179 candidate.GetVertex(candidate_pos)
180
181 if candidate_pos.Z() > self.ship_geo.TrackStation1.z:
182 return False
183 if candidate_pos.Z() < self.decay_vessel_z0:
184 return False
185
186 # if self.dist2InnerWall(candidate)<=5*u.cm: return False
187
188 vertex_node = ROOT.gGeoManager.FindNode(candidate_pos.X(), candidate_pos.Y(), candidate_pos.Z())
189 vertex_elem = vertex_node.GetVolume().GetName()
190 return vertex_elem.startswith("decay_medium")
191
192 def chi2nDOF(self, candidate):
193 """Return the reduced chi^2 of the particle's daughter tracks.
194
195 Tracks without a usable fit yield infinity, which fails the
196 preselection chi^2 cut.
197 """
198 t1, t2 = candidate.GetDaughter(0), candidate.GetDaughter(1)
199
200 chi2ndf = []
201 tracks = get_tracks(self.tree)
202 for tr in [t1, t2]:
203 info = track_info(tracks[tr], self.acts_tracks)
204 if not info.converged or info.ndf <= 0:
205 chi2ndf.append(float("inf"))
206 continue
207 chi2ndf.append(info.chi2 / info.ndf)
208
209 return np.array(chi2ndf)
210
211 def preselection_cut(self, candidate, IP_cut: float = 250, show_table: bool = False) -> bool:
212 """
213 Umbrella method to apply the pre-selection cuts on the candidate.
214
215 show_table=True tabulates the pre-selection parameters.
216 """
217 flag = True
218
219 if len(self.tree.Particles) != 1:
220 flag = False
221 if not (self.is_in_fiducial(candidate)):
222 flag = False
223 if self.dist_to_innerwall(candidate) <= 5 * u.cm:
224 flag = False
225 if self.dist_to_vesselentrance(candidate) <= 100 * u.cm:
226 flag = False
227 if self.impact_parameter(candidate) >= IP_cut * u.cm:
228 flag = False
229 if self.DOCA(candidate) >= 1 * u.cm:
230 flag = False
231 if np.any(self.nDOF(candidate) <= 25):
232 flag = False
233 if np.any(self.chi2nDOF(candidate) >= 5):
234 flag = False
235 if np.any(self.daughtermomentum(candidate) <= 1 * u.GeV):
236 flag = False
237
238 if show_table:
239 table = [
240 [
241 "Number of candidates in event",
242 len(self.tree.Particles),
243 "==1",
244 len(self.tree.Particles) == 1,
245 ],
246 [
247 "Time @ decay vertex (ns)",
248 self.define_candidate_time(candidate),
249 "",
250 "",
251 ],
252 [
253 "Impact Parameter (cm)",
254 self.impact_parameter(candidate),
255 f"IP < {IP_cut * u.cm} cm",
256 self.impact_parameter(candidate) < IP_cut * u.cm,
257 ],
258 [
259 "DOCA (cm)",
260 self.DOCA(candidate),
261 "DOCA < 1 cm",
262 self.DOCA(candidate) < 1 * u.cm,
263 ],
264 [
265 "Is within Fiducial Volume?",
266 self.is_in_fiducial(candidate),
267 "True",
268 self.is_in_fiducial(candidate),
269 ],
270 [
271 "Dist2InnerWall (cm)",
272 self.dist_to_innerwall(candidate),
273 "> 5 cm",
274 self.dist_to_innerwall(candidate) > 5 * u.cm,
275 ],
276 [
277 "Dist2VesselEntrance (cm)",
278 self.dist_to_vesselentrance(candidate),
279 "> 100 cm",
280 self.dist_to_vesselentrance(candidate) > 100 * u.cm,
281 ],
282 ["Invariant Mass (GeV)", self.invariant_mass(candidate), "", ""],
283 [
284 "Daughter Momentum [d1, d2] (GeV)",
285 self.daughtermomentum(candidate),
286 "> 1 GeV",
287 np.all(self.daughtermomentum(candidate) > 1 * u.GeV),
288 ],
289 [
290 "Degrees of Freedom [d1, d2]",
291 self.nDOF(candidate),
292 "> 25",
293 np.all(self.nDOF(candidate) > 25),
294 ],
295 [
296 "Reduced Chi^2 [d1, d2]",
297 self.chi2nDOF(candidate),
298 "< 5",
299 np.all(self.chi2nDOF(candidate) < 5),
300 ],
301 ["\033[1mPre-selection passed:\033[0m", "", "", flag],
302 ]
303
304 for row in table:
305 row[3] = (
306 f"\033[1;32m{row[3]}\033[0m" if row[3] else f"\033[1;31m{row[3]}\033[0m"
307 ) # Green for True, Red for False
308
309 print(
310 tabulate(
311 table,
312 headers=[
313 "Parameter",
314 "Value",
315 "Pre-selection cut",
316 "Pre-selection Check",
317 ],
318 tablefmt="grid",
319 )
320 )
321 return flag
322
323
325 """Class to inspect MCtruth of an Event."""
326
327 def __init__(self) -> None:
328 """Initialize ROOT PDG database."""
329 self.pdg = ROOT.TDatabasePDG.Instance()
330 pythia8_conf.addHNLtoROOT()
331
332 def dump_event(self, event, mom_threshold: float = 0) -> None:
333 """Dump the MCtruth of the event."""
334 headers = [
335 "#",
336 "particle",
337 "pdgcode",
338 "mother_id",
339 "Momentum [Px,Py,Pz] (GeV/c)",
340 "StartVertex[x,y,z] (m)",
341 "Process",
342 "GetWeight()",
343 ]
344
345 event_table = []
346 for trackNr, track in enumerate(event.MCTrack):
347 if track.GetP() / u.GeV < mom_threshold:
348 continue
349
350 particle = self.pdg.GetParticle(track.GetPdgCode())
351 particlename = particle.GetName() if particle else "----"
352
353 event_table.append(
354 [
355 trackNr,
356 particlename,
357 track.GetPdgCode(),
358 track.GetMotherId(),
359 f"[{track.GetPx() / u.GeV:7.3f},{track.GetPy() / u.GeV:7.3f},{track.GetPz() / u.GeV:7.3f}]",
360 f"[{track.GetStartX() / u.m:7.3f},{track.GetStartY() / u.m:7.3f},{track.GetStartZ() / u.m:7.3f}]",
361 track.GetProcName().Data(),
362 track.GetWeight(),
363 ]
364 )
365
366 print(tabulate(event_table, headers=headers, floatfmt=".3f", tablefmt="simple_outline"))
None dump_event(self, event, float mom_threshold=0)
bool preselection_cut(self, candidate, float IP_cut=250, bool show_table=False)