• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python utility.Timer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

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



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

示例1: run_simulation

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,代码行数:7,代码来源:helpers.py


示例2: setup

    def setup(self, load_tuning_prop=False, times={}):

        self.projections = {}
        self.projections['ee'] = []
        self.projections['ei'] = []
        self.projections['ie'] = []
        self.projections['ii'] = []
        if not load_tuning_prop:
            self.tuning_prop_exc = utils.set_tuning_prop(self.params, mode='hexgrid', cell_type='exc')        # set the tuning properties of exc cells: space (x, y) and velocity (u, v)
            self.tuning_prop_inh = utils.set_tuning_prop(self.params, mode='hexgrid', cell_type='inh')        # set the tuning properties of exc cells: space (x, y) and velocity (u, v)
        else:
            self.tuning_prop_exc = np.loadtxt(self.params['tuning_prop_means_fn'])
            self.tuning_prop_inh = np.loadtxt(self.params['tuning_prop_inh_fn'])

        indices, distances = utils.sort_gids_by_distance_to_stimulus(self.tuning_prop_exc, self.params) # cells in indices should have the highest response to the stimulus
        if self.pc_id == 0:
            print "Saving tuning_prop to file:", self.params['tuning_prop_means_fn']
            np.savetxt(self.params['tuning_prop_means_fn'], self.tuning_prop_exc)
            print "Saving tuning_prop to file:", self.params['tuning_prop_inh_fn']
            np.savetxt(self.params['tuning_prop_inh_fn'], self.tuning_prop_inh)
            print 'Saving gids to record to: ', self.params['gids_to_record_fn']
            np.savetxt(self.params['gids_to_record_fn'], indices[:self.params['n_gids_to_record']], fmt='%d')

#        np.savetxt(params['gids_to_record_fn'], indices[:params['n_gids_to_record']], fmt='%d')

        if self.comm != None:
            self.comm.Barrier()
        from pyNN.utility import Timer
        self.timer = Timer()
        self.timer.start()
        self.times = times
        self.times['t_all'] = 0
        # # # # # # # # # # # #
        #     S E T U P       #
        # # # # # # # # # # # #
        (delay_min, delay_max) = self.params['delay_range']
        setup(timestep=0.1, min_delay=delay_min, max_delay=delay_max, rng_seeds_seed=self.params['seed'])
        rng_v = NumpyRNG(seed = sim_cnt*3147 + self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes
        self.rng_conn = NumpyRNG(seed = self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes

        # # # # # # # # # # # # # # # # # # # # # # # # #
        #     R A N D O M    D I S T R I B U T I O N S  #
        # # # # # # # # # # # # # # # # # # # # # # # # #
        self.v_init_dist = RandomDistribution('normal',
                (self.params['v_init'], self.params['v_init_sigma']),
                rng=rng_v,
                constrain='redraw',
                boundaries=(-80, -60))

        self.times['t_setup'] = self.timer.diff()
        self.times['t_calc_conns'] = 0
        if self.comm != None:
            self.comm.Barrier()

        self.torus = space.Space(axes='xy', periodic_boundaries=((0., self.params['torus_width']), (0., self.params['torus_height'])))
开发者ID:physicalist,项目名称:bcpnn-mt,代码行数:55,代码来源:NetworkSimModule.py


示例3: setup

    def setup(self, load_tuning_prop=False):

        if load_tuning_prop:
            print 'Loading tuning properties from', self.params['tuning_prop_means_fn']
            self.tuning_prop_exc = np.loadtxt(self.params['tuning_prop_means_fn'])
        else:
            print 'Preparing tuning properties with limited range....'
            x_range = (0, 1.)
            y_range = (0.2, .5)
            u_range = (.05, 1.0)
            v_range = (-.2, .2)
            tp_exc_good, tp_exc_out_of_range = utils.set_limited_tuning_properties(params, y_range, x_range, u_range, v_range, cell_type='exc')
            self.tuning_prop_exc = tp_exc_good
            print 'n_exc within range: ', tp_exc_good[:, 0].size
            print "Saving tuning_prop to file:", params['tuning_prop_means_fn']
            np.savetxt(params['tuning_prop_means_fn'], tp_exc_good)

        indices, distances = utils.sort_gids_by_distance_to_stimulus(self.tuning_prop_exc, self.params['motion_params'], self.params) # cells in indices should have the highest response to the stimulus
        if self.pc_id == 0:
            print "Saving tuning_prop to file:", self.params['tuning_prop_means_fn']
            np.savetxt(self.params['tuning_prop_means_fn'], self.tuning_prop_exc)
            print 'Saving gids to record to: ', self.params['gids_to_record_fn']
            np.savetxt(self.params['gids_to_record_fn'], indices[:self.params['n_gids_to_record']], fmt='%d')

#        np.savetxt(params['gids_to_record_fn'], indices[:params['n_gids_to_record']], fmt='%d')

        if self.comm != None:
            self.comm.Barrier()
        from pyNN.utility import Timer
        self.timer = Timer()
        self.timer.start()
        self.times = {}
        # # # # # # # # # # # # 
        #     S E T U P       #
        # # # # # # # # # # # #
        (delay_min, delay_max) = self.params['delay_range']
        setup(timestep=0.1, min_delay=delay_min, max_delay=delay_max, rng_seeds_seed=self.params['seed'])
        rng_v = NumpyRNG(seed = sim_cnt*3147 + self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes
        self.rng_conn = NumpyRNG(seed = self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes

        # # # # # # # # # # # # # # # # # # # # # # # # #
        #     R A N D O M    D I S T R I B U T I O N S  #
        # # # # # # # # # # # # # # # # # # # # # # # # #
        self.v_init_dist = RandomDistribution('normal',
                (self.params['v_init'], self.params['v_init_sigma']),
                rng=rng_v,
                constrain='redraw',
                boundaries=(-80, -60))

        self.times['t_setup'] = self.timer.diff()
        self.times['t_calc_conns'] = 0
        if self.comm != None:
            self.comm.Barrier()
开发者ID:MinaKh,项目名称:bcpnn-mt,代码行数:53,代码来源:NetworkSimModuleOnlyExc.py


示例4: main_pynest

def main_pynest(parameters):
    P = parameters
    assert P.sim_name == "pynest"
    timer = Timer()
    import nest
    timer.mark("import")

    nest.SetKernelStatus({"resolution": 0.1})
    timer.mark("setup")

    p = nest.Create("iaf_neuron", n=P.n, params={"I_e": 1000.0})
    timer.mark("build")

    # todo: add recording and data retrieval
    nest.Simulate(P.sim_time)
    timer.mark("run")

    mpi_rank = nest.Rank()
    num_processes = nest.NumProcesses()
    
    data = P.as_dict()
    data.update(num_processes=num_processes,
                timings=timer.marks)
    return mpi_rank, data
开发者ID:jougs,项目名称:PyNN,代码行数:24,代码来源:simple_network.py


示例5: str

            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:
            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"
开发者ID:dguarino,项目名称:SlowDyn,代码行数:31,代码来源:run_closed_old.py


示例6: test

def test(cases=[1]):

    sp = Space(periodic_boundaries=((0, 1), (0, 1), None), axes="xy")
    safe = False
    callback = progress_bar.set_level
    autapse = False
    parallel_safe = True
    render = True
    to_file = 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 = "exp(-d**2/(2*0.1**2))"
        # 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()

        synapse = StaticSynapse(weight=w, delay=delay)
        rng = NumpyRNG(23434, parallel_safe=parallel_safe)

        if case is 1:
            conn = DistanceDependentProbabilityConnector(
                d_expression, safe=safe, callback=callback, allow_self_connections=autapse, rng=rng
            )
            fig_name = "DistanceDependent_%s_np_%d.png" % (simulator_name, np)
        elif case is 2:
            conn = FixedProbabilityConnector(
                0.02, safe=safe, callback=callback, allow_self_connections=autapse, rng=rng
            )
            fig_name = "FixedProbability_%s_np_%d.png" % (simulator_name, np)
        elif case is 3:
            conn = AllToAllConnector(delays=delay, safe=safe, callback=callback, allow_self_connections=autapse)
            fig_name = "AllToAll_%s_np_%d.png" % (simulator_name, np)
        elif case is 4:
            conn = FixedNumberPostConnector(50, safe=safe, callback=callback, allow_self_connections=autapse, rng=rng)
            fig_name = "FixedNumberPost_%s_np_%d.png" % (simulator_name, np)
        elif case is 5:
            conn = FixedNumberPreConnector(50, safe=safe, callback=callback, allow_self_connections=autapse, rng=rng)
            fig_name = "FixedNumberPre_%s_np_%d.png" % (simulator_name, np)
        elif case is 6:
            conn = OneToOneConnector(safe=safe, callback=callback)
            fig_name = "OneToOne_%s_np_%d.png" % (simulator_name, np)
        elif case is 7:
            conn = FromFileConnector(
                files.NumpyBinaryFile("Results/connections.dat", mode="r"),
                safe=safe,
                callback=callback,
                distributed=True,
            )
            fig_name = "FromFile_%s_np_%d.png" % (simulator_name, np)
        elif case is 8:
            conn = SmallWorldConnector(
                degree=0.1, rewiring=0.0, safe=safe, callback=callback, allow_self_connections=autapse
            )
            fig_name = "SmallWorld_%s_np_%d.png" % (simulator_name, np)

        print "Generating data for %s" % fig_name

        prj = Projection(x, x, conn, synapse, space=sp)

        mytime = timer.diff()
        print "Time to connect the cell population:", mytime, "s"
        print "Nb synapses built", prj.size()

        if to_file:
            if not (os.path.isdir("Results")):
                os.mkdir("Results")
            print "Saving Connections...."
            prj.save("all", files.NumpyBinaryFile("Results/connections.dat", mode="w"), gather=True)

        mytime = timer.diff()
        print "Time to save the projection:", mytime, "s"

        if render and to_file:
            print "Saving Positions...."
            x.save_positions("Results/positions.dat")
        end()

        if node_id == 0 and render and to_file:
            figure()
            print "Generating and saving %s" % fig_name
            positions = numpy.loadtxt("Results/positions.dat")

            positions[:, 0] -= positions[:, 0].min()
            connections = files.NumpyBinaryFile("Results/connections.dat", mode="r").read()
            print positions.shape, connections.shape
            connections[:, 0] -= connections[:, 0].min()
            connections[:, 1] -= connections[:, 1].min()
#.........这里部分代码省略.........
开发者ID:bernhardkaplan,项目名称:PyNN,代码行数:101,代码来源:connectors_benchmark.py


示例7: get_script_args

from connector_functions import create_cortical_to_cortical_connection
from connector_functions import normalize_connection_list
from connector_functions import create_cortical_to_cortical_connection_corr
from connector_functions import create_thalamocortical_connection
from analysis_functions import calculate_tuning, visualize_conductances, visualize_conductances_and_voltage
from analysis_functions import conductance_analysis
from plot_functions import plot_spiketrains

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

simulator = get_script_args(1)[0]
exec("import pyNN.%s as simulator" % simulator)
#import pyNN.nest as simulator
#import pyNN.neuron as simulator

timer = Timer()

#############################
##  Parameters
#############################

# ============== Network and simulation parameters =================

contrast = 0.50  # Contrast used (possible range available in ./data)

Nside_lgn = 30  # N_lgn x N_lgn is the size of the LGN
Nside_exc = 40  # N_exc x N_exc is the  size of the cortical excitatory layer
Nside_inh = 20  # N_inh x N_inh is the size of the cortical inhibitory layer

factor = 1  # Reduction factor
开发者ID:OpenSourceBrain,项目名称:V1NetworkModels,代码行数:30,代码来源:troyer_plot3a.py


示例8: setup

    def setup(self, load_tuning_prop=False, times={}):

        self.projections = {}
        self.projections["ee"] = []
        self.projections["ei"] = []
        self.projections["ie"] = []
        self.projections["ii"] = []
        if not load_tuning_prop:
            self.tuning_prop_exc = utils.set_tuning_prop(
                self.params, mode="hexgrid", cell_type="exc"
            )  # set the tuning properties of exc cells: space (x, y) and velocity (u, v)
            self.tuning_prop_inh = utils.set_tuning_prop(
                self.params, mode="hexgrid", cell_type="inh"
            )  # set the tuning properties of exc cells: space (x, y) and velocity (u, v)
        else:
            self.tuning_prop_exc = np.loadtxt(self.params["tuning_prop_means_fn"])
            self.tuning_prop_inh = np.loadtxt(self.params["tuning_prop_inh_fn"])

        indices, distances = utils.sort_gids_by_distance_to_stimulus(
            self.tuning_prop_exc, self.params["motion_params"], self.params
        )  # cells in indices should have the highest response to the stimulus
        if self.pc_id == 0:
            print "Saving tuning_prop to file:", self.params["tuning_prop_means_fn"]
            np.savetxt(self.params["tuning_prop_means_fn"], self.tuning_prop_exc)
            print "Saving tuning_prop to file:", self.params["tuning_prop_inh_fn"]
            np.savetxt(self.params["tuning_prop_inh_fn"], self.tuning_prop_inh)
            print "Saving gids to record to: ", self.params["gids_to_record_fn"]
            np.savetxt(self.params["gids_to_record_fn"], indices[: self.params["n_gids_to_record"]], fmt="%d")

        #        np.savetxt(params['gids_to_record_fn'], indices[:params['n_gids_to_record']], fmt='%d')

        if self.comm != None:
            self.comm.Barrier()
        from pyNN.utility import Timer

        self.timer = Timer()
        self.timer.start()
        self.times = times
        self.times["t_all"] = 0
        # # # # # # # # # # # #
        #     S E T U P       #
        # # # # # # # # # # # #
        (delay_min, delay_max) = self.params["delay_range"]
        setup(timestep=0.1, min_delay=delay_min, max_delay=delay_max, rng_seeds_seed=self.params["seed"])
        rng_v = NumpyRNG(
            seed=sim_cnt * 3147 + self.params["seed"], parallel_safe=True
        )  # if True, slower but does not depend on number of nodes
        self.rng_conn = NumpyRNG(
            seed=self.params["seed"], parallel_safe=True
        )  # if True, slower but does not depend on number of nodes

        # # # # # # # # # # # # # # # # # # # # # # # # #
        #     R A N D O M    D I S T R I B U T I O N S  #
        # # # # # # # # # # # # # # # # # # # # # # # # #
        self.v_init_dist = RandomDistribution(
            "normal",
            (self.params["v_init"], self.params["v_init_sigma"]),
            rng=rng_v,
            constrain="redraw",
            boundaries=(-80, -60),
        )

        self.times["t_setup"] = self.timer.diff()
        self.times["t_calc_conns"] = 0
        if self.comm != None:
            self.comm.Barrier()

        self.torus = space.Space(
            axes="xy", periodic_boundaries=((0.0, self.params["torus_width"]), (0.0, self.params["torus_height"]))
        )
开发者ID:bvogginger,项目名称:bcpnn-mt,代码行数:70,代码来源:NetworkSimModuleNoColumns.py


示例9: run_retina

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,代码行数:64,代码来源:perrinet_retina_pynest.py


示例10: get_script_args

Andrew Davison, UNIC, CNRS
August 2006, November 2009

"""

import socket, os
import csa
import numpy
from pyNN.utility import get_script_args, Timer

simulator_name = get_script_args(1)[0]
exec("from pyNN.%s import *" % simulator_name)

from pyNN.random import NumpyRNG

timer = Timer()
seed = 764756387
tstop = 1000.0 # ms
input_rate = 100.0 # Hz
cell_params = {'tau_refrac': 2.0,  # ms
               'v_thresh':  -50.0, # mV
               'tau_syn_E':  2.0,  # ms
               'tau_syn_I':  2.0}  # ms
n_record = 5

node = setup(timestep=0.025, min_delay=1.0, max_delay=10.0, debug=True, quit_on_end=False)
print "Process with rank %d running on %s" % (node, socket.gethostname())


rng = NumpyRNG(seed=seed, parallel_safe=True)
开发者ID:jougs,项目名称:PyNN,代码行数:30,代码来源:simpleRandomNetwork_csa.py


示例11: synapses

    The IF network is based on the CUBA and COBA models of Vogels & Abbott
    (J. Neurosci, 2005).  The model consists of a network of excitatory and
    inhibitory neurons, connected via current-based "exponential"
    synapses (instantaneous rise, exponential decay).

    Andrew Davison, UNIC, CNRS
    August 2006

Author: Bernhard Kaplan, [email protected]
"""
import time
t0 = time.time()

# to store timing information
from pyNN.utility import Timer
timer = Timer()
timer.start()
times = {} 
times['t_startup'] = time.time() - t0

# check imports
import numpy as np
import os
import socket
from math import *
import json
from pyNN.utility import get_script_args
simulator_name = 'nest'
from pyNN.nest import *
#exec("from pyNN.%s import *" % simulator_name)
try:
开发者ID:jakobj,项目名称:PyNN,代码行数:31,代码来源:Benchmark_PyNN-0.8dev_FixedNumberPost.py


示例12: NetworkModel

class NetworkModel(object):

    def __init__(self, params, comm):

        self.params = params
        self.debug_connectivity = True
        self.comm = comm
        if self.comm != None:
            self.pc_id, self.n_proc = self.comm.rank, self.comm.size
            print "USE_MPI: yes", '\tpc_id, n_proc:', self.pc_id, self.n_proc
        else:
            self.pc_id, self.n_proc = 0, 1
            print "MPI not used"

        np.random.seed(params['np_random_seed'] + self.pc_id)

        if self.params['with_short_term_depression']:
            self.short_term_depression = SynapseDynamics(fast=TsodyksMarkramMechanism(U=0.95, tau_rec=10.0, tau_facil=0.0))

    def import_pynn(self):
        """
        This function needs only be called when this class is used in another script as imported module
        """
        import pyNN

        exec("from pyNN.%s import *" % self.params['simulator'])
        print 'import pyNN\npyNN.version: ', pyNN.__version__



    def setup(self, load_tuning_prop=False, times={}):

        self.projections = {}
        self.projections['ee'] = []
        self.projections['ei'] = []
        self.projections['ie'] = []
        self.projections['ii'] = []
        if not load_tuning_prop:
            self.tuning_prop_exc = utils.set_tuning_prop(self.params, mode='hexgrid', cell_type='exc')        # set the tuning properties of exc cells: space (x, y) and velocity (u, v)
            self.tuning_prop_inh = utils.set_tuning_prop(self.params, mode='hexgrid', cell_type='inh')        # set the tuning properties of exc cells: space (x, y) and velocity (u, v)
        else:
            self.tuning_prop_exc = np.loadtxt(self.params['tuning_prop_means_fn'])
            self.tuning_prop_inh = np.loadtxt(self.params['tuning_prop_inh_fn'])

        indices, distances = utils.sort_gids_by_distance_to_stimulus(self.tuning_prop_exc, self.params) # cells in indices should have the highest response to the stimulus
        if self.pc_id == 0:
            print "Saving tuning_prop to file:", self.params['tuning_prop_means_fn']
            np.savetxt(self.params['tuning_prop_means_fn'], self.tuning_prop_exc)
            print "Saving tuning_prop to file:", self.params['tuning_prop_inh_fn']
            np.savetxt(self.params['tuning_prop_inh_fn'], self.tuning_prop_inh)
            print 'Saving gids to record to: ', self.params['gids_to_record_fn']
            np.savetxt(self.params['gids_to_record_fn'], indices[:self.params['n_gids_to_record']], fmt='%d')

#        np.savetxt(params['gids_to_record_fn'], indices[:params['n_gids_to_record']], fmt='%d')

        if self.comm != None:
            self.comm.Barrier()
        from pyNN.utility import Timer
        self.timer = Timer()
        self.timer.start()
        self.times = times
        self.times['t_all'] = 0
        # # # # # # # # # # # #
        #     S E T U P       #
        # # # # # # # # # # # #
        (delay_min, delay_max) = self.params['delay_range']
        setup(timestep=0.1, min_delay=delay_min, max_delay=delay_max, rng_seeds_seed=self.params['seed'])
        rng_v = NumpyRNG(seed = sim_cnt*3147 + self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes
        self.rng_conn = NumpyRNG(seed = self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes

        # # # # # # # # # # # # # # # # # # # # # # # # #
        #     R A N D O M    D I S T R I B U T I O N S  #
        # # # # # # # # # # # # # # # # # # # # # # # # #
        self.v_init_dist = RandomDistribution('normal',
                (self.params['v_init'], self.params['v_init_sigma']),
                rng=rng_v,
                constrain='redraw',
                boundaries=(-80, -60))

        self.times['t_setup'] = self.timer.diff()
        self.times['t_calc_conns'] = 0
        if self.comm != None:
            self.comm.Barrier()

        self.torus = space.Space(axes='xy', periodic_boundaries=((0., self.params['torus_width']), (0., self.params['torus_height'])))

    def create_neurons_with_limited_tuning_properties(self):
        n_exc = self.tuning_prop_exc[:, 0].size
        n_inh = 0
        if self.params['neuron_model'] == 'IF_cond_exp':
            self.exc_pop = Population(n_exc, IF_cond_exp, self.params['cell_params_exc'], label='exc_cells')
            self.inh_pop = Population(self.params['n_inh'], IF_cond_exp, self.params['cell_params_inh'], label="inh_pop")
        elif self.params['neuron_model'] == 'IF_cond_alpha':
            self.exc_pop = Population(n_exc, IF_cond_alpha, self.params['cell_params_exc'], label='exc_cells')
            self.inh_pop = Population(self.params['n_inh'], IF_cond_alpha, self.params['cell_params_inh'], label="inh_pop")
        elif self.params['neuron_model'] == 'EIF_cond_exp_isfa_ista':
            self.exc_pop = Population(n_exc, EIF_cond_exp_isfa_ista, self.params['cell_params_exc'], label='exc_cells')
            self.inh_pop = Population(self.params['n_inh'], EIF_cond_exp_isfa_ista, self.params['cell_params_inh'], label="inh_pop")
        else:
            print '\n\nUnknown neuron model:\n\t', self.params['neuron_model']
#.........这里部分代码省略.........
开发者ID:physicalist,项目名称:bcpnn-mt,代码行数:101,代码来源:NetworkSimModule.py


示例13: run_model

def run_model(sim, **options):
    """
    Run a simulation using the parameters read from the file "spike_train_statistics.json"

    :param sim: the PyNN backend module to be used.
    :param options: should contain a keyword "simulator" which is the name of the PyNN backend module used.
    :return: a tuple (`data`, `times`) where `data` is a Neo Block containing the recorded spikes
             and `times` is a dict containing the time taken for different phases of the simulation.
    """

    import json
    from pyNN.utility import Timer

    print("Running")

    timer = Timer()

    g = open("spike_train_statistics.json", 'r')
    d = json.load(g)

    N = d['param']['N']
    max_rate = d['param']['max_rate']
    tstop = d['param']['tstop']
    d['SpikeSourcePoisson'] = {
        "duration": tstop
    }

    if options['simulator'] == "hardware.brainscales":
        hardware_preset = d['setup'].pop('hardware_preset', None)
        if hardware_preset:
            d['setup']['hardware'] = sim.hardwareSetup[hardware_preset]
        d['SpikeSourcePoisson']['random'] = True
        place = mapper.place()

    timer.start()
    sim.setup(**d['setup'])

    spike_sources = sim.Population(N, sim.SpikeSourcePoisson, d['SpikeSourcePoisson'])
    delta_rate = max_rate/N
    rates = numpy.linspace(delta_rate, max_rate, N)
    print("Firing rates: %s" % rates)
    if PYNN07:
        spike_sources.tset("rate", rates)
    else:
        spike_sources.set(rate=rates)

    if options['simulator'] == "hardware.brainscales":
        for i, spike_source in enumerate(spike_sources):
            place.to(spike_source, hicann=i//8, neuron=i%64)
        place.commit()

    if PYNN07:
        spike_sources.record()
    else:
        spike_sources.record('spikes')

    setup_time = timer.diff()
    sim.run(tstop)
    run_time = timer.diff()

    if PYNN07:
        spike_array = spike_sources.getSpikes()
        data = spike_array_to_neo(spike_array, spike_sources, tstop)
    else:
        data = spike_sources.get_data()

    sim.end()

    closing_time = timer.diff()
    times = {'setup_time': setup_time, 'run_time': run_time, 'closing_time': closing_time}

    return data, times
开发者ID:CNRS-UNIC,项目名称:hardware-benchmarks,代码行数:72,代码来源:spike_train_statistics.py


示例14: NetworkModel

class NetworkModel(object):

    def __init__(self, params, comm):

        self.params = params
        self.debug_connectivity = True
        self.comm = comm
        if self.comm != None:
            self.pc_id, self.n_proc = self.comm.rank, self.comm.size
            print "USE_MPI: yes", '\tpc_id, n_proc:', self.pc_id, self.n_proc
        else:
            self.pc_id, self.n_proc = 0, 1
            print "MPI not used"


    def import_pynn(self):
        """
        This function needs only be called when this class is used in another script as imported module
        """
        import pyNN
        exec("from pyNN.%s import *" % self.params['simulator'])
        print 'import pyNN\npyNN.version: ', pyNN.__version__



    def setup(self, load_tuning_prop=False):

        if load_tuning_prop:
            print 'Loading tuning properties from', self.params['tuning_prop_means_fn']
            self.tuning_prop_exc = np.loadtxt(self.params['tuning_prop_means_fn'])
        else:
            print 'Preparing tuning properties with limited range....'
            x_range = (0, 1.)
            y_range = (0.2, .5)
            u_range = (.05, 1.0)
            v_range = (-.2, .2)
            tp_exc_good, tp_exc_out_of_range = utils.set_limited_tuning_properties(params, y_range, x_range, u_range, v_range, cell_type='exc')
            self.tuning_prop_exc = tp_exc_good
            print 'n_exc within range: ', tp_exc_good[:, 0].size
            print "Saving tuning_prop to file:", params['tuning_prop_means_fn']
            np.savetxt(params['tuning_prop_means_fn'], tp_exc_good)

        indices, distances = utils.sort_gids_by_distance_to_stimulus(self.tuning_prop_exc, self.params['motion_params'], self.params) # cells in indices should have the highest response to the stimulus
        if self.pc_id == 0:
            print "Saving tuning_prop to file:", self.params['tuning_prop_means_fn']
            np.savetxt(self.params['tuning_prop_means_fn'], self.tuning_prop_exc)
            print 'Saving gids to record to: ', self.params['gids_to_record_fn']
            np.savetxt(self.params['gids_to_record_fn'], indices[:self.params['n_gids_to_record']], fmt='%d')

#        np.savetxt(params['gids_to_record_fn'], indices[:params['n_gids_to_record']], fmt='%d')

        if self.comm != None:
            self.comm.Barrier()
        from pyNN.utility import Timer
        self.timer = Timer()
        self.timer.start()
        self.times = {}
        # # # # # # # # # # # # 
        #     S E T U P       #
        # # # # # # # # # # # #
        (delay_min, delay_max) = self.params['delay_range']
        setup(timestep=0.1, min_delay=delay_min, max_delay=delay_max, rng_seeds_seed=self.params['seed'])
        rng_v = NumpyRNG(seed = sim_cnt*3147 + self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes
        self.rng_conn = NumpyRNG(seed = self.params['seed'], parallel_safe=True) #if True, slower but does not depend on number of nodes

        # # # # # # # # # # # # # # # # # # # # # # # # #
        #     R A N D O M    D I S T R I B U T I O N S  #
        # # # # # # # # # # # # # # # # # # # # # # # # #
        self.v_init_dist = RandomDistribution('normal',
                (self.params['v_init'], self.params['v_init_sigma']),
                rng=rng_v,
                constrain='redraw',
                boundaries=(-80, -60))

        self.times['t_setup'] = self.timer.diff()
        self.times['t_calc_conns'] = 0
        if self.comm != None:
            self.comm.Barrier()

    def create_neurons_with_limited_tuning_properties(self, input_created):
        n_exc = self.tuning_prop_exc[:, 0].size
        n_inh = 0
        if self.params['neuron_model'] == 'IF_cond_exp':
            self.exc_pop = Population(n_exc, IF_cond_exp, self.params['cell_params_exc'], label='exc_cells')
        elif self.params['neuron_model'] == 'EIF_cond_exp_isfa_ista':
            self.exc_pop = Population(n_exc, EIF_cond_exp_isfa_ista, self.params['cell_params_exc'], label='exc_cells')
        else:
            print '\n\nUnknown neuron model:\n\t', self.params['neuron_model']


        self.local_idx_exc = get_local_indices(self.exc_pop, offset=0)
        self.exc_pop.initialize('v', self.v_init_dist)
        if not input_created:
            self.spike_times_container = [ [] for i in xrange(len(self.local_idx_exc))]

#        self.local_idx_inh = get_local_indices(self.inh_pop, offset=self.params['n_exc'])
#        print 'Debug, pc_id %d has local %d inh indices:' % (self.pc_id, len(self.local_idx_inh)), self.local_idx_inh
#        self.inh_pop.initialize('v', self.v_init_dist)
        self.times['t_create'] = self.timer.diff()

#.........这里部分代码省略.........
开发者ID:MinaKh,项目名称:bcpnn-mt,代码行数:101,代码来源:NetworkSimModuleOnlyExc.py


示例15: run

    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,代码行数:97,代码来源:retina.py


示例16: int

#from pyNN.brian import *
#simulator_name = 'brian'
import simulation_parameters
ps = simulation_parameters.parameter_storage()
params = ps.params


# ===================================
#    G E T   P A R A M E T E R S 
# ===================================
x0, y0 = params['motion_params'][0:2]
sim_cnt = int(sys.argv[1])
mp = float(sys.argv[2]), float(sys.argv[3]), float(sys.argv[4]), float(sys.argv[5])

from pyNN.utility import Timer
timer = Timer()
timer.start()
times = {} # stores time stamps
tuning_prop = utils.set_tuning_prop(params, mode='hexgrid')
time = np.arange(0, params['t_stimulus'], params['dt_rate'])

#print 'Prepare spike trains'
#L_input = np.zeros((params['n_exc'], time.shape[0]))
#for i_time, time_ in enumerate(time):
#    if (i_time % 100 == 0):
#        print "t:", time_
#    L_input[:, i_time] = utils.get_input(tuning_prop, params, time_/params['t_sim'])
#    L_input[:, i_time] *= params['f_max_stim']

# ===============
#    S E T U P 
开发者ID:MinaKh,项目名称:bcpnn-mt,代码行数:31,代码来源:measure_tuning_curve_one_run.py


示例17: runBrunelNetwork

该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python bdf.BDF类代码示例发布时间:2022-05-25
下一篇:
Python utility.normalized_filename函数代码示例发布时间:2022-05-25
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap