Ejemplo n.º 1
0
def convex_hull(
    points: List[Union[Tuple[float, float], List[float],
                       Point]]) -> List[Point]:
    """For given list of points return its convex hull"""
    _at = (tuple, list, Point)  # allowed types
    points = [Point.from_iter(i) for i in points
              if type(i) in _at]  # converts to points

    points.sort(key=lambda p: p.x)  # sort points by x axis
    l_upper = [points[0], points[1]]  # add two leftmost points to L(upper) set

    for i in range(2, len(points)):  # for all other points
        l_upper.append(points[i])  # add the next point to L set

        # test the last three points in L
        while len(l_upper) > 2 and not _is_right_turn(l_upper[-3], l_upper[-2],
                                                      l_upper[-1]):
            # remove the middle of tested three points when they don't make right turn
            l_upper.pop(-2)

    l_lower = [points[-1],
               points[-2]]  # L(lower) begins with the two rightmost points
    # apply the same algorithm for reversed values
    for i in reversed(range(len(points) - 3)):
        l_lower.append(points[i])
        while len(l_lower) > 2 and not _is_right_turn(l_lower[-3], l_lower[-2],
                                                      l_lower[-1]):
            l_lower.pop(-2)

    # remove the first from lower L as it is the same as the last in the upper L
    # append lower to upper L
    return l_upper + l_lower[1:]
Ejemplo n.º 2
0
def find_intersections_slow(line_segments: List[LineSegment]) -> List[Point]:
    result = set()
    for i in range(len(line_segments)):
        for ls in line_segments[i + 1:]:
            intersection = LineSegment.intersection(ls, line_segments[i])
            if intersection:
                result.add((intersection.x, intersection.y))
    return [Point.from_iter(i) for i in result]
Ejemplo n.º 3
0
    print(status)
    print()

    del q[event_point.key]
    step += 1

plt_line_segments(line_segments)
plt.scatter([p.x for p in result], [p.y for p in result], c='k')
plt.title("Sweep line algorithm")
plt.axis([-r, r, -r, r])
if legend:
    plt.legend(fancybox=True, framealpha=0.3)
plt.show()

print("=============\nSLOW ALGORITHM")
intersections = [Point.from_iter(i) for i in intersections]
print("Number of intersections:", len(intersections))
print(intersections)

print("\nSWEEP LINE ALGORITHM")
print("Number of intersections:", len(result))
print(result)

print("\nSWEEP LINE ALGORITHM (SOURCE)")
fi = find_intersections(line_segments)
print("Number of intersections:", len(fi))
print(fi)

# the current result and result from the slow algorithm and result from imported algorithm
assert sorted(result) == sorted(intersections) == sorted(fi)