Fix invalid polygon in Shapely Fix invalid polygon in Shapely python python

Fix invalid polygon in Shapely


I found a solution that works for the specific case given:

>>> pp2 = pp.buffer(0)>>> pp2.is_validTrue>>> pp2.exterior.coords[:][(0.0, 0.0), (0.0, 3.0), (3.0, 3.0), (3.0, 0.0), (2.0, 0.0), (0.0, 0.0)]>>> pp2.interiors[0].coords[:][(2.0, 1.0), (2.0, 2.0), (1.0, 2.0), (1.0, 1.0), (2.0, 1.0)]


Untested, but it appears that Shapely have added a function to support this now.

https://shapely.readthedocs.io/en/latest/manual.html#validation.make_valid


Shapely implemented a solution for this matter. Through pip you can use shapely 1.8a3 version and import this way:

from shapely.validation import make_valid

Unfortunately, if you have had to install other libraries via conda such as geopandas you will probably face a dependency problem because at this point conda only offers shapely 1.7.1 version. So you can use the shapely solution at your program as shown below:

def make_valid(ob):

from shapely.geometry.base import geom_factoryfrom shapely.geos import lgeosif ob.is_valid:    return obreturn geom_factory(lgeos.GEOSMakeValid(ob._geom))