Skip to content

Commit

Permalink
Merge pull request #218 from martinfleis/h3
Browse files Browse the repository at this point in the history
COMPAT: compatibility with h3 v4
  • Loading branch information
knaaptime authored Oct 21, 2024
2 parents 915d882 + f6fe42d commit 0963243
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 13 deletions.
2 changes: 1 addition & 1 deletion ci/310.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,6 @@ dependencies:
- coverage
- twine
- pip
- h3-py
- h3-py<4
- joblib
- astropy
38 changes: 26 additions & 12 deletions tobler/util/util.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,14 @@ def h3fy(source, resolution=6, clip=False, buffer=False, return_geoms=True):
if `return_geoms` is True, a geopandas.GeoDataFrame whose rows comprise a hexagonal h3 grid (indexed on h3 hex id).
if `return_geoms` is False, a pandas.Series of h3 hexagon ids
"""
try:
import h3
except ImportError as err:
raise ImportError(
"This function requires the `h3` library. "
"You can install it with `conda install h3-py` or "
"`pip install h3`"
) from err
# h3 hexes only work on polygons, not multipolygons
if source.crs is None:
raise ValueError(
Expand Down Expand Up @@ -189,30 +197,36 @@ def _to_hex(source, resolution=6, return_geoms=True, buffer=True):
"""
try:
import h3
except ImportError:
except ImportError as err:
raise ImportError(
"This function requires the `h3` library. "
"You can install it with `conda install h3-py` or "
"`pip install h3`"
)
) from err

if Version(h3.__version__) > Version("4.0"):
polyfill = h3.geo_to_cells
kwargs = {}
else:
polyfill = h3.polyfill
kwargs = dict(geo_json_conformant=True)

hexids = pandas.Series(
list(
h3.polyfill(
source.__geo_interface__,
resolution,
geo_json_conformant=True,
)
),
list(polyfill(source.__geo_interface__, resolution, **kwargs)),
name="hex_id",
)

if not return_geoms:
return hexids

polys = hexids.apply(
lambda hex_id: Polygon(h3.h3_to_geo_boundary(hex_id, geo_json=True)),
)
if Version(h3.__version__) > Version("4.0"):
polys = hexids.apply(
lambda hex_id: shapely.geometry.shape(h3.cells_to_geo([hex_id])),
)
else:
polys = hexids.apply(
lambda hex_id: Polygon(h3.h3_to_geo_boundary(hex_id, geo_json=True)),
)

hexs = geopandas.GeoDataFrame(hexids, geometry=polys.values, crs=4326).set_index(
"hex_id"
Expand Down

0 comments on commit 0963243

Please sign in to comment.