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 setupLayer_PN(time_space):
    '''
     PN ─┬─── pn_neuron_01
         ├─── pn_neuron_02
         ├─── pn_neuron_03
         ├─── ...
         └─── pn_neuron_100

     PN was used as input layer
    '''
    input_population = spynnaker.Population(NUM_PN_CELLS,
                                            spynnaker.SpikeSourceArray(spike_times=time_space),
                                            label='PN_population')
    return input_population
Exemple #3
0
def setupLayer_PN(time_space):
    '''
     PN ─┬─── pn_neuron_01
         ├─── pn_neuron_02
         ├─── pn_neuron_03
         ├─── ...
         └─── pn_neuron_784
    '''
    NUM_PN_CELLS = 784
    '''
        784只PN神经元放在
    '''
    input_population = spynnaker.Population(
        NUM_PN_CELLS,
        spynnaker.SpikeSourceArray(spike_times=time_space),
        label='PN_population')
    return input_population
        # Post after pre
        else:
            post_phase = 1 - t
            pre_phase = 0

    sim_time = max(sim_time, (num_pairs * time_between_pairs) + abs(t))

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

    # Stimulating populations
    pre_times = [i for i in range(pre_phase, sim_time, time_between_pairs)]
    post_times = [i for i in range(post_phase, sim_time, time_between_pairs)]
    pre_stim = sim.Population(
        1, sim.SpikeSourceArray(spike_times=[pre_times]))
    post_stim = sim.Population(
        1, sim.SpikeSourceArray(spike_times=[post_times]))

    weight = 0.035

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

    # Plastic Connection between pre_pop and post_pop
Exemple #5
0
            pre_phase = t
        # Post after pre
        else:
            post_phase = 1 - t
            pre_phase = 0

    sim_time = max(sim_time, (num_pairs * time_between_pairs) + abs(t))

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

    # Stimulating populations
    pre_times = [i for i in range(pre_phase, sim_time, time_between_pairs)]
    post_times = [i for i in range(post_phase, sim_time, time_between_pairs)]
    pre_stim = sim.Population(1, sim.SpikeSourceArray(spike_times=[pre_times]))
    post_stim = sim.Population(1,
                               sim.SpikeSourceArray(spike_times=[post_times]))

    weight = 2

    # Connections between spike sources and neuron populations
    ee_connector = sim.OneToOneConnector()
    sim.Projection(pre_stim,
                   pre_pop,
                   ee_connector,
                   receptor_type='excitatory',
                   synapse_type=sim.StaticSynapse(weight=weight))
    sim.Projection(post_stim,
                   post_pop,
                   ee_connector,
Exemple #6
0
    'i_offset': 0,
    'tau_m': 20,
    'tau_refrac': 2,
    'tau_syn_E': 50,
    'tau_syn_I': 5,
    'v_reset': -70,
    'v_rest': -65,
    'v_thresh': -55
}

sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100)

G1_1 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G1_1")
G2_2 = sim.Population(10, sim.IF_curr_exp(**cell_params_lif), label="G2_2")
GEN1_3 = sim.Population(
    1, sim.SpikeSourceArray(spike_times=[1, 2, 4, 6, 7], label="GEN1_3"))
G4_4 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G4_4")
Dani_5 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="Dani_5")
G5_6 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G5_6")
G6_7 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G6_7")

input_GEN1_3G1_1 = sim.Projection(GEN1_3,
                                  G1_1,
                                  sim.OneToOneConnector(),
                                  synapse_type=sim.StaticSynapse(weight=1.25,
                                                                 delay=0))
input_G2_2G1_1 = sim.Projection(G2_2,
                                G1_1,
                                sim.OneToOneConnector(),
                                synapse_type=sim.StaticSynapse(weight=0.8,
                                                               delay=0))
Exemple #7
0
            if i == 0:
                projections.append(
                    sim.Projection(input_layer, layers[i + 1],
                                   sim.FromFileConnector(filepath)))
                #projections.append(sim.Projection(input_layer, layers[i+1], sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=5, delay=1)))
            else:
                projections.append(
                    sim.Projection(layers[i], layers[i + 1],
                                   sim.FromFileConnector(filepath)))
    return layers, projections


sim.setup(timestep=1.0)
spike_times = [[i] for i in range(1296)]
input_pop = sim.Population(1296,
                           sim.SpikeSourceArray(spike_times=spike_times),
                           label="InputLayer")

#sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100)
layers, projections = load(path=PATH, filename=MODEL, input_layer=input_pop)

layers[1].record(["spikes", "v"])

simtime = 20
sim.run(simtime)

neo = layers[1].get_data(variables=["spikes", "v"])
spikes = neo.segments[0].spiketrains
print(spikes)
v = neo.segments[0].filter(name='v')[0]
print(v)
Exemple #8
0
    'i_offset': 0,
    'tau_m': 20,
    'tau_refrac': 2,
    'tau_syn_E': 50,
    'tau_syn_I': 5,
    'v_reset': -70,
    'v_rest': -65,
    'v_thresh': -55
}

sim.set_number_of_neurons_per_core(sim.IF_curr_exp, 100)

G1_1 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G1_1")
G2_2 = sim.Population(10, sim.IF_curr_exp(**cell_params_lif), label="G2_2")
GEN1_3 = sim.Population(
    1, sim.SpikeSourceArray(spike_times=[0, 8], label="GEN1_3"))
G4_4 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G4_4")
Dani_5 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="Dani_5")
G5_6 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G5_6")
G6_7 = sim.Population(1, sim.IF_curr_exp(**cell_params_lif), label="G6_7")

input_GEN1_3G1_1 = sim.Projection(GEN1_3,
                                  G1_1,
                                  sim.OneToOneConnector(),
                                  synapse_type=sim.StaticSynapse(weight=1.25,
                                                                 delay=1))
input_G2_2G1_1 = sim.Projection(G2_2,
                                G1_1,
                                sim.OneToOneConnector(),
                                synapse_type=sim.StaticSynapse(weight=0.8,
                                                               delay=1))
Exemple #9
0
spike_times, simtime = misc.extract_spiketimes_from_aedat(
    filepath,
    no_gaps=True,
    start_time=0,
    simtime=SIMTIME,
    eventframe_width=None)

sim.setup(timestep=1.0)

#first = [i for i in range(1000)]
#spike_times = [[i] for i in range(NR)]
#spike_times[0] = first
input_pop = sim.Population(
    size=NR,
    cellclass=sim.SpikeSourceArray(spike_times=spike_times),
    label="spikes")
pop_0 = sim.Population(size=NR,
                       cellclass=sim.IF_curr_exp(),
                       label="1_pre_input")
pop_0.set(v_thresh=0.1)
pop_1 = sim.Population(size=16, cellclass=sim.IF_curr_exp(), label="1_input")
pop_1.set(v_thresh=0.05)
#misc.set_cell_params(pop_1, cellparams)
pop_2 = sim.Population(size=4, cellclass=sim.IF_curr_exp(), label="2_hidden")
pop_2.set(v_thresh=0.1)
#misc.set_cell_params(pop_2, cellparams)
#pop_2.set(i_offset=s[label]['v_thresh'])

# this projection / pop_0 is only used to monitor the input spikes (actually not needed for MLP network)
input_proj = sim.Projection(input_pop,
Exemple #10
0
                               label="All Cells")
    exc_cells = all_cells[:n_exc]
    exc_cells.label = "Excitatory cells"

    inh_cells = all_cells[n_exc:]
    inh_cells.label = "Inhibitory cells"

    exc_cells_input_subset = exc_cells[:n_exc / 4]
    exc_cells_input_subset.label = "Excitatory cells Input subset"

    inh_cells_input_subset = inh_cells[:n_inh]
    inh_cells_input_subset.label = "Inhibitory cells Input subset"

    ext_stim_exc = sim.Population(
        n_stim,
        sim.SpikeSourceArray(spike_times=spike_times_train_up[i].tolist()),
        label="Input spike time array exitatory")
    ext_stim_inh = sim.Population(
        n_stim,
        sim.SpikeSourceArray(spike_times=spike_times_train_dn[i].tolist()),
        label="Input spike time array inhibitory")

    # stdp_mechanism = sim.STDPMechanism(
    #                     timing_dependence=sim.SpikePairRule(**synaptic_parameters['excitatory_stdp']['timing_dependence']),
    #                     weight_dependence=sim.AdditiveWeightDependence(**synaptic_parameters['excitatory_stdp']['weight_dependence']),
    #                     weight=synaptic_parameters['excitatory_stdp']['weight']
    #                     ,delay=synaptic_parameters['excitatory_stdp']['delay'],
    #     dendritic_delay_fraction=0

    # )
    # Determine the connectivity among the population of neuron
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
Exemple #12
0
    #pre_spikes.append(i*v+2)

runTime = (i + 1) * v
cell_params_lif = {
    'cm': 1,  #70
    'i_offset': 0.0,
    'tau_m': 20.0,  #20
    'tau_refrac': 10.0,  #2 more that t inhibit#10
    'tau_syn_E': 2.0,  #2
    'tau_syn_I': 10.0,  #5
    'v_reset': -70.0,
    'v_rest': -65.0,
    'v_thresh': -55.0
}

pre_cell = sim.SpikeSourceArray(pre_spikes)
post_cell = sim.SpikeSourceArray(post_spikes)
layer1 = sim.Population(1, pre_cell, label='inputspikes')
post = sim.Population(1,
                      sim.IF_curr_exp,
                      cellparams=cell_params_lif,
                      label='post')
layer2 = sim.Population(1, post_cell, label='outputspikes')

stim_proj = sim.Projection(layer2,
                           post,
                           sim.OneToOneConnector(),
                           synapse_type=sim.StaticSynapse(weight=7,
                                                          delay=0.25))

stdp = sim.STDPMechanism(
            str(prediction * (100 - current_poucentage)))
        current_poucentage += 1
    if (df['x'].iloc[i] % 4 == 0 & df['y'].iloc[i] % 4 == 0):
        x = df['x'].iloc[i]
        y = df['y'].iloc[i]
        time = df['ts'].iloc[i] * 1.e-3
        if (timemax < time):
            timemax = time
        index = y * x + x - 2
        sourceArray[index] = sourceArray[index] + [time]

# Pour la desambiguisation sur SpiNNaker
sourceArray = [list(elem) for elem in sourceArray]

# lancement d'un simulation ultra simple pour vérifier l'acceptation du spikeSourceArray
import pyNN.spiNNaker as sim
simulator = 'spinnaker'

sim.setup(timestep=10, min_delay=20, max_delay=30)

sources = sim.SpikeSourceArray(spike_times=sourceArray)
spikeSource = sim.Population(1024, sources)
spikeSource.record(['spikes'])

sim.run(simtime=10000)

spikeSources = spikeSource.get_data()  #.segments[0].spiketrains
S_spikes = spikeSources.segments[0].spiketrains

sim.end()
Exemple #14
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
Exemple #15
0
INHIBITORY = True           # use the MLP model with inhibitory synapses (negaitve weights)
output_spikes = []

if INHIBITORY:
    path = './model/dvs36_evtaccCOR_D16_B0_FLAT_30E/'
else:
    path = './model/dvs36_evtacc_D16_B0_FLAT_posW_10E/'
p1 = path + '01Dense_16'
p2 = path + '02Dense_4'


filepaths, labels = misc.get_sample_filepaths_and_labels('./data/aedat/balanced_100/')

sim.setup(timestep=1.0)

input_pop = sim.Population(size=1296, cellclass=sim.SpikeSourceArray(spike_times=[]), label="spikes")
# to measure input spiketrains introduce an additional population
if MEASUREMENTS:
    pop_0 = sim.Population(size=1296, cellclass=sim.IF_curr_exp(), label="1_pre_input")
    pop_0.set(v_thresh=0.1)
    input_proj = sim.Projection(input_pop, pop_0, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=3, delay=1))
pop_1 = sim.Population(size=16, cellclass=sim.IF_curr_exp(), label="1_input")
if INHIBITORY:
    pop_1.set(v_thresh=0.05)
else:
    pop_1.set(v_thresh=0.1)
pop_2 = sim.Population(size=4, cellclass=sim.IF_curr_exp(), label="2_hidden")
pop_2.set(v_thresh=0.1)


if INHIBITORY: