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..61f38c1889999fd6fd3d970f663964a141a6609b --- /dev/null +++ b/README.md @@ -0,0 +1,346 @@ +--- +language: + - it + - en + - es + - zh + - hi + - ar +tags: + - multilingual + - mathematical-word-problems + - natural-language-to-formal-language + - multi-agent-systems + - benchmark + - conversational-interfaces + - formal-verification + - semantic-parsing +pretty_name: "LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading" +configs: + - config_name: corpus + data_files: + - split: train + path: problems/corpus.jsonl +size_categories: + - n<1K +--- + +# LingoLOGOS math-stratum topology + +A conversational layer over the `math` topology: a person asks in one of six written varieties, and +gets the answer of the math stratum back in that same language, at an assurance that includes the +fallibility of the reading. The layer never decides a problem and never raises a verdict; the only +direction it can move the assurance of the math stratum is down. + +``` +python tools/ask.py --lang it "risolvi x^2 - 5*x + 6 = 0 per x" +Reading state : AGREED +Assurance shown : 2 (reading ceiling 2, math assurance 3) +Math layer status : VERIFIED +Orchestrator Z3 check : 8 of 8 envelopes confirmed + +Answer in the language of the question (italiano): + Stato: accordata: due lettori indipendenti piu il vincolo SMT + Problema capito (solve): solve x^2-5*x+6=0 for x + Risposta: {2, 3} + livello 2 di 3 + strato matematico: VERIFIED + Controllo SMT dello strato : 8 di 8 buste confermate +``` + +This dataset is the `math-stratum/` folder of the LingoLOGOS project published as it stands: 67 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 mathematics is not part of this dataset: it lives +in the `math` bundle, published at https://huggingface.co/datasets/tailot/lingologos-math, 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 math stratum, ceiling of the reading) +``` + +| Reading state | ceiling | when | +|---|---|---| +| `AGREED` | 2 | both readers produced the same sentence, and the math stratum is what decides it | +| `PASSTHROUGH` | 2 | the question was already a sentence of the math 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 math stratum is not even asked | +| `AMBIGUOUS` | 0 | a reader reports that the question announces more than one problem, 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 math stratum says it solved something other than the agreed sentence | + +Three is never shown. Level three belongs to the math stratum, whose two formalizers and two +checkers work on a sentence they wrote themselves; 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: a reading that no longer holds the numbers the person wrote is a different problem, 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 `math` 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 math language | the same, independently | +| `equivalence` | proves the two sentences the same, slot by slot and then 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 math stratum, in a separate process, the agreed sentence | the sentence I sent equals the one that came back | +| `boundary` | checks the echo of the math stratum 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 | + +## 3. Two readers, one lexicon + +`read_a.py` matches the shapes stored in `lexicon/.json` (`patterns`: one template per kind of +problem, with slots). `read_b.py` never looks at those shapes: it finds the verb that announces a +problem, then walks the joints of the math language (`for`, `over Z`, `from ... to`, `subject to`, +`wrt`) and cuts the slots out of the gaps between them. They share only the lexicon, the atomizer +(`segment.py`) and the templates of the math language (`canonical.py`). + +That sharing 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 math stratum. + +## 4. Talking to the math stratum + +`invoker.py` is the only door. It launches `python /tools/solve.py --json ` as a +separate process and reads its JSON verdict back; nothing in this folder imports the solver of the +math stratum to decide anything here. The referee then checks the echo: the sentence the math stratum +says it solved has to be the sentence the readers agreed on, otherwise the session is `TAMPERED`. + +| Variable | Meaning | +|---|---| +| `LGSTRATUM_MATH_ROOT` | where the `math` bundle is (default: the sibling folder `datasets/math`) | +| `LGSTRATUM_MATH_BACKEND` | `subprocess` (default), or `none` to disable the math layer entirely | +| `LGSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only | + +A disabled math layer is not tampering: the reading stands, the assurance falls to zero because there +is no math assurance to take the minimum with, and no answer is shown. + +## 5. The corpus + +`problems/corpus.jsonl` holds 73 questions: 12 kinds of problem in 6 varieties, plus items that mix +varieties, full width digits, unspelled matrices, gibberish, questions with an empty slot and +questions whose mathematics is out of reach of the math stratum. 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: **73 of 73** rows agree with their gold (`lgstratum/corpus.py` +grades one row, `tests/test_corpus.py` runs all of them). With the math layer switched off the states +come out 57 `AGREED`, 2 `SINGLE`, 11 `NOT COVERED`, 3 `PASSTHROUGH`; `tools/coverage_report.py` writes +`results/coverage.json` and counts **57** questions read by both readers, **2** by `reader_a` alone and +**14** by neither. Seven rows (`it-13`, `en-11`, `en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`) are agreed +readings on which the math stratum abstains: assurance 0 and no answer, which is the layer refusing to +add an availability it does not have. Two rows (`hi-05`, `hi-10`) stay at `SINGLE`, assurance 1, for the +reason in section 7. + +## 6. Commands + +``` +python tools/ask.py --lang it "quanto fa 2+2?" # one session, eight processes +python tools/ask.py --lang en --json "solve x + 1 = 2 for x" +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 12 --out results/ablation.json +``` + +`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 **510** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 0`, +`caught 18`, `abstained 366`, `masked 126` -- about fifteen minutes. Nothing was ever raised above the +honest assurance, and the 18 `caught` cells all sit in the configuration without `reader_b`, where a +rubber stamped verification node cannot buy back the level the missing witness costs. + +## 7. Limits that are written down, not hidden + +* Two varieties place their joints after the slot instead of before it. `reader_b` cannot cut the + slots there, so those questions are read by one reader only and stay at `SINGLE`, assurance 1 + (`hi-05`, `hi-10`). `tools/coverage_report.py` shows them as one of two readers. +* A missing written accent can collide with a connective: `qual e il determinante di ...` is not read, + because the folded copula is the same atom as the conjunction `e`. +* The fragment of the math stratum is unchanged here: powers inside integer terms and non linear + programs end in `UNKNOWN`, so the assurance is zero even when the reading is agreed. The corpus + keeps those questions as probes (`it-13`, `en-11`, `en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`). +* 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. + +## 8. Tests + +From the repository root: + +``` +python -m pytest -q datasets/math-stratum/tests +``` + +The suite is **290** tests: 121 on the two readers against every row of the corpus, 79 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, 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 math stratum does not move, and +that nothing is ever shown above it. `tests/test_orchestrator_e2e.py` runs two real sessions through +the orchestrator and is skipped when `lingologos_orchestrator` is not importable. The corpus and the +invariant tests call the solver of the math stratum as subprocesses, which here means a copy of the +`math` dataset named by `LGSTRATUM_MATH_ROOT` (section 10); the suite took 3 minutes 52 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: `risolvi x^2 - 5*x + 6 = 0 per x` comes back `AGREED` at assurance 2 against a +math assurance of 3, with **8 of 8** envelope claims confirmed by the referee of the session, and +`python tools/ask.py --corpus problems/corpus.jsonl --limit 8` grades **8 of 8** real sessions against +gold. One question per variety outside Italian (`zh-01`, `ar-01`, `hi-03`, `es-02`) comes back the same +way: `AGREED`, assurance 2, the math stratum `VERIFIED`, 8 of 8 claims confirmed, nothing detected -- +and the block the person reads is written in the language of the question (48, 97 and 104 non-ASCII +characters in the Chinese, Arabic and Hindi replies). + +A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that +`lgmath` may be imported for its SMT plumbing by `lgstratum/compare.py` alone. + +## 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 67 files plus this card: 73 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 run the mathematics it needs the `math` +bundle: download https://huggingface.co/datasets/tailot/lingologos-math somewhere, set +`LGSTRATUM_MATH_ROOT` to that copy, and the `invoker` node calls `tools/solve.py` there as a separate +process, which is the only door through which this bundle ever reaches a solver. Inside a LingoLOGOS +checkout the folder sits at `datasets/math-stratum`, finds `datasets/math` 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 but this README was compared by sha256 after the upload: 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. `tools/publish_dataset.py` +in the folder of the project republishes a changed working copy with the token taken from an environment +variable. Republishing is a separate step, never a side effect of a +test run: `tools/publish_dataset.py` does it with the token taken from an environment variable and +verifies the tree by sha256. + +## 11. The corpus file + +`problems/corpus.jsonl` holds 73 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; the prefix names the variety (`it`, `en`, `es`, `zh`, `hi`, `ar`), or `mixed` on the 5 rows that mix varieties, write digits in full width form or are gibberish | +| `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in | +| `kind` | string | one of the 12 problem kinds, or `negative` (14 rows that must not be read) or `passthrough` (2 rows already written in the math language) | +| `question` | string | the question, between 5 and 53 characters, in the script of its variety | +| `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`) | Rows | Id prefix | Rows | Kind | Rows | +|---|---|---|---|---|---| +| `it` | 13 | `it` | 13 | `evaluate` | 7 | +| `en` | 13 | `en` | 12 | `solve` | 6 | +| `es` | 10 | `es` | 9 | `solvez` | 3 | +| `zh` | 12 | `zh` | 11 | `prove` | 5 | +| `hi` | 12 | `hi` | 11 | `provez` | 8 | +| `ar` | 13 | `ar` | 12 | `derivative` | 4 | +| mixed rows | 5 | `mixed` | 5 | `integral` | 5 | +| | | | | `det`, `rank` | 3, 3 | +| | | | | `inverse` | 4 | +| | | | | `maximize`, `minimize` | 3, 6 | +| | | | | `negative` | 14 | +| | | | | `passthrough` | 2 | + +The fields of `expect` are optional except `referee_clean`, which is present on every row. + +| Field | Rows | Meaning | +|---|---|---| +| `state` | 65 | the reading state the session must end in: `AGREED` 55, `PASSTHROUGH` 3, `SINGLE` 2, `NOT COVERED` 5 | +| `sentence` | 60 | the sentence of the math language both readers have to produce, exactly | +| `answer_contains` | 29 | a substring the answer has to contain, exact rationals written as strings | +| `min_assurance` | 51 | the lowest assurance that is acceptable, on the scale of section 1 | +| `max_assurance` | 22 | the highest assurance that is acceptable: this is what pins the probes that must not rise | +| `no_answer` | 15 | `true` where the row is graded by the refusal: no answer may be shown at all | +| `referee_clean` | 73 | every envelope claim of the session must match what the referee of its node recomputed | + +The eight rows with no `state` are graded on an assurance or on an answer instead: they check that the +reading holds while the math stratum abstains, so the assurance must be 0 and no answer may appear. +Seven of them are the agreed readings on which the mathematics is out of reach (`it-13`, `en-11`, +`en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`), 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/math-stratum", "corpus", split="train") +print(rows[0]) +``` + +This is the same file `tools/ask.py --corpus` walks over, and `lgstratum/corpus.py` plus +`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 73 of 73 +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 73 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 arithmetic questions: they are not a general purpose +dictionary of those languages. + +## 14. Citation + +``` +@misc{lingologos_math_stratum, + title = {LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading}, + author = {LingoLOGOS project}, + year = {2026}, + url = {https://huggingface.co/datasets/tailot/math-stratum}, + note = {bundle of the math-stratum folder of the LingoLOGOS repository: 73 questions in six written + varieties, six lexicons, two independent readers, eight node definitions with SMT claims, the + assurance rule min(math, reading) with the reading capped at 2, fault catalogue and ablation + over the node configurations, 290 tests} +} +``` diff --git a/agents/stratum_agent b/agents/stratum_agent new file mode 100644 index 0000000000000000000000000000000000000000..e214edc29cc19913e33e2889e4d931eace8b8ba2 --- /dev/null +++ b/agents/stratum_agent @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Node executable of the math-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 math 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 math 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 lgstratum import agents, faults # noqa: E402 + + +def main() -> int: + parser = argparse.ArgumentParser(description="Math-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..3b27deb444e9b6cb24b0fc910329d6ca3f55e6f4 --- /dev/null +++ b/lexicon/ar.json @@ -0,0 +1,142 @@ +{ + "lang": "ar", + "name": "العربية", + "script": "arabic", + "noise_chars": "", + "prefixes": ["ال", "وال", "بال", "فال", "لل", "و", "ب", "ل", "ف"], + "kinds": { + "evaluate": { + "verbs": ["احسب", "حساب", "قيمة", "كم قيمة"], + "neutral": true, + "patterns": ["احسب {T}", "احسب قيمة {T}", "كم قيمة {T}", "ما قيمة {T}"], + "frame": {"sequences": [[]]} + }, + "prove": { + "verbs": ["أثبت", "إثبات", "برهن"], + "patterns": ["أثبت أن {F}", "أثبت {F}", "برهن أن {F}", "برهن {F}"], + "frame": {"sequences": [[]]} + }, + "provez": { + "verbs": ["أثبت", "إثبات", "برهن"], + "patterns": ["أثبت أن {F} في أعداد صحيحة", "برهن أن {F} في أعداد صحيحة", "أثبت {F} على أعداد صحيحة"], + "frame": {"sequences": [["over_z"]]} + }, + "solve": { + "verbs": ["حل", "أوجد"], + "patterns": ["حل {F} إيجاد {V}", "حل {F} نسبة إلى {V}"], + "frame": {"sequences": [["for"], ["wrt"]]} + }, + "solvez": { + "verbs": ["حل", "أوجد"], + "patterns": ["حل {F} إيجاد {V} في أعداد صحيحة", "حل {F} نسبة إلى {V} في أعداد صحيحة"], + "frame": {"sequences": [["for", "over_z"]]} + }, + "derivative": { + "verbs": ["مشتقة", "اشتقاق", "اشتق"], + "patterns": ["مشتقة {T}", "احسب مشتقة {T}", "مشتقة {T} نسبة إلى {V}", "اشتق {T} نسبة إلى {V}"], + "frame": {"sequences": [[], ["wrt"]]} + }, + "integral": { + "verbs": ["تكامل"], + "patterns": ["تكامل {T} من {A} إلى {B}", "احسب تكامل {T} من {A} إلى {B}", "تكامل {T} من {A} إلى {B} نسبة إلى {V}", "تكامل {T} نسبة إلى {V} من {A} إلى {B}"], + "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]} + }, + "det": { + "verbs": ["محدد"], + "patterns": ["محدد {M}", "احسب محدد {M}", "احسب محدد مصفوفة {M}"], + "frame": {"sequences": [[]]} + }, + "rank": { + "verbs": ["رتبة"], + "patterns": ["رتبة {M}", "احسب رتبة {M}"], + "frame": {"sequences": [[]]} + }, + "inverse": { + "verbs": ["معاكسة"], + "patterns": ["معاكسة {M}", "احسب معاكسة {M}", "احسب معاكسة مصفوفة {M}"], + "frame": {"sequences": [[]]} + }, + "maximize": { + "verbs": ["عظم", "تعظيم", "عظمى"], + "patterns": ["عظم {T} شرط {F}", "عظم {T} تحت قيود {F}"], + "frame": {"sequences": [["subject_to"]]} + }, + "minimize": { + "verbs": ["صغر", "تصغير", "صغرى"], + "patterns": ["صغر {T} شرط {F}", "صغر {T} تحت قيود {F}"], + "frame": {"sequences": [["subject_to"]]} + } + }, + "connectives": { + "and": ["و"], + "or": ["أو"], + "not": ["ليس"], + "ge": ["على أقل", "لا يقل عن", "أكبر من أو يساوي"], + "le": ["على أكثر", "لا يزيد عن", "أصغر من أو يساوي"], + "gt": ["أكبر من", "أكثر من"], + "lt": ["أصغر من", "أقل من"], + "eq": ["يساوي", "يعادل"], + "ne": ["لا يساوي", "مختلف عن"] + }, + "markers": { + "for": ["إيجاد"], + "over_z": ["في أعداد صحيحة", "على أعداد صحيحة", "في مجموعة أعداد صحيحة"], + "subject_to": ["شرط", "تحت قيود", "في ظل قيود"], + "from": ["من"], + "to": ["إلى"], + "wrt": ["نسبة إلى"] + }, + "noise": ["ما", "أن", "كم", "هو", "هي", "هذه", "ذلك", "رجاء", "مصفوفة"], + "labels": { + "understood": "المسألة كما فهمناها", + "status": "الحالة", + "assurance": "المستوى {n} من 3", + "answer": "الجواب", + "reading": "القراءة", + "math_layer": "الطبقة الرياضية", + "notes": "ملاحظات", + "examples": "جمل تفهمها هذه الطبقة", + "question": "أعد صياغة السؤال بإحدى هذه الصيغ", + "check": "فحص SMT للطبقة : {a} من {b} مغلف مؤكد", + "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_variable": "{slot} ليست متغيرا واحدا من متغيرات لغة الرياضيات", + "bad_matrix": "{slot} ليست مصفوفة مكتوبة بين قوسين مربعين مزدوجين", + "unbalanced": "قوس أو قوس مربع غير مغلق", + "no_math": "الجزء الرياضي غير مكتوب برموز لغة الرياضيات", + "literal_count": "أعداد الجملة ليست هي نفسها عند القارئين", + "math_unknown": "الطبقة الرياضية لا تقبل الجملة: {detail}", + "boundary": "الجملة المرسلة إلى الطبقة الرياضية ليست هي المتفق عليها", + "referee": "الحكم SMT لا يؤكد {detail}", + "domain_letter": "اكتب المجال بالكلمات (مثلا: في الأعداد الصحيحة) لا بحرف مفرد", + "other": "لم تصل القراءة إلى جملة بلغة الرياضيات" + }, + "examples": [ + "احسب ١/٢ + ١/٣", + "أثبت أن x^٢ + ١ > ٠", + "حل x^٢ - ٥*x + ٦ = ٠ إيجاد x", + "احسب محدد المصفوفة [[١, ٢], [٣, ٤]]", + "تكامل ٣*x^٢ من ٠ إلى ٢", + "حل n mod ٣ = ١ لإيجاد n في الأعداد الصحيحة", + "عظم ٣*x + ٤*y شرط x + y <= ١٠" + ] +} diff --git a/lexicon/en.json b/lexicon/en.json new file mode 100644 index 0000000000000000000000000000000000000000..1664486f03e7eabb6c488e5589c10fd9ec5dedea --- /dev/null +++ b/lexicon/en.json @@ -0,0 +1,142 @@ +{ + "lang": "en", + "name": "English", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "evaluate": { + "verbs": ["evaluate", "compute", "calculate", "what is", "value"], + "neutral": true, + "patterns": ["evaluate {T}", "compute {T}", "calculate {T}", "what is {T}", "what is the value of {T}", "the value of {T}"], + "frame": {"sequences": [[]]} + }, + "prove": { + "verbs": ["prove", "show", "verify"], + "patterns": ["prove that {F}", "prove {F}", "show that {F}", "verify that {F}"], + "frame": {"sequences": [[]]} + }, + "provez": { + "verbs": ["prove", "show", "verify"], + "patterns": ["prove that {F} over the integers", "prove {F} over the integers", "show that {F} over the integers"], + "frame": {"sequences": [["over_z"]]} + }, + "solve": { + "verbs": ["solve", "find"], + "patterns": ["solve {F} for {V}", "for {V} solve {F}", "solve {F} with respect to {V}"], + "frame": {"sequences": [["for"], ["wrt"]]} + }, + "solvez": { + "verbs": ["solve", "find"], + "patterns": ["solve {F} for {V} over the integers", "solve {F} for {V} over the set of integers"], + "frame": {"sequences": [["for", "over_z"]]} + }, + "derivative": { + "verbs": ["derivative", "differentiate"], + "patterns": ["the derivative of {T}", "derivative of {T}", "differentiate {T}", "the derivative of {T} with respect to {V}", "differentiate {T} with respect to {V}"], + "frame": {"sequences": [[], ["wrt"]]} + }, + "integral": { + "verbs": ["integral", "integrate"], + "patterns": ["the integral of {T} from {A} to {B}", "integrate {T} from {A} to {B}", "compute the integral of {T} from {A} to {B}", "integrate {T} from {A} to {B} with respect to {V}"], + "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]} + }, + "det": { + "verbs": ["determinant", "det"], + "patterns": ["the determinant of {M}", "determinant of {M}", "det {M}", "what is the determinant of {M}"], + "frame": {"sequences": [[]]} + }, + "rank": { + "verbs": ["rank"], + "patterns": ["the rank of {M}", "rank of {M}", "what is the rank of {M}"], + "frame": {"sequences": [[]]} + }, + "inverse": { + "verbs": ["inverse", "invert"], + "patterns": ["the inverse of {M}", "inverse of {M}", "invert {M}", "what is the inverse of {M}"], + "frame": {"sequences": [[]]} + }, + "maximize": { + "verbs": ["maximize", "maximum"], + "patterns": ["maximize {T} subject to {F}", "maximize {T} under the constraints {F}", "the maximum of {T} subject to {F}"], + "frame": {"sequences": [["subject_to"]]} + }, + "minimize": { + "verbs": ["minimize", "minimum"], + "patterns": ["minimize {T} subject to {F}", "minimize {T} under the constraints {F}", "the minimum of {T} subject to {F}"], + "frame": {"sequences": [["subject_to"]]} + } + }, + "connectives": { + "and": ["and"], + "or": ["or"], + "not": ["not"], + "ge": ["at least", "greater than or equal to", "no less than"], + "le": ["at most", "less than or equal to", "no more than"], + "gt": ["greater than", "more than", "strictly greater than"], + "lt": ["less than", "fewer than", "strictly less than"], + "eq": ["equal to", "equals"], + "ne": ["not equal to", "different from", "distinct from"] + }, + "markers": { + "for": ["for"], + "over_z": ["over the integers", "over the set of integers", "on the integers"], + "subject_to": ["subject to", "under the constraints", "given the constraints"], + "from": ["from"], + "to": ["to"], + "wrt": ["wrt", "with respect to"] + }, + "noise": ["the", "a", "an", "of", "is", "are", "what", "please", "tell", "me", "us", "that", "this", "it", "does"], + "labels": { + "understood": "Problem as understood", + "status": "Status", + "assurance": "level {n} of 3", + "answer": "Answer", + "reading": "Reading", + "math_layer": "math layer", + "notes": "Notes", + "examples": "Sentences this layer understands", + "question": "Ask again in one of these forms", + "check": "SMT check of the layer : {a} of {b} envelopes confirmed", + "kind_of": "kind" + }, + "reading": { + "AGREED": "agreed: two independent readers plus the SMT constraint", + "PASSTHROUGH": "sentence already written in the math language, not translated", + "DISPUTED": "disputed: the two readers propose different sentences", + "NOT COVERED": "outside what this language variety covers", + "AMBIGUOUS": "ambiguous: more than one reading is possible", + "TAMPERED": "tampered: the sentence sent to the math layer is not the agreed reading", + "SINGLE": "a single reading: the other reader did not recognise the sentence", + "NONE": "no reading" + }, + "reasons": { + "unknown_word": "the word {word} is not one of the words this English covers", + "no_verb": "no word announces the kind of problem in this English", + "two_verbs": "the sentence announces more than one kind of problem: {kinds}", + "no_pattern": "the shape of the sentence matches no shape this English covers", + "no_frame": "the connectives do not match any shape of the kind {kind}", + "multiple": "the sentence has two different readings: {first} and {second}", + "disagree": "the two readers propose two different sentences of the math language", + "markers": "the connectives of the sentence are not the ones the kind expects", + "bad_variable": "{slot} is not a single variable of the math language", + "bad_matrix": "{slot} is not a matrix written between double square brackets", + "unbalanced": "a bracket or a square bracket is not closed", + "no_math": "the mathematics is not written with the symbols of the math language", + "literal_count": "the numbers of the sentence are not the same in the two readers", + "math_unknown": "the math layer does not accept the sentence: {detail}", + "boundary": "the sentence sent to the math layer is not the agreed one", + "referee": "the SMT referee does not confirm {detail}", + "domain_letter": "write the domain in words (for example: over the integers), not as a lone letter", + "other": "the reading did not reach a sentence of the math language" + }, + "examples": [ + "evaluate 1/2 + 1/3", + "prove that x^2 + 1 > 0", + "solve x^2 - 5*x + 6 = 0 for x", + "what is the determinant of [[1, 2], [3, 4]]", + "integrate 3*x^2 from 0 to 2", + "solve n mod 3 = 1 for n over the integers", + "maximize 3*x + 4*y subject to x + y <= 10" + ] +} diff --git a/lexicon/es.json b/lexicon/es.json new file mode 100644 index 0000000000000000000000000000000000000000..86b34102eb8ec6381d94b1df0a618f6426f922c1 --- /dev/null +++ b/lexicon/es.json @@ -0,0 +1,142 @@ +{ + "lang": "es", + "name": "español", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "evaluate": { + "verbs": ["calcula", "calcular", "evalúa", "cuánto vale", "valor"], + "neutral": true, + "patterns": ["calcula {T}", "calcula el valor de {T}", "cuánto vale {T}", "evalúa {T}", "el valor de {T}"], + "frame": {"sequences": [[]]} + }, + "prove": { + "verbs": ["demuestra", "demuestra que", "prueba", "prueba que", "verifica"], + "patterns": ["demuestra que {F}", "demuestra {F}", "prueba que {F}", "verifica que {F}"], + "frame": {"sequences": [[]]} + }, + "provez": { + "verbs": ["demuestra", "prueba", "verifica"], + "patterns": ["demuestra que {F} sobre los enteros", "prueba que {F} en los números enteros", "demuestra {F} sobre los enteros"], + "frame": {"sequences": [["over_z"]]} + }, + "solve": { + "verbs": ["resuelve", "resolver", "halla"], + "patterns": ["resuelve {F} para {V}", "para {V} resuelve {F}", "resuelve {F} con respecto a {V}"], + "frame": {"sequences": [["for"], ["wrt"]]} + }, + "solvez": { + "verbs": ["resuelve", "halla"], + "patterns": ["resuelve {F} para {V} sobre los enteros", "resuelve {F} para {V} en los números enteros"], + "frame": {"sequences": [["for", "over_z"]]} + }, + "derivative": { + "verbs": ["derivada", "deriva", "derivar"], + "patterns": ["la derivada de {T}", "derivada de {T}", "derivada de {T} con respecto a {V}", "deriva {T}", "calcula la derivada de {T}", "deriva {T} con respecto a {V}"], + "frame": {"sequences": [[], ["wrt"]]} + }, + "integral": { + "verbs": ["integral", "integra", "integrar"], + "patterns": ["la integral de {T} desde {A} hasta {B}", "integra {T} desde {A} hasta {B}", "calcula la integral de {T} desde {A} hasta {B}", "integra {T} desde {A} hasta {B} con respecto a {V}"], + "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"]]} + }, + "det": { + "verbs": ["determinante", "det"], + "patterns": ["el determinante de {M}", "determinante de {M}", "det {M}"], + "frame": {"sequences": [[]]} + }, + "rank": { + "verbs": ["rango"], + "patterns": ["el rango de {M}", "rango de {M}"], + "frame": {"sequences": [[]]} + }, + "inverse": { + "verbs": ["inversa", "invertir", "invierte"], + "patterns": ["la inversa de {M}", "inversa de {M}", "la matriz inversa de {M}", "invierte {M}"], + "frame": {"sequences": [[]]} + }, + "maximize": { + "verbs": ["maximiza", "máximo"], + "patterns": ["maximiza {T} sujeto a {F}", "maximiza {T} bajo las restricciones {F}", "el máximo de {T} sujeto a {F}"], + "frame": {"sequences": [["subject_to"]]} + }, + "minimize": { + "verbs": ["minimiza", "mínimo"], + "patterns": ["minimiza {T} sujeto a {F}", "minimiza {T} bajo las restricciones {F}", "el mínimo de {T} sujeto a {F}"], + "frame": {"sequences": [["subject_to"]]} + } + }, + "connectives": { + "and": ["y"], + "or": ["o"], + "not": ["no"], + "ge": ["al menos", "mayor o igual que", "no menor que"], + "le": ["a lo sumo", "como máximo", "menor o igual que", "no mayor que"], + "gt": ["mayor que", "estrictamente mayor que"], + "lt": ["menor que", "estrictamente menor que"], + "eq": ["igual a", "es igual a"], + "ne": ["distinto de", "diferente de"] + }, + "markers": { + "for": ["para"], + "over_z": ["sobre los enteros", "en los números enteros", "sobre el conjunto de los enteros"], + "subject_to": ["sujeto a", "sujeta a", "bajo las restricciones"], + "from": ["desde"], + "to": ["hasta"], + "wrt": ["respecto a", "con respecto a"] + }, + "noise": ["el", "la", "los", "las", "un", "una", "de", "del", "que", "en", "es", "cuánto", "por", "favor", "dime", "nos", "está"], + "labels": { + "understood": "Problema entendido", + "status": "Estado", + "assurance": "nivel {n} de 3", + "answer": "Respuesta", + "reading": "Lectura", + "math_layer": "capa matemática", + "notes": "Notas", + "examples": "Frases que esta capa entiende", + "question": "Vuelve a preguntar en una de estas formas", + "check": "Comprobación SMT de la capa : {a} de {b} sobres confirmados", + "kind_of": "tipo" + }, + "reading": { + "AGREED": "acordada: dos lectores independientes más la restricción SMT", + "PASSTHROUGH": "frase ya escrita en el lenguaje matemático, no traducida", + "DISPUTED": "en disputa: los dos lectores proponen frases distintas", + "NOT COVERED": "fuera de lo que esta variedad cubre", + "AMBIGUOUS": "ambigua: hay más de una lectura posible", + "SINGLE": "una sola lectura: el otro lector no reconoció la frase", + "TAMPERED": "alterada: la frase enviada a la capa matemática no es la lectura acordada", + "NONE": "sin lectura" + }, + "reasons": { + "unknown_word": "la palabra {word} no está entre las frases cubiertas en español", + "no_verb": "ninguna palabra anuncia el tipo de problema en español", + "two_verbs": "la frase anuncia más de un tipo de problema: {kinds}", + "no_pattern": "la forma de la frase no corresponde a ninguna forma cubierta en español", + "no_frame": "los conectores no corresponden a ninguna forma del tipo {kind}", + "multiple": "la misma frase tiene dos lecturas distintas: {first} y {second}", + "disagree": "los dos lectores proponen dos frases del lenguaje matemático diferentes", + "markers": "los conectores de la frase no son los que espera el tipo de problema", + "bad_variable": "{slot} no es una única variable del lenguaje matemático", + "bad_matrix": "{slot} no es una matriz escrita entre doble corchete", + "unbalanced": "un paréntesis o un corchete no está cerrado", + "no_math": "las matemáticas no están escritas con los símbolos del lenguaje matemático", + "literal_count": "los números de la frase no son los mismos en los dos lectores", + "math_unknown": "la capa matemática no acepta la frase: {detail}", + "boundary": "la frase enviada a la capa matemática no es la acordada", + "referee": "el árbitro SMT no confirma {detail}", + "domain_letter": "escribe el dominio con palabras (por ejemplo: sobre los enteros), no como una letra suelta", + "other": "la lectura no llegó a una frase del lenguaje matemático" + }, + "examples": [ + "calcula 1/2 + 1/3", + "demuestra que x^2 + 1 > 0", + "resuelve x^2 - 5*x + 6 = 0 para x", + "el determinante de [[1, 2], [3, 4]]", + "la integral de 3*x^2 desde 0 hasta 2", + "resuelve n mod 3 = 1 para n sobre los enteros", + "maximiza 3*x + 4*y sujeto a x + y <= 10" + ] +} diff --git a/lexicon/hi.json b/lexicon/hi.json new file mode 100644 index 0000000000000000000000000000000000000000..a64b56bfa8d5a5224275e4136179eea2c7fc07bd --- /dev/null +++ b/lexicon/hi.json @@ -0,0 +1,142 @@ +{ + "lang": "hi", + "name": "हिन्दी", + "script": "devanagari", + "noise_chars": "", + "prefixes": [], + "kinds": { + "evaluate": { + "verbs": ["गणना करें", "गणना", "मान"], + "neutral": true, + "patterns": ["गणना करें {T}", "{T} की गणना करें", "{T} का मान", "{T} का मान बताइए", "मान बताइए {T}"], + "frame": {"sequences": [[]]} + }, + "prove": { + "verbs": ["सिद्ध करें", "सिद्ध", "दिखाएँ", "सत्यापित करें"], + "patterns": ["सिद्ध करें {F}", "{F} सिद्ध करें", "यह सिद्ध करें {F}", "दिखाएँ {F}", "सत्यापित करें {F}"], + "frame": {"sequences": [[]]} + }, + "provez": { + "verbs": ["सिद्ध करें", "सिद्ध", "दिखाएँ", "सत्यापित करें"], + "patterns": ["सिद्ध करें {F} पूर्णांकों में", "{F} सिद्ध करें पूर्णांकों में", "{F} पूर्णांकों में सिद्ध करें", "दिखाएँ {F} पूर्णांकों में"], + "frame": {"sequences": [["over_z"]]} + }, + "solve": { + "verbs": ["हल करें", "हल", "ज्ञात करें", "ज्ञात"], + "patterns": ["हल करें {F} के लिए {V}", "{F} के लिए {V} हल करें", "ज्ञात करें {F} के लिए {V}", "{V} के लिए {F} का हल", "हल करें {F} का {V} के सापेक्ष"], + "frame": {"sequences": [["for"], ["wrt"]]} + }, + "solvez": { + "verbs": ["हल करें", "हल", "ज्ञात करें", "ज्ञात"], + "patterns": ["हल करें {F} के लिए {V} पूर्णांकों में", "{F} के लिए {V} पूर्णांकों में हल करें", "ज्ञात करें {F} के लिए {V} पूर्णांकों में", "हल करें {F} के लिए {V} पूर्णांकों पर"], + "frame": {"sequences": [["for", "over_z"]]} + }, + "derivative": { + "verbs": ["अवकलज", "अवकलन", "अवकलन करें"], + "patterns": ["{T} का अवकलज", "अवकलन करें {T}", "{T} का {V} के सापेक्ष अवकलज", "अवकलन करें {T} का {V} के सापेक्ष"], + "frame": {"sequences": [[], ["wrt"]]} + }, + "integral": { + "verbs": ["समाकलन", "समाकलन करें"], + "patterns": ["{T} का समाकलन {A} से {B} तक", "समाकलन करें {T} का {A} से {B} तक", "{T} का {V} के सापेक्ष समाकलन {A} से {B} तक", "समाकलन करें {T} का {V} के सापेक्ष {A} से {B} तक"], + "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]} + }, + "det": { + "verbs": ["सारणिक"], + "patterns": ["{M} का सारणिक", "{M} का सारणिक बताइए", "सारणिक बताइए {M}"], + "frame": {"sequences": [[]]} + }, + "rank": { + "verbs": ["कोटि"], + "patterns": ["{M} की कोटि", "{M} की कोटि बताइए", "कोटि बताइए {M}"], + "frame": {"sequences": [[]]} + }, + "inverse": { + "verbs": ["व्युत्क्रम"], + "patterns": ["{M} का व्युत्क्रम", "{M} का व्युत्क्रम बताइए", "व्युत्क्रम बताइए {M}"], + "frame": {"sequences": [[]]} + }, + "maximize": { + "verbs": ["अधिकतम", "अधिकतम करें"], + "patterns": ["अधिकतम करें {T} के अधीन {F}", "{T} के अधीन {F} अधिकतम करें", "{T} का अधिकतम के अधीन {F}"], + "frame": {"sequences": [["subject_to"]]} + }, + "minimize": { + "verbs": ["न्यूनतम", "न्यूनतम करें"], + "patterns": ["न्यूनतम करें {T} के अधीन {F}", "{T} के अधीन {F} न्यूनतम करें", "{T} का न्यूनतम के अधीन {F}"], + "frame": {"sequences": [["subject_to"]]} + } + }, + "connectives": { + "and": ["तथा", "और"], + "or": ["अथवा", "या"], + "not": ["नहीं"], + "ge": ["कम से कम", "के बराबर या उससे अधिक"], + "le": ["अधिक से अधिक", "के बराबर या उससे कम"], + "gt": ["से बड़ा", "से अधिक"], + "lt": ["से छोटा", "से कम"], + "eq": ["के बराबर", "बराबर"], + "ne": ["के बराबर नहीं", "असमान"] + }, + "markers": { + "for": ["के लिए"], + "over_z": ["पूर्णांकों में", "पूर्णांकों पर"], + "subject_to": ["के अधीन"], + "from": ["से"], + "to": ["तक"], + "wrt": ["के सापेक्ष"] + }, + "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_variable": "{slot} गणितीय भाषा का एकल चर नहीं है", + "bad_matrix": "{slot} दोहरी वर्ग कोष्ठकों के बीच लिखा आव्यूह नहीं है", + "unbalanced": "कोई कोष्ठक या वर्ग कोष्ठक बंद नहीं है", + "no_math": "गणित गणितीय भाषा के चिह्नों में नहीं लिखा है", + "literal_count": "वाक्य की संख्याएँ दोनों पाठकों में समान नहीं हैं", + "math_unknown": "गणितीय स्तर यह वाक्य स्वीकार नहीं करता: {detail}", + "boundary": "गणितीय स्तर को भेजा गया वाक्य सहमत वाक्य नहीं है", + "referee": "SMT निर्णायक {detail} की पुष्टि नहीं करता", + "domain_letter": "क्षेत्र शब्दों में लिखें (जैसे: पूर्णांकों में), केवल अकेले अक्षर के रूप में नहीं", + "other": "अर्थ गणितीय भाषा के वाक्य तक नहीं पहुँचा" + }, + "examples": [ + "गणना करें 1/2 + 1/3", + "सिद्ध करें x^2 + 1 > 0", + "हल करें x^2 - 5*x + 6 = 0 के लिए x", + "[[1, 2], [3, 4]] का सारणिक", + "समाकलन करें 3*x^2 का 0 से 2 तक", + "हल करें n mod 3 = 1 के लिए n पूर्णांकों में", + "अधिकतम करें 3*x + 4*y के अधीन x + y <= 10" + ] +} diff --git a/lexicon/it.json b/lexicon/it.json new file mode 100644 index 0000000000000000000000000000000000000000..66998160a84613824eb4260db274e8b15aff0e19 --- /dev/null +++ b/lexicon/it.json @@ -0,0 +1,142 @@ +{ + "lang": "it", + "name": "italiano", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "evaluate": { + "verbs": ["calcola", "calcolare", "quanto fa", "quanto vale", "valuta", "valore"], + "neutral": true, + "patterns": ["calcola {T}", "calcola il valore di {T}", "quanto fa {T}", "quanto vale {T}", "valuta {T}", "il valore di {T}"], + "frame": {"sequences": [[]]} + }, + "prove": { + "verbs": ["dimostra", "dimostrare", "prova", "provare", "verifica"], + "patterns": ["dimostra che {F}", "dimostra {F}", "prova che {F}", "prova {F}", "verifica che {F}"], + "frame": {"sequences": [[]]} + }, + "provez": { + "verbs": ["dimostra", "dimostrare", "prova", "provare", "verifica"], + "patterns": ["dimostra che {F} sugli interi", "dimostra {F} sugli interi", "prova che {F} negli interi", "dimostra {F} nei numeri interi"], + "frame": {"sequences": [["over_z"]]} + }, + "solve": { + "verbs": ["risolvi", "risolvere", "trova"], + "patterns": ["risolvi {F} per {V}", "per {V} risolvi {F}", "risolvi {F} rispetto a {V}"], + "frame": {"sequences": [["for"], ["wrt"]]} + }, + "solvez": { + "verbs": ["risolvi", "risolvere", "trova"], + "patterns": ["risolvi {F} per {V} sugli interi", "risolvi {F} per {V} nei numeri interi"], + "frame": {"sequences": [["for", "over_z"]]} + }, + "derivative": { + "verbs": ["derivata", "deriva", "derivare"], + "patterns": ["la derivata di {T}", "derivata di {T}", "derivata di {T} rispetto a {V}", "calcola la derivata di {T}", "deriva {T}", "deriva {T} rispetto a {V}"], + "frame": {"sequences": [[], ["wrt"]]} + }, + "integral": { + "verbs": ["integrale", "integrare"], + "patterns": ["l'integrale di {T} da {A} a {B}", "integrale di {T} da {A} a {B}", "calcola l'integrale di {T} da {A} a {B}", "l'integrale rispetto a {V} di {T} da {A} a {B}"], + "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]} + }, + "det": { + "verbs": ["determinante", "det"], + "patterns": ["il determinante di {M}", "determinante di {M}", "det {M}"], + "frame": {"sequences": [[]]} + }, + "rank": { + "verbs": ["rango", "rank"], + "patterns": ["il rango di {M}", "rango di {M}", "rank {M}"], + "frame": {"sequences": [[]]} + }, + "inverse": { + "verbs": ["inversa", "invertire"], + "patterns": ["l'inversa di {M}", "la inversa di {M}", "inversa di {M}", "la matrice inversa di {M}"], + "frame": {"sequences": [[]]} + }, + "maximize": { + "verbs": ["massimizza", "massimizzare", "massimo"], + "patterns": ["massimizza {T} soggetto a {F}", "massimizza {T} sotto i vincoli {F}", "il massimo di {T} soggetto a {F}"], + "frame": {"sequences": [["subject_to"]]} + }, + "minimize": { + "verbs": ["minimizza", "minimizzare", "minimo"], + "patterns": ["minimizza {T} soggetto a {F}", "minimizza {T} sotto i vincoli {F}", "il minimo di {T} soggetto a {F}"], + "frame": {"sequences": [["subject_to"]]} + } + }, + "connectives": { + "and": ["e", "ed"], + "or": ["o"], + "not": ["non"], + "ge": ["almeno", "maggiore o uguale a", "non minore di"], + "le": ["al massimo", "minore o uguale a", "non maggiore di"], + "gt": ["maggiore di", "piu grande di", "strettamente maggiore di"], + "lt": ["minore di", "piu piccolo di", "strettamente minore di"], + "eq": ["uguale a", "e uguale a"], + "ne": ["diverso da", "differente da"] + }, + "markers": { + "for": ["per"], + "over_z": ["sugli interi", "negli interi", "nei numeri interi"], + "subject_to": ["soggetto a", "soggetta a", "sotto i vincoli"], + "from": ["da"], + "to": ["a"], + "wrt": ["rispetto a"] + }, + "noise": ["il", "la", "lo", "i", "le", "gli", "un", "uno", "una", "l", "di", "del", "della", "dei", "delle", "che", "in", "con", "quale", "qual", "cos", "cosa"], + "labels": { + "understood": "Problema capito", + "status": "Stato", + "assurance": "livello {n} di 3", + "answer": "Risposta", + "reading": "Lettura", + "math_layer": "strato matematico", + "notes": "Note", + "examples": "Frasi che questo strato capisce", + "question": "Riformula la domanda in una di queste forme", + "check": "Controllo SMT dello strato : {a} di {b} buste confermate", + "kind_of": "tipo" + }, + "reading": { + "AGREED": "accordata: due lettori indipendenti piu il vincolo SMT", + "PASSTHROUGH": "frase gia scritta nella lingua matematica, non tradotta", + "DISPUTED": "in disputa: i due lettori propongono frasi diverse", + "NOT COVERED": "fuori dalla copertura di questa lingua", + "AMBIGUOUS": "ambigua: piu letture possibili", + "TAMPERED": "manomessa: il testo passato allo strato matematico non e la lettura concordata", + "SINGLE": "una sola lettura: l'altro lettore non ha riconosciuto la frase", + "NONE": "nessuna lettura" + }, + "reasons": { + "unknown_word": "la parola {word} non compare nelle frasi coperte in italiano", + "no_verb": "nessuna parola annuncia il tipo di problema in italiano", + "two_verbs": "la frase annuncia piu di un tipo di problema: {kinds}", + "no_pattern": "la forma della frase non corrisponde a nessuna forma coperta in italiano", + "no_frame": "i connettori non corrispondono ad alcuna forma del tipo {kind}", + "multiple": "della stessa frase esistono due letture diverse: {first} e {second}", + "disagree": "i due lettori propongono due frasi della lingua matematica diverse", + "markers": "i connettori della frase non sono quelli attesi per il tipo di problema", + "bad_variable": "{slot} non e una singola variabile della lingua matematica", + "bad_matrix": "{slot} non e una matrice scritta tra doppie parentesi quadre", + "unbalanced": "parentesi o parentesi quadre non chiuse", + "no_math": "la parte matematica non e scritta con i simboli della lingua matematica", + "literal_count": "i numeri della frase non sono gli stessi nei due lettori", + "math_unknown": "lo strato matematico non accetta la frase: {detail}", + "boundary": "la frase passata allo strato matematico non e quella concordata", + "referee": "il controllore SMT non conferma {detail}", + "domain_letter": "il dominio va scritto a parole (ad esempio: sugli interi), non come lettera isolata", + "other": "la lettura non e arrivata a una frase della lingua matematica" + }, + "examples": [ + "calcola 1/2 + 1/3", + "dimostra che x^2 + 1 > 0", + "risolvi x^2 - 5*x + 6 = 0 per x", + "qual è il determinante di [[1, 2], [3, 4]]", + "l'integrale di 3*x^2 da 0 a 2", + "risolvi n mod 3 = 1 per n sugli interi", + "massimizza 3*x + 4*y soggetto a x + y <= 10" + ] +} diff --git a/lexicon/zh.json b/lexicon/zh.json new file mode 100644 index 0000000000000000000000000000000000000000..2ab808d038dc48e6ba0fc62ec73a80ca7369cb90 --- /dev/null +++ b/lexicon/zh.json @@ -0,0 +1,142 @@ +{ + "lang": "zh", + "name": "中文", + "script": "cjk", + "noise_chars": "的了之把被给吧呢吗也则该", + "prefixes": [], + "kinds": { + "evaluate": { + "verbs": ["计算", "值"], + "neutral": true, + "patterns": ["计算 {T}", "请 计算 {T}", "求 {T} 的 值", "{T} 的 值", "计算 {T} 的 值"], + "frame": {"sequences": [[]]} + }, + "prove": { + "verbs": ["证明", "求证"], + "patterns": ["证明 {F}", "求证 {F}", "请 证明 {F}", "试 证明 {F}", "{F} 的 证明"], + "frame": {"sequences": [[]]} + }, + "provez": { + "verbs": ["证明", "求证"], + "patterns": ["证明 {F} 在整数上", "求证 {F} 在整数上", "在整数上 证明 {F}", "证明 {F} 在整数范围内", "求证 {F} 在整数范围内"], + "frame": {"sequences": [["over_z"]]} + }, + "solve": { + "verbs": ["解", "求解"], + "patterns": ["求解 {F} 对 {V}", "解 {F} 对 {V}", "对 {V} 求解 {F}", "求解 {F} 关于 {V}", "解 {F} 关于 {V}"], + "frame": {"sequences": [["for"], ["wrt"]]} + }, + "solvez": { + "verbs": ["解", "求解"], + "patterns": ["求解 {F} 对 {V} 在整数上", "解 {F} 对 {V} 在整数上", "求解 {F} 对 {V} 在整数范围内", "解 {F} 对 {V} 在整数范围内"], + "frame": {"sequences": [["for", "over_z"]]} + }, + "derivative": { + "verbs": ["导数", "导函数"], + "patterns": ["求 {T} 的 导数", "{T} 的 导数", "求 {T} 关于 {V} 的 导数", "{T} 关于 {V} 的 导数", "{T} 的 导函数"], + "frame": {"sequences": [[], ["wrt"]]} + }, + "integral": { + "verbs": ["积分", "定积分"], + "patterns": ["求 {T} 从 {A} 到 {B} 的 积分", "{T} 从 {A} 到 {B} 的 积分", "计算 {T} 从 {A} 到 {B} 的 积分", "求 {T} 关于 {V} 从 {A} 到 {B} 的 积分", "{T} 从 {A} 到 {B} 关于 {V} 的 积分", "{T} 从 {A} 到 {B} 的 定积分"], + "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]} + }, + "det": { + "verbs": ["行列式"], + "patterns": ["求 {M} 的 行列式", "{M} 的 行列式", "计算 {M} 的 行列式"], + "frame": {"sequences": [[]]} + }, + "rank": { + "verbs": ["秩"], + "patterns": ["求 {M} 的 秩", "{M} 的 秩", "计算 {M} 的 秩"], + "frame": {"sequences": [[]]} + }, + "inverse": { + "verbs": ["逆", "逆矩阵"], + "patterns": ["求 {M} 的 逆", "{M} 的 逆", "求 {M} 的 逆矩阵", "{M} 的 逆矩阵"], + "frame": {"sequences": [[]]} + }, + "maximize": { + "verbs": ["最大化", "最大值"], + "patterns": ["最大化 {T} 约束 {F}", "最大化 {T} 约束条件 {F}", "求 {T} 的 最大值 约束 {F}", "{T} 的 最大值 约束 {F}", "在约束条件下 最大化 {T}"], + "frame": {"sequences": [["subject_to"]]} + }, + "minimize": { + "verbs": ["最小化", "最小值"], + "patterns": ["最小化 {T} 约束 {F}", "最小化 {T} 约束条件 {F}", "求 {T} 的 最小值 约束 {F}", "{T} 的 最小值 约束 {F}", "在约束条件下 最小化 {T}"], + "frame": {"sequences": [["subject_to"]]} + } + }, + "connectives": { + "and": ["且", "和", "与"], + "or": ["或", "或者"], + "not": ["非"], + "ge": ["大于等于", "不小于", "至少"], + "le": ["小于等于", "不大于", "至多"], + "gt": ["大于", "严格大于"], + "lt": ["小于", "严格小于"], + "eq": ["等于"], + "ne": ["不等于"] + }, + "markers": { + "for": ["对"], + "over_z": ["在整数上", "在整数范围内"], + "subject_to": ["约束", "约束条件", "在约束条件下"], + "from": ["从"], + "to": ["到"], + "wrt": ["关于"] + }, + "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_variable": "{slot} 不是数学语言中的单个变量", + "bad_matrix": "{slot} 不是写在双方括号之间的矩阵", + "unbalanced": "有个圆括号或方括号没有闭合", + "no_math": "数学部分没有用数学语言的符号书写", + "literal_count": "句子中的数字在两位读者那里并不相同", + "math_unknown": "数学层不接受这个句子:{detail}", + "boundary": "送往数学层的句子不是那个一致的读法", + "referee": "SMT 裁判没有确认 {detail}", + "domain_letter": "请把定义域用词语写出来(例如:在整数上),不要只用一个孤立的字母", + "other": "读法没有得到数学语言中的一个句子" + }, + "examples": [ + "计算 1/2 + 1/3", + "证明 x^2 + 1 > 0", + "解 x^2 - 5*x + 6 = 0 对 x", + "求 [[1, 2], [3, 4]] 的 行列式", + "求 3*x^2 从 0 到 2 的 积分", + "解 n mod 3 = 1 对 n 在整数上", + "最大化 3*x + 4*y 约束 x + y <= 10" + ] +} diff --git a/lgstratum/__init__.py b/lgstratum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e8570836ac9ff777d69e59fceaa3af54e98f5ab8 --- /dev/null +++ b/lgstratum/__init__.py @@ -0,0 +1,20 @@ +"""The library of the math-stratum topology. + +The math-stratum is the conversational stratum of the math topology: it accepts a problem +written in one of six language varieties, reads it into one sentence of the math language, +hands that sentence to the math stratum as a separate process, and presents the verdict of +the math stratum 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 math stratum 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 math 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/lgstratum/agents.py b/lgstratum/agents.py new file mode 100644 index 0000000000000000000000000000000000000000..c7ef05338378c3923def45644250101cb18feb96 --- /dev/null +++ b/lgstratum/agents.py @@ -0,0 +1,276 @@ +"""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 math stratum 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 sentence to the math stratum 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 math stratum, in another process, on one sentence + boundary the math 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 math stratum, ceiling of the reading)``, and the ceiling is below the top +level of the math stratum. A node may lower what the user sees; none may raise it. +""" + +from typing import Any, Dict, List, 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") + + +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 _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 ("drop_marker", "merge_slots", "shift_number"): + if not faults.has(agent, kind): + continue + order = canonical.slots_for(str(reading["kind"])) + slots, changed = faults.mutate_reading(agent, str(reading["kind"]), dict(reading.get("slots") or {}), order) + if not changed: + continue + faults.fire(agent, kind) + try: + reading["math"] = canonical.print_math(str(reading["kind"]), slots) + reading["slots"] = slots + reading["fault"] = kind + except canonical.ReadingError: + reading["math"] = "" + reading["status"] = "NOT COVERED" + reading["notes"].append({"reason": "no_frame", "kind": reading["kind"], "detail": kind}) + 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 = reader.read(lang, 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 math stratum, in its own process, about the sentence 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 sentence was agreed on") + summary = "invoker: nothing to ask the math stratum" + 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 step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]: + """The math verdict enters this stratum here; the echo it carries is checked, not trusted.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + reading = dossier.get("reading_a") or dossier.get("reading_direct") or {} + 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 math stratum answered no sentence 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 = coverage.echo_matches(readings[0], math_verdict) if math_verdict.get("problem_math") else True + for other in readings[1:]: + if other.get("math") and not coverage.echo_matches(other, 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/lgstratum/canonical.py b/lgstratum/canonical.py new file mode 100644 index 0000000000000000000000000000000000000000..f908bd309859dc8a6069eeb342fc3e6186868f79 --- /dev/null +++ b/lgstratum/canonical.py @@ -0,0 +1,218 @@ +"""The canonical sentence: one printer for the math language, shared by both readers. + +A reading is a mapping from a surface sentence to **one sentence of the math language**, which +is what the math stratum 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 kinds of the math +language. The rest of the math language stays available through the direct mode: a sentence +already written in the math language is passed through untouched. +""" + +import re +from typing import Any, Dict, List, Optional, Tuple + +KINDS = ("evaluate", "prove", "provez", "solve", "solvez", "derivative", "integral", + "det", "rank", "inverse", "maximize", "minimize") + +# For each kind, the accepted slot sets and the template each one prints to. A kind with an +# optional slot (the variable a derivative is taken with respect to) has two entries. +TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = { + "evaluate": [(("T",), "evaluate {T}")], + "prove": [(("F",), "prove {F}")], + "provez": [(("F",), "prove {F} over Z")], + "solve": [(("F", "V"), "solve {F} for {V}")], + "solvez": [(("F", "V"), "solve {F} for {V} over Z")], + "derivative": [(("T",), "derivative {T}"), (("T", "V"), "derivative {T} wrt {V}")], + "integral": [(("T", "A", "B"), "integral {T} from {A} to {B}"), + (("T", "A", "B", "V"), "integral {T} from {A} to {B} wrt {V}")], + "det": [(("M",), "det {M}")], + "rank": [(("M",), "rank {M}")], + "inverse": [(("M",), "inverse {M}")], + "maximize": [(("T", "F"), "maximize {T} subject to {F}")], + "minimize": [(("T", "F"), "minimize {T} subject to {F}")], +} + +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()} + +_VARIABLE = re.compile(r"[A-Za-z]") + + +class ReadingError(ValueError): + """A reading cannot be printed as a sentence of the math language.""" + + +def print_math(kind: str, slots: Dict[str, str]) -> str: + """Print one reading as a sentence of the math language.""" + wanted = tuple(name for name in _order(kind) if name in slots and slots[name] != "") + for slots_set, template in TEMPLATES[kind]: + if set(slots_set) == set(wanted): + missing = [name for name in slots_set if not slots.get(name, "").strip()] + if missing: + raise ReadingError("the %s reading has no value for %s" % (kind, ", ".join(missing))) + extra = [name for name in slots if name not in slots_set] + if extra: + raise ReadingError("the %s reading has no slot %s" % (kind, ", ".join(extra))) + return tidy(template.format(**{name: slots[name] for name in slots_set})) + raise ReadingError("the %s reading fills the slots %s, which is not a form of the kind" + % (kind, ", ".join(sorted(wanted)))) + + +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 math 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 = {"for": "for", "over_z": "over Z", "subject_to": "subject to", + "from": "from", "to": "to", "wrt": "wrt"} +_PHRASE_MARKER = {phrase: name for name, phrase in _MARKER_PHRASE.items()} + + +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))) + + +def gap_markers(kind: str, variant: Tuple[str, ...]) -> List[Optional[str]]: + """The joints a form of the math 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 pieces of + mathematics that fall between those joints, and a joint may not be missing or out of order. + """ + parts = re.split(r"\{[TFVABM]\}", template_for(kind, variant)) + gaps: List[Optional[str]] = [] + for index, literal in enumerate(parts): + phrase = literal.strip() + if index == 0 or not phrase: + 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 math 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 math language prints them.""" + return [gap for gap in gap_markers(kind, variant) if gap is not None] + + +_OPERATORS = "+-*/^=<>!|" +_AFTER_CLOSED = "(?<=[0-9A-Za-z\\)\\]])\\s+(?=[%s])" % re.escape(_OPERATORS) +_BEFORE_OPEN = "(?<=[%s])\\s+(?=[0-9A-Za-z\\[\\(])" % re.escape(_OPERATORS) + + +def tidy(text: str) -> str: + """One space between the tokens, none inside a bracket, none around an operator. + + The math language tolerates whitespace anywhere between its tokens -- verified against the + math stratum itself, which answers ``solve x^2-5*x+6=0 for x`` and + ``solve x^2 - 5*x + 6 = 0 for x`` with the same roots -- so tidying never changes what the + math stratum reads. It gives the two readers one normal form to compare, which matters + because the two of them glue the tokens 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 tokens fuse: ``n mod 3`` is three tokens to the + math stratum, and ``nmod3`` is one unknown it has never heard of, 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 = re.sub(r"\s+([,\]\)])", r"\1", out) + out = re.sub(r"([\[\(])\s+", r"\1", out) + out = re.sub(r"(\d)\s+([A-Za-z])(?![A-Za-z0-9])", r"\1*\2", out) + out = re.sub(_AFTER_CLOSED, "", out) + out = re.sub(_BEFORE_OPEN, "", out) + return out + + +def variable(text: str) -> Optional[str]: + """A slot value that is a single variable of the math language, or ``None``.""" + cleaned = tidy(text) + return cleaned if _VARIABLE.fullmatch(cleaned) else None + + +def matrix(text: str) -> Optional[str]: + """A slot value that is a matrix literal (rows between double brackets), or ``None``.""" + cleaned = tidy(text) + if not (cleaned.startswith("[[") and cleaned.endswith("]]")): + return None + return cleaned if cleaned.count("[") == cleaned.count("]") 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 commands of the math language, copied from the parser specification of the math stratum. +# The reading layer covers only part of them; the rest stays reachable through the direct mode. +MATH_COMMANDS = ("evaluate", "prove", "solve", "derivative", "antiderivative", "integral", + "maximize", "minimize", "det", "rank", "inverse", "nullspace", "linsolve", + "product", "power", "maxflow", "reduce", "sos") + +# The words the math language itself uses, copied from the same specification. A sentence that +# carries a word outside this list is not written in the math language, whatever else it looks +# like. This is the third copy of that spec (the math stratum parses with it, its grammar names +# it), and the direct mode is where the copies can disagree out loud. +MATH_LANGUAGE_WORDS = frozenset([ + "evaluate", "prove", "solve", "for", "forall", "exists", "in", "and", "or", "not", + "true", "false", "derivative", "antiderivative", "integral", "from", "to", "wrt", + "maximize", "minimize", "subject", "over", "mod", "div", "det", "rank", "inverse", + "nullspace", "linsolve", "product", "power", "maxflow", "dot", "matvec", "reduce", "sos", +]) + +_NOT_MATH_CHARACTER = re.compile(r"[^A-Za-z0-9\s+\-*/^()\[\]<>=!|,.]") + + +def direct(text: str) -> Optional[Dict[str, Any]]: + """A sentence already written in the math language, or ``None``. + + The direct mode is the only way a user reaches the kinds the reading layer does not cover, and + the only way an untranslated sentence reaches the math stratum: it fires only when the first + word is a command of the math language, every other word is a word of that language or a one + letter variable, and no character outside its alphabet appears. Nothing is translated here, and + the sentence is shown to the user as it arrived. + """ + cleaned = tidy(text) + if not cleaned or _NOT_MATH_CHARACTER.search(cleaned): + return None + words = re.findall(r"[A-Za-z]+", cleaned) + if not words or words[0].lower() not in MATH_COMMANDS: + return None + for word in words[1:]: + if len(word) > 1 and word.lower() not in MATH_LANGUAGE_WORDS: + return None + return {"mode": "direct", "kind": words[0].lower(), "math": cleaned, "slots": {}} diff --git a/lgstratum/compare.py b/lgstratum/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..eeddb5e0cc8f964e9cf79cba78e3bffab6e9c51a --- /dev/null +++ b/lgstratum/compare.py @@ -0,0 +1,261 @@ +"""The SMT equivalence of the two readings: do the two readers mean the same problem? + +Reader A and reader B reach their sentence of the math language by different routes -- surface +patterns and marker frames -- and the topology only trusts the pair when the two sentences 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 math stratum itself does between its two formalizers. + +The translation of the math language into SMT2 is **not reimplemented here**. The math bundle owns +that account, and a second copy of it inside the reading layer would be a third place where the +meaning of the math language could be wrong without anyone noticing. So this module loads the math +bundle (:envvar:`LGSTRATUM_MATH_ROOT`, sibling folder ``math`` by default) and asks it to +formalize both sentences, then states the claim ``the readings differ`` as SMT2 and hands it to +Z3: unsatisfiable means the two readings denote the same problem under every assignment, which is +the same ``equiv: unsat`` discipline the math stratum applies to its own formalizers. + +Two consequences are deliberate and both are limits, not shortcuts: + +* a kind the math bundle cannot put into SMT2 (matrices, flows, integrals of unbounded scope) is + reported ``unknown`` and the session treats it as a dispute: the reading layer would rather + abstain than assume two texts are equal; +* the Z3 claim of this module is *about the readings*, never about the user's problem. The problem + itself is never decided here: the sentence is handed to the math stratum, whose verdict is shown + as it arrived. +""" + +import re +import sys +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, invoker, segment + +_math = None +_MATH_LOOKUP_ERROR: Optional[str] = None + + +def _math_modules() -> Tuple[Any, Any, Optional[str]]: + """The math bundle's parser and SMT builder, or the reason they are not available.""" + global _math, _MATH_LOOKUP_ERROR + if _math is not None: + return _math[0], _math[1], None + if _MATH_LOOKUP_ERROR is not None: + return None, None, _MATH_LOOKUP_ERROR + root = invoker.math_root() + if not (root / "lgmath").is_dir(): + _MATH_LOOKUP_ERROR = "no lgmath package under %s" % root + return None, None, _MATH_LOOKUP_ERROR + text = str(root) + if text not in sys.path: + sys.path.insert(0, text) + try: + from lgmath import parse_a, smt # noqa: PLC0415 - the import of the math bundle is the point + except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently + _MATH_LOOKUP_ERROR = "the math bundle could not be imported: %s" % type(exc).__name__ + return None, None, _MATH_LOOKUP_ERROR + _math = (parse_a, smt) + return _math[0], _math[1], None + + +ONTOLOGY = "(set-option :timeout 8000)\n" + + +def smt_referee(decls: List[str], asserts: List[str]) -> str: + """Run the referee of the math stratum over one claim, the way the orchestrator does each turn. + + The same code answers here and in the math bundle, so an envelope that this stratum writes is + checked by the solver the project already trusts; the stratum adds no second referee. + """ + _parser, smt, _reason = _math_modules() + if smt is None: + return "unknown" + return str(smt.referee(ONTOLOGY, list(decls), list(asserts))) + + +def numbers(text: str) -> List[str]: + """Every number written in a sentence, 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 math bundle's own SMT2 view of one canonical sentence, or ``None``.""" + parse_a, smt, _reason = _math_modules() + if parse_a is None: + return None + try: + node = parse_a.parse_problem(sentence) + return smt.problem_smt(node) + except Exception: # noqa: BLE001 - a sentence this module cannot formalize is a sentence to report + return None + + +_DECLARED = re.compile(r"\(declare-(?:const|fun|sort)\s+([^\s()]+)") + + +def _declared_name(decl: str) -> Optional[str]: + match = _DECLARED.search(decl) + return match.group(1) if match else None + + +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: the negation of the equivalence + of the two formalizations, over the union of their variables. Unsatisfiable means the two + readings denote the same problem under every assignment, which is the same discipline the math + stratum applies to its own two formalizers. 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] = [] + decls: List[str] = [] + declared = set() + for side in (left, right): + for decl in side.get("decls", []): + name = _declared_name(decl) + if name is not None: + if name in declared: + continue + declared.add(name) + decls.append(decl) + for name in side.get("vars", []): + if name not in names: + names.append(name) + for name in names: + if name not in declared: + decls.append("(declare-const %s Real)" % name) + declared.add(name) + if "expr" in left and "expr" in right: + assertions = ["(assert (not (= %s %s)))" % (left["expr"], right["expr"])] + elif "phi" in left and "phi" in right: + assertions = ["(assert (not (= %s %s)))" % (left["phi"], right["phi"])] + else: + return decls, [], "unknown", "unknown", None + status, model = smt.check(decls, assertions, names) + if status == "unsat": + return decls, assertions, "unsat", "equivalent", None + if status == "sat": + return decls, assertions, "sat", "different", model + return decls, assertions, "unknown", "unknown", None + + +def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]: + """The slots one reading actually filled, in the order the math 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.""" + left = canonical.tidy(str(a.get("math", ""))) + right = canonical.tidy(str(b.get("math", ""))) + detail: List[str] = [] + if sorted_numbers(left) != sorted_numbers(right): + detail.append("numbers %s vs %s" % (",".join(sorted_numbers(left)), ",".join(sorted_numbers(right)))) + + 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} + + _parser, smt, reason = _math_modules() + first, second = formalize(left), formalize(right) + if first is None or second is None: + note = reason or "the math bundle gives no SMT2 view of this kind of sentence" + 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 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_math(reading: Dict[str, Any], math_verdict: Dict[str, Any]) -> bool: + """Did the math stratum solve the sentence the readers agreed on? + + The math stratum echoes the problem it understood. That echo is an independent channel: a node + standing between the readers and the math layer can rewrite its own record, but it cannot move + the echo without moving numbers that were counted upstream. + """ + echo = canonical.tidy(str(math_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 sentence warrants. + + The scale is the one the math stratum 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 sentence written in a human + language is never the last word -- the math stratum holds level three for the mathematics it + proved, 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/lgstratum/corpus.py b/lgstratum/corpus.py new file mode 100644 index 0000000000000000000000000000000000000000..4dcc9720a302b4975faab0bf29276b73155b19c1 --- /dev/null +++ b/lgstratum/corpus.py @@ -0,0 +1,81 @@ +"""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 solver -- it is the layer that +decides *which* sentence to hand to the solver and how much confidence to attach to it: + + {"id": "it-solve-1", "lang": "it", "question": "risolvi x^2 - 5*x + 6 = 0 per x", + "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", + "min_assurance": 1}} + +``state`` is the only mandatory key. ``sentence`` is compared after tidying, ``answer_contains`` is +a substring test on the answer the math stratum 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_math: 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_math=call_math) + verdict = grade(item, result) + verdict["records"] = result["records"] + verdict["dossier"] = result["dossier"] + verdict["reply"] = result["reply"] + return verdict diff --git a/lgstratum/coverage.py b/lgstratum/coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7ae81e2f8bdf0effaa5eb3f1253a9f9fae7aaa --- /dev/null +++ b/lgstratum/coverage.py @@ -0,0 +1,93 @@ +"""What the reading kept, and what the math stratum says it solved. + +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 math 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 math stratum 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 math layer can rewrite its own record, but it cannot move + the echo without moving numbers that were counted upstream. + +Neither check decides mathematics. 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(math_verdict: Dict[str, Any]) -> List[str]: + """The numbers of the problem the math stratum says it solved, ordered by value.""" + return compare.sorted_numbers(canonical.tidy(str(math_verdict.get("problem_math", "")))) + + +def echo_matches(reading: Dict[str, Any], math_verdict: Dict[str, Any]) -> bool: + """Did the math stratum solve the sentence the readers agreed on? + + A verdict that names no sentence at all -- the backend was off, or the math stratum could not + be started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls + to zero because there is no math 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(math_verdict.get("problem_math", "")).strip(): + return True + return compare.agrees_with_math(reading, math_verdict) + + +def coverage_claim(question: str, readings: List[Dict[str, Any]], + math_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 math + stratum 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 math_verdict is not None: + echo = echo_numbers(math_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/lgstratum/decide.py b/lgstratum/decide.py new file mode 100644 index 0000000000000000000000000000000000000000..ac1d0972ce9975eb631cb5b3bde2ece56811c80f --- /dev/null +++ b/lgstratum/decide.py @@ -0,0 +1,160 @@ +"""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 math 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 math stratum uses for its own ``decide``. + +The rule the whole module exists to enforce: + + assurance(shown) = min(assurance(math), 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 sentence the math stratum +formalizes 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 math stratum solved it +PASSTHROUGH the sentence was already written in the math language: nothing was translated +SINGLE one reader understood the sentence and the other abstained: the math stratum 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 math + stratum 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 math stratum says it solved 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 math stratum uses. Three is not in this +# table: it belongs to the math stratum alone. +CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0, + "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0} + + +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]], math_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 math_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]], math_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("math_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 math_verdict is not None and math_verdict.get("referee_mismatch"): + out.append("referee") + if asked and math_verdict is not None and math_verdict.get("status") == "UNKNOWN": + out.append("math_unknown") + if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"): + out.append("no_math") + 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") + math_verdict = dossier.get("math") + direct = dossier.get("reading_direct") + echo_ok = dossier.get("echo_ok") + + state = state_of(readings, comparison, coverage, math_verdict, direct, echo_ok) + ceiling = CEILING[state] + assurance = 0 + answer_shown = "" + if state in ("AGREED", "SINGLE", "PASSTHROUGH") and math_verdict is not None: + # The math stratum answers at level three when its own two formalizers and two checkers all + # agree, at level two when one prover stands alone, and at level zero when it says UNKNOWN. + if math_verdict.get("status") in ("VERIFIED", "SINGLE_PROVER"): + assurance = min(ceiling, int(math_verdict.get("assurance", 0) or 0)) + else: + assurance = 0 + answer_shown = math_verdict.get("answer_text") or "" + if assurance == 0: + answer_shown = "" + reasons = reasons_for(state, readings, comparison, coverage, math_verdict, + asked=bool(str(dossier.get("sent") or ""))) + return { + "state": state, + "assurance": assurance, + "ceiling": ceiling, + "math_assurance": int((math_verdict or {}).get("assurance", 0) or 0), + "math_status": (math_verdict or {}).get("status"), + "answer": answer_shown, + "reasons": reasons, + "consulted_math": math_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/lgstratum/faults.py b/lgstratum/faults.py new file mode 100644 index 0000000000000000000000000000000000000000..7f99673c32a550075dcae271247fc89ccb9d9d34 --- /dev/null +++ b/lgstratum/faults.py @@ -0,0 +1,144 @@ +"""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 math language: a reader that drops a number or merges two slots must produce +something the math stratum will happily solve. Otherwise the fault would be caught by the math +stratum refusing to parse, and the experiment would measure nothing about the reading layer. + +Catalogue +--------- +reader_a / reader_b : drop_marker, 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 math stratum 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 = ["drop_marker", "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"], +} + +# Slots a form can lose without becoming ungrammatical: the joint and its slot are both optional. +_OPTIONAL = {"V"} +_NUMBER = re.compile(r"\d+(?:\.\d+)?") + + +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 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 slots a + joint is holding and which of them the math language could do without. + """ + 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 == "drop_marker": + losers = [name for name in reversed(order) if name in candidate and name in _OPTIONAL] + if not losers: + continue + candidate.pop(losers[0]) + elif kind_fault == "merge_slots": + numbered = _slots_with_numbers(candidate, order) + if len(numbered) < 2: + continue + candidate[numbered[1]] = candidate[numbered[0]] + 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 math 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/lgstratum/invoker.py b/lgstratum/invoker.py new file mode 100644 index 0000000000000000000000000000000000000000..472a351ec47ceafefe80579713ae83c6db3c88db --- /dev/null +++ b/lgstratum/invoker.py @@ -0,0 +1,102 @@ +"""The interface toward the math stratum: one subprocess call, no shared code. + +The reading layer and the math layer are separate topologies of the same orchestrator. This +module is the whole of their coupling: it starts ``tools/solve.py`` of the math stratum as a +separate process with the canonical sentence as its argument, asks for the machine readable +outcome, and copies that outcome. Nothing here imports a module of the math stratum, because a +translation layer that reaches inside the mathematics it consults is a translation layer that can +silently change the mathematics. + +Two settings matter, and both are environment variables so no value is hardcoded in a second +place: + +``LGSTRATUM_MATH_ROOT`` the folder of the math stratum (default: ``math``, sibling of this + bundle, which is ``datasets/math`` inside the LingoLOGOS repository) +``LGSTRATUM_MATH_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 math 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 math_root() -> Path: + override = os.environ.get("LGSTRATUM_MATH_ROOT", "").strip() + if override: + return Path(override) + return ROOT.parent / "math" + + +def backend() -> str: + return (os.environ.get("LGSTRATUM_MATH_BACKEND", "subprocess") or "subprocess").strip().lower() + + +def timeout_seconds() -> int: + try: + return max(5, int(os.environ.get("LGSTRATUM_MATH_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(sentence: str) -> Dict[str, Any]: + """Ask the math stratum one sentence of the math language, and return its verdict unchanged.""" + if backend() == "none": + return unavailable("the math backend is disabled by LGSTRATUM_MATH_BACKEND") + root = math_root() + script = root / "tools" / "solve.py" + if not script.is_file(): + return unavailable("no tools/solve.py under %s" % root) + try: + done = subprocess.run( + [sys.executable, str(script), "--json", sentence], + cwd=str(root), capture_output=True, timeout=timeout_seconds()) + except subprocess.TimeoutExpired: + return unavailable("the math stratum did not answer within %d seconds" % timeout_seconds()) + except OSError as exc: + return unavailable("the math stratum could not be started: %s" % exc) + text = done.stdout.decode("utf-8", "replace") + if done.returncode != 0 and not text.strip(): + return unavailable("the math stratum exited with %d: %s" + % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200])) + return outcome(text, done.returncode) + + +def outcome(text: str, returncode: int = 0) -> Dict[str, Any]: + """Extract the verdict of a math session from the JSON the math stratum printed.""" + try: + parsed = json.loads(text) + except ValueError: + return unavailable("the math stratum 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 math stratum 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/lgstratum/lexicon.py b/lgstratum/lexicon.py new file mode 100644 index 0000000000000000000000000000000000000000..2a323dc4cda2f3b6782babb552f5ec5d434404f2 --- /dev/null +++ b/lgstratum/lexicon.py @@ -0,0 +1,421 @@ +"""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 markers must appear, which must not, how many + mathematics regions the sentence holds). + +This mirrors the math topology, 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 math bundle holds the bracket tokens it studies. +""" + +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") + +# Marker names, the same in every variety. The variety supplies the words; the names are how +# the two readers and the canonical printer agree. +MARKERS = ("for", "over_z", "subject_to", "from", "to", "wrt") + +# A word run that is not in the lexicon is a coverage failure, unless it is one of these. +MATH_WORDS = ("mod", "div") +# Domains written as bare letters belong to the math language, not to a reading. +DOMAIN_LETTERS = ("R", "Z") + +# The characters that say "a single letter here is an operand of the mathematics". Digits are not +# among them: Italian "da 0 a 2" puts the single letter a between two numbers, and there it is the +# marker of a bound, not the unknown the sentence is about. +OPERATOR_BEFORE = set("+-*/^=<>|([,") +OPERATOR_AFTER = set("+-*/^=<>|)]") + +# 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 of a sentence open, or the reason the sentence announces none. + + Both readers ask this one question, in one place: a kind is a decision about the mathematics, + 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. + """ + found: List[str] = [] + for item in items: + if item.get("role") != "verb": + continue + for kind in item.get("kinds") or (item.get("value"),): + if kind 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 math 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 + math language needs. The logic connectives are words in the math 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 mathematics. + + ``calcola la derivata di x^2`` announces two kinds, and only one of them is the kind of the + problem: the request verb is neutral, so the reader that carries it steps aside. + """ + return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")} + + +def operand(lang: str, word: str, before: str, after: str) -> bool: + """Whether a single Latin letter touching an operator is the unknown, not the word it spells. + + Spanish writes the conjunction "y" and Italian writes the marker "a" with the same characters a + variable uses, and a sentence like "maximiza 3*x + 4*y" puts one of those letters exactly where + an unknown belongs. Only the operator it touches tells the reader which it is, and both readers + have to use the same test: a shared fact of the math language, not part of either reading + strategy. The trade is stated in the README -- a one letter operand next to an operator always + wins -- which is why a bound marker in the data is chosen to be a word that cannot be a letter. + """ + if len(word) != 1 or not ("a" <= word <= "z") or word in DOMAIN_LETTERS: + return False + if (word,) not in phrase_index(lang): + return True + if before and before[-1] in OPERATOR_BEFORE: + return True + return bool(after and after[0] in OPERATOR_AFTER) + + +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"\{[TFVABM]\}") + + +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. ``la matrice inversa di {M}`` names ``matrice``, and a reader that called that + word 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 + Latin letter is skipped, because a letter is the unknown of the math language and no pattern + ever writes one outside a slot. + """ + 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/lgstratum/pipeline.py b/lgstratum/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..8028742f7e85eeed0f1e322967f9f9d1e557f811 --- /dev/null +++ b/lgstratum/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 math 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 math 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_math: 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_MATH_BACKEND") + if not call_math: + os.environ["LGSTRATUM_MATH_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_math: + if previous is None: + os.environ.pop("LGSTRATUM_MATH_BACKEND", None) + else: + os.environ["LGSTRATUM_MATH_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.""" + math_verdict = dossier.get("math") or {} + if not math_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, math_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/lgstratum/protocol.py b/lgstratum/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..0ca32905577ecd8e065a532d09b00f5fb8b3a99f --- /dev/null +++ b/lgstratum/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 math stratum uses, +which is what lets one orchestrator run either topology without knowing the difference. + +The dossier of a math-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 math language handed to the math stratum +``math`` the verdict the math stratum 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/lgstratum/read_a.py b/lgstratum/read_a.py new file mode 100644 index 0000000000000000000000000000000000000000..12244359ad4e5f62c23f04ed631c3bfca87fa4ce --- /dev/null +++ b/lgstratum/read_a.py @@ -0,0 +1,334 @@ +"""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 mathematics in a slot. A pattern matches only +if every function word it names is present, in order, and if every verb and every marker 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:`lgstratum.read_b`) does something different with the same data -- it looks for the +marker *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 and the atomiser in +:mod:`lgstratum.segment`, just as the two formalizers of the math topology share one written +grammar and one token spec. +""" + +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"\{([TFVABM])\}") +_CONTENT = ("math", "var", "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_variable(word: str, lang: str, before: str, after: str) -> bool: + """A one letter Latin word touching an operator: a variable, not the function word it looks like.""" + return lexicon.operand(lang, word, before, after) + + +def scan(lang: str, text: str) -> List[Dict[str, Any]]: + """Tag every atom: mathematics, variable, or a lexicon phrase with its role and value. + + One longest match per position decides between verb, connective, marker and noise, which is + why a data file must not give one phrase two roles. The comparison connectives are written in + long and short form side by side, so the longer reading of "at least" never degenerates into + the shorter reading of "greater than". + """ + 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) + before = items[-1]["value"] if items and items[-1]["role"] == "math" else "" + after = atoms[index + 1][1] if index + 1 < len(atoms) and atoms[index + 1][0] == "m" else "" + if _is_variable(word, lang, before, after): + items.append({"role": "var", "value": word, "words": [], "surface": atom}) + index += 1 + continue + 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: + (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 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 the mathematics of a slot. + items.append({"role": "noise", "value": "", "words": [word], "surface": atom}) + index += 1 + continue + if word in lexicon.DOMAIN_LETTERS: + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom, + "reason": "domain_letter"}) + index += 1 + continue + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom}) + index += 1 + return items + + +def _text(item: Dict[str, Any]) -> str: + """The mathematics an item contributes to a slot: its symbols, its variable, its relation.""" + 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 mathematics, and mathematics is never 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 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 mathematics held between two positions, or ``None`` when an unnamed word stands there.""" + 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]]) -> 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 -- Hindi writes the integrand and the lower bound one after + the other -- and then the region has to break into exactly one run per slot. 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): + return None + 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 + + +def match(chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]], + attached: List[str]) -> Optional[Dict[str, str]]: + """A value per slot name, or ``None`` when the pattern does not describe the items. + + Every verb and every marker of the sentence has to be consumed by a chunk of the pattern, and + the mathematics left over falls into the slots in the order the pattern names them. A pattern + that ignores a marker the sentence carries is a pattern that misread the sentence, so it fails; + so does a pattern that leaves a piece of mathematics 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 mathematics, but mathematics before it belongs to no slot of the + # pattern, and a verb or a marker 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) + 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: mathematics 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) + if part is None: + return None + filled.update(part) + return filled + + +def _slot_problems(kind: str, slots: Dict[str, str]) -> List[Dict[str, str]]: + """A slot that is not the shape the kind promises: one variable, a matrix, closed brackets.""" + problems: List[Dict[str, str]] = [] + for name, value in sorted(slots.items()): + if name == "V" and canonical.variable(value) is None: + problems.append({"reason": "bad_variable", "slot": name}) + if name == "M" and canonical.matrix(value) is None: + problems.append({"reason": "bad_matrix", "slot": name}) + if not canonical.balanced(canonical.print_math(kind, slots)): + problems.append({"reason": "unbalanced"}) + 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) + 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) + if assigned is None: + continue + try: + math_str = canonical.print_math(kind, assigned) + except canonical.ReadingError as error: + result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)}) + continue + problems = _slot_problems(kind, assigned) + 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 any(note["reason"] in ("bad_variable", "bad_matrix", "unbalanced") + 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/lgstratum/read_b.py b/lgstratum/read_b.py new file mode 100644 index 0000000000000000000000000000000000000000..9249c1cffe8dcebe0392a1cd2d2c8de269ac6efd --- /dev/null +++ b/lgstratum/read_b.py @@ -0,0 +1,306 @@ +"""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 math language: the markers the sentence carries, in the order it +carries them. Where the verb stands, which words surround it and whether the sentence puts the +mathematics first or last are all invisible to B. It asks one question: does the sentence hold the +joints of a form of the math language, with a piece of mathematics 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 math language -- the same +kind of sharing the two formalizers of the math topology accept, where one written grammar is the +specification both are checked against. +""" + +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", "var", "connective") + + +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 "in the integers" 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 _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 _neighbours(atoms: List[Tuple[str, str]], index: int) -> Tuple[str, str]: + """The runs of mathematics standing on either side of an atom, empty where a word stands.""" + before = atoms[index - 1][1] if index and atoms[index - 1][0] == "m" else "" + after = "" + if index + 1 < len(atoms) and atoms[index + 1][0] == "m": + after = atoms[index + 1][1] + return before, after + + +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 is less suspicious than A about a single letter: it calls it a variable whenever no lexicon + phrase claimed it, because it has no operator adjacency to reason with. That is one of the ways + the two readers can part company, and a bare letter in the middle of an Italian phrase is + exactly where they do. + """ + attached = lexicon.prefixes(lang) + 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] + before, after = _neighbours(atoms, index) + if (span["role"] in ("connective", "marker", "verb") + and span["end"] == span["start"] + 1 + and lexicon.operand(lang, fold(atom), before, after)): + # A phrase of one letter claimed a letter that stands against an operator: in the + # math language that letter is the unknown, and a reading that swaps it for the + # conjunction it spells changes the problem the user asked about. + items.append({"role": "var", "value": fold(atom), "words": [], "surface": atom}) + index = span["end"] + continue + 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 len(word) == 1 and "a" <= word <= "z": + items.append({"role": "var", "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 word in lexicon.DOMAIN_LETTERS: + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom, + "reason": "domain_letter"}) + 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 mathematics of a sentence, each tagged with the joint standing before it. + + A joint of the math 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 English, Spanish, + Italian and Chinese front the variable ("for x solve ...") and a reader that filled the slots by + position would put the unknown where the formula belongs. + + The atoms of a region are joined with a space on purpose. The atomiser cuts the mathematics of a + sentence into runs, and one run can be the whole expression while two runs can be the two ends + of one expression split by a word that is mathematics to the math stratum and a word to the + lexicon (``n mod 3 = 1``). 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 _assign_joints(marked: List[Tuple[Optional[str], str]], gaps: List[Optional[str]], + slots: 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 the one region of the sentence no joint claims. A region holding no + mathematics is never a candidate, and every region that does hold mathematics has to end up in a + slot: mathematics left over belongs to no slot of the form, so the form does not describe the + sentence. This is also how a joint the math language puts last (``over Z``) 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. + """ + introduced: Dict[str, List[int]] = {} + unclaimed: List[int] = [] + for index, (joint, _) in enumerate(marked): + if joint is None: + unclaimed.append(index) + else: + introduced.setdefault(joint, []).append(index) + assigned: Dict[str, str] = {} + taken: set = set() + for position, slot in enumerate(slots): + joint = gaps[position] + if joint is None: + candidates = [index for index in unclaimed + if index not in taken and marked[index][1]] + else: + candidates = [index for index in introduced.get(joint, []) + if index not in taken and marked[index][1]] + if len(candidates) != 1: + return None + assigned[slot] = marked[candidates[0]][1] + taken.add(candidates[0]) + last = gaps[len(slots)] + if last is not None and any(marked[index][1] for index in introduced.get(last, [])): + 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]) -> List[Dict[str, str]]: + problems: List[Dict[str, str]] = [] + for name, value in sorted(slots.items()): + if name == "V" and canonical.variable(value) is None: + problems.append({"reason": "bad_variable", "slot": name}) + if name == "M" and canonical.matrix(value) is None: + problems.append({"reason": "bad_matrix", "slot": name}) + if not canonical.balanced(canonical.print_math(kind, slots)): + 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) + 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) + if assigned is None: + result["notes"].append({"reason": "markers", "kind": kind, + "detail": " ".join(markers)}) + continue + try: + math_str = canonical.print_math(kind, assigned) + except ReadingError as error: + result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)}) + continue + problems = _problems(kind, assigned) + 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/lgstratum/render.py b/lgstratum/render.py new file mode 100644 index 0000000000000000000000000000000000000000..5bbd71b85c0774606db1200db863aff1c5508027 --- /dev/null +++ b/lgstratum/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 mathematical content -- the canonical sentence the stratum understood and the answer the math + stratum 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 +``integral 3*x^2 from 0 to 2 wrt x`` 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 math 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 math stratum.""" + 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 solver family the math stratum used is its own bookkeeping and nothing the reader + # of an answer asked for; what belongs in the reply is the verdict and, when the math + # stratum 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("math_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/lgstratum/segment.py b/lgstratum/segment.py new file mode 100644 index 0000000000000000000000000000000000000000..1be79b39ee6382dc31d2dfedee53a460cd18663d --- /dev/null +++ b/lgstratum/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 math language uses. The +mapping from a word to a role is the lexicon, in ``lexicon/.json`` and +:mod:`lgstratum.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 mathematics only between two closed operands, which is what separates an Italian + sentence comma from the comma of a matrix literal. +""" + +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 math language, square brackets included: a matrix literal 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 math 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 math + 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 math language open + a mathematics run. An ASCII letter run is returned as a word: :mod:`lgstratum.read_a` and + :mod:`lgstratum.read_b` decide between a variable 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..59c4ec32f2a8d1e860a87b32fabe49d557022440 --- /dev/null +++ b/nodes/adversary/grammar.gf @@ -0,0 +1,104 @@ +-- Node adversary (adversary): Adversary: states the ceiling the reading layer can honestly claim and writes the inequality a raised assurance would break. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/adversary/ontology.smt2 b/nodes/adversary/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..f3bc940ab3548d892e56c0753fe9c425a0804802 --- /dev/null +++ b/nodes/adversary/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node adversary. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..e7a06149ff45693bfa515ed5b9ba425e86a58b98 --- /dev/null +++ b/nodes/arbiter/grammar.gf @@ -0,0 +1,104 @@ +-- 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. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/arbiter/ontology.smt2 b/nodes/arbiter/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..1f6fa3d8a45c388067c34aa992d1fcbf2bdfad16 --- /dev/null +++ b/nodes/arbiter/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node arbiter. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(set-option :timeout 8000) diff --git a/nodes/arbiter/seed_payload.json b/nodes/arbiter/seed_payload.json new file mode 100644 index 0000000000000000000000000000000000000000..a5cb914ca491c7fd112e206cea6d8280601e32f7 --- /dev/null +++ b/nodes/arbiter/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "arbiter", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "question (it): risolvi x^2 - 5*x + 6 = 0 per x\n@@DOSSIER@@{\"lang\":\"it\",\"question\":\"risolvi x^2 - 5*x + 6 = 0 per x\"}", + "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..f6091d5a0fbaa7ce2cdf03438220b483668cfba9 --- /dev/null +++ b/nodes/boundary/grammar.gf @@ -0,0 +1,104 @@ +-- Node boundary (boundary): Boundary: checks that the sentence the math topology says it solved is the sentence that was sent to it. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/boundary/ontology.smt2 b/nodes/boundary/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..0ad9f99fe47aa06e49183b19d4380a8627f5e467 --- /dev/null +++ b/nodes/boundary/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node boundary. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..a166fe2daae50c3927f76710dd340744676271ce --- /dev/null +++ b/nodes/coverage/grammar.gf @@ -0,0 +1,104 @@ +-- Node coverage (coverage): Coverage: checks that the reading keeps every number written in the question and that the question is inside the coverage of its language. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/coverage/ontology.smt2 b/nodes/coverage/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..e6cc3ecd6c643d1ed507e6c2a6098699faa3800a --- /dev/null +++ b/nodes/coverage/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node coverage. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..03371207836ea7c0a2c2b3cae5b6686ea44d633a --- /dev/null +++ b/nodes/equivalence/grammar.gf @@ -0,0 +1,104 @@ +-- Node equivalence (equivalence): Equivalence: compares the two readings and says whether they state the same problem, with an SMT view when the text view is not enough. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/equivalence/ontology.smt2 b/nodes/equivalence/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..46c6c6c1be15797ca07894db22249c4a819628b1 --- /dev/null +++ b/nodes/equivalence/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node equivalence. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..6ad9299cb6ceab5f92e1a3c02b7543dea915a470 --- /dev/null +++ b/nodes/invoker/grammar.gf @@ -0,0 +1,104 @@ +-- Node invoker (invoker): Invoker: hands the agreed sentence to the math topology as a separate process and carries that verdict back untouched. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/invoker/ontology.smt2 b/nodes/invoker/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..fae3562a2f477d84d1959e9e2b3e7ebaa2f0a9dd --- /dev/null +++ b/nodes/invoker/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node invoker. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..6ed5d53606395b33dca34d8fd8c2ef02751d4ed8 --- /dev/null +++ b/nodes/reader_a/grammar.gf @@ -0,0 +1,104 @@ +-- Node reader_a (reader_a): First reader: turns a question written in one of the six user languages into a sentence of MathLang, without seeing the other reader. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/reader_a/ontology.smt2 b/nodes/reader_a/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..84099c6ff359d445a513c7daa27c9d9d21278394 --- /dev/null +++ b/nodes/reader_a/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node reader_a. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..3161f32d33fbd1199f21fc5fb4893ff913beb9ba --- /dev/null +++ b/nodes/reader_b/grammar.gf @@ -0,0 +1,104 @@ +-- 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. +-- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology. +-- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/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 and variables are written bare (3, x) instead of (Lit 3), (V x), +-- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)), +-- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min. +abstract MathLang = { + cat + Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ; + fun + Evaluate : Term -> Problem ; + Prove, ProveZ : Formula -> Problem ; + Solve, SolveZ : Formula -> Var -> Problem ; + SolveSys : Formula -> Names -> Problem ; + Derivative, Antiderivative : Term -> Problem ; + DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ; + Integral : Term -> Term -> Term -> Problem ; + IntegralWrt : Term -> Var -> Term -> Term -> Problem ; + Optimize : Dir -> Term -> Formula -> Problem ; + Max, Min : Dir ; + Det, Rank, Inverse, Nullspace : Mat -> Problem ; + Linsolve : Mat -> Vec -> Problem ; + Product : Mat -> Mat -> Problem ; + Power : Mat -> Term -> Problem ; + Maxflow : Mat -> Term -> Term -> Problem ; + Reduce : Mat -> Problem ; + Sos : Mat -> Problem ; + Dot : Vec -> Vec -> Term ; + Matvec : Mat -> Vec -> Vec ; + Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ; + And, Or, Imp, Iff : Formula -> Formula -> Formula ; + Not : Formula -> Formula ; + Forall, Exists : Var -> Dom -> Formula -> Formula ; + True, False : Formula ; + Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ; + Neg : Term -> Term ; + Lit : String -> Term ; + V : Var -> Term ; + MkVar : String -> Var ; + R, Z : Dom ; +} + +concrete MathLangEng of MathLang = { + lincat + Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ; + lin + Evaluate t = "evaluate" ++ t ; + Prove f = "prove" ++ f ; + ProveZ f = "prove" ++ f ++ "over" ++ "Z" ; + Solve f v = "solve" ++ f ++ "for" ++ v ; + SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ; + SolveSys f ns = "solve" ++ f ++ "for" ++ ns ; + Derivative t = "derivative" ++ t ; + DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ; + Antiderivative t = "antiderivative" ++ t ; + AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ; + Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ; + IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ; + Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ; + Max = "maximize" ; + Min = "minimize" ; + Det m = "det" ++ m ; + Rank m = "rank" ++ m ; + Inverse m = "inverse" ++ m ; + Nullspace m = "nullspace" ++ m ; + Linsolve m v = "linsolve" ++ m ++ v ; + Product a b = "product" ++ a ++ b ; + Power m t = "power" ++ m ++ t ; + Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ; + Reduce m = "reduce" ++ m ; + Sos m = "sos" ++ m ; + Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ; + Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ; + Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ; + Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ; + Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ; + Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ; + Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ; + Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ; + Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ; + And a b = "(" ++ a ++ "and" ++ b ++ ")" ; + Or a b = "(" ++ a ++ "or" ++ b ++ ")" ; + Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ; + Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ; + Not a = "not" ++ a ; + Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ; + True = "true" ; + False = "false" ; + Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; + Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; + Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; + Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; + Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; + Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ; + Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Lit s = s.s ; + V v = v ; + MkVar s = s.s ; + R = "R" ; + Z = "Z" ; +} diff --git a/nodes/reader_b/ontology.smt2 b/nodes/reader_b/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..85ed2c91fd9f0223b5b07ccea3476e9ecfe1322a --- /dev/null +++ b/nodes/reader_b/ontology.smt2 @@ -0,0 +1,5 @@ +; SMT-LIB 2 ontology for the math-stratum topology node reader_b. +; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options: +; without a timeout one hard nonlinear query could block the whole session, and the claims of +; this stratum are equalities over numerals, which Z3 decides in milliseconds. +(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..f7c26951dc707c338426c7e26c14e60e6f867553 --- /dev/null +++ b/problems/corpus.jsonl @@ -0,0 +1,73 @@ +{"id": "it-01", "lang": "it", "kind": "evaluate", "question": "quanto fa 1/2 + 1/3", "why": "evaluate verb phrase quanto fa; both readers know it, math answers 5/6", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}} +{"id": "it-02", "lang": "it", "kind": "prove", "question": "dimostra che x^2 + 1 > 0", "why": "prove verb dimostra with the complementiser che", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}} +{"id": "it-04", "lang": "it", "kind": "solve", "question": "risolvi x^2 - 5*x + 6 = 0 per x", "why": "solve verb risolvi with the for marker per; math answers the two roots", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}} +{"id": "it-05", "lang": "it", "kind": "det", "question": "il determinante di [[1, 2], [3, 4]]", "why": "noun-first construct pattern; math answers -2", "expect": {"state": "AGREED", "sentence": "det [[1, 2], [3, 4]]", "answer_contains": "-2", "min_assurance": 2, "referee_clean": true}} +{"id": "it-06", "lang": "it", "kind": "inverse", "question": "la matrice inversa di [[2, 0], [0, 2]]", "why": "inverse verb inversa inside the la matrice ... di frame, whose filler word matrice is a word of the variety because the pattern writes it", "expect": {"state": "AGREED", "sentence": "inverse [[2, 0], [0, 2]]", "min_assurance": 2, "referee_clean": true}} +{"id": "it-07", "lang": "it", "kind": "maximize", "question": "massimizza 3*x + 4*y sotto i vincoli x + y <= 10", "why": "maximize verb with the subject to variant sotto i vincoli; the math stratum reads the problem and answers that the objective improves without limit", "expect": {"state": "AGREED", "sentence": "maximize 3*x + 4*y subject to x + y <= 10", "min_assurance": 2, "referee_clean": true}} +{"id": "it-08", "lang": "it", "kind": "integral", "question": "l'integrale di 3*x^2 da 0 a 2", "why": "integral with the from marker da and the to marker a; math answers 8", "expect": {"state": "AGREED", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "min_assurance": 2, "referee_clean": true}} +{"id": "it-09", "lang": "it", "kind": "negative", "question": "glorifram zepivardo frumeta", "why": "latin gibberish: no announce verb and no known word, the layer must not guess", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-10", "lang": "it", "kind": "negative", "question": "dimostra che x e uguale a y", "why": "the connective e for and collides with the equality phrase e uguale a in one gap", "expect": {"max_assurance": 2, "referee_clean": true}} +{"id": "it-11", "lang": "it", "kind": "negative", "question": "il determinante di [1, 2], [3, 4]", "why": "the det pattern is there but the matrix is not written in double brackets", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-12", "lang": "it", "kind": "passthrough", "question": "solve x^2 - 5*x + 6 = 0 for x", "why": "the question is already a sentence of the math language: nothing is translated", "expect": {"state": "PASSTHROUGH", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}} +{"id": "en-01", "lang": "en", "kind": "evaluate", "question": "what is the value of 7/3 - 7/3 * 3", "why": "evaluate verb phrase what is the value of; math answers 0", "expect": {"state": "AGREED", "sentence": "evaluate 7/3 - 7/3 * 3", "min_assurance": 2, "referee_clean": true}} +{"id": "en-02", "lang": "en", "kind": "provez", "question": "show that x + x = 2*x over the integers", "why": "provez verb show that with the over Z phrase over the integers", "expect": {"state": "AGREED", "sentence": "prove x + x = 2*x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}} +{"id": "en-03", "lang": "en", "kind": "solve", "question": "for x solve 2*x + 3 = 11", "why": "fronted for marker: the variable is named before the verb, and both readers must rotate the frame rather than fill the slots by position", "expect": {"state": "AGREED", "sentence": "solve 2*x + 3 = 11 for x", "answer_contains": "{4}", "min_assurance": 2, "referee_clean": true}} +{"id": "en-04", "lang": "en", "kind": "solvez", "question": "solve n mod 3 = 1 for n over the integers", "why": "solvez frame: the same solve verb plus the integer domain", "expect": {"state": "AGREED", "sentence": "solve n mod 3 = 1 for n over Z", "min_assurance": 2, "referee_clean": true}} +{"id": "en-05", "lang": "en", "kind": "derivative", "question": "differentiate x^3 + 2*x with respect to x", "why": "derivative verb with the wrt phrase with respect to", "expect": {"state": "AGREED", "sentence": "derivative x^3 + 2*x wrt x", "min_assurance": 2, "referee_clean": true}} +{"id": "en-06", "lang": "en", "kind": "rank", "question": "what is the rank of [[1, 2, 3], [4, 5, 6]]", "why": "rank noun inside what is the rank of; math answers 2", "expect": {"state": "AGREED", "sentence": "rank [[1, 2, 3], [4, 5, 6]]", "answer_contains": "2", "min_assurance": 2, "referee_clean": true}} +{"id": "en-07", "lang": "en", "kind": "minimize", "question": "the minimum of 2*x + 3*y subject to x + y = 1", "why": "the minimum of pattern with the subject to marker: a canonical sentence would pass through untranslated, so this one must be read", "expect": {"state": "AGREED", "sentence": "minimize 2*x + 3*y subject to x + y = 1", "min_assurance": 2, "referee_clean": true}} +{"id": "en-08", "lang": "en", "kind": "integral", "question": "integrate x^2 from 0 to 3 with respect to x", "why": "integral frame with from, to and the wrt phrase; math answers 9", "expect": {"state": "AGREED", "sentence": "integral x^2 from 0 to 3 wrt x", "answer_contains": "9", "min_assurance": 2, "referee_clean": true}} +{"id": "en-09", "lang": "en", "kind": "negative", "question": "risolvi x^2 - 5*x + 6 = 0 for x", "why": "an Italian solve verb inside an English frame: the English reader must not read it", "expect": {"max_assurance": 2, "referee_clean": true}} +{"id": "en-10", "lang": "en", "kind": "passthrough", "question": "derivative x^3 wrt x", "why": "a canonical sentence using the wrt joint: pass through with nothing translated", "expect": {"state": "PASSTHROUGH", "sentence": "derivative x^3 wrt x", "min_assurance": 2, "referee_clean": true}} +{"id": "es-01", "lang": "es", "kind": "evaluate", "question": "cuánto vale 12345679 * 9", "why": "evaluate verb phrase cuanto vale; math answers 111111111", "expect": {"state": "AGREED", "sentence": "evaluate 12345679 * 9", "answer_contains": "111111111", "min_assurance": 2, "referee_clean": true}} +{"id": "es-02", "lang": "es", "kind": "prove", "question": "demuestra que x^2 + 1 > 0", "why": "prove verb demuestra with the complementiser que", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}} +{"id": "es-03", "lang": "es", "kind": "solve", "question": "para x resuelve 2*x + 3 = 11", "why": "fronted for marker para: the variable comes before the verb", "expect": {"state": "AGREED", "sentence": "solve 2*x + 3 = 11 for x", "min_assurance": 2, "referee_clean": true}} +{"id": "es-04", "lang": "es", "kind": "solvez", "question": "resuelve n mod 3 = 1 para n en los números enteros", "why": "solvez with the accented over Z variant", "expect": {"state": "AGREED", "sentence": "solve n mod 3 = 1 for n over Z", "min_assurance": 2, "referee_clean": true}} +{"id": "es-05", "lang": "es", "kind": "derivative", "question": "la derivada de 3*x^2 con respecto a x", "why": "noun-first derivative pattern with the wrt phrase con respecto a", "expect": {"state": "AGREED", "sentence": "derivative 3*x^2 wrt x", "min_assurance": 2, "referee_clean": true}} +{"id": "es-06", "lang": "es", "kind": "det", "question": "el determinante de [[3, 1], [2, 4]]", "why": "noun-first construct pattern; math answers 10", "expect": {"state": "AGREED", "sentence": "det [[3, 1], [2, 4]]", "answer_contains": "10", "min_assurance": 2, "referee_clean": true}} +{"id": "es-07", "lang": "es", "kind": "inverse", "question": "invierte [[1, 2], [3, 4]]", "why": "imperative of the inverse verb in the bare invierte M pattern", "expect": {"state": "AGREED", "sentence": "inverse [[1, 2], [3, 4]]", "min_assurance": 2, "referee_clean": true}} +{"id": "es-08", "lang": "es", "kind": "minimize", "question": "minimiza 2*x + 3*y sujeto a x + y = 1", "why": "minimize verb with the subject to marker sujeto a", "expect": {"state": "AGREED", "sentence": "minimize 2*x + 3*y subject to x + y = 1", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-01", "lang": "zh", "kind": "evaluate", "question": "计算 1/2 + 1/3", "why": "evaluate verb in the verb then term pattern", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-02", "lang": "zh", "kind": "prove", "question": "证明 x^2 + 1 > 0", "why": "prove verb in the bare prove pattern", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-03", "lang": "zh", "kind": "provez", "question": "证明 x + x = 2*x 在整数上", "why": "provez with the over Z marker meaning over the integers", "expect": {"state": "AGREED", "sentence": "prove x + x = 2*x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-04", "lang": "zh", "kind": "solve", "question": "对 x 求解 x^2 - 5*x + 6 = 0", "why": "fronted for marker before the solve verb", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-05", "lang": "zh", "kind": "derivative", "question": "求 x^3 + 2*x 关于 x 的 导数", "why": "derivative noun with the wrt marker and the noise particle", "expect": {"state": "AGREED", "sentence": "derivative x^3 + 2*x wrt x", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-06", "lang": "zh", "kind": "integral", "question": "求 3*x^2 从 0 到 2 的 积分", "why": "integral noun with the from and to markers; math answers 8", "expect": {"state": "AGREED", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-07", "lang": "zh", "kind": "rank", "question": "求 [[1, 2, 3], [4, 5, 6]] 的 秩", "why": "rank noun in the matrix then particle then rank pattern", "expect": {"state": "AGREED", "sentence": "rank [[1, 2, 3], [4, 5, 6]]", "answer_contains": "2", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-08", "lang": "zh", "kind": "maximize", "question": "最大化 3*x + 4*y 约束 x + y <= 10", "why": "maximize verb with the short subject to marker; the math stratum answers unbounded", "expect": {"state": "AGREED", "sentence": "maximize 3*x + 4*y subject to x + y <= 10", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-09", "lang": "zh", "kind": "negative", "question": "喵叽咕噗噜", "why": "cjk gibberish: no verb and no noise character of the lexicon", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "zh-10", "lang": "zh", "kind": "negative", "question": "求 从 0 到 2 的 积分", "why": "the integral frame carries the from and to joints but the integrand slot is empty", "expect": {"max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "hi-01", "lang": "hi", "kind": "evaluate", "question": "गणना करें 1/2 + 1/3", "why": "evaluate verb in the verb first pattern", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-02", "lang": "hi", "kind": "prove", "question": "सिद्ध करें x^2 + 1 > 0", "why": "prove verb in the verb first prove pattern", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-03", "lang": "hi", "kind": "solve", "question": "x^2 - 5*x + 6 = 0 के लिए x हल करें", "why": "verb final solve order: formula, for marker, variable, verb", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-04", "lang": "hi", "kind": "solvez", "question": "हल करें n mod 3 = 1 के लिए n पूर्णांकों में", "why": "solvez with the for marker and the over Z variant", "expect": {"state": "AGREED", "sentence": "solve n mod 3 = 1 for n over Z", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-05", "lang": "hi", "kind": "derivative", "question": "3*x^2 का x के सापेक्ष अवकलज", "why": "the genitive particle का separates the integrand from the variable without being a joint, so reader A reads the postpositional frame and reader B abstains: one reading only, so the assurance stops at 1 and the answer is still given", "expect": {"state": "SINGLE", "sentence": "derivative 3*x^2 wrt x", "answer_contains": "6*x", "max_assurance": 1, "referee_clean": true}} +{"id": "hi-06", "lang": "hi", "kind": "det", "question": "[[1, 2], [3, 4]] का सारणिक", "why": "det noun in the matrix then particle then rank pattern", "expect": {"state": "AGREED", "sentence": "det [[1, 2], [3, 4]]", "answer_contains": "-2", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-07", "lang": "hi", "kind": "inverse", "question": "व्युत्क्रम बताइए [[2, 0], [0, 2]]", "why": "inverse noun with the tell me pattern", "expect": {"state": "AGREED", "sentence": "inverse [[2, 0], [0, 2]]", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-08", "lang": "hi", "kind": "minimize", "question": "न्यूनतम करें 2*x + 3*y के अधीन x + y = 1", "why": "minimize verb with the subject to marker meaning subject to", "expect": {"state": "AGREED", "sentence": "minimize 2*x + 3*y subject to x + y = 1", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-09", "lang": "hi", "kind": "negative", "question": "झुगपट गैंवूलो डठकू", "why": "devanagari gibberish: no verb and no noise word of the lexicon", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "hi-10", "lang": "hi", "kind": "integral", "question": "समाकलन करें 3*x^2 का 0 से 2 तक", "why": "postpositional from and to markers with the genitive particle: reader A knows this order, reader B abstains, so only one reading stands and the assurance stops at 1", "expect": {"state": "SINGLE", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "max_assurance": 1, "referee_clean": true}} +{"id": "ar-01", "lang": "ar", "kind": "evaluate", "question": "احسب قيمة 1/2 + 1/3", "why": "evaluate verb in the compute the value of pattern", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-02", "lang": "ar", "kind": "prove", "question": "أثبت أن x^2 + 1 > 0", "why": "prove verb with the that complementiser", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-03", "lang": "ar", "kind": "provez", "question": "أثبت x + x = 2*x على أعداد صحيحة", "why": "provez with the over Z variant meaning over the integers", "expect": {"state": "AGREED", "sentence": "prove x + x = 2*x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-04", "lang": "ar", "kind": "solve", "question": "حل x^2 - 5*x + 6 = 0 إيجاد x", "why": "solve verb with the for marker: the same word also names the find verb, which is why the readers must agree here", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-05", "lang": "ar", "kind": "integral", "question": "تكامل 3*x^2 من 0 إلى 2", "why": "integral noun with the from and to markers; math answers 8", "expect": {"state": "AGREED", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-06", "lang": "ar", "kind": "rank", "question": "رتبة [[1, 2, 3], [4, 5, 6]]", "why": "rank noun in the bare construct pattern", "expect": {"state": "AGREED", "sentence": "rank [[1, 2, 3], [4, 5, 6]]", "answer_contains": "2", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-07", "lang": "ar", "kind": "inverse", "question": "معاكسة [[1, 2], [3, 4]]", "why": "inverse noun in the bare construct pattern", "expect": {"state": "AGREED", "sentence": "inverse [[1, 2], [3, 4]]", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-08", "lang": "ar", "kind": "maximize", "question": "عظم 3*x + 4*y شرط x + y <= 10", "why": "maximize verb with the short subject to marker; the math stratum answers unbounded", "expect": {"state": "AGREED", "sentence": "maximize 3*x + 4*y subject to x + y <= 10", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-09", "lang": "ar", "kind": "negative", "question": "شقطبي ملموغ قلفوص", "why": "arabic gibberish: no announce verb and no known word", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "ar-10", "lang": "ar", "kind": "negative", "question": "احسب قيمة xrqt3 + 1/3", "why": "valid evaluate pattern but a latin gibberish symbol inside the math slot: the math layer refuses, so no answer", "expect": {"max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "ar-11", "lang": "ar", "kind": "evaluate", "question": "احسب ١/٢ + ١/٣", "why": "Arabic-Indic digits as the Arabic lexicon itself writes them: segment normalises them to ASCII, so this is the same problem as ar-01", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}} +{"id": "mixed-01", "lang": "en", "kind": "negative", "question": "solve 25 + x = 30 for x", "why": "full width digits inside a math sentence: normalisation turns them into ASCII, so the sentence is accepted", "expect": {"max_assurance": 2, "referee_clean": true}} +{"id": "mixed-02", "lang": "hi", "kind": "negative", "question": "solve x^2 - 5*x + 6 = 0 for x", "why": "an English math sentence asked in Hindi: it passes through without any Hindi word", "expect": {"state": "PASSTHROUGH", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}} +{"id": "mixed-03", "lang": "ar", "kind": "negative", "question": "حل x^2 - 5*x + 6 = 0 per x", "why": "an Italian for marker inside an Arabic solve frame: the joint is not Arabic, so the variable slot stays empty", "expect": {"max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "mixed-04", "lang": "zh", "kind": "negative", "question": "计算 1/2 + 1/3 hello world", "why": "a cjk evaluate frame followed by latin noise: the trailing words are not part of any pattern", "expect": {"max_assurance": 2, "referee_clean": true}} +{"id": "mixed-05", "lang": "es", "kind": "negative", "question": "demuestra que x^2 + 1 > 0حل", "why": "an Arabic verb glued to the end of a Spanish sentence with no space: no reader may invent a boundary", "expect": {"max_assurance": 2, "referee_clean": true}} +{"id": "it-03", "lang": "it", "kind": "provez", "question": "dimostra che 2*x = x + x sugli interi", "why": "provez frame: the over Z marker sugli interi selects the integer domain", "expect": {"state": "AGREED", "sentence": "prove 2*x = x + x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-12", "lang": "ar", "kind": "provez", "question": "أثبت n^2 + n = n*(n + 1) على أعداد صحيحة", "why": "agreed reading, refused by the math stratum: powers over the integers are outside its formalizer", "expect": {"state": "AGREED", "sentence": "prove n^2 + n = n*(n + 1) over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "en-11", "lang": "en", "kind": "provez", "question": "show that x^2 - 1 = (x + 1)*(x - 1) over the integers", "why": "agreed reading, refused by the math stratum: powers over the integers are outside its formalizer, so the stratum withholds the verdict", "expect": {"state": "AGREED", "sentence": "prove x^2 - 1 = (x + 1)*(x - 1) over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "en-12", "lang": "en", "kind": "minimize", "question": "the minimum of x^2 + y^2 subject to x + y = 1", "why": "agreed reading of a nonlinear objective: the math stratum says the problem is not linear, so the stratum lowers the assurance to match", "expect": {"state": "AGREED", "sentence": "minimize x^2 + y^2 subject to x + y = 1", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "es-09", "lang": "es", "kind": "minimize", "question": "minimiza x^2 + y^2 sujeto a x + y = 1", "why": "agreed reading, nonlinear objective: the math stratum abstains and the stratum shows nothing", "expect": {"state": "AGREED", "sentence": "minimize x^2 + y^2 subject to x + y = 1", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "hi-11", "lang": "hi", "kind": "minimize", "question": "न्यूनतम करें x^2 + y^2 के अधीन x + y = 1", "why": "agreed reading, nonlinear objective: the math stratum abstains and the stratum shows nothing", "expect": {"state": "AGREED", "sentence": "minimize x^2 + y^2 subject to x + y = 1", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-13", "lang": "it", "kind": "provez", "question": "dimostra che x^2 + 2*x + 1 = (x + 1)^2 sugli interi", "why": "the reading is agreed by both readers, but the math stratum refuses powers over the integers, so the stratum shows no assurance and no answer: the reading ceiling is never what lifts the verdict", "expect": {"state": "AGREED", "sentence": "prove x^2 + 2*x + 1 = (x + 1)^2 over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "zh-11", "lang": "zh", "kind": "provez", "question": "证明 n^2 + n = n*(n + 1) 在整数上", "why": "agreed reading, refused by the math stratum: powers over the integers are outside its formalizer", "expect": {"state": "AGREED", "sentence": "prove n^2 + n = n*(n + 1) over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}} 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..f97b31227bb68f9a48b7b2f5e005b5186fdc3ba4 --- /dev/null +++ b/results/ablation.json @@ -0,0 +1,2185 @@ +{ + "cells": { + "S1 reader_a | reader_a:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S1 reader_a | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S4 +coverage | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S5 +invoker | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S6 +boundary | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S7 +adversary | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:drop_marker,reader_b:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 full topology | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:merge_slots": { + "abstained": 0, + "activated": 0, + "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": 6, + "activated": 6, + "caught": 0, + "details": [], + "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": 6, + "activated": 6, + "caught": 0, + "details": [], + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "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": 0, + "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": "ar-01", + "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": "en-01", + "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": "es-01", + "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": "hi-01", + "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": "it-01", + "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": "zh-01", + "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": "ar-01", + "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": "en-01", + "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": "es-01", + "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": "hi-01", + "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": "it-01", + "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": "zh-01", + "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": "ar-01", + "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": "en-01", + "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": "es-01", + "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": "hi-01", + "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": "it-01", + "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": "zh-01", + "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:drop_marker": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 6, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:merge_slots": { + "abstained": 0, + "activated": 0, + "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": [ + "ar-01", + "en-01", + "es-01", + "hi-01", + "it-01", + "zh-01" + ], + "seconds": 866.6, + "totals": { + "abstained": 366, + "activated": 510, + "caught": 18, + "lowered": 0, + "masked": 126, + "raised": 0, + "runs": 882, + "silent_error": 0 + }, + "violations": [ + { + "config": "S8 minus reader_b", + "fault": [ + "equivalence:rubber_stamp" + ], + "flagged": false, + "honest": 2, + "id": "ar-01", + "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": "en-01", + "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": "es-01", + "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": "hi-01", + "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": "it-01", + "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": "zh-01", + "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": "ar-01", + "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": "en-01", + "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": "es-01", + "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": "hi-01", + "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": "it-01", + "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": "zh-01", + "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": "ar-01", + "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": "en-01", + "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": "es-01", + "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": "hi-01", + "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": "it-01", + "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": "zh-01", + "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..4ec978d551b6a0910bb78b948c20eeae0b7b73b7 --- /dev/null +++ b/results/coverage.json @@ -0,0 +1,1265 @@ +{ + "inventory": { + "ar": { + "connectives": 17, + "kinds": [ + "derivative", + "det", + "evaluate", + "integral", + "inverse", + "maximize", + "minimize", + "prove", + "provez", + "rank", + "solve", + "solvez" + ], + "markers": 10, + "noise_words": 9, + "pattern_words": 94, + "patterns": 35, + "verb_phrases": 22 + }, + "en": { + "connectives": 20, + "kinds": [ + "derivative", + "det", + "evaluate", + "integral", + "inverse", + "maximize", + "minimize", + "prove", + "provez", + "rank", + "solve", + "solvez" + ], + "markers": 11, + "noise_words": 15, + "pattern_words": 146, + "patterns": 44, + "verb_phrases": 23 + }, + "es": { + "connectives": 18, + "kinds": [ + "derivative", + "det", + "evaluate", + "integral", + "inverse", + "maximize", + "minimize", + "prove", + "provez", + "rank", + "solve", + "solvez" + ], + "markers": 11, + "noise_words": 17, + "pattern_words": 128, + "patterns": 42, + "verb_phrases": 29 + }, + "hi": { + "connectives": 17, + "kinds": [ + "derivative", + "det", + "evaluate", + "integral", + "inverse", + "maximize", + "minimize", + "prove", + "provez", + "rank", + "solve", + "solvez" + ], + "markers": 7, + "noise_words": 14, + "pattern_words": 162, + "patterns": 46, + "verb_phrases": 23 + }, + "it": { + "connectives": 20, + "kinds": [ + "derivative", + "det", + "evaluate", + "integral", + "inverse", + "maximize", + "minimize", + "prove", + "provez", + "rank", + "solve", + "solvez" + ], + "markers": 10, + "noise_words": 22, + "pattern_words": 121, + "patterns": 46, + "verb_phrases": 31 + }, + "zh": { + "connectives": 18, + "kinds": [ + "derivative", + "det", + "evaluate", + "integral", + "inverse", + "maximize", + "minimize", + "prove", + "provez", + "rank", + "solve", + "solvez" + ], + "markers": 9, + "noise_words": 5, + "pattern_words": 273, + "patterns": 55, + "verb_phrases": 18 + } + }, + "items": 73, + "languages": { + "ar": { + "agreed": 10, + "items": 13, + "not covered": 3, + "reader_a_read": 10, + "reader_b_read": 10 + }, + "en": { + "agreed": 11, + "items": 13, + "not covered": 1, + "passthrough": 1, + "reader_a_read": 11, + "reader_b_read": 11 + }, + "es": { + "agreed": 9, + "items": 10, + "not covered": 1, + "reader_a_read": 9, + "reader_b_read": 9 + }, + "hi": { + "agreed": 8, + "items": 12, + "not covered": 1, + "passthrough": 1, + "reader_a_read": 10, + "reader_b_read": 8, + "single": 2 + }, + "it": { + "agreed": 10, + "items": 13, + "not covered": 2, + "passthrough": 1, + "reader_a_read": 10, + "reader_b_read": 10 + }, + "zh": { + "agreed": 9, + "items": 12, + "not covered": 3, + "reader_a_read": 9, + "reader_b_read": 9 + } + }, + "math_consulted": false, + "pairs": { + "ar/evaluate": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "ar/integral": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/inverse": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/maximize": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/negative": { + "items": 3, + "not covered": 3, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "ar/prove": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/provez": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "ar/rank": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/solve": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/derivative": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/evaluate": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/integral": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/minimize": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "en/negative": { + "agreed": 1, + "items": 2, + "not covered": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/passthrough": { + "items": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "en/provez": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "en/rank": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/solve": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/solvez": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/derivative": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/det": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/evaluate": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/inverse": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/minimize": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "es/negative": { + "items": 1, + "not covered": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "es/prove": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/solve": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/solvez": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/derivative": { + "items": 1, + "reader_a_read": 1, + "reader_b_read": 0, + "single": 1 + }, + "hi/det": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/evaluate": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/integral": { + "items": 1, + "reader_a_read": 1, + "reader_b_read": 0, + "single": 1 + }, + "hi/inverse": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/minimize": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "hi/negative": { + "items": 2, + "not covered": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "hi/prove": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/solve": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/solvez": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/det": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/evaluate": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/integral": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/inverse": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/maximize": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/negative": { + "agreed": 1, + "items": 3, + "not covered": 2, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/passthrough": { + "items": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "it/prove": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "it/provez": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "it/solve": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/derivative": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/evaluate": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/integral": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/maximize": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/negative": { + "items": 3, + "not covered": 3, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "zh/prove": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/provez": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "zh/rank": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/solve": { + "agreed": 1, + "items": 1, + "reader_a_read": 1, + "reader_b_read": 1 + } + }, + "rows": [ + { + "assurance": 0, + "id": "it-01", + "kind": "evaluate", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-02", + "kind": "prove", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-04", + "kind": "solve", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-05", + "kind": "det", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-06", + "kind": "inverse", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-07", + "kind": "maximize", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-08", + "kind": "integral", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-09", + "kind": "negative", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "it-10", + "kind": "negative", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-11", + "kind": "negative", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "it-12", + "kind": "passthrough", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "en-01", + "kind": "evaluate", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-02", + "kind": "provez", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-03", + "kind": "solve", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-04", + "kind": "solvez", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-05", + "kind": "derivative", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-06", + "kind": "rank", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-07", + "kind": "minimize", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-08", + "kind": "integral", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-09", + "kind": "negative", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "en-10", + "kind": "passthrough", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "es-01", + "kind": "evaluate", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-02", + "kind": "prove", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-03", + "kind": "solve", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-04", + "kind": "solvez", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-05", + "kind": "derivative", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-06", + "kind": "det", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-07", + "kind": "inverse", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-08", + "kind": "minimize", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-01", + "kind": "evaluate", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-02", + "kind": "prove", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-03", + "kind": "provez", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-04", + "kind": "solve", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-05", + "kind": "derivative", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-06", + "kind": "integral", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-07", + "kind": "rank", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-08", + "kind": "maximize", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-09", + "kind": "negative", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "zh-10", + "kind": "negative", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "hi-01", + "kind": "evaluate", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-02", + "kind": "prove", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-03", + "kind": "solve", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-04", + "kind": "solvez", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-05", + "kind": "derivative", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "NOT COVERED", + "state": "SINGLE" + }, + { + "assurance": 0, + "id": "hi-06", + "kind": "det", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-07", + "kind": "inverse", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-08", + "kind": "minimize", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-09", + "kind": "negative", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "hi-10", + "kind": "integral", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "NOT COVERED", + "state": "SINGLE" + }, + { + "assurance": 0, + "id": "ar-01", + "kind": "evaluate", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-02", + "kind": "prove", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-03", + "kind": "provez", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-04", + "kind": "solve", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-05", + "kind": "integral", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-06", + "kind": "rank", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-07", + "kind": "inverse", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-08", + "kind": "maximize", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-09", + "kind": "negative", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "ar-10", + "kind": "negative", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "ar-11", + "kind": "evaluate", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "mixed-01", + "kind": "negative", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "mixed-02", + "kind": "negative", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "mixed-03", + "kind": "negative", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "mixed-04", + "kind": "negative", + "lang": "zh", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "mixed-05", + "kind": "negative", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "it-03", + "kind": "provez", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-12", + "kind": "provez", + "lang": "ar", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-11", + "kind": "provez", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "en-12", + "kind": "minimize", + "lang": "en", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "es-09", + "kind": "minimize", + "lang": "es", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-11", + "kind": "minimize", + "lang": "hi", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-13", + "kind": "provez", + "lang": "it", + "math_status": "UNKNOWN", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "zh-11", + "kind": "provez", + "lang": "zh", + "math_status": "UNKNOWN", + "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..2488eb4aa56c556b41fc40e6d8cfdf944e9b9f1a --- /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 lgstratum 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_math_stratum_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 math stratum, 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 math stratum 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_math_stratum(): + 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..20e0d6dafd848434b5a68f5b271d42e2881f2d48 --- /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 lgstratum import decide, pipeline + + +def _reading(sentence, kind="evaluate", slots=None, notes=()): + return {"status": "READ", "kind": kind, "math": sentence, "slots": slots or {}, "notes": list(notes)} + + +def _math(status="VERIFIED", assurance=3, answer="4", sentence="evaluate 2+2", **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": "quanto fa 2+2?", "lang": "it", "sent": "evaluate 2+2", + "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_math_stratum(): + # Three belongs to the math stratum: 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_math_answer(): + readings = [_reading("evaluate 2+2"), _reading("evaluate 2+2")] + 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 "4"))) + 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("evaluate 2+2"), {}] + 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("evaluate 2+3"), {}] + final = decide.decide(_dossier(readings, None, {"ok": False}, _math(sentence="evaluate 2+3"))) + 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_math_stratum(): + readings = [_reading("evaluate 2+2"), _reading("evaluate 2+3")] + 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("evaluate 2+2"), _reading("evaluate 2+2")] + 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("evaluate 2+2"), _reading("evaluate 2+2")] + 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_math_language_passes_through(): + direct = {"kind": "evaluate", "math": "evaluate 2+2", "slots": {"T": "2+2"}} + 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_math_stratum_did_not_answer(): + readings = [_reading("evaluate 2+2"), _reading("evaluate 2+2")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, _math("UNKNOWN", 0, ""))) + assert final["assurance"] == 0 + assert final["answer"] == "" + assert "math_unknown" in final["reasons"] + + +def test_the_decision_is_pure_and_leaves_the_evidence_as_it_found_it(): + dossier = _dossier([_reading("evaluate 2+2"), _reading("evaluate 2+2")], {"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("evaluate 2+2"), _reading("evaluate 2+2")], + {"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..7d161da20dbc373b8b7e674c6e5462b684e35b22 --- /dev/null +++ b/tests/test_faults.py @@ -0,0 +1,100 @@ +"""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 math stratum runs: here the misbehaviour is in the +reading and in the reporting, never in the mathematics. 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 lgstratum import agents, canonical, corpus, faults, pipeline + +ITEMS = {item["id"]: item for item in corpus.load()} +ONE = "it-01" + + +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 math + # stratum 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(): + # A reading of an integral carries four slots, and three of them hold a number: every fault of a + # reader has something to bite on. Each one leaves a sentence the math stratum would happily + # solve, which is what makes the experiment measure the readers and not the parser. + kind = "integral" + order = canonical.slots_for(kind) + base = {name: "1" + name for name in order} + for fault in faults.CATALOG["reader_a"]: + faults.configure(["reader_a:" + fault]) + changed, was_changed = faults.mutate_reading("reader_a", kind, base, order) + assert was_changed is True, fault + assert changed != base, fault + assert faults.fired("reader_a") == ["reader_a:" + fault], fault + assert canonical.balanced(canonical.print_math(kind, changed)) is True, fault + faults.configure(()) + + +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_math_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..88af4a5448f4ec8d3512bc52bfdf6bb51cfc41f5 --- /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 lgstratum 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) == 18 + 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 an inverse matrix + # writes the word for matrix 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..8b2339ca4da018f952296fbb4a32c6be080ec885 --- /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 lgstratum 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["it-01"] + 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["it-01"] + 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..665a634085f96ef6b01a25ac3db0a88e07fecf34 --- /dev/null +++ b/tests/test_pinned_invariant.py @@ -0,0 +1,98 @@ +"""The discipline this bundle is built on: changing the conversational layer changes no math verdict. + +The math stratum 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 +math stratum 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 lgstratum import agents, canonical, coverage, corpus, faults, pipeline + +ITEMS = {item["id"]: item for item in corpus.load()} +PINS = ["it-01", "it-04"] +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 _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 math stratum 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_math_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 math stratum 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_math_stratum_was_asked_about_is_the_agreed_one(): + # The echo of the math stratum is written in its own spacing, so what the stratum checks is that + # the echoed sentence carries the reading it was built from: same kind of problem, same numbers. + for item_id in PINS: + dossier = _baseline(item_id)["dossier"] + agreed = str(dossier.get("sent") or "") + assert agreed, item_id + assert agreed == canonical.print_math( + str(dossier["reading_a"]["kind"]), dossier["reading_a"]["slots"]), (item_id, agreed) + assert coverage.echo_matches(dossier.get("reading_a") or {}, dossier.get("math") or {}), item_id + + +def test_the_math_stratum_is_reached_only_as_a_separate_process(): + # Nothing in this bundle may decide the mathematics: the only door toward the math stratum is the + # invoker, and it launches the solver of that bundle as a subprocess. + import inspect + from lgstratum import invoker + + source = inspect.getsource(invoker) + assert "subprocess" in source + assert "lgmath" not in source + for module in (agents, pipeline, faults): + assert "lgmath" not in inspect.getsource(module) diff --git a/tests/test_readers.py b/tests/test_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..daecfa2f8bdc6025d39d66b50472cd0d833c6177 --- /dev/null +++ b/tests/test_readers.py @@ -0,0 +1,79 @@ +"""What the two readers do, taken from the questions the corpus already carries.""" + +import pytest + +from lgstratum import canonical, compare, corpus, 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"] + + +def _item(item_id): + item = ITEMS[item_id] + return str(item["lang"]), str(item["question"]) + + +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 math 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): + lang, question = _item(item_id) + a = read_a.read(lang, question) + b = read_b.read(lang, question) + assert a["status"] == "READ", (item_id, a.get("notes")) + assert b["status"] == "READ", (item_id, b.get("notes")) + assert a["kind"] == b["kind"], (item_id, a["kind"], b["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(canonical.print_math(a["kind"], a["slots"])) == expected, item_id + + +@pytest.mark.parametrize("item_id", AGREED) +def test_a_reader_keeps_every_number_the_question_wrote(item_id): + lang, question = _item(item_id) + reading = read_a.read(lang, question) + 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. + lang, question = _item(item_id) + a = read_a.read(lang, question) + b = read_b.read(lang, question) + assert a["status"] == "READ", (item_id, a.get("notes")) + assert b["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): + lang, question = _item(item_id) + for reading in (read_a.read(lang, question), read_b.read(lang, question)): + assert reading["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_math_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..8a271b877367802fb8c16e208c642d0e931c087d --- /dev/null +++ b/tests/test_topology.py @@ -0,0 +1,88 @@ +"""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 lgstratum 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 math 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 / "lgstratum").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_math_code(): + # The math 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 math 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 / "lgstratum").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.startswith("lgmath"): + 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"): + assert "lgmath" not in (ROOT / "lgstratum" / name).read_text(encoding="ascii"), name + + +def test_the_math_bundle_is_reached_as_a_separate_process(): + source = (ROOT / "lgstratum" / "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) + assert any("tools" in call and "solve.py" in call for call in calls) diff --git a/tools/ablation.py b/tools/ablation.py new file mode 100644 index 0000000000000000000000000000000000000000..1d808a1efece0670266683162993bc5f966e7f45 --- /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 +(``lgstratum/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 math-stratum/tools/ablation.py [--probe N] [--all] [--out math-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 lgstratum 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:drop_marker", "reader_b:drop_marker"), + ("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..a7a6f9433277828855626e0409f8d64ea2f03540 --- /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 math stratum 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/math-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/math-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 lgstratum 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="lgstratum_")) + 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, math assurance %s)" + % (final["assurance"], final.get("ceiling", 0), + final.get("math_assurance"))) + lines.append("Math 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..e79ca08eaa56a9d07b28f4f12d20f68ba953a075 --- /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 math +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 math layer could prove, and the two +ceilings are reported apart on purpose. Pass ``--math`` to add the math verdicts to the same run. + +Usage: python math-stratum/tools/coverage_report.py [--math] + python math-stratum/tools/coverage_report.py --out math-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 lgstratum 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_math: 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_math=use_math) + 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("--math", action="store_true", + help="consult the math stratum 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.math) + 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), "math_consulted": bool(args.math), + "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, math consulted: %s)" + % (destination, len(items), "yes" if args.math else "no")) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tools/publish_dataset.py b/tools/publish_dataset.py new file mode 100644 index 0000000000000000000000000000000000000000..6812c693ee4c258dad1403d75e3ec4aa049abd81 --- /dev/null +++ b/tools/publish_dataset.py @@ -0,0 +1,356 @@ +"""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 +four passages are rewritten because they only make sense inside a LingoLOGOS checkout: where the folder +sits, that it needs the sibling `math` folder, how long the suite took and what section 10 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 lgstratum import corpus # noqa: E402 (after the path fix above) + +REPO = "tailot/math-stratum" +EXPECTED_FILES = 67 # the staged tree: this README is uploaded as the card under the same name +EXPECTED_HUB_OBJECTS = 68 # staged tree plus the .gitattributes the hub adds by itself +EXPECTED_CORPUS_ROWS = 73 +IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git"} +FRONT_MATTER = """--- +language: + - it + - en + - es + - zh + - hi + - ar +tags: + - multilingual + - mathematical-word-problems + - natural-language-to-formal-language + - multi-agent-systems + - benchmark + - conversational-interfaces + - formal-verification + - semantic-parsing +pretty_name: "LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, 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/math-stratum`; every command below is written from inside it and needs the\n" + "sibling folder `datasets/math`, which stays exactly as it is. Only the standard library and\n" + "`z3-solver` are required; the tests need `pytest`.", + "This dataset is the `math-stratum/` folder of the LingoLOGOS project published as it stands: 67 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 mathematics is not part of this dataset: it lives\n" + "in the `math` bundle, published at https://huggingface.co/datasets/tailot/lingologos-math, and section\n" + "10 says how to point this 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/math-stratum. The published snapshot is\n" + "this content: 67 files (plus the card that replaces this README on the hub), 73 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 67 files plus this card: 73 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 results\n" + "under `results/`, and the fault catalogue of section 6. To run the mathematics it needs the `math`\n" + "bundle: download https://huggingface.co/datasets/tailot/lingologos-math somewhere, set\n" + "`LGSTRATUM_MATH_ROOT` to that copy, and the `invoker` node calls `tools/solve.py` there as a separate\n" + "process, which is the only door through which this bundle ever reaches a solver. Inside a LingoLOGOS\n" + "checkout the folder sits at `datasets/math-stratum`, finds `datasets/math` 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 math stratum as subprocesses, and the whole suite took 3 minutes\n" + "52 seconds on this checkout.", + "invariant tests call the solver of the math stratum as subprocesses, which here means a copy of the\n" + "`math` dataset named by `LGSTRATUM_MATH_ROOT` (section 10); the suite took 3 minutes 52 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 `math` folder, this folder is ignored by the git\nrepository of the project: what the project carries is the link in the table of published resources at\nthe top of the repository README, and the documentation of the asset lives in this README and in the\ncard, not in `doc/TECHNICAL_DOCUMENTATION.md`.", + "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. `tools/publish_dataset.py`\nin the folder of the project republishes a changed working copy with the token taken from an environment\nvariable.", + ), +] + +CARD_TAIL = """ +## 11. The corpus file + +`problems/corpus.jsonl` holds 73 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; the prefix names the variety (`it`, `en`, `es`, `zh`, `hi`, `ar`), or `mixed` on the 5 rows that mix varieties, write digits in full width form or are gibberish | +| `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in | +| `kind` | string | one of the 12 problem kinds, or `negative` (14 rows that must not be read) or `passthrough` (2 rows already written in the math language) | +| `question` | string | the question, between 5 and 53 characters, in the script of its variety | +| `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`) | Rows | Id prefix | Rows | Kind | Rows | +|---|---|---|---|---|---| +| `it` | 13 | `it` | 13 | `evaluate` | 7 | +| `en` | 13 | `en` | 12 | `solve` | 6 | +| `es` | 10 | `es` | 9 | `solvez` | 3 | +| `zh` | 12 | `zh` | 11 | `prove` | 5 | +| `hi` | 12 | `hi` | 11 | `provez` | 8 | +| `ar` | 13 | `ar` | 12 | `derivative` | 4 | +| mixed rows | 5 | `mixed` | 5 | `integral` | 5 | +| | | | | `det`, `rank` | 3, 3 | +| | | | | `inverse` | 4 | +| | | | | `maximize`, `minimize` | 3, 6 | +| | | | | `negative` | 14 | +| | | | | `passthrough` | 2 | + +The fields of `expect` are optional except `referee_clean`, which is present on every row. + +| Field | Rows | Meaning | +|---|---|---| +| `state` | 65 | the reading state the session must end in: `AGREED` 55, `PASSTHROUGH` 3, `SINGLE` 2, `NOT COVERED` 5 | +| `sentence` | 60 | the sentence of the math language both readers have to produce, exactly | +| `answer_contains` | 29 | a substring the answer has to contain, exact rationals written as strings | +| `min_assurance` | 51 | the lowest assurance that is acceptable, on the scale of section 1 | +| `max_assurance` | 22 | the highest assurance that is acceptable: this is what pins the probes that must not rise | +| `no_answer` | 15 | `true` where the row is graded by the refusal: no answer may be shown at all | +| `referee_clean` | 73 | every envelope claim of the session must match what the referee of its node recomputed | + +The eight rows with no `state` are graded on an assurance or on an answer instead: they check that the +reading holds while the math stratum abstains, so the assurance must be 0 and no answer may appear. +Seven of them are the agreed readings on which the mathematics is out of reach (`it-13`, `en-11`, +`en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`), 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/math-stratum", "corpus", split="train") +print(rows[0]) +``` + +This is the same file `tools/ask.py --corpus` walks over, and `lgstratum/corpus.py` plus +`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 73 of 73 +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 73 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 arithmetic questions: they are not a general purpose +dictionary of those languages. + +## 14. Citation + +``` +@misc{lingologos_math_stratum, + title = {LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading}, + author = {LingoLOGOS project}, + year = {2026}, + url = {https://huggingface.co/datasets/tailot/math-stratum}, + note = {bundle of the math-stratum folder of the LingoLOGOS repository: 73 questions in six written + varieties, six lexicons, two independent readers, eight node definitions with SMT claims, the + assurance rule min(math, reading) with the reading capped at 2, fault catalogue and ablation + over the node configurations, 290 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: + `lgstratum/__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 == "lgstratum"): + 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_math_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 math-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_math_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_math_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..b8a2e27df6073c0834839ca61f4c1672db4e7a84 --- /dev/null +++ b/topology.json @@ -0,0 +1,98 @@ +{ + "$schema": "https://lingologos.spec/schemas/topology-v1.json", + "sessionId": "lingologos-math-stratum-01", + "maxTurns": 8, + "terminationCondition": "FIXED_PIPELINE", + "instances": [ + { + "id": "reader_a", + "executable": "math-stratum/agents/stratum_agent", + "role": "reader_a" + }, + { + "id": "reader_b", + "executable": "math-stratum/agents/stratum_agent", + "role": "reader_b" + }, + { + "id": "equivalence", + "executable": "math-stratum/agents/stratum_agent", + "role": "equivalence" + }, + { + "id": "coverage", + "executable": "math-stratum/agents/stratum_agent", + "role": "coverage" + }, + { + "id": "invoker", + "executable": "math-stratum/agents/stratum_agent", + "role": "invoker" + }, + { + "id": "boundary", + "executable": "math-stratum/agents/stratum_agent", + "role": "boundary" + }, + { + "id": "adversary", + "executable": "math-stratum/agents/stratum_agent", + "role": "adversary" + }, + { + "id": "arbiter", + "executable": "math-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" + ] + } + ] +}