Shapely的`almost_equals`函数是如何处理起点和错误的?

How does `almost_equals` function of Shapely treat the starting point and errors?

这些多边形具有相同的一组点,但起点不同 points/rounding 错误,但方向仍然相同。

poly1 = Polygon([(0,0),(0,1),(1,1),(1,0)])
poly2 = Polygon([(0,1),(1,1),(1,0),(0,0)])
poly3 = Polygon([(0,1),(1,1.00000001),(1,0),(0,0)])
poly4 = Polygon([(0,0),(0,1),(1,1.00000001),(1,0)])

问题 1:poly1.almost_equals(poly2)returnsFalsepoly1.equals(poly2)returnsTrue。所以 equals 可以处理不同的起点,但 almost_equals 不能。

问题 2:poly1.almost_equals(poly3)returnsFalsepoly1.almost_equals(poly4)returnsTrue。所以 almost_equals 可以处理舍入错误但仍然没有不同的起点。

这就是 almost_equals 函数的行为方式吗?我认为起点不同的多边形仍然是同一个多边形,应该这样对待。有没有方便的方法来解决这个问题?我有一个复杂的自定义解决方案,但想知道是否已在 Shapely 中实现了此类操作。

是的,这是预期的行为。函数的the documentation but you can find it in the docstring中没有明确说明:

def almost_equals(self, other, decimal=6):
    """Returns True if geometries are equal at all coordinates to a
    specified decimal place

    Refers to approximate coordinate equality, which requires coordinates be
    approximately equal and in the same order for all components of a geometry.
    """
    return self.equals_exact(other, 0.5 * 10**(-decimal))

目前,没有任何其他功能可以用来解决您的问题。 GitHub 上有一个 open issue,其中讨论了 almost_equals 的未来。因此,可能很快就会引入一个新的方便的功能。同时,您可以使用几种解决方法:

  1. 计算两个多边形的 symmetric_difference 并将结果面积与某个最小阈值进行比较。
    例如。:
    def almost_equals(polygon, other, threshold):
        # or (polygon ^ other).area < threshold
        return polygon.symmetric_difference(other).area < threshold
    
    almost_equals(poly1, poly3, 1e-6)  # True
    
  2. 首先对两个多边形进行归一化,然后使用 almost_equals。例如,要对它们进行标准化,您可以 orient 边界的顶点 counter-clockwise 然后对顶点进行排序,以便与其他顶点相比,每个多边形的第一个顶点将是最低和最左边的。
    例如。:
    from shapely.geometry.polygon import orient
    
    
    def normalize(polygon):
    
        def normalize_ring(ring):
            coords = ring.coords[:-1]
            start_index = min(range(len(coords)), key=coords.__getitem__)
            return coords[start_index:] + coords[:start_index]
    
        polygon = orient(polygon)
        normalized_exterior = normalize_ring(polygon.exterior)
        normalized_interiors = list(map(normalize_ring, polygon.interiors))
        return Polygon(normalized_exterior, normalized_interiors)
    
    
    normalize(poly1).almost_equals(normalize(poly3))  # True