[BUG] H3HexagonLayer can fail for cells close to poles or antimeridian due to h3-py bug in viewport
Context
When plotting H3 cells with H3HexagonLayer, I ran into an error with certain cells, which itself is probably due to a bug in h3(-py). But this is only used for calculation of the viewport in default_h3_viewport, while lonboard can actually plot the data just fine.
Resulting behaviour, error message or logs
Small example:
import pyarrow as pa
import h3
import shapely
from lonboard import Map, H3HexagonLayer
cells = h3.geo_to_cells(shapely.box(0, 0, 170, 80, ccw=True), res=0)
print(len(cells)) # 29
table = pa.table({"h3": pa.array(cells)})
layer = H3HexagonLayer(
table,
get_hexagon=table["h3"],
)
m = Map(layer)
gives ValueError: Non-empty LatLngPoly loops need at least 3 points. coming from h3.cells_to_geo() call in default_h3_viewport.
While trying to create a minimal reproducer, I noticed that it even segfaults in some cases. For example with those two cells near the poles:
table = pa.table({"h3": pa.array(["8001fffffffffff", "8003fffffffffff"])})
The plotting actually works fine. If I disable the default viewport in the code, the first example gives:
Environment
- OS: Ubuntu
- Browser: Firefox
- Lonboard Version: 0.14.0
And h3-py 4.4.1
For fixing this, I was initially going to suggest putting the h3 call in a try/except and also return no viewport if h3 fails (like when it is not installed). That's probably still useful, but of course that doesn't help for the segfaults ..
An alternative is to get the bounds of each cell individually, and taking the min/max of the coordinates, instead of converting to a MultiPolygon first (I can test if that is more robust against those errors, although it might be too slow)
It seems the error is something that is known in h3 and might hopefully be fixed with a next version (eg https://github.com/uber/h3/issues/1049, https://github.com/uber/h3/issues/1103)
The segfault should be fixed in the latest h3-py (https://github.com/uber/h3-py/issues/476, in 4.4.2, I was using 4.4.1)
Thanks for the report. It's unfortunate it's segfaulting. Looking at the linked issue, if the code returns an error we still won't have valid bounds. I suppose it'll be fine to put this in a try/except. The bounds setting isn't really required at all for Lonboard to render; it's just a convenience for setting the map bounds at the start.
Is someone working on this bug? I would like to fix this issue
I think this is an upstream bug in h3-py? I don't think there's anything to work on here in Lonboard.
There was a bug in the upstream C library that is now fixed, and reflected in the new h3-py 4.5.0 release.
That should fix the issues here. And beyond just properly handling the segfault issue (https://github.com/uber/h3-py/issues/476), the new h3.cells_to_geo in v4.5 should work for any valid set of H3 cells. Please let us know if you have any feedback!
Sounds great! I'll close this then