tailot's picture
geometry corpus with quantified certificates and honest attestations
a3bc68c verified
Raw History Blame Contribute Delete
11.4 kB
"""Exact arithmetic primitives shared by the geometry kernels.
All kernels work over the rationals (fractions.Fraction). Where a square root
is unavoidable the Surd class represents a + b*sqrt(m) in a single quadratic
extension. Floating point input is rejected so that every result is exact.
"""
from __future__ import annotations
import math
from dataclasses import dataclass
from fractions import Fraction
from math import gcd
from typing import List, Optional, Sequence, Union
Scalar = Union[int, Fraction, str]
class GeometryError(ValueError):
"""Base class for every geometric failure raised by the kernels."""
class DegenerateConfigurationError(GeometryError):
"""The input configuration is degenerate (zero determinant, coincident points)."""
class NoSolutionError(GeometryError):
"""The requested object does not exist over the reals."""
def to_fraction(value: Scalar) -> Fraction:
"""Convert an int, Fraction or exact string to Fraction; reject floats."""
if isinstance(value, bool):
raise TypeError("booleans are not valid coordinates")
if isinstance(value, Fraction):
return value
if isinstance(value, int):
return Fraction(value)
if isinstance(value, str):
return Fraction(value.strip())
raise TypeError("exact arithmetic only, got %s" % type(value).__name__)
def fraction_sqrt(q: Fraction) -> Optional[Fraction]:
"""Return the exact square root of q when q is a rational square, else None."""
if q < 0:
return None
n = math.isqrt(q.numerator)
d = math.isqrt(q.denominator)
if n * n == q.numerator and d * d == q.denominator:
return Fraction(n, d)
return None
@dataclass(frozen=True, eq=False)
class Surd:
"""The real number a + b*sqrt(m) with rational a, b and a non-square m > 0.
Rational values are stored canonically with b = 0 and m = 0, so structural
equality coincides with numeric equality inside one radicand.
"""
a: Fraction
b: Fraction = Fraction(0)
m: Fraction = Fraction(0)
@staticmethod
def make(a: Scalar, b: Scalar = 0, m: Scalar = 0) -> "Surd":
a, b, m = to_fraction(a), to_fraction(b), to_fraction(m)
if m < 0:
raise NoSolutionError("negative radicand: no real value")
if b == 0 or m == 0:
return Surd(a, Fraction(0), Fraction(0))
root = fraction_sqrt(m)
if root is not None:
return Surd(a + b * root, Fraction(0), Fraction(0))
return Surd(a, b, m)
@staticmethod
def _coerce(other) -> "Surd":
if isinstance(other, Surd):
return other
return Surd(to_fraction(other))
@staticmethod
def _radicand(x: "Surd", y: "Surd") -> Fraction:
if x.b == 0:
return y.m
if y.b == 0:
return x.m
if x.m != y.m:
raise GeometryError("mixed radicands %s and %s" % (x.m, y.m))
return x.m
@property
def is_rational(self) -> bool:
return self.b == 0
def to_fraction(self) -> Fraction:
if self.b != 0:
raise GeometryError("value is irrational")
return self.a
def __add__(self, other) -> "Surd":
o = Surd._coerce(other)
return Surd.make(self.a + o.a, self.b + o.b, Surd._radicand(self, o))
__radd__ = __add__
def __neg__(self) -> "Surd":
return Surd(-self.a, -self.b, self.m)
def __sub__(self, other) -> "Surd":
return self + (-Surd._coerce(other))
def __rsub__(self, other) -> "Surd":
return Surd._coerce(other) - self
def __mul__(self, other) -> "Surd":
o = Surd._coerce(other)
m = Surd._radicand(self, o)
return Surd.make(self.a * o.a + self.b * o.b * m, self.a * o.b + self.b * o.a, m)
__rmul__ = __mul__
def conjugate(self) -> "Surd":
return Surd(self.a, -self.b, self.m)
def norm(self) -> Fraction:
return self.a * self.a - self.b * self.b * self.m
def __truediv__(self, other) -> "Surd":
o = Surd._coerce(other)
n = o.norm()
if n == 0:
raise DegenerateConfigurationError("division by zero")
num = self * o.conjugate()
return Surd.make(num.a / n, num.b / n, num.m)
def __rtruediv__(self, other) -> "Surd":
return Surd._coerce(other) / self
def sign(self) -> int:
"""Exact sign of the real number."""
if self.b == 0:
return (self.a > 0) - (self.a < 0)
sa = (self.a > 0) - (self.a < 0)
sb = 1 if self.b > 0 else -1
if sa == 0 or sa == sb:
return sb
lhs, rhs = self.a * self.a, self.b * self.b * self.m
if lhs > rhs:
return sa
if lhs < rhs:
return sb
return 0
def __lt__(self, other) -> bool:
return (self - Surd._coerce(other)).sign() < 0
def __le__(self, other) -> bool:
return (self - Surd._coerce(other)).sign() <= 0
def __gt__(self, other) -> bool:
return (self - Surd._coerce(other)).sign() > 0
def __ge__(self, other) -> bool:
return (self - Surd._coerce(other)).sign() >= 0
def __eq__(self, other) -> bool:
if isinstance(other, (int, Fraction)) and not isinstance(other, bool):
return self.b == 0 and self.a == other
if isinstance(other, Surd):
return (self.a, self.b, self.m) == (other.a, other.b, other.m)
return NotImplemented
def __hash__(self) -> int:
if self.b == 0:
return hash(self.a)
return hash((self.a, self.b, self.m))
def __float__(self) -> float:
return float(self.a) + float(self.b) * math.sqrt(float(self.m))
def __str__(self) -> str:
if self.b == 0:
return str(self.a)
mag = abs(self.b)
root = "sqrt(%s)" % self.m if mag == 1 else "%s*sqrt(%s)" % (mag, self.m)
if self.a == 0:
return root if self.b > 0 else "-" + root
return "%s %s %s" % (self.a, "+" if self.b > 0 else "-", root)
def to_json(self):
if self.b == 0:
return str(self.a)
return {"a": str(self.a), "b": str(self.b), "m": str(self.m)}
@dataclass(frozen=True)
class Point:
"""A point of the rational plane."""
x: Fraction
y: Fraction
def __post_init__(self):
object.__setattr__(self, "x", to_fraction(self.x))
object.__setattr__(self, "y", to_fraction(self.y))
def __add__(self, o: "Point") -> "Point":
return Point(self.x + o.x, self.y + o.y)
def __sub__(self, o: "Point") -> "Point":
return Point(self.x - o.x, self.y - o.y)
def scale(self, k: Scalar) -> "Point":
k = to_fraction(k)
return Point(self.x * k, self.y * k)
def dot(self, o: "Point") -> Fraction:
return self.x * o.x + self.y * o.y
def cross(self, o: "Point") -> Fraction:
return self.x * o.y - self.y * o.x
def dist2(self, o: "Point") -> Fraction:
d = self - o
return d.dot(d)
def midpoint(self, o: "Point") -> "Point":
return Point((self.x + o.x) / 2, (self.y + o.y) / 2)
def to_json(self) -> List[str]:
return [str(self.x), str(self.y)]
@dataclass(frozen=True)
class SurdPoint:
"""A point whose coordinates live in one quadratic extension."""
x: Surd
y: Surd
def to_json(self):
return [self.x.to_json(), self.y.to_json()]
@dataclass(frozen=True)
class Line:
"""The line a*x + b*y + c = 0 in canonical integer form."""
a: Fraction
b: Fraction
c: Fraction
def __post_init__(self):
a, b, c = to_fraction(self.a), to_fraction(self.b), to_fraction(self.c)
if a == 0 and b == 0:
raise DegenerateConfigurationError("a line needs a non-zero normal vector")
lcm = 1
for v in (a, b, c):
lcm = lcm * v.denominator // gcd(lcm, v.denominator)
ia, ib, ic = int(a * lcm), int(b * lcm), int(c * lcm)
g = gcd(gcd(abs(ia), abs(ib)), abs(ic)) or 1
ia, ib, ic = ia // g, ib // g, ic // g
if ia < 0 or (ia == 0 and ib < 0):
ia, ib, ic = -ia, -ib, -ic
object.__setattr__(self, "a", Fraction(ia))
object.__setattr__(self, "b", Fraction(ib))
object.__setattr__(self, "c", Fraction(ic))
@staticmethod
def through(p: Point, q: Point) -> "Line":
if p == q:
raise DegenerateConfigurationError("two coincident points do not define a line")
a = p.y - q.y
b = q.x - p.x
return Line(a, b, -(a * p.x + b * p.y))
def contains(self, p: Point) -> bool:
return self.a * p.x + self.b * p.y + self.c == 0
def to_json(self) -> List[str]:
return [str(self.a), str(self.b), str(self.c)]
@dataclass(frozen=True)
class Circle:
"""A circle given by its center and its squared radius."""
center: Point
r2: Fraction
def __post_init__(self):
object.__setattr__(self, "r2", to_fraction(self.r2))
if self.r2 <= 0:
raise DegenerateConfigurationError("the squared radius must be positive")
@property
def radius(self) -> Surd:
return Surd.make(0, 1, self.r2)
def contains(self, p: Point) -> bool:
return p.dist2(self.center) == self.r2
def to_json(self) -> dict:
return {"center": self.center.to_json(), "r2": str(self.r2)}
Matrix = List[List[Fraction]]
def determinant(matrix: Sequence[Sequence[Scalar]]) -> Fraction:
"""Exact determinant by fraction Gaussian elimination."""
n = len(matrix)
m = [[to_fraction(v) for v in row] for row in matrix]
det = Fraction(1)
for col in range(n):
piv = next((r for r in range(col, n) if m[r][col] != 0), None)
if piv is None:
return Fraction(0)
if piv != col:
m[col], m[piv] = m[piv], m[col]
det = -det
det *= m[col][col]
for r in range(col + 1, n):
f = m[r][col] / m[col][col]
if f:
m[r] = [m[r][k] - f * m[col][k] for k in range(n)]
return det
def solve_linear(matrix: Sequence[Sequence[Scalar]], rhs: Sequence[Scalar]) -> List[Fraction]:
"""Solve a square linear system exactly; raise on a singular matrix."""
n = len(matrix)
aug = [[to_fraction(v) for v in row] + [to_fraction(r)] for row, r in zip(matrix, rhs)]
for col in range(n):
piv = next((r for r in range(col, n) if aug[r][col] != 0), None)
if piv is None:
raise DegenerateConfigurationError("singular linear system")
aug[col], aug[piv] = aug[piv], aug[col]
p = aug[col][col]
aug[col] = [v / p for v in aug[col]]
for r in range(n):
if r != col and aug[r][col] != 0:
f = aug[r][col]
aug[r] = [aug[r][k] - f * aug[col][k] for k in range(n + 1)]
return [aug[i][n] for i in range(n)]
def mat_mul(a: Sequence[Sequence[Fraction]], b: Sequence[Sequence[Fraction]]) -> Matrix:
return [[sum(a[i][k] * b[k][j] for k in range(len(b))) for j in range(len(b[0]))] for i in range(len(a))]
def mat_inverse(a: Sequence[Sequence[Scalar]]) -> Matrix:
n = len(a)
cols = []
for j in range(n):
e = [1 if i == j else 0 for i in range(n)]
cols.append(solve_linear(a, e))
return [[cols[j][i] for j in range(n)] for i in range(n)]