Datasets:
Modalities:
Text
Formats:
json
Size:
< 1K
Tags:
multilingual
geometry
theorem-proving
natural-language-to-formal-language
multi-agent-systems
benchmark
Download tools/geometry_runner.py from tailot/geometry-stratum: direct link, hf CLI and curl.
- Browser
- Download file 16.2 kB
-
https://huggingface.co/datasets/tailot/geometry-stratum/resolve/main/tools/geometry_runner.py
- Command line
-
hf download hf://datasets/tailot/geometry-stratum/tools/geometry_runner.py
-
curl -L -o geometry_runner.py https://huggingface.co/datasets/tailot/geometry-stratum/resolve/main/tools/geometry_runner.py
16.2 kB
| #!/usr/bin/env python3 | |
| """Ask the geometry bundle one text of the geometry language, and print its verdict as JSON. | |
| python tools/geometry_runner.py "Point A = (0, 0). Point B = (2, 0). Prove that A, B and M are collinear." | |
| python tools/geometry_runner.py --json "Find the circumcircle of A, B and C." | |
| python tools/geometry_runner.py --record --json "Prove that angle A-B-C is a right angle." | |
| Run from this folder (it is ``datasets/geometry-stratum`` inside the LingoLOGOS repository, and the | |
| bundle root when the dataset is cloned on its own). The geometry bundle it consults is the sibling | |
| folder ``geometry``, or the copy named by ``LGSTRATUM_GEOMETRY_ROOT``. | |
| The reading layer never imports the geometry bundle: the invoker node of the stratum starts this | |
| script as a separate process, and this script is the only place in the bundle where ``geometry`` is | |
| loaded. It starts the seven agent session of the bundle, maps the session's verdict onto the small | |
| shape the reading layer copies, and re-runs the SMT claim of every envelope that session wrote with | |
| the bundle's own solver, so that a verdict reported here is checked against the same query the | |
| session believed it had discharged. Nothing here proves or refutes anything: the geometry stays | |
| in the bundle, and the assurance assigned below is a reading of the evidence the bundle itself | |
| recorded. | |
| Assurance, read off that evidence: | |
| 3 VERIFIED every obligation of the problem was discharged, and each one was discharged by | |
| at least two engines of the bundle that work differently -- the real closed | |
| field solver and the Groebner or Wu-Ritts elimination -- over hypotheses the | |
| solver witnessed as realizable. For a computed answer, the certificate of the | |
| kernel result came out as expected and its non vacuity was witnessed. | |
| 2 SINGLE_PROVER the bundle certified the problem but only one engine confirmed each obligation; | |
| a refutation with a witnessed counterexample also stands here, because it is | |
| decisive even though only the solver produced it. | |
| 0 anything else the bundle refused the text, objected to the model, or stopped without discharging | |
| the obligation. A verdict of zero is reported as it is: the reading layer will | |
| show no answer at all. | |
| """ | |
| import argparse | |
| import json | |
| import sys | |
| from pathlib import Path | |
| from typing import Any, Dict, List, Optional, Tuple | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| from lggeostratum import corpus, invoker # noqa: E402 - the bundle is importable from this folder | |
| _LAYER_STATUS = {"CERTIFIED", "REFUTED", "OBJECTION", "INCONCLUSIVE", "REJECTED"} | |
| def _unknown(reason: str) -> Dict[str, Any]: | |
| return {"status": "UNKNOWN", "assurance": 0, "answer": None, "answer_text": "", "solver": None, | |
| "problem_math": "", "reasons": [reason], "detected": []} | |
| def _load() -> Tuple[Any, Any]: | |
| """The geometry bundle's entry point and its SMT layer, or the failure that explains their absence.""" | |
| root = invoker.geometry_root() | |
| if not (root / "__init__.py").is_file(): | |
| raise RuntimeError("no geometry package at %s" % root) | |
| parent = str(root.parent) | |
| if parent not in sys.path: | |
| sys.path.insert(0, parent) | |
| from geometry.agents import solve # noqa: PLC0415 - the adapter is the point of this script | |
| from geometry.logic import smt | |
| return solve, smt | |
| def _engines(goal: Dict[str, Any]) -> List[str]: | |
| """Which engines of the bundle proved this goal, among the ones that reported on it.""" | |
| routes = goal.get("routes") or {} | |
| found: List[str] = [] | |
| solver = routes.get("z3") or {} | |
| if isinstance(solver, dict) and str(solver.get("status", "")) == "unsat": | |
| found.append("z3") | |
| for name in ("groebner", "wu"): | |
| entry = routes.get(name) | |
| if isinstance(entry, dict) and entry.get("proved") is True: | |
| found.append(name) | |
| return found | |
| def _certificate_clear(certificate: Dict[str, Any]) -> bool: | |
| """Whether a kernel answer was certified, and its configuration shown not to be vacuous.""" | |
| if not certificate.get("ok"): | |
| return False | |
| witness = certificate.get("nonvacuity") or {} | |
| return isinstance(witness, dict) and str(witness.get("status", "")) == "sat" | |
| def _compact(value: Any, limit: int = 400) -> str: | |
| """One stable line for a computed answer: sorted keys, no spaces, so a reader can quote it.""" | |
| try: | |
| text = json.dumps(value, sort_keys=True, separators=(",", ":"), default=str) | |
| except (TypeError, ValueError): | |
| text = str(value) | |
| return text if len(text) <= limit else text[:limit] + "..." | |
| def _answer_text(goals: List[Dict[str, Any]], results: Dict[str, Any], points: Dict[str, Any]) -> str: | |
| """What the bundle answered, in the bundle's own words.""" | |
| if goals: | |
| proven = [str(goal.get("goal") or goal.get("predicate") or "") for goal in goals | |
| if goal.get("status") == "PROVED"] | |
| refuted = [str(goal.get("goal") or goal.get("predicate") or "") for goal in goals | |
| if goal.get("status") == "REFUTED"] | |
| if refuted: | |
| return "the claim does not hold: %s" % "; ".join(refuted) | |
| return "the claim holds: %s" % "; ".join(item for item in proven if item) | |
| parts: List[str] = [] | |
| if results: | |
| parts.append(_compact(results)) | |
| if points: | |
| parts.append("points %s" % _compact(points)) | |
| return " ".join(parts) | |
| def _answer(goals: List[Dict[str, Any]], results: Dict[str, Any], points: Dict[str, Any]) -> Optional[Dict[str, Any]]: | |
| """The machine readable answer the bundle produced, copied without being reinterpreted.""" | |
| if goals: | |
| first = goals[0] | |
| return {"kind": "goal", "predicate": first.get("predicate"), "args": list(first.get("args") or []), | |
| "status": first.get("status"), "routes": sorted(_engines(first))} | |
| if results or points: | |
| return {"kind": "computation", "results": results, "points": points} | |
| return None | |
| def _referee(log: List[Dict[str, Any]], smt: Any) -> List[Dict[str, Any]]: | |
| """Re-run every SMT claim the geometry session made, with the bundle's own solver.""" | |
| entries: List[Dict[str, Any]] = [] | |
| for envelope in log: | |
| payload = envelope.get("payload") or {} | |
| constraints = payload.get("smtConstraints") or {} | |
| declarations = list(constraints.get("declarations") or []) | |
| assertions = list(constraints.get("assertions") or []) | |
| claimed = str(constraints.get("z3Status", "")) | |
| if not declarations and not assertions: | |
| continue | |
| try: | |
| referee = str(smt.check_smt(declarations, assertions).status) | |
| except Exception as exc: # noqa: BLE001 - a claim that cannot be re-run is a claim to report | |
| referee = "error: %s" % type(exc).__name__ | |
| entries.append({"sender": str(envelope.get("sender", "")), "claimed": claimed, "referee": referee}) | |
| return entries | |
| def _final(record: Dict[str, Any], text: str) -> Dict[str, Any]: | |
| """The verdict of a geometry session, in the shape the reading layer copies.""" | |
| status = str(record.get("status", "")) | |
| termination = str(record.get("termination", "")) | |
| goals = [goal for goal in (record.get("goals") or []) if isinstance(goal, dict)] | |
| certificates = [item for item in (record.get("certificates") or []) if isinstance(item, dict)] | |
| results = dict(record.get("results") or {}) | |
| points = dict(record.get("points") or {}) | |
| objections = [item for item in (record.get("objections") or []) if isinstance(item, dict)] | |
| findings = [item for item in (record.get("findings") or []) if isinstance(item, dict)] | |
| fatal = [item for item in objections + findings if str(item.get("severity", "")) == "fatal"] | |
| reasons: List[str] = [] | |
| detected: List[str] = [] | |
| solver = "geometry:%s" % str(record.get("mode", "")) | |
| if status == "CERTIFIED": | |
| proved = [goal for goal in goals if goal.get("status") == "PROVED"] | |
| weak = [goal for goal in goals if goal.get("status") == "PROVED" and len(_engines(goal)) < 2] | |
| vacuous = [goal for goal in goals if goal.get("status") == "VACUOUS"] | |
| unclear = [certificate for certificate in certificates if not _certificate_clear(certificate)] | |
| discharged = bool(goals or certificates) and len(proved) == len(goals) | |
| if discharged and not weak and not vacuous and not unclear and not fatal: | |
| detected.append("%d of %d goals confirmed by two engines" % (sum(1 for goal in goals if len(_engines(goal)) >= 2), len(goals)) | |
| if goals else "the computed answer was certified and its figure witnessed") | |
| return {"status": "VERIFIED", "assurance": 3, "answer": _answer(goals, results, points), | |
| "answer_text": _answer_text(goals, results, points), "solver": solver, | |
| "problem_math": text, "reasons": reasons, "detected": detected} | |
| if weak: | |
| reasons.append("only one engine of the bundle confirmed the obligation") | |
| if vacuous: | |
| reasons.append("the hypotheses admit no configuration, so nothing was proved about a figure") | |
| if unclear: | |
| reasons.append("a certificate was discharged without a witness that the figure exists") | |
| if fatal: | |
| reasons.append("%d fatal objections against the model" % len(fatal)) | |
| return {"status": "SINGLE_PROVER", "assurance": 2, "answer": _answer(goals, results, points), | |
| "answer_text": _answer_text(goals, results, points), "solver": solver, | |
| "problem_math": text, "reasons": reasons, "detected": detected} | |
| if status == "REFUTED": | |
| counterexample: Dict[str, Any] = {} | |
| for goal in goals: | |
| if goal.get("status") == "REFUTED" and isinstance(goal.get("counterexample"), dict): | |
| counterexample = goal.get("counterexample") | |
| break | |
| answer = {"kind": "refutation", "counterexample": counterexample, "figure": points} | |
| detected.append("the bundle showed a configuration of the figure where the claim fails") | |
| # An empty model from the solver means the figure as stated already refutes the claim: the | |
| # coordinates of the points are the counterexample, and the bundle has them recorded. | |
| witness = _compact(counterexample) if counterexample else "the figure as given: %s" % _compact(points) | |
| return {"status": "REFUTED", "assurance": 2, "answer": answer, | |
| "answer_text": "%s (counterexample %s)" % (_answer_text(goals, results, points), witness), | |
| "solver": solver, "problem_math": text, "reasons": reasons, "detected": detected} | |
| for item in fatal: | |
| reasons.append("%s: %s" % (item.get("code", "objection"), str(item.get("message", ""))[:160])) | |
| if not reasons: | |
| reasons.append("the geometry bundle answered %s (%s)" % (status or "UNKNOWN", termination or "no termination")) | |
| return {"status": status if status in _LAYER_STATUS else "UNKNOWN", "assurance": 0, "answer": None, | |
| "answer_text": "", "solver": solver, "problem_math": text, "reasons": reasons, | |
| "detected": detected} | |
| def solve(text: str, keep_log: bool = False) -> Dict[str, Any]: | |
| """Run one text through the geometry bundle and return the checked verdict.""" | |
| try: | |
| run, smt = _load() | |
| except Exception as exc: # noqa: BLE001 - the absence of the bundle is a verdict, not a crash | |
| return {"final": _unknown("the geometry bundle could not be loaded: %s" % exc), "referee": [], "turns": 0} | |
| try: | |
| result = run(text) | |
| except Exception as exc: # noqa: BLE001 - a session that breaks is a session that answered nothing | |
| return {"final": _unknown("the geometry session stopped: %s: %s" | |
| % (type(exc).__name__, str(exc)[:160])), "referee": [], "turns": 0} | |
| record = result.to_record() | |
| final = _final(record, str(getattr(result, "text", "") or text)) | |
| referee = _referee(list(getattr(result, "log", []) or []), smt) | |
| mismatched = sum(1 for entry in referee if entry["claimed"] != entry["referee"]) | |
| if mismatched: | |
| final["reasons"].append("%d claims of the geometry session did not survive the re-check" % mismatched) | |
| final["detected"].append("referee mismatch in %d envelopes" % mismatched) | |
| final["assurance"] = 0 | |
| outcome = {"final": final, "referee": referee, "turns": int(getattr(result, "turns", 0) or 0)} | |
| if keep_log: | |
| outcome["record"] = record | |
| return outcome | |
| def _describe(outcome: Dict[str, Any]) -> str: | |
| final = outcome["final"] | |
| lines = [] | |
| if final.get("problem_math"): | |
| lines.append("Problem as understood : %s" % final["problem_math"]) | |
| lines.append("Status : %s (assurance level %d of 3)" % (final["status"], final["assurance"])) | |
| lines.append("Answer : %s" % (final["answer_text"] or "-")) | |
| if final["reasons"]: | |
| lines.append("Notes : %s" % "; ".join(final["reasons"])) | |
| if outcome["referee"]: | |
| agree = sum(1 for entry in outcome["referee"] if entry["claimed"] == entry["referee"]) | |
| lines.append("Geometry session check: %d of %d envelopes confirmed" % (agree, len(outcome["referee"]))) | |
| return "\n".join(lines) | |
| def _grade(item: Dict[str, Any], final: Dict[str, Any]) -> List[str]: | |
| """What a gold line of the corpus does not accept from the bundle on its own.""" | |
| expect = item.get("expect") or {} | |
| problems: List[str] = [] | |
| if "answer_contains" in expect and str(expect["answer_contains"]) not in str(final.get("answer_text", "")): | |
| problems.append("answer does not contain %r" % expect["answer_contains"]) | |
| if "min_assurance" in expect and int(final.get("assurance", 0) or 0) < int(expect["min_assurance"]): | |
| problems.append("assurance %s below %s" % (final.get("assurance"), expect["min_assurance"])) | |
| if "max_assurance" in expect and int(final.get("assurance", 0) or 0) > int(expect["max_assurance"]): | |
| problems.append("assurance %s above %s" % (final.get("assurance"), expect["max_assurance"])) | |
| return problems | |
| def main() -> int: | |
| parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) | |
| parser.add_argument("problem", nargs="?", help="a text of the geometry language") | |
| parser.add_argument("--json", action="store_true", help="print the full machine readable outcome") | |
| parser.add_argument("--record", action="store_true", help="with --json: include the record of the session") | |
| parser.add_argument("--corpus", help="run the canonical sentence of every corpus line through the bundle") | |
| parser.add_argument("--limit", type=int, default=0, help="with --corpus: only the first N problems") | |
| args = parser.parse_args() | |
| if args.corpus: | |
| rows = [item for item in corpus.load(args.corpus) | |
| if str((item.get("expect") or {}).get("sentence", "")).strip()] | |
| rows = rows[: args.limit] if args.limit else rows | |
| tally: Dict[str, int] = {} | |
| for item in rows: | |
| sentence = str(item["expect"]["sentence"]) | |
| verdict = solve(sentence) | |
| problems = _grade(item, verdict["final"]) | |
| label = "ok" if not problems else "wrong" | |
| tally[label] = tally.get(label, 0) + 1 | |
| print("%-6s %-6s %-14s %s" % (item.get("id", "?"), label, verdict["final"]["status"], sentence[:60])) | |
| for problem in problems: | |
| print(" %s" % problem) | |
| print(json.dumps(tally, sort_keys=True)) | |
| return 0 if tally.get("wrong", 0) == 0 else 1 | |
| if not args.problem: | |
| parser.error("a problem or --corpus is required") | |
| outcome = solve(args.problem, keep_log=args.record) | |
| if args.json: | |
| print(json.dumps(outcome, indent=2, default=str)) | |
| else: | |
| print(_describe(outcome)) | |
| return 0 if outcome["final"]["status"] != "UNKNOWN" else 2 | |
| if __name__ == "__main__": | |
| sys.exit(main()) | |