def csa_example():

    cs = csa.cset(csa.random(0.1), 10000.0, 1.0)

    pop1 = nest.LayoutNetwork("iaf_neuron", [16])
    pop2 = nest.LayoutNetwork("iaf_neuron", [16])

    nest.PrintNetwork(10)

    nest.CGConnect(pop1, pop2, cs, {"weight": 0, "delay": 1})

    pg = nest.Create("poisson_generator", params={"rate": 80000.0})
    nest.DivergentConnect(pg, nest.GetLeaves(pop1)[0], 1.2, 1.0)

    vm_params = {
        "record_to": ["memory"],
        "withgid": True,
        "withtime": True,
        "interval": 0.1
    }
    vm = nest.Create("voltmeter", params=vm_params)
    nest.DivergentConnect(vm, nest.GetLeaves(pop2)[0])

    nest.Simulate(50.0)

    from nest import visualization
    allnodes = pg + nest.GetLeaves(pop1)[0] + nest.GetLeaves(pop2)[0] + vm
    visualization.plot_network(allnodes, "test_csa.png")

    if havePIL:
        im = Image.open("test_csa.png")
        im.show()

    from nest import voltage_trace
    voltage_trace.from_device(vm)
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
    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
Beispiel #4
0
 def _divergentConnectEE(self, pre, post, weights):
     post_global = list(self.E_pop[0] + np.asanyarray(post))
     nest.DivergentConnect([self.E_pop[0] + pre],
                           post_global,
                           model='I_AMPA_NMDA',
                           weight=list(weights),
                           delay=[self.no.delay] * len(weights))
Beispiel #5
0
 def _divergentConnectIE(self, pre, post, weights):
     post_global = list(self.E_pop[0] + np.array(post))
     nest.DivergentConnect([self.I_pop[0] + pre],
                           post_global,
                           model='E_GABA_A',
                           weight=list(weights),
                           delay=[self.no.delay] * len(weights))
Beispiel #6
0
 def inject_into(self, cell_list):
     """Inject this current source into some cells."""
     for id in cell_list:
         if id.local and 'v' not in id.cellclass.recordable:
             raise TypeError("Can't inject current into a spike source.")
     if isinstance(cell_list, Population):
         cell_list = [cell for cell in cell_list]
     nest.DivergentConnect(self._device, cell_list)
    def test_DivergentConnect(self):
        """DivergentConnect pre to post"""

        nest.ResetKernel()
        pre = nest.Create("iaf_neuron", 1)
        post = nest.Create("iaf_neuron", 3)
        nest.DivergentConnect(pre, post)
        connections = nest.FindConnections(pre)
        targets = nest.GetStatus(connections, "target")
        self.assertEqual(targets, post)
Beispiel #8
0
 def inject_into(self, cell_list):
     """Inject this current source into some cells."""
     for id in cell_list:
         if id.local and not id.celltype.injectable:
             raise TypeError("Can't inject current into a spike source.")
     if isinstance(cell_list, (Population, PopulationView, Assembly)):
         self.cell_list = [cell for cell in cell_list]
     else:
         self.cell_list = cell_list
     nest.DivergentConnect(self._device, self.cell_list)
Beispiel #9
0
 def inject_into(self, cells):
     __doc__ = StandardCurrentSource.inject_into.__doc__
     for id in cells:
         if id.local and not id.celltype.injectable:
             raise TypeError("Can't inject current into a spike source.")
     if isinstance(cells, (Population, PopulationView, Assembly)):
         self.cell_list = [cell for cell in cells]
     else:
         self.cell_list = cells
     nest.DivergentConnect(self._device, self.cell_list)
Beispiel #10
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
Beispiel #11
0
def csa_example():

    cs = csa.cset(csa.random(0.1), 10000.0, 1.0)

    # This does not work yet, as the implementation does not yet
    # support nested subnets.
    #
    #pop1 = nest.LayoutNetwork("iaf_neuron", [4,4])
    #pop2 = nest.LayoutNetwork("iaf_neuron", [4,4])

    pop1 = nest.LayoutNetwork("iaf_neuron", [16])
    pop2 = nest.LayoutNetwork("iaf_neuron", [16])

    nest.PrintNetwork(10)

    nest.CGConnect(pop1, pop2, cs, {"weight": 0, "delay": 1})

    pg = nest.Create("poisson_generator", params={"rate": 80000.0})
    nest.DivergentConnect(pg, nest.GetLeaves(pop1)[0], 1.2, 1.0)

    vm = nest.Create("voltmeter",
                     params={
                         "record_to": ["memory"],
                         "withgid": True,
                         "withtime": True,
                         "interval": 0.1
                     })
    nest.DivergentConnect(vm, nest.GetLeaves(pop2)[0])

    nest.Simulate(50.0)

    # Not yet supported in NEST
    #from nest import visualization
    #allnodes = [pg, nest.GetLeaves(pop1)[0], nest.GetLeaves(pop2)[0], vm]
    #visualization.plot_network(allnodes, "test_csa.png", "png", plot_modelnames=True

    #if havePIL:
    #    im = Image.open("test_csa.png")
    #    im.show()

    from nest import voltage_trace
    voltage_trace.from_device(vm)
Beispiel #12
0
    def _divergent_connect(self, source, targets, weights, delays):
        """
        Connect a neuron to one or more other neurons.
        
        `source`  -- the ID of the pre-synaptic cell.
        `targets` -- a list/1D array of post-synaptic cell IDs, or a single ID.
        `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(source):
            assert len(source) == 1
            source = source[0]
        if not core.is_listlike(targets):
            targets = [targets]
        assert len(targets) > 0

        if self.synapse_type not in targets[0].celltype.synapse_types:
            raise errors.ConnectionError(
                "User gave synapse_type=%s, synapse_type must be one of: %s" %
                (self.synapse_type,
                 "'" + "', '".join(st
                                   for st in targets[0].celltype.synapse_types
                                   or ['*No connections supported*'])) + "'")
        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(
                targets[0]):
            weights *= -1  # 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]

        if targets[0].celltype.standard_receptor_type:
            try:
                nest.DivergentConnect([source], targets, weights, delays,
                                      self.synapse_model)
            except nest.NESTError, e:
                raise errors.ConnectionError(
                    "%s. source=%s, targets=%s, weights=%s, delays=%s, synapse model='%s'"
                    %
                    (e, source, targets, weights, delays, self.synapse_model))
    def test_DivergentConnectWD(self):
        """DivergentConnect pre to post with weight and delay"""

        nest.ResetKernel()
        pre = nest.Create("iaf_neuron", 1)
        post = nest.Create("iaf_neuron", 3)
        nest.DivergentConnect(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))
Beispiel #14
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 test_FindConnections(self):
        """FindConnections"""

        nest.ResetKernel()
        
        a=nest.Create("iaf_neuron", 3)
        nest.DivergentConnect(a,a)
        c1=nest.FindConnections(a)
        c2=nest.FindConnections(a, synapse_model="static_synapse")
        self.assertEqual(c1, c2)
        
        d1=[{"weight": w} for w in [2.0, 3.0, 4.0]]

        c3=nest.FindConnections(a, a)
        nest.SetStatus(c3, d1)
        s1=nest.GetStatus(c3, "weight")
        self.assertEqual(s1, [w["weight"] for w in d1])
Beispiel #16
0
    def test_ThreadsFindConnections(self):
        """FindConnections with threads"""

        if not self.nest_multithreaded(): return

        nest.ResetKernel()
        nest.SetKernelStatus({'local_num_threads': 8})
        pre = nest.Create("iaf_neuron")
        post = nest.Create("iaf_neuron", 6)

        nest.DivergentConnect(pre, post)

        conn = nest.FindConnections(pre)
        # Because of threading, targets may be in a different order than
        # in post, so we sort the vector.
        targets = nest.GetStatus(conn, "target")
        targets.sort()

        self.assertEqual(targets, post)
Beispiel #17
0
    def test_GetConnections(self):
        """GetConnections"""

        nest.ResetKernel()

        a = nest.Create("iaf_neuron", 3)
        nest.DivergentConnect(a, a)
        c1 = nest.GetConnections(a)
        c2 = nest.GetConnections(a, synapse_model="static_synapse")
        self.assertEqual(c1, c2)

        weights = (2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0)
        d1 = tuple({"weight": w} for w in weights)

        c3 = nest.GetConnections(a, a)
        nest.SetStatus(c3, d1)
        s1 = nest.GetStatus(c3, "weight")
        self.assertEqual(s1, weights)

        c4 = nest.GetConnections()
        self.assertEqual(c1, c4)
Beispiel #18
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]
Beispiel #19
0
    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)
nest.SetStatus(zmn_nodes_L23i, {"stop": 5000.0})

syn_dict_e = {
    'model': 'zmn_synapse',
    'weight': +ST['zmn_weight'],
    'delay': ST['zmn_delay']
}
syn_dict_i = {
    'model': 'zmn_synapse',
    'weight': -ST['zmn_weight'],
    'delay': ST['zmn_delay']
}
val = 0.12
nest.DivergentConnect(zmn_nodes_L23e,
                      PYR_MC0,
                      model=syn_dict_e['model'],
                      weight=syn_dict_e['weight'],
                      delay=syn_dict_e['delay'])  #adjusted for nest 2.2.2
nest.DivergentConnect(zmn_nodes_L23i,
                      PYR_MC0,
                      model=syn_dict_i['model'],
                      weight=syn_dict_i['weight'],
                      delay=syn_dict_i['delay'])  #adjusted for nest 2.2.2

nest.DivergentConnect(zmn_nodes_L23e,
                      DBC_MC0,
                      model=syn_dict_e['model'],
                      weight=val,
                      delay=syn_dict_e['delay'])  #adjusted for nest 2.2.2
nest.DivergentConnect(zmn_nodes_L23i,
                      DBC_MC0,
Beispiel #21
0
            'radius': 0.5
        }
    },
    "synapse_model": "static_synapse",
    'kernel': {
        'gaussian': {
            'p_center': 1.0,
            'sigma': 0.15
        }
    }
}

tp.ConnectLayers(lexc, lexc, conndict)
tp.ConnectLayers(linh, lexc, conndict)

nest.DivergentConnect(mm, nest.GetLeaves(lexc)[0])
nest.DivergentConnect(exc, nest.GetLeaves(lexc)[0])
nest.DivergentConnect(inh, nest.GetLeaves(linh)[0])

d = nest.GetStatus(mm)[0]['events']['V_m']
nest.Simulate(100)

events = nest.GetStatus(mm)[0]['events']
t = events['times']
print d, t, events
pl.clf()

pl.subplot(211)
pl.plot(t, events['V_m'])
#pl.axis([0, 100, -75, -53])
pl.ylabel('Membrane potential [mV]')
Beispiel #22
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')
Beispiel #23
0
                             'start': 0.,
                             'stop': 2000.
                         })
    sd = nest.Create('spike_detector',
                     params={
                         'to_file': True,
                         'label': file_name_sd
                     })
    vm = nest.Create('voltmeter', params={'interval': 0.01})
    nest.SetStatus(vm, [{
        "withtime": True,
        'to_file': True,
        'label': file_name_mem
    }])

    nest.DivergentConnect(dc_gen, neuron, weight=1.0, delay=1.0)
    nest.Connect(vm, neuron)
    nest.Connect(neuron, sd)
    nest.Simulate(T)
    spikes = nest.GetStatus(sd, 'events')[0]
    potential = nest.GetStatus(vm, 'events')[0]
    ax1 = fig.add_axes([0.1, 0.8 - (i * 0.125), 0.33, 0.1])
    #ax1 = fig.add_axes([0.6,0.66 - (i*0.22),0.37,0.2])
    ax1.plot(potential['times'], potential['V_m'], col_lis[i], linewidth=2)
    ax1.plot(spikes['times'], spikes['senders'] - 50., "ko", markersize=3)
    yr = np.arange(-80., -40., 10.)
    ax1.set_yticks(yr[::3])
    for tl in ax1.get_yticklabels():
        tl.set_fontsize(ticksize)
    #if i == 0:
    #ax1.title('Regular Spiking', fontsize = 50)
Beispiel #24
0
def DivergentConnect(pre, post, *args, **kwargs):
    if hasattr(nest, 'DivergentConnect'):
        nest.DivergentConnect(pre, post, *args, **kwargs)
    else:
        nest.Connect(pre, post, *args, **kwargs)
nest.ResetKernel()
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
    "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."

# 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"
Beispiel #27
0
    def createGenericPlaceCells(self,
                                N,
                                maxRate,
                                weight,
                                start=None,
                                end=None,
                                posIn=None):
        '''
        Generate place cells and connect them to grid 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.
        '''
        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)

        if N != 0:
            gcnLogger.info('Setting up generic place cells')
            NTotal = N * N

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

            PC = nest.Create('place_cell_generator',
                             NTotal,
                             params={
                                 'rate': maxRate,
                                 'field_size': self.no.pc_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
                })

            # test_x = nest.GetStatus([PC[0]], 'rat_pos_x')
            # test_y = nest.GetStatus([PC[0]], 'rat_pos_y')
            # print test_x, test_y

            # Connections
            # Here we extract connections from the PlaceCellInput class that
            # was originaly used as a current input generator for place cell
            # resetting mechanism. The output of this class perfectly matches
            # how divergent connections from a single place cell should be
            # mapped onto the twisted torus grid cell sheet

            # how divergent the connections are, 3sigma rule --> division by 6.
            connStdDev = self.no.gridSep / 2. / 6.
            pc_weight_threshold = 0.1

            pc_input = PlaceCellInput(self.Ne_x,
                                      self.Ne_y,
                                      self.no.arenaSize,
                                      self.no.gridSep, [.0, .0],
                                      fieldSigma=connStdDev)
            ctr_x = nest.GetStatus(PC, 'ctr_x')
            ctr_y = nest.GetStatus(PC, 'ctr_y')
            for pc_id in xrange(NTotal):
                w = pc_input.getSheetInput(ctr_x[pc_id],
                                           ctr_y[pc_id]).flatten()
                gt_th = w > pc_weight_threshold
                post = np.array(self.E_pop)[gt_th]
                w = w[gt_th]
                # print post, w
                nest.DivergentConnect([PC[pc_id]],
                                      list(post),
                                      weight=list(w * weight),
                                      delay=[self.no.delay] * len(w),
                                      model='PC_AMPA')

            return PC, PCHelper, NTotal

        else:
            gcnLogger.warn("trying to set up place cells with N_place_cells "
                           "== 0")

        self._placeCellsLoaded = True
Beispiel #28
0
    np.array([204., 187., 20.]) / 255.
]
amp_arr = np.arange(65000., 80000., 2000.)
sup_fr_lis = []
fig = pl.figure(1, (8, 5))
ax1 = fig.add_axes([0.55, 0.135, 0.37, 0.79])
for kk, jj in enumerate(np.arange(5.)):
    fr_lis = []
    for ii in amp_arr:
        nest.ResetKernel()
        dc_gen = nest.Create("poisson_generator", params={'rate': ii})
        aa = nest.Create("psdb", params={'spb': jj + 1})
        #aa = nest.Create('iaf_neuron')
        sd = nest.Create('spike_detector')
        nest.Connect(aa, sd)
        nest.DivergentConnect(dc_gen, aa, weight=1., delay=1.)
        nest.Simulate(tsim)
        spikes = nest.GetStatus(sd, 'events')[0]
        num_spikes = len(spikes['senders'])
        f_rate = (num_spikes * 1000) / tsim
        fr_lis.append(f_rate)
    ax1.plot(amp_arr,
             fr_lis,
             lw=5.,
             alpha=0.7,
             color=col_lis[kk],
             label=str(jj + 1))

pl.legend(loc='best', prop={'size': 10.})
#pl.xlim(300,500)
ax1.set_ylim(0, 40)
Beispiel #29
0
#! This recording device setup is a bit makeshift. For each population
#! we want to record from, we create one ``multimeter``, then select
#! all nodes of the right model from the target population and
#! connect. ``loc`` is the subplot location for the layer.
print "Connecting: Recording devices"
recorders = {}
for name, loc, population, model in [('TpRelay', 1, Tp, 'TpRelay'),
                                     ('Rp', 2, Rp, 'RpNeuron'),
                                     ('Vp_v L4pyr', 3, Vp_v, 'L4pyr'),
                                     ('Vp_h L4pyr', 4, Vp_h, 'L4pyr')]:
    recorders[name] = (nest.Create('RecordingNode'), loc)
    tgts = [
        nd for nd in nest.GetLeaves(population)[0]
        if nest.GetStatus([nd], 'model')[0] == model
    ]
    nest.DivergentConnect(recorders[name][0], tgts)

#! Example simulation
#! ====================

#! This simulation is set up to create a step-wise visualization of
#! the membrane potential. To do so, we simulate ``sim_interval``
#! milliseconds at a time, then read out data from the multimeters,
#! clear data from the multimeters and plot the data as pseudocolor
#! plots.

#! show time during simulation
nest.SetStatus([0], {'print_time': True})

#! lower and upper limits for color scale, for each of the four
#! populations recorded.
    'tau_m': 20.,
    'V_th': 20.,
    'E_L': 10.,
    't_ref': 2.,
    'V_reset': 0.,
    'C_m': 200.,
    'V_m': 0.
}

neurons = nest.Create('iaf_psc_alpha', N)
sd = nest.Create('spike_detector')
noise = nest.Create('noise_generator')
drive = nest.Create('ac_generator')

nest.SetStatus(drive, [driveparams])
nest.SetStatus(noise, [noiseparams])
nest.SetStatus(sd, [sdparams])
nest.SetStatus(neurons, [neuronparams])
nest.SetStatus(neurons, map(bias, neurons))

nest.DivergentConnect(drive, neurons)
nest.DivergentConnect(noise, neurons)
nest.ConvergentConnect(neurons, sd)

nest.Simulate(T)

print "nest model processing complete with %s neurons" % N

nest.raster_plot.from_device(sd)
nest.raster_plot.show()