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


Python Timer.diff方法代码示例

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


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

示例1: FixedProbabilityConnector

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
connector = FixedProbabilityConnector(pconn, rng=rng, callback=progress_bar)
exc_syn = StaticSynapse(weight=w_exc, delay=delay)
inh_syn = StaticSynapse(weight=w_inh, delay=delay)

connections={}
connections['exc'] = Projection(exc_cells, all_cells, connector, exc_syn, receptor_type='excitatory')
connections['inh'] = Projection(inh_cells, all_cells, connector, inh_syn, receptor_type='inhibitory')
if (benchmark == "COBA"):
    connections['ext'] = Projection(ext_stim, all_cells, ext_conn, ext_syn, receptor_type='excitatory')

# === Setup recording ==========================================================
print "%s Setting up recording..." % node_id
all_cells.record('spikes')
exc_cells[[0, 1]].record('v')

buildCPUTime = timer.diff()

# === Save connections to file =================================================

#print "%s Saving connections to file..." % node_id
#for prj in connections.keys():
#    connections[prj].saveConnections('Results/VAbenchmark_%s_%s_%s_np%d.conn' % (benchmark, prj, simulator_name, np))
#saveCPUTime = timer.diff()

# === Run simulation ===========================================================
print "%d Running simulation..." % node_id

run(tstop)

simCPUTime = timer.diff()
开发者ID:bernhardkaplan,项目名称:PyNN,代码行数:32,代码来源:VAbenchmarks2.py

示例2: abs

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
    dy = abs(pos_1[:, 1] - pos_2[:, 1])
    dx = numpy.minimum(dx, N - dx)
    dy = numpy.minimum(dy, N - dy)
    return sqrt(dx * dx + dy * dy)


timer.start()
node_id = setup(timestep=0.1, min_delay=0.1, max_delay=4.0)
print "Creating cells population..."
N = 30

structure = RandomStructure(Cuboid(1, 1, 1), origin=(0.5, 0.5, 0.5), rng=NumpyRNG(2652))
# structure = Grid2D(dx=1/float(N), dy=1/float(N))

x = Population(N ** 2, IF_curr_exp(), structure=structure)
mytime = timer.diff()
print "Time to build the cell population:", mytime, "s"


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))
开发者ID:bernhardkaplan,项目名称:PyNN,代码行数:33,代码来源:connectors_benchmark.py

示例3: test

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
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,代码行数:103,代码来源:connectors_benchmark.py

示例4: enumerate

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
    # Save weights for all connections
    for i, (ampa_weight_writer, nmda_weight_writer) in enumerate(connection_results):
        # Write AMPA weights
        ampa_weight_writer("%s/connection_%u_e_e_ampa.npy" % (folder, i))

        # Write NMDA weights to correct folder
        if mode == Mode.train_asymmetrical:
            nmda_weight_writer("%s/connection_%u_e_e_nmda_asymmetrical.npy" % (folder, i))
        else:
            nmda_weight_writer("%s/connection_%u_e_e_nmda_symmetrical.npy" % (folder, i))

    # Loop through the HCU results and save data to pickle format
    for i, (hcu_e_data_writer,) in enumerate(hcu_results):
        hcu_e_data_writer("%s/hcu_%u_e_data.pkl" % (folder, i))

    logger.info("Download time %gs", timer.diff())

    # Once data is read, end simulation
    end_simulation()
else:
    # Testing parameters
    testing_simtime = 6000.0   # simulation time [ms]

    ampa_nmda_ratio = 4.795918367
    tau_ca2 = 300.0

    if mode == Mode.test_symmetrical:
        i_alpha = 0.7
        gain_per_hcu = 1.3
    else:
        i_alpha = 0.15
开发者ID:project-rig,项目名称:pynn_spinnaker_bcpnn,代码行数:33,代码来源:experiment_sequence.py

示例5: NetworkModel

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
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["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,代码行数:103,代码来源:NetworkSimModuleNoColumns.py

示例6: Abbott

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
## Start
## The asynchronous irregular network dynamics of the model published in
## Vogels and Abbott (2005) without inhibitory plasticity.
## Original simulation time: 1 min (60000 ms)

excPopulation.record('spikes')
pattern1.record('spikes')
pattern1_stim.record('spikes')
pattern2.record('spikes')
pattern2_stim.record('spikes')
patternIntersection.record('spikes')
controlPopulation.record('spikes')
inhibPopulation.record('spikes')

buildCPUTime = timer.diff()

print("\n\nTime to build the network: %s seconds" % buildCPUTime)

print("\n--- Pre-simulation ---")
print("\nPre-simulation time: %s milliseconds" % timePreSim)

run(timePreSim)

simCPUTime_pre = timer.diff()

print("\nTime to perform the pre-simulation: %d seconds (%0.2f minutes)" % (simCPUTime_pre, simCPUTime_pre / 60))

excSpikes = excPopulation.get_data('spikes', clear="true")
pattern1Spikes = pattern1.get_data('spikes')
pattern1_stimSpikes = pattern1_stim.get_data('spikes', clear="true")
开发者ID:ChristophMetzner,项目名称:VogelsEtAl2011,代码行数:32,代码来源:vogelsEtAl2011.py

示例7: Abbott

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
## 	The asynchronous irregular network dynamics of the model published in
## 	Vogels and Abbott (2005) without inhibitory plasticity.
## 	Original simulation time: 1 min (60000 ms)


excPopulation.record('spikes')
pattern1.record('spikes')
pattern1_stim.record('spikes')
pattern2.record('spikes')
pattern2_stim.record('spikes')
patternIntersection.record('spikes')
controlPopulation.record('spikes')
inhibPopulation.record('spikes')


buildCPUTime = timer.diff()

print("\n\nTime to build the network: %s seconds" %buildCPUTime)

print("\n--- Pre-simulation ---")
print("\nPre-simulation time: %s milliseconds" %timePreSim)


run(timePreSim)


simCPUTime_pre = timer.diff()

print("\nTime to perform the pre-simulation: %d seconds (%0.2f minutes)" %(simCPUTime_pre, simCPUTime_pre/60))

excSpikes			= 	excPopulation.get_data(		'spikes', clear="true")
开发者ID:dvshishkov,项目名称:VogelsEtAl2011,代码行数:33,代码来源:vogelsEtAl2011.py

示例8: enumerate

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
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 
# ===============
(delay_min, delay_max) = params['delay_range']
setup(timestep=0.1, min_delay=delay_min, max_delay=delay_max, rng_seeds_seed=sim_cnt)
times['t_setup'] = timer.diff()
exc_pop = Population(params['n_exc'], IF_cond_exp, params['cell_params_exc'], label='exc_cells')
times['t_create'] = timer.diff()

rng_v = NumpyRNG(seed = sim_cnt*3147 + params['seed'])
v_init_dist = RandomDistribution('normal',
        (params['v_init'], params['v_init_sigma']),
        rng=rng_v,
        constrain='redraw',
        boundaries=(-80, -60))
exc_pop.initialize('v', v_init_dist)

# ==================================
#    C O N N E C T    I N P U T 
# ==================================
for tgt in xrange(params['n_exc']):
开发者ID:MinaKh,项目名称:bcpnn-mt,代码行数:33,代码来源:measure_tuning_curve_one_run.py

示例9: int

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
simulator_name = 'nest'
from pyNN.nest import *
#exec("from pyNN.%s import *" % simulator_name)
try:
    from mpi4py import MPI
    USE_MPI = True
    comm = MPI.COMM_WORLD
    node_id, n_proc = comm.rank, comm.size
    print "USE_MPI:", USE_MPI, 'pc_id, n_proc:', node_id, n_proc
except:
    USE_MPI = False
    node_id, n_proc, comm = 0, 1, None
    print "MPI not used"

from pyNN.random import NumpyRNG, RandomDistribution
times['t_import'] = timer.diff()

# === DEFINE PARAMETERS 
benchmark = "COBA"
rngseed  = 98765
parallel_safe = True
np = num_processes()
folder_name = 'Results_PyNN_FixedNumberPost_np%d/' % (np)
gather = False # gather spikes and membrane potentials on one process
times_fn = 'pynn_times_FixedNumberPost_gather%d_np%d.dat' % (gather, np)

n_cells  = 200 * np 
r_ei     = 4.0   # number of excitatory cells:number of inhibitory cells
n_exc = int(round((n_cells*r_ei/(1+r_ei)))) # number of excitatory cells   
n_inh = n_cells - n_exc                     # number of inhibitory cells
n_cells_to_record = np
开发者ID:jakobj,项目名称:PyNN,代码行数:33,代码来源:Benchmark_PyNN-0.8dev_FixedNumberPost.py

示例10: NetworkModel

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
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,代码行数:103,代码来源:NetworkSimModule.py

示例11: run_model

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
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,代码行数:74,代码来源:spike_train_statistics.py

示例12: NetworkModel

# 需要导入模块: from pyNN.utility import Timer [as 别名]
# 或者: from pyNN.utility.Timer import diff [as 别名]
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,代码行数:103,代码来源:NetworkSimModuleOnlyExc.py


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