Analysis Software
Documentation for sPHENIX simulation software
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
geant4_parallel.py
Go to the documentation of this file. Or view the newest version in sPHENIX GitHub for file geant4_parallel.py
1 #!/usr/bin/env python3
2 from pathlib import Path
3 from multiprocessing import Pool
4 from functools import partial
5 
6 # This script runs a Geant4 simulation in parallel by passing chunks of events to subprocesses.
7 # This is a workaround to achieve parallel processing even though Geant4 is not thread-save
8 # and thus the internal parallelism of the ACTS examples framework cannot be used.
9 #
10 # Note that:
11 # ==========
12 #
13 # * This should give equivalent results to a sequential run if the RNG is initialized with
14 # the same seed in all runs
15 #
16 # * So far this works only for csv outputs, since they write the results in one file per event
17 # (the naming of the csv-files should be equivalent to a sequential run)
18 #
19 # * In principle it is not difficult to extend this for ROOT files as well. One would need to
20 # write the root-files into separate directory per chunk, and then use ROOT's hadd to combine
21 # the output files.
22 #
23 
24 
25 def runGeant4EventRange(beginEvent, endEvent, outputDir):
26  import acts
27  import acts.examples
28  from acts.examples.simulation import addParticleGun, addGeant4, EtaConfig
29  from acts.examples.odd import getOpenDataDetector
30  from common import getOpenDataDetectorDirectory
31 
32  u = acts.UnitConstants
33 
34  detector, trackingGeometry, decorators = getOpenDataDetector(
36  )
37 
38  field = acts.ConstantBField(acts.Vector3(0, 0, 2 * u.T))
39  rnd = acts.examples.RandomNumbers(seed=42)
40 
42  events=endEvent - beginEvent, skip=beginEvent, numThreads=1
43  )
44 
45  outputDir = Path(outputDir)
47  s,
48  EtaConfig(-2.0, 2.0),
49  rnd=rnd,
50  outputDirCsv=outputDir / "csv",
51  outputDirRoot=None,
52  )
53  addGeant4(
54  s,
55  detector,
56  trackingGeometry,
57  field,
58  outputDirCsv=outputDir / "csv",
59  outputDirRoot=None,
60  rnd=rnd,
61  )
62 
63  s.run()
64  del s
65 
66 
67 if "__main__" == __name__:
68  n_events = 100
69  n_jobs = 8
70 
71  chunksize = n_events // (n_jobs - 1)
72  begins = range(0, n_events, chunksize)
73  ends = [min(b + chunksize, n_events) for b in begins]
74 
75  outputDir = Path.cwd()
76 
77  with Pool(n_jobs) as p:
78  p.starmap(partial(runGeant4EventRange, outputDir=outputDir), zip(begins, ends))