FairShip
Loading...
Searching...
No Matches
run_fixedTarget.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 json
6import os
7from types import SimpleNamespace
8
9import geometry_config
10import ROOT
11import shipRoot_conf
12import shipunit as u
13from heavyFlavourScaling import (
14 check_input_flavour,
15 check_run_type_override,
16 derive_cross_sections,
17 file_is_beauty,
18 format_summary,
19)
20
21mcEngine = "TGeant4"
22simEngine = "Pythia8"
23checkOverlap = True
24outputDir = "."
25dy = 6.0 # 10.
26ds = 8 # 9 # 5=TP muon shield, 6=magnetized hadron, 7=short magnet design, 9=optimised with T4 as constraint, 8=requires config file
27
28# example for primary interaction, nobias: python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py -n 10000 -e 10 -f -r 10
29# 10000 events, energy cut 10GeV, run nr 10, override existing output folder
30# example for charm decays, python $FAIRSHIP/muonShieldOptimization/run_fixedTarget.py -C -M -n 10000 -e 10 -r 60 -b 50 -f
31# 10000 events, charm decays, energy cut 10GeV, run nr 60, override existing output folder
32# increase di-muon BRs for resonances < 1.1GeV by a factor 50
33
34# ----------------------------- Yandex production ------------------------------
35import argparse
36import logging
37import shutil
38
39logging.info("")
40logger = logging.getLogger(os.path.splitext(os.path.basename(os.sys.argv[0]))[0])
41logger.setLevel(logging.INFO)
42
43
44def get_work_dir(run_number, tag: str | None = None) -> str:
45 import socket
46
47 host = socket.gethostname()
48 job_base_name = os.path.splitext(os.path.basename(os.sys.argv[0]))[0]
49 if tag:
50 out_dir = f"{host}_{job_base_name}_{run_number}_{tag}"
51 else:
52 out_dir = f"{host}_{job_base_name}_{run_number}"
53 return out_dir
54
55
56logger.info("SHiP proton-on-taget simulator (C) Thomas Ruf, 2017")
57
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)
62ap.add_argument(
63 "--reproducible",
64 action="store_true",
65 help="Reduce nondeterministic log output for reproducibility/testing",
66)
67ap.add_argument(
68 "-e", "--ecut", type=float, help="energy cut", default=0.5
69) # GeV with 1 : ~1sec / event, with 2: 0.4sec / event, 10: 0.13sec
70ap.add_argument("-n", "--num-events", type=int, help="number of events to generate", dest="nev", default=100)
71ap.add_argument(
72 "-G",
73 "--G4only",
74 action=argparse.BooleanOptionalAction,
75 default=False,
76 help="Whether or not to use Geant4 directly, no Pythia8 (--no-G4only or --G4only). Default set to False.",
77)
78ap.add_argument(
79 "-P",
80 "--pythiaDecay",
81 action=argparse.BooleanOptionalAction,
82 default=False,
83 help="Whether or not to use Pythia8 for decays (--no-PythiaDecay or --PythiaDecay). Default set to False.",
84)
85ap.add_argument(
86 "--pythia8-tune",
87 dest="pythia8_tune",
88 default="default",
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).",
92)
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")
97ap.add_argument(
98 "--kaon-pion-splits",
99 type=int,
100 default=0,
101 help="splitting factor for kaons and pions when they decay, in order to boost the number of muons stemming from their decays",
102)
103ap.add_argument(
104 "--intermediate-kaon-pion-splits",
105 type=int,
106 default=2,
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",
110)
111ap.add_argument(
112 "--kaon-pion-lifetime-factor",
113 type=float,
114 default=1.0,
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",
118)
119ap.add_argument(
120 "--store-all-tracks",
121 action="store_true",
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",
125)
126ap.add_argument(
127 "--max-split-buffer",
128 type=int,
129 default=25000,
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)",
133)
134ap.add_argument(
135 "--max-event-size",
136 type=int,
137 default=5_000_000,
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",
142)
143
144ap.add_argument(
145 "--multiple-kpi-splits",
146 action="store_true",
147 help="split kaons and pions multiple times along the track path",
148)
149
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")
152ap.add_argument(
153 "-M",
154 "--storeOnlyMuons",
155 action=argparse.BooleanOptionalAction,
156 default=False,
157 help="store only muons, ignore neutrinos",
158)
159ap.add_argument("-N", "--skipNeutrinos", action=argparse.BooleanOptionalAction, default=False, help="skip neutrinos")
160ap.add_argument(
161 "-D",
162 "--4darkPhoton",
163 action=argparse.BooleanOptionalAction,
164 dest="FourDP",
165 default=False,
166 help="enable ntuple production",
167)
168# for charm production
169# A run is either charm or beauty, so only one ratio override is ever meaningful.
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)"
173)
174cross_section.add_argument(
175 "-bb", "--chibb", type=float, default=None, help="bbbar over mbias cross section (overrides target-derived value)"
176)
177ap.add_argument(
178 "--target-composition",
179 default="W",
180 choices=["W", "Mo"],
181 help="Target composition. Default is Tungsten (W); Molybdenum (Mo) is the other preset.",
182)
183ap.add_argument(
184 "-A",
185 type=float,
186 default=None,
187 help=(
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)."
191 ),
192)
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)
195ap.add_argument(
196 "-I",
197 "--InputFile",
198 type=str,
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",
203)
204ap.add_argument("-o", "--output", type=str, help="output directory", dest="work_dir", default=None)
205ap.add_argument(
206 "-rs", "--seed", type=int, help="random seed; default value is 0, see TRrandom::SetSeed documentation", default=0
207)
208ap.add_argument(
209 "--DecayVolumeMedium",
210 help="Set Decay Volume Medium. Choices are helium (default) or vacuums.",
211 default="helium",
212 choices=["helium", "vacuums"],
213)
214ap.add_argument(
215 "--shieldName",
216 help="Name of the shield in the database.",
217 default="TRY_2026",
218 choices=["TRY_2026"],
219)
220ap.add_argument(
221 "--AddMuonShield",
222 help="Whether or not to add the muon shield. Default set to False.",
223 default=False,
224 action=argparse.BooleanOptionalAction,
225)
226ap.add_argument(
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.",
231 default=True,
232 action=argparse.BooleanOptionalAction,
233)
234ap.add_argument(
235 "--AddHadronAbsorberOnly",
236 help="Whether to only add the hadron absorber part of the muon shield. Default set to True.",
237 default=True,
238 action=argparse.BooleanOptionalAction,
239)
240
241ap.add_argument(
242 "--z-offset", type=float, dest="z_offset", default=-84.0, help="z-offset for the FixedTargetGenerator [mm]"
243)
244ap.add_argument(
245 "--x-offset", type=float, dest="x_offset", default=0.0, help="x-offset for the FixedTargetGenerator [mm]"
246)
247ap.add_argument(
248 "--y-offset", type=float, dest="y_offset", default=0.0, help="y-offset for the FixedTargetGenerator [mm]"
249)
250ap.add_argument(
251 "--beam-smear", type=float, dest="beam_smear", default=16.0, help="beam smearing for the FixedTargetGenerator [mm]"
252)
253ap.add_argument(
254 "--beam-paint",
255 type=float,
256 dest="beam_paint",
257 default=50.0,
258 help="beam painting radius for the FixedTargetGenerator [mm]",
259)
260ap.add_argument(
261 "--TARGET_YAML",
262 dest="TARGET_YAML",
263 help="File for target configuration",
264 default=os.path.expandvars("$FAIRSHIP/geometry/target_config.yaml"),
265)
266
267ap.add_argument(
268 "--AddCylindricalSensPlane",
269 action="store_true",
270 help="Whether or not to add cylindrical sensitive plane around the target. False by default.",
271)
272ap.add_argument(
273 "--AddPostTargetSensPlane",
274 action="store_true",
275 help="Whether or not to add sensitive plane after the target. False by default.",
276)
277
278args = ap.parse_args()
279if args.debug:
280 logger.setLevel(logging.DEBUG)
281
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")
294
295if args.max_split_buffer < args.kaon_pion_splits:
296 ap.error(
297 "--max-split-buffer must be >= --kaon-pion-splits: the clones buffered when the parent "
298 "decays have to fit under the cap"
299 )
300if args.multiple_kpi_splits:
301 # A per-step split has to reserve room for its own clones and for the endpoint clones of the
302 # same track under both caps (see exitHadronAbsorber::ProcessHits); if even the first one
303 # cannot, per-step splitting would silently never happen.
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:
309 ap.error(
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"
313 )
314
315if args.G4only:
316 args.charm = False
317 args.beauty = False
318 withEvtGen = False
319 args.pythiaDecay = False
320elif args.pythiaDecay:
321 withEvtGen = False
322 logger.info("use Pythia8 as primary decayer")
323else:
324 withEvtGen = True
325 logger.info("use EvtGen as primary decayer")
326# withEvtGen = args.withEvtGen
327if args.charm and args.beauty:
328 logger.warning("charm and beauty decays are set! Beauty gets priority")
329 args.charm = False
330charmInputFile = args.charmInputFile
331
332if args.work_dir is None:
333 if args.charm:
334 tag = "charm"
335 elif args.beauty:
336 tag = "beauty"
337 elif args.pythia8_tune != "default":
338 tag = args.pythia8_tune
339 else:
340 tag = None
341 args.work_dir = get_work_dir(args.runnr, tag)
342
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)
347 if args.force:
348 logger.warning("...cleaning")
349 for root, dirs, files in os.walk(args.work_dir):
350 for f in files:
351 os.unlink(os.path.join(root, f))
352 for d in dirs:
353 shutil.rmtree(os.path.join(root, d))
354 else:
355 logger.warning("...use '-f' option to overwrite it")
356else:
357 os.makedirs(args.work_dir)
358
359os.chdir(args.work_dir)
360# -------------------------------------------------------------------
361# PYTHIA8 requires Random:seed to be in range [0, 900000000]
362# When seed=0, ROOT generates a seed from system time which can exceed this limit
363seed = args.seed
364if seed == 0:
365 ROOT.gRandom.SetSeed(0) # Generate time-based seed
366 seed = ROOT.gRandom.GetSeed()
367# Clamp to PYTHIA8's maximum allowed seed value
368if seed > 900000000:
369 seed = seed % 900000000
370ROOT.gRandom.SetSeed(seed)
371shipRoot_conf.configure() # load basic libraries, prepare atexit for python
372if args.reproducible and not args.debug:
373 ROOT.gErrorIgnoreLevel = ROOT.kWarning
374ship_geo_kwargs = {
375 "Yheight": dy,
376 "DecayVolumeMedium": args.DecayVolumeMedium,
377 "shieldName": args.shieldName,
378 "TARGET_YAML": args.TARGET_YAML,
379}
380ship_geo = geometry_config.create_config(**ship_geo_kwargs)
381
382txt = "pythia8_Geant4_"
383if withEvtGen:
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"
387
388# -----Timer--------------------------------------------------------
389timer = ROOT.TStopwatch()
390timer.Start()
391
392# -----Create simulation run----------------------------------------
393run = ROOT.FairRunSim()
394run.SetName(mcEngine) # Transport engine
395if hasattr(run, "SetRunId"):
396 run.SetRunId(args.runnr)
397sink = ROOT.FairRootFileSink(outFile)
398run.SetSink(sink)
399ROOT.SetOwnership(sink, False) # C++ FairRun takes ownership
400if args.boostFactor > 1:
401 # Turn off UseGeneralProcess to access GammaToMuons directly when cross-sections need to be changed
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") # user configuration file default g4Config.C
406rtdb = run.GetRuntimeDb()
407
408# -----Materials----------------------------------------------
409run.SetMaterials("media.geo")
410# -----Create geometry----------------------------------------------
411cave = ROOT.ShipCave("CAVE")
412cave.SetGeometryFileName("caveWithAir.geo")
413
414run.AddModule(cave)
415ROOT.SetOwnership(cave, False) # C++ FairRunSim takes ownership
416
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,
423)
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,
429)
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) # C++ FairRunSim takes ownership
437
438
439if args.AddPostTargetSensPlane:
440 sensPlanePostT = ROOT.exitHadronAbsorber()
441 sensPlanePostT.SetEnergyCut(args.ecut * u.GeV)
442 sensPlanePostT.SetVetoPointName("PlanePostT")
443 # by default, if the z-position is not set, the positioning is behind the hadron abosorber and the tracks are stopped when they hit the sens plane
444 # if the z-position is set and has a reasonable value (below 1E8), then the tracks are not stopped and continue to the last plane after the hadron absorber
445 sensPlanePostT.SetZposition(158.64 * u.cm + 300 * u.mm + 6.2 * u.cm)
446 # NOMINAL target length + vessel shift + shielding length
447 sensPlanePostT.SetUseCaveCoordinates() # position set from the cave to avoid extrusions since the plane is larger than the target vacuum box
448
449 if args.storeOnlyMuons:
450 sensPlanePostT.SetOnlyMuons()
451 if args.skipNeutrinos:
452 sensPlanePostT.SkipNeutrinos()
453 if args.FourDP:
454 sensPlanePostT.SetOpt4DP()
455 run.AddModule(sensPlanePostT)
456 ROOT.SetOwnership(sensPlanePostT, False) # C++ FairRunSim takes ownership
457
458
459if args.AddMuonShield or args.AddHadronAbsorberOnly:
460 params = list(ship_geo.muShield.params)
461 n_magnets = ship_geo.muShield.nMagnets
462 if args.AddHadronAbsorberOnly:
463 # keep only the first magnet, the magnetised hadron absorber
464 params = params[: ROOT.ShipMuonShield.nParams]
465 n_magnets = 1
466
467 MuonShield = ROOT.ShipMuonShield(
468 in_params=params,
469 n_magnets=n_magnets,
470 z=ship_geo.muShield.z,
471 )
472 # MuonShield.SetSupports(False) # otherwise overlap with sensitive Plane
473 run.AddModule(MuonShield) # needs to be added because of magn hadron shield.
474 ROOT.SetOwnership(MuonShield, False) # C++ FairRunSim takes ownership
475
476
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")
486
487sensPlaneT = None
488if args.AddCylindricalSensPlane: # add additional sensitive plane around target
489 sensPlaneT = ROOT.exitHadronAbsorber()
490 sensPlaneT.SetEnergyCut(args.ecut * u.GeV)
491 sensPlaneT.SetVetoPointName("PlaneT")
492 sensPlaneT.SetCylindricalPlane()
493 # by default, if the z-position is not set, the positioning is behind the hadron abosorber and the tracks are stopped when they hit the sens plane
494 # if the z-position is set and has a reasonable value (below 1E8), then the tracks are not stopped and continue to the last plane after the hadron absorber
495 sensPlaneT.SetZposition(ship_geo.target.length)
496
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()
505if args.FourDP: # in case a ntuple should be filled with pi0,etas,omega
506 sensPlaneHA.SetOpt4DP()
507 if sensPlaneT is not None:
508 sensPlaneT.SetOpt4DP()
509
510# Register every other exitHadronAbsorber plane before sensPlaneHA, which owns the kaon/pion split buffer:
511# FairMCApplication calls PreTrack() in registration order, and sensPlaneHA hands its buffered clones only
512# to a track that no earlier plane has stopped. A plane registered after it could stop the carrier and lose
513# the clones. Registering first also keeps the plane's volume its own: the first module to register a volume
514# owns it, and sensPlaneHA registers everything below the target for per-step splitting.
515if sensPlaneT is not None:
516 run.AddModule(sensPlaneT)
517 ROOT.SetOwnership(sensPlaneT, False) # C++ FairRunSim takes ownership
518
519run.AddModule(sensPlaneHA)
520ROOT.SetOwnership(sensPlaneHA, False) # C++ FairRunSim takes ownership
521
522# -----Create PrimaryGenerator--------------------------------------
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)
530# Use geometry constants instead of fragile TGeo navigation
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)
536if args.G4only:
537 P8gen.SetG4only()
538P8gen.SetPythiaTune(args.pythia8_tune)
539if args.JpsiMainly:
540 P8gen.SetJpsiMainly()
541if args.tauOnly:
542 P8gen.SetTauOnly()
543if withEvtGen:
544 P8gen.WithEvtGen()
545if args.boostDiMuon > 1:
546 P8gen.SetBoost(
547 args.boostDiMuon
548 ) # will increase BR for rare eta,omega,rho ... mesons decaying to 2 muons in Pythia8
549 # and later copied to Geant4
550P8gen.SetSeed(seed)
551# for charm/beauty
552# print ' for experts: p pot= number of protons on target per spill to normalize on'
553# print ' : c chicc= ccbar over mbias cross section'
554if args.charm or args.beauty:
555 check_run_type_override(args.beauty, args.chicc, args.chibb)
556 # cascade files written by makeCascadePythia8.py carry the cross section they were made with;
557 # the flavour is taken from the file, as FixedTargetGenerator does
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")
561 _ntuple.GetEntry(0)
562 input_is_beauty = file_is_beauty(_ntuple.M)
563 del _ntuple # owned by the file, which is closed below
564 check_input_flavour(args.beauty, input_is_beauty)
565 if sigma_QQ:
566 flavour = "beauty" if input_is_beauty else "charm"
567 print(
568 f"Input file {flavour} cross section per nucleon: {1e3 * sigma_QQ:.3g} ub, used to scale chi{flavour[0] * 2}"
569 )
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) # C++ FairPrimaryGenerator takes ownership
579#
580run.SetGenerator(primGen)
581ROOT.SetOwnership(primGen, False) # C++ FairRunSim takes ownership
582
583# -----Initialize simulation run------------------------------------
584run.Init()
585
586if (args.AddMuonShield or args.AddHadronAbsorberOnly) and args.AddMuonShieldField:
587 # The muon shield field, including the hadron absorber, comes from the field map
588 import geomGeant4
589
590 fieldMaker = geomGeant4.addVMCFields(SimpleNamespace(muShield=ship_geo.muShield, shieldName=ship_geo.shieldName))
591
592gMC = ROOT.TVirtualMC.GetMC()
593fStack = gMC.GetStack()
594# With --store-all-tracks, tracks without hits are kept as well, e.g. all split clones and the kaons and
595# pions that decay without leaving a hit.
596fStack.SetMinPoints(0 if args.store_all_tracks else 1)
597fStack.SetEnergyCut(-1.0)
598if args.kaon_pion_splits > 0:
599 fStack.SetSplitting()
600
601if args.kaon_pion_lifetime_factor != 1.0:
602 # G4Decay and the per-step splitting in exitHadronAbsorber both read the lifetime from the Geant4
603 # particle definition, so scaling it there after initialisation changes both consistently.
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});"
609 )
610 for pdg in (321, 211):
611 logger.warning(
612 "Lifetime of %d scaled by %g to %.6g ns: validation only, the output is not physical",
613 pdg,
614 args.kaon_pion_lifetime_factor,
615 gMC.ParticleLifeTime(pdg),
616 )
617#
618import AddDiMuonDecayChannelsToG4
619
621
622# boost gamma2muon conversion
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)
632
633# -----Start run----------------------------------------------------
634run.Run(args.nev)
635
636# -----Finish-------------------------------------------------------
637timer.Stop()
638rtime = timer.RealTime()
639ctime = timer.CpuTime()
640print(" ")
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")
645# ---post processing--- remove empty events --- save histograms
646tmpFile = outFile + "tmp"
647# not simply the first open file: for charm and beauty the generator keeps the input file open
648fin = ROOT.gROOT.GetListOfFiles().FindObject(outFile)
649if not fin:
650 fin = ROOT.TFile.Open(outFile)
651fHeader = fin.Get("FileHeader")
652if fHeader:
653 fHeader.SetRunId(args.runnr)
654else:
655 print("WARNING: FileHeader not found in simulation output; skipped FileHeader RunID update")
656if args.charm or args.beauty:
657 # normalization for charm
658 poteq = P8gen.GetPotForCharm()
659 info = "POT equivalent = %7.3G" % (poteq)
660else:
661 info = f"POT = {args.nev}"
662
663conditions = " with ecut=" + str(args.ecut)
664if args.pythia8_tune != "default":
665 conditions += " " + args.pythia8_tune
666if args.JpsiMainly:
667 conditions += " J"
668if args.tauOnly:
669 conditions += " T"
670if withEvtGen:
671 conditions += " V"
672if args.boostDiMuon > 1:
673 conditions += " diMu" + str(args.boostDiMuon)
674if args.boostFactor > 1:
675 conditions += " X" + str(args.boostFactor)
676
677info += conditions
678if fHeader:
679 fHeader.SetTitle(info)
680 print(f"Data generated {fHeader.GetTitle()}")
681else:
682 print(f"Data generated {info}")
683
684nt = fin.Get("4DP")
685if nt:
686 nt = fin["4DP"]
687 tf = ROOT.TFile("FourDP.root", "recreate")
688 tnt = nt.CloneTree(0)
689 for i in range(nt.GetEntries()):
690 rc = nt.GetEvent(i)
691 rc = tnt.Fill(nt.id, nt.px, nt.py, nt.pz, nt.x, nt.y, nt.z)
692 tnt.Write()
693 tf.Close()
694
695t = fin["cbmsim"]
696fout = ROOT.TFile(tmpFile, "recreate")
697sTree = t.CloneTree(0)
698nEvents = 0
699for n in range(t.GetEntries()):
700 rc = t.GetEvent(n)
701 if (
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)
706 ):
707 rc = sTree.Fill()
708 nEvents += 1
709fout.cd()
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:
714 xcopy = x.Clone()
715 rc = xcopy.Write()
716sTree.AutoSave()
717if fHeader:
718 ff = fHeader.Clone(fout.GetName())
719 fout.cd()
720 ff.Write("FileHeader", ROOT.TObject.kSingleKey)
721sTree.Write()
722fout.Close()
723
724rc1 = os.system("rm " + outFile)
725rc2 = os.system("mv " + tmpFile + " " + outFile)
726print("removed out file, moved tmpFile to out file", rc1, rc2)
727
728if rc1 == 0 and rc2 == 0:
729 print("INFO: Adding file summary")
730 fsr = vars(args)
731 with ROOT.TFile.Open(outFile, "UPDATE") as _of:
732 _of.WriteObject(ROOT.TString(json.dumps(fsr)), "FileSummary")
733else:
734 print("WARNING: tempFile mv or rm not successful. No attempt at FileSummary writing")
735
736fin.SetWritable(False) # bpyass flush error
737
738print(f"Number of events produced with activity after hadron absorber: {nEvents}")
739
740if checkOverlap:
741 sGeo = ROOT.gGeoManager
742 sGeo.CheckOverlaps()
743 sGeo.PrintOverlaps()
744 run.CreateGeometryFile("%s/geofile_full.root" % (outputDir))
745 import saveBasicParameters
746
747 saveBasicParameters.execute("%s/geofile_full.root" % (outputDir), ship_geo)
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)