"""Kernel 1: line-line intersection by exact Cramer solution of a 2x2 system.""" from __future__ import annotations from dataclasses import dataclass from fractions import Fraction from typing import Optional from .common import Line, NoSolutionError, Point @dataclass(frozen=True) class LineIntersection: """Outcome of intersecting two lines. kind is "point" (unique common point), "parallel" (no common point) or "coincident" (the two lines are equal). """ kind: str point: Optional[Point] determinant: Fraction def intersect_lines(l1: Line, l2: Line) -> LineIntersection: """Solve a1 x + b1 y = -c1, a2 x + b2 y = -c2 exactly.""" det = l1.a * l2.b - l2.a * l1.b if det == 0: if l1.a * l2.c - l2.a * l1.c == 0 and l1.b * l2.c - l2.b * l1.c == 0: return LineIntersection("coincident", None, det) return LineIntersection("parallel", None, det) x = (l1.b * l2.c - l2.b * l1.c) / det y = (l2.a * l1.c - l1.a * l2.c) / det return LineIntersection("point", Point(x, y), det) def intersection_point(l1: Line, l2: Line) -> Point: """Return the unique common point or raise NoSolutionError.""" res = intersect_lines(l1, l2) if res.point is None: raise NoSolutionError("lines are %s: no unique intersection" % res.kind) return res.point