예제 #1
0
def main(args):

    setup(timestep=0.1)

    random_image = np.random.rand(2,2)
    size = random_image.size


    input_population_arr = Population(random_image.size, SpikeSourceArray, {'spike_times': [0 for i in range(0, random_image.size)]})

    cell_params = {'tau_refrac': 2.0, 'v_thresh': -50.0, 'tau_syn_E': 2.0, 'tau_syn_I': 2.0}
    output_population = Population(1, IF_curr_alpha, cell_params, label="output")

    projection = Projection(input_population_arr, output_population, AllToAllConnector())
    projection.setWeights(1.0)

    input_population_arr.record('spikes')
    output_population.record('spikes')

    tstop = 1000.0

    run(tstop)

    output_population.write_data("simpleNetwork_output.pkl",'spikes')
    input_population_arr.write_data("simpleNetwork_input.pkl",'spikes')
    #output_population.print_v("simpleNetwork.v")
    end()
예제 #2
0
def main():
    # setup timestep of simulation and minimum and maximum synaptic delays
    setup(timestep=simulationTimestep, min_delay=minSynapseDelay, max_delay=maxSynapseDelay)
    
    # create a spike sources
    retinaLeft = createSpikeSource("Retina Left")
    retinaRight = createSpikeSource("Retina Right")
    
    # create network and attach the spike sources 
    network = createCooperativeNetwork(retinaLeft=retinaLeft, retinaRight=retinaRight)
    
    # run simulation for time in milliseconds
    print "Simulation started..."
    run(simulationTime)
    print "Simulation ended."
    # plot results 
    from itertools import repeat
    numberOfLayersToPlot = 4
    layers = zip(repeat(network, numberOfLayersToPlot), range(1, numberOfLayersToPlot+1), repeat(False, numberOfLayersToPlot))
    customLayers = [(network, 20, False),(network, 40, False),(network, 60, False),(network, 80, False)]
    for proc in range(0, numberOfLayersToPlot):
        p = Process(target=plotSimulationResults, args=customLayers[proc])
        p.start()
    
    # finalise program and simulation
    end()
예제 #3
0
def run_sim(ncell):

    print "Cells: ", ncell

    setup0 = time.time()

    sim.setup(timestep=0.1)

    hh_cell_type = sim.HH_cond_exp()

    hh = sim.Population(ncell, hh_cell_type)

    pulse = sim.DCSource(amplitude=0.5, start=20.0, stop=80.0)
    pulse.inject_into(hh)

    hh.record('v')

    setup1 = time.time()

    t0 = time.time()

    sim.run(100.0)

    v = hh.get_data()

    sim.end()

    t1 = time.time()

    setup_total = setup1 - setup0
    run_total = t1 - t0
    print "Setup: ", setup_total
    print "Run: ", run_total
    print "Total sim time: ", setup_total + run_total
    return run_total
def train_weights(feature_dir):
    """
    Trains the basic recognizer weights such that they respond to the features
    found in the directory feature_dir. This function runs a sim.start() -
    sim.end() "session".

    Arguments:

        `feature_dir`: The directory where the features are stored as images

    Returns:

        A pair of weight and feature image dictionaries of the following type:
            weights_dict        :: feature name string -> (weights, shape)
            feature_imgs_dict   :: feature name string -> feature image
    """
    sim.setup()
    weights_dict = {}  # feature name string -> (weights, shape)
    feature_imgs_dict = {}  # feature name string -> feature image
    for training_img in plb.Path(feature_dir).iterdir():
        feature_np_array = cv2.imread(training_img.as_posix(), cv2.CV_8U)
        feature_imgs_dict[training_img.stem] = feature_np_array
        weights = recognizer_weights_from(feature_np_array)
        weights_dict[training_img.stem] = (weights, feature_np_array.shape)
    sim.end()
    return (weights_dict, feature_imgs_dict)
예제 #5
0
def scnn_test(cell_params_lif, l_cnn, w_cnn, num_test, test, max_rate,
              dur_test, silence):
    p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0)
    L = l_cnn
    random.seed(0)
    input_size = L[0][1]
    pops_list = []
    pops_list.append(
        init_inputlayer(input_size, test[:num_test, :], max_rate, dur_test,
                        silence))
    print('SCNN constructing...')
    for l in range(len(w_cnn)):
        pops_list.append(
            construct_layer(cell_params_lif, pops_list[l], L[l + 1][0],
                            L[l + 1][1], w_cnn[l]))
    result = pops_list[-1][0]
    result.record(['v', 'spikes'])  # new

    print('SCNN running...')
    p.run((dur_test + silence) * num_test)
    spike_result = result.getSpikes(compatible_output=True)
    #spike_result = result.get_spike_counts(gather=True) #tuple datta
    #spike_result = result.get_data('spikes')
    p.end()

    print('analysing...')
    spike_result_count = count_spikes(spike_result, 10, num_test, dur_test,
                                      silence)
    print("spike_result_count : ", spike_result_count)
    predict = np.argmax(spike_result_count, axis=0)
    print("predict : ", predict)

    #     prob = np.exp(spike_result_count)/np.sum(np.exp(spike_result_count), axis=0)
    return predict, spike_result
예제 #6
0
def two_neuron_example(
    current=1000.0,
    time_simulation=2000.0,
    weight=0.4,
    neuron_parameters={"v_rest": -50.0, "cm": 1, "tau_m": 20.0, "tau_refrac": 5.0, "v_thresh": -40.0, "v_reset": -50.0},
):

    sim.setup(timestep=0.1, min_delay=0.1)

    pulse = sim.DCSource(amplitude=current, start=0.0, stop=time_simulation)

    pre = sim.Population(1, sim.IF_curr_exp(**neuron_parameters))

    pre.record("spikes")

    pulse.inject_into(pre)

    sim.run(time_simulation)

    # rates in Hz
    rate_pre = len(pre.get_data("spikes").segments[0].spiketrains[0]) / time_simulation * 1000.0

    sim.end()

    return rate_pre
예제 #7
0
def two_neuron_example(
        current=1000.0,
        time_simulation=2000.,
        weight=0.4,
        neuron_parameters={
            'v_rest'     : -65.0,
            'cm'         : 0.1,
            'tau_m'      : 1.0,
            'tau_refrac' : 2.0,
            'tau_syn_E'  : 10.0,
            'tau_syn_I'  : 10.0,
            'i_offset'   : 0.0,
            'v_reset'    : -65.0,
            'v_thresh'   : -50.0,
        },
    ):
    """
        Connects to neurons with corresponding parameters.

        The first is stimulated via current injection while the second receives
        the other one's spikes.
    """

    sim.setup(timestep=0.1, min_delay=0.1)

    pulse = sim.DCSource(amplitude=current, start=0.0, stop=time_simulation)

    pre = sim.Population(1, sim.IF_curr_exp(**neuron_parameters))
    post = sim.Population(1, sim.IF_curr_exp(**neuron_parameters))

    pre.record('spikes')
    post.record('spikes')

    sim.Projection(pre, post, connector=sim.OneToOneConnector(),
            synapse_type=sim.StaticSynapse(weight=weight),
            receptor_type='excitatory')

    pulse.inject_into(pre)

    sim.run(time_simulation)

    # rates in Hz
    rate_pre = len(pre.get_data('spikes').segments[0].spiketrains[0])\
            / time_simulation * 1000.

    rate_post = len(post.get_data('spikes').segments[0].spiketrains[0])\
            / time_simulation * 1000.

    sim.end()

    return rate_pre, rate_post
    def _reset(self, seed):
        '''
        Reset simulator and seed the PRNGs.

        Parameters
        ----------
            seed: PRNG seed value.
        '''

        sim.end()
        sim.setup()

        # Set PRNG seed values:
        if seed is None:
            seed = rnd.randint(10**10)
        seed = 2 * seed
        rnd.seed(seed)
        self._rng = sim.NumpyRNG(seed=seed + 1)
예제 #9
0
def loop():
    for device_instance in Interfaces.DeviceMeta._instances:
        device_instance._create_device()
    print "Entered loop"
    i = 0
    
    while(True):
        sim.run(20.0)
        Observers.Observer.notify()
        Setters.Setter.notify()
        SimulatorPorts.RPCPort.execute()
        for pop_view in population_register.values():
            pass
            #print pop_view.meanSpikeCount()
            #print 'amplitude', pop_view.get_data().segments[0].filter(name='v')
            #print nest.GetStatus(map(int, [pop_view.all_cells[0]]), 'V_m')

        i += 1
    sim.end()
예제 #10
0
def scnn_test(l_cnn, w_cnn, num_test, test, max_rate, dur_test, silence):
    p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0)
    L = l_cnn
    random.seed(0)
    input_size = L[0][1]
    pops_list = []
    pops_list.append(init_inputlayer(input_size, test[:num_test, :], max_rate, dur_test, silence))
    for l in range(len(w_cnn)):
        pops_list.append(construct_layer(pops_list[l], L[l+1][0], L[l+1][1], w_cnn[l]))
    result = pops_list[-1][0]
    result.record()
    
    p.run((dur_test+silence)*num_test)
    spike_result = result.getSpikes(compatible_output=True)
    p.end()
    
    spike_result_count = count_spikes(spike_result, 10, num_test, dur_test, silence)
    predict = np.argmax(spike_result_count, axis=0)
#     prob = np.exp(spike_result_count)/np.sum(np.exp(spike_result_count), axis=0)
    return predict
예제 #11
0
def main():
    # setup timestep of simulation and minimum and maximum synaptic delays
    setup(timestep=simulationTimestep, min_delay=minSynapseDelay, max_delay=maxSynapseDelay, threads=4)

    # create a spike sources
    retinaLeft = createSpikeSource("Retina Left")
    retinaRight = createSpikeSource("Retina Right")
    
    # create network and attach the spike sources 
    network = createCooperativeNetwork(retinaLeft=retinaLeft, retinaRight=retinaRight)
    
    # run simulation for time in milliseconds
    print "Simulation started..."
    run(simulationTime)
    print "Simulation ended."
    
    # plot results 
    plotSimulationResults(network, 1, False)
    
    # finalise program and simulation
    end()
def presentStimuli(pres_duration, num_pres_per_stim, num_source, num_target, bright_on_weights, bright_off_weights, bright_lat_weights, dark_on_weights, dark_off_weights, dark_lat_weights, is_repeated=False):
    """
    For presenting a stimulus to the target network. Callback is used to switch between presentation rates.
    Arguments:  num_source
                num_target
                num_pres_per_stim,
                pres_duration
    """
    num_stim = 2 # two stimuli 'bright' and 'dark'
    total_duration = num_stim * num_pres_per_stim * pres_duration

    source_on_pop = pynn.Population(num_source, pynn.SpikeSourcePoisson(), label='source_on_pop')
    source_off_pop = pynn.Population(num_source, pynn.SpikeSourcePoisson(), label='source_off_pop')
    is_bright, random_on_rates, random_off_rates = getPresentationRatesForCallback(num_stim, num_source, num_pres_per_stim, is_repeated=is_repeated)

    bright_target_pop = pynn.Population(num_target, pynn.IF_cond_exp, {'i_offset':0.11, 'tau_refrac':3.0, 'v_thresh':-51.0}, label='target_pop')
    dark_target_pop = pynn.Population(num_target, pynn.IF_cond_exp, {'i_offset':0.11, 'tau_refrac':3.0, 'v_thresh':-51.0}, label='target_pop')

    bright_on_conn = pynn.Projection(source_on_pop, bright_target_pop, connector=pynn.AllToAllConnector(), synapse_type=pynn.StaticSynapse(weight=bright_on_weights), receptor_type='excitatory')
    bright_off_conn = pynn.Projection(source_off_pop, bright_target_pop, connector=pynn.AllToAllConnector(), synapse_type=pynn.StaticSynapse(weight=bright_off_weights), receptor_type='excitatory')
    bright_lat_conn = pynn.Projection(bright_target_pop, bright_target_pop, connector=pynn.AllToAllConnector(), synapse_type=pynn.StaticSynapse(weight=bright_lat_weights), receptor_type='inhibitory')
    dark_on_conn = pynn.Projection(source_on_pop, dark_target_pop, connector=pynn.AllToAllConnector(), synapse_type=pynn.StaticSynapse(weight=dark_on_weights), receptor_type='excitatory')
    dark_off_conn = pynn.Projection(source_off_pop, dark_target_pop, connector=pynn.AllToAllConnector(), synapse_type=pynn.StaticSynapse(weight=dark_off_weights), receptor_type='excitatory')
    dark_lat_conn = pynn.Projection(dark_target_pop, dark_target_pop, connector=pynn.AllToAllConnector(), synapse_type=pynn.StaticSynapse(weight=dark_lat_weights), receptor_type='inhibitory')

    source_on_pop.record('spikes')
    source_off_pop.record('spikes')
    bright_target_pop.record(['spikes'])
    dark_target_pop.record(['spikes'])

    pynn.run(total_duration, callbacks=[PoissonWeightVariation(source_on_pop, random_on_rates, pres_duration), PoissonWeightVariation(source_off_pop, random_off_rates, pres_duration)])
    pynn.end()

    source_on_spikes = source_on_pop.get_data('spikes').segments[0].spiketrains
    source_off_spikes = source_off_pop.get_data('spikes').segments[0].spiketrains
    bright_spikes = bright_target_pop.get_data('spikes').segments[0].spiketrains
    dark_spikes = dark_target_pop.get_data('spikes').segments[0].spiketrains
    return is_bright, source_on_spikes, source_off_spikes, bright_spikes, dark_spikes
예제 #13
0
def scnn_test(l_cnn, w_cnn, num_test, test, max_rate, dur_test, silence):
    p.setup(timestep=1.0, min_delay=1.0, max_delay=3.0)
    L = l_cnn
    random.seed(0)
    input_size = L[0][1]
    pops_list = []
    pops_list.append(
        init_inputlayer(input_size, test[:num_test, :], max_rate, dur_test,
                        silence))
    for l in range(len(w_cnn)):
        pops_list.append(
            construct_layer(pops_list[l], L[l + 1][0], L[l + 1][1], w_cnn[l]))
    result = pops_list[-1][0]
    result.record()

    p.run((dur_test + silence) * num_test)
    spike_result = result.getSpikes(compatible_output=True)
    p.end()

    spike_result_count = count_spikes(spike_result, 10, num_test, dur_test,
                                      silence)
    predict = np.argmax(spike_result_count, axis=0)
    #     prob = np.exp(spike_result_count)/np.sum(np.exp(spike_result_count), axis=0)
    return predict
예제 #14
0
def runSimGivenStim(stim_type, num_source, num_target, duration, use_stdp,
                    record_source_spikes, source_rates_params, synapse_to_use,
                    ff_conn, lat_conn):
    """
    For running the simulation and returning the required results.
    Arguments:  stim_type, 'bright' or 'dark'
                num_source, number of cells in the source layers
                num_target, number of cells in the target layer
                duration, float
                use_stdp,
                record_source_spikes,
                source_rates_params, params for 8 Gamma distributions
                synapse_to_use, either STDPMechanism or StaticSynapse
                ff_conn, either AllToAllConnector or FixedProbabilityConnector
                lat_conn, same as ff_conn but with a different probability, maybe
    Returns:    target_spikes,
                ff_on_weights,
                ff_off_weights,
                lat_weights,
                ff_on_weights_over_time,
                ff_off_weights_over_time,
                lat_weights_over_time
    """
    on_rates, off_rates = getOnOffSourceRates(
        num_source,
        stim_type,
        on_bright_params=args.source_rates_params[0],
        on_dark_params=args.source_rates_params[1],
        off_bright_params=args.source_rates_params[2],
        off_dark_params=args.source_rates_params[3])
    source_on_pop = pynn.Population(num_source,
                                    pynn.SpikeSourcePoisson(rate=on_rates),
                                    label='source_on_pop')
    source_off_pop = pynn.Population(num_source,
                                     pynn.SpikeSourcePoisson(rate=off_rates),
                                     label='source_off_pop')
    target_pop = pynn.Population(num_target,
                                 pynn.IF_cond_exp, {
                                     'i_offset': 0.11,
                                     'tau_refrac': 3.0,
                                     'v_thresh': -51.0
                                 },
                                 label='target_pop')
    ff_on_proj = pynn.Projection(source_on_pop,
                                 target_pop,
                                 connector=ff_conn,
                                 synapse_type=synapse_to_use,
                                 receptor_type='excitatory')
    ff_off_proj = pynn.Projection(source_off_pop,
                                  target_pop,
                                  connector=ff_conn,
                                  synapse_type=synapse_to_use,
                                  receptor_type='excitatory')
    lat_proj = pynn.Projection(target_pop,
                               target_pop,
                               connector=lat_conn,
                               synapse_type=synapse_to_use,
                               receptor_type='inhibitory')
    target_pop.record(['spikes'])
    [source_on_pop.record('spikes'),
     source_off_pop.record('spikes')] if args.record_source_spikes else None
    ff_on_weight_recorder = WeightRecorder(sampling_interval=1.0,
                                           projection=ff_on_proj)
    ff_off_weight_recorder = WeightRecorder(sampling_interval=1.0,
                                            projection=ff_off_proj)
    lat_weight_recorder = WeightRecorder(sampling_interval=1.0,
                                         projection=lat_proj)
    pynn.run(duration,
             callbacks=[
                 ff_on_weight_recorder, ff_off_weight_recorder,
                 lat_weight_recorder
             ])
    pynn.end()
    target_spikes = target_pop.get_data('spikes').segments[0].spiketrains
    if record_source_spikes:
        source_on_spikes = source_on_pop.get_data(
            'spikes').segments[0].spiketrains
        source_off_spikes = source_off_pop.get_data(
            'spikes').segments[0].spiketrains
    ff_on_weights = ff_on_proj.get('weight', format='array')
    ff_off_weights = ff_off_proj.get('weight', format='array')
    lat_weights = lat_proj.get('weight', format='array')
    ff_on_weights_over_time = ff_on_weight_recorder.get_weights()
    ff_off_weights_over_time = ff_off_weight_recorder.get_weights()
    lat_weights_over_time = lat_weight_recorder.get_weights()
    pynn.reset()
    return target_spikes, ff_on_weights, ff_off_weights, lat_weights, ff_on_weights_over_time, ff_off_weights_over_time, lat_weights_over_time
예제 #15
0
                pynn.nest.GetStatus([connSTDP[i]])[0]['a_acausal'])

    if not timeNow == timeGrid[-1]:
        pynn.run(timeStep)

spikes = neuron.getSpikes()
#membrane = neuron.get_v() #for debugging

print('presynaptic spikes (static synapse)')
print(stimSpikes)
print('presynaptic spikes (plastic synapse)')
print(measureSpikes)
print('postsynaptic spikes')
print(spikes)

pynn.end()

#visualization of results
import matplotlib.pyplot as plt
plt.figure()
plt.plot(timeGrid, weightList, c='b')
plt.xlabel('Time (ms)')
plt.ylabel('Synaptic weight ($\mu$S)')
plt.legend(['Weight'], loc=2)
plt.twinx()
plt.plot(timeGrid, aCausalList, c='g')
plt.plot(timeGrid, aAnticausalList, c='r')
plt.axhline(aThresh, c='k', ls='--')
plt.ylabel('Charge on capacitor (AU)')
plt.legend(['Causal', 'Anticausal', 'Threshold'], loc=1)
plt.savefig('hw_synapse_nest.png')
cells.recorders["iaf_V"].write("Results/nineml_neuron.V", filter=[cells[0]])
cells.recorders["AMPA_g"].write("Results/nineml_neuron.g_exc", filter=[cells[0]])
cells.recorders["GABAa_g"].write("Results/nineml_neuron.g_gabaA", filter=[cells[0]])
cells.recorders["GABAb_g"].write("Results/nineml_neuron.g_gagaB", filter=[cells[0]])


t = cells.recorders["iaf_V"].get()[:, 1]
v = cells.recorders["iaf_V"].get()[:, 2]
gInhA = cells.recorders["GABAa_g"].get()[:, 2]
gInhB = cells.recorders["GABAb_g"].get()[:, 2]
gExc = cells.recorders["AMPA_g"].get()[:, 2]

import pylab

pylab.subplot(211)
pylab.plot(t, v)
pylab.ylabel("voltage [mV]")
pylab.suptitle("AMPA, GABA_A, GABA_B")
pylab.subplot(212)
pylab.plot(t, gInhA, label="GABA_A")
pylab.plot(t, gInhB, label="GABA_B")
pylab.plot(t, gExc, label="AMPA")
pylab.ylabel("conductance [nS]")
pylab.xlabel("t [ms]")
pylab.legend()

pylab.show()

sim.end()
예제 #17
0
 def simulate(self):
     # reset detectors before simulating the next step
     nest.nest.SetStatus(self.network.detectors.values(), 'n_events', 0)
     nest.run(self.simduration)
     nest.end()
예제 #18
0
        plt.title(i)

        to_plot = np.reshape(post[:,i], (input_size, input_size))
        #to_plot = to_plot - np.reshape(pre[:, i], (input_size, input_size))
        img = plt.imshow(to_plot)
        #img.set_clim(0, 0.5)#weight_max)
        plt.colorbar(img, fraction=0.046, pad=0.04)
    #print post[:,0]
    spikes = pop_output.getSpikes(compatible_output=True)
    #spikes = pop_input.getSpikes(compatible_output=True)
    
    plot_spikes(spikes, "output")
    '''
    #pop_output.printSpikes('saved/outspikes_%d.txt'%run_i, gather=False, compatible_output=True)

    p.end()

# In[ ]:

plt.figure(figsize=(18, 6))
for i in range(num_output):
    plt.subplot(2, 5, i + 1)
    plt.title(i)
    to_plot = np.reshape(post[:, i], (input_size, input_size))
    img = plt.imshow(to_plot)  #cmap = cm.Greys_r)
    plt.colorbar(img, fraction=0.046, pad=0.04)
#spikes = pop_output.getSpikes(compatible_output=True)
#plot_spikes(spikes, "output")

# In[ ]:
예제 #19
0
def _run_microcircuit(plot_filename, conf):
    import plotting
    import logging

    simulator = conf['simulator']
    # we here only need nest as simulator, simulator = 'nest'
    import pyNN.nest as sim

    # prepare simulation
    logging.basicConfig()

    # extract parameters from config file
    master_seed = conf['params_dict']['nest']['master_seed']
    layers = conf['layers']
    pops = conf['pops']
    plot_spiking_activity = conf['plot_spiking_activity']
    raster_t_min = conf['raster_t_min']
    raster_t_max = conf['raster_t_max']
    frac_to_plot = conf['frac_to_plot']
    record_corr = conf['params_dict']['nest']['record_corr']
    tau_max = conf['tau_max']

    # Numbers of neurons from which to record spikes
    n_rec = helper_functions.get_n_rec(conf)

    sim.setup(**conf['simulator_params'][simulator])

    if simulator == 'nest':
        n_vp = sim.nest.GetKernelStatus('total_num_virtual_procs')
        if sim.rank() == 0:
            print 'n_vp: ', n_vp
            print 'master_seed: ', master_seed
        sim.nest.SetKernelStatus({'print_time': False,
                                  'dict_miss_is_error': False,
                                  'grng_seed': master_seed,
                                  'rng_seeds': range(master_seed + 1,
                                                     master_seed + n_vp + 1),
                                  # PYTHON2.6: FOR WRITING OUTPUT FROM
                                  # RECORDING DEVICES WITH PYNEST FUNCTIONS,
                                  # THE OUTPUT PATH IS NOT AUTOMATICALLY THE
                                  # CWD BUT HAS TO BE SET MANUALLY
                                  'data_path': conf['system_params']['output_path']})

    import network

    # result of export-files
    results = []

    # create network
    start_netw = time.time()
    n = network.Network(sim)

    # PYTHON2.6: device_list CONTAINS THE GIDs OF THE SPIKE DETECTORS AND VOLTMETERS
    # NEEDED FOR RETRIEVING FILENAMES LATER
    device_list = n.setup(sim, conf)

    end_netw = time.time()
    if sim.rank() == 0:
        print 'Creating the network took ', end_netw - start_netw, ' s'

    # simulate
    if sim.rank() == 0:
        print "Simulating..."
    start_sim = time.time()
    sim.run(conf['simulator_params'][simulator]['sim_duration'])
    end_sim = time.time()
    if sim.rank() == 0:
        print 'Simulation took ', end_sim - start_sim, ' s'

    # extract filename from device_list (spikedetector/voltmeter),
    # gid of neuron and thread. merge outputs from all threads
    # into a single file which is then added to the task output.
    # PYTHON2.6: NEEDS TO BE ADAPTED IF NOT RECORDED VIA PYNEST
    for dev in device_list:
        label = sim.nest.GetStatus(dev)[0]['label']
        gid = sim.nest.GetStatus(dev)[0]['global_id']
        # use the file extension to distinguish between spike and voltage output
        extension = sim.nest.GetStatus(dev)[0]['file_extension']
        if extension == 'gdf':  # spikes
            data = np.empty((0, 2))
        elif extension == 'dat':  # voltages
            data = np.empty((0, 3))
        for thread in xrange(conf['simulator_params']['nest']['threads']):
            filenames = glob.glob(conf['system_params']['output_path']
                                  + '%s-*%d-%d.%s' % (label, gid, thread, extension))
            assert(len(filenames) == 1), 'Multiple input files found. Use a clean output directory.'
            data = np.vstack([data, np.loadtxt(filenames[0])])
            # delete original files
            os.remove(filenames[0])
        order = np.argsort(data[:, 1])
        data = data[order]
        outputfile_name = 'collected_%s-%d.%s' % (label, gid, extension)
        outputfile = open(outputfile_name, 'w')
        # the outputfile should have same format as output from NEST.
        # i.e., [int, float] for spikes and [int, float, float] for voltages,
        # hence we write it line by line and assign the corresponding filetype
        if extension == 'gdf':  # spikes
            for line in data:
                outputfile.write('%d\t%.3f\n' % (line[0], line[1]))
            outputfile.close()
            filetype = 'application/vnd.juelich.nest.spike_times'

        elif extension == 'dat':  # voltages
            for line in data:
                outputfile.write('%d\t%.3f\t%.3f\n' % (line[0], line[1], line[2]))
            outputfile.close()
            filetype = 'application/vnd.juelich.nest.analogue_signal'

        res = (outputfile_name, filetype)
        results.append(res)

    # start_writing = time.time()

    # PYTHON2.6: SPIKE AND VOLTAGE FILES ARE CURRENTLY WRITTEN WHEN A SPIKE
    # DETECTOR OR A VOLTMETER IS CONNECTED WITH 'to_file': True

    # for layer in layers:
    #     for pop in pops:
    #         # filename = conf['system_params']['output_path'] + '/spikes_' + layer + pop + '.dat'
    #         filename = conf['system_params']['output_path'] + 'spikes_' + layer + pop + '.dat'
    #         n.pops[layer][pop].printSpikes(filename, gather=False)

    #         # add filename and filepath into results
    #         subres = (filename, 'application/vnd.juelich.bundle.nest.data')
    #         results.append(subres)

    # if record_v:
    #     for layer in layers:
    #         for pop in pops:
    #             filename = conf['system_params']['output_path'] + '/voltages_' + layer + pop + '.dat'
    #             n.pops[layer][pop].print_v(filename, gather=False)

    if record_corr and simulator == 'nest':
        start_corr = time.time()
        if sim.nest.GetStatus(n.corr_detector, 'local')[0]:
            print 'getting count_covariance on rank ', sim.rank()
            cov_all = sim.nest.GetStatus(n.corr_detector, 'count_covariance')[0]
            delta_tau = sim.nest.GetStatus(n.corr_detector, 'delta_tau')[0]

            cov = {}
            for target_layer in np.sort(layers.keys()):
                for target_pop in pops:
                    target_index = conf['structure'][target_layer][target_pop]
                    cov[target_index] = {}
                    for source_layer in np.sort(layers.keys()):
                        for source_pop in pops:
                            source_index = conf['structure'][source_layer][source_pop]
                            cov[target_index][source_index] = np.array(list(cov_all[target_index][source_index][::-1])
                                                                       + list(cov_all[source_index][target_index][1:]))

            f = open(conf['system_params']['output_path'] + '/covariances.dat', 'w')
            print >>f, 'tau_max: ', tau_max
            print >>f, 'delta_tau: ', delta_tau
            print >>f, 'simtime: ', conf['simulator_params'][simulator]['sim_duration'], '\n'

            for target_layer in np.sort(layers.keys()):
                for target_pop in pops:
                    target_index = conf['structure'][target_layer][target_pop]
                    for source_layer in np.sort(layers.keys()):
                        for source_pop in pops:
                            source_index = conf['structure'][source_layer][source_pop]
                            print >>f, target_layer, target_pop, '-', source_layer, source_pop
                            print >>f, 'n_events_target: ', sim.nest.GetStatus(n.corr_detector, 'n_events')[0][target_index]
                            print >>f, 'n_events_source: ', sim.nest.GetStatus(n.corr_detector, 'n_events')[0][source_index]
                            for i in xrange(len(cov[target_index][source_index])):
                                print >>f, cov[target_index][source_index][i]
                            print >>f, ''
            f.close()

            # add file covariances.dat into bundle
            res_cov = ('covariances.dat',
                       'text/plain')
            results.append(res_cov)

        end_corr = time.time()
        print "Writing covariances took ", end_corr - start_corr, " s"

    # end_writing = time.time()
    # print "Writing data took ", end_writing - start_writing, " s"

    if plot_spiking_activity and sim.rank() == 0:
        plotting.plot_raster_bars(raster_t_min, raster_t_max, n_rec,
                                  frac_to_plot, n.pops,
                                  conf['system_params']['output_path'],
                                  plot_filename, conf)
        res_plot = (plot_filename, 'image/png')
        results.append(res_plot)

    sim.end()

    return results
예제 #20
0
def main(task_id=0):
    """
    Parameters
    ----------
    task_id : int
        Identifier for learning task selection:
            0 : Pattern association
            1 : Mimicking tutor neurons

    Returns
    -------
    rec : record struct
        Container for network output / input pattern recordings during
        simulation runs.
    """
    # === Init. parameters and specify task  ==================================

    # Seed for random number generator (use 'seed = None' for system clock)
    seed = 42

    if task_id == 0:
        # These parameter choices recreate results in Fig. 5 of
        # Gardner & Gruening 2016 (although arbitrary target spikes and exact
        # spike precision are used here)
        # For 200 inputs and T = 200 ms: ~8.7 seconds wall time for 100 runs
        param = values.PatternAssocParam(n_classes=1,
                                         n_patterns_class=1,
                                         n_target_spikes=4,
                                         n_inputs=200,
                                         n_outputs=1,
                                         n_epochs=100,
                                         seed=seed)
        learn_task = task.PatternAssociation(param)
    elif task_id == 1:
        param = values.MimicParam(n_patterns=1,
                                  n_target_spikes=4,
                                  n_inputs=200,
                                  n_outputs=1,
                                  n_epochs=100,
                                  seed=seed)
        learn_task = task.Mimicry(param)
    else:
        # Invalid input argument
        raise ValueError('Invalid main argument')

    # Initialise simulator
    # Must have minimum conductance delay of 0.1 ms, 'off_grid' for
    # exact spiking precision
    sim.setup(timestep=param.dt,
              min_delay=0.1,
              spike_precision='off_grid',
              verbosity='error')

    # === Record ==============================================================

    class Record(object):
        """Simulation recordings container"""
        def __init__(self, learn_task, param):
            # Network error: van Rossum distance
            self.err = np.zeros(param.n_epochs)
            # Network absolute timing displacements
            self.dt_max = np.full(
                (param.n_epochs, param.n_patterns, param.n_outputs), np.inf)
            # Record weights per epoch for output layer
            self.w = np.zeros(
                (param.n_epochs, param.n_inputs, param.n_outputs))
            if task_id == 1:
                # Euclidean distance between actual and tutor weights per epoch
                self.w_err = np.empty(param.n_epochs)

    rec = Record(learn_task, param)

    # === Setup patterns and network ==========================================

    # Generate arbitrary input / target patterns
    # Parameter choices are: {'uniform', 'poisson'}
    learn_task.build_static_patterns('uniform')  # Select static input spikes
    #    learn_task.build_dynamic_patterns('uniform')  # Select noisy input spikes

    #    net = snn.NetworkINST(param, sim)  # Select INST learning rule
    net = snn.NetworkFILT(param, sim)  # Select FILT learning rule

    # === Run simulation ======================================================

    for i in xrange(param.n_epochs):
        # Simulate network
        rec.err[i], rec.dt_max[i] = net.learn(learn_task)
        # Record weights of output layer
        rec.w[i, :, :] = net.w
        if task_id == 1:
            rec.w_err[i] = np.linalg.norm(net.w - net.w_ref)
        # Print progress
        epochs_completed = i + 1
        if epochs_completed % 50 == 0:
            print epochs_completed

    # === Gather and plot results =============================================

    rec.input = learn_task
    if task_id == 1:
        rec.w_ref = net.w_ref

    # Classification performance
    accs = utility.accuracy(rec.dt_max)
    # Exponentially-weighted moving average
    accs_ewma = utility.ewma_vec(accs, len(accs) / 10.)
    # Plots:
    utility.plot_error(rec.err)  # Distance metric
    utility.plot_accuracy(accs_ewma)  # Performance metric

    # Plots for one pattern:
    if param.n_patterns == 1:
        rec.output = net.layer_out.get_data()
        if task_id == 1:
            rec.output_ref = net.layer_out_ref.get_data()
            rec.spikes_ref = [
                Sequence(np.array(spikes_ref))
                for spikes_ref in rec.output_ref.segments[-1].spiketrains
            ]
        else:
            rec.spikes_ref = learn_task.pattern_target[-1].spike_trains
#        utility.plot_signal(rec.output)  # Voltage trace (default last epoch)
#        plt.plot(rec.w[:, :, 0])  # Plot evolution of first output neuron's synaptic weights
#        plt.hist(rec.w[-1, :, 0])  # Plot histogram of first output neuron's synaptic weights
#        utility.plot_spikepattern(rec.input.pattern_input[0].spike_trains, rec.input.param.T)  # Plot an input pattern
        utility.plot_spiker(
            rec.output, rec.spikes_ref,
            neuron_index=0)  # Spike raster of given output neuron


#    if task_id == 1:
#        # Plot Euclidean distance between actual and tutor weights
#        plt.plot(rec.w_err)

# === End simulation ======================================================

    sim.end()
    return rec
예제 #21
0
sim.Projection(source,
               pop_curr_exp,
               connector=sim.FromListConnector([(0, 0, 2.0, 0.1)]))
sim.Projection(source,
               pop_curr_alpha,
               connector=sim.FromListConnector([(0, 0, 2.0, 0.1)]))
sim.Projection(source,
               pop_cond_exp,
               connector=sim.FromListConnector([(0, 0, 0.1, 0.1)]))
sim.Projection(source,
               pop_cond_alpha,
               connector=sim.FromListConnector([(0, 0, 0.1, 0.1)]))

sim.run(1000.0);

print "Current based exponential LIF neuron"
print pop_curr_exp.get_data().segments[0].spiketrains

print "Current based alpha LIF neuron"
print pop_curr_alpha.get_data().segments[0].spiketrains

print "Conductance based exponential LIF neuron"
print pop_cond_exp.get_data().segments[0].spiketrains

print "Conductance based alpha LIF neuron"
print pop_cond_alpha.get_data().segments[0].spiketrains

sim.end();

예제 #22
0
#############################

layer = 0

population_on = lgn_on_populations[layer]
population_off = lgn_off_populations[layer]

population_on.record('spikes')
population_off.record('spikes')

#############################
# Run model
#############################

simulator.run(t)  # Run the simulations for t ms
simulator.end()

#############################
# Extract the data
#############################
data_on = population_on.get_data()  # Creates a Neo Block
data_off = population_off.get_data()

segment_on = data_on.segments[0]  # Takes the first segment
segment_off = data_off.segments[0]


# Plot spike trains
def plot_spiketrains(segment):
    """
    Plots the spikes of all the cells in the given segments
예제 #23
0
def run(a_state):
    output_base = "out/"
    spike_count_filename = "gpi_spike_count.dat"

    weight_filename = conn_filename    # filename, from which the cortex - striatum connections are read

    spike_count_full_filename = output_base + spike_count_filename

    #active_state = int(sys.argv[1])
    active_state = a_state

    #Model of the basal ganglia D1 and D1 pathways. States and actions are populations coded.

    pyNN.utility.init_logging(None, debug=True)

    sim.setup(time_step)

    # cell class for all neurons in the network
    # (on HMF can be one of IF_cond_exp, EIF_cond_exp_isfa_ista)
    cellclass = sim.IF_cond_exp


    # #############
    #  POPULATIONS
    # #############
    #CORTEX input population: N states, poisson inputs

    #?assemblies of m_actions populations or dictionnary of populations?
    #STRIATUM 2 populations of M actions, D1 and D2

    #GPi/SNr 1 population of M actions, baseline firing rate driven by external poisson inputs


    cortex = [
        sim.Population(n_cortex_cells, cellclass, neuron_parameters, label="CORTEX_{}".format(i))
        for i in xrange(n_states)]

    cortex_assembly = sim.Assembly(
        *cortex,
        label="CORTEX")

    # independent Poisson input to cortex populations.
    # /active_state/ determines, which population receives
    # a different firing rate
    cortex_input = []
    for i in xrange(n_states):

        if i == active_state:
            rate = active_state_rate
        else:
            rate = inactive_state_rate

        new_input = sim.Population(
            n_cortex_cells,
            sim.SpikeSourcePoisson,
            {'rate': rate},
            label="STATE_INPUT_" + str(i))
        sim.Projection(
            new_input,
            cortex[i],
            sim.OneToOneConnector(),
            sim.StaticSynapse(weight=cortex_input_weight, delay=cortex_input_delay)
            )

        cortex_input.append(new_input)
    #print 'cortex ok'

    # striatum:
    # exciatatory populations
    striatum_d1 = [
        sim.Population(n_msns, cellclass, neuron_parameters, label="D1_{}".format(i))
        for i in xrange(m_actions)]

    # inhibitory populations
    striatum_d2 = [
        sim.Population(n_msns, cellclass, neuron_parameters, label="D2_{}".format(i))
        for i in xrange(m_actions)]

    # Striatum D2->D2 and D1->D1 lateral inhibition
    for lat_inh_source in xrange(m_actions):
        for lat_inh_target in xrange(m_actions):
            if lat_inh_source == lat_inh_target:
                continue
            sim.Projection(
                striatum_d1[lat_inh_source],
                striatum_d1[lat_inh_target],
                sim.FixedProbabilityConnector(
                    d1_lat_inh_prob),
                    sim.StaticSynapse(
                        weight=d1_lat_inh_weight,
                        delay=d1_lat_inh_delay),
                receptor_type="inhibitory",
                label="d1_lateral_inhibition_{}_{}".format(
                    lat_inh_source, lat_inh_target))
            sim.Projection(
                striatum_d2[lat_inh_source],
                striatum_d2[lat_inh_target],
                sim.FixedProbabilityConnector(
                    d2_lat_inh_prob),
                    sim.StaticSynapse(
                        weight=d2_lat_inh_weight,
                        delay=d2_lat_inh_delay),
                receptor_type="inhibitory",
                label="d2_lateral_inhibition_{}_{}".format(
                    lat_inh_source, lat_inh_target))

    striatum_assembly = sim.Assembly(
        *(striatum_d1 + striatum_d2),
        label="STRIATUM")

    #gids_cortex= []
    #gids_d1= []
    #gids_d2= []

    #for s in xrange(n_states):
    #    gids_cortex.append([gid for gid in cortex_assembly.get_population("CORTEX_"+str(s)).all()])
    #for a in xrange(m_actions):
    #    gids_d1.append([gid1 for gid1 in striatum_assembly.get_population("D1_"+str(a)).all()])
    #    gids_d2.append([gid2 for gid2 in striatum_assembly.get_population("D2_"+str(a)).all()])


    #for i in xrange(0,3):

    #    print i, 'len cortex ', len(gids_cortex[i]), 'unique ', len(np.unique(gids_cortex[i]))
    #    print i, 'len d1', len(gids_d1[i]), 'unique ', len(np.unique(gids_d1[i]))
    #    print i, 'len d2', len(gids_d2[i]), 'unique ', len(np.unique(gids_d2[i]))
    #print "striatum ok"
    
    #for i in xrange(0,3):
    #    print np.unique(gids_cortex[i])
    #    gids_cortex[i][:]-=3

    #if init:
    #    init_w(gids_cortex, gids_d1, gids_d2)

     
    # cortex - striatum connection, all-to-all using loaded weights
    cs = sim.Projection(
        cortex_assembly,
        striatum_assembly,
        #sim.AllToAllConnector(),
        #sim.StaticSynapse(
        #    weight=wd1,
        #    delay=ctx_strd1_delay))
        sim.FromFileConnector(
            weight_filename))
    gpi = [
        sim.Population(n_gpi, cellclass, neuron_parameters,
                       label="GPI_{}".format(i))
        for i in xrange(m_actions)
        ]
    gpi_assembly = sim.Assembly(
        *gpi,
        label="GPi")

    # external Poisson input to GPi
    gpi_input = sim.Population(
        m_actions * n_gpi,
        sim.SpikeSourcePoisson,
        dict(
            duration=sim_duration,
            rate=gpi_external_rate,
            start=0.),
        label="GPI_EXT_INPUT")
    sim.Projection(
        gpi_input,
        gpi_assembly,
        sim.OneToOneConnector(),
        sim.StaticSynapse(
            weight=gpi_external_weight,
            delay= gpi_external_delay))
    # striatum - gpi connections
    for i in xrange(m_actions):
        gpi_p = sim.Projection(
            striatum_d1[i],
            gpi[i],
            sim.FixedProbabilityConnector(d1_gpi_prob), 
            sim.StaticSynapse( weight=d1_gpi_weight, delay = d1_gpi_delay))

        sim.Projection(
            striatum_d2[i],
            gpi[i],
            sim.FixedProbabilityConnector(d2_gpi_prob),
            sim.StaticSynapse(weight=d2_gpi_weight, delay=d2_gpi_delay),
            #target="inhibitory")
            receptor_type="inhibitory")

    #print gpi_p.get('weight', format='list')
    cortex_assembly.record('spikes')
    striatum_assembly.record('spikes')
    gpi_assembly.record('spikes')

    #print 'sim start'
    sim.run(sim_duration)
    sim.end()
    
    label = "CORTEX_0" 
    #print 'cortex get pop', cortex_assembly.get_population(label)
    #print 'cortex describe', cortex_assembly.describe()
    #cortex_assembly.write_data("spikes")
    #cortex_assembly.get_population(label).write_data("spikes")
    #spikes = gpi_assembly  #get_data("spikes", gather=True)
   # print "getdata spikes", spikes
   # print 'spikes.segment', spikes.segments
    #print 'spikes.segments.SpikeTrains', spikes.segments.spike

    #save_spikes(cortex_assembly, output_base, "cortex.dat")
    #save_spikes(striatum_d1, output_base, "striatum_d1.dat")
    #save_spikes(striatum_d2, output_base, "striatum_d2.dat")
    #save_spikes(gpi, output_base, "gpi.dat")

    #output_rates = np.array(
    #    [len(i.getSpikes()) for i in gpi])
    #np.savetxt(spike_count_full_filename, output_rates)
    
   # for seg in cortex_assembly.segments:
   #     print("Analyzing segment %d" % seg.index)
   #     stlist = [st - st.t_start for st in seg.spiketrains]
   #     plt.figure()
   #     count, bins = np.histogram(stlist)
   #     plt.bar(bins[:-1], count, width=bins[1] - bins[0])
   #     plt.title("PSTH in segment %d" % seg.index)
    cortex_mean_spikes = np.zeros(n_states)
    gpi_mean_spikes = np.zeros(m_actions)
    d1_mean_spikes = np.zeros(m_actions)
    d2_mean_spikes = np.zeros(m_actions)
    for i in xrange(n_states):
        cortex_mean_spikes[i] = cortex_assembly.get_population("CORTEX_"+str(i)).mean_spike_count()
    for i in xrange(m_actions):
        gpi_mean_spikes[i] = gpi_assembly.get_population("GPI_"+str(i)).mean_spike_count()
        d1_mean_spikes[i] = striatum_assembly.get_population("D1_"+str(i)).mean_spike_count()
        d2_mean_spikes[i] = striatum_assembly.get_population("D2_"+str(i)).mean_spike_count()

    print 'CORTEX ', cortex_mean_spikes
    print 'D1', d1_mean_spikes
    print 'D2', d2_mean_spikes

    return gpi_mean_spikes
예제 #24
0
def estimate_kb(cell_params_lif):
    cell_para = copy.deepcopy(cell_params_lif)
    random.seed(0)
    p.setup(timestep=1.0, min_delay=1.0, max_delay=16.0)
    run_s = 10.
    runtime = 1000. * run_s
    max_rate = 1000.
    ee_connector = p.OneToOneConnector(weights=1.0, delays=2.0)

    pop_list = []
    pop_output = []
    pop_source = []
    x = np.arange(0., 1.01, 0.1)
    count = 0
    trail = 10

    for i in x:
        for j in range(trail):  #trails for average
            pop_output.append(p.Population(1, p.IF_curr_exp, cell_para))
            poisson_spikes = mu.poisson_generator(i * max_rate, 0, runtime)
            pop_source.append(
                p.Population(1, p.SpikeSourceArray,
                             {'spike_times': poisson_spikes}))
            p.Projection(pop_source[count],
                         pop_output[count],
                         ee_connector,
                         target='excitatory')
            pop_output[count].record()
            count += 1

    count = 0
    for i in x:
        cell_para['i_offset'] = i
        pop_list.append(p.Population(1, p.IF_curr_exp, cell_para))
        pop_list[count].record()
        count += 1
    pop_list[count - 1].record_v()

    p.run(runtime)

    rate_I = np.zeros(count)
    rate_P = np.zeros(count)
    rate_P_max = np.zeros(count)
    rate_P_min = np.ones(count) * 1000.
    for i in range(count):
        spikes = pop_list[i].getSpikes(compatible_output=True)
        rate_I[i] = len(spikes) / run_s
        for j in range(trail):
            spikes = pop_output[i * trail +
                                j].getSpikes(compatible_output=True)
            spike_num = len(spikes) / run_s
            rate_P[i] += spike_num
            if spike_num > rate_P_max[i]:
                rate_P_max[i] = spike_num
            if spike_num < rate_P_min[i]:
                rate_P_min[i] = spike_num
        rate_P[i] /= trail
    '''
    #plot_spikes(spikes, 'Current = 10. mA')
    plt.plot(x, rate_I, label='current',)
    plt.plot(x, rate_P, label='Poisson input')
    plt.fill_between(x, rate_P_min, rate_P_max, facecolor = 'green', alpha=0.3)
    '''
    x0 = np.where(rate_P > 1.)[0][0]
    x1 = 4
    k = (rate_P[x1] - rate_P[x0]) / (x[x1] - x[x0])
    '''
    plt.plot(x, k*(x-x[x0])+rate_P[x0], label='linear')
    plt.legend(loc='upper left', shadow=True)
    plt.grid('on')
    plt.show()
    '''
    p.end()
    return k, x[x0], rate_P[x0]
예제 #25
0
    def tearDown(self):

        import pyNN.nest as sim
        sim.end()
예제 #26
0
def estimate_kb(cell_params_lif):
    cell_para = copy.deepcopy(cell_params_lif)
    random.seed(0)
    p.setup(timestep=1.0, min_delay=1.0, max_delay=16.0)
    run_s = 10.
    runtime = 1000. * run_s
    max_rate = 1000.
    ee_connector = p.OneToOneConnector(weights=1.0, delays=2.0)    


    pop_list = []
    pop_output = []
    pop_source = []
    x = np.arange(0., 1.01, 0.1)
    count = 0
    trail = 10

    for i in x:
        for j in range(trail): #trails for average
            pop_output.append(p.Population(1, p.IF_curr_exp, cell_para))
            poisson_spikes = mu.poisson_generator(i*max_rate, 0, runtime)
            pop_source.append( p.Population(1, p.SpikeSourceArray, {'spike_times' : poisson_spikes}) )
            p.Projection(pop_source[count], pop_output[count], ee_connector, target='excitatory')
            pop_output[count].record()
            count += 1


    count = 0
    for i in x:
        cell_para['i_offset'] = i
        pop_list.append(p.Population(1, p.IF_curr_exp, cell_para))
        pop_list[count].record()
        count += 1
    pop_list[count-1].record_v()

    p.run(runtime)

    rate_I = np.zeros(count)
    rate_P = np.zeros(count)
    rate_P_max = np.zeros(count)
    rate_P_min = np.ones(count) * 1000.
    for i in range(count):
        spikes = pop_list[i].getSpikes(compatible_output=True)
        rate_I[i] = len(spikes)/run_s
        for j in range(trail):
            spikes = pop_output[i*trail+j].getSpikes(compatible_output=True)
            spike_num = len(spikes)/run_s
            rate_P[i] += spike_num
            if spike_num > rate_P_max[i]:
                rate_P_max[i] = spike_num
            if spike_num < rate_P_min[i]:
                rate_P_min[i] = spike_num
        rate_P[i] /= trail
    '''
    #plot_spikes(spikes, 'Current = 10. mA')
    plt.plot(x, rate_I, label='current',)
    plt.plot(x, rate_P, label='Poisson input')
    plt.fill_between(x, rate_P_min, rate_P_max, facecolor = 'green', alpha=0.3)
    '''
    x0 = np.where(rate_P>1.)[0][0]
    x1 = 4
    k = (rate_P[x1] - rate_P[x0])/(x[x1]-x[x0])
    '''
    plt.plot(x, k*(x-x[x0])+rate_P[x0], label='linear')
    plt.legend(loc='upper left', shadow=True)
    plt.grid('on')
    plt.show()
    '''
    p.end()
    return k, x[x0], rate_P[x0]
            aAnticausalList.append(pynn.nest.GetStatus([connSTDP[i]])[0]['a_acausal'])

    if not timeNow == timeGrid[-1]:
        pynn.run(timeStep)

spikes = neuron.getSpikes()
#membrane = neuron.get_v() #for debugging

print 'presynaptic spikes (static synapse)'
print stimSpikes
print 'presynaptic spikes (plastic synapse)'
print measureSpikes
print 'postsynaptic spikes'
print spikes

pynn.end()

#visualization of results
import matplotlib.pyplot as plt
plt.figure()
plt.plot(timeGrid, weightList, c='b')
plt.xlabel('Time (ms)')
plt.ylabel('Synaptic weight ($\mu$S)')
plt.legend(['Weight'], loc=2)
plt.twinx()
plt.plot(timeGrid, aCausalList, c='g')
plt.plot(timeGrid, aAnticausalList, c='r')
plt.axhline(aThresh, c='k', ls='--')
plt.ylabel('Charge on capacitor (AU)')
plt.legend(['Causal', 'Anticausal', 'Threshold'], loc=1)
plt.savefig('hw_synapse_nest.png')
예제 #28
0
    p.Projection(pop_output, pop_output, p.FromListConnector(conn_list), target='inhibitory')

pop_output.record()
#print strftime("------%Y-%m-%d %H:%M:%S", gmtime()), test_offset
start = time.time()
p.run(num_test*(dur_test+silence))
end = time.time()
b_time = num_test*(dur_test+silence)
sim_str = 'test time:%.4f s, biology time:%d ms\n'%(end-start, b_time)
print sim_str
#f=open('log_nest.txt','a')
#f.write(sim_str)
#f.close()
spikes = pop_output.getSpikes(compatible_output=True)
plot_spikes(spikes,'Output Spikes of Decision Neurons')
p.end()


spike_count = list()
for i in range(num_output):
    index_i = np.where(spikes[:,0] == i)
    spike_train = spikes[index_i, 1]
    temp = np.histogram(spike_train, bins=range(0, (dur_test+silence)*num_test+1,dur_test+silence))[0]
    spike_count.append(temp)
spike_group = list()
for i in range(num_digit):
    for j in range(num_cluster):
        if j == 0:
            temp = spike_count[i*num_cluster]
        else:
            temp = temp + spike_count[i*num_cluster+j]
예제 #29
0
 def end(self):
     sim.end()
# Current
noise = simulator.NoisyCurrentSource(mean=0, stdev=8.0, start=1.0, stop=400.0, dt=1.0)
for i in xrange(N_retina):
    noise.inject_into(retinal_neurons[[i]])

#current = simulator.DCSource(amplitude=3.5, start=1.0, stop=400.0) # Create the current
#currentt.inject_into(retinal_neurons) # Inject the current

# Record the voltage
retinal_neurons.record('v')
lgn_neurons.record(['v', 'spikes'])

# Run the simulation
simulator.run(t)  # Run the simulations for t ms
simulator.end()

# Extract the data
retinal_data = retinal_neurons.get_data()
retinal_segments = retinal_data.segments[0]
retinal_array = retinal_segments.analogsignalarrays[0]

lgn_data = lgn_neurons.get_data()
lgn_segments = lgn_data.segments[0]
lgn_array = lgn_segments.analogsignalarrays[0]

# Get spikes
lgn_spikes = lgn_segments.spiketrains[0] # Get the spikes
y = np.ones_like(lgn_spikes)

spike_times = np.zeros(lgn_spikes.size)
예제 #31
0
"""

Two Fruit Test 
Fruits:
 1: Banana, 0;
 2: Apple, 0.
Chair:
    1: 2

"""

import pyNN.nest as sim
from monkeyProblem import MonekyProblem

sim.setup(timestep=1.0,min_delay=1.0,max_delay=1.0, debug=0)

#mp = MonekyProblem(sim, "spinnaker")
mp = MonekyProblem(sim, "nest")

mp.narc.addFact("chairAt", (2,))
mp.narc.addFact("fruit", ("banana",0))
mp.narc.addFact("fruit", ("apple",0))

mp.narc.apply()

sim.run(200)

mp.printSpikes()

sim.end()
예제 #32
0
    def model(self, sim_index=0, sim_params=None, cell_params=None):
        if sim_params is None :
            sim_params = self.sim_params

        if cell_params is None:
            cell_params = self.cell_params

        # === Build the network =========================================================

        sim.setup(timestep=0.1)#, threads=4)#dt=sim_params['dt'])

        python_rng = rng(seed=self.seed)

        #--setting up nodes and neurons--

        #tuning_function = lambda i, j, B, N : np.exp((np.cos(2.*((i-j)/N*np.pi))-1)/(B*np.pi/180)**2)
        N_in = int(sim_params['nb_neurons']*sim_params['p'])
        self.spike_source = sim.Population(N_in, sim.SpikeSourcePoisson(rate=sim_params['input_rate'], duration=sim_params['simtime']))

        if True: #not sim_params['b_input'] == np.inf:
            angle = 1. * np.arange(N_in)
            rates = self.tuning_function(angle, sim_params['angle_input']/180.*N_in, sim_params['b_input'], N_in)
            rates /= rates.mean()
            rates *= sim_params['input_rate']
            # print(rates)
            for i, cell in enumerate(self.spike_source):
                cell.set_parameters(rate=rates[i])


        if sim_params['neuron_model'] == 'cond_exp':
            model = sim.IF_cond_exp
        elif sim_params['neuron_model'] == 'cond_alpha':
            model = sim.IF_cond_alpha

        E_neurons = sim.Population(N_in,
                                   model(**cell_params),
                                   initial_values={'v': rnd('uniform', (sim_params['v_init_min'], sim_params['v_init_max']))},
                                   label="NE")

        I_neurons = sim.Population(sim_params['nb_neurons'] - N_in,
                                   model(**cell_params),
                                   initial_values={'v': rnd('uniform', (sim_params['v_init_min'], sim_params['v_init_max']))},
                                   label="NI")
        #
        # if sim_params['neuron_model'] == 'cond_alpha':
        #     E_neurons = sim.Population(int(sim_params['nb_neurons'] * sim_params['p']),
        #                                sim.IF_cond_alpha(**cell_params),
        #                                initial_values={'v': rnd('uniform', (sim_params['v_init_min'], sim_params['v_init_max']))},
        #                                label="NE")
        #
        #     I_neurons = sim.Population(sim_params['nb_neurons'] - int(sim_params['nb_neurons'] * sim_params['p']),
        #                                sim.IF_cond_alpha(**cell_params),
        #                                initial_values={'v': rnd('uniform', (sim_params['v_init_min'], sim_params['v_init_max']))},
        #                                label="NI")

         #--Setting up connections and optional injections--
        if self.source == 'sweep':
            sweep = sim.DCSource(amplitude=0.1, start=250.0, stop=500.0)
            sweep.inject_into(E_neurons)

        input_exc = sim.Projection(self.spike_source, E_neurons,
                                #connector=sim.FixedProbabilityConnector(sim_params['c_input_exc'], rng=python_rng),
                                #synapse_type=syn['input_exc'],
                                #receptor_type='excitatory')
                                sim.OneToOneConnector(),
                                sim.StaticSynapse(weight=sim_params['w_input_exc'], delay=sim_params['s_input_exc'])
                                )
                                # syn['input_exc'])

        conn_types = ['exc_inh', 'inh_exc', 'exc_exc', 'inh_inh']   #connection types

        syn = {}
        proj = {}

        for conn_type in conn_types :

            weight = sim_params['w_{}'.format(conn_type)]
            delay=sim_params['s_{}'.format(conn_type)]
            syn[conn_type] = sim.StaticSynapse(delay=delay)#weight=weight,
            if conn_type[:3]=='exc':
                pre_neurons = E_neurons
                receptor_type='excitatory'
            else:
                pre_neurons = I_neurons
                receptor_type='inhibitory'
            if conn_type[-3:]=='exc':
                post_neurons = E_neurons
            else:
                post_neurons = I_neurons

            sparseness = sim_params['c_{}'.format(conn_type)]
            proj[conn_type]  = sim.Projection(pre_neurons, post_neurons,
                                            connector=sim.FixedProbabilityConnector(sparseness, rng=python_rng),
                                            synapse_type=syn[conn_type],
                                            receptor_type=receptor_type)

            bw = sim_params['b_{}'.format(conn_type)]
            angle_pre = 1. * np.arange(proj[conn_type].pre.size)
            angle_post = 1. * np.arange(proj[conn_type].post.size)
            w_ij = self.tuning_function(angle_pre[:, np.newaxis], angle_post[np.newaxis, :], bw, N_in)*weight
            proj[conn_type].set(weight=w_ij)

        # exc_inh = sim.Projection(E_neurons, I_neurons,
        #                         connector=sim.FixedProbabilityConnector(sim_params['c_exc_inh'], rng=python_rng),
        #                         synapse_type=syn['exc_inh'],
        #                         receptor_type='excitatory')
        #
        # inh_exc = sim.Projection(I_neurons, E_neurons,
        #                         connector=sim.FixedProbabilityConnector(sim_params['c_inh_exc'], rng=python_rng),
        #                         synapse_type=syn['inh_exc'],
        #                         receptor_type='inhibitory')
        #
        # exc_exc = sim.Projection(E_neurons, E_neurons,
        #                         connector=sim.FixedProbabilityConnector(sim_params['c_exc_exc'], rng=python_rng),
        #                         synapse_type=syn['exc_exc'],
        #                         receptor_type='excitatory')
        #
        # inh_inh = sim.Projection(I_neurons, I_neurons,
        #                         connector=sim.FixedProbabilityConnector(sim_params['c_inh_inh'], rng=python_rng),
        #                         synapse_type=syn['inh_inh'],
        #                         receptor_type='inhibitory')
        #
        # v = locals()
        # for conn_type in conn_types :
        #     proj = v['{}'.format(conn_type)]
        #     if not bw == np.inf:
        #         angle_pre = 1. * np.arange(proj.pre.size)
        #         angle_post = 1. * np.arange(proj.post.size)
        #         w = tuning_function(angle_pre[:, np.newaxis], angle_post[np.newaxis, :], bw, N_in)*w
        #         proj.set(weight=w)
        #

        #--setting up recording--
        self.spike_source.record('spikes')
        E_neurons.record('spikes')
        I_neurons.record('spikes')

        # === Run simulation ============================================================
        sim.run(sim_params['simtime'])

        # === Save ROI data and CV computing ============================================
        spikesE = E_neurons.get_data().segments[0]
        spikesI = I_neurons.get_data().segments[0]
        self.spikesP = self.spike_source.get_data().segments[0]

        self.spikesE = spikesE
        self.spikesI = spikesI

        #------- computing cv -------
        all_CVs = np.array([])
        for st in spikesE.spiketrains :
            all_CVs = np.append(all_CVs, SpikeTrain(np.array(st)).cv_isi())
        for st in spikesI.spiketrains :
            all_CVs = np.append(all_CVs, SpikeTrain(np.array(st)).cv_isi())
        #-----------------------------

        megadico = sim_params.copy()
        megadico.update(cell_params.copy())
        megadico.update({'m_f_rateE': E_neurons.mean_spike_count()})
        megadico.update({'m_f_rateI': I_neurons.mean_spike_count()})
        megadico.update({'m_f_rate' : (E_neurons.mean_spike_count()*sim_params['p'] + I_neurons.mean_spike_count()*(1-sim_params['p']))*1000.0/sim_params['simtime']})
        megadico.update({'cv' : np.nanmean(all_CVs)})

        # === Clearing and return data ==================================================
        sim.end()
        df = ps.DataFrame(data = megadico, index = [sim_index])
        return df, spikesE, spikesI
예제 #33
0
def _run_microcircuit(plot_filename, conf):
    import plotting
    import logging

    simulator = conf['simulator']
    # we here only need nest as simulator, simulator = 'nest'
    import pyNN.nest as sim

    # prepare simulation
    logging.basicConfig()

    # extract parameters from config file
    master_seed = conf['params_dict']['nest']['master_seed']
    layers = conf['layers']
    pops = conf['pops']
    plot_spiking_activity = conf['plot_spiking_activity']
    raster_t_min = conf['raster_t_min']
    raster_t_max = conf['raster_t_max']
    frac_to_plot = conf['frac_to_plot']
    record_corr = conf['params_dict']['nest']['record_corr']
    tau_max = conf['tau_max']

    # Numbers of neurons from which to record spikes
    n_rec = helper_functions.get_n_rec(conf)

    sim.setup(**conf['simulator_params'][simulator])

    if simulator == 'nest':
        n_vp = sim.nest.GetKernelStatus('total_num_virtual_procs')
        if sim.rank() == 0:
            print 'n_vp: ', n_vp
            print 'master_seed: ', master_seed
        sim.nest.SetKernelStatus({'print_time': False,
                                  'dict_miss_is_error': False,
                                  'grng_seed': master_seed,
                                  'rng_seeds': range(master_seed + 1,
                                                     master_seed + n_vp + 1),
                                  'data_path': conf['system_params'] \
                                                   ['output_path']})

    import network

    # result of export-files
    results = []

    # create network
    start_netw = time.time()
    n = network.Network(sim)

    # contains the GIDs of the spike detectors and voltmeters needed for
    # retrieving filenames later
    device_list = n.setup(sim, conf)

    end_netw = time.time()
    if sim.rank() == 0:
        print 'Creating the network took ', end_netw - start_netw, ' s'

    # simulate
    if sim.rank() == 0:
        print "Simulating..."
    start_sim = time.time()
    sim.run(conf['simulator_params'][simulator]['sim_duration'])
    end_sim = time.time()
    if sim.rank() == 0:
        print 'Simulation took ', end_sim - start_sim, ' s'

    # extract filename from device_list (spikedetector/voltmeter),
    # gid of neuron and thread. merge outputs from all threads
    # into a single file which is then added to the task output.
    for dev in device_list:
        label = sim.nest.GetStatus(dev)[0]['label']
        gid = sim.nest.GetStatus(dev)[0]['global_id']
        # use the file extension to distinguish between spike and voltage
        # output
        extension = sim.nest.GetStatus(dev)[0]['file_extension']
        if extension == 'gdf':  # spikes
            data = np.empty((0, 2))
        elif extension == 'dat':  # voltages
            data = np.empty((0, 3))
        for thread in xrange(conf['simulator_params']['nest']['threads']):
            filenames = glob.glob(conf['system_params']['output_path']
                                  + '%s-*%d-%d.%s' % (label, gid, thread, extension))
            assert(
                len(filenames) == 1), 'Multiple input files found. Use a clean output directory.'
            data = np.vstack([data, np.loadtxt(filenames[0])])
            # delete original files
            os.remove(filenames[0])
        order = np.argsort(data[:, 1])
        data = data[order]
        outputfile_name = 'collected_%s-%d.%s' % (label, gid, extension)
        outputfile = open(outputfile_name, 'w')
        # the outputfile should have same format as output from NEST.
        # i.e., [int, float] for spikes and [int, float, float] for voltages,
        # hence we write it line by line and assign the corresponding filetype
        if extension == 'gdf':  # spikes
            for line in data:
                outputfile.write('%d\t%.3f\n' % (line[0], line[1]))
            outputfile.close()
            filetype = 'application/vnd.juelich.nest.spike_times'

        elif extension == 'dat':  # voltages
            for line in data:
                outputfile.write(
                    '%d\t%.3f\t%.3f\n' % (line[0], line[1], line[2]))
            outputfile.close()
            filetype = 'application/vnd.juelich.nest.analogue_signal'

        res = (outputfile_name, filetype)
        results.append(res)

    if record_corr and simulator == 'nest':
        start_corr = time.time()
        if sim.nest.GetStatus(n.corr_detector, 'local')[0]:
            print 'getting count_covariance on rank ', sim.rank()
            cov_all = sim.nest.GetStatus(
                n.corr_detector, 'count_covariance')[0]
            delta_tau = sim.nest.GetStatus(n.corr_detector, 'delta_tau')[0]

            cov = {}
            for target_layer in np.sort(layers.keys()):
                for target_pop in pops:
                    target_index = conf['structure'][target_layer][target_pop]
                    cov[target_index] = {}
                    for source_layer in np.sort(layers.keys()):
                        for source_pop in pops:
                            source_index = conf['structure'][
                                source_layer][source_pop]
                            cov[target_index][source_index] = \
                                np.array(list(
                                    cov_all[target_index][source_index][::-1])
                                + list(cov_all[source_index][target_index][1:]))

            f = open(conf['system_params'][
                     'output_path'] + '/covariances.dat', 'w')
            print >>f, 'tau_max: ', tau_max
            print >>f, 'delta_tau: ', delta_tau
            print >>f, 'simtime: ', conf['simulator_params'][
                simulator]['sim_duration'], '\n'

            for target_layer in np.sort(layers.keys()):
                for target_pop in pops:
                    target_index = conf['structure'][target_layer][target_pop]
                    for source_layer in np.sort(layers.keys()):
                        for source_pop in pops:
                            source_index = conf['structure'][
                                source_layer][source_pop]
                            print >>f, target_layer, target_pop, '-', source_layer, source_pop
                            print >>f, 'n_events_target: ', sim.nest.GetStatus(
                                n.corr_detector, 'n_events')[0][target_index]
                            print >>f, 'n_events_source: ', sim.nest.GetStatus(
                                n.corr_detector, 'n_events')[0][source_index]
                            for i in xrange(len(cov[target_index][source_index])):
                                print >>f, cov[target_index][source_index][i]
                            print >>f, ''
            f.close()

            # add file covariances.dat into bundle
            res_cov = ('covariances.dat',
                       'text/plain')
            results.append(res_cov)

        end_corr = time.time()
        print "Writing covariances took ", end_corr - start_corr, " s"

    if plot_spiking_activity and sim.rank() == 0:
        plotting.plot_raster_bars(raster_t_min, raster_t_max, n_rec,
                                  frac_to_plot, n.pops,
                                  conf['system_params']['output_path'],
                                  plot_filename, conf)
        res_plot = (plot_filename, 'image/png')
        results.append(res_plot)

    sim.end()

    return results
예제 #34
0
from network_builder import createCooperativeNetwork, createSpikeSource
from plotter import plotSimulationResults 
from network_parameters import *

# setup timestep of simulation and minimum and maximum synaptic delays
setup(timestep=0.1, min_delay=0.1, max_delay=5.0)

# 3,4,5,6,7,8,9,10,11,12,13,15,16,17,
# create a spike sources firing at specific spiking times
spikingTimingLeft = [ [[20, 100, 101, 110, 130], [14, 19, 20,30,40,50, 90, 200.6], [90, 100.5], [100.5], [100.5], [100.5]] ]
retinaLeft = createSpikeSource(dx = dimensionRetinaX, dy = dimensionRetinaY, timing = spikingTimingLeft, labelSS = "Left Retina")
spikingTimingRight = [ [[2,3,4,5,6, 500.5], [18, 100, 100.6], [ 15, 100, 110, 120, 130], [100.5], [1000.5], [1000.5]] ]
retinaRight = createSpikeSource(dx = dimensionRetinaX, dy = dimensionRetinaY, timing = spikingTimingRight, labelSS = "Right Retina")

# create network and attach the spike sources 
## TODO: Change to dz= disparityMax when advanced configuration and connections are implemented
network = createCooperativeNetwork(dx = dimensionRetinaX, dy = dimensionRetinaY, dz = dimensionRetinaX, 
	spikeSourceL = retinaLeft, spikeSourceR = retinaRight)

# run simulation for time in milliseconds
simulationTime = 30.0
run(simulationTime)

# plot results s
plotSimulationResults(network, retinaLeft, retinaRight, int(simulationTime), layer=0)

# finalise program and simulation
end()