Skip to content

dist_thresh_weights_sequential

cellseg_gsontools.graphs.dist_thresh_weights_sequential(gdf, w, thresh, id_col=None, include_self=False)

Threshold edges based on distance to center node.

Parameters:

Name Type Description Default
gdf GeoDataFrame

The input geodataframe.

required
w W

The input spatial weights object.

required
thresh float

The distance threshold.

required
id_col str

The unique id column in the gdf. If None, this uses set_uid to set it.

None
include_self bool, default=True

Whether to include self-loops in the neighbors.

False

Returns:

Type Description
W

libpysal.weights.W: A libpysal spatial weights object, containing the neighbor graph data.

Source code in cellseg_gsontools/graphs.py
def dist_thresh_weights_sequential(
    gdf: gpd.GeoDataFrame,
    w: W,
    thresh: float,
    id_col: Optional[str] = None,
    include_self: bool = False,
) -> W:
    """Threshold edges based on distance to center node.

    Parameters:
        gdf (gpd.GeoDataFrame):
            The input geodataframe.
        w (libpysal.weights.W):
            The input spatial weights object.
        thresh (float):
            The distance threshold.
        id_col (str, optional):
            The unique id column in the gdf. If None, this uses `set_uid` to set it.
        include_self (bool, default=True):
            Whether to include self-loops in the neighbors.

    Returns:
        libpysal.weights.W:
            A libpysal spatial weights object, containing the neighbor graph data.
    """
    gdf = gdf.copy()

    # drop duplicate rows
    gdf = gdf.drop_duplicates(subset=[id_col], keep="first")
    gdf["nhood"] = pd.Series(list(w.neighbors.values()), index=gdf.index)

    new_neighbors = []
    for _, row in gdf.iterrows():
        neighbor_rows = gdf[gdf.loc[:, id_col].isin(row.nhood)]
        nhood_dist = [
            np.round(row.geometry.centroid.distance(ngh), 2)
            for ngh in neighbor_rows.geometry.centroid
        ]

        new_neighbors.append(
            _drop_neighbors(row.nhood, nhood_dist, thresh, include_self=include_self)
        )

    gdf["new_neighbors"] = new_neighbors
    return W(dict(zip(gdf[id_col], gdf["new_neighbors"])), silence_warnings=True)