コード例 #1
0
    def test_GetElement(self):
        """Check if GetElement returns proper lists."""
        ldict = {'elements': 'iaf_neuron', 'rows': 4, 'columns': 5}
        nest.ResetKernel()
        l = topo.CreateLayer((ldict, ldict))
        checkpos = [[0, 0], [1, 1], [4, 3]]

        # single gid, single coord gives 1-elem gid list
        n1 = topo.GetElement(l[:1], checkpos[0])
        self.assertEqual(len(n1), 1)
        self.assertIsInstance(n1[0], int)

        # multiple gid, single coord gives l-elem gid list
        n2 = topo.GetElement(l, checkpos[0])
        self.assertEqual(len(n2), len(l))
        self.assertTrue(all(nest.is_sequence_of_gids(n) for n in n2))

        # single gid, multiple coord gives len(checkpos)-elem gid list
        n3 = topo.GetElement(l[:1], checkpos)
        self.assertEqual(len(n3), len(checkpos))
        self.assertTrue(all(nest.is_sequence_of_gids(n) for n in n3))
        self.assertTrue(all(len(n) == 1 for n in n3))

        # multiple gid, multiple coord gives l*len(cp)-elem gid list
        n4 = topo.GetElement(l, checkpos)
        self.assertEqual(len(n4), len(l))

        self.assertTrue(all(nest.is_iterable(n) for n in n4))
        self.assertTrue(all(len(n) == len(checkpos) for n in n4))
        self.assertTrue(all(
            nest.is_sequence_of_gids(m) for n in n4 for m in n))
コード例 #2
0
ファイル: hl_api.py プロジェクト: MogeiWang/nest
def _check_displacement_args(from_arg, to_arg, caller):
    """
    Internal helper function to check arguments to Displacement
    and Distance and make them lists of equal length.
    """

    import numpy

    if isinstance(from_arg, numpy.ndarray):
        from_arg = (from_arg, )
    elif not (nest.is_iterable(from_arg) and len(from_arg) > 0):
        raise nest.NESTError("%s: from_arg must be lists of GIDs or positions" % caller)
    # invariant: from_arg is list
    
    if not nest.is_sequence_of_gids(to_arg):
        raise nest.NESTError("%s: to_arg must be lists of GIDs" % caller)
    # invariant: from_arg and to_arg are sequences
    
    if len(from_arg) > 1 and len(to_arg) > 1 and not len(from_arg) == len(to_arg):
        raise nest.NESTError("%s: If to_arg and from_arg are lists, they must have equal length." % caller)
    # invariant: from_arg and to_arg have equal length, or (at least) one has length 1

    if len(from_arg) == 1:
        from_arg = from_arg*len(to_arg)  # this is a no-op if len(to_arg)==1
    if len(to_arg) == 1:
        to_arg   = to_arg*len(from_arg)  # this is a no-op if len(from_arg)==1
    # invariant: from_arg and to_arg have equal length

    return from_arg, to_arg
コード例 #3
0
ファイル: test_basics.py プロジェクト: apeyser/nest-simulator
    def test_GetElement(self):
        """Check if GetElement returns proper lists."""
        ldict = {'elements': 'iaf_psc_alpha',
                 'rows': 4, 'columns': 5}
        nest.ResetKernel()
        l = topo.CreateLayer((ldict, ldict))
        checkpos = [[0, 0], [1, 1], [4, 3]]

        # single gid, single coord gives 1-elem gid list
        n1 = topo.GetElement(l[:1], checkpos[0])
        self.assertEqual(len(n1), 1)
        self.assertIsInstance(n1[0], int)

        # multiple gid, single coord gives l-elem gid list
        n2 = topo.GetElement(l, checkpos[0])
        self.assertEqual(len(n2), len(l))
        self.assertTrue(all(nest.is_sequence_of_gids(n) for n in n2))

        # single gid, multiple coord gives len(checkpos)-elem gid list
        n3 = topo.GetElement(l[:1], checkpos)
        self.assertEqual(len(n3), len(checkpos))
        self.assertTrue(all(nest.is_sequence_of_gids(n) for n in n3))
        self.assertTrue(all(len(n) == 1 for n in n3))

        # multiple gid, multiple coord gives l*len(cp)-elem gid list
        n4 = topo.GetElement(l, checkpos)
        self.assertEqual(len(n4), len(l))

        self.assertTrue(all(nest.is_iterable(n) for n in n4))
        self.assertTrue(all(len(n) == len(checkpos) for n in n4))
        self.assertTrue(all(nest.is_sequence_of_gids(m)
                            for n in n4 for m in n))
コード例 #4
0
ファイル: lib.py プロジェクト: Ziaeemehr/balanced_network
def raster_plot_from_file(fname,
                          hist=False,
                          hist_binwidth=5.0,
                          xlim=None,
                          sel=None):
    """
    Plot raster from file
    """
    if nest.is_iterable(fname):
        data = None
        for f in fname:
            if data is None:
                data = np.loadtxt(f)
            else:
                data = np.concatenate((data, np.loadtxt(f)))
    else:
        data = np.loadtxt(fname)

    ts = data[:, 1]
    gids = data[:, 0]
    if not len(ts):
        raise nest.NESTError("No events recorded!")

    val = extract_events(ts, gids, sel=sel)
    make_plot(ts, gids, val, hist, hist_binwidth, sel, xlim)
コード例 #5
0
ファイル: raster_plot.py プロジェクト: JanneM/nest-simulator
def from_file(fname, title=None, hist=False, hist_binwidth=5.0, grayscale=False):
    """
    Plot raster from file
    """

    if nest.is_iterable(fname):
        data = None
        for f in fname:
            if data is None:
                data = numpy.loadtxt(f)
            else:
                data = numpy.concatenate((data, numpy.loadtxt(f)))
    else:
        data = numpy.loadtxt(fname)

    return from_data(data, title, hist, hist_binwidth, grayscale)
コード例 #6
0
def from_file(fname,
              title=None,
              hist=False,
              hist_binwidth=5.0,
              grayscale=False):
    """
    Plot raster from file
    """

    if nest.is_iterable(fname):
        data = None
        for f in fname:
            if data is None:
                data = numpy.loadtxt(f)
            else:
                data = numpy.concatenate((data, numpy.loadtxt(f)))
    else:
        data = numpy.loadtxt(fname)

    return from_data(data, title, hist, hist_binwidth, grayscale)
コード例 #7
0
def from_file(fname, **kwargs):
    """Plot raster from file.

    Parameters
    ----------
    fname : str
        Name of file
    kwargs:
        Parameters passed to _make_plot
    """

    if nest.is_iterable(fname):
        data = None
        for f in fname:
            if data is None:
                data = numpy.loadtxt(f)
            else:
                data = numpy.concatenate((data, numpy.loadtxt(f)))
    else:
        data = numpy.loadtxt(fname)

    return from_data(data, **kwargs)
コード例 #8
0
def from_file(fname, title=None, grayscale=False):
    """Plot voltage trace from file.

    Parameters
    ----------
    fname : str or list
        Filename or list of filenames to load from
    title : str, optional
        Plot title
    grayscale : bool, optional
        Plot in grayscale

    Raises
    ------
    ValueError
    """
    if nest.is_iterable(fname):
        data = None
        for f in fname:
            if data is None:
                data = numpy.loadtxt(f)
            else:
                data = numpy.concatenate((data, numpy.loadtxt(f)))
    else:
        data = numpy.loadtxt(fname)

    if grayscale:
        line_style = "k"
    else:
        line_style = ""

    if len(data.shape) == 1:
        print("INFO: only found 1 column in the file. \
            Assuming that only one neuron was recorded.")
        plotid = pylab.plot(data, line_style)
        pylab.xlabel("Time (steps of length interval)")

    elif data.shape[1] == 2:
        print("INFO: found 2 columns in the file. Assuming \
            them to be gid, pot.")

        plotid = []
        data_dict = {}
        for d in data:
            if not d[0] in data_dict:
                data_dict[d[0]] = [d[1]]
            else:
                data_dict[d[0]].append(d[1])

        for d in data_dict:
            plotid.append(
                pylab.plot(data_dict[d], line_style, label="Neuron %i" % d)
            )

        pylab.xlabel("Time (steps of length interval)")
        pylab.legend()

    elif data.shape[1] == 3:
        plotid = []
        data_dict = {}
        g = data[0][0]
        t = []
        for d in data:
            if not d[0] in data_dict:
                data_dict[d[0]] = [d[2]]
            else:
                data_dict[d[0]].append(d[2])
            if d[0] == g:
                t.append(d[1])

        for d in data_dict:
            plotid.append(
                pylab.plot(t, data_dict[d], line_style, label="Neuron %i" % d)
            )

        pylab.xlabel("Time (ms)")
        pylab.legend()

    else:
        raise ValueError("Inappropriate data shape %i!" % data.shape)

    if not title:
        title = "Membrane potential from file '%s'" % fname

    pylab.title(title)
    pylab.ylabel("Membrane potential (mV)")
    pylab.draw()

    return plotid
コード例 #9
0
ファイル: voltage_trace.py プロジェクト: bitSlayer29090/CSL
def from_file(fname, title=None, grayscale=False):
    """Plot voltage trace from file.

    Parameters
    ----------
    fname : str or list
        Filename or list of filenames to load from
    title : str, optional
        Plot title
    grayscale : bool, optional
        Plot in grayscale

    Raises
    ------
    ValueError
    """
    if nest.is_iterable(fname):
        data = None
        for f in fname:
            if data is None:
                data = numpy.loadtxt(f)
            else:
                data = numpy.concatenate((data, numpy.loadtxt(f)))
    else:
        data = numpy.loadtxt(fname)

    if grayscale:
        line_style = "k"
    else:
        line_style = ""

    if len(data.shape) == 1:
        print("INFO: only found 1 column in the file. \
            Assuming that only one neuron was recorded.")
        plotid = pylab.plot(data, line_style)
        pylab.xlabel("Time (steps of length interval)")

    elif data.shape[1] == 2:
        print("INFO: found 2 columns in the file. Assuming \
            them to be gid, pot.")

        plotid = []
        data_dict = {}
        for d in data:
            if not d[0] in data_dict:
                data_dict[d[0]] = [d[1]]
            else:
                data_dict[d[0]].append(d[1])

        for d in data_dict:
            plotid.append(
                pylab.plot(data_dict[d], line_style, label="Neuron %i" % d))

        pylab.xlabel("Time (steps of length interval)")
        pylab.legend()

    elif data.shape[1] == 3:
        plotid = []
        data_dict = {}
        g = data[0][0]
        t = []
        for d in data:
            if not d[0] in data_dict:
                data_dict[d[0]] = [d[2]]
            else:
                data_dict[d[0]].append(d[2])
            if d[0] == g:
                t.append(d[1])

        for d in data_dict:
            plotid.append(
                pylab.plot(t, data_dict[d], line_style, label="Neuron %i" % d))

        pylab.xlabel("Time (ms)")
        pylab.legend()

    else:
        raise ValueError("Inappropriate data shape %i!" % data.shape)

    if not title:
        title = "Membrane potential from file '%s'" % fname

    pylab.title(title)
    pylab.ylabel("Membrane potential (mV)")
    pylab.draw()

    return plotid
コード例 #10
0
ファイル: hl_api.py プロジェクト: MogeiWang/nest
def FindNearestElement(layers, locations, find_all=False):
    """
    Return the node(s) closest to the location(s) in the given layer(s).

    Parameters
    ----------
    layers   : list of layer GIDs
    locations: 2-element array with coordinates of a single position,
               or list of 2-element arrays of positions
    find_all : Default value false: if there are several nodes with same
               minimal distance, return only the first found. If True,
               instead of returning a single GID, return a list of
               GIDs containing all nodes with minimal distance.           

    Returns
    -------
    List of GIDs

    If layers contains a single GID and locations is a single 2-element
    array giving a location, return single-element list with GID
    of layer element closest to the given location.
    
    If layers is a list with a single GID and locations is a list of coordinates,
    the function returns a list of GIDs of the nodes closest to all locations.

    If layers is a list of GIDs and locations single 2-element array giving
    a position location, the function returns a list with the GIDs of the nodes
    in all layers closest to the given location.

    If layers and locations are lists, it returns a list of lists of GIDs,
    one for each layer.

    See also
    --------
    GetElement
    """

    import numpy

    if not nest.is_sequence_of_gids(layers):
        raise TypeError("layers must be a sequence of GIDs")

    if not len(layers) > 0:
        raise nest.NESTError("layers cannot be empty")

    if not nest.is_iterable(locations):
        raise TypeError("locations must be coordinate array or list of coordinate arrays")

    # ensure locations is sequence, keeps code below simpler
    if not nest.is_iterable(locations[0]):
        locations = (locations, )

    result = []  # collect one list per layer
    # loop over layers
    for lyr in layers:
        els = nest.GetChildren((lyr, ))[0]

        lyr_result = []
        # loop over locations
        for loc in locations:
            d = Distance(numpy.array(loc), els)

            if not find_all:
                dx = numpy.argmin(d)   # finds location of one minimum
                lyr_result.append(els[dx])
            else:
                mingids = list(els[:1])
                minval  = d[0]
                for idx in range(1, len(els)):
                    if d[idx] < minval:
                        mingids = [els[idx]]
                        minval = d[idx]
                    elif numpy.abs(d[idx] - minval) <= 1e-14 * minval:
                        mingids.append(els[idx])
                lyr_result.append(tuple(mingids))
        result.append(tuple(lyr_result))

    # If both layers and locations are multi-element lists, result shall remain a nested list
    # Otherwise, either the top or the second level is a single element list and we flatten
    assert(len(result) > 0)
    if len(result) == 1:
        assert(len(layers) == 1)
        return result[0]
    elif len(result[0]) == 1:
        assert(len(locations) == 1)
        return tuple(el[0] for el in result)
    else:
        return tuple(result)
コード例 #11
0
ファイル: hl_api.py プロジェクト: MogeiWang/nest
 def make_tuple(x):
     if not nest.is_iterable(x):
         return (x, )
     else:
         return x
コード例 #12
0
ファイル: hl_api.py プロジェクト: MogeiWang/nest
def GetElement(layers, locations):
    """
    Return the node(s) at the location(s) in the given layer(s).

    Parameters
    ----------
    layers   : list of layer GIDs
    locations: 2-element array with coordinates of a single grid location,
               or list of 2-element arrays of coordinates

    Returns
    -------
    List of GIDs

    This function works for fixed grid layers only.

    If layers contains a single GID and locations is a single 2-element
    array giving a grid location, return a list of GIDs of layer elements
    at the given location.

    If layers is a list with a single GID and locations is a list of
    coordinates, the function returns a list of lists with GIDs of the
    nodes at all locations.

    If layers is a list of GIDs and locations single 2-element array giving
    a grid location, the function returns a list of lists with the GIDs of
    the nodes in all layers at the given location.

    If layers and locations are lists, it returns a nested list of GIDs,
    one list for each layer and each location.

    See also
    --------
    FindNearestElement
    nest.help("topology::GetElement")
    """

    if not nest.is_sequence_of_gids(layers):
        raise TypeError("layers must be a sequence of GIDs")

    if not len(layers) > 0:
        raise nest.NESTError("layers cannot be empty")

    if not (nest.is_iterable(locations) and len(locations) > 0):
        raise nest.NESTError("locations must be coordinate array or list of coordinate arrays")

    # ensure that all layers are grid-based, otherwise one ends up with an
    # incomprehensible error message
    try:
        topology_func('{ [ /topology [ /rows /columns ] ] get ; } forall', layers)
    except: 
        raise nest.NESTError("layers must contain only grid-based topology layers")
    
    # SLI GetElement returns either single GID or list
    def make_tuple(x):
        if not nest.is_iterable(x):
            return (x, )
        else:
            return x

    if nest.is_iterable(locations[0]):

        # layers and locations are now lists
        nodes = topology_func('/locs Set { /lyr Set locs { lyr exch GetElement } Map } Map',
                              layers, locations)

        node_list = tuple(tuple(make_tuple(nodes_at_loc) for nodes_at_loc in nodes_in_lyr)
                     for nodes_in_lyr in nodes)

    else:

        # layers is list, locations is a single location
        nodes = topology_func('/loc Set { loc GetElement } Map', layers, locations)

        node_list = tuple(make_tuple(nodes_in_lyr) for nodes_in_lyr in nodes)

    # If only a single layer is given, un-nest list
    if len(layers)==1: node_list=node_list[0]

    return node_list