Debian Codegraph @

examples/multiprocessing/01_using_cython.py

raw
1 """
2 Parallel processes using Cython
3
4 This example use multiprocessing to run several simulations in parallel.
5 The code is using the default runtime mode (and Cython compilation, if
6 possible).
7
8 The ``numb_proc`` variable set the number of processes. ``run_sim`` is just a
9 toy example that creates a single neuron and connects a `StateMonitor` to
10 record the voltage.
11
12 For more details see the `github issue 1154 <https://github.com/brian-team/brian2/issues/1154#issuecomment-582994117>`_:
13
14 Note that Python's `multiprocessing` module cannot deal with user-defined functions (including `TimedArray`) and other
15 complex code structures. If you run into `PicklingError` or `AttributeError` exceptions, you might
16 have to use the `pathos` (https://pypi.org/project/pathos) package instead, which can handle more complex
17 code structures.
18 """
19 import os
20 import multiprocessing
21
22 from brian2 import *
23
24
25 def run_sim(tau):
26 pid = os.getpid()
27 print(f'RUNNING {pid}')
28 G = NeuronGroup(1, 'dv/dt = -v/tau : 1', method='exact')
29 G.v = 1
30 mon = StateMonitor(G, 'v', record=0)
31 run(100*ms)
32 print(f'FINISHED {pid}')
33 return mon.t/ms, mon.v[0]
34
35
36 if __name__ == "__main__":
37 num_proc = 4
38
39 tau_values = np.arange(10)*ms + 5*ms
40 with multiprocessing.Pool(num_proc) as p:
41 results = p.map(run_sim, tau_values)
42
43 for tau_value, (t, v) in zip(tau_values, results):
44 plt.plot(t, v, label=str(tau_value))
45 plt.legend()
46 plt.show()