| 1 |
""" |
| 2 |
This example shows how to run several, independent simulations in standalone mode using multiple processes to run the |
| 3 |
simulations in parallel. |
| 4 |
Given that this example only involves a single neuron, an alternative – and arguably more elegant – solution |
| 5 |
would be to run the simulations in a single `NeuronGroup`, where each neuron receives input with a different rate. |
| 6 |
|
| 7 |
The example is a standalone equivalent of the one presented in :doc:`/tutorials/3-intro-to-brian-simulations`. |
| 8 |
|
| 9 |
Note that Python's `multiprocessing` module cannot deal with user-defined functions (including `TimedArray`) and other |
| 10 |
complex code structures. If you run into `PicklingError` or `AttributeError` exceptions, you might |
| 11 |
have to use the `pathos` (https://pypi.org/project/pathos) package instead, which can handle more complex |
| 12 |
code structures. |
| 13 |
""" |
| 14 |
import numpy as np |
| 15 |
import matplotlib.pyplot as plt |
| 16 |
import brian2 as b2 |
| 17 |
from time import time |
| 18 |
|
| 19 |
b2.set_device('cpp_standalone', build_on_run=False) |
| 20 |
|
| 21 |
class SimWrapper: |
| 22 |
def __init__(self): |
| 23 |
self.net = b2.Network() |
| 24 |
P = b2.PoissonGroup(num_inputs, rates=input_rate) |
| 25 |
eqs = """ |
| 26 |
dv/dt = -v/tau : 1 |
| 27 |
tau : second (constant) |
| 28 |
""" |
| 29 |
G = b2.NeuronGroup(1, eqs, threshold='v>1', reset='v=0', method='euler', name='neuron') |
| 30 |
S = b2.Synapses(P, G, on_pre='v += weight') |
| 31 |
S.connect() |
| 32 |
M = b2.SpikeMonitor(G, name='spike_monitor') |
| 33 |
self.net.add([P, G, S, M]) |
| 34 |
|
| 35 |
self.net.run(1000 * b2.ms) |
| 36 |
|
| 37 |
self.device = b2.get_device() |
| 38 |
self.device.build(run=False, directory=None) # compile the code, but don't run it yet |
| 39 |
|
| 40 |
def do_run(self, tau_i): |
| 41 |
# Workaround to set the device globally in this context |
| 42 |
from brian2.devices import device_module |
| 43 |
device_module.active_device = self.device |
| 44 |
|
| 45 |
result_dir = f'result_{tau_i}' |
| 46 |
self.device.run(run_args={self.net['neuron'].tau: tau_i}, |
| 47 |
results_directory=result_dir) |
| 48 |
return self.net["spike_monitor"].num_spikes/ b2.second |
| 49 |
|
| 50 |
|
| 51 |
if __name__ == "__main__": |
| 52 |
start_time = time() |
| 53 |
num_inputs = 100 |
| 54 |
input_rate = 10 * b2.Hz |
| 55 |
weight = 0.1 |
| 56 |
|
| 57 |
npoints = 15 |
| 58 |
tau_range = np.linspace(1, 15, npoints) * b2.ms |
| 59 |
|
| 60 |
sim = SimWrapper() |
| 61 |
|
| 62 |
from multiprocessing import Pool |
| 63 |
with Pool(npoints) as pool: |
| 64 |
output_rates = pool.map(sim.do_run, tau_range) |
| 65 |
|
| 66 |
print(f"Done in {time() - start_time}") |
| 67 |
|
| 68 |
plt.plot(tau_range/b2.ms, output_rates) |
| 69 |
plt.xlabel(r"$\tau$ (ms)") |
| 70 |
plt.ylabel("Firing rate (sp/s)") |
| 71 |
plt.show() |