def run_simulation(): G = NeuronGroup(10, 'dv/dt = -v / (10*ms) : 1', reset='v=0', threshold='v>1') G.v = np.linspace(0, 1, 10) run(1*ms) # We return potentially problematic references to a VariableView return G.v
def test_plot_monitors(): set_device('runtime') group = NeuronGroup(10, 'dv/dt = -v/(10*ms) : volt', threshold='False', method='linear') group.v = np.linspace(0, 1, 10)*mV spike_mon = SpikeMonitor(group) rate_mon = PopulationRateMonitor(group) state_mon = StateMonitor(group, 'v', record=[3, 5]) run(10*ms) # Just checking whether the plotting does not fail with an error and that # it retuns an Axis object as promised ax = brian_plot(spike_mon) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_raster(spike_mon.i, spike_mon.t) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = brian_plot(rate_mon) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_rate(rate_mon.t, rate_mon.rate) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = brian_plot(state_mon) assert isinstance(ax, matplotlib.axes.Axes) plt.close() ax = plot_state(state_mon.t, state_mon.v.T) assert isinstance(ax, matplotlib.axes.Axes)
def brian_poisson(rate, duration_ms, dt=1 * ms, n=1): """ :param rate: :param duration_ms: :param dt: :param n: :return: """ q = b2.units.fundamentalunits.Quantity if not isinstance(rate, q): if np.isscalar(rate): rate = rate * Hz else: rate = np.array(rate) * Hz if not isinstance(duration_ms, q): if np.isscalar(duration_ms): duration_ms = duration_ms * ms else: duration_ms = np.array(duration_ms) * ms neuron = b2.NeuronGroup(n, "rate : Hz", threshold='rand()<rate*dt', dt=dt) neuron.rate = rate spikes = b2.SpikeMonitor(neuron, record=True) b2.run(duration_ms) if n == 1: trains = spikes.spike_trains()[0] / dt else: trains = [train / dt for train in spikes.spike_trains().values()] return trains
def main1(): bs.start_scope() tau = 10 * bs.ms # equations must end with : unit # unit is the SI unit of that variable # the unit is 1 since the number "1" is unitless # v represents voltage, but we just keep it unitless for simplicity # 1/s not part of the unit since the unit represents the unit of the variable itself # rather than the unit of the equation eqs = ''' dv/dt = (1-v)/tau: 1 ''' G = bs.NeuronGroup(1, model=eqs, method='exact') # record : bool, sequence of ints # Which indices to record, nothing is recorded for ``False``, # everything is recorded for ``True`` (warning: may use a great deal of # memory), or a specified subset of indices. M = bs.StateMonitor(G, 'v', record=0) print('Before v = %s' % G.v[0]) bs.run(100 * bs.ms) # runs the simulation for 100ms print('After v = %s' % G.v[0]) plt.plot(M.t / bs.ms, M.v[0]) plt.xlabel('Time (ms)') plt.ylabel('v') plt.show()
def test_long_run_dt_change(): # Check that the dt check is not too restrictive, see issue #730 for details group = NeuronGroup(1, '') # does nothing... defaultclock.dt = 0.1*ms run(100*second) defaultclock.dt = 0.01*ms run(1*second)
def setup_spikes(request): def fin(): reinit_devices() request.addfinalizer(fin) EL = -70 * mV VT = -50 * mV DeltaT = 2 * mV C = 1 * nF gL = 30 * nS I = TimedArray(input_current, dt=0.01 * ms) model = Equations(''' dv/dt = (gL*(EL-v)+gL*DeltaT*exp((v-VT)/DeltaT) + I(t))/C : volt ''') group = NeuronGroup(1, model, threshold='v > -50*mV', reset='v = -70*mV', method='exponential_euler') group.v = -70 * mV spike_mon = SpikeMonitor(group) run(60 * ms) spikes = getattr(spike_mon, 't_') return spike_mon, spikes
def simulate_WORM_neuron(input_current, simulation_time=5 * b2.ms, v_leak=V_LEAK, g_leak=G_LEAK, c_m=C_M, rest_pot=R_POT, tau=MEMBRANE_TIME_SCALE, f_t=FIRING_THRESHOLD): # differential equation of neuron model eqs = """ dv/dt = ( g_leak * (v_leak - v) + input_current(t,i) ) / c_m : volt """ # LIF neuron using Brian2 library neuron = b2.NeuronGroup(2, model=eqs, threshold='v>f_t', method="linear") neuron.v = rest_pot # set initial value # monitoring membrane potential of neuron and injecting current state_monitor = b2.StateMonitor(neuron, ["v"], record=True) S = b2.Synapses(neuron, neuron, model='w : volt', on_pre='v += w') S.connect(i=0, j=1) S.w = 0.01 * b2.mV # run the simulation b2.run(simulation_time) return state_monitor
def main3(): # Adding Spikes bs.start_scope() tau = 10 * bs.ms eqs = ''' dv/dt = (1-v)/tau : 1 ''' # conditions for spiking models threshold = 'v>0.8' reset = 'v = -0.8' G = bs.NeuronGroup(1, eqs, threshold=threshold, reset=reset, method='exact') M = bs.StateMonitor(G, 'v', record=0) bs.run(50 * bs.ms) plt.plot(M.t / bs.ms, M.v[0]) plt.xlabel('Time (ms)') plt.ylabel('v') plt.show() # you can also add spike monitor spike_monitor = bs.SpikeMonitor(G) bs.run(50 * bs.ms) print(f"Spike Times: {spike_monitor.t[:]}")
def main4(): # Incorporation of refractory period bs.start_scope() tau = 10 * bs.ms # the (unless refractory) is necessary # refer to the documentation for more detail eqs = ''' dv/dt = (1-v)/tau : 1 (unless refractory) ''' equation = bs.Equations(eqs) # conditions for spiking models threshold = 'v>0.8' reset = 'v = -0.8' refractory = 5 * bs.ms G = bs.NeuronGroup(1, eqs, threshold=threshold, reset=reset, method='exact', refractory=refractory) state_monitor = bs.StateMonitor(G, 'v', record=0) spike_monitor = bs.SpikeMonitor(G) bs.run(50 * bs.ms) plt.plot(state_monitor.t / bs.ms, state_monitor.v[0]) plt.xlabel('Time (ms)') plt.ylabel('v') plt.show()
def run_brian_sim(stim, dt, init_values, param_dict, method = 'exact'): # Model specification eqs = brian2.Equations("") eqs += brian2.Equations("dV/dt = 1 / C * (Ie(t) + I_0 + I_1 - G * (V - El)) : volt (unless refractory)") eqs += brian2.Equations("dTh_s/dt = -b_s * Th_s : volt (unless refractory)") eqs += brian2.Equations("dTh_v/dt = a_v * (V - El) - b_v * (Th_v - Th_inf) : volt (unless refractory)") eqs += brian2.Equations("dI_0/dt = -k_0 * I_0 : amp (unless refractory)") eqs += brian2.Equations("dI_1/dt = -k_1 * I_1 : amp (unless refractory)") reset = "" reset = "\n".join([reset, "V = a_r * V + b_r"]) reset = "\n".join([reset, "Th_s = Th_s + a_s"]) reset = "\n".join([reset, "Th_v = Th_v"]) reset = "\n".join([reset, "I_0 = R_0 * I_0 * exp(-k_0 * (t_ref - dt)) + A_0"]) reset = "\n".join([reset, "I_1 = R_1 * I_1 * exp(-k_1 * (t_ref - dt)) + A_1"]) threshold = "V > Th_v + Th_s" refractory = param_dict['t_ref'] Ie = brian2.TimedArray(stim, dt=dt) nrn = brian2.NeuronGroup(1, eqs, method=method, reset=reset, threshold=threshold, refractory=refractory, namespace=param_dict) nrn.V = init_values['V'] * brian2.units.volt nrn.Th_s = init_values['Th_s'] * brian2.units.volt nrn.Th_v = init_values['Th_v'] * brian2.units.volt nrn.I_0 = init_values['I_0'] * brian2.units.amp nrn.I_1 = init_values['I_1'] * brian2.units.amp monvars = ['V','Th_s','Th_v','I_0','I_1',] mon = brian2.StateMonitor(nrn, monvars, record=True) num_step = len(stim) brian2.defaultclock.dt = dt brian2.run(num_step * dt) return (mon.t / brian2.units.second, mon.V[0] / brian2.units.volt, mon.Th_s[0] / brian2.units.volt, mon.Th_v[0] / brian2.units.volt, mon.I_0[0] / brian2.units.amp, mon.I_1[0] / brian2.units.amp, )
def test_zhang_synapse(): sound = whitenoise(100*ms, samplerate=50*kHz) cf = erbspace(20*Hz, 20*kHz, 100) ihc = TanCarney(MiddleEar(sound), cf) syn = ZhangSynapse(ihc, cf) M = SpikeMonitor(syn) run(sound.duration)
def simulation1(flag_device=False, path="", rec_idx=idx_to_record): if flag_device: set_device('neuroml2', filename=LEMS_OUTPUT_FILENAME) n = 100 duration = 1 * second tau = 10 * ms eqs = ''' dv/dt = (v0 - v) / tau : volt (unless refractory) v0 : volt ''' group = NeuronGroup(n, eqs, threshold='v > 10*mV', reset='v = 0*mV', refractory=5 * ms, method='linear') group.v = 0 * mV group.v0 = '20*mV * i / (N-1)' statemonitor = StateMonitor(group, 'v', record=rec_idx) spikemonitor = SpikeMonitor(group, record=rec_idx) run(duration) if not flag_device: recvec = [] for ri in rec_idx: recvec.append(statemonitor[ri].v) recvec = np.asarray(recvec) return recvec else: return None
def test_magic_network(): # test that magic network functions correctly x = Counter() y = Counter() run(10*ms) assert_equal(x.count, 100) assert_equal(y.count, 100)
def test_magic_network(): # test that magic network functions correctly x = Counter() y = Counter() run(10 * ms) assert_equal(x.count, 100) assert_equal(y.count, 100)
def test_ExportDevice_options(): """ Test the run and build options of ExportDevice """ # test1 set_device('exporter') grp = NeuronGroup(10, 'eqn = 1:1', method='exact') run(100 * ms) _ = StateMonitor(grp, 'eqn', record=False) with pytest.raises(RuntimeError): run(100 * ms) # test2 device.reinit() with pytest.raises(RuntimeError): device.build() # test3 start_scope() net = Network() set_device('exporter', build_on_run=False) grp = NeuronGroup(10, 'eqn = 1:1', method='exact') net.add(grp) net.run(10 * ms) pogrp = PoissonGroup(10, rates=10 * Hz) net.add(pogrp) net.run(10 * ms) mon = StateMonitor(grp, 'eqn', record=False) net.add(mon) net.run(10 * ms) device.build() device.reinit()
def run_simulation(parameters): """Run the simulation. parameters -- dictionary with parameters """ equations = [] for gating_variable in ["m", "n", "h"]: equations.append( construct_gating_variable_inf_equation(gating_variable)) equations.append( construct_gating_variable_tau_equation(gating_variable)) equations.append(construct_gating_variable_ode(gating_variable)) equations += construct_neuron_ode() eqs_HH = reduce(operator.add, equations) group = NeuronGroup(1, eqs_HH, method='euler', namespace=parameters) group.v = parameters["v_initial"] group.m = parameters["m_initial"] group.n = parameters["n_initial"] group.h = parameters["h_initial"] statemon = StateMonitor(group, [ 'v', 'I_ext', 'm', 'n', 'h', 'g_K', 'g_Na', 'I_K', 'I_Na', 'I_L', 'tau_m', 'tau_n', 'tau_h' ], record=True) defaultclock.dt = parameters["defaultclock_dt"] run(parameters["duration"]) return statemon
def test_dependency_check(): def create_net(): G = NeuronGroup(10, 'v: 1', threshold='False') dependent_objects = [ StateMonitor(G, 'v', record=True), SpikeMonitor(G), PopulationRateMonitor(G), Synapses(G, G, pre='v+=1', connect=True) ] return dependent_objects dependent_objects = create_net() # Trying to simulate the monitors/synapses without the group should fail for obj in dependent_objects: assert_raises(ValueError, lambda: Network(obj).run(0*ms)) # simulation with a magic network should work when we have an explicit # reference to one of the objects, but the object should be inactive and # we should get a warning assert all(obj.active for obj in dependent_objects) for obj in dependent_objects: # obj is our explicit reference with catch_logs() as l: run(0*ms) dependency_warnings = [msg[2] for msg in l if msg[1] == 'brian2.core.magic.dependency_warning'] assert len(dependency_warnings) == 1 assert not obj.active
def test_runtime_rounding(): # Test that runtime and standalone round in the same way, see github issue # #695 for details defaultclock.dt = 20.000000000020002 * us G = NeuronGroup(1, 'v:1') mon = StateMonitor(G, 'v', record=True) run(defaultclock.dt * 250) assert len(mon.t) == 250
def test_network_active_flag(): # test that the BrianObject.active flag is recognised by Network.run x = Counter() y = Counter() y.active = False run(1*ms) assert_equal(x.count, 10) assert_equal(y.count, 0)
def simulate_passive_cable(current_injection_location=DEFAULT_INPUT_LOCATION, input_current=DEFAULT_INPUT_CURRENT, length=CABLE_LENGTH, diameter=CABLE_DIAMETER, r_longitudinal=R_LONGITUDINAL, r_transversal=R_TRANSVERSAL, e_leak=E_LEAK, initial_voltage=E_LEAK, capacitance=CAPACITANCE, nr_compartments=200, simulation_time=5 * b2.ms): """Builds a multicompartment cable and numerically approximates the cable equation. Args: t_spikes (int): list of spike times current_injection_location (list): List [] of input locations (Quantity, Length): [123.*b2.um] input_current (TimedArray): TimedArray of current amplitudes. One column per current_injection_location. length (Quantity): Length of the cable: 0.8*b2.mm diameter (Quantity): Diameter of the cable: 0.2*b2.um r_longitudinal (Quantity): The longitudinal (axial) resistance of the cable: 0.5*b2.kohm*b2.mm r_transversal (Quantity): The transversal resistance (=membrane resistance): 1.25*b2.Mohm*b2.mm**2 e_leak (Quantity): The reversal potential of the leak current (=resting potential): -70.*b2.mV initial_voltage (Quantity): Value of the potential at t=0: -70.*b2.mV capacitance (Quantity): Membrane capacitance: 0.8*b2.uF/b2.cm**2 nr_compartments (int): Number of compartments. Spatial discretization: 200 simulation_time (Quantity): Time for which the dynamics are simulated: 5*b2.ms Returns: (StateMonitor, SpatialNeuron): The state monitor contains the membrane voltage in a Time x Location matrix. The SpatialNeuron object specifies the simulated neuron model and gives access to the morphology. You may want to use those objects for spatial indexing: myVoltageStateMonitor[mySpatialNeuron.morphology[0.123*b2.um]].v """ assert isinstance(input_current, b2.TimedArray), "input_current is not of type TimedArray" assert input_current.values.shape[1] == len(current_injection_location),\ "number of injection_locations does not match nr of input currents" cable_morphology = b2.Cylinder(diameter=diameter, length=length, n=nr_compartments) # Im is transmembrane current # Iext is injected current at a specific position on dendrite EL = e_leak RT = r_transversal my_equs = """ Iext = current(t, location_index): amp (point current) location_index : integer (constant) Im = (EL-v)/RT : amp/meter**2 """ cable_model = b2.SpatialNeuron(morphology=cable_morphology, model=my_equs, Cm=capacitance, Ri=r_longitudinal) monitor_v = b2.StateMonitor(cable_model, "v", record=True) # inject all input currents at the specified location: nr_input_locations = len(current_injection_location) input_current_0 = np.insert(input_current.values, 0, 0., axis=1) * b2.amp # insert default current: 0. [amp] current = b2.TimedArray(input_current_0, dt=input_current.dt * b2.second) for current_index in range(nr_input_locations): insert_location = current_injection_location[current_index] compartment_index = int(np.floor(insert_location / (length / nr_compartments))) # next line: current_index+1 because 0 is the default current 0Amp cable_model.location_index[compartment_index] = current_index + 1 # set initial values and run for 1 ms cable_model.v = initial_voltage b2.run(simulation_time) return (monitor_v, cable_model)
def test_multiple_runs_constant_change(): const_v = 1 group = NeuronGroup(1, 'v = const_v : 1') mon = StateMonitor(group, 'v', record=0) run(defaultclock.dt) const_v = 2 run(defaultclock.dt) device.build(direct_call=False, **device.build_options) assert_equal(mon.v[0], [1, 2])
def test_multiple_runs_function_change(): inp = TimedArray([1, 2], dt=defaultclock.dt) group = NeuronGroup(1, 'v = inp(t) : 1') mon = StateMonitor(group, 'v', record=0) run(2 * defaultclock.dt) inp = TimedArray([0, 0, 3, 4], dt=defaultclock.dt) run(2 * defaultclock.dt) device.build(direct_call=False, **device.build_options) assert_equal(mon.v[0], [1, 2, 3, 4])
def run(TSTOP=250, group_size=100, g_time=150, neuron_n=1000, linear=True, ext_w=0.2, inh_w=0.2): """Run a simulation and return the resulting spiketrain""" # Basic equation of the model eq = """dv/dt = -gamma*v + I0 : volt Ie : volt Ii : volt """ thetaU = 16 * mV tauM = 8 * ms gamma = 1 / tauM I0 = 17.6 * mV / tauM #Build the group of neuron to use G = br2.NeuronGroup(neuron_n, threshold="v>thetaU", reset="v=0*mV", method='euler', model=eq) #Record the spikes from this group spikes = br2.SpikeMonitor(G) #Build stimulation stim = br2.SpikeGeneratorGroup(1, [0], [g_time]*ms - br2.defaultclock.dt) stim_syn = br2.Synapses(stim, G, on_pre="v += 2*thetaU") stim_syn.connect(i=0, j=np.arange(group_size)) br2.magic_network.schedule = ['start', 'groups', 'synapses', 'thresholds', 'resets', 'end'] connections = np.random.rand(1000, 1000) < 0.3 exc_or_inh = np.random.rand(1000, 1000) < 0.5 exc_i, exc_j = (connections & exc_or_inh).nonzero() inh_i, inh_j = (connections & ~exc_or_inh).nonzero() if linear: G.run_regularly(''' v += Ie + Ii Ie = 0*mV Ii = 0*mV ''', when='after_synapses') else: G.run_regularly(''' v += clip(Ie, 0*mV, 2*mV) + clip(2*(Ie-2*mV), 0*mV, 4*mV) + Ii Ie = 0*mV Ii = 0*mV ''', when='after_synapses') dt = br2.defaultclock.dt exc_syn = br2.Synapses(G, G, on_pre='Ie += %s*mV' % (ext_w), delay=5*ms-dt) inh_syn = br2.Synapses(G, G, on_pre='Ii -= %s*mV' % (inh_w), delay=5*ms-dt) exc_syn.connect(i=exc_i, j=exc_j) inh_syn.connect(i=inh_i, j=inh_j) #Set random initial conditions G.v = np.random.rand(neuron_n) * 16 * mV br2.run(TSTOP * ms) return spikes
def echo_spike(p, tStim, tTot): start_scope() prefs.codegen.target = "numpy" ################################ # Compute properties ################################ dvInpSpike = p['nu_DV'] # Voltage increase per noise spike dvExcSpike = p['LIF_DV'] # Voltage increase per lateral spike # dvExcSpike = p['LIF_T_0'] / (1.0 * p['N'] * p['p_conn']) # Voltage increase per lateral spike print("typical spike threshold", p['LIF_T_0']) print("typical potential change per noise spike", dvInpSpike) print("typical potential change per lateral spike", dvExcSpike) ################################ # Create input population ################################ nTStimPost = int(tTot / tStim) - 1 # After input switched off, 0-input will be repeated nTStimPost*tStim timesteps patternInp = (np.random.uniform(0, 1, p['N']) < p['nu_p']).astype(int) pattern0 = np.zeros(p['N']) rates_all = np.array([patternInp] + [pattern0]*nTStimPost) * p['nu_FREQ'] rateTimedArray = TimedArray(rates_all, dt=tStim) gInp = PoissonGroup(p['N'], rates="rateTimedArray(t, i)") # gInp = PoissonGroup(p['N'], p['nu_FREQ']) ################################ # Create reservoir population ################################ gExc = brian2wrapper.NeuronGroupLIF(p['N'], p['LIF_V_0'], p['LIF_T_0'], p['LIF_V_TAU']) ################################ # Create synapses ################################ sInpExc = Synapses(gInp, gExc, on_pre='v_post += dvInpSpike', method='exact') sExcExc = Synapses(gExc, gExc, on_pre='v_post += dvExcSpike', method='exact') ################################ # Connect synapses ################################ # * Input and LIF one-to-one # * LIF neurons to each other sparsely sInpExc.connect(j='i') sExcExc.connect(p=p['p_conn']) ################################ # Init Monitors ################################ #spikemonInp = SpikeMonitor(gInp) spikemonExc = SpikeMonitor(gExc) ################################ # Run simulation ################################ run(tTot) return np.array(spikemonExc.i), np.array(spikemonExc.t)
def test_magic_network(): # test that magic network functions correctly x = Counter() y = Counter() run(10*ms) assert_equal(x.count, 100) assert_equal(y.count, 100) assert len(repr(magic_network)) # very basic test... assert len(str(magic_network)) # very basic test...
def test_multiple_runs_report_standalone_3(with_output=False): set_device('cpp_standalone', build_on_run=False) group = NeuronGroup(1, 'dv/dt = 1*Hz : 1') run(1*ms, report='text') run(1*ms, report='text') tempdir = tempfile.mkdtemp() if with_output: print tempdir device.build(directory=tempdir, compile=True, run=True, with_output=with_output)
def HH_Neuron(curr, simtime): """Simple Hodgkin-Huxley neuron implemented in Brian2. Args: curr (TimedArray): Input current injected into the HH neuron simtime (float): Simulation time [seconds] Returns: StateMonitor: Brian2 StateMonitor with recorded fields ['vm', 'I_e', 'm', 'n', 'h'] """ # neuron parameters El = 10.6 * b2.mV EK = -12 * b2.mV ENa = 115 * b2.mV gl = 0.3 * b2.msiemens gK = 36 * b2.msiemens gNa = 120 * b2.msiemens C = 1 * b2.ufarad # forming HH model with differential equations eqs = ''' I_e = curr(t) : amp membrane_Im = I_e + gNa*m**3*h*(ENa-vm) + \ gl*(El-vm) + gK*n**4*(EK-vm) : amp alphah = .07*exp(-.05*vm/mV)/ms : Hz alpham = .1*(25*mV-vm)/(exp(2.5-.1*vm/mV)-1)/mV/ms : Hz alphan = .01*(10*mV-vm)/(exp(1-.1*vm/mV)-1)/mV/ms : Hz betah = 1./(1+exp(3.-.1*vm/mV))/ms : Hz betam = 4*exp(-.0556*vm/mV)/ms : Hz betan = .125*exp(-.0125*vm/mV)/ms : Hz dh/dt = alphah*(1-h)-betah*h : 1 dm/dt = alpham*(1-m)-betam*m : 1 dn/dt = alphan*(1-n)-betan*n : 1 dvm/dt = membrane_Im/C : volt ''' neuron = b2.NeuronGroup(1, eqs, method='exponential_euler') # parameter initialization neuron.vm = 0 neuron.m = 0.0529324852572 neuron.h = 0.596120753508 neuron.n = 0.317676914061 # tracking parameters rec = b2.StateMonitor(neuron, ['vm', 'I_e', 'm', 'n', 'h'], record=True) # running the simulation b2.run(simtime) return rec
def current_pulse_sim_with_opto(args, params=None): if params is None: params = get_neuron_params(args['NRN']) params['Vclamp'] = -80 neurons, eqs = get_membrane_equation(params, [],\ return_equations=True) if args['verbose']: print(eqs) fig, ax = brian2.subplots(figsize=(5,3)) # V value initialization neurons.V = params['El']*brian2.mV trace = brian2.StateMonitor(neurons, 'V', record=0) spikes = brian2.SpikeMonitor(neurons) # rest run brian2.run(args['delay'] * brian2.ms) # first pulse neurons.I0 = args['amp']*brian2.pA brian2.run(args['duration']/3. * brian2.ms) neurons.Gclamp = 1e3*brian2.nS brian2.run(args['duration']/3. * brian2.ms) neurons.Gclamp = 0*brian2.nS brian2.run(args['duration']/3. * brian2.ms) # second pulse neurons.I0 = 0 brian2.run(args['delay'] * brian2.ms) # We draw nicer spikes Vm = trace[0].V[:] for t in spikes.t: ax.plot(t/brian2.ms*np.ones(2), [Vm[int(t/brian2.defaultclock.dt)]/brian2.mV,-10], '--', color=args['color']) ax.plot(trace.t / brian2.ms, Vm / brian2.mV, color=args['color']) if 'NRN' in args.keys(): ax.set_title(args['NRN']) ax.annotate(str(int(params['El']))+'mV', (-50,params['El']-5)) ax.plot([-20], [params['El']], 'k>') ax.plot([0,50], [-50, -50], 'k-', lw=4) ax.plot([0,0], [-50, -40], 'k-', lw=4) ax.annotate('10mV', (-50,-38)) ax.annotate('50ms', (0,-55)) # set_plot(ax, [], xticks=[], yticks=[]) # show() if 'save' in args.keys(): fig.savefig(args['save']) return fig
def main2(): # setting synaptic weight bs.start_scope() n_neurons = 3 eqs = ''' dv/dt = (I-v)/tau : 1 (unless refractory) I : 1 tau: second ''' threshold = 'v>1' reset = 'v = 0' refractory = 10 * bs.ms G = bs.NeuronGroup(N=n_neurons, model=eqs, threshold=threshold, reset=reset, method='exact', refractory=refractory) G.I = [2, 0, 0] # represents the I in eqs # driving current should be bigger than the threshold, otherwise it wont spike at all # I = 0 means that the voltage wont change since there is no driving current G.tau = [10, 100, 100] * bs.ms # represents the tau in eqs # unlike last time, the tau is defined with the neuron so we see the effects of different values # model : `str`, `Equations`, optional # The model equations for the synapses. # you need to set this as model= in Synapses in order to incorporate weight synapse_model = 'w : 1' # So in total, what this model says is that whenever two neurons in G are connected by a synapse, # when the source neuron fires a spike the target neuron will have its value of v increased by 0.2. S = bs.Synapses(source=G, target=G, model=synapse_model, on_pre='v_post += w') S.connect(i=0, j=[1, 2]) # So this will give a synaptic connection from 0 to 1 with weight 0.2=0.2*1 and from 0 to 2 with weight 0.4=0.2*2. S.w = 'j*0.2' state_monitor = bs.StateMonitor(G, 'v', record=True) bs.run(100 * bs.ms) plt.plot(state_monitor.t / bs.ms, state_monitor.v[0], label='Neuron 0') plt.plot(state_monitor.t / bs.ms, state_monitor.v[1], label='Neuron 1') plt.plot(state_monitor.t / bs.ms, state_monitor.v[2], label='Neuron 2') plt.xlabel('Time (ms)') plt.ylabel('v') plt.legend() plt.show()
def test_store_restore_magic(): source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', pre='v+=w', connect='i==j') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) store() # default time slot run(10*ms) store('second') run(10*ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ restore() # Go back to beginning assert magic_network.t == 0*ms run(20*ms) assert defaultclock.t == 20*ms assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle restore('second') assert magic_network.t == 10*ms run(10*ms) assert defaultclock.t == 20*ms assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:])
def main1(): bs.start_scope() # Parameters area = 20000 * bs.umetre**2 Cm = 1 * bs.ufarad * bs.cm**-2 * area gl = 5e-5 * bs.siemens * bs.cm**-2 * area El = -65 * bs.mV EK = -90 * bs.mV ENa = 50 * bs.mV g_na = 100 * bs.msiemens * bs.cm**-2 * area g_kd = 30 * bs.msiemens * bs.cm**-2 * area VT = -63 * bs.mV # HH stands for Hudgkin-Huxley eqs_HH = ''' dv/dt = (gl*(El-v) - g_na*(m*m*m)*h*(v-ENa) - g_kd*(n*n*n*n)*(v-EK) + I)/Cm : volt dm/dt = 0.32*(mV**-1)*(13.*mV-v+VT)/ (exp((13.*mV-v+VT)/(4.*mV))-1.)/ms*(1-m)-0.28*(mV**-1)*(v-VT-40.*mV)/ (exp((v-VT-40.*mV)/(5.*mV))-1.)/ms*m : 1 dn/dt = 0.032*(mV**-1)*(15.*mV-v+VT)/ (exp((15.*mV-v+VT)/(5.*mV))-1.)/ms*(1.-n)-.5*exp((10.*mV-v+VT)/(40.*mV))/ms*n : 1 dh/dt = 0.128*exp((17.*mV-v+VT)/(18.*mV))/ms*(1.-h)-4./(1+exp((40.*mV-v+VT)/(5.*mV)))/ms*h : 1 I : amp ''' group = bs.NeuronGroup(1, eqs_HH, threshold='v > -40*mV', refractory='v > -40*mV', method='exponential_euler') group.v = El state_monitor = bs.StateMonitor(group, 'v', record=True) spike_monitor = bs.SpikeMonitor(group, variables='v') plt.figure(figsize=(9, 4)) for l in range(5): group.I = bs.rand() * 50 * bs.nA bs.run(10 * bs.ms) bs.axvline(l * 10, ls='--', c='k') bs.axhline(El / bs.mV, ls='-', c='lightgray', lw=3) state_time = state_monitor.t spike_time = spike_monitor.t plt.plot(state_time / bs.ms, spike_monitor.v[0] / bs.mV, '-b') plt.plot(spike_time / bs.ms, spike_monitor.v / bs.mV, 'ob') plt.xlabel('Time (ms)') plt.ylabel('v (mV)') plt.show()
def test_network_operations(): # test NetworkOperation and network_operation seq = [] def f1(): seq.append('a') op1 = NetworkOperation(f1, when=('start', 1)) @network_operation def f2(): seq.append('b') @network_operation(when=('end', 1)) def f3(): seq.append('c') run(1*ms) assert_equal(''.join(seq), 'bac'*10)
def simulate(self, current=input_factory.get_zero_current(), time=10 * b2.ms, rheo_threshold=None, v_rest=None, v_reset=None, delta_t=None, time_scale=None, resistance=None, threshold=None, adapt_volt_c=None, adapt_tau=None, adapt_incr=None): if (v_rest == None): v_rest = self.rest_pot if (v_reset == None): v_reset = self.reset_pot if (rheo_threshold == None): rheo_threshold = self.rheo_threshold if (delta_t == None): delta_t = self.delta_t if (time_scale == None): time_scale = self.time_scale if (resistance == None): resistance = self.resistance if (threshold == None): threshold = self.threshold if (adapt_volt_c == None): adapt_volt_c = self.adapt_volt_c if (adapt_tau == None): adapt_tau = self.adapt_tau if (adapt_incr == None): adapt_incr = self.adapt_incr v_spike_str = "v>{:f}*mvolt".format(threshold / b2.mvolt) eqs = """ dv/dt = (-(v-v_rest) +delta_t*exp((v-rheo_threshold)/delta_t)+ resistance * current(t,i) - resistance * w)/(time_scale) : volt dw/dt=(adapt_volt_c*(v-v_rest)-w)/adapt_tau : amp """ neuron = b2.NeuronGroup(1, model=eqs, threshold=v_spike_str, reset="v=v_reset;w+=adapt_incr", method="euler") neuron.v = v_rest neuron.w = 0.0 * b2.pA state_monitor = b2.StateMonitor(neuron, ["v", "w"], record=True) spike_monitor = b2.SpikeMonitor(neuron) b2.run(time) return state_monitor, spike_monitor
def test_ExportDevice_unsupported(): """ Test whether unsupported objects for standard format export are raising Error """ start_scope() set_device('exporter') eqn = ''' v = 1 :1 g :1 ''' G = NeuronGroup(1, eqn) _ = PoissonInput(G, 'g', 1, 1 * Hz, 1) # with pytest.raises(NotImplementedError): run(10 * ms)
def main2(): tau = 10 * bs.ms eqs = ''' dv/dt = (sin(2*pi*100*Hz*t)-v)/tau : 1 ''' G = bs.NeuronGroup(1, eqs, method="euler") G.v = 5 # we can set the initial value M = bs.StateMonitor(G, 'v', record=0) bs.run(60 * bs.ms) plt.plot(M.t / bs.ms, M.v[0]) plt.xlabel('Time (ms)') plt.ylabel('v') plt.show()
def test_multiple_networks_invalid(): x = Counter() net = Network(x) net.run(1*ms) try: run(1*ms) raise AssertionError('Expected a RuntimeError') except RuntimeError: pass # this is expected try: net2 = Network(x) raise AssertionError('Expected a RuntimeError') except RuntimeError: pass # this is expected
def test_magic_weak_reference(): ''' Test that holding a weak reference to an object does not make it get simulated.''' G1 = NeuronGroup(1, 'v:1') # this object should not be included G2 = weakref.ref(NeuronGroup(1, 'v:1')) with catch_logs(log_level=logging.DEBUG) as l: run(1*ms) # Check the debug messages for the number of included objects magic_objects = [msg[2] for msg in l if msg[1] == 'brian2.core.magic.magic_objects'][0] assert '2 objects' in magic_objects, 'Unexpected log message: %s' % magic_objects
def test_magic_unused_object(): '''Test that creating unused objects does not affect the magic system.''' def create_group(): # Produce two objects but return only one G1 = NeuronGroup(1, 'v:1') # no Thresholder or Resetter G2 = NeuronGroup(1, 'v:1') # This object should be garbage collected return G1 G = create_group() with catch_logs(log_level=logging.INFO) as l: run(1*ms) # Check the debug messages for the number of included objects magic_objects = [msg[2] for msg in l if msg[1] == 'brian2.core.magic.magic_objects'][0] assert '2 objects' in magic_objects, 'Unexpected log message: %s' % magic_objects
def run_network(): monitor_dict={} defaultclock.dt= 0.01*ms C=281*pF gL=30*nS EL=-70.6*mV VT=-50.4*mV DeltaT=2*mV tauw=40*ms a=4*nS b=0.08*nA I=8*nA Vcut="vm>2*mV"# practical threshold condition N=10 reset = 'vm=Vr;w+=b' eqs=""" dvm/dt=(gL*(EL-vm)+gL*DeltaT*exp((vm-VT)/DeltaT)+I-w)/C : volt dw/dt=(a*(vm-EL)-w)/tauw : amp Vr:volt """ neuron=NeuronGroup(N,model=eqs,threshold=Vcut,reset=reset) neuron.vm=EL neuron.w=a*(neuron.vm-EL) neuron.Vr=linspace(-48.3*mV,-47.7*mV,N) # bifurcation parameter #run(25*msecond,report='text') # we discard the first spikes MSpike=SpikeMonitor(neuron, variables=['vm']) # record Vr and w at spike times MPopRate = PopulationRateMonitor(neuron) MMultiState = StateMonitor(neuron, ['w','vm'], record=[6,7,8,9]) run(10*msecond,report='text') monitor_dict['SpikeMonitor']=MSpike monitor_dict['MultiState']=MMultiState monitor_dict['PopulationRateMonitor']=MPopRate return monitor_dict
def test_filterbankgroup(): sound1 = tone(1 * kHz, .1 * second) sound2 = whitenoise(.1 * second) sound = sound1 + sound2 sound = sound.ramp() cf = erbspace(20 * Hz, 20 * kHz, 3000) cochlea = Gammatone(sound, cf) # Half-wave rectification and compression [x]^(1/3) ihc = FunctionFilterbank(cochlea, lambda x: 3 * np.clip(x, 0, np.inf) ** (1.0 / 3.0)) # Leaky integrate-and-fire model with noise and refractoriness eqs = ''' dv/dt = (I-v)/(1*ms)+0.2*xi*(2/(1*ms))**.5 : 1 (unless refractory) I : 1 ''' anf = FilterbankGroup(ihc, 'I', eqs, reset='v=0', threshold='v>1', refractory=5*ms, method='euler') M = SpikeMonitor(anf) run(sound.duration)
def simulate_exponential_IF_neuron( tau=MEMBRANE_TIME_SCALE_tau, R=MEMBRANE_RESISTANCE_R, v_rest=V_REST, v_reset=V_RESET, v_rheobase=RHEOBASE_THRESHOLD_v_rh, v_spike=FIRING_THRESHOLD_v_spike, delta_T=SHARPNESS_delta_T, I_stim=input_factory.get_zero_current(), simulation_time=200 * b2.ms, ): """ Implements the dynamics of the exponential Integrate-and-fire model Args: tau (Quantity): Membrane time constant R (Quantity): Membrane resistance v_rest (Quantity): Resting potential v_reset (Quantity): Reset value (vm after spike) v_rheobase (Quantity): Rheobase threshold v_spike (Quantity) : voltage threshold for the spike condition delta_T (Quantity): Sharpness of the exponential term I_stim (TimedArray): Input current simulation_time (Quantity): Duration for which the model is simulated Returns: (voltage_monitor, spike_monitor): A b2.StateMonitor for the variable "v" and a b2.SpikeMonitor """ eqs = """ dv/dt = (-(v-v_rest) +delta_T*exp((v-v_rheobase)/delta_T)+ R * I_stim(t,i))/(tau) : volt """ neuron = b2.NeuronGroup(1, model=eqs, reset="v=v_reset", threshold="v>v_spike", method="euler") neuron.v = v_rest # monitoring membrane potential of neuron and injecting current voltage_monitor = b2.StateMonitor(neuron, ["v"], record=True) spike_monitor = b2.SpikeMonitor(neuron) # run the simulation b2.run(simulation_time) return voltage_monitor, spike_monitor
def simulate_LIF_neuron(input_current, simulation_time=5 * b2.ms, v_rest=V_REST, v_reset=V_RESET, firing_threshold=FIRING_THRESHOLD, membrane_resistance=MEMBRANE_RESISTANCE, membrane_time_scale=MEMBRANE_TIME_SCALE, abs_refractory_period=ABSOLUTE_REFRACTORY_PERIOD): """Basic leaky integrate and fire neuron implementation. Args: input_current (TimedArray): TimedArray of current amplitudes. One column per current_injection_location. simulation_time (Quantity): Time for which the dynamics are simulated: 5ms v_rest (Quantity): Resting potential: -70mV v_reset (Quantity): Reset voltage after spike - 65mV firing_threshold (Quantity) Voltage threshold for spiking -50mV membrane_resistance (Quantity): 10Mohm membrane_time_scale (Quantity): 8ms abs_refractory_period (Quantity): 2ms Returns: StateMonitor: Brian2 StateMonitor for the membrane voltage "v" SpikeMonitor: Biran2 SpikeMonitor """ # differential equation of Leaky Integrate-and-Fire model eqs = """ dv/dt = ( -(v-v_rest) + membrane_resistance * input_current(t,i) ) / membrane_time_scale : volt (unless refractory)""" # LIF neuron using Brian2 library neuron = b2.NeuronGroup( 1, model=eqs, reset="v=v_reset", threshold="v>firing_threshold", refractory=abs_refractory_period, method="linear") neuron.v = v_rest # set initial value # monitoring membrane potential of neuron and injecting current state_monitor = b2.StateMonitor(neuron, ["v"], record=True) spike_monitor = b2.SpikeMonitor(neuron) # run the simulation b2.run(simulation_time) return state_monitor, spike_monitor
def get_trajectory(v0=0., w0=0., I=0., eps=0.1, a=2.0, tend=500.): """Solves the following system of FitzHugh Nagumo equations for given initial conditions: dv/dt = 1/1ms * v * (1-v**2) - w + I dw/dt = eps * (v + 0.5 * (a - w)) Args: v0: Intial condition for v [mV] w0: Intial condition for w [mV] I: Constant input [mV] eps: Inverse time constant of the recovery variable w [1/ms] a: Offset of the w-nullcline [mV] tend: Simulation time [ms] Returns: tuple: (t, v, w) tuple for solutions """ eqs = """ I_e : amp dv/dt = 1/ms * ( v * (1 - (v**2) / (mV**2) ) - w + I_e * Mohm ) : volt dw/dt = eps/ms * (v + 0.5 * (a * mV - w)) : volt """ neuron = b2.NeuronGroup(1, eqs, method="euler") # state initialization neuron.v = v0 * b2.mV neuron.w = w0 * b2.mV # set input current neuron.I_e = I * b2.nA # record states rec = b2.StateMonitor(neuron, ["v", "w"], record=True) # run the simulation b2.run(tend * b2.ms) return (rec.t / b2.ms, rec.v[0] / b2.mV, rec.w[0] / b2.mV)
def LIF_Neuron(curr, simtime): """Simple LIF neuron implemented in Brian2. Args: curr (TimedArray): Input current injected into the neuron simtime (float): Simulation time [seconds] Returns: StateMonitor: Brian2 StateMonitor with input current (I) and voltage (V) recorded """ # constants v_reset = 0.*b2.mV v_threshold = 1.*b2.mV R = 1*b2.Mohm v_rest = 0*b2.mV tau = 1*b2.ms v_reset_ = "v=%f*volt" % v_reset v_threshold_ = "v>%f*volt" % v_threshold # differential equation of Leaky Integrate-and-Fire model eqs = ''' dv/dt = ( -(v-v_rest) + R * I ) / tau : volt I = curr(t) : amp ''' # LIF neuron using Brian2 library IF = b2.NeuronGroup(1, model=eqs, reset=v_reset_, threshold=v_threshold_) IF.v = v_rest # monitoring membrane potential of neuron and injecting current rec = b2.StateMonitor(IF, ['v', 'I'], record=True) # run the simulation b2.run(simtime) return rec
def test_network_t(): # test that Network.t works as expected c1 = Clock(dt=1*ms) c2 = Clock(dt=2*ms) x = Counter(when=c1) y = Counter(when=c2) net = Network(x, y) net.run(4*ms) assert_equal(c1.t, 4*ms) assert_equal(c2.t, 4*ms) assert_equal(net.t, 4*ms) net.run(1*ms) assert_equal(c1.t, 5*ms) assert_equal(c2.t, 6*ms) assert_equal(net.t, 5*ms) assert_equal(x.count, 5) assert_equal(y.count, 3) net.run(0.5*ms) # should only update x assert_equal(c1.t, 6*ms) assert_equal(c2.t, 6*ms) assert_equal(net.t, 5.5*ms) assert_equal(x.count, 6) assert_equal(y.count, 3) net.run(0.5*ms) # shouldn't do anything assert_equal(c1.t, 6*ms) assert_equal(c2.t, 6*ms) assert_equal(net.t, 6*ms) assert_equal(x.count, 6) assert_equal(y.count, 3) net.run(0.5*ms) # should update x and y assert_equal(c1.t, 7*ms) assert_equal(c2.t, 8*ms) assert_equal(net.t, 6.5*ms) assert_equal(x.count, 7) assert_equal(y.count, 4) del c1, c2, x, y, net # now test with magic run c1 = Clock(dt=1*ms) c2 = Clock(dt=2*ms) x = Counter(when=c1) y = Counter(when=c2) run(4*ms) assert_equal(c1.t, 4*ms) assert_equal(c2.t, 4*ms) assert_equal(x.count, 4) assert_equal(y.count, 2) run(4*ms) assert_equal(c1.t, 8*ms) assert_equal(c2.t, 8*ms) assert_equal(x.count, 8) assert_equal(y.count, 4) run(1*ms) assert_equal(c1.t, 9*ms) assert_equal(c2.t, 10*ms) assert_equal(x.count, 9) assert_equal(y.count, 5)
def example_run(debug=False, **build_options): ''' Run a simple example simulation that test whether the Brian2/Brian2GeNN/GeNN pipeline is working correctly. Parameters ---------- debug : bool Whether to display debug information (e.g. compilation output) during the run. Defaults to ``False``. build_options : dict Additional options that will be forwarded to the ``set_device`` call, e.g. ``use_GPU=False``. ''' from brian2.devices.device import set_device, reset_device from brian2 import ms, NeuronGroup, run from brian2.utils.logger import std_silent import numpy as np from numpy.testing import assert_allclose from tempfile import mkdtemp import shutil with std_silent(debug): test_dir = mkdtemp(prefix='brian2genn_test') set_device('genn', directory=test_dir, debug=debug, **build_options) N = 100 tau = 10*ms eqs = ''' dV/dt = -V/tau: 1 ''' G = NeuronGroup(N, eqs, threshold='V>1', reset='V=0', refractory=5 * ms, method='linear') G.V = 'i/100.' run(1*ms) assert_allclose(G.V, np.arange(100)/100.*np.exp(-1*ms/tau)) shutil.rmtree(test_dir, ignore_errors=True) reset_device() print('Example run was successful.')
def timed_run(self, duration): ''' Do a timed run. This means that for RuntimeDevice it will run for defaultclock.dt before running for the rest of the duration. This means total run duration will be duration+defaultclock.dt. For standalone devices, this feature may or may not be implemented. ''' if isinstance(brian2.get_device(), brian2.devices.RuntimeDevice): brian2.run(brian2.defaultclock.dt, level=1) brian2.run(duration, level=1) else: brian2.run(duration, level=1)
def test_dt_changes_between_runs(): defaultclock.dt = 0.1*ms G = NeuronGroup(1, 'v:1') mon = StateMonitor(G, 'v', record=True) run(.5*ms) defaultclock.dt = .5*ms run(.5*ms) defaultclock.dt = 0.1*ms run(.5*ms) assert len(mon.t[:]) == 5 + 1 + 5 assert_allclose(mon.t[:], [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 1., 1.1, 1.2, 1.3, 1.4]*ms)
def test_store_restore_magic_to_file(): filename = tempfile.mktemp(suffix='state', prefix='brian_test') source = NeuronGroup(10, '''dv/dt = rates : 1 rates : Hz''', threshold='v>1', reset='v=0') source.rates = 'i*100*Hz' target = NeuronGroup(10, 'v:1') synapses = Synapses(source, target, model='w:1', on_pre='v+=w') synapses.connect(j='i') synapses.w = 'i*1.0' synapses.delay = 'i*ms' state_mon = StateMonitor(target, 'v', record=True) spike_mon = SpikeMonitor(source) store(filename=filename) # default time slot run(10*ms) store('second', filename=filename) run(10*ms) v_values = state_mon.v[:, :] spike_indices, spike_times = spike_mon.it_ restore(filename=filename) # Go back to beginning assert magic_network.t == 0*ms run(20*ms) assert defaultclock.t == 20*ms assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) # Go back to middle restore('second', filename=filename) assert magic_network.t == 10*ms run(10*ms) assert defaultclock.t == 20*ms assert_equal(v_values, state_mon.v[:, :]) assert_equal(spike_indices, spike_mon.i[:]) assert_equal(spike_times, spike_mon.t_[:]) try: os.remove(filename) except OSError: pass
def test_network_t(): # test that Network.t works as expected x = Counter(dt=1*ms) y = Counter(dt=2*ms) net = Network(x, y) net.run(4*ms) assert_equal(net.t, 4*ms) net.run(1*ms) assert_equal(net.t, 5*ms) assert_equal(x.count, 5) assert_equal(y.count, 3) net.run(0.5*ms) # should only update x assert_equal(net.t, 5.5*ms) assert_equal(x.count, 6) assert_equal(y.count, 3) net.run(0.5*ms) # shouldn't do anything assert_equal(net.t, 6*ms) assert_equal(x.count, 6) assert_equal(y.count, 3) net.run(0.5*ms) # should update x and y assert_equal(net.t, 6.5*ms) assert_equal(x.count, 7) assert_equal(y.count, 4) del x, y, net # now test with magic run x = Counter(dt=1*ms) y = Counter(dt=2*ms) run(4*ms) assert_equal(magic_network.t, 4*ms) assert_equal(x.count, 4) assert_equal(y.count, 2) run(4*ms) assert_equal(magic_network.t, 8*ms) assert_equal(x.count, 8) assert_equal(y.count, 4) run(1*ms) assert_equal(magic_network.t, 9*ms) assert_equal(x.count, 9) assert_equal(y.count, 5)
#Ni = br.NeuronGroup(3, '''dv/dt = (vt - vr)/period : volt (unless refractory) # period: second # fire_once: boolean''', \ # threshold='v>vt', reset='v=vr', # refractory='fire_once') #Ni.period = [1, 1, 7] * br.ms #Ni.fire_once[:] = [True] * 3 indices = np.asarray([0]) times = np.asarray([6]) * br.ms Ni = br.SpikeGeneratorGroup(3, indices=indices, times=times) #Nh = br.NeuronGroup(1, model="""dv/dt=(gtot-v)/(10*ms) : 1 # gtot : 1""") Nh = br.NeuronGroup(1, model="""v = I :1 I : 1""") S = br.Synapses(Ni, Nh, model='''tl : second alpha=exp((tl - t)/tau1) - exp((tl - t)/tau2) : 1 w : 1 I_post = w*alpha : 1 (summed) ''', pre='tl+=t - tl') S.connect('True') S.w[:, :] = '(80+rand())' S.tl[:, :] = '0*second' M = br.StateMonitor(Nh, 'v', record=True) br.run(20*br.ms) br.plot(M[0].t, M[0].v) br.show()
def simulate_brunel_network( N_Excit=5000, N_Inhib=None, N_extern=N_POISSON_INPUT, connection_probability=CONNECTION_PROBABILITY_EPSILON, w0=SYNAPTIC_WEIGHT_W0, g=RELATIVE_INHIBITORY_STRENGTH_G, synaptic_delay=SYNAPTIC_DELAY, poisson_input_rate=POISSON_INPUT_RATE, w_external=None, v_rest=V_REST, v_reset=V_RESET, firing_threshold=FIRING_THRESHOLD, membrane_time_scale=MEMBRANE_TIME_SCALE, abs_refractory_period=ABSOLUTE_REFRACTORY_PERIOD, monitored_subset_size=100, random_vm_init=False, sim_time=100.*b2.ms): """ Fully parametrized implementation of a sparsely connected network of LIF neurons (Brunel 2000) Args: N_Excit (int): Size of the excitatory popluation N_Inhib (int): optional. Size of the inhibitory population. If not set (=None), N_Inhib is set to N_excit/4. N_extern (int): optional. Number of presynaptic excitatory poisson neurons. Note: if set to a value, this number does NOT depend on N_Excit and NOT depend on connection_probability (this is different from the book and paper. Only if N_extern is set to 'None', then N_extern is computed as N_Excit*connection_probability. connection_probability (float): probability to connect to any of the (N_Excit+N_Inhib) neurons CE = connection_probability*N_Excit CI = connection_probability*N_Inhib Cexternal = N_extern w0 (float): Synaptic strength J g (float): relative importance of inhibition. J_exc = w0. J_inhib = -g*w0 synaptic_delay (Quantity): Delay between presynaptic spike and postsynaptic increase of v_m poisson_input_rate (Quantity): Poisson rate of the external population w_external (float): optional. Synaptic weight of the excitatory external poisson neurons onto all neurons in the network. Default is None, in that case w_external is set to w0, which is the standard value in the book and in the paper Brunel2000. The purpose of this parameter is to see the effect of external input in the absence of network feedback(setting w0 to 0mV and w_external>0). v_rest (Quantity): Resting potential v_reset (Quantity): Reset potential firing_threshold (Quantity): Spike threshold membrane_time_scale (Quantity): tau_m abs_refractory_period (Quantity): absolute refractory period, tau_ref monitored_subset_size (int): nr of neurons for which a VoltageMonitor is recording Vm random_vm_init (bool): if true, the membrane voltage of each neuron is initialized with a random value drawn from Uniform(v_rest, firing_threshold) sim_time (Quantity): Simulation time Returns: (rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons) PopulationRateMonitor: Rate Monitor SpikeMonitor: SpikeMonitor for ALL (N_Excit+N_Inhib) neurons StateMonitor: membrane voltage for a selected subset of neurons list: index of monitored neurons. length = monitored_subset_size """ if N_Inhib is None: N_Inhib = int(N_Excit/4) if N_extern is None: N_extern = int(N_Excit*connection_probability) if w_external is None: w_external = w0 J_excit = w0 J_inhib = -g*w0 lif_dynamics = """ dv/dt = -(v-v_rest) / membrane_time_scale : volt (unless refractory)""" network = NeuronGroup( N_Excit+N_Inhib, model=lif_dynamics, threshold="v>firing_threshold", reset="v=v_reset", refractory=abs_refractory_period, method="linear") if random_vm_init: network.v = random.uniform(v_rest/b2.mV, high=firing_threshold/b2.mV, size=(N_Excit+N_Inhib))*b2.mV else: network.v = v_rest excitatory_population = network[:N_Excit] inhibitory_population = network[N_Excit:] exc_synapses = Synapses(excitatory_population, target=network, on_pre="v += J_excit", delay=synaptic_delay) exc_synapses.connect(p=connection_probability) inhib_synapses = Synapses(inhibitory_population, target=network, on_pre="v += J_inhib", delay=synaptic_delay) inhib_synapses.connect(p=connection_probability) external_poisson_input = PoissonInput(target=network, target_var="v", N=N_extern, rate=poisson_input_rate, weight=w_external) # collect data of a subset of neurons: monitored_subset_size = min(monitored_subset_size, (N_Excit+N_Inhib)) idx_monitored_neurons = sample(range(N_Excit+N_Inhib), monitored_subset_size) rate_monitor = PopulationRateMonitor(network) # record= some_list is not supported? :-( spike_monitor = SpikeMonitor(network, record=idx_monitored_neurons) voltage_monitor = StateMonitor(network, "v", record=idx_monitored_neurons) b2.run(sim_time) return rate_monitor, spike_monitor, voltage_monitor, idx_monitored_neurons