7from types
import SimpleNamespace
13from heavyFlavourScaling
import (
15 check_run_type_override,
16 derive_cross_sections,
40logger = logging.getLogger(os.path.splitext(os.path.basename(os.sys.argv[0]))[0])
41logger.setLevel(logging.INFO)
47 host = socket.gethostname()
48 job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0]
50 out_dir = f
"{host}_{job_base_name}_{run_number}_{tag}"
52 out_dir = f
"{host}_{job_base_name}_{run_number}"
56logger.info(
"SHiP proton-on-taget simulator (C) Thomas Ruf, 2017")
58ap = argparse.ArgumentParser(description=
'Run SHiP "pot" simulation')
59ap.add_argument(
"-d",
"--debug", action=
"store_true")
60ap.add_argument(
"-f",
"--force", action=
"store_true", help=
"force overwriting output directory")
61ap.add_argument(
"-r",
"--run-number", type=int, dest=
"runnr", default=1)
65 help=
"Reduce nondeterministic log output for reproducibility/testing",
68 "-e",
"--ecut", type=float, help=
"energy cut", default=0.5
70ap.add_argument(
"-n",
"--num-events", type=int, help=
"number of events to generate", dest=
"nev", default=100)
74 action=argparse.BooleanOptionalAction,
76 help=
"Whether or not to use Geant4 directly, no Pythia8 (--no-G4only or --G4only). Default set to False.",
81 action=argparse.BooleanOptionalAction,
83 help=
"Whether or not to use Pythia8 for decays (--no-PythiaDecay or --PythiaDecay). Default set to False.",
89 choices=[
"default",
"FTFT"],
90 help=
"Pythia8 tune for the primary interaction: default (Monash 2013) or FTFT "
91 "(fixed-target open charm and beauty tune, arXiv:2608.29076).",
93ap.add_argument(
"-t",
"--tau-only", action=argparse.BooleanOptionalAction, dest=
"tauOnly", default=
False)
94ap.add_argument(
"-J",
"--Jpsi-mainly", action=argparse.BooleanOptionalAction, dest=
"JpsiMainly", default=
False)
95ap.add_argument(
"-b",
"--boostDiMuon", type=float, default=1.0, help=
"boost Di-muon branching ratios")
96ap.add_argument(
"-X",
"--boostFactor", type=float, default=1.0, help=
"boost Di-muon prod cross sections")
101 help=
"splitting factor for kaons and pions when they decay, in order to boost the number of muons stemming from their decays",
104 "--intermediate-kaon-pion-splits",
107 help=
"EXPERTS ONLY: intermediate splitting factor for kaons and pions for each GEANT4 step before they decay, "
108 "in order to boost the number of muons stemming from forced decays. "
109 "EXPERTS ONLY: risk of very large memory usage if the number is set without proper testing",
112 "--kaon-pion-lifetime-factor",
115 help=
"VALIDATION ONLY: scale the lifetimes of K+-, pi+- in Geant4 by this factor. Shorter lifetimes make "
116 "decays in flight common, so that split and unsplit samples can be compared at the level of single decays "
117 "with few events. The output is not physical for any factor other than 1",
120 "--store-all-tracks",
122 help=
"VALIDATION ONLY: store every track and every event, not only tracks with hits in a sensitive plane "
123 "(and their ancestors) in events with such hits. Needed to compare split and unsplit samples at the level of "
124 "the kaon/pion decays themselves. Output files are about 100 times larger with --multiple-kpi-splits",
127 "--max-split-buffer",
130 help=
"EXPERTS ONLY: maximum number of split clones buffered per track before further per-step splitting is "
131 "skipped. Memory safety valve for --multiple-kpi-splits; lowering it reduces the statistical boost but "
132 "conserves weight. With the default --max-event-size, that cap is reached first (at about 10k clones)",
138 help=
"EXPERTS ONLY: cap on the projected number of particles in the event, counting "
139 "exitHadronAbsorber::kShowerSafetyFactor (500) for each pending split clone, beyond which further per-step "
140 "splitting is skipped. Memory safety valve for "
141 "--multiple-kpi-splits; lowering it reduces the statistical boost but conserves weight",
145 "--multiple-kpi-splits",
147 help=
"split kaons and pions multiple times along the track path",
150ap.add_argument(
"-C",
"--charm", action=argparse.BooleanOptionalAction, default=
False, help=
"generate charm decays")
151ap.add_argument(
"-B",
"--beauty", action=argparse.BooleanOptionalAction, default=
False, help=
"generate beauty decays")
155 action=argparse.BooleanOptionalAction,
157 help=
"store only muons, ignore neutrinos",
159ap.add_argument(
"-N",
"--skipNeutrinos", action=argparse.BooleanOptionalAction, default=
False, help=
"skip neutrinos")
163 action=argparse.BooleanOptionalAction,
166 help=
"enable ntuple production",
170cross_section = ap.add_mutually_exclusive_group()
171cross_section.add_argument(
172 "-cc",
"--chicc", type=float, default=
None, help=
"ccbar over mbias cross section (overrides target-derived value)"
174cross_section.add_argument(
175 "-bb",
"--chibb", type=float, default=
None, help=
"bbbar over mbias cross section (overrides target-derived value)"
178 "--target-composition",
181 help=
"Target composition. Default is Tungsten (W); Molybdenum (Mo) is the other preset.",
188 "Target mass number; overrides --target-composition preset. "
189 "Used to scale chicc/chibb as (A/A_Mo)^(heavyflavour_Ascale-mbias_Ascale) "
190 "(default exponent: 0.29)."
193ap.add_argument(
"-p",
"--pot", default=4e13, help=
"number of protons on target per spill to normalize on")
194ap.add_argument(
"-S",
"--nStart", type=int, help=
"first event of input file to start", dest=
"nStart", default=0)
199 dest=
"charmInputFile",
200 default=ROOT.gSystem.Getenv(
"EOSSHIP")
201 +
"/eos/experiment/ship/data/Charm/Cascade-parp16-MSTP82-1-MSEL4-76Mpot_1.root",
202 help=
"input file for charm/beauty decays",
204ap.add_argument(
"-o",
"--output", type=str, help=
"output directory", dest=
"work_dir", default=
None)
206 "-rs",
"--seed", type=int, help=
"random seed; default value is 0, see TRrandom::SetSeed documentation", default=0
209 "--DecayVolumeMedium",
210 help=
"Set Decay Volume Medium. Choices are helium (default) or vacuums.",
212 choices=[
"helium",
"vacuums"],
216 help=
"Name of the shield in the database.",
218 choices=[
"TRY_2026"],
222 help=
"Whether or not to add the muon shield. Default set to False.",
224 action=argparse.BooleanOptionalAction,
227 "--AddMuonShieldField",
228 help=
"Whether or not to add the muon shield magnetic field, including the field of the hadron absorber. "
229 "Default set to True: MuonBack continues the scored tracks from the scoring plane, so the field up to the "
230 "plane has to be simulated here.",
232 action=argparse.BooleanOptionalAction,
235 "--AddHadronAbsorberOnly",
236 help=
"Whether to only add the hadron absorber part of the muon shield. Default set to True.",
238 action=argparse.BooleanOptionalAction,
242 "--z-offset", type=float, dest=
"z_offset", default=-84.0, help=
"z-offset for the FixedTargetGenerator [mm]"
245 "--x-offset", type=float, dest=
"x_offset", default=0.0, help=
"x-offset for the FixedTargetGenerator [mm]"
248 "--y-offset", type=float, dest=
"y_offset", default=0.0, help=
"y-offset for the FixedTargetGenerator [mm]"
251 "--beam-smear", type=float, dest=
"beam_smear", default=16.0, help=
"beam smearing for the FixedTargetGenerator [mm]"
258 help=
"beam painting radius for the FixedTargetGenerator [mm]",
263 help=
"File for target configuration",
264 default=os.path.expandvars(
"$FAIRSHIP/geometry/target_config.yaml"),
268 "--AddCylindricalSensPlane",
270 help=
"Whether or not to add cylindrical sensitive plane around the target. False by default.",
273 "--AddPostTargetSensPlane",
275 help=
"Whether or not to add sensitive plane after the target. False by default.",
278args = ap.parse_args()
280 logger.setLevel(logging.DEBUG)
282if args.kaon_pion_splits < 0:
283 ap.error(
"--kaon-pion-splits must be >= 0")
284if args.pythia8_tune !=
"default" and (args.charm
or args.beauty
or args.G4only):
285 ap.error(
"--pythia8-tune only affects the Pythia8 primary interaction, which --charm/--beauty/--G4only do not run")
286if args.multiple_kpi_splits
and (args.kaon_pion_splits < 1
or args.intermediate_kaon_pion_splits < 1):
287 ap.error(
"--multiple-kpi-splits requires --kaon-pion-splits and --intermediate-kaon-pion-splits to be positive")
288if not args.kaon_pion_lifetime_factor > 0:
289 ap.error(
"--kaon-pion-lifetime-factor must be > 0")
290if args.max_split_buffer < 1:
291 ap.error(
"--max-split-buffer must be >= 1")
292if args.max_event_size < 1
or args.max_event_size > 2_147_483_647:
293 ap.error(
"--max-event-size must be >= 1 and <= 2_147_483_647")
295if args.max_split_buffer < args.kaon_pion_splits:
297 "--max-split-buffer must be >= --kaon-pion-splits: the clones buffered when the parent "
298 "decays have to fit under the cap"
300if args.multiple_kpi_splits:
304 clones_per_split = args.kaon_pion_splits + args.intermediate_kaon_pion_splits
305 if args.max_split_buffer < clones_per_split:
306 ap.error(
"--max-split-buffer must be >= --kaon-pion-splits + --intermediate-kaon-pion-splits")
307 shower_safety_factor = ROOT.exitHadronAbsorber.kShowerSafetyFactor
308 if args.max_event_size < shower_safety_factor * clones_per_split:
310 f
"--max-event-size must be >= {shower_safety_factor} * "
311 "(--kaon-pion-splits + --intermediate-kaon-pion-splits), "
312 "the projected event size of a single per-step split"
319 args.pythiaDecay =
False
320elif args.pythiaDecay:
322 logger.info(
"use Pythia8 as primary decayer")
325 logger.info(
"use EvtGen as primary decayer")
327if args.charm
and args.beauty:
328 logger.warning(
"charm and beauty decays are set! Beauty gets priority")
330charmInputFile = args.charmInputFile
332if args.work_dir
is None:
337 elif args.pythia8_tune !=
"default":
338 tag = args.pythia8_tune
343logger.debug(
"work_dir: %s" % args.work_dir)
344logger.debug(
"command line arguments: %s", args)
345if os.path.exists(args.work_dir):
346 logger.warning(
"output directory '%s' already exists." % args.work_dir)
348 logger.warning(
"...cleaning")
349 for root, dirs, files
in os.walk(args.work_dir):
351 os.unlink(os.path.join(root, f))
353 shutil.rmtree(os.path.join(root, d))
355 logger.warning(
"...use '-f' option to overwrite it")
357 os.makedirs(args.work_dir)
359os.chdir(args.work_dir)
365 ROOT.gRandom.SetSeed(0)
366 seed = ROOT.gRandom.GetSeed()
369 seed = seed % 900000000
370ROOT.gRandom.SetSeed(seed)
372if args.reproducible
and not args.debug:
373 ROOT.gErrorIgnoreLevel = ROOT.kWarning
376 "DecayVolumeMedium": args.DecayVolumeMedium,
377 "shieldName": args.shieldName,
378 "TARGET_YAML": args.TARGET_YAML,
382txt =
"pythia8_Geant4_"
384 txt =
"pythia8_evtgen_Geant4_"
385outFile = f
"{outputDir}/{txt}{args.runnr}_{args.ecut}.root"
386parFile = f
"{outputDir}/ship.params.{txt}{args.runnr}_{args.ecut}.root"
389timer = ROOT.TStopwatch()
393run = ROOT.FairRunSim()
395if hasattr(run,
"SetRunId"):
396 run.SetRunId(args.runnr)
397sink = ROOT.FairRootFileSink(outFile)
399ROOT.SetOwnership(sink,
False)
400if args.boostFactor > 1:
402 os.environ[
"SET_GENERAL_PROCESS_TO_FALSE"] =
"1"
403if args.kaon_pion_splits > 0:
404 os.environ[
"KAON_PION_SPLITS"] =
str(args.kaon_pion_splits)
405run.SetUserConfig(
"g4Config.C")
406rtdb = run.GetRuntimeDb()
409run.SetMaterials(
"media.geo")
411cave = ROOT.ShipCave(
"CAVE")
412cave.SetGeometryFileName(
"caveWithAir.geo")
415ROOT.SetOwnership(cave,
False)
417TargetStation = ROOT.ShipTargetStation(
418 name=
"TargetStation",
419 tl=ship_geo.target.length,
420 tz=ship_geo.target.z,
421 nS=ship_geo.target.nS,
422 HeT=ship_geo.target.HeT,
424TargetStation.SetLayerPosMat(
425 d=ship_geo.target.xy,
426 L=ship_geo.target.slices_length,
427 G=ship_geo.target.slices_gap,
428 M=ship_geo.target.slices_material,
430target_version = getattr(ship_geo.target,
"version", 1)
431TargetStation.SetDesign(target_version)
432if target_version >= 2:
433 TargetStation.SetLastDiskDiameter(ship_geo.target.xy2)
434TargetStation.SetShieldingReferenceLength(ship_geo.target.length_fixed)
435run.AddModule(TargetStation)
436ROOT.SetOwnership(TargetStation,
False)
439if args.AddPostTargetSensPlane:
440 sensPlanePostT = ROOT.exitHadronAbsorber()
441 sensPlanePostT.SetEnergyCut(args.ecut * u.GeV)
442 sensPlanePostT.SetVetoPointName(
"PlanePostT")
445 sensPlanePostT.SetZposition(158.64 * u.cm + 300 * u.mm + 6.2 * u.cm)
447 sensPlanePostT.SetUseCaveCoordinates()
449 if args.storeOnlyMuons:
450 sensPlanePostT.SetOnlyMuons()
451 if args.skipNeutrinos:
452 sensPlanePostT.SkipNeutrinos()
454 sensPlanePostT.SetOpt4DP()
455 run.AddModule(sensPlanePostT)
456 ROOT.SetOwnership(sensPlanePostT,
False)
459if args.AddMuonShield
or args.AddHadronAbsorberOnly:
460 params = list(ship_geo.muShield.params)
461 n_magnets = ship_geo.muShield.nMagnets
462 if args.AddHadronAbsorberOnly:
464 params = params[: ROOT.ShipMuonShield.nParams]
467 MuonShield = ROOT.ShipMuonShield(
470 z=ship_geo.muShield.z,
473 run.AddModule(MuonShield)
474 ROOT.SetOwnership(MuonShield,
False)
477sensPlaneHA = ROOT.exitHadronAbsorber()
478sensPlaneHA.SetNSplits(args.kaon_pion_splits)
479sensPlaneHA.SetMaxSplitBuffer(args.max_split_buffer)
480sensPlaneHA.SetMaxEventSize(args.max_event_size)
481if args.multiple_kpi_splits:
482 sensPlaneHA.SetSplitMultipleTimes()
483 sensPlaneHA.SetIntermediateNSplits(args.intermediate_kaon_pion_splits)
484sensPlaneHA.SetEnergyCut(args.ecut * u.GeV)
485sensPlaneHA.SetVetoPointName(
"PlaneHA")
488if args.AddCylindricalSensPlane:
489 sensPlaneT = ROOT.exitHadronAbsorber()
490 sensPlaneT.SetEnergyCut(args.ecut * u.GeV)
491 sensPlaneT.SetVetoPointName(
"PlaneT")
492 sensPlaneT.SetCylindricalPlane()
495 sensPlaneT.SetZposition(ship_geo.target.length)
497if args.storeOnlyMuons:
498 sensPlaneHA.SetOnlyMuons()
499 if sensPlaneT
is not None:
500 sensPlaneT.SetOnlyMuons()
501if args.skipNeutrinos:
502 sensPlaneHA.SkipNeutrinos()
503 if sensPlaneT
is not None:
504 sensPlaneT.SkipNeutrinos()
506 sensPlaneHA.SetOpt4DP()
507 if sensPlaneT
is not None:
508 sensPlaneT.SetOpt4DP()
515if sensPlaneT
is not None:
516 run.AddModule(sensPlaneT)
517 ROOT.SetOwnership(sensPlaneT,
False)
519run.AddModule(sensPlaneHA)
520ROOT.SetOwnership(sensPlaneHA,
False)
523primGen = ROOT.FairPrimaryGenerator()
524P8gen = ROOT.FixedTargetGenerator()
525P8gen.SetZoffset(args.z_offset * u.mm)
526P8gen.SetXoffset(args.x_offset * u.mm)
527P8gen.SetYoffset(args.y_offset * u.mm)
528P8gen.SetSmearBeam(args.beam_smear * u.mm)
529P8gen.SetPaintRadius(args.beam_paint * u.mm)
531P8gen.SetTargetCoordinates(ship_geo.target.z0, ship_geo.target.z0 + ship_geo.target.length)
532P8gen.SetMom(400.0 * u.GeV)
533P8gen.SetEnergyCut(args.ecut * u.GeV)
534P8gen.SetDebug(args.debug)
535P8gen.SetHeartBeat(100000)
538P8gen.SetPythiaTune(args.pythia8_tune)
540 P8gen.SetJpsiMainly()
545if args.boostDiMuon > 1:
554if args.charm
or args.beauty:
555 check_run_type_override(args.beauty, args.chicc, args.chibb)
558 with ROOT.TFile.Open(charmInputFile)
as _fin:
559 sigma_QQ = _fin.Get(
"sigma_QQ").GetVal()
if _fin.Get(
"sigma_QQ")
else None
560 _ntuple = _fin.Get(
"pythia6")
562 input_is_beauty = file_is_beauty(_ntuple.M)
564 check_input_flavour(args.beauty, input_is_beauty)
566 flavour =
"beauty" if input_is_beauty
else "charm"
568 f
"Input file {flavour} cross section per nucleon: {1e3 * sigma_QQ:.3g} ub, used to scale chi{flavour[0] * 2}"
570 cs = derive_cross_sections(args.target_composition, args.A, args.chicc, args.chibb, sigma_QQ, args.beauty)
571 P8gen.SetChicc(cs.chicc)
572 P8gen.SetChibb(cs.chibb)
573 print(format_summary(cs,
None if args.A
is not None else args.target_composition))
574 print(
"--- process heavy flavours ---")
575 if not P8gen.InitForCharmOrBeauty(charmInputFile, args.nev, args.pot, args.nStart):
576 raise SystemExit(f
"Could not use {charmInputFile} as heavy-flavour input, see the error above")
577primGen.AddGenerator(P8gen)
578ROOT.SetOwnership(P8gen,
False)
580run.SetGenerator(primGen)
581ROOT.SetOwnership(primGen,
False)
586if (args.AddMuonShield
or args.AddHadronAbsorberOnly)
and args.AddMuonShieldField:
592gMC = ROOT.TVirtualMC.GetMC()
593fStack = gMC.GetStack()
596fStack.SetMinPoints(0
if args.store_all_tracks
else 1)
597fStack.SetEnergyCut(-1.0)
598if args.kaon_pion_splits > 0:
599 fStack.SetSplitting()
601if args.kaon_pion_lifetime_factor != 1.0:
604 for cls
in (
"G4KaonPlus",
"G4KaonMinus",
"G4PionPlus",
"G4PionMinus"):
605 ROOT.gROOT.ProcessLine(f
'#include "Geant4/{cls}.hh"')
606 ROOT.gROOT.ProcessLine(
607 f
"{cls}::Definition()->SetPDGLifeTime("
608 f
"{cls}::Definition()->GetPDGLifeTime() * {args.kaon_pion_lifetime_factor!r});"
610 for pdg
in (321, 211):
612 "Lifetime of %d scaled by %g to %.6g ns: validation only, the output is not physical",
614 args.kaon_pion_lifetime_factor,
615 gMC.ParticleLifeTime(pdg),
618import AddDiMuonDecayChannelsToG4
623if args.boostFactor > 1:
624 ROOT.gROOT.ProcessLine(
'#include "Geant4/G4ProcessTable.hh"')
625 ROOT.gROOT.ProcessLine(
'#include "Geant4/G4AnnihiToMuPair.hh"')
626 ROOT.gROOT.ProcessLine(
'#include "Geant4/G4GammaConversionToMuons.hh"')
627 gProcessTable = ROOT.G4ProcessTable.GetProcessTable()
628 procAnnihil = gProcessTable.FindProcess(ROOT.G4String(
"AnnihiToMuPair"), ROOT.G4String(
"e+"))
629 procGMuPair = gProcessTable.FindProcess(ROOT.G4String(
"GammaToMuPair"), ROOT.G4String(
"gamma"))
630 procAnnihil.SetCrossSecFactor(args.boostFactor)
631 procGMuPair.SetCrossSecFactor(args.boostFactor)
638rtime = timer.RealTime()
639ctime = timer.CpuTime()
641print(
"Macro finished successfully.")
642print(f
"Output file is {outFile}")
643if not args.reproducible:
644 print(f
"Real time {rtime} s, CPU time {ctime} s")
646tmpFile = outFile +
"tmp"
648fin = ROOT.gROOT.GetListOfFiles().FindObject(outFile)
650 fin = ROOT.TFile.Open(outFile)
651fHeader = fin.Get(
"FileHeader")
653 fHeader.SetRunId(args.runnr)
655 print(
"WARNING: FileHeader not found in simulation output; skipped FileHeader RunID update")
656if args.charm
or args.beauty:
658 poteq = P8gen.GetPotForCharm()
659 info =
"POT equivalent = %7.3G" % (poteq)
661 info = f
"POT = {args.nev}"
663conditions =
" with ecut=" +
str(args.ecut)
664if args.pythia8_tune !=
"default":
665 conditions +=
" " + args.pythia8_tune
672if args.boostDiMuon > 1:
673 conditions +=
" diMu" +
str(args.boostDiMuon)
674if args.boostFactor > 1:
675 conditions +=
" X" +
str(args.boostFactor)
679 fHeader.SetTitle(info)
680 print(f
"Data generated {fHeader.GetTitle()}")
682 print(f
"Data generated {info}")
687 tf = ROOT.TFile(
"FourDP.root",
"recreate")
688 tnt = nt.CloneTree(0)
689 for i
in range(nt.GetEntries()):
691 rc = tnt.Fill(nt.id, nt.px, nt.py, nt.pz, nt.x, nt.y, nt.z)
696fout = ROOT.TFile(tmpFile,
"recreate")
697sTree = t.CloneTree(0)
699for n
in range(t.GetEntries()):
702 args.store_all_tracks
703 or (len(t.PlaneHAPoint) > 0)
704 or (args.AddCylindricalSensPlane
and len(t.PlaneTPoint) > 0)
705 or (args.AddPostTargetSensPlane
and len(t.PlanePostTPoint) > 0)
710for k
in fin.GetListOfKeys():
711 x = fin.Get(k.GetName())
712 className = x.Class().GetName()
713 if className.find(
"TTree") < 0
and className.find(
"TNtuple") < 0:
718 ff = fHeader.Clone(fout.GetName())
720 ff.Write(
"FileHeader", ROOT.TObject.kSingleKey)
724rc1 = os.system(
"rm " + outFile)
725rc2 = os.system(
"mv " + tmpFile +
" " + outFile)
726print(
"removed out file, moved tmpFile to out file", rc1, rc2)
728if rc1 == 0
and rc2 == 0:
729 print(
"INFO: Adding file summary")
731 with ROOT.TFile.Open(outFile,
"UPDATE")
as _of:
732 _of.WriteObject(ROOT.TString(json.dumps(fsr)),
"FileSummary")
734 print(
"WARNING: tempFile mv or rm not successful. No attempt at FileSummary writing")
736fin.SetWritable(
False)
738print(f
"Number of events produced with activity after hadron absorber: {nEvents}")
741 sGeo = ROOT.gGeoManager
744 run.CreateGeometryFile(
"%s/geofile_full.root" % (outputDir))
745 import saveBasicParameters
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)
str get_work_dir(run_number, str|None tag=None)
execute(f, ox, name="ShipGeo")
None configure(darkphoton=None)