Esempio n. 1
0
    def do_run(self):
        sim.setup(timestep=1.0)
        sim.set_number_of_neurons_per_core(sim.IF_curr_exp, neurons_per_core)

        input_spikes = list(range(0, simtime - 50, 10))
        input = sim.Population(1,
                               sim.SpikeSourceArray(spike_times=input_spikes),
                               label="input")
        pop_1 = sim.Population(n_neurons, sim.IF_curr_exp(), label="pop_1")
        sim.Projection(input,
                       pop_1,
                       sim.AllToAllConnector(),
                       synapse_type=sim.StaticSynapse(weight=5, delay=1))
        pop_1.record(["spikes", "v", "gsyn_exc"])
        sim.run(simtime)
        sim.reset()
        pop_2 = sim.Population(n_neurons, sim.IF_curr_exp(), label="pop_2")
        pop_2.record(["spikes", "v", "gsyn_exc"])
        sim.Projection(input,
                       pop_2,
                       sim.AllToAllConnector(),
                       synapse_type=sim.StaticSynapse(weight=5, delay=1))
        sim.run(simtime)
        self.check_data(pop_1, len(input_spikes), simtime, [0, 1])
        self.check_data(pop_2, len(input_spikes), simtime, [1])
        sim.end()
def do_run():
    sim.setup(timestep=1)
    pop_1 = sim.Population(1, sim.IF_curr_exp, {}, label="pop_1")
    inp = sim.Population(
        1, sim.SpikeSourceArray, {'spike_times': [[0]]}, label="input")
    sim.Projection(
        pop_1, pop_1, sim.OneToOneConnector(),
        synapse_type=sim.StaticSynapse(weight=5.0, delay=1),
        receptor_type="excitatory", source=None, space=None)

    pop_1.record("spikes")
    sim.run(20)
    first_spikes = pop_1.spinnaker_get_data("spikes")

    sim.Projection(
        inp, pop_1, sim.FromListConnector([[0, 0, 5, 5]]),
        synapse_type=sim.StaticSynapse(weight=5.0, delay=1),
        receptor_type="excitatory", source=None,
        space=None)

    sim.reset()
    sim.run(20)
    second_spikes = pop_1.spinnaker_get_data("spikes")

    return first_spikes, second_spikes
Esempio n. 3
0
def do_run():
    p.setup(timestep=1, min_delay=1, max_delay=15)

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

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

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

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

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

    p.end()

    return (all1, all2)
Esempio n. 4
0
 def reset_set_with_v_set(self):
     sim.setup(1.0)
     pop = sim.Population(1, sim.IF_curr_exp, {}, label="pop")
     inp = sim.Population(1,
                          sim.SpikeSourceArray(spike_times=[0]),
                          label="input")
     sim.Projection(inp,
                    pop,
                    sim.OneToOneConnector(),
                    synapse_type=sim.StaticSynapse(weight=5))
     pop.set(i_offset=1.0)
     pop.set(tau_syn_E=1)
     pop.initialize(v=-60)
     pop.record(["v"])
     sim.run(5)
     v1 = pop.spinnaker_get_data('v')
     try:
         self.check_from_60(v1)
         raise AssertionError("Unexpected after 60 voltage")
     except AssertionError:
         pass  # That should have failed
     pop.set(tau_syn_E=1)
     sim.reset()
     inp.set(spike_times=[100])
     sim.run(5)
     v2 = pop.spinnaker_get_data('v')
     try:
         self.check_from_65(v2)
     except AssertionError:
         self.known_issue(
             "https://github.com/SpiNNakerManchester/sPyNNaker/issues/599")
     sim.end()
    def do_run(self):
        sim.setup(1.0)
        pop = sim.Population(1, sim.IF_curr_exp(i_offset=5.0), label="pop")
        pop.record("spikes")
        pop_2 = sim.Population(1, sim.IF_curr_exp(), label="pop_2")
        proj = sim.Projection(
            pop, pop_2, sim.AllToAllConnector(),
            sim.STDPMechanism(
                timing_dependence=sim.SpikePairRule(),
                weight_dependence=sim.AdditiveWeightDependence(),
                weight=sim.RandomDistribution("uniform", low=0.3, high=0.7)))
        proj_2 = sim.Projection(
            pop, pop_2, sim.OneToOneConnector(),
            sim.STDPMechanism(
                timing_dependence=sim.SpikePairRule(),
                weight_dependence=sim.AdditiveWeightDependence(),
                weight=sim.RandomDistribution("uniform", low=0.3, high=0.7)))
        sim.run(100)
        weights_1_1 = proj.get("weight", "list")
        weights_1_2 = proj_2.get("weight", "list")
        spikes_1 = pop.get_data("spikes").segments[0].spiketrains

        sim.reset()
        sim.run(100)
        weights_2_1 = proj.get("weight", "list")
        weights_2_2 = proj_2.get("weight", "list")
        spikes_2 = pop.get_data("spikes").segments[1].spiketrains
        sim.end()

        assert(numpy.array_equal(weights_1_1, weights_2_1))
        assert(numpy.array_equal(weights_1_2, weights_2_2))
        assert(numpy.array_equal(spikes_1, spikes_2))
    def forward(self, input, timesteps=None):
        # if timesteps not specified, set to default simulation time
        if timesteps is None:
            timesteps = self.simulation_time

        # first reset the network
        if self.backend == 'nest' or self.backend == 'pynn':
            nest_sim.reset()
        elif self.backend == 'spinnaker':
            spin_sim.reset()

        # set input generators to correct current
        if self.add_bias_as_observation:
            bias = torch.ones(1, dtype=torch.float)
            input = torch.cat((input, bias), dim=0)

        # set offsets to correct current
        # save the original offsets/biases
        bias = []
        for i in range(0, len(self.layers[0])):
            if self.backend == 'pynn' or self.backend == 'spinnaker':
                offset = self.layers[0][i:i+1].get('i_offset')[0]
                bias.append(offset)
                # add the inputs multiplied by their respective weights to the constant input of the
                # first hidden layer
                for j in range(0, len(input)):
                    offset += input[j].detach().item()*self.weights[0][j][i].detach().item()
                self.layers[0][i:i+1].set(i_offset=offset)
            elif self.backend == 'nest':
                offset = self.layers[0][i:i+1].get('I_e')
                bias.append(offset)
                # add the inputs multiplied by their respective weights to the constant input of the
                # first hidden layer
                for j in range(0, len(input)):
                    offset += input[j].detach().item()*self.weights[0][j][i].detach().item()
                self.layers[0][i:i + 1].set(I_e=offset)

        # simulate
        if self.backend == 'nest' or self.backend == 'pynn':
            nest_sim.run(timesteps)
        elif self.backend == 'spinnaker':
            spin_sim.run(timesteps)

        potentials = self.layers[-1].get_data().segments[-1].analogsignals[0][-1]
        # restore original bias in the offset
        for i in range(0, len(self.layers[0])):
            if self.backend == 'pynn' or self.backend == 'spinnaker':
                self.layers[0][i:i + 1].set(i_offset=bias[i])
            elif self.backend == 'nest':
                self.layers[0][i:i + 1].set(I_e=bias[i])
        #  return torch tensor to be compatible with other agents
        return torch.tensor(potentials,dtype=torch.float)
    def with_reset(self):
        p.setup(1.0)

        inp = p.Population(100, p.SpikeSourcePoisson(rate=100), label="input")
        inp.record("spikes")
        p.run(100)
        spikes1 = inp.spinnaker_get_data('spikes')
        p.reset()
        inp.set(rate=10)
        p.run(100)
        spikes2 = inp.spinnaker_get_data('spikes')
        p.end()
        assert len(spikes1) > len(spikes2) * 5
Esempio n. 8
0
    def __run_sim(self, run_times, populations, projections, run_count,
                  spike_times_list, extract_between_runs, get_spikes, record_7,
                  get_v, record_v_7, get_gsyn_exc, record_gsyn_exc_7,
                  get_gsyn_inh, record_gsyn_inh_7, record_input_spikes,
                  record_input_spikes_7, get_all, get_weights, get_delays,
                  new_pop, n_neurons, cell_class, cell_params, weight_to_spike,
                  set_between_runs, reset):
        results = ()

        for runtime in run_times[:-1]:
            # This looks strange but is to allow getting data before run
            if runtime > 0:
                p.run(runtime)
            run_count += 1

            if extract_between_runs:
                self._get_data(populations[0], populations[1], get_spikes,
                               record_7, get_v, record_v_7, get_gsyn_exc,
                               record_gsyn_exc_7, get_gsyn_inh,
                               record_gsyn_inh_7, record_input_spikes,
                               record_input_spikes_7, get_all)
                self._get_weight_delay(projections[0], get_weights, get_delays)

            if new_pop:
                populations.append(
                    p.Population(n_neurons,
                                 cell_class(**cell_params),
                                 label='pop_2'))
                injection_connection = [(n_neurons - 1, 0, weight_to_spike, 1)]
                new_projection = p.Projection(
                    populations[0], populations[2],
                    p.FromListConnector(injection_connection),
                    p.StaticSynapse(weight=weight_to_spike, delay=1))
                projections.append(new_projection)

            if spike_times_list is not None:
                populations[1].set(spike_times=spike_times_list[run_count])

            for (pop, name, value) in set_between_runs:
                new_values = {name: value}
                populations[pop].set(**new_values)

            if reset:
                p.reset()

        p.run(run_times[-1])

        self._default_report_folder = \
            p.globals_variables.get_simulator()._report_default_directory

        return results
Esempio n. 9
0
 def change_nothing(self):
     sim.setup(1.0)
     pop = sim.Population(1, sim.IF_curr_exp, {}, label="pop")
     pop.set(i_offset=1.0)
     pop.set(tau_syn_E=1)
     pop.record(["v"])
     sim.run(5)
     v1 = pop.spinnaker_get_data('v')
     self.check_from_65(v1)
     sim.reset()
     sim.run(5)
     v2 = pop.spinnaker_get_data('v')
     self.check_from_65(v2)
     sim.end()
Esempio n. 10
0
def variable_rate_reset():
    """ Test the ways of changing rates and ensure that they don't change the\
        results
    """
    p.setup(1.0)
    pop = p.Population(100,
                       p.extra_models.SpikeSourcePoissonVariable(
                           rates=[1, 10, 100], starts=[0, 1000, 2000]),
                       additional_parameters={"seed": 0})
    pop_2 = p.Population(100,
                         p.SpikeSourcePoisson(rate=1),
                         additional_parameters={
                             "seed": 0,
                             "max_rate": 100
                         })
    pop.record("spikes")
    pop_2.record("spikes")

    p.run(1000)
    spikes_pop_2_1 = pop_2.get_data("spikes")
    nump = [s.magnitude for s in spikes_pop_2_1.segments[0].spiketrains]
    numpy.savetxt("spikesp2_1.txt", nump[0])
    pop_2.set(rate=10)
    p.run(1000)
    spikes_pop_2_2 = pop_2.get_data("spikes")
    nump = [s.magnitude for s in spikes_pop_2_2.segments[0].spiketrains]
    numpy.savetxt("spikesp2_2.txt", nump[0])
    pop_2.set(rate=100)
    p.run(1000)
    p.reset()
    p.run(3000)
    spikes_pop = pop.get_data("spikes")
    spikes_pop_2 = pop_2.get_data("spikes")
    p.end()

    spikes_1 = [s.magnitude for s in spikes_pop.segments[0].spiketrains]
    spikes_2 = [s.magnitude for s in spikes_pop.segments[1].spiketrains]
    spikes_p_2 = [s.magnitude for s in spikes_pop_2.segments[0].spiketrains]

    print(spikes_1)
    numpy.savetxt("spikes1.txt", spikes_1[0])
    print(spikes_2)
    numpy.savetxt("spikes2.txt", spikes_2[0])
    print(spikes_p_2)
    numpy.savetxt("spikesp2.txt", spikes_p_2[0])

    for s1, s2, s3 in zip(spikes_1, spikes_2, spikes_p_2):
        assert (numpy.array_equal(s1, s2))
        assert (numpy.array_equal(s2, s3))
def do_run(split, seed=None):
    p.setup(1.0)

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

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

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

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

    p.run(100)

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

    p.run(100)

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

    p.reset()

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

    p.run(100)

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

    p.end()

    return (pop_spikes1, inp_spikes1, pop_spikes2, inp_spikes2)
    def do_run(self):
        sim.setup(1.0)
        pop = sim.Population(1, sim.IF_curr_exp, {}, label="pop")
        pop.set(i_offset=1.0)
        pop.record(["v"])
        initial1 = -64.0
        initial2 = -62.0
        initial3 = -63.0
        initial4 = -61.0
        runtime = 10

        pop.initialize(v=initial1)
        sim.run(runtime)

        sim.reset()
        pop.initialize(v=initial2)
        sim.run(runtime)

        sim.reset()
        pop.initialize(v=initial3)
        pop.set(i_offset=2.0)
        sim.run(runtime)

        try:
            pop.initialize(v=initial4)  # this should throw an exception
        except Exception:
            pass

        pop.set(i_offset=2.5)
        sim.run(runtime)

        v = pop.get_data('v')

        sim.end()

        # test values at start of each run() call above
        self.assertEqual(v.segments[0].filter(name='v')[0][0], initial1)
        self.assertEqual(v.segments[1].filter(name='v')[0][0], initial2)
        self.assertEqual(v.segments[2].filter(name='v')[0][0], initial3)
        self.assertNotEqual(v.segments[2].filter(name='v')[0][runtime],
                            initial4)

        # test the lengths of each segment are correct
        self.assertEqual(len(v.segments[0].filter(name='v')[0]), runtime)
        self.assertEqual(len(v.segments[0].filter(name='v')[0]),
                         len(v.segments[1].filter(name='v')[0]))
        self.assertEqual(len(v.segments[2].filter(name='v')[0]), 2 * runtime)
    def do_run(self):
        p.setup(timestep=1.0, min_delay=1.0, max_delay=1.0)

        cell_params = {
            'i_offset': .1,
            'tau_refrac': 3.0,
            'v_rest': -65.0,
            'v_thresh': -51.0,
            'tau_syn_E': 2.0,
            'tau_syn_I': 5.0,
            'v_reset': -70.0,
            'e_rev_E': 0.,
            'e_rev_I': -80.
        }

        # setup test population
        if_pop = p.Population(1, p.IF_cond_exp, cell_params)
        # setup spike sources
        spike_times = [20., 40., 60.]
        exc_pop = p.Population(1, p.SpikeSourceArray,
                               {'spike_times': spike_times})
        inh_pop = p.Population(1, p.SpikeSourceArray,
                               {'spike_times': [120, 140, 160]})
        # setup excitatory and inhibitory connections
        listcon = p.FromListConnector([(0, 0, 0.05, 1.0)])
        p.Projection(exc_pop, if_pop, listcon, receptor_type='excitatory')
        p.Projection(inh_pop, if_pop, listcon, receptor_type='inhibitory')
        # setup recorder
        if_pop.record(["v"])
        p.run(100)
        p.reset()
        if_pop.initialize(v=-65)
        exc_pop.set(spike_times=[])
        inh_pop.set(spike_times=spike_times)
        p.run(100)
        # read out voltage and plot
        neo = if_pop.get_data("all")
        p.end()
        v = neo_convertor.convert_data(neo, "v", run=0)
        v2 = neo_convertor.convert_data(neo, "v", run=1)

        self.assertGreater(v[22][2], v[21][2])
        self.assertGreater(v[42][2], v[41][2])
        self.assertGreater(v[62][2], v[61][2])
        self.assertLess(v2[22][2], v2[21][2])
        self.assertLess(v2[42][2], v2[41][2])
        self.assertLess(v2[62][2], v2[61][2])
Esempio n. 14
0
def do_run():
    p.setup(1.0)

    inp = p.Population(100,
                       p.SpikeSourcePoisson(rate=2, seed=417),
                       label="input")
    inp.record("spikes")

    p.run(100)

    p.reset()

    inp.set(rate=30)

    p.run(100)

    p.end()
Esempio n. 15
0
    def do_run(self):
        sim.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
        prov_path = globals_variables.get_simulator()._app_provenance_file_path
        pop = sim.Population(10, sim.IF_curr_exp(), label='pop_1')
        sim.run(50)

        graph_mapper = globals_variables.get_simulator()._graph_mapper
        placements = globals_variables.get_simulator()._placements
        machine_verts = list(graph_mapper.get_machine_vertices(pop._vertex))
        placement = placements.get_placement_of_vertex(machine_verts[0])

        size1 = self.check_size(prov_path, placement)
        sim.run(50)
        size2 = self.check_size(prov_path, placement)
        self.assertGreater(size2, size1)
        sim.run(50)
        size3 = self.check_size(prov_path, placement)
        self.assertGreater(size3, size2)

        # Soft reset so same provenance
        sim.reset()
        sim.run(50)
        size4 = self.check_size(prov_path, placement)
        self.assertGreater(size4, size3)
        sim.run(50)
        size5 = self.check_size(prov_path, placement)
        self.assertGreater(size5, size4)

        # hard reset so new provenance
        sim.reset()
        sim.Population(10, sim.IF_curr_exp(), label='pop_1')
        sim.run(50)
        prov_patha = \
            globals_variables.get_simulator()._app_provenance_file_path
        self.assertNotEqual(prov_path, prov_patha)
        size6 = self.check_size(prov_patha, placement)
        # Should write the same thing again
        self.assertEqual(size1, size6)
        sim.end()

        # Should not add anything on end.
        size7 = self.check_size(prov_path, placement)
        self.assertEqual(size5, size7)
        size8 = self.check_size(prov_patha, placement)
        self.assertEqual(size8, size6)
def do_run():
    p.setup(1.0)

    inp = p.Population(100,
                       p.SpikeSourcePoisson(rate=2),
                       label="input",
                       additional_parameters={"seed": 417})
    inp.record("spikes")

    p.run(100)

    p.reset()

    inp.set(rate=30)

    p.run(100)

    p.end()
Esempio n. 17
0
 def change_pre_reset(self):
     sim.setup(1.0)
     pop = sim.Population(1, sim.IF_curr_exp, {}, label="pop")
     pop.set(i_offset=1.0)
     pop.set(tau_syn_E=1)
     pop.record(["v"])
     sim.run(5)
     v1 = pop.spinnaker_get_data('v')
     self.check_from_65(v1)
     pop.set(tau_syn_E=1)
     sim.reset()
     sim.run(5)
     v2 = pop.spinnaker_get_data('v')
     try:
         self.check_from_65(v2)
     except AssertionError:
         self.known_issue(
             "https://github.com/SpiNNakerManchester/sPyNNaker/issues/599")
     sim.end()
Esempio n. 18
0
def structural_formation_to_full_with_reset():
    p.setup(1.0)
    stim = p.Population(4, p.SpikeSourceArray(range(10)), label="stim")

    # These populations should experience formation
    pop = p.Population(4, p.IF_curr_exp(), label="pop")

    # Formation with random selection (0 probability elimination), setting
    # with_replacement=False means an all-to-all connection will be the result
    proj = p.Projection(
        stim, pop, p.FromListConnector([]), p.StructuralMechanismStatic(
            partner_selection=p.LastNeuronSelection(),
            formation=p.DistanceDependentFormation([2, 2], 1.0),
            elimination=p.RandomByWeightElimination(4.0, 0, 0),
            f_rew=1000, initial_weight=4.0, initial_delay=3.0,
            s_max=4, seed=0, weight=0.0, delay=1.0, with_replacement=False))

    pop.record("rewiring")

    p.run(1000)

    p.Population(4, p.IF_curr_exp(), label="pop2")
    p.reset()

    p.run(1000)

    # Get the final connections
    conns = proj.get(["weight", "delay"], "list")

    rewiring = pop.get_data("rewiring")

    formation_events = rewiring.segments[0].events[0]
    formation_events2 = rewiring.segments[1].events[0]

    num_forms = len(formation_events.times)
    num_forms2 = len(formation_events2.times)

    first_f = formation_events.labels[0]
    first_f2 = formation_events2.labels[0]

    p.end()

    return conns, num_forms, num_forms2, first_f, first_f2
    def do_run_with_reset(self):
        sim.setup(timestep=1.0)
        runtime = 500
        n_neurons = 10
        spikegap = 50

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

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

        weight = 5
        delay = 5

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

        pop_lif.record("all")

        sim.run(runtime // 2)

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

        sim.run(runtime // 2)

        pps = pop_lif.get_data()

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

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

        sim.end()
Esempio n. 20
0
 def no_change_v(self):
     sim.setup(1.0)
     pop = sim.Population(1, sim.IF_curr_exp, {}, label="pop")
     inp = sim.Population(1,
                          sim.SpikeSourceArray(spike_times=[0]),
                          label="input")
     sim.Projection(inp,
                    pop,
                    sim.OneToOneConnector(),
                    synapse_type=sim.StaticSynapse(weight=5))
     pop.set(i_offset=1.0)
     pop.set(tau_syn_E=1)
     pop.record(["v"])
     sim.run(5)
     sim.reset()
     inp.set(spike_times=[100])
     sim.run(5)
     v2 = pop.spinnaker_get_data('v')
     self.check_from_65(v2)
     sim.end()
Esempio n. 21
0
    def do_run(self):
        sim.setup(timestep=1.0, min_delay=1.0, max_delay=144.0)
        prov_path = globals_variables.get_simulator()._provenance_file_path
        sim.Population(10, sim.IF_curr_exp(), label='pop_1')
        sim.run(50)
        size1 = self.check_size(prov_path)
        sim.run(50)
        size2 = self.check_size(prov_path)
        self.assertGreater(size2, size1)
        sim.run(50)
        size3 = self.check_size(prov_path)
        self.assertGreater(size3, size2)

        # Soft reset so same provenance
        sim.reset()
        sim.run(50)
        size4 = self.check_size(prov_path)
        self.assertGreater(size4, size3)
        sim.run(50)
        size5 = self.check_size(prov_path)
        self.assertGreater(size5, size4)

        # hard reset so new provenance
        sim.reset()
        sim.Population(10, sim.IF_curr_exp(), label='pop_1')
        sim.run(50)
        prov_patha = globals_variables.get_simulator()._provenance_file_path
        self.assertNotEqual(prov_path, prov_patha)
        size6 = self.check_size(prov_patha)
        # Should write the same thing again
        self.assertEqual(size1, size6)
        sim.end()

        # Should not add anything on end.
        size7 = self.check_size(prov_path)
        self.assertEqual(size5, size7)
        size8 = self.check_size(prov_patha)
        self.assertEqual(size8, size6)
Esempio n. 22
0
def do_run():
    p.setup(timestep=1, min_delay=1)

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

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

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

    runtime = 30

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

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

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

    p.end()

    return (all1, all2)
Esempio n. 23
0
    def do_run(self):
        sim.setup(timestep=1.0, n_boards_required=2)
        sim.Population(3, sim.IF_curr_exp(), label="pop_1")
        machine1 = sim.get_machine()
        id1 = id(machine1)
        sim.run(1)
        machine2 = sim.get_machine()
        id2 = id(machine2)
        self.assertEqual(id1, id2)
        sim.run(2)

        machine3 = sim.get_machine()
        id3 = id(machine3)
        self.assertEqual(id1, id3)

        sim.reset()  # soft
        sim.run(3)
        machine4 = sim.get_machine()
        id4 = id(machine4)
        self.assertEqual(id1, id4)

        sim.reset()  # hard due to get_machine
        machine5 = sim.get_machine()
        id5 = id(machine5)
        self.assertNotEqual(id1, id5)
        sim.run(3)

        machine6 = sim.get_machine()
        id6 = id(machine6)
        self.assertEqual(id5, id6)

        sim.reset()  # Hhard due to new pop
        sim.Population(3, sim.IF_curr_exp(), label="pop_2")
        sim.run(3)
        machine7 = sim.get_machine()
        id7 = id(machine7)
        self.assertNotEqual(id1, id7)
        self.assertNotEqual(id5, id7)

        sim.reset()  # soft
        sim.run(3)
        machine8 = sim.get_machine()
        id8 = id(machine8)
        self.assertEqual(id7, id8)

        sim.end()
Esempio n. 24
0
    def projection_with_reset(self):
        p.setup(1.0)

        inp = p.Population(1, p.IF_curr_exp(), label="input")
        layer = p.Population(1, p.IF_curr_exp(), label="layer")
        output = p.Population(1, p.IF_curr_exp(), label="output")

        p.Projection(inp, layer, p.AllToAllConnector(),
                     p.StaticSynapse(weight=5, delay=2))

        p.run(100)

        layer_to_output = p.Projection(layer, output, p.AllToAllConnector(),
                                       p.StaticSynapse(weight=4, delay=10))

        p.reset()

        p.run(100)

        weights_delays_out = layer_to_output.get(["weight", "delay"], "list")

        p.end()

        assert weights_delays_out[0][2] == 4.0
Esempio n. 25
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
Esempio n. 26
0
    # wrongly classified.
    guesses[undecided] = -1
    print('guesses ' + str(guesses))
    # Get classification error of current batch, for each time step.
    top1err = guesses != np.broadcast_to(truth, guesses.shape)

    top1 = not top1err[-1]

    results[batch_idx] = np.array(
        [np.argmax(y_test[batch_idx]), guesses[-1],
         int(top1)])

    print('...done: ' + str(batch_idx + 1) + '/' + str(num_to_test))
    log = 'ClassID: ' + str(
        results[batch_idx][0]) + ', top-1: ' + str(top1) + '\n'

    print(log)
    f.write(log)
    sim.reset()
    #print ('v_thresh: ' + str(layers[1].get('v_thresh')))

acc1 = results.sum(axis=0)[2] / num_to_test
acc_log = 'top-1 acc: ' + str(acc1 * 100) + '%'
print(acc_log)
np.savez(layers_path + '/results_mnist_nest.npz', results)
f.write(acc_log)
#save_confusion_matrix(results,layers_path)

f.close()
sim.end()
def spinn_net():
    np.random.seed(272727)
    global output_labels
    global input_labels
    p.setup(timestep=1.0, min_delay=1, max_delay=60)
    p.set_number_of_neurons_per_core(p.IF_cond_exp, 64)
    n_pop_labels = []
    n_pop_list = []
    n_proj_list = []
    spike_source_list = []
    if offset != 0:
        for i in range(2):
            del output_labels[0]
        for i in range(2):
            del input_labels[0]
    for i in range(no_neuron_pops):
        #set up the input as a live spike source
        if i < 2:
            n_pop_labels.append("Input_pop{}".format(i))
            input_labels.append("Input_pop{}".format(i))
            n_pop_list.append(
                p.Population(pop_sizes[i], p.SpikeSourcePoisson(rate=poisson_rate),
                             label=n_pop_labels[i]))
            n_pop_list[i].record(["spikes"])
            p.external_devices.add_poisson_live_rate_control(
                n_pop_list[i], database_notify_port_num=(160+offset))
        #set up output pop
        elif i < 4:
            n_pop_labels.append("Output_pop{}".format(i))
            output_labels.append("Output_pop{}".format(i))
            n_pop_list.append(p.Population(pop_sizes[i], p.IF_cond_exp(),
                                           label=n_pop_labels[i]))
            p.external_devices.activate_live_output_for(
                n_pop_list[i], database_notify_port_num=(180+offset),
                port=(17000+offset))
            spike_source_list.append(p.Population(pop_sizes[i], p.SpikeSourcePoisson(rate=0.0),
                                                  label="source ".format(n_pop_labels[i])))
            n_pop_list[i].record(["spikes", "v"])
        #set up all other populations
        else:
            n_pop_labels.append("neuron{}".format(i))
            n_pop_list.append(p.Population(pop_sizes[i], p.IF_cond_exp(),
                                           label=n_pop_labels[i]))
            spike_source_list.append(p.Population(pop_sizes[i], p.SpikeSourcePoisson(rate=0.0),
                                                  label="source ".format(n_pop_labels[i])))
            n_pop_list[i].record(["spikes", "v"])



    poisson_control = p.external_devices.SpynnakerPoissonControlConnection(
        poisson_labels=input_labels, local_port=(160+offset))
    poisson_control.add_start_callback(n_pop_list[0].label, from_list_poisson)
    # poisson_control.add_start_callback(n_pop_list[1].label, poisson_setting)
    # poisson_control.add_start_callback(n_pop_list[0].label, poisson_threading)



    live_connection = p.external_devices.SpynnakerLiveSpikesConnection(
        receive_labels=output_labels, local_port=(180+offset))
    live_connection.add_receive_callback(n_pop_labels[2], receive_spikes)
    live_connection.add_receive_callback(n_pop_labels[3], receive_spikes)



    # weight_mu = 0.015
    # weight_sdtev = 0.05
    # delay_mu = 40
    # delay_sdtev = 5
    for i in range(no_neuron_pops):
        np.random.seed(272727)
        weights = RandomDistribution("normal_clipped", mu=weight_mu[i],
                                     sigma=weight_stdev[i], low=0, high=np.inf)
        delays = RandomDistribution("normal_clipped", mu=delay_mu[i],
                                    sigma=delay_stdev[i], low=1, high=55)
        synapse = p.StaticSynapse(weight=weights, delay=delays)
        for j in range(2, no_neuron_pops):
            print "\npop = {}({}) connecting to {}".format(i,pop_sizes[i],j)
            if connect_prob_ex[i][j-2] > 1e-10:
                print "ex = {}\tin = {}".format(connect_prob_ex[i][j-2], connect_prob_in[i][j-2])
                print "\tweight mu = {}\t stdev = {}".format(weight_mu[i], weight_stdev[i])
                print "\tdelay mu = {}\t stdev = {}".format(delay_mu[i], delay_stdev[i])
                n_proj_list.append(
                    p.Projection(n_pop_list[i], n_pop_list[j],
                                 p.FixedProbabilityConnector(connect_prob_ex[i][j-2]),#p.OneToOneConnector(),#
                                 synapse, receptor_type="excitatory"))
                n_proj_list.append(
                    p.Projection(n_pop_list[i], n_pop_list[j],
                                 p.FixedProbabilityConnector(connect_prob_in[i][j-2]),#p.OneToOneConnector(),#
                                 synapse, receptor_type="inhibitory"))
                # n_proj_list.append(p.Projection(n_pop_list[i], n_pop_list[j],
                #                                 p.FixedProbabilityConnector(1),
                #                                 synapse, receptor_type="inhibitory"))
    run = 0
    p.run(duration/timeScaleFactor)

    print "finished 1st"

    run = 1
    p.reset()

    p.run(duration/timeScaleFactor)
    total_v = list()
    spikes = list()
    v = list()
    spikes.append(n_pop_list[0].get_data("spikes"))
    spikes.append(n_pop_list[1].get_data("spikes"))
    for j in range(2,no_neuron_pops):
        spikes.append(n_pop_list[j].get_data("spikes"))
        v.append(n_pop_list[j].get_data("v"))
    Figure(
        # raster plot of the presynaptic neuron spike times
        Panel(spikes[0].segments[0].spiketrains,
              yticks=True, markersize=2, xlim=(0, duration)),
        Panel(spikes[1].segments[0].spiketrains,
              yticks=True, markersize=2, xlim=(0, duration)),
        Panel(spikes[2].segments[0].spiketrains,
              yticks=True, markersize=2, xlim=(0, duration)),
        Panel(spikes[3].segments[0].spiketrains,
              yticks=True, markersize=2, xlim=(0, duration)),
        # Panel(spikes[4].segments[0].spiketrains,
        #       yticks=True, markersize=2, xlim=(0, duration)),
        # Panel(spikes[no_neuron_pops-2].segments[0].spiketrains,
        #       yticks=True, markersize=2, xlim=(0, duration)),
        # Panel(spikes[no_neuron_pops-1].segments[0].spiketrains,
        #       yticks=True, markersize=2, xlim=(0, duration)),
        title="Raster plot",
        annotations="Simulated with {}".format(p.name())
    )
    plt.show()
    Figure(
        #membrane voltage plots
        Panel(v[0].segments[0].filter(name='v')[0],
              ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        Panel(v[1].segments[0].filter(name='v')[0],
              ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        Panel(v[2].segments[0].filter(name='v')[0],
              ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        Panel(v[3].segments[0].filter(name='v')[0],
              ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        # Panel(v[4].segments[0].filter(name='v')[0],
        #       ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        # Panel(v[no_neuron_pops-4].segments[0].filter(name='v')[0],
        #       ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        # Panel(v[no_neuron_pops-3].segments[0].filter(name='v')[0],
        #       ylabel="Membrane potential (mV)", yticks=True, xlim=(0, duration)),
        title="Membrane voltage plot",
    )
    plt.show()

    # p.reset()

    p.end()

    poisson_control.close()
    live_connection.close()

    print "finished run"