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..fc5b706e2ebcfbdd639f7c973d010febf3a938da --- /dev/null +++ b/README.md @@ -0,0 +1,402 @@ +--- +language: + - it + - en + - es + - zh + - hi + - ar +tags: + - multilingual + - physics + - dimensional-analysis + - unit-conversion + - natural-language-to-formal-language + - multi-agent-systems + - benchmark + - conversational-interfaces + - formal-verification + - semantic-parsing +pretty_name: "LingoLOGOS physics-stratum: a question in six written varieties, the answer of the physics 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 physics-stratum topology + +A conversational layer over the `physics` topology: a person asks in one of six written varieties, and +gets the verdict of the physics stratum back in that same language, at an assurance that includes the +fallibility of the reading. The layer never converts a unit, never checks a dimension and never raises +a verdict; the only direction it can move the assurance of the physics stratum is down. + +``` +python tools/ask.py --lang it "converti 3 chilometri in metri" +Reading state : AGREED +Assurance shown : 2 (reading ceiling 2, physics assurance 2) +Physics 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 (convert): convert 3 km to m + Risposta: 3 km = 3000 m (L) + livello 2 di 2 + strato fisica: VERIFIED + Controllo SMT dello strato : 8 di 8 buste confermate +``` + +This dataset is the `physics-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 physics layer is not part of this dataset: it +lives in the `physics` bundle, published at https://huggingface.co/datasets/tailot/lingologos-physics, +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 dimensional check can: +there is no SMT constraint 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 physics stratum, ceiling of the reading) +``` + +| Reading state | ceiling | when | +|---|---|---| +| `AGREED` | 2 | both readers produced the same sentence, and the physics stratum is what decides it | +| `PASSTHROUGH` | 2 | the question was already a sentence of the physics 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 physics 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 physics stratum says it answered something other than the agreed sentence | + +Three is never shown, and for once that is not a limit of this layer: the physics stratum itself stops +at two, because its two formalizers and its referee work on a sentence they wrote themselves and there +is no third road to a number there. A sentence in a human language adds one fallible step before that, +so here the ceiling of an agreed reading is the level of the layer itself, and a reading can only ever +lower the confidence -- it has nothing above it to be capped by. + +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 `physics` 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 physics 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 physics stratum, in a separate process, the agreed sentence | the sentence I sent equals the one that came back | +| `boundary` | checks the echo of the physics 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 | + +The sentence of the physics language has three shapes in this fragment and two joints, `to` and `from`, +so the claims are shorter than in the math stratum and the equivalence node works on units, formulas and +lists of quantities rather than on polynomials. + +## 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 physics language (`to`, `from`, in the words of the variety) and +cuts the slots out of the gaps between them. They share only the lexicon, the atomizer (`segment.py`) +and the templates of the physics 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 physics stratum. + +A phrase of a variety that runs over several atoms -- the Italian phrase for "starting from", the +Chinese phrase for a dimensional analysis -- is one joint for `reader_b`, not one per atom, because the +frame of a sentence has as many joints as its shape has gaps. + +## 4. Talking to the physics stratum + +`invoker.py` is the only door. It launches `python /tools/ask.py --json ` as a separate +process and reads its JSON verdict back; nothing in this folder imports the physics package to decide +anything here. One module, `compare.py`, imports it for the SMT plumbing of the equivalence node, and a +gate in `tests/test_topology.py` pins that exception. The referee then checks the echo: the sentence +the physics stratum says it answered has to be the sentence the readers agreed on, otherwise the +session is `TAMPERED`. + +| Variable | Meaning | +|---|---| +| `LGPHYSSTRATUM_PHYSICS_ROOT` | where the `physics` bundle is (default: the sibling folder `datasets/physics`) | +| `LGPHYSSTRATUM_PHYSICS_BACKEND` | `subprocess` (default), or `none` to disable the physics layer entirely | +| `LGPHYSSTRATUM_PHYSICS_TIMEOUT` | how long one call of the layer may take (default 240 seconds) | +| `LGPHYSSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only | + +What the layer says decides what a person is shown: + +| Status of the physics stratum | Its assurance | What this stratum shows | +|---|---|---| +| `VERIFIED` | 2 | the answer, at the ceiling of the reading | +| `SINGLE_PROVER` | 1 | the answer, one road produced the number where two were expected | +| `REFUSED` | 0 | the explanation the layer wrote, and no answer | +| `GUARD_BLOCKED`, `ABSTAINED`, `UNKNOWN` | 0 | nothing: the reading stands, the assurance is zero | + +A refusal is a verdict and not a failure: `convert 3 kilograms to meters` is a well read question about +a dimensionally impossible conversion, the layer says so, and this stratum repeats that it was refused +without dressing it up as an answer. A disabled physics layer is not tampering either: the reading +stands, the assurance falls to zero because there is no physics assurance to take the minimum with, and +no answer is shown. + +## 5. The corpus + +`problems/corpus.jsonl` holds 64 questions: three kinds of problem in 6 varieties, plus items already +written in the physics language, gibberish, questions in a word order this bundle does not read, +symbols carried inside an article, units outside the fragment of the layer, and questions whose physics +the layer refuses. 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. Here `negative` means "nothing may +be shown at a positive assurance", which covers both a question that cannot be read and a question that +is read well and refused by the layer. + +Graded against the in-process pipeline with the physics layer running: **64 of 64** rows agree with +their gold (`lgphysstratum/corpus.py` grades one row, `tests/test_corpus.py` runs all of them). The +states come out 45 `AGREED`, 11 `NOT COVERED`, 4 `PASSTHROUGH`, 3 `SINGLE`, 1 `AMBIGUOUS`. +`tools/coverage_report.py` writes `results/coverage.json` and counts **45** questions read by both +readers, **3** by `reader_b` alone and **12** by neither, over six lexicons that carry 14 to 20 frames +and 2 to 5 joints each. Eight rows (`it-06`, `it-10`, `it-13`, `en-11`, `es-11`, `zh-10`, `ar-09`, +`hi-10`) are agreed readings on which the physics layer refuses: assurance 0 and no answer, which is the +stratum refusing to add an availability it does not have. Three rows (`it-03`, `zh-03`, `hi-07`) stay at +`SINGLE`, assurance 1, for the reasons in section 7. + +## 6. Commands + +``` +python tools/ask.py --lang it "converti 3 chilometri in metri" # one session, eight processes +python tools/ask.py --lang en --json "convert 3 km to m" +python tools/ask.py --corpus problems/corpus.jsonl --limit 6 +python tools/coverage_report.py --physics --out results/coverage.json +python tools/ablation.py --out results/ablation.json # the run shipped under results/ +python tools/ablation.py --probe 6 --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 the default probe -- twelve questions, the two conversions `*-01` and `*-02` of section +5 in each of the six varieties -- fills **147** cells and **1764** sessions, the fault takes hold in +**1356** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 12`, `caught 8`, +`abstained 1084`, `masked 252` -- 3428.9 seconds, just under an hour. Nothing was ever raised above the +honest assurance, which is the invariant section 1 states. + +Twelve sessions are silent errors, and they are one cell: the full topology with **both** readers +committing `same_units` at the same time, so that each writes the target unit of the question as its +source unit. The two readings agree, every envelope is confirmed, the numbers the person wrote are all +still there, and the physics stratum answers the sentence it was sent -- `convert 3 km to km` -- with +`3 km = 3 km` at assurance 2. No claim of this bundle can see it: the equivalence node compares the two +readings with each other, the coverage node counts the literals, and the echo checks that the layer +answered the sentence it was given. That is the blind spot of section 3 in its purest form -- a fault +common to both readers -- and the bundle reports it rather than hiding it: the units of a reading are +policed between the readers and by the physics stratum, never against a third authority. The same fault +taken by one reader only -- in the two configurations that have lost the other reader, 24 sessions -- +never reaches the assurance of the honest run: 8 are answered at assurance 1 with the sentence and the +answer reported as wrong, and the other 16 withdraw the answer outright. + +## 7. Limits that are written down, not hidden + +* Three word orders are described in one of the two readers only, so those questions stand on one + witness and stay at `SINGLE`, assurance 1: the Italian conversion with the joint `a` (`riduci 250 + centimetri a metri`, read by `reader_b` only), the Chinese `ba` frame with the verb at the end + (`read_a` knows no pattern for it), and the Hindi noun phrase analysis with no verb (`reader_a` asks + for a symbol it does not find). `tools/coverage_report.py` shows them as one of two readers. +* Hindi also writes the verb last (`badlo 3 kilometron ko mitar mein`), and neither reader was given + that order: the question is `NOT COVERED` (`hi-03`) rather than guessed. +* The connective `e` in Italian also means *and*, so `bilancia forza e lunghezza uguale a energia` is + read as a list of quantities and the layer refuses a list where it needs a product (`it-10`). The + reading is reported, the answer is not. +* The physics language is not case free: `v` is the speed and `V` is the volt, `p` is the momentum and + `P` is the power, the gram is `g` and gravity is `g`. Both readers fold a sentence before they cut its + slots, so the canonical printer (`canonical.py`) puts the spelling of the physics language back on + every slot value -- the one place in this stratum where a letter is changed, and a change of spelling + rather than of content. One letter is genuinely lost on the way: a bare `p` arrives folded from both + the momentum and the power, and the printer writes the momentum, because that is the form the physics + language puts in lower case. Writing the word ("power") is how a person keeps the distinction. +* An Arabic quantity written inside the definite article (`al-tul`, "the length") is not in the + lexicon: `reader_a` strips what it can and both readers abstain (`ar-07`), so the stratum says `NOT + COVERED` instead of guessing the two symbols. +* Units outside the fragment of the physics layer (`litres`, `gallons`) are outside this bundle too + (`it-12`, `en-10`, `es-10`): the lexicons do not name what the layer cannot carry, so the question is + not read rather than read into a wrong unit. +* The physics bundle has a fourth family, the circuits of `potential`. No variety of this bundle asks + it -- it is in the grammar specifications of the eight nodes and in no lexicon -- so a circuit is + reachable only through the direct mode, when the person writes the sentence of the physics language + themselves. +* The equivalence node compares readings with SMT over their numbers; units and formulas are compared + slot by slot, which is why a reading that swapped `km` for `kWh` is caught by the slot comparison and + not by the constraint. +* 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. The ablation of section 6 shows the extreme case + of it: the same fault in both readers at once leaves an answer shown at the full assurance of the + physics stratum, and nothing inside this bundle can contradict it. + +## 8. Tests + +From the repository root: + +``` +python -m pytest -q datasets/physics-stratum/tests +``` + +The suite is **271** tests: 109 on the two readers against every row of the corpus, 70 on the +corpus itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 14 on the decision +table, 11 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 physics 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 +physics stratum as subprocesses, and the suite took 6 minutes 15 seconds on the machine that built this +snapshot. + +Real sessions, measured: `converti 3 chilometri in metri` comes back `AGREED` at assurance 2 against a +physics assurance of 2 -- the ceiling of that layer, so the reading cost nothing here -- with **8 of 8** +envelope claims confirmed by the referee of the session, and `python tools/ask.py --corpus +problems/corpus.jsonl --limit 6` grades **6 of 6** real sessions against gold. One question per variety +outside Italian (`zh-01`, `ar-01`, `hi-01`, `en-04`) comes back the same way: `AGREED`, assurance 2, the +physics layer `VERIFIED`, 8 of 8 claims confirmed, nothing detected -- and the block the person reads is +written in the language of the question (48, 98 and 99 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 +`lgphys` may be imported for its SMT plumbing by `lgphysstratum/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 folder is a published snapshot. To work on it as a conversational layer again, clone +https://huggingface.co/datasets/tailot/lingologos-physics next to it, name the physics copy with +`LGPHYSSTRATUM_PHYSICS_ROOT`, and run the sessions of section 3; with that variable unset the folder +looks for a sibling `physics`. Its code is the same as the snapshot published on the hub, which is this +folder with sections 1 to 10 of its README rewritten in place and sections 11 to 14 appended. Every file of this folder is +compared by sha256 after the upload, the card that replaces this README among them: the hub holds one +object per file of this folder plus `.gitattributes`, so the remote count is one above the number +`tools/publish_dataset.py` prints here. The physics bundle lives at +https://huggingface.co/datasets/tailot/lingologos-physics, and the project that built both is +https://github.com/Tailot/LingoLOGOS. + +## 11. The corpus file + +`problems/corpus.jsonl` holds 64 questions, one JSON object per line, each asking one thing in one of six +written varieties: 13 Italian, 11 English, 11 Spanish, 10 Chinese, 10 Hindi, 9 Arabic. Six of them are +written in characters outside the Latin alphabet, and that is the point of the file: the reading layer is +measured across all six, in both directions. + +| field | meaning | +|---|---| +| `id` | `-`; the prefix names the variety, so rows can be grouped without reading the question | +| `lang` | the ISO code of the variety the person wrote in: `it`, `en`, `es`, `zh`, `hi` or `ar` | +| `kind` | what the row is for: `convert`, `audit`, `pi`, `negative` or `passthrough` | +| `question` | the sentence a person would actually type, between 4 and 69 characters | +| `why` | what the row is meant to show, in English | +| `expect` | what a correct run must produce | + +The kind of a row says what kind of question it is. Note that this corpus is a graded record of what the +reading layer can do, so some rows have no `sentence` to point at: an `audit` row, for instance, is both +a question whose surface this layer covers (the physics stratum then checks the equation and rules on it) +and one whose surface it does not (the readers abstain, the stratum says nothing, and the assurance is 0). + +| kind | rows | what the row tests | +|---|---|---| +| `convert` | 17 | a change of unit: km to m, km/h to m/s, cm to m, days to hours | +| `audit` | 13 | a claim that two products carry the same dimensions, checked or rejected by the physics stratum | +| `pi` | 12 | a dimensional derivation: the dimensions of speed, or the period of a mass on a spring | +| `negative` | 18 | a question that must not be read, or must not be answered: two problems in one sentence, an uncovered surface, a false physics | +| `passthrough` | 4 | the question is already a sentence of the physics language, so nothing is translated | + +The `expect` object, field by field: + +| field | rows | what it pins | +|---|---|---| +| `state` | 64 | the reading outcome: 45 `AGREED`, 11 `NOT COVERED`, 4 `PASSTHROUGH`, 3 `SINGLE`, 1 `AMBIGUOUS` | +| `sentence` | 44 | the physics sentence both readers are expected to write | +| `answer_contains` | 44 | a string the answer of the physics stratum has to contain | +| `min_assurance` | 41 | the assurance floor of the row (all 41 are 2, the ceiling of this layer) | +| `max_assurance` | 23 | the assurance ceiling: 0 on the 20 rows that must not answer, 1 on the 3 single-witness rows | +| `no_answer` | 20 | the row must come back with no answer at all | +| `referee_clean` | 64 | no envelope claim of the session may fall to the referee of its node | + +The 20 rows with no `sentence` are the 18 `negative` rows plus `it-06` and `ar-07`: eleven of the +`negative` rows are not read at all, `it-09` announces two problems in one sentence and is refused, and +seven are read and then refused by the physics stratum -- with `it-06` that makes eight read-and-refused +rows, at assurance 0 and with no answer. The two readers agree exactly on each of them. The 3 +single-witness rows are `it-03`, `zh-03` and `hi-07`, and they answer at assurance 1 because only one +reader reached the sentence and that reader kept every number. + +## 12. Loading it + +```python +from datasets import load_dataset + +corpus = load_dataset("tailot/physics-stratum", "corpus", split="train") +print(len(corpus)) # 64 +print(corpus[0]["question"]) # converti 3 chilometri in metri +print(corpus[0]["expect"]["sentence"]) # convert 3 km to m +``` + +The loader is metadata only, and no test of this bundle needs it: every row can be read with `json.loads` +on one line of `problems/corpus.jsonl`, as `lgphysstratum/corpus.py` does. Every row agrees with what this +folder produces: `python tools/ask.py --corpus problems/corpus.jsonl` runs every question through the +eight nodes and grades it against `expect`, and all 64 of 64 agree. `python tools/coverage_report.py +--physics --out results/coverage.json` gives a reading report on each row without a verdict; the verdicts +are in `results/coverage.json`, the faults in `results/ablation.json`. + +## 13. Rights + +The same rights as the rest of the LingoLOGOS project, of which this folder is one published bundle. The +questions are sentences written for this bundle, not text taken from anywhere; they ask about kilometres, +hours, force, energy and the period of a mass on a spring. The Hindi and Arabic lexicons, like the other +four, were written for this bundle inside the repository, and a reader of either is the right person to +check them before this bundle is used for anything other than a measurement. + +## 14. Citation + +```bibtex +@misc{lingologos_physics_stratum, + title = {LingoLOGOS physics-stratum: a question in six written varieties, the answer of the physics stratum, and an assurance that includes the reading}, + author = {LingoLOGOS}, + year = {2026}, + howpublished = {the folder as it stands, 67 files, code and data together, with this card as the README}, + note = {A conversational layer over the physics topology of the same project: 64 questions, 271 tests. The assurance it shows is the minimum of the assurance of the physics stratum and the ceiling of the reading, so a reading that stands alone or loses a number lowers the confidence and can take the answer away. The bundle carries its fault catalogue and an ablation over every subset of its eight nodes, and reports the one blind spot that experiment found: a unit fault taken by both readers at once.} +} +``` diff --git a/agents/stratum_agent b/agents/stratum_agent new file mode 100644 index 0000000000000000000000000000000000000000..abbb809f1f71332f3f3e35f49630d40bd941d790 --- /dev/null +++ b/agents/stratum_agent @@ -0,0 +1,39 @@ +#!/usr/bin/env python3 +"""Node executable of the physics-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 physics 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 physical fact: the sentence the readers agree on is handed to the +physics 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 lgphysstratum import agents, faults # noqa: E402 + + +def main() -> int: + parser = argparse.ArgumentParser(description="Physics-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..d78892662146a1cd4e77f5ec6cccf8562fbaa4d6 --- /dev/null +++ b/lexicon/ar.json @@ -0,0 +1,131 @@ +{ + "lang": "ar", + "name": "العربية", + "script": "arabic", + "noise_chars": "", + "prefixes": ["ال", "وال", "بال", "فال", "لل", "و", "ب", "ل", "ف"], + "kinds": { + "convert": { + "verbs": ["حول", "تحويل", "غير"], + "patterns": [ + "حول {N} {U} الى {V}", + "تحويل {N} {U} الى {V}", + "غير {N} {U} الى {V}", + "الى {V} حول {N} {U}" + ], + "frame": {"sequences": [["to"]]} + }, + "audit": { + "verbs": ["تحقق", "تأكد", "افحص", "دقق", "برهن"], + "patterns": [ + "تحقق {F}", + "تأكد {F}", + "افحص {F}", + "دقق {F}", + "برهن {F}", + "تحقق ان {F}", + "برهن ان {F}" + ], + "frame": {"sequences": [[]]} + }, + "pi": { + "verbs": ["تحليل الأبعاد", "تحليل الابعاد", "جد pi", "احسب pi", "pi"], + "patterns": [ + "pi {T} من {S}", + "جد pi {T} من {S}", + "احسب pi {T} من {S}", + "تحليل الأبعاد {T} من {S}", + "تحليل الابعاد {T} من {S}" + ], + "frame": {"sequences": [["from"]]} + } + }, + "connectives": { + "times": ["ضرب في", "مضروبة في", "ضرب"], + "over": ["مقسومة على", "قسمه على"], + "plus": ["زائد"], + "minus": ["ناقص"], + "power": ["مرفوع الى"], + "equals": ["يساوي", "يعادل"], + "list": ["و"] + }, + "markers": { + "to": ["الى", "إلى"], + "from": ["من"] + }, + "tokens": { + "متر": "m", "امتار": "m", + "كيلومتر": "km", "كيلومترات": "km", + "سنتيمتر": "cm", "سنتيمترات": "cm", + "مليمتر": "mm", "مليمترات": "mm", + "كيلومتر في الساعة": "km/h", "كيلومترات في الساعة": "km/h", + "متر في الثانية": "m/s", "امتار في الثانية": "m/s", + "كيلوغرام": "kg", "كيلوغرامات": "kg", "غرام": "g", "غرامات": "g", + "ثانية": "s", "ثوان": "s", "ميلي ثانية": "ms", + "دقيقة": "min", "دقائق": "min", "ساعة": "h", "ساعات": "h", + "يوم": "day", "ايام": "day", + "امبير": "A", "كلفن": "K", "مول": "mol", "قنديلة": "cd", + "نيوتن": "N", "جول": "J", "وات": "W", "كولوم": "C", "فولت": "V", + "اوم": "ohm", "هرتز": "Hz", "الكترون فولت": "eV", + "كتلة": "mass", "طول": "length", "زمن": "time", "زمن الدورة": "period", + "تردد": "frequency", "سرعة": "speed", "تسارع": "acceleration", + "جاذبية": "gravity", "قوة": "force", "صلابة": "stiffness", "زخم": "momentum", + "طاقة": "energy", "قدرة": "power", "شحنة": "charge", "تيار": "current", + "جهد": "voltage", "مقاومة": "resistance", "درجة الحرارة": "temperature", + "كمية المادة": "amount", "شدة الإضاءة": "luminosity", "ارتفاع": "hgt" + }, + "noise": ["ما", "ان", "أن", "كم", "هو", "هي", "هذه", "ذلك", "رجاء", "في", "على"], + "labels": { + "understood": "المسألة كما فهمناها", + "status": "الحالة", + "assurance": "المستوى {n} من 2", + "answer": "الجواب", + "reading": "القراءة", + "physics_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_number": "{slot} ليس عددا بلغة الفيزياء", + "bad_unit": "{slot} ليست وحدة مكتوبة برموز لغة الفيزياء", + "bad_formula": "{slot} ليست معادلة بعلامة تساوي واحدة ورموز معروفة", + "bad_symbol": "{slot} ليس رمزا لكمية بلغة الفيزياء", + "unbalanced": "قوس أو قوس مربع غير مغلق", + "no_math": "الجزء الفيزيائي غير مكتوب برموز لغة الفيزياء", + "literal_count": "أعداد الجملة ليست هي نفسها عند القارئين", + "physics_unknown": "طبقة الفيزياء لا تقبل الجملة: {detail}", + "boundary": "الجملة المسلّمة إلى طبقة الفيزياء ليست القراءة المتفق عليها", + "referee": "حك SMT لا يؤكد {detail}", + "other": "لم تصل القراءة إلى جملة بلغة الفيزياء" + }, + "examples": [ + "حول 3 كيلومتر الى متر", + "حول 5 كيلومتر في الساعة الى متر في الثانية", + "الى متر في الثانية حول 5 كيلومتر في الساعة", + "تحقق قوة ضرب زمن يساوي كتلة ضرب سرعة", + "برهن قوة ضرب طول يساوي طاقة", + "جد pi زمن الدورة من كتلة و صلابة", + "تحليل الابعاد سرعة من طول و زمن" + ] +} diff --git a/lexicon/en.json b/lexicon/en.json new file mode 100644 index 0000000000000000000000000000000000000000..f7ad23334e9db150b6f75947778f0e144f6f15f0 --- /dev/null +++ b/lexicon/en.json @@ -0,0 +1,136 @@ +{ + "lang": "en", + "name": "English", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "convert": { + "verbs": ["convert", "change", "express", "rewrite"], + "patterns": [ + "convert {N} {U} to {V}", + "convert {N} {U} into {V}", + "change {N} {U} to {V}", + "express {N} {U} in {V}", + "rewrite {N} {U} in {V}", + "to {V} convert {N} {U}" + ], + "frame": {"sequences": [["to"]]} + }, + "audit": { + "verbs": ["audit", "check", "verify", "validate", "test"], + "patterns": [ + "audit {F}", + "check {F}", + "check that {F}", + "verify that {F}", + "verify {F}", + "validate {F}", + "test that {F}" + ], + "frame": {"sequences": [[]]} + }, + "pi": { + "verbs": ["find the pi", "compute the pi", "dimensional analysis", "pi"], + "patterns": [ + "pi {T} from {S}", + "find the pi {T} from {S}", + "compute the pi {T} from {S}", + "dimensional analysis of {T} from {S}", + "what is the pi {T} from {S}" + ], + "frame": {"sequences": [["from"]]} + } + }, + "connectives": { + "times": ["times", "multiplied by"], + "over": ["divided by", "per"], + "plus": ["plus", "added to"], + "minus": ["minus"], + "power": ["raised to the power of"], + "equals": ["equals", "is equal to"], + "list": ["and"] + }, + "markers": { + "to": ["to", "into", "in"], + "from": ["from", "starting from"] + }, + "tokens": { + "meter": "m", "meters": "m", "metre": "m", "metres": "m", + "kilometer": "km", "kilometers": "km", "kilometre": "km", "kilometres": "km", + "centimeter": "cm", "centimeters": "cm", "centimetre": "cm", "centimetres": "cm", + "millimeter": "mm", "millimeters": "mm", "millimetre": "mm", "millimetres": "mm", + "kilometers per hour": "km/h", "kilometres per hour": "km/h", + "meters per second": "m/s", "metres per second": "m/s", + "meters squared": "m^2", "metres squared": "m^2", + "kilogram": "kg", "kilograms": "kg", "gram": "g", "grams": "g", + "second": "s", "seconds": "s", "millisecond": "ms", "milliseconds": "ms", + "minute": "min", "minutes": "min", "hour": "h", "hours": "h", + "day": "day", "days": "day", + "ampere": "A", "kelvin": "K", "mole": "mol", "candela": "cd", + "newton": "N", "newtons": "N", "joule": "J", "joules": "J", "watt": "W", "watts": "W", + "coulomb": "C", "coulombs": "C", "volt": "V", "volts": "V", + "ohm": "ohm", "ohms": "ohm", "hertz": "Hz", "electronvolt": "eV", "electronvolts": "eV", + "mass": "mass", "length": "length", "time": "time", "period": "period", + "frequency": "frequency", "speed": "speed", "velocity": "speed", + "acceleration": "acceleration", "gravity": "gravity", "force": "force", + "stiffness": "stiffness", "momentum": "momentum", "energy": "energy", + "power": "power", "charge": "charge", "current": "current", "voltage": "voltage", + "resistance": "resistance", "temperature": "temperature", "amount": "amount", + "luminosity": "luminosity", "height": "hgt" + }, + "noise": ["the", "a", "an", "that", "what", "is", "of", "it", "this", "how", "much", "for"], + "labels": { + "understood": "Problem understood", + "status": "State", + "assurance": "level {n} of 2", + "answer": "Answer", + "reading": "Reading", + "physics_layer": "physics layer", + "notes": "Notes", + "examples": "Sentences this stratum understands", + "question": "Ask again in one of these forms", + "check": "SMT check of the stratum : {a} of {b} envelopes confirmed", + "kind_of": "kind" + }, + "reading": { + "AGREED": "agreed: two independent readers plus the SMT constraint", + "PASSTHROUGH": "sentence already written in the physics language, not translated", + "DISPUTED": "disputed: the two readers propose different sentences", + "NOT COVERED": "outside the coverage of this language", + "AMBIGUOUS": "ambiguous: more than one reading is possible", + "TAMPERED": "tampered: the text handed to the physics layer is not the agreed reading", + "SINGLE": "one reading only: the other reader did not recognise the sentence", + "NONE": "no reading" + }, + "reasons": { + "unknown_word": "the word {word} does not appear in the sentences covered in English", + "no_verb": "no word announces the kind of problem in English", + "two_verbs": "the sentence announces more than one kind of problem: {kinds}", + "no_pattern": "the shape of the sentence matches no shape covered in English", + "no_frame": "the joints do not match any form of the kind {kind}", + "multiple": "the same sentence has two different readings: {first} and {second}", + "disagree": "the two readers propose two different sentences of the physics language", + "markers": "the joints of the sentence are not the ones the kind of problem expects", + "bad_number": "{slot} is not a number of the physics language", + "bad_unit": "{slot} is not a unit written with the symbols of the physics language", + "bad_formula": "{slot} is not an equation with one equality sign and known symbols", + "bad_symbol": "{slot} is not a quantity symbol of the physics language", + "unbalanced": "brackets or square brackets are not closed", + "no_math": "the physics part is not written with the symbols of the physics language", + "literal_count": "the numbers of the sentence are not the same in the two readers", + "physics_unknown": "the physics layer does not accept the sentence: {detail}", + "boundary": "the sentence handed to the physics layer is not the agreed reading", + "referee": "the SMT referee does not confirm {detail}", + "other": "the reading did not reach a sentence of the physics language" + }, + "examples": [ + "convert 3 kilometers to meters", + "express 5 kilometers per hour in meters per second", + "to meters per second convert 5 kilometers per hour", + "check that force times time equals mass times speed", + "audit force * length = energy", + "find the pi of the period from mass and stiffness", + "the dimensional analysis of speed from length and time" + ] +} diff --git a/lexicon/es.json b/lexicon/es.json new file mode 100644 index 0000000000000000000000000000000000000000..266ff393d15787e22a3de18a788c753a53f2171c --- /dev/null +++ b/lexicon/es.json @@ -0,0 +1,133 @@ +{ + "lang": "es", + "name": "Espanol", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "convert": { + "verbs": ["convierte", "convertir", "expresa", "expresar", "pasa", "pasar"], + "patterns": [ + "convierte {N} {U} a {V}", + "convertir {N} {U} a {V}", + "expresa {N} {U} en {V}", + "pasa {N} {U} a {V}", + "a {V} convierte {N} {U}" + ], + "frame": {"sequences": [["to"]]} + }, + "audit": { + "verbs": ["audita", "verifica", "comprueba", "valida", "demuestra"], + "patterns": [ + "audita {F}", + "verifica {F}", + "verifica que {F}", + "comprueba que {F}", + "demuestra que {F}", + "valida {F}" + ], + "frame": {"sequences": [[]]} + }, + "pi": { + "verbs": ["analisis dimensional", "grupo adimensional", "hallar el pi", "calcula el pi", "pi"], + "patterns": [ + "pi {T} a partir de {S}", + "hallar el pi {T} a partir de {S}", + "calcula el pi {T} a partir de {S}", + "el analisis dimensional {T} a partir de {S}", + "el grupo adimensional {T} a partir de {S}" + ], + "frame": {"sequences": [["from"]]} + } + }, + "connectives": { + "times": ["por", "multiplicado por"], + "over": ["dividido por", "entre"], + "plus": ["mas"], + "minus": ["menos"], + "power": ["elevado a"], + "equals": ["igual a", "es igual a"], + "list": ["y"] + }, + "markers": { + "to": ["a", "en"], + "from": ["a partir de", "partiendo de"] + }, + "tokens": { + "metro": "m", "metros": "m", + "kilometro": "km", "kilometros": "km", + "centimetro": "cm", "centimetros": "cm", + "milimetro": "mm", "milimetros": "mm", + "kilometros por hora": "km/h", "kilometro por hora": "km/h", + "metros por segundo": "m/s", "metro por segundo": "m/s", + "kilogramo": "kg", "kilogramos": "kg", "gramo": "g", "gramos": "g", + "segundo": "s", "segundos": "s", "milisegundo": "ms", "milisegundos": "ms", + "minuto": "min", "minutos": "min", "hora": "h", "horas": "h", + "dia": "day", "dias": "day", + "amperio": "A", "kelvin": "K", "mol": "mol", "candela": "cd", + "newton": "N", "newtons": "N", "julio": "J", "julios": "J", "vatio": "W", "vatios": "W", + "coulomb": "C", "coulombs": "C", "voltio": "V", "voltios": "V", + "ohmio": "ohm", "ohms": "ohm", "hertz": "Hz", "electronvoltio": "eV", "electronvoltios": "eV", + "masa": "mass", "longitud": "length", "tiempo": "time", "periodo": "period", + "frecuencia": "frequency", "velocidad": "speed", "rapidez": "speed", + "aceleracion": "acceleration", "gravedad": "gravity", "fuerza": "force", + "rigidez": "stiffness", "momento": "momentum", "energia": "energy", + "potencia": "power", "carga": "charge", "corriente": "current", + "tension": "voltage", "resistencia": "resistance", "temperatura": "temperature", + "cantidad": "amount", "luminosidad": "luminosity", "altura": "hgt" + }, + "noise": ["el", "la", "lo", "los", "las", "un", "una", "unos", "unas", "de", "del", "que", "cual", "cuales", "cuanto", "cuanta", "es", "se", "para", "con", "como"], + "labels": { + "understood": "Problema entendido", + "status": "Estado", + "assurance": "nivel {n} de 2", + "answer": "Respuesta", + "reading": "Lectura", + "physics_layer": "capa de fisica", + "notes": "Notas", + "examples": "Frases que esta capa entiende", + "question": "Vuelve a preguntar en una de estas formas", + "check": "Comprobacion SMT de la capa : {a} de {b} sobres confirmados", + "kind_of": "tipo" + }, + "reading": { + "AGREED": "acordada: dos lectores independientes mas la restriccion SMT", + "PASSTHROUGH": "frase ya escrita en la lengua de la fisica, no traducida", + "DISPUTED": "en disputa: los dos lectores proponen frases distintas", + "NOT COVERED": "fuera de la cobertura de esta lengua", + "AMBIGUOUS": "ambigua: hay mas de una lectura posible", + "TAMPERED": "manomita: el texto entregado a la capa de fisica no es la lectura acordada", + "SINGLE": "una sola lectura: el otro lector no reconocio la frase", + "NONE": "ninguna lectura" + }, + "reasons": { + "unknown_word": "la palabra {word} no aparece en las frases cubiertas en espanol", + "no_verb": "ninguna palabra anuncia el tipo de problema en espanol", + "two_verbs": "la frase anuncia mas de un tipo de problema: {kinds}", + "no_pattern": "la forma de la frase no corresponde a ninguna forma cubierta en espanol", + "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 de la lengua de la fisica distintas", + "markers": "los conectores de la frase no son los que espera el tipo de problema", + "bad_number": "{slot} no es un numero de la lengua de la fisica", + "bad_unit": "{slot} no es una unidad escrita con los simbolos de la lengua de la fisica", + "bad_formula": "{slot} no es una ecuacion con un solo signo de igualdad y simbolos conocidos", + "bad_symbol": "{slot} no es un simbolo de cantidad de la lengua de la fisica", + "unbalanced": "hay parentesis o corchetes sin cerrar", + "no_math": "la parte de fisica no esta escrita con los simbolos de la lengua de la fisica", + "literal_count": "los numeros de la frase no son los mismos en los dos lectores", + "physics_unknown": "la capa de fisica no acepta la frase: {detail}", + "boundary": "la frase entregada a la capa de fisica no es la lectura acordada", + "referee": "el arbitro SMT no confirma {detail}", + "other": "la lectura no llego a una frase de la lengua de la fisica" + }, + "examples": [ + "convierte 3 kilometros a metros", + "expresa 5 kilometros por hora en metros por segundo", + "a metros por segundo convierte 5 kilometros por hora", + "verifica que fuerza por tiempo es igual a masa por velocidad", + "audita fuerza por longitud = energia", + "hallar el pi del periodo a partir de masa y rigidez", + "el analisis dimensional de la velocidad a partir de longitud y tiempo" + ] +} diff --git a/lexicon/hi.json b/lexicon/hi.json new file mode 100644 index 0000000000000000000000000000000000000000..9707939227a356fc87d746133cb1de6e3bcbc15c --- /dev/null +++ b/lexicon/hi.json @@ -0,0 +1,126 @@ +{ + "lang": "hi", + "name": "हिन्दी", + "script": "devanagari", + "noise_chars": "", + "prefixes": [], + "kinds": { + "convert": { + "verbs": ["बदलो", "बदलें", "परिवर्तित करो", "रूपांतरित करो"], + "patterns": [ + "बदलो {N} {U} में {V}", + "बदलें {N} {U} में {V}", + "परिवर्तित करो {N} {U} में {V}", + "रूपांतरित करो {N} {U} में {V}" + ], + "frame": {"sequences": [["to"]]} + }, + "audit": { + "verbs": ["सिद्ध करें", "सिद्ध", "सत्यापित करें", "जांच करें", "दिखाएँ"], + "patterns": [ + "सिद्ध करें {F}", + "{F} सिद्ध करें", + "सत्यापित करें {F}", + "जांच करें {F}", + "दिखाएँ {F}", + "सिद्ध करें कि {F}" + ], + "frame": {"sequences": [[]]} + }, + "pi": { + "verbs": ["विमीय विश्लेषण", "pi ज्ञात करो", "pi की गणना करो", "pi"], + "patterns": [ + "pi {T} से {S}", + "pi ज्ञात करो {T} से {S}", + "pi की गणना करो {T} से {S}", + "विमीय विश्लेषण {T} से {S}" + ], + "frame": {"sequences": [["from"]]} + } + }, + "connectives": { + "times": ["गुणा", "का गुणा"], + "over": ["भाग", "का भाग"], + "plus": ["जोड़"], + "minus": ["ऋण"], + "power": ["का घात"], + "equals": ["के बराबर", "बराबर"], + "list": ["और", "तथा"] + }, + "markers": { + "to": ["में"], + "from": ["से"] + }, + "tokens": { + "मीटर": "m", "मीटरों": "m", + "किलोमीटर": "km", "किलोमीटरों": "km", + "सेंटीमीटर": "cm", "मिलीमीटर": "mm", + "किलोमीटर प्रति घंटा": "km/h", "मीटर प्रति सेकंड": "m/s", + "किलोग्राम": "kg", "किलोग्रामों": "kg", "ग्राम": "g", "ग्रामों": "g", + "सेकंड": "s", "सेकंडों": "s", "मिलिसेकंड": "ms", + "मिनट": "min", "मिनटों": "min", "घंटा": "h", "घंटे": "h", "दिन": "day", + "एम्पियर": "A", "केल्विन": "K", "मोल": "mol", "कैंडेला": "cd", + "न्यूटन": "N", "जूल": "J", "वाट": "W", "कूलॉम": "C", "वोल्ट": "V", + "ओम": "ohm", "हर्ट्ज": "Hz", "इलेक्ट्रॉनवोल्ट": "eV", + "द्रव्यमान": "mass", "लंबाई": "length", "समय": "time", "आवर्तकाल": "period", + "आवृत्ति": "frequency", "वेग": "speed", "त्वरण": "acceleration", + "गुरुत्वाकर्षण": "gravity", "बल": "force", "कठोरता": "stiffness", + "संवेग": "momentum", "ऊर्जा": "energy", "शक्ति": "power", "आवेश": "charge", + "विद्युत धारा": "current", "विभव": "voltage", "प्रतिरोध": "resistance", + "तापमान": "temperature", "मात्रा": "amount", "दीप्ति तीव्रता": "luminosity", + "ऊंचाई": "hgt" + }, + "noise": ["का", "की", "के", "को", "है", "हैं", "हो", "कि", "यह", "क्या", "मुझे", "कृपया", "बताइए", "दीजिए"], + "labels": { + "understood": "समझी गई समस्या", + "status": "स्थिति", + "assurance": "दो में से {n} स्तर", + "answer": "उत्तर", + "reading": "अर्थ", + "physics_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_number": "{slot} भौतिकी की भाषा की संख्या नहीं है", + "bad_unit": "{slot} भौतिकी की भाषा के प्रतीकों में लिखी इकाई नहीं है", + "bad_formula": "{slot} एक ही समानता चिह्न और ज्ञात प्रतीकों वाला समीकरण नहीं है", + "bad_symbol": "{slot} भौतिकी की भाषा का राशि प्रतीक नहीं है", + "unbalanced": "कोई कोष्ठक या वर्ग कोष्ठक बंद नहीं है", + "no_math": "भौतिकी का भाग भौतिकी की भाषा के प्रतीकों में नहीं लिखा है", + "literal_count": "दोनों पाठकों में वाक्य की संख्याएँ समान नहीं हैं", + "physics_unknown": "भौतिकी स्तर वाक्य नहीं स्वीकारता: {detail}", + "boundary": "भौतिकी स्तर को भेजा गया वाक्य सहमत अर्थ नहीं है", + "referee": "SMT निर्णायक {detail} की पुष्टि नहीं करता", + "other": "अर्थ भौतिकी की भाषा के वाक्य तक नहीं पहुँचा" + }, + "examples": [ + "बदलो 3 किलोमीटर में मीटर", + "परिवर्तित करो 5 किलोमीटर प्रति घंटा में मीटर प्रति सेकंड", + "सिद्ध करें बल गुणा समय के बराबर द्रव्यमान गुणा वेग", + "जांच करें बल गुणा लंबाई बराबर ऊर्जा", + "pi ज्ञात करो आवर्तकाल से द्रव्यमान और कठोरता", + "विमीय विश्लेषण वेग से लंबाई और समय" + ] +} diff --git a/lexicon/it.json b/lexicon/it.json new file mode 100644 index 0000000000000000000000000000000000000000..013f302618a09bcf6a721709f3d304f54bc22186 --- /dev/null +++ b/lexicon/it.json @@ -0,0 +1,141 @@ +{ + "lang": "it", + "name": "Italiano", + "script": "latin", + "noise_chars": "", + "prefixes": [], + "kinds": { + "convert": { + "verbs": ["converti", "convertire", "trasforma", "trasformare", "esprimi", "esprimere", "riduci", "ridurre"], + "patterns": [ + "converti {N} {U} in {V}", + "converti {N} {U} a {V}", + "convertire {N} {U} in {V}", + "trasforma {N} {U} in {V}", + "esprimi {N} {U} in {V}", + "riduci {N} {U} in {V}", + "in {V} converti {N} {U}" + ], + "frame": {"sequences": [["to"]]} + }, + "audit": { + "verbs": ["bilancia", "verifica", "controlla", "valida", "dimostra"], + "patterns": [ + "bilancia {F}", + "verifica {F}", + "verifica che {F}", + "controlla che {F}", + "dimostra che {F}", + "valida {F}" + ], + "frame": {"sequences": [[]]} + }, + "pi": { + "verbs": ["analisi dimensionale", "gruppo adimensionale", "trova il pi", "calcola il pi", "pi"], + "patterns": [ + "trova il pi {T} da {S}", + "trova il pi {T} a partire da {S}", + "calcola il pi {T} a partire da {S}", + "il gruppo adimensionale {T} a partire da {S}", + "il gruppo adimensionale {T} da {S}", + "analisi dimensionale {T} a partire da {S}", + "analisi dimensionale {T} da {S}" + ], + "frame": {"sequences": [["from"]]} + } + }, + "connectives": { + "times": ["per", "volte", "moltiplicato per"], + "over": ["diviso per", "su"], + "plus": ["piu"], + "minus": ["meno"], + "power": ["elevato a"], + "equals": ["uguale a", "e uguale a", "equivale a"], + "list": ["e"] + }, + "markers": { + "to": ["in", "a"], + "from": ["da", "a partire da", "partendo da"] + }, + "tokens": { + "metro": "m", "metri": "m", + "chilometro": "km", "chilometri": "km", + "centimetro": "cm", "centimetri": "cm", + "millimetro": "mm", "millimetri": "mm", + "chilometro all'ora": "km/h", "chilometri all'ora": "km/h", + "metro al secondo": "m/s", "metri al secondo": "m/s", + "metro quadro": "m^2", "metri quadri": "m^2", + "kilometro": "km", "kilometri": "km", + "chilogrammo": "kg", "chilogrammi": "kg", "grammo": "g", "grammi": "g", + "secondo": "s", "secondi": "s", + "millisecondo": "ms", "millisecondi": "ms", + "minuto": "min", "minuti": "min", + "ora": "h", "ore": "h", + "giorno": "day", "giorni": "day", + "ampere": "A", "kelvin": "K", "mole": "mol", "candela": "cd", + "newton": "N", "joule": "J", "watt": "W", "coulomb": "C", "volt": "V", + "ohm": "ohm", "hertz": "Hz", "elettronvolt": "eV", + "massa": "mass", "lunghezza": "length", "tempo": "time", + "periodo": "period", "frequenza": "frequency", + "velocita": "speed", "accelerazione": "acceleration", "gravita": "gravity", + "forza": "force", "rigidita": "stiffness", "momento": "momentum", + "energia": "energy", "potenza": "power", "carica": "charge", + "corrente": "current", "tensione": "voltage", "resistenza": "resistance", + "temperatura": "temperature", "quantita": "amount", "luminosita": "luminosity", + "altezza": "hgt" + }, + "noise": ["il", "la", "lo", "l", "i", "le", "gli", "un", "uno", "una", "di", "del", "della", "dei", "delle", "che", "con", "alla", "alle", "al", "ai", "quale", "quanti", "quante", "quanto", "qual", "cos", "cosa", "perche", "se"], + "labels": { + "understood": "Problema capito", + "status": "Stato", + "assurance": "livello {n} di 2", + "answer": "Risposta", + "reading": "Lettura", + "physics_layer": "strato fisica", + "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 fisica, 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 fisico 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 fisica diverse", + "markers": "i connettori della frase non sono quelli attesi per il tipo di problema", + "bad_number": "{slot} non e un numero della lingua fisica", + "bad_unit": "{slot} non e un'unita scritta con i simboli della lingua fisica", + "bad_formula": "{slot} non e un'equazione con una sola uguaglianza e simboli noti", + "bad_symbol": "{slot} non e un simbolo di quantita della lingua fisica", + "unbalanced": "parentesi o parentesi quadre non chiuse", + "no_math": "la parte fisica non e scritta con i simboli della lingua fisica", + "literal_count": "i numeri della frase non sono gli stessi nei due lettori", + "physics_unknown": "lo strato fisico non accetta la frase: {detail}", + "boundary": "la frase passata allo strato fisico non e quella concordata", + "referee": "il controllore SMT non conferma {detail}", + "other": "la lettura non e arrivata a una frase della lingua fisica" + }, + "examples": [ + "converti 3 chilometri in metri", + "esprimi 5 chilometri all'ora in metri al secondo", + "in metri al secondo converti 5 chilometri all'ora", + "verifica che la forza per il tempo e uguale a massa per velocita", + "bilancia forza per lunghezza = energia", + "trova il pi del periodo a partire da massa e rigidita", + "l'analisi dimensionale della velocita a partire da lunghezza e tempo" + ] +} diff --git a/lexicon/zh.json b/lexicon/zh.json new file mode 100644 index 0000000000000000000000000000000000000000..78f1ec750d896de2f271cc0503ea1c81cdff6e16 --- /dev/null +++ b/lexicon/zh.json @@ -0,0 +1,122 @@ +{ + "lang": "zh", + "name": "中文", + "script": "cjk", + "noise_chars": "的了之把被给吧呢吗也则该", + "prefixes": [], + "kinds": { + "convert": { + "verbs": ["换算", "转换", "改写"], + "patterns": [ + "换算 {N} {U} 成 {V}", + "换算 {N} {U} 为 {V}", + "换算 {N} {U} 到 {V}", + "转换 {N} {U} 成 {V}", + "转换 {N} {U} 为 {V}", + "改写 {N} {U} 为 {V}" + ], + "frame": {"sequences": [["to"]]} + }, + "audit": { + "verbs": ["校验", "检验", "验证", "检查"], + "patterns": [ + "校验 {F}", + "检验 {F}", + "验证 {F}", + "检查 {F}" + ], + "frame": {"sequences": [[]]} + }, + "pi": { + "verbs": ["量纲分析", "求pi", "计算pi", "pi"], + "patterns": [ + "pi {T} 由 {S}", + "求pi {T} 由 {S}", + "计算pi {T} 由 {S}", + "量纲分析 {T} 由 {S}" + ], + "frame": {"sequences": [["from"]]} + } + }, + "connectives": { + "times": ["乘以", "乘"], + "over": ["除以"], + "plus": ["加"], + "minus": ["减"], + "power": ["的幂"], + "equals": ["等于"], + "list": ["和", "与"] + }, + "markers": { + "to": ["成", "为", "到"], + "from": ["由", "从"] + }, + "tokens": { + "米": "m", "公里": "km", "千米": "km", "厘米": "cm", "毫米": "mm", + "千米每小时": "km/h", "公里每小时": "km/h", "米每秒": "m/s", "米平方": "m^2", + "千克": "kg", "公斤": "kg", "克": "g", + "秒": "s", "毫秒": "ms", "分钟": "min", "小时": "h", "天": "day", + "安培": "A", "开尔文": "K", "摩尔": "mol", "坎德拉": "cd", + "牛顿": "N", "焦耳": "J", "瓦特": "W", "库仑": "C", "伏特": "V", + "欧姆": "ohm", "赫兹": "Hz", "电子伏特": "eV", + "质量": "mass", "长度": "length", "时间": "time", "周期": "period", + "频率": "frequency", "速度": "speed", "加速度": "acceleration", + "重力": "gravity", "力": "force", "刚度": "stiffness", "动量": "momentum", + "能量": "energy", "功率": "power", "电荷": "charge", "电流": "current", + "电压": "voltage", "电阻": "resistance", "温度": "temperature", + "物质的量": "amount", "发光强度": "luminosity", "高度": "hgt" + }, + "noise": ["求", "请", "试", "是", "为", "的", "了"], + "labels": { + "understood": "理解的问题", + "status": "状态", + "assurance": "两级中的第 {n} 级", + "answer": "答案", + "reading": "读法", + "physics_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_number": "{slot} 不是物理语言中的一个数", + "bad_unit": "{slot} 不是用物理语言的符号写出的单位", + "bad_formula": "{slot} 不是只含一个等号且符号已知的等式", + "bad_symbol": "{slot} 不是物理语言中的量符号", + "unbalanced": "有个圆括号或方括号没有闭合", + "no_math": "物理部分没有用物理语言的符号书写", + "literal_count": "句子中的数字在两位读者那里并不相同", + "physics_unknown": "物理层不接受这个句子:{detail}", + "boundary": "送往物理层的句子不是那个一致的读法", + "referee": "SMT 裁判没有确认 {detail}", + "other": "读法没有得到物理语言中的一个句子" + }, + "examples": [ + "换算 3 公里 成 米", + "换算 5 千米每小时 为 米每秒", + "校验 力 乘以 时间 等于 质量 乘以 速度", + "检验 力 乘以 长度 等于 能量", + "求pi 周期 由 质量 和 刚度", + "量纲分析 速度 由 长度 和 时间" + ] +} diff --git a/lgphysstratum/__init__.py b/lgphysstratum/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..aa2a1876af8c43f9adfbd11bdcf6a86655da5cd1 --- /dev/null +++ b/lgphysstratum/__init__.py @@ -0,0 +1,10 @@ +"""Physics stratum: the conversational layer that sits on top of the physics topology. + +The modules of this package read a question written in one of six written varieties, agree on one +sentence of the physics language, hand that sentence to the physics topology as a separate process, +and answer in the language of the question with an assurance that never exceeds the assurance of +the physics verdict *and* never exceeds what the reading of the question deserves. +""" + +__all__ = ["agents", "canonical", "compare", "corpus", "coverage", "decide", "faults", "invoker", + "lexicon", "pipeline", "protocol", "read_a", "read_b", "render", "segment"] diff --git a/lgphysstratum/agents.py b/lgphysstratum/agents.py new file mode 100644 index 0000000000000000000000000000000000000000..3cf8c7444c266324864a1fa0b0872c910f4d2b5e --- /dev/null +++ b/lgphysstratum/agents.py @@ -0,0 +1,307 @@ +"""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 physics layer runs, only moved one +level up: two independent readers instead of two independent readers of the formal language, 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 physics layer 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? the parser of the bundle answers, text + identity is a shortcut and the solver settles the numbers + coverage did the readings keep every number the user wrote? + invoker call the physics layer, in another process, on one sentence + boundary the physics 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 physics layer, ceiling of the reading)``. 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, physics=%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("physics") 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 faults.READER_FAULTS: + 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 behind 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 _produced(dossier: Dict[str, Any]) -> List[Dict[str, Any]]: + """The readings that actually produced a sentence, in reader order.""" + return [item for item in (dossier.get("reading_direct") or {}, dossier.get("reading_a") or {}, + dossier.get("reading_b") or {}) if item.get("math")] + + +def _echo_reference(dossier: Dict[str, Any], produced: List[Dict[str, Any]]) -> Dict[str, Any]: + """The reading whose sentence is the one the physics layer was asked about. + + The boundary and the adversary compare the echo of the physics layer with a reading rather than + with the sentence the previous node copied into the dossier, because a reading is an independent + channel. Either reader may be the one that abstained, so the reference is chosen by matching the + sentence, not by reader order. + """ + agreed = canonical.tidy(str(dossier.get("sent") or "")) + return next((item for item in produced if canonical.tidy(str(item.get("math"))) == agreed), + produced[0] if produced else {}) + + +def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]: + """Ask the physics layer, 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["physics"] = invoker.unavailable("no sentence was agreed on") + summary = "invoker: nothing to ask the physics layer" + return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), + ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat") + verdict = invoker.ask(sentence) + dossier["physics"] = verdict + wrote = compare.sorted_numbers(sentence) + echo = compare.sorted_numbers(str(verdict.get("problem_physics") 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 physics verdict enters this stratum here; the echo it carries is checked, not trusted.""" + dossier, turn, tick, rcpt = protocol.start(incoming) + # The echo is checked against a reading, not against the sentence the previous node wrote down: + # a reading is an independent channel. One reading may have failed while the other produced the + # sentence that was asked, so the readings used here are the ones that produced a sentence. + produced = _produced(dossier) + reading = _echo_reference(dossier, produced) + physics_verdict = dict(dossier.get("physics") or {}) + agreed = str(dossier.get("sent") or "") + echo = str(physics_verdict.get("problem_physics") or "") + if echo: + matches = coverage.echo_matches(reading, physics_verdict) + decls, asserts = compare.elementwise(compare.sorted_numbers(agreed), + compare.sorted_numbers(echo), "echo") + asserts = asserts + (["(assert (= 1 1))"] if matches else ["(assert false)"]) + claimed = "sat" if matches else "unsat" + else: + # The physics layer 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_physics") and echo: + tampered, changed = faults.mutate_sentence(node_id, echo) + if changed: + faults.fire(node_id, "tamper_physics") + physics_verdict["problem_physics"] = tampered + physics_verdict["fault"] = "tamper_physics" + dossier["physics"] = physics_verdict + dossier["echo_ok"] = bool(matches) + summary = "boundary: %s echoed=%s" % (physics_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") + physics_verdict = dossier.get("physics") or {} + cover = dossier.get("coverage") + if faults.has(node_id, "rubber_stamp"): + faults.fire(node_id, "rubber_stamp") + echo_ok = True + else: + produced = _produced(dossier) + echo_ok = (coverage.echo_matches(_echo_reference(dossier, produced), physics_verdict) + if physics_verdict.get("problem_physics") else True) + for other in produced: + if not coverage.echo_matches(other, physics_verdict): + echo_ok = False + dossier["echo_ok"] = bool(echo_ok) + state = decide.state_of(readings, comparison, cover, + physics_verdict if physics_verdict.get("status") else None, + dossier.get("reading_direct"), echo_ok) + ceiling = decide.CEILING[state] + shown = min(ceiling, int(physics_verdict.get("assurance", 0) or 0)) + dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown, + "physics_assurance": int(physics_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") + # Three is above the top of the scale this project uses for physics, so the cap claim of this + # very node is the sentence that refutes it. + 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/lgphysstratum/canonical.py b/lgphysstratum/canonical.py new file mode 100644 index 0000000000000000000000000000000000000000..3e8a3d3a98d25fc5a46e503070a62dbb685a1fc6 --- /dev/null +++ b/lgphysstratum/canonical.py @@ -0,0 +1,375 @@ +"""The canonical form of a physics sentence, and the shape a slot must have to be physics. + +The stratum does not parse physics: it *prints* a sentence of the physics language and hands it to +the physics topology, which owns the parser, the unit algebra and the verdict. What this module +owns is the other half of the contract: + +* ``TEMPLATES`` -- one template per kind the reading layer covers, written the way ``canon`` of the + physics topology prints it, so that the sentence the stratum understood and the fingerprint the + two roads of the physics chain compare are the same string; +* ``print_math`` -- fill the slots of a template and tidy the result; +* ``gap_markers`` and ``marker_sequence`` -- the joints of a template (``to`` of a conversion, + ``from`` of a dimensional analysis), which is reader B's skeleton: a reading is what falls + between those joints; +* the slot validators -- ``number``, ``unit``, ``formula``, ``symbol``, ``symbols``. They do not + compute physics: they check that what the readers found has the shape a physics sentence needs, + so that a wrong reading stops here with a reason instead of reaching the physics topology as + nonsense; +* ``direct`` -- a sentence already written in the physics language, which is how the circuit + family stays reachable without a translation. + +``tidy`` is the one normal form the two readers compare notes in. The physics tokenizer separates +its tokens at every space and at every character of ``()[]=^;,``, so tidying never changes what the +physics topology reads. Unlike the math counterpart, it does not insert a multiplication sign +between a number and a letter: in physics ``3 m`` is a number and a unit, two tokens, and gluing +them into ``3*m`` would ask the physics topology to multiply a quantity by a symbol. +""" + +import re +from fractions import Fraction +from typing import Any, Dict, List, Optional, Sequence, Tuple + +KINDS = ("convert", "audit", "pi") + +# kind -> list of (slots, template). The template is what ``lgphys.tree.canon`` prints, so the +# sentence the stratum shows is the sentence the two roads of the physics chain compare. +TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = { + "convert": [(("N", "U", "V"), "convert {N} {U} to {V}")], + "audit": [(("F",), "audit {F}")], + "pi": [(("T", "S"), "pi {T} from {S}")], +} + +SLOT_ORDER: Dict[str, Tuple[str, ...]] = {kind: TEMPLATES[kind][0][0] for kind in KINDS} +VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [slots for slots, _ in TEMPLATES[kind]] + for kind in KINDS} + +# The joints of the physics language: the fixed words between the slots of a template. +MARKERS = ("to", "from") +_PHRASE_MARKER = {"to": "to", "from": "from"} + +_SLOT_MARK = re.compile(r"\{([NUVFST])\}") +_SINGLE_LETTER = re.compile(r"[A-Za-z]$") + + +class ReadingError(Exception): + """A sentence cannot be printed as physics: a slot is missing or a template holds a stray word.""" + + +def template_for(kind: str, variant: Optional[Sequence[str]] = None) -> str: + """The template of one form of one kind.""" + if kind not in TEMPLATES: + raise ReadingError("no template for the kind %s" % kind) + forms = TEMPLATES[kind] + if variant is None: + return forms[0][1] + wanted = tuple(variant) + for slots, text in forms: + if slots == wanted: + return text + raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(wanted))) + + +def slots_for(kind: str, variant: Optional[Sequence[str]] = None) -> Tuple[str, ...]: + """The slots of one form, in the order the template fills them.""" + if kind not in TEMPLATES: + raise ReadingError("no template for the kind %s" % kind) + if variant is None: + return SLOT_ORDER[kind] + wanted = tuple(variant) + if wanted not in VARIANTS[kind]: + raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(wanted))) + return wanted + + +def print_math(kind: str, slots: Dict[str, str], variant: Optional[Sequence[str]] = None) -> str: + """Fill one template and tidy it: the sentence the physics topology is asked to answer.""" + wanted = slots_for(kind, variant) + for name in wanted: + if name not in slots or not str(slots[name]).strip(): + raise ReadingError("the form of %s needs the slot %s" % (kind, name)) + extra = [name for name in slots if name not in wanted] + if extra: + raise ReadingError("%s has no slot named %s" % (kind, " ".join(sorted(extra)))) + return tidy(template_for(kind, variant).format(**{name: _slot_spelling(name, str(slots[name])) + for name in wanted})) + + +def gap_markers(kind: str, variant: Optional[Sequence[str]] = None) -> List[Optional[str]]: + """The joints of a template, one entry per gap around the slots. + + 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 physics + that fall between those joints, and a joint may not be missing or out of order. + """ + # The capture group keeps the slot marks in the list, so the literals sit at the even indices. + parts = re.split(r"(\{[NUVFST]\})", template_for(kind, variant)) + gaps: List[Optional[str]] = [] + for index in range(0, len(parts), 2): + literal = parts[index] + 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 physics language" % (kind, phrase)) + return gaps + + +def marker_sequence(kind: str, variant: Optional[Sequence[str]] = None) -> List[str]: + """The joints of one form, named in the order the physics 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 physics language tolerates whitespace anywhere between its tokens -- verified against the + physics topology itself, which reads ``audit ( F * t ) = ( m * v )`` and + ``audit (F*t)=(m*v)`` as the same equation -- so tidying never changes what physics sees. 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, and for physics that rule is stricter + than for math: ``3 m`` stays ``3 m``, because the number and the unit are two tokens and the + unit table of the physics topology reads them apart. + """ + 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(_AFTER_CLOSED, "", out) + out = re.sub(_BEFORE_OPEN, "", out) + return out + + +def number(text: str) -> Optional[str]: + """A slot value that is a number token of the physics language, or ``None``. + + Integer, decimal or explicit fraction, kept exactly as written: rewriting ``0.5`` as ``1/2`` + would change the digits the question carries, and the coverage check compares those digits. + """ + cleaned = tidy(text) + if not cleaned: + return None + try: + if "/" in cleaned: + head, tail = cleaned.split("/", 1) + Fraction(head.strip()) / Fraction(tail.strip()) + else: + Fraction(cleaned) + except (ValueError, ZeroDivisionError, TypeError): + return None + return cleaned + + +def unit(text: str) -> Optional[str]: + """A slot value that is a unit expression, or ``None``. + + Only the shape is checked here -- known unit names joined by ``*``, ``/`` and an integer power. + Whether the two ends of a conversion are comparable units is physics, and the physics topology + is the one that answers it. + """ + cleaned = tidy(text) + if not cleaned: + return None + seen = False + for part in re.split(r"[\s*/^]+", cleaned): + if not part: + continue + if part.isdigit(): + continue + if _UNIT_FORMS.get(part.lower(), part) not in PHYSICS_UNITS: + return None + seen = True + return normalize_unit(cleaned) if seen else None + + +def formula(text: str) -> Optional[str]: + """A slot value that is one equation of physics terms, or ``None``. + + The check is syntactic and deliberately shallow: one equality sign, brackets closed, and every + word of it a word of the physics language. Dimensional homogeneity is what the audit family of + the physics topology decides, and the stratum never decides it twice. + """ + cleaned = tidy(text) + if not cleaned or cleaned.count("=") != 1 or not balanced(cleaned): + return None + for word in re.findall(r"[A-Za-z]+", cleaned): + if word in PHYSICS_WORDS: + continue + if _FORMULA_FORMS.get(word.lower(), word) in PHYSICS_WORDS: + continue + return None + return _respell(cleaned, _FORMULA_FORMS) + + +def symbol(text: str) -> Optional[str]: + """A slot value that is one quantity symbol, or ``None``.""" + cleaned = tidy(text) + if not cleaned or "," in cleaned: + return None + words = re.findall(r"[A-Za-z]+", cleaned) + if not words or "".join(words) != cleaned.replace(" ", ""): + return None + if len(words) != 1 or _SYMBOL_FORMS.get(words[0].lower(), words[0]) not in PHYSICS_SYMBOLS: + return None + return normalize_symbol(cleaned) + + +def symbols(text: str) -> Optional[str]: + """A slot value that is a list of quantity symbols separated by commas, or ``None``. + + The printed form puts one space after every comma, which is what ``lgphys.tree.canon`` prints + for a Buckingham analysis: ``pi period from mass, stiffness``. + """ + cleaned = tidy(text) + if not cleaned: + return None + parts = [part.strip() for part in cleaned.split(",")] + if len(parts) < 2: + return None + values = [] + for part in parts: + value = symbol(part) + if value is None: + return None + values.append(value) + return ", ".join(values) + + +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 physics language, copied from the parser specification of the physics +# topology. The reading layer covers three of them; the circuit family stays reachable through the +# direct mode. +PHYSICS_COMMANDS = ("convert", "audit", "pi", "potential") + +# The units of the physics topology, copied from ``lgphys.units``. +PHYSICS_UNITS = frozenset([ + "m", "kg", "s", "A", "K", "mol", "cd", + "N", "J", "W", "C", "V", "ohm", "Hz", + "g", "km", "cm", "mm", "ms", "min", "h", "day", "eV", +]) + +# The quantity symbols of the physics topology, copied from the same table. +PHYSICS_SYMBOLS = frozenset([ + "mass", "m", "length", "r", "hgt", "d", + "time", "t", "period", "frequency", + "speed", "v", "acceleration", "a", "gravity", "g", + "force", "F", "stiffness", "k", "momentum", "p", + "energy", "E", "power", "P", "charge", "q", + "current", "I", "voltage", "V", "resistance", "R", + "temperature", "T", "amount", "n", "luminosity", +]) + +# The words the physics language itself uses: the commands, the joints, the keywords of the circuit +# form, every unit and every quantity symbol. A sentence that carries a word outside this list is +# not written in the physics language, whatever else it looks like. This is the third copy of that +# spec (the physics topology parses with it, its grammar names it), and the direct mode is where +# the copies can disagree out loud. ``tests/test_lexicon.py`` checks the copy against the live +# table of the physics topology whenever that folder is present. +PHYSICS_WORDS = frozenset( + set(PHYSICS_COMMANDS) + | set(MARKERS) + | {"node", "circuit", "resistors", "sources", "size", "frequency"} + | set(PHYSICS_UNITS) + | set(PHYSICS_SYMBOLS) +) + +# The spelling maps. Both readers fold the sentence before they read it, and the physics language is +# not case free: the volt is ``V`` and the speed is ``v``, the force is ``F`` and the gram is ``g``. +# So a slot value arrives in a case the physics topology would refuse, and the printer puts the +# spelling of the physics language back: a translation of spelling, not of content, and the only +# place where the stratum is allowed to change a letter. +# +# One letter is genuinely lost on the way. ``p`` reaches the stratum folded from both the momentum +# ``p`` and the power ``P``, and the stratum prints the momentum, because that is the one the physics +# language writes in lower case. Writing the word ("power") is how a user keeps the distinction, and +# the README of this folder says so. +_UNIT_FORMS = {name.lower(): name for name in sorted(PHYSICS_UNITS)} +_SYMBOL_FORMS: Dict[str, str] = {} +for _name in sorted(PHYSICS_SYMBOLS, key=lambda word: (word.lower(), not word.islower())): + _SYMBOL_FORMS.setdefault(_name.lower(), _name) + +_WORD = re.compile(r"[A-Za-z]+") + + +def _respell(text: str, forms: Dict[str, str]) -> str: + """Rewrite every word of a slot value in the spelling the physics topology expects.""" + return _WORD.sub(lambda match: forms.get(match.group(0), match.group(0)), text) + + +def normalize_unit(text: str) -> str: + """The unit expression of a slot, respelled as the physics language writes it.""" + return _respell(tidy(text), _UNIT_FORMS) + + +def normalize_symbol(text: str) -> str: + """The symbol list of a slot, respelled and printed with one space after every comma.""" + return ", ".join(_respell(part.strip(), _SYMBOL_FORMS) for part in text.split(",")) + + +# Inside the term of an audit a word names a quantity, so the symbol spelling wins where a letter is +# both a symbol and a unit: the physics parser of an equation reads ``m`` as the length, and the +# unit table is not consulted there. +_FORMULA_FORMS: Dict[str, str] = dict(_UNIT_FORMS) +_FORMULA_FORMS.update(_SYMBOL_FORMS) + + +def _slot_spelling(name: str, value: str) -> str: + """A slot value in the spelling the physics topology expects, by the shape of the slot.""" + if name in ("U", "V"): + return normalize_unit(value) + if name in ("T", "S"): + return normalize_symbol(value) + if name == "F": + return _respell(tidy(value), _FORMULA_FORMS) + return tidy(value) + + +_NOT_PHYSICS_CHARACTER = re.compile(r"[^A-Za-z0-9\s+\-*/^()\[\]<>=!|,.;]") +_PHYSICS_WORD = re.compile(r"[A-Za-z]+") + + +def direct(text: str) -> Optional[Dict[str, Any]]: + """A sentence already written in the physics 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 physics topology: it fires only when the first + word is a command of the physics language, every other word is a word of that language or a one + letter symbol, 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_PHYSICS_CHARACTER.search(cleaned): + return None + words = _PHYSICS_WORD.findall(cleaned) + if not words or words[0].lower() not in PHYSICS_COMMANDS: + return None + for word in words[1:]: + if len(word) > 1 and word not in PHYSICS_WORDS and word.lower() not in PHYSICS_WORDS: + return None + if not balanced(cleaned): + return None + return {"mode": "direct", "kind": words[0].lower(), "math": cleaned, "slots": {}} diff --git a/lgphysstratum/compare.py b/lgphysstratum/compare.py new file mode 100644 index 0000000000000000000000000000000000000000..ac2fb9a7fcfa5cbd4a132417a6561ff9be78db5e --- /dev/null +++ b/lgphysstratum/compare.py @@ -0,0 +1,259 @@ +"""The equivalence of the two readings: do the two readers mean the same problem? + +Reader A and reader B reach their sentence of the physics 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 the owner of the language, which +is what the physics layer itself does between its two readers. + +The account of the physics language is **not reimplemented here**. The physics bundle owns its +parser and its canonical rendering (:envvar:`LGPHYSSTRATUM_PHYSICS_ROOT`, sibling folder ``physics`` +by default), and a second copy of it inside the reading layer would be a third place where the +meaning of a physical sentence could be wrong without anyone noticing. So this module loads the +bundle, asks it to parse both sentences, and compares the canonical text the bundle itself prints: +two readings whose trees are the same tree are one problem. + +What travels as SMT2 is the part that is genuinely arithmetic: the numbers of the two readings, +pinned to declared reals and compared item by item. The physics bundle checks its laws on exact +rationals in its own units module, not as one SMT program per problem, so a claim about the +*meaning* of a physical sentence is not something this stratum may hand to Z3 and call a proof. +Two limits follow, and both are limits, not shortcuts: + +* a sentence the bundle will not parse is reported ``unknown`` and the session treats it as a + dispute: the reading layer would rather abstain than assume two texts are equal; +* the SMT claim of this module is *about the readings*, never about the user's problem. The problem + itself is never decided here: the sentence is handed to the physics layer, whose verdict is shown + as it arrived. +""" + +import sys +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, invoker, segment + +_physics = None +_PHYSICS_LOOKUP_ERROR: Optional[str] = None + + +def _physics_modules() -> Tuple[Any, Any, Any, Optional[str]]: + """The physics bundle's parser, tree printer and solver, or the reason they are absent.""" + global _physics, _PHYSICS_LOOKUP_ERROR + if _physics is not None: + return _physics[0], _physics[1], _physics[2], None + if _PHYSICS_LOOKUP_ERROR is not None: + return None, None, None, _PHYSICS_LOOKUP_ERROR + root = invoker.physics_root() + if not (root / "lgphys").is_dir(): + _PHYSICS_LOOKUP_ERROR = "no lgphys package under %s" % root + return None, None, None, _PHYSICS_LOOKUP_ERROR + text = str(root) + if text not in sys.path: + sys.path.insert(0, text) + try: + # The import of the physics bundle is the point of this module: one owner of the language. + from lgphys import parse_a, smt, tree # noqa: PLC0415 + except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently + _PHYSICS_LOOKUP_ERROR = "the physics bundle could not be imported: %s" % type(exc).__name__ + return None, None, None, _PHYSICS_LOOKUP_ERROR + _physics = (parse_a, tree, smt) + return _physics[0], _physics[1], _physics[2], None + + +ONTOLOGY = "(set-option :timeout 8000)\n" + + +def smt_referee(decls: List[str], asserts: List[str]) -> str: + """Run the referee of the physics layer over one claim, the way the orchestrator does each turn. + + The same code answers here and in the physics bundle, so an envelope that this stratum writes is + checked by the solver the project already trusts; the stratum adds no second referee. + """ + _parser, _tree, smt, _reason = _physics_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[str]: + """The canonical text the physics bundle prints for one sentence, or ``None``.""" + parse_a, tree, _smt, _reason = _physics_modules() + if parse_a is None: + return None + try: + return str(tree.canon(parse_a.parse(sentence))) + except Exception: # noqa: BLE001 - a sentence the bundle rejects is a sentence to report + return None + + +def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]: + """The slots one reading actually filled, in the order the physics 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 _number_claim(left: str, right: str) -> Tuple[List[str], List[str], str, str, Any]: + """SMT2 for ``the two readings carry different numbers``, and what the solver says. + + The declarations and the assertion are one plain SMT2 program: for each position, two reals + pinned to the two literals, and the negation of their equality. Unsatisfiable means the two + readings carry the same numbers under every assignment. 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. + """ + first = sorted_numbers(left) + second = sorted_numbers(right) + if len(first) != len(second): + return [], ["(assert false)"], "unsat", "different", None + decls: List[str] = [] + asserts: List[str] = [] + names: List[str] = [] + for index, (value, other) in enumerate(zip(first, second)): + name = "eq_%d" % index + decls.append("(declare-const %sa Real)" % name) + decls.append("(declare-const %sb Real)" % name) + asserts.append("(assert (= %sa %s))" % (name, value)) + asserts.append("(assert (= %sb %s))" % (name, other)) + asserts.append("(assert (not (= %sa %sb)))" % (name, name)) + names = names + ["%sa" % name, "%sb" % name] + _parser, _tree, smt, _reason = _physics_modules() + if smt is None: + return decls, asserts, "unknown", "unknown", None + status = str(smt.check(decls, asserts)) + if status == "unsat": + return decls, asserts, "unsat", "same_numbers", None + if status == "sat": + model = smt.solve_values(decls, asserts, names) + return decls, asserts, "sat", "different", ({key: str(value) for key, value in model.items()}) + return decls, asserts, "unknown", "unknown", None + + +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, _tree, _smt, reason = _physics_modules() + first, second = formalize(left), formalize(right) + if first is None or second is None: + note = reason or "the physics bundle does not read one of the two sentences" + 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} + if first == second: + # Two different wordings, one tree: the bundle itself says they are the same problem. + return {"same": True, "why": "tree", "left": first, "right": second, "detail": detail, + "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None} + + decls, assertions, claimed, label, model = _number_claim(first, second) + if claimed == "unknown": + detail.append("the solver gave no answer about the numbers of the two readings") + if label == "different": + detail.append("two readings that carry different numbers") + return {"same": False, "why": "smt", "left": first, "right": second, "detail": detail, + "declarations": decls, "assertions": assertions, "claimed": claimed, "model": model} + detail.append("two sentences the physics bundle prints differently") + return {"same": False, "why": "structure", "left": first, "right": second, "detail": detail, + "declarations": decls, "assertions": assertions, "claimed": claimed, "model": model} + + +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_physics(reading: Dict[str, Any], physics_verdict: Dict[str, Any]) -> bool: + """Did the physics layer solve the sentence the readers agreed on? + + The physics layer echoes the problem it understood. That echo is an independent channel: a node + standing between the readers and the layer can rewrite its own record, but it cannot move the + echo without moving numbers that were counted upstream. The comparison is on the canonical text + of the bundle, because the layer prints spaces around operators and this stratum does not. + """ + echo = canonical.tidy(str(physics_verdict.get("problem_physics", ""))) + agreed = canonical.tidy(str(reading.get("math", ""))) + if not agreed or not echo: + return False + if echo == agreed: + return sorted_numbers(echo) == sorted_numbers(agreed) + left, right = formalize(echo), formalize(agreed) + if left is None or right is None: + return False + return left == right and sorted_numbers(left) == sorted_numbers(right) + + +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 physics layer uses, zero to two, 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 above the layer, because reading a sentence written in a human + language is never the last word -- 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/lgphysstratum/corpus.py b/lgphysstratum/corpus.py new file mode 100644 index 0000000000000000000000000000000000000000..dc7982058c96e26b1d942f602f7a2bee76b477cc --- /dev/null +++ b/lgphysstratum/corpus.py @@ -0,0 +1,90 @@ +"""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-convert-1", "lang": "it", "question": "converti 3 chilometri in metri", + "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "min_assurance": 1}} + +``state`` is the only mandatory key. ``sentence`` is compared after tidying, and when the tidy texts +differ the two are handed to the parser of the physics bundle, which owns the canonical spelling of +its own sentences: a gold line written with the spacing of the layer and a reading written without it +are one sentence. ``answer_contains`` is a substring test on the answer the physics layer 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, compare, 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 _same_sentence(got: str, wanted: str) -> bool: + """Two spellings of one sentence of the physics language?""" + if canonical.tidy(got) == canonical.tidy(wanted): + return True + first, second = compare.formalize(got), compare.formalize(wanted) + return first is not None and first == second + + +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: + got = str((result.get("dossier") or {}).get("sent", "")) + if not _same_sentence(got, str(expect["sentence"])): + problems.append("sentence %r, expected %r" % (canonical.tidy(got), canonical.tidy(expect["sentence"]))) + 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_physics: 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_physics=call_physics) + verdict = grade(item, result) + verdict["records"] = result["records"] + verdict["dossier"] = result["dossier"] + verdict["reply"] = result["reply"] + return verdict diff --git a/lgphysstratum/coverage.py b/lgphysstratum/coverage.py new file mode 100644 index 0000000000000000000000000000000000000000..8268336aed0c217d98fce551a397bbe82e5fb8a9 --- /dev/null +++ b/lgphysstratum/coverage.py @@ -0,0 +1,94 @@ +"""What the reading kept, and what the physics layer 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 physics 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 physics layer 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 layer can rewrite its own record, but it cannot move the + echo without moving numbers that were counted upstream. + +Neither check decides physics. They count tokens, they hand the counting to a solver so that a node +claiming the numbers were kept is checked against that claim, and the identity of two sentences is +settled by the parser of the bundle, which owns that language. +""" + +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(physics_verdict: Dict[str, Any]) -> List[str]: + """The numbers of the problem the physics layer says it solved, ordered by value.""" + return compare.sorted_numbers(canonical.tidy(str(physics_verdict.get("problem_physics", "")))) + + +def echo_matches(reading: Dict[str, Any], physics_verdict: Dict[str, Any]) -> bool: + """Did the physics layer solve the sentence the readers agreed on? + + A verdict that names no sentence at all -- the backend was off, or the physics layer could not + be started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls + to zero because there is no physics 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(physics_verdict.get("problem_physics", "")).strip(): + return True + return compare.agrees_with_physics(reading, physics_verdict) + + +def coverage_claim(question: str, readings: List[Dict[str, Any]], + physics_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 physics + layer 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 physics_verdict is not None: + echo = echo_numbers(physics_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/lgphysstratum/decide.py b/lgphysstratum/decide.py new file mode 100644 index 0000000000000000000000000000000000000000..f432535d86550cc9bf19ba786a4d581f57ff8e0a --- /dev/null +++ b/lgphysstratum/decide.py @@ -0,0 +1,170 @@ +"""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 physics layer 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 physics layer uses for its own ``decide``. + +The rule the whole module exists to enforce: + + assurance(shown) = min(assurance(physics), assurance(reading)) + +and ``assurance(reading)`` is at most two, which is also the highest level the physics layer ever +reaches: no chain of this project adds a third witness on top of a physical statement, because a +law of physics is not proved by a second formalizer but by the agreement of two independent +routes. The stratum therefore never reports more than the layer, and a reading in a human language +carries one more fallible step than a sentence the physics layer formalizes itself. A verdict is +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 eight the lexicon of every covered language names: + +=========== =================================================================== +AGREED both readers produced the same sentence, and the physics layer solved it +PASSTHROUGH the sentence was already written in the physics language: nothing was translated +SINGLE one reader understood the sentence and the other abstained: the physics layer 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 + physics layer 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 physics layer says it solved something other than the agreed sentence +NONE no reading was even attempted +=========== =================================================================== +""" + +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 physics layer uses. Two is the top of this +# scale, and the physics layer stands on the same rung: what raises a verdict above it would be a +# third kind of witness, and this project has none for physics. +CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0, + "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0} + +# The statuses that answer the question. A refusal, a guard block and an abstention are the layer +# explaining why it will not answer, and they carry no answer text at the level of the stratum: +# the state of the layer is reported, the sentence of the layer is not. +ANSWERING = ("VERIFIED", "SINGLE_PROVER") + + +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]], physics_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 physics_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]], physics_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("physics_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 physics_verdict is not None and physics_verdict.get("referee_mismatch"): + out.append("referee") + if asked and physics_verdict is not None and physics_verdict.get("status") == "UNKNOWN": + out.append("physics_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") + physics_verdict = dossier.get("physics") + direct = dossier.get("reading_direct") + echo_ok = dossier.get("echo_ok") + + state = state_of(readings, comparison, coverage, physics_verdict, direct, echo_ok) + ceiling = CEILING[state] + assurance = 0 + answer_shown = "" + if state in ("AGREED", "SINGLE", "PASSTHROUGH") and physics_verdict is not None: + # The physics layer answers at level two when its readers and its provers agree, at level + # one when a lone prover stands, and at level zero when it abstains or says UNKNOWN. A + # refusal stops the answer at zero too: the layer explained itself, it did not answer. + if physics_verdict.get("status") in ANSWERING: + assurance = min(ceiling, int(physics_verdict.get("assurance", 0) or 0)) + else: + assurance = 0 + answer_shown = physics_verdict.get("answer_text") or "" + if assurance == 0: + answer_shown = "" + reasons = reasons_for(state, readings, comparison, coverage, physics_verdict, + asked=bool(str(dossier.get("sent") or ""))) + return { + "state": state, + "assurance": assurance, + "ceiling": ceiling, + "physics_assurance": int((physics_verdict or {}).get("assurance", 0) or 0), + "physics_status": (physics_verdict or {}).get("status"), + "answer": answer_shown, + "reasons": reasons, + "consulted_physics": physics_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/lgphysstratum/faults.py b/lgphysstratum/faults.py new file mode 100644 index 0000000000000000000000000000000000000000..b10ed902f03f32a19c2f9f7aebf651f1b18f316c --- /dev/null +++ b/lgphysstratum/faults.py @@ -0,0 +1,145 @@ +"""Fault injection for the redundancy experiments (tools/ablation.py). + +A fault is ":". Faults are off unless LGPHYSSTRATUM_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 physics language: a reader that shifts a number, copies the source unit into the +target unit or loses one quantity from a dimensional analysis must produce something the physics +layer will happily answer. Otherwise the fault would be caught by the layer refusing to parse, and +the experiment would measure nothing about the reading layer. + +Catalogue +--------- +reader_a / reader_b : shift_number, same_units, drop_symbol +equivalence : rubber_stamp (declares the two readings equal without running the check) +coverage : rubber_stamp (declares every number kept without counting them) +boundary : tamper_physics (asks the physics layer a different question, reports the + agreed one) +adversary : rubber_stamp (skips its own recomputation of the assurance bound) +arbiter : force_assurance (raises the assurance above what the evidence supports) +""" + +import os +import re +from typing import Any, Dict, Iterable, List, Optional, Set, Tuple + +_ACTIVE: Set[str] = set() +FIRED: List[str] = [] + +READER_FAULTS = ["shift_number", "same_units", "drop_symbol"] + +CATALOG = { + "reader_a": READER_FAULTS, + "reader_b": READER_FAULTS, + "equivalence": ["rubber_stamp"], + "coverage": ["rubber_stamp"], + "boundary": ["tamper_physics"], + "adversary": ["rubber_stamp"], + "arbiter": ["force_assurance"], +} + +_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("LGPHYSSTRATUM_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 slot a joint + is holding and which slots this kind of question can lose without the sentence stopping being a + sentence of the physics language. + """ + 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 == "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 + candidate[owner] = _NUMBER.sub(lambda m: str(_next_number(m.group(0))), + candidate[owner], count=1) + elif kind_fault == "same_units": + if not candidate.get("U") or not candidate.get("V"): + continue + candidate["V"] = candidate["U"] + elif kind_fault == "drop_symbol": + parts = [part.strip() for part in str(candidate.get("S", "")).split(",") if part.strip()] + if len(parts) < 2: + continue + candidate["S"] = ", ".join(parts[1:]) + 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 physics language, leaving it grammatical.""" + if not has(agent, "tamper_physics"): + 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_physics") + return damaged, True diff --git a/lgphysstratum/invoker.py b/lgphysstratum/invoker.py new file mode 100644 index 0000000000000000000000000000000000000000..4f1f91161b92ade7489c44056aaa6915f33a67fd --- /dev/null +++ b/lgphysstratum/invoker.py @@ -0,0 +1,111 @@ +"""The interface toward the physics layer: one subprocess call, no shared code. + +The reading layer and the physics layer are separate topologies of the same orchestrator. This +module is the whole of their coupling: it starts ``tools/ask.py`` of the physics layer 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 physics layer, because a translation layer +that reaches inside the physics it consults is a translation layer that can silently change the +physics. + +Two settings matter, and both are environment variables so no value is hardcoded in a second place: + +``LGPHYSSTRATUM_PHYSICS_ROOT`` the folder of the physics layer (default: ``physics``, sibling of + this bundle, which is ``datasets/physics`` inside the LingoLOGOS + repository) +``LGPHYSSTRATUM_PHYSICS_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 physics session + +The one module that does reach inside the bundle is :mod:`lgphysstratum.compare`, and only to ask +the bundle how it prints its own sentences: the parser is the owner of the language, and a second +account of it in the reading layer would be a third place where a physical sentence could be wrong. +""" + +import json +import os +import subprocess +import sys +from pathlib import Path +from typing import Any, Dict + +ROOT = Path(__file__).resolve().parents[1] +DEFAULT_TIMEOUT = 240 + + +def physics_root() -> Path: + override = os.environ.get("LGPHYSSTRATUM_PHYSICS_ROOT", "").strip() + if override: + return Path(override) + return ROOT.parent / "physics" + + +def backend() -> str: + return (os.environ.get("LGPHYSSTRATUM_PHYSICS_BACKEND", "subprocess") or "subprocess").strip().lower() + + +def timeout_seconds() -> int: + try: + return max(5, int(os.environ.get("LGPHYSSTRATUM_PHYSICS_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_physics": "", "reasons": [], "roads": [], "failures": [], + "detected": []} + + +def ask(sentence: str) -> Dict[str, Any]: + """Ask the physics layer one sentence of the physics language, and return its verdict unchanged.""" + if backend() == "none": + return unavailable("the physics backend is disabled by LGPHYSSTRATUM_PHYSICS_BACKEND") + root = physics_root() + script = root / "tools" / "ask.py" + if not script.is_file(): + return unavailable("no tools/ask.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 physics layer did not answer within %d seconds" % timeout_seconds()) + except OSError as exc: + return unavailable("the physics layer could not be started: %s" % exc) + text = done.stdout.decode("utf-8", "replace") + if done.returncode != 0 and not text.strip(): + return unavailable("the physics layer 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 physics session from the JSON the physics layer printed.""" + try: + parsed = json.loads(text) + except ValueError: + return unavailable("the physics layer 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 physics layer 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")] + status = str(final.get("status") or "UNKNOWN") + return { + "ok": status != "UNKNOWN", + "status": status, + "assurance": int(final.get("assurance", 0) or 0), + "answer": final.get("answer"), + "answer_text": final.get("answer_text") or "", + "problem_physics": final.get("problem") or "", + "reasons": list(final.get("reasons") or []), + "roads": list(final.get("roads") or []), + "failures": list(final.get("failures") or []), + "kind": final.get("kind"), + "delegate": final.get("delegate"), + "detected": list(final.get("detected") or []), + "referee_mismatch": len(mismatched), + "turns": parsed.get("turns"), + "error": None if status != "UNKNOWN" else "; ".join(final.get("reasons") or []) or "unknown", + } diff --git a/lgphysstratum/lexicon.py b/lgphysstratum/lexicon.py new file mode 100644 index 0000000000000000000000000000000000000000..c0df2b081c967bf516179b2ada567f4b95359ecf --- /dev/null +++ b/lgphysstratum/lexicon.py @@ -0,0 +1,453 @@ +"""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 the sentence must carry, in which order). + +On top of the two specs a variety carries ``tokens``: the words of that language that name a unit +or a quantity, each mapped to the token the physics language writes. ``metro`` and ``kilometro`` +are Italian, ``m`` and ``km`` are physics, and this table is the only place where the two meet for +a *word*: the two readers use it and nothing else to decide that a word is mathematics. + +This mirrors the physics topology, where the two readers 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 physics bundle holds the unit tokens it studies. +""" + +import json +import os +import re +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical +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: ``to`` opens the target unit of a conversion, +# ``from`` opens the quantities a dimensional analysis starts from. +MARKERS = ("to", "from") + +# A word run that is not in the lexicon is a coverage failure, unless the physics language itself +# writes it: a unit, a quantity symbol, a keyword of the circuit form. +PHYSICS_WORDS = canonical.PHYSICS_WORDS + +# The characters that say "a single letter here is a symbol of the physics". Digits are not among +# them: Italian "da 0 a 2" puts the single letter a between two numbers, and there it is the joint +# of a conversion, not the acceleration 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. A data file may +# also key a connective by the symbol itself; both spellings reach the same physics token. +CONNECTIVE_TEXT = {"times": "*", "over": "/", "plus": "+", "minus": "-", + "power": "^", "equals": "=", "list": ","} + +_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, ...]]] = {} +_token_cache: Dict[str, Dict[Tuple[str, ...], 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: a verb that can open two forms keeps both of them here. Keeping the whole list 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: two forms announced by one verb are one group. + + 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 physics, 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 physics language. + + The data may key a connective by a mnemonic name (``times``) or by the symbol itself; both are + accepted, because the mnemonic is easier to read in a data file and the symbol is what physics + needs. These are the words that spell an operator: ``forza per tempo`` reaches physics as + ``force*time``. + """ + 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 tokens(lang: str) -> Dict[Tuple[str, ...], str]: + """The words of a variety that name a unit or a quantity, mapped to the physics token.""" + if lang in _token_cache: + return _token_cache[lang] + index: Dict[Tuple[str, ...], str] = {} + for phrase, value in sorted(load(lang).get("tokens", {}).items()): + atoms = phrase_atoms(phrase) + if atoms: + index[atoms] = value + _token_cache[lang] = index + return index + + +def neutral_kinds(lang: str) -> set: + """Kinds whose verb is a request for an answer rather than a claim about the physics. + + A request verb sits in every sentence of the variety, so the reader that carries it steps + aside when another verb announced a kind. + """ + return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")} + + +# The single letters the physics language itself uses, folded to lower case: a bare letter in a +# sentence is a symbol or a unit only when physics knows that letter, and never an unknown that +# happens to look like one. +_SYMBOL_LETTERS = frozenset(letter.lower() for letter in canonical.PHYSICS_SYMBOLS if len(letter) == 1) +_UNIT_LETTERS = frozenset(letter.lower() for letter in canonical.PHYSICS_UNITS if len(letter) == 1) + + +def operand(lang: str, word: str, before: str, after: str) -> bool: + """Whether a single Latin letter touching an operator is a symbol, not the word it spells. + + Italian writes the preposition "a" and Chinese pinyin writes "t" with the same characters a + quantity symbol uses, and a sentence like "bilancia v per t" puts one of those letters exactly + where a symbol 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 physics language, not part of either + reading strategy. The trade is stated in the README -- a one letter symbol next to an operator + always wins -- which is why a joint in the data is chosen to be a word that cannot be a letter. + A letter physics has never heard of (``x``, ``y``, ``b``) is not a symbol here either: the + physics language names its quantities, and an unknown letter is a coverage failure, not a + variable. + """ + if len(word) != 1 or not ("a" <= word <= "z"): + return False + if word not in _SYMBOL_LETTERS and word not in _UNIT_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) +# --------------------------------------------------------------------------- +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 = canonical._SLOT_MARK + + +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 lunghezza d'onda di {T}`` names ``lunghezza``, 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 a symbol of the physics 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, token or noise. + + Verbs, connectives, markers, tokens 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. The order of the registrations is the tie break: a verb beats a connective, a + connective beats a marker, a marker beats a token of the physics language, and every explicit + entry beats a word that only happens to appear inside a written pattern. + """ + 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 atoms, value in tokens(lang).items(): + index[atoms] = ("math", value) + 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 atoms, value in tokens(lang).items(): + out.append((" ".join(atoms), "math", value)) + 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 languages(): + return lang + wanted = fold(lang) + for code in languages(): + if fold(code) == wanted or fold(language_name(code)) == wanted: + return code + return None diff --git a/lgphysstratum/pipeline.py b/lgphysstratum/pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..eadd0c9c02c97ca3898d739c5ee089188ea04228 --- /dev/null +++ b/lgphysstratum/pipeline.py @@ -0,0 +1,118 @@ +"""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 physics layer 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" +BACKEND_VARIABLE = "LGPHYSSTRATUM_PHYSICS_BACKEND" + + +def referee(decls: List[str], asserts: List[str]) -> str: + """Run the referee of the physics layer 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_physics: 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(BACKEND_VARIABLE) + if not call_physics: + os.environ[BACKEND_VARIABLE] = "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_physics: + if previous is None: + os.environ.pop(BACKEND_VARIABLE, None) + else: + os.environ[BACKEND_VARIABLE] = 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, "physics_assurance": 0, "physics_status": None, + "answer": "", "reasons": [reason], "consulted_physics": 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.""" + physics_verdict = dossier.get("physics") or {} + if not physics_verdict.get("problem_physics"): + 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, physics_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/lgphysstratum/protocol.py b/lgphysstratum/protocol.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8a808d46f802f19b0f72b052b8e6c7b85aec43 --- /dev/null +++ b/lgphysstratum/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 physics-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 physics language handed to the physics topology +``physics`` the verdict the physics topology 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/lgphysstratum/read_a.py b/lgphysstratum/read_a.py new file mode 100644 index 0000000000000000000000000000000000000000..40f2d139d5ffc9849c1b7ce49cf96cd7a8423366 --- /dev/null +++ b/lgphysstratum/read_a.py @@ -0,0 +1,322 @@ +"""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 physics 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:`lgphysstratum.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:`lgphysstratum.segment`, just as the two readers of the physics 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 = canonical._SLOT_MARK +_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 symbol of physics, not the 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, symbol, or a lexicon phrase with its role and value. + + One longest match per position decides between verb, connective, marker, token and noise, which + is why a data file must not give one phrase two roles. The unit words of a variety are written + in long and short form side by side, so the longer reading of "kilometers per hour" never + degenerates into the shorter reading of "per" as a division. + """ + 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(atom_in, attached) for atom_in in window) + if key in stripped_index: + hit = (stripped_index[key], window) + break + if hit is not None: + (role, value), window = hit + entry = {"role": role, "value": value, "words": list(window), "surface": " ".join(window)} + if role == "verb": + entry["kinds"] = lexicon.verb_atoms_index(lang).get(window, (value,)) + items.append(entry) + index += len(window) + continue + if len(atom) == 1 and atom in lexicon.noise_chars(lang): + items.append({"role": "noise", "value": "", "words": [word], "surface": atom}) + index += 1 + continue + if word in lexicon.PHYSICS_WORDS: + items.append({"role": "math", "value": word, "words": [word], "surface": atom}) + index += 1 + continue + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom}) + index += 1 + return items + + +def _text(item: Dict[str, Any]) -> str: + """What an item contributes to the text of a slot: a connective prints as its symbol.""" + if item["role"] == "connective": + return " %s " % item["value"] + return item["value"] + + +def _claim(words: List[str], chunk: List[str], attached: List[str]) -> bool: + """Whether a run of word atoms is the same phrase as the next piece of a pattern chunk.""" + if words == chunk: + return True + if not attached or len(words) != len(chunk): + return False + stripped = [lexicon.strip_prefix(word, attached) for word in words] + return stripped == [lexicon.strip_prefix(word, attached) for word in chunk] + + +def _find(chunk: List[str], items: List[Dict[str, Any]], start: int, attached: List[str]): + """Where the words of a pattern chunk sit, at or after a position, or ``None``. + + The chunk of a pattern is a run of function words, and a sentence may put a noise word in the + middle of it -- "converti 3 chilometri all'ora a metri al secondo" splits one chunk around a + unit word that the pattern never names. Only words may sit inside a chunk; mathematics inside + it means the sentence is not the shape the pattern describes, and the pattern has to fail on + that sentence rather than succeed on 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 -- "converti 3 chilometri all'ora metri al secondo" writes + the two units 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 physics 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 physics 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 physics, but physics 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: physics 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: a number, a unit, one equation, a symbol.""" + problems: List[Dict[str, str]] = [] + for name, value in sorted(slots.items()): + if name == "N" and canonical.number(value) is None: + problems.append({"reason": "bad_number", "slot": name}) + if name in ("U", "V") and canonical.unit(value) is None: + problems.append({"reason": "bad_unit", "slot": name}) + if name == "F" and canonical.formula(value) is None: + problems.append({"reason": "bad_formula", "slot": name}) + if name == "T" and canonical.symbol(value) is None: + problems.append({"reason": "bad_symbol", "slot": name}) + if name == "S" and canonical.symbols(value) is None: + problems.append({"reason": "bad_symbol", "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_number", "bad_unit", "bad_formula", "bad_symbol", + "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/lgphysstratum/read_b.py b/lgphysstratum/read_b.py new file mode 100644 index 0000000000000000000000000000000000000000..fa6babadb07b15523875aaf32659529315f0d350 --- /dev/null +++ b/lgphysstratum/read_b.py @@ -0,0 +1,339 @@ +"""Reader B: the frame reader, matching the marker frame of a kind. + +Reader B never looks at the surface patterns of the lexicon. It asks one question instead: does +this sentence carry the markers the frame of a kind asks for, in the order the frame asks for them, +and can the regions those markers open be assigned to the slots of the canonical form in exactly +one way? That is a different computation from the left to right pattern matching of reader A, on +the same lexicon and the same atomiser, which is what makes the two readings of one sentence +evidence about each other rather than one reading copied twice. + +The problem lists of this module are written again, deliberately, instead of imported from +:mod:`lgphysstratum.read_a`: two readers that share the code that checks a slot are one reader. +""" + +from typing import Any, Dict, List, Optional, Tuple + +from . import canonical, lexicon +from .segment import atomize, fold, numeric_literals + +_CONTENT = ("math", "var", "connective") + + +def _matches(window: List[str], phrase: str, attached: List[str]) -> bool: + """Whether a window of atoms spells a lexicon phrase, with or without attached prefixes.""" + folded = fold(phrase) + if window == folded.split(): + return True + if not attached or len(window) != len(phrase.split()): + return False + stripped = [lexicon.strip_prefix(word, attached) for word in window] + return stripped == [lexicon.strip_prefix(word, attached) for word in folded.split()] + + +def find_spans(lang: str, atoms: List[Tuple[str, str]]): + """The positions every lexicon phrase of a variety occupies, longest phrase first. + + Reader B never picks one phrase per position: it enumerates every phrase of the variety and + marks every place it occurs, so two readings of one sentence can overlap and both of them stay + visible to the rest of the reader. Reader A does the opposite, a single longest match per + position, and that difference is why the two of them disagree sometimes. + """ + table = sorted(lexicon.phrase_index(lang).items(), + key=lambda entry: (-len(entry[0]), -len("".join(entry[0])), entry[0])) + attached = lexicon.prefixes(lang) + spans: List[Dict[str, Any]] = [] + covered: Dict[int, int] = {} + for phrase, (role, value) in table: + length = len(phrase) + if not length: + continue + start = 0 + while start + length <= len(atoms): + window = [fold(atoms[start + step][1]) for step in range(length) + if atoms[start + step][0] == "w"] + if len(window) != length or any(atoms[start + step][0] != "w" for step in range(length)): + start += 1 + continue + if any(index in covered for index in range(start, start + length)): + start += 1 + continue + if not _matches(window, " ".join(phrase), attached): + start += 1 + continue + entry = {"start": start, "end": start + length, "role": role, "value": value, + "words": window} + if role == "verb": + entry["kinds"] = lexicon.verb_atoms_index(lang).get(phrase, (value,)) + spans.append(entry) + for index in range(start, start + length): + covered[index] = len(spans) - 1 + start += length + return spans, covered + + +def classify(lang: str, atoms: List[Tuple[str, str]], spans: List[Dict[str, Any]], + covered: Dict[int, int]) -> List[Dict[str, Any]]: + """One entry per phrase: what the lexicon says it is, and why an atom is unknown when it is. + + A phrase of the variety that runs over several atoms -- the Italian phrase for "starting from", + the Chinese phrase for a dimensional analysis -- yields one entry, not one per atom. A joint of a + frame is one joint, and three + entries for one joint would make the frame of a sentence carry three joints the form never + promised, which is a bug of the reader and not a fact of the language. + """ + 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) + if index in covered: + span = spans[covered[index]] + entry = {"role": span["role"], "value": span["value"], "words": span["words"], + "surface": " ".join(span["words"])} + if len(span["words"]) == 1 and span["role"] != "verb": + # The phrase table says the letter is a function word of the variety; the letter + # next to an operator is a symbol of physics. A frame reader that has to put some + # physics into a slot cannot leave the letter out of the slot, and reading it as + # the letter of the operator would be reading a symbol into a sentence twice. + before = _neighbour(atoms, index, -1) + after = _neighbour(atoms, index, 1) + if lexicon.operand(lang, word, before, after): + entry["role"] = "var" + items.append(entry) + index = span["end"] + continue + if len(word) == 1 and word in lexicon.noise_chars(lang): + items.append({"role": "noise", "value": "", "words": [word], "surface": atom}) + index += 1 + continue + if (len(word) == 1 and "a" <= word <= "z" + and (word in lexicon._SYMBOL_LETTERS or word in lexicon._UNIT_LETTERS)): + # A bare letter that the physics language knows: a symbol, not the word it spells. + # A letter physics has never heard of stays unknown, so an equation written with + # unknown letters is a coverage failure and not an invented problem. + items.append({"role": "var", "value": word, "words": [], "surface": atom}) + index += 1 + continue + if word in lexicon.PHYSICS_WORDS: + items.append({"role": "math", "value": word, "words": [word], "surface": atom}) + index += 1 + continue + items.append({"role": "unknown", "value": word, "words": [word], "surface": atom}) + index += 1 + return items + + +def _neighbour(atoms: List[Tuple[str, str]], index: int, step: int) -> str: + """The surface of the adjacent atom when it is mathematics, else the empty string.""" + other = index + step + if 0 <= other < len(atoms) and atoms[other][0] == "m": + return atoms[other][1] + return "" + + +def _text(item: Dict[str, Any]) -> str: + """What an item contributes to the text of a slot: a connective prints as its symbol.""" + if item["role"] == "connective": + return " %s " % item["value"] + return item["value"] + + +def _regions_marked(items: List[Dict[str, Any]]): + """The runs of physics words of a sentence, each tagged with the joint standing before it. + + A joint of the physics 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 Italian + and Chinese front the units ("in metri, converti 3 chilometri") and a reader that filled the + slots by position would put the start unit where the target unit belongs. + + The atoms of a region are joined with a space on purpose. The atomiser cuts the physics words of a + sentence into runs, and one run can be the whole term of an audit while two runs can be the two + ends of one term split by a word that is neither a unit nor a quantity. + 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 _slot_groups(slots: List[str], gaps: List[Optional[str]]) -> List[Tuple[Optional[str], List[str]]]: + """The slots of a form grouped by the joint that introduces them. + + Consecutive slots that no joint separates share one region of the sentence: the conversion form + prints a number and a unit with no word between them, so one region carries both. The group of + one slot is the ordinary case and is what the math stratum had everywhere; the group of two is + what the physics language asks for, and it is the one place where reader B has to look inside a + region rather than take it whole. + """ + groups: List[Tuple[Optional[str], List[str]]] = [] + for position, slot in enumerate(slots): + joint = gaps[position] if position < len(gaps) else None + if joint is None and groups and groups[-1][0] is None: + groups[-1][1].append(slot) + else: + groups.append((joint, [slot])) + return groups + + +def _split_region(text: str, count: int): + """One region broken into exactly as many values as the slots that share it, or ``None``. + + The break is structural: the region is read as the pieces the sentence wrote, and the count has + to come out. A region that offers more or fewer pieces than the form needs is a sentence the + form does not describe -- guessing where the number stops and the unit begins would be reader B + inventing the problem it then reports to the physics topology. + """ + parts = [part for part in text.split() if part] + if len(parts) != count: + return None + return parts + + +def _assign_joints(marked, gaps: List[Optional[str]], slots: List[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 + physics is never a candidate, and every region that does hold physics has to end up in a slot: + physics left over belongs to no slot of the form, so the form does not describe the sentence. + This is also how a joint the physics language puts last is policed -- the region it introduces + is empty, and anything written after it makes the form fail -- and why a frame whose slots + arrive in a rotated order still reads, because no slot is identified by its position in the + sentence. Slots that share one region split it by the pieces it was written with. + """ + 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 joint, group in _slot_groups(slots, gaps): + 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 + text = marked[candidates[0]][1] + if len(group) == 1: + assigned[group[0]] = text + else: + parts = _split_region(text, len(group)) + if parts is None: + return None + assigned.update(dict(zip(group, parts))) + taken.add(candidates[0]) + last = gaps[len(slots)] if len(slots) < len(gaps) else None + 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]]: + """A slot that is not the shape the kind promises. Written again on purpose: see the module note.""" + problems: List[Dict[str, str]] = [] + for name, value in sorted(slots.items()): + if name == "N" and canonical.number(value) is None: + problems.append({"reason": "bad_number", "slot": name}) + if name in ("U", "V") and canonical.unit(value) is None: + problems.append({"reason": "bad_unit", "slot": name}) + if name == "F" and canonical.formula(value) is None: + problems.append({"reason": "bad_formula", "slot": name}) + if name in ("T", "S") and canonical.symbol(value) is None and canonical.symbols(value) is None: + problems.append({"reason": "bad_symbol", "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": "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 + marked = _regions_marked(items) + found: List[Tuple[str, str, Dict[str, str]]] = [] + for kind in candidates: + frame = lexicon.frames(lang).get(kind, {}) + allowed = [tuple(sequence) for sequence in frame.get("sequences", [])] + if tuple(result["markers"]) not in allowed: + result["notes"].append({"reason": "no_frame", "kind": kind, + "detail": " ".join(result["markers"]) or "none"}) + continue + for variant in canonical.VARIANTS[kind]: + gaps = canonical.gap_markers(kind, variant) + if tuple(canonical.marker_sequence(kind, variant)) != tuple(result["markers"]): + continue + slots = canonical.slots_for(kind, variant) + assigned = _assign_joints(marked, gaps, slots) + if assigned is None: + result["notes"].append({"reason": "markers", "kind": kind, + "detail": " ".join(result["markers"]) or "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 = _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_number", "bad_unit", "bad_formula", "bad_symbol", + "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/lgphysstratum/render.py b/lgphysstratum/render.py new file mode 100644 index 0000000000000000000000000000000000000000..e966bb531ad3f6415137c4dff51cb81e20f6aed9 --- /dev/null +++ b/lgphysstratum/render.py @@ -0,0 +1,153 @@ +"""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 physical content -- the canonical sentence the stratum understood and the answer the physics + layer 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 +``pi period from mass, stiffness`` 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("physics") 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 physics 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 physics layer.""" + compare = dossier.get("compare") or {} + physics_verdict = dossier.get("physics") or {} + for source in (dossier.get("sent"), compare.get("left"), physics_verdict.get("problem_physics")): + 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 _physics_why(physics_verdict: Dict[str, Any]) -> str: + """What to say about the physics layer next to its status, in one short phrase. + + An error of this stratum comes first -- the layer was not started, was started and died, was + turned off -- because that is the part this layer knows and the user can act on. When the layer + itself refused or abstained, its own one-line sentence about the refusal is shown. The reason + codes the layer carries are bookkeeping of its internal nodes and are not repeated here. + """ + why = str(physics_verdict.get("error") or physics_verdict.get("reason") or "") + if why: + return why + if str(physics_verdict.get("status") or "") in decide_module.ANSWERING: + return "" + return str(physics_verdict.get("answer_text") or "") + + +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)))) + physics_verdict = dossier.get("physics") or {} + if physics_verdict.get("status"): + # Which road of the physics layer carried the answer is its own bookkeeping and nothing the + # reader of an answer asked for; what belongs in the reply is the verdict and, when the layer + # abstained, the reason it abstained. + tail = str(physics_verdict["status"]) + why = _physics_why(physics_verdict) + if why: + tail += " (" + why + ")" + lines.append("%s: %s" % (labels["physics_layer"], tail)) + reasons = [str(reason) for reason in verdict.get("reasons") or []] + if reasons: + fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])}) + fields.setdefault("physics_unknown", {"detail": _physics_why(physics_verdict)}) + 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/lgphysstratum/segment.py b/lgphysstratum/segment.py new file mode 100644 index 0000000000000000000000000000000000000000..15b1c93ab61c34e6687af1184c1586ca4e410ef0 --- /dev/null +++ b/lgphysstratum/segment.py @@ -0,0 +1,244 @@ +"""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 physics language uses. The mapping from +a word to a role is the lexicon, in ``lexicon/.json`` and :mod:`lgphysstratum.lexicon`. + +Three normalisations happen here, and all three are testable on their own: + +* digit scripts: Arabic-Indic, Extended Arabic-Indic, Devanagari and Bengali 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 the comma of a unit + expression from the comma that ends a clause in a sentence. +""" + +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, the Italian way of writing a unit product + "\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 physics language, square brackets included: the resistor list of a circuit +# problem is the reason they are here, and they must be read as mathematics and not dropped as +# stray punctuation. The semicolon is deliberately absent: inside a natural language sentence it +# separates clauses, and the circuit form is reachable through the direct mode, which reads the +# sentence as written. +MATH_CHARS = set("0123456789+-*/^()[]<>=!|,:.") +CLOSED_CHARS = set("0123456789)]") +OPENING_CHARS = set("0123456789[(") + +# The relation and operator symbols the physics 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'unita`` is the article ``l`` and the noun ``unita``, 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 readers of the physics + 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 physics language open + a mathematics run. An ASCII letter run is returned as a word: :mod:`lgphysstratum.read_a` and + :mod:`lgphysstratum.read_b` decide between a token of the physics language 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. The units and quantities of the physics language are written with their ASCII + spelling, which is why folding is safe for them too. + """ + 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..d0a7e9d30f86c8e56f9a15f3545d065afb71f789 --- /dev/null +++ b/nodes/adversary/grammar.gf @@ -0,0 +1,53 @@ +-- Node adversary (adversary): Adversary: re-derives what the previous nodes asserted and writes the cap on the assurance as an inequality meant to be refuted. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/adversary/ontology.smt2 b/nodes/adversary/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..e5376d707fb42989162d9ebc8e4085b4c6cb8c84 --- /dev/null +++ b/nodes/adversary/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..4c05993966ed474cc94d72b3e8db07dd7b9de5ba --- /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..12b93bbaa8825237a3051f5b4bd81369299ebf50 --- /dev/null +++ b/nodes/arbiter/grammar.gf @@ -0,0 +1,53 @@ +-- Node arbiter (arbiter): Arbiter: applies the decision rule of this stratum, shows at most the minimum of the physics assurance and the ceiling of the reading, and answers in the language of the user. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/arbiter/ontology.smt2 b/nodes/arbiter/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..208ff0b57213323a174bc10cf7b9b6a777aafcf3 --- /dev/null +++ b/nodes/arbiter/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..092f1552eaecb823bcc7d2630a9d2b626081a705 --- /dev/null +++ b/nodes/arbiter/seed_payload.json @@ -0,0 +1,18 @@ +{ + "sender": "arbiter", + "turn": 0, + "volatileState": { + "internalTimeTick": 0 + }, + "payload": { + "naturalLanguage": "question (it): converti 3 chilometri in metri\n@@DOSSIER@@{\"lang\":\"it\",\"question\":\"converti 3 chilometri in metri\"}", + "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..dbdcdb18113e4888cec8f22e696a8900a898822e --- /dev/null +++ b/nodes/boundary/grammar.gf @@ -0,0 +1,53 @@ +-- Node boundary (boundary): Boundary: the only place the verdict of the physics topology enters this stratum; the sentence it echoes is compared here, not trusted. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/boundary/ontology.smt2 b/nodes/boundary/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..6d7df3f6880d4702f8adc01f9287885215849e02 --- /dev/null +++ b/nodes/boundary/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..00ed96277440fbe91a7610aaf5ba35faa3dc3677 --- /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..3e6518848c1545c070250d4a7d1954cffc336e63 --- /dev/null +++ b/nodes/coverage/grammar.gf @@ -0,0 +1,53 @@ +-- Node coverage (coverage): Coverer: lists every number the user wrote and checks that each of the readings kept it. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/coverage/ontology.smt2 b/nodes/coverage/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..70af75cfcc548b727dad96add105a6f94b4df77b --- /dev/null +++ b/nodes/coverage/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..3078e2d4899a6dd496e4097fc428fd79c8ae33e4 --- /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..0bd224fa7200705b21bc07f171df35306c478d42 --- /dev/null +++ b/nodes/equivalence/grammar.gf @@ -0,0 +1,53 @@ +-- Node equivalence (equivalence): Comparator: says whether the two readings name one problem, with the parser of the physics topology as referee and the solver for the numbers. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/equivalence/ontology.smt2 b/nodes/equivalence/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..44ebdd2c55d58d8256c9fe8a45f34dcb404f548a --- /dev/null +++ b/nodes/equivalence/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..87b73d558ee22df439d01bf5b4e7db4435c4e3de --- /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..b0862ca11dd6e5cfed8323134ed4819103269f7d --- /dev/null +++ b/nodes/invoker/grammar.gf @@ -0,0 +1,53 @@ +-- Node invoker (invoker): Invoker: hands the agreed sentence to the physics topology in a separate process and records the verdict it comes back with. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/invoker/ontology.smt2 b/nodes/invoker/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..de73ac6feb06cf9fb3284b01b3ff93c1f2d19d69 --- /dev/null +++ b/nodes/invoker/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..0e2c6a03a07e25d303dcfd1b4e2c875c26d856e2 --- /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..1c0cdce2c18e95e6db6c6a636bb1a3a965a2a19d --- /dev/null +++ b/nodes/reader_a/grammar.gf @@ -0,0 +1,53 @@ +-- Node reader_a (reader_a): First reader: turns a question written in one of the six user languages into a sentence of PhysLang, without seeing the other reader. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/reader_a/ontology.smt2 b/nodes/reader_a/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..2b58b99e52c248cbb8354d95185b072f60cd25ea --- /dev/null +++ b/nodes/reader_a/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..5e681dce1266996d15f2733efec305aca77adca7 --- /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..bbc73a2e726b8fadb8d9e50ac5b5f53f36bcbdc2 --- /dev/null +++ b/nodes/reader_b/grammar.gf @@ -0,0 +1,53 @@ +-- Node reader_b (reader_b): Second reader: recovers the same sentence from the marker phrases sitting in the gaps of the frame, without seeing the first reader. +-- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology. +-- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json. +-- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of +-- the physics topology and is listed here because it is part of the target language, but no variety of this stratum +-- writes it yet, and a question that would need it stays outside the coverage of every lexicon. +-- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. +-- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of +-- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2). +abstract PhysLang = { + cat + Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; + fun + Convert : Qty -> Unit -> Problem ; + Audit : Eq -> Problem ; + Pi : Names -> Names -> Problem ; + Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; + MkQty : Num -> Unit -> Qty ; + Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; + Neg : Side -> Side ; + Q : Unit -> Unit ; + Row : Num -> Num -> Num -> Rows ; + Nil : Rows ; + One : Names ; + And : Names -> Names -> Names ; + MkNum : String -> Num ; + Slash : Num -> Num -> Ratio ; +} + +concrete PhysLangEng of PhysLang = { + lincat + Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; + lin + Convert q u = "convert" ++ q ++ "to" ++ u ; + Audit e = "audit" ++ e ; + Pi t ns = "pi" ++ t ++ "from" ++ ns ; + Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k + ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; + MkQty n u = n ++ u ; + 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 ++ ")" ; + Neg a = "(" ++ "-" ++ a ++ ")" ; + Q u = u ; + Row a b c = "[" ++ a ++ b ++ c ++ "]" ; + Nil = "" ; + One n = n ; + And a b = a ++ "," ++ b ; + MkNum s = s.s ; + Slash n d = n ++ "/" ++ d ; +} diff --git a/nodes/reader_b/ontology.smt2 b/nodes/reader_b/ontology.smt2 new file mode 100644 index 0000000000000000000000000000000000000000..b54d0d7cf41d9d9ff76382f7539a724c6a4a0433 --- /dev/null +++ b/nodes/reader_b/ontology.smt2 @@ -0,0 +1,6 @@ +; SMT-LIB 2 ontology for the physics-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 this +; topology carries are equalities over numerals plus one inequality on the assurance shown, +; 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..f5e7a29cdf31e179e3fd9abeacc3b50eadb9e8c0 --- /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..10f00397381d22ea29fa507acf7d0e4539aa9194 --- /dev/null +++ b/problems/corpus.jsonl @@ -0,0 +1,64 @@ +{"id": "it-01", "lang": "it", "kind": "convert", "question": "converti 3 chilometri in metri", "why": "the plain convert verb with the in joint; both readers reach convert 3 km to m and the physics layer converts it", "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "it-02", "lang": "it", "kind": "convert", "question": "esprimi 5 chilometri all'ora in metri al secondo", "why": "the convert verb esprimi with a two word unit written with an elided apostrophe: the unit is one slot, not two", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "it-03", "lang": "it", "kind": "convert", "question": "riduci 250 centimetri a metri", "why": "riduci is a convert verb of the variety but the pattern with the joint a is only written down by reader B, so one witness stands and the assurance stops at one", "expect": {"state": "SINGLE", "sentence": "convert 250 cm to m", "answer_contains": "5/2 m", "max_assurance": 1, "referee_clean": true}} +{"id": "it-04", "lang": "it", "kind": "audit", "question": "verifica che forza per tempo e uguale a massa per velocita", "why": "audit with the complementiser che and the equality phrase e uguale a; the products of the left hand side carry the same dimensions as the right hand side", "expect": {"state": "AGREED", "sentence": "audit force*time=mass*speed", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "it-05", "lang": "it", "kind": "audit", "question": "bilancia forza per lunghezza uguale a energia", "why": "bilancia, the audit verb of the workshop register, with the bare equality phrase uguale a", "expect": {"state": "AGREED", "sentence": "audit force*length=energy", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "it-06", "lang": "it", "kind": "audit", "question": "controlla che forza per tempo uguale a massa per accelerazione", "why": "a well read sentence of a false physics: the two readers agree on the sentence, and the physics layer refuses it, so the stratum reports the refusal and shows no answer", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-07", "lang": "it", "kind": "pi", "question": "trova il pi del periodo a partire da massa e rigidita", "why": "the pi verb phrase with the multi atom joint a partire da; the comma of the symbol list is written as e in the variety", "expect": {"state": "AGREED", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "min_assurance": 2, "referee_clean": true}} +{"id": "it-08", "lang": "it", "kind": "pi", "question": "analisi dimensionale della velocita a partire da lunghezza e tempo", "why": "the noun phrase analysis with no verb at all: reader A matches the whole phrase as a verb, reader B follows the joint", "expect": {"state": "AGREED", "sentence": "pi speed from length, time", "answer_contains": "speed =", "min_assurance": 2, "referee_clean": true}} +{"id": "it-09", "lang": "it", "kind": "negative", "question": "verifica e converti 3 chilometri in metri", "why": "two announce verbs in one sentence: the question asks two different things and the stratum refuses to choose", "expect": {"state": "AMBIGUOUS", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-10", "lang": "it", "kind": "negative", "question": "bilancia forza e lunghezza uguale a energia", "why": "the connective e also means and, so the formula is read as a list and the physics layer refuses a list where it needs a product: the reading is reported, the answer is not", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-11", "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-12", "lang": "it", "kind": "negative", "question": "converti 3 litri in galloni", "why": "a perfectly grammatical Italian convert sentence whose units are not in the physics fragment this stratum sits on", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "it-13", "lang": "it", "kind": "negative", "question": "converti 3 chilogrammi in metri", "why": "a mass asked as a length: both readers agree on the sentence and the physics layer refuses, so nothing is shown as an answer", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "en-01", "lang": "en", "kind": "convert", "question": "convert 3 kilometers to meters", "why": "the canonical convert verb of the variety with the to joint", "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "en-02", "lang": "en", "kind": "convert", "question": "express 5 kilometers per hour in meters per second", "why": "the convert verb express with the in joint and a compound unit spelled out with per", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "en-03", "lang": "en", "kind": "convert", "question": "change 2 days to hours", "why": "the convert verb change over the two calendar units of the fragment", "expect": {"state": "AGREED", "sentence": "convert 2 day to h", "answer_contains": "48 h", "min_assurance": 2, "referee_clean": true}} +{"id": "en-04", "lang": "en", "kind": "audit", "question": "check that force times time equals mass times speed", "why": "the check that frame with times as the product connective and equals as the equality", "expect": {"state": "AGREED", "sentence": "audit force*time=mass*speed", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "en-05", "lang": "en", "kind": "audit", "question": "verify that force times length equals energy", "why": "the verify that frame over a torque sized statement", "expect": {"state": "AGREED", "sentence": "audit force*length=energy", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "en-06", "lang": "en", "kind": "pi", "question": "find the pi of the period from mass and stiffness", "why": "the pi verb phrase find the pi with the and connective filling the comma of the symbol list", "expect": {"state": "AGREED", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "min_assurance": 2, "referee_clean": true}} +{"id": "en-07", "lang": "en", "kind": "pi", "question": "dimensional analysis of speed from length and time", "why": "the noun phrase dimensional analysis carrying the target before the from joint", "expect": {"state": "AGREED", "sentence": "pi speed from length, time", "answer_contains": "speed =", "min_assurance": 2, "referee_clean": true}} +{"id": "en-08", "lang": "en", "kind": "passthrough", "question": "convert 3 km to m", "why": "the question is already a sentence of the physics language: nothing is translated and nothing is added", "expect": {"state": "PASSTHROUGH", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "en-09", "lang": "en", "kind": "negative", "question": "flibbertigibbet waldo quux", "why": "english gibberish: no verb and no unit, so neither reader may produce a sentence", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "en-10", "lang": "en", "kind": "negative", "question": "convert 3 gallons to litres", "why": "a grammatical convert sentence in units the physics fragment does not carry", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "en-11", "lang": "en", "kind": "negative", "question": "convert 3 kilograms to meters", "why": "mass into length: the reading is certain and the layer refuses, so the assurance falls to zero with it", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "es-01", "lang": "es", "kind": "convert", "question": "convierte 3 kilometros a metros", "why": "the convert verb convierte with the joint a", "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "es-02", "lang": "es", "kind": "convert", "question": "expresa 5 kilometros por hora en metros por segundo", "why": "expressa with the en joint and the compound unit written with por", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "es-03", "lang": "es", "kind": "convert", "question": "pasa 250 centimetros a metros", "why": "pasa, the everyday Spanish convert verb, which the two readers both carry as convert", "expect": {"state": "AGREED", "sentence": "convert 250 cm to m", "answer_contains": "5/2 m", "min_assurance": 2, "referee_clean": true}} +{"id": "es-04", "lang": "es", "kind": "audit", "question": "verifica que fuerza por tiempo es igual a masa por velocidad", "why": "the verifica que frame with por as the product connective, the very connective that also means for", "expect": {"state": "AGREED", "sentence": "audit force*time=mass*speed", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "es-05", "lang": "es", "kind": "audit", "question": "comprueba que fuerza por longitud igual a energia", "why": "comprueba que with the bare equality igual a and no copula", "expect": {"state": "AGREED", "sentence": "audit force*length=energy", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "es-06", "lang": "es", "kind": "pi", "question": "hallar el pi del periodo a partir de masa y rigidez", "why": "the infinitive verb phrase hallar el pi with the two atom joint a partir de: one joint, not two", "expect": {"state": "AGREED", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "min_assurance": 2, "referee_clean": true}} +{"id": "es-07", "lang": "es", "kind": "pi", "question": "el analisis dimensional de la velocidad a partir de longitud y tiempo", "why": "the noun phrase analysis with its article, which reader A matches whole and reader B follows by joint", "expect": {"state": "AGREED", "sentence": "pi speed from length, time", "answer_contains": "speed =", "min_assurance": 2, "referee_clean": true}} +{"id": "es-08", "lang": "es", "kind": "passthrough", "question": "audit ( F * t ) = ( m * v )", "why": "a sentence of the physics language asked in a Spanish session: it passes through untouched", "expect": {"state": "PASSTHROUGH", "sentence": "audit ( F * t ) = ( m * v )", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "es-09", "lang": "es", "kind": "negative", "question": "trambolica pifondo zureta", "why": "spanish shaped gibberish: the word shapes are plausible, none of them is a word", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "es-10", "lang": "es", "kind": "negative", "question": "convierte 3 litros a galones", "why": "a grammatical sentence over units that the physics fragment does not carry", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "es-11", "lang": "es", "kind": "negative", "question": "convierte 3 kilogramos a metros", "why": "the same refusal in Spanish: the reading stands, the physics does not", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "zh-01", "lang": "zh", "kind": "convert", "question": "换算 3 公里 成 米", "why": "the convert verb with the cheng joint; the verb stands before both slots, which is the order the patterns carry", "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-02", "lang": "zh", "kind": "convert", "question": "换算 5 千米每小时 为 米每秒", "why": "the wei joint with the two compound units spelled with mei xiao shi", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-03", "lang": "zh", "kind": "convert", "question": "把 3 公里 换算 为 米", "why": "the ba frame, verb final: reader A knows no pattern for it and reader B rebuilds the sentence from the joint alone, so the answer is given at one witness", "expect": {"state": "SINGLE", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "max_assurance": 1, "referee_clean": true}} +{"id": "zh-04", "lang": "zh", "kind": "audit", "question": "校验 力 乘以 时间 等于 质量 乘以 速度", "why": "the audit verb with yi as the product connective and dengyu as the equality", "expect": {"state": "AGREED", "sentence": "audit force*time=mass*speed", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-05", "lang": "zh", "kind": "audit", "question": "检验 力 乘以 长度 等于 能量", "why": "the second audit verb of the variety over the same statement shape", "expect": {"state": "AGREED", "sentence": "audit force*length=energy", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-06", "lang": "zh", "kind": "pi", "question": "求pi 周期 由 质量 和 刚度", "why": "the pi verb qiu pi written without a space before the word pi, with you as the from joint", "expect": {"state": "AGREED", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-07", "lang": "zh", "kind": "pi", "question": "量纲分析 速度 由 长度 和 时间", "why": "the noun phrase dimensional analysis, no verb at all", "expect": {"state": "AGREED", "sentence": "pi speed from length, time", "answer_contains": "speed =", "min_assurance": 2, "referee_clean": true}} +{"id": "zh-08", "lang": "zh", "kind": "passthrough", "question": "pi period from mass, stiffness", "why": "the physics language asked inside a Chinese session: the stratum translates nothing and says so", "expect": {"state": "PASSTHROUGH", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "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": "换算 3 千克 成 米", "why": "a mass asked as a length in the covered order: the reading is certain, the layer refuses", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "ar-01", "lang": "ar", "kind": "convert", "question": "حول 3 كيلومتر الى متر", "why": "the convert verb with the ila joint, in a sentence the atomizer folds from the arabic script", "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-02", "lang": "ar", "kind": "convert", "question": "غير 5 كيلومتر في الساعة الى متر في الثانية", "why": "the convert verb ghayyir with the compound unit written with fi al sa'a, the article folded away by the prefixes of the lexicon", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-03", "lang": "ar", "kind": "convert", "question": "حول 5 كيلومترات في الساعة الى امتار في الثانية", "why": "the broken plural forms of the two units, which the lexicon carries as the same two tokens", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-04", "lang": "ar", "kind": "audit", "question": "تحقق قوة ضرب زمن يساوي كتلة ضرب سرعة", "why": "the audit verb with darab as the product connective and yusawi as the equality, no complementiser", "expect": {"state": "AGREED", "sentence": "audit force*time=mass*speed", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-05", "lang": "ar", "kind": "audit", "question": "برهن ان قوة ضرب طول يساوي طاقة", "why": "the burhan frame with the complementiser an inside the pattern, so the formula starts after it", "expect": {"state": "AGREED", "sentence": "audit force*length=energy", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-06", "lang": "ar", "kind": "pi", "question": "جد pi زمن الدورة من كتلة و صلابة", "why": "the pi verb phrase jadd pi with the single letter wa as the comma of the symbol list", "expect": {"state": "AGREED", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "min_assurance": 2, "referee_clean": true}} +{"id": "ar-07", "lang": "ar", "kind": "pi", "question": "تحليل الأبعاد السرعة من الطول والزمن", "why": "the noun phrase analysis with the symbols carried inside the definite article: the two readers abstain, and the stratum says not covered instead of guessing the two symbols", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "ar-08", "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-09", "lang": "ar", "kind": "negative", "question": "حول 3 كيلوغرام الى متر", "why": "mass into length: the readers agree, the physics layer refuses, the assurance stops at zero", "expect": {"state": "AGREED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "hi-01", "lang": "hi", "kind": "convert", "question": "बदलो 3 किलोमीटर में मीटर", "why": "the imperative convert verb in front of the slots with the postpositional joint mein", "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "answer_contains": "3000 m", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-02", "lang": "hi", "kind": "convert", "question": "परिवर्तित करो 5 किलोमीटर प्रति घंटा में मीटर प्रति सेकंड", "why": "the two word imperative with the compound units written with prati", "expect": {"state": "AGREED", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-03", "lang": "hi", "kind": "negative", "question": "बदलो 3 किलोमीटर को मीटर में", "why": "the object marker before the goal and the verb phrase written apart: no pattern of the variety reads this order, so the stratum abstains", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}} +{"id": "hi-04", "lang": "hi", "kind": "audit", "question": "सिद्ध करें बल गुणा समय के बराबर द्रव्यमान गुणा वेग", "why": "the prove imperative with guna as the product connective and ke barabar as the equality", "expect": {"state": "AGREED", "sentence": "audit force*time=mass*speed", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-05", "lang": "hi", "kind": "audit", "question": "जांच करें बल गुणा लंबाई बराबर ऊर्जा", "why": "the check imperative with the bare equality barabar and no postposition", "expect": {"state": "AGREED", "sentence": "audit force*length=energy", "answer_contains": "homogeneous", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-06", "lang": "hi", "kind": "pi", "question": "pi ज्ञात करो आवर्तकाल से द्रव्यमान और कठोरता", "why": "the pi verb phrase with the postpositional joint se and the connective aur for the comma", "expect": {"state": "AGREED", "sentence": "pi period from mass, stiffness", "answer_contains": "period =", "min_assurance": 2, "referee_clean": true}} +{"id": "hi-07", "lang": "hi", "kind": "pi", "question": "विमीय विश्लेषण आवृत्ति से आवर्तकाल", "why": "the noun phrase analysis, verbless: reader A asks for a symbol it does not find and abstains, reader B follows the joint se, so one witness answers at one", "expect": {"state": "SINGLE", "sentence": "pi frequency from period", "answer_contains": "frequency =", "max_assurance": 1, "referee_clean": true}} +{"id": "hi-08", "lang": "hi", "kind": "passthrough", "question": "convert 5 km/h to m/s", "why": "an english sentence of the physics language asked in a Hindi session: it passes through with nothing translated", "expect": {"state": "PASSTHROUGH", "sentence": "convert 5 km/h to m/s", "answer_contains": "25/18 m/s", "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": "negative", "question": "बदलो 3 किलोग्राम में मीटर", "why": "mass into length in the covered order: the answer is withheld because the layer refused", "expect": {"state": "AGREED", "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..7e3f00b802fd2b61301bac322530a257cec266f4 --- /dev/null +++ b/results/ablation.json @@ -0,0 +1,2306 @@ +{ + "cells": { + "S1 reader_a | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S1 reader_a | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S1 reader_a | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S2 +reader_b | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S2 +reader_b | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | equivalence:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S3 +equivalence | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | coverage:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | equivalence:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S4 +coverage | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S5 +invoker | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | boundary:tamper_physics": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S6 +boundary | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | adversary:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | boundary:tamper_physics": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S7 +adversary | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | adversary:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | boundary:tamper_physics": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | boundary:tamper_physics,adversary:rubber_stamp,arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | boundary:tamper_physics,arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | equivalence:rubber_stamp,coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:drop_symbol,arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:drop_symbol,reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:same_units,reader_b:same_units": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [ + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "es-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "hi-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "it-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "zh-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "es-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "hi-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "it-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "zh-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 12 + }, + "S8 full topology | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:shift_number,equivalence:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_a:shift_number,reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 full topology | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | boundary:tamper_physics": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus adversary | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | adversary:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | boundary:tamper_physics": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus arbiter | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | adversary:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | coverage:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus boundary | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | adversary:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | boundary:tamper_physics": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | equivalence:rubber_stamp": { + "abstained": 0, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 12, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus coverage | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | adversary:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | boundary:tamper_physics": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | coverage:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus equivalence | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | adversary:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | boundary:tamper_physics": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | coverage:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | equivalence:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus invoker | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | adversary:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | boundary:tamper_physics": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | coverage:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | equivalence:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | reader_b:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | reader_b:same_units": { + "abstained": 4, + "activated": 12, + "caught": 8, + "details": [ + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "es-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "hi-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "it-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "zh-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-02", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-02", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'", + "assurance 1 below 2" + ], + "shown": 1 + } + ], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_a | reader_b:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | adversary:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | arbiter:force_assurance": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | boundary:tamper_physics": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | coverage:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | equivalence:rubber_stamp": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:drop_symbol": { + "abstained": 0, + "activated": 0, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:same_units": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + }, + "S8 minus reader_b | reader_a:shift_number": { + "abstained": 12, + "activated": 12, + "caught": 0, + "details": [], + "lowered": 0, + "masked": 0, + "raised": 0, + "runs": 12, + "silent_error": 0 + } + }, + "probe": [ + "ar-01", + "en-01", + "es-01", + "hi-01", + "it-01", + "zh-01", + "ar-02", + "en-02", + "es-02", + "hi-02", + "it-02", + "zh-02" + ], + "seconds": 3428.9, + "totals": { + "abstained": 1084, + "activated": 1356, + "caught": 8, + "lowered": 0, + "masked": 252, + "raised": 0, + "runs": 1764, + "silent_error": 12 + }, + "violations": [ + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "es-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "hi-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "it-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "zh-01", + "label": "silent_error", + "problems": [ + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "es-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "hi-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "it-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 full topology", + "fault": [ + "reader_a:same_units", + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "zh-02", + "label": "silent_error", + "problems": [ + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'" + ], + "shown": 2 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "es-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "hi-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "it-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "zh-01", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 3 km to km', expected 'convert 3 km to m'", + "answer '3 km = 3 km (L)' does not contain '3000 m'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "ar-02", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'", + "assurance 1 below 2" + ], + "shown": 1 + }, + { + "config": "S8 minus reader_a", + "fault": [ + "reader_b:same_units" + ], + "flagged": false, + "honest": 2, + "id": "en-02", + "label": "caught", + "problems": [ + "state SINGLE, expected AGREED", + "sentence 'convert 5 km/h to km/h', expected 'convert 5 km/h to m/s'", + "answer '5 km/h = 5 km/h (L T^-1)' does not contain '25/18 m/s'", + "assurance 1 below 2" + ], + "shown": 1 + } + ] +} diff --git a/results/coverage.json b/results/coverage.json new file mode 100644 index 0000000000000000000000000000000000000000..73cabe1b601c8d29b59d4e305f55740d5dd4100d --- /dev/null +++ b/results/coverage.json @@ -0,0 +1,959 @@ +{ + "inventory": { + "ar": { + "connectives": 11, + "kinds": [ + "audit", + "convert", + "pi" + ], + "markers": 3, + "noise_words": 11, + "pattern_words": 31, + "patterns": 16, + "verb_phrases": 13 + }, + "en": { + "connectives": 11, + "kinds": [ + "audit", + "convert", + "pi" + ], + "markers": 5, + "noise_words": 12, + "pattern_words": 41, + "patterns": 18, + "verb_phrases": 13 + }, + "es": { + "connectives": 10, + "kinds": [ + "audit", + "convert", + "pi" + ], + "markers": 4, + "noise_words": 21, + "pattern_words": 38, + "patterns": 16, + "verb_phrases": 16 + }, + "hi": { + "connectives": 11, + "kinds": [ + "audit", + "convert", + "pi" + ], + "markers": 2, + "noise_words": 14, + "pattern_words": 36, + "patterns": 14, + "verb_phrases": 13 + }, + "it": { + "connectives": 12, + "kinds": [ + "audit", + "convert", + "pi" + ], + "markers": 5, + "noise_words": 30, + "pattern_words": 52, + "patterns": 20, + "verb_phrases": 18 + }, + "zh": { + "connectives": 9, + "kinds": [ + "audit", + "convert", + "pi" + ], + "markers": 5, + "noise_words": 7, + "pattern_words": 38, + "patterns": 14, + "verb_phrases": 11 + } + }, + "items": 64, + "languages": { + "ar": { + "agreed": 7, + "items": 9, + "not covered": 2, + "reader_a_read": 7, + "reader_b_read": 7 + }, + "en": { + "agreed": 8, + "items": 11, + "not covered": 2, + "passthrough": 1, + "reader_a_read": 8, + "reader_b_read": 8 + }, + "es": { + "agreed": 8, + "items": 11, + "not covered": 2, + "passthrough": 1, + "reader_a_read": 8, + "reader_b_read": 8 + }, + "hi": { + "agreed": 6, + "items": 10, + "not covered": 2, + "passthrough": 1, + "reader_a_read": 6, + "reader_b_read": 7, + "single": 1 + }, + "it": { + "agreed": 9, + "ambiguous": 1, + "items": 13, + "not covered": 2, + "reader_a_read": 9, + "reader_b_read": 10, + "single": 1 + }, + "zh": { + "agreed": 7, + "items": 10, + "not covered": 1, + "passthrough": 1, + "reader_a_read": 7, + "reader_b_read": 8, + "single": 1 + } + }, + "pairs": { + "ar/audit": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "ar/convert": { + "agreed": 3, + "items": 3, + "reader_a_read": 3, + "reader_b_read": 3 + }, + "ar/negative": { + "agreed": 1, + "items": 2, + "not covered": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "ar/pi": { + "agreed": 1, + "items": 2, + "not covered": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/audit": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "en/convert": { + "agreed": 3, + "items": 3, + "reader_a_read": 3, + "reader_b_read": 3 + }, + "en/negative": { + "agreed": 1, + "items": 3, + "not covered": 2, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "en/passthrough": { + "items": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "en/pi": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "es/audit": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "es/convert": { + "agreed": 3, + "items": 3, + "reader_a_read": 3, + "reader_b_read": 3 + }, + "es/negative": { + "agreed": 1, + "items": 3, + "not covered": 2, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "es/passthrough": { + "items": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "es/pi": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "hi/audit": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "hi/convert": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "hi/negative": { + "agreed": 1, + "items": 3, + "not covered": 2, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "hi/passthrough": { + "items": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "hi/pi": { + "agreed": 1, + "items": 2, + "reader_a_read": 1, + "reader_b_read": 2, + "single": 1 + }, + "it/audit": { + "agreed": 3, + "items": 3, + "reader_a_read": 3, + "reader_b_read": 3 + }, + "it/convert": { + "agreed": 2, + "items": 3, + "reader_a_read": 2, + "reader_b_read": 3, + "single": 1 + }, + "it/negative": { + "agreed": 2, + "ambiguous": 1, + "items": 5, + "not covered": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "it/pi": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "zh/audit": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + }, + "zh/convert": { + "agreed": 2, + "items": 3, + "reader_a_read": 2, + "reader_b_read": 3, + "single": 1 + }, + "zh/negative": { + "agreed": 1, + "items": 2, + "not covered": 1, + "reader_a_read": 1, + "reader_b_read": 1 + }, + "zh/passthrough": { + "items": 1, + "passthrough": 1, + "reader_a_read": 0, + "reader_b_read": 0 + }, + "zh/pi": { + "agreed": 2, + "items": 2, + "reader_a_read": 2, + "reader_b_read": 2 + } + }, + "physics_consulted": true, + "rows": [ + { + "assurance": 2, + "id": "it-01", + "kind": "convert", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "it-02", + "kind": "convert", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 1, + "id": "it-03", + "kind": "convert", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "NOT COVERED", + "reader_b": "READ", + "state": "SINGLE" + }, + { + "assurance": 2, + "id": "it-04", + "kind": "audit", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "it-05", + "kind": "audit", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-06", + "kind": "audit", + "lang": "it", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "it-07", + "kind": "pi", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "it-08", + "kind": "pi", + "lang": "it", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-09", + "kind": "negative", + "lang": "it", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "AMBIGUOUS" + }, + { + "assurance": 0, + "id": "it-10", + "kind": "negative", + "lang": "it", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "it-11", + "kind": "negative", + "lang": "it", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "it-12", + "kind": "negative", + "lang": "it", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "it-13", + "kind": "negative", + "lang": "it", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-01", + "kind": "convert", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-02", + "kind": "convert", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-03", + "kind": "convert", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-04", + "kind": "audit", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-05", + "kind": "audit", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-06", + "kind": "pi", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-07", + "kind": "pi", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "en-08", + "kind": "passthrough", + "lang": "en", + "physics_status": "VERIFIED", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "en-09", + "kind": "negative", + "lang": "en", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "en-10", + "kind": "negative", + "lang": "en", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "en-11", + "kind": "negative", + "lang": "en", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-01", + "kind": "convert", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-02", + "kind": "convert", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-03", + "kind": "convert", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-04", + "kind": "audit", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-05", + "kind": "audit", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-06", + "kind": "pi", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-07", + "kind": "pi", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "es-08", + "kind": "passthrough", + "lang": "es", + "physics_status": "VERIFIED", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "es-09", + "kind": "negative", + "lang": "es", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "es-10", + "kind": "negative", + "lang": "es", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "es-11", + "kind": "negative", + "lang": "es", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "zh-01", + "kind": "convert", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "zh-02", + "kind": "convert", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 1, + "id": "zh-03", + "kind": "convert", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "NOT COVERED", + "reader_b": "READ", + "state": "SINGLE" + }, + { + "assurance": 2, + "id": "zh-04", + "kind": "audit", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "zh-05", + "kind": "audit", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "zh-06", + "kind": "pi", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "zh-07", + "kind": "pi", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "zh-08", + "kind": "passthrough", + "lang": "zh", + "physics_status": "VERIFIED", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "zh-09", + "kind": "negative", + "lang": "zh", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "zh-10", + "kind": "negative", + "lang": "zh", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "ar-01", + "kind": "convert", + "lang": "ar", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "ar-02", + "kind": "convert", + "lang": "ar", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "ar-03", + "kind": "convert", + "lang": "ar", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "ar-04", + "kind": "audit", + "lang": "ar", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "ar-05", + "kind": "audit", + "lang": "ar", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "ar-06", + "kind": "pi", + "lang": "ar", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "ar-07", + "kind": "pi", + "lang": "ar", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "ar-08", + "kind": "negative", + "lang": "ar", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "ar-09", + "kind": "negative", + "lang": "ar", + "physics_status": "REFUSED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "hi-01", + "kind": "convert", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "hi-02", + "kind": "convert", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 0, + "id": "hi-03", + "kind": "negative", + "lang": "hi", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 2, + "id": "hi-04", + "kind": "audit", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "hi-05", + "kind": "audit", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 2, + "id": "hi-06", + "kind": "pi", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "READ", + "reader_b": "READ", + "state": "AGREED" + }, + { + "assurance": 1, + "id": "hi-07", + "kind": "pi", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "NOT COVERED", + "reader_b": "READ", + "state": "SINGLE" + }, + { + "assurance": 2, + "id": "hi-08", + "kind": "passthrough", + "lang": "hi", + "physics_status": "VERIFIED", + "reader_a": "NONE", + "reader_b": "NONE", + "state": "PASSTHROUGH" + }, + { + "assurance": 0, + "id": "hi-09", + "kind": "negative", + "lang": "hi", + "physics_status": "UNKNOWN", + "reader_a": "NOT COVERED", + "reader_b": "NOT COVERED", + "state": "NOT COVERED" + }, + { + "assurance": 0, + "id": "hi-10", + "kind": "negative", + "lang": "hi", + "physics_status": "REFUSED", + "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..780c0308ad12266ebb5f2751d76730b59b2557e1 --- /dev/null +++ b/tests/test_corpus.py @@ -0,0 +1,65 @@ +"""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 lgphysstratum 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_physics_layer_understands_is_asked_in_some_language(): + asked = {str(item["kind"]) for item in ITEMS if item.get("expect", {}).get("sentence")} + assert set(canonical.KINDS) <= asked, sorted(set(canonical.KINDS) - asked) + + +def test_every_language_is_also_asked_about_something_it_does_not_cover(): + # A stratum that always answers is a stratum that always guesses: the negative items are what + # keep the abstentions real, in every variety at once. + for lang in lexicon.codes(): + negatives = [item for item in ITEMS if str(item["lang"]) == lang and str(item.get("kind")) == "negative"] + assert negatives, lang + + +def test_the_corpus_keeps_a_record_of_what_it_knows_it_cannot_do(): + # Two kinds of limitation are written into the gold data on purpose: the varieties where only one + # reader gets the word order (SINGLE, one level of assurance), and the questions whose physics is + # out of reach of the physics layer, where the reading is agreed and the answer still does not + # come. + single = [item for item in ITEMS if (item.get("expect") or {}).get("state") == "SINGLE"] + silent = [item for item in ITEMS if (item.get("expect") or {}).get("state") in ("AGREED", "PASSTHROUGH") + and (item.get("expect") or {}).get("no_answer") is True] + assert single, "no item records the limit of one reader only" + assert silent, "no item records a question the physics layer cannot answer" + + +@pytest.mark.parametrize("item_id", IDS) +def test_the_gold_answer_of_this_item_is_met(item_id): + outcome = corpus.outcome(BY_ID[item_id]) + assert outcome["ok"] is True, (item_id, outcome["state"], outcome["assurance"], outcome["problems"]) + + +def test_no_item_ever_reaches_the_level_of_the_physics_layer(): + for item in ITEMS: + expect = item.get("expect") or {} + assert int(expect.get("max_assurance", 0) or 0) <= 2, item["id"] + assert int(expect.get("min_assurance", 0) or 0) <= 2, item["id"] diff --git a/tests/test_decide.py b/tests/test_decide.py new file mode 100644 index 0000000000000000000000000000000000000000..568f8af323935cfb0dc61b10da2f42ec1b26b948 --- /dev/null +++ b/tests/test_decide.py @@ -0,0 +1,179 @@ +"""The decision rule, and the ceiling that the stratum is not allowed to cross.""" + +import copy + +from lgphysstratum import decide, pipeline + + +def _reading(sentence, kind="convert", slots=None, notes=()): + return {"status": "READ", "kind": kind, "math": sentence, "slots": slots or {}, "notes": list(notes)} + + +def _physics(status="VERIFIED", assurance=2, answer="3 km = 3000 m (L)", + sentence="convert 3 km to m", **extra): + verdict = {"status": status, "assurance": assurance, "answer_text": answer, + "problem_physics": sentence} + verdict.update(extra) + return verdict + + +def _dossier(readings, comparison, coverage, physics_verdict, direct=None, echo_ok=True): + dossier = {"question": "converti 3 chilometri in metri", "lang": "it", "sent": "convert 3 km to m", + "reading_a": readings[0] if len(readings) > 0 else {}, + "reading_b": readings[1] if len(readings) > 1 else {}, + "compare": comparison, "coverage": coverage, "physics": physics_verdict, + "echo_ok": echo_ok} + if direct is not None: + dossier["reading_direct"] = direct + return dossier + + +def test_no_state_sits_above_the_top_of_the_physics_layer(): + # The physics layer never shows more than two: its own two provers and its referee stop there, + # there is no third level to reach. So the ceiling of a reading is not one level below the layer, + # as it is for a layer that can reach three -- it is the layer itself, and a reading can only ever + # lower the confidence, never lift it. + assert set(decide.STATES) == set(decide.CEILING) + assert max(decide.CEILING.values()) == 2 + for state in decide.STATES: + assert decide.CEILING[state] <= 2, state + assert max(decide.CEILING[state] for state in ("AGREED", "PASSTHROUGH")) == 2 + for state in ("DISPUTED", "AMBIGUOUS", "NOT COVERED", "TAMPERED", "NONE"): + assert decide.CEILING[state] == 0, state + + +def test_two_agreeing_readers_take_the_minimum_with_the_physics_answer(): + readings = [_reading("convert 3 km to m"), _reading("convert 3 km to m")] + # The physics layer stands at two when both of its roads produced the number and at one when a + # lone prover stands; a stratum that reads the sentence with two witnesses cannot add to that. + for status, assurance, expected in (("VERIFIED", 2, 2), ("SINGLE_PROVER", 1, 1), + ("ABSTAINED", 0, 0), ("UNKNOWN", 0, 0)): + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, + _physics(status, assurance, + "" if assurance == 0 else "3 km = 3000 m (L)"))) + assert final["state"] == "AGREED" + assert final["ceiling"] == 2 + assert final["assurance"] == min(2, assurance), (status, final) + assert final["physics_assurance"] == assurance + + +def test_a_refusal_of_the_layer_is_never_shown_as_an_answer(): + # A dimensionally false statement is a verdict too, and the layer states it: the stratum reports + # the refusal, and the reading that was sure of its sentence does not get to show an answer. The + # reason line is the explanation the layer itself wrote, so no reason key of the stratum is added + # here -- the one below, for a layer that stayed silent, is a different case. + readings = [_reading("convert 3 kg to m"), _reading("convert 3 kg to m")] + verdict = _physics("REFUSED", 0, "", sentence="convert 3 kg to m") + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, verdict)) + assert final["state"] == "AGREED" + assert final["assurance"] == 0 + assert final["answer"] == "" + assert final["physics_status"] == "REFUSED" + + +def test_a_missing_witness_caps_the_session_at_one(): + readings = [_reading("convert 3 km to m"), {}] + final = decide.decide(_dossier(readings, None, None, _physics())) + 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}, _physics())) + 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("convert 4 km to m"), {}] + final = decide.decide(_dossier(readings, None, {"ok": False}, _physics(sentence="convert 4 km to m"))) + 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_physics"] is False + assert final["answer"] == "" + + +def test_a_disagreement_is_never_resolved_by_the_physics_layer(): + readings = [_reading("convert 3 km to m"), _reading("convert 3 km to h")] + final = decide.decide(_dossier(readings, {"same": False, "why": "text"}, {"ok": True}, _physics())) + 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("convert 3 km to m"), _reading("convert 3 km to m")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": False}, _physics())) + 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("convert 3 km to m"), _reading("convert 3 km to m")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, _physics(), echo_ok=False)) + assert final["state"] == "TAMPERED" + assert final["assurance"] == 0 + assert "boundary" in final["reasons"] + + +def test_a_sentence_already_written_in_the_physics_language_passes_through(): + direct = {"kind": "convert", "math": "convert 3 km to m", "slots": {}, "mode": "direct"} + final = decide.decide(_dossier([{}, {}], None, {"ok": True}, _physics(), direct=direct)) + assert final["state"] == "PASSTHROUGH" + assert final["ceiling"] == 2 + assert final["assurance"] == 2 + + +def test_no_answer_is_shown_when_the_physics_layer_did_not_answer(): + readings = [_reading("convert 3 km to m"), _reading("convert 3 km to m")] + final = decide.decide(_dossier(readings, {"same": True}, {"ok": True}, + _physics("UNKNOWN", 0, ""))) + assert final["assurance"] == 0 + assert final["answer"] == "" + assert "physics_unknown" in final["reasons"] + + +def test_the_decision_is_pure_and_leaves_the_evidence_as_it_found_it(): + dossier = _dossier([_reading("convert 3 km to m"), _reading("convert 3 km to m")], {"same": True}, + {"ok": True}, _physics()) + 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("convert 3 km to m"), _reading("convert 3 km to m")], + {"same": True}, {"ok": True}, _physics())) + 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..cdc890dc452cda4b6b8c85f84433e41bd404394f --- /dev/null +++ b/tests/test_faults.py @@ -0,0 +1,115 @@ +"""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 physics. 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 lgphysstratum import agents, canonical, corpus, faults, pipeline + +ITEMS = {item["id"]: item for item in corpus.load()} +ONE = "it-01" + +_FULL_SLOTS = {"convert": {"N": "3", "U": "km", "V": "m"}, + "audit": {"F": "force*time=mass*speed"}, + "pi": {"T": "period", "S": "mass, stiffness"}} + + +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 _slots(kind, order): + return {name: _FULL_SLOTS[kind][name] for name in order if name in _FULL_SLOTS[kind]} + + +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 + # physics layer a question, so there is no shortcut it could take. + assert "invoker" not in faults.CATALOG + faults.configure(()) + for node, kinds in faults.CATALOG.items(): + assert kinds, node + assert len(set(kinds)) == len(kinds), node + for kind in kinds: + assert not faults.has(node, kind), (node, kind) + + +def test_a_fault_configured_is_a_fault_fired_once(): + faults.configure(["reader_a:shift_number", "reader_a:shift_number", "coverage:rubber_stamp"]) + assert faults.has("reader_a", "shift_number") + faults.fire("reader_a", "shift_number") + faults.fire("reader_a", "shift_number") + assert faults.fired("reader_a") == ["reader_a:shift_number"] + # 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:shift_number"] + faults.configure(()) + assert not faults.has("reader_a", "shift_number") + + +def test_the_reader_faults_damage_a_reading_that_carries_them(): + # A convert sentence carries a number and two units, a dimensional analysis carries a list of + # quantities: the three faults of a reader bite on different kinds of question, and each of them + # leaves a sentence the physics layer would happily answer. Otherwise the fault would be caught by + # the layer refusing to parse, and the experiment would measure nothing about the readers. + for fault in faults.CATALOG["reader_a"]: + found = None + for kind in canonical.KINDS: + order = canonical.slots_for(kind) + base = _slots(kind, order) + faults.configure(["reader_a:" + fault]) + changed, was_changed = faults.mutate_reading("reader_a", kind, base, order) + recorded = list(faults.fired("reader_a")) + faults.configure(()) + if was_changed: + found = (kind, base, changed, recorded) + break + assert found is not None, fault + kind, base, changed, recorded = found + assert changed != base, fault + assert recorded == ["reader_a:" + fault], fault + assert canonical.balanced(canonical.print_math(kind, changed)) is True, fault + + +def test_a_reader_that_shifts_a_number_is_found_out_by_the_other_reader(): + honest = _ask(ONE) + shifted = _ask(ONE, ["reader_a:shift_number"]) + assert honest["final"]["assurance"] > 0 + assert shifted["final"]["state"] == "DISPUTED", shifted["final"] + assert shifted["final"]["assurance"] == 0 + assert shifted["final"]["answer"] == "" + assert "disagree" in shifted["final"]["reasons"] or "literal_count" in shifted["final"]["reasons"] + + +def test_a_physics_layer_that_answers_another_sentence_is_reported_as_tampering(): + tampered = _ask(ONE, ["boundary:tamper_physics"]) + 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..c0d1cae5389f8c01f23ed17ace031327abc40561 --- /dev/null +++ b/tests/test_lexicon.py @@ -0,0 +1,148 @@ +"""The data files: six varieties must describe the same stratum, in their own words.""" + +import json +from pathlib import Path + +import pytest + +from lgphysstratum import canonical, compare, 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", "physics_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(): + # The reason keys are the vocabulary of the abstentions: a key without a text in one variety would + # leave that variety answering part of an abstention in the language of the bundle. The keys are + # written out here rather than counted, so a key dropped from a data file shows up as a missing + # translation instead of as a changed number. + expected = { + # what a reader could not do with the words it was given + "unknown_word", "no_verb", "two_verbs", "no_pattern", "no_frame", "multiple", "markers", + "bad_number", "bad_unit", "bad_formula", "bad_symbol", "unbalanced", + # what the checking of the two readings, and the physics layer, found + "disagree", "literal_count", "no_math", "physics_unknown", "referee", "boundary", "other", + } + reference = sorted(lexicon.reason_texts(LANGS[0])) + assert set(reference) == expected, reference + assert len(reference) == len(expected) + for lang in LANGS: + assert sorted(lexicon.reason_texts(lang)) == reference, lang + for key in reference: + assert lexicon.translate_reason(lang, key).strip(), (lang, key) + + +def test_every_variety_covers_the_same_kinds(): + kinds = set(canonical.KINDS) + for lang in LANGS: + assert set(lexicon.patterns(lang)) <= kinds, lang + assert set(lexicon.patterns(lang)), lang + + +def _atoms(text): + """The atoms of a shape, folded the way the two readers fold them when they scan a sentence.""" + return [segment.fold(atom) for _kind, atom in segment.atomize(text)] + + +def _consecutive(needle, hay): + return any(hay[start:start + len(needle)] == needle for start in range(len(hay) - len(needle) + 1)) + + +def test_every_pattern_is_announced_by_a_verb_of_its_own_kind(): + # A shape that promises one operation must carry the word that names it: otherwise a reader + # could match a frame whose operation it never heard announced. The comparison runs over the + # folded atom sequences of the readers, because a written accent or a joined article is not a + # different word, and a verb phrase may span several atoms. + for lang in LANGS: + verbs = lexicon.verbs(lang) + for kind, shapes in lexicon.patterns(lang).items(): + announced = [_atoms(phrase) for phrase, kinds in verbs.items() if kind in kinds] + assert announced, "%s has no verb for %s" % (lang, kind) + for shape in shapes: + atoms = _atoms(shape) + assert any(_consecutive(phrase, atoms) for phrase in announced), "%s %r" % (lang, shape) + + +def test_words_written_inside_a_pattern_are_known_words(): + # The filler of a frame may be a word of the variety -- the Italian frame for a dimensional + # analysis writes the word for analysis 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_every_unit_and_quantity_a_variety_names_fits_a_sentence_of_the_physics_language(): + # A lexicon may only point at a word the physics language can carry: a spelling this fragment + # does not have would make a reader produce a sentence the layer stops on, and the fault would + # look like a coverage gap instead of a mistake in a data file. The check is not made against a + # list kept here, but with the parser of the physics bundle itself, which owns that language: a + # unit is put in a convert sentence, a quantity in a dimensional analysis one. + for lang in LANGS: + for phrase, token in lexicon.tokens(lang).items(): + if token in canonical.PHYSICS_SYMBOLS and token not in canonical.PHYSICS_UNITS: + sentence = "pi %s from mass, time" % token + else: + sentence = "convert 3 %s to m" % token + assert compare.formalize(sentence) is not None, (lang, " ".join(phrase), sentence) + + +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..4d36dc9a9f38f71aaedf96ebfb3c6f5ebe327ff5 --- /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 lgphysstratum 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("physics_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["physics_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..c8d494555b474c1fa2324c665d14b6c908689087 --- /dev/null +++ b/tests/test_pinned_invariant.py @@ -0,0 +1,103 @@ +"""The discipline this bundle is built on: changing the conversational layer changes no physics verdict. + +The physics layer answers in a process of its own, from the sentence the readers agreed on. What this +stratum may add is only a reading and a ceiling. So for one question, whatever the conversational +layer does -- which node speaks, which node abstains, which node misbehaves -- the verdict of the +physics layer has to stay identical, and what is shown to the user has to stay at or below it. +""" + +import copy +import re +from typing import Any, Dict, List, Tuple + +import pytest + +from lgphysstratum 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_physics", "answer", "verdict", "claims", + "referee") +PHYSICS_PACKAGE = re.compile(r"(? Dict[str, Any]: + section = dossier.get("physics") 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_physics"): + continue # that fault is an attack on the physics layer itself, not on this layer + configs.append(("%s commits %s" % (node, kind), agents.ORDER, ("%s:%s" % (node, kind),))) + return configs + + +@pytest.mark.parametrize("item_id", PINS) +@pytest.mark.parametrize("label,active,fault_spec", _configurations()) +def test_the_physics_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 = _physics_of(outcome["dossier"]) + base = _physics_of(honest["dossier"]) + shown = outcome["final"] + if base.get("problem_physics") and asked.get("problem_physics"): + # The physics layer was asked the same question by both sessions: its answer is byte for byte + # the same, whatever the conversational layer did on the way there. + assert asked == base, (item_id, label) + physics_level = int(base.get("assurance", 0) or 0) + assert shown["assurance"] <= min(2, physics_level), (item_id, label, shown) + assert shown["physics_assurance"] == physics_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"] <= 2, (item_id, label) + + +def test_the_sentence_the_physics_layer_was_asked_about_is_the_agreed_one(): + # The echo of the physics layer is written in its own spacing, so what the stratum checks is that + # the echoed sentence carries the reading it was built from: same 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("physics") or {}), item_id + + +def test_the_physics_layer_is_reached_only_as_a_separate_process(): + # Nothing in this bundle may decide the physics: the only door toward the physics layer is the + # invoker, and it launches the question tool of that bundle as a subprocess. One module may + # import the package for its own SMT plumbing, and test_topology holds compare.py to that rule; + # here the modules that route, decide and invoke are the ones checked to hold no reference. + import inspect + from lgphysstratum import decide, invoker + + source = inspect.getsource(invoker) + assert "subprocess" in source + assert not PHYSICS_PACKAGE.search(source) + for module in (agents, pipeline, faults, decide): + assert not PHYSICS_PACKAGE.search(inspect.getsource(module)) diff --git a/tests/test_readers.py b/tests/test_readers.py new file mode 100644 index 0000000000000000000000000000000000000000..751af49fc2f0707fe7eb1ec3cfc3a8c0d02dea38 --- /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 lgphysstratum 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 physics 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 word orders a variety allows but this bundle wrote down in one description only are read by + # one witness: the Italian convert with the joint a, the Chinese ba frame with the verb in front + # of nothing, the Hindi analysis without a verb that reader A insists on. The 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") != (b["status"] == "READ"), (item_id, a["status"], b["status"]) + 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_physics_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..f92a044a1400b57415f42b48422977cc3bd9e61b --- /dev/null +++ b/tests/test_topology.py @@ -0,0 +1,92 @@ +"""Shape of the shipped topology, of the node datasets, and of the sources themselves.""" + +import ast +import json +import re +from pathlib import Path + +import pytest + +from lgphysstratum 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 physics bundle: the stratum never invents a second entry point. +SEED_NODE = "arbiter" +# The package of the physics layer, named as a word so that this bundle's own package name, which +# starts with the same letters, is not mistaken for it. +PHYSICS_PACKAGE = re.compile(r"(? 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. The physics reader faults are the three that a physics + sentence makes possible -- a shifted number, a pair of units that no longer convert, a symbol + that fell out of a formula -- so the pairs below are the same mistakes on both channels.""" + out: List[Tuple[str, ...]] = [ + ("reader_a:same_units", "reader_b:same_units"), + ("reader_a:shift_number", "reader_b:shift_number"), + ("reader_a:drop_symbol", "reader_b:drop_symbol"), + ("equivalence:rubber_stamp", "coverage:rubber_stamp"), + ("boundary:tamper_physics", "arbiter:force_assurance"), + ("reader_a:shift_number", "equivalence:rubber_stamp"), + ("reader_a:drop_symbol", "arbiter:force_assurance"), + ("boundary:tamper_physics", "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 an + 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("%-52s 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..36e924e3053d58440f6452a7f4686ff3f850eee8 --- /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 physics stratum back in that language. + + python tools/ask.py --lang it "converti 3 chilometri in metri" + python tools/ask.py --lang en "check that force times time equals mass times speed" --json + python tools/ask.py --lang ar --corpus problems/corpus.jsonl --limit 6 + +Run from this folder (it is ``datasets/physics-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/physics-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 lgphysstratum 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="lgphysstratum_")) + 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("LGPHYSSTRATUM_FAULTS") + os.environ["LGPHYSSTRATUM_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("LGPHYSSTRATUM_FAULTS", None) + else: + os.environ["LGPHYSSTRATUM_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, "physics_assurance": 0, "physics_status": None, + "answer": "", "reasons": [reason], "consulted_physics": 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, physics assurance %s)" + % (final["assurance"], final.get("ceiling", 0), + final.get("physics_assurance"))) + lines.append("Physics layer status : %s" % (final.get("physics_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("%-10s %-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..91a26a6e10eea792ec388c50fe8afda408a6cb40 --- /dev/null +++ b/tools/coverage_report.py @@ -0,0 +1,118 @@ +#!/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 physics +language) reach it by different routes. The physics layer is not consulted by default: a coverage +report asks what the stratum *understood*, not what the physics layer could prove, and the two +ceilings are reported apart on purpose. Pass ``--physics`` to add the physics verdicts to the same +run. + +Usage: python tools/coverage_report.py [--physics] + python tools/coverage_report.py --out 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 lgphysstratum 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_physics: 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_physics=use_physics) + 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")), + "physics_status": str((result["dossier"].get("physics") 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("--physics", action="store_true", + help="consult the physics layer too, and report its verdicts in the same run") + parser.add_argument("--out", default=str(OUT), help="where to write the JSON report") + args = parser.parse_args(argv) + + items = corpus.load() + rows = [] + for item in items: + row = ask(item, args.physics) + 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), "physics_consulted": bool(args.physics), + "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, physics consulted: %s)" + % (destination, len(items), "yes" if args.physics 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..a2f53611bd4aa748f202bcc473fc3377efe0350e --- /dev/null +++ b/tools/publish_dataset.py @@ -0,0 +1,344 @@ +"""Publish this folder as a dataset on the hub, and check that it arrived. + +Run from inside the folder: + + python tools/publish_dataset.py # token taken from HF_TOKEN + python tools/publish_dataset.py --token-env TOKEN # another environment variable + python tools/publish_dataset.py --plan # build the card, upload nothing + python tools/publish_dataset.py --prune # also drop files the folder no longer holds + +The folder README is the body of the dataset card. It is copied with its section numbers intact, and +five passages are rewritten because they only make sense inside a LingoLOGOS checkout: where the folder +sits, that it needs the sibling `physics` folder, how long the suite took, what the heading of section +10 promises and what that section says about this publication. Every replacement has to match, or the +tool stops: a silent miss would publish a card that contradicts the code next to it. Four sections (11 to +14) are then added for readers who met the bundle on the hub: the fields of the corpus file, how to load +it, rights, and citation. This is where the documentation of the published asset lives, and not in the +technical documentation of the project. + +Nothing here runs during a test, and the token is never a command line argument, only the name of an +environment variable. +""" + +import argparse +import hashlib +import os +import shutil +import sys +import tempfile +from pathlib import Path +from typing import List, Tuple + +ROOT = Path(__file__).resolve().parents[1] +sys.path.insert(0, str(ROOT)) + +from lgphysstratum import corpus # noqa: E402 (after the path fix above) + +REPO = "tailot/physics-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 = 64 +IGNORED_DIRS = {"__pycache__", ".pytest_cache", ".git"} +FRONT_MATTER = """--- +language: + - it + - en + - es + - zh + - hi + - ar +tags: + - multilingual + - physics + - dimensional-analysis + - unit-conversion + - natural-language-to-formal-language + - multi-agent-systems + - benchmark + - conversational-interfaces + - formal-verification + - semantic-parsing +pretty_name: "LingoLOGOS physics-stratum: a question in six written varieties, the answer of the physics 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/physics-stratum`; every command below is written from inside it and needs the\n" + "sibling folder `datasets/physics`, which stays exactly as it is. Only the standard library and\n" + "`z3-solver` are required; the tests need `pytest`.", + "This dataset is the `physics-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 physics layer is not part of this dataset: it\n" + "lives in the `physics` bundle, published at https://huggingface.co/datasets/tailot/lingologos-physics,\n" + "and section 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/physics-stratum. The published snapshot is\n" + "this content: 67 files (plus the card that replaces this README on the hub), 64 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. On the hub this\n" + "README is rewritten as a dataset card whose sections 1 to 10 keep the wording and numbers of this file,\n" + "and sections 11 to 14 are added there for readers who met the bundle on the hub rather than in a\n" + "checkout: the fields of the corpus file, how to load it, rights and citation.", + "This folder is a published snapshot. To work on it as a conversational layer again, clone\n" + "https://huggingface.co/datasets/tailot/lingologos-physics next to it, name the physics copy with\n" + "`LGPHYSSTRATUM_PHYSICS_ROOT`, and run the sessions of section 3; with that variable unset the folder\n" + "looks for a sibling `physics`. Its code is the same as the snapshot published on the hub, which is this\n" + "folder with sections 1 to 10 of its README rewritten in place and sections 11 to 14 appended.", + ), + ( + "physics stratum as subprocesses, and the whole suite took 6 minutes 15 seconds on this checkout.", + "physics stratum as subprocesses, and the suite took 6 minutes 15 seconds on the machine that built this\n" + "snapshot.", + ), + ( + "Like the `physics` folder, this folder is ignored by the git\n" + "repository of the project: what the project carries is the link in the table of published resources at\n" + "the top of the repository README, and the documentation of the asset lives in this README and in the\n" + "card, not in `doc/TECHNICAL_DOCUMENTATION.md`. Republishing is a separate step, never a side effect of a\n" + "test run: `tools/publish_dataset.py` does it with the token taken from an environment variable and\n" + "verifies the tree by sha256.", + "The physics bundle lives at\n" + "https://huggingface.co/datasets/tailot/lingologos-physics, and the project that built both is\n" + "https://github.com/Tailot/LingoLOGOS.", + ), +] + +CARD_TAIL = """ + +## 11. The corpus file + +`problems/corpus.jsonl` holds 64 questions, one JSON object per line, each asking one thing in one of six +written varieties: 13 Italian, 11 English, 11 Spanish, 10 Chinese, 10 Hindi, 9 Arabic. Six of them are +written in characters outside the Latin alphabet, and that is the point of the file: the reading layer is +measured across all six, in both directions. + +| field | meaning | +|---|---| +| `id` | `-`; the prefix names the variety, so rows can be grouped without reading the question | +| `lang` | the ISO code of the variety the person wrote in: `it`, `en`, `es`, `zh`, `hi` or `ar` | +| `kind` | what the row is for: `convert`, `audit`, `pi`, `negative` or `passthrough` | +| `question` | the sentence a person would actually type, between 4 and 69 characters | +| `why` | what the row is meant to show, in English | +| `expect` | what a correct run must produce | + +The kind of a row says what kind of question it is. Note that this corpus is a graded record of what the +reading layer can do, so some rows have no `sentence` to point at: an `audit` row, for instance, is both +a question whose surface this layer covers (the physics stratum then checks the equation and rules on it) +and one whose surface it does not (the readers abstain, the stratum says nothing, and the assurance is 0). + +| kind | rows | what the row tests | +|---|---|---| +| `convert` | 17 | a change of unit: km to m, km/h to m/s, cm to m, days to hours | +| `audit` | 13 | a claim that two products carry the same dimensions, checked or rejected by the physics stratum | +| `pi` | 12 | a dimensional derivation: the dimensions of speed, or the period of a mass on a spring | +| `negative` | 18 | a question that must not be read, or must not be answered: two problems in one sentence, an uncovered surface, a false physics | +| `passthrough` | 4 | the question is already a sentence of the physics language, so nothing is translated | + +The `expect` object, field by field: + +| field | rows | what it pins | +|---|---|---| +| `state` | 64 | the reading outcome: 45 `AGREED`, 11 `NOT COVERED`, 4 `PASSTHROUGH`, 3 `SINGLE`, 1 `AMBIGUOUS` | +| `sentence` | 44 | the physics sentence both readers are expected to write | +| `answer_contains` | 44 | a string the answer of the physics stratum has to contain | +| `min_assurance` | 41 | the assurance floor of the row (all 41 are 2, the ceiling of this layer) | +| `max_assurance` | 23 | the assurance ceiling: 0 on the 20 rows that must not answer, 1 on the 3 single-witness rows | +| `no_answer` | 20 | the row must come back with no answer at all | +| `referee_clean` | 64 | no envelope claim of the session may fall to the referee of its node | + +The 20 rows with no `sentence` are the 18 `negative` rows plus `it-06` and `ar-07`: eleven of the +`negative` rows are not read at all, `it-09` announces two problems in one sentence and is refused, and +seven are read and then refused by the physics stratum -- with `it-06` that makes eight read-and-refused +rows, at assurance 0 and with no answer. The two readers agree exactly on each of them. The 3 +single-witness rows are `it-03`, `zh-03` and `hi-07`, and they answer at assurance 1 because only one +reader reached the sentence and that reader kept every number. + +## 12. Loading it + +```python +from datasets import load_dataset + +corpus = load_dataset("tailot/physics-stratum", "corpus", split="train") +print(len(corpus)) # 64 +print(corpus[0]["question"]) # converti 3 chilometri in metri +print(corpus[0]["expect"]["sentence"]) # convert 3 km to m +``` + +The loader is metadata only, and no test of this bundle needs it: every row can be read with `json.loads` +on one line of `problems/corpus.jsonl`, as `lgphysstratum/corpus.py` does. Every row agrees with what this +folder produces: `python tools/ask.py --corpus problems/corpus.jsonl` runs every question through the +eight nodes and grades it against `expect`, and all 64 of 64 agree. `python tools/coverage_report.py +--physics --out results/coverage.json` gives a reading report on each row without a verdict; the verdicts +are in `results/coverage.json`, the faults in `results/ablation.json`. + +## 13. Rights + +The same rights as the rest of the LingoLOGOS project, of which this folder is one published bundle. The +questions are sentences written for this bundle, not text taken from anywhere; they ask about kilometres, +hours, force, energy and the period of a mass on a spring. The Hindi and Arabic lexicons, like the other +four, were written for this bundle inside the repository, and a reader of either is the right person to +check them before this bundle is used for anything other than a measurement. + +## 14. Citation + +```bibtex +@misc{lingologos_physics_stratum, + title = {LingoLOGOS physics-stratum: a question in six written varieties, the answer of the physics stratum, and an assurance that includes the reading}, + author = {LingoLOGOS}, + year = {2026}, + howpublished = {the folder as it stands, 67 files, code and data together, with this card as the README}, + note = {A conversational layer over the physics topology of the same project: 64 questions, 271 tests. The assurance it shows is the minimum of the assurance of the physics stratum and the ceiling of the reading, so a reading that stands alone or loses a number lowers the confidence and can take the answer away. The bundle carries its fault catalogue and an ablation over every subset of its eight nodes, and reports the one blind spot that experiment found: a unit fault taken by both readers at once.} +} +``` +""" + + +def sha256(path: Path) -> str: + digest = hashlib.sha256() + with path.open("rb") as handle: + for block in iter(lambda: handle.read(1 << 20), b""): + digest.update(block) + return digest.hexdigest() + + +def local_files() -> List[Path]: + """The files this bundle holds: sources, data, results; not caches, not scratch files.""" + 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 == "lgphysstratum"): + continue + out.append(path) + return out + + +def build_card(readme: str) -> str: + """The dataset card: the README of this folder, with the checkout-only passages rewritten in place.""" + card = readme + for here, there in REPLACEMENTS: + if here not in card: + raise SystemExit("the README of this folder no longer holds the passage the card rewrites:\n %s" + % here.splitlines()[0]) + card = card.replace(here, there, 1) + return FRONT_MATTER + card.rstrip() + CARD_TAIL + + +def stage(files: List[Path], card: str) -> Path: + """Copy the tree to a staging folder, with this README replaced by the card under the same name.""" + staging = Path(tempfile.mkdtemp(prefix="physics-stratum-hub-")) + for path in files: + relative = path.relative_to(ROOT) + target = staging / relative + target.parent.mkdir(parents=True, exist_ok=True) + if relative.as_posix() == "README.md": + target.write_text(card, encoding="utf-8") + else: + shutil.copy2(path, target) + return staging + + +def main(argv: List[str] = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("--repo", default=REPO, help="where to publish it") + parser.add_argument("--token-env", default="HF_TOKEN", + help="environment variable holding the write token; never a value on the command line") + parser.add_argument("--plan", action="store_true", help="build the card and report the counts, upload nothing") + parser.add_argument("--prune", action="store_true", + help="also remove from the hub the files that no longer exist in this folder") + args = parser.parse_args(argv) + + files = local_files() + readme = (ROOT / "README.md").read_text(encoding="utf-8") + card = build_card(readme) + rows = corpus.load() + print("files %d, card %d chars, corpus %d rows" % (len(files), len(card), len(rows))) + if len(files) != EXPECTED_FILES: + print("EXPECTED %d FILES, FOUND %d" % (EXPECTED_FILES, len(files))) + if len(rows) != EXPECTED_CORPUS_ROWS: + print("EXPECTED %d CORPUS ROWS, FOUND %d" % (EXPECTED_CORPUS_ROWS, len(rows))) + + if args.plan: + for line in card.splitlines(): + if line.startswith("## ") or line.rstrip().endswith(":"): + print("card | %s" % line) + print("nothing uploaded (--plan)") + return 0 + + token = os.environ.get(args.token_env, "").strip() + if not token: + raise SystemExit("no token: set %s, or pass --token-env NAME, or run --plan" % args.token_env) + + from huggingface_hub import HfApi, create_repo + + api = HfApi(token=token) + create_repo(args.repo, repo_type="dataset", token=token, exist_ok=True) + staging = stage(files, card) + differ = [] + try: + api.upload_folder(repo_id=args.repo, repo_type="dataset", folder_path=str(staging), + commit_message="physics-stratum: the conversational layer over the physics topology") + remote = api.list_repo_files(args.repo, repo_type="dataset") + expected = {str(path.relative_to(ROOT)).replace("\\", "/"): path for path in files} + expected["README.md"] = staging / "README.md" + print("local files %d, hub objects %d" % (len(files), len(remote))) + for name in sorted(set(remote) - set(expected)): + print(" on the hub only: %s" % name) + for name in sorted(set(expected) - set(remote)): + print(" missing on the hub: %s" % name) + for name in sorted(set(expected) & set(remote)): + remote_sha = api.hf_hub_download(repo_id=args.repo, repo_type="dataset", filename=name, + token=token, cache_prompt=False) + if sha256(Path(remote_sha)) != sha256(expected[name]): + print(" differs: %s" % name) + differ.append(name) + print("compared by sha256: %d files, %d differ" % (len(set(expected) & set(remote)), len(differ))) + if args.prune: + expected_names = {str(path.relative_to(ROOT)).replace("\\", "/") for path in files} + extra = sorted(set(remote) - expected_names - {".gitattributes"}) + if extra: + api.delete_files(repo_id=args.repo, repo_type="dataset", delete_patterns=extra, token=token, + 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) + + remote_names = set(remote) + missing = sorted({str(path.relative_to(ROOT)).replace("\\", "/") for path in files} - remote_names) + extra = sorted(remote_names - {str(path.relative_to(ROOT)).replace("\\", "/") for path in files} + - {".gitattributes"}) + 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..46bcdf6ffcf7634f1a3529f720a5fed39e0bc68b --- /dev/null +++ b/topology.json @@ -0,0 +1,98 @@ +{ + "$schema": "https://lingologos.spec/schemas/topology-v1.json", + "sessionId": "lingologos-physics-stratum-01", + "maxTurns": 8, + "terminationCondition": "FIXED_PIPELINE", + "instances": [ + { + "id": "reader_a", + "executable": "physics-stratum/agents/stratum_agent", + "role": "reader_a" + }, + { + "id": "reader_b", + "executable": "physics-stratum/agents/stratum_agent", + "role": "reader_b" + }, + { + "id": "equivalence", + "executable": "physics-stratum/agents/stratum_agent", + "role": "equivalence" + }, + { + "id": "coverage", + "executable": "physics-stratum/agents/stratum_agent", + "role": "coverage" + }, + { + "id": "invoker", + "executable": "physics-stratum/agents/stratum_agent", + "role": "invoker" + }, + { + "id": "boundary", + "executable": "physics-stratum/agents/stratum_agent", + "role": "boundary" + }, + { + "id": "adversary", + "executable": "physics-stratum/agents/stratum_agent", + "role": "adversary" + }, + { + "id": "arbiter", + "executable": "physics-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" + ] + } + ] +}