Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: Update to H3 version 4 #37

Merged
merged 1 commit into from
Mar 2, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 1 addition & 4 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,8 @@ dependencies:
- shapely
- geopandas>=0.9.*
- pandas
- h3-py>=4
# Notebooks
- matplotlib
# Pip
- pip
- pip:
# Installing through pip to avoid segfault on Apple Silicon
# https://github.com/uber/h3-py/issues/313
- h3==3.7.6
38 changes: 18 additions & 20 deletions h3pandas/h3pandas.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,14 +8,14 @@
import pandas as pd
import geopandas as gpd

from h3 import h3
import h3
from pandas.core.frame import DataFrame
from geopandas.geodataframe import GeoDataFrame

from .const import COLUMN_H3_POLYFILL, COLUMN_H3_LINETRACE
from .util.decorator import catch_invalid_h3_address, doc_standard
from .util.functools import wrapped_partial
from .util.shapely import polyfill, linetrace
from .util.shapely import cell_to_boundary_lng_lat, polyfill, linetrace, _switch_lat_lng

AnyDataFrame = Union[DataFrame, GeoDataFrame]

Expand Down Expand Up @@ -92,7 +92,7 @@ def geo_to_h3(
lats = self._df[lat_col]

h3addresses = [
h3.geo_to_h3(lat, lng, resolution) for lat, lng in zip(lats, lngs)
h3.latlng_to_cell(lat, lng, resolution) for lat, lng in zip(lats, lngs)
]

colname = self._format_resolution(resolution)
Expand Down Expand Up @@ -130,9 +130,9 @@ def h3_to_geo(self) -> GeoDataFrame:

"""
return self._apply_index_assign(
h3.h3_to_geo,
h3.cell_to_latlng,
"geometry",
lambda x: shapely.geometry.Point(reversed(x)),
lambda x: _switch_lat_lng(shapely.geometry.Point(x)),
lambda x: gpd.GeoDataFrame(x, crs="epsg:4326"),
)

Expand All @@ -158,10 +158,9 @@ def h3_to_geo_boundary(self) -> GeoDataFrame:
881e2659c3fffff 1 POLYGON ((14.99201 51.00565, 14.98973 51.00133...
"""
return self._apply_index_assign(
wrapped_partial(h3.h3_to_geo_boundary, geo_json=True),
wrapped_partial(cell_to_boundary_lng_lat),
"geometry",
lambda x: shapely.geometry.Polygon(x),
lambda x: gpd.GeoDataFrame(x, crs="epsg:4326"),
finalizer=lambda x: gpd.GeoDataFrame(x, crs="epsg:4326"),
)

@doc_standard("h3_resolution", "containing the resolution of each H3 address")
Expand All @@ -176,7 +175,7 @@ def h3_get_resolution(self) -> AnyDataFrame:
881e309739fffff 5 8
881e2659c3fffff 1 8
"""
return self._apply_index_assign(h3.h3_get_resolution, "h3_resolution")
return self._apply_index_assign(h3.get_resolution, "h3_resolution")

@doc_standard("h3_base_cell", "containing the base cell of each H3 address")
def h3_get_base_cell(self):
Expand All @@ -190,7 +189,7 @@ def h3_get_base_cell(self):
881e309739fffff 5 15
881e2659c3fffff 1 15
"""
return self._apply_index_assign(h3.h3_get_base_cell, "h3_base_cell")
return self._apply_index_assign(h3.get_base_cell_number, "h3_base_cell")

@doc_standard("h3_is_valid", "containing the validity of each H3 address")
def h3_is_valid(self):
Expand All @@ -203,7 +202,7 @@ def h3_is_valid(self):
881e309739fffff 5 True
INVALID 1 False
"""
return self._apply_index_assign(h3.h3_is_valid, "h3_is_valid")
return self._apply_index_assign(h3.is_valid_cell, "h3_is_valid")

@doc_standard(
"h3_k_ring", "containing a list H3 addresses within a distance of `k`"
Expand Down Expand Up @@ -250,7 +249,7 @@ def k_ring(self, k: int = 1, explode: bool = False) -> AnyDataFrame:
881e309739fffff 5 881e309739fffff
881e309739fffff 5 881e309731fffff
"""
func = wrapped_partial(h3.k_ring, k=k)
func = wrapped_partial(h3.grid_disk, k=k)
column_name = "h3_k_ring"
if explode:
return self._apply_index_explode(func, column_name, list)
Expand Down Expand Up @@ -295,7 +294,7 @@ def hex_ring(self, k: int = 1, explode: bool = False) -> AnyDataFrame:
881e309739fffff 5 881e309715fffff
881e309739fffff 5 881e309731fffff
"""
func = wrapped_partial(h3.hex_ring, k=k)
func = wrapped_partial(h3.grid_ring, k=k)
column_name = "h3_hex_ring"
if explode:
return self._apply_index_explode(func, column_name, list)
Expand Down Expand Up @@ -330,7 +329,7 @@ def h3_to_parent(self, resolution: int = None) -> AnyDataFrame:
else "h3_parent"
)
return self._apply_index_assign(
wrapped_partial(h3.h3_to_parent, res=resolution), column
wrapped_partial(h3.cell_to_parent, res=resolution), column
)

@doc_standard("h3_center_child", "containing the center child of each H3 address")
Expand All @@ -352,7 +351,7 @@ def h3_to_center_child(self, resolution: int = None) -> AnyDataFrame:
881e2659c3fffff 1 891e2659c23ffff
"""
return self._apply_index_assign(
wrapped_partial(h3.h3_to_center_child, res=resolution), "h3_center_child"
wrapped_partial(h3.cell_to_center_child, res=resolution), "h3_center_child"
)

@doc_standard(
Expand Down Expand Up @@ -395,7 +394,7 @@ def polyfill(self, resolution: int, explode: bool = False) -> AnyDataFrame:
"""

def func(row):
return list(polyfill(row.geometry, resolution, True))
return list(polyfill(row.geometry, resolution))

result = self._df.apply(func, axis=1)

Expand Down Expand Up @@ -553,7 +552,7 @@ def h3_to_parent_aggregate(
811e3ffffffffff 6
"""
parent_h3addresses = [
catch_invalid_h3_address(h3.h3_to_parent)(h3address, resolution)
catch_invalid_h3_address(h3.cell_to_parent)(h3address, resolution)
for h3address in self._df.index
]
h3_parent_column = self._format_resolution(resolution)
Expand Down Expand Up @@ -758,9 +757,7 @@ def polyfill_resample(

return result.h3.h3_to_geo_boundary() if return_geometry else result

def linetrace(
self, resolution : int, explode: bool = False
) -> AnyDataFrame:
def linetrace(self, resolution: int, explode: bool = False) -> AnyDataFrame:
"""Experimental. An H3 cell representation of a (Multi)LineString,
which permits repeated cells, but not if they are repeated in
immediate sequence.
Expand Down Expand Up @@ -792,6 +789,7 @@ def linetrace(
0 LINESTRING (0.00000 0.00000, 1.00000 0.00000, ... 837541fffffffff

"""

def func(row):
return list(linetrace(row.geometry, resolution))

Expand Down
5 changes: 3 additions & 2 deletions h3pandas/util/decorator.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from functools import wraps
from typing import Callable, Iterator
from h3 import H3CellError


def catch_invalid_h3_address(f: Callable) -> Callable:
Expand All @@ -25,7 +24,7 @@ def catch_invalid_h3_address(f: Callable) -> Callable:
def safe_f(*args, **kwargs):
try:
return f(*args, **kwargs)
except (TypeError, ValueError, H3CellError) as e:
except (TypeError, ValueError) as e:
message = "H3 method raised an error. Is the H3 address correct?"
message += f"\nCaller: {f.__name__}({_print_signature(*args, **kwargs)})"
message += f"\nOriginal error: {repr(e)}"
Expand All @@ -47,13 +46,15 @@ def sequential_deduplication(func: Iterator[str]) -> Iterator[str]:
-------
Yields from f, but won't yield two items in a row that are the same.
"""

def inner(*args):
iterable = func(*args)
last = None
while (cell := next(iterable, None)) is not None:
if cell != last:
yield cell
last = cell

return inner


Expand Down
72 changes: 42 additions & 30 deletions h3pandas/util/shapely.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,15 @@
from typing import Union, Set, Tuple, List, Iterator
from typing import Union, Set, Iterator
from shapely.geometry import Polygon, MultiPolygon, LineString, MultiLineString
from h3 import h3
from shapely.ops import transform
import h3
from .decorator import sequential_deduplication


MultiPolyOrPoly = Union[Polygon, MultiPolygon]
MultiLineOrLine = Union[LineString, MultiLineString]


def _extract_coords(polygon: Polygon) -> Tuple[List, List[List]]:
"""Extract the coordinates of outer and inner rings from a Polygon"""
outer = list(polygon.exterior.coords)
inners = [list(g.coords) for g in polygon.interiors]
return outer, inners


def polyfill(
geometry: MultiPolyOrPoly, resolution: int, geo_json: bool = False
) -> Set[str]:
def polyfill(geometry: MultiPolyOrPoly, resolution: int) -> Set[str]:
"""h3.polyfill accepting a shapely (Multi)Polygon

Parameters
Expand All @@ -25,8 +18,6 @@ def polyfill(
Polygon to fill
resolution : int
H3 resolution of the filling cells
geo_json : bool
If True, coordinates are assumed to be lng/lat. Default: False (lat/lng)

Returns
-------
Expand All @@ -36,24 +27,45 @@ def polyfill(
------
TypeError if geometry is not a Polygon or MultiPolygon
"""
if isinstance(geometry, Polygon):
outer, inners = _extract_coords(geometry)
return h3.polyfill_polygon(outer, resolution, inners, geo_json)

elif isinstance(geometry, MultiPolygon):
h3_addresses = []
for poly in geometry.geoms:
h3_addresses.extend(polyfill(poly, resolution, geo_json))

return set(h3_addresses)
if isinstance(geometry, (Polygon, MultiPolygon)):
h3shape = h3.geo_to_h3shape(geometry)
return set(h3.polygon_to_cells(h3shape, resolution))
else:
raise TypeError(f"Unknown type {type(geometry)}")


def cell_to_boundary_lng_lat(h3_address: str) -> MultiLineString:
"""h3.h3_to_geo_boundary equivalent for shapely

Parameters
----------
h3_address : str
H3 address to convert to a boundary

Returns
-------
MultiLineString representing the H3 cell boundary
"""
return _switch_lat_lng(Polygon(h3.cell_to_boundary(h3_address)))


def _switch_lat_lng(geometry: MultiPolyOrPoly) -> MultiPolyOrPoly:
"""Switches the order of coordinates in a Polygon or MultiPolygon

Parameters
----------
geometry : Polygon or Multipolygon
Polygon to switch coordinates

Returns
-------
Polygon or Multipolygon with switched coordinates
"""
return transform(lambda x, y: (y, x), geometry)


@sequential_deduplication
def linetrace(
geometry: MultiLineOrLine, resolution: int
) -> Iterator[str]:
def linetrace(geometry: MultiLineOrLine, resolution: int) -> Iterator[str]:
"""h3.polyfill equivalent for shapely (Multi)LineString
Does not represent lines with duplicate sequential cells,
but cells may repeat non-sequentially to represent
Expand Down Expand Up @@ -82,8 +94,8 @@ def linetrace(
coords = zip(geometry.coords, geometry.coords[1:])
while (vertex_pair := next(coords, None)) is not None:
i, j = vertex_pair
a = h3.geo_to_h3(*i[::-1], resolution)
b = h3.geo_to_h3(*j[::-1], resolution)
yield from h3.h3_line(a, b) # inclusive of a and b
a = h3.latlng_to_cell(*i[::-1], resolution)
b = h3.latlng_to_cell(*j[::-1], resolution)
yield from h3.grid_path_cells(a, b) # inclusive of a and b
else:
raise TypeError(f"Unknown type {type(geometry)}")
Loading
Loading