FairShip
Loading...
Searching...
No Matches
run_simScript.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
5import glob
6import json
7import os
8import sys
9import uuid
10from argparse import ArgumentParser, Namespace
11from array import array
12from datetime import datetime
13from typing import cast
14
15import geometry_config
16import geometry_from_file
17import ROOT
18import rootUtils as ut
19import shipRoot_conf
20import shipunit as u
21import validationTools as validation_tools
22from ShipGeoConfig import load_from_root_file
23
24
25def _fraction_0_1(value: str) -> float:
26 v = float(value)
27 if not 0.0 <= v <= 1.0:
28 raise ValueError("--chargeFraction must be between 0 and 1")
29 return v
30
31
32# Default HNL parameters
33theHNLMass = 1.0 * u.GeV
34theProductionCouplings = theDecayCouplings = None
35
36# Default dark photon parameters
37theDPmass = 0.2 * u.GeV
38
39mcEngine = "TGeant4"
40
41inclusive = "c" # True = all processes if "c" only ccbar -> HNL, if "b" only bbar -> HNL, if "bc" only Bc+/Bc- -> HNL, and for darkphotons: if meson = production through meson decays, pbrem = proton bremstrahlung, qcd = ffbar -> DP.
42
43MCTracksWithHitsOnly = False # copy particles which produced a hit and their history
44MCTracksWithEnergyCutOnly = True # copy particles above a certain kin energy cut
45MCTracksWithHitsOrEnergyCut = False # or of above, factor 2 file size increase compared to MCTracksWithEnergyCutOnly
46
47charmonly = False # option to be set with -A to enable only charm decays, charm x-sec measurement
48HNL = True
49
50inputFile = "$EOSSHIP/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-978Bpot.root"
51defaultInputFile = True
52
53# Input files the generators actually read. Only these belong in the output
54# FileSummary: inputFile above is a placeholder that survives untouched for
55# generators which need no input at all (particle gun, cosmics).
56usedInputFiles: list[str] = []
57
58
59def useInputFile(paths):
60 """Check that the generator input exists and record it for the FileSummary."""
61 ut.checkFileExists(paths)
62 usedInputFiles.extend([paths] if isinstance(paths, str) else list(paths))
63
64
65parser = ArgumentParser()
66
67parser.add_argument("--evtcalc", help="Use EventCalc", action="store_true")
68parser.add_argument("--Pythia6", dest="pythia6", help="Use Pythia6", action="store_true")
69parser.add_argument("--Pythia8", dest="pythia8", help="Use Pythia8", action="store_true")
70parser.add_argument(
71 "--EvtGenDecayer",
72 dest="evtgen_decayer",
73 help="Use TEvtGenDecayer for J/psi and other quarkonium decays",
74 action="store_true",
75)
76parser.add_argument(
77 "--targetOffset", dest="targetOffset", help="z offset for the target coordinate", default=0.0, type=float
78)
79subparsers = parser.add_subparsers(dest="command", help="Which mode to run")
80# === PG subcommand ===
81pg_parser = subparsers.add_parser("PG", help="Use Particle Gun")
82
83pg_parser.add_argument(
84 "--multiplePG", help="Multiple particle guns in a x-y plane at a fixed z or in a 3D volume", action="store_true"
85)
86pg_parser.add_argument("--pID", dest="pID", default=22, type=int, help="id of particle used by the gun (default=22)")
87pg_parser.add_argument(
88 "--Estart", default=10, type=float, help="start of energy range of particle gun (default=10 GeV)"
89)
90pg_parser.add_argument(
91 "--histoFile",
92 dest="histoFile",
93 default=None,
94 help="File with a histogram to generate from. Repeat for multiple files",
95 action="append",
96)
97pg_parser.add_argument(
98 "--histoName",
99 dest="histoName",
100 default=None,
101 help="Histogram name to generate from. Repeat for multiple files",
102 action="append",
103)
104pg_parser.add_argument(
105 "--histoX",
106 dest="histoX",
107 default=None,
108 help="The variable of the histogram X axis. Repeat for multiple files",
109 action="append",
110)
111pg_parser.add_argument(
112 "--histoY",
113 dest="histoY",
114 default=None,
115 help="The variable of the histogram Y axis. Repeat for multiple files",
116 action="append",
117)
118pg_parser.add_argument(
119 "--histoZ",
120 dest="histoZ",
121 default=None,
122 help="The variable of the histogram Z axis. Repeat for multiple files",
123 action="append",
124)
125
126pg_parser.add_argument(
127 "--bothCharges",
128 dest="bothCharges",
129 default=False,
130 action="store_true",
131 help="Generate both charges of given particle ID",
132)
133pg_parser.add_argument(
134 "--chargeFraction",
135 dest="chargeFraction",
136 type=_fraction_0_1,
137 default=0.5,
138 help="Fraction of chosen charge from pID to generate [0,1]",
139)
140pg_parser.add_argument("--Eend", default=10, type=float, help="end of energy range of particle gun (default=10 GeV)")
141pg_parser.add_argument("--Vx", dest="Vx", default=0, type=float, help="x position of particle gun (default=0 cm)")
142pg_parser.add_argument("--Vy", dest="Vy", default=0, type=float, help="y position of particle gun (default=0 cm)")
143pg_parser.add_argument("--Vz", dest="Vz", default=0, type=float, help="z position of particle gun (default=0 cm)")
144pg_parser.add_argument(
145 "--smearMode",
146 dest="smearMode",
147 default="uniform",
148 help="Form of the vertex smearing for the particle gun",
149 type=str,
150)
151pg_parser.add_argument(
152 "--multiplicity", dest="multiplicity", type=int, default=1, help="How many to generate per event"
153)
154pg_parser.add_argument(
155 "--Dx", dest="Dx", type=float, help="size of the full uniform spread of PG xpos: (Vx - Dx/2, Vx + Dx/2)"
156)
157pg_parser.add_argument(
158 "--Dy", dest="Dy", type=float, help="size of the full uniform spread of PG ypos: (Vy - Dy/2, Vy + Dy/2)"
159)
160pg_parser.add_argument(
161 "--Dz",
162 dest="Dz",
163 type=float,
164 default=0,
165 help="size of the full uniform spread of PG zpos: (Vz - Dz/2, Vz + Dz/2), with --smearMode uniform3d",
166)
167pg_parser.add_argument(
168 "--commonVertex",
169 action="store_true",
170 help="give all particles of an event the same vertex (with --multiplePG, drawn once per event)",
171)
172pg_parser.add_argument(
173 "--momentumModel", dest="momentumModel", default=0, type=int, help="Select a model to generate the momentum with"
174)
175pg_parser.add_argument(
176 "--modelPar",
177 dest="modelPar",
178 action="append",
179 help="Momentum model parameters. You must specify them all in order",
180 type=float,
181)
182pg_parser.add_argument(
183 "--showPGModels",
184 dest="showPGModels",
185 action="store_true",
186 default=False,
187 help="Print out the PG models that are available",
188)
189pg_parser.add_argument("--thetaMin", type=float, default=0, help="Minimum polar angle [deg] (default: 0)")
190pg_parser.add_argument("--thetaMax", type=float, default=0, help="Maximum polar angle [deg] (default: 0)")
191# === End of PG commands ===
192# === Genie subcommand ===
193genie_parser = subparsers.add_parser("Genie", help="Genie for reading and processing neutrino interactions")
194genie_parser.add_argument(
195 "--GenieOption",
196 dest="GenieOption",
197 default="simple_gevgen",
198 choices=["simple_gevgen", "genie_geometry"],
199 help="Genie generation option: (simple_gevgen, genie_geometry)",
200)
201genie_parser.add_argument(
202 "--z_start_nu",
203 dest="z_start_nu",
204 default=2844.2850,
205 type=float,
206 help="Genie neutrino start z start position (default=2844.2850 cm)",
207)
208genie_parser.add_argument(
209 "--z_end_nu",
210 dest="z_end_nu",
211 default=3180.4350,
212 type=float,
213 help="Genie neutrino end z position (default=3180.4350 cm)",
214)
215# === End of Genie subcommand ===
216parser.add_argument(
217 "-A",
218 help="b: signal from b, c: from c (default), bc: from Bc, inclusive, or for dark photon: meson,pbrem,qcd",
219 default="c",
220)
221parser.add_argument(
222 "--NuRadio",
223 dest="nuradio",
224 help="misuse GenieGenerator for neutrino radiography and geometry timing test",
225 action="store_true",
226)
227parser.add_argument(
228 "--notSaveGeoFile",
229 dest="save_geofile",
230 default=True,
231 action="store_false",
232 help="Turn off the saving of the geofile at the end.",
233)
234parser.add_argument(
235 "--notSaveParFile",
236 dest="save_parfile",
237 default=True,
238 action="store_false",
239 help="Turn off the saving of the parameter files at the end.",
240)
241
242parser.add_argument("--Ntuple", dest="ntuple", help="Use ntuple as input", action="store_true")
243parser.add_argument("--ttree", help="Use TTree as input", action="store_true")
244parser.add_argument(
245 "--MuonBack",
246 dest="muonback",
247 help="Generate events from muon background file, --Cosmics=0 for cosmic generator data",
248 action="store_true",
249)
250parser.add_argument(
251 "--FollowMuon", dest="followMuon", help="Make muonshield active to follow muons", action="store_true"
252)
253parser.add_argument(
254 "--FastMuon",
255 dest="fastMuon",
256 help="Only transport muons for a fast muon only background estimate",
257 action="store_true",
258)
259parser.add_argument(
260 "--MuonBackFromOrigin",
261 dest="muonBackFromOrigin",
262 help="MuonBack with run_fixedTarget input: start the scored tracks at their production vertex instead of where "
263 "they entered the scoring plane. Biased, as the path to the plane is simulated twice; only for validation",
264 action="store_true",
265)
266parser.add_argument(
267 "--MuonBackAllowNoAbsorberField",
268 dest="muonBackAllowNoAbsorberField",
269 help="MuonBack: accept run_fixedTarget input that was simulated without the hadron absorber field",
270 action="store_true",
271)
272parser.add_argument(
273 "--phiRandom",
274 help="only relevant for muon background generator, random phi (not with run_fixedTarget input)",
275 action="store_true",
276)
277parser.add_argument(
278 "--SmearBeam", dest="SmearBeam", help="Standard deviation of beam smearing [cm]", default=0.8, type=float
279)
280parser.add_argument("--PaintBeam", dest="PaintBeam", help="Radius of beam painting [cm]", default=5, type=float)
281parser.add_argument(
282 "--Cosmics", dest="cosmics", help="Use cosmic generator, argument switch for cosmic generator 0 or 1", default=None
283) # 0/1 selects CosmicsGenerator::Init(largeMom); not store_true, since "0" must enable cosmics with largeMom=False
284parser.add_argument("--MuDIS", dest="mudis", help="Use muon deep inelastic scattering generator", action="store_true")
285parser.add_argument(
286 "--NewMuDIS",
287 dest="newmudis",
288 help="Replay prepared/filtered MuonDIS events with NewMuDISGenerator",
289 action="store_true",
290)
291parser.add_argument("--RpvSusy", dest="RPVSUSY", help="Generate events based on RPV neutralino", action="store_true")
292parser.add_argument("--FixedTarget", dest="fixedTarget", help="Enable fixed target simulation", action="store_true")
293parser.add_argument("--DarkPhoton", help="Generate dark photons", action="store_true")
294parser.add_argument("--SusyBench", dest="RPVSUSYbench", help="Generate HP Susy", type=int, default=2)
295parser.add_argument(
296 "-m",
297 "--mass",
298 dest="theMass",
299 help=f"Mass of hidden particle, default {theHNLMass} GeV for HNL, {theDPmass} GeV for DP",
300 default=None,
301 type=float,
302)
303parser.add_argument(
304 "-c",
305 "--couplings",
306 "--coupling",
307 dest="thecouplings",
308 help="couplings 'U2e,U2mu,U2tau' or -c 'U2e,U2mu,U2tau' to set list of HNL couplings.\
309 TP default for HNL, ctau=53.3km",
310 default="0.447e-9,7.15e-9,1.88e-9",
311)
312parser.add_argument(
313 "-cp",
314 "--production-couplings",
315 dest="theprodcouplings",
316 help="production couplings 'U2e,U2mu,U2tau' to set the couplings for HNL production only",
317 default=None,
318)
319parser.add_argument(
320 "-cd",
321 "--decay-couplings",
322 dest="thedeccouplings",
323 help="decay couplings 'U2e,U2mu,U2tau' to set the couplings for HNL decay only",
324 default=None,
325)
326parser.add_argument(
327 "-e", "--epsilon", dest="theDPepsilon", help="to set mixing parameter epsilon", default=0.00000008, type=float
328)
329parser.add_argument(
330 "-n",
331 "--nEvents",
332 dest="nEvents",
333 help="Number of events to generate (input muons for --NewMuDIS; -1: all)",
334 default=None,
335 type=int,
336)
337parser.add_argument(
338 "-i", "--firstEvent", help="First input entry to use (muon entry for --NewMuDIS)", default=0, type=int
339)
340parser.add_argument(
341 "-s",
342 "--seed",
343 dest="theSeed",
344 help="Seed for random number. Only for experts, see TRrandom::SetSeed documentation",
345 default=0,
346 type=int,
347)
348parser.add_argument(
349 "-S",
350 "--sameSeed",
351 dest="sameSeed",
352 help="can be set to an integer for the muonBackground simulation with specific seed for each muon, only for experts!",
353 default=False,
354 type=int,
355)
356parser.add_argument(
357 "-f",
358 dest="inputFile",
359 action="append",
360 help="Input file (repeat -f for multiple files)",
361 default=None,
362)
363parser.add_argument(
364 "--remote-input",
365 dest="remoteInput",
366 help="Treat -f/--inputFile values as remote ROOT paths/URLs and skip local glob expansion",
367 action="store_true",
368)
369parser.add_argument("--nFiles", dest="nFiles", help="Number of input files to process", default=-1, type=int)
370parser.add_argument(
371 "-g",
372 "--geofile",
373 dest="geofile",
374 help="Transport particles through the geometry stored in this geometry file, written by an earlier"
375 " run_simScript.py, instead of the one the current code builds. The geometry configuration stored in the file is"
376 " used, so geometry options (-Y, --strawDesign, --shieldName, --helium, --vacuums, --SND, --noSND, --SND_design,"
377 " --target-yaml) cannot be given. The stored geometry may differ from the one the current code builds, e.g. in"
378 " its passive volumes, but must have every volume with a magnetic field that the current code builds; other"
379 " differences, such as missing sensitive volumes, which then record no hits, are printed as a warning. A"
380 " detector that the current code cannot build from the stored configuration (e.g. the UBT of a file from before"
381 " the scintillator tiles) is left out, with a warning.",
382 default=None,
383)
384parser.add_argument("-o", "--output", dest="outputDir", help="Output directory", default=".")
385parser.add_argument(
386 "-r",
387 "--run-number",
388 dest="run_number",
389 help="Numeric simulation ID to reuse instead of generating a new UUID",
390 default=None,
391 type=int,
392)
393parser.add_argument(
394 "--reproducible",
395 dest="reproducible",
396 help="Reduce nondeterministic log output for reproducibility/testing",
397 action="store_true",
398)
399parser.add_argument("-Y", dest="dy", help="max height of vacuum tank", default=6.0, type=float)
400parser.add_argument(
401 "--strawDesign",
402 help="Tracker station frame material: 4=Aluminium; 10=steel (default)",
403 default=10,
404 type=int,
405 choices=[4, 10],
406)
407parser.add_argument(
408 "-F",
409 dest="deepCopy",
410 help="default = False: copy only stable particles to stack, except for HNL events",
411 action="store_true",
412)
413parser.add_argument("-t", "--test", dest="testFlag", help="quick test", action="store_true")
414parser.add_argument("--dry-run", dest="dryrun", help="stop after initialize", action="store_true")
415parser.add_argument("-D", "--display", dest="eventDisplay", help="store trajectories", action="store_true")
416parser.add_argument(
417 "--shieldName",
418 help="The name of the muon shield in the database to use.",
419 default="TRY_2026",
420 choices=["TRY_2026"],
421)
422parser.add_argument(
423 "--MesonMother", dest="MM", help="Choose DP production meson source: pi0, eta, omega, eta1, eta11", default="pi0"
424)
425parser.add_argument(
426 "--debug",
427 help="Control FairLogger verbosity: 0=info (default), 1=+debug, 2=+debug1, 3=+debug2",
428 default=0,
429 type=int,
430 choices=range(0, 4),
431)
432parser.add_argument("--print-fields", help="Print VMC fields and weights information", action="store_true")
433parser.add_argument("--check-overlaps", help="Perform geometry overlap checking", action="store_true")
434parser.add_argument(
435 "--field_map",
436 default=None,
437 help="Specify spectrometer field map as files/<name>.root. Default set in geometry_config.py: files/2026_07_02_MainSpectrometerField_V21_2455.root",
438)
439parser.add_argument(
440 "--z-offset", dest="z_offset", help="z-offset for the FixedTargetGenerator [mm]", default=-84.0, type=float
441)
442parser.add_argument(
443 "--helium",
444 dest="decayVolMed",
445 help="Set Decay Volume medium to helium. NOOP, as default is helium",
446 action="store_const",
447 const="helium",
448 default="helium",
449)
450parser.add_argument(
451 "--vacuums",
452 dest="decayVolMed",
453 help="Set Decay Volume medium to vacuum(vessel structure changes)",
454 action="store_const",
455 const="vacuums",
456 default="helium",
457)
458
459parser.add_argument("--SND", dest="SND", help="Activate SND.", action="store_true")
460parser.add_argument(
461 "--SND_design",
462 help="Choose SND design(s) among [1,2,...] or 'all' to enable all. 1: EmulsionTarget, 2: MTC + SiliconTarget",
463 nargs="+",
464 default=[2],
465)
466parser.add_argument(
467 "--noSND", dest="SND", help="Deactivate SND. NOOP, as it currently defaults to off.", action="store_false"
468)
469parser.add_argument(
470 "--target-yaml",
471 help="Path to the yaml target config file",
472 default=os.path.expandvars("$FAIRSHIP/geometry/target_config.yaml"),
473)
474parser.add_argument(
475 "--tag", dest="output_tag", help="Custom tag for output files instead of auto-generated UUID", default=None
476)
477parser.add_argument(
478 "--validation",
479 dest="validation",
480 help="Print an extended simulation validation summary after the run",
481 action="store_true",
482)
483
484
485options = parser.parse_args()
486
487if options.nEvents is None and not options.newmudis:
488 options.nEvents = 100
489
490if options.mudis and options.newmudis:
491 parser.error("--MuDIS and --NewMuDIS are mutually exclusive")
492# Handle SND_design: allow 'all' (case-insensitive) or list of ints
493available_snd_designs = [1, 2] # Extend this list as new designs are added
494if any(str(x).lower() == "all" for x in options.SND_design):
495 options.SND_design = available_snd_designs
496else:
497 try:
498 options.SND_design = [int(x) for x in options.SND_design]
499 except Exception:
500 print("Invalid value for --SND_design. Use integers or 'all'.")
501 sys.exit(1)
502
503if options.A != "c":
504 inclusive = options.A
505 if options.A == "b":
506 inputFile = "$EOSSHIP/eos/experiment/ship/data/Beauty/Cascade-run0-19-parp16-MSTP82-1-MSEL5-5338Bpot.root"
507 if options.A.lower() == "charmonly":
508 charmonly = True
509 HNL = False
510 if options.A not in ["b", "c", "bc", "meson", "pbrem", "qcd"]:
511 inclusive = True
512motherMode = None
513if options.MM:
514 motherMode = options.MM
515Opt_high = None
516if options.cosmics:
517 Opt_high = int(options.cosmics)
518if options.inputFile:
519 if options.inputFile == ["none"]:
520 options.inputFile = None
521 else:
522 inputFile = []
523 for _f in options.inputFile:
524 if options.remoteInput:
525 inputFile.append(os.path.expandvars(_f))
526 else:
527 inputFile.extend(glob.glob(_f))
528 inputFile = list(dict.fromkeys(inputFile))
529 if options.nFiles > 0:
530 inputFile = inputFile[: options.nFiles]
531 # Only disable the default-input fallback when at least one path
532 # actually resolved; an explicit --inputFile that globs to nothing is a
533 # mistake and would otherwise run downstream setup with no input files.
534 if inputFile:
535 defaultInputFile = False
536 else:
537 parser.error(f"--inputFile {options.inputFile} matched no files")
538if options.RPVSUSY:
539 HNL = False
540if options.DarkPhoton:
541 HNL = False
542 if inclusive not in {"meson", "pbrem", "qcd"}:
543 parser.error("For --DarkPhoton, -A must be one of: meson, pbrem, qcd")
544if not options.theMass:
545 if options.DarkPhoton:
546 options.theMass = theDPmass
547 else:
548 options.theMass = theHNLMass
549theCouplings = None
550if options.thecouplings:
551 theCouplings = [float(c) for c in options.thecouplings.split(",")]
552if options.theprodcouplings:
553 theProductionCouplings = [float(c) for c in options.theprodcouplings.split(",")]
554if options.thedeccouplings:
555 theDecayCouplings = [float(c) for c in options.thedeccouplings.split(",")]
556if options.testFlag:
557 inputFile = "$FAIRSHIP/files/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1_5000.root"
558if options.geofile:
559 # The geometry and its configuration both come from the geometry file.
560 # Parse again with these options already set to None: argparse then leaves
561 # them alone unless they are given on the command line.
562 geometry_options = ["dy", "strawDesign", "shieldName", "decayVolMed", "SND", "SND_design", "target_yaml"]
563 probe = parser.parse_args(namespace=Namespace(**dict.fromkeys(geometry_options)))
564 given = [
565 "/".join(flag for action in parser._actions if action.dest == dest for flag in action.option_strings)
566 for dest in geometry_options
567 if getattr(probe, dest) is not None
568 ]
569 if given:
570 parser.error(f"-g/--geofile cannot be combined with geometry options: {', '.join(given)}")
571 options.geofile = os.path.expandvars(options.geofile)
572 try:
573 geometry_from_file.check_file(options.geofile) # fail early if it cannot be used
574 except ValueError as e:
575 parser.error(f"-g/--geofile: {e}")
576
577
578# sanity check
579if (HNL and options.RPVSUSY) or (HNL and options.DarkPhoton) or (options.DarkPhoton and options.RPVSUSY):
580 print("cannot have HNL and SUSY or DP at the same time, abort")
581 sys.exit(2)
582
583if (options.command == "Genie" or options.nuradio) and defaultInputFile:
584 inputFile = "$EOSSHIP/eos/experiment/ship/data/GenieEvents/genie-nu_mu.root"
585if (options.mudis or options.newmudis) and defaultInputFile:
586 print("input file required if simEngine = muonDIS")
587 print(" for example -f $EOSSHIP/eos/experiment/ship/data/muonDIS/muonDis_1.root")
588 sys.exit(1)
589
590if (options.ntuple or options.muonback) and defaultInputFile:
591 print("input file required if simEngine = Ntuple or MuonBack")
592 print(" for example -f $EOSSHIP/eos/experiment/ship/data/Mbias/pythia8_Geant4-withCharm_onlyMuons_4magTarget.root")
593 sys.exit(1)
594# PYTHIA8 requires Random:seed to be in range [0, 900000000]
595# When theSeed=0, ROOT generates a seed from system time which can exceed this limit
596seed = options.theSeed
597if seed == 0:
598 ROOT.gRandom.SetSeed(0) # Generate time-based seed
599 seed = ROOT.gRandom.GetSeed()
600 # Clamp to PYTHIA8's maximum allowed seed value
601if seed > 900000000:
602 seed = seed % 900000000
603ROOT.gRandom.SetSeed(seed)
604shipRoot_conf.configure(0) # load basic libraries, prepare atexit for python
605if options.reproducible and options.debug == 0:
606 ROOT.gErrorIgnoreLevel = ROOT.kWarning
607
608# Configure FairLogger verbosity based on debug level
609ROOT.gInterpreter.ProcessLine('#include "FairLogger.h"')
610if options.debug == 0:
611 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("info");')
612elif options.debug == 1:
613 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug");')
614elif options.debug == 2:
615 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug1");')
616elif options.debug == 3:
617 ROOT.gInterpreter.ProcessLine('fair::Logger::SetConsoleSeverity("debug2");')
618if options.geofile:
619 ship_geo = load_from_root_file(options.geofile, "ShipGeo")
620 # saveBasicParameters replaces the versions with those of this run; keep the
621 # one that built the geometry, set once so later -g runs cannot overwrite it.
622 if "geometryBuiltWithFairShip" not in ship_geo:
623 ship_geo.geometryBuiltWithFairShip = ship_geo.get("FairShip", "unknown")
624 print(f"Geometry configuration loaded from {options.geofile}; particles are transported through its geometry")
625else:
627 Yheight=options.dy,
628 strawDesign=options.strawDesign,
629 shieldName=options.shieldName,
630 DecayVolumeMedium=options.decayVolMed,
631 SND=options.SND,
632 SND_design=options.SND_design,
633 TARGET_YAML=options.target_yaml,
634 )
635
636if not options.command:
637 for g in [
638 "pythia8",
639 "ttree",
640 "evtcalc",
641 "pythia6",
642 "nuradio",
643 "ntuple",
644 "muonback",
645 "mudis",
646 "newmudis",
647 "fixedTarget",
648 "cosmics",
649 ]:
650 if getattr(options, g):
651 break
652 else:
653 options.pythia8 = True # Ensure Pythia8 is enabled by default
654
655# Output file name
656# Use custom tag if provided, otherwise reuse the requested run number or generate a UUID4
657run_identifier = (
658 options.output_tag
659 if options.output_tag
660 else str(options.run_number if options.run_number is not None else uuid.uuid4())
661)
662if not os.path.exists(options.outputDir):
663 os.makedirs(options.outputDir)
664outFile = f"{options.outputDir}/sim_{run_identifier}.root"
665if (
666 options.geofile
667 and os.path.realpath(options.geofile) == os.path.realpath(f"{options.outputDir}/geo_{run_identifier}.root")
668 and options.save_geofile
669):
670 parser.error("-g/--geofile: the geometry file would be overwritten by the output of this run, use another --tag")
671
672# Parameter file name
673parFile = f"{options.outputDir}/params_{run_identifier}.root"
674
675# In general, the following parts need not be touched
676# ========================================================================
677
678# -----Timer--------------------------------------------------------
679timer = ROOT.TStopwatch()
680timer.Start()
681# ------------------------------------------------------------------------
682# -----Create simulation run----------------------------------------
683run = ROOT.FairRunSim()
684run.SetName(mcEngine) # Transport engine
685if options.run_number is not None and hasattr(run, "SetRunId"):
686 run.SetRunId(options.run_number)
687sink = ROOT.FairRootFileSink(outFile)
688run.SetSink(sink)
689ROOT.SetOwnership(sink, False) # C++ FairRun takes ownership
690run.SetUserConfig("g4Config.C") # user configuration file default g4Config.C
691rtdb = run.GetRuntimeDb()
692# -----Create geometry----------------------------------------------
693# import shipMuShield_only as shipDet_conf # special use case for an attempt to convert active shielding geometry for use with FLUKA
694# import shipTarget_only as shipDet_conf
695import shipDet_conf
696
697modules = shipDet_conf.configure(run, ship_geo, geofile=options.geofile)
698# -----Create PrimaryGenerator--------------------------------------
699primGen = ROOT.FairPrimaryGenerator()
700P8gen = None # populated below by the various generator branches
701if options.pythia8:
702 primGen.SetTarget(ship_geo.target.z0, 0.0)
703 # -----Pythia8--------------------------------------
704 if HNL or options.RPVSUSY:
705 P8gen = ROOT.HNLPythia8Generator()
706 import pythia8_conf
707
708 if HNL:
709 print("Generating HNL events of mass %.3f GeV" % options.theMass)
710 if theProductionCouplings is None and theDecayCouplings is None:
711 print("and with couplings=", theCouplings)
712 theProductionCouplings = theDecayCouplings = theCouplings
713 elif theProductionCouplings is not None and theDecayCouplings is not None:
714 print("and with couplings", theProductionCouplings, "at production")
715 print("and", theDecayCouplings, "at decay")
716 else:
717 raise ValueError("Either both production and decay couplings must be specified, or neither.")
719 P8gen, options.theMass, theProductionCouplings, theDecayCouplings, inclusive, options.deepCopy
720 )
721 if options.RPVSUSY:
722 assert theCouplings is not None, "options.thecouplings is required for --RPVSUSY"
723 print("Generating RPVSUSY events of mass %.3f GeV" % theHNLMass)
724 print(f"and with couplings=[{theCouplings[0]:.3f},{theCouplings[1]:.3f}]")
725 print("and with stop mass=%.3f GeV\n" % theCouplings[2])
727 P8gen,
728 options.theMass,
729 [theCouplings[0], theCouplings[1]],
730 theCouplings[2],
731 options.RPVSUSYbench,
732 inclusive,
733 options.deepCopy,
734 )
735 P8gen.SetParameters("ProcessLevel:all = off")
736 if inputFile:
737 useInputFile(inputFile)
738 # read from external file
739 P8gen.UseExternalFile(inputFile, options.firstEvent)
740 if options.DarkPhoton:
741 P8gen = ROOT.DPPythia8Generator()
742 if inclusive == "qcd":
743 P8gen.SetDPId(4900023)
744 else:
745 P8gen.SetDPId(9900015)
746 import pythia8darkphoton_conf
747
749 P8gen, options.theMass, options.theDPepsilon, inclusive, motherMode, options.deepCopy
750 )
751 if passDPconf != 1:
752 sys.exit()
753 if HNL or options.RPVSUSY or options.DarkPhoton:
754 assert P8gen is not None # guaranteed by the three branches above
755 P8gen.SetSmearBeam(options.SmearBeam * u.cm) # Gaussian beam smearing
756 P8gen.SetPaintRadius(options.PaintBeam * u.cm) # beam painting radius
757 P8gen.SetLmin(ship_geo.decayVolume.z0 - ship_geo.target.z0)
758 P8gen.SetLmax((ship_geo.decayVolume.z0 - ship_geo.target.z0) + ship_geo.decayVolume.length)
759 margin = 10 * u.cm # covers beam smearing + non-projectivity of vessel
760 z_end = ship_geo.decayVolume.z0 + ship_geo.decayVolume.length # vessel exit z from target
761 # xEndInner/yEndInner are full inner widths; divide by 2 for half-aperture.
762 # Assumes production vertex at target (z=0). Vessel is approximately
763 # projective, so a single angle cut at the exit (widest point) suffices.
764 max_theta_x = (ship_geo.decayVolume.xEndInner / 2 + margin) / z_end
765 max_theta_y = (ship_geo.decayVolume.yEndInner / 2 + margin) / z_end
766 P8gen.SetMaxTheta(max_theta_x, max_theta_y) # slope bounds: |px/pz|, |py/pz|
767 if charmonly:
768 primGen.SetTarget(0.0, 0.0) # vertex is set in pythia8Generator
769 useInputFile(inputFile)
770 if ship_geo.Box.gausbeam:
771 primGen.SetBeam(0.0, 0.0, 0.5, 0.5) # more central beam, for hits in downstream detectors
772 primGen.SmearGausVertexXY(True) # sigma = x
773 else:
774 primGen.SetBeam(
775 0.0, 0.0, ship_geo.Box.TX - 1.0, ship_geo.Box.TY - 1.0
776 ) # Uniform distribution in x/y on the target (0.5 cm of margin at both sides)
777 primGen.SmearVertexXY(True)
778 P8gen = ROOT.Pythia8Generator()
779 P8gen.UseExternalFile(inputFile, options.firstEvent)
780 # Use geometry constants instead of fragile TGeo navigation
781 P8gen.SetTargetCoordinates(ship_geo.target.z0, ship_geo.target.z0 + ship_geo.target.length)
782 # pion on proton 500GeV
783 # P8gen.SetMom(500.*u.GeV)
784 # P8gen.SetId(-211)
785 primGen.AddGenerator(P8gen)
786 ROOT.SetOwnership(P8gen, False) # C++ FairPrimaryGenerator takes ownership
787if options.fixedTarget:
788 HNL = False
789 P8gen = ROOT.FixedTargetGenerator()
790 P8gen.SetZoffset(options.z_offset * u.mm)
791 # Use geometry constants instead of fragile TGeo navigation
792 P8gen.SetTargetCoordinates(ship_geo.target.z0, ship_geo.target.z0 + ship_geo.target.length)
793 P8gen.SetMom(400.0 * u.GeV)
794 P8gen.SetSmearBeam(options.SmearBeam * u.cm) # Gaussian beam smearing
795 P8gen.SetPaintRadius(options.PaintBeam * u.cm) # beam painting radius
796 P8gen.SetEnergyCut(0.0)
797 P8gen.SetHeartBeat(100000)
798 P8gen.SetG4only()
799 primGen.AddGenerator(P8gen)
800 ROOT.SetOwnership(P8gen, False) # C++ FairPrimaryGenerator takes ownership
801if options.pythia6:
802 # set muon interaction close to decay volume
803 primGen.SetTarget(ship_geo.target.z0 + ship_geo.muShield.length, 0.0)
804 # -----Pythia6-------------------------
805 test = ROOT.TPythia6() # don't know any other way of forcing to load lib
806 P6gen = ROOT.tPythia6Generator()
807 P6gen.SetMom(50.0 * u.GeV)
808 P6gen.SetTarget("gamma/mu+", "n0") # default "gamma/mu-","p+"
809 primGen.AddGenerator(P6gen)
810 ROOT.SetOwnership(P6gen, False) # C++ FairPrimaryGenerator takes ownership
811
812# -----EvtCalc--------------------------------------
813if options.evtcalc:
814 primGen.SetTarget(0.0, 0.0)
815 print(f"Opening input file for EvtCalc generator: {inputFile}")
816 useInputFile(inputFile)
817 EvtCalcGen = ROOT.EvtCalcGenerator()
818 if not EvtCalcGen.Init(inputFile, options.firstEvent):
819 raise RuntimeError(f"Failed to initialize EvtCalcGenerator from input: {inputFile}")
820 EvtCalcGen.SetPositions(zTa=ship_geo.target.z, zDV=ship_geo.decayVolume.z)
821 primGen.AddGenerator(EvtCalcGen)
822 ROOT.SetOwnership(EvtCalcGen, False) # C++ FairPrimaryGenerator takes ownership
823 options.nEvents = (
824 EvtCalcGen.GetNevents() if options.nEvents == -1 else min(options.nEvents, EvtCalcGen.GetNevents())
825 )
826 print(f"Generate {options.nEvents} with EvtCalc input. First event: {options.firstEvent}")
827
828# -----Particle Gun-----------------------
829if options.command == "PG":
830 myPgun = ROOT.ParticleGunGenerator(options.pID, options.multiplicity)
831 if options.showPGModels:
832 myPgun.PrintVertexModels()
833 myPgun.PrintMomentumModels()
834 sys.exit(0)
835 myPgun.SetPRange(options.Estart, options.Eend)
836 myPgun.SetPhiRange(0, 360) # // Azimuth angle range [degree]
837 if options.thetaMin > options.thetaMax:
838 sys.exit(f"thetaMin ({options.thetaMin}) must not exceed thetaMax ({options.thetaMax})")
839 myPgun.SetThetaRange(options.thetaMin, options.thetaMax) # Polar angle in lab system [degree]
840 if options.bothCharges:
841 myPgun.SetBothCharges(True, options.chargeFraction)
842 if options.multiplePG:
843 # multiple PG sources in the x-y plane, or in a volume with uniform3d
844 vertex_pars = [options.Vx * u.cm, options.Dx * u.cm, options.Vy * u.cm, options.Dy * u.cm, options.Vz * u.cm]
845 if options.smearMode == "uniform3d":
846 vertex_pars.append(options.Dz * u.cm)
847 myPgun.SetVertexModel(options.smearMode, vertex_pars)
848 else:
849 # point source
850 myPgun.SetVertexModel(options.smearMode, [options.Vx * u.cm, 0.0, options.Vy * u.cm, 0.0, options.Vz * u.cm])
851 myPgun.SetCommonVertex(options.commonVertex)
852 if options.momentumModel > 0:
853 myPgun.SetMomentumModel(options.momentumModel, options.modelPar)
854 if options.histoFile:
855 histo_files = options.histoFile or []
856 histo_names = options.histoName or []
857 histo_x = options.histoX or []
858 histo_y = options.histoY or []
859 histo_z = options.histoZ or []
860
861 if len(histo_files) != len(histo_names):
862 raise ValueError("Must specify one --histoName per --histoFile")
863 if len(histo_x) != len(histo_files):
864 raise ValueError("Must specify one --histoX per --histoFile")
865
866 for idx, histo_file in enumerate(histo_files):
867 histo_vars = [histo_x[idx]]
868 if idx < len(histo_y):
869 histo_vars.append(histo_y[idx])
870 if idx < len(histo_z):
871 histo_vars.append(histo_z[idx])
872 myPgun.LoadHistoFromFile(histo_file, histo_names[idx], histo_vars)
873
874 primGen.AddGenerator(myPgun)
875 ROOT.SetOwnership(myPgun, False) # C++ FairPrimaryGenerator takes ownership
876# -----muon DIS Background------------------------
877DISgen = None
878if options.mudis or options.newmudis:
879 useInputFile(inputFile)
880 primGen.SetTarget(0.0, 0.0)
881 if options.newmudis:
882 DISgen = ROOT.NewMuDISGenerator()
883 # The default reads at most 100 input muons and replays at most 100 DIS events.
884 DISgen.SetNevents(100 if options.nEvents is None else options.nEvents)
885 else:
886 DISgen = ROOT.MuDISGenerator()
887 # from nu_tau detector to tracking station 2
888 # mu_start, mu_end = ship_geo.tauMudet.zMudetC,ship_geo.TrackStation2.z
889 #
890 # in front of UVT up to tracking station 1
891 mu_start, mu_end = ship_geo.Chamber1.z - ship_geo.chambers.Tub1length - 10.0 * u.cm, ship_geo.TrackStation1.z
892 print("MuDIS position info input=", mu_start, mu_end)
893 DISgen.SetPositions(mu_start, mu_end)
894 if not DISgen.Init(inputFile, options.firstEvent):
895 raise RuntimeError(f"Failed to initialize DIS generator from input: {inputFile}")
896 primGen.AddGenerator(DISgen)
897 ROOT.SetOwnership(DISgen, False) # C++ FairPrimaryGenerator takes ownership
898 if options.newmudis:
899 nDIS = DISgen.GetNevents()
900 options.nEvents = min(nDIS, 100) if options.nEvents is None else nDIS
901 else:
902 options.nEvents = DISgen.GetNevents() if options.nEvents == -1 else min(options.nEvents, DISgen.GetNevents())
903 print("(New)MuDISGenerator: Generating ", options.nEvents, " DIS events, first event ", options.firstEvent)
904# -----Neutrino Background------------------------
905if options.command == "Genie":
906 # Genie
907 useInputFile(inputFile)
908 primGen.SetTarget(0.0, 0.0) # do not interfere with GenieGenerator
909 Geniegen = ROOT.GenieGenerator()
910
911 GenieOptions = {"simple_gevgen": 0, "genie_geometry": 3}
912 genie_option = GenieOptions[options.GenieOption] # 0 standard, 3 GENIE geometry driver
913 Geniegen.SetGenerationOption(genie_option)
914 if not Geniegen.Init(inputFile, options.firstEvent):
915 raise RuntimeError(f"Failed to initialize GenieGenerator from input: {inputFile}")
916 if genie_option == 0:
917 Geniegen.SetPositions(ship_geo.target.z0, options.z_start_nu, options.z_end_nu)
918 primGen.AddGenerator(Geniegen)
919 ROOT.SetOwnership(Geniegen, False) # C++ FairPrimaryGenerator takes ownership
920 options.nEvents = Geniegen.GetNevents() if options.nEvents == -1 else min(options.nEvents, Geniegen.GetNevents())
921 run.SetPythiaDecayer("DecayConfigNuAge.C")
922 print("Generate ", options.nEvents, " with Genie input", " first event", options.firstEvent)
923if options.nuradio:
924 useInputFile(inputFile)
925 primGen.SetTarget(0.0, 0.0) # do not interfere with GenieGenerator
926 Geniegen = ROOT.GenieGenerator()
927 if not Geniegen.Init(inputFile, options.firstEvent):
928 raise RuntimeError(f"Failed to initialize GenieGenerator from input: {inputFile}")
929 # Geniegen.SetPositions(ship_geo.target.z0, ship_geo.target.z0, ship_geo.CaloScoringPlane.z)
930 Geniegen.SetPositions(ship_geo.target.z0, ship_geo.tauMudet.zMudetC, ship_geo.CaloScoringPlane.z)
931 Geniegen.NuOnly()
932 primGen.AddGenerator(Geniegen)
933 ROOT.SetOwnership(Geniegen, False) # C++ FairPrimaryGenerator takes ownership
934 print("Generate ", options.nEvents, " for nuRadiography", " first event", options.firstEvent)
935 # add tungsten to PDG
936 pdg = ROOT.TDatabasePDG.Instance()
937 pdg.AddParticle("W", "Ion", 1.71350e02, True, 0.0, 74, "XXX", 1000741840)
938 #
939 run.SetPythiaDecayer("DecayConfigPy8.C")
940 # this requires writing a C macro, would have been easier to do directly in python!
941 # for i in [431,421,411,-431,-421,-411]:
942 # ROOT.gMC.SetUserDecay(i) # Force the decay to be done w/external decayer
943if options.ttree:
944 useInputFile(inputFile)
945 primGen.SetTarget(0.0 + options.targetOffset * u.m, 0.0)
946 generator = ROOT.SHiP.TTreeGenerator()
947 generator.SetTreeName("converted_ntuple")
948 if not generator.Init(inputFile, options.firstEvent):
949 raise RuntimeError(f"Failed to initialize TTreeGenerator from input: {inputFile}")
950 primGen.AddGenerator(generator)
951 ROOT.SetOwnership(generator, False) # C++ FairPrimaryGenerator takes ownership
952 available_events = max(0, generator.GetNEvents() - options.firstEvent)
953 options.nEvents = available_events if options.nEvents == -1 else min(options.nEvents, available_events)
954 print("Process ", options.nEvents, " from input file")
955if options.ntuple:
956 # reading previously processed muon events, [-50m - 50m]
957 useInputFile(inputFile)
958 primGen.SetTarget(ship_geo.target.z0 + 50 * u.m, 0.0)
959 Ntuplegen = ROOT.NtupleGenerator()
960 if not Ntuplegen.Init(inputFile, options.firstEvent):
961 raise RuntimeError(f"Failed to initialize NtupleGenerator from input: {inputFile}")
962 primGen.AddGenerator(Ntuplegen)
963 ROOT.SetOwnership(Ntuplegen, False) # C++ FairPrimaryGenerator takes ownership
964 options.nEvents = Ntuplegen.GetNevents() if options.nEvents == -1 else min(options.nEvents, Ntuplegen.GetNevents())
965 print("Process ", options.nEvents, " from input file")
966#
967if options.muonback:
968 # reading muon tracks from previous Pythia8/Geant4 simulation with charm replaced by cascade production
969 useInputFile(inputFile)
970 isNew = ut.checkForBranch(
971 inputFile, "PlaneHAPoint"
972 ) # If there is a branch PlaneHAPoint this file is from the new production
973 if isNew:
974 print("INFO: Processing a file from the new production - setting target z offset at 0")
975 primGen.SetTarget(ship_geo.target.z0, 0.0)
976 else:
977 print("INFO: Processing a file from the old production - setting target z offset to 70.845m")
978 primGen.SetTarget(ship_geo.target.z0 + 70.845 * u.m, 0.0)
979 #
980 # run_fixedTarget output (cbmsim) rather than a legacy pythia8-Geant4 ntuple
981 fromStage1 = ut.checkForBranch(inputFile, "MCTrack")
982 startAtPlane = fromStage1 and not options.muonBackFromOrigin
983 if startAtPlane:
984 # The scored tracks continue from the scoring plane, so the first stage must have
985 # simulated the absorber with its field, and it already smeared and painted the beam.
986 if options.phiRandom:
987 raise ValueError(
988 "--phiRandom is not supported with run_fixedTarget input: the hadron absorber field breaks the "
989 "symmetry. Use --MuonBackFromOrigin to reproduce the old behaviour."
990 )
991 if options.SmearBeam != parser.get_default("SmearBeam") or options.PaintBeam != parser.get_default("PaintBeam"):
992 print("WARNING: --SmearBeam/--PaintBeam ignored, run_fixedTarget already applied the beam profile")
993 noSummary, noField = ut.stage1AbsorberFieldOff(inputFile)
994 if noSummary:
995 print(f"WARNING: no FileSummary, cannot check the hadron absorber field of: {', '.join(noSummary)}")
996 if noField:
997 message = (
998 "run_fixedTarget input simulated without the hadron absorber field (--no-AddMuonShieldField), but "
999 f"the tracks now continue from the scoring plane: {', '.join(noField)}"
1000 )
1001 if not options.muonBackAllowNoAbsorberField:
1002 raise ValueError(message + ". Pass --MuonBackAllowNoAbsorberField to accept it.")
1003 print("WARNING: " + message)
1004 MuonBackgen = ROOT.MuonBackGenerator()
1005 # MuonBackgen.FollowAllParticles() # also start non-muons that crossed the scoring plane
1006 if not MuonBackgen.Init(inputFile, options.firstEvent):
1007 raise RuntimeError(f"Failed to initialize MuonBackGenerator from input: {inputFile}")
1008 if options.muonBackFromOrigin:
1009 MuonBackgen.SetStartFromOrigin()
1010 MuonBackgen.SetPaintRadius(options.PaintBeam * u.cm)
1011 MuonBackgen.SetSmearBeam(options.SmearBeam * u.cm)
1012 MuonBackgen.SetPhiRandomize(options.phiRandom)
1013 if options.sameSeed:
1014 MuonBackgen.SetSameSeed(options.sameSeed)
1015 primGen.AddGenerator(MuonBackgen)
1016 ROOT.SetOwnership(MuonBackgen, False) # C++ FairPrimaryGenerator takes ownership
1017 options.nEvents = (
1018 MuonBackgen.GetNevents() if options.nEvents == -1 else min(options.nEvents, MuonBackgen.GetNevents())
1019 )
1020 MCTracksWithHitsOnly = True # otherwise, output file becomes too big
1021 if startAtPlane:
1022 print(
1023 "Process ",
1024 options.nEvents,
1025 " from input file, starting at the scoring plane, with MCTracksWithHitsOnly",
1026 MCTracksWithHitsOnly,
1027 )
1028 else:
1029 print(
1030 "Process ",
1031 options.nEvents,
1032 " from input file, with 𝜎 = ",
1033 options.PaintBeam,
1034 ", with smear radius r = ",
1035 options.SmearBeam * u.cm,
1036 "with MCTracksWithHitsOnly",
1037 MCTracksWithHitsOnly,
1038 )
1039 if options.followMuon:
1040 options.fastMuon = True
1041 modules["Veto"].SetFollowMuon()
1042 if options.fastMuon:
1043 modules["Veto"].SetFastMuon()
1044
1045 # optional, boost gamma2muon conversion
1046 # ROOT.kShipMuonsCrossSectionFactor = 100.
1047#
1048if options.cosmics:
1049 assert Opt_high is not None # guaranteed by the same options.cosmics check above
1050 primGen.SetTarget(0.0, 0.0)
1051 Cosmicsgen = ROOT.CosmicsGenerator()
1052 import CMBG_conf
1053
1054 CMBG_conf.configure(Cosmicsgen, ship_geo)
1055 if not Cosmicsgen.Init(Opt_high):
1056 print("initialization of cosmic background generator failed ", Opt_high)
1057 sys.exit(1)
1058 Cosmicsgen.n_EVENTS = options.nEvents
1059 primGen.AddGenerator(Cosmicsgen)
1060 ROOT.SetOwnership(Cosmicsgen, False) # C++ FairPrimaryGenerator takes ownership
1061 print("Process ", options.nEvents, " Cosmic events with option ", Opt_high)
1062
1063#
1064run.SetGenerator(primGen)
1065ROOT.SetOwnership(primGen, False) # C++ FairRunSim takes ownership
1066# ------------------------------------------------------------------------
1067
1068# ---Store the visualiztion info of the tracks, this make the output file very large!!
1069# --- Use it only to display but not for production!
1070if options.eventDisplay:
1071 run.SetStoreTraj(ROOT.kTRUE)
1072else:
1073 run.SetStoreTraj(ROOT.kFALSE)
1074
1075# -----Configure external decayer globally------------------------------------
1076# Override any previous SetPythiaDecayer calls if EvtGenDecayer is requested
1077if options.evtgen_decayer:
1078 run.SetPythiaDecayer("DecayConfigTEvtGen.C")
1079 print("Using TEvtGenDecayer for J/psi and quarkonium decays with EvtGen")
1080
1081# -----Initialize simulation run------------------------------------
1082run.Init()
1083if options.geofile:
1084 geometry_from_file.check_swapped(modules[geometry_from_file.SWAP_NAME])
1085if options.dryrun: # Early stop after setting up Pythia 8
1086 sys.exit(0)
1087if options.newmudis:
1088 assert isinstance(DISgen, ROOT.NewMuDISGenerator)
1089 if not DISgen.RegisterOutputBranches(sink.GetOutTree()):
1090 raise RuntimeError("Failed to register the MuDIS output branches")
1091gMC = ROOT.TVirtualMC.GetMC()
1092fStack = gMC.GetStack()
1093
1094# -----J/psi external decayer configuration handled in g4config.in------------------------------------
1095# VMC command /mcPhysics/setExtDecayerSelection J/psi forces external decayer usage
1096EnergyCut = 10.0 * u.MeV if (options.mudis or options.newmudis) else 100.0 * u.MeV
1097
1098if MCTracksWithHitsOnly:
1099 fStack.SetMinPoints(1)
1100 fStack.SetEnergyCut(-100.0 * u.MeV)
1101elif MCTracksWithEnergyCutOnly:
1102 fStack.SetMinPoints(-1)
1103 fStack.SetEnergyCut(EnergyCut)
1104elif MCTracksWithHitsOrEnergyCut:
1105 fStack.SetMinPoints(1)
1106 fStack.SetEnergyCut(EnergyCut)
1107elif options.deepCopy:
1108 fStack.SetMinPoints(0)
1109 fStack.SetEnergyCut(0.0 * u.MeV)
1110
1111if options.eventDisplay:
1112 # Set cuts for storing the trajectories, can only be done after initialization of run (?!)
1113 trajFilter = ROOT.FairTrajFilter.Instance()
1114 trajFilter.SetStepSizeCut(1 * u.mm)
1115 trajFilter.SetVertexCut(-20 * u.m, -20 * u.m, ship_geo.target.z0 - 1 * u.m, 20 * u.m, 20 * u.m, 200.0 * u.m)
1116 trajFilter.SetMomentumCutP(0.1 * u.GeV)
1117 trajFilter.SetEnergyCut(0.0, 400.0 * u.GeV)
1118 trajFilter.SetStorePrimaries(ROOT.kTRUE)
1119 trajFilter.SetStoreSecondaries(ROOT.kTRUE)
1120
1121# The VMC sets the fields using the "/mcDet/setIsLocalMagField true" option in "gconfig/g4config.in"
1122import geomGeant4
1123
1124# geomGeant4.setMagnetField() # replaced by VMC, only has effect if /mcDet/setIsLocalMagField false
1125
1126# Define extra VMC B fields not already set by the geometry definitions, e.g. a global field,
1127# any field maps, or defining if any volumes feel only the local or local+global field.
1128# For now, just keep the fields already defined by the C++ code, i.e comment out the fieldMaker
1129if hasattr(ship_geo.Bfield, "fieldMap"):
1130 if options.field_map:
1131 ship_geo.Bfield.fieldMap = options.field_map
1132 fieldMaker = geomGeant4.addVMCFields(ship_geo, verbose=True)
1133
1134# Print VMC fields and associated geometry objects
1135if options.print_fields:
1138 onlyWithField=True,
1139 exclude=["DecayVolume", "Tr1", "Tr2", "Tr3", "Tr4", "Veto", "MuonDetector", "CaloScoringPlane"],
1140 )
1141# Plot the field example
1142# fieldMaker.plotField(1, ROOT.TVector3(-9000.0, 6000.0, 50.0), ROOT.TVector3(-300.0, 300.0, 6.0), 'Bzx.png')
1143# fieldMaker.plotField(2, ROOT.TVector3(-9000.0, 6000.0, 50.0), ROOT.TVector3(-400.0, 400.0, 6.0), 'Bzy.png')
1144
1145# -----Start run----------------------------------------------------
1146run.Run(options.nEvents)
1147# -----Runtime database---------------------------------------------
1148kParameterMerged = ROOT.kTRUE
1149parOut = ROOT.FairParRootFileIo(kParameterMerged)
1150if options.save_parfile:
1151 if os.path.exists(parFile):
1152 os.remove(parFile)
1153 parOut.open(parFile)
1154 rtdb.setOutput(parOut)
1155 ROOT.SetOwnership(parOut, False) # C++ FairRuntimeDb takes ownership
1156 rtdb.saveOutput()
1157 print("Parameter file is ", parFile)
1158# ------------------------------------------------------------------------
1159if options.save_geofile:
1160 geofile_name = f"{options.outputDir}/geo_{run_identifier}.root"
1161 run.CreateGeometryFile(geofile_name)
1162 # save ShipGeo dictionary in geofile
1163 import saveBasicParameters
1164
1165 saveBasicParameters.execute(geofile_name, ship_geo)
1166 print("Geometry file is ", geofile_name)
1167
1168# checking for overlaps
1169if options.check_overlaps:
1170 ROOT.gROOT.SetWebDisplay("off") # Workaround for https://github.com/root-project/root/issues/18881
1171 fGeo = ROOT.gGeoManager
1172 fGeo.SetNmeshPoints(10000)
1173 fGeo.CheckOverlaps(0.1) # 1 micron takes 5minutes
1174 fGeo.PrintOverlaps()
1175 # check subsystems in more detail
1176 for x in fGeo.GetTopNode().GetNodes():
1177 x.CheckOverlaps(0.0001)
1178 fGeo.PrintOverlaps()
1179# -----Finish-------------------------------------------------------
1180timer.Stop()
1181rtime = timer.RealTime()
1182ctime = timer.CpuTime()
1183print(" ")
1184print("Macro finished successfully.")
1185if P8gen is not None:
1186 if HNL:
1187 print("number of retries (no HNL produced) ", P8gen.nrOfRetries())
1188 print("number of geometric rejections (outside vessel acceptance) ", P8gen.nrOfGeoRejections())
1189 elif options.DarkPhoton:
1190 print("number of retries (no DP produced) ", P8gen.nrOfRetries())
1191 print("number of geometric rejections (outside vessel acceptance) ", P8gen.nrOfGeoRejections())
1192 print("total number of dark photons (including multiple meson decays per single collision) ", P8gen.nrOfDP())
1193
1194print("Output file is ", outFile)
1195if not options.reproducible:
1196 print("Real time ", rtime, " s, CPU time ", ctime, "s")
1197
1198
1199# remove empty events
1200if options.muonback:
1201 tmpFile = outFile + "tmp"
1202 target = os.path.normpath(outFile)
1203 fin: ROOT.TFile | None = None
1204 for ff in ROOT.gROOT.GetListOfFiles():
1205 if os.path.normpath(ff.GetName()) == target:
1206 fin = cast(ROOT.TFile, ff)
1207 break
1208 if fin is None:
1209 fin = ROOT.TFile.Open(outFile)
1210 t = fin["cbmsim"]
1211 fout = ROOT.TFile(tmpFile, "recreate")
1212 fSink = ROOT.FairRootFileSink(fout)
1213 ROOT.SetOwnership(fout, False) # FairRootFileSink's unique_ptr now owns fout
1214
1215 sTree = t.CloneTree(0)
1216 nEvents = 0
1217 # Collect branch names containing 'Point' - these are the sensitive detector hit containers
1218 pointContainers = []
1219 for branch in sTree.GetListOfBranches():
1220 name = branch.GetName()
1221 if "Point" in name:
1222 pointContainers.append(name)
1223
1224 # The scoring planes record every crossing with no energy threshold, so on their own they
1225 # must not make an event non-empty.
1226 pointContainers = [n for n in pointContainers if n not in ("CaloScoringPlanePoint", "UpstreamTaggerScoringPoint")]
1227
1228 # Filter out empty events (events with no hits in any Point container)
1229 for event in t:
1230 empty = True
1231 for containerName in pointContainers:
1232 container = getattr(sTree, containerName)
1233 if container.size() > 0:
1234 empty = False
1235 break
1236
1237 if not empty:
1238 sTree.Fill()
1239 nEvents += 1
1240
1241 branches = ROOT.TList()
1242 branches.SetName("BranchList")
1243 branches.SetOwner(True)
1244 for name in (
1245 "MCTrack",
1246 "vetoPoint",
1247 "ShipRpcPoint",
1248 "TargetPoint",
1249 "TTPoint",
1250 "ScoringPoint",
1251 "strawtubesPoint",
1252 "TimeDetPoint",
1253 "CaloScoringPlanePoint",
1254 "MCEventHeader",
1255 "UpstreamTaggerPoint",
1256 "UpstreamTaggerScoringPoint",
1257 "MTCdetPoint",
1258 "SiliconTargetPoint",
1259 "sGeoTracks",
1260 ):
1261 obj = ROOT.TObjString(name)
1262 ROOT.SetOwnership(obj, False) # C++ TList takes ownership
1263 branches.Add(obj)
1264
1265 sTree.AutoSave()
1266 fSink.WriteObject(branches, "BranchList", ROOT.TObject.kSingleKey)
1267 fSink.SetOutTree(sTree)
1268
1269 fout.Close()
1270 print("removed empty events, left with:", nEvents)
1271 rc1 = os.system("rm " + outFile)
1272 rc2 = os.system("mv " + tmpFile + " " + outFile)
1273 fin.SetWritable(False) # bpyass flush error
1274
1275if options.newmudis:
1276 from MuDISGenerator_postProcessing import post_process
1277
1278 post_process(outFile, inputFile, options.firstEvent)
1279elif options.mudis:
1280 temp_filename = outFile.replace(".root", "_tmp.root")
1281
1282 with (
1283 ROOT.TFile.Open(outFile, "read") as f_outputfile,
1284 ROOT.TFile.Open(temp_filename, "recreate") as f_temp,
1285 ):
1286 output_tree = f_outputfile["cbmsim"]
1287 muondis_tree = ROOT.TChain("DIS")
1288 for _f in inputFile:
1289 muondis_tree.Add(_f)
1290
1291 new_tree = output_tree.CloneTree(0)
1292
1293 cross_section = array("f", [0.0])
1294 cross_section_leaf = new_tree.Branch("CrossSection", cross_section, "CrossSection/F")
1295
1296 for output_event, muondis_event in zip(output_tree, muondis_tree):
1297 mu = muondis_event.InMuon[0]
1298 cross_section[0] = mu[10]
1299 new_tree.Fill()
1300
1301 new_tree.Write("", ROOT.TObject.kOverwrite)
1302
1303 os.replace(temp_filename, outFile)
1304 print("Successfully added DISCrossSection to the output file:", outFile)
1305
1306if options.command == "Genie":
1307 # breakpoint()
1308 # Copy Genie (gst TTree) information to the output file
1309 input_path = inputFile[0] if isinstance(inputFile, (list, tuple)) else inputFile
1310 f_input = ROOT.TFile.Open(input_path, "READ")
1311 gst = f_input["gst"]
1312 if not gst:
1313 raise KeyError("TTree 'gst' not found in GENIE input file")
1314
1315 selection_string = "(Entry$ >= " + str(options.firstEvent) + ")"
1316 if (options.firstEvent + options.nEvents) < gst.GetEntries():
1317 selection_string += "&&(Entry$ < " + str(options.firstEvent + options.nEvents) + ")"
1318
1319 # Reopen output file
1320 f_output = ROOT.TFile.Open(outFile, "UPDATE")
1321
1322 # Copy only the events used in this run
1323 gst_copy = gst.CopyTree(selection_string)
1324 gst_copy.Write()
1325
1326 f_input.Close()
1327 f_output.Close()
1328
1329if options.run_number is not None:
1330 with ROOT.TFile.Open(outFile, "UPDATE") as f_output:
1331 file_header = f_output.Get("FileHeader")
1332 if file_header:
1333 file_header.SetRunId(options.run_number)
1334 file_header.Write("FileHeader", ROOT.TObject.kSingleKey)
1335 else:
1336 print("WARNING: FileHeader not found in simulation output; skipped FileHeader RunID update")
1337
1338print("[INFO]: Saving FileSummary")
1339
1340
1341def mergeFileSummary(inFiles: list[str] | str) -> dict:
1342 """
1343 Make a file summary for the output.
1344 Keeps a list of the input files so that the total
1345 provenance of the events can be traced back to the sim files.
1346 """
1347 if isinstance(inFiles, str):
1348 inFiles = [inFiles]
1349
1350 energyCuts = []
1351 prodSites = []
1352 poTperFile = []
1353 mergedFSR: dict = {
1354 "PoT": 0,
1355 "EnergyCut": [],
1356 "prodSite": [],
1357 "inputFiles": [],
1358 "PoTperFile": [],
1359 "date": datetime.today().strftime("%Y-%m-%d"),
1360 }
1361 for _f in inFiles:
1362 mergedFSR["inputFiles"].append(_f)
1363 # The recorded path keeps any $EOSSHIP/$FAIRSHIP prefix for portability,
1364 # but ROOT needs it expanded to open the file.
1365 path = os.path.expandvars(_f)
1366 try:
1367 with ROOT.TFile.Open(path, "READ") as _of:
1368 key_names = [_k.GetName() for _k in _of.GetListOfKeys()]
1369 if "FileSummary" in key_names:
1370 fsr = json.loads(str(_of.Get("FileSummary")))
1371 # Only merged productions have these; the summary of a
1372 # raw run_fixedTarget.py output records its arguments.
1373 if not all(k in fsr for k in ("PoT", "EnergyCut", "prodSite")):
1374 print(f"[WARNING] No PoT, EnergyCut or prodSite in the FileSummary of {_f}")
1375 continue
1376 mergedFSR["PoT"] += fsr["PoT"]
1377 energyCuts.append(fsr["EnergyCut"])
1378 prodSites.append(fsr["prodSite"])
1379 poTperFile.append(fsr["PoT"])
1380 else:
1381 print(f"[WARNING] No FileSummary in {_f}")
1382 except OSError:
1383 # PyROOT raises instead of returning a null file. A summary is not
1384 # worth losing a simulation that has already run to completion.
1385 print(f"[WARNING] Could not open {path} to read its FileSummary")
1386
1387 mergedFSR["EnergyCut"] = list(set(energyCuts)) # Just get unique values
1388 mergedFSR["prodSite"] = list(set(prodSites))
1389 mergedFSR["PoTperFile"] = list(set(poTperFile))
1390 return mergedFSR
1391
1392
1393newFileSummary = mergeFileSummary(usedInputFiles)
1394with ROOT.TFile.Open(outFile, "UPDATE") as _of:
1395 _of.WriteObject(ROOT.TString(json.dumps(newFileSummary)), "FileSummary")
1396
1397print("=" * 72)
1398print("Simulation finished successfully")
1399print("=" * 72)
1400
1401if options.validation:
1402 validation_tools.print_simulation_output_summary(
1403 ROOT,
1404 outFile,
1405 options.nEvents,
1406 {"HNL": HNL, "DarkPhoton": options.DarkPhoton, "fixedTarget": options.fixedTarget},
1407 {
1408 "P8gen": globals().get("P8gen"),
1409 "MuonBackgen": globals().get("MuonBackgen"),
1410 "Ntuplegen": globals().get("Ntuplegen"),
1411 "DISgen": globals().get("DISgen"),
1412 "Geniegen": globals().get("Geniegen"),
1413 },
1414 )
1415
1416# ------------------------------------------------------------------------
1417import checkMagFields
1418
1419
1422
1423
1425 # after /run/initialize, but prints warning messages, problems with TGeo volume
1426 mygMC = ROOT.TGeant4.GetMC()
1427 mygMC.ProcessGeantCommand("/geometry/test/recursion_start 0")
1428 mygMC.ProcessGeantCommand("/geometry/test/recursion_depth 2")
1429 mygMC.ProcessGeantCommand("/geometry/test/run")
configure(CMBG, ship_geo)
Definition CMBG_conf.py:5
None printWeightsandFields(bool onlyWithField=True, exclude=None)
addVMCFields(shipGeo, str controlFile="", bool verbose=False, bool withVirtualMC=True)
None printVMCFields()
create_config(str DecayVolumeMedium="helium", float Yheight=6.0, int strawDesign=10, str shieldName="TRY_2026", int nuTargetPassive=1, bool SND=True, SND_design=None, TARGET_YAML=None)
None check_file(str geofile)
None check_swapped(Any swap)
None configurerpvsusy(P8gen, mass, couplings, sfermionmass, benchmark, inclusive, bool deepCopy=False, bool debug=True)
None configure(P8gen, mass, production_couplings, decay_couplings, process_selection, bool deepCopy=False, bool debug=True)
configure(P8gen, mass, epsilon, inclusive, motherMode, deepCopy=False, debug=True)
None checkOverlapsWithGeant4()
None visualizeMagFields()
dict mergeFileSummary(list[str]|str inFiles)
useInputFile(paths)
float _fraction_0_1(str value)
execute(f, ox, name="ShipGeo")
configure(run, ship_geo, str|None geofile=None)
None configure(darkphoton=None)