populations = list()
projections = list()

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

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

p.run(runtime)

# get data (could be done as one, but can be done bit by bit as well)
示例#2
0
 def test_turn_off_spikes_indexes(self):
     sim.setup(timestep=1)
     if_curr = sim.Population(5, sim.IF_curr_exp())
     if_curr.record("spikes")
     if_curr.record(None)
     self.assertListEq([], if_curr._get_all_recording_variables())
def 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")
    pop_2 = p.Population(1, p.IF_curr_exp(), label="pop_2")

    # These populations should experience elimination
    pop_3 = p.Population(1, p.IF_curr_exp(), label="pop_3")
    pop_4 = p.Population(1, p.IF_curr_exp(), label="pop_4")

    # 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)
示例#4
0
    # The port on which the spiNNaker machine should listen for packets.
    # Packets to be injected should be sent to this port on the spiNNaker
    # machine
    'port': 12346,

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

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

# Create injection populations
injector_forward = Frontend.Population(
    n_neurons,
    Frontend.external_devices.SpikeInjector(
        **cell_params_spike_injector_with_key),
    label='spike_injector_forward')
injector_backward = Frontend.Population(
    n_neurons,
    Frontend.external_devices.SpikeInjector(**cell_params_spike_injector),
    label='spike_injector_backward')
示例#5
0
    def do_run(self,
               psh,
               psw,
               ksh,
               ksw,
               pre_start=(0, 0),
               post_start=(0, 0),
               pre_step=(1, 1),
               post_step=(1, 1)):
        sim.setup(timestep=1.0)

        # determine population size and runtime from the kernel sizes
        n_pop = psw * psh
        runtime = (n_pop * 5) + 1000

        spiking = [[n * 5, (n_pop * 5) - 1 - (n * 5)] for n in range(n_pop)]
        input_pop = sim.Population(n_pop,
                                   sim.SpikeSourceArray(spiking),
                                   label="input")
        pop = sim.Population(n_pop // 4, sim.IF_curr_exp(), label="pop")

        weights = 5.0
        delays = 17.0

        shape_pre = [psh, psw]
        shape_post = [psh // 2, psw // 2]
        shape_kernel = [ksh, ksw]

        weight_list = [[
            7.0 if ((a + b) % 2 == 0) else 5.0 for a in range(ksw)
        ] for b in range(ksh)]
        delay_list = [[
            20.0 if ((a + b) % 2 == 1) else 10.0 for a in range(ksw)
        ] for b in range(ksh)]
        weight_kernel = np.asarray(weight_list)
        delay_kernel = np.asarray(delay_list)

        kernel_connector = sim.KernelConnector(
            shape_pre,
            shape_post,
            shape_kernel,
            weight_kernel=weight_kernel,
            delay_kernel=delay_kernel,
            pre_sample_steps_in_post=pre_step,
            post_sample_steps_in_pre=post_step,
            pre_start_coords_in_post=pre_start,
            post_start_coords_in_pre=post_start)

        c2 = sim.Projection(input_pop, pop, kernel_connector,
                            sim.StaticSynapse(weight=weights, delay=delays))

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

        sim.run(runtime)

        weightsdelays = sorted(c2.get(['weight', 'delay'], 'list'),
                               key=lambda x: x[1])

        sim.end()

        return weightsdelays
示例#6
0
 def test_set_spikes_indexes3(self):
     sim.setup(timestep=1)
     if_curr = sim.Population(5, sim.IF_curr_exp())
     if_curr.record("spikes")
     self.assertCountEqual(["spikes"],
                           if_curr._recorder.get_all_recording_variables())
示例#7
0
文件: DNF2.py 项目: mattapattu/DNF
    loopConnections.append(singleConnection)

for i in range(160, 170):
    singleConnection = ((i, 3, 1, delay))
    loopConnections.append(singleConnection)

for i in range(170, 260):
    singleConnection = ((i, 4, 1, delay))
    loopConnections.append(singleConnection)

for i in range(260, 320):
    singleConnection = ((i, 5, 1, delay))
    loopConnections.append(singleConnection)

populations.append(
    p.Population(320, p.IF_curr_exp(**cell_params_lif), label='pop_1'))
populations.append(
    p.Population(6, p.IF_curr_exp(**cell_params_lif1), label='pop_2'))
populations.append(
    p.Population(
        320,
        p.external_devices.SpikeInjector(label='inputSpikes_1',
                                         database_notify_port_num=19990)))

projections.append(
    p.Projection(
        populations[0],
        populations[1],
        p.FromListConnector(loopConnections),
    ))
projections.append(
示例#8
0
def test_write_data_spec():
    unittest_setup()
    # UGLY but the mock transceiver NEED generate_on_machine to be False
    AbstractGenerateConnectorOnMachine.generate_on_machine = say_false
    machine = virtual_machine(2, 2)

    p.setup(1.0)
    load_config()
    p.set_number_of_neurons_per_core(p.IF_curr_exp, 100)
    pre_pop = p.Population(10,
                           p.IF_curr_exp(),
                           label="Pre",
                           additional_parameters={
                               "splitter":
                               SplitterAbstractPopulationVertexSlice()
                           })
    post_pop = p.Population(10,
                            p.IF_curr_exp(),
                            label="Post",
                            additional_parameters={
                                "splitter":
                                SplitterAbstractPopulationVertexSlice()
                            })
    proj_one_to_one_1 = p.Projection(pre_pop, post_pop, p.OneToOneConnector(),
                                     p.StaticSynapse(weight=1.5, delay=1.0))
    proj_one_to_one_2 = p.Projection(pre_pop, post_pop, p.OneToOneConnector(),
                                     p.StaticSynapse(weight=2.5, delay=2.0))
    proj_all_to_all = p.Projection(
        pre_pop, post_pop, p.AllToAllConnector(allow_self_connections=False),
        p.StaticSynapse(weight=4.5, delay=4.0))

    from_list_list = [(i, i, i, (i * 5) + 1) for i in range(10)]
    proj_from_list = p.Projection(pre_pop, post_pop,
                                  p.FromListConnector(from_list_list),
                                  p.StaticSynapse())

    app_graph = globals_variables.get_simulator().original_application_graph
    context = {"ApplicationGraph": app_graph}
    with (injection_context(context)):
        delay_support_adder(app_graph)
        machine_graph, _ = spynnaker_splitter_partitioner(
            app_graph, machine, 100)
        allocator = ZonedRoutingInfoAllocator()
        n_keys_map = edge_to_n_keys_mapper(machine_graph)
        routing_info = allocator.__call__(machine_graph,
                                          n_keys_map,
                                          flexible=False)

    post_vertex = next(iter(post_pop._vertex.machine_vertices))
    post_vertex_slice = post_vertex.vertex_slice
    post_vertex_placement = Placement(post_vertex, 0, 0, 3)

    temp_spec = tempfile.mktemp()
    spec = DataSpecificationGenerator(io.FileIO(temp_spec, "wb"), None)

    synaptic_matrices = SynapticMatrices(post_vertex_slice,
                                         n_synapse_types=2,
                                         all_single_syn_sz=10000,
                                         synaptic_matrix_region=1,
                                         direct_matrix_region=2,
                                         poptable_region=3,
                                         connection_builder_region=4)
    synaptic_matrices.write_synaptic_data(
        spec,
        post_pop._vertex.incoming_projections,
        all_syn_block_sz=10000,
        weight_scales=[32, 32],
        routing_info=routing_info)
    spec.end_specification()

    with io.FileIO(temp_spec, "rb") as spec_reader:
        executor = DataSpecificationExecutor(spec_reader, 20000)
        executor.execute()

    all_data = bytearray()
    all_data.extend(bytearray(executor.get_header()))
    all_data.extend(bytearray(executor.get_pointer_table(0)))
    for r in range(MAX_MEM_REGIONS):
        region = executor.get_region(r)
        if region is not None:
            all_data.extend(region.region_data)
    transceiver = MockTransceiverRawData(all_data)
    report_folder = mkdtemp()
    try:
        connections_1 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_one_to_one_1._projection_edge,
                proj_one_to_one_1._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_1) == post_vertex_slice.n_atoms
        assert all([conn["weight"] == 1.5 for conn in connections_1])
        assert all([conn["delay"] == 1.0 for conn in connections_1])

        connections_2 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_one_to_one_2._projection_edge,
                proj_one_to_one_2._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_2) == post_vertex_slice.n_atoms
        assert all([conn["weight"] == 2.5 for conn in connections_2])
        assert all([conn["delay"] == 2.0 for conn in connections_2])

        connections_3 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_all_to_all._projection_edge,
                proj_all_to_all._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_3) == 100
        assert all([conn["weight"] == 4.5 for conn in connections_3])
        assert all([conn["delay"] == 4.0 for conn in connections_3])

        connections_4 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_from_list._projection_edge,
                proj_from_list._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_4) == len(from_list_list)
        list_weights = [values[2] for values in from_list_list]
        list_delays = [values[3] for values in from_list_list]
        assert all(list_weights == connections_4["weight"])
        assert all(list_delays == connections_4["delay"])
    finally:
        shutil.rmtree(report_folder, ignore_errors=True)
示例#9
0
    def test_simple(self):
        n_neurons = 5
        label = "pop_1"
        sim.setup(timestep=1.0)
        pop_1 = sim.Population(n_neurons, sim.IF_curr_exp(), label=label)
        mask = [1, 3]
        view = PopulationView(pop_1, mask, label=label)
        self.assertEqual(2, view.size)
        self.assertEqual(2, view.local_size)

        random_view = pop_1.sample(3)
        self.assertEqual(3, random_view.size)

        self.assertEqual(label, view.label)
        self.assertEqual(pop_1.celltype, view.celltype)
        self.assertEqual(pop_1.celltype, random_view.celltype)

        view_initial_values = view.initial_values
        pop_initial_values = pop_1.initial_values
        self.assertEqual(len(view_initial_values), len(pop_initial_values))
        for key in pop_initial_values:
            self.assertEqual(pop_initial_values[key][3],
                             view_initial_values[key][1])

        self.assertEqual(pop_1, view.parent)
        self.assertEqual(mask, view.mask)

        cells = view.all_cells
        self.assertEqual(2, len(cells))
        self.assertEqual(1, cells[0].id)
        self.assertEqual(3, cells[1].id)

        self.assertEqual(cells, view.local_cells)
        self.assertEqual(cells[0], view[1])

        iterator = iter(view)
        self.assertEqual(1, next(iterator).id)
        self.assertEqual(3, next(iterator).id)
        with pytest.raises(StopIteration):
            next(iterator)

        self.assertEqual(2, len(view))

        iterator = view.all()
        self.assertEqual(1, next(iterator).id)
        self.assertEqual(3, next(iterator).id)
        with pytest.raises(StopIteration):
            next(iterator)

        self.assertEqual(view.can_record("v"), pop_1.can_record("v"))
        self.assertEqual(view.conductance_based, pop_1.conductance_based)

        describe = view.describe()
        self.assertIn('PopulationView "pop_1"', describe)
        self.assertIn('parent : "pop_1"', describe)
        self.assertIn('size   : 2', describe)
        self.assertIn('mask   : [1, 3]', describe)

        self.assertEqual(pop_1.find_units("v"), view.find_units("v"))

        sim.end()
 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)
示例#11
0
    def set_initialize_between_runs(self):
        runtime1 = 5
        runtime2 = 5
        runtime3 = 5

        p.setup(timestep=1.0)

        pop = p.Population(3, p.IF_curr_exp())
        pop.record(['v'])
        self.assertEquals([-65, -65, -65], pop.initial_values["v"])

        pop.initialize(v=-64)
        self.assertEquals([-64, -64, -64], pop.initial_values["v"])
        p.run(runtime1)

        self.assertEquals([-64, -64, -64], pop.initial_values["v"])
        pop.initialize(v=-62)
        self.assertEquals([-62, -62, -62], pop.initial_values["v"])
        p.run(runtime2)

        self.assertEquals([-62, -62, -62], pop.initial_values["v"])
        id_mixin = pop[1]
        id_mixin.initialize(v=-60)
        # v on not changed is now the current state not initial value
        self.assertNotEqual(-60, pop.initial_values["v"][0])
        self.assertNotEqual(-62, pop.initial_values["v"][0])
        self.assertEquals(-60, pop.initial_values["v"][1])
        self.assertNotEqual(-60, pop.initial_values["v"][2])
        self.assertNotEqual(-62, pop.initial_values["v"][2])
        p.run(runtime3)

        p.reset()
        self.assertEquals([-64, -64, -64], pop.initial_values["v"])
        pop.initialize(isyn_exc=-0.1)
        self.assertEquals([-64, -64, -64], pop.initial_values["v"])
        p.run(runtime1)
        self.assertEquals([-64, -64, -64], pop.initial_values["v"])
        view = pop[0:2]
        view.initialize(v=-63)
        self.assertEquals(-63, pop.initial_values["v"][0])
        self.assertEquals(-63, pop.initial_values["v"][1])

        # v on not changed is now the current state not initial value
        self.assertNotEqual(-63, pop.initial_values["v"][2])
        self.assertNotEqual(-64, pop.initial_values["v"][2])
        p.run(runtime2)

        neo = pop.get_data('v')
        p.end()

        v0 = neo.segments[0].filter(name='v')[0]
        self.assertListEqual(list(v0[0]), [-64, -64, -64])
        self.assertListEqual(list(v0[runtime1]), [-62.0, -62, -62])
        assert v0[runtime1 + runtime2][0] != -62.0
        assert v0[runtime1 + runtime2][0] != -60.0
        assert v0[runtime1 + runtime2][1] == -60.0
        assert v0[runtime1 + runtime2][2] != -62.0
        assert v0[runtime1 + runtime2][2] != -60.0
        v1 = neo.segments[1].filter(name='v')[0]
        self.assertListEqual(list(v1[0]), [-64.0, -64, -64])
        assert v1[runtime1][0] == -63.0
        assert v1[runtime1][1] == -63.0
        assert v1[runtime1][2] != -63.0
        assert v1[runtime1][2] != -64.0
示例#12
0
import spynnaker8 as sim
import pyNN.utility.plotting as plot
import matplotlib.pyplot as plt

simtime = 500
n_neurons = 100

# Set up the simulation to use a 1ms time step.
sim.setup(timestep=1)

# Create a population of 100 presynaptic neurons.
pre_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="presynaptic")

# Create a spike source array population of 100 sources connected to the
# presynaptic population.
# Set the spikes in the arrays so that each spikes twice 200ms apart,
# and that the first spike for each is 1ms after the first spike of the last
# e.g. [[0, 200], [1, 201], ...]
# (hint: you can do this with a list comprehension).
spike_times = [[x+y for x in [0, 200]] for y in range(n_neurons)]
print spike_times
pre_input = sim.Population(
    n_neurons, sim.SpikeSourceArray(spike_times=spike_times),
    label="pre input")
sim.Projection(pre_input,  pre_pop,  sim.OneToOneConnector(),
               synapse_type=sim.StaticSynapse(weight=5.0))

# Create a population of 100 postsynaptic neurons.
post_pop = sim.Population(n_neurons, sim.IF_curr_exp(), label="postsynaptic")
# Create a spike source array connected to the postsynaptic neurons all
# spiking at 50ms.
示例#13
0
def test_write_data_spec():
    unittest_setup()
    # UGLY but the mock transceiver NEED generate_on_machine to be False
    AbstractGenerateConnectorOnMachine.generate_on_machine = say_false
    machine = virtual_machine(2, 2)

    p.setup(1.0)
    load_config()
    p.set_number_of_neurons_per_core(p.IF_curr_exp, 100)
    pre_pop = p.Population(
        10, p.IF_curr_exp(), label="Pre",
        additional_parameters={
            "splitter": SplitterAbstractPopulationVertexSlice()})
    post_pop = p.Population(
        10, p.IF_curr_exp(), label="Post",
        additional_parameters={
            "splitter": SplitterAbstractPopulationVertexSlice()})
    proj_one_to_one_1 = p.Projection(
        pre_pop, post_pop, p.OneToOneConnector(),
        p.StaticSynapse(weight=1.5, delay=1.0))
    proj_one_to_one_2 = p.Projection(
        pre_pop, post_pop, p.OneToOneConnector(),
        p.StaticSynapse(weight=2.5, delay=2.0))
    proj_all_to_all = p.Projection(
        pre_pop, post_pop, p.AllToAllConnector(allow_self_connections=False),
        p.StaticSynapse(weight=4.5, delay=4.0))

    # spynnaker8.setup(timestep=1)
    # # Add an sdram so max SDRAM is high enough
    # SDRAM(10000)
    #
    # set_config("Simulation", "one_to_one_connection_dtcm_max_bytes", 40)
    #
    # placements = Placements()
    # pre_app_population = MockPopulation(10, "mock pop pre")
    # pre_app_vertex = SimpleTestVertex(10, label="pre")
    # pre_app_vertex.splitter = MockSplitter()
    # pre_app_vertex.splitter._called = True
    # pre_vertex_slice = Slice(0, 9)
    #
    # post_app_population = MockPopulation(10, "mock pop post")
    # pre_vertex = pre_app_vertex.create_machine_vertex(
    #     pre_vertex_slice, None)
    # placements.add_placement(Placement(pre_vertex, 0, 0, 1))
    # post_app_vertex = SimpleTestVertex(10, label="post")
    # post_app_vertex.splitter = MockSplitter()
    # post_app_vertex.splitter._called = True
    # post_vertex_slice = Slice(0, 9)
    # post_vertex = post_app_vertex.create_machine_vertex(
    #     post_vertex_slice, None)
    # post_vertex_placement = Placement(post_vertex, 0, 0, 2)
    # placements.add_placement(post_vertex_placement)
    # delay_app_vertex = DelayExtensionVertex(
    #     10, 16, 51, pre_app_vertex, label="delay")
    # delay_app_vertex.set_new_n_delay_stages_and_delay_per_stage(
    #     16, 51)
    # delay_app_vertex.splitter = SplitterDelayVertexSlice(
    #     pre_app_vertex.splitter)
    # delay_vertex = DelayExtensionMachineVertex(
    #     resources_required=None, label="", constraints=[],
    #     app_vertex=delay_app_vertex, vertex_slice=post_vertex_slice)
    # placements.add_placement(Placement(delay_vertex, 0, 0, 3))
    # one_to_one_connector_1 = OneToOneConnector(None)
    # direct_synapse_information_1 = SynapseInformation(
    #     one_to_one_connector_1, pre_app_population, post_app_population,
    #     False, False, None, SynapseDynamicsStatic(), 0, True, 1.5, 1.0)
    # one_to_one_connector_1.set_projection_information(
    #     direct_synapse_information_1)
    # one_to_one_connector_2 = OneToOneConnector(None)
    # direct_synapse_information_2 = SynapseInformation(
    #     one_to_one_connector_2, pre_app_population, post_app_population,
    #     False, False, None, SynapseDynamicsStatic(), 1, True, 2.5, 2.0)
    # one_to_one_connector_2.set_projection_information(
    #     direct_synapse_information_2)
    # all_to_all_connector = AllToAllConnector(False)
    # all_to_all_synapse_information = SynapseInformation(
    #     all_to_all_connector, pre_app_population, post_app_population,
    #     False, False, None, SynapseDynamicsStatic(), 0, True, 4.5, 4.0)
    # all_to_all_connector.set_projection_information(
    #     all_to_all_synapse_information)
    from_list_list = [(i, i, i, (i * 5) + 1) for i in range(10)]
    proj_from_list = p.Projection(
        pre_pop, post_pop, p.FromListConnector(from_list_list),
        p.StaticSynapse())

    app_graph = globals_variables.get_simulator().original_application_graph
    context = {
        "ApplicationGraph": app_graph
    }
    with (injection_context(context)):
        delay_adder = DelaySupportAdder()
        delay_adder.__call__(app_graph)
        partitioner = SpynnakerSplitterPartitioner()
        machine_graph, _ = partitioner.__call__(app_graph, machine, 100)
        allocator = ZonedRoutingInfoAllocator()
        n_keys_mapper = EdgeToNKeysMapper()
        n_keys_map = n_keys_mapper.__call__(machine_graph)
        routing_info = allocator.__call__(
            machine_graph, n_keys_map, flexible=False)

    post_vertex = next(iter(post_pop._vertex.machine_vertices))
    post_vertex_slice = post_vertex.vertex_slice
    post_vertex_placement = Placement(post_vertex, 0, 0, 3)

    temp_spec = tempfile.mktemp()
    spec = DataSpecificationGenerator(io.FileIO(temp_spec, "wb"), None)

    synaptic_matrices = SynapticMatrices(
        post_vertex_slice, n_synapse_types=2, all_single_syn_sz=10000,
        synaptic_matrix_region=1, direct_matrix_region=2, poptable_region=3,
        connection_builder_region=4)
    synaptic_matrices.write_synaptic_data(
        spec, post_pop._vertex.incoming_projections, all_syn_block_sz=10000,
        weight_scales=[32, 32], routing_info=routing_info)
    spec.end_specification()

    with io.FileIO(temp_spec, "rb") as spec_reader:
        executor = DataSpecificationExecutor(spec_reader, 20000)
        executor.execute()

    all_data = bytearray()
    all_data.extend(bytearray(executor.get_header()))
    all_data.extend(bytearray(executor.get_pointer_table(0)))
    for r in range(MAX_MEM_REGIONS):
        region = executor.get_region(r)
        if region is not None:
            all_data.extend(region.region_data)
    transceiver = MockTransceiverRawData(all_data)
    report_folder = mkdtemp()
    try:
        connections_1 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_one_to_one_1._projection_edge,
                proj_one_to_one_1._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_1) == post_vertex_slice.n_atoms
        assert all([conn["weight"] == 1.5 for conn in connections_1])
        assert all([conn["delay"] == 1.0 for conn in connections_1])

        connections_2 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_one_to_one_2._projection_edge,
                proj_one_to_one_2._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_2) == post_vertex_slice.n_atoms
        assert all([conn["weight"] == 2.5 for conn in connections_2])
        assert all([conn["delay"] == 2.0 for conn in connections_2])

        connections_3 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_all_to_all._projection_edge,
                proj_all_to_all._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_3) == 100
        assert all([conn["weight"] == 4.5 for conn in connections_3])
        assert all([conn["delay"] == 4.0 for conn in connections_3])

        connections_4 = numpy.concatenate(
            synaptic_matrices.get_connections_from_machine(
                transceiver, post_vertex_placement,
                proj_from_list._projection_edge,
                proj_from_list._synapse_information))

        # Check that all the connections have the right weight and delay
        assert len(connections_4) == len(from_list_list)
        list_weights = [values[2] for values in from_list_list]
        list_delays = [values[3] for values in from_list_list]
        assert all(list_weights == connections_4["weight"])
        assert all(list_delays == connections_4["delay"])
    finally:
        shutil.rmtree(report_folder, ignore_errors=True)
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 = 6
    weight_to_spike = 3.0
    delay = 2
    runtime = 200

    # Network population
    pop_1 = p.Population(n, p.IF_curr_exp(**cell_params_lif), label='pop_1')
    pop_2 = p.Population(n/2, p.IF_curr_exp(**cell_params_lif), label='pop_2')

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

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

    # Index-based connectors
    index_based_exc = "(i+j)/"+str(n*(n-n/2.0))
    index_based_exc2 = "2.0*(i+j)/"+str(n*(n-n/2.0))
    index_based_inh = "(i+j)/"+str(n*(n+n/2.0))
    print('index_based_exc: ', index_based_exc)
    print('index_based_exc2: ', index_based_exc2)

    exc_connector = p.IndexBasedProbabilityConnector(
        index_based_exc, allow_self_connections=True)
    inh_connector = p.IndexBasedProbabilityConnector(
        index_based_inh, allow_self_connections=False)
    exc_connector2 = p.IndexBasedProbabilityConnector(
        index_based_exc2, allow_self_connections=True)

    # Projections within populations
    p.Projection(pop_1, pop_1, exc_connector,
                 p.StaticSynapse(weight=2.0, delay=5))
    p.Projection(pop_1, pop_1, inh_connector,
                 p.StaticSynapse(weight=1.5, delay=5))

    p.Projection(pop_1, pop_2, exc_connector2,
                 p.StaticSynapse(weight=1.5, delay=2))

    pop_1.record(['v', 'spikes'])
    pop_2.record(['v', 'spikes'])

    p.run(runtime)

    v = pop_1.get_data('v')
    spikes = pop_1.get_data('spikes')
    v2 = pop_2.get_data('v')
    spikes2 = pop_2.get_data('spikes')

    if plot:
        Figure(
            # raster plot of the presynaptic neurons' spike times
            Panel(spikes.segments[0].spiketrains,
                  yticks=True, markersize=2.0, xlim=(0, runtime), xticks=True),
            # membrane potential of the postsynaptic neurons
            Panel(v.segments[0].filter(name='v')[0],
                  ylabel="Membrane potential pop 1 (mV)",
                  data_labels=[pop_1.label], yticks=True,
                  xlim=(0, runtime), xticks=True),
            # raster plot of the presynaptic neurons' spike times
            Panel(spikes2.segments[0].spiketrains,
                  yticks=True, markersize=2.0, xlim=(0, runtime), xticks=True),
            # membrane potential of the postsynaptic neurons
            Panel(v2.segments[0].filter(name='v')[0],
                  ylabel="Membrane potential pop 2 (mV)",
                  data_labels=[pop_2.label], yticks=True,
                  xlim=(0, runtime), xticks=True),
            title="Simple index-based probability connector",
            annotations="Simulated with {}".format(p.name())
        )
        plt.show()

    p.end()

    return v, spikes, v2, spikes2
示例#15
0
    for j in range(len(spikes0)):
        newEntry.append(spikes0[j] + i * 40.0 / 100.0)
    arrayEntries.append(newEntry)
spikeArray = {'spike_times': arrayEntries}

teachlist = list()
for i in range(nSourceNeurons):
    teachlist.append(teachingSpikes)
teachingSpikeArray = {'spike_times': teachlist}
populations.append(
    p.Population(nSourceNeurons,
                 p.SpikeSourceArray(**spikeArray),
                 label='excit_pop_ss_array'))  # 0
populations.append(
    p.Population(nInhibNeurons,
                 p.IF_curr_exp(**cell_params_lif),
                 label='inhib_pop'))  # 1
populations.append(
    p.Population(nExcitNeurons,
                 p.IF_curr_exp(**cell_params_lif),
                 label='excit_pop'))  # 2
populations.append(
    p.Population(nTeachNeurons,
                 p.SpikeSourceArray(**teachingSpikeArray),
                 label='teaching_ss_array'))  # 3

stdp_model = p.STDPMechanism(
    timing_dependence=p.extra_models.RecurrentRule(accumulator_depression=-6,
                                                   accumulator_potentiation=3,
                                                   mean_pre_window=10.0,
                                                   mean_post_window=10.0,
示例#16
0
def test_pop_based_master_pop_table_standard(undelayed_indices_connected,
                                             delayed_indices_connected,
                                             n_pre_neurons, neurons_per_core,
                                             expect_app_keys, max_delay):
    unittest_setup()
    machine = virtual_machine(12, 12)

    # Build a from list connector with the delays we want
    connections = []
    connections.extend([(i * neurons_per_core + j, j, 0, 10)
                        for i in undelayed_indices_connected
                        for j in range(100)])
    connections.extend([(i * neurons_per_core + j, j, 0, max_delay)
                        for i in delayed_indices_connected
                        for j in range(100)])

    # Make simple source and target, where the source has 1000 atoms
    # split into 10 vertices (100 each) and the target has 100 atoms in
    # a single vertex
    p.setup(1.0)
    post_pop = p.Population(100,
                            p.IF_curr_exp(),
                            label="Post",
                            additional_parameters={
                                "splitter":
                                SplitterAbstractPopulationVertexSlice()
                            })
    p.IF_curr_exp.set_model_max_atoms_per_core(neurons_per_core)
    pre_pop = p.Population(n_pre_neurons,
                           p.IF_curr_exp(),
                           label="Pre",
                           additional_parameters={
                               "splitter":
                               SplitterAbstractPopulationVertexSlice()
                           })
    p.Projection(pre_pop, post_pop, p.FromListConnector(connections),
                 p.StaticSynapse())

    app_graph = globals_variables.get_simulator().original_application_graph
    context = {"ApplicationGraph": app_graph}
    with (injection_context(context)):
        delay_support_adder(app_graph)
        machine_graph, _ = spynnaker_splitter_partitioner(
            app_graph, machine, 100)
        allocator = ZonedRoutingInfoAllocator()
        n_keys_map = edge_to_n_keys_mapper(machine_graph)
        routing_info = allocator.__call__(machine_graph,
                                          n_keys_map,
                                          flexible=False)

    post_mac_vertex = next(iter(post_pop._vertex.machine_vertices))
    post_vertex_slice = post_mac_vertex.vertex_slice

    # Generate the data
    temp_spec = tempfile.mktemp()
    spec = DataSpecificationGenerator(io.FileIO(temp_spec, "wb"), None)

    synaptic_matrices = SynapticMatrices(post_vertex_slice,
                                         n_synapse_types=2,
                                         all_single_syn_sz=10000,
                                         synaptic_matrix_region=1,
                                         direct_matrix_region=2,
                                         poptable_region=3,
                                         connection_builder_region=4)
    synaptic_matrices.write_synaptic_data(
        spec,
        post_pop._vertex.incoming_projections,
        all_syn_block_sz=1000000,
        weight_scales=[32, 32],
        routing_info=routing_info)

    with io.FileIO(temp_spec, "rb") as spec_reader:
        executor = DataSpecificationExecutor(spec_reader,
                                             SDRAM.max_sdram_found)
        executor.execute()

    # Read the population table and check entries
    region = executor.get_region(3)
    mpop_data = numpy.frombuffer(region.region_data,
                                 dtype="uint8").view("uint32")
    n_entries = mpop_data[0]
    n_addresses = mpop_data[1]

    # Compute how many entries and addresses there should be
    expected_n_entries = 0
    expected_n_addresses = 0
    if expect_app_keys:
        # Always one for undelayed, maybe one for delayed if present
        n_app_entries = 1 + int(bool(delayed_indices_connected))
        expected_n_entries += n_app_entries
        # 2 address list entries for each entry, as there is also extra_info
        expected_n_addresses += 2 * n_app_entries

    # If both delayed and undelayed, there is an entry for each incoming
    # machine edge
    elif delayed_indices_connected and undelayed_indices_connected:
        all_connected = set(undelayed_indices_connected)
        all_connected.update(delayed_indices_connected)
        expected_n_entries += len(all_connected)
        expected_n_addresses += len(all_connected)

    # If there are only undelayed indices, there is an entry for each
    elif undelayed_indices_connected:
        expected_n_entries += len(undelayed_indices_connected)
        expected_n_addresses += len(undelayed_indices_connected)

    # If there are only delayed indices, there are two entries for each because
    # the undelayed ones are still connected
    else:
        expected_n_entries += 2 * len(delayed_indices_connected)
        expected_n_addresses += 2 * len(delayed_indices_connected)

    assert (n_entries == expected_n_entries)
    assert (n_addresses == expected_n_addresses)
示例#17
0
def run_script(simtime,
               n_neurons,
               run_split=1,
               record_spikes=False,
               spike_rate=None,
               spike_rec_indexes=None,
               spike_get_indexes=None,
               record_v=False,
               v_rate=None,
               v_rec_indexes=None,
               v_get_indexes=None,
               record_exc=False,
               exc_rate=None,
               exc_rec_indexes=None,
               exc_get_indexes=None,
               record_inh=False,
               inh_rate=None,
               inh_rec_indexes=None,
               inh_get_indexes=None,
               file_prefix=""):

    sim.setup(timestep=1)

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

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

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

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

    sim.end()

    return spikes, v, exc, inh
def do_run(plot):
    p.setup(timestep=1.0)

    # n_pop = 2  # 60
    nNeurons = 10  # 100

    rng = p.NumpyRNG(seed=28374)
    # rng1 = p.NumpyRNG(seed=12345)

    # delay_distr = p.RandomDistribution('uniform', [5, 10], rng)
    # weight_distr = p.RandomDistribution('uniform', [0, 2], rng1)

    v_distr = p.RandomDistribution('uniform', [-55, -95], rng)

    v_inits = []
    for i in range(nNeurons):
        v_inits.append(v_distr.next())

    cell_params_lif_in = {
        'tau_m': 32,
        'v_init': -80,
        'v_rest': -75,
        'v_reset': -95,
        'v_thresh': -55,
        'tau_syn_E': 5,
        'tau_syn_I': 10,
        'tau_refrac': 20,
        'i_offset': 1
    }

    cell_params_lif = {
        'tau_m': 32,
        'v_init': -80,
        'v_rest': -75,
        'v_reset': -95,
        'v_thresh': -55,
        'tau_syn_E': 5,
        'tau_syn_I': 10,
        'tau_refrac': 5,
        'i_offset': 0
    }

    cell_params_ext_dev = {'port': 34567}

    populations = list()
    projections = list()

    weight_to_spike = 20

    populations.append(
        p.Population(nNeurons,
                     p.IF_curr_exp(**cell_params_lif_in),
                     label='pop_%d' % 0))
    populations[0].initialize(v=v_distr)

    p.external_devices.activate_live_output_for(populations[0])

    pop_external = p.Population(
        nNeurons,
        p.external_devices.SpikeInjector(**cell_params_ext_dev),
        label='Babel_Dummy')

    populations.append(
        p.Population(nNeurons,
                     p.IF_curr_exp(**cell_params_lif),
                     label='pop_%d' % 1))

    projections.append(
        p.Projection(pop_external, populations[1], p.OneToOneConnector(),
                     p.StaticSynapse(weight=weight_to_spike, delay=10)))

    # populations[0].record_v()
    #  at the moment is only possible to observe one population per core
    populations[1].record(['v'])

    for pop in populations:
        pop.record(['spikes'], to_file=False)
        # sends spike to the Monitoring application

    #    populations[i].record_variable('rate', save_to='eth')
    #  sends spike to the Monitoring application

    p.run(10000)

    # retrieving spike results and plotting...

    id_accumulator = 0

    shapes = []

    if plot:
        import matplotlib.pyplot as p_plot
    for pop_o in populations:
        data = numpy.asarray(
            neo_convertor.convert_spikes(pop_o.get_data('spikes')))
        print(data.shape)
        shapes.append(data.shape)
        if plot:
            p_plot.scatter(data[:, 0],
                           data[:, 1] + id_accumulator,
                           color='green',
                           s=1)
        id_accumulator = id_accumulator + pop_o.size

    if plot:
        p_plot.show()

    return shapes
示例#19
0
import spynnaker8 as sim
import pyNN.utility.plotting as plot
import matplotlib.pyplot as plt

sim.setup(timestep=1.0)
sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100)

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

neo = pop_1.get_data(variables=["spikes", "v"])
spikes = neo.segments[0].spiketrains
print spikes
v = neo.segments[0].filter(name='v')[0]
print v
sim.end()

plot.Figure(
    # plot voltage for first ([0]) neuron
    plot.Panel(v,
               ylabel="Membrane potential (mV)",
               data_labels=[pop_1.label],
               yticks=True,
               xlim=(0, simtime)),
def do_run():
    # boolean allowing users to use python or c vis
    using_c_vis = False

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    live_spikes_connection_receive = None
    if not using_c_vis:

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

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

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

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

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

    return (spikes_forward, spikes_backward)
示例#21
0
import spynnaker8 as sim
from pyNN.utility.plotting import Figure, Panel
import matplotlib.pyplot as plt

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

delta_cell = sim.Population(1, sim.extra_models.IFCurDelta(**{
    'i_offset': 0.1,
    'tau_refrac': 3.0,
    'v_thresh': -51.0,
    'v_reset': -70.0}))

exp_cell = sim.Population(1, sim.IF_curr_exp(**{
    'i_offset': 0.1,
    'tau_refrac': 3.0,
    'v_thresh': -51.0,
    'v_reset': -70.0,
    'tau_syn_E': 5.0,
    'tau_syn_I': 5.0}))


spike_sourceE = sim.Population(1, sim.SpikeSourceArray(**{
    'spike_times': [float(i) for i in range(5, 105, 10)]}))
spike_sourceI = sim.Population(1, sim.SpikeSourceArray(**{
    'spike_times': [float(i) for i in range(155, 255, 10)]}))

sim.Projection(spike_sourceE, exp_cell,
               sim.OneToOneConnector(),
               synapse_type=sim.StaticSynapse(weight=1.5, delay=2.0),
               receptor_type='excitatory')
sim.Projection(spike_sourceI, exp_cell,
    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()
def do_run(Neurons, sim_time, record, seed=None):
    """

    :param Neurons: Number of Neurons
    :type Neurons: int
    :param sim_time: times for run
    :type sim_time: int
    :param record: If True will aks for spikes to be recorded
    :type record: bool
    """
    g = 5.0
    eta = 2.0
    delay = 2.0
    epsilon = 0.1

    tau_m = 20.0  # ms (20ms will give a FR of 20hz)
    tau_ref = 2.0
    v_reset = 10.0
    v_th = 20.0
    v_rest = 0.0
    tau_syn = 1.0

    n_e = int(round(Neurons * 0.8))
    n_i = int(round(Neurons * 0.2))

    c_e = n_e * 0.1

    # Excitatory and inhibitory weights
    j_e = 0.1
    j_i = -g * j_e

    # The firing rate of a neuron in the external pop
    # is the product of eta time the threshold rate
    # the steady state firing rate which is
    # needed to bring a neuron to threshold.
    nu_ex = eta * v_th / (j_e * c_e * tau_m)

    # population rate of the whole external population.
    # With CE neurons the pop rate is simply the product
    # nu_ex*c_e  the factor 1000.0 changes the units from
    # spikes per ms to spikes per second.
    p_rate = 1000.0 * nu_ex * c_e
    print("Rate is: %f HZ" % (p_rate / 1000))

    # Neural Parameters
    pynn.setup(timestep=1.0, min_delay=1.0, max_delay=16.0)

    # Makes it easy to scale up the number of cores
    pynn.set_number_of_neurons_per_core(pynn.IF_curr_exp, 100)
    pynn.set_number_of_neurons_per_core(pynn.SpikeSourcePoisson, 100)

    exc_cell_params = {
        'cm': 1.0,  # pf
        'tau_m': tau_m,
        'tau_refrac': tau_ref,
        'v_rest': v_rest,
        'v_reset': v_reset,
        'v_thresh': v_th,
        'tau_syn_E': tau_syn,
        'tau_syn_I': tau_syn,
        'i_offset': 0.9
    }

    inh_cell_params = {
        'cm': 1.0,  # pf
        'tau_m': tau_m,
        'tau_refrac': tau_ref,
        'v_rest': v_rest,
        'v_reset': v_reset,
        'v_thresh': v_th,
        'tau_syn_E': tau_syn,
        'tau_syn_I': tau_syn,
        'i_offset': 0.9
    }

    # Set-up pynn Populations
    e_pop = pynn.Population(n_e,
                            pynn.IF_curr_exp(**exc_cell_params),
                            label="e_pop")

    i_pop = pynn.Population(n_i,
                            pynn.IF_curr_exp,
                            inh_cell_params,
                            label="i_pop")

    if seed is None:
        poisson_ext_e = pynn.Population(n_e,
                                        pynn.SpikeSourcePoisson(rate=10.0),
                                        label="Poisson_pop_E")
        poisson_ext_i = pynn.Population(n_i,
                                        pynn.SpikeSourcePoisson(rate=10.0),
                                        label="Poisson_pop_I")
    else:
        poisson_ext_e = pynn.Population(n_e,
                                        pynn.SpikeSourcePoisson(rate=10.0,
                                                                seed=seed),
                                        label="Poisson_pop_E")
        poisson_ext_i = pynn.Population(n_i,
                                        pynn.SpikeSourcePoisson(rate=10.0,
                                                                seed=seed + 1),
                                        label="Poisson_pop_I")

    # Connectors
    e_conn = pynn.FixedProbabilityConnector(epsilon)
    i_conn = pynn.FixedProbabilityConnector(epsilon)

    # Use random delays for the external noise and
    # set the initial membrane voltage below the resting potential
    # to avoid the overshoot of activity in the beginning of the simulation
    rng = NumpyRNG(seed=seed)
    delay_distr = RandomDistribution('uniform', [1.0, 16.0], rng=rng)
    ext_conn = pynn.OneToOneConnector()

    uniform_distr = RandomDistribution('uniform', [-10, 0], rng=rng)
    e_pop.initialize(v=uniform_distr)
    i_pop.initialize(v=uniform_distr)

    # Projections
    pynn.Projection(presynaptic_population=e_pop,
                    postsynaptic_population=e_pop,
                    connector=e_conn,
                    receptor_type="excitatory",
                    synapse_type=pynn.StaticSynapse(weight=j_e,
                                                    delay=delay_distr))
    pynn.Projection(presynaptic_population=i_pop,
                    postsynaptic_population=e_pop,
                    connector=i_conn,
                    receptor_type="inhibitory",
                    synapse_type=pynn.StaticSynapse(weight=j_i, delay=delay))
    pynn.Projection(presynaptic_population=e_pop,
                    postsynaptic_population=i_pop,
                    connector=e_conn,
                    receptor_type="excitatory",
                    synapse_type=pynn.StaticSynapse(weight=j_e,
                                                    delay=delay_distr))
    pynn.Projection(presynaptic_population=i_pop,
                    postsynaptic_population=i_pop,
                    connector=i_conn,
                    receptor_type="inhibitory",
                    synapse_type=pynn.StaticSynapse(weight=j_i, delay=delay))

    pynn.Projection(presynaptic_population=poisson_ext_e,
                    postsynaptic_population=e_pop,
                    connector=ext_conn,
                    receptor_type="excitatory",
                    synapse_type=pynn.StaticSynapse(weight=j_e * 10,
                                                    delay=delay_distr))
    pynn.Projection(presynaptic_population=poisson_ext_i,
                    postsynaptic_population=i_pop,
                    connector=ext_conn,
                    receptor_type="excitatory",
                    synapse_type=pynn.StaticSynapse(weight=j_e * 10,
                                                    delay=delay_distr))

    # Record stuff
    if record:
        e_pop.record('spikes')
        poisson_ext_e.record('spikes')

    pynn.run(sim_time)

    esp = None
    s = None

    if record:
        esp = e_pop.get_data('spikes')
        s = poisson_ext_e.get_data('spikes')

    pynn.end()

    return esp, s, n_e
    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.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(
            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)
        last_pre_spike = pre_spikes[-1]
        considered_post_spikes = post_spikes[post_spikes < last_pre_spike]
        potentiation_time_diff = numpy.ravel(
            numpy.subtract.outer(considered_post_spikes + plastic_delay,
                                 pre_spikes[:-1]))
        potentiation_times = (
            potentiation_time_diff[potentiation_time_diff > 0] * -1)
        depression_time_diff = numpy.ravel(
            numpy.subtract.outer(considered_post_spikes + plastic_delay,
                                 pre_spikes))
        depression_times = depression_time_diff[depression_time_diff < 0]

        # 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, new_weight_exact, rtol=0.001))
示例#25
0
def run_script():
    p.setup(1.0)
    p.set_number_of_neurons_per_core(p.IF_curr_exp, 3)

    inp = p.Population(10,
                       p.SpikeSourceArray(spike_times=[1.0]),
                       label="SpikeSourceArray")
    out = p.Population(10, p.IF_curr_exp(), label="IF_curr_exp")
    out.record("spikes")

    param_projections = [
        (1.0, 1.0),
        (RandomDistribution("uniform", low=1.0, high=10.0), 2.0),
        (3.0, 17.0),
        (4.0, RandomDistribution("normal", mu=22.0, sigma=10.0)),
        (5.0,
         RandomDistribution("normal_clipped",
                            mu=22.0,
                            sigma=10.0,
                            low=5.0,
                            high=32.0)),
        (6.0,
         RandomDistribution("normal_clipped_to_boundary",
                            mu=14.0,
                            sigma=5.0,
                            low=6.0,
                            high=16.0)),
        (7.0, RandomDistribution("exponential", beta=2.0)),
    ]
    connectors = [
        p.OneToOneConnector, p.AllToAllConnector,
        functools.partial(p.AllToAllConnector, allow_self_connections=False),
        functools.partial(p.FixedProbabilityConnector, 0.5),
        functools.partial(p.FixedTotalNumberConnector,
                          50,
                          with_replacement=True),
        functools.partial(p.FixedTotalNumberConnector,
                          20,
                          with_replacement=False)
    ]

    projs = list()
    for weight, delay in param_projections:
        for connector in connectors:
            conn = connector()
            projs.append(
                (weight, delay, conn, False,
                 p.Projection(inp, out, conn,
                              p.StaticSynapse(weight=weight, delay=delay))))
            projs.append((weight, delay, conn, True,
                          p.Projection(
                              inp, out, conn,
                              p.STDPMechanism(p.SpikePairRule(),
                                              p.AdditiveWeightDependence(),
                                              weight=weight,
                                              delay=delay))))

    p.run(10)

    for weight, delay, connector, is_stdp, proj in projs:
        weights = proj.get("weight", "list", with_address=False)
        delays = proj.get("delay", "list", with_address=False)
        if not is_stdp:
            check_params(weight, weights)
        check_params(delay, delays)

    p.end()
示例#26
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 test_receiver():
    # Set up the live connection for sending spikes
    live_spikes_connection_send = \
        Frontend.external_devices.SpynnakerLiveSpikesConnection(
            receive_labels=None, local_port=None,
            send_labels=["spike_injector_forward", "spike_injector_backward"])

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    last_line = str(receiver.stderr.readline(), "UTF-8")
    print(last_line)
    print("Waiting for receiver to stop...")
    receiver.wait()
    print("Done")

    n_spikes = sum(len(s) for s in spikes_forward)
    n_spikes += sum(len(s) for s in spikes_backward)

    # Check spike count, assuming some might get lost
    match = re.match("^Received (.*) spikes$", last_line)
    assert (match)
    assert (n_spikes // 2 <= int(match.group(1)) <= n_spikes)
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.array([
        numpy.linspace(0, nNeurons - 1, nNeurons),
        numpy.linspace(1, nNeurons, nNeurons)
    ], numpy.uint32)
    # connect the final neuron to the first neuron
    loopConnections[1, nNeurons - 1] = 0

    # do the same for the second population, but just for even numbered neurons
    loopConnections2 = numpy.array([
        numpy.linspace(0, nNeurons - 2, nNeurons // 2),
        numpy.linspace(2, nNeurons + 1, nNeurons // 2)
    ], numpy.uint32)
    # connect the final neuron to the first neuron
    loopConnections2[1, (nNeurons // 2) - 1] = 0

    # SpikeInjector
    injectionConnection = numpy.array([[0], [0]], numpy.uint32)
    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
示例#29
0
def split_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",
                       additional_parameters={
                           "splitter":
                           SplitterAbstractPopulationVertexNeuronsSynapses(1)
                       })
    pop_2 = p.Population(1,
                         p.IF_curr_exp(),
                         label="pop_2",
                         additional_parameters={
                             "splitter":
                             SplitterAbstractPopulationVertexNeuronsSynapses(1)
                         })
    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)
                         })
    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)