Download certify.py from tailot/lingologos-geometry: direct link, hf CLI and curl.
- Browser
- Download file 17.5 kB
-
https://huggingface.co/datasets/tailot/lingologos-geometry/resolve/main/certify.py
- Command line
-
hf download hf://datasets/tailot/lingologos-geometry/certify.py
-
curl -L -o certify.py https://huggingface.co/datasets/tailot/lingologos-geometry/resolve/main/certify.py
17.5 kB
| """Z3 certificates for the results of the deterministic kernels. | |
| Each certificate is an SMT-LIB 2 problem that is unsatisfiable exactly when the | |
| claimed result is correct: the assertions state the geometric definition of the | |
| object together with the negation of the claim (including uniqueness of the | |
| answer). Status "unsat" therefore certifies the kernel output independently of | |
| the kernel code. | |
| An "unsat" answer is worthless when the premise part of the obligation is itself | |
| inconsistent, because then the negation of the claim cannot be contradicted. A | |
| certificate therefore also carries `hypotheses`: the assertions that describe | |
| the geometric situation the claim speaks about (existence of the objects, a pair | |
| of distinct intersection points, a point equidistant from three vertices). The | |
| arbiter and the offline validator must decide those hypotheses satisfiable, which | |
| is the non-vacuity obligation of the certificate. Certificates whose whole body | |
| is the negation of a non-existence claim (a line that misses the circle, three | |
| collinear points) have no premise part and carry no such obligation. | |
| Quantified claims (the power of a point: every secant through it) are certified | |
| with the direction as a variable, never with one fixed direction, and the pairs | |
| of intersection parameters of a secant are tied to the line by both Vieta | |
| relations (sum and on-circle membership), otherwise the two parameters may be the | |
| same root twice and their product is not the power. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass, field | |
| from fractions import Fraction | |
| from typing import List, Sequence, Tuple | |
| from .kernels import Circle, Line, Point, Surd, power_of_point, secant_through | |
| from .logic.smt import declare_reals, smt_num | |
| from .language import Node | |
| from .solver import ImageResult, NoResult, NumericSolution, PowerResult, const | |
| class CertificationError(ValueError): | |
| """The result class has no certificate (for example coincident input points).""" | |
| class Certificate: | |
| """An unsat obligation plus, when it has one, its non-vacuity obligation. | |
| `assertions` is the negation of the claim over the geometric definition; | |
| `hypotheses` is the premise part of that negation (the situation the claim | |
| speaks about) and must be satisfiable for the unsat verdict to mean anything. | |
| """ | |
| kind: str | |
| declarations: List[str] | |
| assertions: List[str] | |
| expected: str = "unsat" | |
| claim: str = "" | |
| hypotheses: List[str] = field(default_factory=list) | |
| def _n(q) -> str: | |
| return smt_num(Fraction(q)) | |
| def _add(*t: str) -> str: | |
| return t[0] if len(t) == 1 else "(+ %s)" % " ".join(t) | |
| def _sub(a: str, b: str) -> str: | |
| return "(- %s %s)" % (a, b) | |
| def _mul(*t: str) -> str: | |
| return t[0] if len(t) == 1 else "(* %s)" % " ".join(t) | |
| def _eq(a: str, b: str) -> str: | |
| return "(= %s %s)" % (a, b) | |
| def _and(*t: str) -> str: | |
| return t[0] if len(t) == 1 else "(and %s)" % " ".join(t) | |
| def _or(*t: str) -> str: | |
| return t[0] if len(t) == 1 else "(or %s)" % " ".join(t) | |
| def _not(a: str) -> str: | |
| return "(not %s)" % a | |
| def _gt(a: str, b: str) -> str: | |
| return "(> %s %s)" % (a, b) | |
| def _d2(px: str, py: str, qx: str, qy: str) -> str: | |
| dx, dy = _sub(px, qx), _sub(py, qy) | |
| return _add(_mul(dx, dx), _mul(dy, dy)) | |
| def _line_val(l: Line, x: str, y: str) -> str: | |
| return _add(_mul(_n(l.a), x), _mul(_n(l.b), y), _n(l.c)) | |
| class _Surds: | |
| """Collects the radical variable s needed by irrational coordinates.""" | |
| def __init__(self) -> None: | |
| self.m = None | |
| def term(self, v: Surd) -> str: | |
| if v.b == 0: | |
| return _n(v.a) | |
| if self.m is None: | |
| self.m = v.m | |
| elif self.m != v.m: | |
| raise CertificationError("two different radicands in one result") | |
| return _add(_n(v.a), _mul(_n(v.b), "s")) | |
| def declarations(self) -> Tuple[List[str], List[str]]: | |
| if self.m is None: | |
| return [], [] | |
| return ["(declare-const s Real)"], ["(assert %s)" % _eq(_mul("s", "s"), _n(self.m)), "(assert (> s 0))"] | |
| def _distinct_points(pts: Sequence[Point]) -> bool: | |
| return len(set(pts)) == len(pts) | |
| # -- one function per result kind --------------------------------------------- | |
| def certify_intersection(l1: Line, l2: Line, res) -> Certificate: | |
| decls = declare_reals(["x", "y"]) | |
| e1, e2 = _eq(_line_val(l1, "x", "y"), "0"), _eq(_line_val(l2, "x", "y"), "0") | |
| outcome = res.kind | |
| if outcome == "point": | |
| p = res.point | |
| at_p = _and(_eq(_line_val(l1, _n(p.x), _n(p.y)), "0"), _eq(_line_val(l2, _n(p.x), _n(p.y)), "0")) | |
| body = _or(_and(e1, e2, _not(_and(_eq("x", _n(p.x)), _eq("y", _n(p.y))))), _not(at_p)) | |
| claim = "the lines meet exactly at (%s, %s)" % (p.x, p.y) | |
| hyps = ["(assert %s)" % e1, "(assert %s)" % e2] | |
| elif outcome == "parallel": | |
| body = _and(e1, e2) | |
| claim = "the lines are parallel and distinct: no common point" | |
| hyps = [] | |
| else: | |
| body = _and(e1, _not(e2)) | |
| claim = "the lines coincide: every point of one lies on the other" | |
| hyps = [] | |
| return Certificate("intersection", decls, ["(assert %s)" % body], "unsat", claim, hyps) | |
| def certify_circumcircle(pts: Sequence[Point], payload) -> Certificate: | |
| decls = declare_reals(["cx", "cy"]) | |
| a, b, c = pts | |
| dist = lambda p, cx, cy: _d2(cx, cy, _n(p.x), _n(p.y)) | |
| eqs = _and(_eq(dist(a, "cx", "cy"), dist(b, "cx", "cy")), _eq(dist(a, "cx", "cy"), dist(c, "cx", "cy"))) | |
| if isinstance(payload, NoResult): | |
| if not _distinct_points(pts): | |
| raise CertificationError("coincident points have no certificate") | |
| return Certificate("circumcircle", decls, ["(assert %s)" % eqs], "unsat", | |
| "no point is equidistant from three distinct collinear points") | |
| o, r2 = payload.center, payload.circle.r2 | |
| at_o = _and(*[_eq(dist(p, _n(o.x), _n(o.y)), _n(r2)) for p in pts]) | |
| body = _or(_and(eqs, _not(_and(_eq("cx", _n(o.x)), _eq("cy", _n(o.y))))), _not(at_o)) | |
| return Certificate("circumcircle", decls, ["(assert %s)" % body], "unsat", | |
| "the unique circle through the points has center (%s, %s) and r^2 = %s" % (o.x, o.y, r2), | |
| ["(assert %s)" % eqs]) | |
| def certify_tangents(p: Point, circle: Circle, res) -> Certificate: | |
| sr = _Surds() | |
| decls = declare_reals(["tx", "ty"]) | |
| cx, cy = _n(circle.center.x), _n(circle.center.y) | |
| px, py = _n(p.x), _n(p.y) | |
| def hyp(tx: str, ty: str) -> str: | |
| on_circle = _eq(_d2(tx, ty, cx, cy), _n(circle.r2)) | |
| right = _eq(_add(_mul(_sub(tx, px), _sub(tx, cx)), _mul(_sub(ty, py), _sub(ty, cy))), "0") | |
| return _and(on_circle, right) | |
| if isinstance(res, NoResult): | |
| raise CertificationError(res.reason) | |
| free = hyp("tx", "ty") | |
| if res.kind == "none": | |
| body = free | |
| claim = "the point is inside the circle: no tangent contact point exists" | |
| hyps: List[str] = [] | |
| elif res.kind == "single": | |
| body = _or(_and(free, _not(_and(_eq("tx", px), _eq("ty", py)))), _not(hyp(px, py))) | |
| claim = "the point is on the circle: the only contact point is the point itself" | |
| hyps = ["(assert %s)" % free] | |
| elif res.kind == "two": | |
| if len(res.contact_points) != 2 or len(res.lines) < 2: | |
| raise CertificationError("a %s tangent result does not list two contact points to certify" % res.kind) | |
| t = [(sr.term(c.x), sr.term(c.y)) for c in res.contact_points] | |
| is_t = _or(*[_and(_eq("tx", a), _eq("ty", b)) for a, b in t]) | |
| line_ok = [] | |
| for (a, b, c), (tx, ty) in zip(res.lines, t): | |
| la, lb, lc = sr.term(a), sr.term(b), sr.term(c) | |
| on = lambda x, y: _eq(_add(_mul(la, x), _mul(lb, y), lc), "0") | |
| line_ok.append(_and(on(tx, ty), on(px, py))) | |
| same = _and(_eq(t[0][0], t[1][0]), _eq(t[0][1], t[1][1])) | |
| body = _or( | |
| _and(free, _not(is_t)), | |
| _not(_and(hyp(*t[0]), hyp(*t[1]))), | |
| same, | |
| _not(_and(*line_ok)), | |
| ) | |
| claim = "exactly two contact points exist and the listed lines are the tangents" | |
| hyps = ["(assert %s)" % free] | |
| else: | |
| raise CertificationError("unknown tangent outcome kind %r" % res.kind) | |
| extra_d, extra_a = sr.declarations() | |
| return Certificate("tangents", decls + extra_d, extra_a + ["(assert %s)" % body], "unsat", claim, hyps) | |
| def certify_centers(pts: Sequence[Point], payload) -> Certificate: | |
| a, b, c = pts | |
| decls = declare_reals(["x", "y", "ux", "uy", "vx", "vy"]) | |
| N = lambda q: _n(q) | |
| mid = lambda p, q: (N((p.x + q.x) / 2), N((p.y + q.y) / 2)) | |
| cross = lambda ux, uy, vx, vy: _sub(_mul(ux, vy), _mul(uy, vx)) | |
| if isinstance(payload, NoResult): | |
| return certify_circumcircle(pts, payload) | |
| def on_median(px: str, py: str, v: Point, p: Point, q: Point) -> str: | |
| mx, my = mid(p, q) | |
| return _eq(cross(_sub(px, N(v.x)), _sub(py, N(v.y)), _sub(mx, N(v.x)), _sub(my, N(v.y))), "0") | |
| g = payload.centroid | |
| gx, gy = N(g.x), N(g.y) | |
| cent = _or( | |
| _and(on_median("x", "y", a, b, c), on_median("x", "y", b, c, a), _not(_and(_eq("x", gx), _eq("y", gy)))), | |
| _not(on_median(gx, gy, c, a, b)), | |
| ) | |
| def altitude(px: str, py: str, v: Point, p: Point, q: Point) -> str: | |
| return _eq(_add(_mul(_sub(px, N(v.x)), N(p.x - q.x)), _mul(_sub(py, N(v.y)), N(p.y - q.y))), "0") | |
| h = payload.orthocenter | |
| hx, hy = N(h.x), N(h.y) | |
| orth = _or( | |
| _and(altitude("x", "y", a, b, c), altitude("x", "y", b, a, c), _not(_and(_eq("x", hx), _eq("y", hy)))), | |
| _not(altitude(hx, hy, c, a, b)), | |
| ) | |
| o = payload.circumcenter | |
| ox, oy = N(o.x), N(o.y) | |
| dist = lambda p, qx, qy: _d2(qx, qy, N(p.x), N(p.y)) | |
| circ = _or( | |
| _and(_eq(dist(a, "x", "y"), dist(b, "x", "y")), _eq(dist(a, "x", "y"), dist(c, "x", "y")), | |
| _not(_and(_eq("x", ox), _eq("y", oy)))), | |
| _not(_and(_eq(dist(a, ox, oy), dist(b, ox, oy)), _eq(dist(a, ox, oy), dist(c, ox, oy)))), | |
| ) | |
| euler = _or( | |
| _not(_eq(_mul("3", gx), _add(hx, _mul("2", ox)))), | |
| _not(_eq(_mul("3", gy), _add(hy, _mul("2", oy)))), | |
| ) | |
| body = _or(cent, orth, circ, euler) | |
| hyps = [ | |
| "(assert %s)" % _and(on_median("x", "y", a, b, c), on_median("x", "y", b, c, a)), | |
| "(assert %s)" % _and(altitude("ux", "uy", a, b, c), altitude("ux", "uy", b, a, c)), | |
| "(assert %s)" % _and(_eq(dist(a, "vx", "vy"), dist(b, "vx", "vy")), _eq(dist(a, "vx", "vy"), dist(c, "vx", "vy"))), | |
| ] | |
| return Certificate("centers", decls, ["(assert %s)" % body], "unsat", | |
| "centroid, orthocenter and circumcenter are the unique concurrency points and G = (H + 2 O) / 3", | |
| hyps) | |
| def certify_power(p: Point, circle: Circle, res: PowerResult) -> Certificate: | |
| """Certify the power with the direction of the secant left as a variable. | |
| The obligation says: for every direction and every pair of distinct points | |
| P + t1*d, P + t2*d of the circle on the line through the point, the signed | |
| product t1 * t2 * |d|^2 equals the claimed power. Fixing one direction would | |
| certify a single secant (and would be vacuous when that direction happens to | |
| be tangent), so both dx and dy are quantified here. | |
| """ | |
| decls = declare_reals(["t1", "t2", "dx", "dy"]) | |
| cx, cy, px, py = _n(circle.center.x), _n(circle.center.y), _n(p.x), _n(p.y) | |
| d2 = _add(_mul("dx", "dx"), _mul("dy", "dy")) | |
| on = lambda t: _eq(_d2(_add(px, _mul("dx", t)), _add(py, _mul("dy", t)), cx, cy), _n(circle.r2)) | |
| hyp = _and(_gt(d2, "0"), on("t1"), on("t2"), _not(_eq("t1", "t2"))) | |
| vieta = _not(_eq(_mul("t1", "t2", d2), _n(res.power))) | |
| dc2 = _d2(px, py, cx, cy) | |
| cmp_ = {"outside": "(> %s %s)", "on": "(= %s %s)", "inside": "(< %s %s)"}[res.position] | |
| pos = _not(cmp_ % (dc2, _n(circle.r2))) | |
| return Certificate("power", decls, ["(assert %s)" % _or(_and(hyp, vieta), pos)], "unsat", | |
| "every secant through the point cuts the circle in two points whose signed distance product is %s and the position is %s" % (res.power, res.position), | |
| ["(assert %s)" % hyp]) | |
| def _secant_line(p: Point, circle: Circle, d: Point): | |
| """|d|^2, d.(P-C), the power and the discriminant of the secant equation.""" | |
| d2 = d.dot(d) | |
| w = p - circle.center | |
| dw = d.dot(w) | |
| pw = power_of_point(p, circle) | |
| return d2, dw, pw, dw * dw - d2 * pw | |
| def certify_secants(p: Point, circle: Circle, d1: Point, d2: Point, res) -> Certificate: | |
| """Certify the two secant products of a point along two fixed directions. | |
| Both intersections of a secant line are counted with multiplicity and tied to | |
| the line by the Vieta sum t1 + t2 = -2 d.(P-C) / |d|^2 next to the condition | |
| that each of them lies on the circle. Without the sum the two parameters may | |
| be the same root taken twice and their product is not the power; without the | |
| multiplicity reading a tangent direction would make the premise unsatisfiable | |
| and the unsat verdict vacuous. | |
| """ | |
| cx, cy, px, py = _n(circle.center.x), _n(circle.center.y), _n(p.x), _n(p.y) | |
| decls = declare_reals(["t1", "t2", "u1", "u2"]) | |
| def on(t: str, d: Point) -> str: | |
| return _eq(_d2(_add(px, _mul(_n(d.x), t)), _add(py, _mul(_n(d.y), t)), cx, cy), _n(circle.r2)) | |
| if isinstance(res, NoResult): | |
| for d in (d1, d2): | |
| if d.dot(d) == 0: | |
| raise CertificationError("a zero direction is not a secant line to certify") | |
| try: | |
| secant_through(p, d, circle) | |
| except Exception: | |
| return Certificate("secants", declare_reals(["t1"]), ["(assert %s)" % on("t1", d)], "unsat", | |
| "the line through the point along (%s, %s) misses the circle" % (d.x, d.y)) | |
| raise CertificationError("secants result without a missing line") | |
| def pair(t1: str, t2: str, d: Point) -> Tuple[str, Fraction]: | |
| d2, dw, _pw, disc = _secant_line(p, circle, d) | |
| return _and(on(t1, d), on(t2, d), _eq(_add(t1, t2), _n(Fraction(-2) * dw / d2))), disc | |
| h1, disc1 = pair("t1", "t2", d1) | |
| h2, disc2 = pair("u1", "u2", d2) | |
| n1, n2 = _n(d1.dot(d1)), _n(d2.dot(d2)) | |
| prod1 = _mul("t1", "t2", n1) | |
| prod2 = _mul("u1", "u2", n2) | |
| claimed = res.first.product | |
| if not claimed.is_rational: | |
| raise CertificationError("a secant product must be rational") | |
| body = _and(h1, h2, _or(_not(_eq(prod1, prod2)), _not(_eq(prod1, _n(claimed.a))))) | |
| if not res.equal: | |
| body = _and(h1, h2, _eq(prod1, prod2)) | |
| touch = lambda d, disc: "" if disc > 0 else " (the direction (%s, %s) is tangent: the two intersections coincide)" % (d.x, d.y) | |
| return Certificate("secants", decls, ["(assert %s)" % body], "unsat", | |
| "the signed products of the two secants are %s%s%s" % ( | |
| "equal" if res.equal else "different", touch(d1, disc1), touch(d2, disc2)), | |
| ["(assert %s)" % h1, "(assert %s)" % h2]) | |
| def certify_image(p: Point, res: ImageResult) -> Certificate: | |
| rows = res.transform.rows | |
| decls = declare_reals(["xp", "yp", "x1", "y1", "x2", "y2"]) | |
| defs = [ | |
| "(assert %s)" % _eq("xp", _add(_mul(_n(rows[0][0]), _n(p.x)), _mul(_n(rows[0][1]), _n(p.y)), _n(rows[0][2]))), | |
| "(assert %s)" % _eq("yp", _add(_mul(_n(rows[1][0]), _n(p.x)), _mul(_n(rows[1][1]), _n(p.y)), _n(rows[1][2]))), | |
| ] | |
| wrong = _not(_and(_eq("xp", _n(res.image.x)), _eq("yp", _n(res.image.y)))) | |
| if res.rigid: | |
| img = lambda x, y: ( | |
| _add(_mul(_n(rows[0][0]), x), _mul(_n(rows[0][1]), y), _n(rows[0][2])), | |
| _add(_mul(_n(rows[1][0]), x), _mul(_n(rows[1][1]), y), _n(rows[1][2])), | |
| ) | |
| (ax, ay), (bx, by) = img("x1", "y1"), img("x2", "y2") | |
| broken = _not(_eq(_d2(ax, ay, bx, by), _d2("x1", "y1", "x2", "y2"))) | |
| wrong = _or(wrong, broken) | |
| return Certificate("image", decls, defs + ["(assert %s)" % wrong], "unsat", | |
| "the image is (%s, %s)%s" % (res.image.x, res.image.y, " and the map preserves all distances" if res.rigid else ""), | |
| list(defs)) | |
| def certify_query(qid: str, node: Node, sol: NumericSolution) -> Certificate: | |
| """Build the certificate of the result of one query of a solved problem.""" | |
| kind, payload = sol.results[qid] | |
| a = node.args | |
| pt = lambda name: sol.points[name] | |
| if kind == "intersection": | |
| names = [] | |
| for ref in (a[0], a[1]): | |
| names.append(ref.args[0] if ref.head == "LineRef" else "%s-%s" % ref.args) | |
| return certify_intersection(sol.lines[names[0]], sol.lines[names[1]], payload) | |
| if kind == "circumcircle": | |
| return certify_circumcircle([pt(a[0]), pt(a[1]), pt(a[2])], payload) | |
| if kind == "tangents": | |
| return certify_tangents(pt(a[0]), sol.circles[a[1]], payload) | |
| if kind == "centers": | |
| return certify_centers([pt(a[0]), pt(a[1]), pt(a[2])], payload) | |
| if kind == "power": | |
| return certify_power(pt(a[0]), sol.circles[a[1]], payload) | |
| if kind == "secants": | |
| d1 = Point(const(a[2]), const(a[3])) | |
| d2 = Point(const(a[4]), const(a[5])) | |
| return certify_secants(pt(a[0]), sol.circles[a[1]], d1, d2, payload) | |
| if kind == "image": | |
| return certify_image(pt(a[0]), payload) | |
| raise CertificationError("unknown result kind %s" % kind) | |