""" Тріангуляція Делоне (алгоритм Боуєра–Ватсона) у поєднанні з діаграмою Вороного. Діаграма Вороного будується як двоїста структура до тріангуляції Делоне. Потрібно: pip install matplotlib """ import math import random import matplotlib.pyplot as plt EPS = 1e-12 def circumcircle(a, b, c): """Повертає центр описаного кола трикутника abc та квадрат його радіуса.""" ax, ay = a bx, by = b cx, cy = c d = 2 * (ax * (by - cy) + bx * (cy - ay) + cx * (ay - by)) if abs(d) < EPS: # точки колінеарні return None, float("inf") a2, b2, c2 = ax**2 + ay**2, bx**2 + by**2, cx**2 + cy**2 ux = (a2 * (by - cy) + b2 * (cy - ay) + c2 * (ay - by)) / d uy = (a2 * (cx - bx) + b2 * (ax - cx) + c2 * (bx - ax)) / d return (ux, uy), (ax - ux) ** 2 + (ay - uy) ** 2 def delaunay(points): """Алгоритм Боуєра–Ватсона. Повертає список трикутників (трійки індексів).""" pts = list(points) n = len(pts) # Супертрикутник, що гарантовано містить усі точки xs, ys = [p[0] for p in pts], [p[1] for p in pts] min_x, max_x, min_y, max_y = min(xs), max(xs), min(ys), max(ys) dm = max(max_x - min_x, max_y - min_y, 1.0) * 20 mx, my = (min_x + max_x) / 2, (min_y + max_y) / 2 pts += [(mx - dm, my - dm), (mx, my + dm), (mx + dm, my - dm)] triangles = [(n, n + 1, n + 2)] circles = {triangles[0]: circumcircle(*(pts[i] for i in triangles[0]))} for i in range(n): p = pts[i] # 1. "Погані" трикутники: точка всередині їхнього описаного кола bad = [] for t in triangles: center, r2 = circles[t] if center is not None and (p[0] - center[0]) ** 2 + (p[1] - center[1]) ** 2 < r2 - EPS: bad.append(t) # 2. Межа порожнини: ребра, що належать лише одному поганому трикутнику edge_count = {} for t in bad: for e in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0])): key = tuple(sorted(e)) edge_count[key] = edge_count.get(key, 0) + 1 boundary = [e for e, c in edge_count.items() if c == 1] # 3. Видаляємо погані трикутники і з'єднуємо нову точку з межею for t in bad: triangles.remove(t) del circles[t] for a, b in boundary: t = (a, b, i) triangles.append(t) circles[t] = circumcircle(pts[a], pts[b], pts[i]) # 4. Видаляємо трикутники, пов'язані з вершинами супертрикутника return [t for t in triangles if max(t) < n] def voronoi_from_delaunay(points, triangles, ray_length=1000): """Будує ребра діаграми Вороного з тріангуляції Делоне.""" centers = {t: circumcircle(*(points[i] for i in t))[0] for t in triangles} edge_tris = {} for t in triangles: for e in ((t[0], t[1]), (t[1], t[2]), (t[2], t[0])): edge_tris.setdefault(tuple(sorted(e)), []).append(t) segments = [] for (a, b), tris in edge_tris.items(): if len(tris) == 2: # внутрішнє ребро: з'єднуємо центри описаних кіл c1, c2 = centers[tris[0]], centers[tris[1]] if c1 and c2: segments.append((c1, c2)) else: # крайове ребро: промінь назовні t = tris[0] c = centers[t] if c is None: continue third = [v for v in t if v not in (a, b)][0] (ax, ay), (bx, by) = points[a], points[b] mid = ((ax + bx) / 2, (ay + by) / 2) nx, ny = -(by - ay), bx - ax # перпендикуляр до ребра tx, ty = points[third] if nx * (tx - mid[0]) + ny * (ty - mid[1]) > 0: nx, ny = -nx, -ny # напрямок від третьої вершини (назовні) length = math.hypot(nx, ny) end = (c[0] + nx / length * ray_length, c[1] + ny / length * ray_length) segments.append((c, end)) return segments, list(centers.values()) def read_points(): try: n = int(input("Кількість точок (за замовчуванням 7): ") or 7) except ValueError: n = 7 if n < 3: raise SystemExit("Потрібно щонайменше 3 точки.") mode = input("Ввести точки вручну? (y/N): ").strip().lower() points = [] if mode == "y": for i in range(n): x, y = map(float, input(f"Точка {i + 1} (x y): ").replace(",", " ").split()) points.append((x, y)) else: points = [(round(random.uniform(0, 10), 2), round(random.uniform(0, 10), 2)) for _ in range(n)] points = list(dict.fromkeys(points)) # видалення дублікатів return points def plot(points, triangles, segments, centers): fig, axes = plt.subplots(1, 3, figsize=(18, 6)) titles = ["Тріангуляція Делоне", "Діаграма Вороного", "Делоне + Вороний"] xs, ys = [p[0] for p in points], [p[1] for p in points] pad = (max(max(xs) - min(xs), max(ys) - min(ys)) or 1) * 0.3 for k, ax in enumerate(axes): if k in (0, 2): for t in triangles: poly = [points[i] for i in t] + [points[t[0]]] ax.plot(*zip(*poly), color="tab:blue", lw=1.5) if k in (1, 2): for p1, p2 in segments: ax.plot([p1[0], p2[0]], [p1[1], p2[1]], color="tab:red", lw=1.5, ls="--" if k == 2 else "-") cx = [c[0] for c in centers if c] cy = [c[1] for c in centers if c] ax.scatter(cx, cy, color="tab:red", s=20, zorder=3) ax.scatter(xs, ys, color="black", s=40, zorder=4) for i, (x, y) in enumerate(points): ax.annotate(f"P{i + 1}", (x, y), textcoords="offset points", xytext=(5, 5)) ax.set_xlim(min(xs) - pad, max(xs) + pad) ax.set_ylim(min(ys) - pad, max(ys) + pad) ax.set_aspect("equal") ax.grid(alpha=0.3) ax.set_title(titles[k]) plt.tight_layout() plt.show() def main(): points = read_points() triangles = delaunay(points) if not triangles: raise SystemExit("Тріангуляцію побудувати неможливо (точки колінеарні).") segments, centers = voronoi_from_delaunay(points, triangles) print("\nТочки:") for i, p in enumerate(points): print(f" P{i + 1} = {p}") print(f"\nТрикутники Делоне ({len(triangles)}):") for t in triangles: c, r2 = circumcircle(*(points[i] for i in t)) print(f" P{t[0] + 1}-P{t[1] + 1}-P{t[2] + 1}; центр кола = " f"({c[0]:.2f}, {c[1]:.2f}), R = {math.sqrt(r2):.2f}") print(f"\nРебер діаграми Вороного: {len(segments)}") plot(points, triangles, segments, centers) if __name__ == "__main__": main()