Skip to content

neighborhood

cellseg_gsontools.neighbors.neighborhood(node, spatial_weights, include_self=True, ret_n_neighbors=False)

Get immediate neighborhood of a node given the spatial weights obj.

Note

This function is designed to be used with the gdf_apply function. See the example.

Note

The neighborhood contains the given node itself by default.

Parameters:

Name Type Description Default
node int or Series

Input node uid.

required
spatial_weights W

Libpysal spatial weights object.

required
include_self bool

Flag, whether to include the node itself in the neighborhood. Defaults to True.

True
ret_n_neighbors bool

If True, instead of returning a sequence of the neighbor node uids returns just the number of neighbors. Defaults to False.

False

Returns:

Type Description
Union[List[int], int]

List[int] or int: A list of the neighboring node uids. E.g. [1, 4, 19]. or the number of neighbors if ret_n_neighbors=True.

Examples:

Use gdf_apply to extract the neighboring nodes for each node/cell

>>> from functools import partial
>>> from cellseg_gsontools.data import gland_cells
>>> from cellseg_gsontools.graphs import fit_graph
>>> from cellseg_gsontools.utils import set_uid
>>> from cellseg_gsontools.apply import gdf_apply
>>> from cellseg_gsontools.neighbors import neighborhood
>>> gc = gland_cells()
>>> # To fit the delaunay graph, we need to set a unique id for each cell first
>>> gc = set_uid(gc, id_col="uid")
>>> w = fit_graph(gc, type="delaunay", thresh=100, id_col="uid")
>>> # Get the neihgboring nodes of the graph
>>> func = partial(neighborhood, spatial_weights=w)
>>> gc["nhood"] = gdf_apply(gc, func, columns=["uid"])
>>> gc["nhood"].head(5)
        uid
0       [0, 1, 3, 4, 483, 484]
1     [1, 0, 4, 482, 483, 487]
2       [2, 3, 5, 6, 484, 493]
3      [3, 0, 2, 4, 5, 7, 484]
4    [4, 0, 1, 3, 7, 487, 488]
Name: nhood, dtype: object
Source code in cellseg_gsontools/neighbors.py
def neighborhood(
    node: Union[int, pd.Series],
    spatial_weights: W,
    include_self: bool = True,
    ret_n_neighbors: bool = False,
) -> Union[List[int], int]:
    """Get immediate neighborhood of a node given the spatial weights obj.

    Note:
        This function is designed to be used with the `gdf_apply` function.
        See the example.

    Note:
        The neighborhood contains the given node itself by default.

    Parameters:
        node (int or pd.Series):
            Input node uid.
        spatial_weights (libysal.weights.W):
            Libpysal spatial weights object.
        include_self (bool):
            Flag, whether to include the node itself in the neighborhood.
            Defaults to True.
        ret_n_neighbors (bool):
            If True, instead of returning a sequence of the neighbor node uids
            returns just the number of neighbors. Defaults to False.

    Returns:
        List[int] or int:
            A list of the neighboring node uids. E.g. [1, 4, 19].
            or the number of neighbors if `ret_n_neighbors=True`.

    Examples:
        Use `gdf_apply` to extract the neighboring nodes for each node/cell
        >>> from functools import partial
        >>> from cellseg_gsontools.data import gland_cells
        >>> from cellseg_gsontools.graphs import fit_graph
        >>> from cellseg_gsontools.utils import set_uid
        >>> from cellseg_gsontools.apply import gdf_apply
        >>> from cellseg_gsontools.neighbors import neighborhood
        >>> gc = gland_cells()
        >>> # To fit the delaunay graph, we need to set a unique id for each cell first
        >>> gc = set_uid(gc, id_col="uid")
        >>> w = fit_graph(gc, type="delaunay", thresh=100, id_col="uid")
        >>> # Get the neihgboring nodes of the graph
        >>> func = partial(neighborhood, spatial_weights=w)
        >>> gc["nhood"] = gdf_apply(gc, func, columns=["uid"])
        >>> gc["nhood"].head(5)
                uid
        0       [0, 1, 3, 4, 483, 484]
        1     [1, 0, 4, 482, 483, 487]
        2       [2, 3, 5, 6, 484, 493]
        3      [3, 0, 2, 4, 5, 7, 484]
        4    [4, 0, 1, 3, 7, 487, 488]
        Name: nhood, dtype: object
    """
    if isinstance(node, pd.Series):
        node = node.iloc[0]  # assume that the series is a row

    nhood = np.nan
    if ret_n_neighbors:
        nhood = spatial_weights.cardinalities[node]
    elif node in spatial_weights.neighbors.keys():
        # get spatial neighborhood
        nhood = spatial_weights.neighbors[node]
        if include_self:
            nhood = [node] + list(nhood)

    return nhood