5"""Script to collect muons hitting the 1st Tracking Station (including soft interaction products) to a ROOT file."""
14from tabulate
import tabulate
16pdg = r.TDatabasePDG.Instance()
19logging.basicConfig(level=logging.INFO)
22parser = argparse.ArgumentParser(description=__doc__)
23parser.add_argument(
"--test", dest=
"testing_code", help=
"Run Test", action=
"store_true")
27 default=
"muonsProduction_wsoft_Tr.root",
28 help=
"custom outputfile name",
33 help=
"path to muon background files",
34 default=
"/eos/experiment/ship/simulation/bkg/MuonBack_2024helium/8070735",
36args = parser.parse_args()
39 print(
"test code, output file name overwritten as: muonsProduction_wsoft_Tr_test.root")
40 args.outputfile =
"muonsProduction_wsoft_Tr_test.root"
41 selectedmuons =
"SelectedMuonsTr_test.txt"
43 selectedmuons =
"SelectedMuonsTr.txt"
46logging.info(f
"Path to MuonBackground : {path}")
48fsel =
open(selectedmuons,
"w")
49csvwriter = csv.writer(fsel)
51output_file = r.TFile.Open(args.outputfile,
"recreate")
52output_tree = r.TTree(
"MuonAndSoftInteractions",
"Muon information and soft interaction tracks")
54imuondata = r.TVectorD(10)
55output_tree.Branch(
"imuondata", imuondata)
57track_array = r.TObjArray()
58output_tree.Branch(
"tracks", track_array)
60muon_vetoPoints = r.TClonesArray(
"vetoPoint")
61output_tree.Branch(
"muon_vetoPoints", muon_vetoPoints)
63muon_UpstreamTaggerPoints = r.TClonesArray(
"UpstreamTaggerPoint")
64output_tree.Branch(
"muon_UpstreamTaggerPoints", muon_UpstreamTaggerPoints)
67h[
"PvPt_muon"] = r.TH2F(
69 "The momentum of the muons hitting Tracking Station 1 (unweighted);P(GeV/c);Pt(GeV/c)",
79 "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",
87h[
"n_softtracks"] = r.TH1I(
"n_softtracks",
"Number of soft tracks per muon;;(unweighted)", 200, 0, 2000)
91 """Print MCTrack truth."""
98 particle_name = pdg.GetParticle(mcp.GetPdgCode()).GetName()
100 if particle_name ==
"mu+" or particle_name ==
"mu-":
101 particle_name = f
"{RED}{particle_name}{RESET} "
104 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
112 mcp.GetStartX() / u.m,
113 mcp.GetStartY() / u.m,
114 mcp.GetStartZ() / u.m,
117 mcp.GetProcName().Data(),
122 " %6s %-10s %10i %6.3F %6.3F %7.3F %7.3F %7.3F %7.3F %6s %10.3F %28s"
130 mcp.GetStartX() / u.m,
131 mcp.GetStartY() / u.m,
132 mcp.GetStartZ() / u.m,
135 mcp.GetProcName().Data(),
140def dump(event, pcut: float = 0, print_whole_event: bool =
True) ->
None:
141 """Dump the whole event."""
142 if print_whole_event:
144 "\n %6s %-10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s"
161 " %6s %10s %10s %6s %6s %7s %7s %7s %7s %6s %10s %18s\n "
178 for mcp
in event.MCTrack:
180 if mcp.GetP() / u.GeV < pcut:
182 if print_whole_event:
188events_ = {
"Tr": {},
"Tr_SBT": {},
"Tr_noSBT": {}}
195 f
"nMuons in event>{P_threshold}GeV",
207csvwriter.writerow(headers)
209for inputFolder
in os.listdir(path):
210 if not os.path.isdir(os.path.join(path, inputFolder)):
213 if args.testing_code
and len(events_[
"Tr_noSBT"]) >= 12:
216 logging.info(f
"Processing folder: {inputFolder}")
220 os.path.join(path, inputFolder,
"ship.conical.MuonBack-TGeant4.root"),
224 except Exception
as e:
232 nmu = {
"mu+": 0,
"mu-": 0}
240 for hit
in event.strawtubesPoint:
241 trackingstation_id = hit.GetStationNumber()
243 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
244 if abs(pid) == 13
and trackingstation_id == 1
and P_threshold / u.GeV < P:
245 track_id = hit.GetTrackID()
246 particle_name = pdg.GetParticle(hit.PdgCode()).GetName()
247 if track_id
not in muon_ids:
248 muon_ids.append(track_id)
250 if global_event_nr
not in events_[
"Tr"]:
251 events_[
"Tr"][global_event_nr] = set()
253 events_[
"Tr"][global_event_nr].
add(track_id)
255 if not len(muon_ids):
259 for muon_
in muon_ids:
260 muon_vetoPoints.Clear()
262 if global_event_nr
not in events_[
"Tr_SBT"]:
263 events_[
"Tr_SBT"][global_event_nr] = set()
265 for hit
in event.vetoPoint:
266 detID = hit.GetDetectorID()
268 track_id = hit.GetTrackID()
269 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
271 if track_id == muon_:
272 events_[
"Tr_SBT"][global_event_nr].
add(track_id)
275 if muon_
in events_[
"Tr_SBT"][global_event_nr]:
279 for track
in event.MCTrack:
280 if track.GetMotherId() == muon_
and track.GetProcName().Data() !=
"Muon nuclear interaction":
281 track_array.Add(track)
283 muon_UpstreamTaggerPoints.Clear()
287 for hit
in event.UpstreamTaggerPoint:
288 track_id = hit.GetTrackID()
290 if track_id != muon_:
293 if muon_UpstreamTaggerPoints.GetSize() == ubt_index:
294 muon_UpstreamTaggerPoints.Expand(ubt_index + 1)
295 muon_UpstreamTaggerPoints[ubt_index] = hit
299 for hit
in event.strawtubesPoint:
300 track_id = hit.GetTrackID()
303 P = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2 + hit.GetPz() ** 2)
304 Pt = r.TMath.Sqrt(hit.GetPx() ** 2 + hit.GetPy() ** 2)
306 trackingstation_id = hit.GetStationNumber()
308 if abs(hit.PdgCode()) == 13
and trackingstation_id == 1
and P_threshold / u.GeV < P:
309 if global_event_nr
not in events_[
"Tr_noSBT"]:
310 events_[
"Tr_noSBT"][global_event_nr] = set()
312 events_[
"Tr_noSBT"][global_event_nr].
add(track_id)
314 if global_event_nr
not in processed_events:
315 processed_events[global_event_nr] = []
317 if track_id
not in processed_events[global_event_nr]:
318 processed_events[global_event_nr].append(track_id)
320 particle_name = pdg.GetParticle(hit.PdgCode()).GetName()
322 nmu[particle_name] += 1
324 weight = event.MCTrack[track_id].GetWeight()
327 imuondata[0] = float(hit.PdgCode())
328 imuondata[1] = float(hit.GetPx() / u.GeV)
329 imuondata[2] = float(hit.GetPy() / u.GeV)
330 imuondata[3] = float(hit.GetPz() / u.GeV)
331 imuondata[4] = float(hit.GetX() / u.m)
332 imuondata[5] = float(hit.GetY() / u.m)
333 imuondata[6] = float(hit.GetZ() / u.m)
334 imuondata[7] = float(weight)
335 imuondata[8] = float(hit.GetTime())
336 imuondata[9] = len(muon_ids)
348 len(muon_vetoPoints),
349 len(muon_UpstreamTaggerPoints),
353 h[
"PvPt_muon"].Fill(P, Pt)
354 h[
"n_softtracks"].Fill(len(track_array))
358 h[
"n_muon"].Fill(nmu[
"mu-"], nmu[
"mu+"])
359 csvwriter.writerows(row[1:]
for row
in muon_table)
361 f
"EVENT ID:{global_event_nr}\n\tMuon Summary:\n{tabulate(muon_table, headers=headers, tablefmt='grid')}\n\n"
366 total_muons = sum(len(muons)
for muons
in events_[type_].values())
367 print(f
"{type_}, \tnEvents:{sum(bool(len(muons)) for muons in events_[type_].values())}, \tnMuons:{total_muons}")
377 "------------------------------------------------------file saved, reading",
379 " now----------------------------------------------------------------",
382with r.TFile.Open(args.outputfile,
"read")
as file:
384 tree = file.MuonAndSoftInteractions
385 except Exception
as e:
389 print(f
"Processing tree: {tree.GetName()}")
390 print(f
"Total number of entries: {tree.GetEntries()}")
393 imuondata = event.imuondata
402 weight = imuondata[7]
403 time_hit = imuondata[8]
404 nmuons = imuondata[9]
406 num_tracks = len(event.tracks)
407 num_muonhits = len(event.muon_vetoPoints)
408 num_ubthits = len(event.muon_UpstreamTaggerPoints)
410 P = r.TMath.Sqrt(px**2 + py**2 + pz**2)
427print(tabulate(event_data, headers=headers, tablefmt=
"grid"))
None printMCTrack(int n, MCTrack)
None dump(event, float pcut=0, bool print_whole_event=True)
Coord add(Coord c1, Coord c2)
int open(const char *, int)
Opens a file descriptor.