def connect(self):
        """
        Connect all nodes in the model.
        """
        if self.connected: return
        if not self.built:
            self.build()

        nest.CopyModel("static_synapse_hom_wd", "excitatory", {
            "weight": self.J_E,
            "delay": self.delay
        })
        nest.CopyModel("static_synapse_hom_wd", "inhibitory", {
            "weight": self.J_I,
            "delay": self.delay
        })
        nest.RandomConvergentConnect(self.nodes_E,
                                     self.nodes,
                                     self.C_E,
                                     model="excitatory")
        nest.RandomConvergentConnect(self.nodes_I,
                                     self.nodes,
                                     self.C_I,
                                     model="inhibitory")
        nest.DivergentConnect(self.noise, self.nodes, model="excitatory")
        nest.ConvergentConnect(self.nodes_E[:self.N_rec], self.spikes_E)
        nest.ConvergentConnect(self.nodes_I[:self.N_rec], self.spikes_I)
        self.connected = True
Exemple #2
0
class SpikeDetector(RecordingDevice):
    """A wrapper around the NEST spike_detector device"""
    _nest_connect = lambda device, ids: nest.ConvergentConnect()

    def __init__(self, to_memory=True):
        self.device = nest.Create('spike_detector')
        device_parameters = {
            "precise_times": True,
            "precision": simulator.state.default_recording_precision
        }
        super(SpikeDetector, self).__init__(device_parameters, to_memory)

    def connect_to_cells(self):
        assert not self._connected
        nest.Connect(list(self._all_ids), list(self.device),
                     {'rule': 'all_to_all'}, {'model': 'static_synapse'})
        self._connected = True

    def get_spiketimes(self, desired_ids):
        """
        Return spike times as a dictionary containing one numpy array for
        each neuron, ids as keys.

        Equivalent to `get_data('times', desired_ids)`
        """
        return self.get_data('times', desired_ids)

    def get_spike_counts(self, desired_ids):
        events = nest.GetStatus(self.device, 'events')[0]
        N = {}
        for id in desired_ids:
            mask = events['senders'] == int(id)
            N[int(id)] = len(events['times'][mask])
        return N
Exemple #3
0
    def _convergent_connect(self, presynaptic_indices, postsynaptic_index,
                            **connection_parameters):
        """
        Connect a neuron to one or more other neurons with a static connection.

        `sources`  -- a 1D array of pre-synaptic cell IDs
        `target`   -- the ID of the post-synaptic cell.

        TO UPDATE
        """
        #logger.debug("Connecting to index %s from %s with %s" % (postsynaptic_index, presynaptic_indices, connection_parameters))
        presynaptic_cells = self.pre[presynaptic_indices].all_cells
        postsynaptic_cell = self.post[postsynaptic_index]
        assert len(presynaptic_cells) > 0, presynaptic_cells
        weights = connection_parameters.pop('weight')
        if self.receptor_type == 'inhibitory' and self.post.conductance_based:
            weights *= -1  # NEST wants negative values for inhibitory weights, even if these are conductances
        delays = connection_parameters.pop('delay')
        if postsynaptic_cell.celltype.standard_receptor_type:
            try:
                nest.ConvergentConnect(
                    presynaptic_cells.astype(int).tolist(),
                    [int(postsynaptic_cell)], listify(weights),
                    listify(delays), self.nest_synapse_model)
            except nest.NESTError, e:
                raise errors.ConnectionError(
                    "%s. presynaptic_cells=%s, postsynaptic_cell=%s, weights=%s, delays=%s, synapse model='%s'"
                    % (e, presynaptic_cells, postsynaptic_cell, weights,
                       delays, self.nest_synapse_model))
def create_network(network_obj, weight, JENoise, noise_rate, resolution=0.1,
                   verbose=True, print_time=False):

    ncells = network_obj['ncells']
    ncons = network_obj['ncons']

    if verbose:
        print "Constructing NEST network of %i nodes and %i connections." % (
            ncells, ncons)

    nest.ResetKernel()

    nthreads = cpu_count()

    if verbose:
        nest.set_verbosity('M_INFO')
    else:
        nest.set_verbosity('M_ERROR')

    nest.SetKernelStatus(dict(local_num_threads=nthreads, resolution=0.1,
                              print_time=print_time, overwrite_files=True))

    neuron_params = dict(C_m=1.0, tau_m=20.0, t_ref=2.0, E_L=0.0, V_th=20.0)
    nest.SetDefaults("iaf_neuron", neuron_params)
    neuronsE = nest.Create("iaf_neuron", n=ncells)

    # save GID offset of first neuron - this has the advantage that the output
    # later will be independent of the point at which the neurons were created
    GIDoffset = neuronsE[0]

    espikes = nest.Create("spike_detector")
    nest.ConvergentConnect(neuronsE, espikes)

    noise = nest.Create("poisson_generator", n=1, params=dict(rate=noise_rate))

    # Warning: delay is overwritten later if weights are given!
    nest.SetDefaults("tsodyks_synapse",
                     dict(delay=1.5, tau_rec=500., tau_fac=0., U=0.3))
    nest.CopyModel("tsodyks_synapse", "exc", dict(weight=weight))
    nest.CopyModel("static_synapse", "poisson", dict(weight=JENoise))

    # every neuron gets the same noisy input???
    nest.DivergentConnect(noise, neuronsE, model="poisson")

    for node in network_obj['nodes']:

        presyn_index = node['id']
        postsyn_indices = node['connectedTo']

        nest.DivergentConnect(
            [neuronsE[presyn_index]],                   # from, list of len 1
            [neuronsE[ii] for ii in postsyn_indices],   # to, list
            model='exc',                                # synapse model
        )

    return ncells, ncons, neuronsE, espikes, noise, GIDoffset
Exemple #5
0
 def connect_to_cells(self):
     if not self._connected:
         ids = list(self._all_ids)
         if self.type is "spike_detector":
             nest.ConvergentConnect(ids,
                                    self.device,
                                    model='static_synapse')
         else:
             nest.DivergentConnect(self.device, ids, model='static_synapse')
         self._connected = True
    def test_ConvergentConnect(self):
        """ConvergentConnect pre to post"""

        nest.ResetKernel()
        pre = nest.Create("iaf_neuron", 3)
        post = nest.Create("iaf_neuron", 1)
        nest.ConvergentConnect(pre, post)
        expected_targets = tuple(post[0] for _ in range(len(pre)))
        connections = nest.FindConnections(pre)
        targets = nest.GetStatus(connections, "target")
        self.assertEqual(expected_targets, targets)
Exemple #7
0
 def getSpikeDetector(self, type, N_ids=None):
     '''
     Get a spike detector that records from neurons given N_ids and from the
     population type given by type
     '''
     if type == "E":
         if self.spikeMon_e is not None:
             return self.spikeMon_e
         else:
             if N_ids is None:
                 N_ids = np.arange(len(self.E_pop))
             src = list(np.array(self.E_pop)[N_ids])
             self.spikeMon_e = nest.Create('spike_detector')
             nest.SetStatus(self.spikeMon_e, {
                 "label": "E spikes",
                 'withtime': True,
                 'withgid': True
             })
             nest.ConvergentConnect(src, self.spikeMon_e)
             return self.spikeMon_e
     elif type == "I":
         if self.spikeMon_i is not None:
             return self.spikeMon_i
         else:
             if N_ids is None:
                 N_ids = np.arange(len(self.I_pop))
             src = list(np.array(self.I_pop)[N_ids])
             self.spikeMon_i = nest.Create('spike_detector')
             nest.SetStatus(self.spikeMon_i, {
                 "label": "I spikes",
                 'withtime': True,
                 'withgid': True
             })
             # print src
             nest.ConvergentConnect(src, self.spikeMon_i)
             return self.spikeMon_i
     else:
         raise ValueError("Unsupported type of spike detector: " + type)
    def test_ConvergentConnectWD(self):
        """ConvergentConnect pre to post with weight and delay"""

        nest.ResetKernel()
        pre = nest.Create("iaf_neuron", 3)
        post = nest.Create("iaf_neuron", 1)
        nest.ConvergentConnect(pre,
                               post,
                               weight=(2.0, 2.0, 2.0),
                               delay=(1.0, 2.0, 3.0))
        connections = nest.FindConnections(pre)
        weights = nest.GetStatus(connections, "weight")
        delays = nest.GetStatus(connections, "delay")
        self.assertEqual(weights, (2.0, 2.0, 2.0))
        self.assertEqual(delays, (1.0, 2.0, 3.0))
Exemple #9
0
 def _record(self, new_ids):
     """Called by record()."""
     if self._device is None:
         self._create_device()
     device_name = nest.GetStatus(self._device, "model")[0]
     if device_name == "spike_detector":
         nest.ConvergentConnect(new_ids,
                                self._device,
                                model='static_synapse')
     elif device_name in ('voltmeter', 'conductancemeter'):
         nest.DivergentConnect(self._device,
                               new_ids,
                               model='static_synapse')
     else:
         raise Exception("%s is not a valid recording device" % device_name)
def step(t, n, initial, after, seed=1, dt=0.05):
    """Simulates for n generators for t ms. Step at t/2."""

    nest.ResetKernel()
    nest.SetStatus([0], [{"resolution": dt}])
    nest.SetStatus([0], [{"grng_seed": 256 * seed + 1}])
    nest.SetStatus([0], [{"rng_seeds": [256 * seed + 2]}])

    g = nest.Create('sinusoidal_gamma_generator', n, params=initial)
    sd = nest.Create('spike_detector')
    nest.ConvergentConnect(g, sd)
    nest.Simulate(t / 2)
    nest.SetStatus(g, after)
    nest.Simulate(t / 2)

    return nest.GetStatus(sd, 'events')[0]
Exemple #11
0
    def _convergent_connect(self, sources, target, weights, delays):
        """
        Connect one or more neurons to a single post-synaptic neuron.
        `sources` -- a list/1D array of pre-synaptic cell IDs, or a single ID.
        `target`  -- the ID of the post-synaptic cell.
        `weight`  -- a list/1D array of connection weights, or a single weight.
                     Must have the same length as `targets`.
        `delays`  -- a list/1D array of connection delays, or a single delay.
                     Must have the same length as `targets`.
        """
        # are we sure the targets are all on the current node?
        if core.is_listlike(target):
            assert len(target) == 1
            target = target[0]
        if not core.is_listlike(sources):
            sources = [sources]
        assert len(sources) > 0, sources
        if self.synapse_type not in ('excitatory', 'inhibitory', None):
            raise errors.ConnectionError(
                "synapse_type must be 'excitatory', 'inhibitory', or None (equivalent to 'excitatory')"
            )
        weights = numpy.array(
            weights
        ) * 1000.0  # weights should be in nA or uS, but iaf_neuron uses pA and iaf_cond_neuron uses nS.
        # Using convention in this way is not ideal. We should
        # be able to look up the units used by each model somewhere.
        if self.synapse_type == 'inhibitory' and common.is_conductance(target):
            weights = -1 * weights  # NEST wants negative values for inhibitory weights, even if these are conductances
        if isinstance(weights, numpy.ndarray):
            weights = weights.tolist()
        elif isinstance(weights, float):
            weights = [weights]
        if isinstance(delays, numpy.ndarray):
            delays = delays.tolist()
        elif isinstance(delays, float):
            delays = [delays]

        try:
            nest.ConvergentConnect(sources, [target], weights, delays,
                                   self.synapse_model)
        except nest.NESTError, e:
            raise errors.ConnectionError(
                "%s. sources=%s, target=%s, weights=%s, delays=%s, synapse model='%s'"
                % (e, sources, target, weights, delays, self.synapse_model))
Exemple #12
0
def step(t, n, initial, after, seed=1, dt=0.05):
    """Simulates for n generators for t ms. Step at T/2."""

    ## prepare/reset nest
    nest.ResetKernel()
    ## initialize simulation
    #np.random.seed(256 * seed)
    nest.SetStatus([0], [{"resolution": dt}])
    nest.SetStatus([0], [{"grng_seed": 256 * seed + 1}])
    nest.SetStatus([0], [{"rng_seeds": [256 * seed + 2]}])

    model = 'ac_gamma_generator'

    g = nest.Create(model, n, params=initial)
    sd = nest.Create('spike_detector')
    nest.ConvergentConnect(g, sd)
    nest.Simulate(t / 2)
    nest.SetStatus(g, after)
    nest.Simulate(t / 2)

    return nest.GetStatus(sd, 'events')[0]
Exemple #13
0
    def test_ThreadsGetEvents(self):
        """ Gathering events across threads """

        if not self.nest_multithreaded():
            self.skipTest("NEST was compiled without multi-threading")

        threads = (1, 2, 4, 8)

        n_events_sd = []
        n_events_vm = []

        N = 128
        Simtime = 1000.

        for t in threads:

            nest.ResetKernel()
            nest.SetKernelStatus({'local_num_threads': t})

            n = nest.Create('iaf_psc_alpha', N,
                            {'I_e': 2000.})  # force a lot of spike events
            sd = nest.Create('spike_detector')
            vm = nest.Create('voltmeter')

            nest.ConvergentConnect(n, sd)
            nest.DivergentConnect(vm, n)

            nest.Simulate(Simtime)

            n_events_sd.append(nest.GetStatus(sd, 'n_events')[0])
            n_events_vm.append(nest.GetStatus(vm, 'n_events')[0])

        ref_vm = N * (Simtime - 1)
        ref_sd = n_events_sd[0]

        # could be done more elegantly with any(), ravel(),
        # but we dont want to be dependent on numpy et al
        [self.assertEqual(x, ref_vm) for x in n_events_vm]
        [self.assertEqual(x, ref_sd) for x in n_events_sd]
Exemple #14
0
    def getGenericSpikeDetector(self, gids, label):
        '''
        NEST specific function to get a spike detector that monitors a
        population of neurons with global id set to gids.

        Parameters
        ----------
        gids : list
            A list of global ids of the neurons to monitor.  There is one
            profound limitation of this method: the gids must be a list of
            increasing integers without gaps. Otherwise the local translation
            of neuron numbers when saving the data will not work!.
        '''
        mon = nest.Create('spike_detector')
        nest.SetStatus(mon, {
            "label": label,
            'withtime': True,
            'withgid': True
        })
        nest.ConvergentConnect(gids, mon)

        self._extraSpikeMons[label] = (mon, gids[0])
        return mon
Exemple #15
0
# nest.SetStatus(voltmeter, {'to_file': True, 'interval': 0.1 })

# nest.Connect(voltmeter,hh_neuron)

# nest.Simulate(100)

# nest.voltage_trace.from_device(voltmeter)
# nest.voltage_trace.show()

## Current vs FR Curve

# Env Setup
nest.ResetKernel()
nest.SetDefaults('hh_cond_exp_traub', hh_defaults)
nest.SetKernelStatus({'resolution': 0.01})
nest.SetKernelStatus({'overwrite_files': True})

hh_neurons = nest.Create('hh_cond_exp_traub', n=20)

for k in range(20):
    nest.SetStatus([hh_neurons[k]], {'I_e': k * 200.})

sd = nest.Create('spike_detector')
nest.SetStatus(sd, {'to_file': True})
nest.ConvergentConnect(hh_neurons, sd)

nest.Simulate(1000)

figure()
nest.raster_plot.from_device(sd, hist=True)
                      PYR_MC3,
                      model=syn_dict_ex1['model'],
                      weight=syn_dict_ex1['weight'],
                      delay=syn_dict_ex1['delay'])  #adjusted for nest 2.2.2

# create multimeters
#HYPERCOLUMN0
#DBC0
multimeter_DBC0 = nest.Create("multimeter")
interv = 0.001
nest.SetStatus(multimeter_DBC0, {
    "withtime": True,
    "interval": interv,
    "record_from": ["V_m"]
})
nest.ConvergentConnect(multimeter_DBC0, DBC_MC0)

#PYR0
multimeter_PYR0 = nest.Create("multimeter")
nest.SetStatus(multimeter_PYR0, {
    "withtime": True,
    "interval": interv,
    "record_from": ["V_m"]
})
nest.ConvergentConnect(multimeter_PYR0, [PYR_MC0[0]])

#BS_HC0
multimeter_BS_HC0 = nest.Create("multimeter")
nest.SetStatus(multimeter_BS_HC0, {
    "withtime": True,
    "interval": interv,
Exemple #17
0
                   "receptor_type": 0
               })

nest.Connect(multimeter, [m[0]])

if nest.version()=='NEST 2.12.0':
    syn_dict = {
        "model": 'excitatory',
    }
    conn_dict = {
        "rule": "one_to_one",
    }

    nest.Connect(n, m, conn_dict, syn_dict)
    nest.Connect(m, spikedetector)
    # print 'Connecting ' + ' my_nest.GetConnections ', len(nest.GetConnections(n)), len(n)

if nest.version()=='NEST 2.2.2':

    nest.Connect(n, m, **{
        "model":"excitatory"
    })

    nest.ConvergentConnect(m, spikedetector)

with util.Stopwatch('Speed test'):
    nest.SetKernelStatus({'print_time':True})
    nest.Simulate(1000)

util.show(multimeter, spikedetector)
Exemple #18
0
 def connect_to_cells(self):
     assert not self._connected
     nest.ConvergentConnect(list(self._all_ids),
                            self.device,
                            model='static_synapse')
     self._connected = True
Exemple #19
0
cell_params = {'C_m': 250.0, 'E_L': -70.0, 'E_ex': 0.0, \
    'E_in': -80.0, 'I_e': 0.0, 'V_m': -70.0, 'V_reset': -80.0, 'V_th': -60.0, \
    'g_L': 16.6667, 't_ref': 2.0, 'tau_syn_ex': 5.0, 'tau_syn_in': 5.0}

nrns = nest.Create('iaf_cond_exp_bias', 2, params=cell_params)
voltmeter = nest.Create('multimeter',
                        params={
                            'record_from': ['V_m'],
                            'interval': 0.1
                        })
nest.SetStatus(voltmeter, [{
    "to_file": True,
    "withtime": True,
    'label': 'delme_volt'
}])
nest.ConvergentConnect(voltmeter, nrns)
exc_spike_recorder = nest.Create('spike_detector',
                                 params={
                                     'to_file': True,
                                     'label': 'delme_spikes'
                                 })
nest.ConvergentConnect(nrns, exc_spike_recorder)

source_0 = nest.Create('spike_generator', 1)
# pre synaptic spikes
spike_times_0 = np.array([50., 100., 300., 350., 400.])
# post synaptic spikes
spike_times_1 = np.array([51., 101., 201., 221., 231., 241., 300., 350., 400.])
nest.SetStatus(source_0, {'spike_times': spike_times_0})

delta_t = 3.
nest.SetKernelStatus({'local_num_threads':
                      4})  # show this work for multiple threads

g = nest.Create('sinusoidal_poisson_generator',
                params={
                    'dc': 100.0,
                    'ac': 50.0,
                    'freq': 10.0,
                    'phi': 0.0,
                    'individual_spike_trains': True
                })
p = nest.Create('parrot_neuron', 20)
s = nest.Create('spike_detector')

nest.DivergentConnect(g, p)
nest.ConvergentConnect(p, s)

nest.Simulate(200)
ev = nest.GetStatus(s)[0]['events']
plt.subplot(222)
plt.plot(ev['times'], ev['senders'] - min(ev['senders']), 'o')
plt.ylim([-0.5, 19.5])
plt.yticks([])
plt.title('Individual spike trains for each target')

# now one spike train for all targets
nest.ResetKernel()
nest.SetKernelStatus({'local_num_threads':
                      4})  # show this work for multiple threads

g = nest.Create('sinusoidal_poisson_generator',
Exemple #21
0
import nest
import nest.voltage_trace
from pylab import *

nest.ResetKernel()
nest.SetKernelStatus({"overwrite_files": True, "resolution": 0.001})

neuron = nest.Create("izhikevich", 1, [{"I_e": 30., "c": -65., "d": 8.}])
print nest.GetStatus(neuron)
#noise = nest.Create("poisson_generator", 2)

voltmeter = nest.Create("voltmeter")
# Spike Detectors
spikes = nest.Create('spike_detector', 1)

nest.ConvergentConnect(neuron, spikes)

# nest.SetStatus(noise,[{"rate": 80000.0}, {"rate": 15000.0}])

nest.SetStatus(voltmeter, [{
    "to_file": True,
    "withtime": True,
    "interval": 0.1
}])

#nest.ConvergentConnect(noise, neuron, [1.2, -1.], [1.0, 1.0])
nest.Connect(voltmeter, neuron)

nest.Simulate(100.0)

nest.voltage_trace.from_device(voltmeter)
print "Connecting devices."

nest.CopyModel("static_synapse", "excitatory", {
    "weight": J_ex,
    "delay": delay
})
nest.CopyModel("static_synapse", "inhibitory", {
    "weight": J_in,
    "delay": delay
})

nest.DivergentConnect(noise, nodes_ex, model="excitatory")
nest.DivergentConnect(noise, nodes_in, model="excitatory")

nest.ConvergentConnect(range(1, N_rec + 1), espikes, model="excitatory")
nest.ConvergentConnect(range(NE + 1, NE + 1 + N_rec),
                       ispikes,
                       model="excitatory")

print "Connecting network."

# We now iterate over all neuron IDs, and connect the neuron to
# the sources from our array. The first loop connects the excitatory neurons
# and the second loop the inhibitory neurons.

print "Excitatory connections"

nest.RandomConvergentConnect(nodes_ex,
                             nodes_ex + nodes_in,
                             CE,
    def __init__(self,
                 models='iaf_neuron',
                 n=1,
                 params={},
                 mm_dt=1.0,
                 sname='',
                 spath='',
                 sd=True,
                 mm=True):
        '''
        Constructor
        
        Arguments:
            models      nest model type, can be a list
            n           number of models to create, can be a list
            params      common parameters for models to be set
            mm_dt       multimeter recording precision
            sname       file basename
            spath       Path to save file at 
            sd          boolean, True if spikes should me recorded
            mm          boolean, True if mulitmeter should record  
        '''

        self.connections = {
        }  # Set after network has been built with FindConnections
        self.ids = []
        self.local_ids = []
        self.mm = []  # Id of multimeter
        self.mm_dt = 0  # Recording interval multimeter
        self.models = []
        self.params = []
        self.receptor_types = {}
        self.recordables = {}
        self.sd = []  # Id of spike detector
        self.sname = ''  # Specific file basename
        self.spath = ''  # Path to save file at
        self.signals = {
        }  # dictionary with signals for current, conductance, voltage or spikes

        # If model is a string put it in a list
        if isinstance(models, str):
            models = [models]

        # If n is a integer put it in a list
        if isinstance(n, int):
            n = [n]

        self.models = models

        # If no sname is provided take first model neuron as save name.
        if sname is '': self.sname = self.models[0]
        else: self.sname = sname

        # If no spath is provided current path plus data_tmp is set to
        # spath.
        if spath is '': self.spath = os.getcwd() + '/output_tmp'
        else: self.spath = spath

        # Create save dir if it do not exist
        try:
            os.system('mkdir ' + self.spath)
        except:
            print self.spath + ' already exists'

        print 'Group save path: ' + self.spath

        # For each model create it with i neurons.
        for model, i in zip(models, n):

            self.ids.extend(nest.Create(model, i, params))

        # Get local ids on this processor. Necessary to have for mpi run.
        for id in self.ids:

            nodetype = nest.GetStatus([id])[0]['model']

            if nodetype != 'proxynode':

                self.local_ids.append(id)

        self.params = nest.GetStatus(self.ids)

        # Pick out recordables and receptor types using first model.
        try:
            self.recordables = nest.GetDefaults(models[0])['recordables']
        except:
            print 'No recordables'
        try:
            self.receptor_types = nest.GetDefaults(models[0])['receptor_types']
        except:
            print 'No receptor types'

        # Add spike detector
        if sd: self.sd = nest.Create("spike_detector")

        nest.SetStatus(self.sd, {"withgid": True})
        nest.ConvergentConnect(self.ids, self.sd)

        # Record with multimeter from first neuron

        if mm:
            self.mm = nest.Create("multimeter")
            self.mm_dt = mm_dt  # Recording interval
            nest.SetStatus(self.mm, {
                'interval': self.mm_dt,
                'record_from': self.recordables
            })

            nest.DivergentConnect(self.mm, self.ids)
# tbins in ms
ig_Params = {}
ig_Params['tbins'] = tbins * 1000.0
ig_Params['a'] = a
ig_Params['b'] = b

nest.ResetKernel()

g = nest.Create('inh_gamma_generator', 1)
nest.SetStatus(g, ig_Params)

#p = nest.Create('poisson_generator',1)
#nest.SetStatus(p,{'rate':6.0})

sd = nest.Create('spike_detector', 1)
nest.ConvergentConnect(trials * g, sd, model='static_synapse_S')
#nest.ConvergentConnect(p,sd,model='static_synapse')

print "Simulating inh_gamma_generator test."
t1 = time.time()
nest.Simulate(tsim * 1000.0)
t2 = time.time()
print "Elapsed: ", t2 - t1, " seconds."

spikes = nest.GetStatus(sd, 'events')[0]['times']

# "nice" the spikes, convert to seconds.
spikes = spikes.astype(float) / 1000.0

# plot PSTH
                   "withtime": True,
                   "withgid": True}])

nest.SetStatus(ispikes,[{"label": "brunel-py-in",
                   "withtime": True,
                   "withgid": True}])

print "Connecting devices."

nest.CopyModel("static_synapse","excitatory",{"weight":J_ex, "delay":delay})
nest.CopyModel("static_synapse","inhibitory",{"weight":J_in, "delay":delay})
 
nest.DivergentConnect(noise,nodes_ex,model="excitatory")
nest.DivergentConnect(noise,nodes_in,model="excitatory")

nest.ConvergentConnect(range(1,N_rec+1),espikes,model="excitatory")
nest.ConvergentConnect(range(NE+1,NE+1+N_rec),ispikes,model="excitatory")

print "Connecting network."

# Here, we create the connections from the excitatory neurons to all other
# neurons. We exploit that the neurons have consecutive IDs, running from
# 1,...,NE           for the excitatory neurons and from
# (NE+1),...,(NE+NI) for the inhibitory neurons.

numpy.random.seed(1234)

sources_ex = numpy.random.random_integers(1,NE,(N_neurons,CE))
sources_in = numpy.random.random_integers(NE+1,N_neurons,(N_neurons,CI))

# We now iterate over all neuron IDs, and connect the neuron to
Exemple #26
0
rate   = 10.0
nu_ext =  5.0

g     = -5.0
w_exc = 70.0
w_inh = g*w_exc

alpha = ???

nest.ResetKernel()

neuron = nest.Create('iaf_psc_alpha',1,{'tau_minus': 20.0})

pg_exc = nest.Create('poisson_generator',1,{'rate': rate})
inputs = nest.Create('parrot_neuron',CE)

pg_inh = nest.Create('poisson_generator',1,{'rate': CI*rate})
pg_ext = nest.Create('poisson_generator',1,{'rate': CE*nu_ext})

nest.SetDefaults('stdp_synapse',{'tau_plus': 20.0,
                                 'mu_plus':  mu,
                                 'mu_minus': mu,
                                 'alpha':    alpha,
                                 'lambda':   0.1,
                                 'Wmax':     2.0*w_exc})

nest.DivergentConnect(pg_exc,inputs,1.0,1.0,'static_synapse')
nest.ConvergentConnect(inputs,neuron,w_exc,1.0,'stdp_synapse')
nest.Connect(pg_inh,neuron,w_inh,1.0,'static_synapse')
nest.Connect(pg_ext,neuron,w_exc,1.0,'static_synapse')
Exemple #27
0
def neuron_noise_task():
    '''
        Task Manifest Version: 1
        Full Name: neuron_noise_task
        Caption: One neuron with noise
        Author: nest-initiative.org
        Description: |
            A minimal model with just one neuron and Poisson noise input.
        Categories:
            - NEST
        Compatible_queues: ['cscs_viz', 'epfl_viz']
        Accepts:

        Returns:
            res: image/png

    '''
    nest.ResetKernel()
    nest.SetKernelStatus({"overwrite_files": True})

    neuron = nest.Create("iaf_neuron")
    noise = nest.Create("poisson_generator", 2)
    voltmeter = nest.Create("voltmeter")

    nest.SetStatus(noise, [{"rate": 80000.0}, {"rate": 15000.0}])

    # get default_location of 'to_file' and turn it into manual location
    nest.SetStatus(voltmeter, [{"to_memory": True, "withtime": True}])
    # nest.SetStatus(voltmeter, [{"filenames": newname}])

    nest.ConvergentConnect(noise, neuron, [1.2, -1.], [1.0, 1.0])
    nest.Connect(voltmeter, neuron)
    nest.Simulate(500.0)

    # print nest.GetStatus(voltmeter, "file_extension")[0]
    # print type(nest.GetStatus(voltmeter, "filenames")[0])
    # print nest.GetStatus(voltmeter, "global_id")[0]
    # print nest.GetStatus(voltmeter, "local_id")[0]
    # print nest.GetStatus(voltmeter, "to_screen")[0]
    # print nest.GetStatus(voltmeter, "to_memory")[0]
    # print nest.GetStatus(voltmeter, "to_file")[0]
    # print nest.sli_pop()

    # TODO: check the existence of exported file & move it to somewhere else

    # print nest.GetStatus(voltmeter)

    # ... Visualization : Show image
    nest.voltage_trace.from_device(voltmeter)
    # print plotids
    # nest.voltage_trace.show()
    # name = __filename__+".png"
    # nest.voltage_trace.show()
    # nest.voltage_trace.savefig('foo.png')

    # TODO: write result as image to file, see voltage_trace.py
    out_file_name = 'neuron_noise_task.png'
    with open(out_file_name, 'w') as report_path:
        pylab.savefig(report_path, dpi=100)

    return neuron_noise_task.task.uri.save_file(mime_type='image/png',
                                                src_path=out_file_name,
                                                dst_path=out_file_name)
Exemple #28
0
def ConvergentConnect(pre, post, *args, **kwargs):
    if hasattr(nest, 'ConvergentConnect'):
        nest.ConvergentConnect(pre, post, *args, **kwargs)
    else:
        nest.Connect(pre, post, *args, **kwargs)
Exemple #29
0
    def _createIPlaceCells(self,
                           N,
                           Nconn_pcs,
                           maxRate,
                           weight,
                           field_std,
                           start=None,
                           end=None,
                           posIn=None):
        '''
        Generate place cells and connect them to I cells. The wiring is
        fixed, and there is no plasticity. This method can be used more than
        once, to set up different populations of place cells.

        Here the widths of the place fields are the same as in the case of the
        generic place cells.

        Parameters
        ----------
        Nconn_pcs : int
            Number of place cells connected to each I neurons.
        '''
        if start is None:
            start = self.no.theta_start_t
        if end is None:
            end = self.no.time
        if posIn is None:
            self._loadRatVelocities()
            posIn = PosInputs(self.rat_pos_x, self.rat_pos_y, self.rat_dt)

        NTotal = N * N
        PC = None
        PCHelper = None

        if N != 0:
            gcnLogger.info('Setting up place cells connected to I cells')
            gcnLogger.info(
                "N: %d, Nconn_pcs: %d, maxRate: %f, weight: %f, field_std: %f",
                N, int(Nconn_pcs), maxRate, weight, field_std)

            boxSize = [self.no.arenaSize, self.no.arenaSize]
            PCHelper = UniformBoxPlaceCells(boxSize, (N, N),
                                            maxRate,
                                            field_std,
                                            random=False)

            PC = nest.Create('place_cell_generator',
                             NTotal,
                             params={
                                 'rate': maxRate,
                                 'field_size': field_std,
                                 'start': start,
                                 'stop': end
                             })
            nest.SetStatus(PC, 'ctr_x', PCHelper.centers[:, 0])
            nest.SetStatus(PC, 'ctr_y', PCHelper.centers[:, 1])

            npos = int(self.no.time / posIn.pos_dt)
            nest.SetStatus(
                [PC[0]],
                params={
                    'rat_pos_x': list(posIn.pos_x[0:npos]),
                    'rat_pos_y': list(posIn.pos_y[0:npos]),
                    'rat_pos_dt': posIn.pos_dt
                })

            # Connections
            # I-PCs are connected with a constant connection weight to I cells
            for i_idx in self.I_pop:
                pc_idx = np.random.choice(PC, Nconn_pcs, replace=False)
                nest.ConvergentConnect(pc_idx.tolist(), [i_idx],
                                       weight=weight,
                                       delay=self.no.delay,
                                       model='PC_AMPA')
        else:
            gcnLogger.warn(
                "Trying to set up I place cells with 0 place cells.")

        self._i_placeCellsLoaded = True
        self.IPC = PC
        self.IPCHelper = PCHelper
        self.NIPC = NTotal
Exemple #30
0
nrns = 10000
sim = 1000

nest.ResetKernel()
n = nest.Create('iaf_hill', nrns)
r = nest.GetStatus(n)[0]['recordables']
m = nest.Create('multimeter')
nest.SetStatus(
    m, {
        'record_from': [r['V_m']],
        'to_file': False,
        'withtime': False,
        'withgid': False
    })
nest.ConvergentConnect(m, n)

mm_start = time.time()
nest.Simulate(sim)
mm_stop = time.time()

nest.ResetKernel()
n = nest.Create('iaf_hill', nrns)
r = nest.GetStatus(n)[0]['recordables']
v = nest.Create('voltmeter')
nest.SetStatus(v, {'to_file': False, 'withtime': False, 'withgid': False})
nest.ConvergentConnect(v, n)

vm_start = time.time()
nest.Simulate(sim)
vm_stop = time.time()