tailot commited on
Commit
3a0a69b
·
verified ·
1 Parent(s): 3a62839

physics-stratum: the conversational layer over the physics topology

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitignore +3 -0
  2. README.md +402 -0
  3. agents/stratum_agent +39 -0
  4. lexicon/ar.json +131 -0
  5. lexicon/en.json +136 -0
  6. lexicon/es.json +133 -0
  7. lexicon/hi.json +126 -0
  8. lexicon/it.json +141 -0
  9. lexicon/zh.json +122 -0
  10. lgphysstratum/__init__.py +10 -0
  11. lgphysstratum/agents.py +307 -0
  12. lgphysstratum/canonical.py +375 -0
  13. lgphysstratum/compare.py +259 -0
  14. lgphysstratum/corpus.py +90 -0
  15. lgphysstratum/coverage.py +94 -0
  16. lgphysstratum/decide.py +170 -0
  17. lgphysstratum/faults.py +145 -0
  18. lgphysstratum/invoker.py +111 -0
  19. lgphysstratum/lexicon.py +453 -0
  20. lgphysstratum/pipeline.py +118 -0
  21. lgphysstratum/protocol.py +79 -0
  22. lgphysstratum/read_a.py +322 -0
  23. lgphysstratum/read_b.py +339 -0
  24. lgphysstratum/render.py +153 -0
  25. lgphysstratum/segment.py +244 -0
  26. nodes/adversary/grammar.gf +53 -0
  27. nodes/adversary/ontology.smt2 +6 -0
  28. nodes/adversary/seed_payload.json +18 -0
  29. nodes/arbiter/grammar.gf +53 -0
  30. nodes/arbiter/ontology.smt2 +6 -0
  31. nodes/arbiter/seed_payload.json +18 -0
  32. nodes/boundary/grammar.gf +53 -0
  33. nodes/boundary/ontology.smt2 +6 -0
  34. nodes/boundary/seed_payload.json +18 -0
  35. nodes/coverage/grammar.gf +53 -0
  36. nodes/coverage/ontology.smt2 +6 -0
  37. nodes/coverage/seed_payload.json +18 -0
  38. nodes/equivalence/grammar.gf +53 -0
  39. nodes/equivalence/ontology.smt2 +6 -0
  40. nodes/equivalence/seed_payload.json +18 -0
  41. nodes/invoker/grammar.gf +53 -0
  42. nodes/invoker/ontology.smt2 +6 -0
  43. nodes/invoker/seed_payload.json +18 -0
  44. nodes/reader_a/grammar.gf +53 -0
  45. nodes/reader_a/ontology.smt2 +6 -0
  46. nodes/reader_a/seed_payload.json +18 -0
  47. nodes/reader_b/grammar.gf +53 -0
  48. nodes/reader_b/ontology.smt2 +6 -0
  49. nodes/reader_b/seed_payload.json +18 -0
  50. problems/corpus.jsonl +64 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
README.md ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - it
4
+ - en
5
+ - es
6
+ - zh
7
+ - hi
8
+ - ar
9
+ tags:
10
+ - multilingual
11
+ - physics
12
+ - dimensional-analysis
13
+ - unit-conversion
14
+ - natural-language-to-formal-language
15
+ - multi-agent-systems
16
+ - benchmark
17
+ - conversational-interfaces
18
+ - formal-verification
19
+ - semantic-parsing
20
+ pretty_name: "LingoLOGOS physics-stratum: a question in six written varieties, the answer of the physics stratum, and an assurance that includes the reading"
21
+ configs:
22
+ - config_name: corpus
23
+ data_files:
24
+ - split: train
25
+ path: problems/corpus.jsonl
26
+ size_categories:
27
+ - n<1K
28
+ ---
29
+
30
+ # LingoLOGOS physics-stratum topology
31
+
32
+ A conversational layer over the `physics` topology: a person asks in one of six written varieties, and
33
+ gets the verdict of the physics stratum back in that same language, at an assurance that includes the
34
+ fallibility of the reading. The layer never converts a unit, never checks a dimension and never raises
35
+ a verdict; the only direction it can move the assurance of the physics stratum is down.
36
+
37
+ ```
38
+ python tools/ask.py --lang it "converti 3 chilometri in metri"
39
+ Reading state : AGREED
40
+ Assurance shown : 2 (reading ceiling 2, physics assurance 2)
41
+ Physics layer status : VERIFIED
42
+ Orchestrator Z3 check : 8 of 8 envelopes confirmed
43
+
44
+ Answer in the language of the question (Italiano):
45
+ Stato: accordata: due lettori indipendenti piu il vincolo SMT
46
+ Problema capito (convert): convert 3 km to m
47
+ Risposta: 3 km = 3000 m (L)
48
+ livello 2 di 2
49
+ strato fisica: VERIFIED
50
+ Controllo SMT dello strato : 8 di 8 buste confermate
51
+ ```
52
+
53
+ This dataset is the `physics-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,
54
+ code and data together, plus this card in place of their README. Only the standard library and
55
+ `z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every
56
+ command below is written from inside the folder. The physics layer is not part of this dataset: it
57
+ lives in the `physics` bundle, published at https://huggingface.co/datasets/tailot/lingologos-physics,
58
+ and section 10 says how to point this folder at a copy of it.
59
+
60
+ ## 1. What the stratum is, and what it refuses
61
+
62
+ The certainty of a translation cannot be verified the way the certainty of a dimensional check can:
63
+ there is no SMT constraint that says that a sentence of Hindi was read correctly. That is the
64
+ definition this bundle works with, and it is why the topology is built the way it is: two readers that
65
+ reach their sentence by different roads, an SMT claim about what each reading kept, a referee that
66
+ rechecks every envelope, and a decision that is re-derived from the transcript instead of being trusted
67
+ from the arbiter.
68
+
69
+ The rule the whole bundle exists to enforce:
70
+
71
+ ```
72
+ assurance shown = min(assurance of the physics stratum, ceiling of the reading)
73
+ ```
74
+
75
+ | Reading state | ceiling | when |
76
+ |---|---|---|
77
+ | `AGREED` | 2 | both readers produced the same sentence, and the physics stratum is what decides it |
78
+ | `PASSTHROUGH` | 2 | the question was already a sentence of the physics language: nothing was translated |
79
+ | `SINGLE` | 1 | one reader understood it and the other abstained: no witness, one level less |
80
+ | `DISPUTED` | 0 | the two readers produced different sentences, or a reading lost a number: the physics stratum is not even asked |
81
+ | `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 |
82
+ | `NOT COVERED` | 0 | neither reader found anything: this variety does not say it in a covered way |
83
+ | `TAMPERED` | 0 | the physics stratum says it answered something other than the agreed sentence |
84
+
85
+ Three is never shown, and for once that is not a limit of this layer: the physics stratum itself stops
86
+ at two, because its two formalizers and its referee work on a sentence they wrote themselves and there
87
+ is no third road to a number there. A sentence in a human language adds one fallible step before that,
88
+ so here the ceiling of an agreed reading is the level of the layer itself, and a reading can only ever
89
+ lower the confidence -- it has nothing above it to be capped by.
90
+
91
+ The ceiling is not the only thing that holds on its own. The count of literals is checked on a lone
92
+ reading too: a reading that no longer holds the numbers the person wrote is a different problem, not a
93
+ weaker reading of the same one, and it ends `DISPUTED` even when it is the only reader that understood
94
+ the question. A single witness therefore answers at level one only when it kept every number.
95
+
96
+ ## 2. The eight nodes
97
+
98
+ The session runs through the orchestrator (`src/lingologos_orchestrator`) with the same envelope
99
+ protocol as the `physics` topology: a marker `@@DOSSIER@@` inside `payload.naturalLanguage`, and
100
+ `payload.smtConstraints` carrying what each node claims about its own output, which the referee of
101
+ every node recomputes with Z3. The seed sits in the `arbiter`; `maxTurns` is the number of arcs.
102
+
103
+ | Node | What it does | The claim it carries |
104
+ |---|---|---|
105
+ | `reader_a` | reads the question against the frames written in the lexicon | the numerals of the question are still in my sentence |
106
+ | `reader_b` | reads it by following the joints of the physics language | the same, independently |
107
+ | `equivalence` | proves the two sentences the same, slot by slot and then with SMT | `not (A = B)` is unsatisfiable |
108
+ | `coverage` | counts that every literal the person wrote survived into the sentence | conjunction of the element equalities |
109
+ | `invoker` | asks the physics stratum, in a separate process, the agreed sentence | the sentence I sent equals the one that came back |
110
+ | `boundary` | checks the echo of the physics stratum instead of trusting it | elementwise on the echo, or the empty claim |
111
+ | `adversary` | re-derives the bound and writes its negation | `shown > ceiling` is unsatisfiable |
112
+ | `arbiter` | runs the decision and renders the answer in the language of the question | the same inequality |
113
+
114
+ The sentence of the physics language has three shapes in this fragment and two joints, `to` and `from`,
115
+ so the claims are shorter than in the math stratum and the equivalence node works on units, formulas and
116
+ lists of quantities rather than on polynomials.
117
+
118
+ ## 3. Two readers, one lexicon
119
+
120
+ `read_a.py` matches the shapes stored in `lexicon/<lang>.json` (`patterns`: one template per kind of
121
+ problem, with slots). `read_b.py` never looks at those shapes: it finds the verb that announces a
122
+ problem, then walks the joints of the physics language (`to`, `from`, in the words of the variety) and
123
+ cuts the slots out of the gaps between them. They share only the lexicon, the atomizer (`segment.py`)
124
+ and the templates of the physics language (`canonical.py`).
125
+
126
+ That sharing is deliberate and it is also the known blind spot: a wrong description of a variety is a
127
+ wrong description for both readers, and the topology cannot see it. What shows it is the corpus of
128
+ section 5, whose questions were written and checked by a person. When the two readers disagree the
129
+ assurance goes down, never up: `DISPUTED` does not even consult the physics stratum.
130
+
131
+ A phrase of a variety that runs over several atoms -- the Italian phrase for "starting from", the
132
+ Chinese phrase for a dimensional analysis -- is one joint for `reader_b`, not one per atom, because the
133
+ frame of a sentence has as many joints as its shape has gaps.
134
+
135
+ ## 4. Talking to the physics stratum
136
+
137
+ `invoker.py` is the only door. It launches `python <root>/tools/ask.py --json <sentence>` as a separate
138
+ process and reads its JSON verdict back; nothing in this folder imports the physics package to decide
139
+ anything here. One module, `compare.py`, imports it for the SMT plumbing of the equivalence node, and a
140
+ gate in `tests/test_topology.py` pins that exception. The referee then checks the echo: the sentence
141
+ the physics stratum says it answered has to be the sentence the readers agreed on, otherwise the
142
+ session is `TAMPERED`.
143
+
144
+ | Variable | Meaning |
145
+ |---|---|
146
+ | `LGPHYSSTRATUM_PHYSICS_ROOT` | where the `physics` bundle is (default: the sibling folder `datasets/physics`) |
147
+ | `LGPHYSSTRATUM_PHYSICS_BACKEND` | `subprocess` (default), or `none` to disable the physics layer entirely |
148
+ | `LGPHYSSTRATUM_PHYSICS_TIMEOUT` | how long one call of the layer may take (default 240 seconds) |
149
+ | `LGPHYSSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only |
150
+
151
+ What the layer says decides what a person is shown:
152
+
153
+ | Status of the physics stratum | Its assurance | What this stratum shows |
154
+ |---|---|---|
155
+ | `VERIFIED` | 2 | the answer, at the ceiling of the reading |
156
+ | `SINGLE_PROVER` | 1 | the answer, one road produced the number where two were expected |
157
+ | `REFUSED` | 0 | the explanation the layer wrote, and no answer |
158
+ | `GUARD_BLOCKED`, `ABSTAINED`, `UNKNOWN` | 0 | nothing: the reading stands, the assurance is zero |
159
+
160
+ A refusal is a verdict and not a failure: `convert 3 kilograms to meters` is a well read question about
161
+ a dimensionally impossible conversion, the layer says so, and this stratum repeats that it was refused
162
+ without dressing it up as an answer. A disabled physics layer is not tampering either: the reading
163
+ stands, the assurance falls to zero because there is no physics assurance to take the minimum with, and
164
+ no answer is shown.
165
+
166
+ ## 5. The corpus
167
+
168
+ `problems/corpus.jsonl` holds 64 questions: three kinds of problem in 6 varieties, plus items already
169
+ written in the physics language, gibberish, questions in a word order this bundle does not read,
170
+ symbols carried inside an article, units outside the fragment of the layer, and questions whose physics
171
+ the layer refuses. Each line carries what the answer has to look like (`state`, `sentence`,
172
+ `answer_contains`, `min_assurance`, `max_assurance`, `no_answer`, `referee_clean`) and a `why` that says
173
+ why, including the cases where the expected outcome is an abstention. Here `negative` means "nothing may
174
+ be shown at a positive assurance", which covers both a question that cannot be read and a question that
175
+ is read well and refused by the layer.
176
+
177
+ Graded against the in-process pipeline with the physics layer running: **64 of 64** rows agree with
178
+ their gold (`lgphysstratum/corpus.py` grades one row, `tests/test_corpus.py` runs all of them). The
179
+ states come out 45 `AGREED`, 11 `NOT COVERED`, 4 `PASSTHROUGH`, 3 `SINGLE`, 1 `AMBIGUOUS`.
180
+ `tools/coverage_report.py` writes `results/coverage.json` and counts **45** questions read by both
181
+ readers, **3** by `reader_b` alone and **12** by neither, over six lexicons that carry 14 to 20 frames
182
+ and 2 to 5 joints each. Eight rows (`it-06`, `it-10`, `it-13`, `en-11`, `es-11`, `zh-10`, `ar-09`,
183
+ `hi-10`) are agreed readings on which the physics layer refuses: assurance 0 and no answer, which is the
184
+ stratum refusing to add an availability it does not have. Three rows (`it-03`, `zh-03`, `hi-07`) stay at
185
+ `SINGLE`, assurance 1, for the reasons in section 7.
186
+
187
+ ## 6. Commands
188
+
189
+ ```
190
+ python tools/ask.py --lang it "converti 3 chilometri in metri" # one session, eight processes
191
+ python tools/ask.py --lang en --json "convert 3 km to m"
192
+ python tools/ask.py --corpus problems/corpus.jsonl --limit 6
193
+ python tools/coverage_report.py --physics --out results/coverage.json
194
+ python tools/ablation.py --out results/ablation.json # the run shipped under results/
195
+ python tools/ablation.py --probe 6 --out results/ablation.json
196
+ ```
197
+
198
+ `tools/ask.py` prints the verdict it re-derives from the transcript, not the one the arbiter wrote,
199
+ and exits with code 3 when that re-derivation disagrees with a node about its own envelope, with code
200
+ 2 when the assurance is zero, and with code 1 in corpus mode when a gold expectation fails.
201
+ `tools/ablation.py` walks the configurations of the topology
202
+ one node at a time, injects every fault of the catalogue singly and in pairs, and reports each cell as
203
+ `raised | lowered | masked | caught | abstained | silent_error`: a cell counted `raised` is a violation
204
+ of the rule of section 1, and the tool exits 1 if any happened. A `caught` cell is one where an answer
205
+ was shown that the gold does not accept, but the session said so itself -- a claim fell to the referee
206
+ of its node, or the assurance sits below the honest one because the configuration lost a node.
207
+
208
+ On this checkout the default probe -- twelve questions, the two conversions `*-01` and `*-02` of section
209
+ 5 in each of the six varieties -- fills **147** cells and **1764** sessions, the fault takes hold in
210
+ **1356** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 12`, `caught 8`,
211
+ `abstained 1084`, `masked 252` -- 3428.9 seconds, just under an hour. Nothing was ever raised above the
212
+ honest assurance, which is the invariant section 1 states.
213
+
214
+ Twelve sessions are silent errors, and they are one cell: the full topology with **both** readers
215
+ committing `same_units` at the same time, so that each writes the target unit of the question as its
216
+ source unit. The two readings agree, every envelope is confirmed, the numbers the person wrote are all
217
+ still there, and the physics stratum answers the sentence it was sent -- `convert 3 km to km` -- with
218
+ `3 km = 3 km` at assurance 2. No claim of this bundle can see it: the equivalence node compares the two
219
+ readings with each other, the coverage node counts the literals, and the echo checks that the layer
220
+ answered the sentence it was given. That is the blind spot of section 3 in its purest form -- a fault
221
+ common to both readers -- and the bundle reports it rather than hiding it: the units of a reading are
222
+ policed between the readers and by the physics stratum, never against a third authority. The same fault
223
+ taken by one reader only -- in the two configurations that have lost the other reader, 24 sessions --
224
+ never reaches the assurance of the honest run: 8 are answered at assurance 1 with the sentence and the
225
+ answer reported as wrong, and the other 16 withdraw the answer outright.
226
+
227
+ ## 7. Limits that are written down, not hidden
228
+
229
+ * Three word orders are described in one of the two readers only, so those questions stand on one
230
+ witness and stay at `SINGLE`, assurance 1: the Italian conversion with the joint `a` (`riduci 250
231
+ centimetri a metri`, read by `reader_b` only), the Chinese `ba` frame with the verb at the end
232
+ (`read_a` knows no pattern for it), and the Hindi noun phrase analysis with no verb (`reader_a` asks
233
+ for a symbol it does not find). `tools/coverage_report.py` shows them as one of two readers.
234
+ * Hindi also writes the verb last (`badlo 3 kilometron ko mitar mein`), and neither reader was given
235
+ that order: the question is `NOT COVERED` (`hi-03`) rather than guessed.
236
+ * The connective `e` in Italian also means *and*, so `bilancia forza e lunghezza uguale a energia` is
237
+ read as a list of quantities and the layer refuses a list where it needs a product (`it-10`). The
238
+ reading is reported, the answer is not.
239
+ * The physics language is not case free: `v` is the speed and `V` is the volt, `p` is the momentum and
240
+ `P` is the power, the gram is `g` and gravity is `g`. Both readers fold a sentence before they cut its
241
+ slots, so the canonical printer (`canonical.py`) puts the spelling of the physics language back on
242
+ every slot value -- the one place in this stratum where a letter is changed, and a change of spelling
243
+ rather than of content. One letter is genuinely lost on the way: a bare `p` arrives folded from both
244
+ the momentum and the power, and the printer writes the momentum, because that is the form the physics
245
+ language puts in lower case. Writing the word ("power") is how a person keeps the distinction.
246
+ * An Arabic quantity written inside the definite article (`al-tul`, "the length") is not in the
247
+ lexicon: `reader_a` strips what it can and both readers abstain (`ar-07`), so the stratum says `NOT
248
+ COVERED` instead of guessing the two symbols.
249
+ * Units outside the fragment of the physics layer (`litres`, `gallons`) are outside this bundle too
250
+ (`it-12`, `en-10`, `es-10`): the lexicons do not name what the layer cannot carry, so the question is
251
+ not read rather than read into a wrong unit.
252
+ * The physics bundle has a fourth family, the circuits of `potential`. No variety of this bundle asks
253
+ it -- it is in the grammar specifications of the eight nodes and in no lexicon -- so a circuit is
254
+ reachable only through the direct mode, when the person writes the sentence of the physics language
255
+ themselves.
256
+ * The equivalence node compares readings with SMT over their numbers; units and formulas are compared
257
+ slot by slot, which is why a reading that swapped `km` for `kWh` is caught by the slot comparison and
258
+ not by the constraint.
259
+ * The two readers share their data, so a systematic error in the description of a variety is invisible
260
+ to the topology and can only be found in the corpus. The ablation of section 6 shows the extreme case
261
+ of it: the same fault in both readers at once leaves an answer shown at the full assurance of the
262
+ physics stratum, and nothing inside this bundle can contradict it.
263
+
264
+ ## 8. Tests
265
+
266
+ From the repository root:
267
+
268
+ ```
269
+ python -m pytest -q datasets/physics-stratum/tests
270
+ ```
271
+
272
+ The suite is **271** tests: 109 on the two readers against every row of the corpus, 70 on the
273
+ corpus itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 14 on the decision
274
+ table, 11 on the lexicons and 2 end-to-end sessions. It checks the topology file
275
+ against the node order, the shape and the completeness of the lexicons, both readers against the
276
+ corpus, the decision table, the faults, and every gold answer of the corpus;
277
+ `tests/test_pinned_invariant.py` runs the same questions through every node configuration and every
278
+ fault and asserts that the verdict of the physics stratum does not move, and that nothing is ever shown
279
+ above it. `tests/test_orchestrator_e2e.py` runs two real sessions through the orchestrator and is
280
+ skipped when `lingologos_orchestrator` is not importable. The corpus and the invariant tests call the
281
+ physics stratum as subprocesses, and the suite took 6 minutes 15 seconds on the machine that built this
282
+ snapshot.
283
+
284
+ Real sessions, measured: `converti 3 chilometri in metri` comes back `AGREED` at assurance 2 against a
285
+ physics assurance of 2 -- the ceiling of that layer, so the reading cost nothing here -- with **8 of 8**
286
+ envelope claims confirmed by the referee of the session, and `python tools/ask.py --corpus
287
+ problems/corpus.jsonl --limit 6` grades **6 of 6** real sessions against gold. One question per variety
288
+ outside Italian (`zh-01`, `ar-01`, `hi-01`, `en-04`) comes back the same way: `AGREED`, assurance 2, the
289
+ physics layer `VERIFIED`, 8 of 8 claims confirmed, nothing detected -- and the block the person reads is
290
+ written in the language of the question (48, 98 and 99 non-ASCII characters in the Chinese, Arabic and
291
+ Hindi replies).
292
+
293
+ A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that
294
+ `lgphys` may be imported for its SMT plumbing by `lgphysstratum/compare.py` alone.
295
+
296
+ ## 9. Language policy
297
+
298
+ The prose of this folder -- code, docstrings, comments, tool output, test messages -- is English, and
299
+ the Python sources are ASCII, as the repository requires. The exception is the language under study,
300
+ and it is confined to data: `lexicon/*.json` (the words, frames, joints and labels of the six
301
+ varieties), `problems/corpus.jsonl` (the questions and their gold answers), and the answer block that
302
+ `tools/ask.py` shows a person, which is written in the language of the question because that block is
303
+ the object this bundle measures.
304
+
305
+ ## 10. Putting this dataset back into a LingoLOGOS checkout
306
+
307
+ This folder is a published snapshot. To work on it as a conversational layer again, clone
308
+ https://huggingface.co/datasets/tailot/lingologos-physics next to it, name the physics copy with
309
+ `LGPHYSSTRATUM_PHYSICS_ROOT`, and run the sessions of section 3; with that variable unset the folder
310
+ looks for a sibling `physics`. Its code is the same as the snapshot published on the hub, which is this
311
+ folder with sections 1 to 10 of its README rewritten in place and sections 11 to 14 appended. Every file of this folder is
312
+ compared by sha256 after the upload, the card that replaces this README among them: the hub holds one
313
+ object per file of this folder plus `.gitattributes`, so the remote count is one above the number
314
+ `tools/publish_dataset.py` prints here. The physics bundle lives at
315
+ https://huggingface.co/datasets/tailot/lingologos-physics, and the project that built both is
316
+ https://github.com/Tailot/LingoLOGOS.
317
+
318
+ ## 11. The corpus file
319
+
320
+ `problems/corpus.jsonl` holds 64 questions, one JSON object per line, each asking one thing in one of six
321
+ written varieties: 13 Italian, 11 English, 11 Spanish, 10 Chinese, 10 Hindi, 9 Arabic. Six of them are
322
+ written in characters outside the Latin alphabet, and that is the point of the file: the reading layer is
323
+ measured across all six, in both directions.
324
+
325
+ | field | meaning |
326
+ |---|---|
327
+ | `id` | `<variety>-<number>`; the prefix names the variety, so rows can be grouped without reading the question |
328
+ | `lang` | the ISO code of the variety the person wrote in: `it`, `en`, `es`, `zh`, `hi` or `ar` |
329
+ | `kind` | what the row is for: `convert`, `audit`, `pi`, `negative` or `passthrough` |
330
+ | `question` | the sentence a person would actually type, between 4 and 69 characters |
331
+ | `why` | what the row is meant to show, in English |
332
+ | `expect` | what a correct run must produce |
333
+
334
+ The kind of a row says what kind of question it is. Note that this corpus is a graded record of what the
335
+ reading layer can do, so some rows have no `sentence` to point at: an `audit` row, for instance, is both
336
+ a question whose surface this layer covers (the physics stratum then checks the equation and rules on it)
337
+ and one whose surface it does not (the readers abstain, the stratum says nothing, and the assurance is 0).
338
+
339
+ | kind | rows | what the row tests |
340
+ |---|---|---|
341
+ | `convert` | 17 | a change of unit: km to m, km/h to m/s, cm to m, days to hours |
342
+ | `audit` | 13 | a claim that two products carry the same dimensions, checked or rejected by the physics stratum |
343
+ | `pi` | 12 | a dimensional derivation: the dimensions of speed, or the period of a mass on a spring |
344
+ | `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 |
345
+ | `passthrough` | 4 | the question is already a sentence of the physics language, so nothing is translated |
346
+
347
+ The `expect` object, field by field:
348
+
349
+ | field | rows | what it pins |
350
+ |---|---|---|
351
+ | `state` | 64 | the reading outcome: 45 `AGREED`, 11 `NOT COVERED`, 4 `PASSTHROUGH`, 3 `SINGLE`, 1 `AMBIGUOUS` |
352
+ | `sentence` | 44 | the physics sentence both readers are expected to write |
353
+ | `answer_contains` | 44 | a string the answer of the physics stratum has to contain |
354
+ | `min_assurance` | 41 | the assurance floor of the row (all 41 are 2, the ceiling of this layer) |
355
+ | `max_assurance` | 23 | the assurance ceiling: 0 on the 20 rows that must not answer, 1 on the 3 single-witness rows |
356
+ | `no_answer` | 20 | the row must come back with no answer at all |
357
+ | `referee_clean` | 64 | no envelope claim of the session may fall to the referee of its node |
358
+
359
+ The 20 rows with no `sentence` are the 18 `negative` rows plus `it-06` and `ar-07`: eleven of the
360
+ `negative` rows are not read at all, `it-09` announces two problems in one sentence and is refused, and
361
+ seven are read and then refused by the physics stratum -- with `it-06` that makes eight read-and-refused
362
+ rows, at assurance 0 and with no answer. The two readers agree exactly on each of them. The 3
363
+ single-witness rows are `it-03`, `zh-03` and `hi-07`, and they answer at assurance 1 because only one
364
+ reader reached the sentence and that reader kept every number.
365
+
366
+ ## 12. Loading it
367
+
368
+ ```python
369
+ from datasets import load_dataset
370
+
371
+ corpus = load_dataset("tailot/physics-stratum", "corpus", split="train")
372
+ print(len(corpus)) # 64
373
+ print(corpus[0]["question"]) # converti 3 chilometri in metri
374
+ print(corpus[0]["expect"]["sentence"]) # convert 3 km to m
375
+ ```
376
+
377
+ The loader is metadata only, and no test of this bundle needs it: every row can be read with `json.loads`
378
+ on one line of `problems/corpus.jsonl`, as `lgphysstratum/corpus.py` does. Every row agrees with what this
379
+ folder produces: `python tools/ask.py --corpus problems/corpus.jsonl` runs every question through the
380
+ eight nodes and grades it against `expect`, and all 64 of 64 agree. `python tools/coverage_report.py
381
+ --physics --out results/coverage.json` gives a reading report on each row without a verdict; the verdicts
382
+ are in `results/coverage.json`, the faults in `results/ablation.json`.
383
+
384
+ ## 13. Rights
385
+
386
+ The same rights as the rest of the LingoLOGOS project, of which this folder is one published bundle. The
387
+ questions are sentences written for this bundle, not text taken from anywhere; they ask about kilometres,
388
+ hours, force, energy and the period of a mass on a spring. The Hindi and Arabic lexicons, like the other
389
+ four, were written for this bundle inside the repository, and a reader of either is the right person to
390
+ check them before this bundle is used for anything other than a measurement.
391
+
392
+ ## 14. Citation
393
+
394
+ ```bibtex
395
+ @misc{lingologos_physics_stratum,
396
+ title = {LingoLOGOS physics-stratum: a question in six written varieties, the answer of the physics stratum, and an assurance that includes the reading},
397
+ author = {LingoLOGOS},
398
+ year = {2026},
399
+ howpublished = {the folder as it stands, 67 files, code and data together, with this card as the README},
400
+ 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.}
401
+ }
402
+ ```
agents/stratum_agent ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Node executable of the physics-stratum topology.
3
+
4
+ The orchestrator starts this program once per turn, writes the incoming envelope as JSON on
5
+ stdin and reads the outgoing envelope from stdout. The behaviour is selected by --role, which
6
+ the topology sets to the node id (reader_a, reader_b, equivalence, coverage, invoker, boundary,
7
+ adversary or arbiter). Extra arguments added by the orchestrator are accepted and ignored.
8
+
9
+ The node reads and writes the same envelope as the physics topology: the dossier of the session
10
+ travels inside the natural language field between two markers, and the claim the node makes
11
+ about its own envelope travels in smtConstraints, where the referee of the orchestrator reads
12
+ it. Nothing here decides a physical fact: the sentence the readers agree on is handed to the
13
+ physics topology as a separate process and its verdict is carried back untouched.
14
+ """
15
+
16
+ import argparse
17
+ import json
18
+ import os
19
+ import sys
20
+
21
+ sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
22
+
23
+ from lgphysstratum import agents, faults # noqa: E402
24
+
25
+
26
+ def main() -> int:
27
+ parser = argparse.ArgumentParser(description="Physics-stratum topology node")
28
+ parser.add_argument("--role", required=True, choices=sorted(agents.STEPS))
29
+ parser.add_argument("--node-id", default=None)
30
+ args, _ignored = parser.parse_known_args()
31
+ faults.from_env()
32
+ incoming = json.loads(sys.stdin.read())
33
+ outgoing = agents.run_step(args.role, incoming, args.node_id or args.role)
34
+ sys.stdout.write(json.dumps(outgoing))
35
+ return 0
36
+
37
+
38
+ if __name__ == "__main__":
39
+ sys.exit(main())
lexicon/ar.json ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "ar",
3
+ "name": "العربية",
4
+ "script": "arabic",
5
+ "noise_chars": "",
6
+ "prefixes": ["ال", "وال", "بال", "فال", "لل", "و", "ب", "ل", "ف"],
7
+ "kinds": {
8
+ "convert": {
9
+ "verbs": ["حول", "تحويل", "غير"],
10
+ "patterns": [
11
+ "حول {N} {U} الى {V}",
12
+ "تحويل {N} {U} الى {V}",
13
+ "غير {N} {U} الى {V}",
14
+ "الى {V} حول {N} {U}"
15
+ ],
16
+ "frame": {"sequences": [["to"]]}
17
+ },
18
+ "audit": {
19
+ "verbs": ["تحقق", "تأكد", "افحص", "دقق", "برهن"],
20
+ "patterns": [
21
+ "تحقق {F}",
22
+ "تأكد {F}",
23
+ "افحص {F}",
24
+ "دقق {F}",
25
+ "برهن {F}",
26
+ "تحقق ان {F}",
27
+ "برهن ان {F}"
28
+ ],
29
+ "frame": {"sequences": [[]]}
30
+ },
31
+ "pi": {
32
+ "verbs": ["تحليل الأبعاد", "تحليل الابعاد", "جد pi", "احسب pi", "pi"],
33
+ "patterns": [
34
+ "pi {T} من {S}",
35
+ "جد pi {T} من {S}",
36
+ "احسب pi {T} من {S}",
37
+ "تحليل الأبعاد {T} من {S}",
38
+ "تحليل الابعاد {T} من {S}"
39
+ ],
40
+ "frame": {"sequences": [["from"]]}
41
+ }
42
+ },
43
+ "connectives": {
44
+ "times": ["ضرب في", "مضروبة في", "ضرب"],
45
+ "over": ["مقسومة على", "قسمه على"],
46
+ "plus": ["زائد"],
47
+ "minus": ["ناقص"],
48
+ "power": ["مرفوع الى"],
49
+ "equals": ["يساوي", "يعادل"],
50
+ "list": ["و"]
51
+ },
52
+ "markers": {
53
+ "to": ["الى", "إلى"],
54
+ "from": ["من"]
55
+ },
56
+ "tokens": {
57
+ "متر": "m", "امتار": "m",
58
+ "كيلومتر": "km", "كيلومترات": "km",
59
+ "سنتيمتر": "cm", "سنتيمترات": "cm",
60
+ "مليمتر": "mm", "مليمترات": "mm",
61
+ "كيلومتر في الساعة": "km/h", "كيلومترات في الساعة": "km/h",
62
+ "متر في الثانية": "m/s", "امتار في الثانية": "m/s",
63
+ "كيلوغرام": "kg", "كيلوغرامات": "kg", "غرام": "g", "غرامات": "g",
64
+ "ثانية": "s", "ثوان": "s", "ميلي ثانية": "ms",
65
+ "دقيقة": "min", "دقائق": "min", "ساعة": "h", "ساعات": "h",
66
+ "يوم": "day", "ايام": "day",
67
+ "امبير": "A", "كلفن": "K", "مول": "mol", "قنديلة": "cd",
68
+ "نيوتن": "N", "جول": "J", "وات": "W", "كولوم": "C", "فولت": "V",
69
+ "اوم": "ohm", "هرتز": "Hz", "الكترون فولت": "eV",
70
+ "كتلة": "mass", "طول": "length", "زمن": "time", "زمن الدورة": "period",
71
+ "تردد": "frequency", "سرعة": "speed", "تسارع": "acceleration",
72
+ "جاذبية": "gravity", "قوة": "force", "صلابة": "stiffness", "زخم": "momentum",
73
+ "طاقة": "energy", "قدرة": "power", "شحنة": "charge", "تيار": "current",
74
+ "جهد": "voltage", "مقاومة": "resistance", "درجة الحرارة": "temperature",
75
+ "كمية المادة": "amount", "شدة الإضاءة": "luminosity", "ارتفاع": "hgt"
76
+ },
77
+ "noise": ["ما", "ان", "أن", "كم", "هو", "هي", "هذه", "ذلك", "رجاء", "في", "على"],
78
+ "labels": {
79
+ "understood": "المسألة كما فهمناها",
80
+ "status": "الحالة",
81
+ "assurance": "المستوى {n} من 2",
82
+ "answer": "الجواب",
83
+ "reading": "القراءة",
84
+ "physics_layer": "طبقة الفيزياء",
85
+ "notes": "ملاحظات",
86
+ "examples": "جمل تفهمها هذه الطبقة",
87
+ "question": "أعد صياغة السؤال بإحدى هذه الصيغ",
88
+ "check": "فحص SMT للطبقة : {a} من {b} مغلف مؤكد",
89
+ "kind_of": "نوع"
90
+ },
91
+ "reading": {
92
+ "AGREED": "متفق عليها: قارئان مستقلان مع القيد SMT",
93
+ "PASSTHROUGH": "الجملة مكتوبة أصلا بلغة الفيزياء، لم تترجم",
94
+ "DISPUTED": "متنازع عليها: القارئان يقترحان جملتين مختلفتين",
95
+ "NOT COVERED": "خارج ما تغطيه هذه اللغة",
96
+ "AMBIGUOUS": "مبهمة: أكثر من قراءة ممكنة",
97
+ "SINGLE": "قراءة واحدة فقط: القارئ الآخر لم يتعرف على الجملة",
98
+ "TAMPERED": "مُحرفة: النص المسلّم إلى طبقة الفيزياء ليس القراءة المتفق عليها",
99
+ "NONE": "لا قراءة"
100
+ },
101
+ "reasons": {
102
+ "unknown_word": "الكلمة {word} لا تظهر في الجمل المغطاة بالعربية",
103
+ "no_verb": "لا كلمة تعلن نوع المسألة بالعربية",
104
+ "two_verbs": "الجملة تعلن أكثر من نوع من المسائل: {kinds}",
105
+ "no_pattern": "شكل الجملة لا يطابق أي شكل مغطى بالعربية",
106
+ "no_frame": "الروابط لا تطابق أي شكل من النوع {kind}",
107
+ "multiple": "للجملة نفسها قراءتان مختلفتان: {first} و {second}",
108
+ "disagree": "القارئان يقترحان جملتين مختلفتين بلغة الفيزياء",
109
+ "markers": "روابط الجملة ليست هي التي يتوقعها نوع المسألة",
110
+ "bad_number": "{slot} ليس عددا بلغة الفيزياء",
111
+ "bad_unit": "{slot} ليست وحدة مكتوبة برموز لغة الفيزياء",
112
+ "bad_formula": "{slot} ليست معادلة بعلامة تساوي واحدة ورموز معروفة",
113
+ "bad_symbol": "{slot} ليس رمزا لكمية بلغة الفيزياء",
114
+ "unbalanced": "قوس أو قوس مربع غير مغلق",
115
+ "no_math": "الجزء الفيزيائي غير مكتوب برموز لغة الفيزياء",
116
+ "literal_count": "أعداد الجملة ليست هي نفسها عند القارئين",
117
+ "physics_unknown": "طبقة الفيزياء لا تقبل الجملة: {detail}",
118
+ "boundary": "الجملة المسلّمة إلى طبقة الفيزياء ليست القراءة المتفق عليها",
119
+ "referee": "حك SMT لا يؤكد {detail}",
120
+ "other": "لم تصل القراءة إلى جملة بلغة الفيزياء"
121
+ },
122
+ "examples": [
123
+ "حول 3 كيلومتر الى متر",
124
+ "حول 5 كيلومتر في الساعة الى متر في الثانية",
125
+ "الى متر في الثانية حول 5 كيلومتر في الساعة",
126
+ "تحقق قوة ضرب زمن يساوي كتلة ضرب سرعة",
127
+ "برهن قوة ضرب طول يساوي طاقة",
128
+ "جد pi زمن الدورة من كتلة و صلابة",
129
+ "تحليل الابعاد سرعة من طول و زمن"
130
+ ]
131
+ }
lexicon/en.json ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "en",
3
+ "name": "English",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "convert": {
9
+ "verbs": ["convert", "change", "express", "rewrite"],
10
+ "patterns": [
11
+ "convert {N} {U} to {V}",
12
+ "convert {N} {U} into {V}",
13
+ "change {N} {U} to {V}",
14
+ "express {N} {U} in {V}",
15
+ "rewrite {N} {U} in {V}",
16
+ "to {V} convert {N} {U}"
17
+ ],
18
+ "frame": {"sequences": [["to"]]}
19
+ },
20
+ "audit": {
21
+ "verbs": ["audit", "check", "verify", "validate", "test"],
22
+ "patterns": [
23
+ "audit {F}",
24
+ "check {F}",
25
+ "check that {F}",
26
+ "verify that {F}",
27
+ "verify {F}",
28
+ "validate {F}",
29
+ "test that {F}"
30
+ ],
31
+ "frame": {"sequences": [[]]}
32
+ },
33
+ "pi": {
34
+ "verbs": ["find the pi", "compute the pi", "dimensional analysis", "pi"],
35
+ "patterns": [
36
+ "pi {T} from {S}",
37
+ "find the pi {T} from {S}",
38
+ "compute the pi {T} from {S}",
39
+ "dimensional analysis of {T} from {S}",
40
+ "what is the pi {T} from {S}"
41
+ ],
42
+ "frame": {"sequences": [["from"]]}
43
+ }
44
+ },
45
+ "connectives": {
46
+ "times": ["times", "multiplied by"],
47
+ "over": ["divided by", "per"],
48
+ "plus": ["plus", "added to"],
49
+ "minus": ["minus"],
50
+ "power": ["raised to the power of"],
51
+ "equals": ["equals", "is equal to"],
52
+ "list": ["and"]
53
+ },
54
+ "markers": {
55
+ "to": ["to", "into", "in"],
56
+ "from": ["from", "starting from"]
57
+ },
58
+ "tokens": {
59
+ "meter": "m", "meters": "m", "metre": "m", "metres": "m",
60
+ "kilometer": "km", "kilometers": "km", "kilometre": "km", "kilometres": "km",
61
+ "centimeter": "cm", "centimeters": "cm", "centimetre": "cm", "centimetres": "cm",
62
+ "millimeter": "mm", "millimeters": "mm", "millimetre": "mm", "millimetres": "mm",
63
+ "kilometers per hour": "km/h", "kilometres per hour": "km/h",
64
+ "meters per second": "m/s", "metres per second": "m/s",
65
+ "meters squared": "m^2", "metres squared": "m^2",
66
+ "kilogram": "kg", "kilograms": "kg", "gram": "g", "grams": "g",
67
+ "second": "s", "seconds": "s", "millisecond": "ms", "milliseconds": "ms",
68
+ "minute": "min", "minutes": "min", "hour": "h", "hours": "h",
69
+ "day": "day", "days": "day",
70
+ "ampere": "A", "kelvin": "K", "mole": "mol", "candela": "cd",
71
+ "newton": "N", "newtons": "N", "joule": "J", "joules": "J", "watt": "W", "watts": "W",
72
+ "coulomb": "C", "coulombs": "C", "volt": "V", "volts": "V",
73
+ "ohm": "ohm", "ohms": "ohm", "hertz": "Hz", "electronvolt": "eV", "electronvolts": "eV",
74
+ "mass": "mass", "length": "length", "time": "time", "period": "period",
75
+ "frequency": "frequency", "speed": "speed", "velocity": "speed",
76
+ "acceleration": "acceleration", "gravity": "gravity", "force": "force",
77
+ "stiffness": "stiffness", "momentum": "momentum", "energy": "energy",
78
+ "power": "power", "charge": "charge", "current": "current", "voltage": "voltage",
79
+ "resistance": "resistance", "temperature": "temperature", "amount": "amount",
80
+ "luminosity": "luminosity", "height": "hgt"
81
+ },
82
+ "noise": ["the", "a", "an", "that", "what", "is", "of", "it", "this", "how", "much", "for"],
83
+ "labels": {
84
+ "understood": "Problem understood",
85
+ "status": "State",
86
+ "assurance": "level {n} of 2",
87
+ "answer": "Answer",
88
+ "reading": "Reading",
89
+ "physics_layer": "physics layer",
90
+ "notes": "Notes",
91
+ "examples": "Sentences this stratum understands",
92
+ "question": "Ask again in one of these forms",
93
+ "check": "SMT check of the stratum : {a} of {b} envelopes confirmed",
94
+ "kind_of": "kind"
95
+ },
96
+ "reading": {
97
+ "AGREED": "agreed: two independent readers plus the SMT constraint",
98
+ "PASSTHROUGH": "sentence already written in the physics language, not translated",
99
+ "DISPUTED": "disputed: the two readers propose different sentences",
100
+ "NOT COVERED": "outside the coverage of this language",
101
+ "AMBIGUOUS": "ambiguous: more than one reading is possible",
102
+ "TAMPERED": "tampered: the text handed to the physics layer is not the agreed reading",
103
+ "SINGLE": "one reading only: the other reader did not recognise the sentence",
104
+ "NONE": "no reading"
105
+ },
106
+ "reasons": {
107
+ "unknown_word": "the word {word} does not appear in the sentences covered in English",
108
+ "no_verb": "no word announces the kind of problem in English",
109
+ "two_verbs": "the sentence announces more than one kind of problem: {kinds}",
110
+ "no_pattern": "the shape of the sentence matches no shape covered in English",
111
+ "no_frame": "the joints do not match any form of the kind {kind}",
112
+ "multiple": "the same sentence has two different readings: {first} and {second}",
113
+ "disagree": "the two readers propose two different sentences of the physics language",
114
+ "markers": "the joints of the sentence are not the ones the kind of problem expects",
115
+ "bad_number": "{slot} is not a number of the physics language",
116
+ "bad_unit": "{slot} is not a unit written with the symbols of the physics language",
117
+ "bad_formula": "{slot} is not an equation with one equality sign and known symbols",
118
+ "bad_symbol": "{slot} is not a quantity symbol of the physics language",
119
+ "unbalanced": "brackets or square brackets are not closed",
120
+ "no_math": "the physics part is not written with the symbols of the physics language",
121
+ "literal_count": "the numbers of the sentence are not the same in the two readers",
122
+ "physics_unknown": "the physics layer does not accept the sentence: {detail}",
123
+ "boundary": "the sentence handed to the physics layer is not the agreed reading",
124
+ "referee": "the SMT referee does not confirm {detail}",
125
+ "other": "the reading did not reach a sentence of the physics language"
126
+ },
127
+ "examples": [
128
+ "convert 3 kilometers to meters",
129
+ "express 5 kilometers per hour in meters per second",
130
+ "to meters per second convert 5 kilometers per hour",
131
+ "check that force times time equals mass times speed",
132
+ "audit force * length = energy",
133
+ "find the pi of the period from mass and stiffness",
134
+ "the dimensional analysis of speed from length and time"
135
+ ]
136
+ }
lexicon/es.json ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "es",
3
+ "name": "Espanol",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "convert": {
9
+ "verbs": ["convierte", "convertir", "expresa", "expresar", "pasa", "pasar"],
10
+ "patterns": [
11
+ "convierte {N} {U} a {V}",
12
+ "convertir {N} {U} a {V}",
13
+ "expresa {N} {U} en {V}",
14
+ "pasa {N} {U} a {V}",
15
+ "a {V} convierte {N} {U}"
16
+ ],
17
+ "frame": {"sequences": [["to"]]}
18
+ },
19
+ "audit": {
20
+ "verbs": ["audita", "verifica", "comprueba", "valida", "demuestra"],
21
+ "patterns": [
22
+ "audita {F}",
23
+ "verifica {F}",
24
+ "verifica que {F}",
25
+ "comprueba que {F}",
26
+ "demuestra que {F}",
27
+ "valida {F}"
28
+ ],
29
+ "frame": {"sequences": [[]]}
30
+ },
31
+ "pi": {
32
+ "verbs": ["analisis dimensional", "grupo adimensional", "hallar el pi", "calcula el pi", "pi"],
33
+ "patterns": [
34
+ "pi {T} a partir de {S}",
35
+ "hallar el pi {T} a partir de {S}",
36
+ "calcula el pi {T} a partir de {S}",
37
+ "el analisis dimensional {T} a partir de {S}",
38
+ "el grupo adimensional {T} a partir de {S}"
39
+ ],
40
+ "frame": {"sequences": [["from"]]}
41
+ }
42
+ },
43
+ "connectives": {
44
+ "times": ["por", "multiplicado por"],
45
+ "over": ["dividido por", "entre"],
46
+ "plus": ["mas"],
47
+ "minus": ["menos"],
48
+ "power": ["elevado a"],
49
+ "equals": ["igual a", "es igual a"],
50
+ "list": ["y"]
51
+ },
52
+ "markers": {
53
+ "to": ["a", "en"],
54
+ "from": ["a partir de", "partiendo de"]
55
+ },
56
+ "tokens": {
57
+ "metro": "m", "metros": "m",
58
+ "kilometro": "km", "kilometros": "km",
59
+ "centimetro": "cm", "centimetros": "cm",
60
+ "milimetro": "mm", "milimetros": "mm",
61
+ "kilometros por hora": "km/h", "kilometro por hora": "km/h",
62
+ "metros por segundo": "m/s", "metro por segundo": "m/s",
63
+ "kilogramo": "kg", "kilogramos": "kg", "gramo": "g", "gramos": "g",
64
+ "segundo": "s", "segundos": "s", "milisegundo": "ms", "milisegundos": "ms",
65
+ "minuto": "min", "minutos": "min", "hora": "h", "horas": "h",
66
+ "dia": "day", "dias": "day",
67
+ "amperio": "A", "kelvin": "K", "mol": "mol", "candela": "cd",
68
+ "newton": "N", "newtons": "N", "julio": "J", "julios": "J", "vatio": "W", "vatios": "W",
69
+ "coulomb": "C", "coulombs": "C", "voltio": "V", "voltios": "V",
70
+ "ohmio": "ohm", "ohms": "ohm", "hertz": "Hz", "electronvoltio": "eV", "electronvoltios": "eV",
71
+ "masa": "mass", "longitud": "length", "tiempo": "time", "periodo": "period",
72
+ "frecuencia": "frequency", "velocidad": "speed", "rapidez": "speed",
73
+ "aceleracion": "acceleration", "gravedad": "gravity", "fuerza": "force",
74
+ "rigidez": "stiffness", "momento": "momentum", "energia": "energy",
75
+ "potencia": "power", "carga": "charge", "corriente": "current",
76
+ "tension": "voltage", "resistencia": "resistance", "temperatura": "temperature",
77
+ "cantidad": "amount", "luminosidad": "luminosity", "altura": "hgt"
78
+ },
79
+ "noise": ["el", "la", "lo", "los", "las", "un", "una", "unos", "unas", "de", "del", "que", "cual", "cuales", "cuanto", "cuanta", "es", "se", "para", "con", "como"],
80
+ "labels": {
81
+ "understood": "Problema entendido",
82
+ "status": "Estado",
83
+ "assurance": "nivel {n} de 2",
84
+ "answer": "Respuesta",
85
+ "reading": "Lectura",
86
+ "physics_layer": "capa de fisica",
87
+ "notes": "Notas",
88
+ "examples": "Frases que esta capa entiende",
89
+ "question": "Vuelve a preguntar en una de estas formas",
90
+ "check": "Comprobacion SMT de la capa : {a} de {b} sobres confirmados",
91
+ "kind_of": "tipo"
92
+ },
93
+ "reading": {
94
+ "AGREED": "acordada: dos lectores independientes mas la restriccion SMT",
95
+ "PASSTHROUGH": "frase ya escrita en la lengua de la fisica, no traducida",
96
+ "DISPUTED": "en disputa: los dos lectores proponen frases distintas",
97
+ "NOT COVERED": "fuera de la cobertura de esta lengua",
98
+ "AMBIGUOUS": "ambigua: hay mas de una lectura posible",
99
+ "TAMPERED": "manomita: el texto entregado a la capa de fisica no es la lectura acordada",
100
+ "SINGLE": "una sola lectura: el otro lector no reconocio la frase",
101
+ "NONE": "ninguna lectura"
102
+ },
103
+ "reasons": {
104
+ "unknown_word": "la palabra {word} no aparece en las frases cubiertas en espanol",
105
+ "no_verb": "ninguna palabra anuncia el tipo de problema en espanol",
106
+ "two_verbs": "la frase anuncia mas de un tipo de problema: {kinds}",
107
+ "no_pattern": "la forma de la frase no corresponde a ninguna forma cubierta en espanol",
108
+ "no_frame": "los conectores no corresponden a ninguna forma del tipo {kind}",
109
+ "multiple": "la misma frase tiene dos lecturas distintas: {first} y {second}",
110
+ "disagree": "los dos lectores proponen dos frases de la lengua de la fisica distintas",
111
+ "markers": "los conectores de la frase no son los que espera el tipo de problema",
112
+ "bad_number": "{slot} no es un numero de la lengua de la fisica",
113
+ "bad_unit": "{slot} no es una unidad escrita con los simbolos de la lengua de la fisica",
114
+ "bad_formula": "{slot} no es una ecuacion con un solo signo de igualdad y simbolos conocidos",
115
+ "bad_symbol": "{slot} no es un simbolo de cantidad de la lengua de la fisica",
116
+ "unbalanced": "hay parentesis o corchetes sin cerrar",
117
+ "no_math": "la parte de fisica no esta escrita con los simbolos de la lengua de la fisica",
118
+ "literal_count": "los numeros de la frase no son los mismos en los dos lectores",
119
+ "physics_unknown": "la capa de fisica no acepta la frase: {detail}",
120
+ "boundary": "la frase entregada a la capa de fisica no es la lectura acordada",
121
+ "referee": "el arbitro SMT no confirma {detail}",
122
+ "other": "la lectura no llego a una frase de la lengua de la fisica"
123
+ },
124
+ "examples": [
125
+ "convierte 3 kilometros a metros",
126
+ "expresa 5 kilometros por hora en metros por segundo",
127
+ "a metros por segundo convierte 5 kilometros por hora",
128
+ "verifica que fuerza por tiempo es igual a masa por velocidad",
129
+ "audita fuerza por longitud = energia",
130
+ "hallar el pi del periodo a partir de masa y rigidez",
131
+ "el analisis dimensional de la velocidad a partir de longitud y tiempo"
132
+ ]
133
+ }
lexicon/hi.json ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "hi",
3
+ "name": "हिन्दी",
4
+ "script": "devanagari",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "convert": {
9
+ "verbs": ["बदलो", "बदलें", "परिवर्तित करो", "रूपांतरित करो"],
10
+ "patterns": [
11
+ "बदलो {N} {U} में {V}",
12
+ "बदलें {N} {U} में {V}",
13
+ "परिवर्तित करो {N} {U} में {V}",
14
+ "रूपांतरित करो {N} {U} में {V}"
15
+ ],
16
+ "frame": {"sequences": [["to"]]}
17
+ },
18
+ "audit": {
19
+ "verbs": ["सिद्ध करें", "सिद्ध", "सत्यापित करें", "जांच करें", "दिखाएँ"],
20
+ "patterns": [
21
+ "सिद्ध करें {F}",
22
+ "{F} सिद्ध करें",
23
+ "सत्यापित करें {F}",
24
+ "जांच करें {F}",
25
+ "दिखाएँ {F}",
26
+ "सिद्ध करें कि {F}"
27
+ ],
28
+ "frame": {"sequences": [[]]}
29
+ },
30
+ "pi": {
31
+ "verbs": ["विमीय विश्लेषण", "pi ज्ञात करो", "pi की गणना करो", "pi"],
32
+ "patterns": [
33
+ "pi {T} से {S}",
34
+ "pi ज्ञात करो {T} से {S}",
35
+ "pi की गणना करो {T} से {S}",
36
+ "विमीय विश्लेषण {T} से {S}"
37
+ ],
38
+ "frame": {"sequences": [["from"]]}
39
+ }
40
+ },
41
+ "connectives": {
42
+ "times": ["गुणा", "का गुणा"],
43
+ "over": ["भाग", "का भाग"],
44
+ "plus": ["जोड़"],
45
+ "minus": ["ऋण"],
46
+ "power": ["का घात"],
47
+ "equals": ["के बराबर", "बराबर"],
48
+ "list": ["और", "तथा"]
49
+ },
50
+ "markers": {
51
+ "to": ["में"],
52
+ "from": ["से"]
53
+ },
54
+ "tokens": {
55
+ "मीटर": "m", "मीटरों": "m",
56
+ "किलोमीटर": "km", "किलोमीटरों": "km",
57
+ "सेंटीमीटर": "cm", "मिलीमीटर": "mm",
58
+ "किलोमीटर प्रति घंटा": "km/h", "मीटर प्रति सेकंड": "m/s",
59
+ "किलोग्राम": "kg", "किलोग्रामों": "kg", "ग्राम": "g", "ग्रामों": "g",
60
+ "सेकंड": "s", "सेकंडों": "s", "मिलिसेकंड": "ms",
61
+ "मिनट": "min", "मिनटों": "min", "घंटा": "h", "घंटे": "h", "दिन": "day",
62
+ "एम्पियर": "A", "केल्विन": "K", "मोल": "mol", "कैंडेला": "cd",
63
+ "न्यूटन": "N", "जूल": "J", "वाट": "W", "कूलॉम": "C", "वोल्ट": "V",
64
+ "ओम": "ohm", "हर्ट्ज": "Hz", "इलेक्ट्रॉनवोल्ट": "eV",
65
+ "द्रव्यमान": "mass", "लंबाई": "length", "समय": "time", "आवर्तकाल": "period",
66
+ "आवृत्ति": "frequency", "वेग": "speed", "त्वरण": "acceleration",
67
+ "गुरुत्वाकर्षण": "gravity", "बल": "force", "कठोरता": "stiffness",
68
+ "संवेग": "momentum", "ऊर्जा": "energy", "शक्ति": "power", "आवेश": "charge",
69
+ "विद्युत धारा": "current", "विभव": "voltage", "प्रतिरोध": "resistance",
70
+ "तापमान": "temperature", "मात्रा": "amount", "दीप्ति तीव्रता": "luminosity",
71
+ "ऊंचाई": "hgt"
72
+ },
73
+ "noise": ["का", "की", "के", "को", "है", "हैं", "हो", "कि", "यह", "क्या", "मुझे", "कृपया", "बताइए", "दीजिए"],
74
+ "labels": {
75
+ "understood": "समझी गई समस्या",
76
+ "status": "स्थिति",
77
+ "assurance": "दो में से {n} स्तर",
78
+ "answer": "उत्तर",
79
+ "reading": "अर्थ",
80
+ "physics_layer": "भौतिकी स्तर",
81
+ "notes": "टिप्पणियाँ",
82
+ "examples": "इन वाक्यों को यह स्तर समझता है",
83
+ "question": "इनमें से एक रूप में फिर पूछें",
84
+ "check": "स्तर की SMT जाँच : {b} लिफाफों में से {a} पुष्ट",
85
+ "kind_of": "प्रकार"
86
+ },
87
+ "reading": {
88
+ "AGREED": "सहमत: दो स्वतंत्र पाठक और SMT प्रतिबंध",
89
+ "PASSTHROUGH": "वाक्य पहले से भौतिकी की भाषा में लिखा है, अनुवाद नहीं किया गया",
90
+ "DISPUTED": "विवादित: दोनों पाठक अलग-अलग वाक्य देते ह��ं",
91
+ "NOT COVERED": "इस भाषा की सीमा से बाहर",
92
+ "AMBIGUOUS": "अस्पष्ट: एक से अधिक अर्थ संभव हैं",
93
+ "SINGLE": "केवल एक अर्थ: दूसरे पाठक ने वाक्य नहीं पहचाना",
94
+ "TAMPERED": "छेड़छाड़: भौतिकी स्तर को भेजा गया वाक्य सहमत अर्थ नहीं है",
95
+ "NONE": "कोई अर्थ नहीं"
96
+ },
97
+ "reasons": {
98
+ "unknown_word": "शब्द {word} हिन्दी में समझे गए शब्दों में नहीं है",
99
+ "no_verb": "कोई शब्द समस्या का प्रकार घोषित नहीं करता",
100
+ "two_verbs": "वाक्य एक से अधिक प्रकार घोषित करता है: {kinds}",
101
+ "no_pattern": "वाक्य का रूप हिन्दी में समझे गए किसी रूप से मेल नहीं खाता",
102
+ "no_frame": "जोड़ प्रकार {kind} के किसी रूप से मेल नहीं खाते",
103
+ "multiple": "इसी वाक्य के दो अलग अर्थ हैं: {first} और {second}",
104
+ "disagree": "दोनों पाठक भौतिकी की भाषा में दो अलग वाक्य देते हैं",
105
+ "markers": "वाक्य के जोड़ प्रकार की अपेक्षा अनुसार नहीं हैं",
106
+ "bad_number": "{slot} भौतिकी की भाषा की संख्या नहीं है",
107
+ "bad_unit": "{slot} भौतिकी की भाषा के प्रतीकों में लिखी इकाई नहीं है",
108
+ "bad_formula": "{slot} एक ही समानता चिह्न और ज्ञात प्रतीकों वाला समीकरण नहीं है",
109
+ "bad_symbol": "{slot} भौतिकी की भाषा का राशि प्रतीक नहीं है",
110
+ "unbalanced": "कोई कोष्ठक या वर्ग कोष्ठक बंद नहीं है",
111
+ "no_math": "भौतिकी का भाग भौतिकी की भाषा के प्रतीकों में नहीं लिखा है",
112
+ "literal_count": "दोनों पाठकों में वाक्य की संख्याएँ समान नहीं हैं",
113
+ "physics_unknown": "भौतिकी स्तर वाक्य नहीं स्वीकारता: {detail}",
114
+ "boundary": "भौतिकी स्तर को भेजा गया वाक्य सहमत अर्थ नहीं है",
115
+ "referee": "SMT निर्णायक {detail} की पुष्टि नहीं करता",
116
+ "other": "अर्थ भौतिकी की भाषा के वाक्य तक नहीं पहुँचा"
117
+ },
118
+ "examples": [
119
+ "बदलो 3 किलोमीटर में मीटर",
120
+ "परिवर्तित करो 5 किलोमीटर प्रति घंटा में मीटर प्रति सेकंड",
121
+ "सिद्ध करें बल गुणा समय के बराबर द्रव्यमान गुणा वेग",
122
+ "जांच करें बल गुणा लंबाई बराबर ऊर्जा",
123
+ "pi ज्ञात करो आवर्तकाल से द्रव्यमान और कठोरता",
124
+ "विमीय विश्लेषण वेग से लंबाई और समय"
125
+ ]
126
+ }
lexicon/it.json ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "it",
3
+ "name": "Italiano",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "convert": {
9
+ "verbs": ["converti", "convertire", "trasforma", "trasformare", "esprimi", "esprimere", "riduci", "ridurre"],
10
+ "patterns": [
11
+ "converti {N} {U} in {V}",
12
+ "converti {N} {U} a {V}",
13
+ "convertire {N} {U} in {V}",
14
+ "trasforma {N} {U} in {V}",
15
+ "esprimi {N} {U} in {V}",
16
+ "riduci {N} {U} in {V}",
17
+ "in {V} converti {N} {U}"
18
+ ],
19
+ "frame": {"sequences": [["to"]]}
20
+ },
21
+ "audit": {
22
+ "verbs": ["bilancia", "verifica", "controlla", "valida", "dimostra"],
23
+ "patterns": [
24
+ "bilancia {F}",
25
+ "verifica {F}",
26
+ "verifica che {F}",
27
+ "controlla che {F}",
28
+ "dimostra che {F}",
29
+ "valida {F}"
30
+ ],
31
+ "frame": {"sequences": [[]]}
32
+ },
33
+ "pi": {
34
+ "verbs": ["analisi dimensionale", "gruppo adimensionale", "trova il pi", "calcola il pi", "pi"],
35
+ "patterns": [
36
+ "trova il pi {T} da {S}",
37
+ "trova il pi {T} a partire da {S}",
38
+ "calcola il pi {T} a partire da {S}",
39
+ "il gruppo adimensionale {T} a partire da {S}",
40
+ "il gruppo adimensionale {T} da {S}",
41
+ "analisi dimensionale {T} a partire da {S}",
42
+ "analisi dimensionale {T} da {S}"
43
+ ],
44
+ "frame": {"sequences": [["from"]]}
45
+ }
46
+ },
47
+ "connectives": {
48
+ "times": ["per", "volte", "moltiplicato per"],
49
+ "over": ["diviso per", "su"],
50
+ "plus": ["piu"],
51
+ "minus": ["meno"],
52
+ "power": ["elevato a"],
53
+ "equals": ["uguale a", "e uguale a", "equivale a"],
54
+ "list": ["e"]
55
+ },
56
+ "markers": {
57
+ "to": ["in", "a"],
58
+ "from": ["da", "a partire da", "partendo da"]
59
+ },
60
+ "tokens": {
61
+ "metro": "m", "metri": "m",
62
+ "chilometro": "km", "chilometri": "km",
63
+ "centimetro": "cm", "centimetri": "cm",
64
+ "millimetro": "mm", "millimetri": "mm",
65
+ "chilometro all'ora": "km/h", "chilometri all'ora": "km/h",
66
+ "metro al secondo": "m/s", "metri al secondo": "m/s",
67
+ "metro quadro": "m^2", "metri quadri": "m^2",
68
+ "kilometro": "km", "kilometri": "km",
69
+ "chilogrammo": "kg", "chilogrammi": "kg", "grammo": "g", "grammi": "g",
70
+ "secondo": "s", "secondi": "s",
71
+ "millisecondo": "ms", "millisecondi": "ms",
72
+ "minuto": "min", "minuti": "min",
73
+ "ora": "h", "ore": "h",
74
+ "giorno": "day", "giorni": "day",
75
+ "ampere": "A", "kelvin": "K", "mole": "mol", "candela": "cd",
76
+ "newton": "N", "joule": "J", "watt": "W", "coulomb": "C", "volt": "V",
77
+ "ohm": "ohm", "hertz": "Hz", "elettronvolt": "eV",
78
+ "massa": "mass", "lunghezza": "length", "tempo": "time",
79
+ "periodo": "period", "frequenza": "frequency",
80
+ "velocita": "speed", "accelerazione": "acceleration", "gravita": "gravity",
81
+ "forza": "force", "rigidita": "stiffness", "momento": "momentum",
82
+ "energia": "energy", "potenza": "power", "carica": "charge",
83
+ "corrente": "current", "tensione": "voltage", "resistenza": "resistance",
84
+ "temperatura": "temperature", "quantita": "amount", "luminosita": "luminosity",
85
+ "altezza": "hgt"
86
+ },
87
+ "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"],
88
+ "labels": {
89
+ "understood": "Problema capito",
90
+ "status": "Stato",
91
+ "assurance": "livello {n} di 2",
92
+ "answer": "Risposta",
93
+ "reading": "Lettura",
94
+ "physics_layer": "strato fisica",
95
+ "notes": "Note",
96
+ "examples": "Frasi che questo strato capisce",
97
+ "question": "Riformula la domanda in una di queste forme",
98
+ "check": "Controllo SMT dello strato : {a} di {b} buste confermate",
99
+ "kind_of": "tipo"
100
+ },
101
+ "reading": {
102
+ "AGREED": "accordata: due lettori indipendenti piu il vincolo SMT",
103
+ "PASSTHROUGH": "frase gia scritta nella lingua fisica, non tradotta",
104
+ "DISPUTED": "in disputa: i due lettori propongono frasi diverse",
105
+ "NOT COVERED": "fuori dalla copertura di questa lingua",
106
+ "AMBIGUOUS": "ambigua: piu letture possibili",
107
+ "TAMPERED": "manomessa: il testo passato allo strato fisico non e la lettura concordata",
108
+ "SINGLE": "una sola lettura: l'altro lettore non ha riconosciuto la frase",
109
+ "NONE": "nessuna lettura"
110
+ },
111
+ "reasons": {
112
+ "unknown_word": "la parola {word} non compare nelle frasi coperte in italiano",
113
+ "no_verb": "nessuna parola annuncia il tipo di problema in italiano",
114
+ "two_verbs": "la frase annuncia piu di un tipo di problema: {kinds}",
115
+ "no_pattern": "la forma della frase non corrisponde a nessuna forma coperta in italiano",
116
+ "no_frame": "i connettori non corrispondono ad alcuna forma del tipo {kind}",
117
+ "multiple": "della stessa frase esistono due letture diverse: {first} e {second}",
118
+ "disagree": "i due lettori propongono due frasi della lingua fisica diverse",
119
+ "markers": "i connettori della frase non sono quelli attesi per il tipo di problema",
120
+ "bad_number": "{slot} non e un numero della lingua fisica",
121
+ "bad_unit": "{slot} non e un'unita scritta con i simboli della lingua fisica",
122
+ "bad_formula": "{slot} non e un'equazione con una sola uguaglianza e simboli noti",
123
+ "bad_symbol": "{slot} non e un simbolo di quantita della lingua fisica",
124
+ "unbalanced": "parentesi o parentesi quadre non chiuse",
125
+ "no_math": "la parte fisica non e scritta con i simboli della lingua fisica",
126
+ "literal_count": "i numeri della frase non sono gli stessi nei due lettori",
127
+ "physics_unknown": "lo strato fisico non accetta la frase: {detail}",
128
+ "boundary": "la frase passata allo strato fisico non e quella concordata",
129
+ "referee": "il controllore SMT non conferma {detail}",
130
+ "other": "la lettura non e arrivata a una frase della lingua fisica"
131
+ },
132
+ "examples": [
133
+ "converti 3 chilometri in metri",
134
+ "esprimi 5 chilometri all'ora in metri al secondo",
135
+ "in metri al secondo converti 5 chilometri all'ora",
136
+ "verifica che la forza per il tempo e uguale a massa per velocita",
137
+ "bilancia forza per lunghezza = energia",
138
+ "trova il pi del periodo a partire da massa e rigidita",
139
+ "l'analisi dimensionale della velocita a partire da lunghezza e tempo"
140
+ ]
141
+ }
lexicon/zh.json ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "zh",
3
+ "name": "中文",
4
+ "script": "cjk",
5
+ "noise_chars": "的了之把被给吧呢吗也则该",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "convert": {
9
+ "verbs": ["换算", "转换", "改写"],
10
+ "patterns": [
11
+ "换算 {N} {U} 成 {V}",
12
+ "换算 {N} {U} 为 {V}",
13
+ "换算 {N} {U} 到 {V}",
14
+ "转换 {N} {U} 成 {V}",
15
+ "转换 {N} {U} 为 {V}",
16
+ "改写 {N} {U} 为 {V}"
17
+ ],
18
+ "frame": {"sequences": [["to"]]}
19
+ },
20
+ "audit": {
21
+ "verbs": ["校验", "检验", "验证", "检查"],
22
+ "patterns": [
23
+ "校验 {F}",
24
+ "检验 {F}",
25
+ "验证 {F}",
26
+ "检查 {F}"
27
+ ],
28
+ "frame": {"sequences": [[]]}
29
+ },
30
+ "pi": {
31
+ "verbs": ["量纲分析", "求pi", "计算pi", "pi"],
32
+ "patterns": [
33
+ "pi {T} 由 {S}",
34
+ "求pi {T} 由 {S}",
35
+ "计算pi {T} 由 {S}",
36
+ "量纲分析 {T} 由 {S}"
37
+ ],
38
+ "frame": {"sequences": [["from"]]}
39
+ }
40
+ },
41
+ "connectives": {
42
+ "times": ["乘以", "乘"],
43
+ "over": ["除以"],
44
+ "plus": ["加"],
45
+ "minus": ["减"],
46
+ "power": ["的幂"],
47
+ "equals": ["等于"],
48
+ "list": ["和", "与"]
49
+ },
50
+ "markers": {
51
+ "to": ["成", "为", "到"],
52
+ "from": ["由", "从"]
53
+ },
54
+ "tokens": {
55
+ "米": "m", "公里": "km", "千米": "km", "厘米": "cm", "毫米": "mm",
56
+ "千米每小时": "km/h", "公里每小时": "km/h", "米每秒": "m/s", "米平方": "m^2",
57
+ "千克": "kg", "公斤": "kg", "克": "g",
58
+ "秒": "s", "毫秒": "ms", "分钟": "min", "小时": "h", "天": "day",
59
+ "安培": "A", "开尔文": "K", "摩尔": "mol", "坎德拉": "cd",
60
+ "牛顿": "N", "焦耳": "J", "瓦特": "W", "库仑": "C", "伏特": "V",
61
+ "欧姆": "ohm", "赫兹": "Hz", "电子伏特": "eV",
62
+ "质量": "mass", "长度": "length", "时间": "time", "周期": "period",
63
+ "频率": "frequency", "速度": "speed", "加速度": "acceleration",
64
+ "重力": "gravity", "力": "force", "刚度": "stiffness", "动量": "momentum",
65
+ "能量": "energy", "功率": "power", "电荷": "charge", "电流": "current",
66
+ "电压": "voltage", "电阻": "resistance", "温度": "temperature",
67
+ "物质的量": "amount", "发光强度": "luminosity", "高度": "hgt"
68
+ },
69
+ "noise": ["求", "请", "试", "是", "为", "的", "了"],
70
+ "labels": {
71
+ "understood": "理解的问题",
72
+ "status": "状态",
73
+ "assurance": "两级中的第 {n} 级",
74
+ "answer": "答案",
75
+ "reading": "读法",
76
+ "physics_layer": "物理层",
77
+ "notes": "备注",
78
+ "examples": "这一层能理解的句子",
79
+ "question": "请用下列形式之一重述问题",
80
+ "check": "物理层的 SMT 检查:{b} 个信封中有 {a} 个得到确认",
81
+ "kind_of": "类型"
82
+ },
83
+ "reading": {
84
+ "AGREED": "一致:两位独立读者加上 SMT 约束",
85
+ "PASSTHROUGH": "句子已用物理语言写成,未作翻译",
86
+ "DISPUTED": "有分歧:两位读者给出不同的句子",
87
+ "NOT COVERED": "不在这种语言变体所覆盖的范围之内",
88
+ "AMBIGUOUS": "有歧义:可以有不止一种读法",
89
+ "SINGLE": "只有一种读法:另一位读者没有认出这个句子",
90
+ "TAMPERED": "被篡改:送往物理层的句子不是那个一致的读法",
91
+ "NONE": "没有读法"
92
+ },
93
+ "reasons": {
94
+ "unknown_word": "{word} 不属于这种中文所覆盖的词",
95
+ "no_verb": "没有词宣布问题的类型",
96
+ "two_verbs": "句子宣布了不止一种问题类型:{kinds}",
97
+ "no_pattern": "句子的形状不匹配这种中文所覆盖的任何形状",
98
+ "no_frame": "连接词不匹配类型 {kind} 的任何形状",
99
+ "multiple": "同一句子有两种不同的读法:{first} 和 {second}",
100
+ "disagree": "两位读者给出两个不同的物理语言句子",
101
+ "markers": "句子的连接词不是该类型所期待的那些",
102
+ "bad_number": "{slot} 不是物理语言中的一个数",
103
+ "bad_unit": "{slot} 不是用物理语言的符号写出的单位",
104
+ "bad_formula": "{slot} 不是只含一个等号且符号已知的等式",
105
+ "bad_symbol": "{slot} 不是物理语言中的量符号",
106
+ "unbalanced": "有个圆括号或方括号没有闭合",
107
+ "no_math": "物理部分没有用物理语言的符号书写",
108
+ "literal_count": "句子中的数字在两位读者那里并不相同",
109
+ "physics_unknown": "物理层不接受这个句子:{detail}",
110
+ "boundary": "送往物理层的句子不是那个一致的读法",
111
+ "referee": "SMT 裁判没有确认 {detail}",
112
+ "other": "读法没有得到物理语言中的一个句子"
113
+ },
114
+ "examples": [
115
+ "换算 3 公里 成 米",
116
+ "换算 5 千米每小时 为 米每秒",
117
+ "校验 力 乘以 时间 等于 质量 乘以 速度",
118
+ "检验 力 乘以 长度 等于 能量",
119
+ "求pi 周期 由 质量 和 刚度",
120
+ "量纲分析 速度 由 长度 和 时间"
121
+ ]
122
+ }
lgphysstratum/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ """Physics stratum: the conversational layer that sits on top of the physics topology.
2
+
3
+ The modules of this package read a question written in one of six written varieties, agree on one
4
+ sentence of the physics language, hand that sentence to the physics topology as a separate process,
5
+ and answer in the language of the question with an assurance that never exceeds the assurance of
6
+ the physics verdict *and* never exceeds what the reading of the question deserves.
7
+ """
8
+
9
+ __all__ = ["agents", "canonical", "compare", "corpus", "coverage", "decide", "faults", "invoker",
10
+ "lexicon", "pipeline", "protocol", "read_a", "read_b", "render", "segment"]
lgphysstratum/agents.py ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The eight nodes of the stratum, one step function each.
2
+
3
+ Every node has exactly one job and one claim of its own, and no node is allowed to conclude what the
4
+ next one is supposed to check. The chain is the same shape the physics layer runs, only moved one
5
+ level up: two independent readers instead of two independent readers of the formal language, an
6
+ equivalence node instead of the equivalence checker, a coverage node that counts the numbers the user
7
+ wrote, an invoker that hands the agreed sentence to the physics layer as a separate process, a
8
+ boundary where that verdict enters this stratum, an adversary that re-derives what the others
9
+ asserted, and an arbiter that decides and answers in the user's language.
10
+
11
+ reader_a surface reading: the words of the variety, in the order they appear
12
+ reader_b frame reading: which marker phrase sits in which gap of the frame
13
+ equivalence are the two readings the same problem? the parser of the bundle answers, text
14
+ identity is a shortcut and the solver settles the numbers
15
+ coverage did the readings keep every number the user wrote?
16
+ invoker call the physics layer, in another process, on one sentence
17
+ boundary the physics verdict enters this stratum here, and only here
18
+ adversary re-derive the cross-channel checks and the cap the previous nodes implied
19
+ arbiter decide, cap the assurance, answer in the language of the user
20
+
21
+ The invariant every node here obeys, and which the last three nodes each write down as SMT2 so the
22
+ referee of the orchestrator refutes its negation: the assurance this stratum shows is
23
+ ``min(assurance of the physics layer, ceiling of the reading)``. A node may lower what the user sees;
24
+ none may raise it.
25
+ """
26
+
27
+ from typing import Any, Dict, List, Tuple
28
+
29
+ from . import canonical, compare, coverage, decide, faults, invoker, protocol, read_a, read_b, render
30
+
31
+ ORDER = ("reader_a", "reader_b", "equivalence", "coverage", "invoker", "boundary", "adversary", "arbiter")
32
+
33
+
34
+ def _ast(dossier: Dict[str, Any]) -> str:
35
+ """One ASCII line describing the shape of the dossier, for the abstractSyntaxTree field."""
36
+ def status_of(key: str) -> str:
37
+ part = dossier.get(key)
38
+ if not isinstance(part, dict):
39
+ return "absent"
40
+ return str(part.get("status") or part.get("state") or part.get("kind") or "present")
41
+
42
+ return "Stratum(lang=%s, a=%s, b=%s, equiv=%s, cover=%s, physics=%s, final=%s)" % (
43
+ dossier.get("lang", "?"), status_of("reading_a"), status_of("reading_b"),
44
+ "same" if (dossier.get("compare") or {}).get("same") else "no",
45
+ "ok" if (dossier.get("coverage") or {}).get("ok") else "no",
46
+ (dossier.get("physics") or {}).get("status", "absent"),
47
+ (dossier.get("final") or {}).get("state", "absent"),
48
+ )
49
+
50
+
51
+ def _cap_claim(shown: int, ceiling: int) -> Tuple[List[str], List[str], str]:
52
+ """SMT2 for ``this node raised nothing``: the strict excess over the ceiling is refuted."""
53
+ decls = ["(declare-const shown Real)", "(declare-const ceiling Real)"]
54
+ asserts = ["(assert (= shown %d))" % int(shown), "(assert (= ceiling %d))" % int(ceiling),
55
+ "(assert (> shown ceiling))"]
56
+ return decls, asserts, "unsat"
57
+
58
+
59
+ def _reader_claim(reading: Dict[str, Any], question: str) -> Tuple[List[str], List[str], str]:
60
+ """A reader claims one thing only: it dropped no number the user wrote."""
61
+ step = compare.keeps(reading, question)
62
+ return step["declarations"], step["assertions"], step["claimed"]
63
+
64
+
65
+ def _apply_reader_fault(agent: str, reading: Dict[str, Any]) -> None:
66
+ """Corrupt a reading on purpose, for the ablation experiments: never in a normal session."""
67
+ if not reading.get("kind") or reading.get("status") != "READ":
68
+ return
69
+ for kind in faults.READER_FAULTS:
70
+ if not faults.has(agent, kind):
71
+ continue
72
+ order = canonical.slots_for(str(reading["kind"]))
73
+ slots, changed = faults.mutate_reading(agent, str(reading["kind"]),
74
+ dict(reading.get("slots") or {}), order)
75
+ if not changed:
76
+ continue
77
+ faults.fire(agent, kind)
78
+ try:
79
+ reading["math"] = canonical.print_math(str(reading["kind"]), slots)
80
+ reading["slots"] = slots
81
+ reading["fault"] = kind
82
+ except canonical.ReadingError:
83
+ reading["math"] = ""
84
+ reading["status"] = "NOT COVERED"
85
+ reading["notes"].append({"reason": "no_frame", "kind": reading["kind"], "detail": kind})
86
+ return
87
+
88
+
89
+ def _reading_node(agent: str, reader: Any, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
90
+ """Shared body of the two reader nodes: read the question, keep the reading, claim the numbers."""
91
+ dossier, turn, tick, rcpt = protocol.start(incoming)
92
+ question = str(dossier.get("question", ""))
93
+ lang = str(dossier.get("lang") or "")
94
+ direct = canonical.direct(question)
95
+ if direct is not None:
96
+ dossier["reading_direct"] = direct
97
+ reading = direct
98
+ else:
99
+ reading = reader.read(lang, question)
100
+ _apply_reader_fault(node_id, reading)
101
+ dossier[agent] = reading
102
+ decls, asserts, claimed = _reader_claim(reading, question)
103
+ summary = "%s: %s %s" % (node_id, reading.get("status"), reading.get("math") or "")
104
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
105
+
106
+
107
+ def step_reader_a(incoming: Dict[str, Any], node_id: str = "reader_a") -> Dict[str, Any]:
108
+ """Reader A: surface patterns of the variety, reading left to right."""
109
+ return _reading_node("reading_a", read_a, incoming, node_id)
110
+
111
+
112
+ def step_reader_b(incoming: Dict[str, Any], node_id: str = "reader_b") -> Dict[str, Any]:
113
+ """Reader B: the frame of the problem kind and the marker phrases sitting in its gaps."""
114
+ return _reading_node("reading_b", read_b, incoming, node_id)
115
+
116
+
117
+ def step_equivalence(incoming: Dict[str, Any], node_id: str = "equivalence") -> Dict[str, Any]:
118
+ """Are the two readings one problem? The answer carries the SMT2 program behind it."""
119
+ dossier, turn, tick, rcpt = protocol.start(incoming)
120
+ if faults.has(node_id, "rubber_stamp"):
121
+ faults.fire(node_id, "rubber_stamp")
122
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_a") or {}
123
+ else:
124
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_b") or {}
125
+ direct = dossier.get("reading_direct")
126
+ if direct is not None:
127
+ first, second = direct, dict(dossier.get("reading_b") or direct)
128
+ comparison = compare.equivalence(first, second)
129
+ dossier["compare"] = comparison
130
+ if first.get("math") and (comparison["same"] or not second.get("math")):
131
+ dossier["sent"] = comparison["left"] or str(first["math"])
132
+ elif second.get("math") and not first.get("math"):
133
+ dossier["sent"] = comparison["right"] or str(second["math"])
134
+ summary = "equivalence: %s (%s)" % ("same" if comparison["same"] else "not the same problem",
135
+ comparison["why"])
136
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
137
+ comparison["declarations"], comparison["assertions"], comparison["claimed"])
138
+
139
+
140
+ def step_coverage(incoming: Dict[str, Any], node_id: str = "coverage") -> Dict[str, Any]:
141
+ """Did the readings keep every number the user wrote, and in the same multiset?"""
142
+ dossier, turn, tick, rcpt = protocol.start(incoming)
143
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
144
+ if dossier.get("reading_direct") is not None:
145
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
146
+ if faults.has(node_id, "rubber_stamp"):
147
+ faults.fire(node_id, "rubber_stamp")
148
+ claim = {"ok": True, "wrote": [], "kept": [], "missing": [], "added": [],
149
+ "declarations": ["(declare-const wrote_0 Real)"], "assertions": ["(assert (= wrote_0 0))"],
150
+ "claimed": "sat"}
151
+ else:
152
+ claim = coverage.coverage_claim(str(dossier.get("question", "")), [r for r in readings if r])
153
+ dossier["coverage"] = claim
154
+ summary = "coverage: %s (%d numbers)" % ("kept" if claim["ok"] else "not kept", len(claim["wrote"]))
155
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
156
+ claim["declarations"], claim["assertions"], claim["claimed"])
157
+
158
+
159
+ def _produced(dossier: Dict[str, Any]) -> List[Dict[str, Any]]:
160
+ """The readings that actually produced a sentence, in reader order."""
161
+ return [item for item in (dossier.get("reading_direct") or {}, dossier.get("reading_a") or {},
162
+ dossier.get("reading_b") or {}) if item.get("math")]
163
+
164
+
165
+ def _echo_reference(dossier: Dict[str, Any], produced: List[Dict[str, Any]]) -> Dict[str, Any]:
166
+ """The reading whose sentence is the one the physics layer was asked about.
167
+
168
+ The boundary and the adversary compare the echo of the physics layer with a reading rather than
169
+ with the sentence the previous node copied into the dossier, because a reading is an independent
170
+ channel. Either reader may be the one that abstained, so the reference is chosen by matching the
171
+ sentence, not by reader order.
172
+ """
173
+ agreed = canonical.tidy(str(dossier.get("sent") or ""))
174
+ return next((item for item in produced if canonical.tidy(str(item.get("math"))) == agreed),
175
+ produced[0] if produced else {})
176
+
177
+
178
+ def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]:
179
+ """Ask the physics layer, in its own process, about the sentence the readers agreed on."""
180
+ dossier, turn, tick, rcpt = protocol.start(incoming)
181
+ sentence = str(dossier.get("sent") or "")
182
+ if not sentence:
183
+ dossier["physics"] = invoker.unavailable("no sentence was agreed on")
184
+ summary = "invoker: nothing to ask the physics layer"
185
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
186
+ ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat")
187
+ verdict = invoker.ask(sentence)
188
+ dossier["physics"] = verdict
189
+ wrote = compare.sorted_numbers(sentence)
190
+ echo = compare.sorted_numbers(str(verdict.get("problem_physics") or ""))
191
+ decls, asserts = compare.elementwise(wrote, echo, "asked")
192
+ summary = "invoker: %s (%s)" % (verdict.get("status"), verdict.get("answer_text") or "no answer")
193
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
194
+ decls, asserts + ["(assert (= 1 1))"] if not decls else asserts,
195
+ "sat" if wrote == echo else "unsat")
196
+
197
+
198
+ def step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]:
199
+ """The physics verdict enters this stratum here; the echo it carries is checked, not trusted."""
200
+ dossier, turn, tick, rcpt = protocol.start(incoming)
201
+ # The echo is checked against a reading, not against the sentence the previous node wrote down:
202
+ # a reading is an independent channel. One reading may have failed while the other produced the
203
+ # sentence that was asked, so the readings used here are the ones that produced a sentence.
204
+ produced = _produced(dossier)
205
+ reading = _echo_reference(dossier, produced)
206
+ physics_verdict = dict(dossier.get("physics") or {})
207
+ agreed = str(dossier.get("sent") or "")
208
+ echo = str(physics_verdict.get("problem_physics") or "")
209
+ if echo:
210
+ matches = coverage.echo_matches(reading, physics_verdict)
211
+ decls, asserts = compare.elementwise(compare.sorted_numbers(agreed),
212
+ compare.sorted_numbers(echo), "echo")
213
+ asserts = asserts + (["(assert (= 1 1))"] if matches else ["(assert false)"])
214
+ claimed = "sat" if matches else "unsat"
215
+ else:
216
+ # The physics layer answered no sentence at all: there is nothing to compare, and the honest
217
+ # claim is the empty one, which is satisfiable. A node that wanted to look busy here would be
218
+ # asserting something it has no evidence about.
219
+ matches = True
220
+ decls, asserts, claimed = [], ["(assert (= 1 1))"], "sat"
221
+ if faults.has(node_id, "tamper_physics") and echo:
222
+ tampered, changed = faults.mutate_sentence(node_id, echo)
223
+ if changed:
224
+ faults.fire(node_id, "tamper_physics")
225
+ physics_verdict["problem_physics"] = tampered
226
+ physics_verdict["fault"] = "tamper_physics"
227
+ dossier["physics"] = physics_verdict
228
+ dossier["echo_ok"] = bool(matches)
229
+ summary = "boundary: %s echoed=%s" % (physics_verdict.get("status"), "yes" if matches else "no")
230
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
231
+
232
+
233
+ def step_adversary(incoming: Dict[str, Any], node_id: str = "adversary") -> Dict[str, Any]:
234
+ """Re-derive what the previous nodes asserted, and write the cap as an inequality to refute."""
235
+ dossier, turn, tick, rcpt = protocol.start(incoming)
236
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
237
+ if dossier.get("reading_direct") is not None:
238
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
239
+ comparison = dossier.get("compare")
240
+ physics_verdict = dossier.get("physics") or {}
241
+ cover = dossier.get("coverage")
242
+ if faults.has(node_id, "rubber_stamp"):
243
+ faults.fire(node_id, "rubber_stamp")
244
+ echo_ok = True
245
+ else:
246
+ produced = _produced(dossier)
247
+ echo_ok = (coverage.echo_matches(_echo_reference(dossier, produced), physics_verdict)
248
+ if physics_verdict.get("problem_physics") else True)
249
+ for other in produced:
250
+ if not coverage.echo_matches(other, physics_verdict):
251
+ echo_ok = False
252
+ dossier["echo_ok"] = bool(echo_ok)
253
+ state = decide.state_of(readings, comparison, cover,
254
+ physics_verdict if physics_verdict.get("status") else None,
255
+ dossier.get("reading_direct"), echo_ok)
256
+ ceiling = decide.CEILING[state]
257
+ shown = min(ceiling, int(physics_verdict.get("assurance", 0) or 0))
258
+ dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown,
259
+ "physics_assurance": int(physics_verdict.get("assurance", 0) or 0)}
260
+ decls, asserts, claimed = _cap_claim(shown, ceiling)
261
+ summary = "adversary: ceiling %d, shown %d, echo %s" % (ceiling, shown, "ok" if echo_ok else "mismatch")
262
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
263
+
264
+
265
+ def step_arbiter(incoming: Dict[str, Any], node_id: str = "arbiter") -> Dict[str, Any]:
266
+ """Decide, cap, and answer in the language the user wrote in."""
267
+ dossier, turn, tick, rcpt = protocol.start(incoming)
268
+ final = decide.decide(dossier)
269
+ if faults.has(node_id, "force_assurance"):
270
+ faults.fire(node_id, "force_assurance")
271
+ # Three is above the top of the scale this project uses for physics, so the cap claim of this
272
+ # very node is the sentence that refutes it.
273
+ final = decide.raise_assurance(final, 3)
274
+ dossier["final"] = final
275
+ dossier["reply"] = render.reply(dossier, final)
276
+ ceiling = int(final.get("ceiling", 0) or 0)
277
+ decls, asserts, claimed = _cap_claim(int(final.get("assurance", 0) or 0), ceiling)
278
+ summary = "arbiter: %s (assurance %d) %s" % (final["state"], final["assurance"], final["answer"] or "")
279
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
280
+
281
+
282
+ STEPS = {
283
+ "reader_a": step_reader_a,
284
+ "reader_b": step_reader_b,
285
+ "equivalence": step_equivalence,
286
+ "coverage": step_coverage,
287
+ "invoker": step_invoker,
288
+ "boundary": step_boundary,
289
+ "adversary": step_adversary,
290
+ "arbiter": step_arbiter,
291
+ }
292
+
293
+
294
+ def run_step(role: str, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
295
+ """Run one role, containing any unexpected exception as a crash entry in the dossier.
296
+
297
+ A node that crashes must not stop the session: the arbiter then reports the state NONE with zero
298
+ assurance, so the user is never left with a half-built answer and never with an invented one
299
+ either.
300
+ """
301
+ try:
302
+ return STEPS[role](incoming, node_id)
303
+ except Exception as exc: # noqa: BLE001 - containment is the whole point of this wrapper
304
+ dossier, turn, tick, rcpt = protocol.start(incoming)
305
+ dossier.setdefault("crash", {})[role] = "%s: %s" % (type(exc).__name__, str(exc)[:120])
306
+ return protocol.envelope(node_id, rcpt, turn, tick, "%s crashed" % role, "Crashed", dossier,
307
+ [], ["(assert true)"], "sat")
lgphysstratum/canonical.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The canonical form of a physics sentence, and the shape a slot must have to be physics.
2
+
3
+ The stratum does not parse physics: it *prints* a sentence of the physics language and hands it to
4
+ the physics topology, which owns the parser, the unit algebra and the verdict. What this module
5
+ owns is the other half of the contract:
6
+
7
+ * ``TEMPLATES`` -- one template per kind the reading layer covers, written the way ``canon`` of the
8
+ physics topology prints it, so that the sentence the stratum understood and the fingerprint the
9
+ two roads of the physics chain compare are the same string;
10
+ * ``print_math`` -- fill the slots of a template and tidy the result;
11
+ * ``gap_markers`` and ``marker_sequence`` -- the joints of a template (``to`` of a conversion,
12
+ ``from`` of a dimensional analysis), which is reader B's skeleton: a reading is what falls
13
+ between those joints;
14
+ * the slot validators -- ``number``, ``unit``, ``formula``, ``symbol``, ``symbols``. They do not
15
+ compute physics: they check that what the readers found has the shape a physics sentence needs,
16
+ so that a wrong reading stops here with a reason instead of reaching the physics topology as
17
+ nonsense;
18
+ * ``direct`` -- a sentence already written in the physics language, which is how the circuit
19
+ family stays reachable without a translation.
20
+
21
+ ``tidy`` is the one normal form the two readers compare notes in. The physics tokenizer separates
22
+ its tokens at every space and at every character of ``()[]=^;,``, so tidying never changes what the
23
+ physics topology reads. Unlike the math counterpart, it does not insert a multiplication sign
24
+ between a number and a letter: in physics ``3 m`` is a number and a unit, two tokens, and gluing
25
+ them into ``3*m`` would ask the physics topology to multiply a quantity by a symbol.
26
+ """
27
+
28
+ import re
29
+ from fractions import Fraction
30
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
31
+
32
+ KINDS = ("convert", "audit", "pi")
33
+
34
+ # kind -> list of (slots, template). The template is what ``lgphys.tree.canon`` prints, so the
35
+ # sentence the stratum shows is the sentence the two roads of the physics chain compare.
36
+ TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = {
37
+ "convert": [(("N", "U", "V"), "convert {N} {U} to {V}")],
38
+ "audit": [(("F",), "audit {F}")],
39
+ "pi": [(("T", "S"), "pi {T} from {S}")],
40
+ }
41
+
42
+ SLOT_ORDER: Dict[str, Tuple[str, ...]] = {kind: TEMPLATES[kind][0][0] for kind in KINDS}
43
+ VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [slots for slots, _ in TEMPLATES[kind]]
44
+ for kind in KINDS}
45
+
46
+ # The joints of the physics language: the fixed words between the slots of a template.
47
+ MARKERS = ("to", "from")
48
+ _PHRASE_MARKER = {"to": "to", "from": "from"}
49
+
50
+ _SLOT_MARK = re.compile(r"\{([NUVFST])\}")
51
+ _SINGLE_LETTER = re.compile(r"[A-Za-z]$")
52
+
53
+
54
+ class ReadingError(Exception):
55
+ """A sentence cannot be printed as physics: a slot is missing or a template holds a stray word."""
56
+
57
+
58
+ def template_for(kind: str, variant: Optional[Sequence[str]] = None) -> str:
59
+ """The template of one form of one kind."""
60
+ if kind not in TEMPLATES:
61
+ raise ReadingError("no template for the kind %s" % kind)
62
+ forms = TEMPLATES[kind]
63
+ if variant is None:
64
+ return forms[0][1]
65
+ wanted = tuple(variant)
66
+ for slots, text in forms:
67
+ if slots == wanted:
68
+ return text
69
+ raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(wanted)))
70
+
71
+
72
+ def slots_for(kind: str, variant: Optional[Sequence[str]] = None) -> Tuple[str, ...]:
73
+ """The slots of one form, in the order the template fills them."""
74
+ if kind not in TEMPLATES:
75
+ raise ReadingError("no template for the kind %s" % kind)
76
+ if variant is None:
77
+ return SLOT_ORDER[kind]
78
+ wanted = tuple(variant)
79
+ if wanted not in VARIANTS[kind]:
80
+ raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(wanted)))
81
+ return wanted
82
+
83
+
84
+ def print_math(kind: str, slots: Dict[str, str], variant: Optional[Sequence[str]] = None) -> str:
85
+ """Fill one template and tidy it: the sentence the physics topology is asked to answer."""
86
+ wanted = slots_for(kind, variant)
87
+ for name in wanted:
88
+ if name not in slots or not str(slots[name]).strip():
89
+ raise ReadingError("the form of %s needs the slot %s" % (kind, name))
90
+ extra = [name for name in slots if name not in wanted]
91
+ if extra:
92
+ raise ReadingError("%s has no slot named %s" % (kind, " ".join(sorted(extra))))
93
+ return tidy(template_for(kind, variant).format(**{name: _slot_spelling(name, str(slots[name]))
94
+ for name in wanted}))
95
+
96
+
97
+ def gap_markers(kind: str, variant: Optional[Sequence[str]] = None) -> List[Optional[str]]:
98
+ """The joints of a template, one entry per gap around the slots.
99
+
100
+ The list has one entry per gap: before the first slot, between consecutive slots, after the
101
+ last one. ``None`` marks a gap with no joint, which is where the verb of the sentence sits in
102
+ every language. This is reader B's skeleton: the slots of a reading are the pieces of physics
103
+ that fall between those joints, and a joint may not be missing or out of order.
104
+ """
105
+ # The capture group keeps the slot marks in the list, so the literals sit at the even indices.
106
+ parts = re.split(r"(\{[NUVFST]\})", template_for(kind, variant))
107
+ gaps: List[Optional[str]] = []
108
+ for index in range(0, len(parts), 2):
109
+ literal = parts[index]
110
+ phrase = literal.strip()
111
+ if index == 0 or not phrase:
112
+ gaps.append(None)
113
+ elif phrase in _PHRASE_MARKER:
114
+ gaps.append(_PHRASE_MARKER[phrase])
115
+ else:
116
+ raise ReadingError("the template of %s holds the words %r, which are not a joint of "
117
+ "the physics language" % (kind, phrase))
118
+ return gaps
119
+
120
+
121
+ def marker_sequence(kind: str, variant: Optional[Sequence[str]] = None) -> List[str]:
122
+ """The joints of one form, named in the order the physics language prints them."""
123
+ return [gap for gap in gap_markers(kind, variant) if gap is not None]
124
+
125
+
126
+ _OPERATORS = "+-*/^=<>!|"
127
+ _AFTER_CLOSED = "(?<=[0-9A-Za-z\\)\\]])\\s+(?=[%s])" % re.escape(_OPERATORS)
128
+ _BEFORE_OPEN = "(?<=[%s])\\s+(?=[0-9A-Za-z\\[\\(])" % re.escape(_OPERATORS)
129
+
130
+
131
+ def tidy(text: str) -> str:
132
+ """One space between the tokens, none inside a bracket, none around an operator.
133
+
134
+ The physics language tolerates whitespace anywhere between its tokens -- verified against the
135
+ physics topology itself, which reads ``audit ( F * t ) = ( m * v )`` and
136
+ ``audit (F*t)=(m*v)`` as the same equation -- so tidying never changes what physics sees. It
137
+ gives the two readers one normal form to compare, which matters because the two of them glue
138
+ the tokens of a slot differently: reader A joins what it found with spaces, reader B reads the
139
+ text between two joints as it stands.
140
+
141
+ What the normal form may not do is let two tokens fuse, and for physics that rule is stricter
142
+ than for math: ``3 m`` stays ``3 m``, because the number and the unit are two tokens and the
143
+ unit table of the physics topology reads them apart.
144
+ """
145
+ out = re.sub(r"\s+", " ", text).strip()
146
+ out = re.sub(r"\s+([,\]\)])", r"\1", out)
147
+ out = re.sub(r"([\[\(])\s+", r"\1", out)
148
+ out = re.sub(_AFTER_CLOSED, "", out)
149
+ out = re.sub(_BEFORE_OPEN, "", out)
150
+ return out
151
+
152
+
153
+ def number(text: str) -> Optional[str]:
154
+ """A slot value that is a number token of the physics language, or ``None``.
155
+
156
+ Integer, decimal or explicit fraction, kept exactly as written: rewriting ``0.5`` as ``1/2``
157
+ would change the digits the question carries, and the coverage check compares those digits.
158
+ """
159
+ cleaned = tidy(text)
160
+ if not cleaned:
161
+ return None
162
+ try:
163
+ if "/" in cleaned:
164
+ head, tail = cleaned.split("/", 1)
165
+ Fraction(head.strip()) / Fraction(tail.strip())
166
+ else:
167
+ Fraction(cleaned)
168
+ except (ValueError, ZeroDivisionError, TypeError):
169
+ return None
170
+ return cleaned
171
+
172
+
173
+ def unit(text: str) -> Optional[str]:
174
+ """A slot value that is a unit expression, or ``None``.
175
+
176
+ Only the shape is checked here -- known unit names joined by ``*``, ``/`` and an integer power.
177
+ Whether the two ends of a conversion are comparable units is physics, and the physics topology
178
+ is the one that answers it.
179
+ """
180
+ cleaned = tidy(text)
181
+ if not cleaned:
182
+ return None
183
+ seen = False
184
+ for part in re.split(r"[\s*/^]+", cleaned):
185
+ if not part:
186
+ continue
187
+ if part.isdigit():
188
+ continue
189
+ if _UNIT_FORMS.get(part.lower(), part) not in PHYSICS_UNITS:
190
+ return None
191
+ seen = True
192
+ return normalize_unit(cleaned) if seen else None
193
+
194
+
195
+ def formula(text: str) -> Optional[str]:
196
+ """A slot value that is one equation of physics terms, or ``None``.
197
+
198
+ The check is syntactic and deliberately shallow: one equality sign, brackets closed, and every
199
+ word of it a word of the physics language. Dimensional homogeneity is what the audit family of
200
+ the physics topology decides, and the stratum never decides it twice.
201
+ """
202
+ cleaned = tidy(text)
203
+ if not cleaned or cleaned.count("=") != 1 or not balanced(cleaned):
204
+ return None
205
+ for word in re.findall(r"[A-Za-z]+", cleaned):
206
+ if word in PHYSICS_WORDS:
207
+ continue
208
+ if _FORMULA_FORMS.get(word.lower(), word) in PHYSICS_WORDS:
209
+ continue
210
+ return None
211
+ return _respell(cleaned, _FORMULA_FORMS)
212
+
213
+
214
+ def symbol(text: str) -> Optional[str]:
215
+ """A slot value that is one quantity symbol, or ``None``."""
216
+ cleaned = tidy(text)
217
+ if not cleaned or "," in cleaned:
218
+ return None
219
+ words = re.findall(r"[A-Za-z]+", cleaned)
220
+ if not words or "".join(words) != cleaned.replace(" ", ""):
221
+ return None
222
+ if len(words) != 1 or _SYMBOL_FORMS.get(words[0].lower(), words[0]) not in PHYSICS_SYMBOLS:
223
+ return None
224
+ return normalize_symbol(cleaned)
225
+
226
+
227
+ def symbols(text: str) -> Optional[str]:
228
+ """A slot value that is a list of quantity symbols separated by commas, or ``None``.
229
+
230
+ The printed form puts one space after every comma, which is what ``lgphys.tree.canon`` prints
231
+ for a Buckingham analysis: ``pi period from mass, stiffness``.
232
+ """
233
+ cleaned = tidy(text)
234
+ if not cleaned:
235
+ return None
236
+ parts = [part.strip() for part in cleaned.split(",")]
237
+ if len(parts) < 2:
238
+ return None
239
+ values = []
240
+ for part in parts:
241
+ value = symbol(part)
242
+ if value is None:
243
+ return None
244
+ values.append(value)
245
+ return ", ".join(values)
246
+
247
+
248
+ def balanced(text: str) -> bool:
249
+ """Every bracket of a sentence closed, and no doubled operator at the edges."""
250
+ depth = {"(": 0, "[": 0}
251
+ for ch in text:
252
+ if ch in depth:
253
+ depth[ch] += 1
254
+ elif ch == ")":
255
+ depth["("] -= 1
256
+ elif ch == "]":
257
+ depth["["] -= 1
258
+ if any(value < 0 for value in depth.values()):
259
+ return False
260
+ return all(value == 0 for value in depth.values())
261
+
262
+
263
+ # The commands of the physics language, copied from the parser specification of the physics
264
+ # topology. The reading layer covers three of them; the circuit family stays reachable through the
265
+ # direct mode.
266
+ PHYSICS_COMMANDS = ("convert", "audit", "pi", "potential")
267
+
268
+ # The units of the physics topology, copied from ``lgphys.units``.
269
+ PHYSICS_UNITS = frozenset([
270
+ "m", "kg", "s", "A", "K", "mol", "cd",
271
+ "N", "J", "W", "C", "V", "ohm", "Hz",
272
+ "g", "km", "cm", "mm", "ms", "min", "h", "day", "eV",
273
+ ])
274
+
275
+ # The quantity symbols of the physics topology, copied from the same table.
276
+ PHYSICS_SYMBOLS = frozenset([
277
+ "mass", "m", "length", "r", "hgt", "d",
278
+ "time", "t", "period", "frequency",
279
+ "speed", "v", "acceleration", "a", "gravity", "g",
280
+ "force", "F", "stiffness", "k", "momentum", "p",
281
+ "energy", "E", "power", "P", "charge", "q",
282
+ "current", "I", "voltage", "V", "resistance", "R",
283
+ "temperature", "T", "amount", "n", "luminosity",
284
+ ])
285
+
286
+ # The words the physics language itself uses: the commands, the joints, the keywords of the circuit
287
+ # form, every unit and every quantity symbol. A sentence that carries a word outside this list is
288
+ # not written in the physics language, whatever else it looks like. This is the third copy of that
289
+ # spec (the physics topology parses with it, its grammar names it), and the direct mode is where
290
+ # the copies can disagree out loud. ``tests/test_lexicon.py`` checks the copy against the live
291
+ # table of the physics topology whenever that folder is present.
292
+ PHYSICS_WORDS = frozenset(
293
+ set(PHYSICS_COMMANDS)
294
+ | set(MARKERS)
295
+ | {"node", "circuit", "resistors", "sources", "size", "frequency"}
296
+ | set(PHYSICS_UNITS)
297
+ | set(PHYSICS_SYMBOLS)
298
+ )
299
+
300
+ # The spelling maps. Both readers fold the sentence before they read it, and the physics language is
301
+ # not case free: the volt is ``V`` and the speed is ``v``, the force is ``F`` and the gram is ``g``.
302
+ # So a slot value arrives in a case the physics topology would refuse, and the printer puts the
303
+ # spelling of the physics language back: a translation of spelling, not of content, and the only
304
+ # place where the stratum is allowed to change a letter.
305
+ #
306
+ # One letter is genuinely lost on the way. ``p`` reaches the stratum folded from both the momentum
307
+ # ``p`` and the power ``P``, and the stratum prints the momentum, because that is the one the physics
308
+ # language writes in lower case. Writing the word ("power") is how a user keeps the distinction, and
309
+ # the README of this folder says so.
310
+ _UNIT_FORMS = {name.lower(): name for name in sorted(PHYSICS_UNITS)}
311
+ _SYMBOL_FORMS: Dict[str, str] = {}
312
+ for _name in sorted(PHYSICS_SYMBOLS, key=lambda word: (word.lower(), not word.islower())):
313
+ _SYMBOL_FORMS.setdefault(_name.lower(), _name)
314
+
315
+ _WORD = re.compile(r"[A-Za-z]+")
316
+
317
+
318
+ def _respell(text: str, forms: Dict[str, str]) -> str:
319
+ """Rewrite every word of a slot value in the spelling the physics topology expects."""
320
+ return _WORD.sub(lambda match: forms.get(match.group(0), match.group(0)), text)
321
+
322
+
323
+ def normalize_unit(text: str) -> str:
324
+ """The unit expression of a slot, respelled as the physics language writes it."""
325
+ return _respell(tidy(text), _UNIT_FORMS)
326
+
327
+
328
+ def normalize_symbol(text: str) -> str:
329
+ """The symbol list of a slot, respelled and printed with one space after every comma."""
330
+ return ", ".join(_respell(part.strip(), _SYMBOL_FORMS) for part in text.split(","))
331
+
332
+
333
+ # Inside the term of an audit a word names a quantity, so the symbol spelling wins where a letter is
334
+ # both a symbol and a unit: the physics parser of an equation reads ``m`` as the length, and the
335
+ # unit table is not consulted there.
336
+ _FORMULA_FORMS: Dict[str, str] = dict(_UNIT_FORMS)
337
+ _FORMULA_FORMS.update(_SYMBOL_FORMS)
338
+
339
+
340
+ def _slot_spelling(name: str, value: str) -> str:
341
+ """A slot value in the spelling the physics topology expects, by the shape of the slot."""
342
+ if name in ("U", "V"):
343
+ return normalize_unit(value)
344
+ if name in ("T", "S"):
345
+ return normalize_symbol(value)
346
+ if name == "F":
347
+ return _respell(tidy(value), _FORMULA_FORMS)
348
+ return tidy(value)
349
+
350
+
351
+ _NOT_PHYSICS_CHARACTER = re.compile(r"[^A-Za-z0-9\s+\-*/^()\[\]<>=!|,.;]")
352
+ _PHYSICS_WORD = re.compile(r"[A-Za-z]+")
353
+
354
+
355
+ def direct(text: str) -> Optional[Dict[str, Any]]:
356
+ """A sentence already written in the physics language, or ``None``.
357
+
358
+ The direct mode is the only way a user reaches the kinds the reading layer does not cover, and
359
+ the only way an untranslated sentence reaches the physics topology: it fires only when the first
360
+ word is a command of the physics language, every other word is a word of that language or a one
361
+ letter symbol, and no character outside its alphabet appears. Nothing is translated here, and
362
+ the sentence is shown to the user as it arrived.
363
+ """
364
+ cleaned = tidy(text)
365
+ if not cleaned or _NOT_PHYSICS_CHARACTER.search(cleaned):
366
+ return None
367
+ words = _PHYSICS_WORD.findall(cleaned)
368
+ if not words or words[0].lower() not in PHYSICS_COMMANDS:
369
+ return None
370
+ for word in words[1:]:
371
+ if len(word) > 1 and word not in PHYSICS_WORDS and word.lower() not in PHYSICS_WORDS:
372
+ return None
373
+ if not balanced(cleaned):
374
+ return None
375
+ return {"mode": "direct", "kind": words[0].lower(), "math": cleaned, "slots": {}}
lgphysstratum/compare.py ADDED
@@ -0,0 +1,259 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The equivalence of the two readings: do the two readers mean the same problem?
2
+
3
+ Reader A and reader B reach their sentence of the physics language by different routes -- surface
4
+ patterns and marker frames -- and the topology only trusts the pair when the two sentences are the
5
+ same problem. Textual identity is the easy case. The interesting case is two *different* texts that
6
+ denote one problem, and the only honest way to settle it is to ask the owner of the language, which
7
+ is what the physics layer itself does between its two readers.
8
+
9
+ The account of the physics language is **not reimplemented here**. The physics bundle owns its
10
+ parser and its canonical rendering (:envvar:`LGPHYSSTRATUM_PHYSICS_ROOT`, sibling folder ``physics``
11
+ by default), and a second copy of it inside the reading layer would be a third place where the
12
+ meaning of a physical sentence could be wrong without anyone noticing. So this module loads the
13
+ bundle, asks it to parse both sentences, and compares the canonical text the bundle itself prints:
14
+ two readings whose trees are the same tree are one problem.
15
+
16
+ What travels as SMT2 is the part that is genuinely arithmetic: the numbers of the two readings,
17
+ pinned to declared reals and compared item by item. The physics bundle checks its laws on exact
18
+ rationals in its own units module, not as one SMT program per problem, so a claim about the
19
+ *meaning* of a physical sentence is not something this stratum may hand to Z3 and call a proof.
20
+ Two limits follow, and both are limits, not shortcuts:
21
+
22
+ * a sentence the bundle will not parse is reported ``unknown`` and the session treats it as a
23
+ dispute: the reading layer would rather abstain than assume two texts are equal;
24
+ * the SMT claim of this module is *about the readings*, never about the user's problem. The problem
25
+ itself is never decided here: the sentence is handed to the physics layer, whose verdict is shown
26
+ as it arrived.
27
+ """
28
+
29
+ import sys
30
+ from typing import Any, Dict, List, Optional, Tuple
31
+
32
+ from . import canonical, invoker, segment
33
+
34
+ _physics = None
35
+ _PHYSICS_LOOKUP_ERROR: Optional[str] = None
36
+
37
+
38
+ def _physics_modules() -> Tuple[Any, Any, Any, Optional[str]]:
39
+ """The physics bundle's parser, tree printer and solver, or the reason they are absent."""
40
+ global _physics, _PHYSICS_LOOKUP_ERROR
41
+ if _physics is not None:
42
+ return _physics[0], _physics[1], _physics[2], None
43
+ if _PHYSICS_LOOKUP_ERROR is not None:
44
+ return None, None, None, _PHYSICS_LOOKUP_ERROR
45
+ root = invoker.physics_root()
46
+ if not (root / "lgphys").is_dir():
47
+ _PHYSICS_LOOKUP_ERROR = "no lgphys package under %s" % root
48
+ return None, None, None, _PHYSICS_LOOKUP_ERROR
49
+ text = str(root)
50
+ if text not in sys.path:
51
+ sys.path.insert(0, text)
52
+ try:
53
+ # The import of the physics bundle is the point of this module: one owner of the language.
54
+ from lgphys import parse_a, smt, tree # noqa: PLC0415
55
+ except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently
56
+ _PHYSICS_LOOKUP_ERROR = "the physics bundle could not be imported: %s" % type(exc).__name__
57
+ return None, None, None, _PHYSICS_LOOKUP_ERROR
58
+ _physics = (parse_a, tree, smt)
59
+ return _physics[0], _physics[1], _physics[2], None
60
+
61
+
62
+ ONTOLOGY = "(set-option :timeout 8000)\n"
63
+
64
+
65
+ def smt_referee(decls: List[str], asserts: List[str]) -> str:
66
+ """Run the referee of the physics layer over one claim, the way the orchestrator does each turn.
67
+
68
+ The same code answers here and in the physics bundle, so an envelope that this stratum writes is
69
+ checked by the solver the project already trusts; the stratum adds no second referee.
70
+ """
71
+ _parser, _tree, smt, _reason = _physics_modules()
72
+ if smt is None:
73
+ return "unknown"
74
+ return str(smt.referee(ONTOLOGY, list(decls), list(asserts)))
75
+
76
+
77
+ def numbers(text: str) -> List[str]:
78
+ """Every number written in a sentence, in order, digits normalised."""
79
+ return segment.numeric_literals(text)
80
+
81
+
82
+ def sorted_numbers(text: str) -> List[str]:
83
+ """The same numbers ordered by value, so a reordering of slots is not read as a change."""
84
+ return sorted(numbers(text), key=lambda value: (float(value), value))
85
+
86
+
87
+ def formalize(sentence: str) -> Optional[str]:
88
+ """The canonical text the physics bundle prints for one sentence, or ``None``."""
89
+ parse_a, tree, _smt, _reason = _physics_modules()
90
+ if parse_a is None:
91
+ return None
92
+ try:
93
+ return str(tree.canon(parse_a.parse(sentence)))
94
+ except Exception: # noqa: BLE001 - a sentence the bundle rejects is a sentence to report
95
+ return None
96
+
97
+
98
+ def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]:
99
+ """The slots one reading actually filled, in the order the physics language prints them."""
100
+ kind = str(reading.get("kind", ""))
101
+ slots = reading.get("slots") or {}
102
+ if kind not in canonical.TEMPLATES:
103
+ return ()
104
+ return tuple(name for name in canonical.slots_for(kind) if str(slots.get(name, "")).strip())
105
+
106
+
107
+ def _number_claim(left: str, right: str) -> Tuple[List[str], List[str], str, str, Any]:
108
+ """SMT2 for ``the two readings carry different numbers``, and what the solver says.
109
+
110
+ The declarations and the assertion are one plain SMT2 program: for each position, two reals
111
+ pinned to the two literals, and the negation of their equality. Unsatisfiable means the two
112
+ readings carry the same numbers under every assignment. The program is what travels in the
113
+ envelope, so the referee of the orchestrator re-runs exactly this query and cannot be told
114
+ something else.
115
+ """
116
+ first = sorted_numbers(left)
117
+ second = sorted_numbers(right)
118
+ if len(first) != len(second):
119
+ return [], ["(assert false)"], "unsat", "different", None
120
+ decls: List[str] = []
121
+ asserts: List[str] = []
122
+ names: List[str] = []
123
+ for index, (value, other) in enumerate(zip(first, second)):
124
+ name = "eq_%d" % index
125
+ decls.append("(declare-const %sa Real)" % name)
126
+ decls.append("(declare-const %sb Real)" % name)
127
+ asserts.append("(assert (= %sa %s))" % (name, value))
128
+ asserts.append("(assert (= %sb %s))" % (name, other))
129
+ asserts.append("(assert (not (= %sa %sb)))" % (name, name))
130
+ names = names + ["%sa" % name, "%sb" % name]
131
+ _parser, _tree, smt, _reason = _physics_modules()
132
+ if smt is None:
133
+ return decls, asserts, "unknown", "unknown", None
134
+ status = str(smt.check(decls, asserts))
135
+ if status == "unsat":
136
+ return decls, asserts, "unsat", "same_numbers", None
137
+ if status == "sat":
138
+ model = smt.solve_values(decls, asserts, names)
139
+ return decls, asserts, "sat", "different", ({key: str(value) for key, value in model.items()})
140
+ return decls, asserts, "unknown", "unknown", None
141
+
142
+
143
+ def equivalence(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:
144
+ """Compare two readings: one verdict, the SMT claim behind it, and what differs."""
145
+ left = canonical.tidy(str(a.get("math", "")))
146
+ right = canonical.tidy(str(b.get("math", "")))
147
+ detail: List[str] = []
148
+ if sorted_numbers(left) != sorted_numbers(right):
149
+ detail.append("numbers %s vs %s" % (",".join(sorted_numbers(left)), ",".join(sorted_numbers(right))))
150
+
151
+ if a.get("kind") != b.get("kind"):
152
+ detail.append("kinds %s vs %s" % (a.get("kind"), b.get("kind")))
153
+ return {"same": False, "why": "kind", "left": left, "right": right, "detail": detail,
154
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
155
+ if variant_of(a) != variant_of(b):
156
+ detail.append("slots %s vs %s" % (",".join(variant_of(a)), ",".join(variant_of(b))))
157
+ return {"same": False, "why": "variant", "left": left, "right": right, "detail": detail,
158
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
159
+
160
+ if left and left == right:
161
+ return {"same": True, "why": "text", "left": left, "right": right, "detail": detail,
162
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None}
163
+
164
+ _parser, _tree, _smt, reason = _physics_modules()
165
+ first, second = formalize(left), formalize(right)
166
+ if first is None or second is None:
167
+ note = reason or "the physics bundle does not read one of the two sentences"
168
+ detail.append(note)
169
+ return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail,
170
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None,
171
+ "note": note}
172
+ if first == second:
173
+ # Two different wordings, one tree: the bundle itself says they are the same problem.
174
+ return {"same": True, "why": "tree", "left": first, "right": second, "detail": detail,
175
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None}
176
+
177
+ decls, assertions, claimed, label, model = _number_claim(first, second)
178
+ if claimed == "unknown":
179
+ detail.append("the solver gave no answer about the numbers of the two readings")
180
+ if label == "different":
181
+ detail.append("two readings that carry different numbers")
182
+ return {"same": False, "why": "smt", "left": first, "right": second, "detail": detail,
183
+ "declarations": decls, "assertions": assertions, "claimed": claimed, "model": model}
184
+ detail.append("two sentences the physics bundle prints differently")
185
+ return {"same": False, "why": "structure", "left": first, "right": second, "detail": detail,
186
+ "declarations": decls, "assertions": assertions, "claimed": claimed, "model": model}
187
+
188
+
189
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
190
+ """Whether the reading kept every number the user wrote, and the SMT claim that says so."""
191
+ wrote = sorted_numbers(question)
192
+ kept = sorted_numbers(str(reading.get("math", "")))
193
+ decls, asserts = elementwise(wrote, kept, "keep")
194
+ ok = wrote == kept
195
+ return {
196
+ "ok": ok,
197
+ "wrote": wrote,
198
+ "kept": kept,
199
+ "missing": [value for value in wrote if value not in kept],
200
+ "added": [value for value in kept if value not in wrote],
201
+ "declarations": decls,
202
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
203
+ "claimed": "sat" if ok else "unsat",
204
+ }
205
+
206
+
207
+ def elementwise(left: List[str], right: List[str], prefix: str) -> Tuple[List[str], List[str]]:
208
+ """SMT2 declarations and assertions saying two lists of numbers are equal, item by item."""
209
+ if len(left) != len(right):
210
+ return [], ["(assert false)"]
211
+ decls: List[str] = []
212
+ asserts: List[str] = []
213
+ for index, (first, second) in enumerate(zip(left, right)):
214
+ name = "%s_%d" % (prefix, index)
215
+ decls.append("(declare-const %sa Real)" % name)
216
+ decls.append("(declare-const %sb Real)" % name)
217
+ asserts.append("(assert (= %sa %s))" % (name, first))
218
+ asserts.append("(assert (= %sb %s))" % (name, second))
219
+ asserts.append("(assert (= %sa %sb))" % (name, name))
220
+ return decls, asserts
221
+
222
+
223
+ def agrees_with_physics(reading: Dict[str, Any], physics_verdict: Dict[str, Any]) -> bool:
224
+ """Did the physics layer solve the sentence the readers agreed on?
225
+
226
+ The physics layer echoes the problem it understood. That echo is an independent channel: a node
227
+ standing between the readers and the layer can rewrite its own record, but it cannot move the
228
+ echo without moving numbers that were counted upstream. The comparison is on the canonical text
229
+ of the bundle, because the layer prints spaces around operators and this stratum does not.
230
+ """
231
+ echo = canonical.tidy(str(physics_verdict.get("problem_physics", "")))
232
+ agreed = canonical.tidy(str(reading.get("math", "")))
233
+ if not agreed or not echo:
234
+ return False
235
+ if echo == agreed:
236
+ return sorted_numbers(echo) == sorted_numbers(agreed)
237
+ left, right = formalize(echo), formalize(agreed)
238
+ if left is None or right is None:
239
+ return False
240
+ return left == right and sorted_numbers(left) == sorted_numbers(right)
241
+
242
+
243
+ def assurance_of(comparison: Dict[str, Any], readings: List[Dict[str, Any]],
244
+ coverage: Optional[Dict[str, Any]] = None) -> int:
245
+ """Reading assurance: how much of the answer the *reading* of the sentence warrants.
246
+
247
+ The scale is the one the physics layer uses, zero to two, and this function only ever lowers it:
248
+ two readings that agree and kept every number reach level two, a single reader reaches level
249
+ one, and no reading path reaches above the layer, because reading a sentence written in a human
250
+ language is never the last word -- and the assurance the user sees is the minimum of the two.
251
+ """
252
+ present = [reading for reading in readings if reading.get("math")]
253
+ if not present:
254
+ return 0
255
+ if coverage is not None and not coverage.get("ok", False):
256
+ return 0
257
+ if len(present) < 2:
258
+ return 1
259
+ return 2 if comparison.get("same") else 0
lgphysstratum/corpus.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The gold set of the stratum: sentences in six varieties and what each one must produce.
2
+
3
+ A corpus item is one line of JSON: a language, a question written by a speaker, and the expectation.
4
+ The expectation is deliberately narrow, because the stratum is not a solver -- it is the layer that
5
+ decides *which* sentence to hand to the solver and how much confidence to attach to it:
6
+
7
+ {"id": "it-convert-1", "lang": "it", "question": "converti 3 chilometri in metri",
8
+ "expect": {"state": "AGREED", "sentence": "convert 3 km to m", "min_assurance": 1}}
9
+
10
+ ``state`` is the only mandatory key. ``sentence`` is compared after tidying, and when the tidy texts
11
+ differ the two are handed to the parser of the physics bundle, which owns the canonical spelling of
12
+ its own sentences: a gold line written with the spacing of the layer and a reading written without it
13
+ are one sentence. ``answer_contains`` is a substring test on the answer the physics layer returned,
14
+ and ``max_assurance`` is the ceiling a negative item insists on: an item that ends in DISPUTED,
15
+ AMBIGUOUS or NOT COVERED must show no answer at all.
16
+
17
+ The corpus is the only place a shared translation error can surface: the two readers agree by
18
+ construction whenever both descriptions of a language carry the same mistake, so the gold sentences
19
+ are written from the language and not from the lexicon.
20
+ """
21
+
22
+ import json
23
+ from pathlib import Path
24
+ from typing import Any, Dict, List, Optional
25
+
26
+ from . import canonical, compare, pipeline
27
+
28
+ ROOT = Path(__file__).resolve().parents[1]
29
+ PATH = ROOT / "problems" / "corpus.jsonl"
30
+
31
+
32
+ def load(path: Optional[Path] = None) -> List[Dict[str, Any]]:
33
+ """The corpus, one dictionary per line, skipping blank lines and comments."""
34
+ where = Path(path) if path else PATH
35
+ items: List[Dict[str, Any]] = []
36
+ for line in where.read_text(encoding="utf-8").splitlines():
37
+ text = line.strip()
38
+ if not text or text.startswith("#"):
39
+ continue
40
+ items.append(json.loads(text))
41
+ return items
42
+
43
+
44
+ def _same_sentence(got: str, wanted: str) -> bool:
45
+ """Two spellings of one sentence of the physics language?"""
46
+ if canonical.tidy(got) == canonical.tidy(wanted):
47
+ return True
48
+ first, second = compare.formalize(got), compare.formalize(wanted)
49
+ return first is not None and first == second
50
+
51
+
52
+ def grade(item: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]:
53
+ """Compare one corpus expectation against one run, and say exactly what did not match."""
54
+ expect = item.get("expect") or {}
55
+ final = result.get("final") or {}
56
+ problems: List[str] = []
57
+ state = str(final.get("state", ""))
58
+ if expect.get("state") and expect["state"] != state:
59
+ problems.append("state %s, expected %s" % (state, expect["state"]))
60
+ if "sentence" in expect:
61
+ got = str((result.get("dossier") or {}).get("sent", ""))
62
+ if not _same_sentence(got, str(expect["sentence"])):
63
+ problems.append("sentence %r, expected %r" % (canonical.tidy(got), canonical.tidy(expect["sentence"])))
64
+ if "answer_contains" in expect:
65
+ answer = str(final.get("answer", ""))
66
+ if str(expect["answer_contains"]) not in answer:
67
+ problems.append("answer %r does not contain %r" % (answer, expect["answer_contains"]))
68
+ if "min_assurance" in expect and int(final.get("assurance", 0) or 0) < int(expect["min_assurance"]):
69
+ problems.append("assurance %s below %s" % (final.get("assurance"), expect["min_assurance"]))
70
+ if "max_assurance" in expect and int(final.get("assurance", 0) or 0) > int(expect["max_assurance"]):
71
+ problems.append("assurance %s above %s" % (final.get("assurance"), expect["max_assurance"]))
72
+ if expect.get("no_answer") and final.get("answer"):
73
+ problems.append("an answer was shown for an item that must show none")
74
+ if expect.get("referee_clean") and any(record["claimed"] != record["referee"]
75
+ for record in result.get("records") or []):
76
+ problems.append("a claim did not survive the referee")
77
+ return {"id": item.get("id", "?"), "lang": item.get("lang", "?"), "state": state,
78
+ "assurance": final.get("assurance", 0), "ok": not problems, "problems": problems}
79
+
80
+
81
+ def outcome(item: Dict[str, Any], call_physics: bool = True,
82
+ fault_spec: Optional[List[str]] = None) -> Dict[str, Any]:
83
+ """Run one corpus item in memory and grade it."""
84
+ result = pipeline.ask(str(item.get("question", "")), str(item.get("lang", "")),
85
+ fault_spec=fault_spec, call_physics=call_physics)
86
+ verdict = grade(item, result)
87
+ verdict["records"] = result["records"]
88
+ verdict["dossier"] = result["dossier"]
89
+ verdict["reply"] = result["reply"]
90
+ return verdict
lgphysstratum/coverage.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the reading kept, and what the physics layer says it solved.
2
+
3
+ Two bookkeeping checks stand between the readers and the answer, and both are stated as SMT2 so
4
+ the referee of the orchestrator recomputes them instead of trusting a node:
5
+
6
+ * :func:`keeps` -- every number the user wrote is still in the sentence of the physics language, and
7
+ no number appeared there that the user did not write. A reader that merged two slots or shifted a
8
+ digit changes that multiset, and a sorted element by element equality over declared reals says
9
+ so;
10
+ * :func:`echo_matches` -- the physics layer echoes the problem it understood, and the echo is
11
+ compared with the sentence the readers agreed on. The echo is an independent channel: a node
12
+ standing between the readers and the layer can rewrite its own record, but it cannot move the
13
+ echo without moving numbers that were counted upstream.
14
+
15
+ Neither check decides physics. They count tokens, they hand the counting to a solver so that a node
16
+ claiming the numbers were kept is checked against that claim, and the identity of two sentences is
17
+ settled by the parser of the bundle, which owns that language.
18
+ """
19
+
20
+ from typing import Any, Dict, List, Optional
21
+
22
+ from . import canonical, compare
23
+
24
+
25
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
26
+ """Whether one reading kept every number the user wrote, with the SMT claim that says so."""
27
+ return compare.keeps(reading, question)
28
+
29
+
30
+ def echo_numbers(physics_verdict: Dict[str, Any]) -> List[str]:
31
+ """The numbers of the problem the physics layer says it solved, ordered by value."""
32
+ return compare.sorted_numbers(canonical.tidy(str(physics_verdict.get("problem_physics", ""))))
33
+
34
+
35
+ def echo_matches(reading: Dict[str, Any], physics_verdict: Dict[str, Any]) -> bool:
36
+ """Did the physics layer solve the sentence the readers agreed on?
37
+
38
+ A verdict that names no sentence at all -- the backend was off, or the physics layer could not
39
+ be started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls
40
+ to zero because there is no physics assurance to take the minimum with, but nothing here may be
41
+ read as tampering. Only an echo that names a sentence and names a different one is a mismatch.
42
+ """
43
+ if not str(physics_verdict.get("problem_physics", "")).strip():
44
+ return True
45
+ return compare.agrees_with_physics(reading, physics_verdict)
46
+
47
+
48
+ def coverage_claim(question: str, readings: List[Dict[str, Any]],
49
+ physics_verdict: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
50
+ """One SMT2 claim tying the user's numbers to the readings and, when known, to the echo.
51
+
52
+ Every reading that produced a sentence has to carry the user's numbers, and once the physics
53
+ layer has answered its echo has to carry them too. The assertion set is the conjunction of those
54
+ element equalities: satisfiable exactly when all of them hold, which is what the referee checks
55
+ against the status the node claimed.
56
+ """
57
+ wrote = compare.sorted_numbers(question)
58
+ readings_present = [reading for reading in readings if reading.get("math")]
59
+ steps = [keeps(reading, question) for reading in readings_present]
60
+ ok = all(step["ok"] for step in steps)
61
+ decls: List[str] = []
62
+ asserts: List[str] = []
63
+ for step in steps:
64
+ decls = decls + list(step["declarations"])
65
+ asserts = asserts + list(step["assertions"])
66
+ if physics_verdict is not None:
67
+ echo = echo_numbers(physics_verdict)
68
+ decls2, asserts2 = compare.elementwise(wrote, echo, "echo")
69
+ decls = decls + decls2
70
+ asserts = asserts + asserts2
71
+ ok = ok and echo == wrote
72
+ if not wrote:
73
+ # Nothing was written, so there is nothing to keep: the claim is the empty conjunction,
74
+ # which is satisfiable, and the node says sat.
75
+ return {"ok": ok, "wrote": [], "kept": [], "declarations": [], "assertions": ["(assert (= 1 1))"],
76
+ "claimed": "sat"}
77
+ return {
78
+ "ok": ok,
79
+ "wrote": wrote,
80
+ "kept": [step["kept"] for step in steps],
81
+ "declarations": decls,
82
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
83
+ "claimed": "sat" if ok else "unsat",
84
+ }
85
+
86
+
87
+ def summary(step: Dict[str, Any]) -> Dict[str, Any]:
88
+ """The part of a coverage step that belongs in the dossier and in front of the user."""
89
+ return {
90
+ "ok": step.get("ok", False),
91
+ "wrote": step.get("wrote", []),
92
+ "missing": step.get("missing", []),
93
+ "added": step.get("added", []),
94
+ }
lgphysstratum/decide.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The decision: pure, and never raising anything.
2
+
3
+ One function, no I/O: given what the readers understood, what the equivalence node proved, what
4
+ the coverage node counted and what the physics layer answered, it states the state of the session,
5
+ the assurance the user sees, and whether an answer may be shown at all. The arbiter runs it, the
6
+ tools run it again on the transcript, and a test pins it, so the same rules are checked in three
7
+ places -- the same shape the physics layer uses for its own ``decide``.
8
+
9
+ The rule the whole module exists to enforce:
10
+
11
+ assurance(shown) = min(assurance(physics), assurance(reading))
12
+
13
+ and ``assurance(reading)`` is at most two, which is also the highest level the physics layer ever
14
+ reaches: no chain of this project adds a third witness on top of a physical statement, because a
15
+ law of physics is not proved by a second formalizer but by the agreement of two independent
16
+ routes. The stratum therefore never reports more than the layer, and a reading in a human language
17
+ carries one more fallible step than a sentence the physics layer formalizes itself. A verdict is
18
+ never raised by the stratum; the only direction it can move is down, and the adversary node writes
19
+ the negation of that inequality as SMT2 so the referee of the orchestrator refutes it.
20
+
21
+ The states, which are the eight the lexicon of every covered language names:
22
+
23
+ =========== ===================================================================
24
+ AGREED both readers produced the same sentence, and the physics layer solved it
25
+ PASSTHROUGH the sentence was already written in the physics language: nothing was translated
26
+ SINGLE one reader understood the sentence and the other abstained: the physics layer was
27
+ consulted, and the assurance is capped by the missing witness
28
+ DISPUTED the two readers produced different sentences, or a reading lost a number: the
29
+ physics layer is not consulted at all
30
+ AMBIGUOUS the sentence announces more than one kind of problem: the user has to choose
31
+ NOT COVERED neither reader found anything: the language does not say this in a covered way
32
+ TAMPERED the physics layer says it solved something other than the agreed sentence
33
+ NONE no reading was even attempted
34
+ =========== ===================================================================
35
+ """
36
+
37
+ from typing import Any, Dict, List, Optional
38
+
39
+ AMBIGUOUS_REASONS = ("multiple", "two_verbs")
40
+
41
+ STATES = ("AGREED", "PASSTHROUGH", "SINGLE", "DISPUTED", "AMBIGUOUS", "NOT COVERED", "TAMPERED", "NONE")
42
+
43
+ # The reading assurance of each state, on the scale the physics layer uses. Two is the top of this
44
+ # scale, and the physics layer stands on the same rung: what raises a verdict above it would be a
45
+ # third kind of witness, and this project has none for physics.
46
+ CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0,
47
+ "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0}
48
+
49
+ # The statuses that answer the question. A refusal, a guard block and an abstention are the layer
50
+ # explaining why it will not answer, and they carry no answer text at the level of the stratum:
51
+ # the state of the layer is reported, the sentence of the layer is not.
52
+ ANSWERING = ("VERIFIED", "SINGLE_PROVER")
53
+
54
+
55
+ def reader_notes(readings: List[Dict[str, Any]]) -> List[str]:
56
+ """The reason keys the abstaining readers left behind, in reader order."""
57
+ notes: List[str] = []
58
+ for reading in readings:
59
+ for note in reading.get("notes") or []:
60
+ reason = note.get("reason") if isinstance(note, dict) else str(note)
61
+ if reason and reason not in notes:
62
+ notes.append(reason)
63
+ return notes
64
+
65
+
66
+ def state_of(readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
67
+ coverage: Optional[Dict[str, Any]], physics_verdict: Optional[Dict[str, Any]],
68
+ direct: Optional[Dict[str, Any]] = None, echo_ok: Optional[bool] = None) -> str:
69
+ """The state of a session, from the evidence the nodes collected."""
70
+ present = [reading for reading in readings if reading.get("math")]
71
+ notes = reader_notes(readings)
72
+ if direct is not None:
73
+ return "PASSTHROUGH"
74
+ if physics_verdict is not None and echo_ok is False:
75
+ return "TAMPERED"
76
+ if len(present) >= 2:
77
+ if comparison is None:
78
+ return "DISPUTED"
79
+ if coverage is not None and not coverage.get("ok", False):
80
+ return "DISPUTED"
81
+ return "AGREED" if comparison.get("same") else "DISPUTED"
82
+ if len(present) == 1:
83
+ # A lone witness has to hold the numbers the person wrote: a reading that lost one is not a
84
+ # weaker reading of the same problem, it is a different problem, and the ceiling of SINGLE
85
+ # is not a licence to answer it. This is the case the ablation of the topology uncovered:
86
+ # with one reader there is no second sentence to compare against, so the count of literals
87
+ # is what stands between a shifted number and an answer the gold does not accept.
88
+ if coverage is not None and not coverage.get("ok", False):
89
+ return "DISPUTED"
90
+ return "SINGLE"
91
+ if any(reason in AMBIGUOUS_REASONS for reason in notes):
92
+ return "AMBIGUOUS"
93
+ return "NOT COVERED"
94
+
95
+
96
+ def reasons_for(state: str, readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
97
+ coverage: Optional[Dict[str, Any]], physics_verdict: Optional[Dict[str, Any]],
98
+ asked: bool = True) -> List[str]:
99
+ """The reason keys that explain a state, in the order a reader should read them."""
100
+ out: List[str] = []
101
+ for reason in reader_notes(readings):
102
+ if reason not in out:
103
+ out.append(reason)
104
+ if state == "DISPUTED":
105
+ if coverage is not None and not coverage.get("ok", False):
106
+ out.append("literal_count")
107
+ if comparison is not None and not comparison.get("same"):
108
+ out.append("disagree")
109
+ if comparison is not None and comparison.get("why") == "unknown":
110
+ out.append("physics_unknown")
111
+ if comparison is not None and comparison.get("why") == "smt" and comparison.get("model"):
112
+ if "disagree" not in out:
113
+ out.append("disagree")
114
+ if state == "TAMPERED":
115
+ out.append("boundary")
116
+ if physics_verdict is not None and physics_verdict.get("referee_mismatch"):
117
+ out.append("referee")
118
+ if asked and physics_verdict is not None and physics_verdict.get("status") == "UNKNOWN":
119
+ out.append("physics_unknown")
120
+ if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"):
121
+ out.append("no_math")
122
+ return out
123
+
124
+
125
+ def decide(dossier: Dict[str, Any]) -> Dict[str, Any]:
126
+ """One verdict for one session, with the assurance the user is allowed to see."""
127
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
128
+ if dossier.get("reading_direct"):
129
+ readings = [dossier["reading_direct"]]
130
+ comparison = dossier.get("compare")
131
+ coverage = dossier.get("coverage")
132
+ physics_verdict = dossier.get("physics")
133
+ direct = dossier.get("reading_direct")
134
+ echo_ok = dossier.get("echo_ok")
135
+
136
+ state = state_of(readings, comparison, coverage, physics_verdict, direct, echo_ok)
137
+ ceiling = CEILING[state]
138
+ assurance = 0
139
+ answer_shown = ""
140
+ if state in ("AGREED", "SINGLE", "PASSTHROUGH") and physics_verdict is not None:
141
+ # The physics layer answers at level two when its readers and its provers agree, at level
142
+ # one when a lone prover stands, and at level zero when it abstains or says UNKNOWN. A
143
+ # refusal stops the answer at zero too: the layer explained itself, it did not answer.
144
+ if physics_verdict.get("status") in ANSWERING:
145
+ assurance = min(ceiling, int(physics_verdict.get("assurance", 0) or 0))
146
+ else:
147
+ assurance = 0
148
+ answer_shown = physics_verdict.get("answer_text") or ""
149
+ if assurance == 0:
150
+ answer_shown = ""
151
+ reasons = reasons_for(state, readings, comparison, coverage, physics_verdict,
152
+ asked=bool(str(dossier.get("sent") or "")))
153
+ return {
154
+ "state": state,
155
+ "assurance": assurance,
156
+ "ceiling": ceiling,
157
+ "physics_assurance": int((physics_verdict or {}).get("assurance", 0) or 0),
158
+ "physics_status": (physics_verdict or {}).get("status"),
159
+ "answer": answer_shown,
160
+ "reasons": reasons,
161
+ "consulted_physics": physics_verdict is not None,
162
+ }
163
+
164
+
165
+ def raise_assurance(final: Dict[str, Any], claimed: int) -> Dict[str, Any]:
166
+ """The arbiter fault: an assurance above what the evidence supports (experiments only)."""
167
+ out = dict(final)
168
+ out["assurance"] = max(int(final.get("assurance", 0) or 0), int(claimed))
169
+ out["claimed_above_evidence"] = True
170
+ return out
lgphysstratum/faults.py ADDED
@@ -0,0 +1,145 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fault injection for the redundancy experiments (tools/ablation.py).
2
+
3
+ A fault is "<agent>:<kind>". Faults are off unless LGPHYSSTRATUM_FAULTS (or :func:`configure`) names
4
+ them, so production runs never take these branches. ``FIRED`` records the faults that really changed
5
+ something, which separates dormant faults from activated ones.
6
+
7
+ The faults of the reading layer are chosen so that the damaged sentence is still a *grammatical*
8
+ sentence of the physics language: a reader that shifts a number, copies the source unit into the
9
+ target unit or loses one quantity from a dimensional analysis must produce something the physics
10
+ layer will happily answer. Otherwise the fault would be caught by the layer refusing to parse, and
11
+ the experiment would measure nothing about the reading layer.
12
+
13
+ Catalogue
14
+ ---------
15
+ reader_a / reader_b : shift_number, same_units, drop_symbol
16
+ equivalence : rubber_stamp (declares the two readings equal without running the check)
17
+ coverage : rubber_stamp (declares every number kept without counting them)
18
+ boundary : tamper_physics (asks the physics layer a different question, reports the
19
+ agreed one)
20
+ adversary : rubber_stamp (skips its own recomputation of the assurance bound)
21
+ arbiter : force_assurance (raises the assurance above what the evidence supports)
22
+ """
23
+
24
+ import os
25
+ import re
26
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
27
+
28
+ _ACTIVE: Set[str] = set()
29
+ FIRED: List[str] = []
30
+
31
+ READER_FAULTS = ["shift_number", "same_units", "drop_symbol"]
32
+
33
+ CATALOG = {
34
+ "reader_a": READER_FAULTS,
35
+ "reader_b": READER_FAULTS,
36
+ "equivalence": ["rubber_stamp"],
37
+ "coverage": ["rubber_stamp"],
38
+ "boundary": ["tamper_physics"],
39
+ "adversary": ["rubber_stamp"],
40
+ "arbiter": ["force_assurance"],
41
+ }
42
+
43
+ _NUMBER = re.compile(r"\d+(?:\.\d+)?")
44
+
45
+
46
+ def configure(spec: Optional[Iterable[str]]) -> None:
47
+ _ACTIVE.clear()
48
+ del FIRED[:]
49
+ if spec is None:
50
+ return
51
+ if isinstance(spec, str):
52
+ spec = [s for s in spec.split(",") if s.strip()]
53
+ for item in spec:
54
+ _ACTIVE.add(item.strip())
55
+
56
+
57
+ def from_env() -> None:
58
+ configure(os.environ.get("LGPHYSSTRATUM_FAULTS", ""))
59
+
60
+
61
+ def has(agent: str, kind: str) -> bool:
62
+ return "%s:%s" % (agent, kind) in _ACTIVE
63
+
64
+
65
+ def fire(agent: str, kind: str) -> None:
66
+ label = "%s:%s" % (agent, kind)
67
+ if label not in FIRED:
68
+ FIRED.append(label)
69
+
70
+
71
+ def fired(agent: str) -> List[str]:
72
+ return [item for item in FIRED if item.split(":", 1)[0] == agent]
73
+
74
+
75
+ # ---------------------------------------------------------------------------
76
+ # Reading mutations (reader faults)
77
+ # ---------------------------------------------------------------------------
78
+ def _slots_with_numbers(slots: Dict[str, str], order: List[str]) -> List[str]:
79
+ return [name for name in order if _NUMBER.search(slots.get(name, ""))]
80
+
81
+
82
+ def mutate_reading(agent: str, kind: str, slots: Dict[str, str],
83
+ order: List[str]) -> Tuple[Dict[str, str], bool]:
84
+ """Return a damaged copy of one reading, and whether anything was actually damaged.
85
+
86
+ ``order`` is the slot order of the form the reader chose, so the fault knows which slot a joint
87
+ is holding and which slots this kind of question can lose without the sentence stopping being a
88
+ sentence of the physics language.
89
+ """
90
+ from . import canonical
91
+
92
+ slots = dict(slots)
93
+ for kind_fault in CATALOG.get(agent, []):
94
+ if not has(agent, kind_fault):
95
+ continue
96
+ candidate = dict(slots)
97
+ if kind_fault == "shift_number":
98
+ numbered = _slots_with_numbers(candidate, order)
99
+ if not numbered:
100
+ continue
101
+ owner = numbered[0]
102
+ match = _NUMBER.search(candidate[owner])
103
+ if match is None:
104
+ continue
105
+ candidate[owner] = _NUMBER.sub(lambda m: str(_next_number(m.group(0))),
106
+ candidate[owner], count=1)
107
+ elif kind_fault == "same_units":
108
+ if not candidate.get("U") or not candidate.get("V"):
109
+ continue
110
+ candidate["V"] = candidate["U"]
111
+ elif kind_fault == "drop_symbol":
112
+ parts = [part.strip() for part in str(candidate.get("S", "")).split(",") if part.strip()]
113
+ if len(parts) < 2:
114
+ continue
115
+ candidate["S"] = ", ".join(parts[1:])
116
+ else:
117
+ continue
118
+ try:
119
+ canonical.print_math(kind, candidate)
120
+ except canonical.ReadingError:
121
+ continue
122
+ fire(agent, kind_fault)
123
+ return candidate, True
124
+ return slots, False
125
+
126
+
127
+ def _next_number(text: str) -> Any:
128
+ if "." in text:
129
+ return float(text) + 1.0
130
+ return int(text) + 1
131
+
132
+
133
+ # ---------------------------------------------------------------------------
134
+ # Sentence mutations (the boundary fault)
135
+ # ---------------------------------------------------------------------------
136
+ def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]:
137
+ """Change one number of a sentence of the physics language, leaving it grammatical."""
138
+ if not has(agent, "tamper_physics"):
139
+ return sentence, False
140
+ match = _NUMBER.search(sentence)
141
+ if match is None:
142
+ return sentence, False
143
+ damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():]
144
+ fire(agent, "tamper_physics")
145
+ return damaged, True
lgphysstratum/invoker.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The interface toward the physics layer: one subprocess call, no shared code.
2
+
3
+ The reading layer and the physics layer are separate topologies of the same orchestrator. This
4
+ module is the whole of their coupling: it starts ``tools/ask.py`` of the physics layer as a separate
5
+ process with the canonical sentence as its argument, asks for the machine readable outcome, and
6
+ copies that outcome. Nothing here imports a module of the physics layer, because a translation layer
7
+ that reaches inside the physics it consults is a translation layer that can silently change the
8
+ physics.
9
+
10
+ Two settings matter, and both are environment variables so no value is hardcoded in a second place:
11
+
12
+ ``LGPHYSSTRATUM_PHYSICS_ROOT`` the folder of the physics layer (default: ``physics``, sibling of
13
+ this bundle, which is ``datasets/physics`` inside the LingoLOGOS
14
+ repository)
15
+ ``LGPHYSSTRATUM_PHYSICS_BACKEND`` ``subprocess`` (default) or ``none``; ``none`` refuses to call and
16
+ is what the reading layer tests use, so they can check the reading
17
+ without starting a whole physics session
18
+
19
+ The one module that does reach inside the bundle is :mod:`lgphysstratum.compare`, and only to ask
20
+ the bundle how it prints its own sentences: the parser is the owner of the language, and a second
21
+ account of it in the reading layer would be a third place where a physical sentence could be wrong.
22
+ """
23
+
24
+ import json
25
+ import os
26
+ import subprocess
27
+ import sys
28
+ from pathlib import Path
29
+ from typing import Any, Dict
30
+
31
+ ROOT = Path(__file__).resolve().parents[1]
32
+ DEFAULT_TIMEOUT = 240
33
+
34
+
35
+ def physics_root() -> Path:
36
+ override = os.environ.get("LGPHYSSTRATUM_PHYSICS_ROOT", "").strip()
37
+ if override:
38
+ return Path(override)
39
+ return ROOT.parent / "physics"
40
+
41
+
42
+ def backend() -> str:
43
+ return (os.environ.get("LGPHYSSTRATUM_PHYSICS_BACKEND", "subprocess") or "subprocess").strip().lower()
44
+
45
+
46
+ def timeout_seconds() -> int:
47
+ try:
48
+ return max(5, int(os.environ.get("LGPHYSSTRATUM_PHYSICS_TIMEOUT", DEFAULT_TIMEOUT)))
49
+ except ValueError:
50
+ return DEFAULT_TIMEOUT
51
+
52
+
53
+ def unavailable(reason: str) -> Dict[str, Any]:
54
+ return {"ok": False, "error": reason, "status": "UNKNOWN", "assurance": 0, "answer": None,
55
+ "answer_text": "", "problem_physics": "", "reasons": [], "roads": [], "failures": [],
56
+ "detected": []}
57
+
58
+
59
+ def ask(sentence: str) -> Dict[str, Any]:
60
+ """Ask the physics layer one sentence of the physics language, and return its verdict unchanged."""
61
+ if backend() == "none":
62
+ return unavailable("the physics backend is disabled by LGPHYSSTRATUM_PHYSICS_BACKEND")
63
+ root = physics_root()
64
+ script = root / "tools" / "ask.py"
65
+ if not script.is_file():
66
+ return unavailable("no tools/ask.py under %s" % root)
67
+ try:
68
+ done = subprocess.run(
69
+ [sys.executable, str(script), "--json", sentence],
70
+ cwd=str(root), capture_output=True, timeout=timeout_seconds())
71
+ except subprocess.TimeoutExpired:
72
+ return unavailable("the physics layer did not answer within %d seconds" % timeout_seconds())
73
+ except OSError as exc:
74
+ return unavailable("the physics layer could not be started: %s" % exc)
75
+ text = done.stdout.decode("utf-8", "replace")
76
+ if done.returncode != 0 and not text.strip():
77
+ return unavailable("the physics layer exited with %d: %s"
78
+ % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200]))
79
+ return outcome(text, done.returncode)
80
+
81
+
82
+ def outcome(text: str, returncode: int = 0) -> Dict[str, Any]:
83
+ """Extract the verdict of a physics session from the JSON the physics layer printed."""
84
+ try:
85
+ parsed = json.loads(text)
86
+ except ValueError:
87
+ return unavailable("the physics layer printed something that is not JSON (exit %d)" % returncode)
88
+ final = parsed.get("final") if isinstance(parsed, dict) else None
89
+ if not isinstance(final, dict):
90
+ return unavailable("the physics layer printed no verdict (exit %d)" % returncode)
91
+ referee = parsed.get("referee") if isinstance(parsed.get("referee"), list) else []
92
+ mismatched = [entry for entry in referee
93
+ if isinstance(entry, dict) and entry.get("claimed") != entry.get("referee")]
94
+ status = str(final.get("status") or "UNKNOWN")
95
+ return {
96
+ "ok": status != "UNKNOWN",
97
+ "status": status,
98
+ "assurance": int(final.get("assurance", 0) or 0),
99
+ "answer": final.get("answer"),
100
+ "answer_text": final.get("answer_text") or "",
101
+ "problem_physics": final.get("problem") or "",
102
+ "reasons": list(final.get("reasons") or []),
103
+ "roads": list(final.get("roads") or []),
104
+ "failures": list(final.get("failures") or []),
105
+ "kind": final.get("kind"),
106
+ "delegate": final.get("delegate"),
107
+ "detected": list(final.get("detected") or []),
108
+ "referee_mismatch": len(mismatched),
109
+ "turns": parsed.get("turns"),
110
+ "error": None if status != "UNKNOWN" else "; ".join(final.get("reasons") or []) or "unknown",
111
+ }
lgphysstratum/lexicon.py ADDED
@@ -0,0 +1,453 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The lexicon of the six language varieties, and the two specs each language carries.
2
+
3
+ Every variety lives in one JSON file ``lexicon/<lang>.json`` and carries, for every sentence kind
4
+ the variety covers, **two** independent descriptions of the same surface:
5
+
6
+ ``patterns``
7
+ the surface patterns reader A matches (a slot string per accepted wording);
8
+ ``frames``
9
+ the marker frame reader B matches (which markers the sentence must carry, in which order).
10
+
11
+ On top of the two specs a variety carries ``tokens``: the words of that language that name a unit
12
+ or a quantity, each mapped to the token the physics language writes. ``metro`` and ``kilometro``
13
+ are Italian, ``m`` and ``km`` are physics, and this table is the only place where the two meet for
14
+ a *word*: the two readers use it and nothing else to decide that a word is mathematics.
15
+
16
+ This mirrors the physics topology, where the two readers share one written specification
17
+ (``nodes/*/grammar.gf``) and implement it twice. The consequence is the same and is stated in the
18
+ README: a translation error present in both descriptions of one language is invisible to the
19
+ topology, and only the gold sentences of the corpus can show it.
20
+
21
+ The data files are the object of study, not prose of this repository: they hold the words of six
22
+ languages, exactly as the physics bundle holds the unit tokens it studies.
23
+ """
24
+
25
+ import json
26
+ import os
27
+ import re
28
+ from typing import Any, Dict, List, Optional, Tuple
29
+
30
+ from . import canonical
31
+ from .segment import atomize, fold
32
+
33
+ BUNDLE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
34
+ LEXICON_DIR = os.path.join(BUNDLE, "lexicon")
35
+
36
+ # Marker names, the same in every variety. The variety supplies the words; the names are how
37
+ # the two readers and the canonical printer agree: ``to`` opens the target unit of a conversion,
38
+ # ``from`` opens the quantities a dimensional analysis starts from.
39
+ MARKERS = ("to", "from")
40
+
41
+ # A word run that is not in the lexicon is a coverage failure, unless the physics language itself
42
+ # writes it: a unit, a quantity symbol, a keyword of the circuit form.
43
+ PHYSICS_WORDS = canonical.PHYSICS_WORDS
44
+
45
+ # The characters that say "a single letter here is a symbol of the physics". Digits are not among
46
+ # them: Italian "da 0 a 2" puts the single letter a between two numbers, and there it is the joint
47
+ # of a conversion, not the acceleration the sentence is about.
48
+ OPERATOR_BEFORE = set("+-*/^=<>|([,")
49
+ OPERATOR_AFTER = set("+-*/^=<>|)]")
50
+
51
+ # The mnemonic names a data file may use for a connective, and what it prints as. A data file may
52
+ # also key a connective by the symbol itself; both spellings reach the same physics token.
53
+ CONNECTIVE_TEXT = {"times": "*", "over": "/", "plus": "+", "minus": "-",
54
+ "power": "^", "equals": "=", "list": ","}
55
+
56
+ _cache: Dict[str, Dict[str, Any]] = {}
57
+ _index_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
58
+ _stripped_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
59
+ _verb_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, ...]]] = {}
60
+ _group_cache: Dict[str, Dict[str, Tuple[str, ...]]] = {}
61
+ _token_cache: Dict[str, Dict[Tuple[str, ...], str]] = {}
62
+
63
+
64
+ def languages() -> List[str]:
65
+ """The language codes this bundle can read, in a stable order."""
66
+ return sorted(name[:-5] for name in os.listdir(LEXICON_DIR) if name.endswith(".json"))
67
+
68
+
69
+ def load(lang: str) -> Dict[str, Any]:
70
+ if lang not in _cache:
71
+ path = os.path.join(LEXICON_DIR, lang + ".json")
72
+ with open(path, "r", encoding="utf-8") as handle:
73
+ data = json.load(handle)
74
+ data["_code"] = lang
75
+ _cache[lang] = data
76
+ return _cache[lang]
77
+
78
+
79
+ def script(lang: str) -> str:
80
+ return load(lang).get("script", "latin")
81
+
82
+
83
+ def codes() -> List[str]:
84
+ return languages()
85
+
86
+
87
+ def kinds(lang: str) -> List[str]:
88
+ """The sentence kinds this variety covers."""
89
+ return sorted(load(lang).get("kinds", {}))
90
+
91
+
92
+ def supported_kinds() -> List[str]:
93
+ """The kinds at least one variety covers."""
94
+ seen = set()
95
+ for lang in languages():
96
+ seen.update(kinds(lang))
97
+ return sorted(seen)
98
+
99
+
100
+ def patterns(lang: str) -> Dict[str, List[str]]:
101
+ """Reader A's surface patterns per kind: ``{kind: [pattern, ...]}``."""
102
+ out = {}
103
+ for kind, spec in load(lang).get("kinds", {}).items():
104
+ out[kind] = list(spec.get("patterns", []))
105
+ return out
106
+
107
+
108
+ def frames(lang: str) -> Dict[str, Dict[str, Any]]:
109
+ """Reader B's marker frames per kind."""
110
+ out = {}
111
+ for kind, spec in load(lang).get("kinds", {}).items():
112
+ frame = spec.get("frame")
113
+ if frame is not None:
114
+ out[kind] = frame
115
+ return out
116
+
117
+
118
+ def verbs(lang: str) -> Dict[str, Tuple[Tuple[str, ...], ...]]:
119
+ """Every kind verb phrase of the variety, mapped to the kinds it announces.
120
+
121
+ One phrase announces more than one kind, and that is a fact of the language, not a defect of
122
+ the data: a verb that can open two forms keeps both of them here. Keeping the whole list is
123
+ what lets a reader try both forms of one sentence instead of silently taking the last kind in
124
+ the file.
125
+ """
126
+ out: Dict[str, Tuple[str, ...]] = {}
127
+ for kind, spec in load(lang).get("kinds", {}).items():
128
+ for verb in spec.get("verbs", []):
129
+ phrase = fold(verb)
130
+ out[phrase] = out.get(phrase, ()) + (kind,)
131
+ return out
132
+
133
+
134
+ def verb_atoms_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, ...]]:
135
+ """The verb phrases of a variety, keyed by their atoms, mapped to the kinds they announce."""
136
+ if lang in _verb_cache:
137
+ return _verb_cache[lang]
138
+ index = {phrase_atoms(verb): kinds for verb, kinds in verbs(lang).items()}
139
+ _verb_cache[lang] = index
140
+ return index
141
+
142
+
143
+ def verb_groups(lang: str) -> Dict[str, Tuple[str, ...]]:
144
+ """The kinds a verb phrase can open: two forms announced by one verb are one group.
145
+
146
+ Two kinds belong to the same group when one phrase of the variety announces both of them.
147
+ A sentence whose verb lies in one group is one problem, read in one of two ways; a sentence
148
+ whose verbs lie in two groups is two problems, and no reader may pick one.
149
+ """
150
+ if lang in _group_cache:
151
+ return _group_cache[lang]
152
+ parent = {kind: kind for kind in load(lang).get("kinds", {})}
153
+
154
+ def root(kind: str) -> str:
155
+ while parent[kind] != kind:
156
+ parent[kind] = parent[parent[kind]]
157
+ kind = parent[kind]
158
+ return kind
159
+
160
+ for kinds in verbs(lang).values():
161
+ for other in kinds[1:]:
162
+ first, second = root(kinds[0]), root(other)
163
+ if first != second:
164
+ parent[second] = first
165
+ merged: Dict[str, set] = {}
166
+ for kind in parent:
167
+ merged.setdefault(root(kind), set()).add(kind)
168
+ groups = {kind: tuple(sorted(group)) for group in merged.values() for kind in group}
169
+ _group_cache[lang] = groups
170
+ return groups
171
+
172
+
173
+ def announce(lang: str, items: List[Dict[str, Any]]) -> Tuple[List[str], Optional[Dict[str, str]]]:
174
+ """The kinds the verbs of a sentence open, or the reason the sentence announces none.
175
+
176
+ Both readers ask this one question, in one place: a kind is a decision about the physics, and a
177
+ second implementation of the same rule in the second reader would be one more place where the
178
+ two of them can be wrong in the same way.
179
+ """
180
+ found: List[str] = []
181
+ for item in items:
182
+ if item.get("role") != "verb":
183
+ continue
184
+ for kind in item.get("kinds") or (item.get("value"),):
185
+ if kind and kind not in found:
186
+ found.append(kind)
187
+ if not found:
188
+ return [], {"reason": "no_verb"}
189
+ neutral = neutral_kinds(lang)
190
+ picked = [kind for kind in found if kind not in neutral] or found
191
+ groups = {frozenset(verb_groups(lang)[kind]) for kind in picked}
192
+ if len(groups) > 1:
193
+ return [], {"reason": "two_verbs", "kinds": ", ".join(sorted(picked))}
194
+ merged: set = set()
195
+ for group in groups:
196
+ merged |= group
197
+ return sorted(merged), None
198
+
199
+
200
+ def connectives(lang: str) -> Dict[str, List[str]]:
201
+ """The connective phrases of a variety, keyed by what they print as in the physics language.
202
+
203
+ The data may key a connective by a mnemonic name (``times``) or by the symbol itself; both are
204
+ accepted, because the mnemonic is easier to read in a data file and the symbol is what physics
205
+ needs. These are the words that spell an operator: ``forza per tempo`` reaches physics as
206
+ ``force*time``.
207
+ """
208
+ out: Dict[str, List[str]] = {}
209
+ for name, words in load(lang).get("connectives", {}).items():
210
+ out[CONNECTIVE_TEXT.get(name, name)] = list(words)
211
+ return out
212
+
213
+
214
+ def tokens(lang: str) -> Dict[Tuple[str, ...], str]:
215
+ """The words of a variety that name a unit or a quantity, mapped to the physics token."""
216
+ if lang in _token_cache:
217
+ return _token_cache[lang]
218
+ index: Dict[Tuple[str, ...], str] = {}
219
+ for phrase, value in sorted(load(lang).get("tokens", {}).items()):
220
+ atoms = phrase_atoms(phrase)
221
+ if atoms:
222
+ index[atoms] = value
223
+ _token_cache[lang] = index
224
+ return index
225
+
226
+
227
+ def neutral_kinds(lang: str) -> set:
228
+ """Kinds whose verb is a request for an answer rather than a claim about the physics.
229
+
230
+ A request verb sits in every sentence of the variety, so the reader that carries it steps
231
+ aside when another verb announced a kind.
232
+ """
233
+ return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")}
234
+
235
+
236
+ # The single letters the physics language itself uses, folded to lower case: a bare letter in a
237
+ # sentence is a symbol or a unit only when physics knows that letter, and never an unknown that
238
+ # happens to look like one.
239
+ _SYMBOL_LETTERS = frozenset(letter.lower() for letter in canonical.PHYSICS_SYMBOLS if len(letter) == 1)
240
+ _UNIT_LETTERS = frozenset(letter.lower() for letter in canonical.PHYSICS_UNITS if len(letter) == 1)
241
+
242
+
243
+ def operand(lang: str, word: str, before: str, after: str) -> bool:
244
+ """Whether a single Latin letter touching an operator is a symbol, not the word it spells.
245
+
246
+ Italian writes the preposition "a" and Chinese pinyin writes "t" with the same characters a
247
+ quantity symbol uses, and a sentence like "bilancia v per t" puts one of those letters exactly
248
+ where a symbol belongs. Only the operator it touches tells the reader which it is, and both
249
+ readers have to use the same test: a shared fact of the physics language, not part of either
250
+ reading strategy. The trade is stated in the README -- a one letter symbol next to an operator
251
+ always wins -- which is why a joint in the data is chosen to be a word that cannot be a letter.
252
+ A letter physics has never heard of (``x``, ``y``, ``b``) is not a symbol here either: the
253
+ physics language names its quantities, and an unknown letter is a coverage failure, not a
254
+ variable.
255
+ """
256
+ if len(word) != 1 or not ("a" <= word <= "z"):
257
+ return False
258
+ if word not in _SYMBOL_LETTERS and word not in _UNIT_LETTERS:
259
+ return False
260
+ if (word,) not in phrase_index(lang):
261
+ return True
262
+ if before and before[-1] in OPERATOR_BEFORE:
263
+ return True
264
+ return bool(after and after[0] in OPERATOR_AFTER)
265
+
266
+
267
+ def markers(lang: str) -> Dict[str, List[str]]:
268
+ return load(lang).get("markers", {})
269
+
270
+
271
+ def noise(lang: str) -> List[str]:
272
+ return load(lang).get("noise", [])
273
+
274
+
275
+ def noise_chars(lang: str) -> str:
276
+ """Single characters a word run may hold without being a coverage failure (Chinese particles)."""
277
+ return load(lang).get("noise_chars", "")
278
+
279
+
280
+ def prefixes(lang: str) -> List[str]:
281
+ """Attached prefixes an Arabic word run may carry (definite article, conjunctions)."""
282
+ return load(lang).get("prefixes", [])
283
+
284
+
285
+ def strip_prefix(word: str, prefixes: List[str]) -> str:
286
+ """Remove the longest attached prefix, so that a written form reaches the prefix-free entry.
287
+
288
+ Arabic attaches the definite article and the single letter conjunctions and prepositions in
289
+ front of the word, and the lexicon files record the word without them. The longest prefix wins,
290
+ because the article and a conjunction joined to it are one prefix and not two.
291
+ """
292
+ for prefix in sorted(prefixes, key=len, reverse=True):
293
+ if word.startswith(prefix) and len(word) > len(prefix):
294
+ return word[len(prefix):]
295
+ return word
296
+
297
+
298
+ def prefix_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
299
+ """The same index, keyed with every atom of every phrase written without its prefixes."""
300
+ if lang in _stripped_cache:
301
+ return _stripped_cache[lang]
302
+ attached = prefixes(lang)
303
+ stripped = {}
304
+ for window, hit in phrase_index(lang).items():
305
+ if attached:
306
+ key = tuple(strip_prefix(atom, attached) for atom in window)
307
+ stripped.setdefault(key, hit)
308
+ _stripped_cache[lang] = stripped
309
+ return stripped
310
+
311
+
312
+ # ---------------------------------------------------------------------------
313
+ # Phrase index (reader A) and phrase positions (reader B)
314
+ # ---------------------------------------------------------------------------
315
+ def phrase_atoms(phrase: str) -> Tuple[str, ...]:
316
+ """The atoms a lexicon phrase is written with, through the same atomiser as a sentence.
317
+
318
+ A Chinese term in a data file is one token, and one token is not one atom: the atomiser cuts
319
+ it into characters, exactly as it cuts the sentence the user typed. Doing both sides the same
320
+ way is the only reason a data file and a sentence can be compared at all.
321
+ """
322
+ return tuple(fold(atom) for kind, atom in atomize(phrase) if kind == "w")
323
+
324
+
325
+ _SLOT_MARK = canonical._SLOT_MARK
326
+
327
+
328
+ def pattern_literals(lang: str) -> List[Tuple[str, ...]]:
329
+ """The function words the written patterns of a variety spell out themselves, one atom each.
330
+
331
+ A pattern is part of the data of a variety, so every word it writes is a word of that variety
332
+ by definition. ``la lunghezza d'onda di {T}`` names ``lunghezza``, and a reader that called that
333
+ word unknown would refuse the very shape the data file documents. These words carry no value,
334
+ which is what makes them noise: they may stand in a sentence, they never fill a slot. A single
335
+ Latin letter is skipped, because a letter is a symbol of the physics language and no pattern
336
+ ever writes one outside a slot.
337
+ """
338
+ words: List[Tuple[str, ...]] = []
339
+ for entries in patterns(lang).values():
340
+ for pattern in entries:
341
+ for chunk in _SLOT_MARK.split(pattern):
342
+ for atom in phrase_atoms(chunk):
343
+ if len(atom) == 1 and "a" <= atom <= "z":
344
+ continue
345
+ words.append((atom,))
346
+ return words
347
+
348
+
349
+ def phrase_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
350
+ """Map a folded word sequence to ``(role, value)``: verb, connective, marker, token or noise.
351
+
352
+ Verbs, connectives, markers, tokens and noise words of a variety share one index, because
353
+ reader A has to decide between them with a single longest match. The index is built once per
354
+ variety. The order of the registrations is the tie break: a verb beats a connective, a
355
+ connective beats a marker, a marker beats a token of the physics language, and every explicit
356
+ entry beats a word that only happens to appear inside a written pattern.
357
+ """
358
+ if lang in _index_cache:
359
+ return _index_cache[lang]
360
+ index: Dict[Tuple[str, ...], Tuple[str, str]] = {}
361
+ for verb, kinds in verbs(lang).items():
362
+ index[phrase_atoms(verb)] = ("verb", kinds[0])
363
+ for symbol, words in connectives(lang).items():
364
+ for word in words:
365
+ index[phrase_atoms(word)] = ("connective", symbol)
366
+ for name, words in markers(lang).items():
367
+ for word in words:
368
+ index[phrase_atoms(word)] = ("marker", name)
369
+ for atoms, value in tokens(lang).items():
370
+ index[atoms] = ("math", value)
371
+ for word in noise(lang):
372
+ index.setdefault(phrase_atoms(word), ("noise", ""))
373
+ for atom in pattern_literals(lang):
374
+ index.setdefault(atom, ("noise", ""))
375
+ # A data file with an empty phrase would match at every position and read nothing: drop it.
376
+ index.pop((), None)
377
+ _index_cache[lang] = index
378
+ return index
379
+
380
+
381
+ def max_phrase_length(lang: str) -> int:
382
+ return max((len(key) for key in phrase_index(lang)), default=1)
383
+
384
+
385
+ def phrase_spans(lang: str) -> List[Tuple[str, str, str]]:
386
+ """``(phrase, role, value)`` for every phrase of the variety, longest phrase first.
387
+
388
+ Reader B walks these against the sentence text itself, which is a different mechanism from
389
+ the token by token longest match of reader A.
390
+ """
391
+ out: List[Tuple[str, str, str]] = []
392
+ for verb, kind in verbs(lang).items():
393
+ out.append((verb, "verb", kind))
394
+ for symbol, words in connectives(lang).items():
395
+ for word in words:
396
+ out.append((word, "connective", symbol))
397
+ for name, words in markers(lang).items():
398
+ for word in words:
399
+ out.append((word, "marker", name))
400
+ for atoms, value in tokens(lang).items():
401
+ out.append((" ".join(atoms), "math", value))
402
+ for word in noise(lang):
403
+ out.append((word, "noise", ""))
404
+ out.sort(key=lambda item: (-len(item[0]), item[0]))
405
+ return out
406
+
407
+
408
+ # ---------------------------------------------------------------------------
409
+ # Presentation data
410
+ # ---------------------------------------------------------------------------
411
+ def labels(lang: str) -> Dict[str, str]:
412
+ return load(lang).get("labels", {})
413
+
414
+
415
+ def reading_labels(lang: str) -> Dict[str, str]:
416
+ return load(lang).get("reading", {})
417
+
418
+
419
+ def reason_texts(lang: str) -> Dict[str, str]:
420
+ return load(lang).get("reasons", {})
421
+
422
+
423
+ def examples(lang: str) -> List[str]:
424
+ return load(lang).get("examples", [])
425
+
426
+
427
+ def label(lang: str, key: str, fallback: str = "") -> str:
428
+ return labels(lang).get(key, fallback)
429
+
430
+
431
+ def translate_reason(lang: str, reason: str, **fields: Any) -> str:
432
+ """One reason in the language of the user, with the fields a template asks for."""
433
+ table = reason_texts(lang)
434
+ text = table.get(reason) or table.get("other") or reason
435
+ try:
436
+ return text.format(**fields)
437
+ except (KeyError, IndexError):
438
+ return text
439
+
440
+
441
+ def language_name(lang: str) -> str:
442
+ return load(lang).get("name", lang)
443
+
444
+
445
+ def find_by_hint(lang: str) -> Optional[str]:
446
+ """Resolve a ``--lang`` hint (a code or a name) to a language code, or ``None``."""
447
+ if lang in languages():
448
+ return lang
449
+ wanted = fold(lang)
450
+ for code in languages():
451
+ if fold(code) == wanted or fold(language_name(code)) == wanted:
452
+ return code
453
+ return None
lgphysstratum/pipeline.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One run of the topology in a single process, with every envelope re-checked.
2
+
3
+ The orchestrator runs the eight nodes as separate processes, one turn each. This module chains the
4
+ very same ``step_*`` functions in memory and runs the referee of the physics layer on every envelope
5
+ on the way, which is what the orchestrator does with each turn. It exists for the tests, for the
6
+ coverage report over the corpus, and for the ablation experiments, where thousands of runs are
7
+ needed and a process per node would dominate the time.
8
+
9
+ ``checked_verdict`` is the part that matters outside this module: it recomputes the verdict from the
10
+ evidence the transcript carries, so a node that rewrote its own record is answered by the same rules
11
+ the arbiter was supposed to follow, and the answer shown is whichever of the two is more cautious.
12
+ The tools print that verdict, not the one the arbiter wrote.
13
+ """
14
+
15
+ import os
16
+ from typing import Any, Dict, List, Optional, Sequence
17
+
18
+ from . import agents, compare, coverage, decide, faults, protocol, render
19
+
20
+ ORDER = agents.ORDER
21
+ ONTOLOGY = "(set-option :timeout 8000)\n"
22
+ BACKEND_VARIABLE = "LGPHYSSTRATUM_PHYSICS_BACKEND"
23
+
24
+
25
+ def referee(decls: List[str], asserts: List[str]) -> str:
26
+ """Run the referee of the physics layer over one envelope claim, in this process."""
27
+ status = compare.smt_referee(decls, asserts)
28
+ return status if status in ("sat", "unsat", "unknown", "error") else "unknown"
29
+
30
+
31
+ def seed(question: str, lang: str) -> Dict[str, Any]:
32
+ """The envelope the arbiter node starts a session with: the question and its language."""
33
+ dossier = {"question": question, "lang": lang}
34
+ return {"payload": {"naturalLanguage": protocol.encode("question (%s): %s" % (lang, question), dossier)},
35
+ "sender": "arbiter", "turn": 0, "volatileState": {"internalTimeTick": 0}}
36
+
37
+
38
+ def ask(question: str, lang: str, active: Sequence[str] = ORDER, fault_spec: Optional[Sequence[str]] = None,
39
+ call_physics: bool = True) -> Dict[str, Any]:
40
+ """One session, in memory: returns the dossier, the referee log, the verdict and the reply."""
41
+ faults.configure(fault_spec or ())
42
+ previous = os.environ.get(BACKEND_VARIABLE)
43
+ if not call_physics:
44
+ os.environ[BACKEND_VARIABLE] = "none"
45
+ current = seed(question, lang)
46
+ records: List[Dict[str, Any]] = []
47
+ turn = 0
48
+ try:
49
+ for name in ORDER:
50
+ if name not in active:
51
+ continue
52
+ turn += 1
53
+ incoming = {"sender": current["sender"], "turn": turn,
54
+ "volatileState": {"internalTimeTick": turn}, "payload": current["payload"]}
55
+ out = agents.run_step(name, incoming, name)
56
+ constraints = out["payload"]["smtConstraints"]
57
+ actual = referee(constraints["declarations"], constraints["assertions"])
58
+ records.append({"turn": turn, "sender": name, "claimed": constraints["z3Status"], "referee": actual})
59
+ current = out
60
+ finally:
61
+ if not call_physics:
62
+ if previous is None:
63
+ os.environ.pop(BACKEND_VARIABLE, None)
64
+ else:
65
+ os.environ[BACKEND_VARIABLE] = previous
66
+ dossier = protocol.decode(current["payload"]["naturalLanguage"])
67
+ final = checked_verdict(dossier, records, arbiter_expected="arbiter" in active)
68
+ reply = render.reply(dossier, final, records)
69
+ return {"dossier": dossier, "records": records, "final": final, "reply": reply,
70
+ "faults": sorted(faults.FIRED)}
71
+
72
+
73
+ def _unknown(reason: str) -> Dict[str, Any]:
74
+ return {"state": "NONE", "assurance": 0, "ceiling": 0, "physics_assurance": 0, "physics_status": None,
75
+ "answer": "", "reasons": [reason], "consulted_physics": False, "detected": []}
76
+
77
+
78
+ def referee_adjusted(final: Dict[str, Any], records: List[Dict[str, Any]]) -> Dict[str, Any]:
79
+ """Zero the verdict when the referee disagrees with what a node claimed about its own envelope."""
80
+ bad = [record["sender"] for record in records if record["claimed"] != record["referee"]]
81
+ if bad:
82
+ final = dict(final)
83
+ final["assurance"] = 0
84
+ final["reasons"] = list(final.get("reasons", [])) + ["referee"]
85
+ final["detected"] = list(final.get("detected", [])) + bad
86
+ return final
87
+
88
+
89
+ def independent_echo(dossier: Dict[str, Any]) -> bool:
90
+ """Recompute the echo check from the transcript, without asking the node that wrote it."""
91
+ physics_verdict = dossier.get("physics") or {}
92
+ if not physics_verdict.get("problem_physics"):
93
+ return True
94
+ for key in ("reading_a", "reading_b", "reading_direct"):
95
+ reading = dossier.get(key) or {}
96
+ if reading.get("math") and not coverage.echo_matches(reading, physics_verdict):
97
+ return False
98
+ return True
99
+
100
+
101
+ def checked_verdict(dossier: Dict[str, Any], records: List[Dict[str, Any]],
102
+ arbiter_expected: bool = True) -> Dict[str, Any]:
103
+ """The verdict a user is shown: recomputed from the evidence, then the more cautious of the two."""
104
+ try:
105
+ evidence = dict(dossier)
106
+ evidence["echo_ok"] = independent_echo(dossier)
107
+ recomputed = referee_adjusted(decide.decide(evidence), records)
108
+ except (AttributeError, KeyError, TypeError, ValueError, IndexError, ArithmeticError) as error:
109
+ return _unknown("the decision rule could not read the evidence: %s" % error)
110
+ arbiter = dossier.get("final")
111
+ if not isinstance(arbiter, dict) or "state" not in arbiter or "assurance" not in arbiter:
112
+ return _unknown("the arbiter produced no verdict") if arbiter_expected else recomputed
113
+ if arbiter["state"] == recomputed["state"] and arbiter.get("answer") == recomputed.get("answer"):
114
+ return recomputed
115
+ final = dict(recomputed if recomputed["assurance"] <= int(arbiter.get("assurance", 0) or 0) else arbiter)
116
+ final["reasons"] = list(final.get("reasons", [])) + ["arbiter and recomputed decision disagree"]
117
+ final["detected"] = list(final.get("detected", [])) + ["arbiter"]
118
+ return final
lgphysstratum/protocol.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Envelope helpers: the dossier travels inside payload.naturalLanguage.
2
+
3
+ The orchestrator forwards only the payload of the previous message, so the growing record of a
4
+ session (the dossier) is serialised as JSON after a marker line in ``naturalLanguage``. The text
5
+ before the marker is a one line human summary. This is the same contract the math stratum uses,
6
+ which is what lets one orchestrator run either topology without knowing the difference.
7
+
8
+ The dossier of a physics-stratum session holds, in the order the nodes write it:
9
+
10
+ ``question`` the sentence as the user wrote it, in the user's own language
11
+ ``lang`` the variety the answer must be written back in
12
+ ``reading_a`` what reader A (surface patterns) understood, with its notes
13
+ ``reading_b`` what reader B (marker frames) understood, with its notes
14
+ ``compare`` whether the two readings are the same problem, and on what grounds
15
+ ``coverage`` whether the agreed reading kept every number the user wrote
16
+ ``sent`` the sentence of the physics language handed to the physics topology
17
+ ``physics`` the verdict the physics topology returned, copied without any change
18
+ ``final`` the state, the assurance and the answer shown to the user
19
+ ``crash`` a role that failed, so the arbiter can report UNKNOWN instead of pretending
20
+ """
21
+
22
+ import json
23
+ from typing import Any, Dict, List, Optional
24
+
25
+ MARK = "@@DOSSIER@@"
26
+
27
+
28
+ def encode(summary: str, dossier: Dict[str, Any]) -> str:
29
+ return summary.replace("\n", " ") + "\n" + MARK + json.dumps(dossier, sort_keys=True, separators=(",", ":"))
30
+
31
+
32
+ def decode(text: str) -> Dict[str, Any]:
33
+ """Return the dossier, or a fresh one holding the raw text as the user question."""
34
+ if MARK in text:
35
+ return json.loads(text.split(MARK, 1)[1])
36
+ return {"v": 1, "question": text.strip(), "lang": "en"}
37
+
38
+
39
+ def summary_of(text: str) -> str:
40
+ return text.split("\n", 1)[0]
41
+
42
+
43
+ def envelope(
44
+ node_id: str,
45
+ recipient: Optional[str],
46
+ turn: int,
47
+ tick: int,
48
+ summary: str,
49
+ ast: str,
50
+ dossier: Dict[str, Any],
51
+ decls: List[str],
52
+ assertions: List[str],
53
+ claimed: str,
54
+ ) -> Dict[str, Any]:
55
+ out: Dict[str, Any] = {
56
+ "sender": node_id,
57
+ "turn": turn,
58
+ "volatileState": {"internalTimeTick": tick},
59
+ "payload": {
60
+ "naturalLanguage": encode(summary, dossier),
61
+ "abstractSyntaxTree": ast,
62
+ "smtConstraints": {"declarations": decls, "assertions": assertions, "z3Status": claimed},
63
+ },
64
+ }
65
+ if recipient:
66
+ out["recipient"] = recipient
67
+ return out
68
+
69
+
70
+ def start(incoming: Dict[str, Any]):
71
+ """Decode an incoming envelope into (dossier, turn, tick, sender)."""
72
+ dossier = decode(incoming["payload"]["naturalLanguage"])
73
+ tick = int(incoming.get("volatileState", {}).get("internalTimeTick", 0))
74
+ return dossier, int(incoming["turn"]), tick, incoming["sender"]
75
+
76
+
77
+ def out(node_id: str, rcpt: str, turn: int, tick: int, dossier: Dict[str, Any], summary: str, ast: str,
78
+ decls: List[str], asserts: List[str], claimed: str) -> Dict[str, Any]:
79
+ return envelope(node_id, rcpt, turn, tick, summary, ast, dossier, decls, asserts, claimed)
lgphysstratum/read_a.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reader A: the strict reader, matching the surface patterns of the lexicon.
2
+
3
+ Reader A holds the sentence against the **patterns** of a language variety: each accepted shape is
4
+ written out in ``lexicon/<lang>.json`` with the physics in a slot. A pattern matches only if every
5
+ function word it names is present, in order, and if every verb and every marker the user wrote is
6
+ accounted for. That strictness is the point: when A produces a sentence it read one of the
7
+ documented shapes and nothing else.
8
+
9
+ Reader B (:mod:`lgphysstratum.read_b`) does something different with the same data -- it looks for
10
+ the marker *frame* of a kind in the sentence, ignoring where the verb stands -- and the topology
11
+ only trusts a reading the two agree on. What the two readers share is the lexicon and the atomiser
12
+ in :mod:`lgphysstratum.segment`, just as the two readers of the physics topology share one written
13
+ grammar and one token spec.
14
+ """
15
+
16
+ import re
17
+ from typing import Any, Dict, List, Optional, Tuple
18
+
19
+ from . import canonical, lexicon
20
+ from .segment import atomize, fold, numeric_literals, word_pieces
21
+
22
+ _SLOT = canonical._SLOT_MARK
23
+ _CONTENT = ("math", "var", "connective")
24
+
25
+
26
+ def compile_pattern(pattern: str) -> Tuple[List[List[str]], List[str]]:
27
+ """Split a surface pattern into its literal word chunks and its slot names, in order."""
28
+ parts = _SLOT.split(pattern)
29
+ chunks: List[List[str]] = []
30
+ slots: List[str] = []
31
+ index = 0
32
+ while index < len(parts):
33
+ chunks.append([fold(piece) for word in parts[index].split() for piece in word_pieces(word)])
34
+ index += 1
35
+ if index < len(parts):
36
+ slots.append(parts[index])
37
+ index += 1
38
+ return chunks, slots
39
+
40
+
41
+ def _is_variable(word: str, lang: str, before: str, after: str) -> bool:
42
+ """A one letter Latin word touching an operator: a symbol of physics, not the word it looks like."""
43
+ return lexicon.operand(lang, word, before, after)
44
+
45
+
46
+ def scan(lang: str, text: str) -> List[Dict[str, Any]]:
47
+ """Tag every atom: mathematics, symbol, or a lexicon phrase with its role and value.
48
+
49
+ One longest match per position decides between verb, connective, marker, token and noise, which
50
+ is why a data file must not give one phrase two roles. The unit words of a variety are written
51
+ in long and short form side by side, so the longer reading of "kilometers per hour" never
52
+ degenerates into the shorter reading of "per" as a division.
53
+ """
54
+ phrases = lexicon.phrase_index(lang)
55
+ attached = lexicon.prefixes(lang)
56
+ stripped_index = lexicon.prefix_index(lang) if attached else {}
57
+ longest = lexicon.max_phrase_length(lang)
58
+ atoms = atomize(text)
59
+ items: List[Dict[str, Any]] = []
60
+ index = 0
61
+ while index < len(atoms):
62
+ kind, atom = atoms[index]
63
+ if kind == "m":
64
+ items.append({"role": "math", "value": atom, "words": [], "surface": atom})
65
+ index += 1
66
+ continue
67
+ word = fold(atom)
68
+ before = items[-1]["value"] if items and items[-1]["role"] == "math" else ""
69
+ after = atoms[index + 1][1] if index + 1 < len(atoms) and atoms[index + 1][0] == "m" else ""
70
+ if _is_variable(word, lang, before, after):
71
+ items.append({"role": "var", "value": word, "words": [], "surface": atom})
72
+ index += 1
73
+ continue
74
+ hit = None
75
+ for span in range(min(longest, len(atoms) - index), 0, -1):
76
+ if any(atoms[index + step][0] != "w" for step in range(span)):
77
+ continue
78
+ window = tuple(fold(atoms[index + step][1]) for step in range(span))
79
+ if window in phrases:
80
+ hit = (phrases[window], window)
81
+ break
82
+ if attached:
83
+ key = tuple(lexicon.strip_prefix(atom_in, attached) for atom_in in window)
84
+ if key in stripped_index:
85
+ hit = (stripped_index[key], window)
86
+ break
87
+ if hit is not None:
88
+ (role, value), window = hit
89
+ entry = {"role": role, "value": value, "words": list(window), "surface": " ".join(window)}
90
+ if role == "verb":
91
+ entry["kinds"] = lexicon.verb_atoms_index(lang).get(window, (value,))
92
+ items.append(entry)
93
+ index += len(window)
94
+ continue
95
+ if len(atom) == 1 and atom in lexicon.noise_chars(lang):
96
+ items.append({"role": "noise", "value": "", "words": [word], "surface": atom})
97
+ index += 1
98
+ continue
99
+ if word in lexicon.PHYSICS_WORDS:
100
+ items.append({"role": "math", "value": word, "words": [word], "surface": atom})
101
+ index += 1
102
+ continue
103
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
104
+ index += 1
105
+ return items
106
+
107
+
108
+ def _text(item: Dict[str, Any]) -> str:
109
+ """What an item contributes to the text of a slot: a connective prints as its symbol."""
110
+ if item["role"] == "connective":
111
+ return " %s " % item["value"]
112
+ return item["value"]
113
+
114
+
115
+ def _claim(words: List[str], chunk: List[str], attached: List[str]) -> bool:
116
+ """Whether a run of word atoms is the same phrase as the next piece of a pattern chunk."""
117
+ if words == chunk:
118
+ return True
119
+ if not attached or len(words) != len(chunk):
120
+ return False
121
+ stripped = [lexicon.strip_prefix(word, attached) for word in words]
122
+ return stripped == [lexicon.strip_prefix(word, attached) for word in chunk]
123
+
124
+
125
+ def _find(chunk: List[str], items: List[Dict[str, Any]], start: int, attached: List[str]):
126
+ """Where the words of a pattern chunk sit, at or after a position, or ``None``.
127
+
128
+ The chunk of a pattern is a run of function words, and a sentence may put a noise word in the
129
+ middle of it -- "converti 3 chilometri all'ora a metri al secondo" splits one chunk around a
130
+ unit word that the pattern never names. Only words may sit inside a chunk; mathematics inside
131
+ it means the sentence is not the shape the pattern describes, and the pattern has to fail on
132
+ that sentence rather than succeed on a sentence it does not describe.
133
+ """
134
+ for first in range(start, len(items) + 1):
135
+ cursor = first
136
+ taken = 0
137
+ ok = True
138
+ while taken < len(chunk):
139
+ if cursor >= len(items):
140
+ ok = False
141
+ break
142
+ words = items[cursor]["words"]
143
+ if not _claim(words, chunk[taken:taken + len(words)], attached):
144
+ ok = False
145
+ break
146
+ taken += len(words)
147
+ cursor += 1
148
+ if ok:
149
+ return first, cursor
150
+ return None
151
+
152
+
153
+ def _consume(items: List[Dict[str, Any]], start: int, stop: int) -> Optional[List[Dict[str, Any]]]:
154
+ """The mathematics held between two positions, or ``None`` when an unnamed word stands there."""
155
+ bucket: List[Dict[str, Any]] = []
156
+ for item in items[start:stop]:
157
+ if item["role"] in _CONTENT:
158
+ bucket.append(item)
159
+ elif item["role"] != "noise":
160
+ return None
161
+ return bucket
162
+
163
+
164
+ def _fill(group: List[str], bucket: List[Dict[str, Any]]) -> Optional[Dict[str, str]]:
165
+ """The values of the slots that one region of a sentence feeds.
166
+
167
+ Usually one slot, and the whole region is its value. A pattern may also put two slots side by
168
+ side, with no words between them -- "converti 3 chilometri all'ora metri al secondo" writes
169
+ the two units one after the other -- and then the region has to break into exactly one run per
170
+ slot. A region that does not break that way is a region the pattern cannot read, and guessing
171
+ where one slot ends and the other begins would be the reader inventing the problem it then
172
+ reports.
173
+ """
174
+ if len(bucket) < len(group):
175
+ return None
176
+ if len(group) == 1:
177
+ joined = " ".join(_text(item) for item in bucket).strip()
178
+ if not joined:
179
+ return None
180
+ return {group[0]: canonical.tidy(joined)}
181
+ if len(bucket) != len(group):
182
+ return None
183
+ filled: Dict[str, str] = {}
184
+ for slot, item in zip(group, bucket):
185
+ value = canonical.tidy(_text(item))
186
+ if not value:
187
+ return None
188
+ filled[slot] = value
189
+ return filled
190
+
191
+
192
+ def match(chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]],
193
+ attached: List[str]) -> Optional[Dict[str, str]]:
194
+ """A value per slot name, or ``None`` when the pattern does not describe the items.
195
+
196
+ Every verb and every marker of the sentence has to be consumed by a chunk of the pattern, and
197
+ the physics left over falls into the slots in the order the pattern names them. A pattern that
198
+ ignores a marker the sentence carries is a pattern that misread the sentence, so it fails; so
199
+ does a pattern that leaves a piece of physics outside every slot.
200
+ """
201
+ filled: Dict[str, str] = {}
202
+ group = [slots[0]]
203
+ position = 0
204
+ if chunks[0]:
205
+ # Words before the first slot: a function word the pattern does not name is harmless there,
206
+ # because it carries no physics, but physics before it belongs to no slot of the pattern,
207
+ # and a verb or a marker before it is a joint the pattern does not describe.
208
+ found = _find(chunks[0], items, 0, attached)
209
+ if found is None or _consume(items, 0, found[0]) != []:
210
+ return None
211
+ position = found[1]
212
+ for index in range(1, len(slots)):
213
+ if not chunks[index]:
214
+ group.append(slots[index])
215
+ continue
216
+ found = _find(chunks[index], items, position, attached)
217
+ if found is None:
218
+ return None
219
+ bucket = _consume(items, position, found[0])
220
+ if bucket is None:
221
+ return None
222
+ part = _fill(group, bucket)
223
+ if part is None:
224
+ return None
225
+ filled.update(part)
226
+ group = [slots[index]]
227
+ position = found[1]
228
+ tail = chunks[len(slots)]
229
+ if tail:
230
+ found = _find(tail, items, position, attached)
231
+ # Nothing but function words may follow the last words of the pattern: physics after
232
+ # the end of the shape belongs to no slot, so the shape does not describe the sentence.
233
+ if found is None or _consume(items, found[1], len(items)) != []:
234
+ return None
235
+ bucket = _consume(items, position, found[0])
236
+ else:
237
+ bucket = _consume(items, position, len(items))
238
+ if bucket is None:
239
+ return None
240
+ part = _fill(group, bucket)
241
+ if part is None:
242
+ return None
243
+ filled.update(part)
244
+ return filled
245
+
246
+
247
+ def slot_problems(kind: str, slots: Dict[str, str]) -> List[Dict[str, str]]:
248
+ """A slot that is not the shape the kind promises: a number, a unit, one equation, a symbol."""
249
+ problems: List[Dict[str, str]] = []
250
+ for name, value in sorted(slots.items()):
251
+ if name == "N" and canonical.number(value) is None:
252
+ problems.append({"reason": "bad_number", "slot": name})
253
+ if name in ("U", "V") and canonical.unit(value) is None:
254
+ problems.append({"reason": "bad_unit", "slot": name})
255
+ if name == "F" and canonical.formula(value) is None:
256
+ problems.append({"reason": "bad_formula", "slot": name})
257
+ if name == "T" and canonical.symbol(value) is None:
258
+ problems.append({"reason": "bad_symbol", "slot": name})
259
+ if name == "S" and canonical.symbols(value) is None:
260
+ problems.append({"reason": "bad_symbol", "slot": name})
261
+ if not canonical.balanced(canonical.print_math(kind, slots)):
262
+ problems.append({"reason": "unbalanced"})
263
+ return problems
264
+
265
+
266
+ def read(lang: str, text: str) -> Dict[str, Any]:
267
+ """The reading reader A reaches in one variety, and why it abstained when it did."""
268
+ items = scan(lang, text)
269
+ result: Dict[str, Any] = {"reader": "reader_a", "lang": lang, "mode": "pattern",
270
+ "kind": None, "math": None, "slots": {}, "markers": [], "notes": []}
271
+ unknown = [item for item in items if item["role"] == "unknown"]
272
+ if unknown:
273
+ result["status"] = "NOT COVERED"
274
+ for item in unknown:
275
+ result["notes"].append({"reason": item.get("reason", "unknown_word"),
276
+ "word": item["surface"]})
277
+ return result
278
+ result["markers"] = [item["value"] for item in items if item["role"] == "marker"]
279
+ candidates, why = lexicon.announce(lang, items)
280
+ if not candidates:
281
+ result["status"] = "NOT COVERED"
282
+ result["notes"].append(why)
283
+ return result
284
+ result["announced"] = candidates
285
+ attached = lexicon.prefixes(lang)
286
+ found: List[Tuple[str, str, Dict[str, str]]] = []
287
+ for kind in candidates:
288
+ for pattern in lexicon.patterns(lang).get(kind, []):
289
+ chunks, slots = compile_pattern(pattern)
290
+ assigned = match(chunks, slots, items, attached)
291
+ if assigned is None:
292
+ continue
293
+ try:
294
+ math_str = canonical.print_math(kind, assigned)
295
+ except canonical.ReadingError as error:
296
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
297
+ continue
298
+ problems = slot_problems(kind, assigned)
299
+ if problems:
300
+ result["notes"].extend(problems)
301
+ continue
302
+ if not any(entry[1] == math_str for entry in found):
303
+ found.append((kind, math_str, assigned))
304
+ if not found:
305
+ result["status"] = "NOT COVERED"
306
+ if not any(note["reason"] in ("bad_number", "bad_unit", "bad_formula", "bad_symbol",
307
+ "unbalanced") for note in result["notes"]):
308
+ result["notes"].append({"reason": "no_pattern"})
309
+ return result
310
+ if len(found) > 1:
311
+ result["status"] = "AMBIGUOUS"
312
+ result["notes"].append({"reason": "multiple",
313
+ "first": found[0][1], "second": found[1][1]})
314
+ return result
315
+ kind, math_str, assigned = found[0]
316
+ result["status"] = "READ"
317
+ result["kind"] = kind
318
+ result["math"] = math_str
319
+ result["slots"] = assigned
320
+ result["literals"] = numeric_literals(text)
321
+ result["notes"] = []
322
+ return result
lgphysstratum/read_b.py ADDED
@@ -0,0 +1,339 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reader B: the frame reader, matching the marker frame of a kind.
2
+
3
+ Reader B never looks at the surface patterns of the lexicon. It asks one question instead: does
4
+ this sentence carry the markers the frame of a kind asks for, in the order the frame asks for them,
5
+ and can the regions those markers open be assigned to the slots of the canonical form in exactly
6
+ one way? That is a different computation from the left to right pattern matching of reader A, on
7
+ the same lexicon and the same atomiser, which is what makes the two readings of one sentence
8
+ evidence about each other rather than one reading copied twice.
9
+
10
+ The problem lists of this module are written again, deliberately, instead of imported from
11
+ :mod:`lgphysstratum.read_a`: two readers that share the code that checks a slot are one reader.
12
+ """
13
+
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ from . import canonical, lexicon
17
+ from .segment import atomize, fold, numeric_literals
18
+
19
+ _CONTENT = ("math", "var", "connective")
20
+
21
+
22
+ def _matches(window: List[str], phrase: str, attached: List[str]) -> bool:
23
+ """Whether a window of atoms spells a lexicon phrase, with or without attached prefixes."""
24
+ folded = fold(phrase)
25
+ if window == folded.split():
26
+ return True
27
+ if not attached or len(window) != len(phrase.split()):
28
+ return False
29
+ stripped = [lexicon.strip_prefix(word, attached) for word in window]
30
+ return stripped == [lexicon.strip_prefix(word, attached) for word in folded.split()]
31
+
32
+
33
+ def find_spans(lang: str, atoms: List[Tuple[str, str]]):
34
+ """The positions every lexicon phrase of a variety occupies, longest phrase first.
35
+
36
+ Reader B never picks one phrase per position: it enumerates every phrase of the variety and
37
+ marks every place it occurs, so two readings of one sentence can overlap and both of them stay
38
+ visible to the rest of the reader. Reader A does the opposite, a single longest match per
39
+ position, and that difference is why the two of them disagree sometimes.
40
+ """
41
+ table = sorted(lexicon.phrase_index(lang).items(),
42
+ key=lambda entry: (-len(entry[0]), -len("".join(entry[0])), entry[0]))
43
+ attached = lexicon.prefixes(lang)
44
+ spans: List[Dict[str, Any]] = []
45
+ covered: Dict[int, int] = {}
46
+ for phrase, (role, value) in table:
47
+ length = len(phrase)
48
+ if not length:
49
+ continue
50
+ start = 0
51
+ while start + length <= len(atoms):
52
+ window = [fold(atoms[start + step][1]) for step in range(length)
53
+ if atoms[start + step][0] == "w"]
54
+ if len(window) != length or any(atoms[start + step][0] != "w" for step in range(length)):
55
+ start += 1
56
+ continue
57
+ if any(index in covered for index in range(start, start + length)):
58
+ start += 1
59
+ continue
60
+ if not _matches(window, " ".join(phrase), attached):
61
+ start += 1
62
+ continue
63
+ entry = {"start": start, "end": start + length, "role": role, "value": value,
64
+ "words": window}
65
+ if role == "verb":
66
+ entry["kinds"] = lexicon.verb_atoms_index(lang).get(phrase, (value,))
67
+ spans.append(entry)
68
+ for index in range(start, start + length):
69
+ covered[index] = len(spans) - 1
70
+ start += length
71
+ return spans, covered
72
+
73
+
74
+ def classify(lang: str, atoms: List[Tuple[str, str]], spans: List[Dict[str, Any]],
75
+ covered: Dict[int, int]) -> List[Dict[str, Any]]:
76
+ """One entry per phrase: what the lexicon says it is, and why an atom is unknown when it is.
77
+
78
+ A phrase of the variety that runs over several atoms -- the Italian phrase for "starting from",
79
+ the Chinese phrase for a dimensional analysis -- yields one entry, not one per atom. A joint of a
80
+ frame is one joint, and three
81
+ entries for one joint would make the frame of a sentence carry three joints the form never
82
+ promised, which is a bug of the reader and not a fact of the language.
83
+ """
84
+ items: List[Dict[str, Any]] = []
85
+ index = 0
86
+ while index < len(atoms):
87
+ kind, atom = atoms[index]
88
+ if kind == "m":
89
+ items.append({"role": "math", "value": atom, "words": [], "surface": atom})
90
+ index += 1
91
+ continue
92
+ word = fold(atom)
93
+ if index in covered:
94
+ span = spans[covered[index]]
95
+ entry = {"role": span["role"], "value": span["value"], "words": span["words"],
96
+ "surface": " ".join(span["words"])}
97
+ if len(span["words"]) == 1 and span["role"] != "verb":
98
+ # The phrase table says the letter is a function word of the variety; the letter
99
+ # next to an operator is a symbol of physics. A frame reader that has to put some
100
+ # physics into a slot cannot leave the letter out of the slot, and reading it as
101
+ # the letter of the operator would be reading a symbol into a sentence twice.
102
+ before = _neighbour(atoms, index, -1)
103
+ after = _neighbour(atoms, index, 1)
104
+ if lexicon.operand(lang, word, before, after):
105
+ entry["role"] = "var"
106
+ items.append(entry)
107
+ index = span["end"]
108
+ continue
109
+ if len(word) == 1 and word in lexicon.noise_chars(lang):
110
+ items.append({"role": "noise", "value": "", "words": [word], "surface": atom})
111
+ index += 1
112
+ continue
113
+ if (len(word) == 1 and "a" <= word <= "z"
114
+ and (word in lexicon._SYMBOL_LETTERS or word in lexicon._UNIT_LETTERS)):
115
+ # A bare letter that the physics language knows: a symbol, not the word it spells.
116
+ # A letter physics has never heard of stays unknown, so an equation written with
117
+ # unknown letters is a coverage failure and not an invented problem.
118
+ items.append({"role": "var", "value": word, "words": [], "surface": atom})
119
+ index += 1
120
+ continue
121
+ if word in lexicon.PHYSICS_WORDS:
122
+ items.append({"role": "math", "value": word, "words": [word], "surface": atom})
123
+ index += 1
124
+ continue
125
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
126
+ index += 1
127
+ return items
128
+
129
+
130
+ def _neighbour(atoms: List[Tuple[str, str]], index: int, step: int) -> str:
131
+ """The surface of the adjacent atom when it is mathematics, else the empty string."""
132
+ other = index + step
133
+ if 0 <= other < len(atoms) and atoms[other][0] == "m":
134
+ return atoms[other][1]
135
+ return ""
136
+
137
+
138
+ def _text(item: Dict[str, Any]) -> str:
139
+ """What an item contributes to the text of a slot: a connective prints as its symbol."""
140
+ if item["role"] == "connective":
141
+ return " %s " % item["value"]
142
+ return item["value"]
143
+
144
+
145
+ def _regions_marked(items: List[Dict[str, Any]]):
146
+ """The runs of physics words of a sentence, each tagged with the joint standing before it.
147
+
148
+ A joint of the physics language introduces the region that follows it, and the verb of a
149
+ sentence introduces nothing: it sits in the gap a form leaves without a joint. Tagging a region
150
+ instead of counting regions is what lets B read a frame written out of order, because Italian
151
+ and Chinese front the units ("in metri, converti 3 chilometri") and a reader that filled the
152
+ slots by position would put the start unit where the target unit belongs.
153
+
154
+ The atoms of a region are joined with a space on purpose. The atomiser cuts the physics words of a
155
+ sentence into runs, and one run can be the whole term of an audit while two runs can be the two
156
+ ends of one term split by a word that is neither a unit nor a quantity.
157
+ Gluing the runs without a space invents a token that was never written, and an invented token is
158
+ a changed problem.
159
+ """
160
+ regions: List[Tuple[Optional[str], str]] = []
161
+ buffer: List[str] = []
162
+ joint: Optional[str] = None
163
+ for item in items:
164
+ if item["role"] in ("marker", "verb"):
165
+ regions.append((joint, canonical.tidy(" ".join(buffer))))
166
+ buffer = []
167
+ joint = item["value"] if item["role"] == "marker" else None
168
+ elif item["role"] in _CONTENT:
169
+ buffer.append(_text(item))
170
+ regions.append((joint, canonical.tidy(" ".join(buffer))))
171
+ return regions
172
+
173
+
174
+ def _slot_groups(slots: List[str], gaps: List[Optional[str]]) -> List[Tuple[Optional[str], List[str]]]:
175
+ """The slots of a form grouped by the joint that introduces them.
176
+
177
+ Consecutive slots that no joint separates share one region of the sentence: the conversion form
178
+ prints a number and a unit with no word between them, so one region carries both. The group of
179
+ one slot is the ordinary case and is what the math stratum had everywhere; the group of two is
180
+ what the physics language asks for, and it is the one place where reader B has to look inside a
181
+ region rather than take it whole.
182
+ """
183
+ groups: List[Tuple[Optional[str], List[str]]] = []
184
+ for position, slot in enumerate(slots):
185
+ joint = gaps[position] if position < len(gaps) else None
186
+ if joint is None and groups and groups[-1][0] is None:
187
+ groups[-1][1].append(slot)
188
+ else:
189
+ groups.append((joint, [slot]))
190
+ return groups
191
+
192
+
193
+ def _split_region(text: str, count: int):
194
+ """One region broken into exactly as many values as the slots that share it, or ``None``.
195
+
196
+ The break is structural: the region is read as the pieces the sentence wrote, and the count has
197
+ to come out. A region that offers more or fewer pieces than the form needs is a sentence the
198
+ form does not describe -- guessing where the number stops and the unit begins would be reader B
199
+ inventing the problem it then reports to the physics topology.
200
+ """
201
+ parts = [part for part in text.split() if part]
202
+ if len(parts) != count:
203
+ return None
204
+ return parts
205
+
206
+
207
+ def _assign_joints(marked, gaps: List[Optional[str]], slots: List[str]):
208
+ """Fill the slots of a form from the regions a sentence offers, or fail.
209
+
210
+ A slot takes the region that stands after the joint the form puts before it, and a slot whose
211
+ gap carries no joint takes the one region of the sentence no joint claims. A region holding no
212
+ physics is never a candidate, and every region that does hold physics has to end up in a slot:
213
+ physics left over belongs to no slot of the form, so the form does not describe the sentence.
214
+ This is also how a joint the physics language puts last is policed -- the region it introduces
215
+ is empty, and anything written after it makes the form fail -- and why a frame whose slots
216
+ arrive in a rotated order still reads, because no slot is identified by its position in the
217
+ sentence. Slots that share one region split it by the pieces it was written with.
218
+ """
219
+ introduced: Dict[str, List[int]] = {}
220
+ unclaimed: List[int] = []
221
+ for index, (joint, _) in enumerate(marked):
222
+ if joint is None:
223
+ unclaimed.append(index)
224
+ else:
225
+ introduced.setdefault(joint, []).append(index)
226
+ assigned: Dict[str, str] = {}
227
+ taken: set = set()
228
+ for joint, group in _slot_groups(slots, gaps):
229
+ if joint is None:
230
+ candidates = [index for index in unclaimed
231
+ if index not in taken and marked[index][1]]
232
+ else:
233
+ candidates = [index for index in introduced.get(joint, [])
234
+ if index not in taken and marked[index][1]]
235
+ if len(candidates) != 1:
236
+ return None
237
+ text = marked[candidates[0]][1]
238
+ if len(group) == 1:
239
+ assigned[group[0]] = text
240
+ else:
241
+ parts = _split_region(text, len(group))
242
+ if parts is None:
243
+ return None
244
+ assigned.update(dict(zip(group, parts)))
245
+ taken.add(candidates[0])
246
+ last = gaps[len(slots)] if len(slots) < len(gaps) else None
247
+ if last is not None and any(marked[index][1] for index in introduced.get(last, [])):
248
+ return None
249
+ if any(text for index, (_, text) in enumerate(marked) if text and index not in taken):
250
+ return None
251
+ return assigned
252
+
253
+
254
+ def _problems(kind: str, slots: Dict[str, str]) -> List[Dict[str, str]]:
255
+ """A slot that is not the shape the kind promises. Written again on purpose: see the module note."""
256
+ problems: List[Dict[str, str]] = []
257
+ for name, value in sorted(slots.items()):
258
+ if name == "N" and canonical.number(value) is None:
259
+ problems.append({"reason": "bad_number", "slot": name})
260
+ if name in ("U", "V") and canonical.unit(value) is None:
261
+ problems.append({"reason": "bad_unit", "slot": name})
262
+ if name == "F" and canonical.formula(value) is None:
263
+ problems.append({"reason": "bad_formula", "slot": name})
264
+ if name in ("T", "S") and canonical.symbol(value) is None and canonical.symbols(value) is None:
265
+ problems.append({"reason": "bad_symbol", "slot": name})
266
+ if not canonical.balanced(canonical.print_math(kind, slots)):
267
+ problems.append({"reason": "unbalanced"})
268
+ return problems
269
+
270
+
271
+ def read(lang: str, text: str) -> Dict[str, Any]:
272
+ """The reading reader B reaches in one variety, and why it abstained when it did."""
273
+ atoms = atomize(text)
274
+ spans, covered = find_spans(lang, atoms)
275
+ items = classify(lang, atoms, spans, covered)
276
+ result: Dict[str, Any] = {"reader": "reader_b", "lang": lang, "mode": "frame",
277
+ "kind": None, "math": None, "slots": {}, "markers": [], "notes": []}
278
+ unknown = [item for item in items if item["role"] == "unknown"]
279
+ if unknown:
280
+ result["status"] = "NOT COVERED"
281
+ for item in unknown:
282
+ result["notes"].append({"reason": "unknown_word", "word": item["surface"]})
283
+ return result
284
+ result["markers"] = [item["value"] for item in items if item["role"] == "marker"]
285
+ candidates, why = lexicon.announce(lang, items)
286
+ if not candidates:
287
+ result["status"] = "NOT COVERED"
288
+ result["notes"].append(why)
289
+ return result
290
+ result["announced"] = candidates
291
+ marked = _regions_marked(items)
292
+ found: List[Tuple[str, str, Dict[str, str]]] = []
293
+ for kind in candidates:
294
+ frame = lexicon.frames(lang).get(kind, {})
295
+ allowed = [tuple(sequence) for sequence in frame.get("sequences", [])]
296
+ if tuple(result["markers"]) not in allowed:
297
+ result["notes"].append({"reason": "no_frame", "kind": kind,
298
+ "detail": " ".join(result["markers"]) or "none"})
299
+ continue
300
+ for variant in canonical.VARIANTS[kind]:
301
+ gaps = canonical.gap_markers(kind, variant)
302
+ if tuple(canonical.marker_sequence(kind, variant)) != tuple(result["markers"]):
303
+ continue
304
+ slots = canonical.slots_for(kind, variant)
305
+ assigned = _assign_joints(marked, gaps, slots)
306
+ if assigned is None:
307
+ result["notes"].append({"reason": "markers", "kind": kind,
308
+ "detail": " ".join(result["markers"]) or "none"})
309
+ continue
310
+ try:
311
+ math_str = canonical.print_math(kind, assigned)
312
+ except canonical.ReadingError as error:
313
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
314
+ continue
315
+ problems = _problems(kind, assigned)
316
+ if problems:
317
+ result["notes"].extend(problems)
318
+ continue
319
+ if not any(entry[1] == math_str for entry in found):
320
+ found.append((kind, math_str, assigned))
321
+ if not found:
322
+ result["status"] = "NOT COVERED"
323
+ if not any(note["reason"] in ("bad_number", "bad_unit", "bad_formula", "bad_symbol",
324
+ "unbalanced") for note in result["notes"]):
325
+ result["notes"].append({"reason": "no_pattern"})
326
+ return result
327
+ if len(found) > 1:
328
+ result["status"] = "AMBIGUOUS"
329
+ result["notes"].append({"reason": "multiple",
330
+ "first": found[0][1], "second": found[1][1]})
331
+ return result
332
+ kind, math_str, assigned = found[0]
333
+ result["status"] = "READ"
334
+ result["kind"] = kind
335
+ result["math"] = math_str
336
+ result["slots"] = assigned
337
+ result["literals"] = numeric_literals(text)
338
+ result["notes"] = []
339
+ return result
lgphysstratum/render.py ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The answer the user reads, in the language the user wrote in.
2
+
3
+ Nothing here decides anything: the text is built from the verdict ``decide`` produced and from the
4
+ words the lexicon of that language provides. Two kinds of text meet in one reply, and the boundary
5
+ between them is deliberate:
6
+
7
+ * every label, state name and reason is taken from ``lexicon/<lang>.json``, so the framing of the
8
+ answer belongs to the user's language;
9
+ * the physical content -- the canonical sentence the stratum understood and the answer the physics
10
+ layer returned -- is passed through byte for byte, because it is a value and not prose.
11
+
12
+ The sentence the stratum understood is always shown. A user who wrote in Italian and gets back
13
+ ``pi period from mass, stiffness`` can see which reading was used, and that is the whole point of a
14
+ stratum: the interpretation is inspectable, not hidden inside a model.
15
+
16
+ When no answer can be shown, the reply says so in the user's language and lists the forms this
17
+ language variety does understand, from ``lexicon.examples``, so the failure is a correction and not
18
+ a dead end.
19
+ """
20
+
21
+ import re
22
+ from typing import Any, Dict, List, Optional
23
+
24
+ from . import decide as decide_module
25
+ from . import lexicon
26
+
27
+ FIELDS = ("word", "kind", "detail", "left", "right", "slot")
28
+ _PLACEHOLDER = re.compile(r"\{[a-z_]+\}")
29
+
30
+
31
+ def _fill(text: str) -> str:
32
+ """Drop a placeholder the template kept: an unfilled brace must never reach the user."""
33
+ return _PLACEHOLDER.sub("", text).replace(" ", " ").strip(" ;,:")
34
+
35
+
36
+ def note_fields(dossier: Dict[str, Any]) -> Dict[str, Dict[str, Any]]:
37
+ """The fields each reason carries, collected from the notes the readers left behind."""
38
+ out: Dict[str, Dict[str, Any]] = {}
39
+ for reading in [dossier.get("reading_a") or {}, dossier.get("reading_b") or {},
40
+ dossier.get("reading_direct") or {}]:
41
+ for note in reading.get("notes") or []:
42
+ if isinstance(note, dict) and note.get("reason"):
43
+ fields = {key: note[key] for key in FIELDS if key in note}
44
+ out.setdefault(str(note["reason"]), fields)
45
+ for reason, fields in ((dossier.get("physics") or {}).get("reason_fields") or {}).items():
46
+ out.setdefault(str(reason), dict(fields))
47
+ return out
48
+
49
+
50
+ def _kind_understood(dossier: Dict[str, Any]) -> str:
51
+ """The kind of problem the stratum solved, as the identifier the physics language uses."""
52
+ for key in ("reading_a", "reading_b", "reading_direct"):
53
+ reading = dossier.get(key) or {}
54
+ if reading.get("kind"):
55
+ return str(reading["kind"])
56
+ return ""
57
+
58
+
59
+ def _sentence(dossier: Dict[str, Any]) -> str:
60
+ """The canonical sentence that was, or would have been, handed to the physics layer."""
61
+ compare = dossier.get("compare") or {}
62
+ physics_verdict = dossier.get("physics") or {}
63
+ for source in (dossier.get("sent"), compare.get("left"), physics_verdict.get("problem_physics")):
64
+ if source:
65
+ return str(source)
66
+ for key in ("reading_a", "reading_b", "reading_direct"):
67
+ reading = dossier.get(key) or {}
68
+ if reading.get("math"):
69
+ return str(reading["math"])
70
+ return ""
71
+
72
+
73
+ def _check_line(lang: str, records: Optional[List[Dict[str, Any]]]) -> str:
74
+ """How many envelopes of the run the referee of the orchestrator confirmed."""
75
+ if not records:
76
+ return ""
77
+ good = sum(1 for record in records if record.get("claimed") == record.get("referee"))
78
+ return lexicon.labels(lang)["check"].format(a=good, b=len(records))
79
+
80
+
81
+ def _physics_why(physics_verdict: Dict[str, Any]) -> str:
82
+ """What to say about the physics layer next to its status, in one short phrase.
83
+
84
+ An error of this stratum comes first -- the layer was not started, was started and died, was
85
+ turned off -- because that is the part this layer knows and the user can act on. When the layer
86
+ itself refused or abstained, its own one-line sentence about the refusal is shown. The reason
87
+ codes the layer carries are bookkeeping of its internal nodes and are not repeated here.
88
+ """
89
+ why = str(physics_verdict.get("error") or physics_verdict.get("reason") or "")
90
+ if why:
91
+ return why
92
+ if str(physics_verdict.get("status") or "") in decide_module.ANSWERING:
93
+ return ""
94
+ return str(physics_verdict.get("answer_text") or "")
95
+
96
+
97
+ def reply(dossier: Dict[str, Any], final: Optional[Dict[str, Any]] = None,
98
+ records: Optional[List[Dict[str, Any]]] = None, lang: Optional[str] = None) -> Dict[str, Any]:
99
+ """Build the user-facing answer: one text block plus the machine-readable parts."""
100
+ lang = lang or str(dossier.get("lang") or "en")
101
+ if lang not in lexicon.codes():
102
+ lang = "en"
103
+ verdict = final or decide_module.decide(dossier)
104
+ labels = lexicon.labels(lang)
105
+ states = lexicon.reading_labels(lang)
106
+ fields = note_fields(dossier)
107
+
108
+ lines: List[str] = []
109
+ state = str(verdict.get("state", "NONE"))
110
+ lines.append("%s: %s" % (labels["status"], states.get(state, state)))
111
+ sentence = _sentence(dossier)
112
+ kind = _kind_understood(dossier)
113
+ if sentence and state not in ("NOT COVERED", "NONE"):
114
+ lines.append("%s (%s): %s" % (labels["understood"], kind, sentence))
115
+ if verdict.get("answer"):
116
+ lines.append("%s: %s" % (labels["answer"], verdict["answer"]))
117
+ lines.append(labels["assurance"].replace("{n}", str(verdict.get("assurance", 0))))
118
+ physics_verdict = dossier.get("physics") or {}
119
+ if physics_verdict.get("status"):
120
+ # Which road of the physics layer carried the answer is its own bookkeeping and nothing the
121
+ # reader of an answer asked for; what belongs in the reply is the verdict and, when the layer
122
+ # abstained, the reason it abstained.
123
+ tail = str(physics_verdict["status"])
124
+ why = _physics_why(physics_verdict)
125
+ if why:
126
+ tail += " (" + why + ")"
127
+ lines.append("%s: %s" % (labels["physics_layer"], tail))
128
+ reasons = [str(reason) for reason in verdict.get("reasons") or []]
129
+ if reasons:
130
+ fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])})
131
+ fields.setdefault("physics_unknown", {"detail": _physics_why(physics_verdict)})
132
+ texts = [_fill(lexicon.translate_reason(lang, reason, **(fields.get(reason) or {})))
133
+ for reason in reasons]
134
+ lines.append("%s: %s" % (labels["notes"], "; ".join(texts)))
135
+ check = _check_line(lang, records)
136
+ if check:
137
+ lines.append(check)
138
+ if state in ("NOT COVERED", "AMBIGUOUS", "NONE") and not verdict.get("answer"):
139
+ samples = lexicon.examples(lang)
140
+ if samples:
141
+ lines.append("%s: %s" % (labels["question"], " | ".join(samples[:5])))
142
+ return {
143
+ "lang": lang,
144
+ "language": lexicon.language_name(lang),
145
+ "state": state,
146
+ "assurance": verdict.get("assurance", 0),
147
+ "answer": verdict.get("answer", ""),
148
+ "sentence": sentence,
149
+ "kind": kind,
150
+ "reasons": reasons,
151
+ "lines": lines,
152
+ "text": "\n".join(lines),
153
+ }
lgphysstratum/segment.py ADDED
@@ -0,0 +1,244 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Script aware tokenisation and digit normalisation of a natural language sentence.
2
+
3
+ This module knows nothing about the languages: it splits a sentence into runs of *words* and runs
4
+ of *mathematics*, and it puts every digit in the shape the physics language uses. The mapping from
5
+ a word to a role is the lexicon, in ``lexicon/<lang>.json`` and :mod:`lgphysstratum.lexicon`.
6
+
7
+ Three normalisations happen here, and all three are testable on their own:
8
+
9
+ * digit scripts: Arabic-Indic, Extended Arabic-Indic, Devanagari and Bengali digits become ASCII
10
+ digits, and compatibility normalisation turns the full width forms a Chinese keyboard produces
11
+ into their ASCII counterparts;
12
+ * separators that differ per language: the Arabic decimal sign, the Arabic and Devanagari commas,
13
+ the CJK full stop and question mark, and the bidi control characters disappear or take their
14
+ ASCII counterpart;
15
+ * context for ``.`` and ``,``: a dot is part of a number only between digits, a comma is part of
16
+ the mathematics only between two closed operands, which is what separates the comma of a unit
17
+ expression from the comma that ends a clause in a sentence.
18
+ """
19
+
20
+ import re
21
+ import unicodedata
22
+ from typing import List, Tuple
23
+
24
+ # ---------------------------------------------------------------------------
25
+ # Digits and separators
26
+ # ---------------------------------------------------------------------------
27
+ def _digits(start: int) -> dict:
28
+ return {chr(start + i): str(i) for i in range(10)}
29
+
30
+
31
+ DIGIT_MAP: dict = {}
32
+ DIGIT_MAP.update(_digits(0x0660)) # Arabic-Indic
33
+ DIGIT_MAP.update(_digits(0x06F0)) # Extended Arabic-Indic (Persian/Urdu)
34
+ DIGIT_MAP.update(_digits(0x0966)) # Devanagari
35
+ DIGIT_MAP.update(_digits(0x09E6)) # Bengali
36
+
37
+ SEPARATOR_MAP: dict = {
38
+ "\u060c": " ", # Arabic comma
39
+ "\u061b": " ", # Arabic semicolon
40
+ "\u061f": " ", # Arabic question mark
41
+ "\u066b": ".", # Arabic decimal sign
42
+ "\u066c": "", # Arabic thousands separator
43
+ "\u066d": " ", # Arabic date separator
44
+ "\u0964": " ", # Devanagari danda
45
+ "\u0965": " ", # Devanagari double danda
46
+ "\u3001": " ", # ideographic comma
47
+ "\u3002": " ", # ideographic full stop
48
+ "\uff1f": " ", # full width question mark
49
+ "\uff01": " ", # full width exclamation mark
50
+ "\u201e": " ",
51
+ "\u201f": " ",
52
+ "\u2018": " ",
53
+ "\u2019": "'", # the apostrophe of an elision is kept, and the elision is split apart
54
+ "\u201c": " ",
55
+ "\u201d": " ",
56
+ # The Italian copula would otherwise fold to the connective "e" (and), so it is not a word.
57
+ "\u00e8": " ",
58
+ "\u2013": "-",
59
+ "\u2014": "-",
60
+ "\u2212": "-", # minus sign
61
+ "\u00d7": "*", # multiplication sign
62
+ "\u00b7": "*", # middle dot, the Italian way of writing a unit product
63
+ "\u00f7": "/", # division sign
64
+ "\u2265": ">=",
65
+ "\u2264": "<=",
66
+ "\u2260": "!=",
67
+ }
68
+
69
+ INVISIBLE = (
70
+ "\u200b\u200c\u200d\u200e\u200f\u061c\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\ufeff"
71
+ )
72
+
73
+ # The symbols of the physics language, square brackets included: the resistor list of a circuit
74
+ # problem is the reason they are here, and they must be read as mathematics and not dropped as
75
+ # stray punctuation. The semicolon is deliberately absent: inside a natural language sentence it
76
+ # separates clauses, and the circuit form is reachable through the direct mode, which reads the
77
+ # sentence as written.
78
+ MATH_CHARS = set("0123456789+-*/^()[]<>=!|,:.")
79
+ CLOSED_CHARS = set("0123456789)]")
80
+ OPENING_CHARS = set("0123456789[(")
81
+
82
+ # The relation and operator symbols the physics language accepts. Nothing else is mathematics.
83
+ OPERATORS = ("=>", "<=>", "<=", ">=", "!=", "+", "-", "*", "/", "^", "=", "<", ">", "|")
84
+
85
+
86
+ def normalize(text: str) -> str:
87
+ """Return the sentence in a canonical shape: ASCII digits, ASCII separators, one space."""
88
+ text = unicodedata.normalize("NFKC", text)
89
+ for ch in INVISIBLE:
90
+ text = text.replace(ch, "")
91
+ text = text.translate({ord(k): v for k, v in DIGIT_MAP.items()})
92
+ text = text.translate({ord(k): v for k, v in SEPARATOR_MAP.items()})
93
+ return re.sub(r"\s+", " ", text).strip()
94
+
95
+
96
+ def script_of(text: str) -> str:
97
+ """The dominant non Latin script of a sentence: cjk, arabic, devanagari, latin or none."""
98
+ counts = {"cjk": 0, "arabic": 0, "devanagari": 0, "latin": 0}
99
+ for ch in text:
100
+ if not ch.isalpha():
101
+ continue
102
+ name = unicodedata.name(ch, "")
103
+ if name.startswith("CJK") or name.startswith("IDEOGRAPHIC"):
104
+ counts["cjk"] += 1
105
+ elif name.startswith("ARABIC"):
106
+ counts["arabic"] += 1
107
+ elif name.startswith("DEVANAGARI"):
108
+ counts["devanagari"] += 1
109
+ elif name.startswith("LATIN"):
110
+ counts["latin"] += 1
111
+ best = max(counts, key=lambda k: counts[k])
112
+ return best if counts[best] else "none"
113
+
114
+
115
+ def _is_math_char(ch: str, text: str, index: int) -> bool:
116
+ if ch in MATH_CHARS:
117
+ if ch == ".":
118
+ return _neighbour(text, index, -1).isdigit() and _neighbour(text, index, 1).isdigit()
119
+ if ch == ",":
120
+ return _neighbour(text, index, -1) in CLOSED_CHARS and _neighbour(text, index, 1) in OPENING_CHARS
121
+ return True
122
+ return False
123
+
124
+
125
+ def _neighbour(text: str, index: int, step: int) -> str:
126
+ j = index + step
127
+ while 0 <= j < len(text) and text[j] == " ":
128
+ j += step
129
+ return text[j] if 0 <= j < len(text) else ""
130
+
131
+
132
+ _MARKS = ("Mn", "Mc", "Me")
133
+
134
+
135
+ def _word_char(ch: str) -> bool:
136
+ """A character of a word: a letter of any script, an apostrophe, or a combining mark.
137
+
138
+ The combining marks matter: the vowel signs of Devanagari and the Arabic diacritics are not
139
+ letters, and dropping them would break a word into pieces that no lexicon entry matches.
140
+ """
141
+ return ch.isalpha() or ch in "_'" or unicodedata.category(ch) in _MARKS
142
+
143
+
144
+ def pieces(run: str) -> List[str]:
145
+ """Split a word run at every apostrophe: an Italian elision is two words to the lexicon.
146
+
147
+ ``l'unita`` is the article ``l`` and the noun ``unita``, and only the second of the two is a
148
+ phrase of the lexicon. The lexicon patterns are written with the elision joined, and compiled
149
+ through this same function, so data and matching agree.
150
+ """
151
+ return [piece for piece in run.split("'") if piece]
152
+
153
+
154
+ def is_cjk(run: str) -> bool:
155
+ """Whether a run is written in Chinese characters."""
156
+ return any(unicodedata.name(ch, "").startswith(("CJK", "IDEOGRAPHIC")) for ch in run)
157
+
158
+
159
+ def word_pieces(run: str) -> List[str]:
160
+ """The atoms a word run offers the lexicon: characters for Chinese, pieces elsewhere.
161
+
162
+ Chinese is written without spaces, so the only reliable unit is the character, and a
163
+ multi character term of the lexicon is then a sequence of atoms -- which is how the lexicon
164
+ file writes it too, one space separated token per character group.
165
+ """
166
+ if is_cjk(run):
167
+ return list(run)
168
+ return pieces(run)
169
+
170
+
171
+ def atomize(text: str) -> List[Tuple[str, str]]:
172
+ """A normalized sentence as atoms: ``("m", run)`` mathematics, ``("w", word)`` word atoms.
173
+
174
+ Both readers start here. It is one of the two things they share -- the other is the lexicon --
175
+ and it is the counterpart of the shared token spec that the two readers of the physics
176
+ topology share: sharing the atomiser buys agreement about *what the words are*, while the two
177
+ readers still disagree, productively, about what the sentence means.
178
+ """
179
+ out: List[Tuple[str, str]] = []
180
+ for kind, run in tokens(text):
181
+ if kind == "m":
182
+ out.append(("m", run))
183
+ else:
184
+ for piece in word_pieces(run):
185
+ out.append(("w", piece))
186
+ return out
187
+
188
+
189
+ def tokens(text: str) -> List[Tuple[str, str]]:
190
+ """Split a normalized sentence into ``("m", run)`` mathematics and ``("w", run)`` words.
191
+
192
+ Letters of every script open a word run, digits and the symbols of the physics language open
193
+ a mathematics run. An ASCII letter run is returned as a word: :mod:`lgphysstratum.read_a` and
194
+ :mod:`lgphysstratum.read_b` decide between a token of the physics language and a function word
195
+ through the lexicon.
196
+ """
197
+ text = normalize(text)
198
+ out: List[Tuple[str, str]] = []
199
+ index = 0
200
+ while index < len(text):
201
+ ch = text[index]
202
+ if ch.isspace():
203
+ index += 1
204
+ continue
205
+ if _word_char(ch):
206
+ start = index
207
+ while index < len(text) and _word_char(text[index]):
208
+ index += 1
209
+ out.append(("w", text[start:index]))
210
+ continue
211
+ if _is_math_char(ch, text, index):
212
+ start = index
213
+ while index < len(text) and _is_math_char(text[index], text, index):
214
+ index += 1
215
+ run = text[start:index].strip()
216
+ if run:
217
+ out.append(("m", run))
218
+ continue
219
+ index += 1
220
+ return out
221
+
222
+
223
+ def numeric_literals(text: str) -> List[str]:
224
+ """Every numeric literal of a sentence, in the order it appears, digits normalised."""
225
+ found: List[str] = []
226
+ for _kind, run in tokens(text):
227
+ for match in re.finditer(r"\d+(?:\.\d+)?", run):
228
+ found.append(match.group(0))
229
+ return found
230
+
231
+
232
+ def fold(word: str) -> str:
233
+ """Casefold a Latin word and drop its accents, so that one lexicon entry covers both cases.
234
+
235
+ Non Latin scripts are returned unchanged: casefolding and accent folding do not apply to
236
+ Chinese, Devanagari or Arabic, and the lexicon entries are written in the form the keyboard
237
+ produces. The units and quantities of the physics language are written with their ASCII
238
+ spelling, which is why folding is safe for them too.
239
+ """
240
+ if not any("a" <= ch.lower() <= "z" for ch in word):
241
+ return word
242
+ decomposed = unicodedata.normalize("NFD", word)
243
+ stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
244
+ return stripped.lower()
nodes/adversary/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 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.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/adversary/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node adversary.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/adversary/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "adversary",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/arbiter/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 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.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/arbiter/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node arbiter.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/arbiter/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "arbiter",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "question (it): converti 3 chilometri in metri\n@@DOSSIER@@{\"lang\":\"it\",\"question\":\"converti 3 chilometri in metri\"}",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/boundary/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 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.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/boundary/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node boundary.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/boundary/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "boundary",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/coverage/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node coverage (coverage): Coverer: lists every number the user wrote and checks that each of the readings kept it.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/coverage/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node coverage.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/coverage/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "coverage",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/equivalence/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 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.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/equivalence/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node equivalence.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/equivalence/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "equivalence",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/invoker/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node invoker (invoker): Invoker: hands the agreed sentence to the physics topology in a separate process and records the verdict it comes back with.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/invoker/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node invoker.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/invoker/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "invoker",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/reader_a/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 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.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/reader_a/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node reader_a.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/reader_a/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "reader_a",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/reader_b/grammar.gf ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- 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.
2
+ -- PhysLang: the controlled physical language this stratum writes, which is the input language of the physics topology.
3
+ -- Reference implementation: the readers lgphysstratum/read_a.py and lgphysstratum/read_b.py, the printer lgphysstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- The three funs the readers of this stratum produce are Convert, Audit and Pi. Potential belongs to the language of
5
+ -- the physics topology and is listed here because it is part of the target language, but no variety of this stratum
6
+ -- writes it yet, and a question that would need it stays outside the coverage of every lexicon.
7
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
8
+ -- In the abstractSyntaxTree numbers and unit names are written bare (3, km) instead of (Lit 3), (Q km); a list of
9
+ -- names is written (One period) or (And mass stiffness); and a ratio is written (Slash 1 2).
10
+ abstract PhysLang = {
11
+ cat
12
+ Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ;
13
+ fun
14
+ Convert : Qty -> Unit -> Problem ;
15
+ Audit : Eq -> Problem ;
16
+ Pi : Names -> Names -> Problem ;
17
+ Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ;
18
+ MkQty : Num -> Unit -> Qty ;
19
+ Add, Sub, Mul, Div, Pow : Side -> Side -> Side ;
20
+ Neg : Side -> Side ;
21
+ Q : Unit -> Unit ;
22
+ Row : Num -> Num -> Num -> Rows ;
23
+ Nil : Rows ;
24
+ One : Names ;
25
+ And : Names -> Names -> Names ;
26
+ MkNum : String -> Num ;
27
+ Slash : Num -> Num -> Ratio ;
28
+ }
29
+
30
+ concrete PhysLangEng of PhysLang = {
31
+ lincat
32
+ Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ;
33
+ lin
34
+ Convert q u = "convert" ++ q ++ "to" ++ u ;
35
+ Audit e = "audit" ++ e ;
36
+ Pi t ns = "pi" ++ t ++ "from" ++ ns ;
37
+ Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k
38
+ ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ;
39
+ MkQty n u = n ++ u ;
40
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
41
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
42
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
43
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
44
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
45
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
46
+ Q u = u ;
47
+ Row a b c = "[" ++ a ++ b ++ c ++ "]" ;
48
+ Nil = "" ;
49
+ One n = n ;
50
+ And a b = a ++ "," ++ b ;
51
+ MkNum s = s.s ;
52
+ Slash n d = n ++ "/" ++ d ;
53
+ }
nodes/reader_b/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the physics-stratum topology node reader_b.
2
+ ; The theory of real arithmetic is built into Z3, so the ontology only fixes solver options:
3
+ ; without a timeout one hard nonlinear query could block the whole session, and the claims this
4
+ ; topology carries are equalities over numerals plus one inequality on the assurance shown,
5
+ ; which Z3 decides in milliseconds.
6
+ (set-option :timeout 8000)
nodes/reader_b/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "reader_b",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
problems/corpus.jsonl ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"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}}
2
+ {"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}}
3
+ {"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}}
4
+ {"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}}
5
+ {"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}}
6
+ {"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}}
7
+ {"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}}
8
+ {"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}}
9
+ {"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}}
10
+ {"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}}
11
+ {"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}}
12
+ {"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}}
13
+ {"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}}
14
+ {"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}}
15
+ {"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}}
16
+ {"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}}
17
+ {"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}}
18
+ {"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}}
19
+ {"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}}
20
+ {"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}}
21
+ {"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}}
22
+ {"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}}
23
+ {"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}}
24
+ {"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}}
25
+ {"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}}
26
+ {"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}}
27
+ {"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}}
28
+ {"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}}
29
+ {"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}}
30
+ {"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}}
31
+ {"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}}
32
+ {"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}}
33
+ {"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}}
34
+ {"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}}
35
+ {"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}}
36
+ {"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}}
37
+ {"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}}
38
+ {"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}}
39
+ {"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}}
40
+ {"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}}
41
+ {"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}}
42
+ {"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}}
43
+ {"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}}
44
+ {"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}}
45
+ {"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}}
46
+ {"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}}
47
+ {"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}}
48
+ {"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}}
49
+ {"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}}
50
+ {"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}}
51
+ {"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}}
52
+ {"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}}
53
+ {"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}}
54
+ {"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}}
55
+ {"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}}
56
+ {"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}}
57
+ {"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}}
58
+ {"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}}
59
+ {"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}}
60
+ {"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}}
61
+ {"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}}
62
+ {"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}}
63
+ {"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}}
64
+ {"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}}