Exemplo n.º 1
0
    def test_CSA_OneToOne_subnet_1d(self):
        """One-to-one connectivity with 1-dim subnets"""

        nest.ResetKernel()

        n = 4  # number of neurons

        pop0 = nest.LayoutNetwork("iaf_neuron", [n])
        pop1 = nest.LayoutNetwork("iaf_neuron", [n])

        cg = csa.cset(csa.oneToOne)

        nest.CGConnect(pop0, pop1, cg)

        sources = nest.GetLeaves(pop0)[0]
        targets = nest.GetLeaves(pop1)[0]
        for i in range(n):
            conns = nest.GetStatus(nest.FindConnections([sources[i]]),
                                   'target')
            self.assertEqual(len(conns), 1)
            self.assertEqual(conns[0], targets[i])

            conns = nest.GetStatus(nest.FindConnections([targets[i]]),
                                   'target')
            self.assertEqual(len(conns), 0)
Exemplo n.º 2
0
    def test_PlotTargets(self):
        """Test plotting targets."""
        ldict = {'elements': ['iaf_neuron', 'iaf_psc_alpha'], 'rows': 3,
                 'columns': 3,
                 'extent': [2., 2.], 'edge_wrap': True}
        cdict = {'connection_type': 'divergent',
                 'mask': {'grid': {'rows': 2, 'columns': 2}}}
        nest.ResetKernel()
        l = topo.CreateLayer(ldict)
        ian = [gid for gid in nest.GetLeaves(l)[0]
               if nest.GetStatus([gid], 'model')[0] == 'iaf_neuron']
        ipa = [gid for gid in nest.GetLeaves(l)[0]
               if nest.GetStatus([gid], 'model')[0] == 'iaf_psc_alpha']

        # connect ian -> all using static_synapse
        cdict.update({'sources': {'model': 'iaf_neuron'},
                      'synapse_model': 'static_synapse'})
        topo.ConnectLayers(l, l, cdict)
        for k in ['sources', 'synapse_model']:
            cdict.pop(k)

        # connect ipa -> ipa using stdp_synapse
        cdict.update({'sources': {'model': 'iaf_psc_alpha'},
                      'targets': {'model': 'iaf_psc_alpha'},
                      'synapse_model': 'stdp_synapse'})
        topo.ConnectLayers(l, l, cdict)
        for k in ['sources', 'targets', 'synapse_model']:
            cdict.pop(k)

        ctr = topo.FindCenterElement(l)
        fig = topo.PlotTargets(ctr, l)
        fig.gca().set_title('Plain call')

        self.assertTrue(True)
Exemplo n.º 3
0
    def test_CSA_OneToOne_params(self):
        """One-to-one connectivity"""

        nest.ResetKernel()

        n = 4  # number of neurons

        pop0 = nest.LayoutNetwork("iaf_neuron", [n])
        pop1 = nest.LayoutNetwork("iaf_neuron", [n])

        cs = csa.cset(csa.oneToOne, 10000.0, 1.0)

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

        sources = nest.GetLeaves(pop0)[0]
        targets = nest.GetLeaves(pop1)[0]
        for i in xrange(n):
            conns = nest.GetStatus(nest.FindConnections([sources[i]]),
                                   'target')
            self.assertEqual(len(conns), 1)
            self.assertEqual(conns[0], targets[i])

            conns = nest.GetStatus(nest.FindConnections([targets[i]]),
                                   'target')
            self.assertEqual(len(conns), 0)
Exemplo n.º 4
0
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)
Exemplo n.º 5
0
    def test_GetTargetNodesPositions(self):
        """Interface check for finding targets."""
        ldict = {'elements': ['iaf_neuron', 'iaf_psc_alpha'], 'rows': 3, 'columns':3,
                 'extent': [2., 2.], 'edge_wrap': True}
        cdict = {'connection_type': 'divergent', 
                 'mask': {'grid': {'rows':2, 'columns':2}}}     
        nest.ResetKernel()
        l = topo.CreateLayer(ldict)
        ian = [gid for gid in nest.GetLeaves(l)[0]
               if nest.GetStatus([gid], 'model')[0] == 'iaf_neuron']
        ipa = [gid for gid in nest.GetLeaves(l)[0]
               if nest.GetStatus([gid], 'model')[0] == 'iaf_psc_alpha']
        
        # connect ian -> all using static_synapse
        cdict.update({'sources': {'model': 'iaf_neuron'},
                      'synapse_model': 'static_synapse'})
        topo.ConnectLayers(l, l, cdict)
        for k in ['sources', 'synapse_model']: cdict.pop(k)
        
        # connect ipa -> ipa using stdp_synapse
        cdict.update({'sources': {'model': 'iaf_psc_alpha'},
                      'targets': {'model': 'iaf_psc_alpha'},
                      'synapse_model': 'stdp_synapse'})
        topo.ConnectLayers(l, l, cdict)
        for k in ['sources', 'targets', 'synapse_model']: cdict.pop(k)
        
        t = topo.GetTargetNodes(ian[:1], l)
        self.assertEqual(len(t), 1)

        p = topo.GetTargetPositions(ian[:1], l)
        self.assertEqual(len(p), 1)
        self.assertTrue(all([len(pp)==2 for pp in p[0]]))
        
        t = topo.GetTargetNodes(ian, l)
        self.assertEqual(len(t), len(ian))
        self.assertTrue(all([len(g)==8 for g in t])) # 2x2 mask x 2 neurons / element -> eight targets  

        p = topo.GetTargetPositions(ian, l)
        self.assertEqual(len(p), len(ian))
        

        t = topo.GetTargetNodes(ian, l, tgt_model='iaf_neuron')
        self.assertEqual(len(t), len(ian))
        self.assertTrue(all([len(g)==4 for g in t])) # 2x2 mask  -> four targets  

        t = topo.GetTargetNodes(ian, l, tgt_model='iaf_psc_alpha')
        self.assertEqual(len(t), len(ian))
        self.assertTrue(all([len(g)==4 for g in t])) # 2x2 mask  -> four targets  

        t = topo.GetTargetNodes(ipa, l)
        self.assertEqual(len(t), len(ipa))
        self.assertTrue(all([len(g)==4 for g in t])) # 2x2 mask  -> four targets  

        t = topo.GetTargetNodes(ipa, l, syn_model='static_synapse')
        self.assertEqual(len(t), len(ipa))
        self.assertTrue(all([len(g)==0 for g in t])) # no static syns  

        t = topo.GetTargetNodes(ipa, l, syn_model='stdp_synapse')
        self.assertEqual(len(t), len(ipa))
        self.assertTrue(all([len(g)==4 for g in t])) # 2x2 mask  -> four targets  
Exemplo n.º 6
0
def lgn_to_v1_connections(l_exc, l_inh, sd_exc, sd_inh, l_poiss,
                          self_orientation):
    tp.ConnectLayers(l_poiss, l_exc, dict_poiss_to_v1)
    tp.ConnectLayers(l_poiss, l_inh, dict_poiss_to_v1)
    leaves_exc = nest.GetLeaves(l_exc, local_only=True)[0]
    nest.Connect(leaves_exc, sd_exc)
    leaves_inh = nest.GetLeaves(l_inh, local_only=True)[0]
    nest.Connect(leaves_inh, sd_inh)
Exemplo n.º 7
0
 def start_simulation(self):
     nest.Simulate(self.parameters['Time before stimulation'])
     nest.SetStatus(self.stim2_i, {'rate': self.parameters['Stimulus rate']})
     nest.Simulate(self.parameters['Time of stimulation'])
     nest.SetStatus(self.stim2_i, {'rate': 0.0})
     nest.Simulate(self.parameters['Time after Stimulation'])
     rec_ex_true = nest.GetLeaves(self.rec_ex, local_only=True)[0]
     rec_in_true = nest.GetLeaves(self.rec_in, local_only=True)[0]
     self.events_ex = nest.GetStatus(rec_ex_true, "events")[0]
     self.events_in = nest.GetStatus(rec_in_true, "events")[0]
     # self.events_ex = nest.GetStatus(self.rec_ex, "events")[0]
     # self.events_in = nest.GetStatus(self.rec_in, "events")[0]
     self.df_ex = makePandas(self.events_ex, tp.FindCenterElement(self.l)[0])
     self.df_in = makePandas(self.events_in, tp.FindCenterElement(self.l)[0])
    def _degrees(self):
        '''Return list of degrees.'''

        connections = nest.GetConnections(source=nest.GetLeaves(self._ls)[0])
        i = 0 if self._degree == 'out' else 1
        connections = [conn[i] for conn in connections]
        return self._counter(connections)
Exemplo n.º 9
0
def wd_fig(fig,
           loc,
           ldict,
           cdict,
           what,
           rpos=None,
           xlim=[-1, 51],
           ylim=[0, 1],
           xticks=range(0, 51, 5),
           yticks=np.arange(0., 1.1, 0.2),
           clr='blue',
           label=''):
    nest.ResetKernel()
    l = tp.CreateLayer(ldict)
    tp.ConnectLayers(l, l, cdict)

    ax = fig.add_subplot(loc)

    if rpos is None:
        rn = nest.GetLeaves(l)[0][:1]  # first node
    else:
        rn = tp.FindNearestElement(l, rpos)

    conns = nest.GetConnections(rn)
    cstat = nest.GetStatus(conns)
    vals = np.array([sd[what] for sd in cstat])
    tgts = [sd['target'] for sd in cstat]
    locs = np.array(tp.GetPosition(tgts))
    ax.plot(locs[:, 0], vals, 'o', mec='none', mfc=clr, label=label)
    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    ax.set_xticks(xticks)
    ax.set_yticks(yticks)
Exemplo n.º 10
0
    def _positions(self):
        '''Return positions of all nodes.'''

        return [
            tuple(pos)
            for pos in topo.GetPosition(nest.GetLeaves(self._lt)[0])
        ]
Exemplo n.º 11
0
def pn_fig(fig, loc, ldict, cdict,
           xlim=[0., .5], ylim=[0, 3.5], xticks=range(0, 51, 5),
           yticks=np.arange(0., 1.1, 0.2), clr='blue',
           label=''):
    nest.ResetKernel()
    l = tp.CreateLayer(ldict)
    tp.ConnectLayers(l, l, cdict)

    ax = fig.add_subplot(loc)

    rn = nest.GetLeaves(l)[0]
    conns = nest.GetConnections(rn)
    cstat = nest.GetStatus(conns)
    srcs = [sd['source'] for sd in cstat]
    tgts = [sd['target'] for sd in cstat]
    dist = np.array(tp.Distance(srcs, tgts))
    ax.hist(dist, bins=50, histtype='stepfilled', normed=True)
    r = np.arange(0., 0.51, 0.01)

    plt.plot(r, 2 * np.pi * r * (1 - 2 * r) * 12 / np.pi, 'r-', lw=3,
             zorder=-10)

    ax.set_xlim(xlim)
    ax.set_ylim(ylim)
    """ax.set_xticks(xticks)
    ax.set_yticks(yticks)"""
    # ax.set_aspect(100, 'box')
    ax.set_xlabel('Source-target distance d')
    ax.set_ylabel('Connection probability pconn(d)')
Exemplo n.º 12
0
def generate_recorders(p,layers):
    # Function for creating and connecting recorders to the network
    # Input: input parameters from YML files
    # Output: list of recorders
    
    recorders = []
    
    for i in p["network"]["recorders"]["types"]:
        i["params"]["to_file"] = True if "file" in i["params"]["record_to"] else False
        i["params"]["to_memory"] = True if "memory" in i["params"]["record_to"] else False
        
        nest.CopyModel(i["type"],i["name"],i["params"])
        
    for i in p["network"]["recorders"]["record_from"]:
        r = nest.Create(i["recorder"])
        a = p["network"]["recorders"]["types"]
        b=None
        for z in a:
            b = z["params"]["record_from"] if z["name"] == i["recorder"] else b
        
        if not b:
            print("Recordername not recognized. Check the recorders of the input files for consistency.")
            sys.exit()
        
        recorders.append([r, i["layer"],i["population"],b])
        nest.Connect(r,nest.GetLeaves(layers[i["layer"]][0],properties={"model":i["population"]})[0])
    
    return recorders
Exemplo n.º 13
0
    def test_Distance(self):
        """Interface check on distance calculations."""
        ldict = {'elements': 'iaf_neuron', 'rows': 4, 'columns': 5}
        nest.ResetKernel()
        l = topo.CreateLayer(ldict)
        n = nest.GetLeaves(l)[0]

        # gids -> gids, all displacements must be zero here
        d = topo.Distance(n, n)
        self.assertEqual(len(d), len(n))
        self.assertTrue(all([dd == 0. for dd in d]))

        # single gid -> gids
        d = topo.Distance(n[:1], n)
        self.assertEqual(len(d), len(n))
        self.assertTrue(all([isinstance(dd, float) for dd in d]))

        # gids -> single gid
        d = topo.Distance(n, n[:1])
        self.assertEqual(len(d), len(n))
        self.assertTrue(all([isinstance(dd, float) for dd in d]))

        from numpy import array

        # position -> gids
        d = topo.Distance(array([0.0, 0.0]), n)
        self.assertEqual(len(d), len(n))
        self.assertTrue(all([isinstance(dd, float) for dd in d]))

        # positions -> gids
        d = topo.Distance([array([0.0, 0.0])] * len(n), n)
        self.assertEqual(len(d), len(n))
        self.assertTrue(all([isinstance(dd, float) for dd in d]))
Exemplo n.º 14
0
def intracellular_potentials(fig, recorders, recorded_models, starting_neuron,
                             rows, cols, starting_pos, total_time):  #keiko

    pos = starting_pos
    counter = 0

    for population, model in recorded_models:

        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        senders = data[0]['senders']
        selected_senders = np.where(senders == pop[starting_neuron])

        Vax = plt.subplot2grid((rows, cols), (pos, 0), colspan=cols)
        Vax.plot((data[0]['V_m'])[selected_senders[0]])
        if (counter != (len(recorded_models) - 1)):
            Vax.axes.get_xaxis().set_ticks([])
        plt.setp(Vax, yticks=[-80, 0], yticklabels=['-80', '0'])
        Vax.set_ylabel(model)
        Vax.set_xlabel('time (ms)')
        pos += 1
        counter += 1

        # keiko
        #min_x = np.min(data[0]['times'])
        #max_x = np.max(data[0]['times'])
        plt.xlim(0, total_time)
Exemplo n.º 15
0
def synaptic_currents(recorders, recorded_models, starting_neuron):

    fig = plt.figure()
    counter = 0

    for population, model in recorded_models:
        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        senders = data[0]['senders']
        selected_senders = np.where(senders == pop[starting_neuron])

        Vax = plt.subplot2grid((1, 1), (0, 0), colspan=1)
        Vax.plot((data[0]['I_syn_AMPA'])[selected_senders[0]], label='AMPA')
        Vax.plot((data[0]['I_syn_NMDA'])[selected_senders[0]], label='NMDA')
        Vax.plot((data[0]['I_syn_GABA_A'])[selected_senders[0]],
                 label='GABA_A')
        Vax.plot((data[0]['I_syn_GABA_B'])[selected_senders[0]],
                 label='GABA_B')

        Vax.legend(fancybox=True)
        Vax.set_ylabel(model)
        Vax.set_xlabel('time (ms)')
Exemplo n.º 16
0
    def runSimulation(self, recorded_models, recorded_spikes):

        nest.CopyModel(
            'multimeter', 'RecordingNode', {
                'interval': self.Params['resolution'],
                'record_from': ['V_m'],
                'record_to': ['memory'],
                'withgid': True,
                'withtime': False
            })

        recorders = []

        for population, model in recorded_models:

            rec = nest.Create('RecordingNode')

            recorders.append([rec, population, model])
            tgts = [
                nd for nd in nest.GetLeaves(population)[0]
                if nest.GetStatus([nd], 'model')[0] == model
            ]
            nest.Connect(rec, tgts)

        nest.CopyModel('spike_detector', 'RecordingSpikes', {
            "withtime": True,
            "withgid": True,
            "to_file": False
        })

        spike_detectors = []

        for population, model in recorded_spikes:
            rec = nest.Create('RecordingSpikes')
            spike_detectors.append([rec, population, model])
            tgts = [
                nd for nd in nest.GetLeaves(population)[0]
                if nest.GetStatus([nd], 'model')[0] == model
            ]
            nest.Connect(tgts, rec)

        print("\n--- Simulation ---\n")
        nest.SetStatus([0], {'print_time': True})
        nest.Simulate(self.Params['simtime'])

        return recorders, spike_detectors
Exemplo n.º 17
0
def geometryFunction(topologyLayer):

    positions = topo.GetPosition(nest.GetLeaves(topologyLayer)[0])

    def geometry_function(idx):
        return positions[idx]

    return geometry_function
    def _connect(self):
        '''Connect populations.'''

        g1 = self._geometryFunction(self._ls)
        g2 = self._geometryFunction(self._lt)
        d = csa.euclidMetric2d(g1, g2)
        sigma = self._params['sigma']
        cutoff = self._max_dist
        cs = csa.cset(
            csa.cross([0], xrange(self._N - 1)) *
            (csa.random * (csa.gaussian(sigma, cutoff) * d)), 1.0, 1.0)
        nest.CGConnect(
            nest.GetLeaves(self._ls)[0],
            nest.GetLeaves(self._lt)[0], cs, {
                'weight': 0,
                'delay': 1
            })
Exemplo n.º 19
0
def MyConnectLayers(pre, post, projections):

    if 'n_cluster' in projections.keys():

        n_cluster = projections['n_cluster']
        k = projections['kernel']
        syn_model = projections['synapse_model']
        k_new = k * 1 / (1 - 1 / n_cluster)

        pre_ids = nest.GetLeaves(pre)[0]
        post_ids = nest.GetLeaves(post)[0]

        sources, targets = misc.cluster_connections(pre_ids, post_ids, k_new,
                                                    n_cluster)

        nest.Connect(list(sources), list(targets), model=syn_model)
    else:
        ConnectLayers(pre, post, projections)
Exemplo n.º 20
0
 def test_CreateLayer(self):
     """Creating a single layer from dict."""
     nr = 4
     nc = 5
     nest.ResetKernel()
     l = topo.CreateLayer({'elements': 'iaf_neuron',
                           'rows': nr,
                           'columns': nc})
     self.assertEqual(len(l), 1)
     self.assertEqual(len(nest.GetLeaves(l)[0]), nr*nc)
Exemplo n.º 21
0
def potential_raster(fig, recorders, recorded_models, starting_neuron,
                     number_cells, simtime, resolution, rows, cols,
                     starting_pos):

    pos = starting_pos
    rec_from = ["rate", "V_m"]

    for population, model in recorded_models:

        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        # Retina layer always the first (l=0)
        if l == 0:
            rf = rec_from[0]
        else:
            rf = rec_from[1]

        raster = np.zeros(
            (number_cells, round((simtime - resolution) / resolution)))
        senders = data[0]['senders']

        for neuron in range(0, len(raster)):
            selected_senders = np.where(senders == pop[neuron +
                                                       starting_neuron])
            raster[neuron, :] = (data[0][rf])[selected_senders[0]]

        Vax = plt.subplot2grid((rows, cols), (pos, 0), colspan=cols)

        if l > 0:
            cax = Vax.matshow(raster, aspect='auto', vmin=-70.0, vmax=-45.0)
            Vax.axes.get_xaxis().set_ticks([])
        else:
            # cax = Vax.matshow(raster,aspect='auto') # original
            cax = Vax.matshow(raster, aspect='auto', vmin=0.0,
                              vmax=200.0)  # keiko
            fig.colorbar(cax,
                         ticks=[0.0, 100.0, 200.0],
                         orientation='horizontal')  # keiko

        Vax.xaxis.tick_top()
        plt.setp(Vax,
                 yticks=[0, number_cells],
                 yticklabels=['0', str(number_cells - 1)])
        Vax.set_ylabel(model)
        pos += 1

    fig.colorbar(cax, ticks=[-70.0, -57.5, -45.0], orientation='horizontal')
Exemplo n.º 22
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)
Exemplo n.º 23
0
    def test_CreateLayerN(self):
        """Creating multiple layers from tuple of dicts."""
        nr = 4
        nc = 5
        ldict = {'elements': 'iaf_neuron', 'rows': nr, 'columns': nc}
        nlayers = 3

        nest.ResetKernel()
        l = topo.CreateLayer((ldict, ) * nlayers)
        self.assertEqual(len(l), nlayers)
        self.assertEqual([len(lvs) for lvs in nest.GetLeaves(l)],
                         [nr * nc] * nlayers)
Exemplo n.º 24
0
    def test_GetLeaves(self):
        """GetLeaves"""

        nest.ResetKernel()
        model = 'iaf_neuron'
        l = nest.LayoutNetwork(model, [2, 3])
        allLeaves = [3, 4, 5, 7, 8, 9]

        # test all
        self.assertEqual(nest.GetLeaves(l), [allLeaves])

        # test all with empty dict
        self.assertEqual(nest.GetLeaves(l, properties={}), [allLeaves])

        # test iteration over subnets
        self.assertEqual(nest.GetLeaves(l + l), [allLeaves, allLeaves])

        # children of l are not leaves, should yield empty
        self.assertEqual(nest.GetLeaves(l, properties={'parent': l[0]}), [[]])

        # local id of middle nodes
        self.assertEqual(nest.GetLeaves(l, properties={'local_id': 2}),
                         [[4, 8]])

        # selection by model type
        self.assertEqual(nest.GetLeaves(l, properties={'model': model}),
                         [allLeaves])
Exemplo n.º 25
0
    def test_GetLeaves(self):
        """GetLeaves"""

        nest.ResetKernel()
        model = 'iaf_psc_alpha'
        l = nest.LayoutNetwork(model, (2, 3))
        allLeaves = (3, 4, 5, 7, 8, 9)

        # test all
        self.assertEqual(nest.GetLeaves(l), (allLeaves, ))

        # test all with empty dict
        self.assertEqual(nest.GetLeaves(l, properties={}), (allLeaves, ))

        # test iteration over subnets
        self.assertEqual(nest.GetLeaves(l + l), (allLeaves, allLeaves))

        # children of l are not leaves, should yield empty
        self.assertEqual(nest.GetLeaves(
            l, properties={'parent': l[0]}), (tuple(), ))

        # local id of middle nodes
        self.assertEqual(nest.GetLeaves(
            l, properties={'local_id': 2}), ((4, 8), ))

        # selection by model type
        self.assertEqual(nest.GetLeaves(
            l, properties={'model': model}), (allLeaves, ))
Exemplo n.º 26
0
 def test_GetPosition(self):
     """Check if GetPosition returns proper positions."""
     pos = [[1.0, 0.0], [0.0, 1.0], [3.5, 1.5]]
     ldict = {
         'elements': 'iaf_neuron',
         'extent': [20., 20.],
         'positions': pos
     }
     nlayers = 2
     nest.ResetKernel()
     l = topo.CreateLayer((ldict, ) * nlayers)
     nodepos = [topo.GetPosition(node) for node in nest.GetLeaves(l)]
     self.assertEqual([pos] * nlayers, nodepos)
Exemplo n.º 27
0
def makeMovie(fig, recorders, recorded_models, labels, number_cells, simtime,
              resolution):

    counter = 0

    print "creating movies..."

    for population, model in recorded_models:

        fig = plt.figure(1)
        ax = fig.add_subplot(111)
        ax.set_xlabel('neuron ID')
        ax.set_ylabel('neuron ID')

        im = ax.matshow(np.zeros((number_cells, number_cells)),
                        vmin=-70.0,
                        vmax=-45.0)

        if counter == 0:
            plt.subplot(111)
            cbar = fig.colorbar(im)

        os.system("rm -r movies/" + labels[counter] + "/*")
        os.system("mkdir movies/" + labels[counter])

        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        senders = data[0]['senders']

        for t in np.arange(0.0, simtime - resolution, resolution):
            mult_pos = 0
            raster = np.zeros((number_cells, number_cells))
            for x in range(0, number_cells):
                for y in range(0, number_cells):
                    selected_senders = np.where(senders == pop[mult_pos])
                    ind_rec = (data[0]['V_m'])[selected_senders[0]]
                    raster[y, x] = ind_rec[int(t)]
                    mult_pos += 1

            im = ax.matshow(raster, vmin=-70.0, vmax=-45.0)
            plt.savefig('movies/' + labels[counter] + '/' + str(t) + '.png')

        counter += 1
Exemplo n.º 28
0
 def test_GetLayer(self):
     """Check if GetLayer returns correct information."""
     nr = 4
     nc = 5
     ldict = {'elements': 'iaf_neuron', 'rows': nr, 'columns': nc}
     nlayers = 3
     nest.ResetKernel()
     l = topo.CreateLayer((ldict, ) * nlayers)
     # obtain list containing list of results from GetLayer for all
     # nodes in layers
     leavelayers = [topo.GetLayer(node) for node in nest.GetLeaves(l)]
     # the list comprehension builds a list of lists of layer gids,
     # each list containing nr*nc copies of the layer gid
     self.assertEqual([list(t) for t in zip(*([l] * (nr * nc)))],
                      leavelayers)
Exemplo n.º 29
0
    def test_GetPosition(self):
        """Check if GetPosition returns proper positions."""
        pos = ((1.0, 0.0), (0.0, 1.0), (3.5, 1.5))
        ldict = {'elements': 'iaf_neuron',
                 'extent': (20., 20.),
                 'positions': pos}
        nlayers = 2
        nest.ResetKernel()
        l = topo.CreateLayer((ldict,)*nlayers)

        nodepos_ref = (pos, ) * nlayers
        nodepos_exp = (topo.GetPosition(node) for node in nest.GetLeaves(l))

        for npe, npr in zip(nodepos_exp, nodepos_ref):
            self.assertEqual(npe, npr)
Exemplo n.º 30
0
def topographic_representation(fig, recorders, recorded_models, labels,
                               number_cells, simtime, resolution, rows, cols,
                               start, stop, starting_pos, col_paint):

    col_ind = col_paint
    pos = starting_pos
    counter = 0

    for population, model in recorded_models:

        l = [
            nd for nd in np.arange(0, len(recorders))
            if (recorders[nd][1] == population and recorders[nd][2] == model)
        ][0]
        data = nest.GetStatus(recorders[l][0], keys='events')
        pop = [
            nd for nd in nest.GetLeaves(population)[0]
            if nest.GetStatus([nd], 'model')[0] == model
        ]

        raster = np.zeros((number_cells, number_cells))
        mult_pos = 0
        senders = data[0]['senders']
        for x in range(0, number_cells):
            for y in range(0, number_cells):

                selected_senders = np.where(senders == pop[mult_pos])
                ind_rec = (data[0]['V_m'])[selected_senders[0]]
                raster[y, x] = np.sum(
                    ind_rec[int(start /
                                resolution):int(stop / resolution)]) / (
                                    (stop - start) / resolution)
                mult_pos += 1

        Iax = plt.subplot2grid((rows, cols), (pos, col_ind), colspan=1)
        cax2 = Iax.matshow(raster, aspect='auto', vmin=-70.0, vmax=-45.0)
        Iax.xaxis.tick_bottom()
        Iax.axes.get_xaxis().set_ticks([])
        Iax.axes.get_yaxis().set_ticks([])
        Iax.set_ylabel(model)
        Iax.set_xlabel(labels[counter])
        counter += 1
        col_ind += 1

    fig.colorbar(cax2, ticks=[-70.0, -57.5, -45.0])