mysociety/mapit — pull request #66 by mhl (2013-06-11 11:59:44+00:00)
Title: Add a function that tries to fix invalid polygons

This helper function tries two techniques mentioned in the
helpful document here:

http://s3.opengeo.org/postgis-power.pdf

(Thanks to Matthew Somerville for pointing that out.)

Those are:

ST_Buffer(geom, 0)

... and

ST_BuildArea(
ST_Union(
'LINESTRING EMPTY;,
ST_ExteriorRing(
'POLYGON((...));
)
)
)

... except that we want to do these without a database
connection, so try to do everything with GEOS functions.
Unfortunately, there isn't an equivalent of ST_BuildArea
available via GEOS, as far as I can tell. ST_BuildArea,
however, begins by using GEOSPolygonize which we can use
via Shapely, and produces good results on simple
examples.

The result returned is that from the first of these
methods that produces a valid polygon whose perimeter
length is within 1% of the original's perimeter length.