FairShip
Loading...
Searching...
No Matches
make_nTuple_SBT.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"""Script to collect muons hitting the SBT (including soft interaction products) to a ROOT file."""
6
7import argparse
8import csv
9import logging
10import os
11
12import ROOT as r
13import rootUtils as ut
14import shipunit as u
15from tabulate import tabulate
16
17pdg = r.TDatabasePDG.Instance()
18
19
20logging.basicConfig(level=logging.INFO)
21
22
23parser = argparse.ArgumentParser(description=__doc__)
24parser.add_argument("--test", dest="testing_code", help="Run Test", action="store_true")
25parser.add_argument(
26 "-o",
27 "--outputfile",
28 default="muonsProduction_wsoft_SBT.root",
29 help="custom outputfile name",
30)
31parser.add_argument(
32 "-p",
33 "--path",
34 help="path to muon background files",
35 default="/eos/experiment/ship/simulation/bkg/MuonBack_2024helium/8070735",
36)
37args = parser.parse_args()
38
39if args.testing_code:
40 logging.info("test code, output file name overwritten as: muonsProduction_wsoft_SBT_test.root")
41 args.outputfile = "muonsProduction_wsoft_SBT_test.root"
42 selectedmuons = "SelectedMuonsSBT_test.txt"
43else:
44 selectedmuons = "SelectedMuonsSBT.txt"
45
46path = args.path
47logging.info(f"Path to MuonBackground : {path}")
48
49fsel = open(selectedmuons, "w") # noqa: SIM115
50csvwriter = csv.writer(fsel)
51
52output_file = r.TFile.Open(args.outputfile, "recreate")
53output_tree = r.TTree("MuonAndSoftInteractions", "Muon information and soft interaction tracks")
54
55imuondata = r.TVectorD(10) # 10 values: pid, px, py, pz, x, y, z, weight,time_of_hit,nmuons_in_event
56output_tree.Branch("imuondata", imuondata)
57
58track_array = r.TObjArray()
59output_tree.Branch("tracks", track_array)
60
61muon_vetoPoints = r.TClonesArray("vetoPoint")
62output_tree.Branch("muon_vetoPoints", muon_vetoPoints)
63
64muon_UpstreamTaggerPoints = r.TClonesArray("UpstreamTaggerPoint")
65output_tree.Branch("muon_UpstreamTaggerPoints", muon_UpstreamTaggerPoints)
66
67h: dict[str, "r.TH1"] = {}
68h["PvPt_muon"] = r.TH2F(
69 "PvPt_muon",
70 "The momentum of the muons hitting the SBT(unweighted);P(GeV/c);Pt(GeV/c)",
71 200,
72 0.0,
73 400,
74 40,
75 0.0,
76 20,
77)
78h["n_muon"] = r.TH2I(
79 "n_muon",
80 "Number of muons hitting the SBT per Event;number of mu- per event (unweighted) bin width =1;number of mu+ per event (unweighted) bin width=1",
81 6,
82 0.0,
83 6,
84 6,
85 0.0,
86 6,
87)
88h["n_softtracks"] = r.TH1I("n_softtracks", "Number of soft tracks per muon;;(unweighted)", 200, 0, 2000)
89h["n_sbthits"] = r.TH1I("n_sbthits", "Number of SBT hits per muon;n_sbthits(unweighted);", 900, 0, 900)
90
91
92def printMCTrack(n: int, MCTrack) -> None:
93 """Print MCTrack truth."""
94 mcp = MCTrack[n]
95
96 RED = "\033[91m" # ANSI code Red
97 RESET = "\033[0m" # ANSI code Reset to default
98
99 try:
100 _p = ut.get_particle(mcp.GetPdgCode())
101 particle_name = _p.GetName()
102
103 if particle_name == "mu+" or particle_name == "mu-":
104 particle_name = f"{RED}{particle_name}{RESET} " # Highlight muons in red
105
106 print(
107 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
108 % (
109 n,
110 particle_name,
111 mcp.GetPdgCode(),
112 mcp.GetPx() / u.GeV,
113 mcp.GetPy() / u.GeV,
114 mcp.GetPz() / u.GeV,
115 mcp.GetStartX() / u.m,
116 mcp.GetStartY() / u.m,
117 mcp.GetStartZ() / u.m,
118 mcp.GetMotherId(),
119 mcp.GetWeight(),
120 mcp.GetProcName().Data(),
121 )
122 )
123 except Exception:
124 print(
125 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
126 % (
127 n,
128 "----",
129 mcp.GetPdgCode(),
130 mcp.GetPx() / u.GeV,
131 mcp.GetPy() / u.GeV,
132 mcp.GetPz() / u.GeV,
133 mcp.GetStartX() / u.m,
134 mcp.GetStartY() / u.m,
135 mcp.GetStartZ() / u.m,
136 mcp.GetMotherId(),
137 mcp.GetWeight(),
138 mcp.GetProcName().Data(),
139 )
140 )
141
142
143def dump(event, pcut: float = 0, print_whole_event: bool = True) -> None:
144 """Dump the whole event."""
145 if print_whole_event:
146 print(
147 "\n %6s %-10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s"
148 % (
149 "#",
150 "particle",
151 "pid",
152 "px",
153 "py",
154 "pz",
155 "vx",
156 "vy",
157 "vz",
158 "mid",
159 "w",
160 "Process",
161 )
162 )
163 print(
164 " %6s %10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s\n "
165 % (
166 " ",
167 "--------",
168 "---",
169 "--",
170 "--",
171 "--",
172 "--",
173 "--",
174 "--",
175 "---",
176 "---",
177 "-------",
178 )
179 )
180 n = -1
181 for mcp in event.MCTrack:
182 n += 1
183 if mcp.GetP() / u.GeV < pcut:
184 continue
185 if print_whole_event:
186 printMCTrack(n, event.MCTrack)
187
188 return
189
190
191global_event_nr = 0
192processed_events = {}
193P_threshold = 3
194
195headers = [
196 f"nMuons in event>{P_threshold}GeV",
197 "Muon PID",
198 "Momentum[GeV/c]",
199 "x[m]",
200 "y[m]",
201 "z[m]",
202 "t_muon [ns]",
203 "nSoft Tracks",
204 "nSBT Hits(muon)",
205 "nUBT Hits(muon)",
206 "Weight_muon",
207]
208
209csvwriter.writerow(headers)
210
211for inputFolder in os.listdir(path):
212 if not os.path.isdir(os.path.join(path, inputFolder)):
213 continue
214
215 if args.testing_code and global_event_nr >= 100000:
216 break
217
218 logging.info(f"Processing folder: {inputFolder}")
219
220 f = None
221 try:
222 f = r.TFile.Open(
223 os.path.join(path, inputFolder, "ship.conical.MuonBack-TGeant4.root"),
224 "read",
225 )
226 tree = f["cbmsim"]
227 except Exception as e:
228 logging.debug(f"Error :{e}")
229
230 if f:
231 f.Close()
232 continue
233
234 for eventNr, event in enumerate(tree):
235 global_event_nr += 1
236
237 muon_table = []
238
239 nmu = {"mu+": 0, "mu-": 0}
240
241 muon_ids = []
242 muon_hits = {}
243 # Collect track IDs of muons which hit the SBT
244 for hit in event.vetoPoint:
245 detID = hit.GetDetectorID()
246 pid = hit.PdgCode()
247 track_id = hit.GetTrackID()
248 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
249
250 if 1000 < detID < 999999 and abs(pid) == 13 and P_threshold / u.GeV < P:
251 _p = ut.get_particle(hit.PdgCode())
252 particle_name = _p.GetName()
253 if track_id not in muon_ids:
254 muon_ids.append(track_id)
255 muon_hits[track_id] = 0
256 nmu[particle_name] += 1
257 muon_hits[track_id] += 1
258
259 if not len(muon_ids):
260 continue
261
262 logging.debug(f"\n\nEVENT ID:{global_event_nr}")
263 logging.debug(f"Muon Track Available:{muon_hits.keys()}\n Number of SBT hits within:{muon_hits}")
264
265 for muon_ in muon_ids:
266 imuondata.Zero()
267
268 # saving soft tracks
269 track_array.Clear()
270
271 for track in event.MCTrack:
272 if track.GetMotherId() == muon_ and track.GetProcName().Data() != "Muon nuclear interaction":
273 track_array.Add(track)
274
275 # saving the muon info
276
277 muon_UpstreamTaggerPoints.Clear()
278
279 ubt_index = 0
280
281 for hit in event.UpstreamTaggerPoint:
282 track_id = hit.GetTrackID()
283
284 if track_id != muon_:
285 continue
286
287 ut.assignClonesArrayItem(muon_UpstreamTaggerPoints, ubt_index, hit)
288
289 ubt_index += 1
290
291 index = 0
292
293 muon_vetoPoints.Clear()
294
295 for hit in event.vetoPoint:
296 detID = hit.GetDetectorID()
297 pid = hit.PdgCode()
298 track_id = hit.GetTrackID()
299
300 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
301 Pt = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2)
302
303 if 1000 < detID < 999999 and track_id == muon_ and P_threshold / u.GeV < P:
304 if global_event_nr not in processed_events:
305 processed_events[global_event_nr] = []
306
307 ut.assignClonesArrayItem(muon_vetoPoints, index, hit)
308
309 index += 1
310
311 weight = event.MCTrack[track_id].GetWeight()
312
313 if track_id not in processed_events[global_event_nr]: # only save the info of first SBT hit
314 processed_events[global_event_nr].append(track_id)
315
316 imuondata[0] = float(pid)
317 imuondata[1] = float(hit.GetPx() / u.GeV)
318 imuondata[2] = float(hit.GetPy() / u.GeV)
319 imuondata[3] = float(hit.GetPz() / u.GeV)
320 imuondata[4] = float(hit.GetX() / u.m)
321 imuondata[5] = float(hit.GetY() / u.m)
322 imuondata[6] = float(hit.GetZ() / u.m)
323 imuondata[7] = float(weight)
324 imuondata[8] = float(hit.GetTime())
325 imuondata[9] = len(muon_ids)
326 muon_table.append(
327 [
328 track_id,
329 len(muon_ids),
330 imuondata[0],
331 P,
332 imuondata[4],
333 imuondata[5],
334 imuondata[6],
335 imuondata[8],
336 len(track_array),
337 len(muon_vetoPoints),
338 len(muon_UpstreamTaggerPoints),
339 imuondata[7],
340 ]
341 )
342
343 h["PvPt_muon"].Fill(P, Pt)
344 h["n_softtracks"].Fill(len(track_array))
345
346 # Update the final SBT-hit count (column -3); the row was
347 # appended on the first SBT hit before the count was complete.
348 # (-2 is the already-complete UBT count.)
349 muon_table[-1][-3] = len(muon_vetoPoints)
350
351 h["n_sbthits"].Fill(len(muon_vetoPoints))
352
353 output_tree.Fill()
354
355 h["n_muon"].Fill(nmu["mu-"], nmu["mu+"])
356 csvwriter.writerows(row[1:] for row in muon_table)
357 # dump(event)
358 logging.debug(f"Muon Summary:\n{tabulate(muon_table, headers=headers, tablefmt='grid')}\n\n")
359
360 f.Close()
361
362
363total_muons = sum(len(values) for values in processed_events.values())
364print(f"nMuons saved: {total_muons}, File: {args.outputfile}")
365
366output_file.cd()
367output_tree.Write()
368for histname in h:
369 h[histname].Write()
370output_file.Close()
371fsel.close()
372
373print(
374 "------------------------------------------------------file saved, inspecting",
375 args.outputfile,
376 "now----------------------------------------------------------------",
377)
378
379event_data = []
380with r.TFile.Open(args.outputfile, "read") as file:
381 try:
382 tree = file["MuonAndSoftInteractions"]
383 except Exception as e:
384 print(f"Error: {e}")
385 exit(1)
386
387 print(f"Processing tree: {tree.GetName()}")
388 print(f"Total number of entries: {tree.GetEntries()}")
389
390 for event in tree:
391 imuondata = event.imuondata
392 pid = imuondata[0]
393 px = imuondata[1]
394 py = imuondata[2]
395 pz = imuondata[3]
396 x = imuondata[4]
397 y = imuondata[5]
398 z = imuondata[6]
399
400 weight = imuondata[7]
401 time_hit = imuondata[8]
402 nmuons = imuondata[9]
403
404 num_tracks = len(event.tracks)
405 num_muonhits = len(event.muon_vetoPoints)
406 num_ubthits = len(event.muon_UpstreamTaggerPoints)
407
408 P = r.TMath.Sqrt(px**2 + py**2 + pz**2)
409
410 event_data.append(
411 [
412 nmuons,
413 pid,
414 P,
415 x,
416 y,
417 z,
418 time_hit,
419 num_tracks,
420 num_muonhits,
421 num_ubthits,
422 weight,
423 ]
424 )
425
426print(tabulate(event_data, headers=headers, tablefmt="grid"))
None printMCTrack(int n, MCTrack)
None dump(event, float pcut=0, bool print_whole_event=True)