def intersecting_polygon(p1, p2): poly_1 = Polygon(p1) poly_2 = Polygon(p2) # if poly_1.intersects(poly_2.buffer(SHAPELY_EPSILON_BUFFER)): try: # if poly_1.relate_pattern(poly_2, "2********"): if poly_1.relate_pattern(poly_2, "2********"): # Buffer trick: http://stackoverflow.com/questions/20833344/fix-invalid-polygon-python-shapely intersection = poly_1.intersection(poly_2) if intersection.area < SHAPELY_AREA_LOWER_LIMIT: print("Intersection area too small") return None if isinstance(intersection, MultiPolygon): # print ("Multipolygon intersection") interiors = [ inter.coords for poly in intersection for inter in poly.interiors ] if interiors: log.info("Interiors: " + str(interiors)) return [poly.exterior.coords for poly in intersection] if isinstance(intersection, Polygon): return [intersection.exterior.coords] else: log.debug("No intersection!") return None else: return None except Exception as e: log.error("Error in intersection with polygons".format(e.message), exception=e) log.info(poly_1) log.info(poly_2) return None
def test_relate_pattern(self): # a pair of partially overlapping polygons, and a nearby point g1 = Polygon([(0, 0), (0, 1), (3, 1), (3, 0), (0, 0)]) g2 = Polygon([(1, -1), (1, 2), (2, 2), (2, -1), (1, -1)]) g3 = Point(5, 5) assert(g1.relate(g2) == '212101212') assert(g1.relate_pattern(g2, '212101212')) assert(g1.relate_pattern(g2, '*********')) assert(g1.relate_pattern(g2, '2********')) assert(g1.relate_pattern(g2, 'T********')) assert(not g1.relate_pattern(g2, '112101212')) assert(not g1.relate_pattern(g2, '1********')) assert(g1.relate_pattern(g3, 'FF2FF10F2')) # an invalid pattern should raise an exception with pytest.raises(PredicateError): g1.relate_pattern(g2, 'fail')