File size: 1,344 Bytes
a3bc68c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
"""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