FairShip
Loading...
Searching...
No Matches
ShipReco.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
5from argparse import ArgumentParser
6
7withHists = True
8
9import resource
10
11
12def mem_monitor() -> None:
13 # Getting virtual memory size
14 pid = os.getpid()
15 with open(os.path.join("/proc", str(pid), "status")) as f:
16 lines = f.readlines()
17 _vmsize = [line for line in lines if line.startswith("VmSize")][0]
18 vmsize = int(_vmsize.split()[1])
19 # Getting physical memory size
20 pmsize = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
21 print(f"memory: virtual = {vmsize / 1.0e3:5.2F} MB physical = {pmsize / 1.0e3:5.2F} MB")
22
23
24import os
25import warnings
26
27import global_variables
28import ROOT
29import rootUtils as ut
30import shipRoot_conf
31
33
34parser = ArgumentParser()
35
36parser.add_argument("-f", "--inputFile", dest="inputFile", help="Input file", required=True)
37parser.add_argument(
38 "-n", "--nEvents", dest="nEvents", help="Number of events to reconstruct", required=False, default=999999, type=int
39)
40parser.add_argument("-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True)
41parser.add_argument(
42 "--noVertexing", dest="noVertexing", help="switch off vertexing", required=False, action="store_true"
43)
44parser.add_argument(
45 "--noStrawSmearing",
46 dest="withNoStrawSmearing",
47 help="no smearing of distance to wire, default on",
48 required=False,
49 action="store_true",
50)
51parser.add_argument(
52 "--withT0", dest="withT0", help="simulate arbitrary T0 and correct for it", required=False, action="store_true"
53)
54parser.add_argument(
55 "-i",
56 "--firstEvent",
57 dest="firstEvent",
58 help="First event of input file to use",
59 required=False,
60 default=0,
61 type=int,
62)
63parser.add_argument(
64 "--patRec",
65 dest="patRec",
66 help="Options for pattern recognition. \n\
67 Segments (default) : drift-circle segments matched across the magnet, requires --trackFitter acts.\n\
68 Truth : MC truth hit assignment -- for simulation only, requires --trackFitter acts.\n\
69 FH : Hough transform (deprecated).\n\
70 AR : Artificial retina (deprecated, default with --trackFitter genfit).\n\
71 TemplateMatching : Tracks are searched for based on the template: track seed + hits within a window around the seed (deprecated).",
72 required=False,
73 choices=["FH", "AR", "TemplateMatching", "Truth", "Segments"],
74 default=None,
75)
76parser.add_argument(
77 "--trackFitter",
78 dest="trackFitter",
79 help="Track fitter to use. \n\
80 acts (default) : writes RecoTracks/RecoVertices/Particles branches.\n\
81 genfit (deprecated) : writes FitTracks/goodTracks branches.",
82 required=False,
83 choices=["genfit", "acts"],
84 default="acts",
85)
86parser.add_argument("-dy", dest="dy", help="Max height of tank", required=False, default=None, type=int)
87parser.add_argument("--Debug", dest="Debug", help="Switch on debugging", required=False, action="store_true")
88parser.add_argument(
89 "--caloScoringPlanePID",
90 dest="caloScoringPlanePID",
91 help="YAML file with energy-dependent electron/hadron/muon confusion matrices for the scoring plane "
92 "(format: CaloScoringPlane/README.md, provided: geometry/caloScoringPlane_pid_provided.yaml); default: perfect PID",
93 required=False,
94 default=None,
95)
96parser.add_argument(
97 "--validation",
98 dest="validation",
99 help="Print reconstruction validation summary after finishing",
100 required=False,
101 action="store_true",
102)
103options = parser.parse_args()
104if options.patRec is None:
105 options.patRec = "Segments" if options.trackFitter == "acts" else "AR"
106if options.trackFitter == "genfit":
107 warnings.warn(
108 "GenFit tracking and vertexing (--trackFitter genfit) are deprecated and will be removed, "
109 "use --trackFitter acts",
110 FutureWarning,
111 stacklevel=1,
112 )
113if options.patRec in ("FH", "AR", "TemplateMatching"):
114 warnings.warn(
115 f"--patRec {options.patRec} is deprecated and will be removed, use --patRec Segments with --trackFitter acts",
116 FutureWarning,
117 stacklevel=1,
118 )
119if options.patRec in ("Truth", "Segments") and options.trackFitter != "acts":
120 parser.error(f"--patRec {options.patRec} requires --trackFitter acts")
121vertexing = not options.noVertexing
122
123
124# need to figure out which geometry was used, only needed if no geo file
125dy = options.dy
126if not options.dy:
127 # try to extract from input file name
128 tmp = options.inputFile.split(".")
129 try:
130 dy = float(tmp[1] + "." + tmp[2])
131 except (ValueError, IndexError):
132 dy = None
133
134print(
135 "configured to process ",
136 options.nEvents,
137 " events from ",
138 options.inputFile,
139 " starting with event ",
140 options.firstEvent,
141 " with option Yheight = ",
142 dy,
143 " with vertexing",
144 vertexing,
145 " and pattern reco ",
146 options.patRec,
147 " and track fitter ",
148 options.trackFitter,
149)
150# Determine output filename (will contain only digi/reco branches)
151if not options.inputFile.find("_rec.root") < 0:
152 outFile = options.inputFile
153 options.inputFile = outFile.replace("_rec.root", ".root")
154else:
155 outFile = options.inputFile.replace(".root", "_rec.root")
156 # outfile should be in local directory
157 tmp = outFile.split("/")
158 outFile = tmp[len(tmp) - 1]
159
160if not options.geoFile:
161 tmp = options.inputFile.replace("ship.", "geofile_full.")
162 options.geoFile = tmp.replace("_rec", "")
163
164fgeo = ROOT.TFile.Open(options.geoFile)
165geoMat = ROOT.genfit.TGeoMaterialInterface() # if only called in ShipDigiReco -> crash, reason unknown
166
167from ShipGeoConfig import load_from_root_file
168
169# load Shipgeo dictionary
170ShipGeo = load_from_root_file(fgeo, "ShipGeo")
171
172h = {}
173if withHists:
174 ut.bookHist(h, "distu", "distance to wire", 100, 0.0, 5.0)
175 ut.bookHist(h, "distv", "distance to wire", 100, 0.0, 5.0)
176 ut.bookHist(h, "disty", "distance to wire", 100, 0.0, 5.0)
177 ut.bookHist(h, "nmeas", "nr measurements", 100, 0.0, 50.0)
178 ut.bookHist(h, "chi2", "Chi2/DOF", 100, 0.0, 20.0)
179
180import shipDet_conf
181
182run = ROOT.FairRunSim()
183run.SetName("TGeant4") # Transport engine
184import tempfile
185
186sink = ROOT.FairRootFileSink(tempfile.mktemp(suffix=".root"))
187run.SetSink(sink)
188ROOT.SetOwnership(sink, False) # C++ FairRun takes ownership
189run.SetUserConfig("g4Config_basic.C") # geant4 transport not used, only needed for creating VMC field
190rtdb = run.GetRuntimeDb()
191# -----Create geometry----------------------------------------------
192modules = shipDet_conf.configure(run, ShipGeo)
193# run.Init()
194sGeo = fgeo["FAIRGeom"]
195import geomGeant4
196
197fieldMaker = None
198if hasattr(ShipGeo.Bfield, "fieldMap"):
199 fieldMaker = geomGeant4.addVMCFields(ShipGeo, "", True, withVirtualMC=False)
200
201# make global variables
202global_variables.debug = options.Debug
203global_variables.fieldMaker = fieldMaker
204global_variables.withT0 = options.withT0
205global_variables.patRec = options.patRec
206global_variables.trackFitter = options.trackFitter
207global_variables.vertexing = vertexing
208global_variables.ShipGeo = ShipGeo
209global_variables.modules = modules
210global_variables.withNoStrawSmearing = options.withNoStrawSmearing
211global_variables.h = h
212global_variables.iEvent = 0
213global_variables.caloScoringPlanePIDFile = options.caloScoringPlanePID
214
215# import reco tasks
216import shipDigiReco
217
218SHiP = shipDigiReco.ShipDigiReco(options.inputFile, outFile, fgeo, validation=options.validation)
219nEntries = SHiP.sTree.GetEntries()
220# main loop
221for global_variables.iEvent in range(options.firstEvent, min(nEntries, options.firstEvent + options.nEvents)):
222 if global_variables.iEvent % 1000 == 0 or global_variables.debug:
223 print("event ", global_variables.iEvent)
224 rc = SHiP.sTree.GetEvent(global_variables.iEvent)
225 SHiP.digitize()
226 SHiP.reconstruct()
227 SHiP.recoTree.Fill()
228# memory monitoring
229# mem_monitor()
230# end loop over events
231SHiP.finish()
None mem_monitor()
Definition ShipReco.py:12
addVMCFields(shipGeo, str controlFile="", bool verbose=False, bool withVirtualMC=True)
configure(run, ship_geo, str|None geofile=None)
None configure(darkphoton=None)