tailot's picture
three certified domains: Euclidean constructions, exact predicates, implicit conics
166cfb1 verified
Raw History Blame Contribute Delete
9.57 kB
"""Algebraic model of a geometry problem.
build_model() turns the AST of a problem into polynomial relations over the
rationals: coordinates of the declared points (numbers or free parameters),
equations that define every point introduced by a Let construction, the
nondegeneracy conditions (explicit assumptions and the implicit existence
conditions of each construction) and one coordinate condition per Prove goal.
It also records the implicit and parametric equations of the declared lines
and circles.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Dict, List, Tuple
from .algebra.polynomial import Poly, PolynomialError, Ring, free_identifiers, parse_poly
from .language import Node, ProblemInfo, classify, describe
from .logic.smt import Cond
from .logic.tarski import PREDICATES, PointPoly, coordinate_condition, tarski_formula
class ModelError(ValueError):
"""Raised for semantic errors: undefined names, bad expressions, duplicates."""
@dataclass
class GoalInfo:
predicate: str
args: Tuple[str, ...]
cond: Cond
tarski: str
text: str
@dataclass
class AlgebraicModel:
ring: Ring
params: List[str]
points: Dict[str, PointPoly]
dependent: List[str]
hypotheses: List[Poly]
explicit_nondeg: List[Poly]
implicit_nondeg: List[Poly]
goals: List[GoalInfo]
entities: List[dict] = field(default_factory=list)
@property
def nondegeneracy(self) -> List[Poly]:
return list(dict.fromkeys(self.explicit_nondeg + self.implicit_nondeg))
def hypothesis_cond(self) -> Cond:
return Cond(eqs=list(self.hypotheses), neqs=list(self.nondegeneracy))
def variable_names(self) -> List[str]:
return list(self.ring.names)
Line3 = Tuple[Poly, Poly, Poly]
def _sub(p: PointPoly, q: PointPoly) -> PointPoly:
return (p[0] - q[0], p[1] - q[1])
def _dot(u: PointPoly, v: PointPoly) -> Poly:
return u[0] * v[0] + u[1] * v[1]
def _cross(u: PointPoly, v: PointPoly) -> Poly:
return u[0] * v[1] - u[1] * v[0]
def _line_through(p: PointPoly, q: PointPoly) -> Line3:
a = p[1] - q[1]
b = q[0] - p[0]
return (a, b, -(a * p[0] + b * p[1]))
def parameters_of(info: ProblemInfo) -> List[str]:
"""Free parameters: identifiers used in point coordinates and nonzero assumptions."""
params: List[str] = []
for d in info.declarations:
if d.head == "Point":
for expr in d.args[1:]:
for ident in free_identifiers(expr):
if ident not in params:
params.append(ident)
for a in info.assumptions:
n = a.args[0]
if isinstance(n, Node) and n.head in ("NonZero", "Zero"):
for ident in free_identifiers(n.args[0]):
if ident not in params:
params.append(ident)
return params
def build_model(problem: Node) -> AlgebraicModel:
info = classify(problem)
params = parameters_of(info)
dep_names: List[str] = []
for let in info.lets:
name = let.args[0]
if name in dep_names:
raise ModelError("point %s is constructed twice" % name)
dep_names.append(name)
var_names = list(params)
for n in dep_names:
var_names += ["%s_x" % n, "%s_y" % n]
ring = Ring(var_names, "grevlex")
def expr(text: str) -> Poly:
try:
return parse_poly(text, ring)
except PolynomialError as exc:
raise ModelError("bad expression %r: %s" % (text, exc))
points: Dict[str, PointPoly] = {}
lines: Dict[str, Line3] = {}
entities: List[dict] = []
for d in info.declarations:
h = d.head
if h == "Point":
name = d.args[0]
if name in points:
raise ModelError("point %s is declared twice" % name)
points[name] = (expr(d.args[1]), expr(d.args[2]))
elif h == "LineThrough":
lname, p, q = d.args
lines[lname] = _line_through(_pt(points, p), _pt(points, q))
entities.append(_line_entity(lname, lines[lname], _pt(points, p), _pt(points, q)))
elif h == "LineEq":
lname = d.args[0]
xy = Ring(["x", "y"], "grevlex")
try:
poly = parse_poly(d.args[1], xy) - parse_poly(d.args[2], xy)
except PolynomialError as exc:
raise ModelError("bad line equation: %s" % exc)
if poly.total_degree() != 1:
raise ModelError("line %s must be a linear equation in x and y" % lname)
a = poly.terms.get((1, 0), 0)
b = poly.terms.get((0, 1), 0)
c = poly.terms.get((0, 0), 0)
lines[lname] = (ring.const(a), ring.const(b), ring.const(c))
entities.append(_line_entity(lname, lines[lname], None, None))
elif h == "CircleCenterR2":
cname, cen, r2 = d.args
cp = _pt(points, cen)
entities.append(
{
"kind": "circle",
"name": cname,
"implicit": "(x - (%s))^2 + (y - (%s))^2 = %s" % (cp[0], cp[1], expr(r2)),
"parametric": "(x, y) = (%s, %s) + sqrt(%s)*(cos t, sin t)" % (cp[0], cp[1], expr(r2)),
}
)
# circles through three points, transformations: numeric only, handled by the kernels
hyps: List[Poly] = []
implicit: List[Poly] = []
def lineref(n) -> Line3:
if n.head == "LineRef":
if n.args[0] not in lines:
raise ModelError("line %s is not declared" % n.args[0])
return lines[n.args[0]]
return _line_through(_pt(points, n.args[0]), _pt(points, n.args[1]))
for let in info.lets:
name, cons = let.args
assert isinstance(cons, Node)
x, y = ring.var("%s_x" % name), ring.var("%s_y" % name)
pt: PointPoly = (x, y)
if cons.head == "Midpoint":
p, q = _pt(points, cons.args[0]), _pt(points, cons.args[1])
hyps += [x * 2 - p[0] - q[0], y * 2 - p[1] - q[1]]
elif cons.head == "Centroid":
p, q, r = (_pt(points, a) for a in cons.args)
hyps += [x * 3 - p[0] - q[0] - r[0], y * 3 - p[1] - q[1] - r[1]]
elif cons.head == "Orthocenter":
p, q, r = (_pt(points, a) for a in cons.args)
hyps += [_dot(_sub(pt, p), _sub(q, r)), _dot(_sub(pt, q), _sub(p, r))]
implicit.append(_cross(_sub(q, p), _sub(r, p)))
elif cons.head == "Circumcenter":
p, q, r = (_pt(points, a) for a in cons.args)
d2 = lambda u, v: _dot(_sub(u, v), _sub(u, v))
hyps += [d2(pt, p) - d2(pt, q), d2(pt, p) - d2(pt, r)]
implicit.append(_cross(_sub(q, p), _sub(r, p)))
elif cons.head == "Foot":
# The foot of the perpendicular from a point to a line: the point is
# on the line and the joining segment is perpendicular to it. This
# construction belongs to the Euclidean track, where the classical
# kernel can also give the exact coordinates.
p = _pt(points, cons.args[0])
a, b, c = lineref(cons.args[1])
hyps += [a * x + b * y + c, a * (x - p[0]) + b * (y - p[1])]
implicit.append(a * a + b * b)
elif cons.head == "Intersection":
l1, l2 = lineref(cons.args[0]), lineref(cons.args[1])
hyps += [l1[0] * x + l1[1] * y + l1[2], l2[0] * x + l2[1] * y + l2[2]]
implicit.append(l1[0] * l2[1] - l2[0] * l1[1])
else:
raise ModelError("unknown construction %s" % cons.head)
if name in points:
raise ModelError("point %s is both declared and constructed" % name)
points[name] = pt
explicit: List[Poly] = []
for a in info.assumptions:
n = a.args[0]
assert isinstance(n, Node)
if n.head == "Zero":
hyps.append(expr(n.args[0]))
elif n.head == "NonZero":
explicit.append(expr(n.args[0]))
else:
explicit.extend(coordinate_condition(n.head, [_pt(points, x) for x in n.args]).neqs)
goals: List[GoalInfo] = []
for g in info.goals:
n = g.args[0]
assert isinstance(n, Node)
if n.head not in PREDICATES:
raise ModelError("unknown predicate %s" % n.head)
pred = PREDICATES[n.head]
if len(n.args) != pred.arity:
raise ModelError("%s expects %d points" % (n.head, pred.arity))
cond = coordinate_condition(n.head, [_pt(points, x) for x in n.args])
goals.append(GoalInfo(n.head, tuple(n.args), cond, tarski_formula(n.head, list(n.args)), describe(n)))
explicit = list(dict.fromkeys(explicit))
implicit = [p for p in dict.fromkeys(implicit) if p not in explicit]
return AlgebraicModel(ring, params, points, dep_names, hyps, explicit, implicit, goals, entities)
def _pt(points: Dict[str, PointPoly], name: str) -> PointPoly:
if name not in points:
raise ModelError("point %s is not defined before its use" % name)
return points[name]
def _line_entity(name: str, line: Line3, p, q) -> dict:
a, b, c = line
ent = {
"kind": "line",
"name": name,
"implicit": "(%s)*x + (%s)*y + (%s) = 0" % (a, b, c),
}
if p is not None:
ent["parametric"] = "(x, y) = (%s, %s) + t*(%s, %s)" % (p[0], p[1], q[0] - p[0], q[1] - p[1])
else:
ent["parametric"] = "direction (%s, %s)" % (-b, a)
return ent