예제 #1
0
def run_stdp(NE,NI,v_init,C_e,C_ii,C_ie,mon_bin,dt):
    from brian.neurongroup import NeuronGroup
    from brian.monitor import PopulationRateMonitor
    from brian.stdunits import mV, ms, nS, pF, pA, Hz
    from brian.units import second
    from brian.equations import Equations
    from brian.network import Network
    from brian.connections import Connection
    from brian.stdp import STDP
    from brian.clock import Clock

    runtime = 10*second
   
    eta = 1e-2          # Learning rate
    tau_stdp = 20*ms    # STDP time constant
    alpha = 3*Hz*tau_stdp*2  # Target rate parameter
    gmax = 100               # Maximum inhibitory weight

    eqs_neurons='''
    dv/dt=(-gl*(v-el)-(g_ampa*w*v+g_gaba*(v-er)*w)+bgcurrent)/memc : volt
    dg_ampa/dt = -g_ampa/tau_ampa : 1
    dg_gaba/dt = -g_gaba/tau_gaba : 1
    '''
    namespace = {'tau_ampa':5.0*ms,'tau_gaba':10.0*ms,
                 'bgcurrent':200*pA,'memc':200.0*pF,
                 'el':-60*mV,'w':1.*nS,'gl':10.0*nS,'er':-80*mV}
    eqs_neurons = Equations(eqs_neurons, ** namespace)

    clock = Clock(dt)
    neurons=NeuronGroup(NE+NI,model=eqs_neurons,clock=clock,
                        threshold=-50.*mV,reset=-60*mV,refractory=5*ms)
    neurons.v = v_init
    Pe=neurons.subgroup(NE)
    Pi=neurons.subgroup(NI)
    rme = PopulationRateMonitor(Pe,mon_bin)
    rmi = PopulationRateMonitor(Pi,mon_bin)
   
    con_e = Connection(Pe,neurons,'g_ampa')
    con_ie = Connection(Pi,Pe,'g_gaba')
    con_ii = Connection(Pi,Pi,'g_gaba')
    con_e.connect_from_sparse(C_e, column_access=True)
    con_ie.connect_from_sparse(C_ie, column_access=True)
    con_ii.connect_from_sparse(C_ii, column_access=True)

    eqs_istdp = '''
    dA_pre/dt=-A_pre/tau_stdp : 1
    dA_post/dt=-A_post/tau_stdp : 1
    '''
    stdp_params = {'tau_stdp':tau_stdp, 'eta':eta, 'alpha':alpha}
    eqs_istdp = Equations(eqs_istdp, **stdp_params)
    stdp_ie = STDP(con_ie, eqs=eqs_istdp,
                   pre='''A_pre+=1.
                          w+=(A_post-alpha)*eta''',
                   post='''A_post+=1.
                           w+=A_pre*eta''',
                   wmax=gmax)
   
    net = Network(neurons, con_e, con_ie, con_ii, stdp_ie, rme, rmi)
    net.run(runtime,report='text')
    return (rme.times,rme.rate), (rmi.times,rmi.rate)
예제 #2
0
def test_voxel():

    voxel_params = default_params
    #    voxel_params.e_base=.7
    #    voxel_params.tau_o=2.7*second
    #    voxel_params.tau_s=0.95
    voxel = Voxel(params=voxel_params)
    voxel.G_base = 0.01 * nS
    voxel_monitor = MultiStateMonitor(
        voxel,
        vars=['G_total', 's', 'f_in', 'v', 'f_out', 'q', 'y'],
        record=True)

    @network_operation(when='start')
    def get_input():
        if 5 * second < defaultclock.t < 5.05 * second:
            voxel.G_total = 1 * nS
        else:
            voxel.G_total = voxel.G_base

    net = Network(voxel, get_input, voxel_monitor)
    reinit_default_clock()
    net.run(15 * second)

    voxel_params = zheng_params
    #voxel_params.e_base=.7
    #voxel_params.tau_o=2.7*second
    #voxel_params.tau_s=0.95
    new_voxel = ZhengVoxel(params=voxel_params)
    new_voxel.G_base = 0.01 * nS
    new_voxel_monitor = MultiStateMonitor(new_voxel,
                                          vars=[
                                              'G_total', 's', 'f_in', 'v',
                                              'f_out', 'q', 'y', 'g', 'cmr_o',
                                              'o_e', 'cb'
                                          ],
                                          record=True)

    @network_operation(when='start')
    def get_new_input():
        if 5 * second < defaultclock.t < 5.05 * second:
            new_voxel.G_total = 1 * nS
        else:
            new_voxel.G_total = new_voxel.G_base

    @network_operation()
    def compute_cmro():
        #print('phi=%.3f, f_in=%.3f, o_e=%.3f, o_elog=%.3f, c_ab=%.3f, cb=%.3f, cmr_o=%.3f, g=%.3f' %
        #      (new_voxel.phi, new_voxel.f_in, new_voxel.o_e, new_voxel.oe_log, new_voxel.c_ab, new_voxel.cb, new_voxel.cmr_o, new_voxel.g))
        #new_voxel.cmr_o=(new_voxel.cb-new_voxel.g*new_voxel.params.c_ab)/(new_voxel.params.cb_0-new_voxel.params.g_0*new_voxel.params.c_ab)
        new_voxel.oe_log = np.log(1.0 - new_voxel.o_e / (1.0 - new_voxel.g))

    new_net = Network(new_voxel, get_new_input, compute_cmro,
                      new_voxel_monitor)
    reinit_default_clock()
    new_net.run(15 * second)

    plot_results(voxel_monitor, new_voxel_monitor)
예제 #3
0
def test_max_delay():
    '''Test that changing delays after compression works. '''
    
    reinit_default_clock()
    inp = SpikeGeneratorGroup(1, [(0, 1*ms)])
    G = NeuronGroup(1, model='v:1')
    mon = StateMonitor(G, 'v', record=True)
    
    # one synapse
    syn = Synapses(inp, G, model='w:1', pre='v+=w', max_delay=5*ms)
    
    syn[:, :] = 1
    syn.w[:, :] = 1
    syn.delay[:, :] = 0 * ms
    
    net = Network(inp, G, syn, mon)    
    net.run(defaultclock.dt)
    syn.delay[:, :] = 5 * ms    
    net.run(6.5*ms)
    
    # spike should arrive at 5 + 1 ms    
    assert (mon[0][mon.times >= 6 * ms] == 1).all() 
    assert (mon[0][mon.times < 6 * ms] == 0).all()
    
    # same as above but with two synapses
    reinit_default_clock()
    mon.reinit()
    G.reinit()
    
    syn = Synapses(inp, G, model='w:1', pre='v+=w', max_delay=5*ms)
    
    syn[:, :] = 2
    syn.w[:, :] = 1
    syn.delay[:, :] = [0 * ms, 0 * ms]
    
    net = Network(inp, G, syn, mon)    
    net.run(defaultclock.dt)
    syn.delay[:, :] = [5 * ms, 5 * ms]
    net.run(6.5*ms)
    
    # spike should arrive at 5 + 1 ms
    assert (mon[0][mon.times >= 6 * ms] == 2).all()
    assert (mon[0][mon.times < 6 * ms] == 0).all()    
예제 #4
0
    def _prepare_brian_net(self, stimulus):
        from brian.directcontrol import SpikeGeneratorGroup
        from brian.synapses.synapses import Synapses
        from brian.network import Network
        self.S = []
        netobjs, M_EIP, MV_EIP = ibm.create_netobjs(stimulus,
                                                    global_sympy_params.cur)

        if len(stimulus) > 0:
            N = max(stimulus[:, 0]) + 1
            In1 = SpikeGeneratorGroup(N, stimulus[stimulus[:, 0] < N])
            self.S.append(In1)
        #Create connections, if any
        if len(global_mappings_list) > 0:
            gml = np.array(global_mappings_list).reshape(-1, 3)
            for syn_idx in range(4):

                gml_dict, pgml_dict = _dlist_to_mappingdict(
                    _decode_mappings_list(gml, syn_idx))
                if len(gml_dict) > 0:
                    if len(stimulus) == 0:
                        input_pop = PoissonGroup(max(gml_dict.keys()) + 1, 0)
                    else:
                        input_pop = In1
                    iname, wname = synapse_trans_dict[syn_idx]
                    EIP = netobjs['EIP']
                    S = Synapses(input_pop,
                                 EIP,
                                 model="""w : 1
                                                p : 1""",
                                 pre=iname + "+=w*(rand()<p)")

                    for i in gml_dict:
                        S[i, gml_dict[i]] = True
                        S.w[i, gml_dict[i]] = global_sympy_params.cur[
                            wname] * np.random.normal(1, ibm.sigma_mismatch,
                                                      len(gml_dict[i]))
                        S.p[i, gml_dict[i]] = pgml_dict[i]

                    self.S.append(S)

        net = Network(netobjs.values() + self.S)

        return net, M_EIP, MV_EIP
예제 #5
0
def test_voxel():

    voxel_params=default_params
#    voxel_params.e_base=.7
#    voxel_params.tau_o=2.7*second
#    voxel_params.tau_s=0.95
    voxel=Voxel(params=voxel_params)
    voxel.G_base=0.01*nS
    voxel_monitor = MultiStateMonitor(voxel, vars=['G_total','s','f_in','v','f_out','q','y'], record=True)

    @network_operation(when='start')
    def get_input():
        if 5*second < defaultclock.t < 5.05*second:
            voxel.G_total=1*nS
        else:
            voxel.G_total=voxel.G_base

    net=Network(voxel, get_input, voxel_monitor)
    reinit_default_clock()
    net.run(15*second)

    voxel_params=zheng_params
    #voxel_params.e_base=.7
    #voxel_params.tau_o=2.7*second
    #voxel_params.tau_s=0.95
    new_voxel=ZhengVoxel(params=voxel_params)
    new_voxel.G_base=0.01*nS
    new_voxel_monitor = MultiStateMonitor(new_voxel, vars=['G_total','s','f_in','v','f_out','q','y','g','cmr_o','o_e','cb'],
        record=True)

    @network_operation(when='start')
    def get_new_input():
        if 5*second < defaultclock.t < 5.05*second:
            new_voxel.G_total=1*nS
        else:
            new_voxel.G_total=new_voxel.G_base

    @network_operation()
    def compute_cmro():
        #print('phi=%.3f, f_in=%.3f, o_e=%.3f, o_elog=%.3f, c_ab=%.3f, cb=%.3f, cmr_o=%.3f, g=%.3f' %
        #      (new_voxel.phi, new_voxel.f_in, new_voxel.o_e, new_voxel.oe_log, new_voxel.c_ab, new_voxel.cb, new_voxel.cmr_o, new_voxel.g))
        #new_voxel.cmr_o=(new_voxel.cb-new_voxel.g*new_voxel.params.c_ab)/(new_voxel.params.cb_0-new_voxel.params.g_0*new_voxel.params.c_ab)
        new_voxel.oe_log=np.log(1.0-new_voxel.o_e/(1.0-new_voxel.g))

    new_net=Network(new_voxel, get_new_input, compute_cmro, new_voxel_monitor)
    reinit_default_clock()
    new_net.run(15*second)

    plot_results(voxel_monitor, new_voxel_monitor)
예제 #6
0
        'M_EIP': M_EIP,
        'MV_EIP': MV_EIP
    }

    return netobjs, M_EIP, MV_EIP

if __name__ == '__main__':
    from pylab import *
    from brian.plotting import raster_plot
    ion()
    from paramTranslation import params, loadBiases
    from expSetup import *
    configurator = pyNCS.ConfAPI.Configurator()
    configurator._readCSV('chipfiles/ifslwta.csv')
    configurator.set_parameters(loadBiases('biases/defaultBiases_ifslwta'))
    p = params(configurator, 'chipfiles/ifslwta_paramtrans.xml')
    p.translate('pinj', 2.8)
    p.translate('nsynloclat1', 0.55)
    p.translate('nsynloclat2', 0.53)
    p.translate('nsynexcinh', 0.45)
    p.translate('psynlocinhw', 2.75)
    p.translate('psynlocinhth', .3)
    stim = np.transpose([
        np.random.randint(0, 128, 32000),
        np.cumsum(np.random.random(32000) / 16)
    ])
    netobjs, M_EIP, MV_EIP = create_netobjs(stim, p.cur)
    net = Network(netobjs.values())
    net.run(1)
    raster_plot(*[M_EIP])
def run_wta(wta_params, input_freq, sim_params, pyr_params=pyr_params(), inh_params=inh_params(),
            output_file=None, save_summary_only=False, record_neuron_state=False, record_spikes=True, record_firing_rate=True,
            record_inputs=False, plot_output=False, report='text'):
    """
    Run WTA network
       wta_params = network parameters
       input_freq = mean firing rate of each input group
       output_file = output file to write to
       save_summary_only = whether or not to save all data or just summary data to file
       record_lfp = record LFP data if true
       record_voxel = record voxel data if true
       record_neuron_state = record neuron state data if true
       record_spikes = record spike data if true
       record_firing_rate = record network firing rates if true
       record_inputs = record input firing rates if true
       plot_output = plot outputs if true
    """

    start_time = time()

    simulation_clock=Clock(dt=sim_params.dt)
    input_update_clock=Clock(dt=1/(wta_params.refresh_rate/Hz)*second)

    background_input=PoissonGroup(wta_params.background_input_size, rates=wta_params.background_freq,
        clock=simulation_clock)
    task_inputs=[]
    for i in range(wta_params.num_groups):
        task_inputs.append(PoissonGroup(wta_params.task_input_size, rates=wta_params.task_input_resting_rate,
                                        clock=simulation_clock))

    # Create WTA network
    wta_network=WTANetworkGroup(params=wta_params, background_input=background_input, task_inputs=task_inputs,
        pyr_params=pyr_params, inh_params=inh_params, clock=simulation_clock)

    @network_operation(when='start', clock=input_update_clock)
    def set_task_inputs():
        for idx in range(len(task_inputs)):
            rate=wta_params.task_input_resting_rate
            if sim_params.stim_start_time<=simulation_clock.t<sim_params.stim_end_time:
                rate=input_freq[idx]*Hz+np.random.randn()*wta_params.input_var
                if rate<wta_params.task_input_resting_rate:
                    rate=wta_params.task_input_resting_rate
            task_inputs[idx]._S[0, :]=rate

    @network_operation(clock=simulation_clock)
    def inject_current():
        if simulation_clock.t>sim_params.dcs_start_time:
            wta_network.group_e.I_dcs=sim_params.p_dcs
            wta_network.group_i.I_dcs=sim_params.i_dcs

    # Create network monitor
    wta_monitor=WTAMonitor(wta_network, sim_params, record_neuron_state=record_neuron_state, record_spikes=record_spikes,
                           record_firing_rate=record_firing_rate, record_inputs=record_inputs,
                           save_summary_only=save_summary_only, clock=simulation_clock)

    # Create Brian network and reset clock
    net=Network(background_input, task_inputs,set_task_inputs, wta_network, wta_network.connections.values(),
                wta_monitor.monitors.values(), inject_current)
    print "Initialization time: %.2fs" % (time() - start_time)

    # Run simulation
    start_time = time()
    net.run(sim_params.trial_duration, report=report)
    print "Simulation time: %.2fs" % (time() - start_time)

    # Write output to file
    if output_file is not None:
        start_time = time()
        wta_monitor.write_output(input_freq, output_file)
        print 'Wrote output to %s' % output_file
        print "Write output time: %.2fs" % (time() - start_time)

    # Plot outputs
    if plot_output:
        wta_monitor.plot()

    return wta_monitor
예제 #8
0
def run_wta(wta_params,
            input_freq,
            sim_params,
            pyr_params=pyr_params(),
            inh_params=inh_params(),
            plasticity_params=plasticity_params(),
            output_file=None,
            save_summary_only=False,
            record_lfp=True,
            record_voxel=True,
            record_neuron_state=False,
            record_spikes=True,
            record_firing_rate=True,
            record_inputs=False,
            record_connections=None,
            plot_output=False,
            report='text'):
    """
    Run WTA network
       wta_params = network parameters
       input_freq = mean firing rate of each input group
       output_file = output file to write to
       save_summary_only = whether or not to save all data or just summary data to file
       record_lfp = record LFP data if true
       record_voxel = record voxel data if true
       record_neuron_state = record neuron state data if true
       record_spikes = record spike data if true
       record_firing_rate = record network firing rates if true
       record_inputs = record input firing rates if true
       plot_output = plot outputs if true
    """

    start_time = time()

    simulation_clock = Clock(dt=sim_params.dt)
    input_update_clock = Clock(dt=1 / (wta_params.refresh_rate / Hz) * second)

    background_input = PoissonGroup(wta_params.background_input_size,
                                    rates=wta_params.background_freq,
                                    clock=simulation_clock)
    task_inputs = []
    for i in range(wta_params.num_groups):
        task_inputs.append(
            PoissonGroup(wta_params.task_input_size,
                         rates=wta_params.task_input_resting_rate,
                         clock=simulation_clock))

    # Create WTA network
    wta_network = WTANetworkGroup(params=wta_params,
                                  background_input=background_input,
                                  task_inputs=task_inputs,
                                  pyr_params=pyr_params,
                                  inh_params=inh_params,
                                  plasticity_params=plasticity_params,
                                  clock=simulation_clock)

    @network_operation(when='start', clock=input_update_clock)
    def set_task_inputs():
        for idx in range(len(task_inputs)):
            rate = wta_params.task_input_resting_rate
            if sim_params.stim_start_time <= simulation_clock.t < sim_params.stim_end_time:
                rate = input_freq[idx] * Hz + np.random.randn(
                ) * wta_params.input_var
                if rate < wta_params.task_input_resting_rate:
                    rate = wta_params.task_input_resting_rate
            task_inputs[idx]._S[0, :] = rate

    @network_operation(clock=simulation_clock)
    def inject_current():
        if simulation_clock.t > sim_params.dcs_start_time:
            wta_network.group_e.I_dcs = sim_params.p_dcs
            wta_network.group_i.I_dcs = sim_params.i_dcs

    # LFP source
    lfp_source = LFPSource(wta_network.group_e, clock=simulation_clock)

    # Create voxel
    voxel = Voxel(simulation_clock, network=wta_network)

    # Create network monitor
    wta_monitor = WTAMonitor(wta_network,
                             lfp_source,
                             voxel,
                             sim_params,
                             record_lfp=record_lfp,
                             record_voxel=record_voxel,
                             record_neuron_state=record_neuron_state,
                             record_spikes=record_spikes,
                             record_firing_rate=record_firing_rate,
                             record_inputs=record_inputs,
                             record_connections=record_connections,
                             save_summary_only=save_summary_only,
                             clock=simulation_clock)

    @network_operation(when='start', clock=simulation_clock)
    def inject_muscimol():
        if sim_params.muscimol_amount > 0:
            wta_network.groups_e[
                sim_params.
                injection_site].g_muscimol = sim_params.muscimol_amount

    # Create Brian network and reset clock
    net = Network(background_input, task_inputs, set_task_inputs, wta_network,
                  lfp_source, voxel, wta_network.connections.values(),
                  wta_monitor.monitors.values(), inject_muscimol,
                  inject_current)
    if sim_params.plasticity:
        net.add(wta_network.stdp.values())
    print "Initialization time: %.2fs" % (time() - start_time)

    #    writer=LaTeXDocumentWriter()
    #    labels={}
    #    labels[voxel]=('v',str(voxel))
    #    labels[background_input]=('bi',str(background_input))
    #    labels[lfp_source]=('lfp',str(lfp_source))
    #    labels[wta_network]=('n',str(wta_network))
    #    labels[wta_network.group_e]=('e',str(wta_network.group_e))
    #    labels[wta_network.group_i]=('i',str(wta_network.group_i))
    #    for i,e_group in enumerate(wta_network.groups_e):
    #        labels[e_group]=('e%d' % i,'%s %d' % (str(e_group),i))
    #    for i,task_input in enumerate(task_inputs):
    #        labels[task_input]=('t%d' % i,'%s %d' % (str(task_input),i))
    #    for name,conn in wta_network.connections.iteritems():
    #        labels[conn]=(name,str(conn))
    #    for name,monitor in wta_monitor.monitors.iteritems():
    #        labels[monitor]=(name,str(monitor))
    #    writer.document_network(net=net, labels=labels)

    # Run simulation
    start_time = time()
    net.run(sim_params.trial_duration, report=report)
    print "Simulation time: %.2fs" % (time() - start_time)

    # Compute BOLD signal
    if record_voxel:
        start_time = time()
        wta_monitor.monitors['voxel_exc'] = get_bold_signal(
            wta_monitor.monitors['voxel']['G_total_exc'].values[0],
            voxel.params, [500, 2500], sim_params.trial_duration)
        wta_monitor.monitors['voxel'] = get_bold_signal(
            wta_monitor.monitors['voxel']['G_total'].values[0], voxel.params,
            [500, 2500], sim_params.trial_duration)
        print "BOLD generation time: %.2fs" % (time() - start_time)

    # Write output to file
    if output_file is not None:
        start_time = time()
        wta_monitor.write_output(input_freq, output_file)
        print 'Wrote output to %s' % output_file
        print "Write output time: %.2fs" % (time() - start_time)

    # Plot outputs
    if plot_output:
        wta_monitor.plot()

    return wta_monitor
                   'MV_EIP': MV_EIP}
                   
    return netobjs, M_EIP, MV_EIP
    


if __name__ == '__main__':
    from pylab import *
    from brian.plotting import raster_plot
    ion()
    from paramTranslation import params, loadBiases
    from expSetup import *
    configurator = pyNCS.ConfAPI.Configurator()
    configurator._readCSV('chipfiles/ifslwta.csv')
    configurator.set_parameters(loadBiases('biases/defaultBiases_ifslwta'))
    p=params(configurator, 'chipfiles/ifslwta_paramtrans.xml')
    p.translate('pinj',2.8)    
    p.translate('nsynloclat1',0.55)
    p.translate('nsynloclat2',0.53)
    p.translate('nsynexcinh',0.45)   
    p.translate('psynlocinhw',2.75)
    p.translate('psynlocinhth',.3)
    stim = np.transpose([np.random.randint(0,128,32000), np.cumsum(np.random.random(32000)/16)])
    netobjs,  M_EIP, MV_EIP  = create_netobjs(stim,p.cur)
    net = Network(netobjs.values())
    net.run(1)
    raster_plot(*[M_EIP])
    


예제 #10
0
#    sys.exit()
lif_group.V = Vrest
lif_conn = Connection(lif_group, lif_group, 'V', delay=10*msecond)
netw_size = len(lif_group)
n_layers = 10
for layer in range(1, n_layers):
    prev_start = netw_size/n_layers*(layer-1)
    cur_start = netw_size/n_layers*layer
    cur_end = netw_size/n_layers*(layer+1)
    lif_conn[prev_start:cur_start, cur_start:cur_end] = w_int

print("Setting up monitors ...")
trace_mon = StateMonitor(lif_group, "V", record=True)
input_mon = SpikeMonitor(inp_group)
spike_mon = SpikeMonitor(lif_group)
network = Network(lif_group, inp_group, inp_conn, lif_conn,
                  trace_mon, spike_mon, input_mon)
print("Running for %f seconds ..." % (duration))
network.run(duration)
print("Simulation run finished.")
if spike_mon.nspikes == 0:
    print("No spikes were fired by the network. Aborting!")
    sys.exit()
print("Performing Gaussian convolution ...")
t, conv_spikes = sl.tools.spikeconvolve(spike_mon, 5*msecond)
figure("Spike trains")
splt = subplot(311)
title("External inputs")
raster_plot(input_mon)
axis(xmin=0, xmax=duration/msecond)
subplot(312)
title("Network spikes")
예제 #11
0
def test_construction_single_synapses():
    '''
    Test the construction of synapses with a single synapse per connection.
    '''
    G = NeuronGroup(20, model='v:1', threshold=NoThreshold())
    
    # specifying only one group should use it as source and target
    syn = Synapses(G, model='w:1')
    assert syn.source is syn.target

    # specifying source and target with subgroups
    subgroup1, subgroup2 = G[:10], G[10:]
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')    
    assert syn.source is subgroup1
    assert syn.target is subgroup2

    # create all-to-all connections
    syn[:, :] = True
    assert len(syn) == 10 * 10
    
    # deleting a synapse should not work
    def delete_synapse():
        syn[0, 0] = False
    assert_raises(ValueError, delete_synapse)
    
    # set the weights
    syn.w[:, :] = 2
    # set the delays
    syn.delay[:, :] = 1 * ms

    all_weights = np.array([syn.w[i, j] for i in xrange(len(subgroup1))
                         for j in xrange(len(subgroup2))])
    assert (all_weights == 2).all()
    all_delays = np.array([syn.delay[i, j] for i in xrange(len(subgroup1))
                         for j in xrange(len(subgroup2))])
    assert (all_delays == 1 * ms).all()
    
    # create one-to-one connections
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[:, :] = 'i == j'
    syn.w[:, :] = 2
    assert len(syn) == len(subgroup1)
    for i in xrange(len(subgroup1)):
        for j in xrange(len(subgroup2)):
            if i == j:
                assert syn.w[i, j] == 2
            else:                
                assert len(syn.w[i, j]) == 0
    
    net = Network(G, syn)
    net.run(defaultclock.dt)
    # adding synapses should not work after the simulation has already been run
    def adding_a_synapse():
        syn[0, 1] = True
    assert_raises(AttributeError, adding_a_synapse)
    
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one(subgroup1, subgroup2)
    syn.w[:, :] = 2
    assert len(syn) == len(subgroup1)
    for i in xrange(len(subgroup1)):
        for j in xrange(len(subgroup2)):
            if i == j:
                assert syn.w[i, j] == 2
            else:                
                assert len(syn.w[i, j]) == 0

    # Calling connect_one_to_one without specifying groups should use the full
    # source or target group
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one(subgroup1)
    assert len(syn) == len(subgroup1)

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one(post=subgroup2)
    assert len(syn) == len(subgroup1)

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one()
    assert len(syn) == len(subgroup1)

    # connect_one_to_one should only work with subgroups of the same size
    assert_raises(TypeError, lambda : syn.connect_one_to_one(G[:2], G[:1]))

    # create random connections
    # the only two cases that can be tested exactly are 0 and 100% connection
    # probability
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    # floats are interpreted as connection probabilities
    syn[:, :] = 0.0    
    assert len(syn) == 0
    
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, subgroup2, 0.0)    
    assert len(syn) == 0
    
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[:, :] = 1.0
    assert len(syn) == 10 * 10
    # set the weights
    syn.w[:, :] = 2
    # set the delays
    syn.delay[:, :] = 1 * ms

    all_weights = np.array([syn.w[i, j] for i in xrange(len(subgroup1))
                         for j in xrange(len(subgroup2))])
    assert (all_weights == 2).all()
    all_delays = np.array([syn.delay[i, j] for i in xrange(len(subgroup1))
                         for j in xrange(len(subgroup2))])
    assert (all_delays == 1 * ms).all()
    
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, subgroup2, 1.0)
    assert len(syn) == 10 * 10
    # set the weights
    syn.w[:, :] = 2
    # set the delays
    syn.delay[:, :] = 1 * ms

    all_weights = np.array([syn.w[i, j] for i in xrange(len(subgroup1))
                         for j in xrange(len(subgroup2))])
    assert (all_weights == 2).all()
    all_delays = np.array([syn.delay[i, j] for i in xrange(len(subgroup1))
                         for j in xrange(len(subgroup2))])
    assert (all_delays == 1 * ms).all()

    # Calling connect_random without specifying groups should use the full
    # source or target group
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, sparseness=1.0)
    assert len(syn) == 10 * 10

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(post=subgroup2, sparseness=1.0)
    assert len(syn) == 10 * 10

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(sparseness=1.0)
    assert len(syn) == 10 * 10

    # Just test that probabilities between zero and one work at all
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, subgroup2, 0.3)
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[:, :] = 0.3
    
    # Test that probabilities outside of the legal range raise an error
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    assert_raises(ValueError,
                  lambda : syn.connect_random(subgroup1, subgroup2, 1.3))
    assert_raises(ValueError,
                  lambda : syn.connect_random(subgroup1, subgroup2, -.3))
    def wrong_probability():
        syn[:, :] = -0.3        
    assert_raises(ValueError, wrong_probability)
    def wrong_probability(): #@DuplicatedSignature
        syn[:, :] = 1.3        
    assert_raises(ValueError, wrong_probability)        

    # this test requires python 2.6
    if sys.version_info[0] >= 2 and sys.version_info[1] >=6:
        # Running a model with a synapses object with 0 synapses should raise a warning
        syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            # Trigger a warning.
            syn.compress()
            # Verify some things
            assert len(w) == 1
    
    # use arrays as neuron indices instead of slices or ints
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[np.arange(5), np.arange(5)] = True
    syn.w[np.arange(5), np.arange(5)] = 2
    syn.delay[np.arange(5), np.arange(5)] = 5 * ms
    assert len(syn) == 5 * 5
    assert all([syn.w[i, j] == 2 for i in xrange(5) for j in xrange(5)])
    assert all([syn.delay[i, j] == 5 * ms for i in xrange(5) for j in xrange(5)])
    assert all([len(syn.w[i, j]) == 0 for i in xrange(5, len(subgroup1))
                for j in xrange(5, len(subgroup2))])
    assert all([len(syn.delay[i, j]) == 0 for i in xrange(5, len(subgroup1))
                for j in xrange(5, len(subgroup2))])
    
    # Create a synapse without a model (e.g. a simple connection with constant
    # weights
    syn = Synapses(subgroup1, subgroup2, model='', pre='v+=1')
예제 #12
0
sample_length = 1 / get_samplerate(None)
cf = 1000 * Hz

print 'Testing click response'
duration = 25*ms    
levels = [40, 60, 80, 100, 120]
# a click of two samples
tones = Sound([Sound.sequence([click(sample_length*2, peak=level*dB),
                               silence(duration=duration - sample_length)])
           for level in levels])
ihc = TanCarney(MiddleEar(tones), [cf] * len(levels), update_interval=1)
syn = ZhangSynapse(ihc, cf)
s_mon = StateMonitor(syn, 's', record=True, clock=syn.clock)
R_mon = StateMonitor(syn, 'R', record=True, clock=syn.clock)
spike_mon = SpikeMonitor(syn)
net = Network(syn, s_mon, R_mon, spike_mon)
net.run(duration * 1.5)
for idx, level in enumerate(levels):
    plt.figure(1)
    plt.subplot(len(levels), 1, idx + 1)
    plt.plot(s_mon.times / ms, s_mon[idx])
    plt.xlim(0, 25)
    plt.xlabel('Time (msec)')
    plt.ylabel('Sp/sec')
    plt.text(15, np.nanmax(s_mon[idx])/2., 'Peak SPL=%s SPL' % str(level*dB));
    ymin, ymax = plt.ylim()
    if idx == 0:
        plt.title('Click responses')

    plt.figure(2)
    plt.subplot(len(levels), 1, idx + 1)
예제 #13
0
def test_max_delay():
    '''Test that changing delays after compression works. '''

    reinit_default_clock()
    inp = SpikeGeneratorGroup(1, [(0, 1 * ms)])
    G = NeuronGroup(1, model='v:1')
    mon = StateMonitor(G, 'v', record=True)

    # one synapse
    syn = Synapses(inp, G, model='w:1', pre='v+=w', max_delay=5 * ms)

    syn[:, :] = 1
    syn.w[:, :] = 1
    syn.delay[:, :] = 0 * ms

    net = Network(inp, G, syn, mon)
    net.run(defaultclock.dt)
    syn.delay[:, :] = 5 * ms
    net.run(6.5 * ms)

    # spike should arrive at 5 + 1 ms
    assert (mon[0][mon.times >= 6 * ms] == 1).all()
    assert (mon[0][mon.times < 6 * ms] == 0).all()

    # same as above but with two synapses
    reinit_default_clock()
    mon.reinit()
    G.reinit()

    syn = Synapses(inp, G, model='w:1', pre='v+=w', max_delay=5 * ms)

    syn[:, :] = 2
    syn.w[:, :] = 1
    syn.delay[:, :] = [0 * ms, 0 * ms]

    net = Network(inp, G, syn, mon)
    net.run(defaultclock.dt)
    syn.delay[:, :] = [5 * ms, 5 * ms]
    net.run(6.5 * ms)

    # spike should arrive at 5 + 1 ms
    assert (mon[0][mon.times >= 6 * ms] == 2).all()
    assert (mon[0][mon.times < 6 * ms] == 0).all()
예제 #14
0
def test_construction_single_synapses():
    '''
    Test the construction of synapses with a single synapse per connection.
    '''
    G = NeuronGroup(20, model='v:1', threshold=NoThreshold())

    # specifying only one group should use it as source and target
    syn = Synapses(G, model='w:1')
    assert syn.source is syn.target

    # specifying source and target with subgroups
    subgroup1, subgroup2 = G[:10], G[10:]
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    assert syn.source is subgroup1
    assert syn.target is subgroup2

    # create all-to-all connections
    syn[:, :] = True
    assert len(syn) == 10 * 10

    # deleting a synapse should not work
    def delete_synapse():
        syn[0, 0] = False

    assert_raises(ValueError, delete_synapse)

    # set the weights
    syn.w[:, :] = 2
    # set the delays
    syn.delay[:, :] = 1 * ms

    all_weights = np.array([
        syn.w[i, j] for i in xrange(len(subgroup1))
        for j in xrange(len(subgroup2))
    ])
    assert (all_weights == 2).all()
    all_delays = np.array([
        syn.delay[i, j] for i in xrange(len(subgroup1))
        for j in xrange(len(subgroup2))
    ])
    assert (all_delays == 1 * ms).all()

    # create one-to-one connections
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[:, :] = 'i == j'
    syn.w[:, :] = 2
    assert len(syn) == len(subgroup1)
    for i in xrange(len(subgroup1)):
        for j in xrange(len(subgroup2)):
            if i == j:
                assert syn.w[i, j] == 2
            else:
                assert len(syn.w[i, j]) == 0

    net = Network(G, syn)
    net.run(defaultclock.dt)

    # adding synapses should not work after the simulation has already been run
    def adding_a_synapse():
        syn[0, 1] = True

    assert_raises(AttributeError, adding_a_synapse)

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one(subgroup1, subgroup2)
    syn.w[:, :] = 2
    assert len(syn) == len(subgroup1)
    for i in xrange(len(subgroup1)):
        for j in xrange(len(subgroup2)):
            if i == j:
                assert syn.w[i, j] == 2
            else:
                assert len(syn.w[i, j]) == 0

    # Calling connect_one_to_one without specifying groups should use the full
    # source or target group
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one(subgroup1)
    assert len(syn) == len(subgroup1)

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one(post=subgroup2)
    assert len(syn) == len(subgroup1)

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_one_to_one()
    assert len(syn) == len(subgroup1)

    # connect_one_to_one should only work with subgroups of the same size
    assert_raises(TypeError, lambda: syn.connect_one_to_one(G[:2], G[:1]))

    # create random connections
    # the only two cases that can be tested exactly are 0 and 100% connection
    # probability
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    # floats are interpreted as connection probabilities
    syn[:, :] = 0.0
    assert len(syn) == 0

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, subgroup2, 0.0)
    assert len(syn) == 0

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[:, :] = 1.0
    assert len(syn) == 10 * 10
    # set the weights
    syn.w[:, :] = 2
    # set the delays
    syn.delay[:, :] = 1 * ms

    all_weights = np.array([
        syn.w[i, j] for i in xrange(len(subgroup1))
        for j in xrange(len(subgroup2))
    ])
    assert (all_weights == 2).all()
    all_delays = np.array([
        syn.delay[i, j] for i in xrange(len(subgroup1))
        for j in xrange(len(subgroup2))
    ])
    assert (all_delays == 1 * ms).all()

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, subgroup2, 1.0)
    assert len(syn) == 10 * 10
    # set the weights
    syn.w[:, :] = 2
    # set the delays
    syn.delay[:, :] = 1 * ms

    all_weights = np.array([
        syn.w[i, j] for i in xrange(len(subgroup1))
        for j in xrange(len(subgroup2))
    ])
    assert (all_weights == 2).all()
    all_delays = np.array([
        syn.delay[i, j] for i in xrange(len(subgroup1))
        for j in xrange(len(subgroup2))
    ])
    assert (all_delays == 1 * ms).all()

    # Calling connect_random without specifying groups should use the full
    # source or target group
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, sparseness=1.0)
    assert len(syn) == 10 * 10

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(post=subgroup2, sparseness=1.0)
    assert len(syn) == 10 * 10

    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(sparseness=1.0)
    assert len(syn) == 10 * 10

    # Just test that probabilities between zero and one work at all
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn.connect_random(subgroup1, subgroup2, 0.3)
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[:, :] = 0.3

    # Test that probabilities outside of the legal range raise an error
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    assert_raises(ValueError,
                  lambda: syn.connect_random(subgroup1, subgroup2, 1.3))
    assert_raises(ValueError,
                  lambda: syn.connect_random(subgroup1, subgroup2, -.3))

    def wrong_probability():
        syn[:, :] = -0.3

    assert_raises(ValueError, wrong_probability)

    def wrong_probability():  #@DuplicatedSignature
        syn[:, :] = 1.3

    assert_raises(ValueError, wrong_probability)

    # this test requires python 2.6
    if sys.version_info[0] >= 2 and sys.version_info[1] >= 6:
        # Running a model with a synapses object with 0 synapses should raise a warning
        syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
        with warnings.catch_warnings(record=True) as w:
            # Cause all warnings to always be triggered.
            warnings.simplefilter("always")
            # Trigger a warning.
            syn.compress()
            # Verify some things
            assert len(w) == 1

    # use arrays as neuron indices instead of slices or ints
    syn = Synapses(subgroup1, subgroup2, model='w:1', pre='v += w')
    syn[np.arange(5), np.arange(5)] = True
    syn.w[np.arange(5), np.arange(5)] = 2
    syn.delay[np.arange(5), np.arange(5)] = 5 * ms
    assert len(syn) == 5 * 5
    assert all([syn.w[i, j] == 2 for i in xrange(5) for j in xrange(5)])
    assert all(
        [syn.delay[i, j] == 5 * ms for i in xrange(5) for j in xrange(5)])
    assert all([
        len(syn.w[i, j]) == 0 for i in xrange(5, len(subgroup1))
        for j in xrange(5, len(subgroup2))
    ])
    assert all([
        len(syn.delay[i, j]) == 0 for i in xrange(5, len(subgroup1))
        for j in xrange(5, len(subgroup2))
    ])

    # Create a synapse without a model (e.g. a simple connection with constant
    # weights
    syn = Synapses(subgroup1, subgroup2, model='', pre='v+=1')
예제 #15
0
파일: network.py 프로젝트: jbonaiuto/pySBI
def run_wta(
    wta_params,
    input_freq,
    sim_params,
    pyr_params=pyr_params(),
    inh_params=inh_params(),
    plasticity_params=plasticity_params(),
    output_file=None,
    save_summary_only=False,
    record_lfp=True,
    record_voxel=True,
    record_neuron_state=False,
    record_spikes=True,
    record_firing_rate=True,
    record_inputs=False,
    record_connections=None,
    plot_output=False,
    report="text",
):
    """
    Run WTA network
       wta_params = network parameters
       input_freq = mean firing rate of each input group
       output_file = output file to write to
       save_summary_only = whether or not to save all data or just summary data to file
       record_lfp = record LFP data if true
       record_voxel = record voxel data if true
       record_neuron_state = record neuron state data if true
       record_spikes = record spike data if true
       record_firing_rate = record network firing rates if true
       record_inputs = record input firing rates if true
       plot_output = plot outputs if true
    """

    start_time = time()

    simulation_clock = Clock(dt=sim_params.dt)
    input_update_clock = Clock(dt=1 / (wta_params.refresh_rate / Hz) * second)

    background_input = PoissonGroup(
        wta_params.background_input_size, rates=wta_params.background_freq, clock=simulation_clock
    )
    task_inputs = []
    for i in range(wta_params.num_groups):
        task_inputs.append(
            PoissonGroup(wta_params.task_input_size, rates=wta_params.task_input_resting_rate, clock=simulation_clock)
        )

    # Create WTA network
    wta_network = WTANetworkGroup(
        params=wta_params,
        background_input=background_input,
        task_inputs=task_inputs,
        pyr_params=pyr_params,
        inh_params=inh_params,
        plasticity_params=plasticity_params,
        clock=simulation_clock,
    )

    @network_operation(when="start", clock=input_update_clock)
    def set_task_inputs():
        for idx in range(len(task_inputs)):
            rate = wta_params.task_input_resting_rate
            if sim_params.stim_start_time <= simulation_clock.t < sim_params.stim_end_time:
                rate = input_freq[idx] * Hz + np.random.randn() * wta_params.input_var
                if rate < wta_params.task_input_resting_rate:
                    rate = wta_params.task_input_resting_rate
            task_inputs[idx]._S[0, :] = rate

    @network_operation(clock=simulation_clock)
    def inject_current():
        if simulation_clock.t > sim_params.dcs_start_time:
            wta_network.group_e.I_dcs = sim_params.p_dcs
            wta_network.group_i.I_dcs = sim_params.i_dcs

    # LFP source
    lfp_source = LFPSource(wta_network.group_e, clock=simulation_clock)

    # Create voxel
    voxel = Voxel(simulation_clock, network=wta_network)

    # Create network monitor
    wta_monitor = WTAMonitor(
        wta_network,
        lfp_source,
        voxel,
        sim_params,
        record_lfp=record_lfp,
        record_voxel=record_voxel,
        record_neuron_state=record_neuron_state,
        record_spikes=record_spikes,
        record_firing_rate=record_firing_rate,
        record_inputs=record_inputs,
        record_connections=record_connections,
        save_summary_only=save_summary_only,
        clock=simulation_clock,
    )

    @network_operation(when="start", clock=simulation_clock)
    def inject_muscimol():
        if sim_params.muscimol_amount > 0:
            wta_network.groups_e[sim_params.injection_site].g_muscimol = sim_params.muscimol_amount

    # Create Brian network and reset clock
    net = Network(
        background_input,
        task_inputs,
        set_task_inputs,
        wta_network,
        lfp_source,
        voxel,
        wta_network.connections.values(),
        wta_monitor.monitors.values(),
        inject_muscimol,
        inject_current,
    )
    if sim_params.plasticity:
        net.add(wta_network.stdp.values())
    print "Initialization time: %.2fs" % (time() - start_time)

    #    writer=LaTeXDocumentWriter()
    #    labels={}
    #    labels[voxel]=('v',str(voxel))
    #    labels[background_input]=('bi',str(background_input))
    #    labels[lfp_source]=('lfp',str(lfp_source))
    #    labels[wta_network]=('n',str(wta_network))
    #    labels[wta_network.group_e]=('e',str(wta_network.group_e))
    #    labels[wta_network.group_i]=('i',str(wta_network.group_i))
    #    for i,e_group in enumerate(wta_network.groups_e):
    #        labels[e_group]=('e%d' % i,'%s %d' % (str(e_group),i))
    #    for i,task_input in enumerate(task_inputs):
    #        labels[task_input]=('t%d' % i,'%s %d' % (str(task_input),i))
    #    for name,conn in wta_network.connections.iteritems():
    #        labels[conn]=(name,str(conn))
    #    for name,monitor in wta_monitor.monitors.iteritems():
    #        labels[monitor]=(name,str(monitor))
    #    writer.document_network(net=net, labels=labels)

    # Run simulation
    start_time = time()
    net.run(sim_params.trial_duration, report=report)
    print "Simulation time: %.2fs" % (time() - start_time)

    # Compute BOLD signal
    if record_voxel:
        start_time = time()
        wta_monitor.monitors["voxel_exc"] = get_bold_signal(
            wta_monitor.monitors["voxel"]["G_total_exc"].values[0], voxel.params, [500, 2500], sim_params.trial_duration
        )
        wta_monitor.monitors["voxel"] = get_bold_signal(
            wta_monitor.monitors["voxel"]["G_total"].values[0], voxel.params, [500, 2500], sim_params.trial_duration
        )
        print "BOLD generation time: %.2fs" % (time() - start_time)

    # Write output to file
    if output_file is not None:
        start_time = time()
        wta_monitor.write_output(input_freq, output_file)
        print "Wrote output to %s" % output_file
        print "Write output time: %.2fs" % (time() - start_time)

    # Plot outputs
    if plot_output:
        wta_monitor.plot()

    return wta_monitor