FairShip
Loading...
Searching...
No Matches
prepareEvents.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
5"""Script to collect muons hitting either the UBT extended plane, or the SBT, including soft interaction products, and DIS events, to a ROOT file."""
6
7"""
8Begin of pythia block to avoid aliBuild error
9Uncomment for running with aliBuild
10"""
11# import cppyy
12
19"""
20End of pythia block to avoid aliBuild error
21"""
22
23import argparse
24import logging
25import math
26import sys
27import time
28from pathlib import Path
29
30import ROOT as r
31from filterEvents import load_muon_shield_field
32
33print("Loading ShipMuDIS", flush=True)
34if r.gSystem.Load("libShipMuDIS.so") < 0:
35 raise RuntimeError("Could not load libShipMuDIS.so")
36print("ShipMuDIS loaded", flush=True)
37pdg = r.TDatabasePDG.Instance()
38
39parser = argparse.ArgumentParser()
40parser.add_argument("-f", "--inputfile", help="full path to muon background files", required=True)
41parser.add_argument(
42 "-o",
43 "--outputfile",
44 help="custom outputfile name",
45 default="muonsProduction_wsoft.root",
46)
47parser.add_argument("-n", "--n_events", type=int, default=-1)
48parser.add_argument("-s", "--start_event", type=int, default=0)
49parser.add_argument("--seed", type=int, help="Random seed for Pythia6 and ROOT (default: time-based)")
50parser.add_argument("--check-all-volumes", action="store_true", help="Scan all geometry volumes for diagnostics")
51parser.add_argument("-z", "--z_max", type=float, default=20000)
52parser.add_argument("--z_min", type=float, default=2500, help="Minimum z in cm for diagnostics (default: 2500)")
53parser.add_argument("-d", "--nDIS", help="Number of DIS per muon to generate", required=False, default=1000, type=int)
54parser.add_argument("-g", "--geoFile", dest="geoFile", help="ROOT geofile", required=True)
55parser.add_argument("--muon-shield-field-map", help="Shield field map (default: geometry shieldName)")
56parser.add_argument("--muon-shield-field-z", type=float, help="Shield map z offset in cm (default: geometry entrance)")
57parser.add_argument(
58 "--poca-jump-threshold",
59 type=float,
60 default=1.0,
61 help="Count transverse jumps between measurement lines larger than this value in cm (default: 1)",
62)
63parser.add_argument(
64 "--debug",
65 help="Control FairLogger verbosity: 0=info (default), 1=+debug, 2=+debug1, 3=+debug2",
66 default=0,
67 type=int,
68 choices=range(0, 4),
69)
70
71args = parser.parse_args()
72if not math.isfinite(args.poca_jump_threshold) or args.poca_jump_threshold < 0:
73 parser.error("--poca-jump-threshold must be finite and nonnegative")
74
75if args.debug == 0:
76 r.gErrorIgnoreLevel = r.kWarning
77
78# Configure FairLogger verbosity based on debug level
79r.gInterpreter.ProcessLine('#include "FairLogger.h"')
80if args.debug == 0:
81 r.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("info");')
82 logging.basicConfig(level=logging.INFO)
83elif args.debug == 1:
84 r.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug");')
85 logging.basicConfig(level=logging.DEBUG)
86elif args.debug == 2:
87 r.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug1");')
88 logging.basicConfig(level=logging.DEBUG)
89elif args.debug == 3:
90 r.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug2");')
91 logging.basicConfig(level=logging.DEBUG)
92
93print(logging.getLogger().getEffectiveLevel())
94logging.debug("Debug messages ON")
95
96logging.info(f"Path to MuonBackground : {args.inputfile}")
97
98# Keep the seed nonzero for ROOT and below Pythia6's 900000000 limit.
99theseed = ((args.seed if args.seed is not None else time.time_ns()) - 1) % 899999999 + 1
100logging.info("Random seed: %d", theseed)
101r.gRandom.SetSeed(theseed)
102
103# Read geofile to get gGeoManager
104r.TGeoManager.Import(args.geoFile)
105
106if not r.gGeoManager:
107 logging.error("Failed to load geometry from '%s'", args.geoFile)
108 sys.exit(1)
109
110logging.info("Geometry successfully loaded.")
111
112# Check
113r.gGeoManager.Print() # Read geometry
114
115muDis = r.MuDISProcessor()
116# Keep the maker alive: it owns the map borrowed by the path processor.
117field_maker = r.ShipFieldMaker()
118shield_field, shield_path = load_muon_shield_field(
119 field_maker, args.geoFile, args.muon_shield_field_map, args.muon_shield_field_z
120)
121muDis.SetMuonShieldField(shield_field, r.gGeoManager)
122logging.info("Muon shield field map: %s", shield_path)
123if args.check_all_volumes:
124 muDis.CheckAllVolumes()
125muDis.SetPocaJumpThreshold(args.poca_jump_threshold)
126ok = muDis.init(args.n_events, args.start_event, 2.0, args.nDIS, theseed, args.z_max, args.z_min)
127if not ok:
128 print("Invalid initialisation. Doing nothing.")
129 sys.exit(1)
130
131p = Path(args.inputfile)
132
133if p.is_file():
134 muDis.process_file(args.inputfile, args.outputfile)
135
136elif p.is_dir():
137 pattern = "sim_"
138
139 matching_files = [
140 str(path) for path in p.rglob("*") if path.is_file() and pattern in path.name and ".root" in path.name
141 ]
142
143 print(f"Found {len(matching_files)} files:")
144 if len(matching_files) < 1:
145 print("No input file found in path.")
146 sys.exit(1)
147 for f in matching_files:
148 print(f)
149
150 muDis.process_file(matching_files, args.outputfile)
151else:
152 print("Inputfile string does not exist")
153 sys.exit(1)