FairShip
Loading...
Searching...
No Matches
check_muonback_plane.py
Go to the documentation of this file.
1#!/usr/bin/env python3
2# SPDX-License-Identifier: LGPL-3.0-or-later
3# SPDX-FileCopyrightText: Copyright CERN for the benefit of the SHiP Collaboration
4"""Check that MuonBack continues run_fixedTarget muons from the scoring plane.
5
6Compares a stage-2 output of run_simScript.py --MuonBack with its stage-1 input
7(run_fixedTarget.py). Every tracked plane copy (procID kPTransportation) has to
8start where a muon of the input entered PlaneHA, with the same momentum, time
9and weight, and its mother has to be the untracked origin entry of that muon.
10The start points also have to lie outside dense material in the stage-2
11geometry. Stage 2 drops events without hits, so copies are matched against the
12hits of the whole input rather than event by event.
13"""
14
15import argparse
16import sys
17
18import ROOT
19import shipRoot_conf
20
22
23TOL = 1e-4 # relative, for the float storage of the hits
24
25
26def close(a, b, tol=TOL):
27 return all(abs(x - y) <= tol * max(1.0, abs(y)) for x, y in zip(a, b))
28
29
30def input_muons(tree):
31 """The muons MuonBack starts: the first PlaneHA hit of each muon track."""
32 muons = []
33 for ev in tree:
34 seen = set()
35 for h in ev.PlaneHAPoint:
36 i = h.GetTrackID()
37 if abs(h.PdgCode()) != 13 or i in seen:
38 continue
39 seen.add(i)
40 trk = ev.MCTrack[i]
41 muons.append(
42 {
43 "pdg": h.PdgCode(),
44 "pos": (h.GetX(), h.GetY(), h.GetZ()),
45 "mom": (h.GetPx(), h.GetPy(), h.GetPz()),
46 "time": h.GetTime(),
47 "weight": trk.GetWeight(),
48 "origin": (trk.GetStartX(), trk.GetStartY(), trk.GetStartZ()),
49 }
50 )
51 return muons
52
53
54def main() -> int:
55 ap = argparse.ArgumentParser(description=__doc__)
56 ap.add_argument("stage1", help="run_fixedTarget.py output")
57 ap.add_argument("stage2", help="run_simScript.py --MuonBack output (sim_*.root)")
58 ap.add_argument("--geo", help="stage-2 geometry file (geo_*.root)")
59 ap.add_argument("--max-density", type=float, default=0.01, help="densest material allowed at a start [g/cm3]")
60 args = ap.parse_args()
61
62 f1 = ROOT.TFile.Open(args.stage1)
63 muons = input_muons(f1["cbmsim"])
64 f2 = ROOT.TFile.Open(args.stage2)
65 nav = None
66 if args.geo:
67 ROOT.TGeoManager.Import(args.geo)
68 nav = ROOT.gGeoManager.GetCurrentNavigator()
69
70 failures = []
71 ncopies = 0
72 for n, ev in enumerate(f2["cbmsim"]):
73 tracks = ev.MCTrack
74 for j, trk in enumerate(tracks):
75 if trk.GetProcID() != ROOT.kPTransportation:
76 continue
77 ncopies += 1
78 where = f"event {n}, track {j}"
79 start = (trk.GetStartX(), trk.GetStartY(), trk.GetStartZ())
80 mom = (trk.GetPx(), trk.GetPy(), trk.GetPz())
81 match = [
82 m
83 for m in muons
84 if m["pdg"] == trk.GetPdgCode()
85 and close(start, m["pos"])
86 and close(mom, m["mom"])
87 and close((trk.GetStartT(),), (m["time"],))
88 and close((trk.GetWeight(),), (m["weight"],))
89 ]
90 if not match:
91 failures.append(f"{where}: no input hit at {start} with p = {mom}")
92 continue
93 mother = trk.GetMotherId()
94 if mother < 0:
95 failures.append(f"{where}: plane copy without origin entry")
96 continue
97 origin = tracks[mother]
98 ostart = (origin.GetStartX(), origin.GetStartY(), origin.GetStartZ())
99 if origin.GetPdgCode() != trk.GetPdgCode() or not close(ostart, match[0]["origin"]):
100 failures.append(f"{where}: mother {mother} is not the origin entry")
101 if nav:
102 node = nav.FindNode(*start)
103 material = node.GetVolume().GetMaterial()
104 if material.GetDensity() > args.max_density:
105 failures.append(
106 f"{where}: starts in {node.GetName()} ({material.GetName()}, {material.GetDensity():.3g} g/cm3)"
107 )
108
109 print(f"checked {ncopies} plane copies against {len(muons)} input muons")
110 for msg in failures[:20]:
111 print("FAIL:", msg)
112 if failures:
113 print(f"{len(failures)} failures")
114 return 1
115 if ncopies == 0:
116 print("FAIL: no plane copies found")
117 return 1
118 return 0
119
120
121if __name__ == "__main__":
122 sys.exit(main())
None configure(darkphoton=None)