Пример #1
0
def load(userFileName, dataType):
    """
    load(userFileName, dataType)
    Convenient data loader for results saved as NeuroTools StandardPickleFile. 
    Return the corresponding NeuroTools object. Datatype argument may become 
    optionnal in the future, but for now it is necessary to specify the type 
    of the recorded data. To have a better control on the parameters of the 
    NeuroTools objects, see the load_*** functions.
    
    Inputs:
        userFileName - the user file name
        datatype - A string to specify the type od the data in
                    's' : spikes
                    'g' : conductances
                    'v' : membrane traces
                    'c' : currents
    """
    userFile = StandardPickleFile(userFileName)

    if dataType in ('s', 'spikes'):
        return signals.load_spikelist(userFile)
    elif dataType == 'v':

        #  Need t_start to be None, othervice NeuroTools overwrite loaded
        # t_start with default value 0
        return signals.load_vmlist(userFile, t_start=None)
    elif dataType == 'c':
        return signals.load_currentlist(userFile, t_start=None)
    elif dataType == 'g':
        return signals.load_conductancelist(userFile, t_start=None)
    else:
        raise Exception(
            "The datatype %s is not handled ! Should be 's','g','c' or 'v'" %
            datatype)
Пример #2
0
    def setUp(self):
        #We could run the test from anywhere...
        self.p = '/'.join(os.path.realpath(__file__).split('/')[:-1])

        #The following are used for the make_kernel testcases
        self.box = scipy.io.loadmat(self.p + '/analysis/make_kernel/box.mat')
        self.tri = scipy.io.loadmat(self.p + '/analysis/make_kernel/tri.mat')
        self.epa = scipy.io.loadmat(self.p + '/analysis/make_kernel/epa.mat')
        self.gau = scipy.io.loadmat(self.p + '/analysis/make_kernel/gau.mat')
        self.alp = scipy.io.loadmat(self.p + '/analysis/make_kernel/alp.mat')
        self.exp = scipy.io.loadmat(self.p + '/analysis/make_kernel/exp.mat')
        self.alp_reversed = scipy.io.loadmat(self.p + '/analysis/make_kernel/alp_reversed.mat')
        self.exp_reversed = scipy.io.loadmat(self.p + '/analysis/make_kernel/exp_reversed.mat')

        #Used for the testcases of the crosscorrelate function
        spk = signals.load_spikelist(self.p + '/analysis/crosscorrelate/spike_data')
        self.spk0 = spk[0]
        self.spk1 = spk[1]
Пример #3
0
    def setUp(self):
        #We could run the test from anywhere...
        self.p = '/'.join(os.path.realpath(__file__).split('/')[:-1])

        #The following are used for the make_kernel testcases
        self.box = scipy.io.loadmat(self.p + '/analysis/make_kernel/box.mat')
        self.tri = scipy.io.loadmat(self.p + '/analysis/make_kernel/tri.mat')
        self.epa = scipy.io.loadmat(self.p + '/analysis/make_kernel/epa.mat')
        self.gau = scipy.io.loadmat(self.p + '/analysis/make_kernel/gau.mat')
        self.alp = scipy.io.loadmat(self.p + '/analysis/make_kernel/alp.mat')
        self.exp = scipy.io.loadmat(self.p + '/analysis/make_kernel/exp.mat')
        self.alp_reversed = scipy.io.loadmat(
            self.p + '/analysis/make_kernel/alp_reversed.mat')
        self.exp_reversed = scipy.io.loadmat(
            self.p + '/analysis/make_kernel/exp_reversed.mat')

        #Used for the testcases of the crosscorrelate function
        spk = signals.load_spikelist(self.p +
                                     '/analysis/crosscorrelate/spike_data')
        self.spk0 = spk[0]
        self.spk1 = spk[1]
Пример #4
0
    def run(self, params, verbose=True):
        tmpdir = tempfile.mkdtemp()
        timer = Timer()
        timer.start()  # start timer on construction

        # === Build the network ========================================================
        if verbose: print "Setting up simulation"
        sim.setup(timestep=params.simulation.dt,
                  max_delay=params.simulation.syn_delay,
                  debug=False)

        N = params.N
        #dc_generator
        current_source = sim.DCSource(amplitude=params.snr,
                                      start=params.simulation.simtime / 4,
                                      stop=params.simulation.simtime / 4 * 3)

        # internal noise model (NEST specific)
        noise = sim.Population(N, 'noise_generator', {
            'mean': 0.,
            'std': params.noise_std
        })
        # target population
        output = sim.Population(N, sim.IF_cond_exp)

        # initialize membrane potential
        numpy.random.seed(params.simulation.kernelseed)
        V_rest, V_spike = -70., -53.
        output.tset('v_init',
                    V_rest + numpy.random.rand(N, ) * (V_spike - V_rest))

        #  Connecting the network
        conn = sim.OneToOneConnector(weights=params.weight)
        sim.Projection(noise, output, conn)

        for cell in output:
            cell.inject(current_source)

        output.record()

        # reads out time used for building
        buildCPUTime = timer.elapsedTime()

        # === Run simulation ===========================================================
        if verbose: print "Running simulation"

        timer.reset()  # start timer on construction
        sim.run(params.simulation.simtime)
        simCPUTime = timer.elapsedTime()

        timer.reset()  # start timer on construction

        output_filename = os.path.join(tmpdir, 'output.gdf')
        #print output_filename
        output.printSpikes(output_filename)  #
        output_DATA = load_spikelist(output_filename,
                                     N,
                                     t_start=0.0,
                                     t_stop=params.simulation.simtime)
        writeCPUTime = timer.elapsedTime()

        if verbose:
            print "\nFiber Network Simulation:"
            print "Number of Neurons  : ", N
            print "Mean Output rate    : ", output_DATA.mean_rate(
            ), "Hz during ", params.simulation.simtime, "ms"
            print("Build time             : %g s" % buildCPUTime)
            print("Simulation time        : %g s" % simCPUTime)
            print("Writing time           : %g s" % writeCPUTime)

        os.remove(output_filename)
        os.rmdir(tmpdir)

        return output_DATA
Пример #5
0
pl.rcParams['legend.fontsize'] = 'small'


# load simulation parameters
network_params = simulation_parameters.parameter_storage()  # network_params class containing the simulation parameters
params = network_params.load_params()                       # params stores cell numbers, etc as a dictionary

src = 0
tgt = 2
sim_cnt = 0

gid_list = [src, tgt]
gid_list.sort()
fn = params['exc_spiketimes_fn_merged'] + str(sim_cnt) + '.ras'

spklist = nts.load_spikelist(fn)#, range(params['n_exc_per_mc']), t_start=0, t_stop=params['t_sim'])
spiketrains = spklist.spiketrains
spiketimes_pre = spiketrains[src+1.].spike_times
spiketimes_post = spiketrains[tgt+1.].spike_times

# plot spikes
markersize = 10
fig = pl.figure()
ax = fig.add_subplot(611)
for gid in gid_list:

#    fn = params['exc_spiketimes_fn_base'] + str(gid) + '.ras'
#    d = np.loadtxt(fn)
#    ax.plot(d[:, 0], np.ones(d[:,0].size)*gid, '|', markersize=markersize, color='k')
    
    d = spiketrains[gid+1.].spike_times
Пример #6
0
def bcpnn_offline_noColumns(params, conn_list, sim_cnt=0, save_all=False, comm=None):
    """
    This function computes the weight and bias values based on spiketimes during the simulation.

    Arguments:
        params: parameter dictionary
        conn_list:  two-dim numpy array storing cell-to-cell connections (only non-zero elements will be processed)
                            in the format (src, tgt, weight, delay)
                            or
                            file name in which the date is stored in this way
        sim_cnt: int for recording to file
        save_all: if True all traces will be saved
        comm = MPI communicator

    """
    if (type(conn_list) == type('')):
        d = np.load(conn_list)

    if (comm != None):
        pc_id, n_proc = comm.rank, comm.size
    else:
        pc_id, n_proc = 0, 1
    # extract the local list of elements 'my_conns' from the global conn_list
    n_total = len(conn_list)
    (min_id, max_id) = utils.distribute_n(n_total, n_proc, pc_id)
    my_conns = [(conn_list[i, 0], conn_list[i, 1], conn_list[i, 2], conn_list[i, 3]) for i in xrange(min_id, max_id)]

    fn = params['exc_spiketimes_fn_merged'] + str(sim_cnt) + '.ras'
    spklist = nts.load_spikelist(fn)#, range(params['n_exc_per_mc']), t_start=0, t_stop=params['t_sim'])
    spiketrains = spklist.spiketrains

    new_conn_list = np.zeros((len(my_conns), 4)) # (src, tgt, weight, delay)
    bias_dict = {}
    for i in xrange(params['n_exc']):
        bias_dict[i] = None
    
    for i in xrange(len(my_conns)):
#    for i in xrange(2):
        pre_id = my_conns[i][0]
        post_id = my_conns[i][1]

        # create traces from spiketimes
        # pre
        spiketimes_pre = spiketrains[pre_id+1.].spike_times
        pre_trace = utils.convert_spiketrain_to_trace(spiketimes_pre, params['t_sim'] + 1) # + 1 is to handle spikes in the last time step
        # post
        spiketimes_post = spiketrains[post_id+1.].spike_times
        post_trace = utils.convert_spiketrain_to_trace(spiketimes_post, params['t_sim'] + 1) # + 1 is to handle spikes in the last time step

        # compute
#        print "%d Computing traces for %d -> %d; %.2f percent " % (pc_id, pre_id, post_id, i / float(len(my_conns)) * 100.)
        get_traces = save_all
        if (get_traces):
            wij, bias, pi, pj, pij, ei, ej, eij, zi, zj = get_spiking_weight_and_bias(pre_trace, post_trace, get_traces)
            dw = (wij.max() - wij.min()) * params['dw_scale']
            # bias update
            new_bias = bias.max()
        else:
            dw, new_bias = get_spiking_weight_and_bias(pre_trace, post_trace, get_traces)
            dw *= params['dw_scale']

        # bias update
        if bias_dict[post_id] == None:
            bias_dict[post_id] = new_bias


        # weight update
        new_conn_list[i, 0] = pre_id
        new_conn_list[i, 1] = post_id
        new_conn_list[i, 2] = dw + my_conns[i][2]
        new_conn_list[i, 3] = my_conns[i][3]

#        print "DEBUG Pc %d \t%d\t%d\t%.1e\t%.1e\tbias:%.4e\tconn:" % (pc_id, new_conn_list[i, 0], new_conn_list[i, 1],  new_conn_list[i, 2],  new_conn_list[i, 3], new_bias[i, 1]), my_conns[i]
        if (save_all):
            # save
            output_fn = params['weights_fn_base'] + "%d_%d.npy" % (pre_id, post_id)
            np.save(output_fn, wij)

            output_fn = params['bias_fn_base'] + "%d.npy" % (post_id)
            np.save(output_fn, bias)

            output_fn = params['ztrace_fn_base'] + "%d.npy" % pre_id
            np.save(output_fn, zi)
            output_fn = params['ztrace_fn_base'] + "%d.npy" % post_id
            np.save(output_fn, zj)

            output_fn = params['etrace_fn_base'] + "%d.npy" % pre_id
            np.save(output_fn, ei)
            output_fn = params['etrace_fn_base'] + "%d.npy" % post_id
            np.save(output_fn, ej)
            output_fn = params['etrace_fn_base'] + "%d_%d.npy" % (pre_id, post_id)
            np.save(output_fn, eij)

            output_fn = params['ptrace_fn_base'] + "%d.npy" % pre_id
            np.save(output_fn, pi)
            output_fn = params['ptrace_fn_base'] + "%d.npy" % post_id
            np.save(output_fn, pj)
            output_fn = params['ptrace_fn_base'] + "%d_%d.npy" % (pre_id, post_id)
            np.save(output_fn, pij)

    if (n_proc > 1):
        output_fn_conn_list = params['conn_list_ee_fn_base'] + str(sim_cnt+1) + '.dat'
        utils.gather_conn_list(comm, new_conn_list, n_total, output_fn_conn_list)

        output_fn_bias = params['bias_values_fn_base'] + str(sim_cnt+1) + '.dat'
        utils.gather_bias(comm, bias_dict, n_total, output_fn_bias)

    else:
        print "Debug saving to", params['conn_list_ee_fn_base'] + str(sim_cnt+1) + '.dat'
        np.savetxt(params['conn_list_ee_fn_base'] + str(sim_cnt+1) + '.dat', my_conns)#conn_list)
        print "Debug saving to", params['bias_values_fn_base'] + str(sim_cnt+1) + '.dat'
        np.savetxt(params['bias_values_fn_base'] + str(sim_cnt+1) + '.dat', bias)
Пример #7
0
def bcpnn_offline(params, connection_matrix, sim_cnt=0, pc_id=0, n_proc=1, save_all=False):
    """
    Arguments:
        params: parameter dictionary
        connection_matrix: two-dim numpy array storing cell-to-cell connections (only non-zero elements will be processed)
                            or
                           file name
        sim_cnt: int for recording to file

    This function does basically the same thing as the script bcpnn_offline.py
    """
    if (type(connection_matrix) == type('')):
        connection_matrix = np.load(connection_matrix)
    non_zeros = connection_matrix.nonzero()
    conns = zip(non_zeros[0], non_zeros[1])
    my_conns = utils.distribute_list(conns, n_proc, pc_id)

    n, m = connection_matrix.shape
    for i in xrange(len(my_conns)):
#    for i in xrange(2):
        pre_id = my_conns[i][0]
        post_id = my_conns[i][1]

        # extract the spike times from the file where all cells belonging to one minicolumn are stored
        # pre
        mc_index_pre = pre_id / params['n_exc_per_mc']
        fn_pre = params['exc_spiketimes_fn_base'] + str(pre_id) + '.ras'
        spklist_pre = nts.load_spikelist(fn_pre, range(params['n_exc_per_mc']), t_start=0, t_stop=params['t_sim'])
        spiketimes_pre = spklist_pre[pre_id % params['n_exc_per_mc']].spike_times # TODO: check: + 1 for NeuroTools 
        pre_trace = utils.convert_spiketrain_to_trace(spiketimes_pre, params['t_sim'] + 1) # + 1 is to handle spikes in the last time step

        # post
        mc_index_post = post_id / params['n_exc_per_mc']
        fn_post = params['exc_spiketimes_fn_base'] + str(post_id) + '.ras'
        spklist_post = nts.load_spikelist(fn_post, range(params['n_exc_per_mc']), t_start=0, t_stop=params['t_sim'])
        spiketimes_post = spklist_post[post_id % params['n_exc_per_mc']].spike_times# TODO: check: + 1 for NeuroTools 
        post_trace = utils.convert_spiketrain_to_trace(spiketimes_post, params['t_sim'] + 1)

        # compute
        wij, bias, pi, pj, pij, ei, ej, eij, zi, zj = get_spiking_weight_and_bias(pre_trace, post_trace)

        # update
        dw = (wij.max() - wij.min()) * params['dw_scale']
        print "DEBUG, updating weight[%d, %d] by %.1e to %.1e" % (pre_id, post_id, dw, connection_matrix[pre_id, post_id] + dw)
        connection_matrix[pre_id, post_id] += dw
        bias[post_id] = bias.max()
        
        ids_to_save = []
        if (save_all):
            ids_to_save = []

        if (save_all):
            # save
            output_fn = params['weights_fn_base'] + "%d_%d.npy" % (pre_id, post_id)
            np.save(output_fn, wij)

            output_fn = params['bias_fn_base'] + "%d.npy" % (post_id)
            np.save(output_fn, bias)

            output_fn = params['ztrace_fn_base'] + "%d.npy" % pre_id
            np.save(output_fn, zi)
            output_fn = params['ztrace_fn_base'] + "%d.npy" % post_id
            np.save(output_fn, zj)

            output_fn = params['etrace_fn_base'] + "%d.npy" % pre_id
            np.save(output_fn, ei)
            output_fn = params['etrace_fn_base'] + "%d.npy" % post_id
            np.save(output_fn, ej)
            output_fn = params['etrace_fn_base'] + "%d_%d.npy" % (pre_id, post_id)
            np.save(output_fn, eij)

            output_fn = params['ptrace_fn_base'] + "%d.npy" % pre_id
            np.save(output_fn, pi)
            output_fn = params['ptrace_fn_base'] + "%d.npy" % post_id
            np.save(output_fn, pj)
            output_fn = params['ptrace_fn_base'] + "%d_%d.npy" % (pre_id, post_id)
            np.save(output_fn, pij)

    print "debug", params['conn_mat_ee_fn_base'] + str(sim_cnt+1) + '.npy'
    np.savetxt(params['conn_mat_ee_fn_base'] + str(sim_cnt+1) + '.npy', connection_matrix)
    print "debug", params['bias_values_fn_base'] + str(sim_cnt+1) + '.npy'
    np.savetxt(params['bias_values_fn_base'] + str(sim_cnt+1) + '.npy', bias)

    return connection_matrix, bias
Пример #8
0
        sortmap = pylab.argsort(cell_ids, kind='mergesort')
        cell_ids = pylab.take(cell_ids,sortmap)
        allvdata = pylab.take(allvdata,sortmap)
        for i in 0,1:
            tdata = pylab.arange(0,(n+1)*dt,dt)
            vdata = allvdata.compress(cell_ids==i)
            vdata = pylab.where(vdata>=v_thresh-0.05,0.0,vdata) # add fake APs for plotting
            if len(tdata) > len(vdata):
                print "Warning. Shortening tdata from %d to %d elements (%s)" % (len(tdata),len(vdata),simulator)
                tdata = tdata[0:len(vdata)]
            assert len(tdata)==len(vdata), "%d != %d (%s)" % (len(tdata),len(vdata),simulator)
            subplot.plot(tdata,vdata)
        
        # Plot spike rasters
        subplot = figure.add_axes([x,y0+2*dy,w,h])
        exc_spikedata = signals.load_spikelist("Results/VAbenchmark_%s_exc_%s_np%d.ras" % (benchmark, simulator, num_nodes))
        inh_spikedata = signals.load_spikelist("Results/VAbenchmark_%s_inh_%s_np%d.ras" % (benchmark, simulator, num_nodes))
        exc_spikedata.raster_plot(display=subplot)

        # Inter-spike-interval histograms
        bins = pylab.exp(pylab.arange(0, 8, 0.2))
        isihist, bins = exc_spikedata.isi_hist(bins)
        subplot = figure.add_axes([x,y0+dy,0.4*w,h])
        plot_hist(subplot, isihist, pylab.arange(0, 8, 0.2), 0.2,
            xlabel="Inter-spike interval (ms)", xticks=pylab.log([3,10,30,100,1000]),
            xticklabels=['3','10','30','100','1000'], xmin=pylab.log(2), ymax=0.006)
        subplot.set_title('Exc')
        
        isihist, bins = inh_spikedata.isi_hist(bins)
        subplot = figure.add_axes([x+0.45*dx,y0+dy,0.4*w,h])
        plot_hist(subplot, isihist, pylab.arange(0,8,0.2),0.2,
Пример #9
0
"""
Example to show off some capabilities of the signals module 
and the SpikeList and AnalogSignalList class.

- loads spiking and voltage data simulated with pyNN
- calculates various measurements (mean firing rate, cv...)
- plot the signals
- plots the spike-triggered-averages

Performed at the NeuroTools demo session, INCF booth, 
SfN annual meeting 2008, Washington. DC.
"""
import NeuroTools.signals as signals

# loading spiking data
s = signals.load_spikelist('spike_data')

# raster plot
s.raster_plot()

# mean rate
print 'mean rate: ', s.mean_rate()
print 'mean rates: ', s.mean_rates()
# fano factor of isi
print 'fano factor of isi: ', s.fano_factors_isi()
# cv of isi
print 'cv of isi:', s.cv_isi()

# isi distribution
hs = s.isi_hist(bins=20, display=True)
    def run(self,params, verbose =True):
        tmpdir = tempfile.mkdtemp()
        timer = Timer()
        timer.start() # start timer on construction

        # === Build the network ========================================================
        if verbose: print "Setting up simulation"
        sim.setup(timestep=params.simulation.dt,max_delay=params.simulation.syn_delay, debug=False)

        N = params.N
        #dc_generator
        current_source = sim.DCSource(  amplitude= params.snr,
                                        start=params.simulation.simtime/4,
                                        stop=params.simulation.simtime/4*3)
        
        # internal noise model (NEST specific)
        noise = sim.Population(N,'noise_generator',{'mean':0.,'std':params.noise_std}) 
        # target population
        output = sim.Population(N , sim.IF_cond_exp)

        # initialize membrane potential
        numpy.random.seed(params.simulation.kernelseed)
        V_rest, V_spike = -70., -53.
        output.tset('v_init',V_rest + numpy.random.rand(N,)* (V_spike -V_rest))

        #  Connecting the network
        conn = sim.OneToOneConnector(weights = params.weight)
        sim.Projection(noise, output, conn)

        for cell in output:
            cell.inject(current_source)

        output.record()

        # reads out time used for building
        buildCPUTime= timer.elapsedTime()

        # === Run simulation ===========================================================
        if verbose: print "Running simulation"

        timer.reset() # start timer on construction
        sim.run(params.simulation.simtime)
        simCPUTime = timer.elapsedTime()

        timer.reset()  # start timer on construction

        output_filename = os.path.join(tmpdir,'output.gdf')
        #print output_filename
        output.printSpikes(output_filename)#
        output_DATA = load_spikelist(output_filename,N,
                                        t_start=0.0, t_stop=params.simulation.simtime)
        writeCPUTime = timer.elapsedTime()

        if verbose:
            print "\nFiber Network Simulation:"
            print "Number of Neurons  : ", N
            print "Mean Output rate    : ", output_DATA.mean_rate(), "Hz during ",params.simulation.simtime, "ms"
            print("Build time             : %g s" % buildCPUTime)
            print("Simulation time        : %g s" % simCPUTime)
            print("Writing time           : %g s" % writeCPUTime)

        os.remove(output_filename)
        os.rmdir(tmpdir)

        return output_DATA
Пример #11
0
    def run(self, params, verbose=True):
        """
        params are the parameters to use

        """
        tmpdir = tempfile.mkdtemp()
        myTimer = Timer()
        # === Build the network ========================================================
        if verbose: print "Setting up simulation"
        myTimer.start()  # start timer on construction
        sim.setup(timestep=params['dt'], max_delay=params['syn_delay'])
        N = params['N']
        #dc_generator
        phr_ON = sim.Population((N, ), 'dc_generator')
        phr_OFF = sim.Population((N, ), 'dc_generator')

        for factor, phr in [(-params['snr'], phr_OFF),
                            (params['snr'], phr_ON)]:
            phr.tset('amplitude', params['amplitude'] * factor)
            phr.set({
                'start': params['simtime'] / 4,
                'stop': params['simtime'] / 4 * 3
            })

        # internal noise model (see benchmark_noise)
        noise_ON = sim.Population((N, ), 'noise_generator', {
            'mean': 0.,
            'std': params['noise_std']
        })
        noise_OFF = sim.Population((N, ), 'noise_generator', {
            'mean': 0.,
            'std': params['noise_std']
        })

        # target ON and OFF populations (what about a tridimensional Population?)
        out_ON = sim.Population(
            (N, ), sim.IF_curr_alpha
        )  #'IF_cond_alpha) #iaf_sfa_neuron')# EIF_cond_alpha_isfa_ista, IF_cond_exp_gsfa_grr,sim.IF_cond_alpha)#'iaf_sfa_neuron',params['parameters_gc'])#'iaf_cond_neuron')# IF_cond_alpha) #
        out_OFF = sim.Population(
            (N, ), sim.IF_curr_alpha
        )  #'IF_cond_alpha) #IF_curr_alpha)#'iaf_sfa_neuron')#sim.IF_curr_alpha)#,params['parameters_gc'])

        # initialize membrane potential TODO: and conductances?
        from pyNN.random import RandomDistribution, NumpyRNG
        rng = NumpyRNG(seed=params['kernelseed'])
        vinit_distr = RandomDistribution(distribution='uniform',
                                         parameters=[-70, -55],
                                         rng=rng)
        for out_ in [out_ON, out_OFF]:
            out_.randomInit(vinit_distr)

        retina_proj_ON = sim.Projection(phr_ON, out_ON,
                                        sim.OneToOneConnector())
        retina_proj_ON.setWeights(params['weight'])
        # TODO fix setWeight, add setDelays to 10 ms (relative to stimulus onset)
        retina_proj_OFF = sim.Projection(phr_OFF, out_OFF,
                                         sim.OneToOneConnector())
        retina_proj_OFF.setWeights(params['weight'])

        noise_proj_ON = sim.Projection(noise_ON, out_ON,
                                       sim.OneToOneConnector())
        noise_proj_ON.setWeights(params['weight'])
        noise_proj_OFF = sim.Projection(
            noise_OFF, out_OFF, sim.OneToOneConnector(
            ))  # implication if ON and OFF have the same noise input?
        noise_proj_OFF.setWeights(params['weight'])

        out_ON.record()
        out_OFF.record()

        # reads out time used for building
        buildCPUTime = myTimer.elapsedTime()

        # === Run simulation ===========================================================
        if verbose: print "Running simulation"

        myTimer.reset()  # start timer on construction
        sim.run(params['simtime'])
        simCPUTime = myTimer.elapsedTime()

        myTimer.reset()  # start timer on construction
        # TODO LUP use something like "for pop in [phr, out]" ?
        out_ON_filename = os.path.join(tmpdir, 'out_on.gdf')
        out_OFF_filename = os.path.join(tmpdir, 'out_off.gdf')
        out_ON.printSpikes(out_ON_filename)  #
        out_OFF.printSpikes(out_OFF_filename)  #

        # TODO LUP  get out_ON_DATA on a 2D grid independantly of out_ON.cell.astype(int)
        out_ON_DATA = load_spikelist(out_ON_filename,
                                     range(N),
                                     t_start=0.0,
                                     t_stop=params['simtime'])
        out_OFF_DATA = load_spikelist(out_OFF_filename,
                                      range(N),
                                      t_start=0.0,
                                      t_stop=params['simtime'])

        out = {
            'out_ON_DATA': out_ON_DATA,
            'out_OFF_DATA': out_OFF_DATA
        }  #,'out_ON_pos':out_ON}
        # cleans up
        os.remove(out_ON_filename)
        os.remove(out_OFF_filename)
        os.rmdir(tmpdir)
        writeCPUTime = myTimer.elapsedTime()

        if verbose:
            print "\nRetina Network Simulation:"
            print(params['description'])
            print "Number of Neurons  : ", N
            print "Output rate  (ON) : ", out_ON_DATA.mean_rate(
            ), "Hz/neuron in ", params['simtime'], "ms"
            print "Output rate (OFF)   : ", out_OFF_DATA.mean_rate(
            ), "Hz/neuron in ", params['simtime'], "ms"
            print("Build time             : %g s" % buildCPUTime)
            print("Simulation time        : %g s" % simCPUTime)
            print("Writing time           : %g s" % writeCPUTime)

        return out
Пример #12
0
    def run(self, params, verbose=True):
        """
        params are the parameters to use

        """
        tmpdir = tempfile.mkdtemp()
        myTimer = Timer()
        # === Build the network ========================================================
        if verbose:
            print "Setting up simulation"
        myTimer.start()  # start timer on construction
        sim.setup(timestep=params["dt"], max_delay=params["syn_delay"])
        N = params["N"]
        # dc_generator
        phr_ON = sim.Population((N,), "dc_generator")
        phr_OFF = sim.Population((N,), "dc_generator")

        for factor, phr in [(-params["snr"], phr_OFF), (params["snr"], phr_ON)]:
            phr.tset("amplitude", params["amplitude"] * factor)
            phr.set({"start": params["simtime"] / 4, "stop": params["simtime"] / 4 * 3})

        # internal noise model (see benchmark_noise)
        noise_ON = sim.Population((N,), "noise_generator", {"mean": 0.0, "std": params["noise_std"]})
        noise_OFF = sim.Population((N,), "noise_generator", {"mean": 0.0, "std": params["noise_std"]})

        # target ON and OFF populations (what about a tridimensional Population?)
        out_ON = sim.Population(
            (N,), sim.IF_curr_alpha
        )  #'IF_cond_alpha) #iaf_sfa_neuron')# EIF_cond_alpha_isfa_ista, IF_cond_exp_gsfa_grr,sim.IF_cond_alpha)#'iaf_sfa_neuron',params['parameters_gc'])#'iaf_cond_neuron')# IF_cond_alpha) #
        out_OFF = sim.Population(
            (N,), sim.IF_curr_alpha
        )  #'IF_cond_alpha) #IF_curr_alpha)#'iaf_sfa_neuron')#sim.IF_curr_alpha)#,params['parameters_gc'])

        # initialize membrane potential TODO: and conductances?
        from pyNN.random import RandomDistribution, NumpyRNG

        rng = NumpyRNG(seed=params["kernelseed"])
        vinit_distr = RandomDistribution(distribution="uniform", parameters=[-70, -55], rng=rng)
        for out_ in [out_ON, out_OFF]:
            out_.randomInit(vinit_distr)

        retina_proj_ON = sim.Projection(phr_ON, out_ON, sim.OneToOneConnector())
        retina_proj_ON.setWeights(params["weight"])
        # TODO fix setWeight, add setDelays to 10 ms (relative to stimulus onset)
        retina_proj_OFF = sim.Projection(phr_OFF, out_OFF, sim.OneToOneConnector())
        retina_proj_OFF.setWeights(params["weight"])

        noise_proj_ON = sim.Projection(noise_ON, out_ON, sim.OneToOneConnector())
        noise_proj_ON.setWeights(params["weight"])
        noise_proj_OFF = sim.Projection(
            noise_OFF, out_OFF, sim.OneToOneConnector()
        )  # implication if ON and OFF have the same noise input?
        noise_proj_OFF.setWeights(params["weight"])

        out_ON.record()
        out_OFF.record()

        # reads out time used for building
        buildCPUTime = myTimer.elapsedTime()

        # === Run simulation ===========================================================
        if verbose:
            print "Running simulation"

        myTimer.reset()  # start timer on construction
        sim.run(params["simtime"])
        simCPUTime = myTimer.elapsedTime()

        myTimer.reset()  # start timer on construction
        # TODO LUP use something like "for pop in [phr, out]" ?
        out_ON_filename = os.path.join(tmpdir, "out_on.gdf")
        out_OFF_filename = os.path.join(tmpdir, "out_off.gdf")
        out_ON.printSpikes(out_ON_filename)  #
        out_OFF.printSpikes(out_OFF_filename)  #

        # TODO LUP  get out_ON_DATA on a 2D grid independantly of out_ON.cell.astype(int)
        out_ON_DATA = load_spikelist(out_ON_filename, range(N), t_start=0.0, t_stop=params["simtime"])
        out_OFF_DATA = load_spikelist(out_OFF_filename, range(N), t_start=0.0, t_stop=params["simtime"])

        out = {"out_ON_DATA": out_ON_DATA, "out_OFF_DATA": out_OFF_DATA}  # ,'out_ON_pos':out_ON}
        # cleans up
        os.remove(out_ON_filename)
        os.remove(out_OFF_filename)
        os.rmdir(tmpdir)
        writeCPUTime = myTimer.elapsedTime()

        if verbose:
            print "\nRetina Network Simulation:"
            print (params["description"])
            print "Number of Neurons  : ", N
            print "Output rate  (ON) : ", out_ON_DATA.mean_rate(), "Hz/neuron in ", params["simtime"], "ms"
            print "Output rate (OFF)   : ", out_OFF_DATA.mean_rate(), "Hz/neuron in ", params["simtime"], "ms"
            print ("Build time             : %g s" % buildCPUTime)
            print ("Simulation time        : %g s" % simCPUTime)
            print ("Writing time           : %g s" % writeCPUTime)

        return out
"""
Example to show off some capabilities of the signals module 
and the SpikeList and AnalogSignalList class.

- loads spiking and voltage data simulated with pyNN
- calculates various measurements (mean firing rate, cv...)
- plot the signals
- plots the spike-triggered-averages

Performed at the NeuroTools demo session, INCF booth, 
SfN annual meeting 2008, Washington. DC.
"""
import NeuroTools.signals as signals

# loading spiking data
s = signals.load_spikelist('spike_data')

# raster plot
s.raster_plot()

# mean rate
print 'mean rate: ',s.mean_rate()
print 'mean rates: ',s.mean_rates()
# fano factor of isi
print 'fano factor of isi: ',s.fano_factors_isi()
# cv of isi
print 'cv of isi:',s.cv_isi()

# isi distribution
hs = s.isi_hist(bins=20, display=True)
Пример #14
0
            tdata = pylab.arange(0, (n + 1) * dt, dt)
            vdata = allvdata.compress(cell_ids == i)
            vdata = pylab.where(vdata >= v_thresh - 0.05, 0.0,
                                vdata)  # add fake APs for plotting
            if len(tdata) > len(vdata):
                print "Warning. Shortening tdata from %d to %d elements (%s)" % (
                    len(tdata), len(vdata), simulator)
                tdata = tdata[0:len(vdata)]
            assert len(tdata) == len(
                vdata), "%d != %d (%s)" % (len(tdata), len(vdata), simulator)
            subplot.plot(tdata, vdata)

        # Plot spike rasters
        subplot = figure.add_axes([x, y0 + 2 * dy, w, h])
        exc_spikedata = signals.load_spikelist(
            "Results/VAbenchmark_%s_exc_%s_np%d.ras" %
            (benchmark, simulator, num_nodes))
        inh_spikedata = signals.load_spikelist(
            "Results/VAbenchmark_%s_inh_%s_np%d.ras" %
            (benchmark, simulator, num_nodes))
        exc_spikedata.raster_plot(display=subplot)

        # Inter-spike-interval histograms
        bins = pylab.exp(pylab.arange(0, 8, 0.2))
        isihist, bins = exc_spikedata.isi_hist(bins)
        subplot = figure.add_axes([x, y0 + dy, 0.4 * w, h])
        plot_hist(subplot,
                  isihist,
                  pylab.arange(0, 8, 0.2),
                  0.2,
                  xlabel="Inter-spike interval (ms)",