示例#1
0
    for t in segInh.spiketrains[0]:
        plt.axvline(t, color='red', linewidth=1.)

    for t in segExc.spiketrains[0]:
        plt.axvline(t, color='green', linewidth=1.)

    max_v = np.max(segment.filter(name='v')[0])
    ax0.plot(segment.spiketrains[0],
             0.99 * max_v * np.ones_like(segment.spiketrains[0]), '.b')

    ax0.plot(segment.filter(name='v')[0], color='blue')


timestep = 1.
runtime = 1000.
sim.setup(timestep)

n_neurons = 1
preExc = sim.Population(n_neurons,
                        sim.SpikeSourcePoisson(rate=100),
                        label='input')
preExc.record('spikes')

preInh = sim.Population(n_neurons,
                        sim.SpikeSourcePoisson(rate=100),
                        label='input')
preInh.record('spikes')

parameters = {
    'v_rest': -65.0,  # Resting membrane potential in mV.
    'cm': 1.0,  # Capacity of the membrane in nF
n_inh = n - n_exc  # number of inhibitory cells
if benchmark == "COBA":
    celltype = sim.IF_cond_exp
    w_exc = Gexc * 1e-3  # We convert conductances to uS
    w_inh = Ginh * 1e-3
elif benchmark == "CUBA":
    celltype = sim.IF_curr_exp
    w_exc = 1e-3 * Gexc * (Erev_exc - v_mean
                           )  # (nA) weight of excitatory synapses
    w_inh = 1e-3 * Ginh * (Erev_inh - v_mean)  # (nA)
    assert w_exc > 0
    assert w_inh < 0

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

node_id = sim.setup(timestep=dt, min_delay=dt, max_delay=2.0, **setup_kwargs)

cell_params = {
    'tau_m': tau_m,
    'tau_syn_E': tau_exc,
    'tau_syn_I': tau_inh,
    'v_rest': E_leak,
    'v_reset': v_reset,
    'v_thresh': v_thresh,
    'cm': cm,
    'tau_refrac': t_refrac
}

if (benchmark == "COBA"):
    cell_params['e_rev_E'] = Erev_exc
    cell_params['e_rev_I'] = Erev_inh
示例#3
0
import numpy as np
import matplotlib.pyplot as plt
import pynn_genn as sim


def spikes_from_data(data):
    spikes = [[] for _ in range(len(data.segments[0].spiketrains))]
    for train in data.segments[0].spiketrains:
        spikes[int(train.annotations['source_index'])][:] = \
            [float(t) for t in train]
    return spikes


np.random.seed(1)

sim.setup(timestep=1.0, min_delay=1.0)

max_t = 50  #ms
spikes_per_neuron = int(max_t * 0.1)
n_ssa = 5
n_neurons = [np.random.randint(100, 1000) for _ in range(n_ssa)]

sources = {}

for ssa_id in range(n_ssa):
    sources[ssa_id] = {}

    spike_times = []
    for nid in range(n_neurons[ssa_id]):
        n_spikes = int(np.random.choice(spikes_per_neuron))
        spikes = np.round(np.random.choice(max_t, size=n_spikes,
示例#4
0
                   in_pop,
                   connector,
                   static_synapse,
                   receptor_type='inhibitory')

    # Make inhibitory->excitatory projections
    ie_projection = sim.Projection(in_pop,
                                   ex_pop,
                                   connector,
                                   ie_synapse,
                                   receptor_type='inhibitory')

    return ex_pop, ie_projection


'''
# Build static network
sim.setup(timestep=1.0)
static_ex_pop,_ = build_network(sim.StaticSynapse(weight=0.0, delay=1.0), 300.0)

# Run for 1s
sim.run(1000)

# Get static spikes and save to disk
static_data = static_ex_pop.get_data()

# Clear simulator state
sim.end()
'''
# Clear simulation state
sim.setup(min_delay=1.0, max_delay=7.0, timestep=1.0)
示例#5
0
#     'v_thresh_adapt': -55.0,
#     # 'e_rev_I': -e_rev, #mV
#     # 'e_rev_E': 0.,#e_rev, #mV
#     'tau_m': 10.,  # ms
#     'tau_refrac': 0.1,  # ms
#     'tau_syn_E': 1.0,  # ms
#     'tau_syn_I': 5.0,  # ms
#     'tau_thresh': 50.0,
#     'mult_thresh': 1.8,
#     'i_offset': i_offsets,
# }

sim_time = 100.0
timestep = 1.0

sim.setup(timestep=timestep, min_delay=timestep, backend='SingleThreadedCPU')

post = sim.Population(n_neurons, neuron_class(**base_params))
post.record('spikes')
post.record('v_thresh_adapt')
post.record('v')

pre = sim.Population(
    n_neurons,
    sim.SpikeSourceArray(spike_times=[[10] for _ in range(n_neurons)]),
)
proj = sim.Projection(pre, post, sim.OneToOneConnector(),
                      sim.StaticSynapse(weight=3.2))

sim.run(sim_time)
示例#6
0
import math
import pylab
import pynn_genn as sim

pylab.rc("text", usetex=True)

labels = [
    "Regular spiking", "Fast spiking", "Chattering", "Intrinsically bursting"
]
a = [0.02, 0.1, 0.02, 0.02]
b = [0.2, 0.2, 0.2, 0.2]
c = [-65.0, -65.0, -50.0, -55.0]
d = [8.0, 2.0, 2.0, 4.0]

sim.setup(timestep=0.1, min_delay=0.1, max_delay=4.0)
ifcell = sim.Population(len(labels),
                        sim.Izhikevich(i_offset=0.01, a=a, b=b, c=c, d=d))
ifcell.record("v")

sim.run(200.0)

data = ifcell.get_data()

sim.end()

figure, axes = pylab.subplots(2, 2, sharex="col", sharey="row")

axes[0, 0].set_ylabel("Membrane potential [mV]")
axes[1, 0].set_ylabel("Membrane potential [mV]")
axes[1, 0].set_xlabel("Time [ms]")
axes[1, 1].set_xlabel("Time [ms]")
from LaminartWithSegmentationPyNN import buildNetworkAndConnections
from images2gif import writeGif
# from pyNN.utility import get_simulator
# sim, options = get_simulator()

####################################
### Define parameters down here! ###
####################################

# How time goes
dt = 1.0  # (ms) time step for network updates
stepDuration = 50.0  # (ms) time step for visual input and segmentation signal updates
simTime = 100.0  # (ms)
nTimeSteps = numpy.int(simTime / stepDuration)
sloMoRate = 4.0  # how much the GIFs are slowed vs real time, default is 4.0
sim.setup(timestep=dt, min_delay=1.0, max_delay=10.0)  # delays in ms

# General parameters
fileName = "squares 1"  # this would be removed if it is in the NRP
input, ImageNumPixelRows, ImageNumPixelColumns = setInput.readAndCropBMP(
    fileName, onlyZerosAndOnes=0)
print("Input image dimensions of " + fileName + ": [Rows, Columns] = " +
      str([ImageNumPixelRows, ImageNumPixelColumns]))
weightScale = 1.0  # general weight for all connections between neurons
constantInput = 0.5  # input given to the tonic interneuron layer and to the top-down activated segmentation neurons
inputPoisson = 0  # 1 for a poisson spike source input, 0 for a DC current input
cellParams = {  # parameters for any neuron in the network
    'i_offset': 0.0,  # (nA)
    'tau_m': 10.0,  # (ms)
    'tau_syn_E': 2.0,  # (ms)
    'tau_syn_I': 2.0,  # (ms)
示例#8
0
    'v_rest': -65.,  # mV
    'v_thresh': -55.,  # mV
    'tau_m': 10.,  # ms
    'tau_refrac': 2.0,  # ms
    'tau_syn_E': 1.0,  # ms
    'tau_syn_I': 5.0,  # ms
}

timestep = 0.1
max_w = 0.01
start_w = max_w / 2.0
min_delay = 0.1

sim.setup(timestep,
          min_delay=min_delay,
          backend='CUDA'
          # backend='SingleThreadedCPU'
          )

pre = sim.Population(10, sim.SpikeSourcePoisson(**{'rate': 10}))
post = sim.Population(100, neuron_class(**base_params))

# w = 1.0
w = sim.RandomDistribution('normal', [5.0, 1.0])
synapse = sim.StaticSynapse(weight=w)

prj = sim.Projection(
    pre,
    post,
    sim.FixedProbabilityConnector(0.25),
    # prj = sim.Projection(pre, post, sim.AllToAllConnector(),
Since neurons 1 and 2 have deterministic spiking, they should produce the same spike times with
different simulators. Neurons 3 and 4, being stochastic, should spike at different times.

Reference:

Pozzorini, Christian, Skander Mensi, Olivier Hagens, Richard Naud, Christof Koch, and Wulfram Gerstner (2015)
"Automated High-Throughput Characterization of Single Neurons by Means of Simplified Spiking Models."
PLOS Comput Biol 11 (6): e1004275. doi:10.1371/journal.pcbi.1004275.

"""

import matplotlib.pyplot as plt
import pynn_genn as sim
from pyNN.utility.plotting import Figure, Panel

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

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

t_stop = 300.0

parameters = {
    'neurons': {
        'v_rest': -65.0,  # Resting membrane potential in mV.
        'cm': 1.0,  # Capacity of the membrane in nF
        'tau_m': 20.0,  # Membrane time constant in ms.
        'tau_refrac': 4.0,  # Duration of refractory period in ms.
        'tau_syn_E':
        5.0,  # Decay time of the excitatory synaptic conductance in ms.
        'tau_syn_I':
        5.0,  # Decay time of the inhibitory synaptic conductance in ms.
示例#10
0
    def run(self, params):
        self._do_record = True
        self._network = {}
        self._network['timestep'] = 0.1  #ms
        self._network['min_delay'] = 0.1  #ms
        self._network['run_time'] = 1000

        sim.setup(self._network['timestep'],
                  model_name=self.name,
                  backend='CUDA')

        # Neuron populations
        pops = {}
        pops['input'] = self.gen_input_pop()
        pops['output'] = self.gen_output_pop()
        self._network['populations'] = pops

        # Projections
        projs = {}
        projs['inupt to output'] = self.gen_input_to_output_proj()
        self._network['projections'] = projs

        # Run
        log.info('Running sim for {}ms.'.format(self._network['run_time']))
        sim.run(self._network['run_time'])

        # Collect data
        if self._do_record:
            log.info('Collect data from all populations:')
            for popname, pop in pops.items():
                log.info(' -> Saving recorded data for "{}".'.format(popname))
                # Voltages
                voltagedata = pop.get_data('v')
                signal = voltagedata.segments[0].analogsignals[0]
                source_ids = signal.annotations['source_ids']
                for idx in range(len(source_ids)):
                    s_id = source_ids[idx]
                    filename = "%s_%s_%s.dat" % (
                        pop.label, pop.id_to_index(s_id), signal.name)
                    vm = signal.transpose()[idx]
                    tt = np.array([
                        t * sim.get_time_step() / 1000. for t in range(len(vm))
                    ])
                    times_vm = np.array([tt, vm / 1000.]).transpose()
                    np.savetxt(filename, times_vm, delimiter='\t', fmt='%s')

                    # Spikes
                    log.info(pop)
                    spikedata = pop.get_data('spikes')
                    filename = '{}.spikes'.format(pop.label)
                    thefile = open(filename, 'w')
                    for spiketrain in spikedata.segments[0].spiketrains:
                        source_id = spiketrain.annotations['source_id']
                        source_index = spiketrain.annotations['source_index']
                        #     #log.info(pp.pprint(vars(spiketrain)))
                        for t in spiketrain:
                            thefile.write('%s\t%f\n' %
                                          (source_index, t.magnitude / 1000.))
                    thefile.close()

        # End
        sim.end()
示例#11
0
from sim_params import simulator_params, system_params
sys.path.append(system_params['backend_path'])
sys.path.append(system_params['pyNN_path'])
from network_params import *
# import logging # TODO! Remove if it runs without this line
import pyNN
import time
from neo.io import PyNNTextIO
import plotting


# prepare simulation
# logging.basicConfig() # TODO! Remove if it runs without this line
#exec('import pyNN.%s as sim' % simulator)
import pynn_genn as sim
sim.setup(**simulator_params[simulator])
import network

# create network
start_netw = time.time()
n = network.Network(sim)
n.setup(sim)
end_netw = time.time()
if sim.rank() == 0 :
    print('Creating the network took %g s' % (end_netw - start_netw,))

# simulate
if sim.rank() == 0 :
    print("Simulating...")
start_sim = time.time()
t = sim.run(simulator_params[simulator]['sim_duration'])
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 matplotlib.pyplot as plt
import pynn_genn as sim

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

sim.setup()

# === Create four cells and inject current into each one =====================

cells = sim.Population(
    4, sim.IF_curr_exp(v_thresh=-55.0, tau_refrac=5.0, tau_m=10.0))

current_sources = [
    sim.DCSource(amplitude=0.5, start=50.0, stop=400.0),
    sim.StepCurrentSource(times=[50.0, 210.0, 250.0, 410.0],
                          amplitudes=[0.4, 0.6, -0.2, 0.2]),
    sim.ACSource(start=50.0,
                 stop=450.0,
                 amplitude=0.2,
                 offset=0.1,
                 frequency=10.0,