conn_weight=an_t_weight,
    normalised_space=pop_size,
    get_max_dist=True,
    delay=0.1)
an_t_list = [[] for _ in range(n_tds)]
for (pre, post, w, d) in an_t_master:
    i = np.remainder(post, n_tds)
    an_t_list[i].append((pre, int((float(post) / n_t) * n_sub_t + 0.5), w, d))

# an_t_list = connection_dicts[0]['an_t_list']

for i, source_l in enumerate(an_t_list):
    if len(source_l) > 0:
        sim.Projection(input_pop,
                       t_pops[i],
                       sim.FromListConnector(source_l),
                       synapse_type=sim.StaticSynapse())

duration = 100  #max(input_spikes[0])

sim.run(duration)

for i, pop in enumerate(t_pops):
    t_data[i] = pop.get_data()
    # t_spikes[i] = t_data[i].segments[0].spiketrains

sim.end()

for i, cd_data in enumerate(t_data):
    plt.figure('spikes')
    non_zero_neuron_times = cd_data.segments[0].spiketrains
def do_run():
    # boolean allowing users to use python or c vis
    using_c_vis = False

    # initial call to set up the front end (pynn requirement)
    Frontend.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)

    # neurons per population and the length of runtime in ms for the
    # simulation, as well as the expected weight each spike will contain
    n_neurons = 100
    run_time = 8000
    weight_to_spike = 2.0

    # neural parameters of the ifcur model used to respond to injected spikes.
    # (cell params for a synfire chain)
    cell_params_lif = {'cm': 0.25,
                       'i_offset': 0.0,
                       'tau_m': 20.0,
                       'tau_refrac': 2.0,
                       'tau_syn_E': 5.0,
                       'tau_syn_I': 5.0,
                       'v_reset': -70.0,
                       'v_rest': -65.0,
                       'v_thresh': -50.0
                       }

    ##################################
    # Parameters for the injector population.  This is the minimal set of
    # parameters required, which is for a set of spikes where the key is not
    # important.  Note that a virtual key *will* be assigned to the population,
    # and that spikes sent which do not match this virtual key will be dropped;
    # however, if spikes are sent using 16-bit keys, they will automatically be
    # made to match the virtual key.  The virtual key assigned can be obtained
    # from the database.
    ##################################
    cell_params_spike_injector = {

        # The port on which the spiNNaker machine should listen for packets.
        # Packets to be injected should be sent to this port on the spiNNaker
        # machine
        'port': 12345,
    }

    ##################################
    # Parameters for the injector population.  Note that each injector needs to
    # be given a different port.  The virtual key is assigned here, rather than
    # being allocated later.  As with the above, spikes injected need to match
    # this key, and this will be done automatically with 16-bit keys.
    ##################################
    cell_params_spike_injector_with_key = {

        # The port on which the spiNNaker machine should listen for packets.
        # Packets to be injected should be sent to this port on the spiNNaker
        # machine
        'port': 12346,

        # This is the base key to be used for the injection, which is used to
        # allow the keys to be routed around the spiNNaker machine.  This
        # assignment means that 32-bit keys must have the high-order 16-bit
        # set to 0x7; This will automatically be prepended to 16-bit keys.
        'virtual_key': 0x70000,
    }

    # create synfire populations (if cur exp)
    pop_forward = Frontend.Population(n_neurons,
                                      Frontend.IF_curr_exp(**cell_params_lif),
                                      label='pop_forward')
    pop_backward = Frontend.Population(n_neurons,
                                       Frontend.IF_curr_exp(**cell_params_lif),
                                       label='pop_backward')

    # Create injection populations
    injector_forward = Frontend.Population(
        n_neurons,
        Frontend.external_devices.SpikeInjector(),
        additional_parameters=cell_params_spike_injector_with_key,
        label='spike_injector_forward')
    injector_backward = Frontend.Population(
        n_neurons, Frontend.external_devices.SpikeInjector(),
        additional_parameters=cell_params_spike_injector,
        label='spike_injector_backward')

    # Create a connection from the injector into the populations
    Frontend.Projection(injector_forward, pop_forward,
                        Frontend.OneToOneConnector(),
                        Frontend.StaticSynapse(weight=weight_to_spike))
    Frontend.Projection(injector_backward, pop_backward,
                        Frontend.OneToOneConnector(),
                        Frontend.StaticSynapse(weight=weight_to_spike))

    # Synfire chain connection where each neuron is connected to next neuron
    # NOTE: there is no recurrent connection so that each chain stops once it
    # reaches the end
    loop_forward = list()
    loop_backward = list()
    for i in range(0, n_neurons - 1):
        loop_forward.append((i, (i + 1) % n_neurons, weight_to_spike, 3))
        loop_backward.append(((i + 1) % n_neurons, i, weight_to_spike, 3))
    Frontend.Projection(pop_forward, pop_forward,
                        Frontend.FromListConnector(loop_forward),
                        Frontend.StaticSynapse(weight=weight_to_spike,
                                               delay=3))
    Frontend.Projection(pop_backward, pop_backward,
                        Frontend.FromListConnector(loop_backward),
                        Frontend.StaticSynapse(weight=weight_to_spike,
                                               delay=3))

    # record spikes from the synfire chains so that we can read off valid
    # results in a safe way afterwards, and verify the behaviour
    pop_forward.record(['spikes'])
    pop_backward.record(['spikes'])

    # Activate the sending of live spikes
    Frontend.external_devices.activate_live_output_for(
        pop_forward, database_notify_host="localhost",
        database_notify_port_num=19996)
    Frontend.external_devices.activate_live_output_for(
        pop_backward, database_notify_host="localhost",
        database_notify_port_num=19996)

    # Set up the live connection for sending spikes
    live_spikes_connection_send = \
        Frontend.external_devices.SpynnakerLiveSpikesConnection(
            receive_labels=None, local_port=NOTIFY_PORT,
            send_labels=["spike_injector_forward", "spike_injector_backward"])

    # Set up callbacks to occur at initialisation
    live_spikes_connection_send.add_init_callback(
        "spike_injector_forward", init_pop)
    live_spikes_connection_send.add_init_callback(
        "spike_injector_backward", init_pop)

    # Set up callbacks to occur at the start of simulation
    live_spikes_connection_send.add_start_resume_callback(
        "spike_injector_forward", send_input_forward)
    live_spikes_connection_send.add_start_resume_callback(
        "spike_injector_backward", send_input_backward)

    live_spikes_connection_receive = None
    if not using_c_vis:

        # if not using the c visualiser, then a new spynnaker live spikes
        # connection is created to define that there is a python function which
        # receives the spikes.
        live_spikes_connection_receive = \
            Frontend.external_devices.SpynnakerLiveSpikesConnection(
                receive_labels=["pop_forward", "pop_backward"],
                local_port=19996, send_labels=None)

        # Set up callbacks to occur when spikes are received
        live_spikes_connection_receive.add_receive_callback(
            "pop_forward", receive_spikes)
        live_spikes_connection_receive.add_receive_callback(
            "pop_backward", receive_spikes)

    # Run the simulation on spiNNaker
    Frontend.run(run_time)
    Frontend.run(run_time)

    # Retrieve spikes from the synfire chain population
    spikes_forward = neo_convertor.convert_spikes(
        pop_forward.get_data('spikes'))
    spikes_backward = neo_convertor.convert_spikes(
        pop_backward.get_data('spikes'))

    # Clear data structures on spiNNaker to leave the machine in a clean state
    # for future executions
    Frontend.end()

    return (spikes_forward, spikes_backward)
예제 #3
0
# an2ch_weight = RandomDistribution('normal',[av_weight,0.1])
# an2ch_weight = RandomDistribution('normal',[av_weight,0.5])
# an2ch_weight = RandomDistribution('uniform',[0,av_weight+(av_weight*1.5)])
# an2ch_weight = RandomDistribution('uniform',[0.9*(w2s_target/conn_num),1.1*(w2s_target/conn_num)])
an2ch_weight = RandomDistribution('normal_clipped',[av_weight/2.,av_weight*0.5,0.,1.1*av_weight])
# plt.hist(an2ch_weight.next(1000),bins=100)
# plt.show()
an2ch_list = normal_dist_connection_builder(number_of_inputs,n_ch,RandomDistribution,conn_num,dist,sigma)
pres = np.asarray([pre for (pre,post) in an2ch_list])
x= np.nonzero(pres==25)
posts = np.asarray([post for (pre,post) in an2ch_list])
y = np.nonzero(posts==25)

reduced_list = [(pre,post) for (pre,post) in an2ch_list if post == 500]
pres = [pre for (pre,post) in reduced_list]
an_ch_projection = sim.Projection(input_pop,ch_pop,sim.FromListConnector(an2ch_list),synapse_type=sim.StaticSynapse(weight=an2ch_weight))
# an_ch_projection = sim.Projection(input_pop,ch_pop,sim.FromListConnector(reduced_list),synapse_type=sim.StaticSynapse(weight=an2ch_weight))

#TODO: calculate formulas for these variables so we can scale
an_scale_factor = number_of_inputs/30000.
n_on_inputs = 10.#np.round(an_scale_factor*88.)#upper bound from Xie and Manis (2017)
an_on_p_connect = n_on_inputs/float(number_of_inputs)
# an_on_p_connect = 0.1#0.55
# an_on_weight = w2s_target/(n_on_inputs)
# an_on_weight = 1.5/(n_on_inputs)
av_weight = 0.05#0.05#0.015#0.005#0.002#0.00125#0.0055#0.005#
# av_weight = 4.#0.005#0.002#0.00125#0.0055#0.005#
# an_on_weight =RandomDistribution('uniform',[0.9*av_weight,1.1*av_weight])
an_on_weight =RandomDistribution('uniform',[0,av_weight])

# test = RandomDistribution('normal_clipped',[500,10*number_of_inputs,0,1000])
예제 #4
0
def do_run(plot):

    runtime = 3000
    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
    nNeurons = 200  # number of neurons in each population
    p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 10)

    cell_params_lif = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 5.0,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -50.0
    }

    populations = list()
    projections = list()

    weight_to_spike = 2.0
    delay = 10

    # connection list in a loop for first population
    loopConnections = []
    for i in range(0, nNeurons):
        singleConnection = ((i, (i + 1) % nNeurons))
        loopConnections.append(singleConnection)

    # injection list to set the chain going
    injectionConnection = [(0, 0)]
    spikeArray = {'spike_times': [[0]]}

    # list of populations
    populations.append(
        p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif),
                     label='pop_1'))
    populations.append(
        p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif),
                     label='pop_2'))
    populations.append(
        p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif),
                     label='pop_3'))
    populations.append(
        p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif),
                     label='pop_4'))
    populations.append(
        p.Population(1,
                     p.SpikeSourceArray(**spikeArray),
                     label='inputSpikes_1'))

    # Loop connector: we can just pass in the list we made earlier
    CSA_loop_connector = p.CSAConnector(loopConnections)

    # random connector: each connection has a probability of 0.05
    CSA_random_connector = p.CSAConnector(csa.random(0.05))

    # one-to-one connector: do I really need to explain?
    CSA_onetoone_connector = p.CSAConnector(csa.oneToOne)

    # This creates a block of size (5,10) with a probability of 0.05; then
    # within the block an individual connection has a probability of 0.3
    csa_block_random = csa.block(15, 10) * csa.random(0.05) * csa.random(0.3)
    CSA_randomblock_connector = p.CSAConnector(csa_block_random)

    # list of projections using the connectors above
    projections.append(
        p.Projection(populations[0], populations[0], CSA_loop_connector,
                     p.StaticSynapse(weight=weight_to_spike, delay=delay)))
    projections.append(
        p.Projection(populations[0], populations[1], CSA_random_connector,
                     p.StaticSynapse(weight=weight_to_spike, delay=delay)))
    projections.append(
        p.Projection(populations[1], populations[2], CSA_onetoone_connector,
                     p.StaticSynapse(weight=weight_to_spike, delay=delay)))
    projections.append(
        p.Projection(populations[2], populations[3], CSA_randomblock_connector,
                     p.StaticSynapse(weight=weight_to_spike, delay=delay)))
    projections.append(
        p.Projection(populations[4], populations[0],
                     p.FromListConnector(injectionConnection),
                     p.StaticSynapse(weight=weight_to_spike, delay=1)))

    populations[0].record(['v', 'spikes'])
    populations[1].record(['v', 'spikes'])
    populations[2].record(['v', 'spikes'])
    populations[3].record(['v', 'spikes'])

    p.run(runtime)

    # get data (could be done as one, but can be done bit by bit as well)
    v = populations[0].spinnaker_get_data('v')
    v2 = populations[1].spinnaker_get_data('v')
    v3 = populations[2].spinnaker_get_data('v')
    v4 = populations[3].spinnaker_get_data('v')
    spikes = populations[0].spinnaker_get_data('spikes')
    spikes2 = populations[1].spinnaker_get_data('spikes')
    spikes3 = populations[2].spinnaker_get_data('spikes')
    spikes4 = populations[3].spinnaker_get_data('spikes')

    if plot:
        # Use the show functionality of CSA to display connection sets
        CSA_loop_connector.show_connection_set()
        CSA_random_connector.show_connection_set()
        CSA_onetoone_connector.show_connection_set()
        CSA_randomblock_connector.show_connection_set()

        # Now plot some spikes
        pylab.figure()
        pylab.plot([i[1] for i in spikes], [i[0] for i in spikes], "r.")
        pylab.xlabel('Time/ms')
        pylab.ylabel('spikes')
        pylab.title('spikes: population 1')

        pylab.show()

        pylab.figure()
        pylab.plot([i[1] for i in spikes3], [i[0] for i in spikes3], "g.")
        pylab.plot([i[1] for i in spikes4], [i[0] for i in spikes4], "r.")
        pylab.plot([i[1] for i in spikes2], [i[0] for i in spikes2], "b.")
        pylab.xlabel('Time/ms')
        pylab.ylabel('spikes')
        pylab.title('spikes: populations 2, 3, 4')

        pylab.show()

    p.end()

    return v, v2, v3, v4, spikes, spikes2, spikes3, spikes4
예제 #5
0
                        [5, 0, weight, 1], [9, 0, weight, 1]]
left = 0
right = 1
from_list_conn_out = [[0, left, weight, 1], [6, left, weight, 1],
                      [3, left, weight, 1], [11, left, weight, 1],
                      [2, right, weight, 1], [8, right, weight, 1],
                      [5, right, weight, 1], [9, right, weight, 1]]
output_pop = p.Population(outputs,
                          p.IF_cond_exp(tau_m=0.5,
                                        tau_refrac=0,
                                        v_thresh=-64,
                                        tau_syn_E=1,
                                        tau_syn_I=1),
                          label='out')
output_pop.record(['spikes', 'v', 'gsyn_exc'])
p.Projection(pendulum, output_pop, p.FromListConnector(from_list_conn_out))
output_pop2 = p.Population(outputs,
                           p.IF_cond_exp(tau_m=0.5,
                                         tau_refrac=0,
                                         v_thresh=-64,
                                         tau_syn_E=0.5,
                                         tau_syn_I=0.5),
                           label='out2')
output_pop2.record(['spikes', 'v', 'gsyn_exc'])
p.Projection(null_pop, output_pop2, p.FromListConnector(from_list_conn_out))
arm_conns = [from_list_conn_left, from_list_conn_right]
# for j in range(outputs):
#     arm_collection.append(p.Population(
#         int(np.ceil(np.log2(outputs))),
#         Arm(arm_id=j, reward_delay=exposure_time,
#             rand_seed=[np.random.randint(0xffff) for k in range(4)],
예제 #6
0
    def run_multiple_stdp_mechs_on_same_neuron(self, mode="same"):
        p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
        nNeurons = 200  # number of neurons in each population

        cell_params_lif = {'cm': 0.25, 'i_offset': 0.0, 'tau_m': 20.0,
                           'tau_refrac': 2.0, 'tau_syn_E': 5.0,
                           'tau_syn_I': 5.0, 'v_reset': -70.0, 'v_rest': -65.0,
                           'v_thresh': -50.0}

        populations = list()
        projections = list()

        weight_to_spike = 2.0
        delay = 1

        connections = list()
        for i in range(0, nNeurons):
            singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike,
                                delay)
            connections.append(singleConnection)

        # Plastic Connection between pre_pop and post_pop
        stdp_model1 = p.STDPMechanism(
            timing_dependence=p.SpikePairRule(
                tau_plus=16.7, tau_minus=33.7, A_plus=0.005, A_minus=0.005),
            weight_dependence=p.AdditiveWeightDependence(
                w_min=0.0, w_max=1.0),
        )

        # Plastic Connection between pre_pop and post_pop
        stdp_model2 = p.STDPMechanism(
            timing_dependence=p.SpikePairRule(
                tau_plus=16.7, tau_minus=33.7, A_plus=0.005, A_minus=0.005),
            weight_dependence=p.AdditiveWeightDependence(
                w_min=0.0, w_max=1.0),
        )

        # Plastic Connection between pre_pop and post_pop
        if mode == "same":
            stdp_model3 = p.STDPMechanism(
                timing_dependence=p.SpikePairRule(
                    tau_plus=16.7, tau_minus=33.7, A_plus=0.005,
                    A_minus=0.005),
                weight_dependence=p.AdditiveWeightDependence(
                    w_min=0.0, w_max=1.0),
            )
        elif mode == "weight_dependence":
            stdp_model3 = p.STDPMechanism(
                timing_dependence=p.SpikePairRule(
                    tau_plus=16.7, tau_minus=33.7, A_plus=0.005,
                    A_minus=0.005),
                weight_dependence=p.MultiplicativeWeightDependence(
                    w_min=0.0, w_max=1.0),
            )
        elif mode == "tau":
            stdp_model3 = p.STDPMechanism(
                timing_dependence=p.SpikePairRule(
                    tau_plus=15.7, tau_minus=33.7, A_plus=0.005,
                    A_minus=0.005),
                weight_dependence=p.AdditiveWeightDependence(
                    w_min=0.0, w_max=1.0),
            )
        elif mode == "wmin":
            stdp_model3 = p.STDPMechanism(
                timing_dependence=p.SpikePairRule(
                    tau_plus=16.7, tau_minus=33.7, A_plus=0.005,
                    A_minus=0.005),
                weight_dependence=p.AdditiveWeightDependence(w_min=1.0,
                                                             w_max=1.0), )
        else:
            raise Exception(mode)

        injectionConnection = [(0, 0, weight_to_spike, 1)]
        spikeArray1 = {'spike_times': [[0]]}
        spikeArray2 = {'spike_times': [[25]]}
        spikeArray3 = {'spike_times': [[50]]}
        spikeArray4 = {'spike_times': [[75]]}
        spikeArray5 = {'spike_times': [[100]]}
        spikeArray6 = {'spike_times': [[125]]}
        spikeArray7 = {'spike_times': [[150]]}
        spikeArray8 = {'spike_times': [[175]]}

        populations.append(p.Population(nNeurons, p.IF_curr_exp,
                                        cell_params_lif,
                                        label='pop_1'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray1,
                                        label='inputSpikes_1'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray2,
                                        label='inputSpikes_2'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray3,
                                        label='inputSpikes_3'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray4,
                                        label='inputSpikes_4'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray5,
                                        label='inputSpikes_5'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray6,
                                        label='inputSpikes_6'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray7,
                                        label='inputSpikes_7'))
        populations.append(p.Population(1, p.SpikeSourceArray, spikeArray8,
                                        label='inputSpikes_8'))

        projections.append(p.Projection(populations[0], populations[0],
                                        p.FromListConnector(connections)))
        pop = p.Projection(populations[1], populations[0],
                           p.FromListConnector(injectionConnection))
        pop = p.Projection(populations[2], populations[0],
                           p.FromListConnector(injectionConnection),
                           synapse_type=stdp_model1)
        projections.append(pop)
        # This is expected to raise a SynapticConfigurationException
        pop = p.Projection(populations[3], populations[0],
                           p.FromListConnector(injectionConnection),
                           synapse_type=stdp_model2)
        projections.append(pop)
        pop = p.Projection(populations[4], populations[0],
                           p.FromListConnector(injectionConnection),
                           synapse_type=stdp_model3)
        projections.append(pop)
                                    (i, j,
                                     inhibition_weight_multiplier * w_max, 1))

                        if args.rewiring and not args.fixed_wta:
                            wta_projection = sim.Projection(
                                readout_pop,
                                readout_pop,
                                sim.FixedProbabilityConnector(0.),
                                synapse_type=structure_model_w_stdp,
                                label="wta_strong_inhibition_readout_rewired",
                                receptor_type="inhibitory")
                        else:
                            wta_projection = sim.Projection(
                                readout_pop,
                                readout_pop,
                                sim.FromListConnector(all_to_all_connections),
                                label="wta_strong_inhibition_readout",
                                receptor_type="inhibitory")

                elif phase == TESTING_PHASE:
                    # Extract static connectivity from the training phase
                    # Retrieve readout connectivity (ff and lat)
                    # Always retrieve ff connectivity
                    if snapshots_present:
                        trained_target_readout_connectivity = \
                            target_snapshots[snap_keys[snap]]
                        trained_wta_connectivity = \
                            wta_snapshots[snap_keys[snap]]
                    else:
                        trained_target_readout_connectivity = \
                            readout_training_data['target_readout_projection'][-1]
예제 #8
0
def structural_shared():
    p.setup(1.0)
    pre_spikes = numpy.array(range(0, 10, 2))
    A_plus = 0.01
    A_minus = 0.01
    tau_plus = 20.0
    tau_minus = 20.0
    w_min = 0.0
    w_max = 5.0
    w_init = 5.0
    delay_init = 2.0
    stim = p.Population(1, p.SpikeSourceArray(pre_spikes), label="stim")
    pop = p.Population(1, p.IF_curr_exp(), label="pop")
    pop_2 = p.Population(1, p.IF_curr_exp(), label="pop_2")
    pop_3 = p.Population(1, p.IF_curr_exp(), label="pop_3")
    pop_4 = p.Population(1, p.IF_curr_exp(), label="pop_4")
    pop.record("spikes")
    pop_2.record("spikes")
    struct_pl_static = p.StructuralMechanismStatic(
        partner_selection=p.LastNeuronSelection(),
        formation=p.DistanceDependentFormation([1, 1], 1.0),
        elimination=p.RandomByWeightElimination(2.0, 0, 0),
        f_rew=1000, initial_weight=w_init, initial_delay=delay_init,
        s_max=1, seed=0, weight=0.0, delay=1.0)
    struct_pl_stdp = p.StructuralMechanismSTDP(
            partner_selection=p.LastNeuronSelection(),
            formation=p.DistanceDependentFormation([1, 1], 0.0),
            elimination=p.RandomByWeightElimination(4.0, 1.0, 1.0),
            timing_dependence=p.SpikePairRule(
                tau_plus, tau_minus, A_plus, A_minus),
            weight_dependence=p.AdditiveWeightDependence(w_min, w_max),
            f_rew=1000, initial_weight=2.0, initial_delay=5.0,
            s_max=1, seed=0, weight=0.0, delay=1.0)
    proj = p.Projection(
        stim, pop, p.FromListConnector([]), struct_pl_static)
    proj_2 = p.Projection(
        stim, pop_2, p.FromListConnector([]), struct_pl_static)
    proj_3 = p.Projection(
        stim, pop_3, p.FromListConnector([(0, 0)]), struct_pl_stdp)
    proj_4 = p.Projection(
        stim, pop_4, p.FromListConnector([(0, 0)]), struct_pl_stdp)
    p.Projection(pop_3, pop_4, p.AllToAllConnector(),
                 p.StaticSynapse(weight=1, delay=3))
    p.run(10)

    conns = list(proj.get(["weight", "delay"], "list"))
    conns_2 = list(proj_2.get(["weight", "delay"], "list"))
    conns_3 = list(proj_3.get(["weight", "delay"], "list"))
    conns_4 = list(proj_4.get(["weight", "delay"], "list"))

    p.end()

    print(conns)
    print(conns_2)
    print(conns_3)
    print(conns_4)

    assert(len(conns) == 1)
    assert(tuple(conns[0]) == (0, 0, w_init, delay_init))
    assert(len(conns_2) == 1)
    assert(tuple(conns_2[0]) == (0, 0, w_init, delay_init))
    assert(len(conns_3) == 0)
    assert(len(conns_4) == 0)
예제 #9
0
def do_synfire_npop(nNeurons, n_pops, neurons_per_core, runtime=25000):
    """
    Runs the script Does the run based on the parameters

    :param nNeurons: Number of Neurons in chain
    :type  nNeurons: int
    :param n_pops: Number of populations
    :type  n_pops: int
    :param neurons_per_core: Number of neurons per core
    :type  neurons_per_core: int
    :param runtime: time to run the script for
    :type  runtime: int
    """
    p.setup(timestep=1.0)
    RootTestCase.assert_not_spin_three()
    p.set_number_of_neurons_per_core(p.IF_curr_exp, neurons_per_core)

    cell_params_lif = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 5.0,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -50.0
    }

    populations = list()
    projections = list()

    weight_to_spike = 2.0
    delay = 1

    connections = list()
    for i in range(0, nNeurons - 1):
        singleConnection = (i, i + 1, weight_to_spike, delay)
        connections.append(singleConnection)

    pop_jump_connection = [(nNeurons - 1, 0, weight_to_spike, 1)]

    injectionConnection = [(0, 0, weight_to_spike, 1)]

    spikeArray = {'spike_times': [[0]]}

    for i in range(0, n_pops):
        populations.append(
            p.Population(nNeurons,
                         p.IF_curr_exp(**cell_params_lif),
                         label='pop_{}'.format(i)))

    populations.append(
        p.Population(1,
                     p.SpikeSourceArray(**spikeArray),
                     label='inputSpikes_1'))

    for i in range(0, n_pops):
        projections.append(
            p.Projection(presynaptic_population=populations[i],
                         postsynaptic_population=populations[i],
                         connector=p.FromListConnector(connections),
                         synapse_type=p.StaticSynapse()))

        connector = p.FromListConnector(pop_jump_connection)

        projections.append(
            p.Projection(presynaptic_population=populations[i],
                         postsynaptic_population=populations[((i + 1) %
                                                              n_pops)],
                         connector=connector,
                         synapse_type=p.StaticSynapse()))

    projections.append(
        p.Projection(presynaptic_population=populations[n_pops],
                     postsynaptic_population=populations[0],
                     connector=p.FromListConnector(injectionConnection),
                     synapse_type=p.StaticSynapse()))

    for pop_index in range(0, n_pops):
        populations[pop_index].record("spikes")

    p.run(runtime)

    total_spikes = populations[0].spinnaker_get_data("spikes")
    for pop_index in range(1, n_pops):
        spikes = populations[pop_index].spinnaker_get_data("spikes")
        if spikes is not None:
            for spike in spikes:
                spike[0] += (nNeurons * pop_index)
            total_spikes = numpy.concatenate((total_spikes, spikes), axis=0)

    p.end()

    return total_spikes
예제 #10
0
def do_run():
    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
    nNeurons = 100  # number of neurons in each population
    cell_params_lif = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 5.0,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -50.0
    }

    populations = list()
    projections = list()

    weight_to_spike = 2.0
    delay = 3
    delays = list()
    connections = list()
    for i in range(0, nNeurons):
        delays.append(float(delay))
        singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay)
        connections.append(singleConnection)

    injectionConnection = [(0, 0, weight_to_spike, 1)]
    spikeArray = {'spike_times': [[0]]}

    populations.append(
        p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif),
                     label='pop_1'))
    populations.append(
        p.Population(1,
                     p.SpikeSourceArray(**spikeArray),
                     label='inputSpikes_1'))

    projections.append(
        p.Projection(populations[0], populations[0],
                     p.FromListConnector(connections),
                     p.StaticSynapse(weight=weight_to_spike, delay=delay)))
    projections.append(
        p.Projection(populations[1], populations[0],
                     p.FromListConnector(injectionConnection),
                     p.StaticSynapse(weight=weight_to_spike, delay=1)))

    populations[0].record(['spikes'])
    p.external_devices.activate_live_output_for(populations[0])
    populations[0].add_placement_constraint(0, 0, 2)
    populations[1].add_placement_constraint(0, 0, 3)

    run_time = 1000
    print("Running for {} ms".format(run_time))
    p.run(run_time)

    spikes = neo_convertor.convert_spikes(populations[0].get_data('spikes'))

    p.end()

    return spikes
예제 #11
0
t2 = [[2, 3, 4, 8], [2, 4, 6, 8]]
t1 = [2, 12]

input_celltype = sim.SpikeSourceArray(spike_times=t1)
fc_celltype = sim.IF_cond_exp(**cellparams)

pop0 = sim.Population(1, input_celltype)
pop1 = sim.Population(1, fc_celltype)
pop1.initialize(**cellvalues)
#pop1.set(i_offset=b)

pop1.record(['spikes', 'v'])
pop0.record(['spikes'])

# create synapsis

conn = sim.FromListConnector(w1)
pro = sim.Projection(pop0, pop1, connector=conn)

sim.run(duration)

mem = pop1.get_data().segments[-1].filter(name='v')[0]

from pyNN.utility.plotting import Figure, Panel

Figure(
    Panel(mem,
          ylabel="Membrane potential (mV)",
          xticks=True,
          xlabel="Time (ms)",
          yticks=True))
loopConnections = list()
for i in range(0, nNeurons):
    singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay))
    loopConnections.append(singleConnection)

injectionConnection = [(0, 0)]
spikeArray = {'spike_times': [[0]]}
main_pop = p.Population(nNeurons,
                        p.IF_cond_exp(**cell_params_lif),
                        label='pop_1')
input_pop = p.Population(1,
                         p.SpikeSourceArray(**spikeArray),
                         label='inputSpikes_1')

p.Projection(main_pop, main_pop, p.FromListConnector(loopConnections),
             p.StaticSynapse(weight=weight_to_spike, delay=delay))
p.Projection(input_pop, main_pop, p.FromListConnector(injectionConnection),
             p.StaticSynapse(weight=weight_to_spike, delay=1))

main_pop.record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes'])

intercept_simulator(p, "sim_synfire_if_cond_exp")

from importlib import reload

p = reload(p)
populations, projections = restore_simulator_from_file(
    p, "sim_synfire_if_cond_exp")
p.run(runtime)
예제 #13
0
    def __init__(self):

        # initial call to set up the front end (pynn requirement)
        Frontend.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)

        use_c_visualiser = True
        use_spike_injector = True

        # neurons per population and the length of runtime in ms for the
        # simulation, as well as the expected weight each spike will contain
        self.n_neurons = 100

        # set up gui
        p = None
        if use_spike_injector:
            from multiprocessing import Process
            from multiprocessing import Event
            ready = Event()
            p = Process(target=GUI, args=[self.n_neurons, ready])
            p.start()
            ready.wait()

        # different runtimes for demostration purposes
        run_time = None
        if not use_c_visualiser and not use_spike_injector:
            run_time = 1000
        elif use_c_visualiser and not use_spike_injector:
            run_time = 10000
        elif use_c_visualiser and use_spike_injector:
            run_time = 100000
        elif not use_c_visualiser and use_spike_injector:
            run_time = 10000

        weight_to_spike = 2.0

        # neural parameters of the IF_curr model used to respond to injected
        # spikes.
        # (cell params for a synfire chain)
        cell_params_lif = {
            'cm': 0.25,
            'i_offset': 0.0,
            'tau_m': 20.0,
            'tau_refrac': 2.0,
            'tau_syn_E': 5.0,
            'tau_syn_I': 5.0,
            'v_reset': -70.0,
            'v_rest': -65.0,
            'v_thresh': -50.0
        }

        ##################################
        # Parameters for the injector population.  This is the minimal set of
        # parameters required, which is for a set of spikes where the key is
        # not important.  Note that a virtual key *will* be assigned to the
        # population, and that spikes sent which do not match this virtual key
        # will be dropped; however, if spikes are sent using 16-bit keys, they
        # will automatically be made to match the virtual key.  The virtual
        # key assigned can be obtained from the database.
        ##################################
        cell_params_spike_injector = {

            # The port on which the spiNNaker machine should listen for
            # packets. Packets to be injected should be sent to this port on
            # the spiNNaker machine
            'port': 12345
        }

        ##################################
        # Parameters for the injector population.  Note that each injector
        # needs to be given a different port.  The virtual key is assigned
        # here, rather than being allocated later.  As with the above, spikes
        # injected need to match this key, and this will be done automatically
        # with 16-bit keys.
        ##################################
        cell_params_spike_injector_with_key = {

            # The port on which the spiNNaker machine should listen for
            # packets. Packets to be injected should be sent to this port on
            # the spiNNaker machine
            'port': 12346,

            # This is the base key to be used for the injection, which is used
            # to allow the keys to be routed around the spiNNaker machine.
            # This assignment means that 32-bit keys must have the high-order
            # 16-bit set to 0x7; This will automatically be prepended to
            # 16-bit keys.
            'virtual_key': 0x70000
        }

        # create synfire populations (if cur exp)
        pop_forward = Frontend.Population(
            self.n_neurons,
            Frontend.IF_curr_exp(**cell_params_lif),
            label='pop_forward')
        pop_backward = Frontend.Population(
            self.n_neurons,
            Frontend.IF_curr_exp(**cell_params_lif),
            label='pop_backward')

        # Create injection populations
        injector_forward = None
        injector_backward = None
        if use_spike_injector:
            injector_forward = Frontend.Population(
                self.n_neurons,
                Frontend.external_devices.SpikeInjector(),
                label='spike_injector_forward',
                additional_parameters=cell_params_spike_injector_with_key)
            injector_backward = Frontend.Population(
                self.n_neurons,
                Frontend.external_devices.SpikeInjector(),
                label='spike_injector_backward',
                additional_parameters=cell_params_spike_injector)
        else:
            spike_times = []
            for _ in range(0, self.n_neurons):
                spike_times.append([])
            spike_times[0] = [0]
            spike_times[20] = [(run_time / 100) * 20]
            spike_times[40] = [(run_time / 100) * 40]
            spike_times[60] = [(run_time / 100) * 60]
            spike_times[80] = [(run_time / 100) * 80]
            cell_params_forward = {'spike_times': spike_times}
            spike_times_backwards = []
            for _ in range(0, self.n_neurons):
                spike_times_backwards.append([])
            spike_times_backwards[0] = [(run_time / 100) * 80]
            spike_times_backwards[20] = [(run_time / 100) * 60]
            spike_times_backwards[40] = [(run_time / 100) * 40]
            spike_times_backwards[60] = [(run_time / 100) * 20]
            spike_times_backwards[80] = [0]
            cell_params_backward = {'spike_times': spike_times_backwards}
            injector_forward = Frontend.Population(
                self.n_neurons,
                Frontend.SpikeSourceArray(**cell_params_forward),
                label='spike_injector_forward')
            injector_backward = Frontend.Population(
                self.n_neurons,
                Frontend.SpikeSourceArray(**cell_params_backward),
                label='spike_injector_backward')

        # Create a connection from the injector into the populations
        Frontend.Projection(injector_forward, pop_forward,
                            Frontend.OneToOneConnector(),
                            Frontend.StaticSynapse(weight=weight_to_spike))
        Frontend.Projection(injector_backward, pop_backward,
                            Frontend.OneToOneConnector(),
                            Frontend.StaticSynapse(weight=weight_to_spike))

        # Synfire chain connections where each neuron is connected to its next
        # neuron
        # NOTE: there is no recurrent connection so that each chain stops once
        # it reaches the end
        loop_forward = list()
        loop_backward = list()
        for i in range(0, self.n_neurons - 1):
            loop_forward.append(
                (i, (i + 1) % self.n_neurons, weight_to_spike, 3))
            loop_backward.append(
                ((i + 1) % self.n_neurons, i, weight_to_spike, 3))
        Frontend.Projection(pop_forward, pop_forward,
                            Frontend.FromListConnector(loop_forward))
        Frontend.Projection(pop_backward, pop_backward,
                            Frontend.FromListConnector(loop_backward))

        # record spikes from the synfire chains so that we can read off valid
        # results in a safe way afterwards, and verify the behavior
        pop_forward.record('spikes')
        pop_backward.record('spikes')

        # Activate the sending of live spikes
        Frontend.external_devices.activate_live_output_for(
            pop_forward,
            database_notify_host="localhost",
            database_notify_port_num=19996)
        Frontend.external_devices.activate_live_output_for(
            pop_backward,
            database_notify_host="localhost",
            database_notify_port_num=19996)

        if not use_c_visualiser:
            # if not using the c visualiser, then a new spynnaker live spikes
            # connection is created to define that there are python code which
            # receives the outputted spikes.
            live_spikes_connection_receive = \
                Frontend.external_devices.SpynnakerLiveSpikesConnection(
                    receive_labels=["pop_forward", "pop_backward"],
                    local_port=19999, send_labels=None)

            # Set up callbacks to occur when spikes are received
            live_spikes_connection_receive.add_receive_callback(
                "pop_forward", receive_spikes)
            live_spikes_connection_receive.add_receive_callback(
                "pop_backward", receive_spikes)

        # Run the simulation on spiNNaker
        Frontend.run(run_time)

        # Retrieve spikes from the synfire chain population
        spikes_forward = pop_forward.get_data('spikes')
        spikes_backward = pop_backward.get_data('spikes')

        # Clear data structures on spiNNaker to leave the machine in a clean
        # state for future executions
        Frontend.end()

        if use_spike_injector:
            p.join()

        Figure(
            # raster plot of the presynaptic neuron spike times
            Panel(spikes_forward.segments[0].spiketrains,
                  yticks=True,
                  markersize=0.2,
                  xlim=(0, run_time)),
            Panel(spikes_backward.segments[0].spiketrains,
                  yticks=True,
                  markersize=0.2,
                  xlim=(0, run_time)),
            title="Simple synfire chain example with injected spikes",
            annotations="Simulated with {}".format(Frontend.name()))
        plt.show()
slots_starts = np.ones((N_layer, number_of_slots)) * (range_of_slots * t_stim)
durations = np.ones((N_layer, number_of_slots)) * t_stim
rates = np.random.randint(1, 5, size=(N_layer, number_of_slots))

# Spike sources
poisson_spike_source = sim.Population(N_layer,
                                      SpikeSourcePoissonVariable(
                                          starts=slots_starts,
                                          rates=rates,
                                          durations=durations),
                                      label='poisson_source')

lif_pop = sim.Population(N_layer, sim.IF_curr_exp, label='pop_1')

conns = [[x, x] for x in range(N_layer)]
sim.Projection(poisson_spike_source, lif_pop, sim.FromListConnector(conns),
               sim.StaticSynapse(weight=2, delay=1))

poisson_spike_source.record(['spikes'])
lif_pop.record(['spikes'])

intercept_simulator(sim, "variable_rate_pss")
sim.run(runtime)
pss_spikes = poisson_spike_source.spinnaker_get_data('spikes')
lif_spikes = lif_pop.spinnaker_get_data('spikes')
sim.end()

from importlib import reload

sim = reload(sim)
populations, projections, _ = restore_simulator_from_file(
예제 #15
0
    def _connect_spike_sources(self, retinae=None, verbose=False):

        if verbose:
            print "INFO: Connecting Spike Sources to Network."

        global _retina_proj_l, _retina_proj_r

        # left is 0--dimensionRetinaY-1; right is dimensionRetinaY--dimensionRetinaY*2-1
        connListRetLBlockerL = []
        connListRetLBlockerR = []
        connListRetRBlockerL = []
        connListRetRBlockerR = []
        for y in range(0, self.dim_y):
            connListRetLBlockerL.append((y, y,
                                         self.cell_params['synaptic']['wSaB'],
                                         self.cell_params['synaptic']['dSaB']))
            connListRetLBlockerR.append((y, y + self.dim_y,
                                         self.cell_params['synaptic']['wSzB'],
                                         self.cell_params['synaptic']['dSzB']))
            connListRetRBlockerL.append((y, y,
                                         self.cell_params['synaptic']['wSzB'],
                                         self.cell_params['synaptic']['dSzB']))
            connListRetRBlockerR.append((y, y + self.dim_y,
                                         self.cell_params['synaptic']['wSaB'],
                                         self.cell_params['synaptic']['dSaB']))

        retinaLeft = retinae['left'].pixel_columns
        retinaRight = retinae['right'].pixel_columns
        pixel = 0
        for row in _retina_proj_l:
            for pop in row:
                ps.Projection(retinaLeft[pixel],
                              self.network[pop][1],
                              ps.OneToOneConnector(),
                              ps.StaticSynapse(weight=self.cell_params['synaptic']['wSC'],
                                                   delay=self.cell_params['synaptic']['dSC']),
                              receptor_type='excitatory')
                              #ps.OneToOneConnector(weights=self.cell_params['synaptic']['wSC'],
                              #                     delays=self.cell_params['synaptic']['dSC']),
                              #target='excitatory')
                ps.Projection(retinaLeft[pixel],
                              self.network[pop][0],
                              ps.FromListConnector(connListRetLBlockerL),
                              receptor_type='excitatory')
                              #target='excitatory')
                ps.Projection(retinaLeft[pixel],
                              self.network[pop][0],
                              ps.FromListConnector(connListRetLBlockerR),
                              receptor_type='inhibitory')
                              #target='inhibitory')
            pixel += 1

        pixel = 0
        for col in _retina_proj_r:
            for pop in col:
                ps.Projection(retinaRight[pixel], self.network[pop][1],
                              ps.OneToOneConnector(),
                              ps.StaticSynapse(weight=self.cell_params['synaptic']['wSC'],
                                                   delay=self.cell_params['synaptic']['dSC']),
                              receptor_type='excitatory')
                              #ps.OneToOneConnector(weights=self.cell_params['synaptic']['wSC'],
                              #                     delays=self.cell_params['synaptic']['dSC']),
                              #target='excitatory')
                ps.Projection(retinaRight[pixel],
                              self.network[pop][0],
                              ps.FromListConnector(connListRetRBlockerR),
                              receptor_type='excitatory')
                              #target='excitatory')
                ps.Projection(retinaRight[pixel],
                              self.network[pop][0],
                              ps.FromListConnector(connListRetRBlockerL),
                              receptor_type='inhibitory')
                              #target='inhibitory')
            pixel += 1
예제 #16
0
                                label=label)
    # Set the rest of the specified variables, if any.
    for variable in s['variables']:
        if getattr(population, variable, None) is None:
            setattr(population, variable, s[label][variable])
    if label != 'InputLayer':
        population.set(i_offset=s[label]['i_offset'])
    layers.append(population)
print('assembly loaded')

# ------ Load weights and delays --------
for i in range(len(layers) - 1):
    print('Loading connections for layer ' + str(layers[i].label))
    filepath = os.path.join(layers_path, layers[i + 1].label)
    conn_list = read_from_file2list(filepath)
    exc_connector = sim.FromListConnector(conn_list[0])
    pro_exc = sim.Projection(layers[i],
                             layers[i + 1],
                             connector=exc_connector,
                             receptor_type='excitatory')
    if conn_list[1] != []:
        inh_connector = sim.FromListConnector(read_from_file2list(filepath)[1])
        pro_inh = sim.Projection(layers[i],
                                 layers[i + 1],
                                 connector=inh_connector,
                                 receptor_type='inhibitory')
print('connections loaded')

# -------- Cell initialization -----------
vars_to_record = ['spikes', 'v']
if 'spikes' in vars_to_record:
예제 #17
0
def do_run(nNeurons):

    p.setup(timestep=1.0, min_delay=1.0, max_delay=32.0)

    p.set_number_of_neurons_per_core(p.IF_curr_exp, 100)

    cm = list()
    i_off = list()
    tau_m = list()
    tau_re = list()
    tau_syn_e = list()
    tau_syn_i = list()
    v_reset = list()
    v_rest = list()
    v_thresh = list()

    for atom in range(0, nNeurons):
        cm.append(0.25)
        i_off.append(0.0)
        tau_m.append(10.0)
        tau_re.append(2.0)
        tau_syn_e.append(0.5)
        tau_syn_i.append(0.5)
        v_reset.append(-65.0)
        v_rest.append(-65.0)
        v_thresh.append(-64.4)

    gbar_na_distr = RandomDistribution('normal', (20.0, 2.0),
                                       rng=NumpyRNG(seed=85524))

    cell_params_lif = {
        'cm': cm,
        'i_offset': i_off,
        'tau_m': tau_m,
        'tau_refrac': tau_re,
        'tau_syn_E': tau_syn_e,
        'tau_syn_I': tau_syn_i,
        'v_reset': v_reset,
        'v_rest': v_rest,
        'v_thresh': v_thresh
    }

    populations = list()
    projections = list()

    weight_to_spike = 2
    delay = 1

    connections = list()
    for i in range(0, nNeurons):
        singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay)
        connections.append(singleConnection)

    injectionConnection = [(0, 0, weight_to_spike, delay)]
    spikeArray = {'spike_times': [[0]]}
    populations.append(
        p.Population(nNeurons, p.IF_curr_exp, cell_params_lif, label='pop_1'))
    populations.append(
        p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1'))

    populations[0].set(cm=0.25)
    populations[0].set(cm=cm)
    populations[0].set(tau_m=tau_m, v_thresh=v_thresh)
    populations[0].set(i_offset=gbar_na_distr)
    populations[0].set(i_offset=i_off)

    projections.append(
        p.Projection(populations[0], populations[0],
                     p.FromListConnector(connections)))
    projections.append(
        p.Projection(populations[1], populations[0],
                     p.FromListConnector(injectionConnection)))

    populations[0].record("v")
    populations[0].record("gsyn_exc")
    populations[0].record("spikes")

    p.run(100)

    neo = populations[0].get_data(["v", "spikes", "gsyn_exc"])

    p.end()

    return neo
def structural_with_stdp():
    p.setup(1.0)
    pre_spikes = numpy.array(range(0, 10, 2))
    pre_spikes_last_neuron = pre_spikes[pre_spikes > 0]
    A_plus = 0.01
    A_minus = 0.01
    tau_plus = 20.0
    tau_minus = 20.0
    w_min = 0.0
    w_max = 5.0
    w_init_1 = 5.0
    delay_1 = 2.0
    w_init_2 = 4.0
    delay_2 = 1.0
    stim = p.Population(1, p.SpikeSourceArray(pre_spikes), label="stim")
    pop = p.Population(1, p.IF_curr_exp(), label="pop")
    pop_2 = p.Population(1, p.IF_curr_exp(), label="pop_2")
    pop_3 = p.Population(1, p.IF_curr_exp(), label="pop_3")
    pop_4 = p.Population(1, p.IF_curr_exp(), label="pop_4")
    pop.record("spikes")
    pop_2.record("spikes")
    proj = p.Projection(
        stim, pop, p.FromListConnector([]), p.StructuralMechanismSTDP(
            partner_selection=p.LastNeuronSelection(),
            formation=p.DistanceDependentFormation([1, 1], 1.0),
            elimination=p.RandomByWeightElimination(2.0, 0, 0),
            timing_dependence=p.SpikePairRule(
                tau_plus, tau_minus, A_plus, A_minus),
            weight_dependence=p.AdditiveWeightDependence(w_min, w_max),
            f_rew=1000, initial_weight=w_init_1, initial_delay=delay_1,
            s_max=1, seed=0, weight=0.0, delay=1.0))
    proj_2 = p.Projection(
        stim, pop_2, p.FromListConnector([]), p.StructuralMechanismSTDP(
            partner_selection=p.RandomSelection(),
            formation=p.DistanceDependentFormation([1, 1], 1.0),
            elimination=p.RandomByWeightElimination(4.0, 0, 0),
            timing_dependence=p.SpikePairRule(
                tau_plus, tau_minus, A_plus, A_minus),
            weight_dependence=p.AdditiveWeightDependence(w_min, w_max),
            f_rew=1000, initial_weight=w_init_2, initial_delay=delay_2,
            s_max=1, seed=0, weight=0.0, delay=1.0))
    proj_3 = p.Projection(
        stim, pop_3, p.FromListConnector([(0, 0)]),
        p.StructuralMechanismSTDP(
            partner_selection=p.LastNeuronSelection(),
            formation=p.DistanceDependentFormation([1, 1], 0.0),
            elimination=p.RandomByWeightElimination(4.0, 1.0, 1.0),
            timing_dependence=p.SpikePairRule(
                tau_plus, tau_minus, A_plus, A_minus),
            weight_dependence=p.AdditiveWeightDependence(w_min, w_max),
            f_rew=1000, initial_weight=2.0, initial_delay=5.0,
            s_max=1, seed=0, weight=0.0, delay=1.0))
    proj_4 = p.Projection(
        stim, pop_4, p.FromListConnector([(0, 0)]),
        p.StructuralMechanismSTDP(
            partner_selection=p.RandomSelection(),
            formation=p.DistanceDependentFormation([1, 1], 0.0),
            elimination=p.RandomByWeightElimination(4.0, 1.0, 1.0),
            timing_dependence=p.SpikePairRule(
                tau_plus, tau_minus, A_plus, A_minus),
            weight_dependence=p.AdditiveWeightDependence(w_min, w_max),
            f_rew=1000, initial_weight=4.0, initial_delay=3.0,
            s_max=1, seed=0, weight=0.0, delay=1.0))
    p.run(10)

    conns = list(proj.get(["weight", "delay"], "list"))
    conns_2 = list(proj_2.get(["weight", "delay"], "list"))
    conns_3 = list(proj_3.get(["weight", "delay"], "list"))
    conns_4 = list(proj_4.get(["weight", "delay"], "list"))

    spikes_1 = [s.magnitude
                for s in pop.get_data("spikes").segments[0].spiketrains]
    spikes_2 = [s.magnitude
                for s in pop_2.get_data("spikes").segments[0].spiketrains]

    p.end()

    print(conns)
    print(conns_2)
    print(conns_3)
    print(conns_4)

    w_final_1 = calculate_spike_pair_additive_stdp_weight(
        pre_spikes_last_neuron, spikes_1[0], w_init_1, delay_1, w_max,
        A_plus, A_minus, tau_plus, tau_minus)
    w_final_2 = calculate_spike_pair_additive_stdp_weight(
        pre_spikes, spikes_2[0], w_init_2, delay_2, w_max, A_plus, A_minus,
        tau_plus, tau_minus)
    print(w_final_1, spikes_1[0])
    print(w_final_2, spikes_2[0])

    assert(len(conns) == 1)
    assert(conns[0][3] == delay_1)
    assert(conns[0][2] >= w_final_1 - 0.01 and
           conns[0][2] <= w_final_1 + 0.01)
    assert(len(conns_2) == 1)
    assert(conns_2[0][3] == delay_2)
    assert(conns_2[0][2] >= w_final_2 - 0.01 and
           conns_2[0][2] <= w_final_2 + 0.01)
    assert(len(conns_3) == 0)
    assert(len(conns_4) == 0)
예제 #19
0
def do_run(plot):

    p.setup(timestep=1.0)

    cell_params_lif = {'cm': 0.25,
                       'i_offset': 0.0,
                       'tau_m': 20.0,
                       'tau_refrac': 2.0,
                       'tau_syn_E': 5.0,
                       'tau_syn_I': 5.0,
                       'v_reset': -70.0,
                       'v_rest': -65.0,
                       'v_thresh': -40.0
                       }

    # Parameters
    n = 10
    weight_to_spike = 5.0
    delay = 5
    runtime = 200

    # Populations
    exc_pop = p.Population(n, p.IF_curr_exp(**cell_params_lif),
                           label='exc_pop')
    inh_pop = p.Population(n, p.IF_curr_exp(**cell_params_lif),
                           label='inh_pop')

    # SpikeInjector
    injectionConnection = [(0, 0)]
    spikeArray = {'spike_times': [[0]]}
    inj_pop = p.Population(1, p.SpikeSourceArray(**spikeArray),
                           label='inputSpikes_1')

    # Projection for injector
    p.Projection(inj_pop, exc_pop, p.FromListConnector(injectionConnection),
                 p.StaticSynapse(weight=weight_to_spike, delay=delay))

    # Set up fromfileconnectors by writing to file
    connection_list1 = [
                (0, 0, 0.1, 0.1),
                (3, 0, 0.2, 0.11),
                (2, 3, 0.3, 0.12),
                (5, 1, 0.4, 0.13),
                (0, 1, 0.5, 0.14),
                ]
    path1 = "test1.connections"
    if os.path.exists(path1):
        os.remove(path1)

    current_file_path = os.path.dirname(os.path.abspath(__file__))
    file1 = os.path.join(current_file_path, path1)
    numpy.savetxt(file1, connection_list1)
    file_connector1 = p.FromFileConnector(file1)

    connection_list2 = [
                (4, 9, 0.3, 0.12),
                (1, 5, 0.4, 0.13),
                (7, 6, 0.1, 0.1),
                (6, 5, 0.5, 0.14),
                (8, 2, 0.2, 0.11),
                ]
    path2 = "test2.connections"
    if os.path.exists(path2):
        os.remove(path2)

    file2 = path2
    numpy.savetxt(file2, connection_list2)
    file_connector2 = p.FromFileConnector(file2)

    # Projections within populations
    p.Projection(exc_pop, inh_pop, file_connector1,
                 p.StaticSynapse(weight=2.0, delay=5))
    p.Projection(inh_pop, exc_pop, file_connector2,
                 p.StaticSynapse(weight=1.5, delay=10))

    exc_pop.record(['v', 'spikes'])
    inh_pop.record(['v', 'spikes'])
    p.run(runtime)

    v_exc = exc_pop.get_data('v')
    spikes_exc = exc_pop.get_data('spikes')

    if plot:
        Figure(
            # raster plot of the presynaptic neurons' spike times
            Panel(spikes_exc.segments[0].spiketrains,
                  yticks=True, markersize=1.2, xlim=(0, runtime), xticks=True),
            # membrane potential of the postsynaptic neurons
            Panel(v_exc.segments[0].filter(name='v')[0],
                  ylabel="Membrane potential (mV)",
                  data_labels=[exc_pop.label], yticks=True,
                  xlim=(0, runtime), xticks=True),
            title="Testing FromFileConnector",
            annotations="Simulated with {}".format(p.name())
        )
        plt.show()

    p.end()

    return v_exc, spikes_exc
예제 #20
0
cd_pop.record("all")
#================================================================================================
# Projections
#================================================================================================
n_an_b_connections = RandomDistribution('uniform',[2.,5.])
w2s_b = 5.#
av_an_b = w2s_b/5.
an_b_weight = RandomDistribution('normal_clipped',[av_an_b,0.1*av_an_b,0,av_an_b*2.])
an_b_list, max_dist = normal_dist_connection_builder(number_of_inputs, n_b, RandomDistribution,
                                                     conn_num=n_an_b_connections, dist=1.,
                                                     sigma=1., conn_weight=an_b_weight, delay=timestep,
                                                     normalised_space=pop_size, get_max_dist=True)

# sim.Projection(input_pop,cd_pop,sim.FromListConnector([(0,0)]),synapse_type=sim.StaticSynapse(weight=w2s_b))
sim.Projection(input_pop, cd_pop, sim.FromListConnector(an_b_list),
                                       synapse_type=sim.StaticSynapse())

# sim.Projection(input_pop, cd_pop_2, sim.FromListConnector(an_b_list),
#                                        synapse_type=sim.StaticSynapse())


duration = test_dur_ms#max(input_spikes[0])

sim.run(duration)

cd_data =[]
cd_data.append(cd_pop.get_data())
# input_data = input_pop.get_data()

sim.end()
예제 #21
0
input = sim.Population(1, sim.SpikeSourceArray(spike_times=[[0], [1]]),
                       label="input")
pop = sim.Population(n_neurons, sim.IF_curr_exp(tau_syn_E=5), label="pop")

loop_conns = list()
for i in range(0, n_neurons - 1):
    single_connection = (i, i + 1, weight_to_spike, delay)
    loop_conns.append(single_connection)
single_connection = (n_neurons - 1, 0, weight_to_spike, delay)
loop_conns.append(single_connection)
print loop_conns

input_proj = sim.Projection(input, pop, sim.OneToOneConnector(),
                            synapse_type=sim.StaticSynapse(weight=5, delay=2))
loop_proj = sim.Projection(pop, pop, sim.FromListConnector(loop_conns))

pop.record(["spikes", "v"])
sim.run(simtime)

s_neo = pop.get_data(variables=["spikes"])
spikes = s_neo.segments[0].spiketrains
print spikes
v_neo = pop.get_data(variables=["v"])
v = v_neo.segments[0].filter(name='v')[0]
print v
print "shape"
print v.shape

sim.end()
예제 #22
0
def test_sender():

    # a new spynnaker live spikes connection is created to define that there is
    # a python function which receives the spikes.
    live_spikes_connection_receive = \
        Frontend.external_devices.SpynnakerLiveSpikesConnection(
            receive_labels=["pop_forward", "pop_backward"],
            local_port=None, send_labels=None)

    # Set up callbacks to occur when spikes are received
    live_spikes_connection_receive.add_receive_callback(
        "pop_forward", receive_spikes)
    live_spikes_connection_receive.add_receive_callback(
        "pop_backward", receive_spikes)

    ############################################################
    #             Start the external sender                    #
    ############################################################
    sender = subprocess.Popen(binary_path("sender"), stderr=subprocess.PIPE)
    firstline = str(sender.stderr.readline(), "UTF-8")
    match = re.match("^Listening on (.*)$", firstline)
    if not match:
        receiver.kill()
        raise Exception(f"Sender returned unknown output: {firstline}")
    sender_port = int(match.group(1))

    ############################################################
    # Setup a Simulation to be injected into and received from #
    ############################################################

    # initial call to set up the front end (pynn requirement)
    Frontend.setup(timestep=1.0, min_delay=1.0)

    # neurons per population and the length of runtime in ms for the simulation,
    # as well as the expected weight each spike will contain
    n_neurons = 100
    run_time = 8000
    weight_to_spike = 2.0

    # neural parameters of the ifcur model used to respond to injected spikes.
    # (cell params for a synfire chain)
    cell_params_lif = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 5.0,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -50.0
    }

    ##################################
    # Parameters for the injector population.
    # The virtual key is assigned here, rather than being allocated later.
    # Spikes injected need to match this key, and this will be done automatically
    # with 16-bit keys.
    ##################################
    cell_params_spike_injector_with_key = {

        # This is the base key to be used for the injection, which is used to
        # allow the keys to be routed around the spiNNaker machine.  This
        # assignment means that 32-bit keys must have the high-order 16-bit
        # set to 0x7; This will automatically be prepended to 16-bit keys.
        'virtual_key': 0x70000,
    }

    # create synfire populations (if cur exp)
    pop_forward = Frontend.Population(n_neurons,
                                      Frontend.IF_curr_exp(**cell_params_lif),
                                      label='pop_forward')
    pop_backward = Frontend.Population(n_neurons,
                                       Frontend.IF_curr_exp(**cell_params_lif),
                                       label='pop_backward')

    # Create injection populations
    injector_forward = Frontend.Population(
        n_neurons,
        Frontend.external_devices.SpikeInjector(
            database_notify_port_num=sender_port),
        label='spike_injector_forward',
        additional_parameters=cell_params_spike_injector_with_key)
    injector_backward = Frontend.Population(
        n_neurons,
        Frontend.external_devices.SpikeInjector(
            database_notify_port_num=sender_port),
        label='spike_injector_backward')

    # Create a connection from the injector into the populations
    Frontend.Projection(injector_forward, pop_forward,
                        Frontend.OneToOneConnector(),
                        Frontend.StaticSynapse(weight=weight_to_spike))
    Frontend.Projection(injector_backward, pop_backward,
                        Frontend.OneToOneConnector(),
                        Frontend.StaticSynapse(weight=weight_to_spike))

    # Synfire chain connections where each neuron is connected to its next neuron
    # NOTE: there is no recurrent connection so that each chain stops once it
    # reaches the end
    loop_forward = list()
    loop_backward = list()
    for i in range(0, n_neurons - 1):
        loop_forward.append((i, (i + 1) % n_neurons, weight_to_spike, 3))
        loop_backward.append(((i + 1) % n_neurons, i, weight_to_spike, 3))
    Frontend.Projection(pop_forward, pop_forward,
                        Frontend.FromListConnector(loop_forward))
    Frontend.Projection(pop_backward, pop_backward,
                        Frontend.FromListConnector(loop_backward))

    # record spikes from the synfire chains so that we can read off valid results
    # in a safe way afterwards, and verify the behavior
    pop_forward.record('spikes')
    pop_backward.record('spikes')

    # Activate the sending of live spikes
    Frontend.external_devices.activate_live_output_for(
        pop_forward,
        database_notify_port_num=live_spikes_connection_receive.local_port)
    Frontend.external_devices.activate_live_output_for(
        pop_backward,
        database_notify_port_num=live_spikes_connection_receive.local_port)

    # Run the simulation on spiNNaker
    Frontend.run(run_time)

    spikes_forward = pop_forward.get_data('spikes').segments[0].spiketrains
    spikes_backward = pop_backward.get_data('spikes').segments[0].spiketrains

    # Clear data structures on spiNNaker to leave the machine in a clean state
    # for future executions
    Frontend.end()

    print("Waiting for sender to stop...")
    sender.wait()
    print("Done")

    n_spikes = sum(len(s) for s in spikes_forward)
    n_spikes += sum(len(s) for s in spikes_backward)
    # Some sent spikes might get lost; 6 sent, 3 is fine
    assert (n_spikes >= 300)
예제 #23
0
    def __create_synfire_chain(n_neurons, cell_class, cell_params,
                               use_wrap_around_connections, weight_to_spike,
                               delay, spike_times, spike_times_list,
                               placement_constraint, randomise_v_init, seed,
                               constraint, input_class, rate, start_time,
                               duration, use_spike_connections):
        """ This actually builds the synfire chain. """
        populations = list()
        projections = list()

        loop_connections = list()
        if use_wrap_around_connections:
            for i in range(0, n_neurons):
                single_connection = \
                    (i, ((i + 1) % n_neurons), weight_to_spike, delay)
                loop_connections.append(single_connection)
        else:
            for i in range(0, n_neurons - 1):
                single_connection = (i, i + 1, weight_to_spike, delay)
                loop_connections.append(single_connection)

        injection_connection = [(0, 0, weight_to_spike, 1)]

        run_count = 0
        if spike_times_list is None:
            spike_array = {'spike_times': spike_times}
        else:
            spike_array = {'spike_times': spike_times_list[run_count]}

        populations.append(
            p.Population(n_neurons, cell_class(**cell_params), label='pop_1'))

        if placement_constraint is not None:
            if len(placement_constraint) == 2:
                (x, y) = placement_constraint
                populations[0].add_placement_constraint(x=x, y=y)
            else:
                (x, y, proc) = placement_constraint
                populations[0].add_placement_constraint(x=x, y=y, p=proc)

        if randomise_v_init:
            if seed is None:
                v_init = p.RandomDistribution('uniform', [-60, -40])
            else:
                v_init = p.RandomDistribution('uniform', [-60, -40],
                                              NumpyRNG(seed=seed))
            populations[0].initialize(v=v_init)

        if constraint is not None:
            populations[0].set_constraint(constraint)

        if input_class == SpikeSourceArray:
            populations.append(
                p.Population(1, input_class(**spike_array),
                             label='inputSSA_1'))
        elif seed is None:
            populations.append(
                p.Population(1,
                             input_class(rate=rate,
                                         start=start_time,
                                         duration=duration),
                             label='inputSSP_1'))
        else:
            populations.append(
                p.Population(1,
                             input_class(rate=rate,
                                         start=start_time,
                                         duration=duration,
                                         seed=seed),
                             label='inputSSP_1'))

        # handle projections
        if use_spike_connections:
            projections.append(
                p.Projection(
                    populations[0], populations[0],
                    p.FromListConnector(loop_connections),
                    p.StaticSynapse(weight=weight_to_spike, delay=delay)))

        projections.append(
            p.Projection(populations[1], populations[0],
                         p.FromListConnector(injection_connection),
                         p.StaticSynapse(weight=weight_to_spike, delay=1)))

        return populations, projections, run_count
예제 #24
0
    def make_inference_network(self, weights=None):

        self.populations['spike_sender'] = Frontend.Population(
            self.n_neurons,
            ExternalDevices.SpikeInjector(),
            additional_parameters={'port': 12345},
            label="spike_sender")

        self.populations['cann_pop'] = Frontend.Population(
            self.n_neurons,
            Frontend.IF_curr_exp(),  #**neuron_params),
            label="cann_pop")

        self.populations['inh_pop'] = Frontend.Population(
            1,
            Frontend.IF_curr_exp(),  #**neuron_params),
            label="inh_pop")

        Frontend.Projection(
            self.populations['spike_sender'], self.populations['cann_pop'],
            Frontend.OneToOneConnector(),
            Frontend.StaticSynapse(weight=self.weight_input2cann,
                                   delay=self.delay_input2cann))

        self.projections['cann2inh'] = Frontend.Projection(
            self.populations['cann_pop'],
            self.populations['inh_pop'],
            Frontend.AllToAllConnector(),
            synapse_type=Frontend.StaticSynapse(weight=self.weight_cann2inh,
                                                delay=self.delay_cann2inh),
            receptor_type="excitatory")

        self.projections['inh2cann'] = Frontend.Projection(
            self.populations['inh_pop'],
            self.populations['cann_pop'],
            Frontend.AllToAllConnector(),
            synapse_type=Frontend.StaticSynapse(weight=self.weight_inhibitory,
                                                delay=self.delay_inh2cann),
            receptor_type="inhibitory")

        # LEGI logic for a ring network
        for i in range(self.n_neurons):
            for j in range(self.n_neurons):
                self.dist[i][j] = abs(i - j) % (self.n_neurons)
                if self.dist[i][j] > self.n_neurons / 2:
                    self.dist[i][j] = self.n_neurons - self.dist[i][j]
                self.weights[i][j] = round(self.weight_to_spike * \
                    (1 / (self.sig * np.sqrt(2 * np.pi)) * \
                    (np.exp(-np.power(self.dist[i][j] - self.mu, 2.) \
                    / (2 * np.power(self.sig, 2.))))), 2)
                self.cann_connector.append(
                    (i, j, self.weights[i][j], self.delay_cann2cann))
        # print "Distance matrix:\n", self.dist
        print "Weight matrix:\n", self.weights
        # print "CANN connector:\n",self.cann_connector

        self.projections['cann2cann'] = Frontend.Projection(
            self.populations['cann_pop'],
            self.populations['cann_pop'],
            Frontend.FromListConnector(self.cann_connector),
            receptor_type="excitatory")

        ExternalDevices.activate_live_output_for(
            self.populations['cann_pop'],
            database_notify_host="localhost",
            database_notify_port_num=19996)

        ExternalDevices.activate_live_output_for(
            self.populations['inh_pop'],
            database_notify_host="localhost",
            database_notify_port_num=19998)

        # Recording the values from populations during simulation
        self.populations['cann_pop'].record('spikes')
        self.populations['inh_pop'].record('spikes')
        self.populations['cann_pop'].record('v')
        self.populations['inh_pop'].record('v')
        self.populations['spike_sender'].record('spikes')
# Set up the PushBot control
pushbot = p.Population(len(devices),
                       p.external_devices.PushBotLifSpinnakerLink(
                           protocol=pushbot_protocol,
                           devices=devices,
                           tau_syn_E=500.0),
                       label="PushBot")

# Send in some spikes
stimulation = p.Population(
    len(devices),
    p.SpikeSourceArray(spike_times=[[i * 1000] for i in range(len(devices))]),
    label="input")

connections = [(i, i, weights[device], 1) for i, device in enumerate(devices)]
p.Projection(stimulation, pushbot, p.FromListConnector(connections))

retina_resolution = \
    p.external_devices.PushBotRetinaResolution.DOWNSAMPLE_64_X_64
pushbot_retina = p.Population(
    retina_resolution.value.n_neurons,
    p.external_devices.PushBotSpiNNakerLinkRetinaDevice(
        spinnaker_link_id=spinnaker_link,
        board_address=board_address,
        protocol=pushbot_protocol,
        resolution=retina_resolution))

viewer = p.external_devices.PushBotRetinaViewer(retina_resolution.value,
                                                port=17895)
p.external_devices.activate_live_output_for(pushbot_retina,
                                            port=viewer.local_port,
예제 #26
0
def do_run(nNeurons):
    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)

    p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2)

    cell_params_lif = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 5.0,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -50.0
    }

    p.set_number_of_neurons_per_core(p.IF_cond_exp, nNeurons / 2)

    cell_params_cond = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 5.0,
        'tau_syn_I': 5.0,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -50.0,
        'e_rev_E': 0.,
        'e_rev_I': -80.
    }

    populations = list()
    projections = list()

    weight_to_spike = 0.035
    delay = 17

    injectionConnection = [(0, 0, weight_to_spike, delay)]
    sinkConnection = [(0, 0, weight_to_spike, 1)]

    spikeArray = {'spike_times': [[0]]}

    populations.append(
        p.Population(nNeurons,
                     p.IF_cond_exp,
                     cell_params_cond,
                     label='pop_cond'))
    populations.append(
        p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_1'))

    populations.append(
        p.Population(nNeurons,
                     p.IF_curr_exp,
                     cell_params_lif,
                     label='pop_curr'))
    populations.append(
        p.Population(1, p.SpikeSourceArray, spikeArray, label='inputSpikes_2'))

    populations.append(
        p.Population(nNeurons,
                     p.IF_curr_exp,
                     cell_params_lif,
                     label='sink_pop'))

    projections.append(
        p.Projection(populations[1], populations[0],
                     p.FromListConnector(injectionConnection)))
    projections.append(
        p.Projection(populations[3], populations[2],
                     p.FromListConnector(injectionConnection)))
    projections.append(
        p.Projection(populations[0], populations[4],
                     p.FromListConnector(sinkConnection)))
    projections.append(
        p.Projection(populations[2], populations[4],
                     p.FromListConnector(sinkConnection)))
    populations[0].record("v")
    populations[0].record("gsyn_exc")
    populations[0].record("spikes")

    populations[2].record("v")
    populations[2].record("gsyn_exc")
    populations[2].record("spikes")

    p.run(500)

    neo = populations[0].get_data(["v", "spikes", "gsyn_exc"])

    cond_v = neo_convertor.convert_data(neo, name="v")
    cond_gsyn = neo_convertor.convert_data(neo, name="gsyn_exc")
    cond_spikes = neo_convertor.convert_spikes(neo)

    neo = populations[2].get_data(["v", "spikes", "gsyn_exc"])

    curr_v = neo_convertor.convert_data(neo, name="v")
    curr_gsyn = neo_convertor.convert_data(neo, name="gsyn_exc")
    curr_spikes = neo_convertor.convert_spikes(neo)

    p.end()

    return (cond_v, cond_gsyn, cond_spikes, curr_v, curr_gsyn, curr_spikes)
예제 #27
0
loopConnections = list()
for i in range(0, nNeurons):
    singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay))
    loopConnections.append(singleConnection)

injectionConnection = [(0, 0)]
spikeArray = {'spike_times': [[0]]}
populations.append(
    p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1'))
populations.append(
    p.Population(1, p.SpikeSourceArray(**spikeArray), label='inputSpikes_1'))

projections.append(
    p.Projection(populations[0], populations[0],
                 p.FromListConnector(loopConnections),
                 p.StaticSynapse(weight=weight_to_spike, delay=delay)))
projections.append(
    p.Projection(populations[1], populations[0],
                 p.FromListConnector(injectionConnection),
                 p.StaticSynapse(weight=weight_to_spike, delay=1)))

populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes'])

# New Parts

p.external_devices.activate_live_output_for(populations[0])


def receive_spikes(label, time, neuron_ids):
    print "Received spikes from population {}, neurons {} at time {}".format(
예제 #28
0
    def _interconnect_neurons_inhexc(self, network, verbose=False):

        assert network is not None, \
            "ERROR: Network is not initialised! Interconnecting for inhibitory and excitatory patterns failed."

        if verbose and self.cell_params['topological']['radius_i'] < self.dim_x:
            print "WARNING: Bad radius of inhibition. Uniquness constraint cannot be satisfied."
        if verbose and 0 <= self.cell_params['topological']['radius_e'] > self.dim_x:
            print "WARNING: Bad radius of excitation. "

        # create lists with inhibitory along the Retina Right projective line
        nbhoodInhL = []
        nbhoodInhR = []
        nbhoodExcX = []
        nbhoodEcxY = []
        # used for the triangular form of the matrix in order to remain within the square
        if verbose:
            print "INFO: Generating inhibitory and excitatory connectivity patterns."
        # generate rows
        limiter = self.max_disparity - self.min_disparity + 1
        ensembleIndex = 0

        while ensembleIndex < len(network):
            if ensembleIndex / (self.max_disparity - self.min_disparity + 1) > \
                                    (self.dim_x - self.min_disparity) - (self.max_disparity - self.min_disparity) - 1:
                limiter -= 1
                if limiter == 0:
                    break
            nbhoodInhL.append([ensembleIndex + disp for disp in range(0, limiter)])
            ensembleIndex += limiter

        ensembleIndex = len(network)

        # generate columns
        nbhoodInhR = [[x] for x in nbhoodInhL[0]]
        shiftGlob = 0
        for x in nbhoodInhL[1:]:
            shiftGlob += 1
            shift = 0

            for e in x:
                if (shift + 1) % (self.max_disparity - self.min_disparity + 1) == 0:
                    nbhoodInhR.append([e])
                else:
                    nbhoodInhR[shift + shiftGlob].append(e)
                shift += 1

        # generate all diagonals
        for diag in map(None, *nbhoodInhL):
            sublist = []
            for elem in diag:
                if elem is not None:
                    sublist.append(elem)
            nbhoodExcX.append(sublist)

        # generate all y-axis excitation
        for x in range(0, self.dim_y):
            for e in range(1, self.cell_params['topological']['radius_e'] + 1):
                if x + e < self.dim_y:
                    nbhoodEcxY.append(
                        (x, x + e, self.cell_params['synaptic']['wCCe'], self.cell_params['synaptic']['dCCe']))
                if x - e >= 0:
                    nbhoodEcxY.append(
                        (x, x - e, self.cell_params['synaptic']['wCCe'], self.cell_params['synaptic']['dCCe']))

        # Store these lists as global parameters as they can be used to quickly match the spiking collector neuron
        # with the corresponding pixel xy coordinates (same_disparity_indices)
        # TODO: think of a better way to encode pixels: closed form formula would be perfect
        # These are also used when connecting the spike sources to the network! (retina_proj_l, retina_proj_r)

        global _retina_proj_l, _retina_proj_r, same_disparity_indices

        _retina_proj_l = nbhoodInhL
        _retina_proj_r = nbhoodInhR
        same_disparity_indices = nbhoodExcX

        if verbose:
            print "INFO: Connecting neurons for internal excitation and inhibition."

        for row in nbhoodInhL:
            for pop in row:
                for nb in row:
                    if nb != pop:
                        ps.Projection(network[pop][1],
                                      network[nb][1],
                                      #ps.OneToOneConnector(weights=self.cell_params['synaptic']['wCCi'],
                                      #                     delays=self.cell_params['synaptic']['dCCi']),
                                      #target='inhibitory')
                                      ps.OneToOneConnector(),
                                      ps.StaticSynapse(weight=self.cell_params['synaptic']['wCCi'], delay=self.cell_params['synaptic']['dCCi']),
                                      receptor_type='inhibitory')

        for col in nbhoodInhR:
            for pop in col:
                for nb in col:
                    if nb != pop:
                        ps.Projection(network[pop][1],
                                      network[nb][1],
                                      ps.OneToOneConnector(),
                                      ps.StaticSynapse(weight=self.cell_params['synaptic']['wCCi'],
                                                           delay=self.cell_params['synaptic']['dCCi']),
                                      #ps.OneToOneConnector(weights=self.cell_params['synaptic']['wCCi'],
                                      #                     delays=self.cell_params['synaptic']['dCCi']),
                                      #target='inhibitory'
                                      receptor_type='inhibitory')

        for diag in nbhoodExcX:
            for pop in diag:
                for nb in range(1, self.cell_params['topological']['radius_e'] + 1):
                    if diag.index(pop) + nb < len(diag):
                        ps.Projection(network[pop][1],
                                      network[diag[diag.index(pop) + nb]][1],
                                      ps.OneToOneConnector(),
                                      ps.StaticSynapse(weight=self.cell_params['synaptic']['wCCe'],
                                                           delay=self.cell_params['synaptic']['dCCe']),
                                      receptor_type='excitatory')
                                      #ps.OneToOneConnector(weights=self.cell_params['synaptic']['wCCe'],
                                      #                     delays=self.cell_params['synaptic']['dCCe']),
                                      #target='excitatory')
                    if diag.index(pop) - nb >= 0:
                        ps.Projection(network[pop][1],
                                      network[diag[diag.index(pop) - nb]][1],
                                      ps.OneToOneConnector(),
                                      ps.StaticSynapse(weight=self.cell_params['synaptic']['wCCe'],
                                                           delay=self.cell_params['synaptic']['dCCe']),
                                      receptor_type='excitatory')
                                      #ps.OneToOneConnector(weights=self.cell_params['synaptic']['wCCe'],
                                      #                     delays=self.cell_params['synaptic']['dCCe']),
                                      #target='excitatory')

        for ensemble in network:
            ps.Projection(ensemble[1], ensemble[1], ps.FromListConnector(nbhoodEcxY), receptor_type='excitatory')#target='excitatory')
예제 #29
0
        timing_dependence=sim.SpikePairRule(tau_plus=tau_plus,
                                            tau_minus=tau_minus,
                                            A_plus=a_plus,
                                            A_minus=a_minus),
        weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=g_max),
        backprop_delay=False)
elif case == CASE_CORR_NO_REW:
    structure_model_w_stdp = stdp_model

# structure_model_w_stdp = sim.StructuralMechanism(weight=g_max, s_max=s_max)

if not args.lesion:
    print("No insults")
    ff_projection = sim.Projection(source_pop,
                                   target_pop,
                                   sim.FromListConnector(init_ff_connections),
                                   synapse_type=structure_model_w_stdp,
                                   label="plastic_ff_projection")

    lat_projection = sim.Projection(
        target_pop,
        target_pop,
        sim.FromListConnector(init_lat_connections),
        synapse_type=structure_model_w_stdp,
        label="plastic_lat_projection",
        receptor_type="inhibitory"
        if args.lateral_inhibition else "excitatory")
elif args.lesion == ONE_TO_ONE_LESION:
    # ff_pos = range(len(init_ff_connections))
    # lat_pos = range(len(init_lat_connections))
    # subsample_ff = np.random.choice(ff_pos, 10)
예제 #30
0
delay = 17

loopConnections = list()
for i in range(0, nNeurons):
    singleConnection = ((i, (i + 1) % nNeurons, weight_to_spike, delay))
    loopConnections.append(singleConnection)

injectionConnection = [(0, 0)]
spikeArray = {'spike_times': [[0]]}
populations.append(
    p.Population(nNeurons, p.IF_curr_exp(**cell_params_lif), label='pop_1'))
populations.append(
    p.Population(1, p.external_devices.SpikeInjector(), label='inputSpikes_1'))

projections.append(p.Projection(
    populations[0], populations[0], p.FromListConnector(loopConnections),
    p.StaticSynapse(weight=weight_to_spike, delay=delay)))
projections.append(p.Projection(
    populations[1], populations[0], p.FromListConnector(injectionConnection),
    p.StaticSynapse(weight=weight_to_spike, delay=1)))

populations[0].record(['v', 'gsyn_exc', 'gsyn_inh', 'spikes'])

# New Parts

p.external_devices.activate_live_output_for(populations[0])


def receive_spikes(label, time, neuron_ids):
    print "Received spikes from population {}, neurons {} at time {}".format(
        label, neuron_ids, time)