def live_spike_receive_translated(self):
        self.stored_data = list()

        db_conn = DatabaseConnection(local_port=None)
        db_conn.add_database_callback(self.database_callback)

        p.setup(1.0)
        p.set_number_of_neurons_per_core(p.SpikeSourceArray, 5)

        pop = p.Population(
            25, p.SpikeSourceArray([[1000 + (i * 10)] for i in range(25)]))
        p.external_devices.activate_live_output_for(
            pop,
            translate_keys=True,
            database_notify_port_num=db_conn.local_port,
            tag=1,
            use_prefix=True,
            key_prefix=self.PREFIX,
            prefix_type=EIEIOPrefix.UPPER_HALF_WORD)

        p.run(1500)

        p.end()
        self.listener.close()
        self.conn.close()

        self.assertGreater(len(self.stored_data), 0)
        for key, time in self.stored_data:
            self.assertEqual(key >> 16, self.PREFIX)
            self.assertEqual(1000 + ((key & 0xFFFF) * 10), time)
def mapping_process():

    ###################################
    SIM_TIME = TIME_SLOT*DATA_AMOUNT ##
    ###################################
    
    twitter_text_vectors = sentence_to_vec()
    orig = get_nearest_neighbor(twitter_text_vectors)
    show_result(orig,1,'./retrived_data/original_classification')
    response_space       = generate_vr_response(twitter_text_vectors)
    spiking_space        = generate_spiking_time(response_space) 
    np.savetxt("./retrived_data/input_time.txt",spiking_space,fmt='%s',delimiter=',',newline='\n')

    spynnaker.setup(timestep=1)
    spynnaker.set_number_of_neurons_per_core(spynnaker.IF_curr_exp, 250)

    pn_population  = setupLayer_PN(spiking_space)
    kc_population  = setupLayer_KC()
    kc_population.record(["spikes"])

    pn_kc_projection  = setupProjection_PN_KC(pn_population,kc_population)
    spynnaker.run(SIM_TIME)

    neo = kc_population.get_data(variables=["spikes"])
    spikeData_original= neo.segments[0].spiketrains
    spynnaker.end()
    return spikeData_original
Beispiel #3
0
def mapping_process():

    assert SIM_TIME > 0
    spynnaker.setup(timestep=1)
    spynnaker.set_number_of_neurons_per_core(spynnaker.IF_curr_exp, 50)
    time_space = readData()
    pn_population = setupLayer_PN(time_space)
    kc_population = setupLayer_KC()
    kc_population.record(["spikes"])
    pn_kc_projection = setupProjection_PN_KC(pn_population, kc_population)
    spynnaker.run(SIM_TIME)
    neo = kc_population.get_data(variables=["spikes"])
    spikeData_original = neo.segments[0].spiketrains
    spynnaker.end()
    return spikeData_original
Beispiel #4
0
def mapping_process():

    ###################################
    SIM_TIME = TIME_SLOT * DATA_AMOUNT  ##
    ###################################

    spynnaker.setup(timestep=1)
    spynnaker.set_number_of_neurons_per_core(spynnaker.IF_curr_exp, 50)
    # time_space     = readData()
    # Manage to obtain data correctly

    pn_population = setupLayer_PN(time_space)
    kc_population = setupLayer_KC()
    kc_population.record(["spikes"])

    pn_kc_projection = setupProjection_PN_KC(pn_population, kc_population)
    spynnaker.run(SIM_TIME)

    neo = kc_population.get_data(variables=["spikes"])
    spikeData_original = neo.segments[0].spiketrains
    spynnaker.end()
    return spikeData_original
Beispiel #5
0
def mapping_process():

    ###################################
    SIM_TIME = TIME_SLOT*DATA_AMOUNT ##
    ###################################

    response_space = generate_vr_response()
    spiking_space  = generate_spiking_time(response_space) 

    spynnaker.setup(timestep=1)
    spynnaker.set_number_of_neurons_per_core(spynnaker.IF_curr_exp, 250)

    pn_population  = setupLayer_PN(spiking_space)
    kc_population  = setupLayer_KC()
    kc_population.record(["spikes"])

    pn_kc_projection  = setupProjection_PN_KC(pn_population,kc_population)
    spynnaker.run(SIM_TIME)

    neo = kc_population.get_data(variables=["spikes"])
    spikeData_original= neo.segments[0].spiketrains
    spynnaker.end()
    return spikeData_original
Beispiel #6
0
import pyNN.spiNNaker as sim
import pyNN.utility.plotting as plot
import matplotlib.pyplot as plt
import threading
from random import uniform
from time import sleep
from pykeyboard import PyKeyboard

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

input1 = sim.Population(6,
                        sim.external_devices.SpikeInjector(),
                        label="stateSpikeInjector")

pre_pop = sim.Population(6,
                         sim.IF_curr_exp(tau_syn_E=100, tau_refrac=50),
                         label="statePopulation")

post_pop = sim.Population(1, sim.IF_curr_exp(), label="actorPopulation")
sim.external_devices.activate_live_output_for(pre_pop,
                                              database_notify_host="localhost",
                                              database_notify_port_num=19996)
sim.external_devices.activate_live_output_for(input1,
                                              database_notify_host="localhost",
                                              database_notify_port_num=19998)

timing_rule = sim.SpikePairRule(tau_plus=20.0,
                                tau_minus=20.0,
                                A_plus=0.5,
                                A_minus=0.5)
Beispiel #7
0
      mean_of_means = total_mean / len(means)

   total_std = 0
   if len(stds) > 0:
      for val in stds:
         total_std += val
      mean_of_stds = total_std / len(stds)
   
   return (mean_of_means, mean_of_stds)

if len(sys.argv) is not 4:
    print "Error: expected 3 parameters after filename, but got ", len(sys.argv)-1
    quit()

p.setup(timestep=1.0, min_delay = 1.0, max_delay = 15.0)
p.set_number_of_neurons_per_core("IF_curr_exp", 50)
p.set_number_of_neurons_per_core("SpikeSourcePoisson", poissonSourcesPerCore)

# Parameters to set for each run:
# Level 1:
nL1ExcitNeurons = int(sys.argv[1]) # was 2400
nL2ExcitNeurons = int(sys.argv[2]) # was 2400
L1MeanWeightX2X = float(sys.argv[3])
L1MeanWeightX2I = float(sys.argv[3])
# Common:
StdDev = 1.0
noiseRate = 9 # Hz
print "Spike sources: ", nL1ExcitNeurons

rng = NumpyRNG(seed=1)
E2EmeanDelay = 7.0
import pylab

from pacman.model.constraints.placer_constraints.placer_chip_and_core_constraint import PlacerChipAndCoreConstraint

try:
    import pyNN.spiNNaker as sim
except Exception as e:
    import spynnaker.pyNN as sim

# SpiNNaker setup
sim.setup(timestep=1.0, min_delay=1.0, max_delay=10.0)
sim.set_number_of_neurons_per_core("IF_curr_exp", 50)

# Population parameters
model = sim.IF_curr_exp

n_atoms = 25

cell_params = {
    '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
}

# Define layers
Beispiel #9
0
      mean_of_means = total_mean / len(means)

   total_std = 0
   if len(stds) > 0:
      for val in stds:
         total_std += val
      mean_of_stds = total_std / len(stds)
   
   return (mean_of_means, mean_of_stds)

if len(sys.argv) is not 4:
    print "Error: expected 3 parameters after filename, but got ", len(sys.argv)-1
    quit()

p.setup(timestep=1.0, min_delay = 1.0, max_delay = 15.0)
p.set_number_of_neurons_per_core("IF_curr_exp", 50)
p.set_number_of_neurons_per_core("SpikeSourcePoisson", poissonSourcesPerCore)

# Parameters to set for each run:
# Level 1:
nL1ExcitNeurons = int(sys.argv[1]) # was 2400
nL2ExcitNeurons = int(sys.argv[2]) # was 2400
L1MeanWeightX2X = float(sys.argv[3])
L1MeanWeightX2I = float(sys.argv[3])
# Common:
StdDev = 1.0
noiseRate = 9 # Hz
print "Spike sources: ", nL1ExcitNeurons

rng = NumpyRNG(seed=1)
E2EmeanDelay = 7.0
import pyNN.spiNNaker as p
import numpy, pylab, random, sys
import time
import datetime as dt
from math import *
# import defined retina Functions from another python file
from retinaFunc import *

#Define Simulation Paras
runtime = 10000 # just for gesture single
num_per_core = 256

#INIT pacman103
p.setup(timestep=1.0, min_delay = 1.0, max_delay = 32.0)
p.set_number_of_neurons_per_core('IF_curr_exp', num_per_core)      # this will set one population per core

#external stuff: population requiremenets
connected_chip_coords = {'x': 0, 'y': 0}
virtual_chip_coords = {'x': 0, 'y': 5}
link = 4

integrate_size = 36
#spikeTrains, source_Num = load_inputSpikes3('recorded_data_for_spinnaker/integrate_all.mat', 'integrate', integrate_size)
spikeTrains, source_Num = load_inputSpikes4('recorded_data_for_spinnaker/integrate_all.mat', 'integrate', integrate_size, runtime)
'''
integrate_pop = []
print "source_Num:", source_Num
for i in range(source_Num):
#for i in range(1):
    pop = p.Population(integrate_size * integrate_size, p.SpikeSourceArray, {'spike_times': spikeTrains[i] }, label='retina_pop')
import pyNN.spiNNaker as p
import retina_lib

input_size = 128             # Size of each population
subsample_size = 32
runtime = 60
# Simulation Setup
p.setup(timestep=1.0, min_delay = 1.0, max_delay = 11.0)            # Will add some extra parameters for the spinnPredef.ini in here

p.set_number_of_neurons_per_core('IF_curr_exp', 128)      # this will set one population per core

cell_params = { 'tau_m' : 64, 'i_offset'  : 0,
    'v_rest'    : -75,  'v_reset'    : -95, 'v_thresh'   : -40,
    'tau_syn_E' : 15,   'tau_syn_I'  : 15,  'tau_refrac' : 2}



#external stuff population requiremenets
connected_chip_coords = {'x': 0, 'y': 0}
virtual_chip_coords = {'x': 0, 'y': 5}
link = 4


print "Creating input population: %d x %d" % (input_size, input_size)

input_pol_1_up = p.Population(128*128,
                               p.ExternalRetinaDevice,
                               {'virtual_chip_coords': virtual_chip_coords,
                                'connected_chip_coords':connected_chip_coords,
                                'connected_chip_edge':link,
                                'unique_id': 'R',
"""
Synfirechain-like example
"""
import pyNN.spiNNaker as p
import pylab

p.setup(timestep=1.0, min_delay=1.0, max_delay=32.0)
p.set_number_of_neurons_per_core("IZK_curr_exp", 100)

nNeurons = 200  # number of neurons in each population

cell_params_izk = {'a': 0.02,
                   'b': 0.2,
                   'c': -65,
                   'd': 8,
                   'v_init': -75,
                   'u_init': 0,
                   'tau_syn_E': 2,
                   'tau_syn_I': 2,
                   'i_offset': 0
                   }

populations = list()
projections = list()

weight_to_spike = 40
delay = 1

loopConnections = list()
for i in range(0, nNeurons):
    singleConnection = (i, ((i + 1) % nNeurons), weight_to_spike, delay)
import pyNN.spiNNaker as p
import retina_lib

input_size = 128  # Size of each population
subsample_size = 32
runtime = 60
# Simulation Setup
p.setup(timestep=1.0, min_delay=1.0, max_delay=11.0)  # Will add some extra parameters for the spinnPredef.ini in here

p.set_number_of_neurons_per_core("IF_curr_exp", 128)  # this will set one population per core

cell_params = {
    "tau_m": 64,
    "i_offset": 0,
    "v_rest": -75,
    "v_reset": -95,
    "v_thresh": -40,
    "tau_syn_E": 15,
    "tau_syn_I": 15,
    "tau_refrac": 2,
}


# external stuff population requiremenets
connected_chip_coords = {"x": 0, "y": 0}
virtual_chip_coords = {"x": 0, "y": 5}
link = 4


print "Creating input population: %d x %d" % (input_size, input_size)
Beispiel #14
0
                      }

inj_cell_params = {
  'port': 12345,
}
inj_cell_type = ExternalDevices.SpikeInjector


#~ num_inh = int(num_neurons*(1./4.))

rngseed = int(time.time())
#rngseed = 1
rng = sim.NumpyRNG(seed=rngseed)
neuron_model = sim.IZK_curr_exp

sim.set_number_of_neurons_per_core(neuron_model, 128)
sim.setup(timestep=timestep, min_delay = min_delay, max_delay = max_delay)

############ stdp

stdp_model = sim.STDPMechanism(
    timing_dependence=sim.SpikePairRule(tau_plus=20., tau_minus=20.0,
                                        nearest=True),
    weight_dependence=sim.AdditiveWeightDependence(w_min=0.01, w_max=6.,
                                                   A_plus=0.02, A_minus=0.02)
  )

############ random dist objects

exc_delay_dist = RandomDistribution(distribution='uniform', 
                                    parameters=[0,20.], rng=rng)
def lancement_sim(cellSourceSpikes,
                  path,
                  weight_input=0,
                  weight_inter=0,
                  max_time=800000,
                  TIME_STEP=TIME_STEP,
                  input_n=input_n,
                  nb_neuron_int=nb_neuron_int,
                  nb_neuron_out=nb_neuron_out,
                  delay=delay,
                  p_conn_in_int=p_conn_in_int,
                  p_conn_int_out=p_conn_int_out,
                  v_tresh=v_tresh):

    simulator = 'spinnaker'
    # le max_delay doit être inférieur à 14*time_step
    sim.setup(timestep=TIME_STEP, min_delay=delay, max_delay=delay * 2)
    randoms = np.random.rand(100, 1)

    #defining network topology
    lif_curr_exp_params = {
        'cm': 1.0,  # The capacitance of the LIF neuron in nano-Farads
        'tau_m': 20.0,  # The time-constant of the RC circuit, in milliseconds
        'tau_refrac': 5.0,  # The refractory period, in milliseconds
        'v_reset':
        -65.0,  # The voltage to set the neuron at immediately after a spike
        'v_rest': -65.0,  # The ambient rest voltage of the neuron
        'v_thresh':
        -(v_tresh),  # The threshold voltage at which the neuron will spike
        'tau_syn_E': 5.0,  # The excitatory input current decay time-constant
        'tau_syn_I': 5.0,  # The inhibitory input current decay time-constant
        'i_offset': 0.0,  # A base input current to add each timestep
    }

    # Population d'entrée avec comme source le SpikeSourceArray en paramètre
    Input = sim.Population(input_n,
                           sim.SpikeSourceArray(spike_times=cellSourceSpikes),
                           label="Input")
    Input.record("spikes")

    # Définition des types de neurones et des couches intermédiaire, de sortie, ainsi que celle contenant le neurone de l'attention
    LIF_Intermediate = sim.IF_curr_exp(**lif_curr_exp_params)
    Intermediate = sim.Population(nb_neuron_int,
                                  LIF_Intermediate,
                                  label="Intermediate")
    Intermediate.record(("spikes", "v"))

    LIF_Output = sim.IF_curr_exp(**lif_curr_exp_params)
    Output = sim.Population(nb_neuron_out, LIF_Output, label="Output")
    Output.record(("spikes", "v"))

    LIF_delayer = sim.IF_curr_exp(**lif_curr_exp_params)
    Delay_n = sim.Population(1, LIF_delayer, label="Delay")
    Delay_n.record(("spikes", "v"))

    # set the stdp mechanisim parameters, we are going to use stdp in both connections between (input-intermediate) adn (intermediate-output)
    python_rng = NumpyRNG(seed=98497627)

    delay = delay  # (ms) synaptic time delay
    #A_minus

    # définition des connexions entre couches de neurones entrée <=> intermédiaire, intermédiaire <=> sortie
    # vérificatio pour savoir si on est dans le cas de la première simulation par défault ou si on doit injecter les poids
    if ((weight_input != 0) or (weight_inter != 0)):
        # cas ou l'on inject les poids
        Conn_input_inter = sim.Projection(
            Input,
            Intermediate,
            # Le fromListConnector pour injecter les poids
            connector=sim.FromListConnector(weight_input),
            receptor_type="excitatory",
            label="Connection input to intermediate",
            # des synapses static pour "suprimer" l'apprentissage
            synapse_type=sim.StaticSynapse())

        Conn_inter_output = sim.Projection(
            Intermediate,
            Output,  # pre and post population
            connector=sim.FromListConnector(weight_inter),
            receptor_type="excitatory",
            label="Connection intermediate to output",
            synapse_type=sim.StaticSynapse())

    else:
        # cas par défault
        Conn_input_inter = sim.Projection(
            Input,
            Intermediate,
            connector=sim.FixedProbabilityConnector(
                p_conn_in_int, allow_self_connections=False),
            synapse_type=sim.StaticSynapse(
                weight=RandomDistribution('normal', (3, 2.9), rng=python_rng)),
            receptor_type="excitatory",
            label="Connection input to intermediate")
        Conn_inter_output = sim.Projection(
            Intermediate,
            Output,  # pre and post population
            connector=sim.FixedProbabilityConnector(
                p_conn_int_out, allow_self_connections=False),
            synapse_type=sim.StaticSynapse(
                weight=RandomDistribution('normal', (3, 2.9), rng=python_rng)),
            receptor_type="excitatory",
            label="Connection intermediate to output")

    # définition des connexions inhibitrices des couches intermédiaire et de sortie
    FixedInhibitory_WTA = sim.StaticSynapse(weight=6)
    WTA_INT = sim.Projection(
        Intermediate,
        Intermediate,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_WTA,
        receptor_type="inhibitory",
        label="Connection WTA")

    WTA_OUT = sim.Projection(
        Output,
        Output,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_WTA,
        receptor_type="inhibitory",
        label="Connection WTA")

    # Connexion avec le neurone de l'attention
    FixedInhibitory_delayer = sim.StaticSynapse(weight=2)
    Delay_out = sim.Projection(
        Delay_n,
        Output,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_delayer,
        receptor_type="inhibitory",
        label="Connection WTA")

    Delay_inter = sim.Projection(
        Intermediate,
        Delay_n,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_delayer,
        receptor_type="inhibitory",
        label="Connection WTA")

    # On précise le nombre de neurone par coeurs au cas ou
    sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 255)

    # on arrondie le temps de simulation, sinon avec les callbacks, on a une boucle infinie pour des temps d'arrêts plus précis que la fréquence des callbacks
    simtime = ceil(max_time)

    try:
        #lancement de la simulation
        sim.run(simtime)
        #récupération des infos sur les spike des trois couches
        neo = Output.get_data(variables=["spikes", "v"])
        spikes = neo.segments[0].spiketrains
        #print(spikes)
        v = neo.segments[0].filter(name='v')[0]

        neo_in = Input.get_data(variables=["spikes"])
        spikes_in = neo_in.segments[0].spiketrains
        #print(spikes_in)

        neo_intermediate = Intermediate.get_data(variables=["spikes", "v"])
        spikes_intermediate = neo_intermediate.segments[0].spiketrains
        #print(spikes_intermediate)
        v_intermediate = neo_intermediate.segments[0].filter(name='v')[0]
        #print(v_intermediate)

        sim.reset()
        sim.end()
    except:
        # Si la simulation fail, on set ces deux variables à zéros pour gérer l'erreur dans le script principal
        v = 0
        spikes = 0

    # Création et sauvegarde des graphs des graphs si la simluation s'est bien passée, + envoie des sorties de la fonction
    if (isinstance(spikes, list) and isinstance(v, AnalogSignal)):

        plot.Figure(
            # plot voltage for first ([0]) neuron
            plot.Panel(v,
                       ylabel="Membrane potential (mV)",
                       data_labels=[Output.label],
                       yticks=True,
                       xlim=(0, simtime)),
            # plot spikes (or in this case spike)
            plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)),
            title="Spiking activity of the output layer during test",
            annotations="Simulated with {}".format(sim.name())).save(
                "./Generated_data/tests/" + path +
                "/output_layer_membrane_voltage_and_spikes.png")

        plot.Figure(
            # plot voltage for first ([0]) neuron
            plot.Panel(v_intermediate,
                       ylabel="Membrane potential (mV)",
                       data_labels=[Output.label],
                       yticks=True,
                       xlim=(0, simtime)),
            # plot spikes (or in this case spike)
            plot.Panel(spikes_intermediate,
                       yticks=True,
                       markersize=5,
                       xlim=(0, simtime)),
            title="Spiking activity of the intermediate layer during test",
            annotations="Simulated with {}".format(sim.name())).save(
                "./Generated_data/tests/" + path +
                "/intermediate_layer_membrane_voltage_and_spikes.png")

        return v, spikes
    else:
        print(
            "simulation failed with parameters : (l'affichage des paramètres ayant causés le disfonctionnement de la simulation sera traitée à une date ultérieur, merci!)"
        )
        return 0, 0
"""
Synfirechain-like example
"""
import pyNN.spiNNaker as p
import pylab
import numpy

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

runtime = 1000
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 = 17

loopConnections = list()
for i in range(0, nNeurons):
Beispiel #17
0
import matplotlib.gridspec as gs
import os

#import pyNN.nest as pynn
import pyNN.spiNNaker as pynn


#set sim parameters
sim_time = 150
dt = 0.1
refrac = 0
start_test=78
end_test= 84
print("trials from "+str(start_test)+ "to "+str(end_test)
pynn.setup(dt)
pynn.set_number_of_neurons_per_core(pynn.IF_curr_exp, 64)
weight_scale = 1
rescale_fac = 1000/(1000*dt)

#load data
test_data = np.load("x_test.npz")['arr_0'][start_test:end_test]
test_labels = np.load("y_test.npz")['arr_0'][start_test:end_test]

pred_labels = []

#create network
network = []


#cell defaults
cell_params = {
    def run_sim(self):
        """
        Sets up and runs the simulation
        """
        num_neurons = 1471  # total neurons in network
        num_inputs = 14     # number of neurons considered inputs
        num_runs = 1        # number of times to loop the learning
        num_samples = 1     # number of samples to learn`
        sim_time = 1000.0    # time to run sim for`
        inhibitory_split = 0.2
        connection_probability_factor = 0.02
        plot_spikes = True
        save_figures = True
        show_figures = True
        sim_start_time = strftime("%Y-%m-%d_%H:%M")

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

        # Create the 3d structure of the NeuCube based on the user's given structure file
        network_structure = NetworkStructure()
        network_structure.load_structure_file()
        network_structure.load_input_location_file()
        # Calculate the inter-neuron distance to be used in the small world connections
        network_structure.calculate_distances()
        # Generate two connection matrices for excitatory and inhibitory neurons based on your defined split
        network_structure.calculate_connection_matrix(inhibitory_split, connection_probability_factor)
        # Get these lists to be used when connecting the neurons later
        excitatory_connection_list = network_structure.get_excitatory_connection_list()
        inhibitory_connection_list = network_structure.get_inhibitory_connection_list()
        # Choose the correct neurons to connect them to, based on your a-priori knowledge of the data source -- eg, EEG
        # to 10-20 locations, fMRI to voxel locations, etc.
        input_neuron_indexes = network_structure.find_input_neurons()
        # Make the input connections based on this new list
        input_weight = 4.0
        input_connection_list = []
        for index, input_neuron_index in enumerate(input_neuron_indexes):
            input_connection_list.append((index, input_neuron_index, input_weight, 0))

        for run_number in xrange(num_runs):
            excitatory_weights = []
            inhibitory_weights = []
            for sample_number in xrange(num_samples):
                # At the moment with the limitations of the SpiNNaker hardware we have to reinstantiate EVERYTHING
                # each run. In future there will be some form of repetition added, where the structure stays in memory
                # on the SpiNNaker and only the input spikes need to be updated.

                data_prefix = sim_start_time + "_r" + str(run_number + 1) + "-s" + str(sample_number + 1)

                # Set up the hardware - min_delay should never be less than the timestep.
                # Timestep should = 1.0 (ms) for normal realtime applications
                p.setup(timestep=1.0, min_delay=1.0)
                p.set_number_of_neurons_per_core("IF_curr_exp", 100)

                # Create a population of neurons for the reservoir
                neurons = p.Population(num_neurons, p.IF_curr_exp, cell_params_lif, label="Reservoir")

                # Setup excitatory STDP
                timing_rule_ex = p.SpikePairRule(tau_plus=20.0, tau_minus=20.0)
                weight_rule_ex = p.AdditiveWeightDependence(w_min=0.1, w_max=1.0, A_plus=0.02, A_minus=0.02)
                stdp_model_ex  = p.STDPMechanism(timing_dependence=timing_rule_ex, weight_dependence=weight_rule_ex)
                # Setup inhibitory STDP
                timing_rule_inh = p.SpikePairRule(tau_plus=20.0, tau_minus=20.0)
                weight_rule_inh = p.AdditiveWeightDependence(w_min=0.0, w_max=0.6, A_plus=0.02, A_minus=0.02)
                stdp_model_inh  = p.STDPMechanism(timing_dependence=timing_rule_inh, weight_dependence=weight_rule_inh)

                # record the spikes from that population
                neurons.record('spikes')

                # Generate a population of SpikeSourceArrays containing the encoded input spike data
                # eg. spike_sources = p.Population(14, p.SpikeSourceArray, {'spike_times': [[]]})
                # for the moment I'm going to cheat and just use poisson trains as I don't have data with me
                spike_sources = p.Population(num_inputs, p.SpikeSourcePoisson, {'rate': rand.randint(20, 80)},
                                             label="Poisson_pop_E")

                # Connect the input spike sources with the "input" neurons
                connected_inputs = p.Projection(spike_sources, neurons, p.FromListConnector(input_connection_list))

                # If we have weights saved/recorded from a previous run of this network, load them into the structure
                # population.set(weights=weights_list) and population.setWeights(weight_list) are not supported in
                # SpiNNaker at the moment so we have to do this manually.
                if excitatory_weights and inhibitory_weights:
                    for index, ex_connection in enumerate(excitatory_connection_list):
                        ex_connection[2] = excitatory_weights[index]
                    for index, in_connection in enumerate(inhibitory_connection_list):
                        in_connection[2] = inhibitory_weights[index]

                # Setup the connectors
                excitatory_connector = p.FromListConnector(excitatory_connection_list)
                inhibitory_connector = p.FromListConnector(inhibitory_connection_list)

                # Connect the excitatory and inhibitory neuron populations
                connected_excitatory_neurons = p.Projection(neurons, neurons, excitatory_connector,
                                                            synapse_dynamics=p.SynapseDynamics(slow=stdp_model_ex),
                                                            target="excitatory")
                connected_inhibitory_neurons = p.Projection(neurons, neurons, inhibitory_connector,
                                                            synapse_dynamics=p.SynapseDynamics(slow=stdp_model_inh),
                                                            target="inhibitory")

                # Set up recording the spike trains of all the neurons
                neurons.record()
                spike_sources.record()

                # Run the actual simulation
                p.run(sim_time)

                # Save the output spikes
                spikes_out = neurons.getSpikes(compatible_output=True)
                input_spikes_out = spike_sources.getSpikes(compatible_output=True)
                # Get the synaptic weights of all the neurons
                excitatory_weights = connected_excitatory_neurons.getWeights()
                inhibitory_weights = connected_inhibitory_neurons.getWeights()

                # when we're all done, clean up
                p.end()

                # Make some plots, save them if required. Check if you need to either save or show them, because if not,
                # there's no point wasting time plotting things nobody will ever see.
                if plot_spikes and (save_figures or show_figures):
                    plot = Plot(save_figures, data_prefix)
                    # Plot the 3D structure of the network
                    plot.plot_structure(network_structure.get_positions(), figure_number=0)
                    # Plot the spikes
                    plot.plot_spike_raster(spikes_out, sim_time, num_neurons, figure_number=1)
                    # Plot the weights
                    plot.plot_both_weights(excitatory_weights, inhibitory_weights, figure_number=2)
                    # If we want to show the figures, show them now, otherwise ignore and move on
                    if show_figures:
                        # Show them all at once
                        plot.show_plots()
                    plot.clear_figures()
                    plot = None
"""
Synfirechain-like example
"""
import pyNN.spiNNaker as p
import pylab
import numpy

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

runtime = 1000
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 = 17

loopConnections = list()
for i in range(0, nNeurons):
Beispiel #20
0
def lancement_sim(cellSourceSpikes,
                  max_time=800000,
                  path="default",
                  TIME_STEP=TIME_STEP,
                  input_n=input_n,
                  nb_neuron_int=nb_neuron_int,
                  nb_neuron_out=nb_neuron_out,
                  delay=delay,
                  p_conn_in_int=p_conn_in_int,
                  p_conn_int_out=p_conn_int_out,
                  a_minus=0.6,
                  a_plus=0.6,
                  tau_minus=12.0,
                  tau_plus=10.0,
                  v_tresh=10.0):

    simulator = 'spinnaker'
    sim.setup(timestep=TIME_STEP, min_delay=delay, max_delay=delay * 2)
    randoms = np.random.rand(100, 1)

    lif_curr_exp_params = {
        'cm': 1.0,  # The capacitance of the LIF neuron in nano-Farads
        'tau_m': 20.0,  # The time-constant of the RC circuit, in milliseconds
        'tau_refrac': 5.0,  # The refractory period, in milliseconds
        'v_reset':
        -65.0,  # The voltage to set the neuron at immediately after a spike
        'v_rest': -65.0,  # The ambient rest voltage of the neuron
        'v_thresh':
        -(v_tresh),  # The threshold voltage at which the neuron will spike
        'tau_syn_E': 5.0,  # The excitatory input current decay time-constant
        'tau_syn_I': 5.0,  # The inhibitory input current decay time-constant
        'i_offset': 0.0,  # A base input current to add each timestep
    }
    Input = sim.Population(input_n,
                           sim.SpikeSourceArray(spike_times=cellSourceSpikes),
                           label="Input")
    Input.record("spikes")

    LIF_Intermediate = sim.IF_curr_exp(**lif_curr_exp_params)
    Intermediate = sim.Population(nb_neuron_int,
                                  LIF_Intermediate,
                                  label="Intermediate")
    Intermediate.record(("spikes", "v"))

    LIF_Output = sim.IF_curr_exp(**lif_curr_exp_params)
    Output = sim.Population(nb_neuron_out, LIF_Output, label="Output")
    Output.record(("spikes", "v"))

    LIF_delayer = sim.IF_curr_exp(**lif_curr_exp_params)
    Delay_n = sim.Population(1, LIF_delayer, label="Delay")
    Delay_n.record(("spikes", "v"))

    python_rng = NumpyRNG(seed=98497627)

    delay = delay  # (ms) synaptic time delay

    # Définition du fonctionnement de la stdp
    stdp_proj = sim.STDPMechanism(
        timing_dependence=sim.SpikePairRule(tau_plus=tau_plus,
                                            tau_minus=tau_minus,
                                            A_plus=a_plus,
                                            A_minus=a_minus),
        weight_dependence=sim.AdditiveWeightDependence(w_min=0.1, w_max=6),
        weight=RandomDistribution('normal', (3, 2.9), rng=python_rng),
        delay=delay)

    Conn_input_inter = sim.Projection(
        Input,
        Intermediate,
        connector=sim.FixedProbabilityConnector(p_conn_in_int,
                                                allow_self_connections=False),
        # synapse type set avec la définition de la stdp pour l'aprentsissage
        synapse_type=stdp_proj,
        receptor_type="excitatory",
        label="Connection input to intermediate")

    # second projection with stdp
    Conn_inter_output = sim.Projection(
        Intermediate,
        Output,  # pre and post population
        connector=sim.FixedProbabilityConnector(p_conn_int_out,
                                                allow_self_connections=False),
        synapse_type=stdp_proj,
        receptor_type="excitatory",
        label="Connection intermediate to output")

    FixedInhibitory_WTA = sim.StaticSynapse(weight=6)
    WTA_INT = sim.Projection(
        Intermediate,
        Intermediate,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_WTA,
        receptor_type="inhibitory",
        label="Connection WTA")

    WTA_OUT = sim.Projection(
        Output,
        Output,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_WTA,
        receptor_type="inhibitory",
        label="Connection WTA")

    FixedInhibitory_delayer = sim.StaticSynapse(weight=2)
    Delay_out = sim.Projection(
        Delay_n,
        Output,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_delayer,
        receptor_type="inhibitory",
        label="Connection WTA")

    Delay_inter = sim.Projection(
        Intermediate,
        Delay_n,
        connector=sim.AllToAllConnector(allow_self_connections=False),
        synapse_type=FixedInhibitory_delayer,
        receptor_type="inhibitory",
        label="Connection WTA")

    sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 255)

    # Définition des callbacks pour la récupération de l'écart-type sur les connexions entrée-intermédiaire, intermédiaire-sortie
    weight_recorder1 = WeightRecorder(sampling_interval=1000.0,
                                      projection=Conn_input_inter)
    weight_recorder2 = WeightRecorder(sampling_interval=1000.0,
                                      projection=Conn_inter_output)

    simtime = ceil(max_time)

    # Initialisation des tableaux pour la récupération des poids
    weights_int = []
    weights_out = []

    try:
        sim.run(simtime, callbacks=[weight_recorder1, weight_recorder2])
        neo = Output.get_data(variables=["spikes", "v"])
        spikes = neo.segments[0].spiketrains
        #print(spikes)
        v = neo.segments[0].filter(name='v')[0]
        weights_int = Conn_input_inter.get(["weight"], format="list")

        neo_in = Input.get_data(variables=["spikes"])
        spikes_in = neo_in.segments[0].spiketrains
        #print(spikes_in)

        neo_intermediate = Intermediate.get_data(variables=["spikes", "v"])
        spikes_intermediate = neo_intermediate.segments[0].spiketrains
        #print(spikes_intermediate)
        v_intermediate = neo_intermediate.segments[0].filter(name='v')[0]
        #print(v_intermediate)
        weights_out = Conn_inter_output.get(["weight"], format="list")

        sim.reset()
        sim.end()
    except:
        v = 0
        spikes = 0

    if (isinstance(spikes, list) and isinstance(v, AnalogSignal)):
        # Récupération des écart-types
        standard_deviation_out = weight_recorder2.get_standard_deviations()
        standard_deviation_int = weight_recorder1.get_standard_deviations()
        t = np.arange(0., max_time, 1.)

        # Création et sauvegarde des graphs sur les spikes et écart-types
        savePath = "./Generated_data/training/" + path + "/intermediate_layer_standard_deviation.png"
        plt.plot(standard_deviation_int)
        plt.xlabel("callbacks tick (1s)")
        plt.ylabel("standard deviation of the weights( wmax=6, wmin=0.1 )")
        plt.savefig(savePath)
        plt.clf()

        savePath = "./Generated_data/training/" + path + "/output_layer_standard_deviation.png"
        plt.plot(standard_deviation_out)
        plt.xlabel("callbacks tick")
        plt.ylabel("standard deviation ( wmax=6, wmin=0.1 )")
        plt.savefig(savePath)
        plt.clf()

        savePath = "./Generated_data/training/" + path + "/output_layer_membrane_voltage_and_spikes.png"
        plot.Figure(
            # plot voltage for first ([0]) neuron
            plot.Panel(v,
                       ylabel="Membrane potential (mV)",
                       data_labels=[Output.label],
                       yticks=True,
                       xlim=(0, simtime)),
            # plot spikes (or in this case spike)
            plot.Panel(spikes, yticks=True, markersize=5, xlim=(0, simtime)),
            title="Spiking activity of the output layer during training",
            annotations="Simulated with {}".format(sim.name())).save(savePath)

        savePath = "./Generated_data/training/" + path + "/intermediate_layer_membrane_voltage_and_spikes.png"
        plot.Figure(
            # plot voltage for first ([0]) neuron
            plot.Panel(v_intermediate,
                       ylabel="Membrane potential (mV)",
                       data_labels=[Output.label],
                       yticks=True,
                       xlim=(0, simtime)),
            # plot spikes (or in this case spike)
            plot.Panel(spikes_intermediate,
                       yticks=True,
                       markersize=5,
                       xlim=(0, simtime)),
            title="Spiking activity of the intermediate layer during training",
            annotations="Simulated with {}".format(sim.name())).save(savePath)

        return v, spikes, weights_int, weights_out

    else:
        print(
            "simulation failed with parmaters parameters : (l'affichage des paramètres ayant causés le disfonctionnement de la simulation sera traitée à une date ultérieur, merci!)"
        )
        return 0, 0, 0, 0