5"""Script to collect muons hitting the SBT (including soft interaction products) to a ROOT file."""
15from tabulate
import tabulate
17pdg = r.TDatabasePDG.Instance()
20logging.basicConfig(level=logging.INFO)
23parser = argparse.ArgumentParser(description=__doc__)
24parser.add_argument(
"--test", dest=
"testing_code", help=
"Run Test", action=
"store_true")
28 default=
"muonsProduction_wsoft_SBT.root",
29 help=
"custom outputfile name",
34 help=
"path to muon background files",
35 default=
"/eos/experiment/ship/simulation/bkg/MuonBack_2024helium/8070735",
37args = parser.parse_args()
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"
44 selectedmuons =
"SelectedMuonsSBT.txt"
47logging.info(f
"Path to MuonBackground : {path}")
49fsel = open(selectedmuons,
"w")
50csvwriter = csv.writer(fsel)
52output_file = r.TFile.Open(args.outputfile,
"recreate")
53output_tree = r.TTree(
"MuonAndSoftInteractions",
"Muon information and soft interaction tracks")
55imuondata = r.TVectorD(10)
56output_tree.Branch(
"imuondata", imuondata)
58track_array = r.TObjArray()
59output_tree.Branch(
"tracks", track_array)
61muon_vetoPoints = r.TClonesArray(
"vetoPoint")
62output_tree.Branch(
"muon_vetoPoints", muon_vetoPoints)
64muon_UpstreamTaggerPoints = r.TClonesArray(
"UpstreamTaggerPoint")
65output_tree.Branch(
"muon_UpstreamTaggerPoints", muon_UpstreamTaggerPoints)
67h: dict[str,
"r.TH1"] = {}
68h[
"PvPt_muon"] = r.TH2F(
70 "The momentum of the muons hitting the SBT(unweighted);P(GeV/c);Pt(GeV/c)",
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",
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)
93 """Print MCTrack truth."""
100 _p = ut.get_particle(mcp.GetPdgCode())
101 particle_name = _p.GetName()
103 if particle_name ==
"mu+" or particle_name ==
"mu-":
104 particle_name = f
"{RED}{particle_name}{RESET} "
107 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
115 mcp.GetStartX() / u.m,
116 mcp.GetStartY() / u.m,
117 mcp.GetStartZ() / u.m,
120 mcp.GetProcName().Data(),
125 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
133 mcp.GetStartX() / u.m,
134 mcp.GetStartY() / u.m,
135 mcp.GetStartZ() / u.m,
138 mcp.GetProcName().Data(),
143def dump(event, pcut: float = 0, print_whole_event: bool =
True) ->
None:
144 """Dump the whole event."""
145 if print_whole_event:
147 "\n %6s %-10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s"
164 " %6s %10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s\n "
181 for mcp
in event.MCTrack:
183 if mcp.GetP() / u.GeV < pcut:
185 if print_whole_event:
196 f
"nMuons in event>{P_threshold}GeV",
209csvwriter.writerow(headers)
211for inputFolder
in os.listdir(path):
212 if not os.path.isdir(os.path.join(path, inputFolder)):
215 if args.testing_code
and global_event_nr >= 100000:
218 logging.info(f
"Processing folder: {inputFolder}")
223 os.path.join(path, inputFolder,
"ship.conical.MuonBack-TGeant4.root"),
227 except Exception
as e:
228 logging.debug(f
"Error :{e}")
234 for eventNr, event
in enumerate(tree):
239 nmu = {
"mu+": 0,
"mu-": 0}
244 for hit
in event.vetoPoint:
245 detID = hit.GetDetectorID()
247 track_id = hit.GetTrackID()
248 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
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
259 if not len(muon_ids):
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}")
265 for muon_
in muon_ids:
271 for track
in event.MCTrack:
272 if track.GetMotherId() == muon_
and track.GetProcName().Data() !=
"Muon nuclear interaction":
273 track_array.Add(track)
277 muon_UpstreamTaggerPoints.Clear()
281 for hit
in event.UpstreamTaggerPoint:
282 track_id = hit.GetTrackID()
284 if track_id != muon_:
287 ut.assignClonesArrayItem(muon_UpstreamTaggerPoints, ubt_index, hit)
293 muon_vetoPoints.Clear()
295 for hit
in event.vetoPoint:
296 detID = hit.GetDetectorID()
298 track_id = hit.GetTrackID()
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)
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] = []
307 ut.assignClonesArrayItem(muon_vetoPoints, index, hit)
311 weight = event.MCTrack[track_id].GetWeight()
313 if track_id
not in processed_events[global_event_nr]:
314 processed_events[global_event_nr].append(track_id)
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)
337 len(muon_vetoPoints),
338 len(muon_UpstreamTaggerPoints),
343 h[
"PvPt_muon"].Fill(P, Pt)
344 h[
"n_softtracks"].Fill(len(track_array))
349 muon_table[-1][-3] = len(muon_vetoPoints)
351 h[
"n_sbthits"].Fill(len(muon_vetoPoints))
355 h[
"n_muon"].Fill(nmu[
"mu-"], nmu[
"mu+"])
356 csvwriter.writerows(row[1:]
for row
in muon_table)
358 logging.debug(f
"Muon Summary:\n{tabulate(muon_table, headers=headers, tablefmt='grid')}\n\n")
363total_muons = sum(len(values)
for values
in processed_events.values())
364print(f
"nMuons saved: {total_muons}, File: {args.outputfile}")
374 "------------------------------------------------------file saved, inspecting",
376 "now----------------------------------------------------------------",
380with r.TFile.Open(args.outputfile,
"read")
as file:
382 tree = file[
"MuonAndSoftInteractions"]
383 except Exception
as e:
387 print(f
"Processing tree: {tree.GetName()}")
388 print(f
"Total number of entries: {tree.GetEntries()}")
391 imuondata = event.imuondata
400 weight = imuondata[7]
401 time_hit = imuondata[8]
402 nmuons = imuondata[9]
404 num_tracks = len(event.tracks)
405 num_muonhits = len(event.muon_vetoPoints)
406 num_ubthits = len(event.muon_UpstreamTaggerPoints)
408 P = r.TMath.Sqrt(px**2 + py**2 + pz**2)
426print(tabulate(event_data, headers=headers, tablefmt=
"grid"))
None printMCTrack(int n, MCTrack)
None dump(event, float pcut=0, bool print_whole_event=True)