示例#1
0
def do_run():
    """
    test that tests the printing of v from a pre determined recording
    :return:
    """
    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
    n_neurons = 128 * 128  # number of neurons in each population
    p.set_number_of_neurons_per_core(p.IF_cond_exp, 256)

    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,
                       'e_rev_E': 0.,
                       'e_rev_I': -80.
                       }

    populations = list()
    projections = list()

    weight_to_spike = 0.035
    delay = 17

    spikes = read_spikefile('test.spikes', n_neurons)
    spike_array = {'spike_times': spikes}

    populations.append(p.Population(
        n_neurons, p.SpikeSourceArray, spike_array,
        label='inputSpikes_1'))
    populations.append(p.Population(
        n_neurons, p.IF_cond_exp, cell_params_lif, label='pop_1'))
    projections.append(p.Projection(
        populations[0], populations[1], p.OneToOneConnector(),
        synapse_type=p.StaticSynapse(weight=weight_to_spike, delay=delay)))
    populations[1].record("spikes")

    p.run(1000)

    spikes = populations[1].spinnaker_get_data('spikes')

    p.end()

    return spikes
def do_run(split, seed=None):
    p.setup(1.0)

    if split:
        p.set_number_of_neurons_per_core(p.SpikeSourcePoisson, 27)
        p.set_number_of_neurons_per_core(p.IF_curr_exp, 22)

    inp = p.Population(100,
                       p.SpikeSourcePoisson(rate=100, seed=seed),
                       label="input")
    pop = p.Population(100, p.IF_curr_exp, {}, label="pop")

    p.Projection(inp,
                 pop,
                 p.OneToOneConnector(),
                 synapse_type=p.StaticSynapse(weight=5))

    pop.record("spikes")
    inp.record("spikes")

    p.run(100)

    inp.set(rate=10)
    # pop.set("cm", 0.25)
    pop.set(tau_syn_E=1)

    p.run(100)

    pop_spikes1 = pop.spinnaker_get_data('spikes')
    inp_spikes1 = inp.spinnaker_get_data('spikes')

    p.reset()

    inp.set(rate=0)
    pop.set(i_offset=1.0)
    vs = p.RandomDistribution("uniform", [-65.0, -55.0],
                              rng=NumpyRNG(seed=seed))
    pop.initialize(v=vs)

    p.run(100)

    pop_spikes2 = pop.spinnaker_get_data('spikes')
    inp_spikes2 = inp.spinnaker_get_data('spikes')

    p.end()

    return (pop_spikes1, inp_spikes1, pop_spikes2, inp_spikes2)
def do_run(nNeurons):

    p.setup(timestep=0.1, min_delay=1.0, max_delay=7.5)
    p.set_number_of_neurons_per_core(p.IF_curr_exp, 100)

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

    populations = list()
    projections = list()

    weight_to_spike = 12
    injection_delay = 1
    delay = 1

    spikeArray = {'spike_times': [[0, 10, 20, 30]]}
    populations.append(p.Population(1, p.SpikeSourceArray, spikeArray,
                                    label='pop_0'))
    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'))

    connector = p.AllToAllConnector()
    synapse_type = p.StaticSynapse(weight=weight_to_spike,
                                   delay=injection_delay)
    projections.append(p.Projection(populations[0], populations[1], connector,
                                    synapse_type=synapse_type))
    connector = p.OneToOneConnector()
    synapse_type = p.StaticSynapse(weight=weight_to_spike, delay=delay)
    projections.append(p.Projection(populations[1], populations[2], connector,
                                    synapse_type=synapse_type))

    populations[1].record("v")
    populations[1].record("spikes")

    p.run(100)

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

    v = neo_convertor.convert_data(neo, name="v")
    spikes = neo_convertor.convert_spikes(neo)

    p.end()

    return (v, spikes)
    def test_cause_error(self):
        with self.assertRaises(ConfigurationException):
            sim.setup(timestep=1.0)
            sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100)

            pop_1 = sim.Population(1, sim.IF_curr_exp(), label="pop_1")
            input = sim.Population(1,
                                   sim.SpikeSourceArray(spike_times=[0]),
                                   label="input")
            sim.Projection(input,
                           pop_1,
                           sim.OneToOneConnector(),
                           synapse_type=sim.StaticSynapse(weight=5, delay=1))
            simtime = 10
            sim.run(simtime)

            pop_1.get_data(variables=["v"])
示例#5
0
def test_levels(rates=(500, 1000), weights=(0.005, 0.0005)):
    counter = 0
    receive_pop = []
    spike_input = []
    p.setup(timestep=1, min_delay=1, max_delay=127)
    p.set_number_of_neurons_per_core(p.IF_cond_exp, 10)
    for rate in rates:
        for weight in weights:
            pop_size = 10
            receive_pop.append(p.Population(pop_size, p.IF_cond_exp(
            )))  #, label="receive_pop{}-{}".format(rate, weight)))

            receive_pop[counter].record(['spikes', 'v'])  #["spikes"])

            # Connect key spike injector to input population
            spike_input.append(
                p.Population(pop_size, p.SpikeSourcePoisson(rate=rate))
            )  #, label="input_connect{}-{}".format(rate, weight)))
            p.Projection(spike_input[counter], receive_pop[counter],
                         p.OneToOneConnector(), p.StaticSynapse(weight=weight))

            print "reached here 1"
            runtime = 11000

            counter += 1

    p.run(runtime)
    print "reached here 2"

    for i in range(counter):
        weight_index = i % len(weights)
        rate_index = (i - weight_index) / len(weights)
        print weight_index
        print rate_index
        # for j in range(receive_pop_size):
        spikes = receive_pop[i].get_data('spikes').segments[0].spiketrains
        v = receive_pop[i].get_data('v').segments[0].filter(name='v')[0]
        plt.figure("rate = {} - weight = {}".format(rates[rate_index],
                                                    weights[weight_index]))
        Figure(Panel(spikes, xlabel="Time (ms)", ylabel="nID", xticks=True),
               Panel(v, ylabel="Membrane potential (mV)", yticks=True))
        plt.show()

    # End simulation
    p.end()
 def test_using_static_synapse_singles1(self):
     sim.setup(timestep=1.0)
     input = sim.Population(2, sim.SpikeSourceArray([0]), label="input")
     pop = sim.Population(2, sim.IF_curr_exp(), label="pop")
     conn = sim.Projection(
         input, pop, sim.OneToOneConnector(),
         sim.StaticSynapse(weight=[0.7, 0.3], delay=[3, 33]))
     try:
         sim.run(1)
     except Exception:
         self.known_issue(
             "https://github.com/SpiNNakerManchester/sPyNNaker/issues/618")
     weights = conn.get(['weight', 'delay'], 'list')
     sim.end()
     target = [(0, 0, 0.7, 3), (1, 1, 0.3, 33)]
     for i in range(2):
         for j in range(2):
             self.assertAlmostEqual(weights[i][j], target[i][j], places=3)
def do_run():
    # this test ensures there is too much dtcm used up, thus crashes during
    # initisation
    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)

    input_pop = p.Population(1024, p.SpikeSourcePoisson, {'rate': 10}, "input")
    relay_on = p.Population(1024, p.IF_curr_exp, {}, "input")

    t_rule_LGN = p.SpikePairRule(tau_plus=17, tau_minus=34, A_plus=0.01,
                                 A_minus=0.0085)
    w_rule_LGN = p.AdditiveWeightDependence(w_min=0.0, w_max=0.3)
    stdp_model_LGN = p.STDPMechanism(timing_dependence=t_rule_LGN,
                                     weight_dependence=w_rule_LGN, weight=1)
    # TODO weights=1
    p.Projection(input_pop, relay_on, p.OneToOneConnector(),
                 synapse_type=stdp_model_LGN, receptor_type="excitatory")

    p.run(1000)
    p.end()
    def do_run_with_reset(self):
        sim.setup(timestep=1.0)
        runtime = 500
        n_neurons = 10
        spikegap = 50

        spike_times = list(n for n in range(0, runtime, spikegap))
        pop_src = sim.Population(n_neurons,
                                 sim.SpikeSourceArray(spike_times),
                                 label="src")

        pop_lif = sim.Population(n_neurons, sim.IF_curr_exp(), label="lif")

        weight = 5
        delay = 5

        # define the projection
        sim.Projection(pop_src,
                       pop_lif,
                       sim.OneToOneConnector(),
                       sim.StaticSynapse(weight=weight, delay=delay),
                       receptor_type="excitatory")

        pop_lif.record("all")

        sim.run(runtime // 2)

        # add another population to ensure a hard reset
        sim.Population(n_neurons, sim.IF_curr_exp(), label="lif2")
        sim.reset()

        sim.run(runtime // 2)

        pps = pop_lif.get_data()

        totalpackets = sum(
            pps.segments[0].filter(name='packets-per-timestep')[0]) + sum(
                pps.segments[1].filter(name='packets-per-timestep')[0])

        assert (totalpackets == n_neurons * (runtime // spikegap))

        sim.end()
    def test_recording_poisson_spikes_rate_0(self):
        p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
        n_neurons = 256  # number of neurons in each population
        p.set_number_of_neurons_per_core(p.IF_curr_exp, n_neurons / 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
        }

        populations = list()
        projections = list()

        populations.append(
            p.Population(n_neurons,
                         p.IF_curr_exp,
                         cell_params_lif,
                         label='pop_1'))
        populations.append(
            p.Population(n_neurons,
                         p.SpikeSourcePoisson, {'rate': 0},
                         label='inputSpikes_1'))

        projections.append(
            p.Projection(populations[1], populations[0],
                         p.OneToOneConnector()))

        populations[1].record("spikes")

        p.run(5000)

        spikes = populations[1].get_data("spikes")
        print(spikes)

        p.end()
示例#10
0
 def no_change_v(self):
     sim.setup(1.0)
     pop = sim.Population(1, sim.IF_curr_exp, {}, label="pop")
     inp = sim.Population(1,
                          sim.SpikeSourceArray(spike_times=[0]),
                          label="input")
     sim.Projection(inp,
                    pop,
                    sim.OneToOneConnector(),
                    synapse_type=sim.StaticSynapse(weight=5))
     pop.set(i_offset=1.0)
     pop.set(tau_syn_E=1)
     pop.record(["v"])
     sim.run(5)
     sim.reset()
     inp.set(spike_times=[100])
     sim.run(5)
     v2 = pop.spinnaker_get_data('v')
     self.check_from_65(v2)
     sim.end()
示例#11
0
def do_run():

    p.setup(timestep=1.0)
    inp = p.Population(1, p.SpikeSourceArray(spike_times=[0]))
    out = p.Population(1, p.IF_curr_exp())

    connector = p.OneToOneConnector()

    proj_1 = p.Projection(inp, out, connector,
                          p.StaticSynapse(weight=2.0, delay=2.0))
    proj_2 = p.Projection(inp, out, connector,
                          p.StaticSynapse(weight=1.0, delay=1.0))

    p.run(1)

    proj_1_list = proj_1.get(("weight", "delay"), "list")
    proj_2_list = proj_2.get(("weight", "delay"), "list")
    p.end()

    return proj_1_list, proj_2_list
示例#12
0
def do_run():
    p.setup(timestep=1, min_delay=1)

    spiker = p.Population(1,
                          p.SpikeSourceArray(spike_times=[[5, 25]]),
                          label='inputSSA')

    if_pop = p.Population(1, p.IF_cond_exp(), label='pop')

    if_pop.record("spikes")
    if_pop.record("v")

    runtime = 30

    # Create projection with delay such that the second spike occurs after
    # the run has finished
    weight = 5.0
    delay = 7
    p.Projection(spiker,
                 if_pop,
                 p.OneToOneConnector(),
                 synapse_type=p.StaticSynapse(weight=weight, delay=delay),
                 receptor_type="excitatory",
                 source=None,
                 space=None)

    p.run(runtime)
    all1 = if_pop.get_data(["spikes", "v"])

    # Reset (to time=0) and run again
    p.reset()
    p.run(runtime)
    all2 = if_pop.get_data(["spikes", "v"])

    p.end()

    return (all1, all2)
示例#13
0
def do_run():
    p.setup(timestep=1, min_delay=1, max_delay=15)

    spiker = p.Population(1, p.SpikeSourceArray(spike_times=[[0]]),
                          label='inputSSA_1')

    if_pop = p.Population(2, p.IF_cond_exp(), label='pop_1')

    if_pop.record("spikes")
    if_pop.record("v")
    p.Projection(spiker, if_pop, p.OneToOneConnector(),
                 synapse_type=p.StaticSynapse(weight=5.0, delay=1),
                 receptor_type="excitatory", source=None, space=None)

    p.run(30)
    all1 = if_pop.get_data(["spikes", "v"])

    p.reset()
    p.run(30)
    all2 = if_pop.get_data(["spikes", "v"])

    p.end()

    return (all1, all2)
示例#14
0
    def recording_1_element(self):
        sim.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
        n_neurons = 200

        boxed_array = numpy.zeros(shape=(0, 2))
        spike_array = list()
        for neuron_id in range(0, n_neurons):
            spike_array.append(list())
            for counter in range(0, 50):
                random_time = random.randint(0, 4999)
                boxed_array = numpy.append(boxed_array,
                                           [[neuron_id, random_time]],
                                           axis=0)
                spike_array[neuron_id].append(random_time)
        spike_array_params = {'spike_times': spike_array}
        pop1 = sim.Population(n_neurons, sim.IF_curr_exp, {}, label='pop_1')
        pop1.record("all")
        input = sim.Population(n_neurons,
                               sim.SpikeSourceArray,
                               spike_array_params,
                               label='inputSpikes_1')
        input.record("spikes")

        sim.Projection(input, pop1, sim.OneToOneConnector())

        sim.run(5000)

        spike_array_spikes = input.spinnaker_get_data("spikes")
        boxed_array = boxed_array[numpy.lexsort(
            (boxed_array[:, 1], boxed_array[:, 0]))]
        for i in range(len(spike_array_spikes)):
            numpy.testing.assert_array_equal(spike_array_spikes[i],
                                             boxed_array[i])
        numpy.testing.assert_array_equal(spike_array_spikes, boxed_array)

        sim.end()
示例#15
0
        # Stimulating populations
        pre_times = generate_fixed_frequency_test_data(f, start_time - 1,
                                                       num_pairs + 1)
        post_times = generate_fixed_frequency_test_data(
            f, start_time + t, num_pairs)
        pre_stim = sim.Population(
            1, sim.SpikeSourceArray(spike_times=[pre_times]))
        post_stim = sim.Population(
            1, sim.SpikeSourceArray(spike_times=[post_times]))

        # Update simulation time
        sim_time = max(sim_time, max(max(pre_times), max(post_times)) + 100)

        # Connections between spike sources and neuron populations
        ee_connector = sim.OneToOneConnector()
        sim.Projection(pre_stim,
                       pre_pop,
                       ee_connector,
                       receptor_type='excitatory',
                       synapse_type=sim.StaticSynapse(weight=2))
        sim.Projection(post_stim,
                       post_pop,
                       ee_connector,
                       receptor_type='excitatory',
                       synapse_type=sim.StaticSynapse(weight=2))

        # **HACK**
        param_scale = 0.5

        # Plastic Connection between pre_pop and post_pop
    def potentiation_and_depression(self):
        p.setup(1)
        runtime = 100
        initial_run = 1000  # to negate any initial conditions

        # STDP parameters
        a_plus = 0.1
        a_minus = 0.0375
        tau_plus = 20
        tau_minus = 64
        plastic_delay = 1
        initial_weight = 0.05
        max_weight = 0.1
        min_weight = 0

        pre_spikes = [10, 50]
        extra_spikes = [30]

        for i in range(len(pre_spikes)):
            pre_spikes[i] += initial_run

        for i in range(len(extra_spikes)):
            extra_spikes[i] += initial_run

        # Spike source to send spike via plastic synapse
        pre_pop = p.Population(1,
                               p.SpikeSourceArray, {'spike_times': pre_spikes},
                               label="pre")

        # Spike source to send spike via static synapse to make
        # post-plastic-synapse neuron fire
        extra_pop = p.Population(1,
                                 p.SpikeSourceArray,
                                 {'spike_times': extra_spikes},
                                 label="extra")

        # Post-plastic-synapse population
        post_pop = p.Population(1, p.IF_cond_exp(), label="post")

        # Create projections
        p.Projection(pre_pop,
                     post_pop,
                     p.OneToOneConnector(),
                     p.StaticSynapse(weight=0.1, delay=1),
                     receptor_type="excitatory")

        p.Projection(extra_pop,
                     post_pop,
                     p.OneToOneConnector(),
                     p.StaticSynapse(weight=0.1, delay=1),
                     receptor_type="excitatory")

        syn_plas = p.STDPMechanism(
            timing_dependence=p.extra_models.SpikeNearestPairRule(
                tau_plus=tau_plus,
                tau_minus=tau_minus,
                A_plus=a_plus,
                A_minus=a_minus),
            weight_dependence=p.AdditiveWeightDependence(w_min=min_weight,
                                                         w_max=max_weight),
            weight=initial_weight,
            delay=plastic_delay)

        plastic_synapse = p.Projection(pre_pop,
                                       post_pop,
                                       p.OneToOneConnector(),
                                       synapse_type=syn_plas,
                                       receptor_type='excitatory')

        # Record the spikes
        post_pop.record("spikes")

        # Run
        p.run(initial_run + runtime)

        # Get the weights
        weights = plastic_synapse.get('weight', 'list', with_address=False)

        # Get the spikes
        post_spikes = numpy.array(
            # pylint: disable=no-member
            post_pop.get_data('spikes').segments[0].spiketrains[0].magnitude)

        # End the simulation as all information gathered
        p.end()

        # Get the spikes and time differences that will be considered by
        # the simulation (as the last pre-spike will be considered differently)
        pre_spikes = numpy.array(pre_spikes)
        last_pre_spike = pre_spikes[-1]
        considered_post_spikes = post_spikes[post_spikes < last_pre_spike]
        considered_post_spikes += plastic_delay
        potentiation_times = list()
        depression_times = list()
        for time in pre_spikes:
            post_times = considered_post_spikes[considered_post_spikes > time]
            if len(post_times) > 0:
                last_time = post_times[0]
                potentiation_times.append(time - last_time)
            post_times = considered_post_spikes[considered_post_spikes < time]
            if len(post_times) > 0:
                last_time = post_times[-1]
                depression_times.append(last_time - time)
        potentiation_times = numpy.array(potentiation_times)
        depression_times = numpy.array(depression_times)

        # Work out the weight according to the rules
        potentiations = max_weight * a_plus * numpy.exp(
            (potentiation_times / tau_plus))
        depressions = max_weight * a_minus * numpy.exp(
            (depression_times / tau_minus))
        new_weight_exact = \
            initial_weight + numpy.sum(potentiations) - numpy.sum(depressions)

        # print("Pre neuron spikes at: {}".format(pre_spikes))
        # print("Post-neuron spikes at: {}".format(post_spikes))
        target_spikes = [1013, 1032, 1051, 1056]
        self.assertListEqual(list(post_spikes), target_spikes)
        # print("New weight exact: {}".format(new_weight_exact))
        # print("New weight SpiNNaker: {}".format(weights))

        self.assertTrue(numpy.allclose(weights, new_weight_exact, rtol=0.001))
# Presynaptic population - Input layer - Stimuli
pop_input = sim.Population(
    n_neurons,
    sim.SpikeSourceArray,
    spikeArray,
    # sim.SpikeSourcePoisson(), #(rate=1, duration=sim_time),
    label='pop_input')
# Postsynaptic population
"""
Notes:
    * Interesting property about this neuron model: voltage_based_synapses = True
    * Initial voltage value = -70.0
"""
pop_output = sim.Population(n_neurons, sim.Izhikevich(), label='pop_output')

sim.Projection(pop_input, pop_output, sim.OneToOneConnector(),
               sim.StaticSynapse(weight=20.0, delay=2))

# == Instrument the network ====================================================

# Record all to observe.
"""
Note:
    Recordables of the Izhikevich neuron model are limited with voltage, spikes, and unit(mV/ms) of the population.
"""
pop_output.record("all")

# === Run the simulation =======================================================

sim.run(sim_time)
示例#18
0
# Set the times at which to input a spike
spike_times = range(0, run_time, 100)

p.setup(time_step)

spikeArray = {"spike_times": spike_times}
input_pop = p.Population(1, p.SpikeSourceArray(**spikeArray), label="input")

myModelCurrExpParams = {"my_parameter": -70.0, "i_offset": i_offset}
my_model_pop = p.Population(1,
                            My_Model_Curr_Exp(**myModelCurrExpParams),
                            label="my_model_pop")
p.Projection(input_pop,
             my_model_pop,
             p.OneToOneConnector(),
             receptor_type='excitatory',
             synapse_type=p.StaticSynapse(weight=weight))

myModelCurrMySynapseTypeParams = {
    "my_parameter": -70.0,
    "i_offset": i_offset,
    "my_ex_synapse_parameter": 0.5
}
my_model_my_synapse_type_pop = p.Population(
    1,
    My_Model_Curr_My_Synapse_Type(**myModelCurrMySynapseTypeParams),
    label="my_model_my_synapse_type_pop")
p.Projection(input_pop,
             my_model_my_synapse_type_pop,
             p.OneToOneConnector(),
示例#19
0
outputs = 2

p.setup(timestep=1.0, min_delay=1)
p.set_number_of_neurons_per_core(p.IF_cond_exp, 100)
input_model = gym.Pendulum(
    encoding=encoding, time_increment=time_increment, pole_length=pole_length,
    pole_angle=pole_angle, reward_based=reward_based,
    force_increments=force_increments, max_firing_rate=max_firing_rate,
    number_of_bins=number_of_bins, central=central,
    rand_seed=[np.random.randint(0xffff) for i in range(4)], bin_overlap=3,
    label='pendulum_pop')

pendulum_pop_size = input_model.neurons()
pendulum = p.Population(pendulum_pop_size, input_model)
null_pop = p.Population(4*number_of_bins, p.IF_cond_exp(), label='null')
p.Projection(pendulum, null_pop, p.OneToOneConnector(),
             p.StaticSynapse(weight=0.09))
null_pop.record(['spikes', 'v', 'gsyn_exc'])
# null_pop.record(['spikes', 'v'])
# null_pops = []
# for i in range(4*number_of_bins):
#     null_pops.append(p.Population(1, p.IF_cond_exp(),
#                                   label='null {}'.format(i)))
#     null_pops[i].record(['spikes', 'v'])
#     p.Projection(pendulum, null_pops[i],
#                  p.FromListConnector([[i, 0, weight, 1]]))

arm_collection = []
# input_spikes = []
rate = 5
print('rate = ', rate)
示例#20
0
def main():
    minutes = 0
    seconds = 30
    milliseconds = 0
    run_time = minutes * 60 * 1000 + seconds * 1000 + milliseconds

    weight_to_spike = 4.

    model = sim.IF_curr_exp
    cell_params = {
        'cm': 0.25,  # nF
        'i_offset': 0.0,
        'tau_m': 10.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 2.5,
        'tau_syn_I': 2.5,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -55.4
    }
    # Available resolutions
    # 16, 32, 64, 128
    mode = ExternalDvsEmulatorDevice.MODE_64
    cam_res = int(mode)
    cam_fps = 90
    frames_per_saccade = cam_fps / 3 - 1
    polarity = ExternalDvsEmulatorDevice.MERGED_POLARITY
    output_type = ExternalDvsEmulatorDevice.OUTPUT_TIME
    history_weight = 1.0
    behaviour = VirtualCam.BEHAVE_ATTENTION
    # vcam = VirtualCam("./mnist", behaviour=behaviour, fps=cam_fps,
    #                   resolution=cam_res, frames_per_saccade=frames_per_saccade)

    cam_params = {
        'mode': mode,
        'polarity': polarity,
        'threshold': 12,
        'adaptive_threshold': False,
        'fps': cam_fps,
        'inhibition': False,
        'output_type': output_type,
        'save_spikes': "./spikes_from_cam.pickle",
        'history_weight': history_weight,
        'device_id': 0,  # for an OpenCV webcam device
        #'device_id': 'path/to/video/file', # to encode pre-recorded video
        #'device_id': vcam,
    }
    if polarity == ExternalDvsEmulatorDevice.MERGED_POLARITY:
        num_neurons = 2 * (cam_res**2)
    else:
        num_neurons = cam_res**2

    sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0)

    target = sim.Population(num_neurons, model, cell_params)

    stimulation = sim.Population(num_neurons,
                                 DvsEmulatorDevice,
                                 cam_params,
                                 label="Webcam population")

    connector = sim.OneToOneConnector()

    sim.Projection(stimulation,
                   target,
                   connector,
                   synapse_type=sim.StaticSynapse(weight=weight_to_spike))

    target.record("spikes")

    sim.run(run_time)

    # spikes = target.getSpikes(compatible_output=True)
    target_neo = target.get_data(variables=["spikes"])
    spikes = target_neo.segments[0].spiketrains

    sim.end()
    #stimulation._vertex.stop()

    print("Raster plot of the spikes that Spinnaker echoed back")
    fig = pylab.figure()

    spike_times = [spike_time for (neuron_id, spike_time) in spikes]
    spike_ids = [neuron_id for (neuron_id, spike_time) in spikes]

    pylab.plot(spike_times,
               spike_ids,
               ".",
               markerfacecolor="None",
               markeredgecolor="Blue",
               markersize=3)

    pylab.show()
示例#21
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
示例#22
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')
示例#23
0
def do_run(seed=None):

    random.seed(seed)
    # SpiNNaker setup
    sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0)

    # +-------------------------------------------------------------------+
    # | General Parameters                                                |
    # +-------------------------------------------------------------------+

    # Population parameters
    model = sim.IF_curr_exp

    cell_params = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 10.0,
        'tau_refrac': 2.0,
        'tau_syn_E': 2.5,
        'tau_syn_I': 2.5,
        'v_reset': -70.0,
        'v_rest': -65.0,
        'v_thresh': -55.4
    }

    # Other simulation parameters
    e_rate = 200
    in_rate = 350

    n_stim_test = 5
    n_stim_pairing = 10
    dur_stim = 20

    pop_size = 40

    ISI = 150.
    start_test_pre_pairing = 200.
    start_pairing = 1500.
    start_test_post_pairing = 700.

    simtime = start_pairing + start_test_post_pairing + \
        ISI*(n_stim_pairing + n_stim_test) + 550.  # let's make it 5000

    # Initialisations of the different types of populations
    IAddPre = []
    IAddPost = []

    # +-------------------------------------------------------------------+
    # | Creation of neuron populations                                    |
    # +-------------------------------------------------------------------+

    # Neuron populations
    pre_pop = sim.Population(pop_size, model(**cell_params))
    post_pop = sim.Population(pop_size, model(**cell_params))

    # Test of the effect of activity of the pre_pop population on the post_pop
    # population prior to the "pairing" protocol : only pre_pop is stimulated
    for i in range(n_stim_test):
        IAddPre.append(
            sim.Population(
                pop_size,
                sim.SpikeSourcePoisson(rate=in_rate,
                                       start=start_test_pre_pairing + ISI *
                                       (i),
                                       duration=dur_stim,
                                       seed=random.randint(0, 100000000))))

    # Pairing protocol : pre_pop and post_pop are stimulated with a 10 ms
    # difference
    for i in range(n_stim_pairing):
        IAddPre.append(
            sim.Population(
                pop_size,
                sim.SpikeSourcePoisson(rate=in_rate,
                                       start=start_pairing + ISI * (i),
                                       duration=dur_stim,
                                       seed=random.randint(0, 100000000))))
        IAddPost.append(
            sim.Population(
                pop_size,
                sim.SpikeSourcePoisson(rate=in_rate,
                                       start=start_pairing + ISI * (i) + 10.,
                                       duration=dur_stim,
                                       seed=random.randint(0, 100000000))))

    # Test post pairing : only pre_pop is stimulated
    # (and should trigger activity in Post)
    for i in range(n_stim_test):
        start = start_pairing + ISI * n_stim_pairing + \
                start_test_post_pairing + ISI * i
        IAddPre.append(
            sim.Population(
                pop_size,
                sim.SpikeSourcePoisson(rate=in_rate,
                                       start=start,
                                       duration=dur_stim,
                                       seed=random.randint(0, 100000000))))

    # Noise inputs
    INoisePre = sim.Population(pop_size,
                               sim.SpikeSourcePoisson(rate=e_rate,
                                                      start=0,
                                                      duration=simtime,
                                                      seed=random.randint(
                                                          0, 100000000)),
                               label="expoisson")
    INoisePost = sim.Population(pop_size,
                                sim.SpikeSourcePoisson(rate=e_rate,
                                                       start=0,
                                                       duration=simtime,
                                                       seed=random.randint(
                                                           0, 100000000)),
                                label="expoisson")

    # +-------------------------------------------------------------------+
    # | Creation of connections                                           |
    # +-------------------------------------------------------------------+

    # Connection parameters
    JEE = 3.

    # Connection type between noise poisson generator and
    # excitatory populations
    ee_connector = sim.OneToOneConnector()

    # Noise projections
    sim.Projection(INoisePre,
                   pre_pop,
                   ee_connector,
                   receptor_type='excitatory',
                   synapse_type=sim.StaticSynapse(weight=JEE * 0.05))
    sim.Projection(INoisePost,
                   post_pop,
                   ee_connector,
                   receptor_type='excitatory',
                   synapse_type=sim.StaticSynapse(weight=JEE * 0.05))

    # Additional Inputs projections
    for i in range(len(IAddPre)):
        sim.Projection(IAddPre[i],
                       pre_pop,
                       ee_connector,
                       receptor_type='excitatory',
                       synapse_type=sim.StaticSynapse(weight=JEE * 0.05))
    for i in range(len(IAddPost)):
        sim.Projection(IAddPost[i],
                       post_pop,
                       ee_connector,
                       receptor_type='excitatory',
                       synapse_type=sim.StaticSynapse(weight=JEE * 0.05))

    # Plastic Connections between pre_pop and post_pop
    stdp_model = sim.STDPMechanism(
        timing_dependence=sim.SpikePairRule(tau_plus=20.,
                                            tau_minus=50.0,
                                            A_plus=0.02,
                                            A_minus=0.02),
        weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.9))

    rng = NumpyRNG(seed=seed, parallel_safe=True)
    plastic_projection = \
        sim.Projection(pre_pop, post_pop, sim.FixedProbabilityConnector(
            p_connect=0.5, rng=rng), synapse_type=stdp_model)

    # +-------------------------------------------------------------------+
    # | Simulation and results                                            |
    # +-------------------------------------------------------------------+

    # Record spikes and neurons' potentials
    pre_pop.record(['v', 'spikes'])
    post_pop.record(['v', 'spikes'])

    # Run simulation
    sim.run(simtime)

    weights = plastic_projection.get('weight', 'list')

    pre_spikes = neo_convertor.convert_spikes(pre_pop.get_data('spikes'))
    post_spikes = neo_convertor.convert_spikes(post_pop.get_data('spikes'))

    # End simulation on SpiNNaker
    sim.end()

    return (pre_spikes, post_spikes, weights)
示例#24
0
def run_script(simtime,
               n_neurons,
               run_split=1,
               record_spikes=False,
               spike_rate=None,
               spike_rec_indexes=None,
               spike_get_indexes=None,
               record_v=False,
               v_rate=None,
               v_rec_indexes=None,
               v_get_indexes=None,
               record_exc=False,
               exc_rate=None,
               exc_rec_indexes=None,
               exc_get_indexes=None,
               record_inh=False,
               inh_rate=None,
               inh_rec_indexes=None,
               inh_get_indexes=None,
               file_prefix=""):

    sim.setup(timestep=1)

    pop_1 = sim.Population(n_neurons, sim.IF_curr_exp(), label="pop_1")
    input1 = sim.Population(1,
                            sim.SpikeSourceArray(spike_times=[0]),
                            label="input")
    sim.Projection(input1,
                   pop_1,
                   sim.AllToAllConnector(),
                   synapse_type=sim.StaticSynapse(weight=5, delay=1))
    input2 = sim.Population(n_neurons,
                            sim.SpikeSourcePoisson(rate=100.0),
                            label="Stim_Exc",
                            additional_parameters={"seed": 1})
    sim.Projection(input2,
                   pop_1,
                   sim.OneToOneConnector(),
                   synapse_type=sim.StaticSynapse(weight=5, delay=1))
    if record_spikes:
        if spike_rec_indexes is None:
            pop_1.record(['spikes'], sampling_interval=spike_rate)
        else:
            view = PopulationView(pop_1, spike_rec_indexes)
            view.record(['spikes'], sampling_interval=spike_rate)
    if record_v:
        if v_rec_indexes is None:
            pop_1.record(['v'], sampling_interval=v_rate)
        else:
            view = PopulationView(pop_1, v_rec_indexes)
            view.record(['v'], sampling_interval=v_rate)
    if record_exc:
        if exc_rec_indexes is None:
            pop_1.record(['gsyn_exc'], sampling_interval=exc_rate)
        else:
            view = PopulationView(pop_1, exc_rec_indexes)
            view.record(['gsyn_exc'], sampling_interval=exc_rate)
    if record_inh:
        if inh_rec_indexes is None:
            pop_1.record(['gsyn_inh'], sampling_interval=inh_rate)
        else:
            view = PopulationView(pop_1, inh_rec_indexes)
            view.record(['gsyn_inh'], sampling_interval=inh_rate)
    for i in range(run_split):
        sim.run(simtime / run_split)

    if record_spikes:
        if spike_get_indexes is None:
            neo = pop_1.get_data("spikes")
        else:
            view = PopulationView(pop_1, spike_get_indexes)
            neo = view.get_data("spikes")
        spikes = neo.segments[0].spiketrains
        spike_file = os.path.join(current_file_path,
                                  file_prefix + "spikes.csv")
        write_spikes(spikes, spike_file)
    else:
        spikes = None

    if record_v:
        if v_get_indexes is None:
            neo = pop_1.get_data("v")
        else:
            view = PopulationView(pop_1, v_get_indexes)
            neo = view.get_data("v")
        v = neo.segments[0].filter(name='v')[0]
        v_file = os.path.join(current_file_path, file_prefix + "v.csv")
        numpy.savetxt(v_file, v, delimiter=',')
    else:
        v = None

    if record_exc:
        if exc_get_indexes is None:
            neo = pop_1.get_data('gsyn_exc')
        else:
            view = PopulationView(pop_1, exc_get_indexes)
            neo = view.get_data('gsyn_exc')
        exc = neo.segments[0].filter(name='gsyn_exc')[0]
        exc_file = os.path.join(current_file_path, file_prefix + "exc.csv")
        numpy.savetxt(exc_file, exc, delimiter=',')
    else:
        exc = None
    if record_inh:
        if inh_get_indexes is None:
            neo = pop_1.get_data('gsyn_inh')
        else:
            view = PopulationView(pop_1, inh_get_indexes)
            neo = view.get_data('gsyn_inh')
        inh = neo.segments[0].filter(name='gsyn_inh')[0]
        inh_file = os.path.join(current_file_path, file_prefix + "inh.csv")
        numpy.savetxt(inh_file, inh, delimiter=',')
    else:
        inh = None

    sim.end()

    return spikes, v, exc, inh
示例#25
0
                                   label='pop_backward')

# Create injection populations
injector_forward = Frontend.Population(
    n_neurons,
    Frontend.external_devices.SpikeInjector(
        **cell_params_spike_injector_with_key),
    label='spike_injector_forward')
injector_backward = Frontend.Population(
    n_neurons,
    Frontend.external_devices.SpikeInjector(**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 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))
示例#26
0
    def get_injector_label(self):
        return "MyEthernetSensor"

    def get_injector_parameters(self):
        return {}

    def get_translator(self):
        return None

    def get_database_connection(self):
        return self._live_spikes_connection


p.setup(1.0)

ethernet_sensor = p.external_devices.EthernetSensorPopulation(
    MyEthernetSensor())
ethernet_input_pop = p.Population(1, p.IF_curr_exp())

ethernet_input_pop.record("v")

p.Projection(ethernet_sensor, ethernet_input_pop, p.OneToOneConnector(),
             p.StaticSynapse(weight=1.0))

p.run(1000)

print ethernet_input_pop.get_data("v").segments[0].filter(name='v')

p.end()
示例#27
0
def do_run(nNeurons, neurons_per_core):

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

    nPopulations = 62
    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 = 1.5
    delay = 5

    for i in range(0, nPopulations):
        populations.append(p.Population(nNeurons, p.IF_curr_exp,
                                        cell_params_lif,
                                        label='pop_' + str(i)))
        # print("++++++++++++++++")
        # print("Added population %s" % (i))
        # print("o-o-o-o-o-o-o-o-")
    synapse_type = p.StaticSynapse(weight=weight_to_spike, delay=delay)
    for i in range(0, nPopulations):
        projections.append(p.Projection(populations[i],
                                        populations[(i + 1) % nPopulations],
                                        p.OneToOneConnector(),
                                        synapse_type=synapse_type,
                                        label="Projection from pop {} to pop "
                                              "{}".format(i, (i + 1) %
                                                          nPopulations)))
        # print("++++++++++++++++++++++++++++++++++++++++++++++++++++")
        # print("Added projection from population %s to population %s" \
        #      % (i, (i + 1) % nPopulations))
        # print("----------------------------------------------------")

    # from pprint import pprint as pp
    # pp(projections)
    spikeArray = {'spike_times': [[0]]}
    populations.append(p.Population(1, p.SpikeSourceArray, spikeArray,
                                    label='inputSpikes_1'))
    projections.append(p.Projection(populations[-1], populations[0],
                                    p.AllToAllConnector(),
                                    synapse_type=synapse_type))

    for i in range(0, nPopulations):
        populations[i].record("v")
        populations[i].record("gsyn_exc")
        populations[i].record("spikes")

    p.run(1500)

    ''''
    weights = projections[0].getWeights()
    delays = projections[0].getDelays()
    '''

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

    v = neo_convertor.convert_data(neo, name="v")
    gsyn = neo_convertor.convert_data(neo, name="gsyn_exc")
    spikes = neo_convertor.convert_spikes(neo)

    p.end()

    return (v, gsyn, spikes)
示例#28
0
if rng is None:
    seed = None
else:
    seed = int(rng.next() * 1000)
stim_inh = sim.Population(n_inh,
                          sim.SpikeSourcePoisson(rate=1000.0,
                                                 seed=int(rng.next() * 1000)),
                          label="Stim_Inh")

# Create a one-to-one excitatory connection
# from the excitatory poisson stimulation population
# to the excitatory population with a weight of 0.1nA and a delay of 1.0ms
# TODO values
ex_proj = sim.Projection(stim_exc,
                         pop_exc,
                         sim.OneToOneConnector(),
                         synapse_type=sim.StaticSynapse(weight=0.1, delay=1.0),
                         receptor_type="excitatory")

# Create a similar excitatory connection
# from the inhibitory poisson stimulation population
# to the inhibitory population.
in_proj = sim.Projection(stim_inh,
                         pop_inh,
                         sim.OneToOneConnector(),
                         synapse_type=sim.StaticSynapse(weight=0.1, delay=1.0),
                         receptor_type="excitatory")

# Create an excitatory connection from the excitatory population
# to the inhibitory population
# with a fixed probability of connection of 0.1,
示例#29
0
                              pynn.SpikeSourcePoisson(rate=10.0),
                              label="Poisson_pop_E")
Poiss_ext_I = pynn.Population(N_I,
                              pynn.SpikeSourcePoisson(rate=10.0),
                              label="Poisson_pop_I")

# Connectors
E_conn = pynn.FixedProbabilityConnector(epsilon)
I_conn = pynn.FixedProbabilityConnector(epsilon)

# Use random delays for the external noise and
# set the inital membrance voltage below the resting potential
# to avoid the overshoot of activity in the beginning of the simulation
rng = NumpyRNG(seed=1)
delay_distr = RandomDistribution('uniform', low=1.0, high=16.0, rng=rng)
Ext_conn = pynn.OneToOneConnector()

uniformDistr = RandomDistribution('uniform', low=-10, high=0, rng=rng)
E_pop.initialize(v=uniformDistr)
I_pop.initialize(v=uniformDistr)

# Projections
E_E = pynn.Projection(E_pop,
                      E_pop,
                      E_conn,
                      receptor_type="excitatory",
                      synapse_type=pynn.StaticSynapse(weight=J_E, delay=delay))
I_E = pynn.Projection(I_pop,
                      E_pop,
                      I_conn,
                      receptor_type="inhibitory",
示例#30
0
def test_agent(arm1, arm2):

    arm = [arm1, arm2]

    print "arm = ", arm

    connections = read_agent()

    p.setup(timestep=1.0, min_delay=1, max_delay=127)
    p.set_number_of_neurons_per_core(p.IF_cond_exp, 100)
    bandit = p.Population(len(arm), Bandit(arm, exposure_time, reward_based=reward, label='bandit_pop'))
    [in2e, in2i, e_size, e2e, e2i, i_size, i2e, i2i, e2out, i2out] = connections
    if e_size > 0:
        excite = p.Population(e_size, p.IF_cond_exp(), label='excite_pop')
        excite_noise = p.Population(e_size, p.SpikeSourcePoisson(rate=noise_rate))
        p.Projection(excite_noise, excite, p.OneToOneConnector(),
                     p.StaticSynapse(weight=noise_weight), receptor_type='excitatory')
        excite.record('spikes')
    if i_size > 0:
        inhib = p.Population(i_size, p.IF_cond_exp(), label='inhib_pop')
        inhib_noise = p.Population(i_size, p.SpikeSourcePoisson(rate=noise_rate))
        p.Projection(inhib_noise, inhib, p.OneToOneConnector(),
                     p.StaticSynapse(weight=noise_weight), receptor_type='excitatory')
        inhib.record('spikes')
    if len(in2e) != 0:
        p.Projection(bandit, excite, p.FromListConnector(in2e),
                     receptor_type='excitatory')
        # p.Projection(starting_pistol, excite, p.FromListConnector(in2e),
        #              receptor_type='excitatory')
    if len(in2i) != 0:
        p.Projection(bandit, inhib, p.FromListConnector(in2i),
                     receptor_type='excitatory')
        # p.Projection(starting_pistol, inhib, p.FromListConnector(in2i),
        #              receptor_type='excitatory')
    if len(e2e) != 0:
        p.Projection(excite, excite, p.FromListConnector(e2e),
                     receptor_type='excitatory')
    if len(e2i) != 0:
        p.Projection(excite, inhib, p.FromListConnector(e2i),
                     receptor_type='excitatory')
    if len(i2e) != 0:
        p.Projection(inhib, excite, p.FromListConnector(i2e),
                     receptor_type='inhibitory')
    if len(i2i) != 0:
        p.Projection(inhib, inhib, p.FromListConnector(i2i),
                     receptor_type='inhibitory')
    if len(e2out) != 0:
        p.Projection(excite, bandit, p.FromListConnector(e2out),
                     receptor_type='excitatory')
    if len(i2out) != 0:
        p.Projection(inhib, bandit, p.FromListConnector(i2out),
                     receptor_type='inhibitory')

    simulator = get_simulator()
    p.run(runtime)

    scores = get_scores(game_pop=bandit, simulator=simulator)
    print scores
    print arm

    e_spikes = excite.get_data('spikes').segments[0].spiketrains
    i_spikes = inhib.get_data('spikes').segments[0].spiketrains
    # v = receive_pop[i].get_data('v').segments[0].filter(name='v')[0]
    plt.figure("[{}, {}] - {}".format(arm1, arm2, scores))
    Figure(
        Panel(e_spikes, xlabel="Time (ms)", ylabel="nID", xticks=True),
        Panel(i_spikes, xlabel="Time (ms)", ylabel="nID", xticks=True)
    )
    plt.show()

    p.end()