Fixing GEOSException: IllegalArgumentException: Argument must be Polygonal or LinearRing

Brendan Ashworth

October 26, 2022

This exception is a really annoying error I get occasionally when entering sometimes invalid shapely.geometry objects into shapely functions:

GEOSException: IllegalArgumentException:
    Argument must be Polygonal or LinearRing

I solved this by uninstalling pygeos and installing Rtree (we use Rtree==1.0.1):

$ pip uninstall pygeos
$ pip install Rtree

Downsides of substituting Rtree for pygeos

Rtree is not a complete replacement for pygeos because the geopandas spatial index does not use the same argument format for gdf.sindex.nearest() queries.

This behavior is documented on the geopandas SpatialIndex page:

nearest currently only works with PyGEOS >= 0.10.

Note that if PyGEOS is not available, geopandas will use rtree for the spatial index, where nearest has a different function signature to temporarily preserve existing functionality. See the documentation of rtree.index.Index.nearest() for the details on the rtree-based implementation.

Documentation on the rtree.index.Index.nearest() argument formats can be found on the rtree readthedocs.

Syntax difference with rtree's nearest()

While the pygeos nearest() function takes in shapely.geometry objects, the Rtree nearest() function only takes in arrays of coordinates:

from rtree import index

idx = index.Index()

idx.insert(4321, (34.37, 26.73, 49.37, 41.73), obj=42)

hits = idx.nearest((0, 0, 10, 10), 3, objects=True)