10from argparse
import ArgumentParser, Namespace
11from array
import array
12from datetime
import datetime
13from typing
import cast
16import geometry_from_file
21import validationTools
as validation_tools
22from ShipGeoConfig
import load_from_root_file
27 if not 0.0 <= v <= 1.0:
28 raise ValueError(
"--chargeFraction must be between 0 and 1")
33theHNLMass = 1.0 * u.GeV
34theProductionCouplings = theDecayCouplings =
None
37theDPmass = 0.2 * u.GeV
43MCTracksWithHitsOnly =
False
44MCTracksWithEnergyCutOnly =
True
45MCTracksWithHitsOrEnergyCut =
False
50inputFile =
"$EOSSHIP/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-978Bpot.root"
51defaultInputFile =
True
56usedInputFiles: list[str] = []
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))
65parser = ArgumentParser()
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")
72 dest=
"evtgen_decayer",
73 help=
"Use TEvtGenDecayer for J/psi and other quarkonium decays",
77 "--targetOffset", dest=
"targetOffset", help=
"z offset for the target coordinate", default=0.0, type=float
79subparsers = parser.add_subparsers(dest=
"command", help=
"Which mode to run")
81pg_parser = subparsers.add_parser(
"PG", help=
"Use Particle Gun")
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"
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)"
90pg_parser.add_argument(
94 help=
"File with a histogram to generate from. Repeat for multiple files",
97pg_parser.add_argument(
101 help=
"Histogram name to generate from. Repeat for multiple files",
104pg_parser.add_argument(
108 help=
"The variable of the histogram X axis. Repeat for multiple files",
111pg_parser.add_argument(
115 help=
"The variable of the histogram Y axis. Repeat for multiple files",
118pg_parser.add_argument(
122 help=
"The variable of the histogram Z axis. Repeat for multiple files",
126pg_parser.add_argument(
131 help=
"Generate both charges of given particle ID",
133pg_parser.add_argument(
135 dest=
"chargeFraction",
138 help=
"Fraction of chosen charge from pID to generate [0,1]",
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(
148 help=
"Form of the vertex smearing for the particle gun",
151pg_parser.add_argument(
152 "--multiplicity", dest=
"multiplicity", type=int, default=1, help=
"How many to generate per event"
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)"
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)"
160pg_parser.add_argument(
165 help=
"size of the full uniform spread of PG zpos: (Vz - Dz/2, Vz + Dz/2), with --smearMode uniform3d",
167pg_parser.add_argument(
170 help=
"give all particles of an event the same vertex (with --multiplePG, drawn once per event)",
172pg_parser.add_argument(
173 "--momentumModel", dest=
"momentumModel", default=0, type=int, help=
"Select a model to generate the momentum with"
175pg_parser.add_argument(
179 help=
"Momentum model parameters. You must specify them all in order",
182pg_parser.add_argument(
187 help=
"Print out the PG models that are available",
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)")
193genie_parser = subparsers.add_parser(
"Genie", help=
"Genie for reading and processing neutrino interactions")
194genie_parser.add_argument(
197 default=
"simple_gevgen",
198 choices=[
"simple_gevgen",
"genie_geometry"],
199 help=
"Genie generation option: (simple_gevgen, genie_geometry)",
201genie_parser.add_argument(
206 help=
"Genie neutrino start z start position (default=2844.2850 cm)",
208genie_parser.add_argument(
213 help=
"Genie neutrino end z position (default=3180.4350 cm)",
218 help=
"b: signal from b, c: from c (default), bc: from Bc, inclusive, or for dark photon: meson,pbrem,qcd",
224 help=
"misuse GenieGenerator for neutrino radiography and geometry timing test",
231 action=
"store_false",
232 help=
"Turn off the saving of the geofile at the end.",
238 action=
"store_false",
239 help=
"Turn off the saving of the parameter files at the end.",
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")
247 help=
"Generate events from muon background file, --Cosmics=0 for cosmic generator data",
251 "--FollowMuon", dest=
"followMuon", help=
"Make muonshield active to follow muons", action=
"store_true"
256 help=
"Only transport muons for a fast muon only background estimate",
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",
267 "--MuonBackAllowNoAbsorberField",
268 dest=
"muonBackAllowNoAbsorberField",
269 help=
"MuonBack: accept run_fixedTarget input that was simulated without the hadron absorber field",
274 help=
"only relevant for muon background generator, random phi (not with run_fixedTarget input)",
278 "--SmearBeam", dest=
"SmearBeam", help=
"Standard deviation of beam smearing [cm]", default=0.8, type=float
280parser.add_argument(
"--PaintBeam", dest=
"PaintBeam", help=
"Radius of beam painting [cm]", default=5, type=float)
282 "--Cosmics", dest=
"cosmics", help=
"Use cosmic generator, argument switch for cosmic generator 0 or 1", default=
None
284parser.add_argument(
"--MuDIS", dest=
"mudis", help=
"Use muon deep inelastic scattering generator", action=
"store_true")
288 help=
"Replay prepared/filtered MuonDIS events with NewMuDISGenerator",
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)
299 help=f
"Mass of hidden particle, default {theHNLMass} GeV for HNL, {theDPmass} GeV for DP",
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",
314 "--production-couplings",
315 dest=
"theprodcouplings",
316 help=
"production couplings 'U2e,U2mu,U2tau' to set the couplings for HNL production only",
322 dest=
"thedeccouplings",
323 help=
"decay couplings 'U2e,U2mu,U2tau' to set the couplings for HNL decay only",
327 "-e",
"--epsilon", dest=
"theDPepsilon", help=
"to set mixing parameter epsilon", default=0.00000008, type=float
333 help=
"Number of events to generate (input muons for --NewMuDIS; -1: all)",
338 "-i",
"--firstEvent", help=
"First input entry to use (muon entry for --NewMuDIS)", default=0, type=int
344 help=
"Seed for random number. Only for experts, see TRrandom::SetSeed documentation",
352 help=
"can be set to an integer for the muonBackground simulation with specific seed for each muon, only for experts!",
360 help=
"Input file (repeat -f for multiple files)",
366 help=
"Treat -f/--inputFile values as remote ROOT paths/URLs and skip local glob expansion",
369parser.add_argument(
"--nFiles", dest=
"nFiles", help=
"Number of input files to process", default=-1, type=int)
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.",
384parser.add_argument(
"-o",
"--output", dest=
"outputDir", help=
"Output directory", default=
".")
389 help=
"Numeric simulation ID to reuse instead of generating a new UUID",
396 help=
"Reduce nondeterministic log output for reproducibility/testing",
399parser.add_argument(
"-Y", dest=
"dy", help=
"max height of vacuum tank", default=6.0, type=float)
402 help=
"Tracker station frame material: 4=Aluminium; 10=steel (default)",
410 help=
"default = False: copy only stable particles to stack, except for HNL events",
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")
418 help=
"The name of the muon shield in the database to use.",
420 choices=[
"TRY_2026"],
423 "--MesonMother", dest=
"MM", help=
"Choose DP production meson source: pi0, eta, omega, eta1, eta11", default=
"pi0"
427 help=
"Control FairLogger verbosity: 0=info (default), 1=+debug, 2=+debug1, 3=+debug2",
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")
437 help=
"Specify spectrometer field map as files/<name>.root. Default set in geometry_config.py: files/2026_07_02_MainSpectrometerField_V21_2455.root",
440 "--z-offset", dest=
"z_offset", help=
"z-offset for the FixedTargetGenerator [mm]", default=-84.0, type=float
445 help=
"Set Decay Volume medium to helium. NOOP, as default is helium",
446 action=
"store_const",
453 help=
"Set Decay Volume medium to vacuum(vessel structure changes)",
454 action=
"store_const",
459parser.add_argument(
"--SND", dest=
"SND", help=
"Activate SND.", action=
"store_true")
462 help=
"Choose SND design(s) among [1,2,...] or 'all' to enable all. 1: EmulsionTarget, 2: MTC + SiliconTarget",
467 "--noSND", dest=
"SND", help=
"Deactivate SND. NOOP, as it currently defaults to off.", action=
"store_false"
471 help=
"Path to the yaml target config file",
472 default=os.path.expandvars(
"$FAIRSHIP/geometry/target_config.yaml"),
475 "--tag", dest=
"output_tag", help=
"Custom tag for output files instead of auto-generated UUID", default=
None
480 help=
"Print an extended simulation validation summary after the run",
485options = parser.parse_args()
487if options.nEvents
is None and not options.newmudis:
488 options.nEvents = 100
490if options.mudis
and options.newmudis:
491 parser.error(
"--MuDIS and --NewMuDIS are mutually exclusive")
493available_snd_designs = [1, 2]
494if any(str(x).lower() ==
"all" for x
in options.SND_design):
495 options.SND_design = available_snd_designs
498 options.SND_design = [
int(x)
for x
in options.SND_design]
500 print(
"Invalid value for --SND_design. Use integers or 'all'.")
504 inclusive = options.A
506 inputFile =
"$EOSSHIP/eos/experiment/ship/data/Beauty/Cascade-run0-19-parp16-MSTP82-1-MSEL5-5338Bpot.root"
507 if options.A.lower() ==
"charmonly":
510 if options.A
not in [
"b",
"c",
"bc",
"meson",
"pbrem",
"qcd"]:
514 motherMode = options.MM
517 Opt_high =
int(options.cosmics)
519 if options.inputFile == [
"none"]:
520 options.inputFile =
None
523 for _f
in options.inputFile:
524 if options.remoteInput:
525 inputFile.append(os.path.expandvars(_f))
527 inputFile.extend(glob.glob(_f))
528 inputFile = list(dict.fromkeys(inputFile))
529 if options.nFiles > 0:
530 inputFile = inputFile[: options.nFiles]
535 defaultInputFile =
False
537 parser.error(f
"--inputFile {options.inputFile} matched no files")
540if options.DarkPhoton:
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
548 options.theMass = theHNLMass
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(
",")]
557 inputFile =
"$FAIRSHIP/files/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1_5000.root"
562 geometry_options = [
"dy",
"strawDesign",
"shieldName",
"decayVolMed",
"SND",
"SND_design",
"target_yaml"]
563 probe = parser.parse_args(namespace=Namespace(**dict.fromkeys(geometry_options)))
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
570 parser.error(f
"-g/--geofile cannot be combined with geometry options: {', '.join(given)}")
571 options.geofile = os.path.expandvars(options.geofile)
574 except ValueError
as e:
575 parser.error(f
"-g/--geofile: {e}")
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")
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")
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")
596seed = options.theSeed
598 ROOT.gRandom.SetSeed(0)
599 seed = ROOT.gRandom.GetSeed()
602 seed = seed % 900000000
603ROOT.gRandom.SetSeed(seed)
605if options.reproducible
and options.debug == 0:
606 ROOT.gErrorIgnoreLevel = ROOT.kWarning
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");')
619 ship_geo = load_from_root_file(options.geofile,
"ShipGeo")
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")
628 strawDesign=options.strawDesign,
629 shieldName=options.shieldName,
630 DecayVolumeMedium=options.decayVolMed,
632 SND_design=options.SND_design,
633 TARGET_YAML=options.target_yaml,
636if not options.command:
650 if getattr(options, g):
653 options.pythia8 =
True
659 if options.output_tag
660 else str(options.run_number
if options.run_number
is not None else uuid.uuid4())
662if not os.path.exists(options.outputDir):
663 os.makedirs(options.outputDir)
664outFile = f
"{options.outputDir}/sim_{run_identifier}.root"
667 and os.path.realpath(options.geofile) == os.path.realpath(f
"{options.outputDir}/geo_{run_identifier}.root")
668 and options.save_geofile
670 parser.error(
"-g/--geofile: the geometry file would be overwritten by the output of this run, use another --tag")
673parFile = f
"{options.outputDir}/params_{run_identifier}.root"
679timer = ROOT.TStopwatch()
683run = ROOT.FairRunSim()
685if options.run_number
is not None and hasattr(run,
"SetRunId"):
686 run.SetRunId(options.run_number)
687sink = ROOT.FairRootFileSink(outFile)
689ROOT.SetOwnership(sink,
False)
690run.SetUserConfig(
"g4Config.C")
691rtdb = run.GetRuntimeDb()
699primGen = ROOT.FairPrimaryGenerator()
702 primGen.SetTarget(ship_geo.target.z0, 0.0)
704 if HNL
or options.RPVSUSY:
705 P8gen = ROOT.HNLPythia8Generator()
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")
717 raise ValueError(
"Either both production and decay couplings must be specified, or neither.")
719 P8gen, options.theMass, theProductionCouplings, theDecayCouplings, inclusive, options.deepCopy
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])
729 [theCouplings[0], theCouplings[1]],
731 options.RPVSUSYbench,
735 P8gen.SetParameters(
"ProcessLevel:all = off")
739 P8gen.UseExternalFile(inputFile, options.firstEvent)
740 if options.DarkPhoton:
741 P8gen = ROOT.DPPythia8Generator()
742 if inclusive ==
"qcd":
743 P8gen.SetDPId(4900023)
745 P8gen.SetDPId(9900015)
746 import pythia8darkphoton_conf
749 P8gen, options.theMass, options.theDPepsilon, inclusive, motherMode, options.deepCopy
753 if HNL
or options.RPVSUSY
or options.DarkPhoton:
754 assert P8gen
is not None
755 P8gen.SetSmearBeam(options.SmearBeam * u.cm)
756 P8gen.SetPaintRadius(options.PaintBeam * u.cm)
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)
760 z_end = ship_geo.decayVolume.z0 + ship_geo.decayVolume.length
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)
768 primGen.SetTarget(0.0, 0.0)
770 if ship_geo.Box.gausbeam:
771 primGen.SetBeam(0.0, 0.0, 0.5, 0.5)
772 primGen.SmearGausVertexXY(
True)
775 0.0, 0.0, ship_geo.Box.TX - 1.0, ship_geo.Box.TY - 1.0
777 primGen.SmearVertexXY(
True)
778 P8gen = ROOT.Pythia8Generator()
779 P8gen.UseExternalFile(inputFile, options.firstEvent)
781 P8gen.SetTargetCoordinates(ship_geo.target.z0, ship_geo.target.z0 + ship_geo.target.length)
785 primGen.AddGenerator(P8gen)
786 ROOT.SetOwnership(P8gen,
False)
787if options.fixedTarget:
789 P8gen = ROOT.FixedTargetGenerator()
790 P8gen.SetZoffset(options.z_offset * u.mm)
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)
795 P8gen.SetPaintRadius(options.PaintBeam * u.cm)
796 P8gen.SetEnergyCut(0.0)
797 P8gen.SetHeartBeat(100000)
799 primGen.AddGenerator(P8gen)
800 ROOT.SetOwnership(P8gen,
False)
803 primGen.SetTarget(ship_geo.target.z0 + ship_geo.muShield.length, 0.0)
805 test = ROOT.TPythia6()
806 P6gen = ROOT.tPythia6Generator()
807 P6gen.SetMom(50.0 * u.GeV)
808 P6gen.SetTarget(
"gamma/mu+",
"n0")
809 primGen.AddGenerator(P6gen)
810 ROOT.SetOwnership(P6gen,
False)
814 primGen.SetTarget(0.0, 0.0)
815 print(f
"Opening input file for EvtCalc generator: {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)
824 EvtCalcGen.GetNevents()
if options.nEvents == -1
else min(options.nEvents, EvtCalcGen.GetNevents())
826 print(f
"Generate {options.nEvents} with EvtCalc input. First event: {options.firstEvent}")
829if options.command ==
"PG":
830 myPgun = ROOT.ParticleGunGenerator(options.pID, options.multiplicity)
831 if options.showPGModels:
832 myPgun.PrintVertexModels()
833 myPgun.PrintMomentumModels()
835 myPgun.SetPRange(options.Estart, options.Eend)
836 myPgun.SetPhiRange(0, 360)
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)
840 if options.bothCharges:
841 myPgun.SetBothCharges(
True, options.chargeFraction)
842 if options.multiplePG:
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)
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 []
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")
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)
874 primGen.AddGenerator(myPgun)
875 ROOT.SetOwnership(myPgun,
False)
878if options.mudis
or options.newmudis:
880 primGen.SetTarget(0.0, 0.0)
882 DISgen = ROOT.NewMuDISGenerator()
884 DISgen.SetNevents(100
if options.nEvents
is None else options.nEvents)
886 DISgen = ROOT.MuDISGenerator()
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)
899 nDIS = DISgen.GetNevents()
900 options.nEvents = min(nDIS, 100)
if options.nEvents
is None else nDIS
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)
905if options.command ==
"Genie":
908 primGen.SetTarget(0.0, 0.0)
909 Geniegen = ROOT.GenieGenerator()
911 GenieOptions = {
"simple_gevgen": 0,
"genie_geometry": 3}
912 genie_option = GenieOptions[options.GenieOption]
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)
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)
925 primGen.SetTarget(0.0, 0.0)
926 Geniegen = ROOT.GenieGenerator()
927 if not Geniegen.Init(inputFile, options.firstEvent):
928 raise RuntimeError(f
"Failed to initialize GenieGenerator from input: {inputFile}")
930 Geniegen.SetPositions(ship_geo.target.z0, ship_geo.tauMudet.zMudetC, ship_geo.CaloScoringPlane.z)
932 primGen.AddGenerator(Geniegen)
933 ROOT.SetOwnership(Geniegen,
False)
934 print(
"Generate ", options.nEvents,
" for nuRadiography",
" first event", options.firstEvent)
936 pdg = ROOT.TDatabasePDG.Instance()
937 pdg.AddParticle(
"W",
"Ion", 1.71350e02,
True, 0.0, 74,
"XXX", 1000741840)
939 run.SetPythiaDecayer(
"DecayConfigPy8.C")
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)
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")
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)
964 options.nEvents = Ntuplegen.GetNevents()
if options.nEvents == -1
else min(options.nEvents, Ntuplegen.GetNevents())
965 print(
"Process ", options.nEvents,
" from input file")
970 isNew = ut.checkForBranch(
971 inputFile,
"PlaneHAPoint"
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)
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)
981 fromStage1 = ut.checkForBranch(inputFile,
"MCTrack")
982 startAtPlane = fromStage1
and not options.muonBackFromOrigin
986 if options.phiRandom:
988 "--phiRandom is not supported with run_fixedTarget input: the hadron absorber field breaks the "
989 "symmetry. Use --MuonBackFromOrigin to reproduce the old behaviour."
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)
995 print(f
"WARNING: no FileSummary, cannot check the hadron absorber field of: {', '.join(noSummary)}")
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)}"
1001 if not options.muonBackAllowNoAbsorberField:
1002 raise ValueError(message +
". Pass --MuonBackAllowNoAbsorberField to accept it.")
1003 print(
"WARNING: " + message)
1004 MuonBackgen = ROOT.MuonBackGenerator()
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)
1018 MuonBackgen.GetNevents()
if options.nEvents == -1
else min(options.nEvents, MuonBackgen.GetNevents())
1020 MCTracksWithHitsOnly =
True
1025 " from input file, starting at the scoring plane, with MCTracksWithHitsOnly",
1026 MCTracksWithHitsOnly,
1032 " from input file, with 𝜎 = ",
1034 ", with smear radius r = ",
1035 options.SmearBeam * u.cm,
1036 "with MCTracksWithHitsOnly",
1037 MCTracksWithHitsOnly,
1039 if options.followMuon:
1040 options.fastMuon =
True
1041 modules[
"Veto"].SetFollowMuon()
1042 if options.fastMuon:
1043 modules[
"Veto"].SetFastMuon()
1049 assert Opt_high
is not None
1050 primGen.SetTarget(0.0, 0.0)
1051 Cosmicsgen = ROOT.CosmicsGenerator()
1055 if not Cosmicsgen.Init(Opt_high):
1056 print(
"initialization of cosmic background generator failed ", Opt_high)
1058 Cosmicsgen.n_EVENTS = options.nEvents
1059 primGen.AddGenerator(Cosmicsgen)
1060 ROOT.SetOwnership(Cosmicsgen,
False)
1061 print(
"Process ", options.nEvents,
" Cosmic events with option ", Opt_high)
1064run.SetGenerator(primGen)
1065ROOT.SetOwnership(primGen,
False)
1070if options.eventDisplay:
1071 run.SetStoreTraj(ROOT.kTRUE)
1073 run.SetStoreTraj(ROOT.kFALSE)
1077if options.evtgen_decayer:
1078 run.SetPythiaDecayer(
"DecayConfigTEvtGen.C")
1079 print(
"Using TEvtGenDecayer for J/psi and quarkonium decays with EvtGen")
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()
1096EnergyCut = 10.0 * u.MeV
if (options.mudis
or options.newmudis)
else 100.0 * u.MeV
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)
1111if options.eventDisplay:
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)
1129if hasattr(ship_geo.Bfield,
"fieldMap"):
1130 if options.field_map:
1131 ship_geo.Bfield.fieldMap = options.field_map
1135if options.print_fields:
1139 exclude=[
"DecayVolume",
"Tr1",
"Tr2",
"Tr3",
"Tr4",
"Veto",
"MuonDetector",
"CaloScoringPlane"],
1146run.Run(options.nEvents)
1148kParameterMerged = ROOT.kTRUE
1149parOut = ROOT.FairParRootFileIo(kParameterMerged)
1150if options.save_parfile:
1151 if os.path.exists(parFile):
1153 parOut.open(parFile)
1154 rtdb.setOutput(parOut)
1155 ROOT.SetOwnership(parOut,
False)
1157 print(
"Parameter file is ", parFile)
1159if options.save_geofile:
1160 geofile_name = f
"{options.outputDir}/geo_{run_identifier}.root"
1161 run.CreateGeometryFile(geofile_name)
1163 import saveBasicParameters
1166 print(
"Geometry file is ", geofile_name)
1169if options.check_overlaps:
1170 ROOT.gROOT.SetWebDisplay(
"off")
1171 fGeo = ROOT.gGeoManager
1172 fGeo.SetNmeshPoints(10000)
1173 fGeo.CheckOverlaps(0.1)
1174 fGeo.PrintOverlaps()
1176 for x
in fGeo.GetTopNode().GetNodes():
1177 x.CheckOverlaps(0.0001)
1178 fGeo.PrintOverlaps()
1181rtime = timer.RealTime()
1182ctime = timer.CpuTime()
1184print(
"Macro finished successfully.")
1185if P8gen
is not None:
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())
1194print(
"Output file is ", outFile)
1195if not options.reproducible:
1196 print(
"Real time ", rtime,
" s, CPU time ", ctime,
"s")
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)
1209 fin = ROOT.TFile.Open(outFile)
1211 fout = ROOT.TFile(tmpFile,
"recreate")
1212 fSink = ROOT.FairRootFileSink(fout)
1213 ROOT.SetOwnership(fout,
False)
1215 sTree = t.CloneTree(0)
1218 pointContainers = []
1219 for branch
in sTree.GetListOfBranches():
1220 name = branch.GetName()
1222 pointContainers.append(name)
1226 pointContainers = [n
for n
in pointContainers
if n
not in (
"CaloScoringPlanePoint",
"UpstreamTaggerScoringPoint")]
1231 for containerName
in pointContainers:
1232 container = getattr(sTree, containerName)
1233 if container.size() > 0:
1241 branches = ROOT.TList()
1242 branches.SetName(
"BranchList")
1243 branches.SetOwner(
True)
1253 "CaloScoringPlanePoint",
1255 "UpstreamTaggerPoint",
1256 "UpstreamTaggerScoringPoint",
1258 "SiliconTargetPoint",
1261 obj = ROOT.TObjString(name)
1262 ROOT.SetOwnership(obj,
False)
1266 fSink.WriteObject(branches,
"BranchList", ROOT.TObject.kSingleKey)
1267 fSink.SetOutTree(sTree)
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)
1276 from MuDISGenerator_postProcessing
import post_process
1278 post_process(outFile, inputFile, options.firstEvent)
1280 temp_filename = outFile.replace(
".root",
"_tmp.root")
1283 ROOT.TFile.Open(outFile,
"read")
as f_outputfile,
1284 ROOT.TFile.Open(temp_filename,
"recreate")
as f_temp,
1286 output_tree = f_outputfile[
"cbmsim"]
1287 muondis_tree = ROOT.TChain(
"DIS")
1288 for _f
in inputFile:
1289 muondis_tree.Add(_f)
1291 new_tree = output_tree.CloneTree(0)
1293 cross_section = array(
"f", [0.0])
1294 cross_section_leaf = new_tree.Branch(
"CrossSection", cross_section,
"CrossSection/F")
1296 for output_event, muondis_event
in zip(output_tree, muondis_tree):
1297 mu = muondis_event.InMuon[0]
1298 cross_section[0] = mu[10]
1301 new_tree.Write(
"", ROOT.TObject.kOverwrite)
1303 os.replace(temp_filename, outFile)
1304 print(
"Successfully added DISCrossSection to the output file:", outFile)
1306if options.command ==
"Genie":
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"]
1313 raise KeyError(
"TTree 'gst' not found in GENIE input file")
1315 selection_string =
"(Entry$ >= " + str(options.firstEvent) +
")"
1316 if (options.firstEvent + options.nEvents) < gst.GetEntries():
1317 selection_string +=
"&&(Entry$ < " + str(options.firstEvent + options.nEvents) +
")"
1320 f_output = ROOT.TFile.Open(outFile,
"UPDATE")
1323 gst_copy = gst.CopyTree(selection_string)
1329if options.run_number
is not None:
1330 with ROOT.TFile.Open(outFile,
"UPDATE")
as f_output:
1331 file_header = f_output.Get(
"FileHeader")
1333 file_header.SetRunId(options.run_number)
1334 file_header.Write(
"FileHeader", ROOT.TObject.kSingleKey)
1336 print(
"WARNING: FileHeader not found in simulation output; skipped FileHeader RunID update")
1338print(
"[INFO]: Saving FileSummary")
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.
1347 if isinstance(inFiles, str):
1359 "date": datetime.today().strftime(
"%Y-%m-%d"),
1362 mergedFSR[
"inputFiles"].append(_f)
1365 path = os.path.expandvars(_f)
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")))
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}")
1376 mergedFSR[
"PoT"] += fsr[
"PoT"]
1377 energyCuts.append(fsr[
"EnergyCut"])
1378 prodSites.append(fsr[
"prodSite"])
1379 poTperFile.append(fsr[
"PoT"])
1381 print(f
"[WARNING] No FileSummary in {_f}")
1385 print(f
"[WARNING] Could not open {path} to read its FileSummary")
1387 mergedFSR[
"EnergyCut"] = list(set(energyCuts))
1388 mergedFSR[
"prodSite"] = list(set(prodSites))
1389 mergedFSR[
"PoTperFile"] = list(set(poTperFile))
1394with ROOT.TFile.Open(outFile,
"UPDATE")
as _of:
1395 _of.WriteObject(ROOT.TString(json.dumps(newFileSummary)),
"FileSummary")
1398print(
"Simulation finished successfully")
1401if options.validation:
1402 validation_tools.print_simulation_output_summary(
1406 {
"HNL": HNL,
"DarkPhoton": options.DarkPhoton,
"fixedTarget": options.fixedTarget},
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"),
1417import checkMagFields
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)
None printWeightsandFields(bool onlyWithField=True, exclude=None)
addVMCFields(shipGeo, str controlFile="", bool verbose=False, bool withVirtualMC=True)
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)
float _fraction_0_1(str value)
execute(f, ox, name="ShipGeo")
configure(run, ship_geo, str|None geofile=None)
None configure(darkphoton=None)