Exemple #1
0
def initialize():
    global sim
    global options
    global extra
    global rngseed
    global parallel_safe
    global rng
    global n_ext
    global n_exc
    global n_inh

    sim, options = get_simulator(
        ("--plot-figure", "Plot the connections to a file."))

    init_logging(None, debug=True)

    # === General parameters =================================================

    threads = 1
    rngseed = 98765
    parallel_safe = True
    rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)

    # === general network parameters (except connections) ====================

    n_ext = 60  # number of external stimuli
    n_exc = 60  # number of excitatory cells
    n_inh = 60  # number of inhibitory cells

    # === Options ============================================================

    extra = {
        'loglevel': 2,
        'useSystemSim': True,
        'maxNeuronLoss': 0.,
        'maxSynapseLoss': 0.4,
        'hardwareNeuronSize': 8,
        'threads': threads,
        'filename': "connections.xml",
        'label': 'VA'
    }
    if sim.__name__ == "pyNN.hardware.brainscales":
        extra['hardware'] = sim.hardwareSetup['small']

    if options.simulator == "neuroml":
        extra["file"] = "connections.xml"
Exemple #2
0
def initialize():
    global sim
    global options
    global extra
    global rngseed
    global parallel_safe
    global rng
    global n_ext
    global n_exc
    global n_inh
    
    sim, options = get_simulator(
        ("--plot-figure", "Plot the connections to a file."))

    init_logging(None, debug=True)

    # === General parameters =================================================

    threads = 1
    rngseed = 98765
    parallel_safe = True
    rng = NumpyRNG(seed=rngseed, parallel_safe=parallel_safe)

    # === general network parameters (except connections) ====================

    n_ext = 60   # number of external stimuli
    n_exc = 60  # number of excitatory cells
    n_inh = 60  # number of inhibitory cells

    # === Options ============================================================

    extra = {'loglevel': 2, 'useSystemSim': True,
            'maxNeuronLoss': 0., 'maxSynapseLoss': 0.4,
            'hardwareNeuronSize': 8,
            'threads': threads,
            'filename': "connections.xml",
            'label': 'VA'}
    if sim.__name__ == "pyNN.hardware.brainscales":
        extra['hardware'] = sim.hardwareSetup['small']

    if options.simulator == "neuroml":
        extra["file"] = "connections.xml"
Exemple #3
0
"""
Example of using a cell type defined in 9ML
"""

import sys
from copy import deepcopy
from nineml.abstraction import (Dynamics, Regime, On, OutputEvent,
                                StateVariable, AnalogReceivePort,
                                AnalogReducePort, AnalogSendPort,
                                EventSendPort, Parameter)
from nineml import units as un
from pyNN.utility import init_logging, get_simulator, normalized_filename

sim, options = get_simulator(
    ("--plot-figure", "plot a figure with the given filename"))

init_logging(None, debug=True)

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

iaf = Dynamics(
    name="iaf",
    regimes=[
        Regime(
            name="subthresholdregime",
            time_derivatives=["dV/dt = ( gl*( vrest - V ) + ISyn)/(cm)"],
            transitions=On(
                "V > vthresh",
                do=["tspike = t", "V = vreset",
                    OutputEvent('spikeoutput')],
                to="refractoryregime"),
Exemple #4
0
    inhibitory_cells = sim.create(iaf_neuron, n=n_inh)
    inputs = sim.create(sim.SpikeSourcePoisson(**stimulation_params), n=n_input)
    all_cells = excitatory_cells + inhibitory_cells
    sim.initialize(all_cells, v=cell_params['v_rest'])

    sim.connect(excitatory_cells, all_cells, weight=w_exc, delay=delay,
                receptor_type='excitatory', p=pconn_recurr)
    sim.connect(inhibitory_cells, all_cells, weight=w_exc, delay=delay,
                receptor_type='inhibitory', p=pconn_recurr)
    sim.connect(inputs, all_cells, weight=w_input, delay=delay,
                receptor_type='excitatory', p=pconn_input)
    sim.record('spikes', all_cells, "scenario1a_%s_spikes.pkl" % sim.__name__)
    sim.record('v', excitatory_cells[0:2], "scenario1a_%s_v.pkl" % sim.__name__)

    sim.run(tstop)

    E_count = excitatory_cells.mean_spike_count()
    I_count = inhibitory_cells.mean_spike_count()
    print "Excitatory rate        : %g Hz" % (E_count*1000.0/tstop,)
    print "Inhibitory rate        : %g Hz" % (I_count*1000.0/tstop,)
    sim.end()
    for filename in glob.glob("scenario1a_*"):
        os.remove(filename)


if __name__ == '__main__':
    from pyNN.utility import get_simulator
    sim, args = get_simulator()
    scenario1(sim)
    scenario1a(sim)
"""
Network of integrate-and-fire neurons with distance-dependent connectivity and STDP.
"""

from pyNN.utility import get_simulator
sim, options = get_simulator()
from pyNN import space

n_exc = 80
n_inh = 20
n_stim = 20
cell_parameters = {
    'tau_m' : 20.0,    'tau_syn_E': 2.0,    'tau_syn_I': 5.0,
    'v_rest': -65.0,   'v_reset'  : -70.0,  'v_thresh':  -50.0,
    'cm':     1.0,     'tau_refrac': 2.0,   'e_rev_E':   0.0,
    'e_rev_I': -70.0,
}
grid_parameters = {
    'aspect_ratio': 1, 'dx': 50.0, 'dy': 50.0, 'fill_order': 'random'
}
stimulation_parameters = {
    'rate': 100.0,
    'duration': 50.0
}

connectivity_parameters = {
    'gaussian': {'d_expression': 'exp(-d**2/1e4)'},
    'global': {'p_connect': 0.1},
    'input': {'n': 10},
}
positional arguments:
  simulator      neuron, nest, brian or another backend simulator

optional arguments:
  -h, --help     show this help message and exit
  --plot-figure  Plot the simulation results to a file.
"""

import numpy as np
from pyNN.utility import get_simulator, normalized_filename, ProgressBar
from pyNN.utility.plotting import Figure, Panel
from pyNN.parameters import Sequence

sim, options = get_simulator(
    ("--plot-figure", "Plot the simulation results to a file.", {
        "action": "store_true"
    }))

rate_increment = 20
interval = 200


class SetRate(object):
    """
    A callback which changes the firing rate of a population of spike
    sources at a fixed interval.
    """
    def __init__(self, population, rate_generator, update_interval=20.0):
        assert isinstance(population.celltype, sim.SpikeSourceArray)
        self.population = population
        self.update_interval = update_interval
# encoding: utf-8
"""
Example of simple stochastic synapses

"""

import matplotlib

matplotlib.use('Agg')
import numpy as np
from pyNN.utility import get_simulator, init_logging, normalized_filename

# === Configure the simulator ================================================

sim, options = get_simulator(
    ("--plot-figure", "Plot the simulation results to a file.", {
        "action": "store_true"
    }), ("--debug", "Print debugging information"))

if options.debug:
    init_logging(None, debug=True)

sim.setup(quit_on_end=False)

# === Build and instrument the network =======================================

spike_source = sim.Population(
    1, sim.SpikeSourceArray(spike_times=np.arange(10, 100, 10)))

connector = sim.AllToAllConnector()

synapse_types = {
optional arguments:
  -h, --help     show this help message and exit
  --plot-figure  Plot the simulation results to a file.
  --debug DEBUG  Print debugging information

"""

import matplotlib
matplotlib.use('Agg')
import numpy as np
from pyNN.utility import get_simulator, init_logging, normalized_filename


# === Configure the simulator ================================================

sim, options = get_simulator(("--plot-figure", "Plot the simulation results to a file.", {"action": "store_true"}),
                             ("--debug", "Print debugging information"))

if options.debug:
    init_logging(None, debug=True)

sim.setup(quit_on_end=False)


# === Build and instrument the network =======================================

spike_times = np.hstack((np.arange(10, 100, 10), np.arange(250, 350, 10)))
spike_source = sim.Population(1, sim.SpikeSourceArray(spike_times=spike_times))

connector = sim.AllToAllConnector()

depressing = dict(U=0.8, tau_rec=100.0, tau_facil=0.0, weight=0.01, delay=0.5)
Exemple #9
0
    firing_period / 2,  # (ms) long refractory period to prevent bursting
}
n = 60  # number of synapses / number of presynaptic neurons
delta_t = 1.0  # (ms) time difference between the firing times of neighbouring neurons
t_stop = 10 * firing_period + n * delta_t
delay = 3.0  # (ms) synaptic time delay

# === Configure the simulator ===============================================

sim, options = get_simulator((
    "--plot-figure", "Plot the simulation results to a file", {
        "action": "store_true"
    }
), (
    "--fit-curve",
    "Calculate the best-fit curve to the weight-delta_t measurements", {
        "action": "store_true"
    }
), ("--dendritic-delay-fraction",
    "What fraction of the total transmission delay is due to dendritic propagation",
    {
        "default": 1
    }), ("--debug", "Print debugging information"))

if options.debug:
    init_logging(None, debug=True)

sim.setup(timestep=0.01, min_delay=delay, max_delay=delay)

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

Exemple #10
0
        import argparse
        from importlib import import_module
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "simulator",
            help="neuron, nest, brian, pcsim or another backend simulator")
        for argument in arguments:
            arg_name, help_text = argument[:2]
            extra_args = {}
            if len(argument) > 2:
                extra_args = argument[2]
            parser.add_argument(arg_name, help=help_text, **extra_args)
        args = parser.parse_args()

        # hack around current backend naming issues
        if args.simulator in ("nmpm1", ):
            import pyhmf as sim
        else:
            sim = import_module("pyNN.%s" % args.simulator)

        return sim, args


sim, options = get_simulator(("--plot-figure", "plot a graph of the result"))

list_benchmarks = glob("run_*.py")
for f in list_benchmarks:
    exec("from %s import benchmarks" % splitext(f)[0])
    #    benchmarks(sim=sim, **vars(options))
    benchmarks(sim=sim, plot_figure=True)
Exemple #11
0
Usage: python VAbenchmarks.py <simulator> <benchmark>

    <simulator> is either neuron, nest, brian or pcsim
    <benchmark> is either CUBA or COBA.

Andrew Davison, UNIC, CNRS
August 2006

"""

import os
import socket
from math import *

from pyNN.utility import get_simulator, Timer, ProgressBar, init_logging, normalized_filename
sim, options = get_simulator(("benchmark", "Either CUBA or COBA"))

from pyNN.random import NumpyRNG, RandomDistribution

init_logging(None, debug=True)
timer = Timer()

# === Define parameters ========================================================

threads  = 1
rngseed  = 98765
parallel_safe = True

n        = 4000  # number of cells
r_ei     = 4.0   # number of excitatory cells:number of inhibitory cells
pconn    = 0.02  # connection probability
    "v_reset": -60.0,    # (mV)
    "v_rest": -60.0,     # (mV)
    "cm": 1.0,           # (nF)
    "tau_refrac": 20,    # (ms) long refractory period to prevent bursting
}

n = 256                  # number of synapses / number of presynaptic neurons
t_stop = 0               # defined later if is == 0
delay = 3.0              # (ms) synaptic time delay
episodes = 5;


# === Configure the simulator ===============================================

sim, options = get_simulator(("--plot-figure", "Plot the simulation results to a file", {"action": "store_true"}),
                             ("--fit-curve", "Calculate the best-fit curve to the weight-delta_t measurements", {"action": "store_true"}),
                             ("--debug", "Print debugging information"))

if options.debug:
    init_logging(None, debug=True)

sim.setup(timestep=0.01, min_delay=delay, max_delay=delay)


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

def get_data(filename):
    dvs_data = scipy.io.loadmat(filename)
    ts = dvs_data['ts'][0]
    ts = (ts - ts[0])/1000 #from ns to ms
    x = dvs_data['X'][0]
Exemple #13
0
# Search Example:
# python run.py --folder EPSPsearch --params epsp_response.py --search search.py --map yes nest
# python run.py --folder IPSPsearch --params ipsp_response.py --search search.py --map yes nest
# python plot_map.py

# Analysis Example
# python run.py --folder EPSPsearch --params epsp_response.py --search search.py --analysis true nest

sim, opts = get_simulator(("--analysis", "Perform analysis only", {
    "type": bool
}), ("--remove", "Remove data files (after analysis)", {
    "type": bool
}), ("--folder", "Folder to save the data in (created if it does not exists)",
     {
         "dest": "data_folder",
         "required": True
     }), ("--params", "Parameter filename", {
         "dest": "param_file",
         "required": True
     }), ("--search", "Parameter search filename", {
         "dest": "search_file"
     }), ("--map", "Produce a map of 2D parameter search", {
         "type": bool
     }), ("--debug", "Print debugging information"))

if opts.debug:
    init_logging(None, debug=True)

if opts.analysis:
    print("\nRunning analysis and plotting only ...")

if opts.remove:
              "command_line_options": options,
              "timestamp": timestamp}
    with open("I_f_curve.json", 'r') as f:
        output["configuration"] = {"model": json.load(f)}
    print("RESULTS")
    print(output)  # debug
    with open("results/%s/%s.json" % (timestamp, BENCHMARK_NAME), 'w') as f:
        json.dump(output, f, indent=4)


def benchmarks(sim, **options):
    from spike_train_statistics import run_model
    data, times = run_model(sim, **options)
    timestamp = datetime.now().isoformat()
    if not os.path.exists("results/" + timestamp):
        os.makedirs("results/" + timestamp)
    results = []
    results.append(analysis_quality(data, timestamp, **options))
    results = analysis_performance(times, results)
    output_result(results, options, timestamp)


if __name__ == '__main__':
    try:
        from pyNN.utility import get_simulator  # PyNN 0.8
    except ImportError:
        from utility import get_simulator

    sim, options = get_simulator(("--plot-figure", "plot a graph of the result"))
    benchmarks(sim=sim, **vars(options))
Exemple #15
0
    t = sim.run(t_step)  # no more synaptic input, neurons decay

    spiketimes += 2 * t_step
    spikesources[0].spike_times = spiketimes
    # note we add no new spikes to the second source
    t = sim.run(t_step)  # first neuron gets depolarized again

    vm = cells.get_data().segments[0].analogsignals[0]
    final_v_0 = vm[-1, 0]
    final_v_1 = vm[-1, 1]

    sim.end()

    if plot_figure:
        import matplotlib.pyplot as plt
        plt.plot(vm.times, vm[:, 0])
        plt.plot(vm.times, vm[:, 1])
        plt.savefig("ticket166_%s.png" % sim.__name__)

    assert final_v_0 > -60.0  # first neuron has been depolarized again
    assert final_v_1 < -64.99  # second neuron has decayed back towards rest


if __name__ == '__main__':
    from pyNN.utility import get_simulator
    sim, args = get_simulator(("--plot-figure", {
        "help": "generate a figure",
        "action": "store_true"
    }))
    ticket166(sim, plot_figure=args.plot_figure)
Exemple #16
0
    "cm": 1.0,  # (nF)
    "tau_refrac": firing_period / 2,  # (ms) long refractory period to prevent bursting
}
n = 60  # number of synapses / number of presynaptic neurons
delta_t = 1.0  # (ms) time difference between the firing times of neighbouring neurons
t_stop = 10 * firing_period + n * delta_t
delay = 3.0  # (ms) synaptic time delay


# === Configure the simulator ===============================================

sim, options = get_simulator(
    ("--plot-figure", "Plot the simulation results to a file", {"action": "store_true"}),
    ("--fit-curve", "Calculate the best-fit curve to the weight-delta_t measurements", {"action": "store_true"}),
    (
        "--dendritic-delay-fraction",
        "What fraction of the total transmission delay is due to dendritic propagation",
        {"default": 1},
    ),
    ("--debug", "Print debugging information"),
)

if options.debug:
    init_logging(None, debug=True)

sim.setup(timestep=0.01, min_delay=delay, max_delay=delay)


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


def build_spike_sequences(period, duration, n, delta_t):
Exemple #17
0
    "v_rest": -60.0,  # (mV)
    "cm": 1.0,  # (nF)
    "tau_refrac":
    firing_period / 2,  # (ms) long refractory period to prevent bursting
}
n = 60  # number of synapses / number of presynaptic neurons
delta_t = 1.0  # (ms) time difference between the firing times of neighbouring neurons
t_stop = 10 * firing_period + n * delta_t
delay = 1.0  # (ms) synaptic time delay

# === Configure the simulator ===============================================

sim, options = get_simulator(
    ("--plot-figure", "Plot the simulation results to a file", {
        "action": "store_true"
    }), ("--fit-curve",
         "Calculate the best-fit curve to the weight-delta_t measurements", {
             "action": "store_true"
         }), ("--debug", "Print debugging information"))

if options.debug:
    init_logging(None, debug=True)

sim.setup(timestep=0.01, min_delay=delay)

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


def build_spike_sequences(period, duration, n, delta_t):
    """
    Return a spike time generator for `n` neurons (spike sources), where
Exemple #18
0
Usage: python VAbenchmarks.py <simulator> <benchmark>

    <simulator> is either neuron, nest, brian or pcsim
    <benchmark> is either CUBA or COBA.

Andrew Davison, UNIC, CNRS
August 2006

"""

import os
import socket
from math import *

from pyNN.utility import get_simulator, Timer, ProgressBar, init_logging, normalized_filename
sim, options = get_simulator(("benchmark", "Either CUBA or COBA"))

from pyNN.random import NumpyRNG, RandomDistribution

init_logging(None, debug=True)
timer = Timer()

# === Define parameters ========================================================

threads = 1
rngseed = 98765
parallel_safe = True

n = 4000  # number of cells
r_ei = 4.0  # number of excitatory cells:number of inhibitory cells
pconn = 0.02  # connection probability
Exemple #19
0
"""

import socket
from math import *
from pyNN.utility import get_simulator, Timer, ProgressBar, init_logging, normalized_filename
from pyNN.random import NumpyRNG, RandomDistribution

# === Configure the simulator ================================================

sim, options = get_simulator(
    ("benchmark", "either CUBA or COBA"),
    ("--plot-figure", "plot the simulation results to a file", {
        "action": "store_true"
    }), ("--use-views", "use population views in creating the network", {
        "action": "store_true"
    }), ("--use-assembly", "use assemblies in creating the network", {
        "action": "store_true"
    }), ("--use-csa",
         "use the Connection Set Algebra to define the connectivity", {
             "action": "store_true"
         }), ("--debug", "print debugging information"))

if options.use_csa:
    import csa

if options.debug:
    init_logging(None, debug=True)

timer = Timer()

# === Define parameters ========================================================
        assert_less(D, 0.1)

    return data
test_SpikeSourcePoissonRefractory.__test__ = False



@register()
def issue511(sim):
    """Giving SpikeSourceArray an array of non-ordered spike times should produce an InvalidParameterValueError error"""
    sim.setup()
    celltype = sim.SpikeSourceArray(spike_times=[[2.4, 4.8, 6.6, 9.4], [3.5, 6.8, 9.6, 8.3]])
    assert_raises(InvalidParameterValueError, sim.Population, 2, celltype)



# todo: add test of Izhikevich model


if __name__ == '__main__':
    from pyNN.utility import get_simulator
    sim, args = get_simulator(("--plot-figure",
                               {"help": "generate a figure",
                                "action": "store_true"}))
    test_EIF_cond_alpha_isfa_ista(sim, plot_figure=args.plot_figure)
    test_HH_cond_exp(sim, plot_figure=args.plot_figure)
    issue367(sim, plot_figure=args.plot_figure)
    test_SpikeSourcePoisson(sim, plot_figure=args.plot_figure)
    test_SpikeSourceGamma(sim, plot_figure=args.plot_figure)
    test_SpikeSourcePoissonRefractory(sim, plot_figure=args.plot_figure)
    issue511(sim)
"""
Test of the EIF_cond_alpha_isfa_ista model

Andrew Davison, UNIC, CNRS
December 2007

"""

from pyNN.utility import get_simulator, normalized_filename

sim, options = get_simulator(("--plot-figure",
                              "Plot the simulation results to a file."))

sim.setup(timestep=0.01, min_delay=0.1, max_delay=4.0)

cell_type = sim.EIF_cond_alpha_isfa_ista(i_offset=1.0, tau_refrac=2.0, v_spike=-40)
ifcell = sim.create(cell_type)
print ifcell[0].get_parameters()

filename = normalized_filename("Results", "EIF_cond_alpha_isfa_ista", "pkl",
                               options.simulator)
sim.record('v', ifcell, filename, annotations={'script_name': __file__})
sim.run(200.0)

if options.plot_figure:
    from pyNN.utility.plotting import Figure, Panel
    data = ifcell.get_data().segments[0]
    vm = data.filter(name="v")[0]
    Figure(
        Panel(vm, ylabel="Membrane potential (mV)", xlabel="Time (ms)",
              xticks=True),
Exemple #22
0

# ADDITIONAL FUNCTIONS ---------------------------------------------------------

def replace(dic, keys,value):
    getValue(dic,keys[:-1])[keys[-1]]=value

def getValue(dic, keys):
    return reduce(lambda d, k: d[k], keys, dic)


sim, opts = get_simulator(
        ("--analysis", "Perform analysis only", {"type":bool}),
        ("--remove", "Remove data files (after analysis)", {"type":bool}),
        ("--folder", "Folder to save the data in (created if it does not exists)", {"dest":"data_folder", "required":True}),
        ("--params", "Parameter filename", {"dest":"param_file", "required":True}),
        ("--search", "Parameter search filename", {"dest":"search_file"}),
        ("--map",    "Produce a map of 2D parameter search", {"type":bool}),
        ("--debug", "Print debugging information")
    )

if opts.debug:
    init_logging(None, debug=True)

if opts.analysis:
    print "Running analysis and plotting only ..."

if opts.remove:
    print "Removing data files after analysis ..."

if opts.data_folder:
Exemple #23
0
        
        file_name = self.results_dir
        if fname == None:
            file_name += datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        else:
            if fname_time:
                file_name += datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            file_name += fname
        file_name += '.csv'
        
        with open(file_name, 'w') as f:
            f.write('Time/ms,NeuronID\n')
            for i in range(neurons.shape[0]):
                line = '{},{}'.format(spike_times[i], neurons[i])
                f.write(line + '\n')



if __name__ == '__main__':
    from pyNN.utility import get_simulator
    Gexc = ("Gexc","Excitatory Conductance", {"action":"store", "type": float})
    Ginh = ("Ginh","Inhibitory Conductance", {"action":"store", "type": float})
    pconn = ("pconn", "Probability of Connectivity", {"action":"store", "type":
                                                      float})
    n = ("n", "Number of Neurons", {"action":"store", "type":int})
    tstop = ("tstop", "Length of Sim", {"action":"store", "type":int})

    p, options = get_simulator(Gexc, Ginh, pconn, n, tstop)

    run_script(p, options)
Exemple #24
0
"""

"""

from pyNN.utility import get_simulator
sim, options = get_simulator()

sim.setup(timestep=0.01)

cell = sim.Population(
    1, sim.EIF_cond_exp_isfa_ista(v_thresh=-55.0, tau_refrac=5.0))
current_source = sim.StepCurrentSource(
    times=[50.0, 200.0, 250.0, 400.0, 450.0, 600.0, 650.0, 800.0],
    amplitudes=[1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0])
cell.inject(current_source)
cell.record('v')

for a in (0.0, 4.0, 20.0, 100.0):
    print("Setting current to %g nA" % a)
    cell.set(a=a)
    sim.run(200.0)

cell.write_data("Results/parameter_changes_%s.pkl" % options.simulator)

sim.end()
Exemple #25
0
"""

import os
import socket
from math import *
from pyNN.utility import get_simulator, Timer, ProgressBar, init_logging, normalized_filename
from pyNN.random import NumpyRNG, RandomDistribution


# === Configure the simulator ================================================

sim, options = get_simulator(
                    ("benchmark", "either CUBA or COBA"),
                    ("--plot-figure", "plot the simulation results to a file", {"action": "store_true"}),
                    ("--use-views", "use population views in creating the network", {"action": "store_true"}),
                    ("--use-assembly", "use assemblies in creating the network", {"action": "store_true"}),
                    ("--use-csa", "use the Connection Set Algebra to define the connectivity", {"action": "store_true"}),
                    ("--debug", "print debugging information"))

if options.use_csa:
    import csa

if options.debug:
    init_logging(None, debug=True)

timer = Timer()

# === Define parameters ========================================================

threads  = 1
Exemple #26
0
    """
    dt = 0.1
    sim.setup(timestep=dt, min_delay=dt)
    p = sim.Population(1, sim.IF_curr_exp())
    c = sim.DCSource(amplitude=0.5)
    c.inject_into(p)
    p.record('v')

    simtime = 200.0
    sim.run(100.0)
    sim.run(100.0)

    v = p.get_data().segments[0].filter(name="v")[0]

    # check that the length of vm vector is as expected theoretically
    assert (len(v) == (int(simtime / dt) + 1))


if __name__ == '__main__':
    from pyNN.utility import get_simulator
    sim, args = get_simulator()
    test_changing_electrode(sim)
    ticket226(sim)
    issue165(sim)
    issue321(sim)
    issue437(sim)
    issue442(sim)
    issue445(sim)
    issue451(sim)
    issue483(sim)
Exemple #27
0
from numpy import arange
#from pyNN.carlsim import *
from pyNN.utility import get_simulator
import time
# Configure the application (i.e) configure the additional
# simualator parameters

sim, options = get_simulator(
    ("netName", "String for name of simulation"),
    ("--gpuMode", "Enable GPU_MODE (CPU_MODE by default)", {
        "action": "store_true"
    }), ("logMode", "Enter logger mode (USER by default)", {
        "default": "USER"
    }), ("ithGPUs", "Number of GPUs"), ("randSeed", "Random seed"))

##################################################################
# Utility section (move to different utility class later)
##################################################################

# Create file scope vars for options
netName = None
simMode = None
logMode = None
ithGPUs = None
randSeed = None

# Validate and assign appropriate options
netName = options.netName

if options.gpuMode:
    simMode = sim.GPU_MODE
Usage: varying_poisson.py [-h] [--plot-figure] simulator

positional arguments:
  simulator      neuron, nest, brian or another backend simulator

optional arguments:
  -h, --help     show this help message and exit
  --plot-figure  Plot the simulation results to a file.
"""

import numpy as np
from pyNN.utility import get_simulator, normalized_filename, ProgressBar
from pyNN.utility.plotting import Figure, Panel

sim, options = get_simulator(("--plot-figure", "Plot the simulation results to a file.",
                              {"action": "store_true"}))

rate_increment = 20
interval = 200

class SetRate(object):
    """
    A callback which changes the firing rate of a population of poisson
    processes at a fixed interval.
    """

    def __init__(self, population, rate_generator, interval=20.0):
        assert isinstance(population.celltype, sim.SpikeSourcePoisson)
        self.population = population
        self.interval = interval
        self.rate_generator = rate_generator
"""
Example of using a cell type defined in 9ML
"""

import sys
from copy import deepcopy
from nineml.abstraction import (
    Dynamics, Regime, On, OutputEvent, StateVariable, AnalogReceivePort,
    AnalogReducePort, AnalogSendPort, EventSendPort, Parameter)
from nineml import units as un
from pyNN.utility import init_logging, get_simulator, normalized_filename

sim, options = get_simulator(("--plot-figure", "plot a figure with the given filename"))

init_logging(None, debug=True)

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


iaf = Dynamics(
    name="iaf",
    regimes=[
        Regime(
            name="subthresholdregime",
            time_derivatives=["dV/dt = ( gl*( vrest - V ) + ISyn)/(cm)"],
            transitions=On("V > vthresh",
                           do=["tspike = t",
                               "V = vreset",
                               OutputEvent('spikeoutput')],
                           to="refractoryregime"),
        ),