Skip to content

ENH: Implement a "finer polyfill" #6

@DahnJ

Description

@DahnJ

A common use-case is to generate all hexagons that intersect with a given polygon. That's not straightforward to do using H3.

One approximate solution is to first generate a finer resolution grid using polyfill and then return to the desired resolution using h3_to_parent.

The H3-Pandas API could thus contain a convenience function that performs both of these operations in a single pass.

A quick demonstration of the idea:

import geopandas as gpd
import h3pandas

gdf = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

# Resample to H3 cells
gdf = gdf.h3.polyfill_resample(4)
gdf = gdf.h3.h3_to_parent_aggregate(2)

Sidenote

The above code yields a "strange" result:

image

This is because a number of the hexagons cross the anti-meridian, and get rendered wrongly. Since this case might be reasonably common, H3-Pandas could perhaps provide a fix, something like

import numpy as np
from shapely.geometry import Polygon

def fix(cell):
    cell_coords = np.array(cell.boundary.coords)
    lngs = cell_coords[:, 0]
    if not (np.any(lngs < 0) and np.any(lngs > 0)) or not (np.any(np.abs(lngs) > 170)):
        return cell
    
    negative = lngs < 0
    lngs[negative] = lngs[negative] + 360
    return Polygon(cell_coords)

Applying the fix to the dataframe's geometries

gdf['geometry'] = gdf['geometry'].apply(fix)

fixes the visual output

image

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions