当前位置: 首页>>代码示例>>Python>>正文


Python Timer.elapsedTime方法代码示例

本文整理汇总了Python中pyNN.utility.Timer.elapsedTime方法的典型用法代码示例。如果您正苦于以下问题:Python Timer.elapsedTime方法的具体用法?Python Timer.elapsedTime怎么用?Python Timer.elapsedTime使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pyNN.utility.Timer的用法示例。


在下文中一共展示了Timer.elapsedTime方法的14个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: run_simulation

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
def run_simulation(sim,Params):
    print "Running Network"
    timer = Timer()
    timer.reset()
    sim.run(Params['run_time'])
    simCPUtime = timer.elapsedTime()
    print "Simulation Time: %s" % str(simCPUtime)
开发者ID:dguarino,项目名称:SlowDyn,代码行数:9,代码来源:helpers.py

示例2: len

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
    if len(cortical_exc_inh_connections) !=0:

        cortical_exc_inh_projection = simulator.Projection(cortical_neurons_exc, cortical_neurons_inh,
                                                           cortical_exc_inh_connector, receptor_type='excitatory')


#############################n
# Recordings
#############################

cortical_neurons_exc.record(['gsyn_exc', 'gsyn_inh','v', 'spikes'])
cortical_neurons_inh.record(['gsyn_exc', 'gsyn_inh', 'v', 'spikes'])
#cortical_neurons_exc.record('spikes', 'v')

# read out time used for building
build_time = timer.elapsedTime()

#############################
# Run model and print information
#############################
simulator.run(t)  # Run the simulations for t ms
simulation_time = timer.elapsedTime()

print 'Construction time', build_time
print 'Simulation time', simulation_time

simulator.end()

#############################
# Extract the data
#############################
开发者ID:OpenSourceBrain,项目名称:V1NetworkModels,代码行数:33,代码来源:troyer_plot3a.py

示例3: range

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
# cell_params will be passed to the constructor of the Population Object

cell_params = {
    'tau_m'      : tau_m,    'cm'         : cm,    
    'v_rest'     : -65,   'v_reset'    : -65,  'v_thresh'   : -45,
    'tau_syn_E'       : tau_syn_exc,        'tau_syn_I'       : tau_syn_inh, 'tau_refrac'       : t_refrac, 'i_offset' : 0
    }


# population and projection containers
v4_pop = []
pfc = []
projections = []

print "%g - Creating v4 populations" % timer.elapsedTime()

for i in range(orientations):           # Cycles orientations
    # creates a population for each connection
    v4_pop.append(Population(base_v4_num_neurons*base_v4_num_neurons,         # size 
	          IF_curr_exp,   # Neuron Type
		  cell_params,   # Neuron Parameters
		  label="v4_%d" % i)) # Label)      
    if layer_to_observe == 'v4' or layer_to_observe == 'all':                     
        print "%g - observing v4" % timer.elapsedTime()    
        # if layer_to_observe == 'v4':    v4_pop[i].set_mapping_constraint({'x':0, 'y':1})
        v4_pop[i].record() # ('spikes', to_file=False)     

print "%g - Creating PFC population" % timer.elapsedTime()

for i in range(orientations):           # Cycles orientations
开发者ID:Paul92,项目名称:sPyNNaker,代码行数:32,代码来源:testrandomInit.py

示例4: run_retina

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
def run_retina(params):
    """Run the retina using the specified parameters."""

    print "Setting up simulation"
    timer = Timer()
    timer.start()  # start timer on construction
    pyNN.setup(timestep=params['dt'], max_delay=params['syn_delay'], threads=params['threads'], rng_seeds=params['kernelseeds'])

    N = params['N']
    phr_ON = pyNN.Population((N, N), pyNN.native_cell_type('dc_generator')())
    phr_OFF = pyNN.Population((N, N), pyNN.native_cell_type('dc_generator')())
    noise_ON = pyNN.Population((N, N), pyNN.native_cell_type('noise_generator')(mean=0.0, std=params['noise_std']))
    noise_OFF = pyNN.Population((N, N), pyNN.native_cell_type('noise_generator')(mean=0.0, std=params['noise_std']))

    phr_ON.set(start=params['simtime']/4, stop=params['simtime']/4*3,
               amplitude=params['amplitude'] * params['snr'])
    phr_OFF.set(start=params['simtime']/4, stop=params['simtime']/4*3,
                amplitude=-params['amplitude'] * params['snr'])

    # target ON and OFF populations
    v_init = params['parameters_gc'].pop('Vinit')
    out_ON = pyNN.Population((N, N), pyNN.native_cell_type('iaf_cond_exp_sfa_rr')(**params['parameters_gc']))
    out_OFF = pyNN.Population((N, N), pyNN.native_cell_type('iaf_cond_exp_sfa_rr')(**params['parameters_gc']))
    out_ON.initialize(v=v_init)
    out_OFF.initialize(v=v_init)

    #print "Connecting the network"

    retina_proj_ON = pyNN.Projection(phr_ON, out_ON, pyNN.OneToOneConnector())
    retina_proj_ON.set(weight=params['weight'])
    retina_proj_OFF = pyNN.Projection(phr_OFF, out_OFF, pyNN.OneToOneConnector())
    retina_proj_OFF.set(weight=params['weight'])

    noise_proj_ON = pyNN.Projection(noise_ON, out_ON, pyNN.OneToOneConnector())
    noise_proj_ON.set(weight=params['weight'])
    noise_proj_OFF = pyNN.Projection(noise_OFF, out_OFF, pyNN.OneToOneConnector())
    noise_proj_OFF.set(weight=params['weight'])

    out_ON.record('spikes')
    out_OFF.record('spikes')

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

    print "Running simulation"

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

    out_ON_DATA = out_ON.get_data().segments[0]
    out_OFF_DATA = out_OFF.get_data().segments[0]

    print "\nRetina Network Simulation:"
    print(params['description'])
    print "Number of Neurons : ", N**2
    print "Output rate  (ON) : ", out_ON.mean_spike_count(), \
        "spikes/neuron in ", params['simtime'], "ms"
    print "Output rate (OFF) : ", out_OFF.mean_spike_count(), \
        "spikes/neuron in ", params['simtime'], "ms"
    print "Build time        : ", buildCPUTime, "s"
    print "Simulation time   : ", simCPUTime, "s"

    return out_ON_DATA, out_OFF_DATA
开发者ID:apdavison,项目名称:topographica,代码行数:66,代码来源:perrinet_retina_pynest.py

示例5: test

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
def test(cases=[1]):    
    
    sp            = Space(periodic_boundaries=((0,1), (0,1), None))
    safe          = False
    verbose       = True
    autapse       = False
    parallel_safe = True    
    render        = True
        
    for case in cases:
        #w = RandomDistribution('uniform', (0,1))
        w = "0.2 + d/0.2"
        #w = 0.1
        #w = lambda dist : 0.1 + numpy.random.rand(len(dist[0]))*sqrt(dist[0]**2 + dist[1]**2) 
        
        #delay = RandomDistribution('uniform', (0.1,5.))
        delay = "0.1 + d/0.2"
        #delay = 0.1    
        #delay = lambda distances : 0.1 + numpy.random.rand(len(distances))*distances 
    
        d_expression = "d < 0.1"
        #d_expression = "(d[0] < 0.05) & (d[1] < 0.05)"
        #d_expression = "(d[0]/(0.05**2) + d[1]/(0.1**2)) < 100*numpy.random.rand()"
    
        timer   = Timer()
        np      = num_processes()
        timer.start()    
        if case is 1:
            conn  = DistanceDependentProbabilityConnector(d_expression, delays=delay, weights=w, space=sp, safe=safe, verbose=verbose, allow_self_connections=autapse)
            fig_name = "DistanceDependent_%s_np_%d.png" %(simulator_name, np)
        elif case is 2:
            conn  = FixedProbabilityConnector(0.05, weights=w, delays=delay, space=sp, safe=safe, verbose=verbose, allow_self_connections=autapse)
            fig_name = "FixedProbability_%s_np_%d.png" %(simulator_name, np)
        elif case is 3:
            conn  = AllToAllConnector(delays=delay, weights=w, space=sp, safe=safe, verbose=verbose, allow_self_connections=autapse)
            fig_name = "AllToAll_%s_np_%d.png" %(simulator_name, np)
        elif case is 4:
            conn  = FixedNumberPostConnector(50, weights=w, delays=delay, space=sp, safe=safe, verbose=verbose, allow_self_connections=autapse)
            fig_name = "FixedNumberPost_%s_np_%d.png" %(simulator_name, np)
        elif case is 5:
            conn  = FixedNumberPreConnector(50, weights=w, delays=delay, space=sp, safe=safe, verbose=verbose, allow_self_connections=autapse)
            fig_name = "FixedNumberPre_%s_np_%d.png" %(simulator_name, np)
        elif case is 6:
            conn  = OneToOneConnector(safe=safe, weights=w, delays=delay, verbose=verbose)
            fig_name = "OneToOne_%s_np_%d.png" %(simulator_name, np)
        elif case is 7:
            conn  = FromFileConnector('connections.dat', safe=safe, verbose=verbose)
            fig_name = "FromFile_%s_np_%d.png" %(simulator_name, np)
        elif case is 8:
            conn  = SmallWorldConnector(degree=0.1, rewiring=0., weights=w, delays=delay, safe=safe, verbose=verbose, allow_self_connections=autapse, space=sp)
            fig_name = "SmallWorld_%s_np_%d.png" %(simulator_name, np)
        
        
        print "Generating data for %s" %fig_name
        rng   = NumpyRNG(23434, num_processes=np, parallel_safe=parallel_safe)
        prj   = Projection(x, x, conn, rng=rng)

        simulation_time = timer.elapsedTime()
        print "Building time", simulation_time
        print "Nb synapses built", len(prj)

        if render : 
            if not(os.path.isdir('Results')):
                os.mkdir('Results')

            print "Saving Positions...."
            x.savePositions('Results/positions.dat')

            print "Saving Connections...."
            prj.saveConnections('Results/connections.dat', compatible_output=False)
            
        if node_id == 0 and render:
            figure()
            print "Generating and saving %s" %fig_name
            positions   = numpy.loadtxt('Results/positions.dat')
            connections = numpy.loadtxt('Results/connections.dat')
            positions   = positions[numpy.argsort(positions[:,0])]
            idx_pre     = (connections[:,0] - x.first_id).astype(int)
            idx_post    = (connections[:,1] - x.first_id).astype(int)
            d           = distances(positions[idx_pre,1:3], positions[idx_post,1:3], 1)
            subplot(231)
            title('Cells positions')
            plot(positions[:,1], positions[:,2], '.')
            subplot(232)
            title('Weights distribution')
            hist(connections[:,2], 50)
            subplot(233)
            title('Delay distribution')
            hist(connections[:,3], 50)
            subplot(234)
            ids   = numpy.random.permutation(numpy.unique(positions[:,0]))[0:6]
            colors = ['k', 'r', 'b', 'g', 'c', 'y'] 
            for count, cell in enumerate(ids):
                draw_rf(cell, positions, connections, colors[count])
            subplot(235)
            plot(d, connections[:,2], '.')

            subplot(236)
            plot(d, connections[:,3], '.')
            savefig("Results/" + fig_name)            
#.........这里部分代码省略.........
开发者ID:agravier,项目名称:pynn,代码行数:103,代码来源:connectors_benchmark.py

示例6: int

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
print "[%d] Creating populations" % node
n_spikes = int(2*tstop*input_rate/1000.0)
spike_times = numpy.add.accumulate(rng.next(n_spikes, 'exponential',
                                            {'beta': 1000.0/input_rate}, mask_local=False))

input_population  = Population(100, SpikeSourceArray(spike_times=spike_times), label="input")
output_population = Population(10, IF_curr_exp(**cell_params), label="output")
print "[%d] input_population cells: %s" % (node, input_population.local_cells)
print "[%d] output_population cells: %s" % (node, output_population.local_cells)

print "[%d] Connecting populations" % node
timer.start()
connector = CSAConnector(csa.random(0.5))
syn = StaticSynapse(weight=0.1)
projection = Projection(input_population, output_population, connector, syn)
print connector.describe(), timer.elapsedTime()

file_stem = "Results/simpleRandomNetwork_csa_np%d_%s" % (num_processes(), simulator_name)

projection.save('all', '%s.conn' % file_stem)

input_population.record('spikes')
output_population.record('spikes')
output_population.sample(n_record, rng).record('v')

print "[%d] Running simulation" % node
run(tstop)

print "[%d] Writing spikes and Vm to disk" % node
output_population.write_data('%s_output.pkl' % file_stem)
#input_population.write_data('%s_input.pkl' % file_stem)
开发者ID:jougs,项目名称:PyNN,代码行数:33,代码来源:simpleRandomNetwork_csa.py

示例7: runBrunelNetwork

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]

#.........这里部分代码省略.........
    E_net.record('spikes')
    if N_rec_v>0:
        E_net[0:min(NE,N_rec_v)].record('v')

    print("%d Setting up recording in inhibitory population." % rank)
    I_net.record('spikes')
    if N_rec_v>0:
        I_net[0:min(NI,N_rec_v)].record('v')

    progress_bar = ProgressBar(width=20)
    connector = FixedProbabilityConnector(epsilon, rng=rng, callback=progress_bar)
    E_syn = StaticSynapse(weight=JE, delay=delay)
    I_syn = StaticSynapse(weight=JI, delay=delay)
    ext_Connector = OneToOneConnector(callback=progress_bar)
    ext_syn = StaticSynapse(weight=JE, delay=dt)

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

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

    # read out time used for building
    buildCPUTime = timer.elapsedTime()
    # === Run simulation ===========================================================

    # run, measure computer time
    timer.start()  # start timer on construction
    print("%d Running simulation for %g ms (dt=%sms)." % (rank, simtime, dt))
    run(simtime)
    print("Done")
    simCPUTime = timer.elapsedTime()

    # write data to file
    #print("%d Writing data to file." % rank)
    #(E_net + I_net).write_data("Results/brunel_np%d_%s.pkl" % (np, simulator_name))
    if save and not simulator_name=='neuroml':
        for pop in [E_net , I_net]:
            io = PyNNTextIO(filename="brunel-PyNN-%s-%s-%i.gdf"%(simulator_name, pop.label, rank))
            spikes =  pop.get_data('spikes', gather=False)
            for segment in spikes.segments:
                io.write_segment(segment)
                
            io = PyNNTextIO(filename="brunel-PyNN-%s-%s-%i.dat"%(simulator_name, pop.label, rank))
            vs =  pop.get_data('v', gather=False)
            for segment in vs.segments:
                io.write_segment(segment)
            
    spike_data = {}
    spike_data['senders'] = []
    spike_data['times'] = []
    index_offset = 1
    for pop in [E_net , I_net]:
        if rank == 0:
            spikes =  pop.get_data('spikes', gather=False)
            #print(spikes.segments[0].all_data)
开发者ID:OpenSourceBrain,项目名称:Brunel2000,代码行数:70,代码来源:brunel08.py

示例8: compute_sdram_entries

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
        out_file_string += compute_sdram_entries(db, c, memory_pointer, process_id=process_id)
        memory_pointer = BASE + len(out_file_string)
    
    # If there's something write the file
    if len(out_file_string) > 0:            
        f = open(filename,'w+')
        f.write(out_file_string)
        f.close()


if __name__ == '__main__':
    if DEBUG:	print "\n----- creating SDRAM files"
    db = pacman.load_db(sys.argv[1])       # IMPORTS THE DB (it will also load the model libraray by default)
    global n_synapses
    n_synapses = 0
    print("Loading DB: %g" %timer.elapsedTime())
    
    image_map = db.get_image_map()

    chip_map = [ (c['x'],c['y']) for c in image_map ]
    chip_map = list(set(chip_map))  # removing duplicates http://love-python.blogspot.co.uk/2008/09/remove-duplicate-items-from-list-using.html

    
    for c in chip_map:
        x = c[0]
        y = c[1]    
        filename = './binaries/SDRAM_%d_%d.dat' % (x, y)
#            filename = '/tmp/SDRAM_%d_%d.dat' % (x, y)
        used_cores = [ el for el in image_map if el['x']==x and el['y']==y ]
        out_file_string = ""
        memory_pointer = BASE
开发者ID:galluppf,项目名称:spackage_conv,代码行数:33,代码来源:synapse_writer.py

示例9: Timer

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
timer = Timer()
timer.start()


# cell_params will be passed to the constructor of the Population Object

cell_params = {
    'tau_m'      : tau_m,    'cm'         : cm,    
    'v_rest'     : v_rest,   'v_reset'    : v_reset,  'v_thresh'   : v_thresh,
    'tau_syn_E'       : tau_syn_exc,        'tau_syn_I'       : tau_syn_inh, 'tau_refrac'       : t_refrac, 'i_offset' : i_offset
    }




print "%g - Creating input population: %d x %d" % (timer.elapsedTime(), scale.input_size[0], scale.input_size[1])
if input_file_type:
   input_file = open(InputFilePol1, 'r')
   input_spike_list = eval(input_file.readline())
   data_input_1 = convert_spike_list_to_timed_spikes(spike_list=input_spike_list, min_idx=0, max_idx=scale.input_size[0]*scale.input_size[1], tmin=0, tmax=runtime, tstep=int(time_step))
else:
   data_input_1 = convert_file_to_spikes(input_file_name=InputFilePol1, min_idx=0, max_idx=scale.input_size[0]*scale.input_size[1], tmin=0, tmax=runtime)
data_input_1 = subsample_spikes_by_time(data_input_1, 0, 100, 6)
data_input_1 = random_skew_times(data_input_1, 3)
data_input_1 = [data_input_1[neuron] if neuron in data_input_1 else [] for neuron in range(scale.input_size[0]*scale.input_size[1])]
input_pol_1 = Population(scale.input_size[0]*scale.input_size[1],         # size 
              SpikeSourceArray,   # Neuron Type
              {'spike_times': data_input_1},   # Neuron Parameters
              label="input_pol_1") # Label
if layer_to_observe == 'input_pol_1' or layer_to_observe == 'all':
   print "%g - observing input (positive polarity)" % timer.elapsedTime()    
开发者ID:Paul92,项目名称:sPyNNaker,代码行数:33,代码来源:va_network_scaled_IEEE_TNNLS_ref.py

示例10: len

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
	print "Bas --> Bas\t\t", len(Bas_to_Bas), "connections"
	Ext_to_Bas = Projection(bas_poisson, Bas_net, BasExt_Connector, target="excitatory")
	print "Ext --> Bas\t", len(Ext_to_Bas), "connections"

	Pyr_to_Sli = []

	print "%d Connecting slow inhibitory population." % (rank)
	for pre in range(NP):
		P2S_sub = Projection(Pyr_net[pre], Sli_net, SliExc_Connector, rng=rng, target="excitatory")
		print "Pyr --> SlowInh\t\t", len(P2S_sub), "connections"
		Pyr_to_Sli.append(P2S_sub)
	Ext_to_Sli = Projection(sli_poisson, Sli_net, SliExt_Connector, target="excitatory")
	print "Ext --> SlowInh\t", len(Ext_to_Sli), "connections"

	# read out time used for building
	buildCPUTime = timer.elapsedTime()
	# === Run simulation ===========================================================

	# run, measure computer time
	timer.start() # start timer on construction
	print "%d Running simulation for %g ms." % (rank, simtime)
	run(simtime)
	simCPUTime = timer.elapsedTime()

	print "%d Writing data to file." % rank

	filename_spike_pyr = []
	filename_v_pyr = []
	for sp in range(NP):
		filename_spike_sub = "Results/%s_pyr%d_np%d_%s.ras" % (run_name, sp, np, simulator_name) # output file for excit. population
		filename_spike_pyr.append(filename_spike_sub)
开发者ID:SzKunigunda,项目名称:Gamma-model,代码行数:33,代码来源:ca3net8_gamma62_lif.py

示例11: run

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
    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
开发者ID:JuergenNeubauer,项目名称:NeuroTools,代码行数:67,代码来源:simple_single_neuron.py

示例12: run

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
    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
开发者ID:JuergenNeubauer,项目名称:NeuroTools,代码行数:99,代码来源:retina.py

示例13: str

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
     already_computed = 0
     for pop in params['Populations'].keys():
         if os.path.exists(opts.data_folder + str(run) +'/'+pop+str(comb)+'.pkl'):
             already_computed = already_computed + 1
     if already_computed > 0:
         print "already computed"
     else:
         Populations = h.build_network(sim,params)
         h.record_data(params, Populations)
         h.perform_injections(params, Populations)
         print "Running Network"
         timer = Timer()
         timer.reset()
         interval = 10
         sim.run(params['run_time'], callbacks = SetInput(Populations, interval, params['dt']))
         simCPUtime = timer.elapsedTime()
         print "Simulation Time: %s" % str(simCPUtime)
         h.save_data(Populations, opts.data_folder + str(run), str(comb))
         sim.end()
 else :
     if search:
         already_computed = 0
         for pop in params['Populations'].keys():
             if os.path.exists(opts.data_folder + str(run) +'/'+pop+str(comb)+'.png'):
                 already_computed = already_computed + 1
         if already_computed > len(params['Populations']) - 1:
             print "already analysed"
         else:
             ratio,fqcy,psd,freq, fqcy_ratio = h.analyse(params, opts.data_folder + str(run), str(comb), opts.remove)
             print "ratio",ratio,"fqcy",fqcy,"psd",psd,"freq",freq
             
开发者ID:dguarino,项目名称:SlowDyn,代码行数:32,代码来源:run_closed_old.py

示例14: run_simulation

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import elapsedTime [as 别名]
def run_simulation(run):

    info = {}
    # run combinations
    for i,comb in enumerate(combinations):
        print "param combination",i, "trial",run
        print "current set:",comb

        # replacement
        for ckey,val in comb.iteritems():
            keys = ckey.split('.') # get list from dotted string
            replace(params,keys,val)

        # save parameters in the data_folder
        if not os.path.exists(opts.data_folder+str(run)):
            os.makedirs(opts.data_folder+str(run))
        shutil.copy('./'+opts.param_file, opts.data_folder + str(run)+'/'+opts.param_file+'_'+str(comb)+'.py')

        if not opts.analysis: #run simulation
	    # run simulation if it hasn't already been ran for these parameters
            already_computed = 0
            for pop in params['Populations'].keys():
                if os.path.exists(opts.data_folder + str(run) +'/'+pop+str(comb)+'.pkl'):
                    already_computed = already_computed + 1
            if already_computed > 0:
                print "already computed"
            else:
                Populations = h.build_network(sim,params)
                h.record_data(params, Populations)
                h.perform_injections(params, Populations)
                print "Running Network"
                timer = Timer()
                timer.reset()
		inject_spikes = partial(inject_spikes_pop,Populations = Populations)
                sim.run(params['run_time'], [inject_spikes])
                simCPUtime = timer.elapsedTime()
                print "Simulation Time: %s" % str(simCPUtime)
                h.save_data(Populations, opts.data_folder + str(run), str(comb))
                sim.end()

        else : #do analysis
            if search: #then compute the csv needed for the search maps
                already_analysed = 0 #analyse only those that haven't already been analysed
                for pop in params['Populations'].keys():
                    if os.path.exists(opts.data_folder + str(run) +'/'+pop+str(comb)+'.png'):
                        already_analysed = already_analysed + 1
                if already_analysed >= len(params['Populations'])-1 :
                    print "already analysed"
                else:	
                    ratio,fqcy,psd,freq, fqcy_ratio = h.analyse(params, opts.data_folder + str(run), str(comb), opts.remove)
 		    #save computed values in csv files                   
                    gen = (pop for pop in params['Populations'].keys() if pop != 'ext')
                    for pop in gen:
                        if i == 0:
                            with open(opts.data_folder+ str(run)+'/map-'+pop+'.csv', 'wb') as csvfile:
                                mywriter = csv.writer(csvfile)
                                mywriter.writerow( ['#'+str(testParams[1])+ ':' +str(search[testParams[1]]) ] )
                                mywriter.writerow( ['#'+str(testParams[0])+ ':' +str(search[testParams[0]]) ] )

                            with open(opts.data_folder+ str(run)+'/psdmap-'+pop+'.csv', 'wb') as csvfile:
                                mywriter = csv.writer(csvfile)
                                mywriter.writerow( ['#'+str(testParams[1])+ ':' +str(search[testParams[1]]) ] )
                                mywriter.writerow( ['#'+str(testParams[0])+ ':' +str(search[testParams[0]]) ] )
                                if pop in freq:
                                    mywriter.writerow(freq[pop])
			    info[pop] = []

                        if pop in ratio and pop in fqcy:
                            info[pop].append([ratio[pop],fqcy[pop],fqcy_ratio[pop]])
                            if (i+1)%len(search[testParams[1]]) == 0:
                                with open(opts.data_folder+str(run)+'/map-'+pop+'.csv', 'a') as csvfile:
                                    mywriter = csv.writer(csvfile)
                                    mywriter.writerow(info[pop])
                                    info[pop] = []
                        if pop in psd:
                            with open(opts.data_folder+str(run)+'/psdmap-'+pop+'.csv', 'a') as csvfile:
                                mywriter = csv.writer(csvfile)
                                mywriter.writerow(psd[pop])

            else:
                h.analyse(params, opts.data_folder+str(run), str(comb), opts.remove)
开发者ID:dguarino,项目名称:SlowDyn,代码行数:83,代码来源:run_closed.py


注:本文中的pyNN.utility.Timer.elapsedTime方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。