예제 #1
0
def setupProjection_PN_KC(pn_population,kc_population):

    connectionList = list()                                        # Connection list between PN and KC
    for each_kc_cell in xrange(NUM_KC_CELLS):

        count          = 6
        selectedCells = random.sample(xrange(NUM_PN_CELLS),count) 

        for each_pn_cell in selectedCells:
            single_coonection = (each_pn_cell,each_kc_cell)
            connectionList.append(single_coonection)

    pnkcProjection = spynnaker.Projection(pn_population,
                                          kc_population,
                                          spynnaker.FromListConnector(connectionList),
                                          spynnaker.StaticSynapse(weight=WEIGHT_PN_KC, delay=DELAY_PN_KC))
    return pnkcProjection
예제 #2
0
def setupProjection_PN_KC(pn_population, kc_population):

    WEIGHT_PN_KC = 5
    DELAY_PN_KC = 1.0
    NUM_KC_CELLS = 2000
    NUM_PN_CELLS = 784

    connectionList = list()  # Build up a connection list between PN and KC
    for each_kc_cell in xrange(NUM_KC_CELLS):

        count = random.randint(
            5, 7)  # How many pn_cells will connect to this kc_cell
        selectedCells = random.sample(
            xrange(NUM_PN_CELLS), count)  # Index of randomly selected PN cells

        for each_pn_cell in selectedCells:
            single_coonection = (each_pn_cell, each_kc_cell)
            connectionList.append(single_coonection)

    pnkcProjection = spynnaker.Projection(
        pn_population, kc_population,
        spynnaker.FromListConnector(connectionList),
        spynnaker.StaticSynapse(weight=WEIGHT_PN_KC, delay=DELAY_PN_KC))
    return pnkcProjection
예제 #3
0
try:
    import pyNN.spiNNaker as p
except Exception as e:
    import spynnaker8 as p

# set up the tools
p.setup(timestep=1.0, min_delay=1.0, max_delay=32.0)

# set up the virtual chip coordinates for the motor
connected_chip_coords = {'x': 0, 'y': 0}
link = 4

populations = list()
projections = list()

input_population = p.Population(6, p.SpikeSourcePoisson(rate=10))
control_population = p.Population(6, p.IF_curr_exp())
motor_device = p.Population(
    6, p.external_devices.MunichMotorDevice(spinnaker_link_id=0))

p.Projection(input_population,
             control_population,
             p.OneToOneConnector(),
             synapse_type=p.StaticSynapse(weight=5.0))

p.external_devices.activate_live_output_to(control_population, motor_device)

p.run(1000)
p.end()
예제 #4
0
# declare python code when received spikes for a timer tick
def receive_spikes(label, time, neuron_ids):
    for neuron_id in neuron_ids:
        print("Received spike at time {} from {}-{}"
              "".format(time, label, neuron_id))


p.setup(timestep=1.0)
p1 = p.Population(1, p.IF_curr_exp(), label="pop_1")
input_injector = p.Population(1, p.external_devices.SpikeInjector(),
                              label=INJECTOR_LABEL)
# set up python live spike connection
live_spikes_connection = p.external_devices.SpynnakerLiveSpikesConnection(
    receive_labels=[RECEIVER_LABEL])

# register python receiver with live spike connection
live_spikes_connection.add_receive_callback(RECEIVER_LABEL, receive_spikes)


input_proj = p.Projection(input, p1, p.OneToOneConnector(),
                          p.StaticSynapse(weight=5, delay=3))
p1.record(["spikes", "v"])

p.run(50)

neo = p1.get_data(["spikes", "v"])
spikes = neo.segments[0].spiketrains
print(spikes)
v = neo.segments[0].filter(name='v')[0]
print(v)
    'tau_syn_I': 2.5,
    'v_reset': -70.0,
    'v_rest': -65.0,
    'v_thresh': -55.0
}

neurons = sim.Population(100, sim.IF_cond_exp(**cell_params))
inputs = sim.Population(100, sim.SpikeSourcePoisson(rate=0.0))

# set input firing rates as a linear function of cell index
input_firing_rates = np.linspace(0.0, 1000.0, num=inputs.size)
inputs.set(rate=input_firing_rates)

# create one-to-one connections
wiring = sim.OneToOneConnector()
static_synapse = sim.StaticSynapse(weight=0.1, delay=2.0)
connections = sim.Projection(inputs, neurons, wiring, static_synapse)

# configure recording
neurons.record('spikes')

# run simulation
sim_duration = 10.0  # seconds
sim.run(sim_duration * 1000.0)

# retrieve recorded data
spike_counts = neurons.get_spike_counts()
print(spike_counts)
output_firing_rates = np.array(
    [value for (key, value) in sorted(spike_counts.items())]) / sim_duration
예제 #6
0
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))
input_G4_4G1_1 = sim.Projection(G4_4,
                                G1_1,
                                sim.OneToOneConnector(),
                                synapse_type=sim.StaticSynapse(weight=1.7,
                                                               delay=0))
input_Dani_5G1_1 = sim.Projection(Dani_5,
                                  G1_1,
                                  sim.OneToOneConnector(),
                                  synapse_type=sim.StaticSynapse(weight=1.3,
                                                                 delay=0))
예제 #7
0
                                                label=label)

    def get_outgoing_partition_constraints(self, partition):
        return [
            FixedKeyAndMaskConstraint([BaseKeyAndMask(0x12340000, 0xFFFF0000)])
        ]


class MySpiNNakerLinkDeviceDataHolder(DataHolder):
    def __init__(self, spinnaker_link_id, label=None):
        DataHolder.__init__(self, {
            "spinnaker_link_id": spinnaker_link_id,
            "label": label
        })

    @staticmethod
    def build_model():
        return MySpiNNakerLinkDevice


p.setup(1.0)

pop = p.Population(1, p.IF_curr_exp())
device = p.Population(1, MySpiNNakerLinkDeviceDataHolder(spinnaker_link_id=0))

p.Projection(device, pop, p.OneToOneConnector(), p.StaticSynapse(weight=1.0))

p.run(100)

p.end()
예제 #8
0
import pyNN.spiNNaker as sim
import pyNN.utility.plotting as plot
import matplotlib.pyplot as plt

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

# Define Input neuron
input = sim.Population(1, sim.SpikeSourcePoisson(), label="Input")

# Define output neuron
pop_1 = sim.Population(1,sim.IF_curr_exp(),label="pop_1")

# Connect Input Neuron with Output neuron
input_proj=sim.Projection(input,pop_1,sim.OneToOneConnector(),synapse_type=sim.StaticSynapse(weight=5,delay=1))

pop_1.record(["spikes","v"])
input.record(["spikes"])

simtime = 30000
sim.run(simtime)

# Input neuron
neo_input=input.get_data(variables=["spikes"])

spikes_input=neo_input.segments[0].spiketrains
print(spikes_input)
print( len(spikes_input[0]) )

# Pop1 neuron
neo_pop1=pop_1.get_data(variables=["spikes","v"])
예제 #9
0
파일: z4.py 프로젝트: ferper/nesimRT
		'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)

GEN1_1= sim.Population(1,simSpikeSourceArray(spike_times=[0,8], label="GEN1_1")
G1_2= sim.Population(1,sim.IF_curr_exp(**cell_params_lif), label="G1_2")
G3_4= sim.Population(1,sim.IF_curr_exp(**cell_params_lif), label="G3_4")
G4_5= sim.Population(1,sim.IF_curr_exp(**cell_params_lif), label="G4_5")
G2_6= sim.Population(1,sim.IF_curr_exp(**cell_params_lif), label="G2_6")

input_GEN1_1G1_2=sim.Projection(GEN1_1,G1_2, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=1.25, delay=0))
input_G4_5G1_2=sim.Projection(G4_5,G1_2, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=0.8, delay=0))
input_G4_5G3_4=sim.Projection(G4_5,G3_4, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=0.9, delay=0))
input_G2_6G4_5=sim.Projection(G2_6,G4_5, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=1, delay=0))
input_G1_2G2_6=sim.Projection(G1_2,G2_6, sim.OneToOneConnector(), synapse_type=sim.StaticSynapse(weight=1.6, delay=0))

GEN1_1.record(["spikes","v","gsyn_exc"])

simtime =50
sim.run(simtime)

neo = GEN1_1.get_data(variables=["spikes","v","gsync_exc"])
spikes = neo.segments[0].spiketrains
print spikes
v = neo.segments[0].filter(name='v')[0]
print v
예제 #10
0
def finalize_wiring(conn_ee, conn_ie, conn_ei, conn_ii):
    ii_srcs, ii_tgs = get_sets(conn_ii)
    ei_srcs, ei_tgs = get_sets(conn_ei)
    ee_srcs, ee_tgs = get_sets(conn_ee)
    ie_srcs, ie_tgs = get_sets(conn_ie)

    _ = con_check_one(conn_ee,ee_srcs, ee_tgs)
    _ = con_check_one(conn_ii,ii_srcs,ii_tgs)
    _ = con_check_one(conn_ei,ei_srcs,ei_tgs)
    _ = con_check_one(conn_ie,ie_srcs,ie_tgs)

    len_es_srcs = len(list(ee_srcs))


    # the network is dominated by inhibitory neurons, which is unusual for modellers.
    # Plot all the Projection pairs as a connection matrix (Excitatory and Inhibitory Connections)
    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)

    all_cells = sim.Population(len(index_exc)+len(index_inh), sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0))

    pop_exc = sim.PopulationView(all_cells,index_exc)
    pop_inh = sim.PopulationView(all_cells,index_inh)
    NEXC = len(index_exc)
    NINH = len(index_inh)
    # add random variation into Izhi parameters
    for pe in index_exc:
        pe = all_cells[pe]
        r = random.uniform(0.0, 1.0)
        pe.set_parameters(a=0.02, b=0.2, c=-65+15*r, d=8-r**2, i_offset=0)

    for pi in index_inh:
        pi = all_cells[pi]
        r = random.uniform(0.0, 1.0)
        pi.set_parameters(a=0.02+0.08*r, b=0.25-0.05*r, c=-65, d= 2, i_offset=0)

    [ all_cells[i].get_parameters() for i,_ in enumerate(all_cells) ]
    exc_syn = sim.StaticSynapse(weight = wg, delay=delay_distr)
    assert np.any(conn_ee.conn_list[:,0]) < len_es_srcs
    prj_exc_exc = sim.Projection(all_cells, all_cells, conn_ee, exc_syn, receptor_type='excitatory')
    prj_exc_inh = sim.Projection(all_cells, all_cells, conn_ei, exc_syn, receptor_type='excitatory')
    inh_syn = sim.StaticSynapse(weight = wg, delay=delay_distr)
    delay_distr = RandomDistribution('normal', [1, 100e-3], rng=rng)
    prj_inh_inh = sim.Projection(all_cells, all_cells, conn_ii, inh_syn, receptor_type='inhibitory')
    prj_inh_exc = sim.Projection(all_cells, all_cells, conn_ie, inh_syn, receptor_type='inhibitory')
    inh_distr = RandomDistribution('normal', [1, 2.1e-3], rng=rng)

    prj_change(prj_exc_exc,wg)
    prj_change(prj_exc_inh,wg)
    prj_change(prj_inh_exc,wg)
    prj_change(prj_inh_inh,wg)

    prj_check(prj_exc_exc)
    prj_check(prj_exc_inh)
    prj_check(prj_inh_exc)
    prj_check(prj_inh_inh)



    try:
        others = [prj_exc_exc, prj_exc_inh, inh_syn, prj_inh_inh, prj_inh_exc, inh_distr ]
    except:
        pass

    return ( all_cells, pop_exc, pop_inh, NEXC, NINH )

    all_cells, pop_exc, pop_inh, NEXC, NINH  = finalize_wiring(conn_ee, conn_ie, conn_ei, conn_ii)


    def run_network(current, tstop, all_cells, pop_exc, pop_inh, NEXC, NINH):
        noisee,noisei = current
        pop_exc.inject(noisee)
        pop_inh.inject(noisei)

        ##
        # Setup and run a simulation. Note there is no current injection into the neuron.
        # All cells in the network are in a quiescent state, so its not a surprise that xthere are no spikes
        ##

        arange = np.arange
        all_cells.record(['v','spikes'])  # , 'u'])
        all_cells.initialize(v=-65.0, u=-14.0)
        # === Run the simulation =====================================================
        #tstop = 2000.0
        all_cells.record("spikes")

        sim.run(tstop)
        vms = np.array(data.analogsignals[0].as_array().T)
        cleaned = []
        for i,vm in enumerate(vms):
            if np.max(vm) > 900.0 or np.min(vm) <- 900.0:
            else:
                cleaned.append(vm)
        vms = cleaned
                #vm = s#.as_array()[:,
        cnt = 0
        vm_spiking = []
        vm_not_spiking = []
        spike_trains = []
        binary_trains = []
        for spiketrain in data.spiketrains:
            y = np.ones_like(spiketrain) * spiketrain.annotations['source_id']
            # argument edges is the time interval you want to be considered.
            pspikes = pyspike.SpikeTrain(spiketrain,edges=(0,len(ass)))
            spike_trains.append(pspikes)
            if len(spiketrain) > max_spikes:
                max_spikes = len(spiketrain)

            if np.max(ass[spiketrain.annotations['source_id']]) > 0.0:
                vm_spiking.append(vms[spiketrain.annotations['source_id']])
            else:
                vm_not_spiking.append(vms[spiketrain.annotations['source_id']])
            cnt+= 1

        for spiketrain in data.spiketrains:
            x = conv.BinnedSpikeTrain(spiketrain, binsize=1 * pq.ms, t_start=0 * pq.s)
            binary_trains.append(x)
        end_floor = np.floor(float(mdf1.t_stop))
        dt = float(mdf1.t_stop) % end_floor
        data.t_start
        #v = mdf1.take_slice_of_analogsignalarray_by_unit()
        t_spike_axis = np.arange(float(mdf1.t_start), float(mdf1.t_stop), dt)

        return data,vms,binary_trains,t_spike_axis
예제 #11
0
                                tau_minus=20.0,
                                A_plus=0.5,
                                A_minus=0.5)
weight_rule = sim.AdditiveWeightDependence(w_max=25.0, w_min=0.0)
stdp_model = sim.STDPMechanism(timing_dependence=timing_rule,
                               weight_dependence=weight_rule,
                               weight=2.0,
                               delay=1)
stdp_projection = sim.Projection(pre_pop,
                                 post_pop,
                                 sim.OneToOneConnector(),
                                 synapse_type=stdp_model)
input_projection1 = sim.Projection(input1,
                                   pre_pop,
                                   sim.OneToOneConnector(),
                                   synapse_type=sim.StaticSynapse(weight=5,
                                                                  delay=1))

pre_pop.record(["spikes", "v"])
post_pop.record(["spikes", "v"])
simtime = 100

k = PyKeyboard()


def receive_spikes(label, time, neuron_ids):
    try:
        for neuron_id in neuron_ids:
            if str(neuron_id) is '0':
                print 'press right'
                k.press_key(k.right_key)
            if str(neuron_id) is '1':
예제 #12
0
def sim_runner(wg):

    #import pyNN.neuron as sim
    try:
        import pyNN.spiNNaker as sim
    except:
        import pyNN.neuron as sim

    nproc = sim.num_processes()
    node = sim.rank()
    print(nproc)

    #import mpi4py
    #threads  = sim.rank()
    threads = 1
    rngseed = 98765
    parallel_safe = False
    #extra = {'threads' : threads}

    # Get some hippocampus connectivity data, based on a conversation with
    # academic researchers on GH:
    # https://github.com/Hippocampome-Org/GraphTheory/issues?q=is%3Aissue+is%3Aclosed
    # scrape hippocamome connectivity data, that I intend to use to program neuromorphic hardware.
    # conditionally get files if they don't exist.

    # This is literally the starting point of the connection map
    path_xl = '_hybrid_connectivity_matrix_20171103_092033.xlsx'

    if not os.path.exists(path_xl):
        os.system(
            'wget https://github.com/Hippocampome-Org/GraphTheory/files/1657258/_hybrid_connectivity_matrix_20171103_092033.xlsx'
        )

    xl = pd.ExcelFile(path_xl)

    dfall = xl.parse()
    dfall.loc[0].keys()
    dfm = dfall.as_matrix()

    rcls = dfm[:, :1]  # real cell labels.
    rcls = rcls[1:]
    rcls = {k: v
            for k, v in enumerate(rcls)
            }  # real cell labels, cast to dictionary
    import pickle

    with open('cell_names.p', 'wb') as f:
        pickle.dump(rcls, f)
    pd.DataFrame(rcls).to_csv('cell_names.csv', index=False)

    filtered = dfm[:, 3:]
    filtered = filtered[1:]
    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)
    weight_distr = RandomDistribution('normal', [45, 1e-1], rng=rng)

    sanity_e = []
    sanity_i = []

    EElist = []
    IIlist = []
    EIlist = []
    IElist = []

    with open('wire_map_online.p', 'wb') as f:
        pickle.dump(filtered, f)

    for i, j in enumerate(filtered):
        for k, xaxis in enumerate(j):
            if xaxis == 1 or xaxis == 2:
                source = i
                sanity_e.append(i)
                target = k

            if xaxis == -1 or xaxis == -2:
                sanity_i.append(i)
                source = i
                target = k

    index_exc = list(set(sanity_e))
    index_inh = list(set(sanity_i))
    import pickle
    with open('cell_indexs.p', 'wb') as f:
        returned_list = [index_exc, index_inh]
        pickle.dump(returned_list, f)
    '''
    import numpy
    a = numpy.asarray(index_exc)
    numpy.savetxt('pickles/'+str(k)+'excitatory_nunber_labels.csv', a, delimiter=",")
    a = numpy.asarray(index_inh)
    numpy.savetxt('pickles/'+str(k)+'inhibitory_nunber_labels.csv', a, delimiter=",")
    '''
    for i, j in enumerate(filtered):
        for k, xaxis in enumerate(j):
            if xaxis == 1 or xaxis == 2:
                source = i
                sanity_e.append(i)
                target = k
                delay = delay_distr.next()
                weight = 1.0
                if target in index_inh:
                    EIlist.append((source, target, delay, weight))
                else:
                    EElist.append((source, target, delay, weight))

            if xaxis == -1 or xaxis == -2:
                sanity_i.append(i)

                source = i
                target = k
                delay = delay_distr.next()
                weight = 1.0
                if target in index_exc:
                    IElist.append((source, target, delay, weight))
                else:
                    IIlist.append((source, target, delay, weight))

    internal_conn_ee = sim.FromListConnector(EElist)
    ee = internal_conn_ee.conn_list

    ee_srcs = ee[:, 0]
    ee_tgs = ee[:, 1]

    internal_conn_ie = sim.FromListConnector(IElist)
    ie = internal_conn_ie.conn_list
    ie_srcs = set([int(e[0]) for e in ie])
    ie_tgs = set([int(e[1]) for e in ie])

    internal_conn_ei = sim.FromListConnector(EIlist)
    ei = internal_conn_ei.conn_list
    ei_srcs = set([int(e[0]) for e in ei])
    ei_tgs = set([int(e[1]) for e in ei])

    internal_conn_ii = sim.FromListConnector(IIlist)
    ii = internal_conn_ii.conn_list
    ii_srcs = set([int(e[0]) for e in ii])
    ii_tgs = set([int(e[1]) for e in ii])

    for e in internal_conn_ee.conn_list:
        assert e[0] in ee_srcs
        assert e[1] in ee_tgs

    for i in internal_conn_ii.conn_list:
        assert i[0] in ii_srcs
        assert i[1] in ii_tgs

    ml = len(filtered[1]) + 1
    pre_exc = []
    post_exc = []
    pre_inh = []
    post_inh = []

    rng = NumpyRNG(seed=64754)
    delay_distr = RandomDistribution('normal', [2, 1e-1], rng=rng)

    plot_EE = np.zeros(shape=(ml, ml), dtype=bool)
    plot_II = np.zeros(shape=(ml, ml), dtype=bool)
    plot_EI = np.zeros(shape=(ml, ml), dtype=bool)
    plot_IE = np.zeros(shape=(ml, ml), dtype=bool)

    for i in EElist:
        plot_EE[i[0], i[1]] = int(0)
        if i[0] != i[1]:  # exclude self connections
            plot_EE[i[0], i[1]] = int(1)
            pre_exc.append(i[0])
            post_exc.append(i[1])

    assert len(pre_exc) == len(post_exc)
    for i in IIlist:
        plot_II[i[0], i[1]] = int(0)
        if i[0] != i[1]:
            plot_II[i[0], i[1]] = int(1)
            pre_inh.append(i[0])
            post_inh.append(i[1])

    for i in IElist:
        plot_IE[i[0], i[1]] = int(0)
        if i[0] != i[1]:  # exclude self connections
            plot_IE[i[0], i[1]] = int(1)
            pre_inh.append(i[0])
            post_inh.append(i[1])

    for i in EIlist:
        plot_EI[i[0], i[1]] = int(0)
        if i[0] != i[1]:
            plot_EI[i[0], i[1]] = int(1)
            pre_exc.append(i[0])
            post_exc.append(i[1])

    plot_excit = plot_EI + plot_EE
    plot_inhib = plot_IE + plot_II

    assert len(pre_inh) == len(post_inh)

    num_exc = [i for i, e in enumerate(plot_excit) if sum(e) > 0]
    num_inh = [y for y, i in enumerate(plot_inhib) if sum(i) > 0]

    # the network is dominated by inhibitory neurons, which is unusual for modellers.
    assert num_inh > num_exc
    assert np.sum(plot_inhib) > np.sum(plot_excit)
    assert len(num_exc) < ml
    assert len(num_inh) < ml
    # # Plot all the Projection pairs as a connection matrix (Excitatory and Inhibitory Connections)

    nproc = sim.num_processes()
    nproc = 8
    host_name = socket.gethostname()
    node_id = sim.setup(timestep=0.01, min_delay=1.0)  #, **extra)
    print("Host #%d is on %s" % (node_id + 1, host_name))
    rng = NumpyRNG(seed=64754)

    all_cells = sim.Population(
        len(index_exc) + len(index_inh),
        sim.Izhikevich(a=0.02, b=0.2, c=-65, d=8, i_offset=0))
    pop_exc = sim.PopulationView(all_cells, index_exc)
    pop_inh = sim.PopulationView(all_cells, index_inh)

    for pe in pop_exc:
        pe = all_cells[pe]
        r = random.uniform(0.0, 1.0)
        pe.set_parameters(a=0.02,
                          b=0.2,
                          c=-65 + 15 * r,
                          d=8 - r**2,
                          i_offset=0)

    for pi in index_inh:
        pi = all_cells[pi]
        r = random.uniform(0.0, 1.0)
        pi.set_parameters(a=0.02 + 0.08 * r,
                          b=0.25 - 0.05 * r,
                          c=-65,
                          d=2,
                          i_offset=0)

    NEXC = len(num_exc)
    NINH = len(num_inh)

    exc_syn = sim.StaticSynapse(weight=wg, delay=delay_distr)
    assert np.any(internal_conn_ee.conn_list[:, 0]) < ee_srcs.size
    prj_exc_exc = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ee,
                                 exc_syn,
                                 receptor_type='excitatory')
    prj_exc_inh = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ei,
                                 exc_syn,
                                 receptor_type='excitatory')
    inh_syn = sim.StaticSynapse(weight=wg, delay=delay_distr)
    delay_distr = RandomDistribution('normal', [1, 100e-3], rng=rng)
    prj_inh_inh = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ii,
                                 inh_syn,
                                 receptor_type='inhibitory')
    prj_inh_exc = sim.Projection(all_cells,
                                 all_cells,
                                 internal_conn_ie,
                                 inh_syn,
                                 receptor_type='inhibitory')
    inh_distr = RandomDistribution('normal', [1, 2.1e-3], rng=rng)

    ext_Connector = OneToOneConnector(callback=progress_bar)
    ext_syn = StaticSynapse(weight=JE, delay=dt)
    '''
    print("%d Connecting excitatory population with connection probability %g, weight %g nA and delay %g ms." % (rank, epsilon, JE, delay))
    E_to_E = Projection(E_net, E_net, connector, E_syn, receptor_type="excitatory")
    print("E --> E\t\t", len(E_to_E), "connections")
    I_to_E = Projection(I_net, E_net, connector, I_syn, receptor_type="inhibitory")
    print("I --> E\t\t", len(I_to_E), "connections")
    input_to_E = Projection(expoisson, E_net, ext_Connector, ext_syn, receptor_type="excitatory")
    print("input --> E\t", len(input_to_E), "connections")

    print("%d Connecting inhibitory population with connection probability %g, weight %g nA and delay %g ms." % (rank, epsilon, JI, delay))
    E_to_I = Projection(E_net, I_net, connector, E_syn, receptor_type="excitatory")
    print("E --> I\t\t", len(E_to_I), "connections")
    I_to_I = Projection(I_net, I_net, connector, I_syn, receptor_type="inhibitory")
    print("I --> I\t\t", len(I_to_I), "connections")
    input_to_I = Projection(inpoisson, I_net, ext_Connector, ext_syn, receptor_type="excitatory")
    print("input --> I\t", len(input_to_I), "connections")
    '''
    def prj_change(prj, wg):
        prj.setWeights(wg)

    prj_change(prj_exc_exc, wg)
    prj_change(prj_exc_inh, wg)
    prj_change(prj_inh_exc, wg)
    prj_change(prj_inh_inh, wg)

    def prj_check(prj):
        for w in prj.weightHistogram():
            for i in w:
                print(i)

    prj_check(prj_exc_exc)
    prj_check(prj_exc_inh)
    prj_check(prj_inh_exc)
    prj_check(prj_inh_inh)

    #print(rheobase['value'])
    #print(float(rheobase['value']),1.25/1000.0)
    '''Old values that worked
    noise = sim.NoisyCurrentSource(mean=0.85/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_exc.inject(noise)
    #1000.0 pA


    noise = sim.NoisyCurrentSource(mean=1.740/1000.0, stdev=5.00/1000.0, start=0.0, stop=2000.0, dt=1.0)
    pop_inh.inject(noise)
    #1750.0 pA
    '''

    noise = sim.NoisyCurrentSource(mean=0.74 / 1000.0,
                                   stdev=4.00 / 1000.0,
                                   start=0.0,
                                   stop=2000.0,
                                   dt=1.0)
    pop_exc.inject(noise)
    #1000.0 pA

    noise = sim.NoisyCurrentSource(mean=1.440 / 1000.0,
                                   stdev=4.00 / 1000.0,
                                   start=0.0,
                                   stop=2000.0,
                                   dt=1.0)
    pop_inh.inject(noise)

    ##
    # Setup and run a simulation. Note there is no current injection into the neuron.
    # All cells in the network are in a quiescent state, so its not a surprise that xthere are no spikes
    ##

    sim = pyNN.neuron
    arange = np.arange
    import re
    all_cells.record(['v', 'spikes'])  # , 'u'])
    all_cells.initialize(v=-65.0, u=-14.0)
    # === Run the simulation =====================================================
    tstop = 2000.0
    sim.run(tstop)
    data = None
    data = all_cells.get_data().segments[0]

    if not os.path.exists("pickles"):
        os.mkdir("pickles")

    #print(len(data.analogsignals[0].times))
    with open('pickles/qi' + str(wg) + '.p', 'wb') as f:
        pickle.dump(data, f)
    # make data none or else it will grow in a loop
    all_cells = None
    data = None
    noise = None
예제 #13
0
    array_connectivity_small_world_exc_inh = sim.ArrayConnector(
        connection_matrix_small_world_exc_inh)
    array_connectivity_small_world_inh_exc = sim.ArrayConnector(
        connection_matrix_small_world_inh_exc)

    input_connectivity_exc = sim.FixedNumberPostConnector(
        **connectivity_parameters['input_exc'])
    input_connectivity_inh = sim.FixedNumberPostConnector(
        **connectivity_parameters['input_inh'])

    input_exc_exc_connections = sim.Projection(
        ext_stim_exc,
        exc_cells_input_subset,
        input_connectivity_exc,
        receptor_type='excitatory',
        synapse_type=sim.StaticSynapse(**synaptic_parameters['input']),
        label='Input connections')

    input_inh_inh_connections = sim.Projection(
        ext_stim_inh,
        inh_cells_input_subset,
        input_connectivity_inh,
        receptor_type='excitatory',
        synapse_type=sim.StaticSynapse(**synaptic_parameters['input']),
        label='Input connections')

    exc_exc_connections = sim.Projection(
        exc_cells,
        exc_cells,
        array_connectivity_small_world_exc_exc,
        receptor_type='excitatory',
예제 #14
0
connected_chip_details = {
    "spinnaker_link_id": 0,
}


def get_updated_params(params):
    params.update(connected_chip_details)
    return params


# Setup
p.setup(timestep=1.0)

# FPGA Retina - Down Polarity
retina_pop = p.Population(
    None, p.external_devices.ExternalFPGARetinaDevice, get_updated_params({
        'retina_key': 0x5,
        'mode': p.external_devices.ExternalFPGARetinaDevice.MODE_128,
        'polarity': (
            p.external_devices.ExternalFPGARetinaDevice.DOWN_POLARITY)}),
    label='External retina')

population = p.Population(256, p.IF_curr_exp(), label='pop_1')
p.Projection(
    retina_pop, population, p.FixedProbabilityConnector(0.1),
    synapse_type=p.StaticSynapse(weight=0.1))

# q.activate_live_output_for(population)
p.run(1000)
p.end()
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
예제 #16
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(
    weight=0,
    #weight=0.02,  # this is the initial value of the weight
    #delay="0.2 + 0.01*d",
    timing_dependence=sim.SpikePairRule(tau_plus=30,
                                        tau_minus=10,
                                        A_plus=0.5,
                                        A_minus=0.5),
    #weight_dependence=sim.MultiplicativeWeightDependence(w_min=wMin, w_max=wMax),
    weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=5),
    #weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.4),
    dendritic_delay_fraction=1.0)

stdp_proj = sim.Projection(layer1,
예제 #17
0
def train(spikeTimes,untrained_weights=None):
    organisedStim = {}
    labelSpikes = []
    #spikeTimes = generate_data()


        #for j in range(5):
        #    labelSpikes
        
    #labelSpikes[label] = [(input_len-1)*v_co+1,(input_len-1)*v_co*2+1,(input_len-1)*v_co*3+1,]
    
    
    if untrained_weights == None:
        untrained_weights = RandomDistribution('uniform', low=wMin, high=wMaxInit).next(input_size*output_size)
        #untrained_weights = RandomDistribution('normal_clipped', mu=0.1, sigma=0.05, low=wMin, high=wMaxInit).next(input_size*output_size)
        untrained_weights = np.around(untrained_weights, 3)
        #saveWeights(untrained_weights, 'untrained_weightssupmodel1traj')
        print ("init!")

    print "length untrained_weights :", len(untrained_weights)

    if len(untrained_weights)>input_size:
        training_weights = [[0 for j in range(output_size)] for i in range(input_size)] #np array? size 1024x25
        k=0
        for i in range(input_size):
            for j in range(output_size):
                training_weights[i][j] = untrained_weights[k]
                k += 1
    else:
        training_weights = untrained_weights

    connections = []
    for n_pre in range(input_size): # len(untrained_weights) = input_size
        for n_post in range(output_size): # len(untrained_weight[0]) = output_size; 0 or any n_pre
            connections.append((n_pre, n_post, training_weights[n_pre][n_post], __delay__)) #index
    runTime = int(max(max(spikeTimes))/3)+100
    #####################
    sim.setup(timestep=1)
    #def populations
    layer1=sim.Population(input_size,sim.SpikeSourceArray, {'spike_times': spikeTimes},label='inputspikes')
    layer2=sim.Population(output_size,sim.IF_curr_exp,cellparams=cell_params_lif,label='outputspikes')
    #supsignal=sim.Population(output_size,sim.SpikeSourceArray, {'spike_times': labelSpikes},label='supersignal')

    #def learning rule
    stdp = sim.STDPMechanism(
                            weight=untrained_weights,
                            #weight=0.02,  # this is the initial value of the weight
                            #delay="0.2 + 0.01*d",
                            timing_dependence=sim.SpikePairRule(tau_plus=tauPlus, tau_minus=tauMinus,A_plus=aPlus, A_minus=aMinus),
                            #weight_dependence=sim.MultiplicativeWeightDependence(w_min=wMin, w_max=wMax),
                            weight_dependence=sim.AdditiveWeightDependence(w_min=wMin, w_max=wMax),
                            #weight_dependence=sim.AdditiveWeightDependence(w_min=0, w_max=0.4),
                            dendritic_delay_fraction=1.0)
    #def projections

    #stdp_proj = sim.Projection(layer1, layer2, sim.FromListConnector(connections), synapse_type=stdp)
    stdp_proj = sim.Projection(layer1, layer2, sim.AllToAllConnector(), synapse_type=stdp)
    inhibitory_connections = sim.Projection(layer2, layer2, sim.AllToAllConnector(allow_self_connections=False), 
                                            synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__), 
                                            receptor_type='inhibitory')
    #stim_proj = sim.Projection(supsignal, layer2, sim.OneToOneConnector(), 
    #                            synapse_type=sim.StaticSynapse(weight=stimWeight, delay=__delay__))
    
    layer1.record(['spikes'])

    layer2.record(['v','spikes'])
    #supsignal.record(['spikes'])
    sim.run(runTime)

    print("Weights:{}".format(stdp_proj.get('weight', 'list')))

    weight_list = [stdp_proj.get('weight', 'list'), stdp_proj.get('weight', format='list', with_address=False)]
    neo = layer2.get_data(["spikes", "v"])
    spikes = neo.segments[0].spiketrains
    v = neo.segments[0].filter(name='v')[0]
    #neostim = supsignal.get_data(["spikes"])
    #spikestim = neostim.segments[0].spiketrains
    neoinput= layer1.get_data(["spikes"])
    spikesinput = neoinput.segments[0].spiketrains

    plt.close('all')
    pplt.Figure(
    pplt.Panel(spikesinput,xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(a) Spikes of Input Layer'),
    #pplt.Panel(spikestim, xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(c) Spikes of Supervised Layer'),
    pplt.Panel(spikes, xticks=True, xlabel="(b) Spikes of Output Layer", yticks=True, markersize=2, xlim=(0,runTime)),
    pplt.Panel(v, ylabel="Membrane potential (mV)", xticks=True, yticks=True, xlim=(0,runTime),xlabel='(c) Membrane Potential of Output Layer\nTime (ms)'),
    title="Two Training",
    annotations="Twoway Training"
                ).save('SNN_DVS_un/plot_for_twoway/'+str(trylabel)+'_training.png')
    #plt.hist(weight_list[1], bins=100)
    
    plt.close('all')
    plt.hist([weight_list[1][0:input_size], weight_list[1][input_size:input_size*2], weight_list[1][input_size*2:]], bins=20, label=['neuron 0', 'neuron 1', 'neuron 2'], range=(0, wMax))
    plt.title('weight distribution')
    plt.xlabel('Weight value')
    plt.ylabel('Weight count')
    #plt.show()
    #plt.show()
                
    sim.end()
    return weight_list[1]
    # 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
    stdp_model = sim.STDPMechanism(
        timing_dependence=sim.SpikePairRule(
            tau_plus=16.7, tau_minus=33.7, A_plus=0.005, A_minus=0.005),
        weight_dependence=sim.AdditiveWeightDependence(
            w_min=0.0, w_max=0.0175), weight=start_w)

    projections.append(sim.Projection(
        pre_pop, post_pop, sim.OneToOneConnector(),
        synapse_type=stdp_model))
예제 #19
0
def test(spikeTimes,trained_weights):

    #spikeTimes = extractSpikes(sample)
    runTime = int(max(max(spikeTimes)))+100

    ##########################################

    sim.setup(timestep=1)

    pre_pop = sim.Population(input_size, sim.SpikeSourceArray, {'spike_times': spikeTimes}, label="pre_pop")
    post_pop = sim.Population(output_size, sim.IF_curr_exp , cell_params_lif, label="post_pop")
   
    if len(trained_weights) > input_size:
        weigths = [[0 for j in range(output_size)] for i in range(input_size)] #np array? size 1024x25
        k=0
        for i in range(input_size):
            for j in range(output_size):
                weigths[i][j] = trained_weights[k]
                k += 1
    else:
        weigths = trained_weights

    connections = []
    
    #k = 0
    for n_pre in range(input_size): # len(untrained_weights) = input_size
        for n_post in range(output_size): # len(untrained_weight[0]) = output_size; 0 or any n_pre
            #connections.append((n_pre, n_post, weigths[n_pre][n_post]*(wMax), __delay__))
            connections.append((n_pre, n_post, weigths[n_pre][n_post]*(wMax)/max(trained_weights), __delay__)) 
            #connections.append((n_pre, n_post, min(weigths[n_pre][n_post],0.2), __delay__)) 
            #connections.append((n_pre, n_post, weigths[n_pre][n_post]*(1)/max(trained_weights), __delay__))#
            #k += 1

    prepost_proj = sim.Projection(pre_pop, post_pop, sim.FromListConnector(connections), synapse_type=sim.StaticSynapse(), receptor_type='excitatory') # no more learning !!
    inhib_proj = sim.Projection(post_pop, post_pop, sim.AllToAllConnector(), synapse_type=sim.StaticSynapse(weight=inhibWeight, delay=__delay__), receptor_type='inhibitory')
    # no more lateral inhib
    pre_pop.record(['spikes'])
    post_pop.record(['v', 'spikes'])
    sim.run(runTime)

    neo = post_pop.get_data(['v', 'spikes'])
    spikes = neo.segments[0].spiketrains
    v = neo.segments[0].filter(name='v')[0]
    neoinput= pre_pop.get_data(["spikes"])
    spikesinput = neoinput.segments[0].spiketrains
    plt.close('all')
    pplt.Figure(
    # plot voltage 
    
    # raster plot
    pplt.Panel(spikesinput,xticks=True, yticks=True, markersize=2, xlim=(0,runTime),xlabel='(a) Spikes of Input Layer'),
    pplt.Panel(spikes, xlabel="(b) Spikes of Output Layer", xticks=True, yticks=True, markersize=2, xlim=(0, runTime+100)),
    pplt.Panel(v, ylabel="Membrane potential (mV)", xticks=True, yticks=True, xlim=(0, runTime+100),xlabel='(c) Membrane Potential of Output Layer\nTime (ms)'),
    title='Twoway Test'#,
    #annotations='T'
                ).save('SNN_DVS_un/plot_for_twoway/'+str(trylabel)+'_test2.png')
    #f1.fig.texts=[]
    print("Weights:{}".format(prepost_proj.get('weight', 'list')))

    weight_list = [prepost_proj.get('weight', 'list'), prepost_proj.get('weight', format='list', with_address=False)]
    #predict_label=
    sim.end()
    return spikes
예제 #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
sim.external_devices.activate_live_output_for(actorPopulation, database_notify_host="localhost", database_notify_port_num=20000)
sim.external_devices.activate_live_output_for(actorSpikeInjector, database_notify_host="localhost", database_notify_port_num=20002)
sim.external_devices.activate_live_output_for(firstSpikeTrigger, database_notify_host="localhost", database_notify_port_num=20004)

timing_rule = sim.SpikePairRule(tau_plus=50.0, tau_minus=50.0,
                                A_plus=0.001, A_minus=0.001)
weight_rule = sim.AdditiveWeightDependence(w_max=5.0, w_min=-5.0)
stdp_model = sim.STDPMechanism(timing_dependence=timing_rule,
                               weight_dependence=weight_rule,
                               weight=2, delay=1)

stdp_projection = sim.Projection(statePopulation, actorPopulation, sim.OneToOneConnector(),
                                 synapse_type=stdp_model)

state_projection = sim.Projection(stateSpikeInjector, statePopulation, sim.OneToOneConnector(),
                                  synapse_type=sim.StaticSynapse(weight=5, delay=2))

actorProjection = sim.Projection(actorSpikeInjector, actorPopulation, sim.OneToOneConnector(),
                                 synapse_type=sim.StaticSynapse(weight=5, delay=0))

connectionList = []

for step in range(numberOfSteps-1):
    for action in range(numberOfActions):
        connectionList.append((action, action + numberOfActions))

moves_projection = sim.Projection(actorPopulation, actorPopulation, sim.FromListConnector(connectionList),
                                  synapse_type=sim.StaticSynapse(weight=5, delay=2))

connectionList = []
예제 #22
0
    def device_control_uses_payload(self):
        return True

    @property
    def device_control_timesteps_between_sending(self):
        return 10

    @property
    def device_control_partition_id(self):
        return "MySpiNNakerLinkDevice"


p.setup(1.0)

pop = p.Population(1, p.SpikeSourcePoisson(rate=100))
spinnaker_link_device_control = p.external_devices.ExternalDeviceLifControl(
    devices=[MySpiNNakerLinkDevice(n_atoms=1, spinnaker_link_id=1)],
    create_edges=True)
spinnaker_link_device = p.Population(1, spinnaker_link_device_control)

spinnaker_link_device.record("v")

p.Projection(pop, spinnaker_link_device, p.OneToOneConnector(),
             p.StaticSynapse(weight=1.0))

p.run(1000)

print spinnaker_link_device.get_data("v").segments[0].filter(name='v')

p.end()
예제 #23
0
# +-------------------------------------------------------------------+
# | Creation of connections                                           |
# +-------------------------------------------------------------------+

# Connection parameters
JEE = 3.

# Connection type between noise poisson generator and excitatory populations
ee_connector = sim.OneToOneConnector()

# Noise projections
sim.Projection(INoisePre,
               pre_pop,
               ee_connector,
               receptor_type='excitatory',
               synapse_type=sim.StaticSynapse(weight=JEE * 0.05))
sim.Projection(INoisePost,
               post_pop,
               ee_connector,
               receptor_type='excitatory',
               synapse_type=sim.StaticSynapse(weight=JEE * 0.05))

# Additional Inputs projections
for i in range(len(IAddPre)):
    sim.Projection(IAddPre[i],
                   pre_pop,
                   ee_connector,
                   receptor_type='excitatory',
                   synapse_type=sim.StaticSynapse(weight=JEE * 0.05))
for i in range(len(IAddPost)):
    sim.Projection(IAddPost[i],
else:
    LGNBright, LGNDark, V1, V2, V4Bright, V4Dark = network

LGNBright.record("spikes")
LGNDark.record("spikes")
V1.record("spikes")
V2.record("spikes")
V4Bright.record("spikes")
V4Dark.record("spikes")
if inputPoisson:
    LGNBrightInput = sim.Population(ImageNumPixelRows * ImageNumPixelColumns,
                                    sim.SpikeSourcePoisson())
    LGNDarkInput = sim.Population(ImageNumPixelRows * ImageNumPixelColumns,
                                  sim.SpikeSourcePoisson())
    sim.Projection(LGNBrightInput, LGNBright, sim.OneToOneConnector(),
                   sim.StaticSynapse(weight=connections['brightInputToLGN']))
    sim.Projection(LGNDarkInput, LGNDark, sim.OneToOneConnector(),
                   sim.StaticSynapse(weight=connections['darkInputToLGN']))
if numSegmentationLayers > 1:
    if useBoundarySegmentation:
        # BoundarySegmentationOnInter3.inject(sim.DCSource(amplitude=constantInput, start=0.0, stop=simTime))
        BoundarySegmentationOnInter3.set('i_offset', 0.5)

########################################################################################
### Network is defined, now set up stimulus, segmentation signal and run everything! ###
########################################################################################

# Stuff to plot activity of LGN, V1, V2, etc. layers
cumplotDensityLGNBright = [[0 for j in range(ImageNumPixelColumns)]
                           for i in range(ImageNumPixelRows)]
cumplotDensityLGNDark = [[0 for j in range(ImageNumPixelColumns)]