83 parser = argparse.ArgumentParser(description=__doc__)
84 parser.add_argument(
85 "-f",
86 "--inputfile",
87 nargs="+",
88 required=True,
89 help="Input file(s) or directories to search recursively for .root files",
90 )
91 parser.add_argument(
92 "--ignore-input-containing",
93 action="append",
94 default=None,
95 metavar="STRING",
96 help="Ignore discovered input files whose filename contains STRING (repeatable; default: filtered)",
97 )
98 parser.add_argument("-o", "--outputfile", required=True, help="New ROOT file (must not exist)")
99 parser.add_argument(
100 "-n",
101 "--n_events",
102 type=int,
103 default=-1,
104 help="Number of input events to process (-1: all remaining events; default: -1)",
105 )
106 parser.add_argument(
107 "-s", "--start_event", type=int, default=0, help="First input event to process (zero-based; default: 0)"
108 )
109 parser.add_argument(
110 "--filter-option",
111 type=int,
112 choices=(0, 1, 2),
113 default=0,
114 help="0: charged hits at Tr1; 1: two charged tracks at tracking and timing planes; "
115 "2: any non-neutrino daughter entering the Tr1-to-calorimeter volume",
116 )
117 parser.add_argument(
118 "--detailed-histograms",
119 action="store_true",
120 help="Also store redundant projections and per-cell z efficiency inputs",
121 )
122 parser.add_argument("--min-charged", type=int, default=2, help="Minimum charged daughters for filter option 0")
123 parser.add_argument("--exclude-muons", action="store_true")
124 parser.add_argument("-g", "--geoFile", help="ROOT geometry containing the first SST station (Tr1)")
125 parser.add_argument(
126 "--field-map", "--field_map", dest="field_map", help="Override geometry ShipGeo.Bfield.fieldMap"
127 )
128 parser.add_argument("--detector-z", type=float, help="Acceptance plane z in cm (default: Tr1 centre)")
129 parser.add_argument("--field-z", type=float, help="Map z offset in cm (default: geometry ShipGeo.Bfield.z)")
130 parser.add_argument("--muon-shield-field-map", help="Override files/<ShipGeo.shieldName>.root for the shield")
131 parser.add_argument(
132 "--muon-shield-field-z", type=float, help="Shield map z offset in cm (default: ShipGeo.muShield.Entrance[0])"
133 )
134 parser.add_argument(
135 "--filter-efficiency-x-bounds",
136 type=float,
137 nargs=2,
138 metavar=("MIN", "MAX"),
139 default=(-200.0, 200.0),
140 help="X-axis bounds in cm (default: -200 200)",
141 )
142 parser.add_argument(
143 "--filter-efficiency-x-bins", type=int, default=5, help="Odd number of X bins, centred on zero (default: 5)"
144 )
145 parser.add_argument(
146 "--filter-efficiency-y-bounds",
147 type=float,
148 nargs=2,
149 metavar=("MIN", "MAX"),
150 default=(-300.0, 300.0),
151 help="Y-axis bounds in cm (default: -300 300)",
152 )
153 parser.add_argument(
154 "--filter-efficiency-y-bins", type=int, default=5, help="Odd number of Y bins, centred on zero (default: 5)"
155 )
156 parser.add_argument(
157 "--filter-efficiency-z-bounds",
158 type=float,
159 nargs=2,
160 metavar=("MIN", "MAX"),
161 default=(2500.0, 9500.0),
162 help="Z-axis bounds in cm (default: 2500 9500)",
163 )
164 parser.add_argument("--filter-efficiency-z-bins", type=int, default=70, help="Number of Z bins (default: 70)")
165 parser.add_argument("--no-detector-acceptance", action="store_true", help="Use charged multiplicity alone")
166 parser.add_argument(
167 "--pythia-decays", action="store_true", help="Decay daughters upstream of Tr1 with Pythia8 before filtering"
168 )
169 parser.add_argument(
170 "--pythia-decay-seed", type=int, default=0, help="Pythia8 daughter-decay random seed (0: time-based, default)"
171 )
172 parser.add_argument(
173 "--debug",
174 help="Control FairLogger verbosity: 0=info (default), 1=+debug, 2=+debug1, 3=+debug2",
175 default=0,
176 type=int,
177 choices=range(0, 4),
178 )
179 args = parser.parse_args()
180 if args.min_charged < 0 or args.start_event < 0 or args.n_events < -1:
181 parser.error("Counts must be nonnegative, except -n -1 for all entries")
182 if args.ignore_input_containing is None:
183 args.ignore_input_containing = ["filtered"]
184 if any(not pattern for pattern in args.ignore_input_containing):
185 parser.error("--ignore-input-containing must not be empty")
186 if not 0 <= args.pythia_decay_seed <= 900000000:
187 parser.error("--pythia-decay-seed must be in [0, 900000000]")
188 for axis, bounds, bins, centered in (
189 ("x", args.filter_efficiency_x_bounds, args.filter_efficiency_x_bins, True),
190 ("y", args.filter_efficiency_y_bounds, args.filter_efficiency_y_bins, True),
191 ("z", args.filter_efficiency_z_bounds, args.filter_efficiency_z_bins, False),
192 ):
193 if not all(math.isfinite(value) for value in bounds) or bounds[0] >= bounds[1] or bins <= 0:
194 parser.error(f"Filter-efficiency {axis} axis requires finite increasing bounds and positive bins")
195 if centered and (bins % 2 == 0 or not math.isclose(bounds[0], -bounds[1], rel_tol=1.0e-12, abs_tol=1.0e-12)):
196 parser.error(f"Filter-efficiency {axis} axis requires symmetric bounds and an odd bin count to centre zero")
197 if (not args.no_detector_acceptance or args.pythia_decays) and not args.geoFile:
198 parser.error("Detector acceptance requires -g/--geoFile")
199 if args.pythia_decays and args.no_detector_acceptance:
200 parser.error("--pythia-decays requires detector acceptance to determine the Tr1 position")
201 if args.filter_option != 0 and args.no_detector_acceptance:
202 parser.error("Filter options 1 and 2 require detector acceptance")
203 if args.filter_option != 0 and args.detector_z is not None:
204 parser.error("--detector-z applies only to filter option 0; options 1 and 2 use geometry extents")
205 for value in (args.detector_z, args.field_z, args.muon_shield_field_z):
206 if value is not None and not math.isfinite(value):
207 parser.error("Detector and field z positions must be finite")
208 auxiliary_paths = {
209 Path(p).expanduser().resolve() for p in (args.geoFile, args.field_map, args.muon_shield_field_map) if p
210 }
211
212 _field_maker = field = shield_field = geometry = None
213 if not args.no_detector_acceptance:
214 geometry_path = str(Path(args.geoFile).expanduser().resolve())
215 if not Path(geometry_path).is_file():
216 parser.error(f"Geometry does not exist: {geometry_path}")
217 geometry = ROOT.TGeoManager.Import(geometry_path)
218 if not geometry:
219 parser.error(f"Cannot load geometry: {geometry_path}")
220 try:
221 _field_maker, field, field_path = load_spectrometer_field(geometry_path, args.field_map, args.field_z)
222 except (AttributeError, KeyError, ValueError, RuntimeError, OSError) as error:
223 parser.error(
224 f"Cannot configure SST field (use --field-map/--field-z to override geometry settings): {error}"
225 )
226 auxiliary_paths.add(field_path)
227 if geometry.GetVolume("MuonShieldArea") or args.muon_shield_field_map or args.muon_shield_field_z is not None:
228 try:
229 shield_field, shield_path = load_muon_shield_field(
230 _field_maker,
231 geometry_path,
232 args.muon_shield_field_map,
233 args.muon_shield_field_z,
234 )
235 except (AttributeError, IndexError, KeyError, ValueError, RuntimeError, OSError) as error:
236 parser.error(
237 f"Cannot configure muon shield field (use --muon-shield-field-map/"
238 f"--muon-shield-field-z to override geometry settings): {error}"
239 )
240 auxiliary_paths.add(shield_path)
241 file_names = []
242 seen = set()
243 output_path = Path(args.outputfile).resolve()
244 for name in args.inputfile:
245 path = Path(name).expanduser()
246 if path.is_dir():
247 candidates = sorted(
248 p
249 for p in path.rglob("*.root")
250 if p.is_file() and not any(pattern in p.name for pattern in args.ignore_input_containing)
251 )
252 elif path.is_file():
253 candidates = [path]
254 else:
255 parser.error(f"Input does not exist or is not a file/directory: {name}")
256 for candidate in candidates:
257 resolved = candidate.resolve()
258 if resolved in auxiliary_paths:
259 continue
260 if resolved == output_path:
261 parser.error(f"Output file is also an input: {candidate}")
262 if resolved not in seen:
263 seen.add(resolved)
264 file_names.append(str(candidate))
265 if not file_names:
266 parser.error("No ROOT input files found")
267 print(f"Found {len(file_names)} input file(s): ", file_names, flush=True)
268
269
270 wall_start = time.perf_counter()
271 cpu_start = time.process_time()
272 if ROOT.gSystem.Load("libShipMuDIS.so") < 0:
273 raise RuntimeError("Cannot load libShipMuDIS.so")
274 if args.debug == 0:
275 ROOT.gErrorIgnoreLevel = ROOT.kWarning
276 ROOT.gInterpreter.ProcessLine('#include "FairLogger.h"')
277 if args.debug == 0:
278 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("info");')
279 logging.basicConfig(level=logging.INFO)
280 elif args.debug == 1:
281 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug");')
282 logging.basicConfig(level=logging.DEBUG)
283 elif args.debug == 2:
284 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug1");')
285 else:
286 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug2");')
287 selection = ROOT.MuDISFilter()
288 selection.init(args.n_events, args.start_event)
289 selection.SetFilterOption(args.filter_option)
290 selection.SetDetailedHistograms(args.detailed_histograms)
291 selection.SetMinChargedDaughters(args.min_charged)
292 selection.SetIncludeMuons(not args.exclude_muons)
293 selection.SetFilterEfficiencyBinning(
294 args.filter_efficiency_x_bounds[0],
295 args.filter_efficiency_x_bounds[1],
296 args.filter_efficiency_x_bins,
297 args.filter_efficiency_y_bounds[0],
298 args.filter_efficiency_y_bounds[1],
299 args.filter_efficiency_y_bins,
300 args.filter_efficiency_z_bounds[0],
301 args.filter_efficiency_z_bounds[1],
302 args.filter_efficiency_z_bins,
303 )
304 if args.no_detector_acceptance:
305 selection.SetUseDetectorAcceptance(False)
306 else:
307 assert geometry is not None
308 detector_z = args.detector_z if args.detector_z is not None else float("nan")
309 selection.SetDetectorAcceptance(field, geometry, detector_z, shield_field or ROOT.nullptr)
310 if args.filter_option == 0:
311 print(f"Detector acceptance: |x| <= 200 cm, |y| <= 300 cm at z = {selection.GetDetectorZ():g} cm")
312 elif args.filter_option == 1:
313 print("Detector acceptance: filter option 1, individual tracking/TD geometry bounds")
314 else:
315 print("Detector acceptance: filter option 2, |x| <= 200 cm, |y| <= 300 cm")
316 if args.pythia_decays:
317 selection.SetPythiaDecaySeed(args.pythia_decay_seed)
318 selection.SetUsePythiaDecays(True)
319 inputs = ROOT.std.vector("string")()
320 for name in file_names:
321 inputs.push_back(name)
322 selection.process_file(inputs, args.outputfile)
323 wall_seconds = time.perf_counter() - wall_start
324 cpu_seconds = time.process_time() - cpu_start
325 cpu_percent = 100.0 * cpu_seconds / wall_seconds if wall_seconds else 0.0
326 print(
327 f"Performance (initialization + filtering): wall time {wall_seconds:.3f} s, "
328 f"CPU time {cpu_seconds:.3f} s, average CPU utilization {cpu_percent:.1f}%"
329 )
330
331