5"""Script to collect muons hitting the 1st Tracking Station (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_Tr.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 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"
44 selectedmuons =
"SelectedMuonsTr.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 Tracking Station 1 (unweighted);P(GeV/c);Pt(GeV/c)",
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",
88h[
"n_softtracks"] = r.TH1I(
"n_softtracks",
"Number of soft tracks per muon;;(unweighted)", 200, 0, 2000)
92 """Print MCTrack truth."""
99 _p = ut.get_particle(mcp.GetPdgCode())
100 particle_name = _p.GetName()
102 if particle_name ==
"mu+" or particle_name ==
"mu-":
103 particle_name = f
"{RED}{particle_name}{RESET} "
106 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
114 mcp.GetStartX() / u.m,
115 mcp.GetStartY() / u.m,
116 mcp.GetStartZ() / u.m,
119 mcp.GetProcName().Data(),
124 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
132 mcp.GetStartX() / u.m,
133 mcp.GetStartY() / u.m,
134 mcp.GetStartZ() / u.m,
137 mcp.GetProcName().Data(),
142def dump(event, pcut: float = 0, print_whole_event: bool =
True) ->
None:
143 """Dump the whole event."""
144 if print_whole_event:
146 "\n %6s %-10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s"
163 " %6s %10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s\n "
180 for mcp
in event.MCTrack:
182 if mcp.GetP() / u.GeV < pcut:
184 if print_whole_event:
190events_ = {
"Tr": {},
"Tr_SBT": {},
"Tr_noSBT": {}}
197 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 len(events_[
"Tr_noSBT"]) >= 12:
218 logging.info(f
"Processing folder: {inputFolder}")
222 os.path.join(path, inputFolder,
"ship.conical.MuonBack-TGeant4.root"),
226 except Exception
as e:
234 nmu = {
"mu+": 0,
"mu-": 0}
242 for hit
in event.strawtubesPoint:
243 trackingstation_id = hit.GetStationNumber()
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)
253 if global_event_nr
not in events_[
"Tr"]:
254 events_[
"Tr"][global_event_nr] = set()
256 events_[
"Tr"][global_event_nr].add(track_id)
258 if not len(muon_ids):
262 for muon_
in muon_ids:
263 muon_vetoPoints.Clear()
265 if global_event_nr
not in events_[
"Tr_SBT"]:
266 events_[
"Tr_SBT"][global_event_nr] = set()
268 for hit
in event.vetoPoint:
269 detID = hit.GetDetectorID()
271 track_id = hit.GetTrackID()
272 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
274 if track_id == muon_:
275 events_[
"Tr_SBT"][global_event_nr].add(track_id)
278 if muon_
in events_[
"Tr_SBT"][global_event_nr]:
282 for track
in event.MCTrack:
283 if track.GetMotherId() == muon_
and track.GetProcName().Data() !=
"Muon nuclear interaction":
284 track_array.Add(track)
286 muon_UpstreamTaggerPoints.Clear()
290 for hit
in event.UpstreamTaggerPoint:
291 track_id = hit.GetTrackID()
293 if track_id != muon_:
296 ut.assignClonesArrayItem(muon_UpstreamTaggerPoints, ubt_index, hit)
300 for hit
in event.strawtubesPoint:
301 track_id = hit.GetTrackID()
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)
307 trackingstation_id = hit.GetStationNumber()
310 abs(hit.PdgCode()) == 13
311 and track_id == muon_
312 and trackingstation_id == 1
313 and P_threshold / u.GeV < P
315 if global_event_nr
not in events_[
"Tr_noSBT"]:
316 events_[
"Tr_noSBT"][global_event_nr] = set()
318 events_[
"Tr_noSBT"][global_event_nr].add(track_id)
320 if global_event_nr
not in processed_events:
321 processed_events[global_event_nr] = []
323 if track_id
not in processed_events[global_event_nr]:
324 processed_events[global_event_nr].append(track_id)
326 _p = ut.get_particle(hit.PdgCode())
327 particle_name = _p.GetName()
329 nmu[particle_name] += 1
331 weight = event.MCTrack[track_id].GetWeight()
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)
355 len(muon_vetoPoints),
356 len(muon_UpstreamTaggerPoints),
360 h[
"PvPt_muon"].Fill(P, Pt)
361 h[
"n_softtracks"].Fill(len(track_array))
365 h[
"n_muon"].Fill(nmu[
"mu-"], nmu[
"mu+"])
366 csvwriter.writerows(row[1:]
for row
in muon_table)
368 f
"EVENT ID:{global_event_nr}\n\tMuon Summary:\n{tabulate(muon_table, headers=headers, tablefmt='grid')}\n\n"
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}")
384 "------------------------------------------------------file saved, reading",
386 " now----------------------------------------------------------------",
389with r.TFile.Open(args.outputfile,
"read")
as file:
391 tree = file[
"MuonAndSoftInteractions"]
392 except Exception
as e:
396 print(f
"Processing tree: {tree.GetName()}")
397 print(f
"Total number of entries: {tree.GetEntries()}")
400 imuondata = event.imuondata
409 weight = imuondata[7]
410 time_hit = imuondata[8]
411 nmuons = imuondata[9]
413 num_tracks = len(event.tracks)
414 num_muonhits = len(event.muon_vetoPoints)
415 num_ubthits = len(event.muon_UpstreamTaggerPoints)
417 P = r.TMath.Sqrt(px**2 + py**2 + pz**2)
434print(tabulate(event_data, headers=headers, tablefmt=
"grid"))
None printMCTrack(int n, MCTrack)
None dump(event, float pcut=0, bool print_whole_event=True)