Debian Codegraph @

examples/multiprocessing/03_standalone_joblib.py

raw
1 """
2 This example use C++ standalone mode for the simulation and the
3 `joblib library <https://joblib.readthedocs.io>`_
4 to parallelize the code. See the previous example (``02_using_standalone.py``)
5 for more explanations.
6 """
7 from joblib import Parallel, delayed
8 from time import time as wall_time
9 from brian2 import *
10 import os
11
12
13 def run_sim(tau):
14 pid = os.getpid()
15 directory = f"standalone{pid}"
16 set_device('cpp_standalone', directory=directory)
17 print(f'RUNNING {pid}')
18
19 G = NeuronGroup(1, 'dv/dt = -v/tau : 1', method='euler')
20 G.v = 1
21
22 mon = StateMonitor(G, 'v', record=0)
23 net = Network()
24 net.add(G, mon)
25 net.run(100 * ms)
26 res = (mon.t/ms, mon.v[0])
27
28 device.reinit()
29
30 print(f'FINISHED {pid}')
31 return res
32
33
34 if __name__ == "__main__":
35 start_time = wall_time()
36
37 n_jobs = 4
38 tau_values = np.arange(10)*ms + 5*ms
39
40 results = Parallel(n_jobs=n_jobs)(map(delayed(run_sim), tau_values))
41
42 print(f"Done in {wall_time() - start_time:10.3f}")
43
44 for tau_value, (t, v) in zip(tau_values, results):
45 plt.plot(t, v, label=str(tau_value))
46 plt.legend()
47 plt.show()