I am looking for a toy example to use multiprocssing
with standalone C++ mode.
I found some questions in the group, but I could not found an example the run without error.
I pass an array of tau
values to the run_sim
function and used Pool.map
for multiprocessing.
This is my try:
import os
import multiprocessing
from brian2 import *
set_device('cpp_standalone', build_on_run=False, directory=None)
def run_sim(tau):
pid = os.getpid()
print(f'RUNNING {pid}')
G = NeuronGroup(1, 'dv/dt = -v/tau : 1', method='euler')
G.v = 1
mon = StateMonitor(G, 'v', record=0)
net = Network()
net.add(G, mon)
net.run(100 * ms)
device.build(
directory='standalone{}'.format(
os.getpid()),
# directory=None,
compile=True, run=True)
device.reinit()
print(f'FINISHED {pid}')
return (mon.t/ms, mon.v[0])
if __name__ == "__main__":
num_proc = 4
tau_values = np.arange(10)*ms + 5*ms
with multiprocessing.Pool(num_proc) as p:
results = p.map(run_sim, tau_values)
for tau_value, (t, v) in zip(tau_values, results):
plt.plot(t, v, label=str(tau_value))
plt.legend()
plt.show()
error:
Traceback (most recent call last):
File "/usr/lib/python3.6/multiprocessing/pool.py", line 119, in worker
result = (True, func(*args, **kwds))
File "/usr/lib/python3.6/multiprocessing/pool.py", line 44, in mapstar
return list(map(*args))
File "01_example.py", line 24, in run_sim
compile=True, run=True)
File "/home/abolfazl/.local/lib/python3.6/site-packages/brian2/devices/cpp_standalone/device.py", line 1105, in build
raise RuntimeError('The network has already been built and run '
RuntimeError: The network has already been built and run before. To build several simulations in the same script, call "device.reinit()" and "device.activate()". Note that you will have to set build options (e.g. the directory) and defaultclock.dt again.
"""
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "01_example.py", line 36, in <module>
results = p.map(run_sim, tau_values)
File "/usr/lib/python3.6/multiprocessing/pool.py", line 266, in map
return self._map_async(func, iterable, mapstar, chunksize).get()
File "/usr/lib/python3.6/multiprocessing/pool.py", line 644, in get
raise self._value
RuntimeError: The network has already been built and run before. To build several simulations in the same script, call "device.reinit()" and "device.activate()". Note that you will have to set build options (e.g. the directory) and defaultclock.dt again.
Thank you in advance for any guide.