How to fix spherical geometry errors caused by conversion from GEOS to s2

5.2k views Asked by At

I'm having the same problem as How to resolve spherical geometry failures when joining spatial data

My code that used to work now doesn't work with the conversion from GEOS to s2.

I'm not sure how I would create a reproducible example of this error. The sample datasets that come with the sf package work fine with this code since I'm sure they have been updated to work with the s2 pacakge as well. The best

ranges <- st_read("Data/Range maps/PRISM_shorebird_ranges_breeding/PRISM_shorebird_ranges_breeding.shp")

ranges2 <- ranges %>%
  group_by(binomial) %>%
  select(-seasonal, -Shape_Area) %>%
  summarize()

Error in s2_geography_from_wkb(x, oriented = oriented, check = check) : 
  Evaluation error: Found 2 features with invalid spherical geometry.
[1] Loop 0 is not valid: Edge 319 has duplicate vertex with edge 322
[2] Loop 0 is not valid: Edge 53052 has duplicate vertex with edge 53055.

I tried the solutions in How to resolve spherical geometry failures when joining spatial data

You have two options:

1. turn off the s2 processing via sf::sf_use_s2(FALSE) in your script; in theory the behaviour should revert to the one before release 1.0

This worked, but doesn't seem like a good long term solution. Will I keep having this problem with my other code? How to I prevent this from happening and use the updated sf package in it's full functionality?

2. repair the spherical geometry of your polygons object; this will depend on the actual nature of your errors."

ranges$geometry <- ranges$geometry %>%
  s2::s2_rebuild() %>%
  sf::st_as_sfc()

Error in s2_geography_from_wkb(x, oriented = oriented, check = check) : 
  Evaluation error: Found 22 features with invalid spherical geometry.
[1] Loop 2 is not valid: Edge 846 has duplicate vertex with edge 853
[2] Loop 10 is not valid: Edge 0 has duplicate vertex with edge 4
... and 20 more.

As you can see, this solution didn't work for me. How can I fix this spherical geometry error?

1

There are 1 answers

0
Michael Entin On BEST ANSWER

This is not a problem with code, the issue is with data. S2 is just more strict about polygon conformance, and throws this errors when it encounters an invalid polygon.

The polygons here seem to have self-intersection, like

A--B
|  |
D--C--E
   |  |
   G--F

This shape should be described as two polygons, ABCDA and CEFGC. But often it is described as a single polygon ABCEFGCDA (note C is repeated twice) - which probably happened here too. Some libraries would happily accept this, but S2 complains about duplicate vertex C in non-consecutive edges BC and GC.

If you can, fix the data, before loading it. I know PostgreSQL/PostGIS can usually fix these - it would accept the input WKB, and has ST_MakeValid that will split this into multiple polygons. R seem to have st_make_valid https://rdrr.io/cran/sf/man/valid.html too (I don't have personal experience with it).