lingologos-geometry / solver.py
tailot's picture
geometry corpus with quantified certificates and honest attestations
a3bc68c verified
Raw History Blame Contribute Delete
15.1 kB
"""Numeric solving of geometry problems with the Rete network and the kernels.
Every declaration, construction (Let) and query of a fully numeric problem is
asserted as a fact. Productions join those facts with the entities they need
(points, lines, circles, transformations) and call the deterministic kernels,
asserting the results as new facts. Because Rete is incremental, constructions
that depend on earlier constructions fire as soon as their inputs exist.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from fractions import Fraction
from typing import Any, Dict, Iterable, List, Tuple
from .algebra.polynomial import PolynomialError, Ring, parse_poly
from .kernels import (
Affine,
Circle,
GeometryError,
Line,
Point,
Secant,
centroid,
circle_through_three_points,
circumcenter,
intersect_lines,
orthocenter,
position,
power_of_point,
secant_through,
tangents_from_point,
triangle_centers,
)
from .language import Node, classify
from .model import ModelError, parameters_of
from .rete import Fact, Production, ReteNetwork
class SymbolicProblemError(ModelError):
"""The problem has free parameters and cannot be solved numerically."""
@dataclass(frozen=True)
class NoResult:
"""A certified non-existence outcome (degenerate input or no real solution)."""
reason: str
@dataclass(frozen=True)
class PowerResult:
point: Point
circle: Circle
power: Fraction
position: str
@dataclass(frozen=True)
class SecantsResult:
point: Point
circle: Circle
first: Secant
second: Secant
equal: bool
@dataclass(frozen=True)
class ImageResult:
point: Point
image: Point
transform: Affine
rigid: bool
@dataclass
class NumericSolution:
points: Dict[str, Point] = field(default_factory=dict)
lines: Dict[str, Line] = field(default_factory=dict)
circles: Dict[str, Circle] = field(default_factory=dict)
transforms: Dict[str, Affine] = field(default_factory=dict)
results: Dict[str, Tuple[str, Any]] = field(default_factory=dict)
errors: List[Tuple[str, str]] = field(default_factory=list)
queries: Dict[str, Node] = field(default_factory=dict)
firings: int = 0
_CONST_RING = Ring([], "grevlex")
def const(text: str) -> Fraction:
try:
p = parse_poly(text, _CONST_RING)
except PolynomialError:
raise SymbolicProblemError("expression %r contains symbols" % text)
return p.const_value()
def _safe(key_fn, fn):
"""Wrap a kernel action: geometry errors become ("error", key, message) facts."""
def action(b) -> Iterable[Fact]:
try:
return list(fn(b))
except GeometryError as exc:
return [("error", key_fn(b), str(exc))]
return action
def _productions() -> List[Production]:
P: List[Production] = []
def add(name, conds, fn, key=None):
P.append(Production(name, tuple(conds), _safe(key or (lambda b: name), fn)))
pt = lambda v, o: ("point", v, o)
add("line_through", [("def_line_through", "?l", "?p", "?q"), pt("?p", "?P"), pt("?q", "?Q")],
lambda b: [("line", b["?l"], Line.through(b["?P"], b["?Q"]))], lambda b: b["?l"])
add("circle_r2", [("def_circle_r2", "?c", "?p", "?r"), pt("?p", "?P")],
lambda b: [("circle", b["?c"], Circle(b["?P"], b["?r"]))], lambda b: b["?c"])
add("circle_through", [("def_circle_through", "?c", "?a", "?b", "?d"), pt("?a", "?A"), pt("?b", "?B"), pt("?d", "?D")],
lambda b: [("circle", b["?c"], circle_through_three_points(b["?A"], b["?B"], b["?D"]).circle)],
lambda b: b["?c"])
add("rotation", [("def_rotation", "?r", "?c", "?s", "?p"), pt("?p", "?P")],
lambda b: [("transform", b["?r"], Affine.rotation_about(b["?P"], b["?c"], b["?s"]))], lambda b: b["?r"])
add("reflection", [("def_reflection", "?f", "?l"), ("line", "?l", "?L")],
lambda b: [("transform", b["?f"], Affine.reflection(b["?L"]))], lambda b: b["?f"])
add("compose", [("def_compose", "?u", "?a", "?b"), ("transform", "?a", "?A"), ("transform", "?b", "?B")],
lambda b: [("transform", b["?u"], b["?B"].compose(b["?A"]))], lambda b: b["?u"])
add("let_midpoint", [("let_midpoint", "?m", "?p", "?q"), pt("?p", "?P"), pt("?q", "?Q")],
lambda b: [("point", b["?m"], b["?P"].midpoint(b["?Q"]))], lambda b: b["?m"])
add("let_centroid", [("let_centroid", "?g", "?p", "?q", "?r"), pt("?p", "?P"), pt("?q", "?Q"), pt("?r", "?R")],
lambda b: [("point", b["?g"], centroid(b["?P"], b["?Q"], b["?R"]))], lambda b: b["?g"])
add("let_orthocenter", [("let_orthocenter", "?h", "?p", "?q", "?r"), pt("?p", "?P"), pt("?q", "?Q"), pt("?r", "?R")],
lambda b: [("point", b["?h"], orthocenter(b["?P"], b["?Q"], b["?R"]))], lambda b: b["?h"])
add("let_circumcenter", [("let_circumcenter", "?o", "?p", "?q", "?r"), pt("?p", "?P"), pt("?q", "?Q"), pt("?r", "?R")],
lambda b: [("point", b["?o"], circumcenter(b["?P"], b["?Q"], b["?R"]))], lambda b: b["?o"])
def let_intersection(b):
res = intersect_lines(b["?L"], b["?M"])
if res.point is None:
return [("error", b["?x"], "the lines are %s: no unique intersection point" % res.kind)]
return [("point", b["?x"], res.point)]
add("let_intersection", [("let_intersection", "?x", "?l", "?m"), ("line", "?l", "?L"), ("line", "?m", "?M")],
let_intersection, lambda b: b["?x"])
def req(kind, conds, fn):
def run(b):
try:
return [("result", b["?id"], kind, fn(b))]
except GeometryError as exc:
return [("result", b["?id"], kind, NoResult(str(exc)))]
P.append(Production("req_" + kind, tuple(conds), run))
req("intersection", [("req", "intersection", "?id", "?l", "?m"), ("line", "?l", "?L"), ("line", "?m", "?M")],
lambda b: intersect_lines(b["?L"], b["?M"]))
req("circumcircle", [("req", "circumcircle", "?id", "?a", "?b", "?d"), pt("?a", "?A"), pt("?b", "?B"), pt("?d", "?D")],
lambda b: circle_through_three_points(b["?A"], b["?B"], b["?D"]))
req("tangents", [("req", "tangents", "?id", "?p", "?c"), pt("?p", "?P"), ("circle", "?c", "?C")],
lambda b: tangents_from_point(b["?P"], b["?C"]))
req("centers", [("req", "centers", "?id", "?a", "?b", "?d"), pt("?a", "?A"), pt("?b", "?B"), pt("?d", "?D")],
lambda b: triangle_centers(b["?A"], b["?B"], b["?D"]))
req("power", [("req", "power", "?id", "?p", "?c"), pt("?p", "?P"), ("circle", "?c", "?C")],
lambda b: PowerResult(b["?P"], b["?C"], power_of_point(b["?P"], b["?C"]), position(b["?P"], b["?C"])))
def secants(b):
s1 = secant_through(b["?P"], b["?d1"], b["?C"])
s2 = secant_through(b["?P"], b["?d2"], b["?C"])
return SecantsResult(b["?P"], b["?C"], s1, s2, s1.product == s2.product)
req("secants", [("req", "secants", "?id", "?p", "?c", "?d1", "?d2"), pt("?p", "?P"), ("circle", "?c", "?C")], secants)
req("image", [("req", "image", "?id", "?p", "?t"), pt("?p", "?P"), ("transform", "?t", "?T")],
lambda b: ImageResult(b["?P"], b["?T"].apply(b["?P"]), b["?T"], b["?T"].is_rigid()))
return P
def _lref_name(n: Node, facts: List[Fact]) -> str:
if n.head == "LineRef":
return n.args[0]
name = "%s-%s" % n.args
fact = ("def_line_through", name, n.args[0], n.args[1])
if fact not in facts:
facts.append(fact)
return name
def _line_of(poly) -> Line:
"""Coefficients of a linear equation in x and y as a Line.
Anything but degree one is refused: reading the coefficients of a quadratic
equation as a line would silently drop its higher terms and answer a
different question. The algebraic route refuses the same input in
`model.py`, so both routes now agree on what a line equation is.
"""
if poly.total_degree() != 1:
raise ModelError("line equation must be linear in x and y, got total degree %d" % poly.total_degree())
return Line(poly.terms.get((1, 0), 0), poly.terms.get((0, 1), 0), poly.terms.get((0, 0), 0))
def build_facts(problem: Node) -> Tuple[List[Fact], Dict[str, Node], List[Tuple[str, str]]]:
info = classify(problem)
if parameters_of(info):
raise SymbolicProblemError("free parameters %s: use the algebraic route" % parameters_of(info))
facts: List[Fact] = []
errors: List[Tuple[str, str]] = []
queries: Dict[str, Node] = {}
def guarded(key: str, fn) -> None:
try:
fn()
except (GeometryError, ValueError) as exc:
errors.append((key, str(exc)))
for d in info.declarations:
h, a = d.head, d.args
if h == "Point":
facts.append(("point", a[0], Point(const(a[1]), const(a[2]))))
elif h == "LineThrough":
facts.append(("def_line_through", a[0], a[1], a[2]))
elif h == "LineEq":
xy = Ring(["x", "y"], "grevlex")
poly = parse_poly(a[1], xy) - parse_poly(a[2], xy)
guarded(a[0], lambda: facts.append(("line", a[0], _line_of(poly))))
elif h == "CircleCenterR2":
facts.append(("def_circle_r2", a[0], a[1], const(a[2])))
elif h == "CircleThrough":
facts.append(("def_circle_through", a[0], a[1], a[2], a[3]))
elif h == "Rotation":
c, s = const(a[1]), const(a[2])
if a[3] == "origin":
guarded(a[0], lambda: facts.append(("transform", a[0], Affine.rotation(c, s))))
else:
facts.append(("def_rotation", a[0], c, s, a[3]))
elif h == "Translation":
facts.append(("transform", a[0], Affine.translation(const(a[1]), const(a[2]))))
elif h == "Scaling":
guarded(a[0], lambda: facts.append(("transform", a[0], Affine.scaling(const(a[1]), const(a[2])))))
elif h == "Reflection":
facts.append(("def_reflection", a[0], _lref_name(a[1], facts)))
elif h == "Compose":
facts.append(("def_compose", a[0], a[1], a[2]))
else:
raise ModelError("unsupported declaration %s" % h)
for let in info.lets:
name, cons = let.args
h, a = cons.head, cons.args
if h == "Midpoint":
facts.append(("let_midpoint", name, a[0], a[1]))
elif h == "Centroid":
facts.append(("let_centroid", name, a[0], a[1], a[2]))
elif h == "Orthocenter":
facts.append(("let_orthocenter", name, a[0], a[1], a[2]))
elif h == "Circumcenter":
facts.append(("let_circumcenter", name, a[0], a[1], a[2]))
elif h == "Intersection":
facts.append(("let_intersection", name, _lref_name(a[0], facts), _lref_name(a[1], facts)))
for i, q in enumerate(info.queries):
qid = "q%d" % i
n = q.args[0]
h, a = n.head, n.args
queries[qid] = n
if h == "Intersection":
facts.append(("req", "intersection", qid, _lref_name(a[0], facts), _lref_name(a[1], facts)))
elif h == "Circumcircle":
facts.append(("req", "circumcircle", qid, a[0], a[1], a[2]))
elif h == "Tangents":
facts.append(("req", "tangents", qid, a[0], a[1]))
elif h == "TriangleCenters":
facts.append(("req", "centers", qid, a[0], a[1], a[2]))
elif h == "Power":
facts.append(("req", "power", qid, a[0], a[1]))
elif h == "Secants":
facts.append(("req", "secants", qid, a[0], a[1], Point(const(a[2]), const(a[3])), Point(const(a[4]), const(a[5]))))
elif h == "Image":
facts.append(("req", "image", qid, a[0], a[1]))
else:
raise ModelError("unsupported query %s" % h)
return facts, queries, errors
def solve_numeric(problem: Node) -> NumericSolution:
"""Solve a numeric problem with the Rete network and the kernels."""
facts, queries, errors = build_facts(problem)
net = ReteNetwork()
for prod in _productions():
net.add_production(prod)
for f in facts:
net.assert_fact(f)
net.run()
sol = NumericSolution(queries=queries, errors=list(errors), firings=net.firings)
for f in net.facts():
kind = f[0]
if kind == "point":
sol.points[f[1]] = f[2]
elif kind == "line":
sol.lines[f[1]] = f[2]
elif kind == "circle":
sol.circles[f[1]] = f[2]
elif kind == "transform":
sol.transforms[f[1]] = f[2]
elif kind == "result":
sol.results[f[1]] = (f[2], f[3])
elif kind == "error":
sol.errors.append((f[1], f[2]))
return sol
# -- JSON encoding of results -------------------------------------------------
def _surd_pair(t):
return [t[0].to_json(), t[1].to_json()]
def encode_result(kind: str, payload: Any) -> dict:
"""JSON-serializable exact encoding of a query result."""
if isinstance(payload, NoResult):
return {"kind": kind, "outcome": "none", "reason": payload.reason}
if kind == "intersection":
out = {"kind": kind, "outcome": payload.kind, "determinant": str(payload.determinant)}
if payload.point is not None:
out["point"] = payload.point.to_json()
return out
if kind == "circumcircle":
return {
"kind": kind,
"outcome": "circle",
"center": payload.center.to_json(),
"r2": str(payload.circle.r2),
"coefficients": [str(c) for c in payload.coefficients],
"determinant": str(payload.determinant),
}
if kind == "tangents":
return {
"kind": kind,
"outcome": payload.kind,
"tangent_length2": str(payload.tangent_length2),
"half_aperture_sin2": None if payload.half_aperture_sin2 is None else str(payload.half_aperture_sin2),
"contact_points": [c.to_json() for c in payload.contact_points],
"directions": [_surd_pair(d) for d in payload.directions],
"lines": [[c.to_json() for c in ln] for ln in payload.lines],
}
if kind == "centers":
return {
"kind": kind,
"outcome": "triangle",
"centroid": payload.centroid.to_json(),
"orthocenter": payload.orthocenter.to_json(),
"circumcenter": payload.circumcenter.to_json(),
"euler_relation": payload.euler_relation_holds,
}
if kind == "power":
return {"kind": kind, "outcome": payload.position, "power": str(payload.power)}
if kind == "secants":
return {
"kind": kind,
"outcome": "equal" if payload.equal else "different",
"products": [payload.first.product.to_json(), payload.second.product.to_json()],
"power": str(payload.first.point.dist2(payload.circle.center) - payload.circle.r2),
}
if kind == "image":
return {"kind": kind, "outcome": "image", "image": payload.image.to_json(), "rigid": payload.rigid}
raise ValueError("unknown result kind %s" % kind)