diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a160f494b397adda8d5741d811f8444558aa261a --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +__pycache__/ +*.py[cod] +.pytest_cache/ diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..837d14b2381fbb40599a848c5252d5835689fbee --- /dev/null +++ b/README.md @@ -0,0 +1,434 @@ +--- +language: + - it + - en + - es + - zh + - hi + - ar +tags: + - multilingual + - geometry + - theorem-proving + - natural-language-to-formal-language + - multi-agent-systems + - benchmark + - conversational-interfaces + - formal-verification + - semantic-parsing +pretty_name: "LingoLOGOS geometry-stratum: a question in six written varieties, the answer of the geometry layer, and an assurance that includes the reading" +configs: + - config_name: corpus + data_files: + - split: train + path: problems/corpus.jsonl +size_categories: + - n<1K +--- + +# LingoLOGOS geometry-stratum topology + +A conversational layer over the `geometry` topology: a person draws a figure in words and asks about it +in one of six written varieties, and gets the verdict of the geometry layer back in that same language, +at an assurance that includes the fallibility of the reading. The layer never decides a figure and never +raises a verdict; the only direction it can move the assurance of the geometry layer is down. + +``` +python tools/ask.py --lang zh "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。证明 A, B 和 C 共线。" +Reading state : AGREED +Assurance shown : 2 (reading ceiling 2, geometry assurance 3) +Geometry layer status : VERIFIED +Orchestrator Z3 check : 8 of 8 envelopes confirmed + +Answer in the language of the question (中文): + 状态: 一致:两位独立读者加上 SMT 约束 + 这种变体理解的问题 (problem): Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear. + 答案: the claim holds: A, B and C are collinear + 三级中的第 2 级 + 几何层: VERIFIED + 几何层的 SMT 检查:8 个信封中有 8 个得到确认 +``` + +The answer line is the geometry layer's own sentence, carried unchanged: restating it would break the +echo the boundary node checks. A person who asked in Chinese reads the labels in Chinese and the verdict +in the language the formal layer writes. + +This dataset is the `geometry-stratum/` folder of the LingoLOGOS project published as it stands: 68 files, +code and data together, plus this card in place of their README. Only the standard library and +`z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every +command below is written from inside the folder. The geometry layer is not part of this dataset: it +lives in the `geometry` bundle, published at +https://huggingface.co/datasets/tailot/lingologos-geometry, and section 10 says how to point this +folder at a copy of it. + +## 1. What the stratum is, and what it refuses + +The certainty of a translation cannot be verified the way the certainty of a proof can: there is no SMT +check that says that a sentence of Hindi was read correctly. That is the definition this bundle works +with, and it is why the topology is built the way it is: two readers that reach their sentence by +different roads, an SMT claim about what each reading kept, a referee that rechecks every envelope, and a +decision that is re-derived from the transcript instead of being trusted from the arbiter. + +The rule the whole bundle exists to enforce: + +``` +assurance shown = min(assurance of the geometry layer, ceiling of the reading) +``` + +| Reading state | ceiling | when | +|---|---|---| +| `AGREED` | 2 | both readers produced the same figure, and the geometry layer is what decides it | +| `PASSTHROUGH` | 2 | the question was already a text of the geometry language: nothing was translated | +| `SINGLE` | 1 | one reader understood it and the other abstained: no witness, one level less | +| `DISPUTED` | 0 | the two readers produced different sentences, or a reading lost a number: the geometry layer is not even asked | +| `AMBIGUOUS` | 0 | a reader reports that the question announces more than one figure, or leaves a slot with several readings: the person has to choose | +| `NOT COVERED` | 0 | neither reader found anything: this variety does not say it in a covered way | +| `TAMPERED` | 0 | the geometry layer says it solved something other than the agreed sentence | + +Three is never shown. Level three belongs to the geometry layer, whose parser, kernel and critics work on +a text they were built for; a sentence in a human language adds one fallible step before that, and this +layer is that step. + +The ceiling is not the only thing that holds on its own. The count of literals is checked on a lone +reading too, and in a figure that weighs more than it does in an equation: the coordinates are the +problem, so a reading that no longer holds the numbers the person wrote is a different figure and not a +weaker reading of the same one, and it ends `DISPUTED` even when it is the only reader that understood +the question. A single witness therefore answers at level one only when it kept every number. + +## 2. The eight nodes + +The session runs through the orchestrator (`src/lingologos_orchestrator`) with the same envelope protocol +as the `geometry` topology: a marker `@@DOSSIER@@` inside `payload.naturalLanguage`, and +`payload.smtConstraints` carrying what each node claims about its own output, which the referee of every +node recomputes with Z3. The seed sits in the `arbiter`; `maxTurns` is the number of arcs. + +| Node | What it does | The claim it carries | +|---|---|---| +| `reader_a` | reads the question against the frames written in the lexicon | the numerals of the question are still in my sentence | +| `reader_b` | reads it by following the joints of the geometry language (`through`, `with center ... and`, `of the triangle ... and`, `perpendicular to`, the postpositions) | the same, independently | +| `equivalence` | proves the two sentences the same: the numbers first, then the slots with SMT | `not (A = B)` is unsatisfiable | +| `coverage` | counts that every literal the person wrote survived into the sentence | conjunction of the element equalities | +| `invoker` | asks the geometry layer, in a separate process, the agreed figure | the sentence I sent equals the one that came back | +| `boundary` | checks the echo of the geometry layer instead of trusting it | elementwise on the echo, or the empty claim | +| `adversary` | re-derives the bound and writes its negation | `shown > ceiling` is unsatisfiable | +| `arbiter` | runs the decision and renders the answer in the language of the question | the same inequality | + +The echo here is the geometry bundle's own record: the runner hands back the text that bundle parsed, +next to its verdict, and the boundary node compares that text with the sentence the readers agreed on, +atom by atom. A figure that comes back different is `TAMPERED`, however strong the verdict on it looks. + +## 3. Two readers, one lexicon + +`read_a.py` matches the shapes stored in `lexicon/.json` (`patterns`: one template per kind of +statement, with slots). `read_b.py` never looks at those shapes: it finds the verb that announces a +statement, then walks the joints of the geometry language and cuts the slots out of the gaps between them, +in whatever order the variety puts them. They share only the lexicon, the atomizer (`segment.py`) and the +templates of the geometry language (`canonical.py`). + +How much of the 19 statement kinds each variety describes, and with how much material: + +| Variety | Kinds | Patterns | Verb phrases | Connectives | Markers | Noise words | +|---|---|---|---|---|---|---| +| `en` | 19 | 33 | 14 | 3 | 43 | 53 | +| `it` | 18 | 42 | 23 | 4 | 46 | 72 | +| `es` | 19 | 27 | 16 | 3 | 43 | 64 | +| `zh` | 13 | 18 | 9 | 4 | 21 | 20 | +| `hi` | 11 | 18 | 11 | 3 | 23 | 33 | +| `ar` | 11 | 13 | 10 | 3 | 30 | 31 | + +A question in this corpus is a whole figure: the points, the lines and the circle defined first, then the +claim about them, in one text -- and the geometry language requires the definitions before the claim that +uses them. `agents.py` therefore splits the question at the sentence markers (the full stop, `。`, the +danda), reads every part with the reader in question, and re-assembles the parts into one text of the +geometry language in the order the bundle expects. The compound reading carries `compound: true` and the +list of its parts, and it stands at the worst status of its parts. Its literals are re-read from the +question itself (`compare.sorted_numbers`) rather than trusted from the reading. + +Every stored shape has to name the verb of its own kind, and `tests/test_lexicon.py` checks it for all +six varieties. That is a deliberate cost: it means a pattern can never open on a bare noun phrase, and so +the verbless nominal phrasing of a figure -- `the point A, coordinates (0, 0)` -- is not read and ends +`no_verb`. The Italian shapes carry no copula, because the atomizer folds the accented `è` of +`è perpendicolare` into a space; a person who writes that copula plain is read the same way, which is +why a missing accent costs nothing here while it costs a reading in the arithmetic stratum of the same +project. + +That sharing of one lexicon is deliberate and it is also the known blind spot: a wrong description of a +variety is a wrong description for both readers, and the topology cannot see it. What shows it is the +corpus of section 5, whose questions were written and checked by a person. When the two readers disagree +the assurance goes down, never up: `DISPUTED` does not even consult the geometry layer. + +## 4. Talking to the geometry layer + +`invoker.py` is the only door, and it is a subprocess and a set of environment variables. It launches +`python tools/geometry_runner.py --json
` -- a script of this folder -- and reads its JSON verdict +back; nothing in this folder imports the geometry bundle to decide anything here. That runner is the only +place in the bundle where `geometry` is loaded: it finds the bundle in the sibling folder +`datasets/geometry`, or in the copy named by `LGSTRATUM_GEOMETRY_ROOT`, starts the seven agent session of +that bundle, maps the session's verdict onto the small shape this 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. + +| Variable | Meaning | +|---|---| +| `LGSTRATUM_GEOMETRY_ROOT` | where the `geometry` bundle is (default: the sibling folder `datasets/geometry`) | +| `LGSTRATUM_GEOMETRY_BACKEND` | `subprocess` (default), or `none` to disable the geometry layer entirely | +| `LGSTRATUM_GEOMETRY_TIMEOUT` | seconds that session may take (default 180) | +| `LGSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only | + +The assurance the runner reports, read off the evidence the bundle itself recorded: + +``` +3 VERIFIED every obligation of the problem discharged, each 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 stands here too, 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 zero is reported as it is, and this layer then shows no answer +``` + +A disabled geometry layer is not tampering: the reading stands, the assurance falls to zero because there +is no geometry assurance to take the minimum with, and no answer is shown. + +## 5. The corpus + +`problems/corpus.jsonl` holds 56 questions: 19 kinds of statement in 6 written varieties (English 20 rows, +Italian 12, Spanish, Chinese, Hindi and Arabic 6 each), 6 questions that must not be read -- an area, an +inscribed rectangle, a bisector: objects the geometry language of the bundle does not name -- and one +question already written in that language. Each line carries what the answer has to look like (`state`, +`sentence`, `answer_contains`, `min_assurance`, `max_assurance`, `no_answer`, `referee_clean`) and a `why` +that says why, including the cases where the expected outcome is an abstention. + +Graded against the in-process pipeline: **56 of 56** rows agree with their gold (`lggeostratum/corpus.py` +grades one row, `tests/test_corpus.py` runs all of them). The states come out 46 `AGREED`, 3 `SINGLE`, 1 +`PASSTHROUGH` and 6 `NOT COVERED`; `tools/coverage_report.py` writes `results/coverage.json` and counts +**46** questions read by both readers, **3** by `reader_a` alone and **6** by neither -- the +`PASSTHROUGH` row was never read at all, because there was nothing to translate. Eleven rows (`point-en`, +`line-en`, `circle-en`, `circle-it`, `assume-en`, `centroid-en`, `centroid-it`, `circumcentre-en`, +`intersect-en`, `image-en`, `mid-en-def`) are agreed readings on which the geometry layer abstains: a +figure of definitions with no claim in it, or a `find the image` with no transformation named. The +assurance is 0 and no answer appears, which is the layer refusing to add an availability it does not +have. Three rows (`mid-zh-single`, `mid-hi-single`, `findintersect-es`) stay at `SINGLE`, assurance 1, for +the reason in section 7. + +## 6. Commands + +``` +python tools/ask.py --lang zh "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。证明 A, B 和 C 共线。" +python tools/ask.py --lang it --json "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear." +python tools/ask.py --lang ar --corpus problems/corpus.jsonl --limit 6 +python tools/coverage_report.py --out results/coverage.json # which frames each variety carries +python tools/ablation.py --probe 6 --out results/ablation.json +``` + +The first line is one session through the orchestrator, eight processes; the second is the same shape +with a question that needs no translation, and ends `PASSTHROUGH`. + +`tools/ask.py` prints the verdict it re-derives from the transcript, not the one the arbiter wrote, and +exits with code 3 when that re-derivation disagrees with a node about its own envelope, with code 2 when +the assurance is zero, and with code 1 in corpus mode when a gold expectation fails. +`tools/ablation.py` walks the configurations of the topology one node at a time, injects every fault of +the catalogue singly and in pairs, and reports each cell as +`raised | lowered | masked | caught | abstained | silent_error`: a cell counted `raised` is a violation of +the rule of section 1, and the tool exits 1 if any happened. A `caught` cell is one where an answer was +shown that the gold does not accept, but the session said so itself -- a claim fell to the referee of its +node, or the assurance sits below the honest one because the configuration lost a node. + +On this checkout `--probe 6` (one question per variety) fills **147 cells** and **882 sessions**, the fault +takes hold in **720** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 1`, `caught 32`, +`abstained 561`, `masked 126` -- under four minutes. Nothing was ever raised above the honest assurance. +The 32 `caught` cells all sit in the two configurations that are missing one reader, where a rubber +stamped node cannot buy back the level that the missing witness costs. The shape of the columns differs +from the arithmetic stratum of the same project: in a figure a damaged reading almost never survives as +a weaker answer, because what the readers produce has to stay a parseable problem with every coordinate +kept, so 561 cells end with no answer at all rather than a lower one. The one `silent_error` is the blind +spot of section 3 shown in numbers: with `merge_slots` fired in both readers at once, the Spanish +congruence row turns into `segment A-B is congruent to segment A-B` -- both readers merged the same pair +of names, so the two readings agree, the claim is trivially provable, the bundle certifies it, and the +session answers at level 2 about a question nobody asked. The only witness against it is the person. + +## 7. Limits that are written down, not hidden + +* Three rows are cut by `reader_a` alone, because one clause of the figure puts its joint after the names + instead of between them: `设 M 平分 线段 A B` in Chinese, `मान लें M, A और B का मध्यबिंदु है` in Hindi, + where the postposition closes the clause, and `Halle el punto en comun de la recta r y la recta s` in + Spanish, where both line names follow the words for the common point. `reader_b` cannot cut the slots + there, so those rows stay at `SINGLE`, assurance 1 (`mid-zh-single`, `mid-hi-single`, + `findintersect-es`), and `tools/coverage_report.py` shows them as read by one of two readers. +* `lexicon/it.json` describes 18 of the 19 kinds: the image of a figure under a named transformation has + no Italian surface here, and Chinese, Hindi and Arabic stop at 13, 11 and 11 kinds. What a variety + does not describe ends `NOT COVERED` with assurance 0: the stratum says it did not read it, and does + not guess. +* The verbless nominal phrasing of a figure is not read in any variety, because every stored shape has to + name the verb of its own kind (section 3). A person who writes `the point A, coordinates (0, 0)` is + asked to say it as a definition. +* The fragment of the geometry bundle is unchanged here: a figure with definitions and no claim, or a + `find the image` with no transformation named, ends `INCONCLUSIVE` in that bundle and assurance 0 here, + even when the reading is agreed. The corpus keeps those eleven rows as probes of the ceiling. +* The two readers share their data, so a systematic error in the description of a variety is invisible to + the topology and can only be found in the corpus. Section 6 counts the one case the ablation managed to + produce, and it is an answer, not a refusal. +* `equivalence` never spends a solver call on two readings whose numbers differ: it compares the + multisets of literals, says `numbers`, and stops (section 1). A veto, not a heuristic: the equivalence + claim of that node is then a failed claim, and it is still rechecked by its referee. + +## 8. Tests + +From the repository root: + +``` +python -m pytest -q datasets/geometry-stratum/tests +``` + +The suite is **255** tests: 103 on the two readers against every row of the corpus, 62 on the corpus +itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 13 on the decision table, +10 on the lexicons and 2 end-to-end sessions. It checks the topology file against the node order, the +shape and the completeness of the lexicons -- including that every pattern of every variety is announced +by a verb of its own kind, and that the six sets of reason sentences ask for the same fillers -- both +readers against the corpus, the decision table, the faults, and every gold answer of the corpus; +`tests/test_pinned_invariant.py` runs the same questions through every node configuration and every fault +and asserts that the verdict of the geometry layer does not move, and that nothing is ever shown above +it. `tests/test_orchestrator_e2e.py` runs two real sessions through the orchestrator, one honest and one +in which the arbiter is forced to raise its own assurance -- which the referee of that node undoes, and +which the tool reports -- and the test is skipped when `lingologos_orchestrator` is not importable. The +corpus and the invariant tests call the solver of the geometry layer as subprocesses, which here means a copy of the +`geometry` dataset named by `LGSTRATUM_GEOMETRY_ROOT` (section 10); the suite took 57 seconds inside a +LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is +not importable. + +Real sessions, measured: the Chinese session at the top of this file comes back `AGREED` at assurance 2 +against a geometry assurance of 3, with **8 of 8** envelope claims confirmed by the referee of the +session. The Italian perpendicularity row (`perp-it-true`: four points, then a claim about two lines) +comes back the same way -- `AGREED`, assurance 2, the geometry layer `VERIFIED`, 8 of 8 claims confirmed, +nothing detected. + +A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that +inside the library only `lggeostratum/compare.py` may import the `geometry` package, and only for the SMT +plumbing of its own equivalence claim; the modules that decide, route and invoke hold no reference to it, +and the session is reached as a separate process. + +## 9. Language policy + +The prose of this folder -- code, docstrings, comments, tool output, test messages -- is English, and the +Python sources are ASCII, as the repository requires. The exception is the language under study, and it is +confined to data: `lexicon/*.json` (the words, frames, joints and labels of the six varieties), +`problems/corpus.jsonl` (the questions and their gold answers), and the answer block that `tools/ask.py` +shows a person, which is written in the language of the question because that block is the object this +bundle measures. + +## 10. Putting this dataset back into a LingoLOGOS checkout + +This dataset is 68 files plus this card: 56 questions in one corpus file, the six lexicons, the eight +node definitions, the two readers, the decision rule of section 1, the corpus grading and fault +results under `results/`, and the fault catalogue of section 6. To decide a figure it needs the +`geometry` bundle: download https://huggingface.co/datasets/tailot/lingologos-geometry somewhere, set +`LGSTRATUM_GEOMETRY_ROOT` to that copy, and the `invoker` node of this folder starts +`tools/geometry_runner.py`, which loads that copy in a separate process -- the only door through which +this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at +`datasets/geometry-stratum`, finds `datasets/geometry` by itself, and needs +`src/lingologos_orchestrator` importable for the two end to end sessions of section 8. On the hub this +README is rewritten as a dataset card whose sections 1 to 10 keep the wording and numbers of this file, +and sections 11 to 14 are added there for readers who met the bundle on the hub rather than in a +checkout: the fields of the corpus file, how to load it, rights and citation. Every file of this folder is +compared by sha256 after the upload, the card that replaces this README among them: the hub holds one +object per file of this folder plus `.gitattributes`, so the remote count is one above the number +`tools/publish_dataset.py` prints here. +What the LingoLOGOS repository carries is the link to this +dataset in the table of published resources at the top of its README; the documentation of the asset +lives here, in this card, and not in the technical documentation of the project. Republishing is a +separate step, never a side effect of a test run: `tools/publish_dataset.py` in the folder of the +project does it with the token taken from an environment variable and verifies the tree by sha256. + +## 11. The corpus file + +`problems/corpus.jsonl` holds 56 questions, one JSON object per line, written and checked by a person. +It is a benchmark for the stratum: there is no prompt, no response pair and nothing to fine tune on. +Each row says what the session has to end like, including the rows whose expected outcome is a refusal +to answer, and a `why` that says why. + +| Field | Type | Meaning | +|---|---|---| +| `id` | string | unique; `-`, sometimes with a third part (`-true`, `-false`, `-single`, `-unknown`, `-def`) | +| `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in | +| `kind` | string | one of the 19 statement kinds of the geometry language, or `negative` (6 rows that must not be read) | +| `question` | string | the question, between 18 and 306 characters, in the script of its variety: a whole figure, the definitions first and the claim about them last | +| `why` | string | the reason the row behaves as it does, written by the person who wrote the row | +| `expect` | object | the expectation, described below | + +| Variety (`lang`) | `en` | `it` | `es` | `zh` | `hi` | `ar` | +|---|---|---|---|---|---|---| +| Rows | 20 | 12 | 6 | 6 | 6 | 6 | + +| Kind | Rows | Kind | Rows | Kind | Rows | +|---|---|---|---|---|---| +| `collinear` | 13 | `find_circumcircle` | 3 | `between` | 1 | +| `perp` | 6 | `find_intersect` | 3 | `assume` | 1 | +| `negative` | 6 | `centroid` | 2 | `mid` | 1 | +| `par` | 4 | `define_circle` | 2 | `intersect` | 1 | +| `find_tangents` | 4 | `oncircle` | 2 | `define_line` | 1 | +| `right` | 2 | `circumcentre` | 1 | `cong` | 1 | +| | | `find_image` | 1 | `define_point` | 1 | + +The fields of `expect` are optional except `state` and `referee_clean`, which are present on every row. + +| Field | Rows | Meaning | +|---|---|---| +| `state` | 56 | the reading state the session must end in: `AGREED` 46, `SINGLE` 3, `PASSTHROUGH` 1, `NOT COVERED` 6 | +| `sentence` | 50 | the text of the geometry language both readers have to produce, exactly: the whole figure, in the order the bundle expects it | +| `answer_contains` | 36 | a substring the answer has to contain: a sentence of the geometry layer, or the certificate of a computed answer | +| `min_assurance` | 39 | the lowest assurance that is acceptable, on the scale of section 1 | +| `max_assurance` | 20 | the highest assurance that is acceptable: this is what pins the probes that must not rise | +| `no_answer` | 17 | `true` where the row is graded by the refusal: no answer may be shown at all | +| `referee_clean` | 56 | every envelope claim of the session must match what the referee of its node recomputed | + +The six rows with no `sentence` are exactly the six negative rows, where the reading itself has to fail. +The 17 rows with `no_answer` split in two: 6 are those negative rows, and 11 are agreed readings of a +figure that carries no claim the geometry layer can decide (`point-en`, `line-en`, `circle-en`, +`circle-it`, `assume-en`, `centroid-en`, `centroid-it`, `circumcentre-en`, `intersect-en`, `image-en`, +`mid-en-def`); on those eleven the assurance must be 0 and no answer may appear, which is the stratum +refusing to add an availability it does not have. + +## 12. Loading it + +Load the file with the `datasets` library, or with one `json.loads` per line, which needs no +dependency: + +```python +from datasets import load_dataset +rows = load_dataset("tailot/geometry-stratum", "corpus", split="train") +print(rows[0]) +``` + +This is the same file `tools/ask.py --corpus` walks over, and `lggeostratum/corpus.py` plus +`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 56 of 56 +rows agree with what they expect. + +## 13. Rights + +No license is declared for this dataset, its lexicons, its corpus or its code: reuse is not granted by +this page. The six lexicons, the 56 questions with their gold expectations, the grammar specifications, +the node data and the Python sources were written by hand as part of the LingoLOGOS project. Ask before +redistributing or building on them, and expect the answer to be yes for academic work with attribution. +Z3 is a separate product with its own license and is not redistributed here; `z3-solver` is only named +as a dependency in `requirements.txt`. The lexicons of Hindi, Arabic and Chinese describe written +varieties as this project needs them for questions about a figure drawn in words: they are not a general +purpose dictionary of those languages. + +## 14. Citation + +``` +@misc{lingologos_geometry_stratum, + title = {LingoLOGOS geometry-stratum: a question in six written varieties, the answer of the geometry layer, and an assurance that includes the reading}, + author = {LingoLOGOS project}, + year = {2026}, + url = {https://huggingface.co/datasets/tailot/geometry-stratum}, + note = {bundle of the geometry-stratum folder of the LingoLOGOS repository: 56 questions about a + figure drawn in words, in six written varieties, over the 19 statement kinds of the geometry + language, with six lexicons, two independent readers, eight node definitions with SMT claims, + the assurance rule min(geometry, reading) with the reading capped at 2, fault catalogue and + ablation over the node configurations, 255 tests} +} +``` diff --git a/agents/stratum_agent b/agents/stratum_agent new file mode 100644 index 0000000000000000000000000000000000000000..5824d86a508a46a375de53c7bb919c994f97a6be --- /dev/null +++ b/agents/stratum_agent @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Node executable of the geometry-stratum topology. + +The orchestrator starts this program once per turn, writes the incoming envelope as JSON on +stdin and reads the outgoing envelope from stdout. The behaviour is selected by --role, which +the topology sets to the node id (reader_a, reader_b, equivalence, coverage, invoker, boundary, +adversary or arbiter). Extra arguments added by the orchestrator are accepted and ignored. + +The node reads and writes the same envelope as the geometry topology: the dossier of the session +travels inside the natural language field between two markers, and the claim the node makes +about its own envelope travels in smtConstraints, where the referee of the orchestrator reads +it. Nothing here decides a mathematical fact: the sentence the readers agree on is handed to +the geometry topology as a separate process and its verdict is carried back untouched. +""" + +import argparse +import json +import os +import sys + +sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + +from lggeostratum import agents, faults # noqa: E402 + + +def main() -> int: + parser = argparse.ArgumentParser(description="geometry-stratum topology node") + parser.add_argument("--role", required=True, choices=sorted(agents.STEPS)) + parser.add_argument("--node-id", default=None) + args, _ignored = parser.parse_known_args() + faults.from_env() + incoming = json.loads(sys.stdin.read()) + outgoing = agents.run_step(args.role, incoming, args.node_id or args.role) + sys.stdout.write(json.dumps(outgoing)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/lexicon/ar.json b/lexicon/ar.json new file mode 100644 index 0000000000000000000000000000000000000000..16cc4572e234ea6153cb0df13263b61ea6e955bb --- /dev/null +++ b/lexicon/ar.json @@ -0,0 +1,275 @@ +{ + "lang": "ar", + "name": "العربية", + "script": "arabic", + "noise_chars": "", + "prefixes": ["ال", "وال", "بال", "فال", "لل", "و", "ب", "ل", "ف"], + "kinds": { + "define_point": { + "verbs": [ + "لتكن", + "خذ", + "ضع" + ], + "patterns": [ + "لتكن النقطة {P} إحداثياتها {V}" + ], + "frame": { + "sequences": [ + [ + "eq" + ] + ] + } + }, + "define_line": { + "verbs": [ + "ارسم", + "رسم" + ], + "patterns": [ + "ارسم المستقيم {E} المار بالنقطتين {P} و {Q}" + ], + "frame": { + "sequences": [ + [ + "through" + ] + ] + } + }, + "define_circle": { + "verbs": [ + "ارسم", + "رسم" + ], + "patterns": [ + "ارسم الدائرة {E} مركزها {P} مربع نصف القطر {V}", + "ارسم الدائرة {E} المارة بالنقاط {X}" + ], + "frame": { + "sequences": [ + [ + "center", + "radius_squared" + ], + [ + "through" + ] + ] + } + }, + "mid": { + "verbs": [ + "لتكن", + "خذ", + "ضع" + ], + "patterns": [ + "خذ {T} منتصف {P} و {Q}", + "لتكن {T} منتصف {P} و {Q}" + ], + "frame": { + "sequences": [ + [ + "let_mid" + ] + ] + } + }, + "collinear": { + "verbs": [ + "أثبت", + "برهن", + "أظهر" + ], + "patterns": [ + "أثبت أن {X} على استقامة واحدة" + ], + "frame": { + "sequences": [ + [ + "collinear" + ] + ] + } + }, + "perp": { + "verbs": [ + "أثبت", + "برهن", + "أظهر" + ], + "patterns": [ + "أثبت أن المستقيم {L} عمودي على المستقيم {K}" + ], + "frame": { + "sequences": [ + [ + "perp" + ] + ] + } + }, + "par": { + "verbs": [ + "أثبت", + "برهن", + "أظهر" + ], + "patterns": [ + "أثبت أن المستقيم {L} موازٍ للمستقيم {K}" + ], + "frame": { + "sequences": [ + [ + "par" + ] + ] + } + }, + "cong": { + "verbs": [ + "أثبت", + "برهن", + "أظهر" + ], + "patterns": [ + "أثبت أن القطعة {L} تساوي القطعة {K}" + ], + "frame": { + "sequences": [ + [ + "cong" + ] + ] + } + }, + "right": { + "verbs": [ + "أثبت", + "برهن", + "أظهر" + ], + "patterns": [ + "أثبت أن الزاوية {A} قائمة" + ], + "frame": { + "sequences": [ + [ + "right" + ] + ] + } + }, + "find_circumcircle": { + "neutral": true, + "verbs": [ + "أوجد", + "احسب" + ], + "patterns": [ + "أوجد الدائرة المحيطة بالمثلث {X}" + ], + "frame": { + "sequences": [ + [] + ] + } + }, + "find_tangents": { + "neutral": true, + "verbs": [ + "أوجد", + "احسب" + ], + "patterns": [ + "أوجد المماسات من {P} إلى الدائرة {E}" + ], + "frame": { + "sequences": [ + [ + "to_entity" + ] + ] + } + } + }, + "connectives": { + "and": ["و"], + "or": ["أو"], + "not": ["ليس"] + }, + "markers": { + "eq": ["إحداثياتها", "إحداثيات هي", "إحداثيات"], + "through": ["المار بالنقطتين", "المارة بالنقاط", "المار ب", "يمر ب", "يمر بالنقطتين"], + "center": ["مركزها", "مركزه هو", "مركزه"], + "radius_squared": ["مربع نصف القطر", "ومربع نصف القطر"], + "let_mid": ["منتصف", "نقطة منتصف"], + "collinear": ["على استقامة واحدة", "متساوية الاستقامة"], + "perp": ["عمودي على", "عمود على", "متعامد على"], + "par": ["موازٍ للمستقيم", "موازٍ ل", "موازي ل", "المتوازي مع"], + "cong": ["تساوي", "متساوية مع"], + "right": ["قائمة", "زاوية قائمة"], + "to_entity": ["إلى الدائرة", "إلى"] + }, + "noise": [ + "نقطة", "نقاط", "نقطتين", "مستقيم", "دائرة", "قطعة", "زاوية", "مثلث", + "مركز", "نصف", "قطر", "إحداثيات", "منتصف", "استقامة", "عمودي", "متعامد", + "مماس", "مماسات", "محيط", "محيطة", "المارة", "أن", "في", "على", "من", + "إلى", "هي", "ذلك", "هذا", "كل", "بين" + ], + "labels": { + "understood": "فُهم السؤال بهذه الصيغ", + "status": "الحالة", + "assurance": "المستوى {n} من 3", + "answer": "الجواب", + "reading": "القراءة", + "math_layer": "طبقة الهندسة", + "notes": "ملاحظات", + "examples": "تفهم الطبقة السؤال بهذه الصيغ", + "question": "اكتب السؤال بإحدى هذه الصيغ", + "check": "فحص SMT للطبقة : تأكيد {a} من {b} ظرف", + "kind_of": "النوع" + }, + "reading": { + "AGREED": "قرأ القارئان الجملة نفسها", + "PASSTHROUGH": "كان السؤال بلغة الطبقة نفسها", + "DISPUTED": "قرأ القارئان جملتين مختلفتين", + "NOT COVERED": "لم يفهم أي قارئ السؤال", + "AMBIGUOUS": "للسؤال قراءتان محتملتان", + "SINGLE": "قرأ قارئ واحد السؤال", + "TAMPERED": "الجملة لا تطابق السؤال", + "NONE": "لم يصل السؤال إلى الطبقة الرسمية" + }, + "reasons": { + "unknown_word": "كلمة غير معجمية : {word}", + "no_verb": "لا فعل في الجملة يعلن نوع الطلب", + "two_verbs": "يفعلان نوعين في الجملة : {kinds}", + "no_pattern": "الجملة لا تطابق أي صيغة في هذه اللغة", + "no_frame": "روابط الجملة لا تطابق صيغة النوع {kind}", + "multiple": "قراءتان للجملة : {first} و {second}", + "disagree": "اختلفت الجملتان اللتان قرأهما القارئان", + "markers": "روابط الجملة لا تناسب هذا النوع", + "bad_point": "الحقل {slot} لا يحتوي النقطة المطلوبة", + "bad_line": "الحقل {slot} لا يحتوي مستقيما", + "bad_angle": "الحقل {slot} لا يحتوي زاوية بثلاث نقاط", + "bad_entity": "الحقل {slot} لا يحتوي اسما لشكل", + "bad_value": "الحقل {slot} لا يحتوي قيمة", + "bad_slot": "الحقل {slot} الذي ينص عليه القواعد فارغ", + "unbalanced": "قوس لم يغلق", + "literal_count": "أعداد السؤال ليست في القراءة", + "geometry_unknown": "لم تجب طبقة الهندسة : {detail}", + "no_geometry": "السؤال الهندسي ليس بلغة الهندسة", + "boundary": "الجملة الرسمية المرسلة ليست القراءة المتفق عليها", + "referee": "لم يؤكد محكم SMT : {detail}", + "other": "لم تخرج من القراءة جملة رسمية" + }, + "examples": [ + "النقطة A إحداثياتها (0, 0)", + "أثبت أن A و B و C على استقامة واحدة", + "خذ M منتصف A و B", + "أثبت أن المستقيم A-B عمودي على المستقيم C-D", + "أوجد المماسات من P إلى الدائرة c" + ] +} diff --git a/lexicon/en.json b/lexicon/en.json new file mode 100644 index 0000000000000000000000000000000000000000..ebd8172e9b71190c02eeee670014526d000c22b5 --- /dev/null +++ b/lexicon/en.json @@ -0,0 +1,229 @@ +{ + "lang": "en", + "name": "English", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "define_point": { + "verbs": ["let", "place", "mark", "take", "has"], + "patterns": [ + "let {P} be the point with coordinates {V}", + "place the point {P} at {V}", + "the point {P} has coordinates {V}" + ], + "frame": {"sequences": [["eq"]]} + }, + "define_line": { + "verbs": ["draw", "let"], + "patterns": [ + "draw the line {E} through the points {P} and {Q}", + "let the line {E} pass through {P} and {Q}" + ], + "frame": {"sequences": [["through"]]} + }, + "define_circle": { + "verbs": ["draw", "let"], + "patterns": [ + "draw the circle {E} with center {P} and radius squared {V}", + "draw the circle {E} through {X}" + ], + "frame": {"sequences": [["center", "radius_squared"], ["through"]]} + }, + "mid": { + "verbs": ["let", "take"], + "patterns": ["let {T} be the midpoint of {P} and {Q}"], + "frame": {"sequences": [["let_mid"]]} + }, + "centroid": { + "verbs": ["let", "take"], + "patterns": ["let {T} be the centroid of the triangle {X}"], + "frame": {"sequences": [["let_centroid"]]} + }, + "circumcentre": { + "verbs": ["let", "take"], + "patterns": ["let {T} be the circumcenter of the triangle {X}"], + "frame": {"sequences": [["let_circumcentre"]]} + }, + "intersect": { + "verbs": ["let", "take"], + "patterns": ["let {T} be the intersection of the line {L} and the line {K}"], + "frame": {"sequences": [["let_intersect"]]} + }, + "assume": { + "verbs": ["suppose", "assume"], + "patterns": [ + "suppose {X} are not collinear", + "suppose {Y} are distinct" + ], + "frame": {"sequences": [["not_collinear"], ["distinct"]]} + }, + "collinear": { + "verbs": ["prove", "show", "verify"], + "patterns": [ + "prove that {X} are collinear", + "prove that the points {X} are collinear" + ], + "frame": {"sequences": [["collinear"]]} + }, + "perp": { + "verbs": ["prove", "show", "verify"], + "patterns": [ + "prove that the line {L} is perpendicular to the line {K}", + "prove that the line {L} is perpendicular to {K}", + "prove that line {L} is perpendicular to line {K}" + ], + "frame": {"sequences": [["perp"]]} + }, + "par": { + "verbs": ["prove", "show", "verify"], + "patterns": [ + "prove that the line {L} is parallel to the line {K}", + "prove that the line {L} is parallel to {K}", + "prove that line {L} is parallel to line {K}" + ], + "frame": {"sequences": [["par"]]} + }, + "cong": { + "verbs": ["prove", "show", "verify"], + "patterns": [ + "prove that the segment {L} is congruent to the segment {K}", + "prove that segment {L} is congruent to segment {K}" + ], + "frame": {"sequences": [["cong"]]} + }, + "right": { + "verbs": ["prove", "show", "verify"], + "patterns": ["prove that the angle {A} is a right angle"], + "frame": {"sequences": [["right"]]} + }, + "between": { + "verbs": ["prove", "show", "verify"], + "patterns": ["prove that {P} lies between {Q} and {R}"], + "frame": {"sequences": [["between"]]} + }, + "oncircle": { + "verbs": ["prove", "show", "verify"], + "patterns": [ + "prove that {P} lies on the circle with center {Q} through {R}" + ], + "frame": {"sequences": [["oncircle", "through"]]} + }, + "find_circumcircle": { + "neutral": true, + "verbs": ["find", "compute", "determine"], + "patterns": ["find the circumcircle of the triangle {X}"], + "frame": {"sequences": [[]]} + }, + "find_tangents": { + "neutral": true, + "verbs": ["find", "compute", "determine"], + "patterns": ["find the tangents from {P} to the circle {E}", + "find the tangents from {P} to circle {E}"], + "frame": {"sequences": [["to_entity"]]} + }, + "find_image": { + "neutral": true, + "verbs": ["find", "compute", "determine"], + "patterns": ["find the image of {P} under the transformation {E}"], + "frame": {"sequences": [["under"]]} + }, + "find_intersect": { + "neutral": true, + "verbs": ["find", "compute", "determine"], + "patterns": ["find the intersection of the line {L} and the line {K}", + "find the intersection of line {L} and line {K}", + "find where the line {L} and the line {K} meet"], + "frame": {"sequences": [[]]} + } + }, + "connectives": { + "and": ["and"], + "or": ["or"], + "not": ["not"] + }, + "markers": { + "eq": ["with coordinates", "has coordinates", "coordinates", "at"], + "through": ["through the points", "pass through", "through"], + "center": ["with center", "center of"], + "radius_squared": ["and radius squared", "radius squared"], + "not_collinear": ["are not collinear", "not collinear", "do not lie on one line"], + "distinct": ["are distinct", "distinct"], + "let_mid": ["the midpoint of", "midpoint of"], + "let_centroid": ["the centroid of the triangle", "centroid of the triangle"], + "let_circumcentre": ["the circumcenter of the triangle", "circumcenter of the triangle"], + "let_intersect": ["the intersection of", "point of intersection of"], + "to_entity": ["to the circle", "to circle"], + "under": ["under the transformation", "under"], + "collinear": ["are collinear", "lie on one line", "are on one line"], + "perp": ["is perpendicular to", "perpendicular to"], + "par": ["is parallel to", "parallel to"], + "cong": ["is congruent to", "congruent to"], + "right": ["is a right angle", "right angle"], + "between": ["lies between", "is between"], + "oncircle": ["lies on the circle with center", "is on the circle with center"] + }, + "noise": [ + "the", "a", "an", "of", "to", "on", "with", "that", "be", "is", "are", + "one", "its", "given", "known", + "point", "points", "line", "lines", "circle", "circles", "segment", "segments", + "angle", "angles", "triangle", "triangles", "transformation", "transformations", + "center", "centers", "coordinates", "radius", "squared", "image", "intersection", + "tangent", "tangents", "circumcircle", "circumference", "perpendicular", "parallel", + "congruent", "collinear", "between", "lie", "lies", "midpoint", "centroid", + "circumcenter", "distinct", "right", "same" + ], + "labels": { + "understood": "The question was understood in these varieties", + "status": "state", + "assurance": "level {n} of 3", + "answer": "answer", + "reading": "reading", + "math_layer": "geometry layer", + "notes": "notes", + "examples": "examples", + "question": "question", + "check": "Stratum SMT check: {a} of {b} envelopes confirmed", + "kind_of": "kind" + }, + "reading": { + "AGREED": "the two readers agree", + "PASSTHROUGH": "the question was already written in the formal language", + "DISPUTED": "the two readers disagree", + "NOT COVERED": "no reader understood the question", + "AMBIGUOUS": "the question allows two readings", + "TAMPERED": "the sentence does not match the question", + "SINGLE": "one reader understood the question", + "NONE": "the question does not reach the formal layer" + }, + "reasons": { + "unknown_word": "word outside the lexicon: {word}", + "no_verb": "no verb of the lexicon in the sentence", + "two_verbs": "verbs of two different groups in the sentence: {kinds}", + "no_pattern": "no pattern of the grammar recognised", + "no_frame": "the joints of the sentence follow no frame: {kind}", + "multiple": "the sentence matches two different readings: {first} and {second}", + "disagree": "the two readings do not coincide", + "markers": "the joints of the sentence are not enough to fill the frame", + "bad_point": "the slot of the points does not hold the points asked for: {slot}", + "bad_line": "the slot of the line does not hold a line: {slot}", + "bad_angle": "the slot of the angle does not hold three points: {slot}", + "bad_entity": "the slot of the entity does not hold a name: {slot}", + "bad_value": "the slot of the value does not hold a value: {slot}", + "bad_slot": "the slot {slot} of the grammar is not filled", + "unbalanced": "the sentence of the reading is not balanced", + "literal_count": "the numbers of the question are not all in the reading", + "geometry_unknown": "the geometry layer did not answer: {detail}", + "no_geometry": "the geometry question was not written in the language of geometry", + "boundary": "the question leaves the domain of the stratum", + "referee": "envelope discarded by the SMT referee: {detail}", + "other": "reading discarded" + }, + "examples": [ + "place the point A at (0, 0)", + "prove that the points A, B and C are collinear", + "let M be the midpoint of A and B", + "prove that the line AB is perpendicular to the line CD", + "find the tangents from P to the circle c" + ] +} diff --git a/lexicon/es.json b/lexicon/es.json new file mode 100644 index 0000000000000000000000000000000000000000..ad6eb64b9059335ccfb7c47fdb07ed54e2594b3c --- /dev/null +++ b/lexicon/es.json @@ -0,0 +1,224 @@ +{ + "lang": "es", + "name": "español", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "define_point": { + "verbs": ["sea", "fije", "marque", "tome", "tiene"], + "patterns": [ + "sea {P} el punto con coordenadas {V}", + "fije el punto {P} en {V}", + "el punto {P} tiene coordenadas {V}" + ], + "frame": {"sequences": [["eq"]]} + }, + "define_line": { + "verbs": ["trace", "dibuje", "sea"], + "patterns": [ + "trace la recta {E} por los puntos {P} y {Q}", + "sea la recta {E} que pasa por {P} y {Q}" + ], + "frame": {"sequences": [["through"]]} + }, + "define_circle": { + "verbs": ["trace", "dibuje", "sea"], + "patterns": [ + "trace la circunferencia {E} con centro {P} y radio al cuadrado {V}", + "trace la circunferencia {E} que pasa por {X}" + ], + "frame": {"sequences": [["center", "radius_squared"], ["through"]]} + }, + "mid": { + "verbs": ["sea", "tome"], + "patterns": ["sea {T} el punto medio de {P} y {Q}"], + "frame": {"sequences": [["let_mid"]]} + }, + "centroid": { + "verbs": ["sea", "tome"], + "patterns": ["sea {T} el baricentro del triangulo {X}"], + "frame": {"sequences": [["let_centroid"]]} + }, + "circumcentre": { + "verbs": ["sea", "tome"], + "patterns": ["sea {T} el circocentro del triangulo {X}"], + "frame": {"sequences": [["let_circumcentre"]]} + }, + "intersect": { + "verbs": ["sea", "tome"], + "patterns": ["sea {T} la interseccion de la recta {L} y la recta {K}"], + "frame": {"sequences": [["let_intersect"]]} + }, + "assume": { + "verbs": ["suponga", "admita"], + "patterns": [ + "suponga que {X} no son colineales", + "suponga que {Y} son distintos" + ], + "frame": {"sequences": [["not_collinear"], ["distinct"]]} + }, + "collinear": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": [ + "demuestre que {X} son colineales", + "demuestre que los puntos {X} son colineales" + ], + "frame": {"sequences": [["collinear"]]} + }, + "perp": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": [ + "demuestre que la recta {L} es perpendicular a la recta {K}", + "demuestre que la recta {L} es perpendicular a {K}" + ], + "frame": {"sequences": [["perp"]]} + }, + "par": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": [ + "demuestre que la recta {L} es paralela a la recta {K}", + "demuestre que la recta {L} es paralela a {K}" + ], + "frame": {"sequences": [["par"]]} + }, + "cong": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": [ + "demuestre que el segmento {L} es congruente con el segmento {K}" + ], + "frame": {"sequences": [["cong"]]} + }, + "right": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": ["demuestre que el angulo {A} es un angulo recto"], + "frame": {"sequences": [["right"]]} + }, + "between": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": ["demuestre que {P} esta entre {Q} y {R}"], + "frame": {"sequences": [["between"]]} + }, + "oncircle": { + "verbs": ["demuestre", "pruebe", "verifique", "muestre"], + "patterns": [ + "demuestre que {P} esta en la circunferencia con centro {Q} que pasa por {R}" + ], + "frame": {"sequences": [["oncircle", "through"]]} + }, + "find_circumcircle": { + "neutral": true, + "verbs": ["halle", "calcule", "determine"], + "patterns": ["halle la circunferencia circunscrita al triangulo {X}"], + "frame": {"sequences": [[]]} + }, + "find_tangents": { + "neutral": true, + "verbs": ["halle", "calcule", "determine"], + "patterns": ["halle las tangentes desde {P} a la circunferencia {E}"], + "frame": {"sequences": [["to_entity"]]} + }, + "find_image": { + "neutral": true, + "verbs": ["halle", "calcule", "determine"], + "patterns": ["halle la imagen de {P} bajo la transformacion {E}"], + "frame": {"sequences": [["under"]]} + }, + "find_intersect": { + "neutral": true, + "verbs": ["halle", "calcule", "determine"], + "patterns": ["halle el punto en comun de la recta {L} y la recta {K}"], + "frame": {"sequences": [[]]} + } + }, + "connectives": { + "and": ["y"], + "or": ["o"], + "not": ["no"] + }, + "markers": { + "eq": ["con coordenadas", "tiene coordenadas", "coordenadas", "en"], + "through": ["que pasa por", "pasa por", "por los puntos", "por"], + "center": ["con centro"], + "radius_squared": ["y radio al cuadrado", "radio al cuadrado"], + "not_collinear": ["no son colineales", "no colineales", "no yacen en una recta"], + "distinct": ["son distintos", "distintos"], + "let_mid": ["el punto medio de", "punto medio de"], + "let_centroid": ["el baricentro del triangulo", "baricentro del triangulo"], + "let_circumcentre": ["el circocentro del triangulo", "circocentro del triangulo"], + "let_intersect": ["la interseccion de", "el punto de interseccion de"], + "to_entity": ["a la circunferencia", "al circulo"], + "under": ["bajo la transformacion", "bajo"], + "collinear": ["son colineales", "estan en una recta", "yacen en una recta"], + "perp": ["es perpendicular a", "perpendicular a"], + "par": ["es paralela a", "paralela a"], + "cong": ["es congruente con", "congruente con"], + "right": ["es un angulo recto", "angulo recto"], + "between": ["esta entre", "se encuentra entre"], + "oncircle": ["esta en la circunferencia con centro", "se encuentra en la circunferencia con centro"] + }, + "noise": [ + "el", "la", "los", "las", "un", "una", "unos", "unas", "de", "del", "al", "con", + "que", "es", "son", "esta", "se", "encuentra", "su", "dado", "dada", "conocido", + "punto", "puntos", "recta", "rectas", "circunferencia", "circunferencias", "circulo", + "circulos", "segmento", "segmentos", "angulo", "angulos", "triangulo", "triangulos", + "transformacion", "transformaciones", "centro", "centros", "coordenadas", "radio", + "cuadrado", "imagen", "interseccion", "tangente", "tangentes", "circunscrita", + "perpendicular", "paralela", "congruente", "colineales", "colineal", "entre", + "yace", "yacen", "esta", "punto", "medio", "baricentro", "circocentro", "distintos", + "recto", "misma" + ], + "labels": { + "understood": "La pregunta se entendio en estas variantes", + "status": "estado", + "assurance": "nivel {n} de 3", + "answer": "respuesta", + "reading": "lectura", + "math_layer": "capa de geometria", + "notes": "notas", + "examples": "ejemplos", + "question": "pregunta", + "check": "Comprobacion SMT de la capa : {a} de {b} sobres confirmados", + "kind_of": "tipo" + }, + "reading": { + "AGREED": "los dos lectores estan de acuerdo", + "PASSTHROUGH": "la pregunta ya estaba escrita en el lenguaje formal", + "DISPUTED": "los dos lectores no estan de acuerdo", + "NOT COVERED": "ningun lector entendio la pregunta", + "AMBIGUOUS": "la pregunta admite dos lecturas", + "TAMPERED": "la frase no corresponde a la pregunta", + "SINGLE": "un solo lector entendio la pregunta", + "NONE": "la pregunta no llega a la capa formal" + }, + "reasons": { + "unknown_word": "palabra fuera del lexicon : {word}", + "no_verb": "ningun verbo del lexicon en la frase", + "two_verbs": "verbos de dos grupos distintos en la frase : {kinds}", + "no_pattern": "ningun modelo de la gramatica reconocido", + "no_frame": "los conectores de la frase no siguen ningun esquema : {kind}", + "multiple": "la frase corresponde a dos lecturas diferentes : {first} y {second}", + "disagree": "las dos lecturas no coinciden", + "markers": "los conectores de la frase no bastan para rellenar el esquema", + "bad_point": "el hueco de los puntos no contiene los puntos pedidos : {slot}", + "bad_line": "el hueco de la recta no contiene una recta : {slot}", + "bad_angle": "el hueco del angulo no contiene tres puntos : {slot}", + "bad_entity": "el hueco de la entidad no contiene un nombre : {slot}", + "bad_value": "el hueco del valor no contiene un valor : {slot}", + "bad_slot": "el hueco {slot} de la gramatica no esta rellenado", + "unbalanced": "la frase de la lectura no esta equilibrada", + "literal_count": "los numeros de la pregunta no estan todos en la lectura", + "geometry_unknown": "la capa de geometria no ha respondido : {detail}", + "no_geometry": "la pregunta geometrica no esta escrita en el lenguaje de la geometria", + "boundary": "la pregunta sale del dominio de la capa", + "referee": "sobre descartado por el referee SMT : {detail}", + "other": "lectura descartada" + }, + "examples": [ + "fije el punto A en (0, 0)", + "demuestre que los puntos A, B y C son colineales", + "sea M el punto medio de A y B", + "demuestre que la recta AB es perpendicular a la recta CD", + "halle las tangentes desde P a la circunferencia c" + ] +} diff --git a/lexicon/hi.json b/lexicon/hi.json new file mode 100644 index 0000000000000000000000000000000000000000..6f6ebe9bc9073fb110507b543f4b0979a8758840 --- /dev/null +++ b/lexicon/hi.json @@ -0,0 +1,281 @@ +{ + "lang": "hi", + "name": "हिन्दी", + "script": "devanagari", + "noise_chars": "", + "prefixes": [], + "kinds": { + "define_point": { + "verbs": [ + "मान लें", + "दिया गया है", + "लीजिए", + "लिखिए" + ], + "patterns": [ + "मान लें बिंदु {P} के निर्देशांक {V} हैं" + ], + "frame": { + "sequences": [ + [ + "eq" + ] + ] + } + }, + "define_line": { + "verbs": [ + "खींचिए", + "बनाइए" + ], + "patterns": [ + "खींचिए रेखा {E} बिंदु {P} और {Q} से गुजरती है", + "बनाइए रेखा {E} जो गुजरती है {P} और {Q} से" + ], + "frame": { + "sequences": [ + [ + "through" + ] + ] + } + }, + "define_circle": { + "verbs": [ + "खींचिए", + "बनाइए" + ], + "patterns": [ + "बनाइए वृत्त {E} का केंद्र {P} त्रिज्या का वर्ग {V} है", + "खींचिए वृत्त {E} केंद्र {P} त्रिज्या वर्ग {V}", + "बनाइए वृत्त {E} जो गुजरता है {X} से" + ], + "frame": { + "sequences": [ + [ + "center", + "radius_squared" + ], + [ + "through" + ] + ] + } + }, + "mid": { + "verbs": [ + "मान लें", + "दिया गया है", + "लीजिए" + ], + "patterns": [ + "मान लें {T} रेखाखंड {P} और {Q} का मध्यबिंदु है", + "मान लें {T} {P} और {Q} का मध्यबिंदु है" + ], + "frame": { + "sequences": [ + [ + "let_mid" + ] + ] + } + }, + "collinear": { + "verbs": [ + "सिद्ध कीजिए", + "सिद्ध", + "बताइए" + ], + "patterns": [ + "सिद्ध कीजिए कि {X} संरेख हैं" + ], + "frame": { + "sequences": [ + [ + "collinear" + ] + ] + } + }, + "perp": { + "verbs": [ + "सिद्ध कीजिए", + "सिद्ध", + "बताइए" + ], + "patterns": [ + "सिद्ध कीजिए कि रेखा {L} रेखा {K} के लंब है", + "सिद्ध कीजिए कि रेखा {L} लंब है रेखा {K} पर" + ], + "frame": { + "sequences": [ + [ + "perp" + ] + ] + } + }, + "par": { + "verbs": [ + "सिद्ध कीजिए", + "सिद्ध", + "बताइए" + ], + "patterns": [ + "सिद्ध कीजिए कि रेखा {L} रेखा {K} के समानांतर है", + "सिद्ध कीजिए कि रेखा {L} समानांतर है रेखा {K} के" + ], + "frame": { + "sequences": [ + [ + "par" + ] + ] + } + }, + "cong": { + "verbs": [ + "सिद्ध कीजिए", + "सिद्ध", + "बताइए" + ], + "patterns": [ + "सिद्ध कीजिए कि रेखाखंड {L} रेखाखंड {K} के बराबर है", + "सिद्ध कीजिए कि रेखाखंड {L} बराबर है रेखाखंड {K} के" + ], + "frame": { + "sequences": [ + [ + "cong" + ] + ] + } + }, + "right": { + "verbs": [ + "सिद्ध कीजिए", + "सिद्ध", + "बताइए" + ], + "patterns": [ + "सिद्ध कीजिए कि कोण {A} समकोण है" + ], + "frame": { + "sequences": [ + [ + "right" + ] + ] + } + }, + "find_circumcircle": { + "neutral": true, + "verbs": [ + "ज्ञात कीजिए", + "गणना कीजिए" + ], + "patterns": [ + "ज्ञात कीजिए त्रिभुज {X} का परिवृत्त" + ], + "frame": { + "sequences": [ + [] + ] + } + }, + "find_tangents": { + "neutral": true, + "verbs": [ + "ज्ञात कीजिए", + "गणना कीजिए" + ], + "patterns": [ + "ज्ञात कीजिए {P} से वृत्त {E} की स्पर्शरेखाएँ" + ], + "frame": { + "sequences": [ + [ + "to_entity" + ] + ] + } + } + }, + "connectives": { + "and": ["और"], + "or": ["या"], + "not": ["नहीं"] + }, + "markers": { + "eq": ["के निर्देशांक", "निर्देशांक"], + "through": ["से गुजरती", "से गुजरता", "गुजरती", "गुजरता"], + "center": ["का केंद्र", "के केंद्र"], + "radius_squared": ["त्रिज्या का वर्ग"], + "let_mid": ["का मध्यबिंदु", "मध्यबिंदु"], + "collinear": ["संरेख हैं", "संरेख"], + "perp": ["के लंब", "लंब है"], + "par": ["के समानांतर", "समानांतर है"], + "cong": ["के बराबर", "बराबर है"], + "right": ["समकोण है", "समकोण"], + "to_entity": ["से वृत्त की", "से वृत्त"] + }, + "noise": [ + "बिंदु", "रेखा", "वृत्त", "रेखाखंड", "कोण", "त्रिभुज", "केंद्र", "त्रिज्या", "वर्ग", + "निर्देशांक", "समकोण", "लंब", "समानांतर", "बराबर", "मध्यबिंदु", "परिवृत्त", + "स्पर्शरेखा", "स्पर्शरेखाएँ", "कि", "हैं", "है", "से", "का", "की", "के", "में", + "यह", "वह", "दिया", "गया", "हुआ", "पर", "तथा" + ], + "labels": { + "understood": "इन रूपों में प्रश्न समझा गया", + "status": "स्थिति", + "assurance": "3 में से स्तर {n}", + "answer": "उत्तर", + "reading": "पठन", + "math_layer": "ज्यामितीय परत", + "notes": "टिप्पणियाँ", + "examples": "इन रूपों में परत प्रश्न समझती है", + "question": "प्रश्न इन रूपों में से किसी में लिखिए", + "check": "परत की SMT जाँच : {b} लिफाफों में से {a} पुष्ट", + "kind_of": "प्रकार" + }, + "reading": { + "AGREED": "दोनों पाठकों ने एक ही वाक्य बनाया", + "PASSTHROUGH": "प्रश्न पहले से औपचारिक भाषा में था", + "DISPUTED": "दोनों पाठकों ने भिन्न वाक्य बनाए", + "NOT COVERED": "कोई पाठक प्रश्न नहीं समझा", + "AMBIGUOUS": "प्रश्न के दो पठन बनते हैं", + "SINGLE": "एक ही पाठक ने प्रश्न समझा", + "TAMPERED": "वाक्य प्रश्न से मेल नहीं खाता", + "NONE": "प्रश्न औपचारिक परत तक नहीं पहुँचा" + }, + "reasons": { + "unknown_word": "शब्द कोश में नहीं : {word}", + "no_verb": "वाक्य में कोई क्रिया प्रकार नहीं बताती", + "two_verbs": "वाक्य दो प्रकार घोषित करते हैं : {kinds}", + "no_pattern": "वाक्य इस भाषा के किसी रूप से मेल नहीं खाता", + "no_frame": "संबंधक प्रकार {kind} के किसी रूप से मेल नहीं खाते", + "multiple": "एक ही वाक्य के दो पठन : {first} और {second}", + "disagree": "दोनों पाठकों के वाक्य भिन्न हैं", + "markers": "वाक्य के संबंधक इस प्रकार के अपेक्षित नहीं हैं", + "bad_point": "{slot} में अपेक्षित बिंदु नहीं हैं", + "bad_line": "{slot} में रेखा नहीं है", + "bad_angle": "{slot} में तीन बिंदुओं का कोण नहीं है", + "bad_entity": "{slot} में आकृति का नाम नहीं है", + "bad_value": "{slot} में मान नहीं है", + "bad_slot": "व्याकरण का {slot} खाली है", + "unbalanced": "कोई कोष्ठक बंद नहीं है", + "literal_count": "प्रश्न की संख्याएँ पठन में नहीं हैं", + "geometry_unknown": "ज्यामितीय परत ने उत्तर नहीं दिया : {detail}", + "no_geometry": "ज्यामितीय प्रश्न ज्यामिति की भाषा में नहीं लिखा गया", + "boundary": "औपचारिक परत को भेजा गया वाक्य सहमत पठन नहीं है", + "referee": "SMT रेफरी ने पुष्टि नहीं की : {detail}", + "other": "पठन से औपचारिक वाक्य नहीं मिला" + }, + "examples": [ + "बिंदु A के निर्देशांक (0, 0) हैं", + "सिद्ध कीजिए कि A, B और C संरेख हैं", + "मान लें M, A और B का मध्यबिंदु है", + "सिद्ध कीजिए कि रेखा A-B लंब है रेखा C-D पर", + "ज्ञात कीजिए P से वृत्त c की स्पर्शरेखाएँ" + ] +} diff --git a/lexicon/it.json b/lexicon/it.json new file mode 100644 index 0000000000000000000000000000000000000000..32683ac2ac1b6ad735b1cc3b3a2f5c6484f21134 --- /dev/null +++ b/lexicon/it.json @@ -0,0 +1,245 @@ +{ + "lang": "it", + "name": "italiano", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "define_point": { + "verbs": ["sia", "siano", "sia dato", "siano date", "sia data", "consideriamo", "prendiamo"], + "patterns": [ + "sia {P} il punto di coordinate {V}", + "siano {P} e {Q} i punti di coordinate {V} e {W}", + "consideriamo il punto {P} di coordinate {V}" + ], + "frame": {"sequences": [["eq"]]} + }, + "assume": { + "verbs": ["supponiamo", "ipotizziamo", "sia noto", "dato che", "assumiamo"], + "patterns": [ + "supponiamo che i punti {X} non siano allineati", + "supponiamo che i punti {Y} siano distinti" + ], + "frame": {"sequences": [["not_collinear"], ["distinct"]]} + }, + "define_line": { + "verbs": ["disegna", "traccia", "considera", "sia"], + "patterns": [ + "disegna la retta {E} per i punti {P} e {Q}", + "sia {E} la retta per i punti {P} e {Q}" + ], + "frame": {"sequences": [["through"]]} + }, + "define_circle": { + "verbs": ["disegna", "traccia", "considera", "sia"], + "patterns": [ + "disegna la circonferenza {E} con centro {P} e raggio al quadrato {V}", + "sia {E} la circonferenza con centro {P} e raggio al quadrato {V}", + "disegna la circonferenza {E} per i punti {X}" + ], + "frame": {"sequences": [["center", "radius_squared"], ["through"]]} + }, + "mid": { + "verbs": ["sia", "sia dato", "consideriamo", "prendiamo"], + "patterns": [ + "sia {T} il punto medio di {P} e {Q}", + "sia {T} il punto medio del segmento {P} e {Q}" + ], + "frame": {"sequences": [["let_mid"]]} + }, + "centroid": { + "verbs": ["sia", "sia dato", "consideriamo"], + "patterns": ["sia {T} il baricentro del triangolo {X}"], + "frame": {"sequences": [["let_centroid"]]} + }, + "circumcentre": { + "verbs": ["sia", "sia dato", "consideriamo"], + "patterns": ["sia {T} il circocentro del triangolo {X}"], + "frame": {"sequences": [["let_circumcentre"]]} + }, + "intersect": { + "verbs": ["sia", "sia dato", "consideriamo", "sia noto"], + "patterns": [ + "sia {T} l intersezione di {L} e {K}", + "sia {T} un punto di intersezione di {L} e {K}" + ], + "frame": {"sequences": [["let_intersect"]]} + }, + "find_circumcircle": { + "neutral": true, + "verbs": ["trova", "calcola", "determina"], + "patterns": ["trova la circonferenza circoscritta al triangolo {X}"], + "frame": {"sequences": [[]]} + }, + "find_tangents": { + "neutral": true, + "verbs": ["trova", "calcola", "determina"], + "patterns": [ + "trova le tangenti da {P} alla circonferenza {E}", + "trova le rette tangenti da {P} alla circonferenza {E}" + ], + "frame": {"sequences": [["to_entity"]]} + }, + "find_intersect": { + "neutral": true, + "verbs": ["trova", "calcola", "determina"], + "patterns": [ + "trova il punto in comune tra la retta {L} e la retta {K}" + ], + "frame": {"sequences": [[]]} + }, + "collinear": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"], + "patterns": [ + "dimostra che {X} sono collineari", + "dimostra che i punti {X} sono collineari", + "dimostra che {X} sono allineati", + "dimostra che i punti {X} sono allineati" + ], + "frame": {"sequences": [["collinear"]]} + }, + "perp": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"], + "patterns": [ + "dimostra che {L} e perpendicolare a {K}", + "dimostra che la retta {L} e perpendicolare alla retta {K}", + "dimostra che la retta {L} perpendicolare alla retta {K}", + "dimostra che {L} perpendicolare a {K}", + "dimostra che {L} e ortogonale a {K}" + ], + "frame": {"sequences": [["perp"]]} + }, + "par": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"], + "patterns": [ + "dimostra che {L} e parallela a {K}", + "dimostra che la retta {L} e parallela alla retta {K}", + "dimostra che la retta {L} parallela alla retta {K}", + "dimostra che {L} parallela a {K}" + ], + "frame": {"sequences": [["par"]]} + }, + "cong": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"], + "patterns": [ + "dimostra che {L} e congruente a {K}", + "dimostra che il segmento {L} e congruente al segmento {K}", + "dimostra che il segmento {L} congruente al segmento {K}", + "dimostra che {L} congruente a {K}" + ], + "frame": {"sequences": [["cong"]]} + }, + "right": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"], + "patterns": [ + "dimostra che l angolo {A} e un angolo retto", + "dimostra che l angolo {A} e retto" + ], + "frame": {"sequences": [["right"]]} + }, + "between": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica"], + "patterns": ["dimostra che {P} e compreso fra {Q} e {R}"], + "frame": {"sequences": [["between"]]} + }, + "oncircle": { + "verbs": ["dimostra", "dimostrare", "prova", "verifica"], + "patterns": [ + "dimostra che {P} giace sulla circonferenza di centro {Q} e passante per {R}", + "dimostra che {P} sta sulla circonferenza di centro {Q} e passante per {R}" + ], + "frame": {"sequences": [["oncircle", "through"]]} + } + }, + "connectives": { + "and": ["e", "ed"], + "or": ["o"], + "not": ["non"] + }, + "markers": { + "eq": ["coordinate", "di coordinate", "le coordinate"], + "not_collinear": ["non sono allineati", "non sono collineari"], + "distinct": ["sono distinti", "sono diversi"], + "let_mid": ["punto medio", "punto medio di"], + "let_centroid": ["baricentro", "baricentro di"], + "let_circumcentre": ["circocentro", "circocentro di"], + "let_intersect": ["intersezione", "punto di intersezione"], + "through": ["passante per", "per i punti", "per"], + "center": ["centro", "con centro"], + "radius_squared": ["raggio al quadrato", "quadrato del raggio"], + "to_entity": ["alla circonferenza", "al cerchio"], + "collinear": ["sono collineari", "risultano collineari", "sono allineati", + "risultano allineati", "giacciono sulla stessa retta"], + "perp": ["perpendicolare a", "perpendicolare alla", "ortogonale a"], + "par": ["parallela a", "parallelo a", "parallela alla", "parallelo alla"], + "cong": ["congruente a", "congruente con", "congruente al", "congruente alla"], + "right": ["angolo retto", "e retto"], + "between": ["e compreso fra", "sta fra"], + "oncircle": ["giace sulla circonferenza di centro", "sta sulla circonferenza di centro"] + }, + "noise": [ + "la", "lo", "l", "i", "gli", "il", "un", "una", "uno", "dello", "della", "degli", + "dei", "del", "l'", "a", "al", "alla", "ai", "alle", "da", "dal", "dalla", "di", + "in", "con", "su", "sul", "sulla", "fra", "tra", "che", "di coordinate", + "punto", "punti", "retta", "rette", "segmento", "segmenti", "circonferenza", + "cerchio", "angolo", "angoli", "triangolo", "triangoli", "piano", "figura", + "intersezione", "tangente", "tangenti", "rette tangenti", "semiretta", "lunghezza", + "quadrato", "raggio", "coordinate", "circonferenza circoscritta", "compreso", + "passante", "giace", "sta", "ortogonale", "parallel", "parallela", "perpendicolare", + "congruente", "collineari", "allineati", "retto", "distincti", "su cui", "tale che" + ], + "labels": { + "understood": "domanda capita in queste forme", + "status": "stato", + "assurance": "livello {n} di 3", + "answer": "risposta", + "reading": "lettura", + "math_layer": "strato geometrico", + "notes": "note", + "examples": "lo strato capisce la domanda in queste forme", + "question": "riformula la domanda in una di queste forme", + "check": "controllo SMT dello strato : {a} di {b} buste confermate", + "kind_of": "tipo" + }, + "reading": { + "AGREED": "i due lettori hanno letto la stessa frase", + "PASSTHROUGH": "la domanda era gia nella lingua dello strato", + "DISPUTED": "i due lettori hanno letto frasi diverse", + "NOT COVERED": "nessun lettore ha capito la domanda", + "AMBIGUOUS": "la domanda ha due letture possibili", + "SINGLE": "un solo lettore ha capito la domanda", + "TAMPERED": "la frase non corrisponde alla domanda", + "NONE": "la domanda non e arrivata allo strato formale" + }, + "reasons": { + "unknown_word": "parola non nel lessico : {word}", + "no_verb": "nessun verbo nella frase annuncia il tipo di richiesta", + "two_verbs": "due verbi annunciano due tipi : {kinds}", + "no_pattern": "la frase non corrisponde a nessuna forma di questa lingua", + "no_frame": "i connettivi della frase non corrispondono a nessuna forma del tipo {kind}", + "multiple": "la frase ha due letture : {first} e {second}", + "disagree": "diversa la frase dei due lettori", + "markers": "i connettivi della frase non sono quelli attesi per questo tipo", + "bad_point": "lo slot {slot} non contiene un punto", + "bad_line": "lo slot {slot} non contiene una retta", + "bad_angle": "lo slot {slot} non contiene un angolo di tre punti", + "bad_entity": "lo slot {slot} non contiene una figura", + "bad_value": "lo slot {slot} non contiene un valore", + "bad_slot": "lo slot {slot} previsto dalla grammatica e vuoto", + "unbalanced": "una parentesi non e chiusa", + "literal_count": "i numeri della domanda non sono nella lettura", + "geometry_unknown": "lo strato geometrico non ha risposto : {detail}", + "no_geometry": "la domanda geometrica non e scritta nella lingua della geometria", + "boundary": "la frase formale inviata non e la lettura concordata", + "referee": "il referee SMT non ha confermato : {detail}", + "other": "la lettura non produce una frase formale" + }, + "examples": [ + "Sia A il punto di coordinate (0, 0).", + "Dimostra che i punti A, B e C sono collineari.", + "Sia M il punto medio di A e B.", + "Disegna la retta r per i punti A e B.", + "Dimostra che la retta AB e perpendicolare alla retta CD.", + "Trova le tangenti da P alla circonferenza c." + ] +} diff --git a/lexicon/zh.json b/lexicon/zh.json new file mode 100644 index 0000000000000000000000000000000000000000..5963c7f3c36a4ad438bd37d56518f5bb444bbcf4 --- /dev/null +++ b/lexicon/zh.json @@ -0,0 +1,159 @@ +{ + "lang": "zh", + "name": "中文", + "script": "cjk", + "noise_chars": "的了之把被给吧呢吗也则该是在为于其此各两上再经和与或不是", + "prefixes": [], + "kinds": { + "define_point": { + "verbs": ["设", "取", "标出"], + "patterns": [ + "设 点 {P} 的 坐标 为 {V}", + "设 {P} 的 坐标 为 {V}" + ], + "frame": {"sequences": [["eq"]]} + }, + "define_line": { + "verbs": ["作", "画"], + "patterns": ["作 直线 {E} 经过 点 {P} 和 {Q}"], + "frame": {"sequences": [["through"]]} + }, + "define_circle": { + "verbs": ["作", "画"], + "patterns": [ + "作 圆 {E} 的 圆心 为 {P} 半径 的 平方 为 {V}", + "作 圆 {E} 经过 {X}" + ], + "frame": {"sequences": [["center", "radius_squared"], ["through"]]} + }, + "mid": { + "verbs": ["设", "取"], + "patterns": ["设 {T} 为 {P} 和 {Q} 的 中点", "设 {T} 平分 {P} {Q}"], + "frame": {"sequences": [["let_mid"]]} + }, + "collinear": { + "verbs": ["证明", "求证"], + "patterns": ["证明 {X} 共线", "证明 点 {X} 共线"], + "frame": {"sequences": [["collinear"]]} + }, + "perp": { + "verbs": ["证明", "求证"], + "patterns": ["证明 直线 {L} 垂直于 直线 {K}"], + "frame": {"sequences": [["perp"]]} + }, + "par": { + "verbs": ["证明", "求证"], + "patterns": ["证明 直线 {L} 平行于 直线 {K}"], + "frame": {"sequences": [["par"]]} + }, + "cong": { + "verbs": ["证明", "求证"], + "patterns": ["证明 线段 {L} 全等于 线段 {K}"], + "frame": {"sequences": [["cong"]]} + }, + "right": { + "verbs": ["证明", "求证"], + "patterns": ["证明 角 {A} 为 直角"], + "frame": {"sequences": [["right"]]} + }, + "between": { + "verbs": ["证明", "求证"], + "patterns": ["证明 {P} 在 {Q} 和 {R} 之间"], + "frame": {"sequences": [["between"]]} + }, + "oncircle": { + "verbs": ["证明", "求证"], + "patterns": ["证明 {P} 在 圆心 为 {Q} 经过 {R} 的 圆 上", "证明 {P} 属于 圆心 为 {Q} 经过 {R} 的 圆"], + "frame": {"sequences": [["oncircle", "through"]]} + }, + "find_circumcircle": { + "neutral": true, + "verbs": ["求", "计算"], + "patterns": ["求 三角形 {X} 的 外接圆"], + "frame": {"sequences": [[]]} + }, + "find_tangents": { + "neutral": true, + "verbs": ["求", "计算"], + "patterns": ["求 从 {P} 到 圆 {E} 的 切线"], + "frame": {"sequences": [["to_entity"]]} + } + }, + "connectives": { + "and": ["和", "与"], + "or": ["或"], + "not": ["不"] + }, + "markers": { + "eq": ["的坐标为", "坐标为"], + "through": ["经过", "过"], + "center": ["的圆心为", "圆心为"], + "radius_squared": ["半径的平方为", "半径平方为", "的平方为"], + "let_mid": ["的中点", "中点", "平分"], + "collinear": ["共线"], + "perp": ["垂直于"], + "par": ["平行于"], + "cong": ["全等于"], + "right": ["为直角", "是直角"], + "between": ["在"], + "oncircle": ["圆心为"], + "to_entity": ["到圆"] + }, + "noise": [ + "点", "直线", "圆", "圆周", "线段", "角", "三角形", "半径", "平方", "中点", + "切线", "外接圆", "圆心", "坐标", "变换", "从", "到", "直角", "之间", "属于" + ], + "labels": { + "understood": "这种变体理解的问题", + "status": "状态", + "assurance": "三级中的第 {n} 级", + "answer": "答案", + "reading": "读法", + "math_layer": "几何层", + "notes": "备注", + "examples": "这一层能理解的句子", + "question": "请用下列形式之一重述问题", + "check": "几何层的 SMT 检查:{b} 个信封中有 {a} 个得到确认", + "kind_of": "类型" + }, + "reading": { + "AGREED": "一致:两位独立读者加上 SMT 约束", + "PASSTHROUGH": "句子已用几何语言写成,未作翻译", + "DISPUTED": "有分歧:两位读者给出不同的句子", + "NOT COVERED": "不在这种语言变体所覆盖的范围之内", + "AMBIGUOUS": "有歧义:可以有不止一种读法", + "SINGLE": "只有一种读法:另一位读者没有认出这个句子", + "TAMPERED": "被篡改:送往几何层的句子不是那个一致的读法", + "NONE": "没有读法" + }, + "reasons": { + "unknown_word": "{word} 不属于这种中文所覆盖的词", + "no_verb": "没有词宣布问题的类型", + "two_verbs": "句子宣布了不止一种问题类型:{kinds}", + "no_pattern": "句子的形状不匹配这种中文所覆盖的任何形状", + "no_frame": "连接词不匹配类型 {kind} 的任何形状", + "multiple": "同一句子有两种不同的读法:{first} 和 {second}", + "disagree": "两位读者给出两个不同的几何语言句子", + "markers": "句子的连接词不是该类型所期待的那些", + "bad_point": "{slot} 不是几何语言中所要求的点", + "bad_line": "{slot} 不是几何语言中的一条直线", + "bad_angle": "{slot} 不是三个点组成的角", + "bad_entity": "{slot} 不是图形的名字", + "bad_value": "{slot} 不是一个数值", + "bad_slot": "语法中的 {slot} 没有被填满", + "unbalanced": "有个圆括号或方括号没有闭合", + "literal_count": "句子中的数字在两位读者那里并不相同", + "geometry_unknown": "几何层不接受这个句子:{detail}", + "no_geometry": "这道几何题没有用几何语言书写", + "boundary": "送往几何层的句子不是那个一致的读法", + "referee": "SMT 裁判没有确认 {detail}", + "other": "读法没有得到几何语言中的一个句子" + }, + "examples": [ + "设点A的坐标为 (0, 0)", + "证明点A、B和C共线", + "设M为A和B的中点", + "证明直线AB垂直于直线CD", + "求从P到圆c的切线" + ] +} diff --git a/lggeostratum/__init__.py b/lggeostratum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..89bfdaf803cfaae5b790201850556eaf09f77536 --- /dev/null +++ b/lggeostratum/__init__.py @@ -0,0 +1,20 @@ +"""The library of the geometry-stratum topology. + +The geometry-stratum is the conversational stratum of the geometry topology: it accepts a problem +written in one of six language varieties, reads it into one sentence of the geometry language, +hands that sentence to the geometry layer as a separate process, and presents the verdict of +the geometry layer back in the language the user wrote in. + +Two words carry the whole design: + +* **reading**: what the stratum does is a reading, never a proof. The certainty of a reading + is not verifiable, because the space of natural language sentences is not. The stratum + therefore never raises the assurance the geometry layer reported, and every stage of the + reading can only take verdicts away. +* **coverage**: the multilingual layer is a documented fragment, in the same spirit as the + fragment of the geometry language. Anything outside it abstains with a question in the + language of the user, and never guesses. +""" + +__all__ = ["agents", "canonical", "compare", "corpus", "coverage", "decide", "faults", "invoker", + "lexicon", "pipeline", "protocol", "read_a", "read_b", "render", "segment"] diff --git a/lggeostratum/agents.py b/lggeostratum/agents.py new file mode 100644 index 0000000000000000000000000000000000000000..35affd4b21060957e9d34b9e101288640821fd5d --- /dev/null +++ b/lggeostratum/agents.py @@ -0,0 +1,364 @@ +"""The eight nodes of the stratum, one step function each. + +Every node has exactly one job and one claim of its own, and no node is allowed to conclude what +the next one is supposed to check. The chain is the same shape the reading layer of the geometry +experiment runs, only moved one level up: two independent readers instead of two independent +formalizers, an equivalence node instead of the equivalence checker, a coverage node that counts +the numbers the user wrote, an invoker that hands the agreed text to the geometry bundle as a +separate process, a boundary where that verdict enters this stratum, an adversary that re-derives +what the others asserted, and an arbiter that decides and answers in the user's language. + + reader_a surface reading: the words of the variety, in the order they appear + reader_b frame reading: which marker phrase sits in which gap of the frame + equivalence are the two readings the same problem? SMT2 answers, text identity is a shortcut + coverage did the readings keep every number the user wrote? + invoker call the geometry bundle, in another process, on one text + boundary the geometry verdict enters this stratum here, and only here + adversary re-derive the cross-channel checks and the cap the previous nodes implied + arbiter decide, cap the assurance, answer in the language of the user + +The invariant every node here obeys, and which the last three nodes each write down as SMT2 so the +referee of the orchestrator refutes its negation: the assurance this stratum shows is +``min(assurance of the geometry bundle, ceiling of the reading)``, and the ceiling is below the top +level of the bundle. A node may lower what the user sees; none may raise it. + +A figure problem is stated over several sentences -- the points and their coordinates, then the +claim -- so each reader node reads sentence by sentence and hands on the text those sentences form +together. That joining is a property of this layer, not of the readers: a reader sees one sentence +of one language, exactly as the grammar of its variety describes one sentence. +""" + +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, compare, coverage, decide, faults, invoker, protocol, read_a, read_b, render + +ORDER = ("reader_a", "reader_b", "equivalence", "coverage", "invoker", "boundary", "adversary", "arbiter") + +WORST = ("NOT COVERED", "AMBIGUOUS", "READ") + + +def _ast(dossier: Dict[str, Any]) -> str: + """One ASCII line describing the shape of the dossier, for the abstractSyntaxTree field.""" + def status_of(key: str) -> str: + part = dossier.get(key) + if not isinstance(part, dict): + return "absent" + return str(part.get("status") or part.get("state") or part.get("kind") or "present") + + return "Stratum(lang=%s, a=%s, b=%s, equiv=%s, cover=%s, math=%s, final=%s)" % ( + dossier.get("lang", "?"), status_of("reading_a"), status_of("reading_b"), + "same" if (dossier.get("compare") or {}).get("same") else "no", + "ok" if (dossier.get("coverage") or {}).get("ok") else "no", + (dossier.get("math") or {}).get("status", "absent"), + (dossier.get("final") or {}).get("state", "absent"), + ) + + +def _cap_claim(shown: int, ceiling: int) -> Tuple[List[str], List[str], str]: + """SMT2 for ``this node raised nothing``: the strict excess over the ceiling is refuted.""" + decls = ["(declare-const shown Real)", "(declare-const ceiling Real)"] + asserts = ["(assert (= shown %d))" % int(shown), "(assert (= ceiling %d))" % int(ceiling), + "(assert (> shown ceiling))"] + return decls, asserts, "unsat" + + +def _reader_claim(reading: Dict[str, Any], question: str) -> Tuple[List[str], List[str], str]: + """A reader claims one thing only: it dropped no number the user wrote.""" + step = compare.keeps(reading, question) + return step["declarations"], step["assertions"], step["claimed"] + + +def _read(lang: str, reader: Any, question: str) -> Dict[str, Any]: + """One reading of a whole question: each sentence on its own, then the text they build together. + + The geometry language states a figure problem as a sequence of commands, and a speaker states it + the same way -- the coordinates first, the claim last. Each sentence is read by the reader of + that variety, so a reading is still a reading of one sentence at a time; what the node adds is + the joining, and the state of the joined reading is the worst state among its parts. A reading + that lost one of the sentences of the figure is therefore never better than the reading that + read all of them. + """ + sentences = [item for item in canonical.split_sentences(question) if str(item).strip()] + if len(sentences) <= 1: + return reader.read(lang, question) + parts: List[Dict[str, Any]] = [] + notes: List[Dict[str, Any]] = [] + for sentence in sentences: + part = reader.read(lang, sentence) + parts.append(part) + for note in part.get("notes") or []: + if isinstance(note, dict): + notes.append(note) + state = "READ" + for part in parts: + if part.get("status") in WORST: + if WORST.index(str(part.get("status"))) < WORST.index(state): + state = str(part["status"]) + read_parts = [part for part in parts if part.get("math")] + text = " ".join("%s." % str(part["math"]).rstrip(".") for part in read_parts if str(part.get("math", "")).strip()) + kinds = [str(part["kind"]) for part in parts if part.get("kind")] + kind = kinds[0] if len(set(kinds)) == 1 and kinds else ("problem" if kinds else None) + reading: Dict[str, Any] = { + "status": state, + "kind": kind, + "math": text if state == "READ" else "", + "slots": {}, + "notes": notes, + "compound": True, + "parts": [{"kind": part.get("kind"), "slots": dict(part.get("slots") or {}), + "math": str(part.get("math") or ""), "status": part.get("status")} for part in parts], + } + reading["literals"] = compare.sorted_numbers(question) + return reading + + +def _apply_reader_fault(agent: str, reading: Dict[str, Any]) -> None: + """Corrupt a reading on purpose, for the ablation experiments: never in a normal session.""" + if not reading.get("kind") or reading.get("status") != "READ": + return + for kind in ("rename_slot", "merge_slots", "shift_number"): + if not faults.has(agent, kind): + continue + parts: List[Tuple[Dict[str, Any], Optional[Dict[str, Any]]]] = [] + if reading.get("compound"): + parts = [(part, part) for part in reading.get("parts") or [] if part.get("kind")] + else: + parts = [(reading, reading)] + for holder, part in parts: + if not part.get("kind"): + continue + order = canonical.slots_for(str(part["kind"])) + slots, changed = faults.mutate_reading(agent, str(part["kind"]), + dict(part.get("slots") or {}), order) + if not changed: + continue + faults.fire(agent, kind) + try: + printed = canonical.print_geometry(str(part["kind"]), slots) + except canonical.ReadingError: + reading["math"] = "" + reading["status"] = "NOT COVERED" + reading["notes"].append({"reason": "no_frame", "kind": part["kind"], "detail": kind}) + return + holder["slots"] = slots + holder["math"] = printed + reading["fault"] = kind + if reading.get("compound"): + reading["math"] = " ".join("%s." % str(item.get("math") or "").rstrip(".") + for item in reading.get("parts") or [] + if str(item.get("math") or "").strip()) + return + return + + +def _reading_node(agent: str, reader: Any, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]: + """Shared body of the two reader nodes: read the question, keep the reading, claim the numbers.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + question = str(dossier.get("question", "")) + lang = str(dossier.get("lang") or "") + direct = canonical.direct(question) + if direct is not None: + dossier["reading_direct"] = direct + reading = direct + else: + reading = _read(lang, reader, question) + _apply_reader_fault(node_id, reading) + dossier[agent] = reading + decls, asserts, claimed = _reader_claim(reading, question) + summary = "%s: %s %s" % (node_id, reading.get("status"), reading.get("math") or "") + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed) + + +def step_reader_a(incoming: Dict[str, Any], node_id: str = "reader_a") -> Dict[str, Any]: + """Reader A: surface patterns of the variety, reading left to right.""" + return _reading_node("reading_a", read_a, incoming, node_id) + + +def step_reader_b(incoming: Dict[str, Any], node_id: str = "reader_b") -> Dict[str, Any]: + """Reader B: the frame of the problem kind and the marker phrases sitting in its gaps.""" + return _reading_node("reading_b", read_b, incoming, node_id) + + +def step_equivalence(incoming: Dict[str, Any], node_id: str = "equivalence") -> Dict[str, Any]: + """Are the two readings one problem? The answer carries the SMT2 program that proves it.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + if faults.has(node_id, "rubber_stamp"): + faults.fire(node_id, "rubber_stamp") + first, second = dossier.get("reading_a") or {}, dossier.get("reading_a") or {} + else: + first, second = dossier.get("reading_a") or {}, dossier.get("reading_b") or {} + direct = dossier.get("reading_direct") + if direct is not None: + first, second = direct, dict(dossier.get("reading_b") or direct) + comparison = compare.equivalence(first, second) + dossier["compare"] = comparison + if first.get("math") and (comparison["same"] or not second.get("math")): + dossier["sent"] = comparison["left"] or str(first["math"]) + elif second.get("math") and not first.get("math"): + dossier["sent"] = comparison["right"] or str(second["math"]) + summary = "equivalence: %s (%s)" % ("same" if comparison["same"] else "not the same problem", + comparison["why"]) + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), + comparison["declarations"], comparison["assertions"], comparison["claimed"]) + + +def step_coverage(incoming: Dict[str, Any], node_id: str = "coverage") -> Dict[str, Any]: + """Did the readings keep every number the user wrote, and in the same multiset?""" + dossier, turn, tick, rcpt = protocol.start(incoming) + readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}] + if dossier.get("reading_direct") is not None: + readings = [dossier["reading_direct"], dossier.get("reading_b") or {}] + if faults.has(node_id, "rubber_stamp"): + faults.fire(node_id, "rubber_stamp") + claim = {"ok": True, "wrote": [], "kept": [], "missing": [], "added": [], + "declarations": ["(declare-const wrote_0 Real)"], "assertions": ["(assert (= wrote_0 0))"], + "claimed": "sat"} + else: + claim = coverage.coverage_claim(str(dossier.get("question", "")), [r for r in readings if r]) + dossier["coverage"] = claim + summary = "coverage: %s (%d numbers)" % ("kept" if claim["ok"] else "not kept", len(claim["wrote"])) + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), + claim["declarations"], claim["assertions"], claim["claimed"]) + + +def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]: + """Ask the geometry bundle, in its own process, about the text the readers agreed on.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + sentence = str(dossier.get("sent") or "") + if not sentence: + dossier["math"] = invoker.unavailable("no text was agreed on") + summary = "invoker: nothing to ask the geometry bundle" + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), + ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat") + verdict = invoker.solve(sentence) + dossier["math"] = verdict + wrote = compare.sorted_numbers(sentence) + echo = compare.sorted_numbers(str(verdict.get("problem_math") or "")) + decls, asserts = compare.elementwise(wrote, echo, "asked") + summary = "invoker: %s (%s)" % (verdict.get("status"), verdict.get("answer_text") or "no answer") + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), + decls, asserts + ["(assert (= 1 1))"] if not decls else asserts, + "sat" if wrote == echo else "unsat") + + +def _agreed_reading(dossier: Dict[str, Any]) -> Dict[str, Any]: + """The reading whose sentence this stratum sent to the geometry bundle. + + The echo of the bundle is a statement about one sentence, so it is checked against that + sentence and not against a reader that abstained. When only one of the two readers read the + question, the reading that carried the sentence is the one with standing here; a reading with + no sentence at all has nothing to be echoed and never vetoes. + """ + sent = str(dossier.get("sent") or "") + for key in ("reading_direct", "reading_a", "reading_b"): + item = dossier.get(key) or {} + if sent and str(item.get("math") or "") == sent: + return item + for key in ("reading_a", "reading_b", "reading_direct"): + item = dossier.get(key) or {} + if item.get("math"): + return item + return {} + + +def step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]: + """The geometry verdict enters this stratum here; the echo it carries is checked, not trusted.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + reading = _agreed_reading(dossier) + math_verdict = dict(dossier.get("math") or {}) + agreed = str(dossier.get("sent") or "") + echo = str(math_verdict.get("problem_math") or "") + if echo: + matches = coverage.echo_matches(reading, math_verdict) + decls, asserts = compare.elementwise(compare.sorted_numbers(agreed), compare.sorted_numbers(echo), "echo") + claimed = "sat" if matches else "unsat" + else: + # The bundle answered no text at all: there is nothing to compare, and the honest claim is + # the empty one, which is satisfiable. A node that wanted to look busy here would be + # asserting something it has no evidence about. + matches = True + decls, asserts, claimed = [], ["(assert (= 1 1))"], "sat" + if faults.has(node_id, "tamper_math") and echo: + tampered, changed = faults.mutate_sentence(node_id, echo) + if changed: + faults.fire(node_id, "tamper_math") + math_verdict["problem_math"] = tampered + math_verdict["fault"] = "tamper_math" + dossier["math"] = math_verdict + dossier["echo_ok"] = bool(matches) + summary = "boundary: %s echoed=%s" % (math_verdict.get("status"), "yes" if matches else "no") + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), + decls, asserts, claimed) + + +def step_adversary(incoming: Dict[str, Any], node_id: str = "adversary") -> Dict[str, Any]: + """Re-derive what the previous nodes asserted, and write the cap as an inequality to refute.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}] + if dossier.get("reading_direct") is not None: + readings = [dossier["reading_direct"], dossier.get("reading_b") or {}] + comparison = dossier.get("compare") + math_verdict = dossier.get("math") or {} + cover = dossier.get("coverage") + if faults.has(node_id, "rubber_stamp"): + faults.fire(node_id, "rubber_stamp") + echo_ok = True + else: + echo_ok = True + if math_verdict.get("problem_math"): + for item in [_agreed_reading(dossier)] + [one for one in readings if one.get("math")]: + if item.get("math") and not coverage.echo_matches(item, math_verdict): + echo_ok = False + dossier["echo_ok"] = bool(echo_ok) + state = decide.state_of(readings, comparison, cover, math_verdict if math_verdict.get("status") else None, + dossier.get("reading_direct"), echo_ok) + ceiling = decide.CEILING[state] + shown = min(ceiling, int(math_verdict.get("assurance", 0) or 0)) + dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown, + "math_assurance": int(math_verdict.get("assurance", 0) or 0)} + decls, asserts, claimed = _cap_claim(shown, ceiling) + summary = "adversary: ceiling %d, shown %d, echo %s" % (ceiling, shown, "ok" if echo_ok else "mismatch") + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed) + + +def step_arbiter(incoming: Dict[str, Any], node_id: str = "arbiter") -> Dict[str, Any]: + """Decide, cap, and answer in the language the user wrote in.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + final = decide.decide(dossier) + if faults.has(node_id, "force_assurance"): + faults.fire(node_id, "force_assurance") + final = decide.raise_assurance(final, 3) + dossier["final"] = final + dossier["reply"] = render.reply(dossier, final) + ceiling = int(final.get("ceiling", 0) or 0) + decls, asserts, claimed = _cap_claim(int(final.get("assurance", 0) or 0), ceiling) + summary = "arbiter: %s (assurance %d) %s" % (final["state"], final["assurance"], final["answer"] or "") + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed) + + +STEPS = { + "reader_a": step_reader_a, + "reader_b": step_reader_b, + "equivalence": step_equivalence, + "coverage": step_coverage, + "invoker": step_invoker, + "boundary": step_boundary, + "adversary": step_adversary, + "arbiter": step_arbiter, +} + + +def run_step(role: str, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]: + """Run one role, containing any unexpected exception as a crash entry in the dossier. + + A node that crashes must not stop the session: the arbiter then reports the state NONE with + zero assurance, so the user is never left with a half-built answer and never with an invented + one either. + """ + try: + return STEPS[role](incoming, node_id) + except Exception as exc: # noqa: BLE001 - containment is the whole point of this wrapper + dossier, turn, tick, rcpt = protocol.start(incoming) + dossier.setdefault("crash", {})[role] = "%s: %s" % (type(exc).__name__, str(exc)[:120]) + return protocol.envelope(node_id, rcpt, turn, tick, "%s crashed" % role, "Crashed", dossier, + [], ["(assert true)"], "sat") diff --git a/lggeostratum/canonical.py b/lggeostratum/canonical.py new file mode 100644 index 0000000000000000000000000000000000000000..eae9c811d19e594cc0ab351e996245250eef675a --- /dev/null +++ b/lggeostratum/canonical.py @@ -0,0 +1,662 @@ +"""The canonical sentence: one printer for the geometry language, shared by both readers. + +A reading is a mapping from a surface sentence to **one sentence of the geometry language**, +which is what the geometry layer is handed. The printers here are deliberately small and +exhaustive: each covered kind has a fixed template, so the only freedom a reader has is how it +decided the kind and where it cut the slots. That decision is what the two readers must agree on. + +The kinds covered by the multilingual reading layer are a subset of the sentence forms of the +geometry language: the Euclidean track, with declared points, lines and circles, the classic +constructions (midpoint, centroid, circumcenter, intersection) and the coordinate predicates +(collinearity, perpendicularity, parallelism, congruence, right angle, betweenness, incidence on +a circle). The rest of the geometry language -- conics, the spherical and the hyperbolic track, +the exact predicates over the rational plane -- stays available through the direct mode: a +sentence already written in the geometry language is passed through untouched, declarations +included. + +A geometry problem is a sequence of sentences, each ending with a full stop. This module always +prints the terminating full stop, and only this module writes it: a reader that lost the stop has +lost the shape of the language, and the coverage node counts it. +""" + +import re +from typing import Any, Dict, List, Optional, Tuple + +KINDS = ("define_point", "define_line", "define_circle", "assume", "mid", "centroid", + "circumcentre", "intersect", "find_circumcircle", "find_intersect", "find_tangents", + "find_image", "collinear", "perp", "par", "cong", "right", "between", "oncircle") + +# For each kind, the accepted slot sets and the template each one prints to. A kind with two +# forms (the circle given by a center and a radius, or by three points; the assumption about +# three points not being collinear, or about two points being distinct) has two entries, and a +# reader that cannot tell which one the sentence describes reports the pair as ambiguous. The slots +# X and Y hold a list of point names: the geometry language states a collinearity, a circumcircle +# and an assumption about a list it writes in one breath ("A, B and C"), so the list arrives from a +# reader as one region and is printed as one list. +TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = { + "define_point": [(("P", "V"), "Point {P} = {V}")], + "define_line": [(("E", "P", "Q"), "Line {E} through {P} and {Q}")], + "define_circle": [(("E", "P", "V"), "Circle {E} with center {P} and radius squared {V}"), + (("E", "X"), "Circle {E} through {X}")], + "assume": [(("X",), "Assume {X} are not collinear"), + (("Y",), "Assume {Y} are distinct")], + "mid": [(("T", "P", "Q"), "Let {T} be the midpoint of {P} and {Q}")], + "centroid": [(("T", "X"), "Let {T} be the centroid of triangle {X}")], + "circumcentre": [(("T", "X"), "Let {T} be the circumcenter of triangle {X}")], + "intersect": [(("T", "L", "K"), "Let {T} be the intersection of {L} and {K}")], + "find_circumcircle": [(("X",), "Find the circumcircle of {X}")], + "find_intersect": [(("L", "K"), "Find the intersection of {L} and {K}")], + "find_tangents": [(("P", "E"), "Find the tangents from {P} to circle {E}")], + "find_image": [(("P", "E"), "Find the image of {P} under {E}")], + "collinear": [(("X",), "Prove that {X} are collinear")], + "perp": [(("L", "K"), "Prove that {L} is perpendicular to {K}")], + "par": [(("L", "K"), "Prove that {L} is parallel to {K}")], + "cong": [(("L", "K"), "Prove that {L} is congruent to {K}")], + "right": [(("A",), "Prove that angle {A} is a right angle")], + "between": [(("P", "Q", "R"), "Prove that {P} lies between {Q} and {R}")], + "oncircle": [(("P", "Q", "R"), "Prove that {P} lies on the circle with center {Q} through {R}")], +} + +SLOT_ORDER = {kind: [slot for slot, _template in variants] + for kind, variants in TEMPLATES.items()} + +VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [slots for slots, _ in variants] + for kind, variants in TEMPLATES.items()} + +_POINT = re.compile(r"[A-Z][A-Za-z0-9_]*") + +# A line or an angle written as one word: "AB" is the line through A and B, "ABC" is the angle at +# B. The split is exact -- two names, three names -- so a name that is not exactly that many names +# stays the name it is. +_GLUED_PAIR = re.compile(r"([A-Z][a-z0-9_]*)([A-Z][a-z0-9_]*)") +_GLUED_TRIPLE = re.compile(r"([A-Z][a-z0-9_]*)([A-Z][a-z0-9_]*)([A-Z][a-z0-9_]*)") + + +class ReadingError(ValueError): + """A reading cannot be printed as a sentence of the geometry language.""" + + +def print_geometry(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> str: + """Print one reading as a sentence of the geometry language, full stop included. + + The slot values arrive as the two readers wrote them, and the two of them write the same + value differently: reader A cuts a slot between the words of a surface pattern, reader B reads + the whole region between two joints of the language, keyword and conjunctions included. The + normalisation here is where that difference is settled, and it is shared for exactly the same + reason the two formalizers of the geometry topology share one grammar: a value the two readings + print to different sentences is not one reading, and a value that is not a name of the + geometry language is refused out loud rather than carried into the geometry layer. + + ``joins`` are the conjunctions of the variety (Italian ``e``, Chinese ``he``) and ``keywords`` + the words with which that variety says *line*, *circle*, *angle*, *segment*: both lists come + from the lexicon of the variety, because a name of a figure written by a person in their own + language arrives together with the words around it. + """ + values = normalize_slots(kind, slots, joins, keywords) + wanted = tuple(name for name in _order(kind) if name in values and values[name] != "") + for slots_set, template in TEMPLATES[kind]: + if set(slots_set) == set(wanted): + missing = [name for name in slots_set if not values.get(name, "").strip()] + if missing: + raise ReadingError("the %s reading has no value for %s" % (kind, ", ".join(missing))) + extra = [name for name in values if name not in slots_set] + if extra: + raise ReadingError("the %s reading has no slot %s" % (kind, ", ".join(extra))) + body = template.format(**{name: values[name] for name in slots_set}) + return tidy(body) + "." + raise ReadingError("the %s reading fills the slots %s, which is not a form of the kind" + % (kind, ", ".join(sorted(wanted)))) + + +# The sibling bundle of this project is printed by a function named print_math; the geometry layer +# is printed by this one, and the alias keeps the readers of the two bundles interchangeable. +print_math = print_geometry + + +def is_name(token: str) -> bool: + """Whether a token is a point name of the geometry language.""" + return bool(_POINT.fullmatch(token)) + + +# The rule table of the geometry bundle names a line, a circle, a transformation with a small +# letter. The atomiser of a variety sees that letter on its own, and the only thing telling it +# from a word of the variety is that no phrase of the lexicon claims it: both readers use this. +_ENTITY = re.compile(r"[a-z]") + + +def is_entity_name(token: str) -> bool: + """Whether a token is the name of a line, of a circle, of a transformation.""" + return bool(_ENTITY.fullmatch(token)) + + +def split_units(text: str, joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> List[List[str]]: + """The entities a slot region holds, as groups of tokens, in the order they were written. + + A region of a geometry sentence is a string the reader cut out of the sentence, and inside it + the entities are separated by commas and by the conjunctions of the variety: ``the circle c + with center O`` and ``la circonferenza c con centro O`` cut to the same two entities once the + comma, the conjunction and the keyword of the entity are accounted for. A keyword of the + language opens the entity it introduces, and two names joined by a hyphen are one entity -- + the line ``A-B`` and the angle ``A-B-C`` are written as single names by the geometry language + itself. A relation word (=, <, >) opens a unit too: no slot of the geometry language holds an + operator, so an operator always stands between two values of a region. + """ + tokens: List[str] = [] + for token in tidy(text).split(" "): + if token and token != "-": + tokens.append(token) + cut = {",", "and"} + separators = {fold_join(word) for word in joins} | cut + openers = set(keywords) | {fold_join(word) for word in keywords} + groups: List[List[str]] = [] + current: List[str] = [] + for token in tokens: + low = token.lower() + if token == "," or low == "and" or low in separators: + if current: + groups.append(current) + current = [] + continue + if token and all(character in "=<>!" for character in token): + if current: + groups.append(current) + current = [] + continue + if (low in keywords or fold_join(low) in openers) and not ( + current and current[-1].lower() in openers): + if current: + groups.append(current) + current = [] + current.append(token) + continue + current.append(token) + if current: + groups.append(current) + return groups + + +_JOIN_FOLD_CACHE: Dict[str, str] = {} + + +def fold_join(word: str) -> str: + """The comparison form of a conjunction of a variety (``fold`` from the atomiser).""" + if word not in _JOIN_FOLD_CACHE: + from .segment import fold + _JOIN_FOLD_CACHE[word] = fold(word) + return _JOIN_FOLD_CACHE[word] + + +def _unit_is_hyphenated(unit: List[str]) -> bool: + return len(unit) > 1 and all("-" in token and _POINT.fullmatch(part) + for token in unit for part in token.split("-")) + + +# Which keyword of the geometry language names the entity held by the entity slot of each kind: +# a tangency is taken to a *circle*, the image of a point is taken under a *transformation*, and +# the declaration of a line or of a circle names that line or circle. +ENTITY_KEYWORD_FOR = {"define_line": "line", "define_circle": "circle", + "find_tangents": "circle", "find_image": "transformation"} + + +def kind_entity_keyword(kind: str, slot: str = "E") -> str: + """The figure the entity slot of a kind names, so that the word of the variety can be read off.""" + keyword = ENTITY_KEYWORD_FOR.get(kind) + if keyword is None: + raise ReadingError("the kind %s has no entity slot" % kind) + return keyword + + +# Which word of the geometry language introduces a line slot: a congruence is stated of two +# *segments*, a perpendicularity and a parallelism of two *lines*, and the rule of the language +# asks for that word, so the slot carries it. +LINE_WORD_FOR = {"cong": "segment"} + + +def normalize_slot(kind: str, name: str, text: str, joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> str: + """One slot value, printed in the shape the geometry language wants for that slot. + + A value that is not a name of the language -- a lowercase word standing where a point should + be, a bare letter that is not a name, an unbalanced expression -- is refused here, in one + place, by both readers. + """ + slot_type = SLOT_TYPES.get(name) + if slot_type is None: + raise ReadingError("the kind %s has no slot %s" % (kind, name)) + units = split_units(text, joins, keywords) + if slot_type == "value": + if len(units) != 1: + raise ReadingError("the value of %s %s holds %d entities" + % (kind, name, len(units))) + cleaned = value(" ".join(units[0])) + if cleaned is None: + raise ReadingError("the value of %s %s is not an expression of the language: %r" + % (kind, name, text)) + return cleaned + if slot_type in ("points2", "points3"): + need = 2 if slot_type == "points2" else 3 + names = point_names(text) + if len(names) == 1: + # One word holding the whole list: Chinese writes "ABC" for the three points of a + # triangle, and so does a person in Rome who types fast. The expansion is exact, so a + # run that is not exactly the number of names the slot holds stays one name. + glued = (_GLUED_TRIPLE if need == 3 else _GLUED_PAIR).fullmatch(names[0]) + if glued: + names = list(glued.groups()) + if len(names) != need: + raise ReadingError("the list slot %s of %s holds %d point names, not %d: %r" + % (name, kind, len(names), need, text)) + return point_list(", ".join(names), need) + if slot_type == "point": + if len(units) != 1: + raise ReadingError("the point slot %s of %s holds %d entities" + % (name, kind, len(units))) + unit = units[0] + if _unit_is_hyphenated(unit): + return "-".join(unit) + # A variety says "the point A", and Chinese writes one character per morpheme, so the unit + # of a point slot is the name plus the words that introduce it. The name is what the + # geometry language wants, and a second name in the same unit is a second point, which the + # slot cannot hold. + names = [token for token in unit if is_name(token)] + if len(names) == 1: + return names[0] + raise ReadingError("the value of %s %s is not a point name: %r" % (kind, name, text)) + if slot_type == "entity": + found = _entity_name(text, keywords) + if found is None: + raise ReadingError("the entity slot %s of %s is not a named entity: %r" + % (kind, name, text)) + # The word of the figure belongs to the template, not to the slot: the geometry language + # has one rule per shape ("Circle c through ...", "to circle c", "under t"), so a slot that + # carried the word too would print it twice and stop matching its rule. + return found + if slot_type == "line": + word = LINE_WORD_FOR.get(kind, "line") + names = point_names(text) + if len(names) == 2: + return "%s %s-%s" % (word, names[0], names[1]) + if len(names) == 1: + glued = _GLUED_PAIR.fullmatch(names[0]) + if glued: + # The people who write geometry glue the two names of a line together: "AB" is the + # line through A and B, and it is the shape every variety puts in front of its word + # for line. A run that is not two names exactly stays a name, and the geometry + # layer decides whether it knows that line. + return "%s %s-%s" % (word, glued.group(1), glued.group(2)) + else: + named = _entity_name(text, keywords) + if named is not None: + return "%s %s" % (word, named) + raise ReadingError("the value of %s %s is not a line of the language: %r" + % (kind, name, text)) + if slot_type == "angle": + names = point_names(text) + if len(names) == 1: + glued = _GLUED_TRIPLE.fullmatch(names[0]) + if glued: + names = list(glued.groups()) + if len(names) == 3: + return "%s-%s-%s" % tuple(names) + raise ReadingError("the value of %s %s is not an angle of the language: %r" + % (kind, name, text)) + raise ReadingError("the slot type %s is not one of the shapes of the language" % slot_type) + + +_WORD_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*") + + +def _entity_name(text: str, keywords: Tuple[str, ...] = ()) -> Optional[str]: + """The name of the figure an entity region holds, written as the geometry language writes it. + + The name of a line, of a circle or of a transformation is the last word of the region a reader + found: a variety puts its own word for the figure in front of the name ("la retta r", the + characters for line and then the letter), and those words are words of its lexicon, which the + lexicon also lists as the words that introduce an entity, while the name is not one of them. + """ + openers = set(keywords) | {fold_join(word) for word in keywords} + for token in reversed(tidy(text).split()): + if not _WORD_NAME.fullmatch(token): + continue + if token.lower() in openers or fold_join(token) in openers: + continue + return token.lower() + return None + + +def normalize_slots(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> Dict[str, str]: + """Every slot of a reading, normalised to the shape of the geometry language.""" + return {name: normalize_slot(kind, name, text, joins, keywords) + for name, text in sorted(slots.items()) if text and text.strip()} + + +def _order(kind: str) -> List[str]: + if kind not in TEMPLATES: + raise ReadingError("the kind %s is not one of the kinds the reading layer covers" % kind) + seen: List[str] = [] + for slots in VARIANTS[kind]: + for name in slots: + if name not in seen: + seen.append(name) + return seen + + +def slots_for(kind: str) -> List[str]: + return _order(kind) + + +# The words the geometry language itself uses to hold a slot in place. Reader B reads a sentence +# by these joints, so it needs them as names, not as text inside a template. +_MARKER_PHRASE = { + "eq": "=", + "not_collinear": "are not collinear", + "distinct": "are distinct", + "let_mid": "be the midpoint of", + "let_centroid": "be the centroid of triangle", + "let_orthocentre": "be the orthocenter of triangle", + "let_circumcentre": "be the circumcenter of triangle", + "let_intersect": "be the intersection of", + "find_circumcircle": "the circumcircle of", + "find_intersect": "the intersection of", + "find_tangents": "the tangents from", + "to_entity": "to circle", + "find_image": "the image of", + "under": "under", + "collinear": "are collinear", + "perp": "is perpendicular to", + "par": "is parallel to", + "cong": "is congruent to", + "right": "is a right angle", + "between": "lies between", + "oncircle": "lies on the circle with center", + "through": "through", + "center": "with center", + "radius_squared": "and radius squared", +} +# The conjunction that lists entities is deliberately absent here: it is a connective of the +# variety, not a joint of a form, and the gap it sits in is read as no joint at all. +_PHRASE_MARKER = {phrase: name for name, phrase in _MARKER_PHRASE.items()} + +# The joint names, exported so that the lexicon and the two readers can share one list. +MARKER_NAMES = tuple(sorted(_MARKER_PHRASE)) + +# What kind of value each slot of the geometry language takes. A slot letter is a type here, and +# this is the one place where the two readers and the corpus can check a slot against the same +# shape: the reading layer never accepts a value that is not a name of the language. +SLOT_TYPES = {"P": "point", "Q": "point", "R": "point", "S": "point", "T": "point", + "E": "entity", "L": "line", "K": "line", "A": "angle", "V": "value", + "X": "points3", "Y": "points2"} + +# The reason a reader reports when a slot holds something that is not a value of the language. A +# list of points is reported as a point problem, so that the lexicon of a variety has one word for +# what went wrong with a name and not one per list shape. +SLOT_REASON = {"points3": "point", "points2": "point"} + + +def slot_reason(name: str) -> str: + """The name of the shape a slot of this name expects, as a reader reports it.""" + shape = SLOT_TYPES.get(name, "slot") + return SLOT_REASON.get(shape, shape) + + +def template_for(kind: str, variant: Tuple[str, ...]) -> str: + """The template a kind prints for one slot set.""" + for slots, template in TEMPLATES[kind]: + if tuple(slots) == tuple(variant): + return template + raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(variant))) + + +_SLOT_LETTERS = "PQRSTKELOGYAXV" + + +def gap_markers(kind: str, variant: Tuple[str, ...]) -> List[Optional[str]]: + """The joints a form of the geometry language puts around its slots, in order. + + The list has one entry per gap: before the first slot, between consecutive slots, after the + last one. ``None`` marks a gap with no joint, which is where the verb of the sentence sits in + every language. This is reader B's skeleton: the slots of a reading are the entities that + fall between those joints, and a joint may not be missing or out of order. + """ + parts = re.split(r"\{([%s])\}" % _SLOT_LETTERS, template_for(kind, variant)) + gaps: List[Optional[str]] = [] + for index in range(0, len(parts), 2): + literal = parts[index] + if index == 0: + # The words the geometry language puts before its first slot are the claim of the + # problem ("Prove that", "Let", "Find"), never a joint: a reader is expected to find + # them as the verb of the sentence, in whatever order the variety writes them. + gaps.append(None) + continue + phrase = literal.strip().rstrip(".") + if not phrase or phrase in (",", "and"): + # Neither a comma nor the conjunction that lists the entities of a slot is a joint of + # the geometry language: both separate two entities inside one region, and reader B + # breaks that region with the same rule it uses on a run of names written with no word + # between them. The conjunction is a connective of the variety, listed with the words + # of "and", and never a marker of a frame. + gaps.append(None) + elif phrase in _PHRASE_MARKER: + gaps.append(_PHRASE_MARKER[phrase]) + else: + raise ReadingError("the template of %s holds the words %r, which are not a joint " + "of the geometry language" % (kind, phrase)) + return gaps + + +def marker_sequence(kind: str, variant: Tuple[str, ...]) -> List[str]: + """The joints of one form, named in the order the geometry language prints them.""" + return [gap for gap in gap_markers(kind, variant) if gap is not None] + + +_HYPHEN_BETWEEN_NAMES = re.compile(r"(?<=[A-Za-z0-9_])\s*-\s*(?=[A-Za-z0-9_])") +_SPACE_BEFORE_CLOSE = re.compile(r"\s+(?=[,).])") +_SPACE_AFTER_OPEN = re.compile(r"\(\s+") +_SPACE_BEFORE_OPEN = re.compile(r"\s+(?=\()") + + +def tidy(text: str) -> str: + """One space between the words, none inside a coordinate, none around a name hyphen. + + The geometry language tolerates whitespace anywhere between its words -- verified against the + geometry bundle itself, whose rules join the words of a keyword with spaces and collapse the + expressions inside a pair of parentheses -- so tidying never changes what the geometry layer + reads. It gives the two readers one normal form to compare, which matters because the two of + them glue the atoms of a slot differently: reader A joins what it found with spaces, reader B + reads the text between two joints as it stands. + + What the normal form may not do is let two words fuse: ``line A - B`` is the line reference + ``A-B`` of the geometry language, and ``line AB`` would be another line, named ``AB``, so + every rule here removes spaces or leaves them, never moves a letter across a word boundary. + """ + out = re.sub(r"\s+", " ", text).strip() + out = _HYPHEN_BETWEEN_NAMES.sub("-", out) + out = _SPACE_BEFORE_CLOSE.sub("", out) + out = _SPACE_AFTER_OPEN.sub("", out) + out = _SPACE_BEFORE_OPEN.sub(" ", out) + return out + + +def point_name(text: str) -> Optional[str]: + """A slot value that is exactly one point name of the geometry language, or ``None``.""" + cleaned = tidy(text) + return cleaned if _POINT.fullmatch(cleaned) else None + + +_NAME_RUN = re.compile(r"[A-Z][A-Za-z0-9_]*(?:-[A-Z][A-Za-z0-9_]*)*") + + +def point_names(text: str) -> List[str]: + """The point names a region holds, in the order the sentence says them. + + A list of points arrives with the words of a variety around it -- "i punti A, B e C", the + characters for triangle in front of the three names -- and those words are lowercase or written + in another script, so the names of the geometry language are picked out by their shape: a + capital letter, and a run of them joined by a hyphen when the reader found the names of a line + written together. + """ + names: List[str] = [] + for run in _NAME_RUN.findall(tidy(text)): + names.extend(part for part in run.split("-") if part) + return names + + +def point_list(text: str, count: Optional[int] = None) -> Optional[str]: + """A slot value that is a list of point names, printed the way the language writes them. + + The geometry language writes a list of names as ``A, B and C`` and a pair as ``A and B``: the + reader collects the names it found, separated by commas or by the translated conjunction, and + this function prints the one list the language accepts. A pair joined by a hyphen is not a + list, it is a line, and it belongs to ``line_ref``. + """ + names = [part for part in re.split(r"\s*(?:,|\band\b)\s*", tidy(text)) if part.strip()] + if not names or not all(_POINT.fullmatch(name) for name in names): + return None + if count is not None and len(names) != count: + return None + if len(names) == 1: + return names[0] + head = ", ".join(names[:-2]) + tail = "%s and %s" % (names[-2], names[-1]) + return "%s, %s" % (head, tail) if head else tail + + +_LINE_REF = re.compile(r"(?:line\s+)?([A-Z][A-Za-z0-9_]*)\s*-\s*([A-Z][A-Za-z0-9_]*)") +_NAMED_LINE = re.compile(r"line\s+([a-z][A-Za-z0-9_]*)") + + +def line_ref(text: str) -> Optional[str]: + """A slot value that is a line reference of the geometry language, or ``None``. + + The language knows two forms: a named line ``line l`` and the line through two named points + ``line A-B``. The second one is how the geometry bundle writes the line of a side of a + triangle, and it is what a person says in every language they speak, so the readers hand it + over already shaped. + """ + cleaned = tidy(text) + match = _LINE_REF.fullmatch(cleaned) + if match: + return "line %s-%s" % (match.group(1), match.group(2)) + match = _NAMED_LINE.fullmatch(cleaned) + if match: + return "line %s" % match.group(1) + return None + + +def entity_name(text: str, keyword: str = "circle") -> Optional[str]: + """A slot value that is a named entity (circle, transformation), keyword included, or ``None``.""" + match = re.fullmatch(r"%s\s+([a-z][A-Za-z0-9_]*)" % keyword, tidy(text)) + if match: + return "%s %s" % (keyword, match.group(1)) + return None + + +_ANGLE_REF = re.compile(r"([A-Z][A-Za-z0-9_]*)-([A-Z][A-Za-z0-9_]*)-([A-Z][A-Za-z0-9_]*)") + + +def angle_ref(text: str) -> Optional[str]: + """A slot value that is an angle reference ``A-B-C`` of the geometry language, or ``None``.""" + match = _ANGLE_REF.fullmatch(tidy(text)) + if match: + return "%s-%s-%s" % (match.group(1), match.group(2), match.group(3)) + return None + + +def value(text: str) -> Optional[str]: + """A slot value that is a number or an expression of the geometry language, or ``None``. + + Coordinates and radii are rational expressions over the parameters of a generic triangle: + ``9``, ``3/2``, ``u1`` and ``u2*u2 + u3*u3`` are all values the geometry bundle parses. The + check here is on the shape only -- brackets balanced, no stray character -- because the + meaning of an expression is decided by the geometry layer, not by the reading layer. + """ + cleaned = tidy(text) + if not cleaned or not re.fullmatch(r"[A-Za-z0-9_+\-*/^()., ]+", cleaned): + return None + return cleaned if balanced(cleaned) else None + + +def balanced(text: str) -> bool: + """Every bracket of a sentence closed, and no doubled operator at the edges.""" + depth = {"(": 0, "[": 0} + for ch in text: + if ch in depth: + depth[ch] += 1 + elif ch == ")": + depth["("] -= 1 + elif ch == "]": + depth["["] -= 1 + if any(value < 0 for value in depth.values()): + return False + return all(value == 0 for value in depth.values()) + + +# The leading words of the geometry language, copied from the rule table of the geometry bundle. +# The reading layer covers only part of them; the rest stays reachable through the direct mode. +GEOMETRY_COMMANDS = ( + "point", "line", "circle", "rotation", "translation", "scaling", "reflection", + "transformation", "let", "assume", "find", "prove", "conic", "spherical", "hyperbolic", +) + +# The words the geometry language itself uses, copied from the same rule table. A sentence that +# carries a lowercase word outside this list is not written in the geometry language, whatever +# else it looks like. This is the third copy of that spec (the geometry bundle parses with it, +# its grammar names it), and the direct mode is where the copies can disagree out loud. +GEOMETRY_WORDS = frozenset(""" +point points line lines circle circles through with center radius squared rotation by about +translation scaling reflection across transformation is then let be the midpoint centroid +orthocenter circumcenter intersection assume are not collinear distinct find circumcircle +tangents from to power respect secant products along image under prove that perpendicular +parallel segment congruent lies on circle lies between angle right angles orientation whether +inside convex hull conic kind decomposition tangent polar at and or of triangle triangles +incenter excenters nine-point lemoine contact cosine cosines foot altitude sides spherical +hyperbolic law sines cosines duality sum exceeds pi less than two similar but congruent +between intersections parallels for as given a an over rational plane unit great the +""".split()) + +_NOT_GEOMETRY_CHARACTER = re.compile(r"[^A-Za-z0-9\s+\-*/^()\[\]<>=!|,.]") + +# A problem text is a run of commands, and each command is one sentence: the premises of the +# figure first, the claim last. Chinese writes its full stop as its own character, and the +# atomiser folds that character to a space, so the split has to see it in the text itself. +_SENTENCE_SPLIT = re.compile(r"\.(?=\s|$)|\u3002|\u0964|\u0965") + + +def split_sentences(text: str) -> List[str]: + """The sentences of a geometry problem text, each without its terminating full stop.""" + return [part.strip() for part in _SENTENCE_SPLIT.split(text) if part.strip()] + + +def direct(text: str) -> Optional[Dict[str, Any]]: + """A problem text already written in the geometry language, or ``None``. + + The direct mode is the only way a user reaches the kinds the reading layer does not cover -- + conics, the spherical and the hyperbolic track, the exact predicates -- and the only way an + untranslated text reaches the geometry layer: it fires only when the text ends with a full + stop, every one of its sentences starts with a keyword of the geometry language and carries + no lowercase word outside the vocabulary of that language. Declared points and named lines + are the reason single letter words are allowed: ``l`` and ``c`` are names, not prose. Nothing + is translated here, and the text is shown to the user as it arrived. + """ + cleaned = tidy(text) + if not cleaned or not cleaned.endswith(".") or not cleaned[0].isupper(): + return None + if _NOT_GEOMETRY_CHARACTER.search(cleaned): + return None + sentences = split_sentences(cleaned) + if not sentences: + return None + kinds: List[str] = [] + for sentence in sentences: + words = re.findall(r"[A-Za-z]+", sentence) + if not words or words[0].lower() not in GEOMETRY_COMMANDS: + return None + kinds.append(words[0].lower()) + for word in words[1:]: + if len(word) > 1 and word.lower() not in GEOMETRY_WORDS: + return None + return {"mode": "direct", "kind": kinds[0] if len(set(kinds)) == 1 else "problem", + "math": cleaned, "slots": {}, "sentences": len(sentences)} diff --git a/lggeostratum/compare.py b/lggeostratum/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..ce19c91b642d09bd63a66cb692ec9927b940aa64 --- /dev/null +++ b/lggeostratum/compare.py @@ -0,0 +1,313 @@ +"""The SMT equivalence of the two readings: do the two readers mean the same problem? + +Reader A and reader B reach their text of the geometry language by different routes -- surface +patterns and marker frames -- and the topology only trusts the pair when the two texts are the same +problem. Textual identity is the easy case. The interesting case is two *different* texts that +denote one problem, and the only honest way to settle it is to ask a theorem prover, which is what +the geometry bundle itself does between its independent provers. + +The translation of the geometry language into algebra and into SMT2 is **not reimplemented here**. +The geometry bundle owns that account, and a second copy of it inside the reading layer would be a +third place where the meaning of the geometry language could be wrong without anyone noticing. So +this module loads the geometry bundle (:envvar:`LGSTRATUM_GEOMETRY_ROOT`, sibling folder +``geometry`` by default), parses both texts with its parser, builds both algebraic models with its +model builder, and then states the claim ``the readings differ`` as SMT2 over the union of the two +models' variables: unsatisfiable means the two readings denote the same problem under every +assignment of the coordinates, which is the same ``unsat`` discipline the bundle applies to its own +provers when it asks whether a theorem holds. + +Two consequences are deliberate and both are limits, not shortcuts: + +* a text the geometry bundle cannot turn into a model (a sentence it refuses to parse, a + construction whose non degeneracy it cannot state) is reported ``unknown`` and the session treats + it as a dispute: the reading layer would rather abstain than assume two texts are equal; +* the SMT claim of this module is *about the readings*, never about the user's problem. The problem + itself is never decided here: the text is handed to the geometry bundle, whose verdict is shown + as it arrived. +""" + +import re +import sys +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, invoker, segment + +_geometry: Optional[Tuple[Any, Any, Any]] = None +_GEOMETRY_LOOKUP_ERROR: Optional[str] = None + + +def _geometry_modules() -> Tuple[Optional[Any], Optional[Any], Optional[Any], Optional[str]]: + """The geometry bundle's parser, model builder and SMT layer, or the reason they are absent. + + The bundle is a package, so its parent folder goes on the import path and the package is + imported by the name it has on disk: this module reaches it the way a reader of the repository + would, never by copying a file of it into the reading layer. + """ + global _geometry, _GEOMETRY_LOOKUP_ERROR + if _geometry is not None: + return _geometry[0], _geometry[1], _geometry[2], None + if _GEOMETRY_LOOKUP_ERROR is not None: + return None, None, None, _GEOMETRY_LOOKUP_ERROR + root = invoker.geometry_root() + if not (root / "__init__.py").is_file(): + _GEOMETRY_LOOKUP_ERROR = "no geometry package at %s" % root + return None, None, None, _GEOMETRY_LOOKUP_ERROR + parent = str(root.parent) + if parent not in sys.path: + sys.path.insert(0, parent) + try: + from geometry import language, model # noqa: PLC0415 - importing the bundle is the point + from geometry.logic import smt + except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently + _GEOMETRY_LOOKUP_ERROR = "the geometry bundle could not be imported: %s" % type(exc).__name__ + return None, None, None, _GEOMETRY_LOOKUP_ERROR + _geometry = (language, model, smt) + return language, model, smt, None + + +ONTOLOGY = "(set-option :timeout 8000)\n" + +_DECLARED = re.compile(r"\(declare-(?:const|fun|sort)\s+([^\s()]+)") + + +def smt_referee(decls: List[str], asserts: List[str]) -> str: + """Re-run one claim of an envelope the way the orchestrator does, ontology first. + + The geometry bundle exposes no referee of its own, so the reading layer runs the plain solver + over the same text the envelope carries: the declarations and assertions it printed, with a + declaration never repeated. The claim of an envelope is linear arithmetic about counters and + assurance levels, which needs no nonlinear engine; the problem itself is decided by the + geometry bundle, and this function never sees it. + """ + try: + import z3 # noqa: PLC0415 - the referee of the orchestrator is the solver, not a copy of one + except ImportError: + return "unknown" + declared = set(_DECLARED.findall(ONTOLOGY)) + kept: List[str] = [] + for decl in decls: + match = _DECLARED.search(decl) + if match: + if match.group(1) in declared: + continue + declared.add(match.group(1)) + kept.append(decl) + try: + solver = z3.Solver() + solver.from_string("\n".join([ONTOLOGY] + kept + list(asserts))) + result = solver.check() + return "sat" if result == z3.sat else "unsat" if result == z3.unsat else "unknown" + except Exception: # noqa: BLE001 - a claim the solver cannot read is reported, never guessed + return "error" + + +def numbers(text: str) -> List[str]: + """Every number written in a text, in order, digits normalised.""" + return segment.numeric_literals(text) + + +def sorted_numbers(text: str) -> List[str]: + """The same numbers ordered by value, so a reordering of slots is not read as a change.""" + return sorted(numbers(text), key=lambda value: (float(value), value)) + + +def formalize(sentence: str) -> Optional[Dict[str, Any]]: + """The geometry bundle's own algebraic view of one canonical text, or ``None``. + + The bundle states a problem as the conjunction of its hypotheses -- the coordinates, the + constructions, the non degeneracy of the figure -- and of the conditions of its goals. That + conjunction is what this function returns, as bare SMT2 expressions, together with the names of + the coordinates it speaks about. Nothing here computes a polynomial: the two calls to the + bundle are its parser and its model builder, the same two the provers of the bundle run. + """ + language, model, _smt, _reason = _geometry_modules() + if language is None or model is None: + return None + try: + node = language.parse_problem(sentence) + built = model.build_model(node) + cond = built.hypothesis_cond() + for goal in getattr(built, "goals", []) or []: + cond = cond + goal.cond + names = [str(name) for name in (built.variable_names() or [])] + for name in cond.variables(): + if name not in names: + names.append(name) + return {"conjuncts": cond.conjuncts(), "vars": names} + except Exception: # noqa: BLE001 - a text this module cannot formalize is a text to report + return None + + +def _formula(side: Dict[str, Any]) -> str: + """One SMT2 expression for the conjunction a side of the comparison stands on.""" + parts = list(side.get("conjuncts") or []) + if not parts: + return "true" + if len(parts) == 1: + return parts[0] + return "(and %s)" % " ".join(parts) + + +def _smt_claim(smt: Any, left: Dict[str, Any], right: Dict[str, Any]) -> Tuple[List[str], List[str], str, str, Any]: + """SMT2 for ``the two readings differ``, and what the solver says about it. + + The declarations and the assertion are one plain SMT2 program: an assignment of the coordinates + that satisfies one reading's problem and not the other's, in either direction. Unsatisfiable + means the two readings denote the same problem under every assignment, which is the discipline + the geometry bundle applies when it asks whether its own theorems hold. The program is what + travels in the envelope, so the referee of the orchestrator re-runs exactly this query and + cannot be told something else. + """ + names: List[str] = [] + for side in (left, right): + for name in side.get("vars", []): + if name not in names: + names.append(name) + decls = ["(declare-const %s Real)" % name for name in names] + first, second = _formula(left), _formula(right) + assertions = ["(assert (or (and %s (not %s)) (and %s (not %s))))" % (first, second, second, first)] + if smt is None: + return decls, assertions, "unknown", "unknown", None + try: + result = smt.check_smt(decls, assertions, SMT_TIMEOUT_MS) + except Exception: # noqa: BLE001 - a query the bundle cannot run is a query to report + return decls, assertions, "unknown", "unknown", None + status = str(getattr(result, "status", "unknown")) + if status == "unsat": + return decls, assertions, "unsat", "equivalent", None + if status == "sat": + return decls, assertions, "sat", "different", getattr(result, "model", None) + return decls, assertions, "unknown", "unknown", None + + +SMT_TIMEOUT_MS = 20000 + + +def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]: + """The slots one reading actually filled, in the order the geometry language prints them.""" + kind = str(reading.get("kind", "")) + slots = reading.get("slots") or {} + if kind not in canonical.TEMPLATES: + return () + return tuple(name for name in canonical.slots_for(kind) if str(slots.get(name, "")).strip()) + + +def equivalence(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]: + """Compare two readings: one verdict, the SMT claim behind it, and what differs. + + The numbers are looked at before the solver, and they are a veto: a problem with other numbers is + another problem, even when the two claims it states are both true. + """ + left = canonical.tidy(str(a.get("math", ""))) + right = canonical.tidy(str(b.get("math", ""))) + detail: List[str] = [] + wrote, kept = sorted_numbers(left), sorted_numbers(right) + if wrote != kept: + # A geometry problem is its figure, and the figure is written in numbers: two readings that + # wrote different numbers describe two different figures, and no solver query turns that into + # one problem stated twice. The query below compares claims, and two concrete claims can be + # equally true while speaking of different triangles, so the numbers are a veto here and not + # a note next to the solver's answer. + return {"same": False, "why": "numbers", "left": left, "right": right, + "detail": ["numbers %s vs %s" % (",".join(wrote), ",".join(kept))], + "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None} + + if a.get("kind") != b.get("kind"): + detail.append("kinds %s vs %s" % (a.get("kind"), b.get("kind"))) + return {"same": False, "why": "kind", "left": left, "right": right, "detail": detail, + "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None} + if variant_of(a) != variant_of(b): + detail.append("slots %s vs %s" % (",".join(variant_of(a)), ",".join(variant_of(b)))) + return {"same": False, "why": "variant", "left": left, "right": right, "detail": detail, + "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None} + + if left and left == right: + return {"same": True, "why": "text", "left": left, "right": right, "detail": detail, + "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None} + + _language, _model, smt, reason = _geometry_modules() + first, second = formalize(left), formalize(right) + if first is None or second is None: + note = reason or "the geometry bundle gives no algebraic view of this text" + detail.append(note) + return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail, + "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None, + "note": note} + + decls, assertions, claimed, label, model = _smt_claim(smt, first, second) + if claimed == "unknown": + detail.append("the solver gave no answer about the two readings") + if label == "different": + detail.append("an assignment of the coordinates where the two readings disagree") + return {"same": label == "equivalent", "why": "smt" if label != "unknown" else "unknown", + "left": left, "right": right, "detail": detail, + "declarations": decls, "assertions": assertions, "claimed": claimed, + "model": ({key: str(value) for key, value in model.items()} if model else None)} + + +def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]: + """Whether the reading kept every number the user wrote, and the SMT claim that says so.""" + wrote = sorted_numbers(question) + kept = sorted_numbers(str(reading.get("math", ""))) + decls, asserts = elementwise(wrote, kept, "keep") + ok = wrote == kept + return { + "ok": ok, + "wrote": wrote, + "kept": kept, + "missing": [value for value in wrote if value not in kept], + "added": [value for value in kept if value not in wrote], + "declarations": decls, + "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]), + "claimed": "sat" if ok else "unsat", + } + + +def elementwise(left: List[str], right: List[str], prefix: str) -> Tuple[List[str], List[str]]: + """SMT2 declarations and assertions saying two lists of numbers are equal, item by item.""" + if len(left) != len(right): + return [], ["(assert false)"] + decls: List[str] = [] + asserts: List[str] = [] + for index, (first, second) in enumerate(zip(left, right)): + name = "%s_%d" % (prefix, index) + decls.append("(declare-const %sa Real)" % name) + decls.append("(declare-const %sb Real)" % name) + asserts.append("(assert (= %sa %s))" % (name, first)) + asserts.append("(assert (= %sb %s))" % (name, second)) + asserts.append("(assert (= %sa %sb))" % (name, name)) + return decls, asserts + + +def agrees_with_layer(reading: Dict[str, Any], geometry_verdict: Dict[str, Any]) -> bool: + """Did the geometry bundle answer the text the readers agreed on? + + The geometry bundle echoes the problem it understood. That echo is an independent channel: a + node standing between the readers and the geometry layer can rewrite its own record, but it + cannot move the echo without moving numbers that were counted upstream. + """ + echo = canonical.tidy(str(geometry_verdict.get("problem_math", ""))) + agreed = canonical.tidy(str(reading.get("math", ""))) + if not agreed or not echo: + return False + return echo == agreed and sorted_numbers(echo) == sorted_numbers(agreed) + + +def assurance_of(comparison: Dict[str, Any], readings: List[Dict[str, Any]], + coverage: Optional[Dict[str, Any]] = None) -> int: + """Reading assurance: how much of the answer the *reading* of the text warrants. + + The scale is the one the geometry bundle uses, zero to three, and this function only ever + lowers it: two readings that agree and kept every number reach level two, a single reader + reaches level one, and no reading path reaches three, because reading a text written in a human + language is never the last word -- the geometry bundle holds level three for the theorem it + proved by two independent routes, and the assurance the user sees is the minimum of the two. + """ + present = [reading for reading in readings if reading.get("math")] + if not present: + return 0 + if coverage is not None and not coverage.get("ok", False): + return 0 + if len(present) < 2: + return 1 + return 2 if comparison.get("same") else 0 diff --git a/lggeostratum/corpus.py b/lggeostratum/corpus.py new file mode 100644 index 0000000000000000000000000000000000000000..8dd89a0a924d92f7d3f30119847eff87e64af1b6 --- /dev/null +++ b/lggeostratum/corpus.py @@ -0,0 +1,84 @@ +"""The gold set of the stratum: sentences in six varieties and what each one must produce. + +A corpus item is one line of JSON: a language, a question written by a speaker, and the expectation. +The expectation is deliberately narrow, because the stratum is not a prover -- it is the layer that +decides *which* sentence to hand to the geometry bundle and how much confidence to attach to it: + + {"id": "it-collinear-1", "lang": "it", + "question": "A=(0,0), B=(2,0), C=(1,0). Dimostra che A, B e C sono allineati", + "expect": {"state": "AGREED", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). " + "Prove that A, B and C are collinear.", + "min_assurance": 1}} + +``state`` is the only mandatory key. ``sentence`` is compared after tidying, ``answer_contains`` is +a substring test on the answer the geometry bundle returned, and ``max_assurance`` is the ceiling a +negative item insists on: an item that ends in DISPUTED, AMBIGUOUS or NOT COVERED must show no +answer at all. + +The corpus is the only place a shared translation error can surface: the two readers agree by +construction whenever both descriptions of a language carry the same mistake, so the gold sentences +are written from the language and not from the lexicon. +""" + +import json +from pathlib import Path +from typing import Any, Dict, List, Optional + +from . import canonical, pipeline + +ROOT = Path(__file__).resolve().parents[1] +PATH = ROOT / "problems" / "corpus.jsonl" + + +def load(path: Optional[Path] = None) -> List[Dict[str, Any]]: + """The corpus, one dictionary per line, skipping blank lines and comments.""" + where = Path(path) if path else PATH + items: List[Dict[str, Any]] = [] + for line in where.read_text(encoding="utf-8").splitlines(): + text = line.strip() + if not text or text.startswith("#"): + continue + items.append(json.loads(text)) + return items + + +def grade(item: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]: + """Compare one corpus expectation against one run, and say exactly what did not match.""" + expect = item.get("expect") or {} + final = result.get("final") or {} + problems: List[str] = [] + state = str(final.get("state", "")) + if expect.get("state") and expect["state"] != state: + problems.append("state %s, expected %s" % (state, expect["state"])) + if "sentence" in expect: + wanted = canonical.tidy(str(expect["sentence"])) + got = canonical.tidy(str((result.get("dossier") or {}).get("sent", ""))) + if got != wanted: + problems.append("sentence %r, expected %r" % (got, wanted)) + if "answer_contains" in expect: + answer = str(final.get("answer", "")) + if str(expect["answer_contains"]) not in answer: + problems.append("answer %r does not contain %r" % (answer, 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"])) + if expect.get("no_answer") and final.get("answer"): + problems.append("an answer was shown for an item that must show none") + if expect.get("referee_clean") and any(record["claimed"] != record["referee"] + for record in result.get("records") or []): + problems.append("a claim did not survive the referee") + return {"id": item.get("id", "?"), "lang": item.get("lang", "?"), "state": state, + "assurance": final.get("assurance", 0), "ok": not problems, "problems": problems} + + +def outcome(item: Dict[str, Any], call_geometry: bool = True, + fault_spec: Optional[List[str]] = None) -> Dict[str, Any]: + """Run one corpus item in memory and grade it.""" + result = pipeline.ask(str(item.get("question", "")), str(item.get("lang", "")), fault_spec=fault_spec, + call_geometry=call_geometry) + verdict = grade(item, result) + verdict["records"] = result["records"] + verdict["dossier"] = result["dossier"] + verdict["reply"] = result["reply"] + return verdict diff --git a/lggeostratum/coverage.py b/lggeostratum/coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..ab9c59d98b0180ce1dbb40b7dbc224f0858b285d --- /dev/null +++ b/lggeostratum/coverage.py @@ -0,0 +1,93 @@ +"""What the reading kept, and what the geometry bundle says it settled. + +Two bookkeeping checks stand between the readers and the answer, and both are stated as SMT2 so +the referee of the orchestrator recomputes them instead of trusting a node: + +* :func:`keeps` -- every number the user wrote is still in the sentence of the geometry language, + and no number appeared there that the user did not write. A reader that merged two slots or + shifted a digit changes that multiset, and a sorted element by element equality over declared + reals says so; +* :func:`echo_matches` -- the geometry bundle echoes the problem it understood, and the echo is + compared with the sentence the readers agreed on. The echo is an independent channel: a node + standing between the readers and the geometry layer can rewrite its own record, but it cannot + move the echo without moving numbers that were counted upstream. + +Neither check decides geometry. They count tokens, and they hand the counting to a solver so +that a node claiming the numbers were kept is checked against that claim. +""" + +from typing import Any, Dict, List, Optional + +from . import canonical, compare + + +def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]: + """Whether one reading kept every number the user wrote, with the SMT claim that says so.""" + return compare.keeps(reading, question) + + +def echo_numbers(geometry_verdict: Dict[str, Any]) -> List[str]: + """The numbers of the problem the geometry bundle says it settled, ordered by value.""" + return compare.sorted_numbers(canonical.tidy(str(geometry_verdict.get("problem_math", "")))) + + +def echo_matches(reading: Dict[str, Any], geometry_verdict: Dict[str, Any]) -> bool: + """Did the geometry bundle settle the sentence the readers agreed on? + + A verdict that names no sentence at all -- the backend was off, or the geometry bundle could not + be started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls + to zero because there is no geometry assurance to take the minimum with, but nothing here may be + read as tampering. Only an echo that names a sentence and names a different one is a mismatch. + """ + if not str(geometry_verdict.get("problem_math", "")).strip(): + return True + return compare.agrees_with_layer(reading, geometry_verdict) + + +def coverage_claim(question: str, readings: List[Dict[str, Any]], + geometry_verdict: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: + """One SMT2 claim tying the user's numbers to the readings and, when known, to the echo. + + Every reading that produced a sentence has to carry the user's numbers, and once the geometry + bundle has answered its echo has to carry them too. The assertion set is the conjunction of + those element equalities: satisfiable exactly when all of them hold, which is what the referee + checks against the status the node claimed. + """ + wrote = compare.sorted_numbers(question) + readings_present = [reading for reading in readings if reading.get("math")] + steps = [keeps(reading, question) for reading in readings_present] + ok = all(step["ok"] for step in steps) + decls: List[str] = [] + asserts: List[str] = [] + for step in steps: + decls = decls + list(step["declarations"]) + asserts = asserts + list(step["assertions"]) + if geometry_verdict is not None: + echo = echo_numbers(geometry_verdict) + decls2, asserts2 = compare.elementwise(wrote, echo, "echo") + decls = decls + decls2 + asserts = asserts + asserts2 + ok = ok and echo == wrote + if not wrote: + # Nothing was written, so there is nothing to keep: the claim is the empty conjunction, + # which is satisfiable, and the node says sat. + return {"ok": ok, "wrote": [], "kept": [], "declarations": [], "assertions": ["(assert (= 1 1))"], + "claimed": "sat"} + return { + "ok": ok, + "wrote": wrote, + "kept": [step["kept"] for step in steps], + "declarations": decls, + "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]), + "claimed": "sat" if ok else "unsat", + } + + +def summary(step: Dict[str, Any]) -> Dict[str, Any]: + """The part of a coverage step that belongs in the dossier and in front of the user.""" + return { + "ok": step.get("ok", False), + "wrote": step.get("wrote", []), + "missing": step.get("missing", []), + "added": step.get("added", []), + } diff --git a/lggeostratum/decide.py b/lggeostratum/decide.py new file mode 100644 index 0000000000000000000000000000000000000000..042fd60137e7cedf37fb6e4fa0acfbed6540c765 --- /dev/null +++ b/lggeostratum/decide.py @@ -0,0 +1,166 @@ +"""The decision: pure, and never raising anything. + +One function, no I/O: given what the readers understood, what the equivalence node proved, what the +coverage node counted and what the geometry stratum answered, it states the state of the session, +the assurance the user sees, and whether an answer may be shown at all. The arbiter runs it, the +tools run it again on the transcript, and a test pins it, so the same rules are checked in three +places -- the same shape the geometry stratum uses for its own decision. + +The rule the whole module exists to enforce: + + assurance(shown) = min(assurance(geometry), assurance(reading)) + +and ``assurance(reading)`` is at most two, so the stratum never reports the top level: a sentence +written in a human language carries one more fallible step than a text the geometry bundle parses +itself, and the reading layer is where that step lives. A verdict is therefore never raised by the +stratum; the only direction it can move is down, and the adversary node writes the negation of that +inequality as SMT2 so the referee of the orchestrator refutes it. + +The states, which are the seven the lexicon of every covered language names: + +=========== =================================================================== +AGREED both readers produced the same sentence, and the geometry bundle settled it +PASSTHROUGH the text was already written in the geometry language: nothing was translated +SINGLE one reader understood the sentence and the other abstained: the geometry bundle was + consulted, and the assurance is capped by the missing witness +DISPUTED the two readers produced different sentences, or a reading lost a number: the geometry + bundle is not consulted at all +AMBIGUOUS the sentence announces more than one kind of problem: the user has to choose +NOT COVERED neither reader found anything: the language does not say this in a covered way +TAMPERED the geometry bundle says it settled something other than the agreed sentence +============ =================================================================== +""" + +from typing import Any, Dict, List, Optional + +AMBIGUOUS_REASONS = ("multiple", "two_verbs") + +STATES = ("AGREED", "PASSTHROUGH", "SINGLE", "DISPUTED", "AMBIGUOUS", "NOT COVERED", "TAMPERED", "NONE") + +# The reading assurance of each state, on the scale the geometry bundle uses. Three is not in this +# table: it belongs to the geometry bundle alone. +CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0, + "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0} + +# The verdicts of the bundle that carry an answer: the obligation was discharged, or the claim was +# shown false on a figure of the problem itself. Anything else -- a refusal, an objection, a session +# that stopped short -- is a verdict with no answer to show. +ANSWERING = ("VERIFIED", "SINGLE_PROVER", "REFUTED") + + +def reader_notes(readings: List[Dict[str, Any]]) -> List[str]: + """The reason keys the abstaining readers left behind, in reader order.""" + notes: List[str] = [] + for reading in readings: + for note in reading.get("notes") or []: + reason = note.get("reason") if isinstance(note, dict) else str(note) + if reason and reason not in notes: + notes.append(reason) + return notes + + +def state_of(readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]], + coverage: Optional[Dict[str, Any]], geometry_verdict: Optional[Dict[str, Any]], + direct: Optional[Dict[str, Any]] = None, echo_ok: Optional[bool] = None) -> str: + """The state of a session, from the evidence the nodes collected.""" + present = [reading for reading in readings if reading.get("math")] + notes = reader_notes(readings) + if direct is not None: + return "PASSTHROUGH" + if geometry_verdict is not None and echo_ok is False: + return "TAMPERED" + if len(present) >= 2: + if comparison is None: + return "DISPUTED" + if coverage is not None and not coverage.get("ok", False): + return "DISPUTED" + return "AGREED" if comparison.get("same") else "DISPUTED" + if len(present) == 1: + # A lone witness has to hold the numbers the person wrote: a reading that lost one is not a + # weaker reading of the same problem, it is a different problem, and the ceiling of SINGLE is + # not a licence to answer it. This is the case the ablation of the topology uncovered: with + # one reader there is no second sentence to compare against, so the count of literals is what + # stands between a shifted number and an answer the gold does not accept. + if coverage is not None and not coverage.get("ok", False): + return "DISPUTED" + return "SINGLE" + if any(reason in AMBIGUOUS_REASONS for reason in notes): + return "AMBIGUOUS" + return "NOT COVERED" + + +def reasons_for(state: str, readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]], + coverage: Optional[Dict[str, Any]], geometry_verdict: Optional[Dict[str, Any]], + asked: bool = True) -> List[str]: + """The reason keys that explain a state, in the order a reader should read them.""" + out: List[str] = [] + for reason in reader_notes(readings): + if reason not in out: + out.append(reason) + if state == "DISPUTED": + if coverage is not None and not coverage.get("ok", False): + out.append("literal_count") + if comparison is not None and not comparison.get("same"): + out.append("disagree") + if comparison is not None and comparison.get("why") == "unknown": + out.append("geometry_unknown") + if comparison is not None and comparison.get("why") == "smt" and comparison.get("model"): + if "disagree" not in out: + out.append("disagree") + if state == "TAMPERED": + out.append("boundary") + if geometry_verdict is not None and geometry_verdict.get("referee_mismatch"): + out.append("referee") + if asked and geometry_verdict is not None and geometry_verdict.get("status") == "UNKNOWN": + out.append("geometry_unknown") + if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"): + out.append("no_geometry") + return out + + +def decide(dossier: Dict[str, Any]) -> Dict[str, Any]: + """One verdict for one session, with the assurance the user is allowed to see.""" + readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}] + if dossier.get("reading_direct"): + readings = [dossier["reading_direct"]] + comparison = dossier.get("compare") + coverage = dossier.get("coverage") + geometry_verdict = dossier.get("math") + direct = dossier.get("reading_direct") + echo_ok = dossier.get("echo_ok") + + state = state_of(readings, comparison, coverage, geometry_verdict, direct, echo_ok) + ceiling = CEILING[state] + assurance = 0 + answer_shown = "" + if state in ("AGREED", "SINGLE", "PASSTHROUGH") and geometry_verdict is not None: + # The geometry bundle answers at level three when two engines of its own and a witnessed + # figure stand behind every obligation, at level two when one prover stands alone or a + # counterexample refutes the claim, and at level zero when it refuses or stops short. + if geometry_verdict.get("status") in ANSWERING: + assurance = min(ceiling, int(geometry_verdict.get("assurance", 0) or 0)) + else: + assurance = 0 + answer_shown = geometry_verdict.get("answer_text") or "" + if assurance == 0: + answer_shown = "" + reasons = reasons_for(state, readings, comparison, coverage, geometry_verdict, + asked=bool(str(dossier.get("sent") or ""))) + return { + "state": state, + "assurance": assurance, + "ceiling": ceiling, + "math_assurance": int((geometry_verdict or {}).get("assurance", 0) or 0), + "math_status": (geometry_verdict or {}).get("status"), + "answer": answer_shown, + "reasons": reasons, + "consulted_math": geometry_verdict is not None, + } + + +def raise_assurance(final: Dict[str, Any], claimed: int) -> Dict[str, Any]: + """The arbiter fault: an assurance above what the evidence supports (experiments only).""" + out = dict(final) + out["assurance"] = max(int(final.get("assurance", 0) or 0), int(claimed)) + out["claimed_above_evidence"] = True + return out diff --git a/lggeostratum/faults.py b/lggeostratum/faults.py new file mode 100644 index 0000000000000000000000000000000000000000..b7b247e6a81fa1cd91cc0417c75658157d3045da --- /dev/null +++ b/lggeostratum/faults.py @@ -0,0 +1,188 @@ +"""Fault injection for the redundancy experiments (tools/ablation.py). + +A fault is ":". Faults are off unless LGSTRATUM_FAULTS (or :func:`configure`) names +them, so production runs never take these branches. ``FIRED`` records the faults that really +changed something, which separates dormant faults from activated ones. + +The faults of the reading layer are chosen so that the damaged sentence is still a *grammatical* +sentence of the geometry language: a reader that writes another name or a shifted number must +produce something the geometry layer will happily solve. Otherwise the fault would be caught by the +geometry layer refusing to parse, and the experiment would measure nothing about the reading layer. + +Catalogue +--------- +reader_a / reader_b : rename_slot, merge_slots, shift_number +equivalence : rubber_stamp (declares the two readings equal without running SMT) +coverage : rubber_stamp (declares every number kept without counting them) +boundary : tamper_math (asks the geometry layer a different question, reports the agreed one) +adversary : rubber_stamp (skips its own recomputation of the assurance bound) +arbiter : force_assurance (raises the assurance above what the evidence supports) +""" + +import os +import re +from typing import Any, Dict, Iterable, List, Optional, Set, Tuple + +_ACTIVE: Set[str] = set() +FIRED: List[str] = [] + +READER_FAULTS = ["rename_slot", "merge_slots", "shift_number"] + +CATALOG = { + "reader_a": READER_FAULTS, + "reader_b": READER_FAULTS, + "equivalence": ["rubber_stamp"], + "coverage": ["rubber_stamp"], + "boundary": ["tamper_math"], + "adversary": ["rubber_stamp"], + "arbiter": ["force_assurance"], +} + +# The geometry language has no slot a sentence could do without: every name sits in the frame that +# requires it. What a reader can do to a reading without leaving the language is therefore to write +# another name, to write one name where two stood, or to write another number. +_NAME = re.compile(r"[A-Z]") +_NUMBER = re.compile(r"\d+(?:\.\d+)?") +_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + + +def configure(spec: Optional[Iterable[str]]) -> None: + _ACTIVE.clear() + del FIRED[:] + if spec is None: + return + if isinstance(spec, str): + spec = [s for s in spec.split(",") if s.strip()] + for item in spec: + _ACTIVE.add(item.strip()) + + +def from_env() -> None: + configure(os.environ.get("LGSTRATUM_FAULTS", "")) + + +def has(agent: str, kind: str) -> bool: + return "%s:%s" % (agent, kind) in _ACTIVE + + +def fire(agent: str, kind: str) -> None: + label = "%s:%s" % (agent, kind) + if label not in FIRED: + FIRED.append(label) + + +def fired(agent: str) -> List[str]: + return [item for item in FIRED if item.split(":", 1)[0] == agent] + + +# --------------------------------------------------------------------------- +# Reading mutations (reader faults) +# --------------------------------------------------------------------------- +def _slots_with_numbers(slots: Dict[str, str], order: List[str]) -> List[str]: + return [name for name in order if _NUMBER.search(slots.get(name, ""))] + + +def _names(value: str) -> List[str]: + return [ch for ch in value if ch.isascii() and ch.isupper()] + + +def _rename_name(slots: Dict[str, str], order: List[str]) -> Optional[Dict[str, str]]: + """Write in the first slot that holds one a name the reading never used. + + The letter is chosen among those absent from every slot, so the damaged sentence speaks of a + point the question never named: it stays inside the language, and it is no longer the figure the + person described. + """ + used = set() + for value in slots.values(): + used.update(_names(value)) + fresh = "" + for letter in _ALPHABET: + if letter not in used: + fresh = letter + break + if not fresh: + return None + for name in order: + value = slots.get(name, "") + match = _NAME.search(value) + if match is None: + continue + changed = dict(slots) + changed[name] = value[:match.start()] + fresh + value[match.end():] + return changed + return None + + +def _twins(slots: Dict[str, str], order: List[str]) -> Optional[Tuple[str, str]]: + """The last two slots that hold a name: a reader that collapses them names one figure twice.""" + holders = [name for name in order if _names(slots.get(name, ""))] + if len(holders) < 2: + return None + return holders[-2], holders[-1] + + +def mutate_reading(agent: str, kind: str, slots: Dict[str, str], order: List[str]) -> Tuple[Dict[str, str], bool]: + """Return a damaged copy of one reading, and whether anything was actually damaged. + + ``order`` is the slot order of the form the reader chose, so the fault knows which slot holds a + name of a figure and which one holds the coordinates or the number the sentence is about. + """ + from . import canonical + + slots = dict(slots) + for kind_fault in CATALOG.get(agent, []): + if not has(agent, kind_fault): + continue + candidate = dict(slots) + if kind_fault == "rename_slot": + renamed = _rename_name(candidate, order) + if renamed is None: + continue + candidate = renamed + elif kind_fault == "merge_slots": + twins = _twins(candidate, order) + if twins is None: + continue + first, second = twins + candidate[second] = candidate[first] + elif kind_fault == "shift_number": + numbered = _slots_with_numbers(candidate, order) + if not numbered: + continue + owner = numbered[0] + match = _NUMBER.search(candidate[owner]) + if match is None: + continue + bumped = _NUMBER.sub(lambda m: str(_next_number(m.group(0))), candidate[owner], count=1) + candidate[owner] = bumped + else: + continue + try: + canonical.print_math(kind, candidate) + except canonical.ReadingError: + continue + fire(agent, kind_fault) + return candidate, True + return slots, False + + +def _next_number(text: str) -> Any: + if "." in text: + return float(text) + 1.0 + return int(text) + 1 + + +# --------------------------------------------------------------------------- +# Sentence mutations (the boundary fault) +# --------------------------------------------------------------------------- +def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]: + """Change one number of a sentence of the geometry language, leaving it grammatical.""" + if not has(agent, "tamper_math"): + return sentence, False + match = _NUMBER.search(sentence) + if match is None: + return sentence, False + damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():] + fire(agent, "tamper_math") + return damaged, True diff --git a/lggeostratum/invoker.py b/lggeostratum/invoker.py new file mode 100644 index 0000000000000000000000000000000000000000..cd363d05ddb6df5fc636085dcd78e7f975ba5773 --- /dev/null +++ b/lggeostratum/invoker.py @@ -0,0 +1,103 @@ +"""The interface toward the geometry stratum: one subprocess call, no shared code. + +The reading layer and the geometry layer are separate topologies of the same orchestrator. This +module is the whole of their coupling: it starts ``tools/geometry_runner.py`` of this bundle as a +separate process with the canonical text as its argument, asks for the machine readable outcome, +and copies that outcome. Nothing here imports a module of the geometry bundle, because a +translation layer that reaches inside the geometry it consults is a translation layer that can +silently change the geometry. The runner is a thin adapter, and the only place in this bundle +where the package ``geometry`` is loaded. + +Two settings matter, and both are environment variables so no value is hardcoded in a second +place: + +``LGSTRATUM_GEOMETRY_ROOT`` the folder of the geometry bundle (default: ``geometry``, sibling + of this bundle, which is ``datasets/geometry`` inside the LingoLOGOS + repository) +``LGSTRATUM_GEOMETRY_BACKEND`` ``subprocess`` (default) or ``none``; ``none`` refuses to call and + is what the reading layer tests use, so they can check the reading + without starting a whole geometry session +""" + +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict, Optional + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_TIMEOUT = 180 + + +def geometry_root() -> Path: + override = os.environ.get("LGSTRATUM_GEOMETRY_ROOT", "").strip() + if override: + return Path(override) + return ROOT.parent / "geometry" + + +def backend() -> str: + return (os.environ.get("LGSTRATUM_GEOMETRY_BACKEND", "subprocess") or "subprocess").strip().lower() + + +def timeout_seconds() -> int: + try: + return max(5, int(os.environ.get("LGSTRATUM_GEOMETRY_TIMEOUT", DEFAULT_TIMEOUT))) + except ValueError: + return DEFAULT_TIMEOUT + + +def unavailable(reason: str) -> Dict[str, Any]: + return {"ok": False, "error": reason, "status": "UNKNOWN", "assurance": 0, "answer": None, + "answer_text": "", "problem_math": "", "reasons": [], "solver": None, "detected": []} + + +def solve(text: str) -> Dict[str, Any]: + """Ask the geometry bundle one text of the geometry language, and return its verdict unchanged.""" + if backend() == "none": + return unavailable("the geometry backend is disabled by LGSTRATUM_GEOMETRY_BACKEND") + script = ROOT / "tools" / "geometry_runner.py" + if not script.is_file(): + return unavailable("no tools/geometry_runner.py in this bundle") + try: + done = subprocess.run( + [sys.executable, str(script), "--json", text], + cwd=str(ROOT), capture_output=True, timeout=timeout_seconds()) + except subprocess.TimeoutExpired: + return unavailable("the geometry bundle did not answer within %d seconds" % timeout_seconds()) + except OSError as exc: + return unavailable("the geometry bundle could not be started: %s" % exc) + text_out = done.stdout.decode("utf-8", "replace") + if done.returncode != 0 and not text_out.strip(): + return unavailable("the geometry bundle exited with %d: %s" + % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200])) + return outcome(text_out, done.returncode) + + +def outcome(text: str, returncode: int = 0) -> Dict[str, Any]: + """Extract the verdict of a geometry session from the JSON the runner printed.""" + try: + parsed = json.loads(text) + except ValueError: + return unavailable("the geometry bundle printed something that is not JSON (exit %d)" % returncode) + final = parsed.get("final") if isinstance(parsed, dict) else None + if not isinstance(final, dict): + return unavailable("the geometry bundle printed no verdict (exit %d)" % returncode) + referee = parsed.get("referee") if isinstance(parsed.get("referee"), list) else [] + mismatched = [entry for entry in referee + if isinstance(entry, dict) and entry.get("claimed") != entry.get("referee")] + return { + "ok": final.get("status") != "UNKNOWN", + "status": final.get("status", "UNKNOWN"), + "assurance": int(final.get("assurance", 0) or 0), + "answer": final.get("answer"), + "answer_text": final.get("answer_text") or "", + "problem_math": final.get("problem_math") or "", + "reasons": list(final.get("reasons") or []), + "solver": final.get("solver"), + "detected": list(final.get("detected") or []), + "referee_mismatch": len(mismatched), + "turns": parsed.get("turns"), + "error": None if final.get("status") != "UNKNOWN" else "; ".join(final.get("reasons") or []) or "unknown", + } diff --git a/lggeostratum/lexicon.py b/lggeostratum/lexicon.py new file mode 100644 index 0000000000000000000000000000000000000000..5adc2bedfb890573217d890e27a3d0e4c37f0f8b --- /dev/null +++ b/lggeostratum/lexicon.py @@ -0,0 +1,462 @@ +"""The lexicon of the six language varieties, and the two specs each language carries. + +Every variety lives in one JSON file ``lexicon/.json`` and carries, for every sentence +kind the variety covers, **two** independent descriptions of the same surface: + +``patterns`` + the surface patterns reader A matches (a slot string per accepted wording); +``frames`` + the marker frame reader B matches (which joints of the geometry language must appear, and in + which order). + +This mirrors the geometry bundle, where the two formalizers share one written specification +(``nodes/*/grammar.gf``) and implement it twice. The consequence is the same and is stated in +the README: a translation error present in both descriptions of one language is invisible to +the topology, and only the gold sentences of the corpus can show it. + +The data files are the object of study, not prose of this repository: they hold the words of +six languages, exactly as the geometry bundle holds the polynomials it studies. + +One rule of the geometry language shapes every data file here: the *names* of a figure are not +translated. A person writing in any of the six varieties writes the points of a figure as the +capitalised names of the language of the geometry layer -- ``A``, ``B``, ``M``, ``P1`` -- because +that is what stands on the figure, and only the words around them belong to the variety. +""" + +import json +import os +import re +from typing import Any, Dict, List, Optional, Tuple + +from .segment import atomize, fold + +BUNDLE = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +LEXICON_DIR = os.path.join(BUNDLE, "lexicon") + +# Joint names, the same in every variety. The variety supplies the words; the names are how the +# two readers and the canonical printer agree, and they are the names the frame sequences of +# reader B are written with. They come from the templates of the geometry language. +from .canonical import MARKER_NAMES as MARKERS + +# The keywords of the geometry language that introduce a named entity. A variety translates the +# keyword -- Italian "retta", the Chinese word for line -- and the name that follows it stays written in the +# ASCII names of the geometry language, because that is how a person copies a point from a figure. +ENTITY_KEYWORDS = ("line", "circle", "angle", "segment") +# Words of the geometry language that appear in a sentence without introducing an entity, and +# therefore never count as a coverage failure when a reading has already explained them. +EXTRA_WORDS = ("triangle",) + +# A word run that is not in the lexicon is a coverage failure, unless it is one of these. +MATH_WORDS = EXTRA_WORDS + +# A point is named by one capitalised word in the geometry language, and only a capitalised word +# that is not a word of the variety is one: the readers never guess a name out of lowercase prose. +NAME_START = re.compile(r"[A-Z]") + +# The mnemonic names a data file may use for a connective, and what it prints as. +CONNECTIVE_TEXT = {"and": "and", "or": "or", "not": "not", + "eq": "=", "ne": "!=", "lt": "<", "le": "<=", "gt": ">", "ge": ">="} + +_cache: Dict[str, Dict[str, Any]] = {} +_index_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {} +_stripped_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {} +_verb_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, ...]]] = {} +_group_cache: Dict[str, Dict[str, Tuple[str, ...]]] = {} + + +def languages() -> List[str]: + """The language codes this bundle can read, in a stable order.""" + return sorted(name[:-5] for name in os.listdir(LEXICON_DIR) if name.endswith(".json")) + + +def load(lang: str) -> Dict[str, Any]: + if lang not in _cache: + path = os.path.join(LEXICON_DIR, lang + ".json") + with open(path, "r", encoding="utf-8") as handle: + data = json.load(handle) + data["_code"] = lang + _cache[lang] = data + return _cache[lang] + + +def script(lang: str) -> str: + return load(lang).get("script", "latin") + + +def codes() -> List[str]: + return languages() + + +def kinds(lang: str) -> List[str]: + """The sentence kinds this variety covers.""" + return sorted(load(lang).get("kinds", {})) + + +def supported_kinds() -> List[str]: + """The kinds at least one variety covers.""" + seen = set() + for lang in languages(): + seen.update(kinds(lang)) + return sorted(seen) + + +def patterns(lang: str) -> Dict[str, List[str]]: + """Reader A's surface patterns per kind: ``{kind: [pattern, ...]}``.""" + out = {} + for kind, spec in load(lang).get("kinds", {}).items(): + out[kind] = list(spec.get("patterns", [])) + return out + + +def frames(lang: str) -> Dict[str, Dict[str, Any]]: + """Reader B's marker frames per kind.""" + out = {} + for kind, spec in load(lang).get("kinds", {}).items(): + frame = spec.get("frame") + if frame is not None: + out[kind] = frame + return out + + +def verbs(lang: str) -> Dict[str, Tuple[Tuple[str, ...], ...]]: + """Every kind verb phrase of the variety, mapped to the kinds it announces. + + One phrase announces more than one kind, and that is a fact of the language, not a defect of + the data: Italian "dimostra" opens both ``prove`` and ``provez``, which differ only by the + marker for the domain. Keeping the whole list here is what lets a reader try both forms of + one sentence instead of silently taking the last kind in the file. + """ + out: Dict[str, Tuple[str, ...]] = {} + for kind, spec in load(lang).get("kinds", {}).items(): + for verb in spec.get("verbs", []): + phrase = fold(verb) + out[phrase] = out.get(phrase, ()) + (kind,) + return out + + +def verb_atoms_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, ...]]: + """The verb phrases of a variety, keyed by their atoms, mapped to the kinds they announce.""" + if lang in _verb_cache: + return _verb_cache[lang] + index = {phrase_atoms(verb): kinds for verb, kinds in verbs(lang).items()} + _verb_cache[lang] = index + return index + + +def verb_groups(lang: str) -> Dict[str, Tuple[str, ...]]: + """The kinds a verb phrase can open: ``prove`` and ``provez`` are one group, ``det`` another. + + Two kinds belong to the same group when one phrase of the variety announces both of them. + A sentence whose verb lies in one group is one problem, read in one of two ways; a sentence + whose verbs lie in two groups is two problems, and no reader may pick one. + """ + if lang in _group_cache: + return _group_cache[lang] + parent = {kind: kind for kind in load(lang).get("kinds", {})} + + def root(kind: str) -> str: + while parent[kind] != kind: + parent[kind] = parent[parent[kind]] + kind = parent[kind] + return kind + + for kinds in verbs(lang).values(): + for other in kinds[1:]: + first, second = root(kinds[0]), root(other) + if first != second: + parent[second] = first + merged: Dict[str, set] = {} + for kind in parent: + merged.setdefault(root(kind), set()).add(kind) + groups = {kind: tuple(sorted(group)) for group in merged.values() for kind in group} + _group_cache[lang] = groups + return groups + + +def announce(lang: str, items: List[Dict[str, Any]]) -> Tuple[List[str], Optional[Dict[str, str]]]: + """The kinds the verbs **and the joints** of a sentence open, or the reason it announces none. + + Both readers ask this one question, in one place: a kind is a decision about the geometry, and + a second implementation of the same rule in the second reader would be one more place where + the two of them can be wrong in the same way. + + In the geometry language the claim of a problem is very often carried by the joint itself -- + "A, B e C **sono allineati**", "AB **perpendicolare a** CD", "ABC **un angolo retto**" -- + and a reader that only listened to verbs would call those sentences unannounced. A joint whose + name is the name of a kind announces that kind, which is why the joint names of the data file + are the names of the forms of the geometry language. + """ + found: List[str] = [] + kinds_of = load(lang).get("kinds", {}) + for item in items: + role = item.get("role") + if role == "verb": + candidates = item.get("kinds") or (item.get("value"),) + elif role == "marker": + value = item.get("value") + candidates = (value,) if value in kinds_of else () + else: + candidates = () + for kind in candidates: + if kind and kind in kinds_of and kind not in found: + found.append(kind) + if not found: + return [], {"reason": "no_verb"} + neutral = neutral_kinds(lang) + picked = [kind for kind in found if kind not in neutral] or found + groups = {frozenset(verb_groups(lang)[kind]) for kind in picked} + if len(groups) > 1: + return [], {"reason": "two_verbs", "kinds": ", ".join(sorted(picked))} + merged: set = set() + for group in groups: + merged |= group + return sorted(merged), None + + + +def connectives(lang: str) -> Dict[str, List[str]]: + """The connective phrases of a variety, keyed by what they print as in the geometry language. + + The data may key a connective by a mnemonic name (``ge``) or by the symbol itself; both are + accepted, because the mnemonic is easier to read in a data file and the symbol is what the + geometry language needs. The logic connectives are words in the geometry language, so they stay words. + """ + out: Dict[str, List[str]] = {} + for name, words in load(lang).get("connectives", {}).items(): + out[CONNECTIVE_TEXT.get(name, name)] = list(words) + return out + + +def neutral_kinds(lang: str) -> set: + """Kinds whose verb is a request for an answer rather than a claim about the configuration. + + ``trova il circocentro di A, B e C`` announces a request, and the sentence that follows it in + the same problem announces the claim the geometry layer has to certify: the request verb is + neutral, so the reader that carries it steps aside when the two verbs meet in one sentence. + """ + return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")} + + +def conjunction_words(lang: str) -> List[str]: + """The words a variety uses to join the names of a list, and the comma it writes. + + The canonical printer of the geometry language needs these to cut ``A, B e C`` into three + points: a conjunction of the variety standing inside a slot is not part of a name, and the + comma that the atomiser leaves as a word between two names is listed with them, because in a + geometry sentence a comma between names is exactly the conjunction the language prints. + """ + out: List[str] = [] + for word in connectives(lang).get("and", []): + if word not in out: + out.append(word) + return out + + +def entity_keyword_words(lang: str) -> List[str]: + """The words with which a variety names a line, a circle, an angle, a segment. + + Reader B and the canonical printer meet here: a region of a sentence may carry the noun of + the variety in front of the name -- ``la retta AB``, ``the circle c`` -- and that noun has to + be recognised as the keyword of the geometry language, not as a word of prose, before the + slot can be printed as ``line A-B`` or as ``circle c``. + """ + out: List[str] = [] + for word in noise(lang): + for piece in word.split(): + if piece and piece not in out: + out.append(piece) + for words in markers(lang).values(): + for word in words: + for piece in word.split(): + if piece and piece not in out: + out.append(piece) + return out + + +def markers(lang: str) -> Dict[str, List[str]]: + return load(lang).get("markers", {}) + + +def noise(lang: str) -> List[str]: + return load(lang).get("noise", []) + + +def noise_chars(lang: str) -> str: + """Single characters a word run may hold without being a coverage failure (Chinese particles).""" + return load(lang).get("noise_chars", "") + + +def prefixes(lang: str) -> List[str]: + """Attached prefixes an Arabic word run may carry (definite article, conjunctions).""" + return load(lang).get("prefixes", []) + + +def strip_prefix(word: str, prefixes: List[str]) -> str: + """Remove the longest attached prefix, so that a written form reaches the prefix-free entry. + + Arabic attaches the definite article and the single letter conjunctions and prepositions in + front of the word, and the lexicon files record the word without them. The longest prefix wins, + because the article and a conjunction joined to it are one prefix and not two. + """ + for prefix in sorted(prefixes, key=len, reverse=True): + if word.startswith(prefix) and len(word) > len(prefix): + return word[len(prefix):] + return word + + +def prefix_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]: + """The same index, keyed with every atom of every phrase written without its prefixes.""" + if lang in _stripped_cache: + return _stripped_cache[lang] + attached = prefixes(lang) + stripped = {} + for window, hit in phrase_index(lang).items(): + if attached: + key = tuple(strip_prefix(atom, attached) for atom in window) + stripped.setdefault(key, hit) + _stripped_cache[lang] = stripped + return stripped + + +# --------------------------------------------------------------------------- +# Phrase index (reader A) and phrase positions (reader B) +# --------------------------------------------------------------------------- +Phrase = Tuple[Tuple[str, ...], str, str] + + +def phrase_atoms(phrase: str) -> Tuple[str, ...]: + """The atoms a lexicon phrase is written with, through the same atomiser as a sentence. + + A Chinese term in a data file is one token, and one token is not one atom: the atomiser cuts + it into characters, exactly as it cuts the sentence the user typed. Doing both sides the same + way is the only reason a data file and a sentence can be compared at all. + """ + return tuple(fold(atom) for kind, atom in atomize(phrase) if kind == "w") + + +_SLOT_MARK = re.compile(r"\{[A-Z]\}") + + +def pattern_literals(lang: str) -> List[Tuple[str, ...]]: + """The function words the written patterns of a variety spell out themselves, one atom each. + + A pattern is part of the data of a variety, so every word it writes is a word of that variety + by definition. ``sia M il punto medio di A e B`` names ``punto`` and ``medio``, and a reader + that called those words unknown would refuse the very shape the data file documents. These + words carry no value, which is what makes them noise: they may stand in a sentence, they + never fill a slot. A single ASCII letter is skipped, because a capital letter is the name of + a point and a lowercase letter of a pattern is an article or a preposition written apart. + """ + words: List[Tuple[str, ...]] = [] + for entries in patterns(lang).values(): + for pattern in entries: + for chunk in _SLOT_MARK.split(pattern): + for atom in phrase_atoms(chunk): + if len(atom) == 1 and "a" <= atom <= "z": + continue + words.append((atom,)) + return words + + +def phrase_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]: + """Map a folded word sequence to ``(role, value)``: verb, connective, marker or noise. + + Verbs, connectives, markers and noise words of a variety share one index, because reader A + has to decide between them with a single longest match. The index is built once per variety. + """ + if lang in _index_cache: + return _index_cache[lang] + index: Dict[Tuple[str, ...], Tuple[str, str]] = {} + for verb, kinds in verbs(lang).items(): + index[phrase_atoms(verb)] = ("verb", kinds[0]) + for symbol, words in connectives(lang).items(): + for word in words: + index[phrase_atoms(word)] = ("connective", symbol) + for name, words in markers(lang).items(): + for word in words: + index[phrase_atoms(word)] = ("marker", name) + for word in noise(lang): + index.setdefault(phrase_atoms(word), ("noise", "")) + for atom in pattern_literals(lang): + index.setdefault(atom, ("noise", "")) + # A data file with an empty phrase would match at every position and read nothing: drop it. + index.pop((), None) + _index_cache[lang] = index + return index + + +def max_phrase_length(lang: str) -> int: + return max((len(key) for key in phrase_index(lang)), default=1) + + +def phrase_spans(lang: str) -> List[Tuple[str, str, str]]: + """``(phrase, role, value)`` for every phrase of the variety, longest phrase first. + + Reader B walks these against the sentence text itself, which is a different mechanism from + the token by token longest match of reader A. + """ + out: List[Tuple[str, str, str]] = [] + for verb, kind in verbs(lang).items(): + out.append((verb, "verb", kind)) + for symbol, words in connectives(lang).items(): + for word in words: + out.append((word, "connective", symbol)) + for name, words in markers(lang).items(): + for word in words: + out.append((word, "marker", name)) + for word in noise(lang): + out.append((word, "noise", "")) + out.sort(key=lambda item: (-len(item[0]), item[0])) + return out + + +# --------------------------------------------------------------------------- +# Presentation data +# --------------------------------------------------------------------------- +def labels(lang: str) -> Dict[str, str]: + return load(lang).get("labels", {}) + + +def reading_labels(lang: str) -> Dict[str, str]: + return load(lang).get("reading", {}) + + +def reason_texts(lang: str) -> Dict[str, str]: + return load(lang).get("reasons", {}) + + +def examples(lang: str) -> List[str]: + return load(lang).get("examples", []) + + +def label(lang: str, key: str, fallback: str = "") -> str: + return labels(lang).get(key, fallback) + + +def translate_reason(lang: str, reason: str, **fields: Any) -> str: + """One reason in the language of the user, with the fields a template asks for.""" + table = reason_texts(lang) + text = table.get(reason) or table.get("other") or reason + try: + return text.format(**fields) + except (KeyError, IndexError): + return text + + +def language_name(lang: str) -> str: + return load(lang).get("name", lang) + + +def find_by_hint(lang: str) -> Optional[str]: + """Resolve a ``--lang`` hint (a code or a name) to a language code, or ``None``.""" + if lang in _available(): + return lang + wanted = fold(lang) + for code in languages(): + if fold(code) == wanted or fold(language_name(code)) == wanted: + return code + return None + + +def _available() -> List[str]: + return languages() diff --git a/lggeostratum/pipeline.py b/lggeostratum/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..7a5f98730c3c027880de78a66acaf1c73b69e400 --- /dev/null +++ b/lggeostratum/pipeline.py @@ -0,0 +1,116 @@ +"""One run of the topology in a single process, with every envelope re-checked. + +The orchestrator runs the eight nodes as separate processes, one turn each. This module chains the +very same ``step_*`` functions in memory and runs the referee of the stratum on every envelope on +the way, which is what the orchestrator does with each turn. It exists for the tests, for the +coverage report over the corpus, and for the ablation experiments, where thousands of runs are +needed and a process per node would dominate the time. + +``checked_verdict`` is the part that matters outside this module: it recomputes the verdict from the +evidence the transcript carries, so a node that rewrote its own record is answered by the same rules +the arbiter was supposed to follow, and the answer shown is whichever of the two is more cautious. +The tools print that verdict, not the one the arbiter wrote. +""" + +import os +from typing import Any, Dict, List, Optional, Sequence + +from . import agents, compare, coverage, decide, faults, protocol, render + +ORDER = agents.ORDER +ONTOLOGY = "(set-option :timeout 8000)\n" + + +def referee(decls: List[str], asserts: List[str]) -> str: + """Run the referee of the stratum over one envelope claim, in this process.""" + status = compare.smt_referee(decls, asserts) + return status if status in ("sat", "unsat", "unknown", "error") else "unknown" + + +def seed(question: str, lang: str) -> Dict[str, Any]: + """The envelope the arbiter node starts a session with: the question and its language.""" + dossier = {"question": question, "lang": lang} + return {"payload": {"naturalLanguage": protocol.encode("question (%s): %s" % (lang, question), dossier)}, + "sender": "arbiter", "turn": 0, "volatileState": {"internalTimeTick": 0}} + + +def ask(question: str, lang: str, active: Sequence[str] = ORDER, fault_spec: Optional[Sequence[str]] = None, + call_geometry: bool = True) -> Dict[str, Any]: + """One session, in memory: returns the dossier, the referee log, the verdict and the reply.""" + faults.configure(fault_spec or ()) + previous = os.environ.get("LGSTRATUM_GEOMETRY_BACKEND") + if not call_geometry: + os.environ["LGSTRATUM_GEOMETRY_BACKEND"] = "none" + current = seed(question, lang) + records: List[Dict[str, Any]] = [] + turn = 0 + try: + for name in ORDER: + if name not in active: + continue + turn += 1 + incoming = {"sender": current["sender"], "turn": turn, + "volatileState": {"internalTimeTick": turn}, "payload": current["payload"]} + out = agents.run_step(name, incoming, name) + constraints = out["payload"]["smtConstraints"] + actual = referee(constraints["declarations"], constraints["assertions"]) + records.append({"turn": turn, "sender": name, "claimed": constraints["z3Status"], "referee": actual}) + current = out + finally: + if not call_geometry: + if previous is None: + os.environ.pop("LGSTRATUM_GEOMETRY_BACKEND", None) + else: + os.environ["LGSTRATUM_GEOMETRY_BACKEND"] = previous + dossier = protocol.decode(current["payload"]["naturalLanguage"]) + final = checked_verdict(dossier, records, arbiter_expected="arbiter" in active) + reply = render.reply(dossier, final, records) + return {"dossier": dossier, "records": records, "final": final, "reply": reply, + "faults": sorted(faults.FIRED)} + + +def _unknown(reason: str) -> Dict[str, Any]: + return {"state": "NONE", "assurance": 0, "ceiling": 0, "math_assurance": 0, "math_status": None, + "answer": "", "reasons": [reason], "consulted_math": False, "detected": []} + + +def referee_adjusted(final: Dict[str, Any], records: List[Dict[str, Any]]) -> Dict[str, Any]: + """Zero the verdict when the referee disagrees with what a node claimed about its own envelope.""" + bad = [record["sender"] for record in records if record["claimed"] != record["referee"]] + if bad: + final = dict(final) + final["assurance"] = 0 + final["reasons"] = list(final.get("reasons", [])) + ["referee"] + final["detected"] = list(final.get("detected", [])) + bad + return final + + +def independent_echo(dossier: Dict[str, Any]) -> bool: + """Recompute the echo check from the transcript, without asking the node that wrote it.""" + geometry_verdict = dossier.get("math") or {} + if not geometry_verdict.get("problem_math"): + return True + for key in ("reading_a", "reading_b", "reading_direct"): + reading = dossier.get(key) or {} + if reading.get("math") and not coverage.echo_matches(reading, geometry_verdict): + return False + return True + + +def checked_verdict(dossier: Dict[str, Any], records: List[Dict[str, Any]], arbiter_expected: bool = True) -> Dict[str, Any]: + """The verdict a user is shown: recomputed from the evidence, then the more cautious of the two.""" + try: + evidence = dict(dossier) + evidence["echo_ok"] = independent_echo(dossier) + recomputed = referee_adjusted(decide.decide(evidence), records) + except (AttributeError, KeyError, TypeError, ValueError, IndexError, ArithmeticError) as error: + return _unknown("the decision rule could not read the evidence: %s" % error) + arbiter = dossier.get("final") + if not isinstance(arbiter, dict) or "state" not in arbiter or "assurance" not in arbiter: + return _unknown("the arbiter produced no verdict") if arbiter_expected else recomputed + if arbiter["state"] == recomputed["state"] and arbiter.get("answer") == recomputed.get("answer"): + return recomputed + final = dict(recomputed if recomputed["assurance"] <= int(arbiter.get("assurance", 0) or 0) else arbiter) + final["reasons"] = list(final.get("reasons", [])) + ["arbiter and recomputed decision disagree"] + final["detected"] = list(final.get("detected", [])) + ["arbiter"] + return final diff --git a/lggeostratum/protocol.py b/lggeostratum/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..312f42d6a97c22732326c904f0a1f6dfbf3046f6 --- /dev/null +++ b/lggeostratum/protocol.py @@ -0,0 +1,79 @@ +"""Envelope helpers: the dossier travels inside payload.naturalLanguage. + +The orchestrator forwards only the payload of the previous message, so the growing record of a +session (the dossier) is serialised as JSON after a marker line in ``naturalLanguage``. The text +before the marker is a one line human summary. This is the same contract the geometry layer uses, +which is what lets one orchestrator run either topology without knowing the difference. + +The dossier of a geometry-stratum session holds, in the order the nodes write it: + +``question`` the sentence as the user wrote it, in the user's own language +``lang`` the variety the answer must be written back in +``reading_a`` what reader A (surface patterns) understood, with its notes +``reading_b`` what reader B (marker frames) understood, with its notes +``compare`` whether the two readings are the same problem, and on what grounds +``coverage`` whether the agreed reading kept every number the user wrote +``sent`` the sentence of the geometry language handed to the geometry layer +``math`` the verdict the geometry layer returned, copied without any change +``final`` the state, the assurance and the answer shown to the user +``crash`` a role that failed, so the arbiter can report UNKNOWN instead of pretending +""" + +import json +from typing import Any, Dict, List, Optional + +MARK = "@@DOSSIER@@" + + +def encode(summary: str, dossier: Dict[str, Any]) -> str: + return summary.replace("\n", " ") + "\n" + MARK + json.dumps(dossier, sort_keys=True, separators=(",", ":")) + + +def decode(text: str) -> Dict[str, Any]: + """Return the dossier, or a fresh one holding the raw text as the user question.""" + if MARK in text: + return json.loads(text.split(MARK, 1)[1]) + return {"v": 1, "question": text.strip(), "lang": "en"} + + +def summary_of(text: str) -> str: + return text.split("\n", 1)[0] + + +def envelope( + node_id: str, + recipient: Optional[str], + turn: int, + tick: int, + summary: str, + ast: str, + dossier: Dict[str, Any], + decls: List[str], + assertions: List[str], + claimed: str, +) -> Dict[str, Any]: + out: Dict[str, Any] = { + "sender": node_id, + "turn": turn, + "volatileState": {"internalTimeTick": tick}, + "payload": { + "naturalLanguage": encode(summary, dossier), + "abstractSyntaxTree": ast, + "smtConstraints": {"declarations": decls, "assertions": assertions, "z3Status": claimed}, + }, + } + if recipient: + out["recipient"] = recipient + return out + + +def start(incoming: Dict[str, Any]): + """Decode an incoming envelope into (dossier, turn, tick, sender).""" + dossier = decode(incoming["payload"]["naturalLanguage"]) + tick = int(incoming.get("volatileState", {}).get("internalTimeTick", 0)) + return dossier, int(incoming["turn"]), tick, incoming["sender"] + + +def out(node_id: str, rcpt: str, turn: int, tick: int, dossier: Dict[str, Any], summary: str, ast: str, + decls: List[str], asserts: List[str], claimed: str) -> Dict[str, Any]: + return envelope(node_id, rcpt, turn, tick, summary, ast, dossier, decls, asserts, claimed) diff --git a/lggeostratum/read_a.py b/lggeostratum/read_a.py new file mode 100644 index 0000000000000000000000000000000000000000..f0f7d9d8931429e60b8ded1053c8461709131537 --- /dev/null +++ b/lggeostratum/read_a.py @@ -0,0 +1,402 @@ +"""Reader A: the strict reader, matching the surface patterns of the lexicon. + +Reader A holds the sentence against the **patterns** of a language variety: each accepted shape +is written out in ``lexicon/.json`` with the entities of the figure in a slot. A pattern +matches only if every function word it names is present, in order, and if every verb and every +joint the user wrote is accounted for. That strictness is the point: when A produces a sentence +it read one of the documented shapes and nothing else. + +Reader B (:mod:`lggeostratum.read_b`) does something different with the same data -- it looks for +the joint *frame* of a kind in the sentence, ignoring where the verb stands -- and the topology +only trusts a reading the two agree on. What the two readers share is the lexicon, the atomiser +in :mod:`lggeostratum.segment` and the templates of the geometry language in +:mod:`lggeostratum.canonical`, just as the two formalizers of the geometry topology share one written +grammar and one token spec. + +One difference against the geometry bundle runs through this whole module: the values of the slots of +a geometry sentence are not expressions, they are **names** -- the capitalised names of the +points of a figure, the small letter name of a line or of a circle -- and a name is not a word of +any variety. A capitalised atom that no lexicon phrase claims is therefore a name, and that is +the rule both readers use to tell a point from prose. +""" + +import re +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, lexicon +from .segment import atomize, fold, numeric_literals, word_pieces + +_SLOT = re.compile(r"\{([A-Z])\}") +_NAME = re.compile(r"[A-Z][A-Za-z0-9_]*") +_ENTITY_LETTER = re.compile(r"[a-z]") +_CONTENT = ("math", "name", "connective") + + +def compile_pattern(pattern: str) -> Tuple[List[List[str]], List[str]]: + """Split a surface pattern into its literal word chunks and its slot names, in order.""" + parts = _SLOT.split(pattern) + chunks: List[List[str]] = [] + slots: List[str] = [] + index = 0 + while index < len(parts): + chunks.append([fold(piece) for word in parts[index].split() for piece in word_pieces(word)]) + index += 1 + if index < len(parts): + slots.append(parts[index]) + index += 1 + return chunks, slots + + +def is_name(atom: str) -> bool: + """Whether an atom as written is a point name of the geometry language.""" + return bool(_NAME.fullmatch(atom)) + + +def is_entity_name(atom: str) -> bool: + """Whether an atom no variety claims is the name of a line, a circle, a transformation. + + The geometry language names its points with a capital letter and its other entities with one + small letter, and only the points look like names to a reader of a variety: *r* and *c* are + ordinary letters. A small letter that no phrase of the variety claims is therefore the name of + an entity of the figure -- the one shape the formal language contributes to the atomiser, next + to the capitalised point names, and the spec of both is the naming rule of the bundle. A word + of two or more letters is never treated that way: the bundle names its entities with a single + letter, and a longer unknown word stays what it is. + """ + return canonical.is_entity_name(atom) + + +def _shadowed_by_name(window: Tuple[str, ...], atom: str) -> bool: + """Whether a one letter word of the variety is really the name of a point. + + Italian writes the preposition *a* and the article *l* with the same letters the geometry + language uses for the points A and L, and the data of a variety has to name those prepositions + somewhere. The atomiser folds case, so the two are the same atom once they reach the lexicon: + what tells them apart is the case the sentence wrote, and the convention the six varieties of + this bundle keep -- a name of the figure is always written with its capital letter, in every + language, and a word of the variety never starts with one. A single letter entry of the + lexicon therefore loses to a capitalised atom, and a multi letter word never does, which is + why *Il* at the head of a sentence stays an article and *A* stays a point. + """ + return len(window) == 1 and len(window[0]) == 1 and is_name(atom) + + +def scan(lang: str, text: str) -> List[Dict[str, Any]]: + """Tag every atom: mathematics, a name of the figure, or a lexicon phrase with its role. + + One longest match per position decides between verb, joint, connective and noise, which is + why a data file must not give one phrase two roles. Only after the lexicon has had its turn + does a capitalised atom become a name: the lexicon of a variety claims its own words first, + and a data file that wrote a word twice would be a data file that reads the same sentence two + ways. + """ + phrases = lexicon.phrase_index(lang) + attached = lexicon.prefixes(lang) + stripped_index = lexicon.prefix_index(lang) if attached else {} + longest = lexicon.max_phrase_length(lang) + atoms = atomize(text) + items: List[Dict[str, Any]] = [] + index = 0 + while index < len(atoms): + kind, atom = atoms[index] + if kind == "m": + items.append({"role": "math", "value": atom, "words": [], "surface": atom}) + index += 1 + continue + word = fold(atom) + hit = None + for span in range(min(longest, len(atoms) - index), 0, -1): + if any(atoms[index + step][0] != "w" for step in range(span)): + continue + window = tuple(fold(atoms[index + step][1]) for step in range(span)) + if window in phrases: + hit = (phrases[window], window) + break + if attached: + key = tuple(lexicon.strip_prefix(w, attached) for w in window) + if key in stripped_index: + hit = (stripped_index[key], key) + break + if hit and _shadowed_by_name(window, atom): + hit = None + if hit: + (role, value), key = hit + # The item carries the atoms as the sentence wrote them; the lexicon key it matched is + # kept only to look the verb up, because Arabic writes a lexicon word with prefixes + # attached and the data file records it without them. + item = {"role": role, "value": value, "words": list(window), "surface": atom} + if role == "verb": + table = lexicon.verb_atoms_index(lang) + item["kinds"] = table.get(window) or table.get(key) or (value,) + items.append(item) + index += len(window) + continue + if is_name(atom): + # A name of the figure: it carries its value as written, and no words, so it can never + # be claimed by a literal chunk of a pattern. + items.append({"role": "name", "value": atom, "words": [], "surface": atom}) + index += 1 + continue + if is_entity_name(word): + # The small letter the geometry language gives to a line, to a circle, to a + # transformation. A variety never writes that letter as a word -- the article and the + # preposition of Italian are claimed by the lexicon before this line is reached -- so a + # small letter standing on its own is the name of an entity of the figure. + items.append({"role": "name", "value": word, "words": [], "surface": atom}) + index += 1 + continue + if word in lexicon.MATH_WORDS: + items.append({"role": "math", "value": word, "words": [], "surface": atom}) + index += 1 + continue + if atom and atom in lexicon.noise_chars(lang): + # A single character particle of a script written without spaces (Chinese particles). + # It carries its own atom as its words so that a pattern naming the particle can match + # it; it carries no value, so it never reaches a slot of a reading. + items.append({"role": "noise", "value": "", "words": [word], "surface": atom}) + index += 1 + continue + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom}) + index += 1 + return items + + +def _text(item: Dict[str, Any]) -> str: + """What an item contributes to a slot: a name, an expression, a relation word.""" + if item["role"] == "connective": + return " %s " % item["value"] + return item["value"] + + +def _claim(words: List[str], chunk_slice: List[str], attached: List[str]) -> bool: + """Whether the atoms an item carries are the atoms a chunk of the pattern asks for. + + Arabic writes a word with its article and its conjunctions attached to it, and the pattern in + the data file names the bare word. Stripping the attachment from both sides is what lets a + pattern name a word the sentence wrote in another form, and nothing else is forgiven: an item + that carries no atoms is a name or a piece of mathematics, and neither is ever a word of a + pattern. + """ + if not words: + return False + if list(words) == list(chunk_slice): + return True + if not attached: + return False + return ([lexicon.strip_prefix(word, attached) for word in words] + == [lexicon.strip_prefix(word, attached) for word in chunk_slice]) + + +def _find(chunk: List[str], items: List[Dict[str, Any]], start: int, + attached: List[str]) -> Optional[Tuple[int, int]]: + """Where in the item stream the literal words of a pattern chunk appear, or ``None``. + + A chunk is contiguous: it may not span a name or a piece of mathematics, and no function word + the pattern did not name may sit inside it. That is what stops a pattern from swallowing a + sentence it does not describe. + """ + for first in range(start, len(items) + 1): + cursor = first + taken = 0 + ok = True + while taken < len(chunk): + if cursor >= len(items): + ok = False + break + words = items[cursor]["words"] + if not _claim(words, chunk[taken:taken + len(words)], attached): + ok = False + break + taken += len(words) + cursor += 1 + if ok: + return first, cursor + return None + + +def _consume(items: List[Dict[str, Any]], start: int, stop: int) -> Optional[List[Dict[str, Any]]]: + """The entities held between two positions, or ``None`` when an unnamed word stands there. + + The conjunction a variety uses to list the entities of a slot -- the "e" of "A, B e C" -- is a + connective in this layer, exactly as the "and" it prints as, so it belongs to the region like a + comma does and says where one entity stops and the next begins. A marker of the geometry + language is a joint the pattern did not name, and it stops the region. + """ + bucket: List[Dict[str, Any]] = [] + for item in items[start:stop]: + if item["role"] in _CONTENT: + bucket.append(item) + elif item["role"] != "noise": + return None + return bucket + + +def _fill(group: List[str], bucket: List[Dict[str, Any]], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> Optional[Dict[str, str]]: + """The values of the slots that one region of a sentence feeds. + + Usually one slot, and the whole region is its value. A pattern may also put two slots side by + side, with no words between them -- Italian writes the two endpoints of a line one after the + other, ``il punto medio di A e B`` -- and then the region has to break into exactly one entity + per slot. One entity per item is the first try, because the atomiser hands a region over as + items and the items of ``A, B`` are already two; when the items do not line up with the slots, + the text of the region is asked for its entities, which is where a conjunction of the variety + and a coordinate pair are accounted for. A region that does not break that way is a region the + pattern cannot read, and guessing where one slot ends and the other begins would be the reader + inventing the problem it then reports. + """ + if len(bucket) < len(group): + return None + if len(group) == 1: + joined = " ".join(_text(item) for item in bucket).strip() + if not joined: + return None + return {group[0]: canonical.tidy(joined)} + if len(bucket) == len(group): + filled: Dict[str, str] = {} + for slot, item in zip(group, bucket): + value = canonical.tidy(_text(item)) + if not value: + return None + filled[slot] = value + return filled + joined = canonical.tidy(" ".join(_text(item) for item in bucket).strip()) + units = canonical.split_units(joined, joins, keywords) + if len(units) != len(group): + return None + filled = {} + for slot, unit in zip(group, units): + value = canonical.tidy(" ".join(unit)) + if not value: + return None + filled[slot] = value + return filled + + +def match(chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]], + attached: List[str], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> Optional[Dict[str, str]]: + """A value per slot name, or ``None`` when the pattern does not describe the items. + + Every verb and every joint of the sentence has to be consumed by a chunk of the pattern, and + the names and expressions left over fall into the slots in the order the pattern names them. + A pattern that ignores a joint the sentence carries is a pattern that misread the sentence, so + it fails; so does a pattern that leaves a name outside every slot. + """ + filled: Dict[str, str] = {} + group = [slots[0]] + position = 0 + if chunks[0]: + # Words before the first slot: a function word the pattern does not name is harmless there, + # because it carries no entity, but a name before it belongs to no slot of the pattern, and + # a verb or a joint before it is a joint the pattern does not describe. + found = _find(chunks[0], items, 0, attached) + if found is None or _consume(items, 0, found[0]) != []: + return None + position = found[1] + for index in range(1, len(slots)): + if not chunks[index]: + group.append(slots[index]) + continue + found = _find(chunks[index], items, position, attached) + if found is None: + return None + bucket = _consume(items, position, found[0]) + if bucket is None: + return None + part = _fill(group, bucket, joins, keywords) + if part is None: + return None + filled.update(part) + group = [slots[index]] + position = found[1] + tail = chunks[len(slots)] + if tail: + found = _find(tail, items, position, attached) + # Nothing but function words may follow the last words of the pattern: a name after the + # end of the shape belongs to no slot, so the shape does not describe the sentence. + if found is None or _consume(items, found[1], len(items)) != []: + return None + bucket = _consume(items, position, found[0]) + else: + bucket = _consume(items, position, len(items)) + if bucket is None: + return None + part = _fill(group, bucket, joins, keywords) + if part is None: + return None + filled.update(part) + return filled + + +def _slot_problems(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> List[Dict[str, str]]: + """A slot that is not the shape the kind promises: a name where a line belongs, a stray word.""" + problems: List[Dict[str, str]] = [] + for name, value in sorted(slots.items()): + try: + canonical.normalize_slot(kind, name, value, joins, keywords) + except canonical.ReadingError as error: + problems.append({"reason": "bad_" + canonical.slot_reason(name), + "slot": name, "detail": str(error)}) + return problems + + +def read(lang: str, text: str) -> Dict[str, Any]: + """The reading reader A reaches in one variety, and why it abstained when it did.""" + items = scan(lang, text) + result: Dict[str, Any] = {"reader": "reader_a", "lang": lang, "mode": "pattern", + "kind": None, "math": None, "slots": {}, "markers": [], "notes": []} + unknown = [item for item in items if item["role"] == "unknown"] + if unknown: + result["status"] = "NOT COVERED" + for item in unknown: + result["notes"].append({"reason": item.get("reason", "unknown_word"), + "word": item["surface"]}) + return result + result["markers"] = [item["value"] for item in items if item["role"] == "marker"] + candidates, why = lexicon.announce(lang, items) + if not candidates: + result["status"] = "NOT COVERED" + result["notes"].append(why) + return result + result["announced"] = candidates + attached = lexicon.prefixes(lang) + joins = tuple(lexicon.conjunction_words(lang)) + keywords = tuple(lexicon.entity_keyword_words(lang)) + found: List[Tuple[str, str, Dict[str, str]]] = [] + for kind in candidates: + for pattern in lexicon.patterns(lang).get(kind, []): + chunks, slots = compile_pattern(pattern) + assigned = match(chunks, slots, items, attached, joins, keywords) + if assigned is None: + continue + problems = _slot_problems(kind, assigned, joins, keywords) + if problems: + result["notes"].extend(problems) + continue + try: + math_str = canonical.print_geometry(kind, assigned, joins, keywords) + except canonical.ReadingError as error: + result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)}) + continue + if not any(entry[1] == math_str for entry in found): + found.append((kind, math_str, assigned)) + if not found: + result["status"] = "NOT COVERED" + if not any(note["reason"].startswith("bad_") for note in result["notes"]): + result["notes"].append({"reason": "no_pattern"}) + return result + if len(found) > 1: + result["status"] = "AMBIGUOUS" + result["notes"].append({"reason": "multiple", + "first": found[0][1], "second": found[1][1]}) + return result + kind, math_str, assigned = found[0] + result["status"] = "READ" + result["kind"] = kind + result["math"] = math_str + result["slots"] = assigned + result["literals"] = numeric_literals(text) + result["notes"] = [] + return result diff --git a/lggeostratum/read_b.py b/lggeostratum/read_b.py new file mode 100644 index 0000000000000000000000000000000000000000..3723bd312bbc18ac4cbbd831dccba250650a9152 --- /dev/null +++ b/lggeostratum/read_b.py @@ -0,0 +1,338 @@ +"""Reader B: the frame reader, which never looks at a surface pattern. + +Reader B finds the lexicon phrases in a sentence by searching for them -- longest phrase first, +over the whole sentence, instead of walking the sentence from left to right -- and then reads the +sentence by the **joints** of the geometry language: the markers the sentence carries, in the +order it carries them. Where the verb stands, which words surround it and whether the sentence +names the points before or after the claim are all invisible to B. It asks one question: does the +sentence hold the joints of a form of the geometry language, with an entity of the figure between +each pair? + +That is a different question from reader A's ("does this sentence have one of the shapes the +lexicon writes down?"), so the two reach different answers on real sentences, which is the point. +What they share is the lexicon, the atomiser and the templates of the geometry language -- the +same kind of sharing the two formalizers of the geometry topology accept, where one written grammar +is the specification both are checked against. + +In a geometry sentence the joints are mostly prepositional phrases -- "with center", "lies +between", "is perpendicular to" -- and the verb of the kind is often one of them: the frame is +then the order of those phrases alone, and the entity the claim is about stands in the gap the +form leaves without a joint. +""" + +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, lexicon +from .canonical import ReadingError +from .segment import atomize, fold, numeric_literals + +_CONTENT = ("math", "name", "connective") +_NAME = canonical.is_name + + +def _matches(window: List[str], phrase: Tuple[str, ...], attached: List[str]) -> bool: + """Whether a window of folded word atoms is a phrase, with or without attached prefixes. + + The data file of Arabic writes "on the straight line" without its article, and a sentence + writes it with one. The comparison then strips the attachment from both sides, which is what + lets the article of the sentence and the absence of it in the data file meet in the same + written form. + """ + if list(window) == list(phrase): + return True + if not attached: + return False + stripped = [lexicon.strip_prefix(atom, attached) for atom in window] + return stripped == list(phrase) or stripped == [lexicon.strip_prefix(a, attached) for a in phrase] + + +def find_spans(lang: str, atoms: List[Tuple[str, str]]) -> Tuple[List[Dict[str, Any]], List[bool]]: + """Every occurrence of every lexicon phrase, longest first, never overlapping. + + Reader A resolves one position at a time by taking the longest phrase there. B enumerates the + whole phrase table, longest entries first, and lets each entry claim its occurrences wherever + they are. The two orderings disagree on purpose: a sentence whose phrases interleave gives the + two readers different chances, and a reading only counts when both take it. + """ + folded = [fold(atom) if kind == "w" else "" for kind, atom in atoms] + attached = lexicon.prefixes(lang) + covered = [False] * len(atoms) + table = sorted(lexicon.phrase_index(lang).items(), + key=lambda entry: (-len(entry[0]), -len("".join(entry[0])), entry[0])) + spans: List[Dict[str, Any]] = [] + for phrase, hit in table: + role, value = hit + if not phrase: + continue + start = 0 + while start <= len(atoms) - len(phrase): + found = None + for position in range(start, len(atoms) - len(phrase) + 1): + if any(covered[position + step] or atoms[position + step][0] != "w" + for step in range(len(phrase))): + continue + if len(phrase) == 1 and len(phrase[0]) == 1 and _NAME(atoms[position][1]): + # A one letter word of the variety and a point of the figure are the same + # letters once the case is folded: the capital the sentence wrote is what + # tells them apart, and the name wins. See reader A for the same convention. + continue + if _matches(folded[position:position + len(phrase)], phrase, attached): + found = position + break + if found is None: + break + for step in range(len(phrase)): + covered[found + step] = True + spans.append({"start": found, "end": found + len(phrase), "role": role, + "value": value, "words": folded[found:found + len(phrase)], + "kinds": (lexicon.verb_atoms_index(lang).get(phrase, (value,)) + if role == "verb" else (value,))}) + start = found + len(phrase) + spans.sort(key=lambda span: span["start"]) + return spans, covered + + +def classify(lang: str, atoms: List[Tuple[str, str]], spans: List[Dict[str, Any]], + covered: List[bool]) -> List[Dict[str, Any]]: + """Tag each atom from the spans, and name what no phrase claimed. + + B has no left to right walk to reason with, so an atom no phrase of the variety claimed is + judged by its shape alone: a capitalised atom is a name of the figure -- names are not + translated, in any variety -- and anything else that is not a particle of the script is an + unknown word. Reader A, which reads a phrase table position by position, gives its lexicon the + first chance at the same atom: that is one of the ways the two readers can part company, and a + capitalised word a variety also uses as a noun is exactly where they do. + """ + particles = lexicon.load(lang).get("noise_chars", "") + starts = {span["start"]: span for span in spans} + items: List[Dict[str, Any]] = [] + index = 0 + while index < len(atoms): + kind, atom = atoms[index] + if kind == "m": + items.append({"role": "math", "value": atom, "words": [], "surface": atom}) + index += 1 + continue + if index in starts: + span = starts[index] + items.append({"role": span["role"], "value": span["value"], "words": span["words"], + "kinds": span.get("kinds", (span["value"],)), "surface": atom}) + index = span["end"] + continue + word = fold(atom) + if atom and atom in particles: + items.append({"role": "noise", "value": "", "words": [], "surface": atom}) + index += 1 + continue + if _NAME(atom): + items.append({"role": "name", "value": atom, "words": [], "surface": atom}) + index += 1 + continue + if canonical.is_entity_name(word): + # The one small letter the geometry language gives to a line, to a circle, to a + # transformation. No phrase of the lexicon reached it, so it is a name of the figure: + # reader A states the same convention where it walks the sentence itself. + items.append({"role": "name", "value": word, "words": [], "surface": atom}) + index += 1 + continue + if word in lexicon.MATH_WORDS: + items.append({"role": "math", "value": word, "words": [], "surface": atom}) + index += 1 + continue + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom}) + index += 1 + return items + + +def _text(item: Dict[str, Any]) -> str: + if item["role"] == "connective": + return " %s " % item["value"] + return item["value"] + + +def _regions_marked(items: List[Dict[str, Any]]) -> List[Tuple[Optional[str], str]]: + """The runs of entities of a sentence, each tagged with the joint standing before it. + + A joint of the geometry language introduces the region that follows it, and the verb of a + sentence introduces nothing: it sits in the gap a form leaves without a joint. Tagging a + region instead of counting regions is what lets B read a frame written out of order, because + a variety may put the points before the claim ("A, B e C sono allineati") or after it + ("sono allineati A, B e C") and a reader that filled the slots by position would put the + subject of the claim where its object belongs. + + The atoms of a region are joined with a space on purpose. The atomiser cuts a sentence into + runs, and one run can be the whole coordinate pair while two runs can be the two ends of one + line reference split by nothing but a hyphen ("A-B"). Gluing the runs without a space invents + a token that was never written, and an invented token is a changed problem. + """ + regions: List[Tuple[Optional[str], str]] = [] + buffer: List[str] = [] + joint: Optional[str] = None + for item in items: + if item["role"] in ("marker", "verb"): + regions.append((joint, canonical.tidy(" ".join(buffer)))) + buffer = [] + joint = item["value"] if item["role"] == "marker" else None + elif item["role"] in _CONTENT: + buffer.append(_text(item)) + regions.append((joint, canonical.tidy(" ".join(buffer)))) + return regions + + +def _groups(slots: Tuple[str, ...], gaps: List[Optional[str]]) -> List[List[Tuple[int, str]]]: + """The slots a form fills from one region each, run together where it leaves no joint. + + The geometry language writes the three points of a collinearity with a joint only before the + last of them ("A, B and C"), so the first two slots of that form share one region of the + sentence, and the pair has to be taken apart by the entities it holds -- the same rule reader + A applies to a pattern with two slots side by side. + """ + out: List[List[Tuple[int, str]]] = [] + for position, slot in enumerate(slots): + if gaps[position] is not None or not out: + out.append([(position, slot)]) + else: + out[-1].append((position, slot)) + return out + + +def _candidates(marked: List[Tuple[Optional[str], str]], joint: Optional[str], + taken: set) -> List[int]: + if joint is None: + return [index for index, (before, text) in enumerate(marked) + if before is None and text and index not in taken] + return [index for index, (before, text) in enumerate(marked) + if before == joint and text and index not in taken] + + +def _assign_joints(marked: List[Tuple[Optional[str], str]], gaps: List[Optional[str]], + slots: Tuple[str, ...], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> Optional[Dict[str, str]]: + """Fill the slots of a form from the regions a sentence offers, or fail. + + A slot takes the region that stands after the joint the form puts before it, and a slot whose + gap carries no joint takes one of the regions of the sentence no joint claims. A region + holding no entity is never a candidate, and every region that does hold one has to end up in a + slot: an entity left over belongs to no slot of the form, so the form does not describe the + sentence. This is also how a joint the geometry language puts last is policed -- the region it + introduces is empty, and anything written after it makes the form fail -- and why a frame whose + slots arrive in a rotated order still reads, because no slot is identified by its position in + the sentence. + """ + assigned: Dict[str, str] = {} + taken: set = set() + for group in _groups(slots, gaps): + joint = gaps[group[0][0]] + candidates = _candidates(marked, joint, taken) + if len(group) == 1: + if len(candidates) != 1: + return None + assigned[group[0][1]] = marked[candidates[0]][1] + taken.add(candidates[0]) + continue + if len(candidates) == len(group): + for (position, slot), index in zip(group, candidates): + assigned[slot] = marked[index][1] + taken.add(index) + continue + if len(candidates) != 1: + return None + units = canonical.split_units(marked[candidates[0]][1], joins, keywords) + if len(units) != len(group): + return None + for (position, slot), unit in zip(group, units): + assigned[slot] = canonical.tidy(" ".join(unit)) + taken.add(candidates[0]) + last = gaps[len(slots)] + if last is not None and any(text for before, text in marked if before == last and text): + return None + if any(text for index, (_, text) in enumerate(marked) if text and index not in taken): + return None + return assigned + + +def _problems(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (), + keywords: Tuple[str, ...] = ()) -> List[Dict[str, str]]: + problems: List[Dict[str, str]] = [] + for name, value in sorted(slots.items()): + try: + canonical.normalize_slot(kind, name, value, joins, keywords) + except ReadingError as error: + problems.append({"reason": "bad_" + canonical.slot_reason(name), + "slot": name, "detail": str(error)}) + if not canonical.balanced(canonical.print_geometry(kind, slots, joins, keywords)): + problems.append({"reason": "unbalanced"}) + return problems + + +def read(lang: str, text: str) -> Dict[str, Any]: + """The reading reader B reaches in one variety, and why it abstained when it did.""" + atoms = atomize(text) + spans, covered = find_spans(lang, atoms) + items = classify(lang, atoms, spans, covered) + result: Dict[str, Any] = {"reader": "reader_b", "lang": lang, "mode": "frame", + "kind": None, "math": None, "slots": {}, "markers": [], "notes": []} + unknown = [item for item in items if item["role"] == "unknown"] + if unknown: + result["status"] = "NOT COVERED" + for item in unknown: + result["notes"].append({"reason": item.get("reason", "unknown_word"), + "word": item["surface"]}) + return result + markers = [item["value"] for item in items if item["role"] == "marker"] + result["markers"] = markers + candidates, why = lexicon.announce(lang, items) + if not candidates: + result["status"] = "NOT COVERED" + result["notes"].append(why) + return result + result["announced"] = candidates + regions = _regions_marked(items) + frame_table = lexicon.frames(lang) + joins = tuple(lexicon.conjunction_words(lang)) + keywords = tuple(lexicon.entity_keyword_words(lang)) + found: List[Tuple[str, str, Dict[str, str]]] = [] + for kind in candidates: + allowed = [list(sequence) for sequence in frame_table.get(kind, {}).get("sequences", [])] + if markers not in allowed: + result["notes"].append({"reason": "no_frame", "kind": kind, + "detail": " ".join(markers) or "none"}) + continue + for variant in canonical.VARIANTS.get(kind, []): + if canonical.marker_sequence(kind, variant) != markers: + continue + assigned = _assign_joints(regions, canonical.gap_markers(kind, variant), variant, + joins, keywords) + if assigned is None: + result["notes"].append({"reason": "markers", "kind": kind, + "detail": " ".join(markers)}) + continue + try: + math_str = canonical.print_geometry(kind, assigned, joins, keywords) + except ReadingError as error: + result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)}) + continue + problems = _problems(kind, assigned, joins, keywords) + if problems: + result["notes"].extend(problems) + continue + if not any(entry[1] == math_str for entry in found): + found.append((kind, math_str, assigned)) + if not found: + result["status"] = "NOT COVERED" + if not result["notes"]: + result["notes"].append({"reason": "no_pattern"}) + return result + if len(found) > 1: + result["status"] = "AMBIGUOUS" + result["notes"].append({"reason": "multiple", + "first": found[0][1], "second": found[1][1]}) + return result + read_kind, math_str, assigned = found[0] + result["status"] = "READ" + result["kind"] = read_kind + result["math"] = math_str + result["slots"] = assigned + result["literals"] = numeric_literals(text) + result["notes"] = [] + return result diff --git a/lggeostratum/render.py b/lggeostratum/render.py new file mode 100644 index 0000000000000000000000000000000000000000..68fe199eb0f78b1c4d309cf27997815c1e15623a --- /dev/null +++ b/lggeostratum/render.py @@ -0,0 +1,140 @@ +"""The answer the user reads, in the language the user wrote in. + +Nothing here decides anything: the text is built from the verdict ``decide`` produced and from the +words the lexicon of that language provides. Two kinds of text meet in one reply, and the boundary +between them is deliberate: + +* every label, state name and reason is taken from ``lexicon/.json``, so the framing of the + answer belongs to the user's language; +* the formal content -- the canonical sentence the stratum understood and the answer the + geometry bundle returned -- is passed through byte for byte, because it is a value and not prose. + +The sentence the stratum understood is always shown. A user who wrote in Italian and gets back +``Prove that A, B and C are collinear.`` can see which reading was used, and that is the whole point +of a stratum: the interpretation is inspectable, not hidden inside a model. + +When no answer can be shown, the reply says so in the user's language and lists the forms this +language variety does understand, from ``lexicon.examples``, so the failure is a correction and not +a dead end. +""" + +import re +from typing import Any, Dict, List, Optional + +from . import decide as decide_module +from . import lexicon + +FIELDS = ("word", "kind", "detail", "left", "right", "slot") +_PLACEHOLDER = re.compile(r"\{[a-z_]+\}") + + +def _fill(text: str) -> str: + """Drop a placeholder the template kept: an unfilled brace must never reach the user.""" + return _PLACEHOLDER.sub("", text).replace(" ", " ").strip(" ;,:") + + +def note_fields(dossier: Dict[str, Any]) -> Dict[str, Dict[str, Any]]: + """The fields each reason carries, collected from the notes the readers left behind.""" + out: Dict[str, Dict[str, Any]] = {} + for reading in [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}, + dossier.get("reading_direct") or {}]: + for note in reading.get("notes") or []: + if isinstance(note, dict) and note.get("reason"): + fields = {key: note[key] for key in FIELDS if key in note} + out.setdefault(str(note["reason"]), fields) + for reason, fields in ((dossier.get("math") or {}).get("reason_fields") or {}).items(): + out.setdefault(str(reason), dict(fields)) + return out + + +def _kind_understood(dossier: Dict[str, Any]) -> str: + """The kind of problem the stratum solved, as the identifier the geometry language uses.""" + for key in ("reading_a", "reading_b", "reading_direct"): + reading = dossier.get(key) or {} + if reading.get("kind"): + return str(reading["kind"]) + return "" + + +def _sentence(dossier: Dict[str, Any]) -> str: + """The canonical sentence that was, or would have been, handed to the geometry bundle.""" + compare = dossier.get("compare") or {} + math_verdict = dossier.get("math") or {} + for source in (dossier.get("sent"), compare.get("left"), math_verdict.get("problem_math")): + if source: + return str(source) + for key in ("reading_a", "reading_b", "reading_direct"): + reading = dossier.get(key) or {} + if reading.get("math"): + return str(reading["math"]) + return "" + + +def _check_line(lang: str, records: Optional[List[Dict[str, Any]]]) -> str: + """How many envelopes of the run the referee of the orchestrator confirmed.""" + if not records: + return "" + good = sum(1 for record in records if record.get("claimed") == record.get("referee")) + return lexicon.labels(lang)["check"].format(a=good, b=len(records)) + + +def reply(dossier: Dict[str, Any], final: Optional[Dict[str, Any]] = None, + records: Optional[List[Dict[str, Any]]] = None, lang: Optional[str] = None) -> Dict[str, Any]: + """Build the user-facing answer: one text block plus the machine-readable parts.""" + lang = lang or str(dossier.get("lang") or "en") + if lang not in lexicon.codes(): + lang = "en" + verdict = final or decide_module.decide(dossier) + labels = lexicon.labels(lang) + states = lexicon.reading_labels(lang) + fields = note_fields(dossier) + + lines: List[str] = [] + state = str(verdict.get("state", "NONE")) + lines.append("%s: %s" % (labels["status"], states.get(state, state))) + sentence = _sentence(dossier) + kind = _kind_understood(dossier) + if sentence and state not in ("NOT COVERED", "NONE"): + lines.append("%s (%s): %s" % (labels["understood"], kind, sentence)) + if verdict.get("answer"): + lines.append("%s: %s" % (labels["answer"], verdict["answer"])) + lines.append(labels["assurance"].replace("{n}", str(verdict.get("assurance", 0)))) + math_verdict = dossier.get("math") or {} + if math_verdict.get("status"): + # Which engine of the bundle settled which obligation is its own bookkeeping and nothing + # the reader of an answer asked for; what belongs in the reply is the verdict and, when the + # bundle abstained, the reason it abstained. + tail = str(math_verdict["status"]) + why = math_verdict.get("reason") or math_verdict.get("note") or "" + if not why and math_verdict.get("reasons"): + why = str(math_verdict["reasons"][0]) + if why: + tail += " (" + why + ")" + lines.append("%s: %s" % (labels["math_layer"], tail)) + reasons = [str(reason) for reason in verdict.get("reasons") or []] + if reasons: + math_verdict = dossier.get("math") or {} + fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])}) + fields.setdefault("geometry_unknown", {"detail": str(math_verdict.get("reason") + or math_verdict.get("note") or "")}) + texts = [_fill(lexicon.translate_reason(lang, reason, **(fields.get(reason) or {}))) for reason in reasons] + lines.append("%s: %s" % (labels["notes"], "; ".join(texts))) + check = _check_line(lang, records) + if check: + lines.append(check) + if state in ("NOT COVERED", "AMBIGUOUS", "NONE") and not verdict.get("answer"): + samples = lexicon.examples(lang) + if samples: + lines.append("%s: %s" % (labels["question"], " | ".join(samples[:5]))) + return { + "lang": lang, + "language": lexicon.language_name(lang), + "state": state, + "assurance": verdict.get("assurance", 0), + "answer": verdict.get("answer", ""), + "sentence": sentence, + "kind": kind, + "reasons": reasons, + "lines": lines, + "text": "\n".join(lines), + } diff --git a/lggeostratum/segment.py b/lggeostratum/segment.py new file mode 100644 index 0000000000000000000000000000000000000000..12fb177e7fb918e31ecc5b8765e87f2d1eafad92 --- /dev/null +++ b/lggeostratum/segment.py @@ -0,0 +1,240 @@ +"""Script aware tokenisation and digit normalisation of a natural language sentence. + +This module knows nothing about the languages: it splits a sentence into runs of *words* and +runs of *mathematics*, and it puts every digit in the shape the geometry language uses. The +mapping from a word to a role is the lexicon, in ``lexicon/.json`` and +:mod:`lggeostratum.lexicon`. + +Three normalisations happen here, and all three are testable on their own: + +* digit scripts: Arabic-Indic, Extended Arabic-Indic and Devanagari digits become ASCII + digits, and compatibility normalisation turns the full width forms a Chinese keyboard + produces into their ASCII counterparts; +* separators that differ per language: the Arabic decimal sign, the Arabic and Devanagari + commas, the CJK full stop and question mark, and the bidi control characters disappear or + take their ASCII counterpart; +* context for ``.`` and ``,``: a dot is part of a number only between digits, a comma is part + of the geometryematics only between two closed operands, which is what separates the comma of a + coordinate pair ``(0, 0)`` from the comma that lists the three points of a triangle. +""" + +import re +import unicodedata +from typing import List, Tuple + +# --------------------------------------------------------------------------- +# Digits and separators +# --------------------------------------------------------------------------- +def _digits(start: int) -> dict: + return {chr(start + i): str(i) for i in range(10)} + + +DIGIT_MAP: dict = {} +DIGIT_MAP.update(_digits(0x0660)) # Arabic-Indic +DIGIT_MAP.update(_digits(0x06F0)) # Extended Arabic-Indic (Persian/Urdu) +DIGIT_MAP.update(_digits(0x0966)) # Devanagari +DIGIT_MAP.update(_digits(0x09E6)) # Bengali + +SEPARATOR_MAP: dict = { + "\u060c": " ", # Arabic comma + "\u061b": " ", # Arabic semicolon + "\u061f": " ", # Arabic question mark + "\u066b": ".", # Arabic decimal sign + "\u066c": "", # Arabic thousands separator + "\u066d": " ", # Arabic date separator + "\u0964": " ", # Devanagari danda + "\u0965": " ", # Devanagari double danda + "\u3001": " ", # ideographic comma + "\u3002": " ", # ideographic full stop + "\uff1f": " ", # full width question mark + "\uff01": " ", # full width exclamation mark + "\u201e": " ", + "\u201f": " ", + "\u2018": " ", + "\u2019": "'", # the apostrophe of an elision is kept, and the elision is split apart + "\u201c": " ", + "\u201d": " ", + # The Italian copula would otherwise fold to the connective "e" (and), so it is not a word. + "\u00e8": " ", + "\u2013": "-", + "\u2014": "-", + "\u2212": "-", # minus sign + "\u00d7": "*", # multiplication sign + "\u00b7": "*", # middle dot + "\u00f7": "/", # division sign + "\u2265": ">=", + "\u2264": "<=", + "\u2260": "!=", +} + +INVISIBLE = ( + "\u200b\u200c\u200d\u200e\u200f\u061c\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\ufeff" +) + +# The symbols of the geometry language, parentheses included: a coordinate pair is the reason +# they are here, and they must be read as mathematics and not dropped as stray punctuation. +MATH_CHARS = set("0123456789+-*/^()[]<>=!|,:.") +CLOSED_CHARS = set("0123456789)]") +OPENING_CHARS = set("0123456789[(") + +# The relation and operator symbols the geometry language accepts. Nothing else is mathematics. +OPERATORS = ("=>", "<=>", "<=", ">=", "!=", "+", "-", "*", "/", "^", "=", "<", ">", "|") + + +def normalize(text: str) -> str: + """Return the sentence in a canonical shape: ASCII digits, ASCII separators, one space.""" + text = unicodedata.normalize("NFKC", text) + for ch in INVISIBLE: + text = text.replace(ch, "") + text = text.translate({ord(k): v for k, v in DIGIT_MAP.items()}) + text = text.translate({ord(k): v for k, v in SEPARATOR_MAP.items()}) + return re.sub(r"\s+", " ", text).strip() + + +def script_of(text: str) -> str: + """The dominant non Latin script of a sentence: cjk, arabic, devanagari, latin or none.""" + counts = {"cjk": 0, "arabic": 0, "devanagari": 0, "latin": 0} + for ch in text: + if not ch.isalpha(): + continue + name = unicodedata.name(ch, "") + if name.startswith("CJK") or name.startswith("IDEOGRAPHIC"): + counts["cjk"] += 1 + elif name.startswith("ARABIC"): + counts["arabic"] += 1 + elif name.startswith("DEVANAGARI"): + counts["devanagari"] += 1 + elif name.startswith("LATIN"): + counts["latin"] += 1 + best = max(counts, key=lambda k: counts[k]) + return best if counts[best] else "none" + + +def _is_math_char(ch: str, text: str, index: int) -> bool: + if ch in MATH_CHARS: + if ch == ".": + return _neighbour(text, index, -1).isdigit() and _neighbour(text, index, 1).isdigit() + if ch == ",": + return _neighbour(text, index, -1) in CLOSED_CHARS and _neighbour(text, index, 1) in OPENING_CHARS + return True + return False + + +def _neighbour(text: str, index: int, step: int) -> str: + j = index + step + while 0 <= j < len(text) and text[j] == " ": + j += step + return text[j] if 0 <= j < len(text) else "" + + +_MARKS = ("Mn", "Mc", "Me") + + +def _word_char(ch: str) -> bool: + """A character of a word: a letter of any script, an apostrophe, or a combining mark. + + The combining marks matter: the vowel signs of Devanagari and the Arabic diacritics are not + letters, and dropping them would break a word into pieces that no lexicon entry matches. + """ + return ch.isalpha() or ch in "_'" or unicodedata.category(ch) in _MARKS + + +def pieces(run: str) -> List[str]: + """Split a word run at every apostrophe: an Italian elision is two words to the lexicon. + + ``l'integrale`` is the article ``l`` and the noun ``integrale``, and only the second of the + two is a phrase of the lexicon. The lexicon patterns are written with the elision joined, + and compiled through this same function, so data and matching agree. + """ + return [piece for piece in run.split("'") if piece] + + +def is_cjk(run: str) -> bool: + """Whether a run is written in Chinese characters.""" + return any(unicodedata.name(ch, "").startswith(("CJK", "IDEOGRAPHIC")) for ch in run) + + +def word_pieces(run: str) -> List[str]: + """The atoms a word run offers the lexicon: characters for Chinese, pieces elsewhere. + + Chinese is written without spaces, so the only reliable unit is the character, and a + multi character term of the lexicon is then a sequence of atoms -- which is how the lexicon + file writes it too, one space separated token per character group. + """ + if is_cjk(run): + return list(run) + return pieces(run) + + +def atomize(text: str) -> List[Tuple[str, str]]: + """A normalized sentence as atoms: ``("m", run)`` mathematics, ``("w", word)`` word atoms. + + Both readers start here. It is one of the two things they share -- the other is the lexicon -- + and it is the counterpart of the shared token spec that the two formalizers of the geometry + topology share: sharing the atomiser buys agreement about *what the words are*, while the two + readers still disagree, productively, about what the sentence means. + """ + out: List[Tuple[str, str]] = [] + for kind, run in tokens(text): + if kind == "m": + out.append(("m", run)) + else: + for piece in word_pieces(run): + out.append(("w", piece)) + return out + + +def tokens(text: str) -> List[Tuple[str, str]]: + """Split a normalized sentence into ``("m", run)`` mathematics and ``("w", run)`` words. + + Letters of every script open a word run, digits and the symbols of the geometry language + open a mathematics run. An ASCII letter run is returned as a word: :mod:`lggeostratum.read_a` + and :mod:`lggeostratum.read_b` decide between a name and a function word through the lexicon. + """ + text = normalize(text) + out: List[Tuple[str, str]] = [] + index = 0 + while index < len(text): + ch = text[index] + if ch.isspace(): + index += 1 + continue + if _word_char(ch): + start = index + while index < len(text) and _word_char(text[index]): + index += 1 + out.append(("w", text[start:index])) + continue + if _is_math_char(ch, text, index): + start = index + while index < len(text) and _is_math_char(text[index], text, index): + index += 1 + run = text[start:index].strip() + if run: + out.append(("m", run)) + continue + index += 1 + return out + + +def numeric_literals(text: str) -> List[str]: + """Every numeric literal of a sentence, in the order it appears, digits normalised.""" + found: List[str] = [] + for _kind, run in tokens(text): + for match in re.finditer(r"\d+(?:\.\d+)?", run): + found.append(match.group(0)) + return found + + +def fold(word: str) -> str: + """Casefold a Latin word and drop its accents, so that one lexicon entry covers both cases. + + Non Latin scripts are returned unchanged: casefolding and accent folding do not apply to + Chinese, Devanagari or Arabic, and the lexicon entries are written in the form the keyboard + produces. + """ + if not any("a" <= ch.lower() <= "z" for ch in word): + return word + decomposed = unicodedata.normalize("NFD", word) + stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch)) + return stripped.lower() diff --git a/nodes/adversary/grammar.gf b/nodes/adversary/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..47a77ec3e221688b4fc6cf44b6691459f0b718ad --- /dev/null +++ b/nodes/adversary/grammar.gf @@ -0,0 +1,76 @@ +-- Node adversary (adversary): Adversary: states the ceiling the reading layer can honestly claim and writes the inequality a raised assurance would break. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/adversary/ontology.smt2 b/nodes/adversary/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..44674bbf06f5305463d290aa041d3cc93f34fbb4 --- /dev/null +++ b/nodes/adversary/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node adversary. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/adversary/seed_payload.json b/nodes/adversary/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..5867897d496a71bbd0524ee3aa8363ab7e0666ca --- /dev/null +++ b/nodes/adversary/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "adversary", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/arbiter/grammar.gf b/nodes/arbiter/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..765bb0fc8e66e91e1dcf1606f781dae9afd535c2 --- /dev/null +++ b/nodes/arbiter/grammar.gf @@ -0,0 +1,76 @@ +-- Node arbiter (arbiter): Interface with the user: holds the question and its language, applies the decision rule, and answers in the language of the question. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/arbiter/ontology.smt2 b/nodes/arbiter/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..993e2989f61027ec45c3b3e9c04fe173dc4ed9b9 --- /dev/null +++ b/nodes/arbiter/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node arbiter. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/arbiter/seed_payload.json b/nodes/arbiter/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..9086d63264db6a63722a3de96aaad62cdc3cf02c --- /dev/null +++ b/nodes/arbiter/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "arbiter", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "question (it): dato il punto A = (0, 0), il punto B = (2, 0) e il punto C = (1, 1), dimostra che A, B e C sono collineari\n@@DOSSIER@@{\"lang\":\"it\",\"question\":\"dato il punto A = (0, 0), il punto B = (2, 0) e il punto C = (1, 1), dimostra che A, B e C sono collineari\"}", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/boundary/grammar.gf b/nodes/boundary/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..8931b9240fca1b96bfa85783c4f2a78940a475e4 --- /dev/null +++ b/nodes/boundary/grammar.gf @@ -0,0 +1,76 @@ +-- Node boundary (boundary): Boundary: checks that the sentence the geometry topology says it solved is the sentence that was sent to it. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/boundary/ontology.smt2 b/nodes/boundary/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..eaf41cd1d28af276c7d7f970e16a8ed1e7d86955 --- /dev/null +++ b/nodes/boundary/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node boundary. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/boundary/seed_payload.json b/nodes/boundary/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..cab5fd2bf76df39fcf0a95f344654cf4849651b9 --- /dev/null +++ b/nodes/boundary/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "boundary", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/coverage/grammar.gf b/nodes/coverage/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..28b55f4e026f782ff2511a6d658568a5594eced1 --- /dev/null +++ b/nodes/coverage/grammar.gf @@ -0,0 +1,76 @@ +-- Node coverage (coverage): Coverage: checks that the reading keeps every number and every name written in the question and that the question is inside the coverage of its language. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/coverage/ontology.smt2 b/nodes/coverage/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..6de7aecd9c8d6bfeb274ca829a3e33d3728e3b9e --- /dev/null +++ b/nodes/coverage/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node coverage. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/coverage/seed_payload.json b/nodes/coverage/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..f64c5d5597bca01474affd416e07b05d3cc2f063 --- /dev/null +++ b/nodes/coverage/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "coverage", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/equivalence/grammar.gf b/nodes/equivalence/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..b710a06693911c1e049c3181e9a1d5c89bb6b5c1 --- /dev/null +++ b/nodes/equivalence/grammar.gf @@ -0,0 +1,76 @@ +-- Node equivalence (equivalence): Equivalence: compares the two readings and says whether they state the same figure and the same claim, with an SMT view when the text view is not enough. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/equivalence/ontology.smt2 b/nodes/equivalence/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..6aaa08a85d09a87576ad02b28ac3db5900883838 --- /dev/null +++ b/nodes/equivalence/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node equivalence. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/equivalence/seed_payload.json b/nodes/equivalence/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..744f57fcbed30dc26046f8a90d5a002c3873e112 --- /dev/null +++ b/nodes/equivalence/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "equivalence", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/invoker/grammar.gf b/nodes/invoker/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..9ecfa4520cdb5b784075850833151e8eccc1f8e5 --- /dev/null +++ b/nodes/invoker/grammar.gf @@ -0,0 +1,76 @@ +-- Node invoker (invoker): Invoker: hands the agreed sentence to the geometry topology as a separate process and carries that verdict back untouched. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/invoker/ontology.smt2 b/nodes/invoker/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..4b7f5a0bb8f1de5c96b6e9ab37fa415368fdb6dd --- /dev/null +++ b/nodes/invoker/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node invoker. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/invoker/seed_payload.json b/nodes/invoker/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..41b18cc8bf75d0fd3197bfbb171423adceda7dc0 --- /dev/null +++ b/nodes/invoker/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "invoker", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/reader_a/grammar.gf b/nodes/reader_a/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..2e274e9161eceb12649622e0f9c78555acf7aec2 --- /dev/null +++ b/nodes/reader_a/grammar.gf @@ -0,0 +1,76 @@ +-- Node reader_a (reader_a): First reader: turns a question written in one of the six user languages into a sentence of GeoLang, without seeing the other reader. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/reader_a/ontology.smt2 b/nodes/reader_a/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..b342c9adfe3c70bd25c4efb3cbfd327ee05eac9c --- /dev/null +++ b/nodes/reader_a/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node reader_a. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/reader_a/seed_payload.json b/nodes/reader_a/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..0d2aa4edb1bad0ece84b5270a6501faa6ed5d6d0 --- /dev/null +++ b/nodes/reader_a/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "reader_a", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/nodes/reader_b/grammar.gf b/nodes/reader_b/grammar.gf new file mode 100644 index 0000000000000000000000000000000000000000..f8d35b4534fa1b02962936affac90eaf56f04f25 --- /dev/null +++ b/nodes/reader_b/grammar.gf @@ -0,0 +1,76 @@ +-- Node reader_b (reader_b): Second reader: an independent reading of the same question, its own search over the same lexicon and the same templates. +-- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology. +-- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/canonical.py, the words lexicon/{lang}.json. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree string literals are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"), +-- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written +-- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word. +abstract GeoLang = { + cat + Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ; + fun + Point : Name -> Num -> Num -> Decl ; + Line : Ent -> Name -> Name -> Decl ; + CircleCentre : Ent -> Name -> Num -> Decl ; + CircleThree : Ent -> Names -> Decl ; + Midpoint : Name -> Name -> Name -> Decl ; + Centroid : Name -> Names -> Decl ; + Circumcentre : Name -> Names -> Decl ; + Intersection : Name -> Ref -> Ref -> Decl ; + NotCollinear : Names -> Decl ; + Distinct : Names -> Decl ; + FindCircumcircle : Names -> Problem ; + FindIntersection : Ref -> Ref -> Problem ; + FindTangents : Name -> Ent -> Problem ; + FindImage : Name -> Ent -> Problem ; + Prove : Goal -> Problem ; + Collinear : Names -> Goal ; + Perpendicular : Ref -> Ref -> Goal ; + Parallel : Ref -> Ref -> Goal ; + Congruent : Ref -> Ref -> Goal ; + RightAngle : Ref -> Goal ; + Between : Name -> Name -> Name -> Goal ; + OnCircle : Name -> Name -> Ref -> Goal ; + PName : String -> Name ; + EName : String -> Ent ; + Number : String -> Num ; + LineOf : Name -> Name -> Ref ; + SegmentOf : Name -> Name -> Ref ; + AngleOf : Name -> Name -> Name -> Ref ; + CircleNamed : Ent -> Ref ; +} + +concrete GeoLangEng of GeoLang = { + lincat + Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ; + lin + Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ; + Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ; + CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ; + CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ; + Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ; + Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ; + Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ; + Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ; + NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ; + Distinct xs = "Assume " ++ xs ++ " are distinct" ; + FindCircumcircle xs = "Find the circumcircle of " ++ xs ; + FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ; + FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ; + FindImage p e = "Find the image of " ++ p ++ " under " ++ e ; + Prove g = "Prove that " ++ g ; + Collinear xs = xs ++ " are collinear" ; + Perpendicular l k = l ++ " is perpendicular to " ++ k ; + Parallel l k = l ++ " is parallel to " ++ k ; + Congruent l k = l ++ " is congruent to " ++ k ; + RightAngle a = "angle " ++ a ++ " is a right angle" ; + Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ; + OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ; + PName s = s.s ; + EName s = s.s ; + Number s = s.s ; + LineOf a b = "line " ++ a ++ "-" ++ b ; + SegmentOf a b = "segment " ++ a ++ "-" ++ b ; + AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ; + CircleNamed e = "circle " ++ e ; +} diff --git a/nodes/reader_b/ontology.smt2 b/nodes/reader_b/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..e3c99cc6f7a5b610612873fd06386aec3495be2d --- /dev/null +++ b/nodes/reader_b/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the geometry-stratum topology node reader_b. +; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared +; radii and squared distances, which the theory of real arithmetic built into Z3 decides in +; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers +; constructed objects, and without a timeout one nonlinear configuration could block the session. +(set-option :timeout 8000) diff --git a/nodes/reader_b/seed_payload.json b/nodes/reader_b/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..f1cd10c677aedbc06495710fb55817e823321ff5 --- /dev/null +++ b/nodes/reader_b/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "reader_b", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "Idle until the question arrives.", + "abstractSyntaxTree": "Idle", + "smtConstraints": { + "declarations": [], + "assertions": [ + "(assert true)" + ], + "z3Status": "sat" + } + } +} diff --git a/problems/corpus.jsonl b/problems/corpus.jsonl new file mode 100644 index 0000000000000000000000000000000000000000..e8e81a5bdcc393e260c35851f65b0b54ceb9e0d9 --- /dev/null +++ b/problems/corpus.jsonl @@ -0,0 +1,56 @@ +{"id": "collinear-en-true", "lang": "en", "kind": "collinear", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Prove that A, B and C are collinear.", "why": "Three points on the x axis: the claim is true and both readers build the same sentence.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}} +{"id": "collinear-en-false", "lang": "en", "kind": "collinear", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Prove that A, B and C are collinear.", "why": "The third point leaves the line, so the bundle must answer with a counterexample.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim does not hold: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Prove that A, B and C are collinear."}} +{"id": "perp-en-true", "lang": "en", "kind": "perp", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Let D be the point with coordinates (1, 2). Prove that line A-B is perpendicular to line C-D.", "why": "A vertical line against a horizontal one, written with the line reference of the formal language.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}} +{"id": "tangent-en", "lang": "en", "kind": "find_tangents", "question": "Let O be the point with coordinates (0, 0). Draw the circle c with center O and radius squared 4. Let P be the point with coordinates (4, 0). Find the tangents from P to circle c.", "why": "A point outside a circle: the bundle answers the computation, not a proof.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}} +{"id": "mid-en", "lang": "en", "kind": "perp", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (4, 0). Let M be the midpoint of A and B. Let C be the point with coordinates (2, 2). Prove that line A-B is perpendicular to line M-C.", "why": "The midpoint is defined, then used in a claim about two perpendicular lines.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line M-C", "sentence": "Point A = (0, 0). Point B = (4, 0). Let M be the midpoint of A and B. Point C = (2, 2). Prove that line A-B is perpendicular to line M-C."}} +{"id": "collinear-it-true", "lang": "it", "kind": "collinear", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 0). Dimostra che i punti A, B e C sono collineari.", "why": "Italian with the copula of the definition spelled out and the claim carried by the joint.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}} +{"id": "collinear-it-false", "lang": "it", "kind": "collinear", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 1). Dimostra che i punti A, B e C sono allineati.", "why": "The same Italian sentence with a point off the line.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim does not hold: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Prove that A, B and C are collinear."}} +{"id": "perp-it-true", "lang": "it", "kind": "perp", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 0). Sia D il punto di coordinate (1, 2). Dimostra che la retta A-B è perpendicolare alla retta C-D.", "why": "Italian contracted preposition, perpendicolare alla retta, on both sides of the relation.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}} +{"id": "circumcircle-it", "lang": "it", "kind": "find_circumcircle", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 1). Trova la circonferenza circoscritta al triangolo A, B e C.", "why": "A find problem in Italian: the request has no marker, so the frame is empty.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"center\":[\"1\",\"0\"]", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Find the circumcircle of A, B and C."}} +{"id": "tangent-it", "lang": "it", "kind": "find_tangents", "question": "Sia O il punto di coordinate (0, 0). Disegna la circonferenza c con centro O e raggio al quadrato 4. Sia P il punto di coordinate (4, 0). Trova le tangenti da P alla circonferenza c.", "why": "A tangent request in Italian: the circle is named with its article and the point of departure with its preposition.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}} +{"id": "bisector-it-unknown", "lang": "it", "kind": "negative", "question": "Traccia la bisettrice dell angolo B in A e C.", "why": "A bisector is not in the lexicon of any variety: the layer must refuse and show no answer.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}} +{"id": "passthrough-it", "lang": "it", "kind": "collinear", "question": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear.", "why": "The question is already the formal language, so it is handed over unread.", "expect": {"state": "PASSTHROUGH", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}} +{"id": "cong-es-true", "lang": "es", "kind": "cong", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (4, 0). Demuestre que el segmento A-B es congruente con el segmento B-C.", "why": "Spanish congruence of two segments on one line.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: segment A-B is congruent to segment B-C", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C."}} +{"id": "collinear-es-false", "lang": "es", "kind": "collinear", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (1, 1). Demuestre que los puntos A, B y C son colineales.", "why": "Spanish with a point off the line, so the answer is a counterexample.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim does not hold: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Prove that A, B and C are collinear."}} +{"id": "mid-es-true", "lang": "es", "kind": "collinear", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea M el punto medio de A y B. Sea C el punto con coordenadas (1, 0). Demuestre que los puntos A, M y C son colineales.", "why": "Spanish midpoint, then a collinearity claim that uses the defined point.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, M and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Point C = (1, 0). Prove that A, M and C are collinear."}} +{"id": "circumcircle-es", "lang": "es", "kind": "find_circumcircle", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (1, 1). Halle la circunferencia circunscrita al triangulo A, B y C.", "why": "A Spanish find problem with the circumscribed circle named in the variety.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"center\":[\"1\",\"0\"]", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Find the circumcircle of A, B and C."}} +{"id": "collinear-zh-true", "lang": "zh", "kind": "collinear", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。证明 A, B 和 C 共线。", "why": "Chinese written with spaces between the atoms of the figure.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}} +{"id": "perp-zh-true", "lang": "zh", "kind": "perp", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。设 D 的坐标为 (1, 2)。证明 直线 A-B 垂直于 直线 C-D。", "why": "Chinese perpendicularity with the line reference of the formal language.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}} +{"id": "circumcircle-zh", "lang": "zh", "kind": "find_circumcircle", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 1)。求 三角形 A, B 和 C 的 外接圆。", "why": "A Chinese find problem whose request is a two character sequence recognised as one atom.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"center\":[\"1\",\"0\"]", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Find the circumcircle of A, B and C."}} +{"id": "mid-zh-single", "lang": "zh", "kind": "collinear", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 M 平分 线段 A B。证明 A, M 和 B 共线。", "why": "The Chinese form glues the two endpoints into one region, so only one reader builds a sentence.", "expect": {"state": "SINGLE", "referee_clean": true, "min_assurance": 1, "max_assurance": 1, "answer_contains": "the claim holds: A, M and B are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Prove that A, M and B are collinear."}} +{"id": "collinear-hi-true", "lang": "hi", "kind": "collinear", "question": "मान लें बिंदु A के निर्देशांक (0, 0) हैं। मान लें बिंदु B के निर्देशांक (2, 0) हैं। मान लें बिंदु C के निर्देशांक (1, 0) हैं। सिद्ध कीजिए कि A, B और C संरेख हैं।", "why": "Hindi with the coordinate marker before the value and the claim carried by the joint.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}} +{"id": "perp-hi-true", "lang": "hi", "kind": "perp", "question": "मान लें बिंदु A के निर्देशांक (0, 0) हैं। मान लें बिंदु B के निर्देशांक (2, 0) हैं। मान लें बिंदु C के निर्देशांक (1, 0) हैं। मान लें बिंदु D के निर्देशांक (1, 2) हैं। सिद्ध कीजिए कि रेखा A-B लंब है रेखा C-D पर।", "why": "Hindi puts the verb of the relation before the second line, which the frame of the kind accepts.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}} +{"id": "mid-hi-single", "lang": "hi", "kind": "collinear", "question": "मान लें बिंदु A के निर्देशांक (0, 0) हैं। मान लें बिंदु B के निर्देशांक (2, 0) हैं। मान लें M, A और B का मध्यबिंदु है। सिद्ध कीजिए कि A, M और B संरेख हैं।", "why": "Hindi closes the sentence with the midpoint marker, after the two endpoints, so the frame of the kind is not met.", "expect": {"state": "SINGLE", "referee_clean": true, "min_assurance": 1, "max_assurance": 1, "answer_contains": "the claim holds: A, M and B are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Prove that A, M and B are collinear."}} +{"id": "tangent-hi", "lang": "hi", "kind": "find_tangents", "question": "मान लें बिंदु O के निर्देशांक (0, 0) हैं। बनाइए वृत्त c का केंद्र O त्रिज्या का वर्ग 4 है। मान लें बिंदु P के निर्देशांक (4, 0) हैं। ज्ञात कीजिए P से वृत्त c की स्पर्शरेखाएँ।", "why": "A Hindi find problem with the circle of the figure named in the variety.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}} +{"id": "collinear-ar-true", "lang": "ar", "kind": "collinear", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). لتكن النقطة C إحداثياتها (1, 0). أثبت أن A و B و C على استقامة واحدة.", "why": "Arabic with the conjunction written as its own atom between the names.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}} +{"id": "perp-ar-true", "lang": "ar", "kind": "perp", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). لتكن النقطة C إحداثياتها (1, 0). لتكن النقطة D إحداثياتها (1, 2). أثبت أن المستقيم A-B عمودي على المستقيم C-D.", "why": "Arabic perpendicularity with the article attached to the word for line.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}} +{"id": "tangent-ar", "lang": "ar", "kind": "find_tangents", "question": "لتكن النقطة O إحداثياتها (0, 0). ارسم الدائرة c مركزها O مربع نصف القطر 4. لتكن النقطة P إحداثياتها (4, 0). أوجد المماسات من P إلى الدائرة c.", "why": "An Arabic find problem: the circle is named with its article and the point of departure with its preposition.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}} +{"id": "mid-ar-true", "lang": "ar", "kind": "collinear", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). خذ M منتصف A و B. أثبت أن A و M و B على استقامة واحدة.", "why": "Arabic midpoint written with the imperative of the definition and the two endpoints in order.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, M and B are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Prove that A, M and B are collinear."}} +{"id": "point-en", "lang": "en", "kind": "define_point", "question": "Let A be the point with coordinates (0, 0). Let P be the point with coordinates (2, 3).", "why": "A definition with nothing to prove: both readers write the points, and the layer has no question to answer, so no assurance is shown.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point P = (2, 3)."}} +{"id": "line-en", "lang": "en", "kind": "define_line", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Draw the line r through the points A and B.", "why": "A line through two named points, with the article of the variety before the word for line; the figure is built and nothing is claimed.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Line r through A and B."}} +{"id": "circle-en", "lang": "en", "kind": "define_circle", "question": "Let O be the point with coordinates (0, 0). Draw the circle c with center O and radius squared 4.", "why": "A circle given by its centre and its squared radius, read by both readers.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4."}} +{"id": "assume-en", "lang": "en", "kind": "assume", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Suppose A, B and C are not collinear.", "why": "The question states a premise and asks nothing: the assumption is carried into the sentence and the layer stays silent.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Assume A, B and C are not collinear."}} +{"id": "centroid-en", "lang": "en", "kind": "centroid", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Let G be the centroid of the triangle A, B and C.", "why": "The centroid of a named triangle, with the article that the pattern of English asks for.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Let G be the centroid of triangle A, B and C."}} +{"id": "circumcentre-en", "lang": "en", "kind": "circumcentre", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Let G be the circumcenter of the triangle A, B and C.", "why": "The circumcenter of a named triangle, one joint of the frame per reader.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Let G be the circumcenter of triangle A, B and C."}} +{"id": "intersect-en", "lang": "en", "kind": "intersect", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Let D be the point with coordinates (1, 2). Let X be the intersection of the line A-B and the line C-D.", "why": "The intersection point of two lines given by their endpoints, defined but not asked about.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Let X be the intersection of line A-B and line C-D."}} +{"id": "right-en", "lang": "en", "kind": "right", "question": "Let A be the point with coordinates (2, 0). Let B be the point with coordinates (0, 0). Let C be the point with coordinates (0, 2). Prove that the angle A-B-C is a right angle.", "why": "A right angle named by its three letters, dashed the way the formal language writes an angle reference.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: angle A-B-C is a right angle", "sentence": "Point A = (2, 0). Point B = (0, 0). Point C = (0, 2). Prove that angle A-B-C is a right angle."}} +{"id": "between-en", "lang": "en", "kind": "between", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Prove that C lies between A and B.", "why": "Betweenness of three points on one line, the relation named after the point that lies in the middle.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: C lies between A and B", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that C lies between A and B."}} +{"id": "oncircle-en", "lang": "en", "kind": "oncircle", "question": "Let O be the point with coordinates (0, 0). Let A be the point with coordinates (2, 0). Let P be the point with coordinates (0, 2). Prove that P lies on the circle with center O through A.", "why": "A point on a circle described by its centre and by a point the circle passes through.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: P lies on the circle with center O through A", "sentence": "Point O = (0, 0). Point A = (2, 0). Point P = (0, 2). Prove that P lies on the circle with center O through A."}} +{"id": "par-en", "lang": "en", "kind": "par", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (0, 1). Let D be the point with coordinates (2, 1). Prove that line A-B is parallel to line C-D.", "why": "Two horizontal lines: parallelism written with the line reference of the formal language.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}} +{"id": "image-en", "lang": "en", "kind": "find_image", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Draw the line r through the points A and B. Let P be the point with coordinates (1, 1). Find the image of P under the transformation r.", "why": "The transformation is named with the word of the variety but never defined, so the layer cannot answer and the stratum shows no result even though both readers agree.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Line r through A and B. Point P = (1, 1). Find the image of P under r."}} +{"id": "findintersect-en", "lang": "en", "kind": "find_intersect", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Let D be the point with coordinates (1, 2). Draw the line r through the points A and B. Draw the line s through the points C and D. Find where the line r and the line s meet.", "why": "A find problem with no marker at all: a verb and two line references, and both readers build the same sentence.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"kind\":\"intersection\"", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Line r through A and B. Line s through C and D. Find the intersection of line r and line s."}} +{"id": "bisector-en", "lang": "en", "kind": "negative", "question": "Find the bisector of the angle A-B-C.", "why": "A bisector is outside the lexicon of every variety, so the stratum refuses and answers nothing.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}} +{"id": "par-it", "lang": "it", "kind": "par", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (0, 1). Sia D il punto di coordinate (2, 1). Dimostra che la retta A-B è parallela alla retta C-D.", "why": "Italian parallelism with the contracted preposition on both sides of the relation.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}} +{"id": "circle-it", "lang": "it", "kind": "define_circle", "question": "Sia O il punto di coordinate (0, 0). Disegna la circonferenza c con centro O e raggio al quadrato 4.", "why": "An Italian circle with centre and squared radius, the conjunction of the frame inside one chunk of the pattern.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4."}} +{"id": "findintersect-it", "lang": "it", "kind": "find_intersect", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 0). Sia D il punto di coordinate (1, 2). Disegna la retta r per i punti A e B. Disegna la retta s per i punti C e D. Trova il punto in comune tra la retta r e la retta s.", "why": "The same request in Italian, with the point in common named in the variety.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"kind\":\"intersection\"", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Line r through A and B. Line s through C and D. Find the intersection of line r and line s."}} +{"id": "centroid-it", "lang": "it", "kind": "centroid", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 1). Sia G il baricentro del triangolo A, B e C.", "why": "An Italian definition of the centroid of a triangle, with no claim attached.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Let G be the centroid of triangle A, B and C."}} +{"id": "oncircle-it", "lang": "it", "kind": "oncircle", "question": "Sia O il punto di coordinate (0, 0). Sia A il punto di coordinate (2, 0). Sia P il punto di coordinate (0, 2). Dimostra che P giace sulla circonferenza di centro O e passante per A.", "why": "Italian: the circle is named by its centre and by the point it passes through.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: P lies on the circle with center O through A", "sentence": "Point O = (0, 0). Point A = (2, 0). Point P = (0, 2). Prove that P lies on the circle with center O through A."}} +{"id": "findintersect-es", "lang": "es", "kind": "find_intersect", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (1, 0). Sea D el punto con coordenadas (1, 2). Trace la recta r por los puntos A y B. Trace la recta s por los puntos C y D. Halle el punto en comun de la recta r y la recta s.", "why": "Spanish meets it with one reader only: reader A follows the pattern, while reader B finds a marker where the kind expects none.", "expect": {"state": "SINGLE", "referee_clean": true, "min_assurance": 1, "max_assurance": 1, "answer_contains": "\"kind\":\"intersection\"", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Line r through A and B. Line s through C and D. Find the intersection of line r and line s."}} +{"id": "negative-es", "lang": "es", "kind": "negative", "question": "Halle el area del triangulo A, B y C.", "why": "The area of a figure is not a request of this language: the layer refuses it.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}} +{"id": "par-zh", "lang": "zh", "kind": "par", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (0, 1)。设 D 的坐标为 (2, 1)。证明 直线 A-B 平行于 直线 C-D。", "why": "", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}} +{"id": "negative-zh", "lang": "zh", "kind": "negative", "question": "求 A, B 和 C 的 内接矩形。", "why": "Chinese names a figure that no variety of this stratum has a word for.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}} +{"id": "right-hi", "lang": "hi", "kind": "right", "question": "मान लें बिंदु A के निर्देशांक (2, 0) हैं। मान लें बिंदु B के निर्देशांक (0, 0) हैं। मान लें बिंदु C के निर्देशांक (0, 2) हैं। सिद्ध कीजिए कि कोण A-B-C समकोण है", "why": "", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: angle A-B-C is a right angle", "sentence": "Point A = (2, 0). Point B = (0, 0). Point C = (0, 2). Prove that angle A-B-C is a right angle."}} +{"id": "negative-hi", "lang": "hi", "kind": "negative", "question": "ज्ञात कीजिए त्रिभुज A, B और C का क्षेत्रफल", "why": "Hindi asks for a quantity the geometry layer does not compute.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}} +{"id": "par-ar", "lang": "ar", "kind": "par", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). لتكن النقطة C إحداثياتها (0, 1). لتكن النقطة D إحداثياتها (2, 1). أثبت أن المستقيم A-B موازٍ للمستقيم C-D.", "why": "", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}} +{"id": "negative-ar", "lang": "ar", "kind": "negative", "question": "أوجد مساحة المثلث A و B و C", "why": "Arabic asks for an area, which lies outside the controlled language.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}} +{"id": "mid-en-def", "lang": "en", "kind": "mid", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (4, 0). Let M be the midpoint of A and B.", "why": "The midpoint of two points, defined on its own: the sentence is read and the layer has nothing to answer.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (4, 0). Let M be the midpoint of A and B."}} diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ab05168c193a28922a3a4c494ad50ef8775cc13c --- /dev/null +++ b/requirements.txt @@ -0,0 +1,2 @@ +z3-solver>=4.12 +pytest>=7 diff --git a/results/ablation.json b/results/ablation.json new file mode 100644 index 0000000000000000000000000000000000000000..95688773bb24437df582acbea68ea0880468de24 --- /dev/null +++ b/results/ablation.json @@ -0,0 +1,2650 @@ +{ + "cells": { + "S1 reader_a | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S1 reader_a | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S1 reader_a | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | equivalence:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | coverage:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | equivalence:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | boundary:tamper_math,adversary:rubber_stamp,arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | boundary:tamper_math,arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | equivalence:rubber_stamp,coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:merge_slots,arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:merge_slots,reader_b:merge_slots": { + "abstained": 0, + "activated": 1, + "caught": 0, + "details": [ + { + "config": "S8 full topology", + "fault": [ + "reader_a:merge_slots", + "reader_b:merge_slots" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "silent_error", + "problems": [ + "sentence 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment A-B.', expected 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C.'", + "answer 'the claim holds: segment A-B is congruent to segment A-B' does not contain 'the claim holds: segment A-B is congruent to segment B-C'" + ], + "shown": 2 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 1 + }, + "S8 full topology | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:rename_slot,reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:shift_number,equivalence:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:shift_number,reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 6, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | adversary:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | boundary:tamper_math": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | coverage:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | adversary:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | boundary:tamper_math": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | coverage:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | equivalence:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:merge_slots": { + "abstained": 1, + "activated": 1, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 6, + "details": [ + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 6, + "details": [ + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | equivalence:rubber_stamp": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | reader_b:merge_slots": { + "abstained": 0, + "activated": 1, + "caught": 1, + "details": [ + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:merge_slots" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment A-B.', expected 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C.'", + "answer 'the claim holds: segment A-B is congruent to segment A-B' does not contain 'the claim holds: segment A-B is congruent to segment B-C'", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | reader_b:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_a | reader_b:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | adversary:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 6, + "details": [ + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | arbiter:force_assurance": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | boundary:tamper_math": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | coverage:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 6, + "details": [ + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 6, + "caught": 6, + "details": [ + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:merge_slots": { + "abstained": 0, + "activated": 1, + "caught": 1, + "details": [ + { + "config": "S8 minus reader_b", + "fault": [ + "reader_a:merge_slots" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment A-B.', expected 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C.'", + "answer 'the claim holds: segment A-B is congruent to segment A-B' does not contain 'the claim holds: segment A-B is congruent to segment B-C'", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:rename_slot": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:shift_number": { + "abstained": 6, + "activated": 6, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + } + }, + "probe": [ + "collinear-ar-true", + "collinear-en-true", + "cong-es-true", + "collinear-hi-true", + "collinear-it-true", + "collinear-zh-true" + ], + "seconds": 238.8, + "totals": { + "abstained": 561, + "activated": 720, + "caught": 32, + "lowered": 0, + "masked": 126, + "raised": 0, + "runs": 882, + "silent_error": 1 + }, + "violations": [ + { + "config": "S8 full topology", + "fault": [ + "reader_a:merge_slots", + "reader_b:merge_slots" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "silent_error", + "problems": [ + "sentence 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment A-B.', expected 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C.'", + "answer 'the claim holds: segment A-B is congruent to segment A-B' does not contain 'the claim holds: segment A-B is congruent to segment B-C'" + ], + "shown": 2 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:merge_slots" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment A-B.', expected 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C.'", + "answer 'the claim holds: segment A-B is congruent to segment A-B' does not contain 'the claim holds: segment A-B is congruent to segment B-C'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "reader_a:merge_slots" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment A-B.', expected 'Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C.'", + "answer 'the claim holds: segment A-B is congruent to segment A-B' does not contain 'the claim holds: segment A-B is congruent to segment B-C'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "coverage:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-ar-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-en-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "cong-es-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-hi-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-it-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_b", + "fault": [ + "adversary:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "collinear-zh-true", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "assurance 1 below 2" + ], + "shown": 1 + } + ] +} diff --git a/results/coverage.json b/results/coverage.json new file mode 100644 index 0000000000000000000000000000000000000000..451473318561c123e3e970faf9ae4567a96e8ee6 --- /dev/null +++ b/results/coverage.json @@ -0,0 +1,1060 @@ +{ + "geometry_consulted": true, + "inventory": { + "ar": { + "connectives": 3, + "kinds": [ + "collinear", + "cong", + "define_circle", + "define_line", + "define_point", + "find_circumcircle", + "find_tangents", + "mid", + "par", + "perp", + "right" + ], + "markers": 30, + "noise_words": 31, + "pattern_words": 58, + "patterns": 13, + "verb_phrases": 10 + }, + "en": { + "connectives": 3, + "kinds": [ + "assume", + "between", + "centroid", + "circumcentre", + "collinear", + "cong", + "define_circle", + "define_line", + "define_point", + "find_circumcircle", + "find_image", + "find_intersect", + "find_tangents", + "intersect", + "mid", + "oncircle", + "par", + "perp", + "right" + ], + "markers": 43, + "noise_words": 53, + "pattern_words": 219, + "patterns": 33, + "verb_phrases": 14 + }, + "es": { + "connectives": 3, + "kinds": [ + "assume", + "between", + "centroid", + "circumcentre", + "collinear", + "cong", + "define_circle", + "define_line", + "define_point", + "find_circumcircle", + "find_image", + "find_intersect", + "find_tangents", + "intersect", + "mid", + "oncircle", + "par", + "perp", + "right" + ], + "markers": 43, + "noise_words": 64, + "pattern_words": 170, + "patterns": 27, + "verb_phrases": 16 + }, + "hi": { + "connectives": 3, + "kinds": [ + "collinear", + "cong", + "define_circle", + "define_line", + "define_point", + "find_circumcircle", + "find_tangents", + "mid", + "par", + "perp", + "right" + ], + "markers": 23, + "noise_words": 33, + "pattern_words": 122, + "patterns": 18, + "verb_phrases": 11 + }, + "it": { + "connectives": 4, + "kinds": [ + "assume", + "between", + "centroid", + "circumcentre", + "collinear", + "cong", + "define_circle", + "define_line", + "define_point", + "find_circumcircle", + "find_intersect", + "find_tangents", + "intersect", + "mid", + "oncircle", + "par", + "perp", + "right" + ], + "markers": 46, + "noise_words": 72, + "pattern_words": 228, + "patterns": 42, + "verb_phrases": 23 + }, + "zh": { + "connectives": 4, + "kinds": [ + "between", + "collinear", + "cong", + "define_circle", + "define_line", + "define_point", + "find_circumcircle", + "find_tangents", + "mid", + "oncircle", + "par", + "perp", + "right" + ], + "markers": 21, + "noise_words": 20, + "pattern_words": 128, + "patterns": 18, + "verb_phrases": 9 + } + }, + "items": 56, + "languages": { + "ar": { + "agreed": 5, + "items": 6, + "not covered": 1, + "reader_a_read": 5, + "reader_b_read": 5 + }, + "en": { + "agreed": 19, + "items": 20, + "not covered": 1, + "reader_a_read": 19, + "reader_b_read": 19 + }, + "es": { + "agreed": 4, + "items": 6, + "not covered": 1, + "reader_a_read": 5, + "reader_b_read": 4, + "single": 1 + }, + "hi": { + "agreed": 4, + "items": 6, + "not covered": 1, + "reader_a_read": 5, + "reader_b_read": 4, + "single": 1 + }, + "it": { + "agreed": 10, + "items": 12, + "not covered": 1, + "passthrough": 1, + "reader_a_read": 10, + "reader_b_read": 10 + }, + "zh": { + "agreed": 4, + "items": 6, + "not covered": 1, + "reader_a_read": 5, + "reader_b_read": 4, + "single": 1 + } + }, + "pairs": { + "ar/collinear": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "ar/find_tangents": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "ar/par": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/perp": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/assume": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/between": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/centroid": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/circumcentre": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/collinear": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "en/define_circle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/define_line": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/define_point": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/find_image": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/find_intersect": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/find_tangents": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/intersect": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/mid": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "en/oncircle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/par": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/perp": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "en/right": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/collinear": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "es/cong": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/find_circumcircle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/find_intersect": { + "items": 1, + "reader_a_read": 1, + "reader_b_read": 0, + "single": 1 + }, + "es/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "hi/collinear": { + "agreed": 1, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 1, + "single": 1 + }, + "hi/find_tangents": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "hi/perp": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/right": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/centroid": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/collinear": { + "agreed": 2, + "items": 3, + "passthrough": 1, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "it/define_circle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/find_circumcircle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/find_intersect": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/find_tangents": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "it/oncircle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/par": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/perp": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/collinear": { + "agreed": 1, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 1, + "single": 1 + }, + "zh/find_circumcircle": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "zh/par": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/perp": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + } + }, + "rows": [ + { + "assurance": 2, + "id": "collinear-en-true", + "kind": "collinear", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "collinear-en-false", + "kind": "collinear", + "lang": "en", + "math_status": "REFUTED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "perp-en-true", + "kind": "perp", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "tangent-en", + "kind": "find_tangents", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "mid-en", + "kind": "perp", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "collinear-it-true", + "kind": "collinear", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "collinear-it-false", + "kind": "collinear", + "lang": "it", + "math_status": "REFUTED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "perp-it-true", + "kind": "perp", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "circumcircle-it", + "kind": "find_circumcircle", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "tangent-it", + "kind": "find_tangents", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "bisector-it-unknown", + "kind": "negative", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 2, + "id": "passthrough-it", + "kind": "collinear", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 2, + "id": "cong-es-true", + "kind": "cong", + "lang": "es", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "collinear-es-false", + "kind": "collinear", + "lang": "es", + "math_status": "REFUTED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "mid-es-true", + "kind": "collinear", + "lang": "es", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "circumcircle-es", + "kind": "find_circumcircle", + "lang": "es", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "collinear-zh-true", + "kind": "collinear", + "lang": "zh", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "perp-zh-true", + "kind": "perp", + "lang": "zh", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "circumcircle-zh", + "kind": "find_circumcircle", + "lang": "zh", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 1, + "id": "mid-zh-single", + "kind": "collinear", + "lang": "zh", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "NOT COVERED", + "state": "SINGLE" + }, + { + "assurance": 2, + "id": "collinear-hi-true", + "kind": "collinear", + "lang": "hi", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "perp-hi-true", + "kind": "perp", + "lang": "hi", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 1, + "id": "mid-hi-single", + "kind": "collinear", + "lang": "hi", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "NOT COVERED", + "state": "SINGLE" + }, + { + "assurance": 2, + "id": "tangent-hi", + "kind": "find_tangents", + "lang": "hi", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "collinear-ar-true", + "kind": "collinear", + "lang": "ar", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "perp-ar-true", + "kind": "perp", + "lang": "ar", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "tangent-ar", + "kind": "find_tangents", + "lang": "ar", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "mid-ar-true", + "kind": "collinear", + "lang": "ar", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "point-en", + "kind": "define_point", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "line-en", + "kind": "define_line", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "circle-en", + "kind": "define_circle", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "assume-en", + "kind": "assume", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "centroid-en", + "kind": "centroid", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "circumcentre-en", + "kind": "circumcentre", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "intersect-en", + "kind": "intersect", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "right-en", + "kind": "right", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "between-en", + "kind": "between", + "lang": "en", + "math_status": "SINGLE_PROVER", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "oncircle-en", + "kind": "oncircle", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "par-en", + "kind": "par", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "image-en", + "kind": "find_image", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "findintersect-en", + "kind": "find_intersect", + "lang": "en", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "bisector-en", + "kind": "negative", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 2, + "id": "par-it", + "kind": "par", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "circle-it", + "kind": "define_circle", + "lang": "it", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "findintersect-it", + "kind": "find_intersect", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "centroid-it", + "kind": "centroid", + "lang": "it", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "oncircle-it", + "kind": "oncircle", + "lang": "it", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 1, + "id": "findintersect-es", + "kind": "find_intersect", + "lang": "es", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "NOT COVERED", + "state": "SINGLE" + }, + { + "assurance": 0, + "id": "negative-es", + "kind": "negative", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 2, + "id": "par-zh", + "kind": "par", + "lang": "zh", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "negative-zh", + "kind": "negative", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 2, + "id": "right-hi", + "kind": "right", + "lang": "hi", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "negative-hi", + "kind": "negative", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 2, + "id": "par-ar", + "kind": "par", + "lang": "ar", + "math_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "negative-ar", + "kind": "negative", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "mid-en-def", + "kind": "mid", + "lang": "en", + "math_status": "INCONCLUSIVE", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + } + ] +} diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..86353070bafb86f0b0ef495822a92978a01b0d1b --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,15 @@ +"""Make the stratum package importable when pytest is started from the repository root.""" + +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +if str(ROOT) not in sys.path: + sys.path.insert(0, str(ROOT)) +# Inside the repository this bundle is several levels below the orchestrator package, so look for an +# ancestor that carries src/lingologos_orchestrator instead of assuming the bundle sits at the root. +for _parent in ROOT.parents: + _candidate = _parent / "src" + if (_candidate / "lingologos_orchestrator").is_dir() and str(_candidate) not in sys.path: + sys.path.insert(0, str(_candidate)) + break diff --git a/tests/test_corpus.py b/tests/test_corpus.py new file mode 100644 index 0000000000000000000000000000000000000000..a2904d74081110463f37635da958c49985568933 --- /dev/null +++ b/tests/test_corpus.py @@ -0,0 +1,64 @@ +"""The gold answers of this bundle. + +The corpus is the only place where a mistake common to both readers can show up: the two readers +share the lexicon, the atomizer and the templates, so a wrong description of a variety is invisible +to the topology and visible only here, in a sentence a person wrote and checked. +""" + +import pytest + +from lggeostratum import canonical, corpus, lexicon + +ITEMS = corpus.load() +IDS = [str(item["id"]) for item in ITEMS] +BY_ID = {str(item["id"]): item for item in ITEMS} + + +def test_every_item_has_its_own_identifier_and_a_question(): + assert IDS and len(set(IDS)) == len(IDS) + for item in ITEMS: + assert str(item.get("question", "")).strip(), item.get("id") + assert str(item.get("lang", "")) in lexicon.codes(), item.get("id") + assert str(item.get("kind", "")), item.get("id") + + +def test_every_covered_language_is_asked_and_answered(): + asked = {str(item["lang"]) for item in ITEMS} + assert asked == set(lexicon.codes()), (asked, lexicon.codes()) + + +def test_every_kind_the_geometry_layer_understands_is_asked_in_some_language(): + asked = {str(item["kind"]) for item in ITEMS if item.get("expect", {}).get("sentence")} + assert set(canonical.KINDS) <= asked, sorted(set(canonical.KINDS) - asked) + + +def test_every_language_is_also_asked_about_something_it_does_not_cover(): + # A stratum that always answers is a stratum that always guesses: the negative items are what + # keep the abstentions real, in every variety at once. + for lang in lexicon.codes(): + negatives = [item for item in ITEMS if str(item["lang"]) == lang and str(item.get("kind")) == "negative"] + assert negatives, lang + + +def test_the_corpus_keeps_a_record_of_what_it_knows_it_cannot_do(): + # Two kinds of limitation are written into the gold data on purpose: the varieties where only one + # reader gets the joint (SINGLE, one level of assurance), and the questions whose mathematics is + # out of reach of the geometry layer, where the reading is agreed and the answer still does not come. + single = [item for item in ITEMS if (item.get("expect") or {}).get("state") == "SINGLE"] + silent = [item for item in ITEMS if (item.get("expect") or {}).get("state") in ("AGREED", "PASSTHROUGH") + and (item.get("expect") or {}).get("no_answer") is True] + assert single, "no item records the limit of one reader only" + assert silent, "no item records a question the geometry layer cannot answer" + + +@pytest.mark.parametrize("item_id", IDS) +def test_the_gold_answer_of_this_item_is_met(item_id): + outcome = corpus.outcome(BY_ID[item_id]) + assert outcome["ok"] is True, (item_id, outcome["state"], outcome["assurance"], outcome["problems"]) + + +def test_no_item_ever_reaches_the_level_of_the_geometry_layer(): + for item in ITEMS: + expect = item.get("expect") or {} + assert int(expect.get("max_assurance", 0) or 0) < 3, item["id"] + assert int(expect.get("min_assurance", 0) or 0) < 3, item["id"] diff --git a/tests/test_decide.py b/tests/test_decide.py new file mode 100644 index 0000000000000000000000000000000000000000..8e0fa2f1fb9904dc2bb01317997a33042cd3d35a --- /dev/null +++ b/tests/test_decide.py @@ -0,0 +1,153 @@ +"""The decision rule, and the ceiling that the stratum is not allowed to cross.""" + +import copy + +from lggeostratum import decide, pipeline + + +def _reading(sentence, kind="collinear", slots=None, notes=()): + return {"status": "READ", "kind": kind, "math": sentence, "slots": slots or {}, "notes": list(notes)} + + +def _math(status="VERIFIED", assurance=3, answer="the claim holds: A, B and C are collinear", sentence="Prove that A, B and C are collinear", **extra): + verdict = {"status": status, "assurance": assurance, "answer_text": answer, "problem_math": sentence} + verdict.update(extra) + return verdict + + +def _dossier(readings, comparison, coverage, math_verdict, direct=None, echo_ok=True): + dossier = {"question": "dimostra che A, B e C sono collineari", "lang": "it", "sent": "Prove that A, B and C are collinear", + "reading_a": readings[0] if len(readings) > 0 else {}, + "reading_b": readings[1] if len(readings) > 1 else {}, + "compare": comparison, "coverage": coverage, "math": math_verdict, + "echo_ok": echo_ok} + if direct is not None: + dossier["reading_direct"] = direct + return dossier + + +def test_no_state_carries_the_top_level_of_the_geometry_layer(): + # Three belongs to the geometry layer: it is what its own two formalizers and two checkers give a + # proved sentence. A question written in a human language adds one fallible step before that, so + # every state of this stratum is capped below three. + assert set(decide.STATES) == set(decide.CEILING) + assert max(decide.CEILING.values()) == 2 + for state in decide.STATES: + assert decide.CEILING[state] < 3, state + + +def test_two_agreeing_readers_take_the_minimum_with_the_layer_answer(): + readings = [_reading("Prove that A, B and C are collinear"), _reading("Prove that A, B and C are collinear")] + for status, assurance, expected in (("VERIFIED", 3, 2), ("SINGLE_PROVER", 2, 2), ("UNKNOWN", 0, 0)): + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, + _math(status, assurance, "" if status == "UNKNOWN" else "the claim holds: A, B and C are collinear"))) + assert final["state"] == "AGREED" + assert final["ceiling"] == 2 + assert final["assurance"] == min(2, assurance), (status, final) + assert final["math_assurance"] == assurance + + +def test_a_missing_witness_caps_the_session_at_one(): + readings = [_reading("Prove that A, B and C are collinear"), {}] + final = decide.decide(_dossier(readings, None, None, _math())) + assert final["state"] == "SINGLE" + assert final["assurance"] == 1 + # The cap is not the only thing that holds with one reader: the count of literals still does, so a + # witness that stands alone does not thereby get to answer another problem. + kept = decide.decide(_dossier(readings, None, {"ok": True}, _math())) + assert kept["state"] == "SINGLE" + assert kept["assurance"] == 1 + + +def test_a_lone_reading_that_lost_a_number_answers_a_different_problem(): + # What the ablation of the topology found: with the second reader switched out, a number shifted by + # the first one used to reach the person as a single witness answer. The ceiling said one, but the + # answer was of another problem, so the count of the literals refuses it instead. + readings = [_reading("Point A = (0, 3). Prove that A, B and C are collinear"), {}] + final = decide.decide(_dossier(readings, None, {"ok": False}, _math(sentence="Point A = (0, 3). Prove that A, B and C are collinear"))) + assert final["state"] == "DISPUTED" + assert final["assurance"] == 0 + assert final["answer"] == "" + assert "literal_count" in final["reasons"] + + +def test_a_question_that_announces_two_kinds_of_problem_is_left_to_the_user(): + readings = [{"status": "AMBIGUOUS", "kind": None, "math": "", "slots": {}, + "notes": [{"reason": "two_verbs"}]}, {}] + final = decide.decide(_dossier(readings, None, None, None)) + assert final["state"] == "AMBIGUOUS" + assert final["ceiling"] == 0 + assert final["assurance"] == 0 + assert "two_verbs" in final["reasons"] + + +def test_a_question_this_language_does_not_write_is_not_covered(): + final = decide.decide(_dossier([{}, {}], None, None, None)) + assert final["state"] == "NOT COVERED" + assert final["assurance"] == 0 + assert final["consulted_math"] is False + assert final["answer"] == "" + + +def test_a_disagreement_is_never_resolved_by_the_geometry_layer(): + readings = [_reading("Prove that A, B and C are collinear"), _reading("Point A = (0, 3). Prove that A, B and C are collinear")] + final = decide.decide(_dossier(readings, {"same": False, "why": "text"}, {"ok": True}, _math())) + assert final["state"] == "DISPUTED" + assert final["assurance"] == 0 + assert final["answer"] == "" + assert "disagree" in final["reasons"] + + +def test_a_reading_that_lost_a_number_is_disputed_even_when_the_readers_agree(): + readings = [_reading("Prove that A, B and C are collinear"), _reading("Prove that A, B and C are collinear")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": False}, _math())) + assert final["state"] == "DISPUTED" + assert "literal_count" in final["reasons"] + assert final["assurance"] == 0 + + +def test_an_echo_that_names_another_sentence_is_reported_as_tampering(): + readings = [_reading("Prove that A, B and C are collinear"), _reading("Prove that A, B and C are collinear")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, _math(), echo_ok=False)) + assert final["state"] == "TAMPERED" + assert final["assurance"] == 0 + assert "boundary" in final["reasons"] + + +def test_a_sentence_already_written_in_the_geometry_language_passes_through(): + direct = {"kind": "collinear", "math": "Prove that A, B and C are collinear", "slots": {"X": "A, B and C"}} + final = decide.decide(_dossier([{}, {}], None, {"ok": True}, _math(), direct=direct)) + assert final["state"] == "PASSTHROUGH" + assert final["ceiling"] == 2 + assert final["assurance"] == 2 + + +def test_no_answer_is_shown_when_the_geometry_layer_did_not_answer(): + readings = [_reading("Prove that A, B and C are collinear"), _reading("Prove that A, B and C are collinear")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, _math("UNKNOWN", 0, ""))) + assert final["assurance"] == 0 + assert final["answer"] == "" + assert "geometry_unknown" in final["reasons"] + + +def test_the_decision_is_pure_and_leaves_the_evidence_as_it_found_it(): + dossier = _dossier([_reading("Prove that A, B and C are collinear"), _reading("Prove that A, B and C are collinear")], {"same": True}, + {"ok": True}, _math()) + before = copy.deepcopy(dossier) + first = decide.decide(dossier) + second = decide.decide(dossier) + assert first == second + assert dossier == before + + +def test_a_claimed_assurance_is_marked_and_the_tools_lower_it_again(): + honest = decide.decide(_dossier([_reading("Prove that A, B and C are collinear"), _reading("Prove that A, B and C are collinear")], + {"same": True}, {"ok": True}, _math())) + forced = decide.raise_assurance(honest, 3) + assert forced["assurance"] == 3 + assert forced["claimed_above_evidence"] is True + # The tools do not show what the arbiter wrote: they re-run the decision on the transcript, and + # what stands is the more cautious of the two. + checked = pipeline.referee_adjusted(forced, [{"sender": "arbiter", "claimed": "unsat", "referee": "sat"}]) + assert checked["assurance"] <= min(2, honest["assurance"]) + assert "arbiter" in (checked.get("detected") or []) diff --git a/tests/test_faults.py b/tests/test_faults.py new file mode 100644 index 0000000000000000000000000000000000000000..de12d7556150349c1ba0f48b2481c28d35b0b1aa --- /dev/null +++ b/tests/test_faults.py @@ -0,0 +1,112 @@ +"""The faults this bundle can switch on, and what each of them is required to leave behind. + +The catalogue is the counterpart of the one the geometry layer runs: here the misbehaviour is in the +reading and in the reporting, never in the formal layer. A fault is worth having only if the stratum +reports it, so every experiment below ends by asking the same question -- did the assurance fall, and +did the reason name the node that fell short? +""" + +import pytest + +from lggeostratum import agents, canonical, corpus, faults, pipeline + +ITEMS = {item["id"]: item for item in corpus.load()} +ONE = "perp-it-true" +# The readings the faults of a reader are tried on: a line drawn through two named points, and a +# point given by its coordinates. One carries the names a reader can write twice or exchange for +# another, the other the number a reader can shift. +FIXTURES = [ + ("define_line", {"E": "r", "P": "A", "Q": "B"}), + ("define_point", {"P": "A", "V": "(0, 0)"}), +] + + +def _ask(item_id, fault_spec=(), active=agents.ORDER): + item = ITEMS[item_id] + return pipeline.ask(str(item["question"]), str(item["lang"]), active=active, fault_spec=fault_spec) + + +def test_the_catalogue_names_nodes_of_this_topology_only(): + assert set(faults.CATALOG) <= set(agents.ORDER) + # The invoker is not in the catalogue: it reads nothing and proves nothing, it only asks the geometry + # layer a question, so there is no shortcut it could take. + assert "invoker" not in faults.CATALOG + faults.configure(()) + for node, kinds in faults.CATALOG.items(): + assert kinds, node + assert len(set(kinds)) == len(kinds), node + for kind in kinds: + assert not faults.has(node, kind), (node, kind) + + +def test_a_fault_configured_is_a_fault_fired_once(): + faults.configure(["reader_a:merge_slots", "reader_a:merge_slots", "coverage:rubber_stamp"]) + assert faults.has("reader_a", "merge_slots") + faults.fire("reader_a", "merge_slots") + faults.fire("reader_a", "merge_slots") + assert faults.fired("reader_a") == ["reader_a:merge_slots"] + # Configured is not the same as fired: only a fault that really changed something is recorded, so + # the ablation can tell an activated fault from a dormant one. + assert faults.has("coverage", "rubber_stamp") + assert "coverage:rubber_stamp" not in faults.FIRED + assert faults.FIRED == ["reader_a:merge_slots"] + faults.configure(()) + assert not faults.has("reader_a", "merge_slots") + + +def test_the_reader_faults_damage_a_reading_that_carries_them(): + # Every fault of a reader has something to bite on in one of the two readings above. Each one + # leaves a sentence the geometry layer would happily solve, which is what makes the experiment + # measure the readers and not the parser of the geometry layer. + for fault in faults.CATALOG["reader_a"]: + bitten = [] + for kind, base in FIXTURES: + order = canonical.slots_for(kind) + faults.configure(["reader_a:" + fault]) + changed, was_changed = faults.mutate_reading("reader_a", kind, base, order) + fired = list(faults.fired("reader_a")) + faults.configure(()) + if not was_changed: + continue + bitten.append(kind) + assert changed != base, (fault, kind) + assert fired == ["reader_a:" + fault], (fault, kind, fired) + sentence = canonical.print_geometry(kind, changed) + assert canonical.balanced(sentence) is True, (fault, kind, sentence) + assert bitten, fault + + +def test_a_reader_that_shifts_a_number_is_found_out_by_the_other_reader(): + honest = _ask(ONE) + shifted = _ask(ONE, ["reader_a:shift_number"]) + assert honest["final"]["assurance"] > 0 + assert shifted["final"]["state"] == "DISPUTED", shifted["final"] + assert shifted["final"]["assurance"] == 0 + assert shifted["final"]["answer"] == "" + assert "disagree" in shifted["final"]["reasons"] or "literal_count" in shifted["final"]["reasons"] + + +def test_a_geometry_layer_that_answers_another_sentence_is_reported_as_tampering(): + tampered = _ask(ONE, ["boundary:tamper_math"]) + assert tampered["final"]["state"] == "TAMPERED", tampered["final"] + assert tampered["final"]["assurance"] == 0 + assert tampered["final"]["answer"] == "" + assert "boundary" in tampered["final"]["reasons"] + + +def test_an_arbiter_that_lifts_the_assurance_is_overruled_by_the_tools(): + honest = _ask(ONE) + forced = _ask(ONE, ["arbiter:force_assurance"]) + assert any(record["claimed"] != record["referee"] for record in forced["records"]), forced["records"] + assert forced["final"]["assurance"] <= honest["final"]["assurance"], forced["final"] + assert forced["final"]["assurance"] <= 2 + assert "arbiter" in (forced["final"].get("detected") or []) + + +@pytest.mark.parametrize("node", sorted(faults.CATALOG)) +def test_no_single_fault_lifts_the_assurance_above_the_honest_one(node): + honest = _ask(ONE) + for kind in faults.CATALOG[node]: + outcome = _ask(ONE, ["%s:%s" % (node, kind)]) + shown = outcome["final"] + assert shown["assurance"] <= min(2, honest["final"]["assurance"]), (node, kind, shown) diff --git a/tests/test_lexicon.py b/tests/test_lexicon.py new file mode 100644 index 0000000000000000000000000000000000000000..569fb3bb8b781ac6a28c552a35da6e207011817a --- /dev/null +++ b/tests/test_lexicon.py @@ -0,0 +1,120 @@ +"""The data files: six varieties must describe the same stratum, in their own words.""" + +import json +from pathlib import Path + +import pytest + +from lggeostratum import canonical, decide, lexicon, segment + +ROOT = Path(__file__).resolve().parents[1] +LANGS = lexicon.codes() + + +def _raw(lang): + return json.loads((ROOT / "lexicon" / ("%s.json" % lang)).read_text(encoding="utf-8")) + + +def test_all_six_varieties_are_present_and_named(): + assert sorted(LANGS) == ["ar", "en", "es", "hi", "it", "zh"] + assert len(LANGS) == len(set(LANGS)) + for lang in LANGS: + assert lexicon.language_name(lang), lang + + +def test_every_variety_carries_the_same_sections(): + shapes = {lang: sorted(_raw(lang)) for lang in LANGS} + first = shapes[LANGS[0]] + for lang in LANGS[1:]: + assert shapes[lang] == first, lang + + +def test_every_variety_names_every_reading_state(): + states = set(decide.CEILING) + assert len(states) == 8 + for lang in LANGS: + assert set(lexicon.reading_labels(lang)) == states, lang + + +def test_every_variety_translates_the_labels_the_reply_needs(): + needed = {"status", "understood", "answer", "assurance", "notes", "math_layer", "check", "examples"} + reference = sorted(lexicon.labels(LANGS[0])) + for lang in LANGS: + labels = lexicon.labels(lang) + assert sorted(labels) == reference, lang + assert needed <= set(labels), lang + assert "{n}" in labels["assurance"], lang + + +def test_every_variety_translates_every_reason(): + reference = sorted(lexicon.reason_texts(LANGS[0])) + assert len(reference) == 21 + for lang in LANGS: + assert sorted(lexicon.reason_texts(lang)) == reference, lang + for key in reference: + assert lexicon.translate_reason(lang, key).strip(), (lang, key) + + +def test_every_variety_covers_the_same_kinds(): + kinds = set(canonical.KINDS) + for lang in LANGS: + assert set(lexicon.patterns(lang)) <= kinds, lang + assert set(lexicon.patterns(lang)), lang + + +def _atoms(text): + """The atoms of a shape, folded the way the two readers fold them when they scan a sentence.""" + return [segment.fold(atom) for _kind, atom in segment.atomize(text)] + + +def _consecutive(needle, hay): + return any(hay[start:start + len(needle)] == needle for start in range(len(hay) - len(needle) + 1)) + + +def test_every_pattern_is_announced_by_a_verb_of_its_own_kind(): + # A shape that promises one operation must carry the word that names it: otherwise a reader + # could match a frame whose operation it never heard announced. The comparison runs over the + # folded atom sequences of the readers, because a written accent or a joined article is not a + # different word, and a verb phrase may span several atoms. + for lang in LANGS: + verbs = lexicon.verbs(lang) + for kind, shapes in lexicon.patterns(lang).items(): + announced = [_atoms(phrase) for phrase, kinds in verbs.items() if kind in kinds] + assert announced, "%s has no verb for %s" % (lang, kind) + for shape in shapes: + atoms = _atoms(shape) + assert any(_consecutive(phrase, atoms) for phrase in announced), "%s %r" % (lang, shape) + + +def test_words_written_inside_a_pattern_are_known_words(): + # The filler of a frame may be a word of the variety -- the Italian frame for a circle + # writes the word for circle itself. A reader must know it, or it reports an unknown word in a + # sentence that this bundle is supposed to read. + for lang in LANGS: + index = lexicon.phrase_index(lang) + for word in lexicon.pattern_literals(lang): + assert word in index, "%s writes %r in a pattern but does not know it" % (lang, word) + + +def test_the_examples_of_each_variety_are_written_in_that_variety(): + # The example lines show what the stratum can be asked; they are data, so they stay in the + # language under study, and they must not be copies of another variety. + for lang in LANGS: + examples = _raw(lang).get("examples") or [] + assert examples, lang + for other in LANGS: + if other == lang: + continue + assert set(examples).isdisjoint(set(_raw(other).get("examples") or [])), (lang, other) + + +def test_the_reasons_of_all_varieties_ask_for_the_same_fillers(): + # A reason template may name what it wants filled in -- the word, the kind, the detail -- but + # those names are identifiers, not prose: every variety must ask for the same ones, so that the + # renderer has one set of fields to supply and never leaves a brace in front of a reader. + import re + pattern = re.compile(r"\{([a-z_]+)\}") + for key in lexicon.reason_texts(LANGS[0]): + reference = set(pattern.findall(lexicon.reason_texts(LANGS[0])[key])) + for lang in LANGS[1:]: + assert set(pattern.findall(lexicon.reason_texts(lang)[key])) == reference, (lang, key) diff --git a/tests/test_orchestrator_e2e.py b/tests/test_orchestrator_e2e.py new file mode 100644 index 0000000000000000000000000000000000000000..c102f21e28da469ebf32c99ca71667d439ecaf34 --- /dev/null +++ b/tests/test_orchestrator_e2e.py @@ -0,0 +1,57 @@ +"""The same sessions, run by the orchestrator itself instead of in memory. + +The in-memory pipeline is the fast path; what the user is served with is a session of eight separate +processes that exchange envelopes. This test asks the orchestrator to run two of them, and checks +that every envelope came back with a claim the referee of the session confirmed, that the assurance +shown is the one the decision rule allows, and that a node which misbehaves is found out there too. +""" + +import importlib.util +import sys +from pathlib import Path + +import pytest + +from lggeostratum import corpus, lexicon + +ROOT = Path(__file__).resolve().parent.parent +ITEMS = {item["id"]: item for item in corpus.load()} + + +def _tool(): + path = ROOT / "tools" / "ask.py" + spec = importlib.util.spec_from_file_location("stratum_ask_tool", path) + module = importlib.util.module_from_spec(spec) + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +def test_the_eight_nodes_of_the_topology_exchange_envelopes(): + pytest.importorskip("lingologos_orchestrator") + tool = _tool() + item = ITEMS["perp-it-true"] + result = tool.ask(str(item["question"]), str(item["lang"])) + assert len(result["records"]) == 8, result["records"] + for record in result["records"]: + assert record["claimed"] == record["referee"], record + final = result["final"] + assert final["state"] == "AGREED", final + assert 0 < final["assurance"] <= 2, final + assert final["assurance"] <= int(final.get("math_assurance", 0) or 0), final + assert str(final["answer"]).strip(), final + labels = lexicon.labels(str(item["lang"])) + text = str(result["reply"].get("text", "")) + assert labels["math_layer"] in text, text + assert labels["understood"] in text, text + + +def test_the_orchestrator_reports_a_verdict_that_is_not_the_one_the_arbiter_wrote(): + pytest.importorskip("lingologos_orchestrator") + tool = _tool() + item = ITEMS["perp-it-true"] + honest = tool.ask(str(item["question"]), str(item["lang"])) + forced = tool.ask(str(item["question"]), str(item["lang"]), faults_spec="arbiter:force_assurance") + assert any(record["claimed"] != record["referee"] for record in forced["records"]), forced["records"] + assert forced["final"]["assurance"] <= honest["final"]["assurance"], forced["final"] + assert "arbiter" in (forced["final"].get("detected") or []), forced["final"] diff --git a/tests/test_pinned_invariant.py b/tests/test_pinned_invariant.py new file mode 100644 index 0000000000000000000000000000000000000000..47cd670f700d91ca42567982986ec5704a2aac2d --- /dev/null +++ b/tests/test_pinned_invariant.py @@ -0,0 +1,108 @@ +"""The discipline this bundle is built on: changing the conversational layer changes no geometry verdict. + +The geometry layer answers in a process of its own, from the sentence the readers agreed on. What this +stratum may add is only a reading and a ceiling. So for one question, whatever the conversational +layer does -- which node speaks, which node abstains, which node misbehaves -- the verdict of the +geometry layer has to stay identical, and what is shown to the user has to stay at or below it. +""" + +import copy +from typing import Any, Dict, List, Tuple + +import pytest + +from lggeostratum import agents, canonical, coverage, corpus, faults, pipeline + +ITEMS = {item["id"]: item for item in corpus.load()} +PINS = ["perp-it-true", "circumcircle-it"] +TRACKED = ("status", "assurance", "answer_text", "problem_math", "answer", "verdict", "claims", "referee") + +_BASE: Dict[str, Dict[str, Any]] = {} + + +def _math_of(dossier: Dict[str, Any]) -> Dict[str, Any]: + section = dossier.get("math") or {} + return {key: copy.deepcopy(section[key]) for key in TRACKED if key in section} + + +def _printed(reading: Dict[str, Any]) -> str: + """The sentence a reading describes: one for a question of one sentence, joined for a question + that states its figures and then asks about them.""" + parts = [part for part in (reading.get("parts") or [reading]) if part.get("kind")] + return " ".join(canonical.print_geometry(str(part["kind"]), dict(part.get("slots") or {})) + for part in parts) + + +def _baseline(item_id: str) -> Dict[str, Any]: + if item_id not in _BASE: + item = ITEMS[item_id] + _BASE[item_id] = pipeline.ask(str(item["question"]), str(item["lang"])) + return _BASE[item_id] + + +def _configurations() -> List[Tuple[str, Tuple[str, ...], Tuple[str, ...]]]: + configs: List[Tuple[str, Tuple[str, ...], Tuple[str, ...]]] = [("all eight nodes", agents.ORDER, ())] + for name in agents.ORDER: + if name == "arbiter": + continue + configs.append(("without " + name, tuple(node for node in agents.ORDER if node != name), ())) + for node in sorted(faults.CATALOG): + for kind in faults.CATALOG[node]: + if (node, kind) == ("boundary", "tamper_math"): + continue # that fault is an attack on the geometry layer itself, not on this layer + configs.append(("%s commits %s" % (node, kind), agents.ORDER, ("%s:%s" % (node, kind),))) + return configs + + +@pytest.mark.parametrize("item_id", PINS) +@pytest.mark.parametrize("label,active,fault_spec", _configurations()) +def test_the_layer_verdict_does_not_move(item_id, label, active, fault_spec): + item = ITEMS[item_id] + outcome = pipeline.ask(str(item["question"]), str(item["lang"]), active=active, fault_spec=fault_spec) + honest = _baseline(item_id) + asked = _math_of(outcome["dossier"]) + base = _math_of(honest["dossier"]) + shown = outcome["final"] + if base.get("problem_math") and asked.get("problem_math"): + # The geometry layer was asked the same question by both sessions: its answer is byte for byte + # the same, whatever the conversational layer did on the way there. + assert asked == base, (item_id, label) + math_level = int(base.get("assurance", 0) or 0) + assert shown["assurance"] <= min(2, math_level), (item_id, label, shown) + assert shown["math_assurance"] == math_level, (item_id, label) + if shown["assurance"] > 0: + assert shown["answer"] == base.get("answer_text"), (item_id, label) + else: + # The layer withheld the question -- a witness missing, a reading disputed, the invoker gone. + # That is the only direction the conversational layer may move the verdict in, and it leaves + # nothing to show. + assert shown["assurance"] == 0, (item_id, label, shown) + assert shown["answer"] == "", (item_id, label, shown) + assert shown["assurance"] < 3, (item_id, label) + + +def test_the_sentence_the_geometry_layer_was_asked_about_is_the_agreed_one(): + # The echo of the geometry layer is written in its own spacing, so what the stratum checks is that + # the echoed sentence carries the reading it was built from: same figures, same claim, same numbers. + for item_id in PINS: + dossier = _baseline(item_id)["dossier"] + agreed = str(dossier.get("sent") or "") + assert agreed, item_id + assert canonical.tidy(agreed) == canonical.tidy(_printed(dossier.get("reading_a") or {})), (item_id, agreed) + assert coverage.echo_matches(dossier.get("reading_a") or {}, dossier.get("math") or {}), item_id + + +def test_the_geometry_layer_is_reached_only_as_a_separate_process(): + # Nothing in this bundle may decide a geometric verdict: the only door toward the geometry layer is + # the invoker, and it launches the solver of that bundle as a subprocess. + import inspect + from lggeostratum import invoker + + source = inspect.getsource(invoker) + assert "subprocess" in source + assert "import geometry" not in source + assert "from geometry" not in source + for module in (agents, pipeline, faults): + text = inspect.getsource(module) + assert "import geometry" not in text, module.__name__ + assert "from geometry" not in text, module.__name__ diff --git a/tests/test_readers.py b/tests/test_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..02f7ee424081cc0fd7394244d5eebc2f97382df7 --- /dev/null +++ b/tests/test_readers.py @@ -0,0 +1,91 @@ +"""What the two readers do, taken from the questions the corpus already carries. + +A question of this stratum is often several sentences long: the person states the figures and then +asks about them. One reading of such a question is a reading of each of its sentences, so the tests +below look at the readings the pipeline itself put in the dossier, the place where a compound +reading is assembled, rather than at the output of one reader over the whole text. +""" + +import pytest + +from lggeostratum import canonical, compare, corpus, pipeline, read_a, read_b + +ITEMS = {item["id"]: item for item in corpus.load()} +AGREED = [item_id for item_id, item in ITEMS.items() if (item.get("expect") or {}).get("state") == "AGREED"] +SINGLE = [item_id for item_id, item in ITEMS.items() if (item.get("expect") or {}).get("state") == "SINGLE"] +NEGATIVE = [item_id for item_id, item in ITEMS.items() + if (item.get("expect") or {}).get("state") == "NOT COVERED"] +PASSTHROUGH = [item_id for item_id, item in ITEMS.items() + if (item.get("expect") or {}).get("state") == "PASSTHROUGH"] + +_SESSIONS = {} + + +def _item(item_id): + item = ITEMS[item_id] + return str(item["lang"]), str(item["question"]) + + +def _readings(item_id): + """The two readings of the item, as the reading layer assembled them, without a geometry session.""" + if item_id not in _SESSIONS: + lang, question = _item(item_id) + _SESSIONS[item_id] = pipeline.ask(question, lang, call_geometry=False)["dossier"] + dossier = _SESSIONS[item_id] + return dossier.get("reading_a") or {}, dossier.get("reading_b") or {} + + +def test_the_readers_are_read_from_the_data_not_from_a_fork(): + # Two readers that share nothing but the data files are the whole point: one matches the shapes + # written in the frames, the other follows the joints of the geometry language. If they became the + # same procedure, the stratum would be reading a question twice with one pair of eyes. + assert read_a.read.__module__ != read_b.read.__module__ + import inspect + assert "gap_markers" not in inspect.getsource(read_a.read) + assert "compile_pattern" not in inspect.getsource(read_b.read) + + +@pytest.mark.parametrize("item_id", AGREED) +def test_both_readers_reach_the_same_sentence(item_id): + a, b = _readings(item_id) + assert a.get("status") == "READ", (item_id, a.get("notes")) + assert b.get("status") == "READ", (item_id, b.get("notes")) + assert a.get("kind") == b.get("kind"), (item_id, a.get("kind"), b.get("kind")) + assert compare.equivalence(a, b)["same"] is True, (item_id, compare.equivalence(a, b).get("why")) + expected = canonical.tidy(str((ITEMS[item_id].get("expect") or {}).get("sentence", ""))) + if expected: + assert canonical.tidy(str(a.get("math", ""))) == expected, item_id + + +@pytest.mark.parametrize("item_id", AGREED) +def test_a_reader_keeps_every_number_the_question_wrote(item_id): + reading, _other = _readings(item_id) + _lang, question = _item(item_id) + assert compare.keeps(reading, question)["ok"] is True, (item_id, compare.keeps(reading, question)) + + +@pytest.mark.parametrize("item_id", SINGLE) +def test_one_reader_may_abstain_where_the_other_reads(item_id): + # The varieties that put the joints after the slot, rather than before it, are read by the strict + # reader and not by the frame reader. That disagreement is reported, never hidden, and it is what + # keeps the assurance of those questions at one. + a, b = _readings(item_id) + assert a.get("status") == "READ", (item_id, a.get("notes")) + assert b.get("status") != "READ", (item_id, b.get("notes")) + assert compare.equivalence(a, b)["same"] is False, item_id + + +@pytest.mark.parametrize("item_id", NEGATIVE) +def test_a_question_this_variety_does_not_write_is_not_read(item_id): + for reading in _readings(item_id): + assert reading.get("status") != "READ", (item_id, reading.get("kind"), reading.get("slots")) + assert not reading.get("math"), (item_id, reading.get("math")) + + +@pytest.mark.parametrize("item_id", PASSTHROUGH) +def test_the_geometry_language_is_handed_on_without_being_read(item_id): + _lang, question = _item(item_id) + direct = canonical.direct(question) + assert direct is not None, item_id + assert canonical.tidy(str(direct.get("math", ""))) == canonical.tidy( + str((ITEMS[item_id].get("expect") or {}).get("sentence", ""))), item_id diff --git a/tests/test_topology.py b/tests/test_topology.py new file mode 100644 index 0000000000000000000000000000000000000000..d38305826079d1c7dd8c328468feee47a93750c5 --- /dev/null +++ b/tests/test_topology.py @@ -0,0 +1,95 @@ +"""Shape of the shipped topology, of the node datasets, and of the sources themselves.""" + +import ast +import json +from pathlib import Path + +import pytest + +from lggeostratum import agents + +ROOT = Path(__file__).resolve().parents[1] +TOPOLOGY = json.loads((ROOT / "topology.json").read_text(encoding="utf-8")) +NODE_IDS = [instance["id"] for instance in TOPOLOGY["instances"]] +# The question and its language enter through the arbiter, exactly as the seed of a problem enters +# through the arbiter of the geometry bundle: the stratum never invents a second entry point. +SEED_NODE = "arbiter" + + +def test_instances_are_the_eight_nodes_in_execution_order(): + assert NODE_IDS == list(agents.ORDER) + assert all(instance["role"] == instance["id"] for instance in TOPOLOGY["instances"]) + assert sorted(NODE_IDS) == sorted(agents.STEPS) + + +def test_routing_follows_the_execution_order_and_closes_the_cycle(): + edges = [(row["from"], target) for row in TOPOLOGY["routingMatrix"] for target in row["to"]] + assert [source for source, _ in edges] == NODE_IDS + # A sender reads the latest output of its recipient: every node reads the node before it, and + # the first one reads the seed the arbiter holds, so the arbiter closes the cycle. + assert [target for _, target in edges] == [SEED_NODE] + NODE_IDS[:-1] + assert TOPOLOGY["maxTurns"] == len(edges) + + +def test_the_termination_condition_is_not_an_early_exit(): + # The orchestrator stops on UNSAT_BREAKER or SAT_CONVERGENCE; here the cycle must run its full + # length, so the shipped condition may not name either shortcut. + condition = TOPOLOGY.get("terminationCondition", "") + assert "UNSAT_BREAKER" not in condition + assert "SAT_CONVERGENCE" not in condition + + +@pytest.mark.parametrize("node", NODE_IDS) +def test_node_dataset_is_complete(node): + folder = ROOT / "nodes" / node + for name in ("grammar.gf", "ontology.smt2", "seed_payload.json"): + assert (folder / name).is_file(), name + seed = json.loads((folder / "seed_payload.json").read_text(encoding="utf-8")) + assert seed["sender"] == node + ontology = (folder / "ontology.smt2").read_text(encoding="utf-8") + assert "(set-option :timeout" in ontology + assert "(declare-" not in ontology + + +def test_python_sources_are_ascii_only(): + paths = (list((ROOT / "lggeostratum").glob("*.py")) + list((ROOT / "tools").glob("*.py")) + + list((ROOT / "tests").glob("*.py")) + [ROOT / "agents" / "stratum_agent"]) + for path in paths: + path.read_text(encoding="ascii") + + +def test_only_the_equivalence_referee_may_touch_the_geometry_code(): + # The geometry verdict of a session reaches this bundle as the output of a separate process, so it + # cannot be rewritten on the way in. One module is allowed to import the geometry package, and only + # for its own SMT plumbing: compare.py asks whether two readings of a question say the same + # thing, which is a claim about the readings and never about the answer. The modules that + # decide, route and invoke are checked to hold no reference to that package at all. + for path in (ROOT / "lggeostratum").glob("*.py"): + tree = ast.parse(path.read_text(encoding="ascii")) + for node in ast.walk(tree): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + names = [node.module or ""] + else: + continue + for name in names: + if name == "geometry" or name.startswith("geometry."): + assert path.name == "compare.py", "%s imports %s" % (path.name, name) + for name in ("decide.py", "pipeline.py", "agents.py", "invoker.py", "protocol.py", "coverage.py"): + text = (ROOT / "lggeostratum" / name).read_text(encoding="ascii") + assert "import geometry" not in text, name + assert "from geometry" not in text, name + + +def test_the_geometry_bundle_is_reached_as_a_separate_process(): + source = (ROOT / "lggeostratum" / "invoker.py").read_text(encoding="ascii") + tree = ast.parse(source) + calls = [ast.unparse(node) for node in ast.walk(tree) if isinstance(node, ast.Call)] + assert any("subprocess.run" in call for call in calls) + # The door is this bundle's own adapter: the invoker launches it as a process and never loads the + # package it wraps. + assert "geometry_runner.py" in source + assert (ROOT / "tools" / "geometry_runner.py").is_file() + assert "import geometry" not in source + assert "from geometry" not in source diff --git a/tools/ablation.py b/tools/ablation.py new file mode 100644 index 0000000000000000000000000000000000000000..0c3e32f56e564a825d8071b9130e4663a4c97a07 --- /dev/null +++ b/tools/ablation.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""Fault injection: how many conversational nodes does the assurance ceiling need? + +For every configuration (a subset of the eight nodes) and every fault of the catalogue +(``lggeostratum/faults.py``) a probe set of the corpus is run in memory with the very same node code +the orchestrator runs. A run is *activated* when the injected fault really changed a node. Each +activated run is then measured against the honest result of the same item, and ends in one of: + + raised : the fault pushed the shown assurance above the honest ceiling -- an invariant + violation, and the only outcome this topology is not allowed to produce + lowered : the answer stayed what the gold asked but the confidence dropped: another node + compensated by withdrawing certainty, which is the designed reaction + masked : the gold still holds at the same assurance, because the fault changed nothing + that the referee reads + abstained : the layer withdrew the answer entirely (assurance zero) while the gold expected one + caught : an answer was shown that the gold does not accept, but the session pointed at its + own gap: a claim fell to the referee of its node, or the assurance sits below the + honest one because the configuration itself lost a node + silent_error : a wrong answer presented with confidence while nothing in the session said so + +Usage: python geometry-stratum/tools/ablation.py [--probe N] [--all] [--out geometry-stratum/results/ablation.json] +""" + +import argparse +import json +import sys +import time +from pathlib import Path +from typing import Any, Dict, List, Tuple + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from lggeostratum import agents, corpus, faults, pipeline # noqa: E402 + +FULL = list(agents.ORDER) +OUT = ROOT / "results" / "ablation.json" + +CONFIGS: Dict[str, List[str]] = { + "S1 reader_a": ["reader_a"], + "S2 +reader_b": ["reader_a", "reader_b"], + "S3 +equivalence": ["reader_a", "reader_b", "equivalence"], + "S4 +coverage": ["reader_a", "reader_b", "equivalence", "coverage"], + "S5 +invoker": ["reader_a", "reader_b", "equivalence", "coverage", "invoker"], + "S6 +boundary": FULL[:6], + "S7 +adversary": FULL[:7], + "S8 full topology": FULL, +} +for _node in FULL: + CONFIGS["S8 minus %s" % _node] = [node for node in FULL if node != _node] + + +def single_faults(active: List[str]) -> List[Tuple[str, ...]]: + # Not every node has a fault to commit: the invoker reads nothing and proves nothing. + return [("%s:%s" % (node, kind),) for node in active for kind in faults.CATALOG.get(node, [])] + + +def multi_faults() -> List[Tuple[str, ...]]: + """The pairs that matter here: both readers wrong in the same way, and certainty forced on + top of a reading that no longer holds.""" + out: List[Tuple[str, ...]] = [ + ("reader_a:merge_slots", "reader_b:merge_slots"), + ("reader_a:shift_number", "reader_b:shift_number"), + ("reader_a:rename_slot", "reader_b:rename_slot"), + ("equivalence:rubber_stamp", "coverage:rubber_stamp"), + ("boundary:tamper_math", "arbiter:force_assurance"), + ("reader_a:shift_number", "equivalence:rubber_stamp"), + ("reader_a:merge_slots", "arbiter:force_assurance"), + ("boundary:tamper_math", "adversary:rubber_stamp", "arbiter:force_assurance"), + ] + return [spec for spec in out if all(part.split(":")[0] in faults.CATALOG for part in spec)] + + +def honest(item: Dict[str, Any]) -> Dict[str, Any]: + """The baseline the injected runs are measured against: no fault, full topology.""" + faults.configure([]) + result = pipeline.ask(item["question"], item["lang"], active=FULL) + grade = corpus.grade(item, result) + return {"ok": bool(grade["ok"]), "assurance": int(result["final"].get("assurance", 0)), + "state": str(result["final"].get("state", "NONE")), "problems": grade["problems"]} + + +def flagged(result: Dict[str, Any]) -> bool: + """Did the session itself point at the problem: a claim that did not survive its own referee.""" + final = result.get("final") or {} + if final.get("detected"): + return True + return any(record["claimed"] != record["referee"] for record in result.get("records") or []) + + +def classify(base: Dict[str, Any], item: Dict[str, Any], result: Dict[str, Any]) -> str: + """What an injected fault ended up doing to what the layer shows. + + ``raised`` is the violation the tool exists to look for. ``silent_error`` is the narrower thing it + is supposed to prevent: a wrong answer was shown, and nothing in the session said so. When a + envelope claim fell to its referee, or the assurance sits below the honest one because the + topology itself was weakened, the run is ``caught``: the layer still answered, but it pointed at + its own gap. + """ + shown = int(result["final"].get("assurance", 0)) + grade = corpus.grade(item, result) + if shown > base["assurance"]: + return "raised" + if grade["ok"]: + return "lowered" if shown < base["assurance"] else "masked" + if shown == 0: + return "abstained" + return "caught" if (flagged(result) or shown < base["assurance"]) else "silent_error" + + +def run_cell(items: List[Dict[str, Any]], active: List[str], spec: Tuple[str, ...], + base: Dict[str, Dict[str, Any]], config: str = "") -> Dict[str, Any]: + tally = {"runs": 0, "activated": 0, "raised": 0, "lowered": 0, "masked": 0, "caught": 0, + "abstained": 0, "silent_error": 0, "details": []} + for item in items: + # The session itself has to carry the fault: asking for it beforehand is not enough, because + # a session configures the faults it was given and leaves the others off. + result = pipeline.ask(item["question"], item["lang"], active=active, fault_spec=list(spec)) + tally["runs"] += 1 + if not faults.FIRED: + continue + tally["activated"] += 1 + label = classify(base[item["id"]], item, result) + tally[label] += 1 + if label in ("raised", "silent_error", "caught"): + grade = corpus.grade(item, result) + tally["details"].append({"id": item["id"], "config": config, "fault": list(spec), + "label": label, "honest": base[item["id"]]["assurance"], + "shown": int(result["final"].get("assurance", 0)), + "flagged": flagged(result), "problems": grade["problems"]}) + return tally + + +def probe_set(items: List[Dict[str, Any]], count: int) -> List[Dict[str, Any]]: + """Spread the probe across the languages instead of taking the first N of one variety.""" + if count >= len(items): + return list(items) + by_lang: Dict[str, List[Dict[str, Any]]] = {} + for item in items: + by_lang.setdefault(item["lang"], []).append(item) + picked: List[Dict[str, Any]] = [] + rank = 0 + while len(picked) < count: + added = False + for lang in sorted(by_lang): + pool = by_lang[lang] + if rank < len(pool) and len(picked) < count: + picked.append(pool[rank]) + added = True + if not added: + break + rank += 1 + return picked + + +def main(argv: List[str] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--probe", type=int, default=12, help="how many corpus items to run per cell") + parser.add_argument("--all", action="store_true", help="run the whole corpus in every cell") + parser.add_argument("--out", default=str(OUT), help="where to write the JSON report") + args = parser.parse_args(argv) + + items = corpus.load() + probes = items if args.all else probe_set(items, max(1, args.probe)) + print("probe set: %d items over %s" % (len(probes), ", ".join(sorted({i["lang"] for i in probes})))) + base = {} + for item in probes: + base[item["id"]] = honest(item) + print("honest %-9s %-12s assurance %d %s" % (item["id"], base[item["id"]]["state"], + base[item["id"]]["assurance"], + "" if base[item["id"]]["ok"] else base[item["id"]]["problems"])) + + report: Dict[str, Any] = {"probe": [item["id"] for item in probes], "cells": {}} + started = time.time() + for name in sorted(CONFIGS): + active = CONFIGS[name] + specs = single_faults(active) + if name == "S8 full topology": + specs.extend(multi_faults()) + for spec in specs: + cell = run_cell(probes, active, spec, base, config=name) + key = "%s | %s" % (name, ",".join(spec)) + report["cells"][key] = cell + print("%-46s runs %2d activated %2d raised %d silent %d caught %d abstained %d " + "lowered %d masked %d" + % (key, cell["runs"], cell["activated"], cell["raised"], cell["silent_error"], + cell["caught"], cell["abstained"], cell["lowered"], cell["masked"])) + totals = {"runs": 0, "activated": 0, "raised": 0, "lowered": 0, "masked": 0, "caught": 0, + "abstained": 0, "silent_error": 0} + for cell in report["cells"].values(): + for key in totals: + totals[key] += cell[key] + report["totals"] = totals + report["seconds"] = round(time.time() - started, 1) + report["violations"] = [detail for cell in report["cells"].values() for detail in cell["details"]] + + destination = Path(args.out) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8") + print("") + print("cells %d, activated %d, raised %d, silent errors %d, caught %d, abstained %d, lowered %d, " + "masked %d" + % (len(report["cells"]), totals["activated"], totals["raised"], totals["silent_error"], + totals["caught"], totals["abstained"], totals["lowered"], totals["masked"])) + print("wrote %s in %.1f seconds" % (destination, report["seconds"])) + return 1 if totals["raised"] else 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/ask.py b/tools/ask.py new file mode 100644 index 0000000000000000000000000000000000000000..3c293fe7d520fd2a5d7569697e070c23402dbefe --- /dev/null +++ b/tools/ask.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +"""Ask a question in a human language and get the answer of the geometry layer back in that language. + + python tools/ask.py --lang it "risolvi x^2 - 5*x + 6 = 0 per x" + python tools/ask.py --lang en "solve x^2 - 5*x + 6 = 0 for x" --json + python tools/ask.py --lang ar --corpus problems/corpus.jsonl --limit 6 + +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 script builds a throw away workspace (node datasets, seed with the question and its language, +launcher), runs the eight node processes through ``MultiInstanceOrchestrator``, and then re-derives +the verdict from the transcript: it recomputes the arbiter's decision from the evidence the envelopes +carry, and checks that the Z3 run of the orchestrator agrees with what every node claimed about its +own envelope. What is printed is that re-derived verdict, not the one the arbiter wrote. + +The prose of this script and of its labels stays English, as the repository requires; the answer +block is the one piece of data that is deliberately written in the language of the question, because +that answer is the object this bundle studies. +""" + +import argparse +import json +import os +import shutil +import stat +import sys +import tempfile +from pathlib import Path +from typing import Any, Dict, List + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) +# Inside the repository this bundle sits at /datasets/geometry-stratum, so the orchestrator +# package is no longer a sibling of the bundle. Walk up the tree until an ancestor carries it. +for _parent in ROOT.parents: + _candidate = _parent / "src" + if (_candidate / "lingologos_orchestrator").is_dir(): + sys.path.insert(0, str(_candidate)) + break + +from lggeostratum import corpus, pipeline, protocol, render # noqa: E402 + + +def _launcher(directory: Path) -> Path: + agent = ROOT / "agents" / "stratum_agent" + if os.name == "nt": + path = directory / "stratum_agent.cmd" + path.write_text('@echo off\r\n"%s" "%s" %%*\r\n' % (sys.executable, agent)) + else: + path = directory / "stratum_agent.sh" + path.write_text('#!/bin/sh\nexec "%s" "%s" "$@"\n' % (sys.executable, agent)) + path.chmod(path.stat().st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) + return path + + +def ask(question: str, lang: str, faults_spec: str = "", keep: bool = False) -> Dict[str, Any]: + """Run one question through the real orchestrator and return the checked verdict.""" + from lingologos_orchestrator.orchestrator import MultiInstanceOrchestrator + from lingologos_orchestrator.schema import OrchestratorError + + workspace = Path(tempfile.mkdtemp(prefix="lggeostratum_")) + try: + datasets = workspace / "datasets" + shutil.copytree(ROOT / "nodes", datasets) + seed_path = datasets / "arbiter" / "seed_payload.json" + seed = json.loads(seed_path.read_text(encoding="utf-8")) + seed["payload"]["naturalLanguage"] = pipeline.seed(question, lang)["payload"]["naturalLanguage"] + seed_path.write_text(json.dumps(seed, ensure_ascii=False), encoding="utf-8") + launcher = _launcher(workspace) + topology = json.loads((ROOT / "topology.json").read_text(encoding="utf-8")) + for instance in topology["instances"]: + instance["executable"] = str(launcher) + topology_path = workspace / "topology.json" + topology_path.write_text(json.dumps(topology), encoding="utf-8") + previous = os.environ.get("LGSTRATUM_FAULTS") + os.environ["LGSTRATUM_FAULTS"] = faults_spec + try: + orchestrator = MultiInstanceOrchestrator.from_config_file( + config_path=topology_path, datasets_dir=datasets, + runtime_state_dir=workspace / "runtime_state", workspace_dir=workspace) + result = orchestrator.run_session().to_dict() + except OrchestratorError as exc: + return {"final": _unknown("orchestrator error: %s" % str(exc)[:200]), "referee": [], + "records": [], "reply": None} + finally: + if previous is None: + os.environ.pop("LGSTRATUM_FAULTS", None) + else: + os.environ["LGSTRATUM_FAULTS"] = previous + return _check(result) + finally: + if keep: + print("workspace kept at %s" % workspace, file=sys.stderr) + else: + shutil.rmtree(workspace, ignore_errors=True) + + +def _unknown(reason: str) -> Dict[str, Any]: + return {"state": "NONE", "assurance": 0, "ceiling": 0, "math_assurance": 0, "math_status": None, + "answer": "", "reasons": [reason], "consulted_math": False, "detected": []} + + +def _check(result: Dict[str, Any]) -> Dict[str, Any]: + records: List[Dict[str, Any]] = result["records"] + referee = [{"sender": r["sender"], "claimed": r["envelope"]["payload"]["smtConstraints"]["z3Status"], + "referee": r["smt_result"]["status"]} for r in records] + dossier = protocol.decode(records[-1]["envelope"]["payload"]["naturalLanguage"]) + final = pipeline.checked_verdict(dossier, referee, arbiter_expected=True) + return {"final": final, "referee": referee, "records": referee, "transcript": records, + "dossier": dossier, "reply": render.reply(dossier, final, referee), "turns": result["total_turns"]} + + +def _describe(outcome: Dict[str, Any]) -> str: + final = outcome["final"] + lines = [] + lines.append("Reading state : %s" % final["state"]) + lines.append("Assurance shown : %d (reading ceiling %d, geometry assurance %s)" + % (final["assurance"], final.get("ceiling", 0), + final.get("math_assurance"))) + lines.append("Geometry layer status : %s" % (final.get("math_status") or "-")) + if final["reasons"]: + lines.append("Notes : %s" % "; ".join(final["reasons"])) + if final.get("detected"): + lines.append("Detected : %s" % ", ".join(str(item) for item in final["detected"])) + if outcome["referee"]: + agree = sum(1 for r in outcome["referee"] if r["claimed"] == r["referee"]) + lines.append("Orchestrator Z3 check : %d of %d envelopes confirmed" % (agree, len(outcome["referee"]))) + reply = outcome.get("reply") + if reply: + lines.append("") + lines.append("Answer in the language of the question (%s):" % reply["language"]) + for line in reply["lines"]: + lines.append(" %s" % line) + return "\n".join(lines) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("question", nargs="?", help="the question, written in the language given by --lang") + parser.add_argument("--lang", default="it", help="language of the question: it, en, es, zh, hi or ar") + parser.add_argument("--json", action="store_true", help="print the full machine readable outcome") + parser.add_argument("--faults", default="", help="comma separated node:fault pairs (experiments only)") + parser.add_argument("--keep", action="store_true", help="keep the temporary workspace") + parser.add_argument("--corpus", help="run every question of a corpus file and compare with its gold expectations") + parser.add_argument("--limit", type=int, default=0, help="with --corpus: only the first N questions") + args = parser.parse_args() + if args.corpus: + rows = corpus.load(args.corpus) + rows = rows[: args.limit] if args.limit else rows + tally: Dict[str, int] = {} + for item in rows: + outcome = ask(item["question"], item["lang"], args.faults, args.keep) + verdict = corpus.grade(item, outcome) + label = "ok" if verdict["ok"] else "wrong" + tally[label] = tally.get(label, 0) + 1 + print("%-8s %-6s %-14s %s" % (verdict["id"], label, verdict["state"], item["question"])) + for problem in verdict["problems"]: + print(" %s" % problem) + print(json.dumps(tally, sort_keys=True)) + return 0 if tally.get("wrong", 0) == 0 else 1 + if not args.question: + parser.error("a question or --corpus is required") + outcome = ask(args.question, args.lang, args.faults, args.keep) + if args.json: + printable = {key: value for key, value in outcome.items() if key != "records"} + print(json.dumps(printable, indent=2, ensure_ascii=False, default=str)) + else: + print(_describe(outcome)) + if outcome["final"].get("detected"): + return 3 + return 0 if int(outcome["final"].get("assurance", 0) or 0) > 0 else 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tools/coverage_report.py b/tools/coverage_report.py new file mode 100644 index 0000000000000000000000000000000000000000..a426dc717b0fdc05f59c0e26559b81fa6b125841 --- /dev/null +++ b/tools/coverage_report.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Reading coverage: which variety reads which kind, and how often the two readers agree. + +This is the one table the corpus cannot fake. A language covers a kind only if its data file +writes the verbs, the patterns and the joints for it, and a reading only counts as confirmed when +reader A (which matches the surface shapes) and reader B (which follows the joints of the geometry +language) reach it by different routes. The math stratum is not consulted by default: a coverage +report asks what the stratum *understood*, not what the geometry layer could prove, and the two +ceilings are reported apart on purpose. Pass ``--geometry`` to add the geometry verdicts to the same run. + +Usage: python geometry-stratum/tools/coverage_report.py [--geometry] + python geometry-stratum/tools/coverage_report.py --out geometry-stratum/results/coverage.json +""" + +import argparse +import collections +import json +import sys +from pathlib import Path +from typing import Any, Dict, List + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from lggeostratum import corpus, lexicon, pipeline # noqa: E402 + +OUT = ROOT / "results" / "coverage.json" + + +def inventory() -> Dict[str, Dict[str, Any]]: + """What the data files of each variety actually carry, counted rather than claimed.""" + table: Dict[str, Dict[str, Any]] = {} + for lang in lexicon.codes(): + patterns = lexicon.patterns(lang) + verbs = lexicon.verbs(lang) + table[lang] = { + "kinds": sorted(patterns), + "patterns": sum(len(entries) for entries in patterns.values()), + "verb_phrases": len(verbs), + "markers": sum(len(words) for words in lexicon.markers(lang).values()), + "connectives": sum(len(words) for words in lexicon.connectives(lang).values()), + "noise_words": len(lexicon.noise(lang)), + "pattern_words": len(lexicon.pattern_literals(lang)), + } + return table + + +def ask(item: Dict[str, Any], use_geometry: bool) -> Dict[str, Any]: + """One corpus question through the eight nodes, in memory, with the fault catalogue closed.""" + result = pipeline.ask(item["question"], item["lang"], call_geometry=use_geometry) + reading_a = result["dossier"].get("reading_a") or {} + reading_b = result["dossier"].get("reading_b") or {} + return {"id": item["id"], "lang": item["lang"], "kind": item.get("kind", "?"), + "state": str(result["final"].get("state", "NONE")), + "assurance": int(result["final"].get("assurance", 0)), + "reader_a": str(reading_a.get("status", "NONE")), + "reader_b": str(reading_b.get("status", "NONE")), + "math_status": str((result["dossier"].get("math") or {}).get("status", "SKIPPED"))} + + +def tally(rows: List[Dict[str, Any]]) -> Dict[str, int]: + counts: Dict[str, int] = collections.Counter() + for row in rows: + counts["items"] += 1 + counts[row["state"].lower()] += 1 + counts["reader_a_read"] += 1 if row["reader_a"] in ("READ", "DIRECT") else 0 + counts["reader_b_read"] += 1 if row["reader_b"] in ("READ", "DIRECT") else 0 + return dict(sorted(counts.items())) + + +def main(argv: List[str] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--geometry", action="store_true", + help="consult the geometry layer too, and report its verdicts in the same run") + parser.add_argument("--out", default=str(OUT), help="where to write the JSON report") + args = parser.parse_args(argv) + + items = corpus.load() + rows = [] + for item in items: + row = ask(item, args.geometry) + rows.append(row) + print("%-9s %-4s %-11s %-12s a=%-11s b=%-11s assurance %d" + % (row["id"], row["lang"], row["kind"], row["state"], row["reader_a"], + row["reader_b"], row["assurance"])) + + by_pair: Dict[str, Dict[str, int]] = {} + for lang in lexicon.codes(): + for kind in sorted({row["kind"] for row in rows if row["lang"] == lang}): + subset = [row for row in rows if row["lang"] == lang and row["kind"] == kind] + by_pair["%s/%s" % (lang, kind)] = tally(subset) + languages = {lang: tally([row for row in rows if row["lang"] == lang]) + for lang in lexicon.codes()} + + print("") + print("%-6s %-12s %5s %7s %7s %7s %7s" % ("lang", "kind", "items", "agree", "single", "other", "read by A/B")) + for key in sorted(by_pair): + cell = by_pair[key] + print("%-6s %-12s %5d %7d %7d %7d %4d/%-3d" + % (key.split("/")[0], key.split("/")[1], cell.get("items", 0), + cell.get("agreed", 0), cell.get("single", 0), + cell.get("not_covered", 0) + cell.get("disputed", 0) + cell.get("ambiguous", 0), + cell.get("reader_a_read", 0), cell.get("reader_b_read", 0))) + + report = {"items": len(items), "geometry_consulted": bool(args.geometry), + "inventory": inventory(), "languages": languages, "pairs": by_pair, "rows": rows} + destination = Path(args.out) + destination.parent.mkdir(parents=True, exist_ok=True) + destination.write_text(json.dumps(report, indent=1, sort_keys=True) + "\n", encoding="utf-8") + print("") + print("wrote %s (%d items, geometry consulted: %s)" + % (destination, len(items), "yes" if args.geometry else "no")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/geometry_runner.py b/tools/geometry_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..bc23795b9bd7558ad559b938e11bf8b2df7f6508 --- /dev/null +++ b/tools/geometry_runner.py @@ -0,0 +1,298 @@ +#!/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()) diff --git a/tools/publish_dataset.py b/tools/publish_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..19ca2de92a184697aa995618ea1279cd4c6be10e --- /dev/null +++ b/tools/publish_dataset.py @@ -0,0 +1,361 @@ +"""Publish this folder as a dataset on the hub, and check that it arrived. + +Run from inside the folder: + + python tools/publish_dataset.py # token taken from HF_TOKEN + python tools/publish_dataset.py --token-env TOKEN # another environment variable + python tools/publish_dataset.py --plan # build the card, upload nothing + python tools/publish_dataset.py --prune # also drop files the folder no longer holds + +The folder README is the body of the dataset card. It is copied with its section numbers intact, and +five passages are rewritten because they only make sense inside a LingoLOGOS checkout: where the folder +sits, that it needs the sibling `geometry` folder, how long the suite took, what the heading of section +10 promises and what that section says about this publication. Every replacement has to match, or the +tool stops: a silent miss would publish a card that contradicts the code next to it. Four sections (11 to +14) are then added for readers who met the bundle on the hub: the fields of the corpus file, how to load +it, rights, and citation. This is where +the documentation of the published asset lives, and not in the technical documentation of the project. + +Nothing here runs during a test, and the token is never a command line argument, only the name of an +environment variable. +""" + +import argparse +import hashlib +import os +import shutil +import sys +import tempfile +from pathlib import Path +from typing import List, Tuple + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from lggeostratum import corpus # noqa: E402 (after the path fix above) + +REPO = "tailot/geometry-stratum" +EXPECTED_FILES = 68 # the staged tree: this README is uploaded as the card under the same name +EXPECTED_HUB_OBJECTS = 69 # staged tree plus the .gitattributes the hub adds by itself +EXPECTED_CORPUS_ROWS = 56 +IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git"} +FRONT_MATTER = """--- +language: + - it + - en + - es + - zh + - hi + - ar +tags: + - multilingual + - geometry + - theorem-proving + - natural-language-to-formal-language + - multi-agent-systems + - benchmark + - conversational-interfaces + - formal-verification + - semantic-parsing +pretty_name: "LingoLOGOS geometry-stratum: a question in six written varieties, the answer of the geometry layer, and an assurance that includes the reading" +configs: + - config_name: corpus + data_files: + - split: train + path: problems/corpus.jsonl +size_categories: + - n<1K +--- + +""" + +# Passages that are true in a checkout and misleading on the hub. Each pair is (here, there), and the +# first has to appear in the README of this folder. +REPLACEMENTS: List[Tuple[str, str]] = [ + ( + "The folder is `datasets/geometry-stratum`; every command below is written from inside it and needs the\n" + "sibling folder `datasets/geometry`, which stays exactly as it is. Only the standard library and\n" + "`z3-solver` are required; the tests need `pytest`.", + "This dataset is the `geometry-stratum/` folder of the LingoLOGOS project published as it stands: 68 files,\n" + "code and data together, plus this card in place of their README. Only the standard library and\n" + "`z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every\n" + "command below is written from inside the folder. The geometry layer is not part of this dataset: it\n" + "lives in the `geometry` bundle, published at\n" + "https://huggingface.co/datasets/tailot/lingologos-geometry, and section 10 says how to point this\n" + "folder at a copy of it.", + ), + ( + "## 10. Using this folder as an external dataset", + "## 10. Putting this dataset back into a LingoLOGOS checkout", + ), + ( + "The split is published: https://huggingface.co/datasets/tailot/geometry-stratum. The published snapshot is\n" + "this content: 68 files (plus the card that replaces this README on the hub), 56 questions in one corpus\n" + "file, the six lexicons, the eight node definitions, the two readers, the decision rule of section 1, the\n" + "corpus grading and fault results under `results/`, and the fault catalogue of section 6.", + "This dataset is 68 files plus this card: 56 questions in one corpus file, the six lexicons, the eight\n" + "node definitions, the two readers, the decision rule of section 1, the corpus grading and fault\n" + "results under `results/`, and the fault catalogue of section 6. To decide a figure it needs the\n" + "`geometry` bundle: download https://huggingface.co/datasets/tailot/lingologos-geometry somewhere, set\n" + "`LGSTRATUM_GEOMETRY_ROOT` to that copy, and the `invoker` node of this folder starts\n" + "`tools/geometry_runner.py`, which loads that copy in a separate process -- the only door through which\n" + "this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at\n" + "`datasets/geometry-stratum`, finds `datasets/geometry` by itself, and needs\n" + "`src/lingologos_orchestrator` importable for the two end to end sessions of section 8.", + ), + ( + "invariant tests call the solver of the geometry layer as subprocesses, and the whole suite\n" + "took 57 seconds on this checkout.", + "invariant tests call the solver of the geometry layer as subprocesses, which here means a copy of the\n" + "`geometry` dataset named by `LGSTRATUM_GEOMETRY_ROOT` (section 10); the suite took 57 seconds inside a\n" + "LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is\n" + "not importable.", + ), + ( + "Like the `geometry` folder, this folder is ignored by the git repository of the project: what the project\ncarries is the link in the table of published resources at the top of the repository README, and the\ndocumentation of the asset lives in this README and in the card, not in\n`doc/TECHNICAL_DOCUMENTATION.md`. Republishing is a separate step, never a side effect of a test run:\n`tools/publish_dataset.py` does it with the token taken from an environment variable and verifies the\ntree by sha256.", + "What the LingoLOGOS repository carries is the link to this\ndataset in the table of published resources at the top of its README; the documentation of the asset\nlives here, in this card, and not in the technical documentation of the project. Republishing is a\nseparate step, never a side effect of a test run: `tools/publish_dataset.py` in the folder of the\nproject does it with the token taken from an environment variable and verifies the tree by sha256.", + ), +] + +CARD_TAIL = """ +## 11. The corpus file + +`problems/corpus.jsonl` holds 56 questions, one JSON object per line, written and checked by a person. +It is a benchmark for the stratum: there is no prompt, no response pair and nothing to fine tune on. +Each row says what the session has to end like, including the rows whose expected outcome is a refusal +to answer, and a `why` that says why. + +| Field | Type | Meaning | +|---|---|---| +| `id` | string | unique; `-`, sometimes with a third part (`-true`, `-false`, `-single`, `-unknown`, `-def`) | +| `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in | +| `kind` | string | one of the 19 statement kinds of the geometry language, or `negative` (6 rows that must not be read) | +| `question` | string | the question, between 18 and 306 characters, in the script of its variety: a whole figure, the definitions first and the claim about them last | +| `why` | string | the reason the row behaves as it does, written by the person who wrote the row | +| `expect` | object | the expectation, described below | + +| Variety (`lang`) | `en` | `it` | `es` | `zh` | `hi` | `ar` | +|---|---|---|---|---|---|---| +| Rows | 20 | 12 | 6 | 6 | 6 | 6 | + +| Kind | Rows | Kind | Rows | Kind | Rows | +|---|---|---|---|---|---| +| `collinear` | 13 | `find_circumcircle` | 3 | `between` | 1 | +| `perp` | 6 | `find_intersect` | 3 | `assume` | 1 | +| `negative` | 6 | `centroid` | 2 | `mid` | 1 | +| `par` | 4 | `define_circle` | 2 | `intersect` | 1 | +| `find_tangents` | 4 | `oncircle` | 2 | `define_line` | 1 | +| `right` | 2 | `circumcentre` | 1 | `cong` | 1 | +| | | `find_image` | 1 | `define_point` | 1 | + +The fields of `expect` are optional except `state` and `referee_clean`, which are present on every row. + +| Field | Rows | Meaning | +|---|---|---| +| `state` | 56 | the reading state the session must end in: `AGREED` 46, `SINGLE` 3, `PASSTHROUGH` 1, `NOT COVERED` 6 | +| `sentence` | 50 | the text of the geometry language both readers have to produce, exactly: the whole figure, in the order the bundle expects it | +| `answer_contains` | 36 | a substring the answer has to contain: a sentence of the geometry layer, or the certificate of a computed answer | +| `min_assurance` | 39 | the lowest assurance that is acceptable, on the scale of section 1 | +| `max_assurance` | 20 | the highest assurance that is acceptable: this is what pins the probes that must not rise | +| `no_answer` | 17 | `true` where the row is graded by the refusal: no answer may be shown at all | +| `referee_clean` | 56 | every envelope claim of the session must match what the referee of its node recomputed | + +The six rows with no `sentence` are exactly the six negative rows, where the reading itself has to fail. +The 17 rows with `no_answer` split in two: 6 are those negative rows, and 11 are agreed readings of a +figure that carries no claim the geometry layer can decide (`point-en`, `line-en`, `circle-en`, +`circle-it`, `assume-en`, `centroid-en`, `centroid-it`, `circumcentre-en`, `intersect-en`, `image-en`, +`mid-en-def`); on those eleven the assurance must be 0 and no answer may appear, which is the stratum +refusing to add an availability it does not have. + +## 12. Loading it + +Load the file with the `datasets` library, or with one `json.loads` per line, which needs no +dependency: + +```python +from datasets import load_dataset +rows = load_dataset("tailot/geometry-stratum", "corpus", split="train") +print(rows[0]) +``` + +This is the same file `tools/ask.py --corpus` walks over, and `lggeostratum/corpus.py` plus +`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 56 of 56 +rows agree with what they expect. + +## 13. Rights + +No license is declared for this dataset, its lexicons, its corpus or its code: reuse is not granted by +this page. The six lexicons, the 56 questions with their gold expectations, the grammar specifications, +the node data and the Python sources were written by hand as part of the LingoLOGOS project. Ask before +redistributing or building on them, and expect the answer to be yes for academic work with attribution. +Z3 is a separate product with its own license and is not redistributed here; `z3-solver` is only named +as a dependency in `requirements.txt`. The lexicons of Hindi, Arabic and Chinese describe written +varieties as this project needs them for questions about a figure drawn in words: they are not a general +purpose dictionary of those languages. + +## 14. Citation + +``` +@misc{lingologos_geometry_stratum, + title = {LingoLOGOS geometry-stratum: a question in six written varieties, the answer of the geometry layer, and an assurance that includes the reading}, + author = {LingoLOGOS project}, + year = {2026}, + url = {https://huggingface.co/datasets/tailot/geometry-stratum}, + note = {bundle of the geometry-stratum folder of the LingoLOGOS repository: 56 questions about a + figure drawn in words, in six written varieties, over the 19 statement kinds of the geometry + language, with six lexicons, two independent readers, eight node definitions with SMT claims, + the assurance rule min(geometry, reading) with the reading capped at 2, fault catalogue and + ablation over the node configurations, 255 tests} +} +``` +""" + + +def local_files() -> List[Path]: + """The files of this folder that go to the hub, caches and inner git history excluded. + + Whole path components named `.git`, `__pycache__` or `.pytest_cache` are cut at any depth, which is + what keeps the compiled copies of the modules out of the published tree. A file whose own name + starts with an underscore is working notes and is not published either, with one exception: + `lggeostratum/__init__.py`, the package marker, shares that prefix by the convention of Python rather + than by being a note, and dropping it would publish a tree whose library cannot be imported as a + package. A file named `.gitignore` is content for the same reason. + """ + out: List[Path] = [] + for path in sorted(ROOT.rglob("*")): + if not path.is_file(): + continue + relative = path.relative_to(ROOT) + if IGNORED_DIRS & set(relative.parts): + continue + if ".git" in relative.parts: + continue + if path.name.startswith("_") and not (path.name == "__init__.py" and path.parent.name == "lggeostratum"): + continue + out.append(path) + return out + + +def build_card() -> str: + """The README of this folder with the checkout-only passages rewritten for the hub.""" + text = (ROOT / "README.md").read_text(encoding="utf-8").replace("\r\n", "\n") + for here, there in REPLACEMENTS: + if here not in text: + raise SystemExit("card replacement not found in README.md: %r" % here[:70]) + text = text.replace(here, there, 1) + return FRONT_MATTER + text.rstrip() + "\n" + CARD_TAIL + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with open(path, "rb") as handle: + for block in iter(lambda: handle.read(65536), b""): + digest.update(block) + return digest.hexdigest() + + +def stage(card: str) -> Path: + """A copy of the tree to upload, with the README replaced by the card. + + The tree that lands on the hub has the same number of files as this folder does, because the card + replaces this README instead of being added to it; the hub adds its own `.gitattributes`, which is + why the remote count is one above the number of staged files. + """ + staging = Path(tempfile.mkdtemp(prefix="lingologos_geometry_stratum_")) + for path in local_files(): + target = staging / path.relative_to(ROOT) + target.parent.mkdir(parents=True, exist_ok=True) + shutil.copy2(path, target) + (staging / "README.md").write_text(card, encoding="utf-8", newline="\n") + return staging + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--repo", default=REPO) + parser.add_argument("--token-env", default="HF_TOKEN", help="environment variable holding the token") + parser.add_argument("--message", default="update geometry-stratum bundle", help="commit message, five words or fewer") + parser.add_argument("--plan", action="store_true", help="build the card and report, upload nothing") + parser.add_argument("--prune", action="store_true", + help="also delete hub files that this folder no longer holds") + args = parser.parse_args() + + files = local_files() + rows = len(corpus.load(str(ROOT / "problems" / "corpus.jsonl"))) + print("files that will be uploaded: %d (this README is uploaded as the card)" % len(files)) + print("corpus rows: %d" % rows) + if (len(files), rows) != (EXPECTED_FILES, EXPECTED_CORPUS_ROWS): + print("UNEXPECTED: expected %d files and %d rows" % (EXPECTED_FILES, EXPECTED_CORPUS_ROWS)) + return 1 + + card = build_card() + print("card: %d bytes" % len(card.encode("utf-8"))) + if args.plan: + preview = Path(tempfile.gettempdir()) / "lingologos_geometry_stratum_card.md" + preview.write_text(card, encoding="utf-8", newline="\n") + print("card written to %s, nothing uploaded" % preview) + return 0 + + token = os.environ.get(args.token_env, "") + if not token: + print("no token in %s" % args.token_env) + return 1 + from huggingface_hub import HfApi + + api = HfApi(token=token) + who = api.whoami(token) + print("uploading as %s" % who.get("name", "?")) + staging = stage(card) + staging_card = Path(staging) / "README.md" + remote: List[str] = [] + missing: List[str] = [] + extra: List[str] = [] + differ: List[str] = [] + try: + api.upload_folder( + repo_id=args.repo, + repo_type="dataset", + folder_path=str(staging), + commit_message=args.message, + ) + remote = api.list_repo_files(args.repo, repo_type="dataset") + print("objects on the hub: %d" % len(remote)) + expected_names = {str(path.relative_to(ROOT)).replace("\\", "/") for path in files} + missing = sorted(expected_names - set(remote)) + extra = sorted(set(remote) - expected_names - {".gitattributes"}) + print("missing: %d %s" % (len(missing), missing[:6])) + print("unexpected: %d %s" % (len(extra), extra[:6])) + + cache = tempfile.mkdtemp(prefix="lingologos_geometry_stratum_check_") + for path in files: + relative = str(path.relative_to(ROOT)).replace("\\", "/") + # The staged copy of the README is the card, so it is compared against what was just uploaded: + # a silent skip would leave the most read file of the dataset unverified. + local = staging_card if relative == "README.md" else path + downloaded = api.hf_hub_download(args.repo, filename=relative, repo_type="dataset", cache_dir=cache) + if sha256(Path(downloaded)) != sha256(local): + differ.append(relative) + shutil.rmtree(cache, ignore_errors=True) + print("files compared by sha256: %d (the card among them: 1), differing: %d %s" + % (len(files), len(differ), differ[:6])) + + if extra and args.prune: + api.delete_files(repo_id=args.repo, repo_type="dataset", delete_patterns=extra, + commit_message="drop removed files") + remote = api.list_repo_files(args.repo, repo_type="dataset") + expected_names = {str(path.relative_to(ROOT)).replace("\\", "/") for path in files} + missing = sorted(expected_names - set(remote)) + extra = sorted(set(remote) - expected_names - {".gitattributes"}) + print("after the removal: %d objects, missing %d, unexpected %d" + % (len(remote), len(missing), len(extra))) + finally: + shutil.rmtree(staging, ignore_errors=True) + + ok = (len(remote) == EXPECTED_HUB_OBJECTS and not missing and not extra and not differ) + print("RESULT: %s" % ("ok" if ok else "check the numbers above")) + print("https://huggingface.co/datasets/%s" % args.repo) + return 0 if ok else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/topology.json b/topology.json new file mode 100644 index 0000000000000000000000000000000000000000..0f5c3b372b46ef86a6f311b23600905de506e5f4 --- /dev/null +++ b/topology.json @@ -0,0 +1,98 @@ +{ + "$schema": "https://lingologos.spec/schemas/topology-v1.json", + "sessionId": "lingologos-geometry-stratum-01", + "maxTurns": 8, + "terminationCondition": "FIXED_PIPELINE", + "instances": [ + { + "id": "reader_a", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "reader_a" + }, + { + "id": "reader_b", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "reader_b" + }, + { + "id": "equivalence", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "equivalence" + }, + { + "id": "coverage", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "coverage" + }, + { + "id": "invoker", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "invoker" + }, + { + "id": "boundary", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "boundary" + }, + { + "id": "adversary", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "adversary" + }, + { + "id": "arbiter", + "executable": "geometry-stratum/agents/stratum_agent", + "role": "arbiter" + } + ], + "routingMatrix": [ + { + "from": "reader_a", + "to": [ + "arbiter" + ] + }, + { + "from": "reader_b", + "to": [ + "reader_a" + ] + }, + { + "from": "equivalence", + "to": [ + "reader_b" + ] + }, + { + "from": "coverage", + "to": [ + "equivalence" + ] + }, + { + "from": "invoker", + "to": [ + "coverage" + ] + }, + { + "from": "boundary", + "to": [ + "invoker" + ] + }, + { + "from": "adversary", + "to": [ + "boundary" + ] + }, + { + "from": "arbiter", + "to": [ + "adversary" + ] + } + ] +}