Skip to content

hexgrid_overlay

cellseg_gsontools.grid.hexgrid_overlay(gdf, resolution=9, to_lonlat=True)

Fit a h3 hexagonal grid on top of a geopandas.GeoDataFrame.

Parameters:

Name Type Description Default
gdf GeoDataFrame

GeoDataFrame to fit grid to.

required
resolution int

H3 resolution, by default 9.

9
to_lonlat bool

Whether to convert to lonlat coordinates, by default True.

True

Returns:

Type Description
GeoDataFrame

gpd.GeoDataFrame: Fitted h3 hex grid.

Examples:

Fit a hexagonal grid to a gdf:

>>> from cellseg_gsontools import read_gdf
>>> from cellseg_gsontools.grid import hexgrid_overlay
>>> # Read in the tissue areas
>>> area_gdf = gpd.read_file("path/to/area.geojson")
>>> # Fit the grid
>>> hex_grid = hexgrid_overlay(area_gdf, resolution=9)
>>> hex_grid
gpd.GeoDataFrame
Source code in cellseg_gsontools/grid.py
def hexgrid_overlay(
    gdf: gpd.GeoDataFrame, resolution: int = 9, to_lonlat: bool = True
) -> gpd.GeoDataFrame:
    """Fit a `h3` hexagonal grid on top of a `geopandas.GeoDataFrame`.

    Parameters:
        gdf (gpd.GeoDataFrame):
            GeoDataFrame to fit grid to.
        resolution (int):
            H3 resolution, by default 9.
        to_lonlat (bool):
            Whether to convert to lonlat coordinates, by default True.

    Returns:
        gpd.GeoDataFrame:
            Fitted h3 hex grid.

    Examples:
        Fit a hexagonal grid to a gdf:
        >>> from cellseg_gsontools import read_gdf
        >>> from cellseg_gsontools.grid import hexgrid_overlay
        >>> # Read in the tissue areas
        >>> area_gdf = gpd.read_file("path/to/area.geojson")
        >>> # Fit the grid
        >>> hex_grid = hexgrid_overlay(area_gdf, resolution=9)
        >>> hex_grid
        gpd.GeoDataFrame
    """
    if gdf.empty or gdf is None:
        return

    # drop invalid geometries if there are any after buffer
    gdf.geometry = gdf.geometry.buffer(0)
    gdf = gdf[gdf.is_valid]

    orig_crs = gdf.crs

    poly = shapely.force_2d(gdf.unary_union)
    if isinstance(poly, Polygon):
        hexagons = poly2hexgrid(poly, resolution=resolution, to_lonlat=to_lonlat)
    else:
        output = []
        for geom in poly.geoms:
            hexes = poly2hexgrid(geom, resolution=resolution, to_lonlat=to_lonlat)
            output.append(hexes)
        hexagons = pd.concat(output)

    return hexagons.set_crs(
        orig_crs, inplace=True, allow_override=True
    ).drop_duplicates("geometry")