FairShip
Loading...
Searching...
No Matches
make_nTuple_Tr.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 1st Tracking Station (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_Tr.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 print("test code, output file name overwritten as: muonsProduction_wsoft_Tr_test.root")
41 args.outputfile = "muonsProduction_wsoft_Tr_test.root"
42 selectedmuons = "SelectedMuonsTr_test.txt"
43else:
44 selectedmuons = "SelectedMuonsTr.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 Tracking Station 1 (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 Tracking Station 1 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)
89
90
91def printMCTrack(n: int, MCTrack) -> None:
92 """Print MCTrack truth."""
93 mcp = MCTrack[n]
94
95 RED = "\033[91m" # ANSI code Red
96 RESET = "\033[0m" # ANSI code Reset to default
97
98 try:
99 _p = ut.get_particle(mcp.GetPdgCode())
100 particle_name = _p.GetName()
101
102 if particle_name == "mu+" or particle_name == "mu-":
103 particle_name = f"{RED}{particle_name}{RESET} " # Highlight muons in red
104
105 print(
106 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
107 % (
108 n,
109 particle_name,
110 mcp.GetPdgCode(),
111 mcp.GetPx() / u.GeV,
112 mcp.GetPy() / u.GeV,
113 mcp.GetPz() / u.GeV,
114 mcp.GetStartX() / u.m,
115 mcp.GetStartY() / u.m,
116 mcp.GetStartZ() / u.m,
117 mcp.GetMotherId(),
118 mcp.GetWeight(),
119 mcp.GetProcName().Data(),
120 )
121 )
122 except Exception:
123 print(
124 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
125 % (
126 n,
127 "----",
128 mcp.GetPdgCode(),
129 mcp.GetPx() / u.GeV,
130 mcp.GetPy() / u.GeV,
131 mcp.GetPz() / u.GeV,
132 mcp.GetStartX() / u.m,
133 mcp.GetStartY() / u.m,
134 mcp.GetStartZ() / u.m,
135 mcp.GetMotherId(),
136 mcp.GetWeight(),
137 mcp.GetProcName().Data(),
138 )
139 )
140
141
142def dump(event, pcut: float = 0, print_whole_event: bool = True) -> None:
143 """Dump the whole event."""
144 if print_whole_event:
145 print(
146 "\n %6s %-10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s"
147 % (
148 "#",
149 "particle",
150 "pid",
151 "px",
152 "py",
153 "pz",
154 "vx",
155 "vy",
156 "vz",
157 "mid",
158 "w",
159 "Process",
160 )
161 )
162 print(
163 " %6s %10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s\n "
164 % (
165 " ",
166 "--------",
167 "---",
168 "--",
169 "--",
170 "--",
171 "--",
172 "--",
173 "--",
174 "---",
175 "---",
176 "-------",
177 )
178 )
179 n = -1
180 for mcp in event.MCTrack:
181 n += 1
182 if mcp.GetP() / u.GeV < pcut:
183 continue
184 if print_whole_event:
185 printMCTrack(n, event.MCTrack)
186
187 return
188
189
190events_ = {"Tr": {}, "Tr_SBT": {}, "Tr_noSBT": {}}
191global_event_nr = 0
192processed_events = {}
193
194P_threshold = 3
195
196headers = [
197 f"nMuons in event>{P_threshold}GeV",
198 "Muon PID",
199 "Momentum[GeV/c]",
200 "x[m]",
201 "y[m]",
202 "z[m]",
203 "t_muon [ns]",
204 "nSoft Tracks",
205 "nSBT Hits(muon)",
206 "nUBT Hits(muon)",
207 "Weight_muon",
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 len(events_["Tr_noSBT"]) >= 12:
216 break
217
218 logging.info(f"Processing folder: {inputFolder}")
219 f = None
220 try:
221 f = r.TFile.Open(
222 os.path.join(path, inputFolder, "ship.conical.MuonBack-TGeant4.root"),
223 "read",
224 )
225 tree = f["cbmsim"]
226 except Exception as e:
227 print(f"Error :{e}")
228
229 if f:
230 f.Close()
231 continue
232
233 for event in tree:
234 nmu = {"mu+": 0, "mu-": 0}
235
236 muon_table = []
237 global_event_nr += 1
238
239 muon_ids = []
240
241 # Collect track IDs of muons which hit the Tracking Station
242 for hit in event.strawtubesPoint:
243 trackingstation_id = hit.GetStationNumber()
244 pid = hit.PdgCode()
245 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
246 if abs(pid) == 13 and trackingstation_id == 1 and P_threshold / u.GeV < P:
247 track_id = hit.GetTrackID()
248 _p = ut.get_particle(hit.PdgCode())
249 particle_name = _p.GetName()
250 if track_id not in muon_ids:
251 muon_ids.append(track_id)
252
253 if global_event_nr not in events_["Tr"]:
254 events_["Tr"][global_event_nr] = set()
255
256 events_["Tr"][global_event_nr].add(track_id)
257
258 if not len(muon_ids):
259 continue
260 # dump(event)
261
262 for muon_ in muon_ids:
263 muon_vetoPoints.Clear()
264
265 if global_event_nr not in events_["Tr_SBT"]:
266 events_["Tr_SBT"][global_event_nr] = set()
267
268 for hit in event.vetoPoint:
269 detID = hit.GetDetectorID()
270 pid = hit.PdgCode()
271 track_id = hit.GetTrackID()
272 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
273
274 if track_id == muon_:
275 events_["Tr_SBT"][global_event_nr].add(track_id)
276 continue
277
278 if muon_ in events_["Tr_SBT"][global_event_nr]:
279 continue
280
281 track_array.Clear()
282 for track in event.MCTrack:
283 if track.GetMotherId() == muon_ and track.GetProcName().Data() != "Muon nuclear interaction":
284 track_array.Add(track)
285
286 muon_UpstreamTaggerPoints.Clear()
287
288 ubt_index = 0
289
290 for hit in event.UpstreamTaggerPoint:
291 track_id = hit.GetTrackID()
292
293 if track_id != muon_:
294 continue
295
296 ut.assignClonesArrayItem(muon_UpstreamTaggerPoints, ubt_index, hit)
297
298 ubt_index += 1
299
300 for hit in event.strawtubesPoint:
301 track_id = hit.GetTrackID()
302 pid = hit.PdgCode()
303
304 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
305 Pt = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2)
306
307 trackingstation_id = hit.GetStationNumber()
308
309 if (
310 abs(hit.PdgCode()) == 13
311 and track_id == muon_
312 and trackingstation_id == 1
313 and P_threshold / u.GeV < P
314 ):
315 if global_event_nr not in events_["Tr_noSBT"]:
316 events_["Tr_noSBT"][global_event_nr] = set()
317
318 events_["Tr_noSBT"][global_event_nr].add(track_id)
319
320 if global_event_nr not in processed_events:
321 processed_events[global_event_nr] = []
322
323 if track_id not in processed_events[global_event_nr]: # only save the info of first SBT hit
324 processed_events[global_event_nr].append(track_id)
325
326 _p = ut.get_particle(hit.PdgCode())
327 particle_name = _p.GetName()
328
329 nmu[particle_name] += 1
330
331 weight = event.MCTrack[track_id].GetWeight()
332
333 # Fill imuondata
334 imuondata[0] = float(hit.PdgCode())
335 imuondata[1] = float(hit.GetPx() / u.GeV)
336 imuondata[2] = float(hit.GetPy() / u.GeV)
337 imuondata[3] = float(hit.GetPz() / u.GeV)
338 imuondata[4] = float(hit.GetX() / u.m)
339 imuondata[5] = float(hit.GetY() / u.m)
340 imuondata[6] = float(hit.GetZ() / u.m)
341 imuondata[7] = float(weight)
342 imuondata[8] = float(hit.GetTime())
343 imuondata[9] = len(muon_ids)
344 muon_table.append(
345 [
346 track_id,
347 len(muon_ids),
348 imuondata[0],
349 P,
350 imuondata[4],
351 imuondata[5],
352 imuondata[6],
353 imuondata[8],
354 len(track_array),
355 len(muon_vetoPoints),
356 len(muon_UpstreamTaggerPoints),
357 imuondata[7],
358 ]
359 )
360 h["PvPt_muon"].Fill(P, Pt)
361 h["n_softtracks"].Fill(len(track_array))
362 output_tree.Fill()
363
364 if len(muon_table):
365 h["n_muon"].Fill(nmu["mu-"], nmu["mu+"])
366 csvwriter.writerows(row[1:] for row in muon_table)
367 logging.debug(
368 f"EVENT ID:{global_event_nr}\n\tMuon Summary:\n{tabulate(muon_table, headers=headers, tablefmt='grid')}\n\n"
369 )
370
371for type_ in events_:
372 # Calculate total number of muons
373 total_muons = sum(len(muons) for muons in events_[type_].values())
374 print(f"{type_}, \tnEvents:{sum(bool(len(muons)) for muons in events_[type_].values())}, \tnMuons:{total_muons}")
375output_file.cd()
376output_tree.Write()
377for histname in h:
378 h[histname].Write()
379output_file.Close()
380fsel.close()
381
382
383print(
384 "------------------------------------------------------file saved, reading",
385 args.outputfile,
386 " now----------------------------------------------------------------",
387)
388event_data = []
389with r.TFile.Open(args.outputfile, "read") as file:
390 try:
391 tree = file["MuonAndSoftInteractions"]
392 except Exception as e:
393 print(f"Error: {e}")
394 exit(1)
395
396 print(f"Processing tree: {tree.GetName()}")
397 print(f"Total number of entries: {tree.GetEntries()}")
398
399 for event in tree:
400 imuondata = event.imuondata
401 pid = imuondata[0]
402 px = imuondata[1]
403 py = imuondata[2]
404 pz = imuondata[3]
405 x = imuondata[4]
406 y = imuondata[5]
407 z = imuondata[6]
408
409 weight = imuondata[7]
410 time_hit = imuondata[8]
411 nmuons = imuondata[9]
412
413 num_tracks = len(event.tracks)
414 num_muonhits = len(event.muon_vetoPoints)
415 num_ubthits = len(event.muon_UpstreamTaggerPoints)
416
417 P = r.TMath.Sqrt(px**2 + py**2 + pz**2)
418
419 event_data.append(
420 [
421 nmuons,
422 pid,
423 P,
424 x,
425 y,
426 z,
427 time_hit,
428 num_tracks,
429 num_muonhits,
430 num_ubthits,
431 weight,
432 ]
433 )
434print(tabulate(event_data, headers=headers, tablefmt="grid"))
None printMCTrack(int n, MCTrack)
None dump(event, float pcut=0, bool print_whole_event=True)