Search code examples
pythonpolygonshapelyopentripplanner

An empty polygon generated with OpenTripPlanner generates error with .is_empty Shapely instruction


I have an isochron polygon generated with OpenTripPlanner:

{"type":"FeatureCollection","features":[{"type":"Feature","geometry":{"type":"MultiPolygon","coordinates":[]},"properties":{"time":-47},"id":"fid--576b228b_15b66d32d71_-7cbd"}]}

This polygon is translated as a Shapely object with the following instruction:

isochrone = shapely.geometry.asShape(isochroneJSON['features'][0]['geometry'])

This is how it looks like in Spyder:

{u'type': u'FeatureCollection', u'features': [{u'geometry': {u'type': u'MultiPolygon', u'coordinates': []}, u'type': u'Feature', u'properties': {u'time': -47}, u'id': u'fid--576b228b_15b66d32d71_-7a54'}]}

It really looks like an empty polygon to me. My problem is that I want to exclude it from the rest of my treatment and to check if it is valid and/or empty. And the following instruction:

if not isochrone.is_empty:

Generates an error with .is_empty shapely instruction:

return (self._geom is None) or bool(self.impl['is_empty'](self))
self.__geom__, n = self.factory(self.context)

And I am completely lost because the only similar question seems to not have my own problem.


Solution

  • Empty geometries are a bit tricky, in your particular case (MultiPolygons), you could partially fix it by using shape instead of asShape:

    import json
    from shapely.geometry import MultiPolygon, shape, mapping, asShape
    
    Q = shape({'type': 'MultiPolygon', 'coordinates': []})
    print(Q.is_empty)
    print(Q.geom_type)
    print(json.dumps(mapping(Q)))
    

    this outputs (the geom_type is in the case of empty multipolygon indeed not equal to MultiPolygon):

    True
    GeometryCollection
    {"type": "MultiPolygon", "coordinates": []}