Skip to content

Instantly share code, notes, and snippets.

@mstimberg
Created November 10, 2015 16:59
Show Gist options
  • Save mstimberg/061cab0e8e470fbea5fd to your computer and use it in GitHub Desktop.
Save mstimberg/061cab0e8e470fbea5fd to your computer and use it in GitHub Desktop.
Stop a Brian2 simulation if the network firing rate is too high
from brian2 import *
from brian2.devices.cpp_standalone import CPPStandaloneCodeObject
# The following code works only for numpy runtime or C++ standalone
set_device('cpp_standalone')
prefs.codegen.cpp.headers += ['"run.h"'] # This is necessary to use brian_end()
#prefs.codegen.target = 'numpy'
# Simple model, the neurons will increasingly spike
G = NeuronGroup(10000, 'dv/dt = t/second**2 : 1',
threshold='v>1', reset='v=0')
G.v = 'rand()'
# Only for visualization, not used for the stop criterion
monitor = PopulationRateMonitor(G)
######## Code for stopping the simulation if there are too many spikes in one time step
@implementation(CPPStandaloneCodeObject, '''
double stop_if_too_high(double rate) {
if (rate > 30) {
brian_end(); // save all data to disk
std::exit(0);
}
return 0.0;
}
''')
@implementation('numpy', discard_units=True)
@check_units(rate=Hz, result=1)
def stop_if_too_high(rate):
if rate > 30*Hz:
stop()
# Store the instanteneous firing rate (could also be a low-pass filtered version)
instant_rate = NeuronGroup(1, 'rate: Hz', threshold='True', reset='rate=0*Hz')
con = Synapses(G, instant_rate, pre='rate += 1.0/dt/N_incoming', connect=True)
instant_rate.run_regularly('dummy = stop_if_too_high(rate)', when='after_synapses')
########
run(10*second, report='text')
device.build(run=True, compile=True)
print 'simulated for', monitor.t[-1]
plot(monitor.t/second, monitor.rate/Hz)
show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment