BerGeo/h2/quick_hull.py

72 lines
1.8 KiB
Python
Raw Normal View History

2018-09-20 14:59:42 +00:00
from math import sqrt
2018-09-20 13:44:39 +00:00
from typing import Set
2018-10-18 16:41:18 +00:00
from profile import Profiler
2018-10-09 17:26:55 +00:00
from util import Point, gen_point, display
2018-09-20 12:50:16 +00:00
2018-09-20 13:44:39 +00:00
def distance(a, b, c):
2018-09-20 14:54:47 +00:00
nom = abs((b.y - a.y) * c.x - (b.x - a.x) * c.y + b.x * a.y - b.y * a.x)
den = sqrt((b.y - a.y) ** 2 + (b.x - a.x) ** 2)
return nom / den
2018-09-20 12:50:16 +00:00
2018-09-20 13:44:39 +00:00
def is_left(a: Point, b: Point, c: Point):
return ((b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)) > 0
2018-09-20 12:50:16 +00:00
2018-10-18 16:41:18 +00:00
@Profiler("quick_hull")
2018-09-20 13:44:39 +00:00
def quick_hull(points: Set[Point]):
left = min(points)
right = max(points)
2018-09-20 12:50:16 +00:00
2018-09-20 13:44:39 +00:00
hull = {left, right}
2018-09-20 13:58:02 +00:00
points = points - hull
2018-09-20 12:50:16 +00:00
2018-10-18 16:41:18 +00:00
with Profiler("partitioning set"):
partition = {p for p in points if not is_left(left, right, p)}
find_hull(partition,
2018-09-20 13:44:39 +00:00
left,
right,
hull)
2018-09-20 12:50:16 +00:00
2018-10-18 16:41:18 +00:00
with Profiler("partitioning set"):
partition = {p for p in points if not is_left(right, left, p)}
find_hull(partition,
2018-09-20 13:44:39 +00:00
right,
left,
hull)
2018-09-20 12:50:16 +00:00
2018-09-20 13:44:39 +00:00
return hull
2018-09-20 12:50:16 +00:00
2018-09-20 13:44:39 +00:00
def find_hull(points: Set[Point], p: Point, q: Point, hull: Set[Point]):
if not points:
return
2018-09-20 12:50:16 +00:00
2018-10-18 16:41:18 +00:00
with Profiler("finding farthest point from line"):
farthest = max(points, key=lambda point: abs(distance(p, q, point)))
hull.add(farthest)
points.remove(farthest)
2018-09-20 12:50:16 +00:00
2018-10-18 16:41:18 +00:00
with Profiler("partitioning set"):
partition = {po for po in points if not is_left(p, farthest, po)}
find_hull(partition,
2018-09-20 14:54:47 +00:00
p,
farthest,
hull)
2018-09-20 12:50:16 +00:00
2018-10-18 16:41:18 +00:00
with Profiler("partitioning set"):
partition = {po for po in points if not is_left(farthest, q, po)}
find_hull(partition,
2018-09-20 14:54:47 +00:00
farthest,
q,
hull)
2018-09-20 12:50:16 +00:00
2018-10-11 12:38:59 +00:00
if __name__ == '__main__':
points = {gen_point() for _ in range(30)}
hull = quick_hull(points)
2018-09-20 12:50:16 +00:00
2018-10-11 12:38:59 +00:00
display(points, hull)