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
|
#!/usr/bin/env python
import sys
import optparse
import time
import os
import multiprocessing
import detectors
import optics
import gpu
import g4gen
from fileio import root
import numpy as np
import math
import ROOT
def pick_seed():
'''Returns a seed for a random number generator selected using
a mixture of the current time and the current process ID.'''
return int(time.time()) ^ (os.getpid() << 16)
def info(type, value, tb):
if hasattr(sys, 'ps1') or not sys.stderr.isatty():
# we are in interactive mode or we don't have a tty-like
# device, so we call the default hook
sys.__excepthook__(type, value, tb)
else:
import traceback, pdb
# we are NOT in interactive mode, print the exception...
traceback.print_exception(type, value, tb)
print
# ...then start the debugger in post-mortem mode.
pdb.pm()
class GeneratorProcess(multiprocessing.Process):
def __init__(self, particle, energy, position, direction, nevents, material,
queue, seed=None):
multiprocessing.Process.__init__(self)
self.particle = particle
self.energy = energy
self.position = position
self.direction = direction
self.nevents = nevents
self.material = material
self.seed = seed
self.queue = queue
self.daemon = True
def run(self):
print >>sys.stderr, 'Starting generator thread...'
generator = g4gen.G4Generator(self.material, seed=self.seed)
for i in xrange(self.nevents):
if self.particle == 'pi0':
photons = generator.generate_pi0(total_energy=self.energy,
position=self.position,
direction=self.direction)
else:
photons = generator.generate_photons(particle_name=self.particle,
total_energy=self.energy,
position=self.position,
direction=self.direction)
self.queue.put(photons)
def partition(num, partitions):
'''Generator that returns num//partitions, with the last item including the remainder.
Useful for partitioning a number into mostly equal parts while preserving the sum.
>>> list(partition(800, 3))
[266, 266, 268]
>>> sum(list(partition(800, 3)))
800
'''
step = num // partitions
for i in xrange(partitions):
if i < partitions - 1:
yield step
else:
yield step + (num % partitions)
# Allow profile decorator to exist, but do nothing if not running under kernprof
try:
profile = profile
except NameError:
profile = lambda x: x
@profile
def main():
parser = optparse.OptionParser('%prog')
parser.add_option('-b', type='int', dest='nbits', default=10)
parser.add_option('-j', type='int', dest='device', default=None)
parser.add_option('-n', type='int', dest='nblocks', default=64)
parser.add_option('-s', type='int', dest='seed', default=None,
help='Set random number generator seed')
parser.add_option('-g', type='int', dest='ngenerators', default=4,
help='Number of GEANT4 generator processes')
parser.add_option('--detector', type='string', dest='detector', default='microlbne')
parser.add_option('--nevents', type='int', dest='nevents', default=100)
parser.add_option('--particle', type='string', dest='particle', default='e-')
parser.add_option('--energy', type='float', dest='energy', default=100.0)
parser.add_option('--pos', type='string', dest='pos', default='(0,0,0)')
parser.add_option('--dir', type='string', dest='dir', default='(1,0,0)')
parser.add_option('--save-photon-start', action='store_true',
dest='save_photon_start', default=False,
help='Save initial photon vertices to disk')
parser.add_option('--save-photon-stop', action='store_true',
dest='save_photon_stop', default=False,
help='Save final photon vertices to disk')
options, args = parser.parse_args()
if len(args) != 1:
print 'Must specify output filename!'
sys.exit(1)
else:
output_filename = args[0]
if options.nevents <= 0:
print '--nevents must be greater than 0!'
sys.exit(1)
position = np.array(eval(options.pos), dtype=float)
direction = np.array(eval(options.dir), dtype=float)
detector = detectors.find(options.detector)
if options.seed is None:
options.seed = pick_seed()
print >>sys.stderr, 'RNG seed:', options.seed
print >>sys.stderr, 'Creating generator...'
detector_material = optics.water_wcsim
queue = multiprocessing.Queue()
generators = [GeneratorProcess(particle=options.particle,
energy=options.energy,
position=position,
direction=direction,
nevents=nevents,
material=detector_material,
seed=options.seed + seed_offset,
queue=queue)
for seed_offset, nevents in
enumerate(partition(options.nevents, options.ngenerators))]
print >>sys.stderr, 'WARNING: ASSUMING DETECTOR IS WCSIM WATER!!'
# Do this now so we can get ahead of the photon propagation
print >>sys.stderr, 'Starting GEANT4 generators...'
for generator in generators:
generator.start()
print >>sys.stderr, 'Creating BVH for detector "%s" with %d bits...' % (options.detector, options.nbits)
detector.build(bits=options.nbits)
print >>sys.stderr, 'Initializing GPU...'
gpu_worker = gpu.GPU(options.device)
print >>sys.stderr, 'Loading detector onto GPU...'
gpu_worker.load_geometry(detector)
print >>sys.stderr, 'Initializing random numbers generators...'
gpu_worker.setup_propagate(seed=options.seed)
gpu_worker.setup_daq(max(detector.pmtids))
# Create output file
writer = root.RootWriter(output_filename)
# Set generator info
writer.set_generated_particle(name=options.particle, position=position,
direction=direction, total_e=options.energy)
print >>sys.stderr, 'Starting simulation...'
start_sim = time.time()
nphotons = 0
for i in xrange(options.nevents):
photons = queue.get()
assert len(photons['pos']) > 0, 'GEANT4 generated event with no photons!'
nphotons += len(photons['pos'])
gpu_worker.load_photons(pos=photons['pos'], dir=photons['dir'], pol=photons['pol'],
t0=photons['t0'], wavelength=photons['wavelength'])
gpu_worker.propagate()
gpu_worker.run_daq()
hits = gpu_worker.get_hits()
if options.save_photon_start:
photon_start = photons
else:
photon_start = None
if options.save_photon_stop:
photon_stop = gpu_worker.get_photons()
else:
photon_stop = None
if 'subtracks' in photons:
subtracks = photons['subtracks']
else:
subtracks = None
writer.write_event(i, hits, photon_start=photon_start, photon_stop=photon_stop,
subtracks=subtracks)
if i % 10 == 0:
print >>sys.stderr, "\rEvent:", i,
end_sim = time.time()
print >>sys.stderr, "\rEvent:", options.nevents - 1
writer.close()
print >>sys.stderr, 'Done. %1.1f events/sec, %1.0f photons/sec.' % (options.nevents/(end_sim - start_sim), nphotons/(end_sim - start_sim))
if __name__ == '__main__':
sys.excepthook = info
main()
|