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(
                    **cell_params_spike_injector_with_key),
                label='spike_injector_forward')
            injector_backward = Frontend.Population(
                self.n_neurons,
                Frontend.external_devices.SpikeInjector(
                    **cell_params_spike_injector),
                label='spike_injector_backward')
        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()
Пример #2
0
pop_1 = sim.Population(2, sim.IF_curr_exp(), label="pop_1")
# Consisting of two input source neurons ...with default parameters Have the
# first input neuron spike at time 0.0ms and the second spike at time 1.0ms.
input = sim.Population(2,
                       sim.SpikeSourceArray(spike_times=[[0], [1]]),
                       label="input")
input_proj = sim.Projection(input,
                            pop_1,
                            sim.OneToOneConnector(),
                            synapse_type=sim.StaticSynapse(weight=5, delay=2))

# Record and plot the spikes received against time.
pop_1.record(["spikes"])
sim.run(simtime)

neo = pop_1.get_data(variables=["spikes"])
spikes = neo.segments[0].spiketrains
print spikes
sim.end()

plot.Figure(
    # plot spikes (or in this case spike)
    plot.Panel(spikes,
               yticks=True,
               xticks=True,
               markersize=5,
               xlim=(0, simtime)),
    title="Simple Example",
    annotations="Simulated with {}".format(sim.name()))
plt.show()
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()

    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
    }

    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"])

    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)
Пример #4
0
def split_potentiation_and_depression():
    p.setup(1.0)
    runtime = 100
    initial_run = 1000  # to negate any initial conditions

    # STDP parameters
    a_plus = 0.01
    a_minus = 0.01
    tau_plus = 20
    tau_minus = 20
    plastic_delay = 3
    initial_weight = 2.5
    max_weight = 5
    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_curr_exp(),  label="post", additional_parameters={
            "splitter": SplitterAbstractPopulationVertexNeuronsSynapses(1)})

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

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

    syn_plas = p.STDPMechanism(
        timing_dependence=p.SpikePairRule(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()

    new_weight_exact = calculate_spike_pair_additive_stdp_weight(
        pre_spikes, post_spikes, initial_weight, plastic_delay, max_weight,
        a_plus, a_minus, tau_plus, tau_minus)

    print("Pre neuron spikes at: {}".format(pre_spikes))
    print("Post-neuron spikes at: {}".format(post_spikes))
    target_spikes = [1014,  1032, 1053]
    assert(all(s1 == s2
               for s1, s2 in zip(list(post_spikes), target_spikes)))
    print("New weight exact: {}".format(new_weight_exact))
    print("New weight SpiNNaker: {}".format(weights))

    assert(numpy.allclose(weights, new_weight_exact, rtol=0.001))
Пример #5
0
 def test_only_end(self):
     setup_for_unittest()
     sim.end()
    def potentiation_and_depression(self):
        p.setup(1)
        runtime = 100
        initial_run = 1000  # to negate any initial conditions

        # STDP parameters
        a_plus = 0.01
        a_minus = 0.01
        tau_plus = 20
        tau_minus = 20
        plastic_delay = 3
        initial_weight = 2.5
        max_weight = 5
        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_curr_exp(), label="post")

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

        p.Projection(extra_pop,
                     post_pop,
                     p.OneToOneConnector(),
                     p.StaticSynapse(weight=5.0, 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(
            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 = [1014, 1032, 1053]
        self.assertListEqual(list(post_spikes), target_spikes)
        # print("Potentiation time differences: {}".format(potentiation_times))
        # print("Depression time differences: {}".format(depression_times))
        # print("Potentiation: {}".format(potentiations))
        # print("Depressions: {}".format(depressions))
        # print("New weight exact: {}".format(new_weight_exact))
        # print("New weight SpiNNaker: {}".format(weights))

        self.assertTrue(
            numpy.allclose(weights[0], new_weight_exact, atol=0.001))
Пример #7
0
def do_run():
    p.setup(1.0)
    n_neurons = 2

    pop_a = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[10, 20, 50], starts=[0, 500, 1000]),
                         label="pop_a")
    pop_a.record("spikes")

    pop_b = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[[1, 2, 5], [10, 20, 50]],
                             starts=[0, 500, 1000]),
                         label="pop_b")
    pop_b.record("spikes")

    pop_c = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[10, 20, 50],
                             starts=[10, 600, 1200],
                             durations=[500, 500, 500]),
                         label="pop_c")
    pop_c.record("spikes")

    pop_d = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[[1, 2, 5], [10, 20, 50]],
                             starts=[0, 500, 1000],
                             durations=[500, 400, 300]),
                         label="pop_d")
    pop_d.record("spikes")

    pop_e = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[[1, 2, 5], [10, 20, 50]],
                             starts=[[0, 500, 1000], [100, 600, 1100]],
                             durations=[400, 300, 200]),
                         label="pop_e")
    pop_e.record("spikes")

    pop_f = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[[1, 2, 5], [10, 20, 50]],
                             starts=[[0, 500, 1000], [100, 600, 1100]],
                             durations=[[400, 300, 200], [300, 200, 100]]),
                         label="pop_f")
    pop_f.record("spikes")

    pop_g = p.Population(n_neurons,
                         p.extra_models.SpikeSourcePoissonVariable(
                             rates=[[1, 2, 5], [10, 50]],
                             starts=[[0, 100, 200], [200, 300]]),
                         label="pop_g")
    pop_g.record("spikes")

    pop_h = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=1),
                         label="pop_h")
    pop_h.record("spikes")

    pop_i = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=1, start=100),
                         label="pop_i")
    pop_i.record("spikes")

    pop_j = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=[1, 10]),
                         label="pop_j")
    pop_j.record("spikes")

    pop_k = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=1, start=[0, 500]),
                         label="pop_k")
    pop_k.record("spikes")

    pop_l = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=1, start=10, duration=500),
                         label="pop_l")
    pop_l.record("spikes")

    pop_m = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=[1, 10],
                                              start=[0, 500],
                                              duration=500),
                         label="pop_m")
    pop_m.record("spikes")

    pop_n = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=[1, 10],
                                              start=[0, 500],
                                              duration=[500, 800]),
                         label="pop_n")
    pop_n.record("spikes")

    pop_o = p.Population(n_neurons,
                         p.SpikeSourcePoisson(rate=1, duration=500),
                         label="pop_o")
    pop_o.record("spikes")

    p.run(2000)

    p.end()
def record_weights_using_callback():

    ######################################
    # Setup
    ######################################
    sim.setup(timestep=simulationParameters["timeStep"])

    ######################################
    # Neuron pop
    ######################################
    # Input neurons
    ILayer = sim.Population(popNeurons["ILayer"],
                            sim.SpikeSourceArray(spike_times=ILSpike),
                            label="ILayer")
    # LIF neurons
    LIFLayer = sim.Population(popNeurons["LIFLayer"],
                              sim.IF_curr_exp(**neuronParameters["LIFL"]),
                              label="LIFLayer")
    LIFLayer.set(v=initNeuronParameters["LIFL"]["vInit"])

    ######################################
    # Synapses
    ######################################

    # ILayer-LIFLayer -> statics
    sim.Projection(ILayer,
                   LIFLayer,
                   sim.OneToOneConnector(),
                   synapse_type=sim.StaticSynapse(
                       weight=synParameters["IL-LIFL"]["initWeight"],
                       delay=synParameters["IL-LIFL"]["delay"]))

    # LIFLayer-ILayer -> STDP
    timing_rule = sim.SpikePairRule(
        tau_plus=synParameters["LIFL-LIFL"]["tau_plus"],
        tau_minus=synParameters["LIFL-LIFL"]["tau_minus"],
        A_plus=synParameters["LIFL-LIFL"]["A_plus"],
        A_minus=synParameters["LIFL-LIFL"]["A_minus"])
    weight_rule = sim.AdditiveWeightDependence(
        w_max=synParameters["LIFL-LIFL"]["w_max"],
        w_min=synParameters["LIFL-LIFL"]["w_min"])
    stdp_model = sim.STDPMechanism(
        timing_dependence=timing_rule,
        weight_dependence=weight_rule,
        weight=synParameters["LIFL-LIFL"]["initWeight"],
        delay=synParameters["LIFL-LIFL"]["delay"])
    LIFLayer_LIFLayer_conn = sim.Projection(
        LIFLayer,
        LIFLayer,
        sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=stdp_model)

    ######################################
    # Record parameters
    ######################################
    LIFLayer.record(["spikes", "v"])
    weightRecorderLIF_LIF = weight_recorder(
        sampling_interval=simulationParameters["timeStep"],
        projection=LIFLayer_LIFLayer_conn)

    ######################################
    # Run simulation
    ######################################
    sim.run(simulationParameters["simTime"], callbacks=[weightRecorderLIF_LIF])

    ######################################
    # Recall data
    ######################################
    populationData = LIFLayer.get_data(variables=["spikes", "v"])
    LIFLSpikes = populationData.segments[0].spiketrains
    vLIFL = populationData.segments[0].filter(name='v')[0]
    w_LIFL_LIFL = weightRecorderLIF_LIF.get_weights()

    ######################################
    # End simulation
    ######################################
    sim.end()

    ######################################
    # Return parameters
    ######################################
    return ILSpike, LIFLSpikes, vLIFL, w_LIFL_LIFL
Пример #9
0
                        I_pop,
                        Ext_conn,
                        receptor_type="excitatory",
                        synapse_type=pynn.StaticSynapse(weight=J_E * 10,
                                                        delay=delay_distr))

# Record stuff
E_pop.record("spikes")

pynn.run(sim_time)

esp = None
isp = None
pe = None
pi = None
v_esp = None

esp = E_pop.get_data("spikes")

Figure(
    # raster plot of the presynaptic neuron spike times
    Panel(esp.segments[0].spiketrains,
          yticks=True,
          markersize=1,
          xlim=(0, sim_time)),
    title="Simple synfire chain example",
    annotations="Simulated with {}".format(pynn.name()))
plt.show()

pynn.end()
Пример #10
0
def do_run(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, min_delay=1.0, max_delay=144.0)
    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
    def simulation_teardown(self):
        """Tear down the SpiNNaker simulation framework

        :return: None
        """
        p.end()
def do_run(plot):

    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
    p.set_number_of_neurons_per_core(p.IF_cond_exp, 100)

    # Experiment Parameters
    n_groups = 6  # Number of Synfire Groups
    n_exc = 100  # Number of excitatory neurons per group
    n_inh = 25  # Number of inhibitory neurons per group

    sim_duration = 500.

    # defining the initial pulse-packet
    pp_a = 5  # Nr of pulses in the packet
    pp_sigma = 5.0  # sigma of pulse-packet
    pp_start = 50.  # start = center of pulse-packet

    # Neuron Parameters as in Kremkow et al. paper
    cell_params = {
        'cm': 0.290,  # nF
        'tau_m': 290.0 / 29.0,  # pF / nS = ms
        'v_rest': -70.0,  # mV
        'v_thresh': -57.0,  # mV
        'tau_syn_E': 1.5,  # ms
        'tau_syn_I': 10.0,  # ms
        'tau_refrac': 2.0,  # ms
        'v_reset': -70.0,  # mV
        'e_rev_E': 0.0,  # mV
        'e_rev_I': -75.0,  # mV
    }

    weight_exc = 0.05  # uS weight for excitatory to excitatory connections
    weight_inh = 0.002  # uS weight for inhibitory to excitatory connections

    # list of excitatory populations
    exc_pops = []
    # list of inhibitory populations
    inh_pops = []
    # and Assembly of all populations
    all_populations = []

    # Create Groups
    print("Creating ", n_groups, " SynfireGroups")
    for group_index in range(n_groups):
        # create the excitatory Population
        exc_pop = p.Population(n_exc,
                               p.IF_cond_exp(**cell_params),
                               label=("pop_exc_%s" % group_index))

        exc_pops.append(exc_pop)  # append to excitatory populations
        all_populations += [exc_pop]  # and to the Assembly

        # create the inhibitory Population
        inh_pop = p.Population(n_inh,
                               p.IF_cond_exp(**cell_params),
                               label=("pop_inh_%s" % group_index))
        inh_pops.append(inh_pop)
        all_populations += [inh_pop]

        # connect Inhibitory to excitatory Population
        p.Projection(inh_pop,
                     exc_pop,
                     p.AllToAllConnector(),
                     synapse_type=p.StaticSynapse(weight=weight_inh, delay=8.),
                     receptor_type='inhibitory')

    # Create Stimulus and connect it to first group
    print("Create Stimulus Population")
    # We create a Population of SpikeSourceArrays of the same dimension
    # as excitatory neurons in a synfire group
    pop_stim = p.Population(n_exc, p.SpikeSourceArray({}), label="pop_stim")

    # We create a normal distribution around pp_start with sigma = pp_sigma
    rd = pyNN.random.RandomDistribution('normal', [pp_start, pp_sigma])
    all_spiketimes = []
    # for each cell in the population, we take pp_a values from the
    # random distribution
    for cell in range(len(pop_stim)):
        spiketimes = []
        for pulse in range(pp_a):
            spiketimes.append(rd.next())  # draw from the random distribution
        spiketimes.sort()
        all_spiketimes.append(spiketimes)

    # convert into a numpy array
    all_spiketimes = numpy.array(all_spiketimes)
    # 'topographic' setting of parameters.
    # all_spiketimes must have the same dimension as the Population
    pop_stim.set(spike_times=all_spiketimes)

    # Connect Groups with the subsequent ones
    print("Connecting Groups with subsequent ones")
    for group_index in range(n_groups - 1):
        p.Projection(exc_pops[group_index % n_groups],
                     exc_pops[(group_index + 1) % n_groups],
                     p.FixedTotalNumberConnector(160),
                     synapse_type=p.StaticSynapse(weight=weight_exc,
                                                  delay=10.),
                     receptor_type='excitatory')
        p.Projection(exc_pops[group_index % n_groups],
                     inh_pops[(group_index + 1) % n_groups],
                     p.FixedTotalNumberConnector(160),
                     synapse_type=p.StaticSynapse(weight=weight_exc,
                                                  delay=10.),
                     receptor_type='excitatory')

    # Make another projection for testing that connects to itself
    p.Projection(exc_pops[1],
                 exc_pops[1],
                 p.FixedTotalNumberConnector(50,
                                             with_replacement=False,
                                             allow_self_connections=False),
                 synapse_type=p.StaticSynapse(weight=weight_exc, delay=10.),
                 receptor_type='excitatory')

    # Connect the Stimulus to the first group
    print("Connecting Stimulus to first group")
    p.Projection(pop_stim,
                 inh_pops[0],
                 p.FixedTotalNumberConnector(60),
                 synapse_type=p.StaticSynapse(weight=weight_exc, delay=20.),
                 receptor_type='excitatory')
    p.Projection(pop_stim,
                 exc_pops[0],
                 p.FixedTotalNumberConnector(60),
                 synapse_type=p.StaticSynapse(weight=weight_exc, delay=20.),
                 receptor_type='excitatory')

    # Recording spikes
    pop_stim.record('spikes')

    for pop in all_populations:
        pop.record('spikes')

    # Run
    print("Run the simulation")
    p.run(sim_duration)

    # Get data
    print("Simulation finished, now collect all spikes and plot them")
    stim_spikes = pop_stim.spinnaker_get_data('spikes')
    stim_spikes[:, 0] -= n_exc

    # collect all spikes and make a raster_plot
    spklist_exc = []
    spklist_inh = []
    for group in range(n_groups):
        EXC_spikes = exc_pops[group].spinnaker_get_data('spikes')
        INH_spikes = inh_pops[group].spinnaker_get_data('spikes')
        EXC_spikes[:, 0] += group * (n_exc + n_inh)
        INH_spikes[:, 0] += group * (n_exc + n_inh) + n_exc
        spklist_exc += EXC_spikes.tolist()
        spklist_inh += INH_spikes.tolist()

    # Plot
    if plot:
        pylab.figure()
        pylab.plot([i[1] for i in spklist_exc], [i[0] for i in spklist_exc],
                   "r.")
        pylab.plot([i[1] for i in spklist_inh], [i[0] for i in spklist_inh],
                   "b.")
        pylab.plot([i[1] for i in stim_spikes], [i[0] for i in stim_spikes],
                   "k.")
        pylab.xlabel('Time/ms')
        pylab.ylabel('spikes')
        pylab.title('spikes')

        for group in range(n_groups):
            pylab.axhline(y=(group + 1) * (n_exc + n_inh), color="lightgrey")
            pylab.axhline(y=(group + 1) * (n_exc + n_inh) - n_inh,
                          color="lightgrey")

        pylab.axhline(y=0, color="grey", linewidth=1.5)
        pylab.show()

    p.end()

    return stim_spikes, spklist_exc, spklist_inh
Пример #13
0
 def test_is_local(self):
     sim.setup(timestep=1.0)
     pop_1 = sim.Population(N_NEURONS, sim.IF_curr_exp(), label=LABEL)
     cells = pop_1.all_cells
     assert pop_1.is_local(2) == cells[2].local
     sim.end()
Пример #14
0
    def do_run(self,
               n_neurons,
               time_step=1,
               max_delay=144.0,
               input_class=SpikeSourceArray,
               spike_times=None,
               rate=None,
               start_time=None,
               duration=None,
               seed=None,
               spike_times_list=None,
               placement_constraint=None,
               weight_to_spike=2.0,
               delay=17,
               neurons_per_core=10,
               cell_class=IF_curr_exp,
               constraint=None,
               cell_params=CELL_PARAMS_LIF,
               run_times=None,
               reset=False,
               extract_between_runs=True,
               set_between_runs=None,
               new_pop=False,
               record_input_spikes=False,
               record_input_spikes_7=False,
               record=True,
               get_spikes=None,
               spike_path=None,
               record_7=False,
               record_v=True,
               get_v=None,
               v_path=None,
               record_v_7=False,
               v_sampling_rate=None,
               record_gsyn_exc=True,
               record_gsyn_inh=True,
               get_gsyn_exc=None,
               get_gsyn_inh=None,
               gsyn_path_exc=None,
               gsyn_path_inh=None,
               record_gsyn_exc_7=False,
               record_gsyn_inh_7=False,
               gsyn_exc_sampling_rate=None,
               gsyn_inh_sampling_rate=None,
               get_all=False,
               use_spike_connections=True,
               use_wrap_around_connections=True,
               get_weights=False,
               get_delays=False,
               end_before_print=False,
               randomise_v_init=False):
        """

        :param n_neurons: Number of Neurons in chain
        :type n_neurons: int
        :param time_step: time step value to be used in p.setup
        :type time_step: float
        :param max_delay: max_delay value to be used in p.setup
        :type max_delay: float
        :param rate: the rate of the SSP to fire at
        :type rate: float
        :param start_time: the start time for the SSP
        :type start_time: float
        :param duration: the length of time for the SSP to fire for
        :type duration: float
        :param seed: Random seed
        :type seed: int
        :param input_class: the class for inputs spikes (SSA or SSP)
        :type input_class: SpikeSourceArray, SpikeSourcePoisson
        :param spike_times: times the SSA sends in spikes
        :type spike_times: matrix of int times the SSA sends in spikes
        :param spike_times_list: list of times the SSA sends in spikes
            - must be the same length as  run times
            - If set the spike_time parameter is ignored
        :type spike_times: list of matrix of int times the SSA sends in spikes
        :param weight_to_spike: weight for the OneToOne Connector.\
            Not used by any test at the moment
        :type weight_to_spike: float
        :param delay: time delay in the single connectors in the spike chain
        :type delay: float
        :param neurons_per_core: Number of neurons per core.\
            If set to None, no set_number_of_neurons_per_core call will be made
        :type neurons_per_core: int or None
        :param constraint: A Constraint to be place on populations[0]
        :type constraint: AbstractConstraint
        :param cell_class: class to be used for the main population.\
            Not used by any test at the moment
        :type cell_class: AbstractPopulationVertex
        :param cell_params: values for the main population.\
            Not used by any test at the moment.\
            Note: the values must match what is expected by the cellclass
        :type cell_params: dict
        :param run_times: times for each run.\
            A zero will skip run but trigger reset and get date ext as set
        :type run_times: list of int
        :param reset: if True will call reset after each run except the last
        :type reset: bool
        :param extract_between_runs: \
            If True reads V, gysn and spikes between each run.
        :type extract_between_runs: bool
        :param set_between_runs: set instructions to be carried out between\
            runs. Should be a list of tuples.
            First element of each tuple is 0 or 1:
              * 0 for main population
              * 1 for input population
            Second element a String for name of property to change.
            Third element the new value
        :type set_between_runs: List[(int, String, any)]
        :param new_pop: If True will add a new population before the second run
        :type new_pop: bool
        :param record_input_spikes: check for recording input spikes
        :type record_input_spikes: bool
        :param record_input_spikes_7: \
            Check for recording input spikes in PyNN7 format
        :type record_input_spikes_7: bool
        :param record: If True will asks for spikes to be recorded
        :type record: bool
        :param get_spikes: If set overrides the normal behaviour\
            of getting spikes if and only if record is True.\
            If left None the value of record is used.
        :type get_spikes: bool
        :param spike_path: The path to print(write) the last spike data too
        :type spike_path: str or None
        :param record_7: \
            If True will asks for spikes to be recorded in PyNN7 format
        :type record_7: bool
        :param record_v: If True will ask for voltage to be recorded
        :type record_v: bool
        :param get_v: If set overrides the normal behaviour\
            of getting v if and only if record_v is True.\
            If left None the value of record_v is used.
        :type get_v: bool
        :param v_path: The path to print(write) the last v data too
        :type v_path: str or None
        :param get_v_7: If True ???????
        :type get_v_7: bool
        :param record_v_7: If True will ask for voltage to be recorded\
            in PyNN7 format
        :type record_v_7: bool
        :param v_sampling_rate: Rate at which to sample v.
        :type v_sampling_rate: int, float ot None
        :param record_gsyn_exc: If True will aks for gsyn exc to be recorded
        :param record_gsyn_exc: If True will ask for gsyn exc to be recorded
        :type record_gsyn_exc: bool
        :param record_gsyn_inh: If True will ask for gsyn inh to be recorded
        :type record_gsyn_inh: bool
        :param gsyn_path_exc: \
            The path to print(write) the last gsyn exc data to.
        :type gsyn_path_exc: str or None
        :param get_gsyn_exc: If set overrides the normal behaviour\
            of getting gsyn exc if and only if record_gsyn_exc is True.\
            If left None the value of record_gsyn_exc is used.
        :type get_gsyn_exc: bool
        :param get_gsyn_inh: If set overrides the normal behaviour\
            of getting gsyn inh if and only if record_gsyn_inh is True.\
            If left None the value of record_gsyn_ihn is used.
        :type get_gsyn_inh: bool
        :param gsyn_path_inh: \
            The path to print(write) the last gsyn in the data to.
        :type gsyn_path_inh: str or None
        :param record_gsyn_exc_7: \
            If True will ask for gsyn exc to be recorded in PyNN 7 format
        :type record_gsyn_exc_7: bool
        :param record_gsyn_inh_7: \
            If True will ask for gsyn inh to be recorded in PyNN 7 format
        :type record_gsyn_inh_7: bool
        :param get_all: if True will obtain another neo object with all the
            data set to be recorded by any other parameter
        :type get_all: bool
        :param get_weights: If True set will add a weight value to the return
        :type get_weights: bool
        :param get_delays: If True delays will be gotten
        :type get_delays: bool
        :param end_before_print: If True will call end() before running the\
            optional print commands.
            Note: end will always be called twice even if no print path\
            provided
            WARNING: This is expected to cause an Exception \
                if spike_path, v_path or gsyn_path provided
        :type end_before_print: bool
        :param randomise_v_init: randomises the v_init of the output pop.
        :type randomise_v_init: bool
        :param use_loop_connections: \
            True will put looping connections in. False won't.
        :type use_loop_connections: bool
        :return (v, gsyn, spikes, weights .....)
            v: Voltage after last or each run (if requested else None)
            gysn: gysn after last or each run (if requested else None)
            spikes: spikes after last or each run (if requested else None)
            weights: weights after last or each run (if requested else skipped)

            All three/four values will repeated once per run is requested
        """
        self.__init_object_state()

        # Initialise/verify various values
        cell_params, run_times, set_between_runs, spike_times, get_spikes, \
            get_v, get_gsyn_exc, get_gsyn_inh = self.__verify_parameters(
                cell_params, run_times, set_between_runs, spike_times,
                get_spikes, record, record_7, spike_path, get_v, record_v,
                record_v_7, v_path, get_gsyn_exc, record_gsyn_exc,
                record_gsyn_exc_7, gsyn_path_exc, get_gsyn_inh,
                record_gsyn_inh, record_gsyn_inh_7, gsyn_path_inh)

        p.setup(timestep=time_step, min_delay=1.0, max_delay=max_delay)
        if neurons_per_core is not None:
            p.set_number_of_neurons_per_core(p.IF_curr_exp, neurons_per_core)

        populations, projections, run_count = self.__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)

        # handle recording
        if record or record_7 or spike_path:
            populations[0].record("spikes")
        if record_v or record_v_7 or v_path:
            populations[0].record(variables="v",
                                  sampling_interval=v_sampling_rate)
        if record_gsyn_exc or record_gsyn_exc_7 or gsyn_path_exc:
            populations[0].record(variables="gsyn_exc",
                                  sampling_interval=gsyn_exc_sampling_rate)
        if record_gsyn_inh or record_gsyn_inh_7 or gsyn_path_inh:
            populations[0].record(variables="gsyn_inh",
                                  sampling_interval=gsyn_inh_sampling_rate)
        if record_input_spikes or record_input_spikes_7:
            populations[1].record("spikes")

        results = self.__run_sim(
            run_times, populations, projections, run_count, spike_times_list,
            extract_between_runs, get_spikes, record_7, get_v, record_v_7,
            get_gsyn_exc, record_gsyn_exc_7, get_gsyn_inh, record_gsyn_inh_7,
            record_input_spikes, record_input_spikes_7, get_all, get_weights,
            get_delays, new_pop, n_neurons, cell_class, cell_params,
            weight_to_spike, set_between_runs, reset)

        self._get_data(populations[0], populations[1], get_spikes, record_7,
                       get_v, record_v_7, get_gsyn_exc, record_gsyn_exc_7,
                       get_gsyn_inh, record_gsyn_inh_7, record_input_spikes,
                       record_input_spikes_7, get_all)

        self._get_weight_delay(projections[0], get_weights, get_delays)

        if end_before_print:
            if v_path is not None or spike_path is not None or \
                    gsyn_path_exc is not None or gsyn_path_inh is not None:
                print("NOTICE! end is being called before print.. commands "
                      "which could cause an exception")
            p.end()

        if v_path is not None:
            populations[0].write_data(v_path, "v")
        if spike_path is not None:
            populations[0].write_data(spike_path, "spikes")
        if gsyn_path_exc is not None:
            populations[0].write_data(gsyn_path_exc, "gsyn_exc")
        if gsyn_path_inh is not None:
            populations[0].write_data(gsyn_path_inh, "gsyn_inh")
        if not end_before_print:
            p.end()

        return results
Пример #15
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': -50.0
    }

    # Parameters
    nNeurons = 200
    weight_to_spike = 2.0
    delay = 17
    runtime = 5000
    p.set_number_of_neurons_per_core(p.IF_curr_exp, nNeurons / 2)

    # Populations
    pop = p.Population(nNeurons,
                       p.IF_curr_exp(**cell_params_lif),
                       label='pop_1')
    pop2 = p.Population(nNeurons,
                        p.IF_curr_exp(**cell_params_lif),
                        label='pop_2')

    # create loopConnections array for first population using numpy linspaces
    loopConnections = numpy.zeros((nNeurons, nNeurons))
    for i in range(nNeurons):
        if i != (nNeurons - 1):
            loopConnections[i, i + 1] = True
        else:
            loopConnections[i, 0] = True

    # do the same for the second population, but just for even numbered neurons
    loopConnections2 = numpy.zeros((nNeurons, nNeurons))
    for i in range(0, nNeurons, 2):
        if i != (nNeurons - 2):
            loopConnections2[i, i + 2] = True
        else:
            loopConnections2[i, 0] = True

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

    # Projection for injector
    p.Projection(inj_pop, pop, p.ArrayConnector(injectionConnection),
                 p.StaticSynapse(weight=weight_to_spike, delay=1))
    p.Projection(inj_pop, pop2, p.ArrayConnector(injectionConnection),
                 p.StaticSynapse(weight=weight_to_spike, delay=1))

    # Projection within populations
    p.Projection(pop, pop, p.ArrayConnector(loopConnections),
                 p.StaticSynapse(weight=weight_to_spike, delay=delay))
    p.Projection(pop2, pop2, p.ArrayConnector(loopConnections2),
                 p.StaticSynapse(weight=weight_to_spike, delay=delay))

    pop.record(['v', 'spikes'])
    pop2.record(['v', 'spikes'])
    p.run(runtime)

    v = pop.get_data('v')
    spikes = pop.get_data('spikes')
    v2 = pop2.get_data('v')
    spikes2 = pop2.get_data('spikes')

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

    p.end()

    return v, spikes, v2, spikes2
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)
Пример #17
0
    def debug(self, run_zero):
        reports = [
            # write_energy_report
            "Detailed_energy_report.rpt",
            "energy_summary_report.rpt",
            # write_text_specs = False
            "data_spec_text_files",
            # write_router_reports
            reports_names._ROUTING_FILENAME,
            # write_partitioner_reports
            reports_names._PARTITIONING_FILENAME,
            # write_application_graph_placer_report
            reports_names._PLACEMENT_VTX_GRAPH_FILENAME,
            reports_names._PLACEMENT_CORE_GRAPH_FILENAME,
            reports_names._SDRAM_FILENAME,
            # write_machine_graph_placer_report
            reports_names._PLACEMENT_VTX_SIMPLE_FILENAME,
            reports_names._PLACEMENT_CORE_SIMPLE_FILENAME,
            # repeats reports_names._SDRAM_FILENAME,
            # write_router_info_report
            reports_names._VIRTKEY_FILENAME,
            # write_routing_table_reports
            reports_names._ROUTING_TABLE_DIR,
            reports_names._C_ROUTING_TABLE_DIR,
            reports_names._COMPARED_FILENAME,
            # write_routing_compression_checker_report
            "routing_compression_checker_report.rpt",
            # write_routing_tables_from_machine_report
            routing_tables_from_machine_report,
            # write_memory_map_report
            # ??? used by MachineExecuteDataSpecification but not called ???
            # write_network_specification_report
            NetworkSpecification._FILENAME,
            # write_provenance_data
            "provenance_data",
            # write_tag_allocation_reports
            reports_names._TAGS_FILENAME,
            # write_algorithm_timings
            # "provenance_data/pacman.xml"  = different test
            # write_board_chip_report
            BoardChipReport.AREA_CODE_REPORT_NAME,
        ]

        sim.setup(1.0)
        configs = globals_variables.get_simulator()._config
        if (configs.getboolean("Machine", "enable_advanced_monitor_support")
                and not configs.getboolean("Java", "use_java")):
            # write_data_speed_up_report
            reports.append(DataSpeedUpPacketGatherMachineVertex.REPORT_NAME)
        pop = sim.Population(100, sim.IF_curr_exp, {}, label="pop")
        pop.record("v")
        inp = sim.Population(1,
                             sim.SpikeSourceArray(spike_times=[0]),
                             label="input")
        sim.Projection(inp,
                       pop,
                       sim.AllToAllConnector(),
                       synapse_type=sim.StaticSynapse(weight=5))
        if run_zero:
            sim.run(0)
        sim.run(1000)
        pop.get_data("v")
        report_directory = globals_variables.get_simulator().\
            _report_default_directory
        sim.end()

        found = os.listdir(report_directory)
        for report in reports:
            self.assertIn(report, found)
Пример #18
0
 def do_run(self):
     p.setup(timestep=1.0, min_delay=1.0)
     p.run(100)
     p.end()
def do_run():
    p.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)

    cell_params_lif = {
        'cm': 0.25,  # nF
        '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(sources, p.IF_curr_exp, cell_params_lif, label='pop_1'))

    populations.append(
        p.Population(targets, p.IF_curr_exp, cell_params_lif, label='pop_2'))

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

    p.run(1)

    # before
    pre_delays_array = projections[0].get(attribute_names=["delay"],
                                          format="nparray")
    pre_delays_list = projections[0].get(attribute_names=["delay"],
                                         format="list")
    pre_weights_array = projections[0].get(attribute_names=["weight"],
                                           format="array")
    pre_weights_list = projections[0].get(attribute_names=["weight"],
                                          format="list")

    p.run(100)

    # after
    post_delays_array = projections[0].get(attribute_names=["delay"],
                                           format="nparray")
    post_delays_list = projections[0].get(attribute_names=["delay"],
                                          format="list")
    post_weights_array = projections[0].get(attribute_names=["weight"],
                                            format="array")
    post_weights_list = projections[0].get(attribute_names=["weight"],
                                           format="list")

    p.end()

    return (pre_delays_array, pre_delays_list, pre_weights_array,
            pre_weights_list, post_delays_array, post_delays_list,
            post_weights_array, post_weights_list)
Пример #20
0
    # 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)

spikes_forward = pop_forward.get_data('spikes')
spikes_backward = pop_backward.get_data('spikes')

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()

# Clear data structures on spiNNaker to leave the machine in a clean state for
# future executions
Frontend.end()
Пример #21
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, 250)

    cell_params_lif = {
        'cm': 0.25,
        'i_offset': 0.0,
        'tau_m': 20.0,
        'tau_refrac': 5.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 = 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'))

    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(1000)
    ''''
    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)
Пример #22
0
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)
Пример #23
0
 def test_double_end(self):
     sim.setup(1.0)
     sim.end()
     sim.end()
Пример #24
0
def do_run():
    # 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}

    delta_t = 10
    time_between_pairs = 150
    num_pre_pairs = 10
    num_pairs = 100
    num_post_pairs = 10
    pop_size = 1

    pairing_start_time = (num_pre_pairs * time_between_pairs) + delta_t
    pairing_end_time = pairing_start_time + (num_pairs * time_between_pairs)
    sim_time = pairing_end_time + (num_post_pairs * time_between_pairs)

    # +-------------------------------------------------------------------+
    # | Creation of neuron populations                                    |
    # +-------------------------------------------------------------------+
    # Neuron populations
    pre_pop = sim.Population(pop_size, model, cell_params)
    post_pop = sim.Population(pop_size, model, cell_params)

    # Stimulating populations
    pre_stim = sim.Population(pop_size, sim.SpikeSourceArray,
                              {'spike_times':
                               [[i for i in range(0, sim_time,
                                                  time_between_pairs)], ]})
    post_stim = sim.Population(pop_size, sim.SpikeSourceArray,
                               {'spike_times':
                                [[i for i in range(pairing_start_time,
                                                   pairing_end_time,
                                                   time_between_pairs)], ]})

    # +-------------------------------------------------------------------+
    # | Creation of connections                                           |
    # +-------------------------------------------------------------------+
    # Connection type between noise poisson generator and
    # excitatory populations
    ee_connector = sim.OneToOneConnector()
    synapse_type = sim.StaticSynapse(weight=2)

    sim.Projection(pre_stim, pre_pop, ee_connector, synapse_type=synapse_type,
                   receptor_type='excitatory')
    sim.Projection(post_stim, post_pop, ee_connector,
                   synapse_type=synapse_type, receptor_type='excitatory')

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

    sim.Projection(pre_pop, post_pop, sim.OneToOneConnector(),
                   synapse_type=stdp_model)

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

    # Run simulation
    sim.run(sim_time)

    neo = pre_pop.get_data("spikes")
    pre_spikes = neo_convertor.convert_spikes(neo)

    neo = post_pop.get_data("spikes")
    post_spikes = neo_convertor.convert_spikes(neo)

    # End simulation on SpiNNaker
    sim.end()

    return (pre_spikes, post_spikes)
Пример #25
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 = 256
    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 fromfileconnector
    current_file_path = os.path.dirname(os.path.abspath(__file__))
    file1 = os.path.join(current_file_path, "large.connections")
    file_connector1 = p.FromFileConnector(file1)

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

    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:
        # pylint: disable=no-member
        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
Пример #26
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
                       }

    def create_grid(n, label, dx=1.0, dy=1.0):
        grid_structure = p.Grid2D(dx=dx, dy=dy, x0=0.0, y0=0.0)
        return p.Population(n*n, p.IF_curr_exp(**cell_params_lif),
                            structure=grid_structure, label=label)

    n = 4
    weight_to_spike = 5.0
    delay = 5
    runtime = 200

    # Network
    grid = create_grid(n, 'grid')

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

    p.Projection(inj_pop, grid, p.FromListConnector(injectionConnection),
                 p.StaticSynapse(weight=weight_to_spike, delay=delay))

    # Connectors
    exc_connector = p.AllToAllConnector()
    inh_connector = p.FixedProbabilityConnector(0.5, rng=NumpyRNG(seed=10101))

    # Wire grid
    exc_proj = p.Projection(grid, grid, exc_connector,
                            p.StaticSynapse(
                                weight="1.0 + (2.0*exp(-d))", delay=5))
    inh_proj = p.Projection(grid, grid, inh_connector,
                            p.StaticSynapse(
                                weight=1.5, delay="2 + 2.0*d"))

    grid.record(['v', 'spikes'])

    p.run(runtime)

    v = grid.get_data('v')
    spikes = grid.get_data('spikes')

    exc_weights_delays = exc_proj.get(['weight', 'delay'], 'list')
    inh_weights_delays = inh_proj.get(['weight', 'delay'], 'list')

    if plot:
        Figure(
            # raster plot of the presynaptic neurons' spike times
            Panel(spikes.segments[0].spiketrains,
                  yticks=True, markersize=0.2, xlim=(0, runtime), xticks=True),
            # membrane potential of the postsynaptic neurons
            Panel(v.segments[0].filter(name='v')[0],
                  ylabel="Membrane potential (mV)",
                  data_labels=[grid.label], yticks=True, xlim=(0, runtime),
                  xticks=True),
            title="Simple 2D grid distance-dependent weights and delays",
            annotations="Simulated with {}".format(p.name())
        )
        plt.show()

    p.end()

    return exc_weights_delays, inh_weights_delays
weight_to_spike = 2.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.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)))

p.run(runtime)

print projections[0].get(['weight', 'delay'], 'list')

p.end()
Пример #28
0
def split_structural_without_stdp():
    p.setup(1.0)
    stim = p.Population(1, p.SpikeSourceArray(range(10)), label="stim")

    # These populations should experience formation
    pop = p.Population(1,
                       p.IF_curr_exp(),
                       label="pop",
                       additional_parameters={
                           "splitter":
                           SplitterAbstractPopulationVertexNeuronsSynapses(1)
                       })
    pop_2 = p.Population(1,
                         p.IF_curr_exp(),
                         label="pop_2",
                         additional_parameters={
                             "splitter":
                             SplitterAbstractPopulationVertexNeuronsSynapses(1)
                         })

    # These populations should experience elimination
    pop_3 = p.Population(1,
                         p.IF_curr_exp(),
                         label="pop_3",
                         additional_parameters={
                             "splitter":
                             SplitterAbstractPopulationVertexNeuronsSynapses(1)
                         })
    pop_4 = p.Population(1,
                         p.IF_curr_exp(),
                         label="pop_4",
                         additional_parameters={
                             "splitter":
                             SplitterAbstractPopulationVertexNeuronsSynapses(1)
                         })

    # Formation with last-neuron selection (0 probability elimination)
    proj = p.Projection(
        stim, pop, p.FromListConnector([]),
        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=2.0,
            initial_delay=5.0,
            s_max=1,
            seed=0,
            weight=0.0,
            delay=1.0))

    # Formation with random selection (0 probability elimination)
    proj_2 = p.Projection(
        stim, pop_2, p.FromListConnector([]),
        p.StructuralMechanismStatic(
            partner_selection=p.RandomSelection(),
            formation=p.DistanceDependentFormation([1, 1], 1.0),
            elimination=p.RandomByWeightElimination(4.0, 0, 0),
            f_rew=1000,
            initial_weight=4.0,
            initial_delay=3.0,
            s_max=1,
            seed=0,
            weight=0.0,
            delay=1.0))

    # Elimination with last neuron selection (0 probability formation)
    proj_3 = p.Projection(
        stim, pop_3, p.FromListConnector([(0, 0)]),
        p.StructuralMechanismStatic(
            partner_selection=p.LastNeuronSelection(),
            formation=p.DistanceDependentFormation([1, 1], 0.0),
            elimination=p.RandomByWeightElimination(4.0, 1.0, 1.0),
            f_rew=1000,
            initial_weight=2.0,
            initial_delay=5.0,
            s_max=1,
            seed=0,
            weight=0.0,
            delay=1.0))

    # Elimination with random selection (0 probability formation)
    proj_4 = p.Projection(
        stim, pop_4, p.FromListConnector([(0, 0)]),
        p.StructuralMechanismStatic(
            partner_selection=p.RandomSelection(),
            formation=p.DistanceDependentFormation([1, 1], 0.0),
            elimination=p.RandomByWeightElimination(4.0, 1.0, 1.0),
            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)

    # Get the final connections
    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)

    # These should be formed with specified parameters
    assert (len(conns) == 1)
    assert (tuple(conns[0]) == (0, 0, 2.0, 5.0))
    assert (len(conns_2) == 1)
    assert (tuple(conns_2[0]) == (0, 0, 4.0, 3.0))

    # These should have no connections since eliminated
    assert (len(conns_3) == 0)
    assert (len(conns_4) == 0)
Пример #29
0
def agent_fitness(agent, light_distance, light_theta, print_move):
    global port_offset
    global number_of_runs
    global counter
    global current_agent
    global current_fitness
    global current_light_distance
    global current_light_theta
    global currently_running
    current_agent = agent
    print "\n\nStarting agent - {}\n\n".format(agent)
    p.setup(timestep=1.0, min_delay=delay_min, max_delay=delay_max)
    p.set_number_of_neurons_per_core(p.IF_cond_exp, 20)
    # setup of different neuronal populations
    #neuron_pop = list();
    neuron_pop = []
    if port_offset != 1:
        for i in range(agent_neurons):
            del neuron_labels[0]
    inhibitory_count = 0
    excitatory_count = 0
    for i in range(agent_neurons):
        if agent_pop[agent][inhibitory_loc + i] == -1:
            neuron_labels.append("Inhibitory{}-neuron{}-agent{}-port{}".format(
                inhibitory_count, i, agent, port_offset))
            neuron_pop.append(
                p.Population(neuron_pop_size,
                             p.IF_cond_exp(),
                             label=neuron_labels[i]))
            inhibitory_count += 1
        else:
            neuron_labels.append("Excitatory{}-neuron{}-agent{}-port{}".format(
                excitatory_count, i, agent, port_offset))
            neuron_pop.append(
                p.Population(neuron_pop_size,
                             p.IF_cond_exp(),
                             label=neuron_labels[i]))
            excitatory_count += 1
        # if print_move == True:
        #     neuron_pop[i].record(["spikes", "v"])

    # connect neuronal population according to genentic instructions
    projection_list = list()
    for i in range(agent_neurons):
        for j in range(agent_neurons):
            # if theres a connection connect
            if agent_pop[agent][set2loc + (i * agent_neurons) + j] != 0:
                # if connection is inhibitory set as such
                if agent_pop[agent][inhibitory_loc + i] == -1:
                    synapse = p.StaticSynapse(
                        weight=-agent_pop[agent][(i * agent_neurons) + j],
                        delay=agent_pop[agent][delay_loc +
                                               ((i * agent_neurons) + j)])
                    projection_list.append(
                        p.Projection(neuron_pop[i],
                                     neuron_pop[j],
                                     p.AllToAllConnector(),
                                     synapse,
                                     receptor_type="inhibitory"))
                # set as excitatory
                else:
                    synapse = p.StaticSynapse(
                        weight=agent_pop[agent][(i * agent_neurons) + j],
                        delay=agent_pop[agent][delay_loc +
                                               ((i * agent_neurons) + j)])
                    projection_list.append(
                        p.Projection(neuron_pop[i],
                                     neuron_pop[j],
                                     p.AllToAllConnector(),
                                     synapse,
                                     receptor_type="excitatory"))
                    # set STDP, weight goes to negative if inhibitory?
                    # stdp_model = p.STDPMechanism(
                    #     timing_dependence=p.SpikePairRule(
                    #         tau_plus=20., tau_minus=20.0, A_plus=0.5, A_minus=0.5),
                    #         weight_dependence=p.AdditiveWeightDependence(w_min=weight_min, w_max=weight_max))

    # connect in and out live links
    #visual_input = list()
    visual_input = []
    visual_projection = []  #list()
    input_labels = []  #list()
    #sensor_poisson = [0 for j in range(visual_discrete)]
    sensor_poisson = poisson_rate(agent, light_distance, light_theta)

    for i in range(visual_discrete):
        print i
        input_labels.append("input_spikes{}".format(i))
        visual_input.append(
            p.Population(1,
                         p.SpikeSourcePoisson(rate=sensor_poisson[i]),
                         label=input_labels[i]))
        visual_projection.append(
            p.Projection(
                visual_input[i], neuron_pop[i], p.OneToOneConnector(),
                p.StaticSynapse(weight=visual_weight, delay=visual_delay)))
        p.external_devices.add_poisson_live_rate_control(
            visual_input[i], database_notify_port_num=16000 + port_offset)
        # poisson_control = p.external_devices.SpynnakerPoissonControlConnection(poisson_labels=[visual_input[i].label])#,local_port=18000+(port_offset*visual_discrete)+i)
        # poisson_control.add_start_callback(visual_input[i].label, poisson_setting)
    # visual_input = p.Population(visual_discrete, p.SpikeSourcePoisson(rate=sensor_poisson), label=input)
    # p.Projection(
    #     visual_input, neuron_pop[(i for i in range(0,visual_discrete))], p.OneToOneConnector(), p.StaticSynapse(weight=visual_weight, delay=visual_delay))
    # p.external_devices.add_poisson_live_rate_control(visual_input)
    poisson_control = p.external_devices.SpynnakerPoissonControlConnection(
        poisson_labels=input_labels, local_port=16000 + port_offset)
    poisson_control.add_start_callback(visual_input[0].label, poisson_setting)
    # poisson_control.add_start_callback(visual_input[1].label, empty_function)
    # poisson_control2 = p.external_devices.SpynnakerPoissonControlConnection(poisson_labels=[visual_input[1].label],local_port=19998)#+(port_offset*visual_discrete)+i)
    # poisson_control2.add_start_callback(visual_input[1].label, poisson_setting2)
    # poisson_control.add_start_callback(visual_input[1].label, poisson_setting)

    # for i in range(visual_discrete):
    #     print i
    #     input_labels.append("input_spikes{}".format(i))
    #     visual_input.append(p.Population(
    #         1, p.SpikeSourcePoisson(rate=sensor_poisson[i]), label=input_labels[i]))
    #     visual_projection.append(p.Projection(
    #         visual_input[i], neuron_pop[i], p.OneToOneConnector(), p.StaticSynapse(
    #             weight=visual_weight, delay=visual_delay)))
    #     p.external_devices.add_poisson_live_rate_control(visual_input[i]) #possible all at once
    # poisson_control = p.external_devices.SpynnakerPoissonControlConnection(poisson_labels=[input_labels[0], input_labels[1]])
    # #for i in range(visual_discrete):
    # poisson_control.add_start_callback(input_labels[i], poisson_setting)

    # for i in range(4):
    #     del motor_labels[0]
    motor_labels = []
    for i in range(4):
        print i
        motor_labels.append(neuron_labels[agent_neurons - (i + 1)])
        p.external_devices.activate_live_output_for(
            neuron_pop[agent_neurons - (i + 1)],
            database_notify_port_num=18000 + port_offset)
    live_connection = p.external_devices.SpynnakerLiveSpikesConnection(
        receive_labels=[
            motor_labels[0], motor_labels[1], motor_labels[2], motor_labels[3]
        ],
        local_port=(18000 + port_offset))
    for i in range(4):
        live_connection.add_receive_callback(motor_labels[i], receive_spikes)
    #fitness = 0
    # spikes = list()
    # v = list()

    current_fitness = 0
    current_light_theta = light_theta
    current_light_distance = light_distance
    currently_running = True
    p.run(total_runtime)
    currently_running = False

    no_move_distance = light_distance * total_runtime / time_slice
    fitness = current_fitness
    if abs(fitness - no_move_distance) < 1e-10:
        fitness *= no_move_punishment
        print "agent failed to move so was punished"
    # if print_move == True:
    #     spikes = []
    #     v = []
    #     for j in range(agent_neurons):
    #         spikes.append(neuron_pop[j].get_data("spikes"))
    #         v.append(neuron_pop[j].get_data("v"))
    live_connection.close()
    live_connection._handle_possible_rerun_state()
    p.end()
    if counter != number_of_runs:
        counter += 1
        port_offset += 1
        reset_agent(agent)
        if print_move == True:
            with open(
                    'movement {}.csv'.format(
                        (port_offset - counter) / number_of_runs),
                    'a') as file:
                writer = csv.writer(file, delimiter=',', lineterminator='\n')
                writer.writerow([
                    light_distance * np.sin(light_theta),
                    light_distance * np.cos(light_theta)
                ])
        port_recurse_check = port_offset
        fitness += agent_fitness(agent, light_distance, -light_theta,
                                 print_move)
    else:
        counter = 1
        port_offset -= 1
    port_offset += 1
    reset_agent(agent)
    return fitness
Пример #30
0
def do_run():
    simulator_name = 'spiNNaker'

    timer = Timer()

    # === Define parameters =========================================

    rngseed = 98766987
    parallel_safe = True

    n = 1500  # number of cells
    # number of excitatory cells:number of inhibitory cells
    r_ei = 4.0
    pconn = 0.02  # connection probability

    dt = 0.1  # (ms) simulation timestep
    tstop = 200  # (ms) simulaton duration
    delay = 1

    # Cell parameters
    area = 20000.  # (µm²)
    tau_m = 20.  # (ms)
    cm = 1.  # (µF/cm²)
    g_leak = 5e-5  # (S/cm²)
    e_leak = -49.  # (mV)
    v_thresh = -50.  # (mV)
    v_reset = -60.  # (mV)
    t_refrac = 5.  # (ms) (clamped at v_reset)
    # (mV) 'mean' membrane potential,  for calculating CUBA weights
    v_mean = -60.
    tau_exc = 5.  # (ms)
    tau_inh = 10.  # (ms)
    # (nS) #Those weights should be similar to the COBA weights
    g_exc = 0.27
    # (nS) # but the delpolarising drift should be taken into account
    g_inh = 4.5
    e_rev_exc = 0.  # (mV)
    e_rev_inh = -80.  # (mV)

    # === Calculate derived parameters ===============================

    area *= 1e-8  # convert to cm²
    cm *= area * 1000  # convert to nF
    r_m = 1e-6 / (g_leak * area)  # membrane resistance in MΩ
    assert tau_m == cm * r_m  # just to check

    # number of excitatory cells
    n_exc = int(round((n * r_ei / (1 + r_ei))))
    n_inh = n - n_exc  # number of inhibitory cells

    celltype = p.IF_curr_exp
    # (nA) weight of excitatory synapses
    w_exc = 1e-3 * g_exc * (e_rev_exc - v_mean)
    w_inh = 1e-3 * g_inh * (e_rev_inh - v_mean)  # (nA)
    assert w_exc > 0
    assert w_inh < 0

    # === Build the network ==========================================

    p.setup(timestep=dt, min_delay=delay, max_delay=delay)

    if simulator_name == 'spiNNaker':
        # this will set 100 neurons per core
        p.set_number_of_neurons_per_core(p.IF_curr_exp, 10)
        # this will set 50 neurons per core
        p.set_number_of_neurons_per_core(p.IF_cond_exp, 10)

    # node_id = 1
    # np = 1

    # host_name = socket.gethostname()

    cell_params = {'tau_m': tau_m, 'tau_syn_E': tau_exc, 'tau_syn_I': tau_inh,
                   'v_rest': e_leak, 'v_reset': v_reset, 'v_thresh': v_thresh,
                   'cm': cm, 'tau_refrac': t_refrac, 'i_offset': 0}

    timer.start()

    exc_cells = p.Population(n_exc, celltype, cell_params,
                             label="Excitatory_Cells")
    inh_cells = p.Population(n_inh, celltype, cell_params,
                             label="Inhibitory_Cells")
    p.NativeRNG(12345)

    rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)
    uniform_distr = RandomDistribution('uniform', [v_reset, v_thresh], rng=rng)
    exc_cells.initialize(v=uniform_distr)
    inh_cells.initialize(v=uniform_distr)

    exc_conn = p.FixedProbabilityConnector(pconn, rng=rng)
    synapse_exc = p.StaticSynapse(weight=w_exc, delay=delay)
    inh_conn = p.FixedProbabilityConnector(pconn, rng=rng)
    synapse_inh = p.StaticSynapse(weight=w_inh, delay=delay)

    connections = dict()
    connections['e2e'] = p.Projection(exc_cells, exc_cells, exc_conn,
                                      synapse_type=synapse_exc,
                                      receptor_type='excitatory')
    connections['e2i'] = p.Projection(exc_cells, inh_cells, exc_conn,
                                      synapse_type=synapse_exc,
                                      receptor_type='excitatory')
    connections['i2e'] = p.Projection(inh_cells, exc_cells, inh_conn,
                                      synapse_type=synapse_inh,
                                      receptor_type='inhibitory')
    connections['i2i'] = p.Projection(inh_cells, inh_cells, inh_conn,
                                      synapse_type=synapse_inh,
                                      receptor_type='inhibitory')

    # === Setup recording ==============================
    exc_cells.record("spikes")

    # === Run simulation ================================
    p.run(tstop)

    exc_spikes = exc_cells.get_data("spikes")

    exc_cells.write_data(neo_path, "spikes")

    p.end()

    return exc_spikes