def smooth_tracking(): group = bp.NeuGroup(cann, geometry=N, monitors=['u']) group.ST['x'] = np.linspace(z_min, z_max, group.num) group.Jxx = make_conn(group.ST['x']) dur1, dur2, dur3 = 20., 20., 20. num1 = int(dur1 / bp.profile.get_dt()) num2 = int(dur2 / bp.profile.get_dt()) num3 = int(dur3 / bp.profile.get_dt()) position = np.zeros(num1 + num2 + num3) position[num1:num1 + num2] = np.linspace(0., 12., num2) position[num1 + num2:] = 12. position = position.reshape((-1, 1)) Iext = A * np.exp(-0.25 * np.square(dist(group.ST['x'] - position) / a)) group.run(duration=dur1 + dur2 + dur3, inputs=('ST.input', Iext)) bp.visualize.animate_1D( dynamical_vars=[{ 'ys': group.mon.u, 'xs': group.ST['x'], 'legend': 'u' }, { 'ys': Iext, 'xs': group.ST['x'], 'legend': 'Iext' }], show=True, frame_step=5, frame_delay=25, # save_path='tracking.mp4' )
def template_matching(): global k k = 8.1 group = bp.NeuGroup(cann, geometry=N, monitors=['u']) group.ST['x'] = np.linspace(z_min, z_max, group.num) group.Jxx = make_conn(group.ST['x']) dur1, dur2, dur3 = 20., 50., 0. num1 = int(dur1 / bp.profile.get_dt()) num2 = int(dur2 / bp.profile.get_dt()) num3 = int(dur3 / bp.profile.get_dt()) Iext = np.zeros((num1 + num2 + num3, group.num)) Iext[:num1] = A * np.exp(-0.25 * np.square(dist(group.ST['x'] + 0.5) / a)) Iext[num1:num1 + num2] = A * np.exp(-0.25 * np.square(dist(group.ST['x'] - 0.) / a)) Iext[num1:num1 + num2] += 0.1 * A * np.random.randn(num2, group.num) group.run(duration=dur1 + dur2 + dur3, inputs=('ST.input', Iext)) bp.visualize.animate_1D( dynamical_vars=[{ 'ys': group.mon.u, 'xs': group.ST['x'], 'legend': 'u' }, { 'ys': Iext, 'xs': group.ST['x'], 'legend': 'Iext' }], show=True, frame_step=5, frame_delay=50, # save_path='decoding.mp4' )
def population_coding(): global k k = 0.1 group = bp.NeuGroup(cann, geometry=N, monitors=['u']) group.ST['x'] = np.linspace(z_min, z_max, group.num) group.Jxx = make_conn(group.ST['x']) I1 = A * np.exp(-0.25 * np.square(dist(group.ST['x'] - 0.) / a)) Iext, duration = bp.inputs.constant_current([(0., 5.), (I1, 30.), (0., 30.)]) group.run(duration=duration, inputs=('ST.input', Iext)) bp.visualize.animate_1D( dynamical_vars=[{ 'ys': group.mon.u, 'xs': group.ST['x'], 'legend': 'u' }, { 'ys': Iext, 'xs': group.ST['x'], 'legend': 'Iext' }], show=True, frame_step=5, frame_delay=50, # save_path='encoding.mp4' )
def test_input_fix(): if not cuda.is_available(): return bp.profile.set(jit=True, device='gpu') lif = define_lif() num = 100 group = bp.NeuGroup(lif, geometry=(num, )) runner = Runner(group) res = runner.get_codes_of_input([('ST.input', 1., '=', 'fix')]) assert res['input-0']['num_data'] == num assert res['input-0']['codes'][-1].endswith('ST_input_inp') print() pprint(res) print('\n' * 3) runner = Runner(group) res = runner.get_codes_of_input([('ST.input', np.random.random(100), '=', 'fix')]) assert res['input-0']['num_data'] == num assert res['input-0']['codes'][-1].endswith('ST_input_inp[cuda_i]') pprint(res)
def test_lif(num, device): print('Scale:{}, Model:LIF, Device:{}, '.format(num, device), end='') st_build = time.time() bp.profile.set(jit=True, device=device, dt=0.1, numerical_method='exponential') V_rest = -52.0 V_reset = -60.0 V_th = -50.0 neu = bpmodels.neurons.get_LIF(V_rest=V_rest, V_reset=V_reset, V_th=V_th, noise=0., mode='scalar') syn = bpmodels.synapses.get_exponential(tau_decay=2.0, mode='scalar') num_exc = int(num / 2) num_inh = int(num / 2) prob = 0.01 JE = 1 / np.sqrt(prob * num_exc) JI = 1 / np.sqrt(prob * num_inh) group = bp.NeuGroup(neu, geometry=num_exc + num_inh, monitors=['spike']) group.ST['V'] = np.random.random(num_exc + num_inh) * (V_th - V_rest) + V_rest exc_conn = bp.SynConn(syn, pre_group=group[:num_exc], post_group=group, conn=bp.connect.FixedProb(prob=prob)) exc_conn.ST['g'] = JE inh_conn = bp.SynConn(syn, pre_group=group[num_exc:], post_group=group, conn=bp.connect.FixedProb(prob=prob)) exc_conn.ST['g'] = -JI net = bp.Network(group, exc_conn, inh_conn) ed_build = time.time() st_run = time.time() net.run(duration=1000., inputs=(group, 'ST.input', 3.)) ed_run = time.time() build_time = float(ed_build - st_build) run_time = float(ed_run - st_run) print('BuildT:{:.2f}s, RunT:{:.2f}s'.format(build_time, run_time)) return run_time, build_time
def hh_compare_cpu_and_gpu(num=1000): print(f'HH, device=cpu', end=', ') bp.profile.set(jit=True, device='cpu', show_code=True) HH = define_hh() HH.mode = 'scalar' neu = bp.NeuGroup(HH, geometry=num) t0 = time.time() neu.run(duration=1000., report=True) t_cpu = time.time() - t0 print('used {:.3f} ms'.format(t_cpu)) print(f'HH, device=gpu', end=', ') bp.profile.set(jit=True, device='gpu') neu = bp.NeuGroup(HH, geometry=num) t0 = time.time() neu.run(duration=1000., report=True) t_multi_cpu = time.time() - t0 print('used {:.3f} ms'.format(t_multi_cpu)) print(f"HH model with multi-cpu speeds up {t_cpu / t_multi_cpu}") print()
def hh_compare_cpu_and_multi_cpu(num=1000, vector=True): print(f'HH, vector_based={vector}, device=cpu', end=', ') bp.profile.set(jit=True, device='cpu') HH = define_hh() HH.mode = 'vector' if vector else 'scalar' neu = bp.NeuGroup(HH, size=num) t0 = time.time() neu.run(duration=1000., report=True) t_cpu = time.time() - t0 print('used {:.3f} ms'.format(t_cpu)) print(f'HH, vector_based={vector}, device=multi-cpu', end=', ') bp.profile.set(jit=True, device='multi-cpu') neu = bp.NeuGroup(HH, size=num) t0 = time.time() neu.run(duration=1000., report=True) t_multi_cpu = time.time() - t0 print('used {:.3f} ms'.format(t_multi_cpu)) print(f"HH model with multi-cpu speeds up {t_cpu / t_multi_cpu}") print()
def test_neuron_steps(): if not cuda.is_available(): return bp.profile.set(jit=True, device='gpu') lif = define_lif() num = 100 group = bp.NeuGroup(lif, geometry=(num, )) runner = Runner(group) res = runner.step_scalar_model() pprint(res) # assert res['monitor-0']['num_data'] == num # assert res['monitor-0']['codes'][-1].endswith('ST[2, cuda_i]') # # pprint(res) print('\n' * 4)
def hh_compare_cpu_and_gpu(num=1000): print(f'HH, device=cpu', end=', ') bp.profile.set(jit=True, device='cpu', show_code=False) HH = define_hh() HH.mode = 'scalar' # neu = bp.NeuGroup(HH, geometry=num) # # t0 = time.time() # neu.run(duration=1000., report=True) # t_cpu = time.time() - t0 # print('used {:.3f} ms'.format(t_cpu)) print(f'HH, device=gpu', end=', ') bp.profile.set(jit=True, device='gpu') neu = bp.NeuGroup(HH, size=num) t0 = time.time() neu.run(duration=1000., report=True) t_multi_cpu = time.time() - t0 print('used {:.3f} ms'.format(t_multi_cpu))
def test_monitor(): if not cuda.is_available(): return bp.profile.set(jit=True, device='gpu') lif = define_lif() num = 100 group = bp.NeuGroup(lif, geometry=(num, ), monitors=['spike']) runner = Runner(group) mon, res = runner.get_codes_of_monitor([('ST.spike', None)], 1000) assert res['monitor-0']['num_data'] == num assert res['monitor-0']['codes'][-1].endswith('ST[2, cuda_i]') pprint(res) print('\n' * 4) runner = Runner(group) mon, res = runner.get_codes_of_monitor([('ST.spike', [1, 2, 4])], 1000) assert res['monitor-0']['num_data'] == 3 assert res['monitor-0']['codes'][-1].endswith('= ST[2, mon_idx]') pprint(res)
def test_input_iter(): if not cuda.is_available(): return bp.profile.set(jit=True, device='gpu') lif = define_lif() num = 100 group = bp.NeuGroup(lif, size=(num, )) runner = NumbaCPUNodeRunner(group) res = runner.get_codes_of_input([('ST.input', np.random.random(1000), '=', 'iter')]) assert res['input-0']['num_data'] == num assert res['input-0']['codes'][-1].endswith('ST_input_inp[_i]') pprint(res) print('\n' * 3) runner = NumbaCPUNodeRunner(group) res = runner.get_codes_of_input([('ST.input', np.random.random( (1000, num)), '=', 'iter')]) assert res['input-0']['num_data'] == num assert res['input-0']['codes'][-1].endswith('ST_input_inp[_i, cuda_i]') pprint(res)
import brainpy as bp import bpmodels import numpy as np import matplotlib.pyplot as plt print("version:", bp.__version__) ## set global params dt = 0.002 # update variables per <dt> ms duration = 20. # simulate duration bp.profile.set(jit=True, dt=dt, merge_steps=True, show_code=False) # define neuron type RF_neuron = bpmodels.neurons.get_ResonateandFire() # build neuron group neu = bp.NeuGroup(RF_neuron, geometry=(10, ), monitors=['x', 'V', 'spike']) neu.runner.set_schedule(['input', 'update', 'monitor', 'reset']) # create input current = bp.inputs.spike_current([0.1], bp.profile._dt, -2., duration=duration) # simulate neu.run(duration=duration, inputs=["ST.input", current], report=True) # simulate for 100 ms. Give external input = current # paint ts = neu.mon.ts fig, gs = bp.visualize.get_figure(1, 2, 4, 8)
def output(ST, post): post['input'] += ST['g'] syn = bp.SynType(name='exponential_synapse', ST=bp.types.SynState(['s', 'g', 'w']), steps=(update, output), mode='scalar') # ------- # network # ------- group = bp.NeuGroup(neu, geometry=num_exc + num_inh, monitors=['spike']) group.ST['V'] = np.random.random(num_exc + num_inh) * (V_threshld - V_rest) + V_rest exc_conn = bp.SynConn(syn, pre_group=group[:num_exc], post_group=group, conn=bp.connect.FixedProb(prob=prob)) exc_conn.ST['w'] = JE inh_conn = bp.SynConn(syn, pre_group=group[num_exc:], post_group=group, conn=bp.connect.FixedProb(prob=prob)) inh_conn.ST['w'] = -JI
def update(ST, _t): ST['y'] = int_y(ST['y'], _t, ST['x']) ST['z'] = int_z(ST['z'], _t, ST['x']) x = int_x(ST['x'], _t, ST['y'], ST['z'], ST['input']) ST['spike'] = np.logical_and(x >= Vth, ST['x'] < Vth) ST['x'] = x ST['input'] = 0. return bp.NeuType(name='Hindmarsh_Rose_model', ST=state, steps=update) neuron = get_model() # simulation group = bp.NeuGroup(neuron, 1, monitors=['x', 'y', 'z']) group.run(100., inputs=('ST.input', 1.)) bp.visualize.line_plot( group.mon.ts, group.mon.x, legend='x', ) bp.visualize.line_plot( group.mon.ts, group.mon.y, legend='y', ) bp.visualize.line_plot(group.mon.ts, group.mon.z, legend='z', show=True) # phase plane analysis analyzer = bp.PhasePortraitAnalyzer(model=neuron,
# -*- coding: utf-8 -*- import brainpy as bp import numpy as np import matplotlib.pyplot as plt import bpmodels bp.profile.set(jit=True, dt=0.02, merge_steps=True) ML = bpmodels.neurons.get_MorrisLecar(noise=1.) '''The current is constant''' neu = bp.NeuGroup(ML, geometry=(100, ), monitors=['V', 'W']) current = bp.inputs.ramp_current(90, 90, 1000, 0, 1000) neu.run(duration=1000., inputs=['ST.input', current], report=False) fig, gs = bp.visualize.get_figure(2, 2, 3, 6) fig.add_subplot(gs[0, 0]) plt.plot(neu.mon.V[:, 0], neu.mon.W[:, 0], label='V') plt.xlabel('Membrane potential (mV)') plt.ylabel('Recovery Variable') plt.title('W - V') plt.legend() fig.add_subplot(gs[0, 1]) plt.plot(neu.mon.ts, neu.mon.V[:, 0], label='V') plt.xlabel('Time (ms)') plt.ylabel('Membrane potential') plt.title('V - t') plt.legend() fig.add_subplot(gs[1, 0])
@bp.integrate def int_f(V, t, Isyn): return (-V + Isyn + 2 * np.sin(2 * np.pi * t / tau)) / tau def update(ST, _t): V = int_f(ST['V'], _t, ST['input']) spike = V >= Vth ST['spike'] = spike ST['V'] = np.where(spike, Vr, V) ST['input'] = 0. ST = bp.types.NeuState({'V': 0, 'spike': 0., 'input': 0.}) lif = bp.NeuType(name='LIF', ST=ST, steps=update) group = bp.NeuGroup(lif, geometry=2000, monitors=['spike']) inputs = np.linspace(2., 4., group.num) group.run(duration=10 * 1000., inputs=('input', inputs), report=True) idx = int(5 * 1000. / bp.profile.get_dt()) indices, times = bp.measure.raster_plot(group.mon.spike[idx:], group.mon.ts[idx:]) plt.plot((times % tau) / tau, inputs[indices], ',') plt.xlabel('Spike phase') plt.ylabel('Parameter (input)') plt.show()
def test_hh(num, device): print('Scale:{}, Model:HH, Device:{}, '.format(num, device), end='') st_build = time.time() bp.profile.set(jit=True, device=device, dt=0.1, numerical_method='exponential') num_exc = int(num * 0.8) num_inh = int(num * 0.2) num = num_exc + num_inh Cm = 200 # Membrane Capacitance [pF] gl = 10. # Leak Conductance [nS] El = -60. # Resting Potential [mV] g_Na = 20. * 1000 ENa = 50. # reversal potential (Sodium) [mV] g_Kd = 6. * 1000 # K Conductance [nS] EK = -90. # reversal potential (Potassium) [mV] VT = -63. Vt = -20. # Time constants taue = 5. # Excitatory synaptic time constant [ms] taui = 10. # Inhibitory synaptic time constant [ms] # Reversal potentials Ee = 0. # Excitatory reversal potential (mV) Ei = -80. # Inhibitory reversal potential (Potassium) [mV] # excitatory synaptic weight we = 6.0 * np.sqrt(3200) / np.sqrt( num_exc) # excitatory synaptic conductance [nS] # inhibitory synaptic weight wi = 67.0 * np.sqrt(800) / np.sqrt( num_inh) # inhibitory synaptic conductance [nS] inf = 0.05 neu_ST = bp.types.NeuState('V', 'm', 'n', 'h', 'sp', 'ge', 'gi') @bp.integrate def int_ge(ge, t): return -ge / taue @bp.integrate def int_gi(gi, t): return -gi / taui @bp.integrate def int_m(m, t, V): a = 13.0 - V + VT b = V - VT - 40.0 m_alpha = 0.32 * a / (exp(a / 4.) - 1.) m_beta = 0.28 * b / (exp(b / 5.) - 1.) dmdt = (m_alpha * (1. - m) - m_beta * m) return dmdt @bp.integrate def int_m_zeroa(m, t, V): b = V - VT - 40.0 m_alpha = 0.32 m_beta = 0.28 * b / (exp(b / 5.) - 1.) dmdt = (m_alpha * (1. - m) - m_beta * m) return dmdt @bp.integrate def int_m_zerob(m, t, V): a = 13.0 - V + VT m_alpha = 0.32 * a / (exp(a / 4.) - 1.) m_beta = 0.28 dmdt = (m_alpha * (1. - m) - m_beta * m) return dmdt @bp.integrate def int_h(h, t, V): h_alpha = 0.128 * exp((17. - V + VT) / 18.) h_beta = 4. / (1. + exp(-(V - VT - 40.) / 5.)) dhdt = (h_alpha * (1. - h) - h_beta * h) return dhdt @bp.integrate def int_n(n, t, V): c = 15. - V + VT n_alpha = 0.032 * c / (exp(c / 5.) - 1.) n_beta = .5 * exp((10. - V + VT) / 40.) dndt = (n_alpha * (1. - n) - n_beta * n) return dndt @bp.integrate def int_n_zero(n, t, V): n_alpha = 0.032 n_beta = .5 * exp((10. - V + VT) / 40.) dndt = (n_alpha * (1. - n) - n_beta * n) return dndt @bp.integrate def int_V(V, t, m, h, n, ge, gi): g_na_ = g_Na * (m * m * m) * h g_kd_ = g_Kd * (n * n * n * n) dvdt = (gl * (El - V) + ge * (Ee - V) + gi * (Ei - V) - g_na_ * (V - ENa) - g_kd_ * (V - EK)) / Cm return dvdt def neu_update(ST, _t): ST['ge'] = int_ge(ST['ge'], _t) ST['gi'] = int_gi(ST['gi'], _t) if abs(ST['V'] - (40.0 + VT)) < inf: ST['m'] = int_m_zerob(ST['m'], _t, ST['V']) elif abs(ST['V'] - (13.0 + VT)) < inf: ST['m'] = int_m_zeroa(ST['m'], _t, ST['V']) else: ST['m'] = int_m(ST['m'], _t, ST['V']) ST['h'] = int_h(ST['h'], _t, ST['V']) if abs(ST['V'] - (15.0 + VT)) > inf: ST['n'] = int_n(ST['n'], _t, ST['V']) else: ST['n'] = int_n_zero(ST['n'], _t, ST['V']) V = int_V(ST['V'], _t, ST['m'], ST['h'], ST['n'], ST['ge'], ST['gi']) sp = ST['V'] < Vt and V >= Vt ST['sp'] = sp ST['V'] = V neuron = bp.NeuType(name='CUBA-HH', ST=neu_ST, steps=neu_update, mode='scalar') requires_exc = { 'pre': bp.types.NeuState( ['sp'], help='Pre-synaptic neuron state must have "spike" item.'), 'post': bp.types.NeuState( ['ge'], help='Post-synaptic neuron state must have "V" and "input" item.') } def update_syn_exc(ST, pre, post): if pre['sp']: post['ge'] += we exc_syn = bp.SynType(name='exc_syn', ST=bp.types.SynState(), requires=requires_exc, steps=update_syn_exc, mode='scalar') requires_inh = { 'pre': bp.types.NeuState( ['sp'], help='Pre-synaptic neuron state must have "spike" item.'), 'post': bp.types.NeuState( ['gi'], help='Post-synaptic neuron state must have "V" and "input" item.') } def update_syn_inh(ST, pre, post): if pre['sp']: post['gi'] -= wi inh_syn = bp.SynType(name='inh_syn', ST=bp.types.SynState(), requires=requires_inh, steps=update_syn_inh, mode='scalar') group = bp.NeuGroup(neuron, geometry=num) group.ST['V'] = El + (np.random.randn(num_exc + num_inh) * 5. - 5.) group.ST['ge'] = (np.random.randn(num_exc + num_inh) * 1.5 + 4.) * 10. group.ST['gi'] = (np.random.randn(num_exc + num_inh) * 12. + 20.) * 10. exc_conn = bp.SynConn(exc_syn, pre_group=group[:num_exc], post_group=group, conn=bp.connect.FixedProb(prob=0.02)) inh_conn = bp.SynConn(inh_syn, pre_group=group[num_exc:], post_group=group, conn=bp.connect.FixedProb(prob=0.02)) net = bp.Network(group, exc_conn, inh_conn) ed_build = time.time() st_run = time.time() net.run(duration=1000.0) ed_run = time.time() build_time = float(ed_build - st_build) run_time = float(ed_run - st_run) print('BuildT:{:.2f}s, RunT:{:.2f}s'.format(build_time, run_time)) return run_time, build_time
import matplotlib.pyplot as plt import bpmodels print("version:", bp.__version__) ## set global params dt = 0.02 # update variables per <dt> ms duration = 100. # simulate duration bp.profile.set(jit=True, dt=dt, merge_steps=True) # define neuron type LIF_neuron = bpmodels.neurons.get_LIF() # build neuron group neu = bp.NeuGroup(LIF_neuron, geometry=(10, ), monitors=['V', 'refractory', "spike", "t_last_spike"]) neu.runner.set_schedule(['input', 'update', 'monitor', 'reset']) neu.pars['V_rest'] = np.random.randint(0, 2, size=(10, )) neu.pars['tau'] = np.random.randint(5, 10, size=(10, )) neu.pars['noise'] = 1. # simulate neu.run(duration=duration, inputs=["ST.input", 26.], report=True) # simulate for 100 ms. Give external input = 26. # paint ts = neu.mon.ts fig, gs = bp.visualize.get_figure(1, 1, 4, 8) fig.add_subplot(gs[0, 0]) plt.plot(
return bp.NeuType(name='fr_zombie_neuron', ST=ST, steps=update, mode='scalar') # set params pre_neu_num = 2 post_neu_num = 1 bp.profile.set(jit=True, dt=0.02, merge_steps=True, show_code=False) # build network fr_neu = get_fr_neu() oja_synapse = bpmodels.learning_rules.get_Oja() pre_neu = bp.NeuGroup(fr_neu, geometry=(pre_neu_num, ), monitors=['r']) post_neu = bp.NeuGroup(fr_neu, geometry=(post_neu_num, ), monitors=['r']) pre_neu.ST['r'] = 1. post_neu.ST['r'] = 1. syn = bp.SynConn(oja_synapse, pre_group=pre_neu, post_group=post_neu, conn=bp.connect.All2All(), monitors=['w']) net = bp.Network(pre_neu, syn, post_neu) # create input current_mat_in = [] current_mat_out = []
# -*- coding: utf-8 -*- import matplotlib.pyplot as plt import brainpy as bp import numpy as np import bpmodels bp.profile.set(jit=True, merge_steps=True) Izhikevich = bpmodels.neurons.get_Izhikevich(type='None') neu = bp.NeuGroup(Izhikevich, 10, monitors=['V', 'u']) neu.pars['noise'] = 0. current2 = bp.inputs.ramp_current(10, 10, 300, 0, 300) current1 = np.zeros(int(np.ceil(100 / 0.1))) current = np.append(current1, current2) neu.run(duration=400., inputs=['input', current], report=False) fig, gs = bp.visualize.get_figure(3, 1, 3, 8) fig.add_subplot(gs[0, 0]) plt.plot(neu.mon.ts, neu.mon.V[:, 0], label='V') plt.ylabel('Membrane potential') plt.xlim(-0.1, 400.1) plt.xlabel('Time (ms)') plt.legend() fig.add_subplot(gs[1, 0]) plt.plot(neu.mon.ts, current, label='Input') plt.xlim(-0.1, 400.1) plt.ylim(0, 60)
import matplotlib.pyplot as plt import brainpy as bp import numpy as np from bpmodels.neurons import get_LIF import bpmodels if __name__ == '__main__': duration = 100. dt = 0.02 bp.profile.set(jit=True, dt=dt, merge_steps=True, show_code=False) LIF_neuron = get_LIF() two_exponentials_syn = bpmodels.synapses.get_two_exponentials() # Set pre & post NeuGroup pre = bp.NeuGroup(LIF_neuron, geometry=(10, ), monitors=['V', 'input', 'spike']) pre.runner.set_schedule(['input', 'update', 'monitor', 'reset']) pre.ST['V'] = -65. post = bp.NeuGroup(LIF_neuron, geometry=(10, ), monitors=['V', 'input', 'spike']) post.runner.set_schedule(['input', 'update', 'monitor', 'reset']) pre.ST['V'] = -65. # Set synapse connection & network two_exponentials = bp.SynConn(model=two_exponentials_syn, pre_group=pre, post_group=post, conn=bp.connect.All2All(), monitors=['g'],
def run_brianpy(num_neu, duration, device='cpu'): num_inh = int(num_neu / 5) num_exc = num_neu - num_inh bp.profile.set(jit=True, device=device, dt=dt) # Parameters taum = 20 taue = 5 taui = 10 Vt = -50 Vr = -60 El = -60 Erev_exc = 0. Erev_inh = -80. I = 20. we = 0.6 # excitatory synaptic weight (voltage) wi = 6.7 # inhibitory synaptic weight ref = 5.0 neu_ST = bp.types.NeuState({ 'sp_t': -1e7, 'V': Vr, 'spike': 0., 'ge': 0., 'gi': 0. }) @bp.integrate def int_ge(ge, t): return -ge / taue @bp.integrate def int_gi(gi, t): return -gi / taui @bp.integrate def int_V(V, t, ge, gi): return (ge * (Erev_exc - V) + gi * (Erev_inh - V) + (El - V) + I) / taum def neu_update(ST, _t): ST['ge'] = int_ge(ST['ge'], _t) ST['gi'] = int_gi(ST['gi'], _t) ST['spike'] = 0. if (_t - ST['sp_t']) > ref: V = int_V(ST['V'], _t, ST['ge'], ST['gi']) ST['spike'] = 0. if V >= Vt: ST['V'] = Vr ST['spike'] = 1. ST['sp_t'] = _t else: ST['V'] = V neuron = bp.NeuType(name='COBA', ST=neu_ST, steps=neu_update, mode='scalar') def syn_update1(pre, post, pre2post): for pre_id in range(len(pre2post)): if pre['spike'][pre_id] > 0.: post_ids = pre2post[pre_id] for i in post_ids: post['ge'][i] += we exc_syn = bp.SynType('exc_syn', steps=syn_update1, ST=bp.types.SynState([]), mode='vector') def syn_update2(pre, post, pre2post): for pre_id in range(len(pre2post)): if pre['spike'][pre_id] > 0.: post_ids = pre2post[pre_id] for i in post_ids: post['gi'][i] += wi inh_syn = bp.SynType('inh_syn', steps=syn_update2, ST=bp.types.SynState([]), mode='vector') group = bp.NeuGroup(neuron, geometry=num_exc + num_inh) group.ST['V'] = np.random.randn(num_exc + num_inh) * 5. - 55. exc_conn = bp.SynConn(exc_syn, pre_group=group[:num_exc], post_group=group, conn=bp.connect.FixedProb(prob=0.02)) inh_conn = bp.SynConn(inh_syn, pre_group=group[num_exc:], post_group=group, conn=bp.connect.FixedProb(prob=0.02)) net = bp.Network(group, exc_conn, inh_conn) t0 = time.time() net.run(duration) t = time.time() - t0 print(f'BrainPy ({device}) used time {t} s.') return t
post_ids = pre2post[pre_id] post['ge'][post_ids] += we def inh_update(pre, post, pre2post): for pre_id in range(len(pre2post)): if pre['sp'][pre_id] > 0.: post_ids = pre2post[pre_id] post['gi'][post_ids] += wi exc_syn = bp.SynType('exc_syn', steps=exc_update, ST=bp.types.SynState([])) inh_syn = bp.SynType('inh_syn', steps=inh_update, ST=bp.types.SynState([])) group = bp.NeuGroup(neuron, geometry=num_exc + num_inh, monitors=['sp']) group.ST['V'] = El + (np.random.randn(num_exc + num_inh) * 5 - 5) group.ST['ge'] = (np.random.randn(num_exc + num_inh) * 1.5 + 4) * 10. / unit group.ST['gi'] = (np.random.randn(num_exc + num_inh) * 12 + 20) * 10. / unit exc_conn = bp.SynConn(exc_syn, pre_group=group[:num_exc], post_group=group, conn=bp.connect.FixedProb(prob=0.02)) inh_conn = bp.SynConn(inh_syn, pre_group=group[num_exc:], post_group=group, conn=bp.connect.FixedProb(prob=0.02)) net = bp.Network(group, exc_conn, inh_conn)
ST['r'] = g(ST['r'], ST['input']) def reset(ST): ST['input'] = 0. return bp.NeuType(name='rate', steps=[update, reset], ST=ST, mode='vector') w_max = 2. bp.profile.set(dt=.1) n_post = 1 neuron = rate_neuron() post = bp.NeuGroup(neuron, n_post, monitors=['r']) pre = bp.NeuGroup(neuron, 20, monitors=['r']) #mode = 'matrix' mode = 'vector' print(mode) bcm1 = get_BCM(learning_rate=0.005, w_max=w_max, mode=mode) bcm = bp.SynConn(model=bcm1, pre_group=pre, post_group=post, conn=bp.connect.All2All(), monitors=['w', 'dwdt'], delay=0) bcm.r_th = np.zeros(n_post) bcm.post_r = np.zeros(n_post)
mode = 'irregular_bursting' param = { 'quiescence': [1.0, 2.0], #a 'spiking': [3.5, 5.0], #c 'bursting': [2.5, 3.0], #d 'irregular_spiking': [2.95, 3.3], #h 'irregular_bursting': [2.8, 3.7], #g } #params of b and I_ext corresponding to different firing mode print(f"parameters is set to firing mode <{mode}>") # define neuron type HindmarshRose_neuron = bpmodels.neurons.get_HindmarshRose() # build neuron group neu = bp.NeuGroup(HindmarshRose_neuron, geometry=(10, ), monitors=['V', 'y', 'z']) neu.runner.set_schedule(['input', 'update', 'monitor', 'reset']) neu.pars['b'] = param[mode][0] # create input current, pos_dur = bp.inputs.constant_current([(param[mode][1], 1000.)]) # simulate neu.run(duration=pos_dur, inputs=["ST.input", current], report=True) # paint ts = neu.mon.ts fig, gs = bp.visualize.get_figure(1, 1, 4, 8) fig.add_subplot(gs[0, 0]) plt.plot(ts, neu.mon.V[:, 0], label="V")
ST['u'] = int_u3(ST['u'], _t_, ST['V']) if ST['V'] >= Vth3: ST['V'] = c ST['u'] += d ST['sp_t'] = _t_ ST['sp'] = True ST['inp'] = 0. Izhikevich = bp.NeuType(name='Izhikevich', requires={'ST': state}, steps=update, vector_based=False) if __name__ == '__main__1': group = bp.NeuGroup(HH, geometry=10) runner = TrajectoryRunner(group, target_vars=['m', 'h']) print(runner.target_vars) print(runner.fixed_vars) def get_trajectories( model: NeuType, target_vars: typing.Union[typing.List[str], typing.Tuple[str]], initials: typing.Union[typing.List, typing.Tuple], duration: typing.Union[int, typing.List, typing.Tuple], fixed_vars: typing.Dict = None, inputs: typing.Union[typing.List, typing.Tuple] = (), pars_update: typing.Dict = None, ):
import brainpy as bp import numpy as np import bpmodels from bpmodels.neurons import get_GeneralizedIF print("version:", bp.__version__) ## set global params dt = 0.02 # update variables per <dt> ms duration = 200. # simulate duration bp.profile.set(jit=True, dt=dt, merge_steps=True) # define neuron type GIF_neuron = get_GeneralizedIF(noise=1.) # build neuron group neu = bp.NeuGroup(GIF_neuron, geometry=(10, ), monitors=['V', 'V_th', 'input']) neu.runner.set_schedule(['input', 'update', 'monitor', 'reset']) # simulate mode = "hyperpolarization_induced_bursting" print(f"Choose parameters fit for <{mode}> mode") if mode == 'tonic_spiking': neu.run(duration=duration, inputs=["ST.input", 1.5], report=True) elif mode == "class_1": neu.run(duration=500., inputs=["ST.input", 1. + 1e-6], report=True) elif mode == "spike_frequency_adaptation": neu.pars['a'] = 0.005 neu.run(duration=duration, inputs=["ST.input", 2.], report=True) elif mode == "phasic_spiking": neu.pars['a'] = 0.005 neu.run(duration=500., inputs=["ST.input", 1.5], report=True)
ST['u'] = int_u3(ST['u'], _t_, ST['V']) if ST['V'] >= Vth3: ST['V'] = c ST['u'] += d ST['sp_t'] = _t_ ST['sp'] = True ST['inp'] = 0. Izhikevich = bp.NeuType(name='Izhikevich', requires={'ST': state}, steps=update, vector_based=False) if __name__ == '__main__1': group = bp.NeuGroup(HH, size=10) runner = TrajectoryNumbaRunner(group, target_vars=['m', 'h']) print(runner.target_vars) print(runner.fixed_vars) def get_trajectories( model: NeuType, target_vars: typing.Union[typing.List[str], typing.Tuple[str]], initials: typing.Union[typing.List, typing.Tuple], duration: typing.Union[int, typing.List, typing.Tuple], fixed_vars: typing.Dict = None, inputs: typing.Union[typing.List, typing.Tuple] = (), pars_update: typing.Dict = None, ):
def inh_update(pre, post, pre2post): for pre_id in range(len(pre2post)): if pre['sp'][pre_id] > 0.: post_ids = pre2post[pre_id] # post['gi'][post_ids] += wi for p_id in post_ids: post['gi'][p_id] += wi exc_syn = bp.SynType('exc_syn', steps=exc_update, ST=bp.types.SynState()) inh_syn = bp.SynType('inh_syn', steps=inh_update, ST=bp.types.SynState()) group = bp.NeuGroup(neuron, size=num_exc + num_inh, monitors=['sp']) group.ST['V'] = El + (np.random.randn(num_exc + num_inh) * 5 - 5) group.ST['ge'] = (np.random.randn(num_exc + num_inh) * 1.5 + 4) * 10. group.ST['gi'] = (np.random.randn(num_exc + num_inh) * 12 + 20) * 10. exc_conn = bp.TwoEndConn(exc_syn, pre=group[:num_exc], post=group, conn=bp.connect.FixedProb(prob=0.02)) inh_conn = bp.TwoEndConn(inh_syn, pre=group[num_exc:], post=group, conn=bp.connect.FixedProb(prob=0.02)) net = bp.Network(group, exc_conn, inh_conn)
import brainpy as bp import bpmodels import numpy as np import matplotlib.pyplot as plt print("version:", bp.__version__) ## set global params dt = 0.125 # update variables per <dt> ms duration = 350. # simulate duration bp.profile.set(jit=True, dt=dt, merge_steps=True, show_code=False) # define neuron type Exp_LIF_neuron = bpmodels.neurons.get_ExpIF(noise=1.) # build neuron group neu = bp.NeuGroup(Exp_LIF_neuron, geometry=(10, ), monitors=['V']) neu.runner.set_schedule(['input', 'update', 'monitor', 'reset']) neu.pars['V_rest'] = np.random.randint(-65, -63, size=(10, )) neu.pars['tau'] = np.random.randint(5, 10, size=(10, )) # create input current, pos_dur = bp.inputs.constant_current([(0.30, duration)]) # simulate neu.run(duration=pos_dur, inputs=["ST.input", current], report=True) # simulate for 100 ms. Give external input = current # paint ts = neu.mon.ts fig, gs = bp.visualize.get_figure(1, 1, 4, 8) fig.add_subplot(gs[0, 0])