This repository has been archived by the owner on Sep 1, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
slave.py
executable file
·236 lines (215 loc) · 7.25 KB
/
slave.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
#!/usr/bin/env python2
import os
from time import sleep
import numpy as np
import copy
import json
import argparse
import shutil
import subprocess
import filelock
import ROOT as r
import config
import shipunit as u
import geomGeant4
from ShipGeoConfig import ConfigRegistry
import shipDet_conf
from analyse import analyse
from disney_common import create_id, ParseParams
from common import generate_geo
def generate(
inputFile,
paramFile,
outFile,
seed=1,
nEvents=None
):
"""Generate muon background and transport it through the geometry.
Parameters
----------
inputFile : str
File with muon ntuple
paramFile : str
File with the muon shield parameters
outFile : str
File in which `cbmsim` tree is saved
seed : int
Determines the seed passed on to the MuonBackGenerator instance
nEvents : int
Number of events to be read from inputFile
If falsy, generate will run over the entire file.
"""
firstEvent = 0
dy = 10.
vessel_design = 5
shield_design = 8
mcEngine = 'TGeant4'
sameSeed = seed
theSeed = 1
phiRandom = False # only relevant for muon background generator
followMuon = True # only transport muons for a fast muon only background
print 'FairShip setup to produce', nEvents, 'events'
r.gRandom.SetSeed(theSeed)
ship_geo = ConfigRegistry.loadpy(
'$FAIRSHIP/geometry/geometry_config.py',
Yheight=dy,
tankDesign=vessel_design,
muShieldDesign=shield_design,
muShieldGeo=paramFile)
run = r.FairRunSim()
run.SetName(mcEngine) # Transport engine
run.SetOutputFile(outFile) # Output file
# user configuration file default g4Config.C
run.SetUserConfig('g4Config.C')
modules = shipDet_conf.configure(run, ship_geo)
primGen = r.FairPrimaryGenerator()
primGen.SetTarget(ship_geo.target.z0 + 50 * u.m, 0.)
MuonBackgen = r.MuonBackGenerator()
MuonBackgen.Init(inputFile, firstEvent, phiRandom)
MuonBackgen.SetSmearBeam(3 * u.cm) # beam size mimicking spiral
if sameSeed:
MuonBackgen.SetSameSeed(sameSeed)
primGen.AddGenerator(MuonBackgen)
if not nEvents:
nEvents = MuonBackgen.GetNevents()
else:
nEvents = min(nEvents, MuonBackgen.GetNevents())
print 'Process ', nEvents, ' from input file, with Phi random=', phiRandom
if followMuon:
modules['Veto'].SetFastMuon()
run.SetGenerator(primGen)
run.SetStoreTraj(r.kFALSE)
run.Init()
print 'Initialised run.'
geomGeant4.setMagnetField()
print 'Start run of {} events.'.format(nEvents)
run.Run(nEvents)
print 'Finished simulation of {} events.'.format(nEvents)
def main():
tmpl = copy.deepcopy(config.RESULTS_TEMPLATE)
tmpl['args'] = vars(args)
with open(args.results, 'w') as f:
json.dump(tmpl, f)
tmpl['status'] = 'Parsing parameters...'
try:
params = ParseParams(args.params.decode('base64'))
except Exception as e:
tmpl['error'] = e.__repr__()
with open(args.results, 'w') as f:
json.dump(tmpl, f)
raise
tmpl['status'] = 'Parsed parameters.'
paramFile = '/shared/params_{}.root'.format(
create_id(params)
)
geoinfoFile = paramFile.replace('params', 'geoinfo')
heavy = '/shared/heavy_{}'.format(create_id(params))
lockfile = paramFile + '.lock'
if os.path.exists(geoinfoFile):
geolockfile = geoinfoFile + '.lock'
lock = filelock.FileLock(geolockfile)
if not lock.is_locked:
with lock:
with open(geoinfoFile, 'r') as f:
length, weight = map(float, f.read().strip().split(','))
tmpl['weight'] = weight
tmpl['length'] = length
while not os.path.exists(paramFile) and not os.path.exists(heavy):
lock = filelock.FileLock(lockfile)
if not lock.is_locked:
with lock:
tmpl['status'] = 'Aquired lock.'
tmp_paramFile = generate_geo(
paramFile.replace('.', '.tmp.'),
params
)
subprocess.call(
[
'python2',
'/code/get_geo.py',
'-g', tmp_paramFile,
'-o', geoinfoFile
])
shutil.move(
'/shield/geofiles/' + os.path.basename(tmp_paramFile),
paramFile.replace(
'shared', 'output'
).replace(
'params', 'geo'
)
)
with open(geoinfoFile, 'r') as f:
length, weight = map(float, f.read().strip().split(','))
tmpl['weight'] = weight
tmpl['length'] = length
if weight < 3e6:
shutil.move(tmp_paramFile, paramFile)
else:
open(heavy, 'a').close()
with open(args.results, 'w') as f:
json.dump(tmpl, f)
tmpl['status'] = 'Created geometry.'
else:
sleep(60)
if os.path.exists(heavy):
tmpl['status'] = 'Too heavy.'
tmpl['error'] = None
with open(args.results, 'w') as f:
json.dump(tmpl, f)
return
outFile = "/output/ship.conical.MuonBack-TGeant4.root"
try:
try:
tmpl['status'] = 'Simulating...'
generate(
inputFile=args.input,
paramFile=paramFile,
outFile=outFile,
seed=args.seed,
nEvents=args.nEvents
)
except Exception as e:
raise RuntimeError(
"Simulation failed with exception: %s",
e
)
try:
tmpl['status'] = 'Analysing...'
chain = r.TChain('cbmsim')
chain.Add(outFile)
xs = analyse(chain, args.hists)
np.save(args.xs_path, np.array(xs))
tmpl['muons'] = len(xs)
tmpl['muons_w'] = sum(xs)
except Exception as e:
raise RuntimeError(
"Analysis failed with exception: %s",
e
)
tmpl['error'] = None
tmpl['status'] = 'Done.'
except RuntimeError, e:
tmpl['error'] = e.__repr__()
finally:
with open(args.results, 'w') as f:
json.dump(tmpl, f)
if os.path.exists(outFile):
os.remove(outFile)
if __name__ == '__main__':
r.gErrorIgnoreLevel = r.kWarning
r.gSystem.Load('libpythia8')
parser = argparse.ArgumentParser()
parser.add_argument(
'-f',
'--input',
default='root://eospublic.cern.ch/'
'/eos/experiment/ship/data/Mbias/'
'pythia8_Geant4-withCharm_onlyMuons_4magTarget.root')
parser.add_argument('--results', default='results.json')
parser.add_argument('--hists', default='hists.root')
parser.add_argument('--params', required=True)
parser.add_argument('--seed', type=int, default=1)
parser.add_argument('--xs_path', default='xs.npz')
parser.add_argument('-n', '--nEvents', type=int)
args = parser.parse_args()
main()