tailot commited on
Commit
e9dac18
·
verified ·
1 Parent(s): 22e10b1

publish math-stratum bundle

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 +346 -0
  3. agents/stratum_agent +39 -0
  4. lexicon/ar.json +142 -0
  5. lexicon/en.json +142 -0
  6. lexicon/es.json +142 -0
  7. lexicon/hi.json +142 -0
  8. lexicon/it.json +142 -0
  9. lexicon/zh.json +142 -0
  10. lgstratum/__init__.py +20 -0
  11. lgstratum/agents.py +276 -0
  12. lgstratum/canonical.py +218 -0
  13. lgstratum/compare.py +261 -0
  14. lgstratum/corpus.py +81 -0
  15. lgstratum/coverage.py +93 -0
  16. lgstratum/decide.py +160 -0
  17. lgstratum/faults.py +144 -0
  18. lgstratum/invoker.py +102 -0
  19. lgstratum/lexicon.py +421 -0
  20. lgstratum/pipeline.py +116 -0
  21. lgstratum/protocol.py +79 -0
  22. lgstratum/read_a.py +334 -0
  23. lgstratum/read_b.py +306 -0
  24. lgstratum/render.py +140 -0
  25. lgstratum/segment.py +240 -0
  26. nodes/adversary/grammar.gf +104 -0
  27. nodes/adversary/ontology.smt2 +5 -0
  28. nodes/adversary/seed_payload.json +18 -0
  29. nodes/arbiter/grammar.gf +104 -0
  30. nodes/arbiter/ontology.smt2 +5 -0
  31. nodes/arbiter/seed_payload.json +18 -0
  32. nodes/boundary/grammar.gf +104 -0
  33. nodes/boundary/ontology.smt2 +5 -0
  34. nodes/boundary/seed_payload.json +18 -0
  35. nodes/coverage/grammar.gf +104 -0
  36. nodes/coverage/ontology.smt2 +5 -0
  37. nodes/coverage/seed_payload.json +18 -0
  38. nodes/equivalence/grammar.gf +104 -0
  39. nodes/equivalence/ontology.smt2 +5 -0
  40. nodes/equivalence/seed_payload.json +18 -0
  41. nodes/invoker/grammar.gf +104 -0
  42. nodes/invoker/ontology.smt2 +5 -0
  43. nodes/invoker/seed_payload.json +18 -0
  44. nodes/reader_a/grammar.gf +104 -0
  45. nodes/reader_a/ontology.smt2 +5 -0
  46. nodes/reader_a/seed_payload.json +18 -0
  47. nodes/reader_b/grammar.gf +104 -0
  48. nodes/reader_b/ontology.smt2 +5 -0
  49. nodes/reader_b/seed_payload.json +18 -0
  50. problems/corpus.jsonl +73 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
README.md ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - it
4
+ - en
5
+ - es
6
+ - zh
7
+ - hi
8
+ - ar
9
+ tags:
10
+ - multilingual
11
+ - mathematical-word-problems
12
+ - natural-language-to-formal-language
13
+ - multi-agent-systems
14
+ - benchmark
15
+ - conversational-interfaces
16
+ - formal-verification
17
+ - semantic-parsing
18
+ pretty_name: "LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading"
19
+ configs:
20
+ - config_name: corpus
21
+ data_files:
22
+ - split: train
23
+ path: problems/corpus.jsonl
24
+ size_categories:
25
+ - n<1K
26
+ ---
27
+
28
+ # LingoLOGOS math-stratum topology
29
+
30
+ A conversational layer over the `math` topology: a person asks in one of six written varieties, and
31
+ gets the answer of the math stratum back in that same language, at an assurance that includes the
32
+ fallibility of the reading. The layer never decides a problem and never raises a verdict; the only
33
+ direction it can move the assurance of the math stratum is down.
34
+
35
+ ```
36
+ python tools/ask.py --lang it "risolvi x^2 - 5*x + 6 = 0 per x"
37
+ Reading state : AGREED
38
+ Assurance shown : 2 (reading ceiling 2, math assurance 3)
39
+ Math layer status : VERIFIED
40
+ Orchestrator Z3 check : 8 of 8 envelopes confirmed
41
+
42
+ Answer in the language of the question (italiano):
43
+ Stato: accordata: due lettori indipendenti piu il vincolo SMT
44
+ Problema capito (solve): solve x^2-5*x+6=0 for x
45
+ Risposta: {2, 3}
46
+ livello 2 di 3
47
+ strato matematico: VERIFIED
48
+ Controllo SMT dello strato : 8 di 8 buste confermate
49
+ ```
50
+
51
+ This dataset is the `math-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,
52
+ code and data together, plus this card in place of their README. Only the standard library and
53
+ `z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every
54
+ command below is written from inside the folder. The mathematics is not part of this dataset: it lives
55
+ in the `math` bundle, published at https://huggingface.co/datasets/tailot/lingologos-math, and section
56
+ 10 says how to point this folder at a copy of it.
57
+
58
+ ## 1. What the stratum is, and what it refuses
59
+
60
+ The certainty of a translation cannot be verified the way the certainty of a proof can: there is no
61
+ SMT check that says that a sentence of Hindi was read correctly. That is the definition this bundle
62
+ works with, and it is why the topology is built the way it is: two readers that reach their sentence
63
+ by different roads, an SMT claim about what each reading kept, a referee that rechecks every envelope,
64
+ and a decision that is re-derived from the transcript instead of being trusted from the arbiter.
65
+
66
+ The rule the whole bundle exists to enforce:
67
+
68
+ ```
69
+ assurance shown = min(assurance of the math stratum, ceiling of the reading)
70
+ ```
71
+
72
+ | Reading state | ceiling | when |
73
+ |---|---|---|
74
+ | `AGREED` | 2 | both readers produced the same sentence, and the math stratum is what decides it |
75
+ | `PASSTHROUGH` | 2 | the question was already a sentence of the math language: nothing was translated |
76
+ | `SINGLE` | 1 | one reader understood it and the other abstained: no witness, one level less |
77
+ | `DISPUTED` | 0 | the two readers produced different sentences, or a reading lost a number: the math stratum is not even asked |
78
+ | `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 |
79
+ | `NOT COVERED` | 0 | neither reader found anything: this variety does not say it in a covered way |
80
+ | `TAMPERED` | 0 | the math stratum says it solved something other than the agreed sentence |
81
+
82
+ Three is never shown. Level three belongs to the math stratum, whose two formalizers and two
83
+ checkers work on a sentence they wrote themselves; a sentence in a human language adds one fallible
84
+ step before that, and this layer is that step.
85
+
86
+ The ceiling is not the only thing that holds on its own. The count of literals is checked on a lone
87
+ reading too: a reading that no longer holds the numbers the person wrote is a different problem, not a
88
+ weaker reading of the same one, and it ends `DISPUTED` even when it is the only reader that understood
89
+ the question. A single witness therefore answers at level one only when it kept every number.
90
+
91
+ ## 2. The eight nodes
92
+
93
+ The session runs through the orchestrator (`src/lingologos_orchestrator`) with the same envelope
94
+ protocol as the `math` topology: a marker `@@DOSSIER@@` inside `payload.naturalLanguage`, and
95
+ `payload.smtConstraints` carrying what each node claims about its own output, which the referee of
96
+ every node recomputes with Z3. The seed sits in the `arbiter`; `maxTurns` is the number of arcs.
97
+
98
+ | Node | What it does | The claim it carries |
99
+ |---|---|---|
100
+ | `reader_a` | reads the question against the frames written in the lexicon | the numerals of the question are still in my sentence |
101
+ | `reader_b` | reads it by following the joints of the math language | the same, independently |
102
+ | `equivalence` | proves the two sentences the same, slot by slot and then with SMT | `not (A = B)` is unsatisfiable |
103
+ | `coverage` | counts that every literal the person wrote survived into the sentence | conjunction of the element equalities |
104
+ | `invoker` | asks the math stratum, in a separate process, the agreed sentence | the sentence I sent equals the one that came back |
105
+ | `boundary` | checks the echo of the math stratum instead of trusting it | elementwise on the echo, or the empty claim |
106
+ | `adversary` | re-derives the bound and writes its negation | `shown > ceiling` is unsatisfiable |
107
+ | `arbiter` | runs the decision and renders the answer in the language of the question | the same inequality |
108
+
109
+ ## 3. Two readers, one lexicon
110
+
111
+ `read_a.py` matches the shapes stored in `lexicon/<lang>.json` (`patterns`: one template per kind of
112
+ problem, with slots). `read_b.py` never looks at those shapes: it finds the verb that announces a
113
+ problem, then walks the joints of the math language (`for`, `over Z`, `from ... to`, `subject to`,
114
+ `wrt`) and cuts the slots out of the gaps between them. They share only the lexicon, the atomizer
115
+ (`segment.py`) and the templates of the math language (`canonical.py`).
116
+
117
+ That sharing is deliberate and it is also the known blind spot: a wrong description of a variety is
118
+ a wrong description for both readers, and the topology cannot see it. What shows it is the corpus of
119
+ section 5, whose questions were written and checked by a person. When the two readers disagree the
120
+ assurance goes down, never up: `DISPUTED` does not even consult the math stratum.
121
+
122
+ ## 4. Talking to the math stratum
123
+
124
+ `invoker.py` is the only door. It launches `python <root>/tools/solve.py --json <sentence>` as a
125
+ separate process and reads its JSON verdict back; nothing in this folder imports the solver of the
126
+ math stratum to decide anything here. The referee then checks the echo: the sentence the math stratum
127
+ says it solved has to be the sentence the readers agreed on, otherwise the session is `TAMPERED`.
128
+
129
+ | Variable | Meaning |
130
+ |---|---|
131
+ | `LGSTRATUM_MATH_ROOT` | where the `math` bundle is (default: the sibling folder `datasets/math`) |
132
+ | `LGSTRATUM_MATH_BACKEND` | `subprocess` (default), or `none` to disable the math layer entirely |
133
+ | `LGSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only |
134
+
135
+ A disabled math layer is not tampering: the reading stands, the assurance falls to zero because there
136
+ is no math assurance to take the minimum with, and no answer is shown.
137
+
138
+ ## 5. The corpus
139
+
140
+ `problems/corpus.jsonl` holds 73 questions: 12 kinds of problem in 6 varieties, plus items that mix
141
+ varieties, full width digits, unspelled matrices, gibberish, questions with an empty slot and
142
+ questions whose mathematics is out of reach of the math stratum. Each line carries what the answer
143
+ has to look like (`state`, `sentence`, `answer_contains`, `min_assurance`, `max_assurance`,
144
+ `no_answer`, `referee_clean`) and a `why` that says why, including the cases where the expected
145
+ outcome is an abstention.
146
+
147
+ Graded against the in-process pipeline: **73 of 73** rows agree with their gold (`lgstratum/corpus.py`
148
+ grades one row, `tests/test_corpus.py` runs all of them). With the math layer switched off the states
149
+ come out 57 `AGREED`, 2 `SINGLE`, 11 `NOT COVERED`, 3 `PASSTHROUGH`; `tools/coverage_report.py` writes
150
+ `results/coverage.json` and counts **57** questions read by both readers, **2** by `reader_a` alone and
151
+ **14** by neither. Seven rows (`it-13`, `en-11`, `en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`) are agreed
152
+ readings on which the math stratum abstains: assurance 0 and no answer, which is the layer refusing to
153
+ add an availability it does not have. Two rows (`hi-05`, `hi-10`) stay at `SINGLE`, assurance 1, for the
154
+ reason in section 7.
155
+
156
+ ## 6. Commands
157
+
158
+ ```
159
+ python tools/ask.py --lang it "quanto fa 2+2?" # one session, eight processes
160
+ python tools/ask.py --lang en --json "solve x + 1 = 2 for x"
161
+ python tools/ask.py --lang ar --corpus problems/corpus.jsonl --limit 6
162
+ python tools/coverage_report.py --out results/coverage.json # which frames each variety carries
163
+ python tools/ablation.py --probe 12 --out results/ablation.json
164
+ ```
165
+
166
+ `tools/ask.py` prints the verdict it re-derives from the transcript, not the one the arbiter wrote,
167
+ and exits with code 3 when that re-derivation disagrees with a node about its own envelope, with code
168
+ 2 when the assurance is zero, and with code 1 in corpus mode when a gold expectation fails.
169
+ `tools/ablation.py` walks the configurations of the topology
170
+ one node at a time, injects every fault of the catalogue singly and in pairs, and reports each cell as
171
+ `raised | lowered | masked | caught | abstained | silent_error`: a cell counted `raised` is a violation
172
+ of the rule of section 1, and the tool exits 1 if any happened. A `caught` cell is one where an answer
173
+ was shown that the gold does not accept, but the session said so itself -- a claim fell to the referee
174
+ of its node, or the assurance sits below the honest one because the configuration lost a node.
175
+
176
+ On this checkout `--probe 6` (one question per variety) fills **147 cells** and **882 sessions**, the
177
+ fault takes hold in **510** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 0`,
178
+ `caught 18`, `abstained 366`, `masked 126` -- about fifteen minutes. Nothing was ever raised above the
179
+ honest assurance, and the 18 `caught` cells all sit in the configuration without `reader_b`, where a
180
+ rubber stamped verification node cannot buy back the level the missing witness costs.
181
+
182
+ ## 7. Limits that are written down, not hidden
183
+
184
+ * Two varieties place their joints after the slot instead of before it. `reader_b` cannot cut the
185
+ slots there, so those questions are read by one reader only and stay at `SINGLE`, assurance 1
186
+ (`hi-05`, `hi-10`). `tools/coverage_report.py` shows them as one of two readers.
187
+ * A missing written accent can collide with a connective: `qual e il determinante di ...` is not read,
188
+ because the folded copula is the same atom as the conjunction `e`.
189
+ * The fragment of the math stratum is unchanged here: powers inside integer terms and non linear
190
+ programs end in `UNKNOWN`, so the assurance is zero even when the reading is agreed. The corpus
191
+ keeps those questions as probes (`it-13`, `en-11`, `en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`).
192
+ * The two readers share their data, so a systematic error in the description of a variety is invisible
193
+ to the topology and can only be found in the corpus.
194
+
195
+ ## 8. Tests
196
+
197
+ From the repository root:
198
+
199
+ ```
200
+ python -m pytest -q datasets/math-stratum/tests
201
+ ```
202
+
203
+ The suite is **290** tests: 121 on the two readers against every row of the corpus, 79 on the corpus
204
+ itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 13 on the decision
205
+ table, 10 on the lexicons and 2 end-to-end sessions. It checks the topology file against the node
206
+ order, the shape and the completeness of the lexicons, both readers against the corpus, the decision
207
+ table, the faults, and every gold answer of the corpus; `tests/test_pinned_invariant.py` runs the same questions through every node
208
+ configuration and every fault and asserts that the verdict of the math stratum does not move, and
209
+ that nothing is ever shown above it. `tests/test_orchestrator_e2e.py` runs two real sessions through
210
+ the orchestrator and is skipped when `lingologos_orchestrator` is not importable. The corpus and the
211
+ invariant tests call the solver of the math stratum as subprocesses, which here means a copy of the
212
+ `math` dataset named by `LGSTRATUM_MATH_ROOT` (section 10); the suite took 3 minutes 52 seconds inside a
213
+ LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is
214
+ not importable.
215
+
216
+ Real sessions, measured: `risolvi x^2 - 5*x + 6 = 0 per x` comes back `AGREED` at assurance 2 against a
217
+ math assurance of 3, with **8 of 8** envelope claims confirmed by the referee of the session, and
218
+ `python tools/ask.py --corpus problems/corpus.jsonl --limit 8` grades **8 of 8** real sessions against
219
+ gold. One question per variety outside Italian (`zh-01`, `ar-01`, `hi-03`, `es-02`) comes back the same
220
+ way: `AGREED`, assurance 2, the math stratum `VERIFIED`, 8 of 8 claims confirmed, nothing detected --
221
+ and the block the person reads is written in the language of the question (48, 97 and 104 non-ASCII
222
+ characters in the Chinese, Arabic and Hindi replies).
223
+
224
+ A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that
225
+ `lgmath` may be imported for its SMT plumbing by `lgstratum/compare.py` alone.
226
+
227
+ ## 9. Language policy
228
+
229
+ The prose of this folder -- code, docstrings, comments, tool output, test messages -- is English, and
230
+ the Python sources are ASCII, as the repository requires. The exception is the language under study,
231
+ and it is confined to data: `lexicon/*.json` (the words, frames, joints and labels of the six
232
+ varieties), `problems/corpus.jsonl` (the questions and their gold answers), and the answer block that
233
+ `tools/ask.py` shows a person, which is written in the language of the question because that block is
234
+ the object this bundle measures.
235
+
236
+ ## 10. Putting this dataset back into a LingoLOGOS checkout
237
+
238
+ This dataset is 67 files plus this card: 73 questions in one corpus file, the six lexicons, the eight
239
+ node definitions, the two readers, the decision rule of section 1, the corpus grading and fault results
240
+ under `results/`, and the fault catalogue of section 6. To run the mathematics it needs the `math`
241
+ bundle: download https://huggingface.co/datasets/tailot/lingologos-math somewhere, set
242
+ `LGSTRATUM_MATH_ROOT` to that copy, and the `invoker` node calls `tools/solve.py` there as a separate
243
+ process, which is the only door through which this bundle ever reaches a solver. Inside a LingoLOGOS
244
+ checkout the folder sits at `datasets/math-stratum`, finds `datasets/math` by itself, and needs
245
+ `src/lingologos_orchestrator` importable for the two end to end sessions of section 8. On the hub this
246
+ README is rewritten as a dataset card whose sections 1 to 10 keep the wording and numbers of this file,
247
+ and sections 11 to 14 are added there for readers who met the bundle on the hub rather than in a
248
+ checkout: the fields of the corpus file, how to load it, rights and citation. Every file but this README was compared by sha256 after the upload: the hub holds one object
249
+ per file of this folder plus `.gitattributes`, so the remote count is one above the number
250
+ `tools/publish_dataset.py` prints here. What the LingoLOGOS repository carries is the link to this
251
+ dataset in the table of published resources at the top of its README; the documentation of the asset
252
+ lives here, in this card, and not in the technical documentation of the project. `tools/publish_dataset.py`
253
+ in the folder of the project republishes a changed working copy with the token taken from an environment
254
+ variable. Republishing is a separate step, never a side effect of a
255
+ test run: `tools/publish_dataset.py` does it with the token taken from an environment variable and
256
+ verifies the tree by sha256.
257
+
258
+ ## 11. The corpus file
259
+
260
+ `problems/corpus.jsonl` holds 73 questions, one JSON object per line, written and checked by a person.
261
+ It is a benchmark for the stratum: there is no prompt, no response pair and nothing to fine tune on.
262
+ Each row says what the session has to end like, including the rows whose expected outcome is a refusal
263
+ to answer, and a `why` that says why.
264
+
265
+ | Field | Type | Meaning |
266
+ |---|---|---|
267
+ | `id` | string | unique; the prefix names the variety (`it`, `en`, `es`, `zh`, `hi`, `ar`), or `mixed` on the 5 rows that mix varieties, write digits in full width form or are gibberish |
268
+ | `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in |
269
+ | `kind` | string | one of the 12 problem kinds, or `negative` (14 rows that must not be read) or `passthrough` (2 rows already written in the math language) |
270
+ | `question` | string | the question, between 5 and 53 characters, in the script of its variety |
271
+ | `why` | string | the reason the row behaves as it does, written by the person who wrote the row |
272
+ | `expect` | object | the expectation, described below |
273
+
274
+ | Variety (`lang`) | Rows | Id prefix | Rows | Kind | Rows |
275
+ |---|---|---|---|---|---|
276
+ | `it` | 13 | `it` | 13 | `evaluate` | 7 |
277
+ | `en` | 13 | `en` | 12 | `solve` | 6 |
278
+ | `es` | 10 | `es` | 9 | `solvez` | 3 |
279
+ | `zh` | 12 | `zh` | 11 | `prove` | 5 |
280
+ | `hi` | 12 | `hi` | 11 | `provez` | 8 |
281
+ | `ar` | 13 | `ar` | 12 | `derivative` | 4 |
282
+ | mixed rows | 5 | `mixed` | 5 | `integral` | 5 |
283
+ | | | | | `det`, `rank` | 3, 3 |
284
+ | | | | | `inverse` | 4 |
285
+ | | | | | `maximize`, `minimize` | 3, 6 |
286
+ | | | | | `negative` | 14 |
287
+ | | | | | `passthrough` | 2 |
288
+
289
+ The fields of `expect` are optional except `referee_clean`, which is present on every row.
290
+
291
+ | Field | Rows | Meaning |
292
+ |---|---|---|
293
+ | `state` | 65 | the reading state the session must end in: `AGREED` 55, `PASSTHROUGH` 3, `SINGLE` 2, `NOT COVERED` 5 |
294
+ | `sentence` | 60 | the sentence of the math language both readers have to produce, exactly |
295
+ | `answer_contains` | 29 | a substring the answer has to contain, exact rationals written as strings |
296
+ | `min_assurance` | 51 | the lowest assurance that is acceptable, on the scale of section 1 |
297
+ | `max_assurance` | 22 | the highest assurance that is acceptable: this is what pins the probes that must not rise |
298
+ | `no_answer` | 15 | `true` where the row is graded by the refusal: no answer may be shown at all |
299
+ | `referee_clean` | 73 | every envelope claim of the session must match what the referee of its node recomputed |
300
+
301
+ The eight rows with no `state` are graded on an assurance or on an answer instead: they check that the
302
+ reading holds while the math stratum abstains, so the assurance must be 0 and no answer may appear.
303
+ Seven of them are the agreed readings on which the mathematics is out of reach (`it-13`, `en-11`,
304
+ `en-12`, `es-09`, `zh-11`, `hi-11`, `ar-12`), which is the stratum refusing to add an availability it
305
+ does not have.
306
+
307
+ ## 12. Loading it
308
+
309
+ Load the file with the `datasets` library, or with one `json.loads` per line, which needs no
310
+ dependency:
311
+
312
+ ```python
313
+ from datasets import load_dataset
314
+ rows = load_dataset("tailot/math-stratum", "corpus", split="train")
315
+ print(rows[0])
316
+ ```
317
+
318
+ This is the same file `tools/ask.py --corpus` walks over, and `lgstratum/corpus.py` plus
319
+ `tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 73 of 73
320
+ rows agree with what they expect.
321
+
322
+ ## 13. Rights
323
+
324
+ No license is declared for this dataset, its lexicons, its corpus or its code: reuse is not granted by
325
+ this page. The six lexicons, the 73 questions with their gold expectations, the grammar specifications,
326
+ the node data and the Python sources were written by hand as part of the LingoLOGOS project. Ask before
327
+ redistributing or building on them, and expect the answer to be yes for academic work with attribution.
328
+ Z3 is a separate product with its own license and is not redistributed here; `z3-solver` is only named
329
+ as a dependency in `requirements.txt`. The lexicons of Hindi, Arabic and Chinese describe written
330
+ varieties as this project needs them for arithmetic questions: they are not a general purpose
331
+ dictionary of those languages.
332
+
333
+ ## 14. Citation
334
+
335
+ ```
336
+ @misc{lingologos_math_stratum,
337
+ title = {LingoLOGOS math-stratum: a question in six written varieties, the answer of the math stratum, and an assurance that includes the reading},
338
+ author = {LingoLOGOS project},
339
+ year = {2026},
340
+ url = {https://huggingface.co/datasets/tailot/math-stratum},
341
+ note = {bundle of the math-stratum folder of the LingoLOGOS repository: 73 questions in six written
342
+ varieties, six lexicons, two independent readers, eight node definitions with SMT claims, the
343
+ assurance rule min(math, reading) with the reading capped at 2, fault catalogue and ablation
344
+ over the node configurations, 290 tests}
345
+ }
346
+ ```
agents/stratum_agent ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Node executable of the math-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 math 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 mathematical fact: the sentence the readers agree on is handed to
13
+ the math 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 lgstratum import agents, faults # noqa: E402
24
+
25
+
26
+ def main() -> int:
27
+ parser = argparse.ArgumentParser(description="Math-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,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "ar",
3
+ "name": "العربية",
4
+ "script": "arabic",
5
+ "noise_chars": "",
6
+ "prefixes": ["ال", "وال", "بال", "فال", "لل", "و", "ب", "ل", "ف"],
7
+ "kinds": {
8
+ "evaluate": {
9
+ "verbs": ["احسب", "حساب", "قيمة", "كم قيمة"],
10
+ "neutral": true,
11
+ "patterns": ["احسب {T}", "احسب قيمة {T}", "كم قيمة {T}", "ما قيمة {T}"],
12
+ "frame": {"sequences": [[]]}
13
+ },
14
+ "prove": {
15
+ "verbs": ["أثبت", "إثبات", "برهن"],
16
+ "patterns": ["أثبت أن {F}", "أثبت {F}", "برهن أن {F}", "برهن {F}"],
17
+ "frame": {"sequences": [[]]}
18
+ },
19
+ "provez": {
20
+ "verbs": ["أثبت", "إثبات", "برهن"],
21
+ "patterns": ["أثبت أن {F} في أعداد صحيحة", "برهن أن {F} في أعداد صحيحة", "أثبت {F} على أعداد صحيحة"],
22
+ "frame": {"sequences": [["over_z"]]}
23
+ },
24
+ "solve": {
25
+ "verbs": ["حل", "أوجد"],
26
+ "patterns": ["حل {F} إيجاد {V}", "حل {F} نسبة إلى {V}"],
27
+ "frame": {"sequences": [["for"], ["wrt"]]}
28
+ },
29
+ "solvez": {
30
+ "verbs": ["حل", "أوجد"],
31
+ "patterns": ["حل {F} إيجاد {V} في أعداد صحيحة", "حل {F} نسبة إلى {V} في أعداد صحيحة"],
32
+ "frame": {"sequences": [["for", "over_z"]]}
33
+ },
34
+ "derivative": {
35
+ "verbs": ["مشتقة", "اشتقاق", "اشتق"],
36
+ "patterns": ["مشتقة {T}", "احسب مشتقة {T}", "مشتقة {T} نسبة إلى {V}", "اشتق {T} نسبة إلى {V}"],
37
+ "frame": {"sequences": [[], ["wrt"]]}
38
+ },
39
+ "integral": {
40
+ "verbs": ["تكامل"],
41
+ "patterns": ["تكامل {T} من {A} إلى {B}", "احسب تكامل {T} من {A} إلى {B}", "تكامل {T} من {A} إلى {B} نسبة إلى {V}", "تكامل {T} نسبة إلى {V} من {A} إلى {B}"],
42
+ "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]}
43
+ },
44
+ "det": {
45
+ "verbs": ["محدد"],
46
+ "patterns": ["محدد {M}", "احسب محدد {M}", "احسب محدد مصفوفة {M}"],
47
+ "frame": {"sequences": [[]]}
48
+ },
49
+ "rank": {
50
+ "verbs": ["رتبة"],
51
+ "patterns": ["رتبة {M}", "احسب رتبة {M}"],
52
+ "frame": {"sequences": [[]]}
53
+ },
54
+ "inverse": {
55
+ "verbs": ["معاكسة"],
56
+ "patterns": ["معاكسة {M}", "احسب معاكسة {M}", "احسب معاكسة مصفوفة {M}"],
57
+ "frame": {"sequences": [[]]}
58
+ },
59
+ "maximize": {
60
+ "verbs": ["عظم", "تعظيم", "عظمى"],
61
+ "patterns": ["عظم {T} شرط {F}", "عظم {T} تحت قيود {F}"],
62
+ "frame": {"sequences": [["subject_to"]]}
63
+ },
64
+ "minimize": {
65
+ "verbs": ["صغر", "تصغير", "صغرى"],
66
+ "patterns": ["صغر {T} شرط {F}", "صغر {T} تحت قيود {F}"],
67
+ "frame": {"sequences": [["subject_to"]]}
68
+ }
69
+ },
70
+ "connectives": {
71
+ "and": ["و"],
72
+ "or": ["أو"],
73
+ "not": ["ليس"],
74
+ "ge": ["على أقل", "لا يقل عن", "أكبر من أو يساوي"],
75
+ "le": ["على أكثر", "لا يزيد عن", "أصغر من أو يساوي"],
76
+ "gt": ["أكبر من", "أكثر من"],
77
+ "lt": ["أصغر من", "أقل من"],
78
+ "eq": ["يساوي", "يعادل"],
79
+ "ne": ["لا يساوي", "مختلف عن"]
80
+ },
81
+ "markers": {
82
+ "for": ["إيجاد"],
83
+ "over_z": ["في أعداد صحيحة", "على أعداد صحيحة", "في مجموعة أعداد صحيحة"],
84
+ "subject_to": ["شرط", "تحت قيود", "في ظل قيود"],
85
+ "from": ["من"],
86
+ "to": ["إلى"],
87
+ "wrt": ["نسبة إلى"]
88
+ },
89
+ "noise": ["ما", "أن", "كم", "هو", "هي", "هذه", "ذلك", "رجاء", "مصفوفة"],
90
+ "labels": {
91
+ "understood": "المسألة كما فهمناها",
92
+ "status": "الحالة",
93
+ "assurance": "المستوى {n} من 3",
94
+ "answer": "الجواب",
95
+ "reading": "القراءة",
96
+ "math_layer": "الطبقة الرياضية",
97
+ "notes": "ملاحظات",
98
+ "examples": "جمل تفهمها هذه الطبقة",
99
+ "question": "أعد صياغة السؤال بإحدى هذه الصيغ",
100
+ "check": "فحص SMT للطبقة : {a} من {b} مغلف مؤكد",
101
+ "kind_of": "النوع"
102
+ },
103
+ "reading": {
104
+ "AGREED": "متفق عليها: قارئان مستقلان وقيد SMT",
105
+ "PASSTHROUGH": "الجملة مكتوبة أصلا بلغة الرياضيات ولم تترجم",
106
+ "DISPUTED": "متنازع عليها: القارئان يقترحان جملتين مختلفتين",
107
+ "NOT COVERED": "خارج ما تغطيه هذه الطبقة",
108
+ "AMBIGUOUS": "مبهمة: أكثر من قراءة ممكنة",
109
+ "SINGLE": "قراءة واحدة: القارئ الآخر لم يتعرف على الجملة",
110
+ "TAMPERED": "محرفة: الجملة المرسلة إلى الطبقة الرياضية ليست القراءة المتفق عليها",
111
+ "NONE": "لا قراءة"
112
+ },
113
+ "reasons": {
114
+ "unknown_word": "الكلمة {word} ليست من كلمات هذه العربية",
115
+ "no_verb": "لا كلمة تعلن نوع المسألة في هذه العربية",
116
+ "two_verbs": "الجملة تعلن أكثر من نوع للمسألة: {kinds}",
117
+ "no_pattern": "شكل الجملة لا يطابق أي شكل تغطيه هذه العربية",
118
+ "no_frame": "الروابط لا تطابق أي شكل للنوع {kind}",
119
+ "multiple": "للجملة قراءتان مختلفتان: {first} و {second}",
120
+ "disagree": "القارئان يقترحان جملتين مختلفتين بلغة الرياضيات",
121
+ "markers": "روابط الجملة ليست هي الروابط المتوقعة لهذا النوع",
122
+ "bad_variable": "{slot} ليست متغيرا واحدا من متغيرات لغة الرياضيات",
123
+ "bad_matrix": "{slot} ليست مصفوفة مكتوبة بين قوسين مربعين مزدوجين",
124
+ "unbalanced": "قوس أو قوس مربع غير مغلق",
125
+ "no_math": "الجزء الرياضي غير مكتوب برموز لغة الرياضيات",
126
+ "literal_count": "أعداد الجملة ليست هي نفسها عند القارئين",
127
+ "math_unknown": "الطبقة الرياضية لا تقبل الجملة: {detail}",
128
+ "boundary": "الجملة المرسلة إلى الطبقة الرياضية ليست هي المتفق عليها",
129
+ "referee": "الحكم SMT لا يؤكد {detail}",
130
+ "domain_letter": "اكتب المجال بالكلمات (مثلا: في الأعداد الصحيحة) لا بحرف مفرد",
131
+ "other": "لم تصل القراءة إلى جملة بلغة الرياضيات"
132
+ },
133
+ "examples": [
134
+ "احسب ١/٢ + ١/٣",
135
+ "أثبت أن x^٢ + ١ > ٠",
136
+ "حل x^٢ - ٥*x + ٦ = ٠ إيجاد x",
137
+ "احسب محدد المصفوفة [[١, ٢], [٣, ٤]]",
138
+ "تكامل ٣*x^٢ من ٠ إلى ٢",
139
+ "حل n mod ٣ = ١ لإيجاد n في الأعداد الصحيحة",
140
+ "عظم ٣*x + ٤*y شرط x + y <= ١٠"
141
+ ]
142
+ }
lexicon/en.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "en",
3
+ "name": "English",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "evaluate": {
9
+ "verbs": ["evaluate", "compute", "calculate", "what is", "value"],
10
+ "neutral": true,
11
+ "patterns": ["evaluate {T}", "compute {T}", "calculate {T}", "what is {T}", "what is the value of {T}", "the value of {T}"],
12
+ "frame": {"sequences": [[]]}
13
+ },
14
+ "prove": {
15
+ "verbs": ["prove", "show", "verify"],
16
+ "patterns": ["prove that {F}", "prove {F}", "show that {F}", "verify that {F}"],
17
+ "frame": {"sequences": [[]]}
18
+ },
19
+ "provez": {
20
+ "verbs": ["prove", "show", "verify"],
21
+ "patterns": ["prove that {F} over the integers", "prove {F} over the integers", "show that {F} over the integers"],
22
+ "frame": {"sequences": [["over_z"]]}
23
+ },
24
+ "solve": {
25
+ "verbs": ["solve", "find"],
26
+ "patterns": ["solve {F} for {V}", "for {V} solve {F}", "solve {F} with respect to {V}"],
27
+ "frame": {"sequences": [["for"], ["wrt"]]}
28
+ },
29
+ "solvez": {
30
+ "verbs": ["solve", "find"],
31
+ "patterns": ["solve {F} for {V} over the integers", "solve {F} for {V} over the set of integers"],
32
+ "frame": {"sequences": [["for", "over_z"]]}
33
+ },
34
+ "derivative": {
35
+ "verbs": ["derivative", "differentiate"],
36
+ "patterns": ["the derivative of {T}", "derivative of {T}", "differentiate {T}", "the derivative of {T} with respect to {V}", "differentiate {T} with respect to {V}"],
37
+ "frame": {"sequences": [[], ["wrt"]]}
38
+ },
39
+ "integral": {
40
+ "verbs": ["integral", "integrate"],
41
+ "patterns": ["the integral of {T} from {A} to {B}", "integrate {T} from {A} to {B}", "compute the integral of {T} from {A} to {B}", "integrate {T} from {A} to {B} with respect to {V}"],
42
+ "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]}
43
+ },
44
+ "det": {
45
+ "verbs": ["determinant", "det"],
46
+ "patterns": ["the determinant of {M}", "determinant of {M}", "det {M}", "what is the determinant of {M}"],
47
+ "frame": {"sequences": [[]]}
48
+ },
49
+ "rank": {
50
+ "verbs": ["rank"],
51
+ "patterns": ["the rank of {M}", "rank of {M}", "what is the rank of {M}"],
52
+ "frame": {"sequences": [[]]}
53
+ },
54
+ "inverse": {
55
+ "verbs": ["inverse", "invert"],
56
+ "patterns": ["the inverse of {M}", "inverse of {M}", "invert {M}", "what is the inverse of {M}"],
57
+ "frame": {"sequences": [[]]}
58
+ },
59
+ "maximize": {
60
+ "verbs": ["maximize", "maximum"],
61
+ "patterns": ["maximize {T} subject to {F}", "maximize {T} under the constraints {F}", "the maximum of {T} subject to {F}"],
62
+ "frame": {"sequences": [["subject_to"]]}
63
+ },
64
+ "minimize": {
65
+ "verbs": ["minimize", "minimum"],
66
+ "patterns": ["minimize {T} subject to {F}", "minimize {T} under the constraints {F}", "the minimum of {T} subject to {F}"],
67
+ "frame": {"sequences": [["subject_to"]]}
68
+ }
69
+ },
70
+ "connectives": {
71
+ "and": ["and"],
72
+ "or": ["or"],
73
+ "not": ["not"],
74
+ "ge": ["at least", "greater than or equal to", "no less than"],
75
+ "le": ["at most", "less than or equal to", "no more than"],
76
+ "gt": ["greater than", "more than", "strictly greater than"],
77
+ "lt": ["less than", "fewer than", "strictly less than"],
78
+ "eq": ["equal to", "equals"],
79
+ "ne": ["not equal to", "different from", "distinct from"]
80
+ },
81
+ "markers": {
82
+ "for": ["for"],
83
+ "over_z": ["over the integers", "over the set of integers", "on the integers"],
84
+ "subject_to": ["subject to", "under the constraints", "given the constraints"],
85
+ "from": ["from"],
86
+ "to": ["to"],
87
+ "wrt": ["wrt", "with respect to"]
88
+ },
89
+ "noise": ["the", "a", "an", "of", "is", "are", "what", "please", "tell", "me", "us", "that", "this", "it", "does"],
90
+ "labels": {
91
+ "understood": "Problem as understood",
92
+ "status": "Status",
93
+ "assurance": "level {n} of 3",
94
+ "answer": "Answer",
95
+ "reading": "Reading",
96
+ "math_layer": "math layer",
97
+ "notes": "Notes",
98
+ "examples": "Sentences this layer understands",
99
+ "question": "Ask again in one of these forms",
100
+ "check": "SMT check of the layer : {a} of {b} envelopes confirmed",
101
+ "kind_of": "kind"
102
+ },
103
+ "reading": {
104
+ "AGREED": "agreed: two independent readers plus the SMT constraint",
105
+ "PASSTHROUGH": "sentence already written in the math language, not translated",
106
+ "DISPUTED": "disputed: the two readers propose different sentences",
107
+ "NOT COVERED": "outside what this language variety covers",
108
+ "AMBIGUOUS": "ambiguous: more than one reading is possible",
109
+ "TAMPERED": "tampered: the sentence sent to the math layer is not the agreed reading",
110
+ "SINGLE": "a single reading: the other reader did not recognise the sentence",
111
+ "NONE": "no reading"
112
+ },
113
+ "reasons": {
114
+ "unknown_word": "the word {word} is not one of the words this English covers",
115
+ "no_verb": "no word announces the kind of problem in this English",
116
+ "two_verbs": "the sentence announces more than one kind of problem: {kinds}",
117
+ "no_pattern": "the shape of the sentence matches no shape this English covers",
118
+ "no_frame": "the connectives do not match any shape of the kind {kind}",
119
+ "multiple": "the sentence has two different readings: {first} and {second}",
120
+ "disagree": "the two readers propose two different sentences of the math language",
121
+ "markers": "the connectives of the sentence are not the ones the kind expects",
122
+ "bad_variable": "{slot} is not a single variable of the math language",
123
+ "bad_matrix": "{slot} is not a matrix written between double square brackets",
124
+ "unbalanced": "a bracket or a square bracket is not closed",
125
+ "no_math": "the mathematics is not written with the symbols of the math language",
126
+ "literal_count": "the numbers of the sentence are not the same in the two readers",
127
+ "math_unknown": "the math layer does not accept the sentence: {detail}",
128
+ "boundary": "the sentence sent to the math layer is not the agreed one",
129
+ "referee": "the SMT referee does not confirm {detail}",
130
+ "domain_letter": "write the domain in words (for example: over the integers), not as a lone letter",
131
+ "other": "the reading did not reach a sentence of the math language"
132
+ },
133
+ "examples": [
134
+ "evaluate 1/2 + 1/3",
135
+ "prove that x^2 + 1 > 0",
136
+ "solve x^2 - 5*x + 6 = 0 for x",
137
+ "what is the determinant of [[1, 2], [3, 4]]",
138
+ "integrate 3*x^2 from 0 to 2",
139
+ "solve n mod 3 = 1 for n over the integers",
140
+ "maximize 3*x + 4*y subject to x + y <= 10"
141
+ ]
142
+ }
lexicon/es.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "es",
3
+ "name": "español",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "evaluate": {
9
+ "verbs": ["calcula", "calcular", "evalúa", "cuánto vale", "valor"],
10
+ "neutral": true,
11
+ "patterns": ["calcula {T}", "calcula el valor de {T}", "cuánto vale {T}", "evalúa {T}", "el valor de {T}"],
12
+ "frame": {"sequences": [[]]}
13
+ },
14
+ "prove": {
15
+ "verbs": ["demuestra", "demuestra que", "prueba", "prueba que", "verifica"],
16
+ "patterns": ["demuestra que {F}", "demuestra {F}", "prueba que {F}", "verifica que {F}"],
17
+ "frame": {"sequences": [[]]}
18
+ },
19
+ "provez": {
20
+ "verbs": ["demuestra", "prueba", "verifica"],
21
+ "patterns": ["demuestra que {F} sobre los enteros", "prueba que {F} en los números enteros", "demuestra {F} sobre los enteros"],
22
+ "frame": {"sequences": [["over_z"]]}
23
+ },
24
+ "solve": {
25
+ "verbs": ["resuelve", "resolver", "halla"],
26
+ "patterns": ["resuelve {F} para {V}", "para {V} resuelve {F}", "resuelve {F} con respecto a {V}"],
27
+ "frame": {"sequences": [["for"], ["wrt"]]}
28
+ },
29
+ "solvez": {
30
+ "verbs": ["resuelve", "halla"],
31
+ "patterns": ["resuelve {F} para {V} sobre los enteros", "resuelve {F} para {V} en los números enteros"],
32
+ "frame": {"sequences": [["for", "over_z"]]}
33
+ },
34
+ "derivative": {
35
+ "verbs": ["derivada", "deriva", "derivar"],
36
+ "patterns": ["la derivada de {T}", "derivada de {T}", "derivada de {T} con respecto a {V}", "deriva {T}", "calcula la derivada de {T}", "deriva {T} con respecto a {V}"],
37
+ "frame": {"sequences": [[], ["wrt"]]}
38
+ },
39
+ "integral": {
40
+ "verbs": ["integral", "integra", "integrar"],
41
+ "patterns": ["la integral de {T} desde {A} hasta {B}", "integra {T} desde {A} hasta {B}", "calcula la integral de {T} desde {A} hasta {B}", "integra {T} desde {A} hasta {B} con respecto a {V}"],
42
+ "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"]]}
43
+ },
44
+ "det": {
45
+ "verbs": ["determinante", "det"],
46
+ "patterns": ["el determinante de {M}", "determinante de {M}", "det {M}"],
47
+ "frame": {"sequences": [[]]}
48
+ },
49
+ "rank": {
50
+ "verbs": ["rango"],
51
+ "patterns": ["el rango de {M}", "rango de {M}"],
52
+ "frame": {"sequences": [[]]}
53
+ },
54
+ "inverse": {
55
+ "verbs": ["inversa", "invertir", "invierte"],
56
+ "patterns": ["la inversa de {M}", "inversa de {M}", "la matriz inversa de {M}", "invierte {M}"],
57
+ "frame": {"sequences": [[]]}
58
+ },
59
+ "maximize": {
60
+ "verbs": ["maximiza", "máximo"],
61
+ "patterns": ["maximiza {T} sujeto a {F}", "maximiza {T} bajo las restricciones {F}", "el máximo de {T} sujeto a {F}"],
62
+ "frame": {"sequences": [["subject_to"]]}
63
+ },
64
+ "minimize": {
65
+ "verbs": ["minimiza", "mínimo"],
66
+ "patterns": ["minimiza {T} sujeto a {F}", "minimiza {T} bajo las restricciones {F}", "el mínimo de {T} sujeto a {F}"],
67
+ "frame": {"sequences": [["subject_to"]]}
68
+ }
69
+ },
70
+ "connectives": {
71
+ "and": ["y"],
72
+ "or": ["o"],
73
+ "not": ["no"],
74
+ "ge": ["al menos", "mayor o igual que", "no menor que"],
75
+ "le": ["a lo sumo", "como máximo", "menor o igual que", "no mayor que"],
76
+ "gt": ["mayor que", "estrictamente mayor que"],
77
+ "lt": ["menor que", "estrictamente menor que"],
78
+ "eq": ["igual a", "es igual a"],
79
+ "ne": ["distinto de", "diferente de"]
80
+ },
81
+ "markers": {
82
+ "for": ["para"],
83
+ "over_z": ["sobre los enteros", "en los números enteros", "sobre el conjunto de los enteros"],
84
+ "subject_to": ["sujeto a", "sujeta a", "bajo las restricciones"],
85
+ "from": ["desde"],
86
+ "to": ["hasta"],
87
+ "wrt": ["respecto a", "con respecto a"]
88
+ },
89
+ "noise": ["el", "la", "los", "las", "un", "una", "de", "del", "que", "en", "es", "cuánto", "por", "favor", "dime", "nos", "está"],
90
+ "labels": {
91
+ "understood": "Problema entendido",
92
+ "status": "Estado",
93
+ "assurance": "nivel {n} de 3",
94
+ "answer": "Respuesta",
95
+ "reading": "Lectura",
96
+ "math_layer": "capa matemática",
97
+ "notes": "Notas",
98
+ "examples": "Frases que esta capa entiende",
99
+ "question": "Vuelve a preguntar en una de estas formas",
100
+ "check": "Comprobación SMT de la capa : {a} de {b} sobres confirmados",
101
+ "kind_of": "tipo"
102
+ },
103
+ "reading": {
104
+ "AGREED": "acordada: dos lectores independientes más la restricción SMT",
105
+ "PASSTHROUGH": "frase ya escrita en el lenguaje matemático, no traducida",
106
+ "DISPUTED": "en disputa: los dos lectores proponen frases distintas",
107
+ "NOT COVERED": "fuera de lo que esta variedad cubre",
108
+ "AMBIGUOUS": "ambigua: hay más de una lectura posible",
109
+ "SINGLE": "una sola lectura: el otro lector no reconoció la frase",
110
+ "TAMPERED": "alterada: la frase enviada a la capa matemática no es la lectura acordada",
111
+ "NONE": "sin lectura"
112
+ },
113
+ "reasons": {
114
+ "unknown_word": "la palabra {word} no está entre las frases cubiertas en español",
115
+ "no_verb": "ninguna palabra anuncia el tipo de problema en español",
116
+ "two_verbs": "la frase anuncia más de un tipo de problema: {kinds}",
117
+ "no_pattern": "la forma de la frase no corresponde a ninguna forma cubierta en español",
118
+ "no_frame": "los conectores no corresponden a ninguna forma del tipo {kind}",
119
+ "multiple": "la misma frase tiene dos lecturas distintas: {first} y {second}",
120
+ "disagree": "los dos lectores proponen dos frases del lenguaje matemático diferentes",
121
+ "markers": "los conectores de la frase no son los que espera el tipo de problema",
122
+ "bad_variable": "{slot} no es una única variable del lenguaje matemático",
123
+ "bad_matrix": "{slot} no es una matriz escrita entre doble corchete",
124
+ "unbalanced": "un paréntesis o un corchete no está cerrado",
125
+ "no_math": "las matemáticas no están escritas con los símbolos del lenguaje matemático",
126
+ "literal_count": "los números de la frase no son los mismos en los dos lectores",
127
+ "math_unknown": "la capa matemática no acepta la frase: {detail}",
128
+ "boundary": "la frase enviada a la capa matemática no es la acordada",
129
+ "referee": "el árbitro SMT no confirma {detail}",
130
+ "domain_letter": "escribe el dominio con palabras (por ejemplo: sobre los enteros), no como una letra suelta",
131
+ "other": "la lectura no llegó a una frase del lenguaje matemático"
132
+ },
133
+ "examples": [
134
+ "calcula 1/2 + 1/3",
135
+ "demuestra que x^2 + 1 > 0",
136
+ "resuelve x^2 - 5*x + 6 = 0 para x",
137
+ "el determinante de [[1, 2], [3, 4]]",
138
+ "la integral de 3*x^2 desde 0 hasta 2",
139
+ "resuelve n mod 3 = 1 para n sobre los enteros",
140
+ "maximiza 3*x + 4*y sujeto a x + y <= 10"
141
+ ]
142
+ }
lexicon/hi.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "hi",
3
+ "name": "हिन्दी",
4
+ "script": "devanagari",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "evaluate": {
9
+ "verbs": ["गणना करें", "गणना", "मान"],
10
+ "neutral": true,
11
+ "patterns": ["गणना करें {T}", "{T} की गणना करें", "{T} का मान", "{T} का मान बताइए", "मान बताइए {T}"],
12
+ "frame": {"sequences": [[]]}
13
+ },
14
+ "prove": {
15
+ "verbs": ["सिद्ध करें", "सिद्ध", "दिखाएँ", "सत्यापित करें"],
16
+ "patterns": ["सिद्ध करें {F}", "{F} सिद्ध करें", "यह सिद्ध करें {F}", "दिखाएँ {F}", "सत्यापित करें {F}"],
17
+ "frame": {"sequences": [[]]}
18
+ },
19
+ "provez": {
20
+ "verbs": ["सिद्ध करें", "सिद्ध", "दिखाएँ", "सत्यापित करें"],
21
+ "patterns": ["सिद्ध करें {F} पूर्णांकों में", "{F} सिद्ध करें पूर्णांकों में", "{F} पूर्णांकों में सिद्ध करें", "दिखाएँ {F} पूर्णांकों में"],
22
+ "frame": {"sequences": [["over_z"]]}
23
+ },
24
+ "solve": {
25
+ "verbs": ["हल करें", "हल", "ज्ञात करें", "ज्ञात"],
26
+ "patterns": ["हल करें {F} के लिए {V}", "{F} के लिए {V} हल करें", "ज्ञात करें {F} के लिए {V}", "{V} के लिए {F} का हल", "हल करें {F} का {V} के सापेक्ष"],
27
+ "frame": {"sequences": [["for"], ["wrt"]]}
28
+ },
29
+ "solvez": {
30
+ "verbs": ["हल करें", "हल", "ज्ञात करें", "ज्ञात"],
31
+ "patterns": ["हल करें {F} के लिए {V} पूर्णांकों में", "{F} के लिए {V} पूर्णांकों में हल करें", "ज्ञात करें {F} के लिए {V} पूर्णांकों में", "हल करें {F} के लिए {V} पूर्णांकों पर"],
32
+ "frame": {"sequences": [["for", "over_z"]]}
33
+ },
34
+ "derivative": {
35
+ "verbs": ["अवकलज", "अवकलन", "अवकलन करें"],
36
+ "patterns": ["{T} का अवकलज", "अवकलन करें {T}", "{T} का {V} के सापेक्ष अवकलज", "अवकलन करें {T} का {V} के सापेक्ष"],
37
+ "frame": {"sequences": [[], ["wrt"]]}
38
+ },
39
+ "integral": {
40
+ "verbs": ["समाकलन", "समाकलन करें"],
41
+ "patterns": ["{T} का समाकलन {A} से {B} तक", "समाकलन करें {T} का {A} से {B} तक", "{T} का {V} के सापेक्ष समाकलन {A} से {B} तक", "समाकलन करें {T} का {V} के सापेक्ष {A} से {B} तक"],
42
+ "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]}
43
+ },
44
+ "det": {
45
+ "verbs": ["सारणिक"],
46
+ "patterns": ["{M} का सारणिक", "{M} का सारणिक बताइए", "सारणिक बताइए {M}"],
47
+ "frame": {"sequences": [[]]}
48
+ },
49
+ "rank": {
50
+ "verbs": ["कोटि"],
51
+ "patterns": ["{M} की कोटि", "{M} की कोटि बताइए", "कोटि बताइए {M}"],
52
+ "frame": {"sequences": [[]]}
53
+ },
54
+ "inverse": {
55
+ "verbs": ["व्युत्क्रम"],
56
+ "patterns": ["{M} का व्युत्क्रम", "{M} का व्युत्क्रम बताइए", "व्युत्क्रम बताइए {M}"],
57
+ "frame": {"sequences": [[]]}
58
+ },
59
+ "maximize": {
60
+ "verbs": ["अधिकतम", "अधिकतम करें"],
61
+ "patterns": ["अधिकतम करें {T} के अधीन {F}", "{T} के अधीन {F} अधिकतम करें", "{T} का अधिकतम के अधीन {F}"],
62
+ "frame": {"sequences": [["subject_to"]]}
63
+ },
64
+ "minimize": {
65
+ "verbs": ["न्यूनतम", "न्यूनतम करें"],
66
+ "patterns": ["न्यूनतम करें {T} के अधीन {F}", "{T} के अधीन {F} न्यूनतम करें", "{T} का न्यूनतम के अधीन {F}"],
67
+ "frame": {"sequences": [["subject_to"]]}
68
+ }
69
+ },
70
+ "connectives": {
71
+ "and": ["तथा", "और"],
72
+ "or": ["अथवा", "या"],
73
+ "not": ["नहीं"],
74
+ "ge": ["कम से कम", "के बराबर या उससे अधिक"],
75
+ "le": ["अधिक से अधिक", "के बराबर या उससे कम"],
76
+ "gt": ["से बड़ा", "से अधिक"],
77
+ "lt": ["से छोटा", "से कम"],
78
+ "eq": ["के बराबर", "बराबर"],
79
+ "ne": ["के बराबर नहीं", "असमान"]
80
+ },
81
+ "markers": {
82
+ "for": ["के लिए"],
83
+ "over_z": ["पूर्णांकों में", "पूर्णांकों पर"],
84
+ "subject_to": ["के अधीन"],
85
+ "from": ["से"],
86
+ "to": ["तक"],
87
+ "wrt": ["के सापेक्ष"]
88
+ },
89
+ "noise": ["का", "की", "के", "को", "है", "हैं", "हो", "कि", "यह", "क्या", "मुझे", "कृपया", "बताइए", "दीजिए"],
90
+ "labels": {
91
+ "understood": "समझी गई समस्या",
92
+ "status": "स्थिति",
93
+ "assurance": "तीन में से {n} स्तर",
94
+ "answer": "उत्तर",
95
+ "reading": "अर्थ",
96
+ "math_layer": "गणितीय स्तर",
97
+ "notes": "टिप्पणियाँ",
98
+ "examples": "ये वाक्य यह स्तर समझता है",
99
+ "question": "इनमें से किसी एक रूप में फिर पूछें",
100
+ "check": "इस स्तर की SMT जाँच : कुल {b} में से {a} रूप पुष्ट हुए",
101
+ "kind_of": "प्रकार"
102
+ },
103
+ "reading": {
104
+ "AGREED": "सहमत : दो स्वतंत्र पाठक और SMT प्रतिबंध",
105
+ "PASSTHROUGH": "वाक्य पहले से गणितीय भाषा में लिखा है, अनुवादित नहीं किया",
106
+ "DISPUTED": "विवादित : दोनों पाठक अलग-अलग वाक्य प्रस्तावित करते हैं",
107
+ "NOT COVERED": "इस भाषा-शैली की पहुँच से बाहर",
108
+ "AMBIGUOUS": "अस्पष्ट : एक से अधिक अर्थ संभव हैं",
109
+ "SINGLE": "एक ही अर्थ : दूसरे पाठक ने वाक्य नहीं पहचाना",
110
+ "TAMPERED": "छेड़छाड़ : गणितीय स्तर को भेजा गया वाक्य सहमत अर्थ नहीं है",
111
+ "NONE": "कोई अर्थ नहीं"
112
+ },
113
+ "reasons": {
114
+ "unknown_word": "शब्द {word} इस हिन्दी के शब्दों में शामिल नहीं है",
115
+ "no_verb": "इस हिन्दी में समस्या का प्रकार बताने वाला कोई शब्द नहीं है",
116
+ "two_verbs": "यह वाक्य एक से अधिक प्रकार की समस्या बताता है: {kinds}",
117
+ "no_pattern": "वाक्य की बनती इस हिन्दी की किसी बनती से मेल नहीं खाती",
118
+ "no_frame": "संबंधक शब्द प्रकार {kind} की किसी बनती से नहीं मिलते",
119
+ "multiple": "इस वाक्य के दो अलग अर्थ बनते हैं: {first} और {second}",
120
+ "disagree": "दोनों पाठक गणितीय भाषा के दो अलग वाक्य प्रस्तावित करते हैं",
121
+ "markers": "वाक्य के संबंधक शब्द उस प्रकार के लिए अपेक्षित नहीं हैं",
122
+ "bad_variable": "{slot} गणितीय भाषा का एकल चर नहीं है",
123
+ "bad_matrix": "{slot} दोहरी वर्ग कोष्ठकों के बीच लिखा आव्यूह नहीं है",
124
+ "unbalanced": "कोई कोष्ठक या वर्ग कोष्ठक बंद नहीं है",
125
+ "no_math": "गणित गणितीय भाषा के चिह्नों में नहीं लिखा है",
126
+ "literal_count": "वाक्य की संख्याएँ दोनों पाठकों में समान नहीं हैं",
127
+ "math_unknown": "गणितीय स्तर यह वाक्य स्वीकार नहीं करता: {detail}",
128
+ "boundary": "गणितीय स्तर को भेजा गया वाक्य सहमत वाक्य नहीं है",
129
+ "referee": "SMT निर्णायक {detail} की पुष्टि नहीं करता",
130
+ "domain_letter": "क्षेत्र शब्दों में लिखें (जैसे: पूर्णांकों में), केवल अकेले अक्षर के रूप में नहीं",
131
+ "other": "अर्थ ��णितीय भाषा के वाक्य तक नहीं पहुँचा"
132
+ },
133
+ "examples": [
134
+ "गणना करें 1/2 + 1/3",
135
+ "सिद्ध करें x^2 + 1 > 0",
136
+ "हल करें x^2 - 5*x + 6 = 0 के लिए x",
137
+ "[[1, 2], [3, 4]] का सारणिक",
138
+ "समाकलन करें 3*x^2 का 0 से 2 तक",
139
+ "हल करें n mod 3 = 1 के लिए n पूर्णांकों में",
140
+ "अधिकतम करें 3*x + 4*y के अधीन x + y <= 10"
141
+ ]
142
+ }
lexicon/it.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "it",
3
+ "name": "italiano",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "evaluate": {
9
+ "verbs": ["calcola", "calcolare", "quanto fa", "quanto vale", "valuta", "valore"],
10
+ "neutral": true,
11
+ "patterns": ["calcola {T}", "calcola il valore di {T}", "quanto fa {T}", "quanto vale {T}", "valuta {T}", "il valore di {T}"],
12
+ "frame": {"sequences": [[]]}
13
+ },
14
+ "prove": {
15
+ "verbs": ["dimostra", "dimostrare", "prova", "provare", "verifica"],
16
+ "patterns": ["dimostra che {F}", "dimostra {F}", "prova che {F}", "prova {F}", "verifica che {F}"],
17
+ "frame": {"sequences": [[]]}
18
+ },
19
+ "provez": {
20
+ "verbs": ["dimostra", "dimostrare", "prova", "provare", "verifica"],
21
+ "patterns": ["dimostra che {F} sugli interi", "dimostra {F} sugli interi", "prova che {F} negli interi", "dimostra {F} nei numeri interi"],
22
+ "frame": {"sequences": [["over_z"]]}
23
+ },
24
+ "solve": {
25
+ "verbs": ["risolvi", "risolvere", "trova"],
26
+ "patterns": ["risolvi {F} per {V}", "per {V} risolvi {F}", "risolvi {F} rispetto a {V}"],
27
+ "frame": {"sequences": [["for"], ["wrt"]]}
28
+ },
29
+ "solvez": {
30
+ "verbs": ["risolvi", "risolvere", "trova"],
31
+ "patterns": ["risolvi {F} per {V} sugli interi", "risolvi {F} per {V} nei numeri interi"],
32
+ "frame": {"sequences": [["for", "over_z"]]}
33
+ },
34
+ "derivative": {
35
+ "verbs": ["derivata", "deriva", "derivare"],
36
+ "patterns": ["la derivata di {T}", "derivata di {T}", "derivata di {T} rispetto a {V}", "calcola la derivata di {T}", "deriva {T}", "deriva {T} rispetto a {V}"],
37
+ "frame": {"sequences": [[], ["wrt"]]}
38
+ },
39
+ "integral": {
40
+ "verbs": ["integrale", "integrare"],
41
+ "patterns": ["l'integrale di {T} da {A} a {B}", "integrale di {T} da {A} a {B}", "calcola l'integrale di {T} da {A} a {B}", "l'integrale rispetto a {V} di {T} da {A} a {B}"],
42
+ "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]}
43
+ },
44
+ "det": {
45
+ "verbs": ["determinante", "det"],
46
+ "patterns": ["il determinante di {M}", "determinante di {M}", "det {M}"],
47
+ "frame": {"sequences": [[]]}
48
+ },
49
+ "rank": {
50
+ "verbs": ["rango", "rank"],
51
+ "patterns": ["il rango di {M}", "rango di {M}", "rank {M}"],
52
+ "frame": {"sequences": [[]]}
53
+ },
54
+ "inverse": {
55
+ "verbs": ["inversa", "invertire"],
56
+ "patterns": ["l'inversa di {M}", "la inversa di {M}", "inversa di {M}", "la matrice inversa di {M}"],
57
+ "frame": {"sequences": [[]]}
58
+ },
59
+ "maximize": {
60
+ "verbs": ["massimizza", "massimizzare", "massimo"],
61
+ "patterns": ["massimizza {T} soggetto a {F}", "massimizza {T} sotto i vincoli {F}", "il massimo di {T} soggetto a {F}"],
62
+ "frame": {"sequences": [["subject_to"]]}
63
+ },
64
+ "minimize": {
65
+ "verbs": ["minimizza", "minimizzare", "minimo"],
66
+ "patterns": ["minimizza {T} soggetto a {F}", "minimizza {T} sotto i vincoli {F}", "il minimo di {T} soggetto a {F}"],
67
+ "frame": {"sequences": [["subject_to"]]}
68
+ }
69
+ },
70
+ "connectives": {
71
+ "and": ["e", "ed"],
72
+ "or": ["o"],
73
+ "not": ["non"],
74
+ "ge": ["almeno", "maggiore o uguale a", "non minore di"],
75
+ "le": ["al massimo", "minore o uguale a", "non maggiore di"],
76
+ "gt": ["maggiore di", "piu grande di", "strettamente maggiore di"],
77
+ "lt": ["minore di", "piu piccolo di", "strettamente minore di"],
78
+ "eq": ["uguale a", "e uguale a"],
79
+ "ne": ["diverso da", "differente da"]
80
+ },
81
+ "markers": {
82
+ "for": ["per"],
83
+ "over_z": ["sugli interi", "negli interi", "nei numeri interi"],
84
+ "subject_to": ["soggetto a", "soggetta a", "sotto i vincoli"],
85
+ "from": ["da"],
86
+ "to": ["a"],
87
+ "wrt": ["rispetto a"]
88
+ },
89
+ "noise": ["il", "la", "lo", "i", "le", "gli", "un", "uno", "una", "l", "di", "del", "della", "dei", "delle", "che", "in", "con", "quale", "qual", "cos", "cosa"],
90
+ "labels": {
91
+ "understood": "Problema capito",
92
+ "status": "Stato",
93
+ "assurance": "livello {n} di 3",
94
+ "answer": "Risposta",
95
+ "reading": "Lettura",
96
+ "math_layer": "strato matematico",
97
+ "notes": "Note",
98
+ "examples": "Frasi che questo strato capisce",
99
+ "question": "Riformula la domanda in una di queste forme",
100
+ "check": "Controllo SMT dello strato : {a} di {b} buste confermate",
101
+ "kind_of": "tipo"
102
+ },
103
+ "reading": {
104
+ "AGREED": "accordata: due lettori indipendenti piu il vincolo SMT",
105
+ "PASSTHROUGH": "frase gia scritta nella lingua matematica, non tradotta",
106
+ "DISPUTED": "in disputa: i due lettori propongono frasi diverse",
107
+ "NOT COVERED": "fuori dalla copertura di questa lingua",
108
+ "AMBIGUOUS": "ambigua: piu letture possibili",
109
+ "TAMPERED": "manomessa: il testo passato allo strato matematico non e la lettura concordata",
110
+ "SINGLE": "una sola lettura: l'altro lettore non ha riconosciuto la frase",
111
+ "NONE": "nessuna lettura"
112
+ },
113
+ "reasons": {
114
+ "unknown_word": "la parola {word} non compare nelle frasi coperte in italiano",
115
+ "no_verb": "nessuna parola annuncia il tipo di problema in italiano",
116
+ "two_verbs": "la frase annuncia piu di un tipo di problema: {kinds}",
117
+ "no_pattern": "la forma della frase non corrisponde a nessuna forma coperta in italiano",
118
+ "no_frame": "i connettori non corrispondono ad alcuna forma del tipo {kind}",
119
+ "multiple": "della stessa frase esistono due letture diverse: {first} e {second}",
120
+ "disagree": "i due lettori propongono due frasi della lingua matematica diverse",
121
+ "markers": "i connettori della frase non sono quelli attesi per il tipo di problema",
122
+ "bad_variable": "{slot} non e una singola variabile della lingua matematica",
123
+ "bad_matrix": "{slot} non e una matrice scritta tra doppie parentesi quadre",
124
+ "unbalanced": "parentesi o parentesi quadre non chiuse",
125
+ "no_math": "la parte matematica non e scritta con i simboli della lingua matematica",
126
+ "literal_count": "i numeri della frase non sono gli stessi nei due lettori",
127
+ "math_unknown": "lo strato matematico non accetta la frase: {detail}",
128
+ "boundary": "la frase passata allo strato matematico non e quella concordata",
129
+ "referee": "il controllore SMT non conferma {detail}",
130
+ "domain_letter": "il dominio va scritto a parole (ad esempio: sugli interi), non come lettera isolata",
131
+ "other": "la lettura non e arrivata a una frase della lingua matematica"
132
+ },
133
+ "examples": [
134
+ "calcola 1/2 + 1/3",
135
+ "dimostra che x^2 + 1 > 0",
136
+ "risolvi x^2 - 5*x + 6 = 0 per x",
137
+ "qual è il determinante di [[1, 2], [3, 4]]",
138
+ "l'integrale di 3*x^2 da 0 a 2",
139
+ "risolvi n mod 3 = 1 per n sugli interi",
140
+ "massimizza 3*x + 4*y soggetto a x + y <= 10"
141
+ ]
142
+ }
lexicon/zh.json ADDED
@@ -0,0 +1,142 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "zh",
3
+ "name": "中文",
4
+ "script": "cjk",
5
+ "noise_chars": "的了之把被给吧呢吗也则该",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "evaluate": {
9
+ "verbs": ["计算", "值"],
10
+ "neutral": true,
11
+ "patterns": ["计算 {T}", "请 计算 {T}", "求 {T} 的 值", "{T} 的 值", "计算 {T} 的 值"],
12
+ "frame": {"sequences": [[]]}
13
+ },
14
+ "prove": {
15
+ "verbs": ["证明", "求证"],
16
+ "patterns": ["证明 {F}", "求证 {F}", "请 证明 {F}", "试 证明 {F}", "{F} 的 证明"],
17
+ "frame": {"sequences": [[]]}
18
+ },
19
+ "provez": {
20
+ "verbs": ["证明", "求证"],
21
+ "patterns": ["证明 {F} 在整数上", "求证 {F} 在整数上", "在整数上 证明 {F}", "证明 {F} 在整数范围内", "求证 {F} 在整数范围内"],
22
+ "frame": {"sequences": [["over_z"]]}
23
+ },
24
+ "solve": {
25
+ "verbs": ["解", "求解"],
26
+ "patterns": ["求解 {F} 对 {V}", "解 {F} 对 {V}", "对 {V} 求解 {F}", "求解 {F} 关于 {V}", "解 {F} 关于 {V}"],
27
+ "frame": {"sequences": [["for"], ["wrt"]]}
28
+ },
29
+ "solvez": {
30
+ "verbs": ["解", "求解"],
31
+ "patterns": ["求解 {F} 对 {V} 在整数上", "解 {F} 对 {V} 在整数上", "求解 {F} 对 {V} 在整数范围内", "解 {F} 对 {V} 在整数范围内"],
32
+ "frame": {"sequences": [["for", "over_z"]]}
33
+ },
34
+ "derivative": {
35
+ "verbs": ["导数", "导函数"],
36
+ "patterns": ["求 {T} 的 导数", "{T} 的 导数", "求 {T} 关于 {V} 的 导数", "{T} 关于 {V} 的 导数", "{T} 的 导函数"],
37
+ "frame": {"sequences": [[], ["wrt"]]}
38
+ },
39
+ "integral": {
40
+ "verbs": ["积分", "定积分"],
41
+ "patterns": ["求 {T} 从 {A} 到 {B} 的 积分", "{T} 从 {A} 到 {B} 的 积分", "计算 {T} 从 {A} 到 {B} 的 积分", "求 {T} 关于 {V} 从 {A} 到 {B} 的 积分", "{T} 从 {A} 到 {B} 关于 {V} 的 积分", "{T} 从 {A} 到 {B} 的 定积分"],
42
+ "frame": {"sequences": [["from", "to"], ["from", "to", "wrt"], ["wrt", "from", "to"]]}
43
+ },
44
+ "det": {
45
+ "verbs": ["行列式"],
46
+ "patterns": ["求 {M} 的 行列式", "{M} 的 行列式", "计算 {M} 的 行列式"],
47
+ "frame": {"sequences": [[]]}
48
+ },
49
+ "rank": {
50
+ "verbs": ["秩"],
51
+ "patterns": ["求 {M} 的 秩", "{M} 的 秩", "计算 {M} 的 秩"],
52
+ "frame": {"sequences": [[]]}
53
+ },
54
+ "inverse": {
55
+ "verbs": ["逆", "逆矩阵"],
56
+ "patterns": ["求 {M} 的 逆", "{M} 的 逆", "求 {M} 的 逆矩阵", "{M} 的 逆矩阵"],
57
+ "frame": {"sequences": [[]]}
58
+ },
59
+ "maximize": {
60
+ "verbs": ["最大化", "最大值"],
61
+ "patterns": ["最大化 {T} 约束 {F}", "最大化 {T} 约束条件 {F}", "求 {T} 的 最大值 约束 {F}", "{T} 的 最大值 约束 {F}", "在约束条件下 最大化 {T}"],
62
+ "frame": {"sequences": [["subject_to"]]}
63
+ },
64
+ "minimize": {
65
+ "verbs": ["最小化", "最小值"],
66
+ "patterns": ["最小化 {T} 约束 {F}", "最小化 {T} 约束条件 {F}", "求 {T} 的 最小值 约束 {F}", "{T} 的 最小值 约束 {F}", "在约束条件下 最小化 {T}"],
67
+ "frame": {"sequences": [["subject_to"]]}
68
+ }
69
+ },
70
+ "connectives": {
71
+ "and": ["且", "和", "与"],
72
+ "or": ["或", "或者"],
73
+ "not": ["非"],
74
+ "ge": ["大于等于", "不小于", "至少"],
75
+ "le": ["小于等于", "不大于", "至多"],
76
+ "gt": ["大于", "严格大于"],
77
+ "lt": ["小于", "严格小于"],
78
+ "eq": ["等于"],
79
+ "ne": ["不等于"]
80
+ },
81
+ "markers": {
82
+ "for": ["对"],
83
+ "over_z": ["在整数上", "在整数范围内"],
84
+ "subject_to": ["约束", "约束条件", "在约束条件下"],
85
+ "from": ["从"],
86
+ "to": ["到"],
87
+ "wrt": ["关于"]
88
+ },
89
+ "noise": ["求", "请", "试", "是", "为"],
90
+ "labels": {
91
+ "understood": "理解的问题",
92
+ "status": "状态",
93
+ "assurance": "三级中的第 {n} 级",
94
+ "answer": "答案",
95
+ "reading": "读法",
96
+ "math_layer": "数学层",
97
+ "notes": "备注",
98
+ "examples": "这一层能理解的句子",
99
+ "question": "请用下列形式之一重述问题",
100
+ "check": "数学层的 SMT 检查:{b} 个信封中有 {a} 个得到确认",
101
+ "kind_of": "类型"
102
+ },
103
+ "reading": {
104
+ "AGREED": "一致:两位独立读者加上 SMT 约束",
105
+ "PASSTHROUGH": "句子已用数学语言写成,未作翻译",
106
+ "DISPUTED": "有分歧:两位读者给出不同的句子",
107
+ "NOT COVERED": "不在这种语言变体所覆盖的范围之内",
108
+ "AMBIGUOUS": "有歧义:可以有不止一种读法",
109
+ "SINGLE": "只有一种读法:另一位读者没有认出这个句子",
110
+ "TAMPERED": "被篡改:送往数学层的句子不是那个一致的读法",
111
+ "NONE": "没有读法"
112
+ },
113
+ "reasons": {
114
+ "unknown_word": "{word} 不属于这种中文所覆盖的词",
115
+ "no_verb": "没有词宣布问题的类型",
116
+ "two_verbs": "句子宣布了不止一种问题类型:{kinds}",
117
+ "no_pattern": "句子的形状不匹配这种中��所覆盖的任何形状",
118
+ "no_frame": "连接词不匹配类型 {kind} 的任何形状",
119
+ "multiple": "同一句子有两种不同的读法:{first} 和 {second}",
120
+ "disagree": "两位读者给出两个不同的数学语言句子",
121
+ "markers": "句子的连接词不是该类型所期待的那些",
122
+ "bad_variable": "{slot} 不是数学语言中的单个变量",
123
+ "bad_matrix": "{slot} 不是写在双方括号之间的矩阵",
124
+ "unbalanced": "有个圆括号或方括号没有闭合",
125
+ "no_math": "数学部分没有用数学语言的符号书写",
126
+ "literal_count": "句子中的数字在两位读者那里并不相同",
127
+ "math_unknown": "数学层不接受这个句子:{detail}",
128
+ "boundary": "送往数学层的句子不是那个一致的读法",
129
+ "referee": "SMT 裁判没有确认 {detail}",
130
+ "domain_letter": "请把定义域用词语写出来(例如:在整数上),不要只用一个孤立的字母",
131
+ "other": "读法没有得到数学语言中的一个句子"
132
+ },
133
+ "examples": [
134
+ "计算 1/2 + 1/3",
135
+ "证明 x^2 + 1 > 0",
136
+ "解 x^2 - 5*x + 6 = 0 对 x",
137
+ "求 [[1, 2], [3, 4]] 的 行列式",
138
+ "求 3*x^2 从 0 到 2 的 积分",
139
+ "解 n mod 3 = 1 对 n 在整数上",
140
+ "最大化 3*x + 4*y 约束 x + y <= 10"
141
+ ]
142
+ }
lgstratum/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The library of the math-stratum topology.
2
+
3
+ The math-stratum is the conversational stratum of the math topology: it accepts a problem
4
+ written in one of six language varieties, reads it into one sentence of the math language,
5
+ hands that sentence to the math stratum as a separate process, and presents the verdict of
6
+ the math stratum back in the language the user wrote in.
7
+
8
+ Two words carry the whole design:
9
+
10
+ * **reading**: what the stratum does is a reading, never a proof. The certainty of a reading
11
+ is not verifiable, because the space of natural language sentences is not. The stratum
12
+ therefore never raises the assurance the math stratum reported, and every stage of the
13
+ reading can only take verdicts away.
14
+ * **coverage**: the multilingual layer is a documented fragment, in the same spirit as the
15
+ fragment of the math language. Anything outside it abstains with a question in the
16
+ language of the user, and never guesses.
17
+ """
18
+
19
+ __all__ = ["agents", "canonical", "compare", "corpus", "coverage", "decide", "faults", "invoker",
20
+ "lexicon", "pipeline", "protocol", "read_a", "read_b", "render", "segment"]
lgstratum/agents.py ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4
+ the next one is supposed to check. The chain is the same shape the math stratum runs, only moved
5
+ one level up: two independent readers instead of two independent formalizers, an equivalence node
6
+ instead of the equivalence checker, a coverage node that counts the numbers the user wrote, an
7
+ invoker that hands the agreed sentence to the math stratum as a separate process, a boundary where
8
+ that verdict enters this stratum, an adversary that re-derives what the others asserted, and an
9
+ 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? SMT2 answers, text identity is a shortcut
14
+ coverage did the readings keep every number the user wrote?
15
+ invoker call the math stratum, in another process, on one sentence
16
+ boundary the math verdict enters this stratum here, and only here
17
+ adversary re-derive the cross-channel checks and the cap the previous nodes implied
18
+ arbiter decide, cap the assurance, answer in the language of the user
19
+
20
+ The invariant every node here obeys, and which the last three nodes each write down as SMT2 so the
21
+ referee of the orchestrator refutes its negation: the assurance this stratum shows is
22
+ ``min(assurance of the math stratum, ceiling of the reading)``, and the ceiling is below the top
23
+ level of the math stratum. A node may lower what the user sees; none may raise it.
24
+ """
25
+
26
+ from typing import Any, Dict, List, Tuple
27
+
28
+ from . import canonical, compare, coverage, decide, faults, invoker, protocol, read_a, read_b, render
29
+
30
+ ORDER = ("reader_a", "reader_b", "equivalence", "coverage", "invoker", "boundary", "adversary", "arbiter")
31
+
32
+
33
+ def _ast(dossier: Dict[str, Any]) -> str:
34
+ """One ASCII line describing the shape of the dossier, for the abstractSyntaxTree field."""
35
+ def status_of(key: str) -> str:
36
+ part = dossier.get(key)
37
+ if not isinstance(part, dict):
38
+ return "absent"
39
+ return str(part.get("status") or part.get("state") or part.get("kind") or "present")
40
+
41
+ return "Stratum(lang=%s, a=%s, b=%s, equiv=%s, cover=%s, math=%s, final=%s)" % (
42
+ dossier.get("lang", "?"), status_of("reading_a"), status_of("reading_b"),
43
+ "same" if (dossier.get("compare") or {}).get("same") else "no",
44
+ "ok" if (dossier.get("coverage") or {}).get("ok") else "no",
45
+ (dossier.get("math") or {}).get("status", "absent"),
46
+ (dossier.get("final") or {}).get("state", "absent"),
47
+ )
48
+
49
+
50
+ def _cap_claim(shown: int, ceiling: int) -> Tuple[List[str], List[str], str]:
51
+ """SMT2 for ``this node raised nothing``: the strict excess over the ceiling is refuted."""
52
+ decls = ["(declare-const shown Real)", "(declare-const ceiling Real)"]
53
+ asserts = ["(assert (= shown %d))" % int(shown), "(assert (= ceiling %d))" % int(ceiling),
54
+ "(assert (> shown ceiling))"]
55
+ return decls, asserts, "unsat"
56
+
57
+
58
+ def _reader_claim(reading: Dict[str, Any], question: str) -> Tuple[List[str], List[str], str]:
59
+ """A reader claims one thing only: it dropped no number the user wrote."""
60
+ step = compare.keeps(reading, question)
61
+ return step["declarations"], step["assertions"], step["claimed"]
62
+
63
+
64
+ def _apply_reader_fault(agent: str, reading: Dict[str, Any]) -> None:
65
+ """Corrupt a reading on purpose, for the ablation experiments: never in a normal session."""
66
+ if not reading.get("kind") or reading.get("status") != "READ":
67
+ return
68
+ for kind in ("drop_marker", "merge_slots", "shift_number"):
69
+ if not faults.has(agent, kind):
70
+ continue
71
+ order = canonical.slots_for(str(reading["kind"]))
72
+ slots, changed = faults.mutate_reading(agent, str(reading["kind"]), dict(reading.get("slots") or {}), order)
73
+ if not changed:
74
+ continue
75
+ faults.fire(agent, kind)
76
+ try:
77
+ reading["math"] = canonical.print_math(str(reading["kind"]), slots)
78
+ reading["slots"] = slots
79
+ reading["fault"] = kind
80
+ except canonical.ReadingError:
81
+ reading["math"] = ""
82
+ reading["status"] = "NOT COVERED"
83
+ reading["notes"].append({"reason": "no_frame", "kind": reading["kind"], "detail": kind})
84
+ return
85
+
86
+
87
+ def _reading_node(agent: str, reader: Any, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
88
+ """Shared body of the two reader nodes: read the question, keep the reading, claim the numbers."""
89
+ dossier, turn, tick, rcpt = protocol.start(incoming)
90
+ question = str(dossier.get("question", ""))
91
+ lang = str(dossier.get("lang") or "")
92
+ direct = canonical.direct(question)
93
+ if direct is not None:
94
+ dossier["reading_direct"] = direct
95
+ reading = direct
96
+ else:
97
+ reading = reader.read(lang, question)
98
+ _apply_reader_fault(node_id, reading)
99
+ dossier[agent] = reading
100
+ decls, asserts, claimed = _reader_claim(reading, question)
101
+ summary = "%s: %s %s" % (node_id, reading.get("status"), reading.get("math") or "")
102
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
103
+
104
+
105
+ def step_reader_a(incoming: Dict[str, Any], node_id: str = "reader_a") -> Dict[str, Any]:
106
+ """Reader A: surface patterns of the variety, reading left to right."""
107
+ return _reading_node("reading_a", read_a, incoming, node_id)
108
+
109
+
110
+ def step_reader_b(incoming: Dict[str, Any], node_id: str = "reader_b") -> Dict[str, Any]:
111
+ """Reader B: the frame of the problem kind and the marker phrases sitting in its gaps."""
112
+ return _reading_node("reading_b", read_b, incoming, node_id)
113
+
114
+
115
+ def step_equivalence(incoming: Dict[str, Any], node_id: str = "equivalence") -> Dict[str, Any]:
116
+ """Are the two readings one problem? The answer carries the SMT2 program that proves it."""
117
+ dossier, turn, tick, rcpt = protocol.start(incoming)
118
+ if faults.has(node_id, "rubber_stamp"):
119
+ faults.fire(node_id, "rubber_stamp")
120
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_a") or {}
121
+ else:
122
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_b") or {}
123
+ direct = dossier.get("reading_direct")
124
+ if direct is not None:
125
+ first, second = direct, dict(dossier.get("reading_b") or direct)
126
+ comparison = compare.equivalence(first, second)
127
+ dossier["compare"] = comparison
128
+ if first.get("math") and (comparison["same"] or not second.get("math")):
129
+ dossier["sent"] = comparison["left"] or str(first["math"])
130
+ elif second.get("math") and not first.get("math"):
131
+ dossier["sent"] = comparison["right"] or str(second["math"])
132
+ summary = "equivalence: %s (%s)" % ("same" if comparison["same"] else "not the same problem",
133
+ comparison["why"])
134
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
135
+ comparison["declarations"], comparison["assertions"], comparison["claimed"])
136
+
137
+
138
+ def step_coverage(incoming: Dict[str, Any], node_id: str = "coverage") -> Dict[str, Any]:
139
+ """Did the readings keep every number the user wrote, and in the same multiset?"""
140
+ dossier, turn, tick, rcpt = protocol.start(incoming)
141
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
142
+ if dossier.get("reading_direct") is not None:
143
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
144
+ if faults.has(node_id, "rubber_stamp"):
145
+ faults.fire(node_id, "rubber_stamp")
146
+ claim = {"ok": True, "wrote": [], "kept": [], "missing": [], "added": [],
147
+ "declarations": ["(declare-const wrote_0 Real)"], "assertions": ["(assert (= wrote_0 0))"],
148
+ "claimed": "sat"}
149
+ else:
150
+ claim = coverage.coverage_claim(str(dossier.get("question", "")), [r for r in readings if r])
151
+ dossier["coverage"] = claim
152
+ summary = "coverage: %s (%d numbers)" % ("kept" if claim["ok"] else "not kept", len(claim["wrote"]))
153
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
154
+ claim["declarations"], claim["assertions"], claim["claimed"])
155
+
156
+
157
+ def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]:
158
+ """Ask the math stratum, in its own process, about the sentence the readers agreed on."""
159
+ dossier, turn, tick, rcpt = protocol.start(incoming)
160
+ sentence = str(dossier.get("sent") or "")
161
+ if not sentence:
162
+ dossier["math"] = invoker.unavailable("no sentence was agreed on")
163
+ summary = "invoker: nothing to ask the math stratum"
164
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
165
+ ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat")
166
+ verdict = invoker.solve(sentence)
167
+ dossier["math"] = verdict
168
+ wrote = compare.sorted_numbers(sentence)
169
+ echo = compare.sorted_numbers(str(verdict.get("problem_math") or ""))
170
+ decls, asserts = compare.elementwise(wrote, echo, "asked")
171
+ summary = "invoker: %s (%s)" % (verdict.get("status"), verdict.get("answer_text") or "no answer")
172
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
173
+ decls, asserts + ["(assert (= 1 1))"] if not decls else asserts,
174
+ "sat" if wrote == echo else "unsat")
175
+
176
+
177
+ def step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]:
178
+ """The math verdict enters this stratum here; the echo it carries is checked, not trusted."""
179
+ dossier, turn, tick, rcpt = protocol.start(incoming)
180
+ reading = dossier.get("reading_a") or dossier.get("reading_direct") or {}
181
+ math_verdict = dict(dossier.get("math") or {})
182
+ agreed = str(dossier.get("sent") or "")
183
+ echo = str(math_verdict.get("problem_math") or "")
184
+ if echo:
185
+ matches = coverage.echo_matches(reading, math_verdict)
186
+ decls, asserts = compare.elementwise(compare.sorted_numbers(agreed), compare.sorted_numbers(echo), "echo")
187
+ claimed = "sat" if matches else "unsat"
188
+ else:
189
+ # The math stratum answered no sentence at all: there is nothing to compare, and the honest
190
+ # claim is the empty one, which is satisfiable. A node that wanted to look busy here would
191
+ # be asserting something it has no evidence about.
192
+ matches = True
193
+ decls, asserts, claimed = [], ["(assert (= 1 1))"], "sat"
194
+ if faults.has(node_id, "tamper_math") and echo:
195
+ tampered, changed = faults.mutate_sentence(node_id, echo)
196
+ if changed:
197
+ faults.fire(node_id, "tamper_math")
198
+ math_verdict["problem_math"] = tampered
199
+ math_verdict["fault"] = "tamper_math"
200
+ dossier["math"] = math_verdict
201
+ dossier["echo_ok"] = bool(matches)
202
+ summary = "boundary: %s echoed=%s" % (math_verdict.get("status"), "yes" if matches else "no")
203
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
204
+ decls, asserts, claimed)
205
+
206
+
207
+ def step_adversary(incoming: Dict[str, Any], node_id: str = "adversary") -> Dict[str, Any]:
208
+ """Re-derive what the previous nodes asserted, and write the cap as an inequality to refute."""
209
+ dossier, turn, tick, rcpt = protocol.start(incoming)
210
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
211
+ if dossier.get("reading_direct") is not None:
212
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
213
+ comparison = dossier.get("compare")
214
+ math_verdict = dossier.get("math") or {}
215
+ cover = dossier.get("coverage")
216
+ if faults.has(node_id, "rubber_stamp"):
217
+ faults.fire(node_id, "rubber_stamp")
218
+ echo_ok = True
219
+ else:
220
+ echo_ok = coverage.echo_matches(readings[0], math_verdict) if math_verdict.get("problem_math") else True
221
+ for other in readings[1:]:
222
+ if other.get("math") and not coverage.echo_matches(other, math_verdict):
223
+ echo_ok = False
224
+ dossier["echo_ok"] = bool(echo_ok)
225
+ state = decide.state_of(readings, comparison, cover, math_verdict if math_verdict.get("status") else None,
226
+ dossier.get("reading_direct"), echo_ok)
227
+ ceiling = decide.CEILING[state]
228
+ shown = min(ceiling, int(math_verdict.get("assurance", 0) or 0))
229
+ dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown,
230
+ "math_assurance": int(math_verdict.get("assurance", 0) or 0)}
231
+ decls, asserts, claimed = _cap_claim(shown, ceiling)
232
+ summary = "adversary: ceiling %d, shown %d, echo %s" % (ceiling, shown, "ok" if echo_ok else "mismatch")
233
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
234
+
235
+
236
+ def step_arbiter(incoming: Dict[str, Any], node_id: str = "arbiter") -> Dict[str, Any]:
237
+ """Decide, cap, and answer in the language the user wrote in."""
238
+ dossier, turn, tick, rcpt = protocol.start(incoming)
239
+ final = decide.decide(dossier)
240
+ if faults.has(node_id, "force_assurance"):
241
+ faults.fire(node_id, "force_assurance")
242
+ final = decide.raise_assurance(final, 3)
243
+ dossier["final"] = final
244
+ dossier["reply"] = render.reply(dossier, final)
245
+ ceiling = int(final.get("ceiling", 0) or 0)
246
+ decls, asserts, claimed = _cap_claim(int(final.get("assurance", 0) or 0), ceiling)
247
+ summary = "arbiter: %s (assurance %d) %s" % (final["state"], final["assurance"], final["answer"] or "")
248
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
249
+
250
+
251
+ STEPS = {
252
+ "reader_a": step_reader_a,
253
+ "reader_b": step_reader_b,
254
+ "equivalence": step_equivalence,
255
+ "coverage": step_coverage,
256
+ "invoker": step_invoker,
257
+ "boundary": step_boundary,
258
+ "adversary": step_adversary,
259
+ "arbiter": step_arbiter,
260
+ }
261
+
262
+
263
+ def run_step(role: str, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
264
+ """Run one role, containing any unexpected exception as a crash entry in the dossier.
265
+
266
+ A node that crashes must not stop the session: the arbiter then reports the state NONE with
267
+ zero assurance, so the user is never left with a half-built answer and never with an invented
268
+ one either.
269
+ """
270
+ try:
271
+ return STEPS[role](incoming, node_id)
272
+ except Exception as exc: # noqa: BLE001 - containment is the whole point of this wrapper
273
+ dossier, turn, tick, rcpt = protocol.start(incoming)
274
+ dossier.setdefault("crash", {})[role] = "%s: %s" % (type(exc).__name__, str(exc)[:120])
275
+ return protocol.envelope(node_id, rcpt, turn, tick, "%s crashed" % role, "Crashed", dossier,
276
+ [], ["(assert true)"], "sat")
lgstratum/canonical.py ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The canonical sentence: one printer for the math language, shared by both readers.
2
+
3
+ A reading is a mapping from a surface sentence to **one sentence of the math language**, which
4
+ is what the math stratum is handed. The printers here are deliberately small and exhaustive:
5
+ each covered kind has a fixed template, so the only freedom a reader has is how it decided the
6
+ kind and where it cut the slots. That decision is what the two readers must agree on.
7
+
8
+ The kinds covered by the multilingual reading layer are a subset of the kinds of the math
9
+ language. The rest of the math language stays available through the direct mode: a sentence
10
+ already written in the math language is passed through untouched.
11
+ """
12
+
13
+ import re
14
+ from typing import Any, Dict, List, Optional, Tuple
15
+
16
+ KINDS = ("evaluate", "prove", "provez", "solve", "solvez", "derivative", "integral",
17
+ "det", "rank", "inverse", "maximize", "minimize")
18
+
19
+ # For each kind, the accepted slot sets and the template each one prints to. A kind with an
20
+ # optional slot (the variable a derivative is taken with respect to) has two entries.
21
+ TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = {
22
+ "evaluate": [(("T",), "evaluate {T}")],
23
+ "prove": [(("F",), "prove {F}")],
24
+ "provez": [(("F",), "prove {F} over Z")],
25
+ "solve": [(("F", "V"), "solve {F} for {V}")],
26
+ "solvez": [(("F", "V"), "solve {F} for {V} over Z")],
27
+ "derivative": [(("T",), "derivative {T}"), (("T", "V"), "derivative {T} wrt {V}")],
28
+ "integral": [(("T", "A", "B"), "integral {T} from {A} to {B}"),
29
+ (("T", "A", "B", "V"), "integral {T} from {A} to {B} wrt {V}")],
30
+ "det": [(("M",), "det {M}")],
31
+ "rank": [(("M",), "rank {M}")],
32
+ "inverse": [(("M",), "inverse {M}")],
33
+ "maximize": [(("T", "F"), "maximize {T} subject to {F}")],
34
+ "minimize": [(("T", "F"), "minimize {T} subject to {F}")],
35
+ }
36
+
37
+ SLOT_ORDER = {kind: [slot for slot, _template in variants]
38
+ for kind, variants in TEMPLATES.items()}
39
+
40
+ VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [slots for slots, _ in variants]
41
+ for kind, variants in TEMPLATES.items()}
42
+
43
+ _VARIABLE = re.compile(r"[A-Za-z]")
44
+
45
+
46
+ class ReadingError(ValueError):
47
+ """A reading cannot be printed as a sentence of the math language."""
48
+
49
+
50
+ def print_math(kind: str, slots: Dict[str, str]) -> str:
51
+ """Print one reading as a sentence of the math language."""
52
+ wanted = tuple(name for name in _order(kind) if name in slots and slots[name] != "")
53
+ for slots_set, template in TEMPLATES[kind]:
54
+ if set(slots_set) == set(wanted):
55
+ missing = [name for name in slots_set if not slots.get(name, "").strip()]
56
+ if missing:
57
+ raise ReadingError("the %s reading has no value for %s" % (kind, ", ".join(missing)))
58
+ extra = [name for name in slots if name not in slots_set]
59
+ if extra:
60
+ raise ReadingError("the %s reading has no slot %s" % (kind, ", ".join(extra)))
61
+ return tidy(template.format(**{name: slots[name] for name in slots_set}))
62
+ raise ReadingError("the %s reading fills the slots %s, which is not a form of the kind"
63
+ % (kind, ", ".join(sorted(wanted))))
64
+
65
+
66
+ def _order(kind: str) -> List[str]:
67
+ if kind not in TEMPLATES:
68
+ raise ReadingError("the kind %s is not one of the kinds the reading layer covers" % kind)
69
+ seen: List[str] = []
70
+ for slots in VARIANTS[kind]:
71
+ for name in slots:
72
+ if name not in seen:
73
+ seen.append(name)
74
+ return seen
75
+
76
+
77
+ def slots_for(kind: str) -> List[str]:
78
+ return _order(kind)
79
+
80
+
81
+ # The words the math language itself uses to hold a slot in place. Reader B reads a sentence by
82
+ # these joints, so it needs them as names, not as text inside a template.
83
+ _MARKER_PHRASE = {"for": "for", "over_z": "over Z", "subject_to": "subject to",
84
+ "from": "from", "to": "to", "wrt": "wrt"}
85
+ _PHRASE_MARKER = {phrase: name for name, phrase in _MARKER_PHRASE.items()}
86
+
87
+
88
+ def template_for(kind: str, variant: Tuple[str, ...]) -> str:
89
+ """The template a kind prints for one slot set."""
90
+ for slots, template in TEMPLATES[kind]:
91
+ if tuple(slots) == tuple(variant):
92
+ return template
93
+ raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(variant)))
94
+
95
+
96
+ def gap_markers(kind: str, variant: Tuple[str, ...]) -> List[Optional[str]]:
97
+ """The joints a form of the math language puts around its slots, in order.
98
+
99
+ The list has one entry per gap: before the first slot, between consecutive slots, after the
100
+ last one. ``None`` marks a gap with no joint, which is where the verb of the sentence sits in
101
+ every language. This is reader B's skeleton: the slots of a reading are the pieces of
102
+ mathematics that fall between those joints, and a joint may not be missing or out of order.
103
+ """
104
+ parts = re.split(r"\{[TFVABM]\}", template_for(kind, variant))
105
+ gaps: List[Optional[str]] = []
106
+ for index, literal in enumerate(parts):
107
+ phrase = literal.strip()
108
+ if index == 0 or not phrase:
109
+ gaps.append(None)
110
+ elif phrase in _PHRASE_MARKER:
111
+ gaps.append(_PHRASE_MARKER[phrase])
112
+ else:
113
+ raise ReadingError("the template of %s holds the words %r, which are not a joint of "
114
+ "the math language" % (kind, phrase))
115
+ return gaps
116
+
117
+
118
+ def marker_sequence(kind: str, variant: Tuple[str, ...]) -> List[str]:
119
+ """The joints of one form, named in the order the math language prints them."""
120
+ return [gap for gap in gap_markers(kind, variant) if gap is not None]
121
+
122
+
123
+ _OPERATORS = "+-*/^=<>!|"
124
+ _AFTER_CLOSED = "(?<=[0-9A-Za-z\\)\\]])\\s+(?=[%s])" % re.escape(_OPERATORS)
125
+ _BEFORE_OPEN = "(?<=[%s])\\s+(?=[0-9A-Za-z\\[\\(])" % re.escape(_OPERATORS)
126
+
127
+
128
+ def tidy(text: str) -> str:
129
+ """One space between the tokens, none inside a bracket, none around an operator.
130
+
131
+ The math language tolerates whitespace anywhere between its tokens -- verified against the
132
+ math stratum itself, which answers ``solve x^2-5*x+6=0 for x`` and
133
+ ``solve x^2 - 5*x + 6 = 0 for x`` with the same roots -- so tidying never changes what the
134
+ math stratum reads. It gives the two readers one normal form to compare, which matters
135
+ because the two of them glue the tokens of a slot differently: reader A joins what it found
136
+ with spaces, reader B reads the text between two joints as it stands.
137
+
138
+ What the normal form may not do is let two tokens fuse: ``n mod 3`` is three tokens to the
139
+ math stratum, and ``nmod3`` is one unknown it has never heard of, so every rule here removes
140
+ spaces or leaves them, never moves a letter across a word boundary.
141
+ """
142
+ out = re.sub(r"\s+", " ", text).strip()
143
+ out = re.sub(r"\s+([,\]\)])", r"\1", out)
144
+ out = re.sub(r"([\[\(])\s+", r"\1", out)
145
+ out = re.sub(r"(\d)\s+([A-Za-z])(?![A-Za-z0-9])", r"\1*\2", out)
146
+ out = re.sub(_AFTER_CLOSED, "", out)
147
+ out = re.sub(_BEFORE_OPEN, "", out)
148
+ return out
149
+
150
+
151
+ def variable(text: str) -> Optional[str]:
152
+ """A slot value that is a single variable of the math language, or ``None``."""
153
+ cleaned = tidy(text)
154
+ return cleaned if _VARIABLE.fullmatch(cleaned) else None
155
+
156
+
157
+ def matrix(text: str) -> Optional[str]:
158
+ """A slot value that is a matrix literal (rows between double brackets), or ``None``."""
159
+ cleaned = tidy(text)
160
+ if not (cleaned.startswith("[[") and cleaned.endswith("]]")):
161
+ return None
162
+ return cleaned if cleaned.count("[") == cleaned.count("]") else None
163
+
164
+
165
+ def balanced(text: str) -> bool:
166
+ """Every bracket of a sentence closed, and no doubled operator at the edges."""
167
+ depth = {"(": 0, "[": 0}
168
+ for ch in text:
169
+ if ch in depth:
170
+ depth[ch] += 1
171
+ elif ch == ")":
172
+ depth["("] -= 1
173
+ elif ch == "]":
174
+ depth["["] -= 1
175
+ if any(value < 0 for value in depth.values()):
176
+ return False
177
+ return all(value == 0 for value in depth.values())
178
+
179
+
180
+ # The commands of the math language, copied from the parser specification of the math stratum.
181
+ # The reading layer covers only part of them; the rest stays reachable through the direct mode.
182
+ MATH_COMMANDS = ("evaluate", "prove", "solve", "derivative", "antiderivative", "integral",
183
+ "maximize", "minimize", "det", "rank", "inverse", "nullspace", "linsolve",
184
+ "product", "power", "maxflow", "reduce", "sos")
185
+
186
+ # The words the math language itself uses, copied from the same specification. A sentence that
187
+ # carries a word outside this list is not written in the math language, whatever else it looks
188
+ # like. This is the third copy of that spec (the math stratum parses with it, its grammar names
189
+ # it), and the direct mode is where the copies can disagree out loud.
190
+ MATH_LANGUAGE_WORDS = frozenset([
191
+ "evaluate", "prove", "solve", "for", "forall", "exists", "in", "and", "or", "not",
192
+ "true", "false", "derivative", "antiderivative", "integral", "from", "to", "wrt",
193
+ "maximize", "minimize", "subject", "over", "mod", "div", "det", "rank", "inverse",
194
+ "nullspace", "linsolve", "product", "power", "maxflow", "dot", "matvec", "reduce", "sos",
195
+ ])
196
+
197
+ _NOT_MATH_CHARACTER = re.compile(r"[^A-Za-z0-9\s+\-*/^()\[\]<>=!|,.]")
198
+
199
+
200
+ def direct(text: str) -> Optional[Dict[str, Any]]:
201
+ """A sentence already written in the math language, or ``None``.
202
+
203
+ The direct mode is the only way a user reaches the kinds the reading layer does not cover, and
204
+ the only way an untranslated sentence reaches the math stratum: it fires only when the first
205
+ word is a command of the math language, every other word is a word of that language or a one
206
+ letter variable, and no character outside its alphabet appears. Nothing is translated here, and
207
+ the sentence is shown to the user as it arrived.
208
+ """
209
+ cleaned = tidy(text)
210
+ if not cleaned or _NOT_MATH_CHARACTER.search(cleaned):
211
+ return None
212
+ words = re.findall(r"[A-Za-z]+", cleaned)
213
+ if not words or words[0].lower() not in MATH_COMMANDS:
214
+ return None
215
+ for word in words[1:]:
216
+ if len(word) > 1 and word.lower() not in MATH_LANGUAGE_WORDS:
217
+ return None
218
+ return {"mode": "direct", "kind": words[0].lower(), "math": cleaned, "slots": {}}
lgstratum/compare.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The SMT 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 math 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 a theorem prover, which is what
7
+ the math stratum itself does between its two formalizers.
8
+
9
+ The translation of the math language into SMT2 is **not reimplemented here**. The math bundle owns
10
+ that account, and a second copy of it inside the reading layer would be a third place where the
11
+ meaning of the math language could be wrong without anyone noticing. So this module loads the math
12
+ bundle (:envvar:`LGSTRATUM_MATH_ROOT`, sibling folder ``math`` by default) and asks it to
13
+ formalize both sentences, then states the claim ``the readings differ`` as SMT2 and hands it to
14
+ Z3: unsatisfiable means the two readings denote the same problem under every assignment, which is
15
+ the same ``equiv: unsat`` discipline the math stratum applies to its own formalizers.
16
+
17
+ Two consequences are deliberate and both are limits, not shortcuts:
18
+
19
+ * a kind the math bundle cannot put into SMT2 (matrices, flows, integrals of unbounded scope) is
20
+ reported ``unknown`` and the session treats it as a dispute: the reading layer would rather
21
+ abstain than assume two texts are equal;
22
+ * the Z3 claim of this module is *about the readings*, never about the user's problem. The problem
23
+ itself is never decided here: the sentence is handed to the math stratum, whose verdict is shown
24
+ as it arrived.
25
+ """
26
+
27
+ import re
28
+ import sys
29
+ from typing import Any, Dict, List, Optional, Tuple
30
+
31
+ from . import canonical, invoker, segment
32
+
33
+ _math = None
34
+ _MATH_LOOKUP_ERROR: Optional[str] = None
35
+
36
+
37
+ def _math_modules() -> Tuple[Any, Any, Optional[str]]:
38
+ """The math bundle's parser and SMT builder, or the reason they are not available."""
39
+ global _math, _MATH_LOOKUP_ERROR
40
+ if _math is not None:
41
+ return _math[0], _math[1], None
42
+ if _MATH_LOOKUP_ERROR is not None:
43
+ return None, None, _MATH_LOOKUP_ERROR
44
+ root = invoker.math_root()
45
+ if not (root / "lgmath").is_dir():
46
+ _MATH_LOOKUP_ERROR = "no lgmath package under %s" % root
47
+ return None, None, _MATH_LOOKUP_ERROR
48
+ text = str(root)
49
+ if text not in sys.path:
50
+ sys.path.insert(0, text)
51
+ try:
52
+ from lgmath import parse_a, smt # noqa: PLC0415 - the import of the math bundle is the point
53
+ except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently
54
+ _MATH_LOOKUP_ERROR = "the math bundle could not be imported: %s" % type(exc).__name__
55
+ return None, None, _MATH_LOOKUP_ERROR
56
+ _math = (parse_a, smt)
57
+ return _math[0], _math[1], None
58
+
59
+
60
+ ONTOLOGY = "(set-option :timeout 8000)\n"
61
+
62
+
63
+ def smt_referee(decls: List[str], asserts: List[str]) -> str:
64
+ """Run the referee of the math stratum over one claim, the way the orchestrator does each turn.
65
+
66
+ The same code answers here and in the math bundle, so an envelope that this stratum writes is
67
+ checked by the solver the project already trusts; the stratum adds no second referee.
68
+ """
69
+ _parser, smt, _reason = _math_modules()
70
+ if smt is None:
71
+ return "unknown"
72
+ return str(smt.referee(ONTOLOGY, list(decls), list(asserts)))
73
+
74
+
75
+ def numbers(text: str) -> List[str]:
76
+ """Every number written in a sentence, in order, digits normalised."""
77
+ return segment.numeric_literals(text)
78
+
79
+
80
+ def sorted_numbers(text: str) -> List[str]:
81
+ """The same numbers ordered by value, so a reordering of slots is not read as a change."""
82
+ return sorted(numbers(text), key=lambda value: (float(value), value))
83
+
84
+
85
+ def formalize(sentence: str) -> Optional[Dict[str, Any]]:
86
+ """The math bundle's own SMT2 view of one canonical sentence, or ``None``."""
87
+ parse_a, smt, _reason = _math_modules()
88
+ if parse_a is None:
89
+ return None
90
+ try:
91
+ node = parse_a.parse_problem(sentence)
92
+ return smt.problem_smt(node)
93
+ except Exception: # noqa: BLE001 - a sentence this module cannot formalize is a sentence to report
94
+ return None
95
+
96
+
97
+ _DECLARED = re.compile(r"\(declare-(?:const|fun|sort)\s+([^\s()]+)")
98
+
99
+
100
+ def _declared_name(decl: str) -> Optional[str]:
101
+ match = _DECLARED.search(decl)
102
+ return match.group(1) if match else None
103
+
104
+
105
+ def _smt_claim(smt: Any, left: Dict[str, Any], right: Dict[str, Any]) -> Tuple[List[str], List[str], str, str, Any]:
106
+ """SMT2 for ``the two readings differ``, and what the solver says about it.
107
+
108
+ The declarations and the assertion are one plain SMT2 program: the negation of the equivalence
109
+ of the two formalizations, over the union of their variables. Unsatisfiable means the two
110
+ readings denote the same problem under every assignment, which is the same discipline the math
111
+ stratum applies to its own two formalizers. The program is what travels in the envelope, so
112
+ the referee of the orchestrator re-runs exactly this query and cannot be told something else.
113
+ """
114
+ names: List[str] = []
115
+ decls: List[str] = []
116
+ declared = set()
117
+ for side in (left, right):
118
+ for decl in side.get("decls", []):
119
+ name = _declared_name(decl)
120
+ if name is not None:
121
+ if name in declared:
122
+ continue
123
+ declared.add(name)
124
+ decls.append(decl)
125
+ for name in side.get("vars", []):
126
+ if name not in names:
127
+ names.append(name)
128
+ for name in names:
129
+ if name not in declared:
130
+ decls.append("(declare-const %s Real)" % name)
131
+ declared.add(name)
132
+ if "expr" in left and "expr" in right:
133
+ assertions = ["(assert (not (= %s %s)))" % (left["expr"], right["expr"])]
134
+ elif "phi" in left and "phi" in right:
135
+ assertions = ["(assert (not (= %s %s)))" % (left["phi"], right["phi"])]
136
+ else:
137
+ return decls, [], "unknown", "unknown", None
138
+ status, model = smt.check(decls, assertions, names)
139
+ if status == "unsat":
140
+ return decls, assertions, "unsat", "equivalent", None
141
+ if status == "sat":
142
+ return decls, assertions, "sat", "different", model
143
+ return decls, assertions, "unknown", "unknown", None
144
+
145
+
146
+ def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]:
147
+ """The slots one reading actually filled, in the order the math language prints them."""
148
+ kind = str(reading.get("kind", ""))
149
+ slots = reading.get("slots") or {}
150
+ if kind not in canonical.TEMPLATES:
151
+ return ()
152
+ return tuple(name for name in canonical.slots_for(kind) if str(slots.get(name, "")).strip())
153
+
154
+
155
+ def equivalence(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:
156
+ """Compare two readings: one verdict, the SMT claim behind it, and what differs."""
157
+ left = canonical.tidy(str(a.get("math", "")))
158
+ right = canonical.tidy(str(b.get("math", "")))
159
+ detail: List[str] = []
160
+ if sorted_numbers(left) != sorted_numbers(right):
161
+ detail.append("numbers %s vs %s" % (",".join(sorted_numbers(left)), ",".join(sorted_numbers(right))))
162
+
163
+ if a.get("kind") != b.get("kind"):
164
+ detail.append("kinds %s vs %s" % (a.get("kind"), b.get("kind")))
165
+ return {"same": False, "why": "kind", "left": left, "right": right, "detail": detail,
166
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
167
+ if variant_of(a) != variant_of(b):
168
+ detail.append("slots %s vs %s" % (",".join(variant_of(a)), ",".join(variant_of(b))))
169
+ return {"same": False, "why": "variant", "left": left, "right": right, "detail": detail,
170
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
171
+
172
+ if left and left == right:
173
+ return {"same": True, "why": "text", "left": left, "right": right, "detail": detail,
174
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None}
175
+
176
+ _parser, smt, reason = _math_modules()
177
+ first, second = formalize(left), formalize(right)
178
+ if first is None or second is None:
179
+ note = reason or "the math bundle gives no SMT2 view of this kind of sentence"
180
+ detail.append(note)
181
+ return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail,
182
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None,
183
+ "note": note}
184
+
185
+ decls, assertions, claimed, label, model = _smt_claim(smt, first, second)
186
+ if claimed == "unknown":
187
+ detail.append("the solver gave no answer about the two readings")
188
+ if label == "different":
189
+ detail.append("an assignment where the two readings disagree")
190
+ return {"same": label == "equivalent", "why": "smt" if label != "unknown" else "unknown",
191
+ "left": left, "right": right, "detail": detail,
192
+ "declarations": decls, "assertions": assertions, "claimed": claimed,
193
+ "model": ({key: str(value) for key, value in model.items()} if model else None)}
194
+
195
+
196
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
197
+ """Whether the reading kept every number the user wrote, and the SMT claim that says so."""
198
+ wrote = sorted_numbers(question)
199
+ kept = sorted_numbers(str(reading.get("math", "")))
200
+ decls, asserts = elementwise(wrote, kept, "keep")
201
+ ok = wrote == kept
202
+ return {
203
+ "ok": ok,
204
+ "wrote": wrote,
205
+ "kept": kept,
206
+ "missing": [value for value in wrote if value not in kept],
207
+ "added": [value for value in kept if value not in wrote],
208
+ "declarations": decls,
209
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
210
+ "claimed": "sat" if ok else "unsat",
211
+ }
212
+
213
+
214
+ def elementwise(left: List[str], right: List[str], prefix: str) -> Tuple[List[str], List[str]]:
215
+ """SMT2 declarations and assertions saying two lists of numbers are equal, item by item."""
216
+ if len(left) != len(right):
217
+ return [], ["(assert false)"]
218
+ decls: List[str] = []
219
+ asserts: List[str] = []
220
+ for index, (first, second) in enumerate(zip(left, right)):
221
+ name = "%s_%d" % (prefix, index)
222
+ decls.append("(declare-const %sa Real)" % name)
223
+ decls.append("(declare-const %sb Real)" % name)
224
+ asserts.append("(assert (= %sa %s))" % (name, first))
225
+ asserts.append("(assert (= %sb %s))" % (name, second))
226
+ asserts.append("(assert (= %sa %sb))" % (name, name))
227
+ return decls, asserts
228
+
229
+
230
+ def agrees_with_math(reading: Dict[str, Any], math_verdict: Dict[str, Any]) -> bool:
231
+ """Did the math stratum solve the sentence the readers agreed on?
232
+
233
+ The math stratum echoes the problem it understood. That echo is an independent channel: a node
234
+ standing between the readers and the math layer can rewrite its own record, but it cannot move
235
+ the echo without moving numbers that were counted upstream.
236
+ """
237
+ echo = canonical.tidy(str(math_verdict.get("problem_math", "")))
238
+ agreed = canonical.tidy(str(reading.get("math", "")))
239
+ if not agreed or not echo:
240
+ return False
241
+ return echo == agreed and sorted_numbers(echo) == sorted_numbers(agreed)
242
+
243
+
244
+ def assurance_of(comparison: Dict[str, Any], readings: List[Dict[str, Any]],
245
+ coverage: Optional[Dict[str, Any]] = None) -> int:
246
+ """Reading assurance: how much of the answer the *reading* of the sentence warrants.
247
+
248
+ The scale is the one the math stratum uses, zero to three, and this function only ever lowers
249
+ it: two readings that agree and kept every number reach level two, a single reader reaches
250
+ level one, and no reading path reaches three, because reading a sentence written in a human
251
+ language is never the last word -- the math stratum holds level three for the mathematics it
252
+ proved, and the assurance the user sees is the minimum of the two.
253
+ """
254
+ present = [reading for reading in readings if reading.get("math")]
255
+ if not present:
256
+ return 0
257
+ if coverage is not None and not coverage.get("ok", False):
258
+ return 0
259
+ if len(present) < 2:
260
+ return 1
261
+ return 2 if comparison.get("same") else 0
lgstratum/corpus.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-solve-1", "lang": "it", "question": "risolvi x^2 - 5*x + 6 = 0 per x",
8
+ "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x",
9
+ "min_assurance": 1}}
10
+
11
+ ``state`` is the only mandatory key. ``sentence`` is compared after tidying, ``answer_contains`` is
12
+ a substring test on the answer the math stratum returned, and ``max_assurance`` is the ceiling a
13
+ negative item insists on: an item that ends in DISPUTED, AMBIGUOUS or NOT COVERED must show no
14
+ answer at all.
15
+
16
+ The corpus is the only place a shared translation error can surface: the two readers agree by
17
+ construction whenever both descriptions of a language carry the same mistake, so the gold sentences
18
+ are written from the language and not from the lexicon.
19
+ """
20
+
21
+ import json
22
+ from pathlib import Path
23
+ from typing import Any, Dict, List, Optional
24
+
25
+ from . import canonical, pipeline
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ PATH = ROOT / "problems" / "corpus.jsonl"
29
+
30
+
31
+ def load(path: Optional[Path] = None) -> List[Dict[str, Any]]:
32
+ """The corpus, one dictionary per line, skipping blank lines and comments."""
33
+ where = Path(path) if path else PATH
34
+ items: List[Dict[str, Any]] = []
35
+ for line in where.read_text(encoding="utf-8").splitlines():
36
+ text = line.strip()
37
+ if not text or text.startswith("#"):
38
+ continue
39
+ items.append(json.loads(text))
40
+ return items
41
+
42
+
43
+ def grade(item: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]:
44
+ """Compare one corpus expectation against one run, and say exactly what did not match."""
45
+ expect = item.get("expect") or {}
46
+ final = result.get("final") or {}
47
+ problems: List[str] = []
48
+ state = str(final.get("state", ""))
49
+ if expect.get("state") and expect["state"] != state:
50
+ problems.append("state %s, expected %s" % (state, expect["state"]))
51
+ if "sentence" in expect:
52
+ wanted = canonical.tidy(str(expect["sentence"]))
53
+ got = canonical.tidy(str((result.get("dossier") or {}).get("sent", "")))
54
+ if got != wanted:
55
+ problems.append("sentence %r, expected %r" % (got, wanted))
56
+ if "answer_contains" in expect:
57
+ answer = str(final.get("answer", ""))
58
+ if str(expect["answer_contains"]) not in answer:
59
+ problems.append("answer %r does not contain %r" % (answer, expect["answer_contains"]))
60
+ if "min_assurance" in expect and int(final.get("assurance", 0) or 0) < int(expect["min_assurance"]):
61
+ problems.append("assurance %s below %s" % (final.get("assurance"), expect["min_assurance"]))
62
+ if "max_assurance" in expect and int(final.get("assurance", 0) or 0) > int(expect["max_assurance"]):
63
+ problems.append("assurance %s above %s" % (final.get("assurance"), expect["max_assurance"]))
64
+ if expect.get("no_answer") and final.get("answer"):
65
+ problems.append("an answer was shown for an item that must show none")
66
+ if expect.get("referee_clean") and any(record["claimed"] != record["referee"]
67
+ for record in result.get("records") or []):
68
+ problems.append("a claim did not survive the referee")
69
+ return {"id": item.get("id", "?"), "lang": item.get("lang", "?"), "state": state,
70
+ "assurance": final.get("assurance", 0), "ok": not problems, "problems": problems}
71
+
72
+
73
+ def outcome(item: Dict[str, Any], call_math: bool = True, fault_spec: Optional[List[str]] = None) -> Dict[str, Any]:
74
+ """Run one corpus item in memory and grade it."""
75
+ result = pipeline.ask(str(item.get("question", "")), str(item.get("lang", "")), fault_spec=fault_spec,
76
+ call_math=call_math)
77
+ verdict = grade(item, result)
78
+ verdict["records"] = result["records"]
79
+ verdict["dossier"] = result["dossier"]
80
+ verdict["reply"] = result["reply"]
81
+ return verdict
lgstratum/coverage.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the reading kept, and what the math stratum 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 math language, and
7
+ no number appeared there that the user did not write. A reader that merged two slots or shifted
8
+ a digit changes that multiset, and a sorted element by element equality over declared reals says
9
+ so;
10
+ * :func:`echo_matches` -- the math stratum 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 math layer can rewrite its own record, but it cannot move
13
+ the echo without moving numbers that were counted upstream.
14
+
15
+ Neither check decides mathematics. They count tokens, and they hand the counting to a solver so
16
+ that a node claiming the numbers were kept is checked against that claim.
17
+ """
18
+
19
+ from typing import Any, Dict, List, Optional
20
+
21
+ from . import canonical, compare
22
+
23
+
24
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
25
+ """Whether one reading kept every number the user wrote, with the SMT claim that says so."""
26
+ return compare.keeps(reading, question)
27
+
28
+
29
+ def echo_numbers(math_verdict: Dict[str, Any]) -> List[str]:
30
+ """The numbers of the problem the math stratum says it solved, ordered by value."""
31
+ return compare.sorted_numbers(canonical.tidy(str(math_verdict.get("problem_math", ""))))
32
+
33
+
34
+ def echo_matches(reading: Dict[str, Any], math_verdict: Dict[str, Any]) -> bool:
35
+ """Did the math stratum solve the sentence the readers agreed on?
36
+
37
+ A verdict that names no sentence at all -- the backend was off, or the math stratum could not
38
+ be started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls
39
+ to zero because there is no math assurance to take the minimum with, but nothing here may be
40
+ read as tampering. Only an echo that names a sentence and names a different one is a mismatch.
41
+ """
42
+ if not str(math_verdict.get("problem_math", "")).strip():
43
+ return True
44
+ return compare.agrees_with_math(reading, math_verdict)
45
+
46
+
47
+ def coverage_claim(question: str, readings: List[Dict[str, Any]],
48
+ math_verdict: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
49
+ """One SMT2 claim tying the user's numbers to the readings and, when known, to the echo.
50
+
51
+ Every reading that produced a sentence has to carry the user's numbers, and once the math
52
+ stratum has answered its echo has to carry them too. The assertion set is the conjunction of
53
+ those element equalities: satisfiable exactly when all of them hold, which is what the referee
54
+ checks against the status the node claimed.
55
+ """
56
+ wrote = compare.sorted_numbers(question)
57
+ readings_present = [reading for reading in readings if reading.get("math")]
58
+ steps = [keeps(reading, question) for reading in readings_present]
59
+ ok = all(step["ok"] for step in steps)
60
+ decls: List[str] = []
61
+ asserts: List[str] = []
62
+ for step in steps:
63
+ decls = decls + list(step["declarations"])
64
+ asserts = asserts + list(step["assertions"])
65
+ if math_verdict is not None:
66
+ echo = echo_numbers(math_verdict)
67
+ decls2, asserts2 = compare.elementwise(wrote, echo, "echo")
68
+ decls = decls + decls2
69
+ asserts = asserts + asserts2
70
+ ok = ok and echo == wrote
71
+ if not wrote:
72
+ # Nothing was written, so there is nothing to keep: the claim is the empty conjunction,
73
+ # which is satisfiable, and the node says sat.
74
+ return {"ok": ok, "wrote": [], "kept": [], "declarations": [], "assertions": ["(assert (= 1 1))"],
75
+ "claimed": "sat"}
76
+ return {
77
+ "ok": ok,
78
+ "wrote": wrote,
79
+ "kept": [step["kept"] for step in steps],
80
+ "declarations": decls,
81
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
82
+ "claimed": "sat" if ok else "unsat",
83
+ }
84
+
85
+
86
+ def summary(step: Dict[str, Any]) -> Dict[str, Any]:
87
+ """The part of a coverage step that belongs in the dossier and in front of the user."""
88
+ return {
89
+ "ok": step.get("ok", False),
90
+ "wrote": step.get("wrote", []),
91
+ "missing": step.get("missing", []),
92
+ "added": step.get("added", []),
93
+ }
lgstratum/decide.py ADDED
@@ -0,0 +1,160 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math stratum 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 math stratum uses for its own ``decide``.
8
+
9
+ The rule the whole module exists to enforce:
10
+
11
+ assurance(shown) = min(assurance(math), assurance(reading))
12
+
13
+ and ``assurance(reading)`` is at most two, so the stratum never reports the top level: a sentence
14
+ written in a human language carries one more fallible step than a sentence the math stratum
15
+ formalizes itself, and the reading layer is where that step lives. A verdict is therefore never
16
+ raised by the stratum; the only direction it can move is down, and the adversary node writes the
17
+ negation of that inequality as SMT2 so the referee of the orchestrator refutes it.
18
+
19
+ The states, which are the seven the lexicon of every covered language names:
20
+
21
+ =========== ===================================================================
22
+ AGREED both readers produced the same sentence, and the math stratum solved it
23
+ PASSTHROUGH the sentence was already written in the math language: nothing was translated
24
+ SINGLE one reader understood the sentence and the other abstained: the math stratum was
25
+ consulted, and the assurance is capped by the missing witness
26
+ DISPUTED the two readers produced different sentences, or a reading lost a number: the math
27
+ stratum is not consulted at all
28
+ AMBIGUOUS the sentence announces more than one kind of problem: the user has to choose
29
+ NOT COVERED neither reader found anything: the language does not say this in a covered way
30
+ TAMPERED the math stratum says it solved something other than the agreed sentence
31
+ =========== ===================================================================
32
+ """
33
+
34
+ from typing import Any, Dict, List, Optional
35
+
36
+ AMBIGUOUS_REASONS = ("multiple", "two_verbs")
37
+
38
+ STATES = ("AGREED", "PASSTHROUGH", "SINGLE", "DISPUTED", "AMBIGUOUS", "NOT COVERED", "TAMPERED", "NONE")
39
+
40
+ # The reading assurance of each state, on the scale the math stratum uses. Three is not in this
41
+ # table: it belongs to the math stratum alone.
42
+ CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0,
43
+ "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0}
44
+
45
+
46
+ def reader_notes(readings: List[Dict[str, Any]]) -> List[str]:
47
+ """The reason keys the abstaining readers left behind, in reader order."""
48
+ notes: List[str] = []
49
+ for reading in readings:
50
+ for note in reading.get("notes") or []:
51
+ reason = note.get("reason") if isinstance(note, dict) else str(note)
52
+ if reason and reason not in notes:
53
+ notes.append(reason)
54
+ return notes
55
+
56
+
57
+ def state_of(readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
58
+ coverage: Optional[Dict[str, Any]], math_verdict: Optional[Dict[str, Any]],
59
+ direct: Optional[Dict[str, Any]] = None, echo_ok: Optional[bool] = None) -> str:
60
+ """The state of a session, from the evidence the nodes collected."""
61
+ present = [reading for reading in readings if reading.get("math")]
62
+ notes = reader_notes(readings)
63
+ if direct is not None:
64
+ return "PASSTHROUGH"
65
+ if math_verdict is not None and echo_ok is False:
66
+ return "TAMPERED"
67
+ if len(present) >= 2:
68
+ if comparison is None:
69
+ return "DISPUTED"
70
+ if coverage is not None and not coverage.get("ok", False):
71
+ return "DISPUTED"
72
+ return "AGREED" if comparison.get("same") else "DISPUTED"
73
+ if len(present) == 1:
74
+ # A lone witness has to hold the numbers the person wrote: a reading that lost one is not a
75
+ # weaker reading of the same problem, it is a different problem, and the ceiling of SINGLE is
76
+ # not a licence to answer it. This is the case the ablation of the topology uncovered: with
77
+ # one reader there is no second sentence to compare against, so the count of literals is what
78
+ # stands between a shifted number and an answer the gold does not accept.
79
+ if coverage is not None and not coverage.get("ok", False):
80
+ return "DISPUTED"
81
+ return "SINGLE"
82
+ if any(reason in AMBIGUOUS_REASONS for reason in notes):
83
+ return "AMBIGUOUS"
84
+ return "NOT COVERED"
85
+
86
+
87
+ def reasons_for(state: str, readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
88
+ coverage: Optional[Dict[str, Any]], math_verdict: Optional[Dict[str, Any]],
89
+ asked: bool = True) -> List[str]:
90
+ """The reason keys that explain a state, in the order a reader should read them."""
91
+ out: List[str] = []
92
+ for reason in reader_notes(readings):
93
+ if reason not in out:
94
+ out.append(reason)
95
+ if state == "DISPUTED":
96
+ if coverage is not None and not coverage.get("ok", False):
97
+ out.append("literal_count")
98
+ if comparison is not None and not comparison.get("same"):
99
+ out.append("disagree")
100
+ if comparison is not None and comparison.get("why") == "unknown":
101
+ out.append("math_unknown")
102
+ if comparison is not None and comparison.get("why") == "smt" and comparison.get("model"):
103
+ if "disagree" not in out:
104
+ out.append("disagree")
105
+ if state == "TAMPERED":
106
+ out.append("boundary")
107
+ if math_verdict is not None and math_verdict.get("referee_mismatch"):
108
+ out.append("referee")
109
+ if asked and math_verdict is not None and math_verdict.get("status") == "UNKNOWN":
110
+ out.append("math_unknown")
111
+ if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"):
112
+ out.append("no_math")
113
+ return out
114
+
115
+
116
+ def decide(dossier: Dict[str, Any]) -> Dict[str, Any]:
117
+ """One verdict for one session, with the assurance the user is allowed to see."""
118
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
119
+ if dossier.get("reading_direct"):
120
+ readings = [dossier["reading_direct"]]
121
+ comparison = dossier.get("compare")
122
+ coverage = dossier.get("coverage")
123
+ math_verdict = dossier.get("math")
124
+ direct = dossier.get("reading_direct")
125
+ echo_ok = dossier.get("echo_ok")
126
+
127
+ state = state_of(readings, comparison, coverage, math_verdict, direct, echo_ok)
128
+ ceiling = CEILING[state]
129
+ assurance = 0
130
+ answer_shown = ""
131
+ if state in ("AGREED", "SINGLE", "PASSTHROUGH") and math_verdict is not None:
132
+ # The math stratum answers at level three when its own two formalizers and two checkers all
133
+ # agree, at level two when one prover stands alone, and at level zero when it says UNKNOWN.
134
+ if math_verdict.get("status") in ("VERIFIED", "SINGLE_PROVER"):
135
+ assurance = min(ceiling, int(math_verdict.get("assurance", 0) or 0))
136
+ else:
137
+ assurance = 0
138
+ answer_shown = math_verdict.get("answer_text") or ""
139
+ if assurance == 0:
140
+ answer_shown = ""
141
+ reasons = reasons_for(state, readings, comparison, coverage, math_verdict,
142
+ asked=bool(str(dossier.get("sent") or "")))
143
+ return {
144
+ "state": state,
145
+ "assurance": assurance,
146
+ "ceiling": ceiling,
147
+ "math_assurance": int((math_verdict or {}).get("assurance", 0) or 0),
148
+ "math_status": (math_verdict or {}).get("status"),
149
+ "answer": answer_shown,
150
+ "reasons": reasons,
151
+ "consulted_math": math_verdict is not None,
152
+ }
153
+
154
+
155
+ def raise_assurance(final: Dict[str, Any], claimed: int) -> Dict[str, Any]:
156
+ """The arbiter fault: an assurance above what the evidence supports (experiments only)."""
157
+ out = dict(final)
158
+ out["assurance"] = max(int(final.get("assurance", 0) or 0), int(claimed))
159
+ out["claimed_above_evidence"] = True
160
+ return out
lgstratum/faults.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Fault injection for the redundancy experiments (tools/ablation.py).
2
+
3
+ A fault is "<agent>:<kind>". Faults are off unless LGSTRATUM_FAULTS (or :func:`configure`) names
4
+ them, so production runs never take these branches. ``FIRED`` records the faults that really
5
+ changed 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 math language: a reader that drops a number or merges two slots must produce
9
+ something the math stratum will happily solve. Otherwise the fault would be caught by the math
10
+ stratum refusing to parse, and the experiment would measure nothing about the reading layer.
11
+
12
+ Catalogue
13
+ ---------
14
+ reader_a / reader_b : drop_marker, merge_slots, shift_number
15
+ equivalence : rubber_stamp (declares the two readings equal without running SMT)
16
+ coverage : rubber_stamp (declares every number kept without counting them)
17
+ boundary : tamper_math (asks the math stratum a different question, reports the agreed one)
18
+ adversary : rubber_stamp (skips its own recomputation of the assurance bound)
19
+ arbiter : force_assurance (raises the assurance above what the evidence supports)
20
+ """
21
+
22
+ import os
23
+ import re
24
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
25
+
26
+ _ACTIVE: Set[str] = set()
27
+ FIRED: List[str] = []
28
+
29
+ READER_FAULTS = ["drop_marker", "merge_slots", "shift_number"]
30
+
31
+ CATALOG = {
32
+ "reader_a": READER_FAULTS,
33
+ "reader_b": READER_FAULTS,
34
+ "equivalence": ["rubber_stamp"],
35
+ "coverage": ["rubber_stamp"],
36
+ "boundary": ["tamper_math"],
37
+ "adversary": ["rubber_stamp"],
38
+ "arbiter": ["force_assurance"],
39
+ }
40
+
41
+ # Slots a form can lose without becoming ungrammatical: the joint and its slot are both optional.
42
+ _OPTIONAL = {"V"}
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("LGSTRATUM_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], order: List[str]) -> Tuple[Dict[str, str], bool]:
83
+ """Return a damaged copy of one reading, and whether anything was actually damaged.
84
+
85
+ ``order`` is the slot order of the form the reader chose, so the fault knows which slots a
86
+ joint is holding and which of them the math language could do without.
87
+ """
88
+ from . import canonical
89
+
90
+ slots = dict(slots)
91
+ for kind_fault in CATALOG.get(agent, []):
92
+ if not has(agent, kind_fault):
93
+ continue
94
+ candidate = dict(slots)
95
+ if kind_fault == "drop_marker":
96
+ losers = [name for name in reversed(order) if name in candidate and name in _OPTIONAL]
97
+ if not losers:
98
+ continue
99
+ candidate.pop(losers[0])
100
+ elif kind_fault == "merge_slots":
101
+ numbered = _slots_with_numbers(candidate, order)
102
+ if len(numbered) < 2:
103
+ continue
104
+ candidate[numbered[1]] = candidate[numbered[0]]
105
+ elif kind_fault == "shift_number":
106
+ numbered = _slots_with_numbers(candidate, order)
107
+ if not numbered:
108
+ continue
109
+ owner = numbered[0]
110
+ match = _NUMBER.search(candidate[owner])
111
+ if match is None:
112
+ continue
113
+ bumped = _NUMBER.sub(lambda m: str(_next_number(m.group(0))), candidate[owner], count=1)
114
+ candidate[owner] = bumped
115
+ else:
116
+ continue
117
+ try:
118
+ canonical.print_math(kind, candidate)
119
+ except canonical.ReadingError:
120
+ continue
121
+ fire(agent, kind_fault)
122
+ return candidate, True
123
+ return slots, False
124
+
125
+
126
+ def _next_number(text: str) -> Any:
127
+ if "." in text:
128
+ return float(text) + 1.0
129
+ return int(text) + 1
130
+
131
+
132
+ # ---------------------------------------------------------------------------
133
+ # Sentence mutations (the boundary fault)
134
+ # ---------------------------------------------------------------------------
135
+ def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]:
136
+ """Change one number of a sentence of the math language, leaving it grammatical."""
137
+ if not has(agent, "tamper_math"):
138
+ return sentence, False
139
+ match = _NUMBER.search(sentence)
140
+ if match is None:
141
+ return sentence, False
142
+ damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():]
143
+ fire(agent, "tamper_math")
144
+ return damaged, True
lgstratum/invoker.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The interface toward the math stratum: one subprocess call, no shared code.
2
+
3
+ The reading layer and the math layer are separate topologies of the same orchestrator. This
4
+ module is the whole of their coupling: it starts ``tools/solve.py`` of the math stratum as a
5
+ separate process with the canonical sentence as its argument, asks for the machine readable
6
+ outcome, and copies that outcome. Nothing here imports a module of the math stratum, because a
7
+ translation layer that reaches inside the mathematics it consults is a translation layer that can
8
+ silently change the mathematics.
9
+
10
+ Two settings matter, and both are environment variables so no value is hardcoded in a second
11
+ place:
12
+
13
+ ``LGSTRATUM_MATH_ROOT`` the folder of the math stratum (default: ``math``, sibling of this
14
+ bundle, which is ``datasets/math`` inside the LingoLOGOS repository)
15
+ ``LGSTRATUM_MATH_BACKEND`` ``subprocess`` (default) or ``none``; ``none`` refuses to call and is
16
+ what the reading layer tests use, so they can check the reading
17
+ without starting a whole math session
18
+ """
19
+
20
+ import json
21
+ import os
22
+ import subprocess
23
+ import sys
24
+ from pathlib import Path
25
+ from typing import Any, Dict, Optional
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ DEFAULT_TIMEOUT = 180
29
+
30
+
31
+ def math_root() -> Path:
32
+ override = os.environ.get("LGSTRATUM_MATH_ROOT", "").strip()
33
+ if override:
34
+ return Path(override)
35
+ return ROOT.parent / "math"
36
+
37
+
38
+ def backend() -> str:
39
+ return (os.environ.get("LGSTRATUM_MATH_BACKEND", "subprocess") or "subprocess").strip().lower()
40
+
41
+
42
+ def timeout_seconds() -> int:
43
+ try:
44
+ return max(5, int(os.environ.get("LGSTRATUM_MATH_TIMEOUT", DEFAULT_TIMEOUT)))
45
+ except ValueError:
46
+ return DEFAULT_TIMEOUT
47
+
48
+
49
+ def unavailable(reason: str) -> Dict[str, Any]:
50
+ return {"ok": False, "error": reason, "status": "UNKNOWN", "assurance": 0, "answer": None,
51
+ "answer_text": "", "problem_math": "", "reasons": [], "solver": None, "detected": []}
52
+
53
+
54
+ def solve(sentence: str) -> Dict[str, Any]:
55
+ """Ask the math stratum one sentence of the math language, and return its verdict unchanged."""
56
+ if backend() == "none":
57
+ return unavailable("the math backend is disabled by LGSTRATUM_MATH_BACKEND")
58
+ root = math_root()
59
+ script = root / "tools" / "solve.py"
60
+ if not script.is_file():
61
+ return unavailable("no tools/solve.py under %s" % root)
62
+ try:
63
+ done = subprocess.run(
64
+ [sys.executable, str(script), "--json", sentence],
65
+ cwd=str(root), capture_output=True, timeout=timeout_seconds())
66
+ except subprocess.TimeoutExpired:
67
+ return unavailable("the math stratum did not answer within %d seconds" % timeout_seconds())
68
+ except OSError as exc:
69
+ return unavailable("the math stratum could not be started: %s" % exc)
70
+ text = done.stdout.decode("utf-8", "replace")
71
+ if done.returncode != 0 and not text.strip():
72
+ return unavailable("the math stratum exited with %d: %s"
73
+ % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200]))
74
+ return outcome(text, done.returncode)
75
+
76
+
77
+ def outcome(text: str, returncode: int = 0) -> Dict[str, Any]:
78
+ """Extract the verdict of a math session from the JSON the math stratum printed."""
79
+ try:
80
+ parsed = json.loads(text)
81
+ except ValueError:
82
+ return unavailable("the math stratum printed something that is not JSON (exit %d)" % returncode)
83
+ final = parsed.get("final") if isinstance(parsed, dict) else None
84
+ if not isinstance(final, dict):
85
+ return unavailable("the math stratum printed no verdict (exit %d)" % returncode)
86
+ referee = parsed.get("referee") if isinstance(parsed.get("referee"), list) else []
87
+ mismatched = [entry for entry in referee
88
+ if isinstance(entry, dict) and entry.get("claimed") != entry.get("referee")]
89
+ return {
90
+ "ok": final.get("status") != "UNKNOWN",
91
+ "status": final.get("status", "UNKNOWN"),
92
+ "assurance": int(final.get("assurance", 0) or 0),
93
+ "answer": final.get("answer"),
94
+ "answer_text": final.get("answer_text") or "",
95
+ "problem_math": final.get("problem_math") or "",
96
+ "reasons": list(final.get("reasons") or []),
97
+ "solver": final.get("solver"),
98
+ "detected": list(final.get("detected") or []),
99
+ "referee_mismatch": len(mismatched),
100
+ "turns": parsed.get("turns"),
101
+ "error": None if final.get("status") != "UNKNOWN" else "; ".join(final.get("reasons") or []) or "unknown",
102
+ }
lgstratum/lexicon.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4
+ kind 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 must appear, which must not, how many
10
+ mathematics regions the sentence holds).
11
+
12
+ This mirrors the math topology, where the two formalizers share one written specification
13
+ (``nodes/*/grammar.gf``) and implement it twice. The consequence is the same and is stated in
14
+ the README: a translation error present in both descriptions of one language is invisible to
15
+ the topology, and only the gold sentences of the corpus can show it.
16
+
17
+ The data files are the object of study, not prose of this repository: they hold the words of
18
+ six languages, exactly as the math bundle holds the bracket tokens it studies.
19
+ """
20
+
21
+ import json
22
+ import os
23
+ import re
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ from .segment import atomize, fold
27
+
28
+ BUNDLE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
29
+ LEXICON_DIR = os.path.join(BUNDLE, "lexicon")
30
+
31
+ # Marker names, the same in every variety. The variety supplies the words; the names are how
32
+ # the two readers and the canonical printer agree.
33
+ MARKERS = ("for", "over_z", "subject_to", "from", "to", "wrt")
34
+
35
+ # A word run that is not in the lexicon is a coverage failure, unless it is one of these.
36
+ MATH_WORDS = ("mod", "div")
37
+ # Domains written as bare letters belong to the math language, not to a reading.
38
+ DOMAIN_LETTERS = ("R", "Z")
39
+
40
+ # The characters that say "a single letter here is an operand of the mathematics". Digits are not
41
+ # among them: Italian "da 0 a 2" puts the single letter a between two numbers, and there it is the
42
+ # marker of a bound, not the unknown the sentence is about.
43
+ OPERATOR_BEFORE = set("+-*/^=<>|([,")
44
+ OPERATOR_AFTER = set("+-*/^=<>|)]")
45
+
46
+ # The mnemonic names a data file may use for a connective, and what it prints as.
47
+ CONNECTIVE_TEXT = {"and": "and", "or": "or", "not": "not",
48
+ "eq": "=", "ne": "!=", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
49
+
50
+ _cache: Dict[str, Dict[str, Any]] = {}
51
+ _index_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
52
+ _stripped_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
53
+ _verb_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, ...]]] = {}
54
+ _group_cache: Dict[str, Dict[str, Tuple[str, ...]]] = {}
55
+
56
+
57
+ def languages() -> List[str]:
58
+ """The language codes this bundle can read, in a stable order."""
59
+ return sorted(name[:-5] for name in os.listdir(LEXICON_DIR) if name.endswith(".json"))
60
+
61
+
62
+ def load(lang: str) -> Dict[str, Any]:
63
+ if lang not in _cache:
64
+ path = os.path.join(LEXICON_DIR, lang + ".json")
65
+ with open(path, "r", encoding="utf-8") as handle:
66
+ data = json.load(handle)
67
+ data["_code"] = lang
68
+ _cache[lang] = data
69
+ return _cache[lang]
70
+
71
+
72
+ def script(lang: str) -> str:
73
+ return load(lang).get("script", "latin")
74
+
75
+
76
+ def codes() -> List[str]:
77
+ return languages()
78
+
79
+
80
+ def kinds(lang: str) -> List[str]:
81
+ """The sentence kinds this variety covers."""
82
+ return sorted(load(lang).get("kinds", {}))
83
+
84
+
85
+ def supported_kinds() -> List[str]:
86
+ """The kinds at least one variety covers."""
87
+ seen = set()
88
+ for lang in languages():
89
+ seen.update(kinds(lang))
90
+ return sorted(seen)
91
+
92
+
93
+ def patterns(lang: str) -> Dict[str, List[str]]:
94
+ """Reader A's surface patterns per kind: ``{kind: [pattern, ...]}``."""
95
+ out = {}
96
+ for kind, spec in load(lang).get("kinds", {}).items():
97
+ out[kind] = list(spec.get("patterns", []))
98
+ return out
99
+
100
+
101
+ def frames(lang: str) -> Dict[str, Dict[str, Any]]:
102
+ """Reader B's marker frames per kind."""
103
+ out = {}
104
+ for kind, spec in load(lang).get("kinds", {}).items():
105
+ frame = spec.get("frame")
106
+ if frame is not None:
107
+ out[kind] = frame
108
+ return out
109
+
110
+
111
+ def verbs(lang: str) -> Dict[str, Tuple[Tuple[str, ...], ...]]:
112
+ """Every kind verb phrase of the variety, mapped to the kinds it announces.
113
+
114
+ One phrase announces more than one kind, and that is a fact of the language, not a defect of
115
+ the data: Italian "dimostra" opens both ``prove`` and ``provez``, which differ only by the
116
+ marker for the domain. Keeping the whole list here is what lets a reader try both forms of
117
+ one sentence instead of silently taking the last kind in the file.
118
+ """
119
+ out: Dict[str, Tuple[str, ...]] = {}
120
+ for kind, spec in load(lang).get("kinds", {}).items():
121
+ for verb in spec.get("verbs", []):
122
+ phrase = fold(verb)
123
+ out[phrase] = out.get(phrase, ()) + (kind,)
124
+ return out
125
+
126
+
127
+ def verb_atoms_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, ...]]:
128
+ """The verb phrases of a variety, keyed by their atoms, mapped to the kinds they announce."""
129
+ if lang in _verb_cache:
130
+ return _verb_cache[lang]
131
+ index = {phrase_atoms(verb): kinds for verb, kinds in verbs(lang).items()}
132
+ _verb_cache[lang] = index
133
+ return index
134
+
135
+
136
+ def verb_groups(lang: str) -> Dict[str, Tuple[str, ...]]:
137
+ """The kinds a verb phrase can open: ``prove`` and ``provez`` are one group, ``det`` another.
138
+
139
+ Two kinds belong to the same group when one phrase of the variety announces both of them.
140
+ A sentence whose verb lies in one group is one problem, read in one of two ways; a sentence
141
+ whose verbs lie in two groups is two problems, and no reader may pick one.
142
+ """
143
+ if lang in _group_cache:
144
+ return _group_cache[lang]
145
+ parent = {kind: kind for kind in load(lang).get("kinds", {})}
146
+
147
+ def root(kind: str) -> str:
148
+ while parent[kind] != kind:
149
+ parent[kind] = parent[parent[kind]]
150
+ kind = parent[kind]
151
+ return kind
152
+
153
+ for kinds in verbs(lang).values():
154
+ for other in kinds[1:]:
155
+ first, second = root(kinds[0]), root(other)
156
+ if first != second:
157
+ parent[second] = first
158
+ merged: Dict[str, set] = {}
159
+ for kind in parent:
160
+ merged.setdefault(root(kind), set()).add(kind)
161
+ groups = {kind: tuple(sorted(group)) for group in merged.values() for kind in group}
162
+ _group_cache[lang] = groups
163
+ return groups
164
+
165
+
166
+ def announce(lang: str, items: List[Dict[str, Any]]) -> Tuple[List[str], Optional[Dict[str, str]]]:
167
+ """The kinds the verbs of a sentence open, or the reason the sentence announces none.
168
+
169
+ Both readers ask this one question, in one place: a kind is a decision about the mathematics,
170
+ and a second implementation of the same rule in the second reader would be one more place
171
+ where the two of them can be wrong in the same way.
172
+ """
173
+ found: List[str] = []
174
+ for item in items:
175
+ if item.get("role") != "verb":
176
+ continue
177
+ for kind in item.get("kinds") or (item.get("value"),):
178
+ if kind and kind not in found:
179
+ found.append(kind)
180
+ if not found:
181
+ return [], {"reason": "no_verb"}
182
+ neutral = neutral_kinds(lang)
183
+ picked = [kind for kind in found if kind not in neutral] or found
184
+ groups = {frozenset(verb_groups(lang)[kind]) for kind in picked}
185
+ if len(groups) > 1:
186
+ return [], {"reason": "two_verbs", "kinds": ", ".join(sorted(picked))}
187
+ merged: set = set()
188
+ for group in groups:
189
+ merged |= group
190
+ return sorted(merged), None
191
+
192
+
193
+
194
+ def connectives(lang: str) -> Dict[str, List[str]]:
195
+ """The connective phrases of a variety, keyed by what they print as in the math language.
196
+
197
+ The data may key a connective by a mnemonic name (``ge``) or by the symbol itself; both are
198
+ accepted, because the mnemonic is easier to read in a data file and the symbol is what the
199
+ math language needs. The logic connectives are words in the math language, so they stay words.
200
+ """
201
+ out: Dict[str, List[str]] = {}
202
+ for name, words in load(lang).get("connectives", {}).items():
203
+ out[CONNECTIVE_TEXT.get(name, name)] = list(words)
204
+ return out
205
+
206
+
207
+ def neutral_kinds(lang: str) -> set:
208
+ """Kinds whose verb is a request for an answer rather than a claim about the mathematics.
209
+
210
+ ``calcola la derivata di x^2`` announces two kinds, and only one of them is the kind of the
211
+ problem: the request verb is neutral, so the reader that carries it steps aside.
212
+ """
213
+ return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")}
214
+
215
+
216
+ def operand(lang: str, word: str, before: str, after: str) -> bool:
217
+ """Whether a single Latin letter touching an operator is the unknown, not the word it spells.
218
+
219
+ Spanish writes the conjunction "y" and Italian writes the marker "a" with the same characters a
220
+ variable uses, and a sentence like "maximiza 3*x + 4*y" puts one of those letters exactly where
221
+ an unknown belongs. Only the operator it touches tells the reader which it is, and both readers
222
+ have to use the same test: a shared fact of the math language, not part of either reading
223
+ strategy. The trade is stated in the README -- a one letter operand next to an operator always
224
+ wins -- which is why a bound marker in the data is chosen to be a word that cannot be a letter.
225
+ """
226
+ if len(word) != 1 or not ("a" <= word <= "z") or word in DOMAIN_LETTERS:
227
+ return False
228
+ if (word,) not in phrase_index(lang):
229
+ return True
230
+ if before and before[-1] in OPERATOR_BEFORE:
231
+ return True
232
+ return bool(after and after[0] in OPERATOR_AFTER)
233
+
234
+
235
+ def markers(lang: str) -> Dict[str, List[str]]:
236
+ return load(lang).get("markers", {})
237
+
238
+
239
+ def noise(lang: str) -> List[str]:
240
+ return load(lang).get("noise", [])
241
+
242
+
243
+ def noise_chars(lang: str) -> str:
244
+ """Single characters a word run may hold without being a coverage failure (Chinese particles)."""
245
+ return load(lang).get("noise_chars", "")
246
+
247
+
248
+ def prefixes(lang: str) -> List[str]:
249
+ """Attached prefixes an Arabic word run may carry (definite article, conjunctions)."""
250
+ return load(lang).get("prefixes", [])
251
+
252
+
253
+ def strip_prefix(word: str, prefixes: List[str]) -> str:
254
+ """Remove the longest attached prefix, so that a written form reaches the prefix-free entry.
255
+
256
+ Arabic attaches the definite article and the single letter conjunctions and prepositions in
257
+ front of the word, and the lexicon files record the word without them. The longest prefix wins,
258
+ because the article and a conjunction joined to it are one prefix and not two.
259
+ """
260
+ for prefix in sorted(prefixes, key=len, reverse=True):
261
+ if word.startswith(prefix) and len(word) > len(prefix):
262
+ return word[len(prefix):]
263
+ return word
264
+
265
+
266
+ def prefix_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
267
+ """The same index, keyed with every atom of every phrase written without its prefixes."""
268
+ if lang in _stripped_cache:
269
+ return _stripped_cache[lang]
270
+ attached = prefixes(lang)
271
+ stripped = {}
272
+ for window, hit in phrase_index(lang).items():
273
+ if attached:
274
+ key = tuple(strip_prefix(atom, attached) for atom in window)
275
+ stripped.setdefault(key, hit)
276
+ _stripped_cache[lang] = stripped
277
+ return stripped
278
+
279
+
280
+ # ---------------------------------------------------------------------------
281
+ # Phrase index (reader A) and phrase positions (reader B)
282
+ # ---------------------------------------------------------------------------
283
+ Phrase = Tuple[Tuple[str, ...], str, str]
284
+
285
+
286
+ def phrase_atoms(phrase: str) -> Tuple[str, ...]:
287
+ """The atoms a lexicon phrase is written with, through the same atomiser as a sentence.
288
+
289
+ A Chinese term in a data file is one token, and one token is not one atom: the atomiser cuts
290
+ it into characters, exactly as it cuts the sentence the user typed. Doing both sides the same
291
+ way is the only reason a data file and a sentence can be compared at all.
292
+ """
293
+ return tuple(fold(atom) for kind, atom in atomize(phrase) if kind == "w")
294
+
295
+
296
+ _SLOT_MARK = re.compile(r"\{[TFVABM]\}")
297
+
298
+
299
+ def pattern_literals(lang: str) -> List[Tuple[str, ...]]:
300
+ """The function words the written patterns of a variety spell out themselves, one atom each.
301
+
302
+ A pattern is part of the data of a variety, so every word it writes is a word of that variety
303
+ by definition. ``la matrice inversa di {M}`` names ``matrice``, and a reader that called that
304
+ word unknown would refuse the very shape the data file documents. These words carry no value,
305
+ which is what makes them noise: they may stand in a sentence, they never fill a slot. A single
306
+ Latin letter is skipped, because a letter is the unknown of the math language and no pattern
307
+ ever writes one outside a slot.
308
+ """
309
+ words: List[Tuple[str, ...]] = []
310
+ for entries in patterns(lang).values():
311
+ for pattern in entries:
312
+ for chunk in _SLOT_MARK.split(pattern):
313
+ for atom in phrase_atoms(chunk):
314
+ if len(atom) == 1 and "a" <= atom <= "z":
315
+ continue
316
+ words.append((atom,))
317
+ return words
318
+
319
+
320
+ def phrase_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
321
+ """Map a folded word sequence to ``(role, value)``: verb, connective, marker or noise.
322
+
323
+ Verbs, connectives, markers and noise words of a variety share one index, because reader A
324
+ has to decide between them with a single longest match. The index is built once per variety.
325
+ """
326
+ if lang in _index_cache:
327
+ return _index_cache[lang]
328
+ index: Dict[Tuple[str, ...], Tuple[str, str]] = {}
329
+ for verb, kinds in verbs(lang).items():
330
+ index[phrase_atoms(verb)] = ("verb", kinds[0])
331
+ for symbol, words in connectives(lang).items():
332
+ for word in words:
333
+ index[phrase_atoms(word)] = ("connective", symbol)
334
+ for name, words in markers(lang).items():
335
+ for word in words:
336
+ index[phrase_atoms(word)] = ("marker", name)
337
+ for word in noise(lang):
338
+ index.setdefault(phrase_atoms(word), ("noise", ""))
339
+ for atom in pattern_literals(lang):
340
+ index.setdefault(atom, ("noise", ""))
341
+ # A data file with an empty phrase would match at every position and read nothing: drop it.
342
+ index.pop((), None)
343
+ _index_cache[lang] = index
344
+ return index
345
+
346
+
347
+ def max_phrase_length(lang: str) -> int:
348
+ return max((len(key) for key in phrase_index(lang)), default=1)
349
+
350
+
351
+ def phrase_spans(lang: str) -> List[Tuple[str, str, str]]:
352
+ """``(phrase, role, value)`` for every phrase of the variety, longest phrase first.
353
+
354
+ Reader B walks these against the sentence text itself, which is a different mechanism from
355
+ the token by token longest match of reader A.
356
+ """
357
+ out: List[Tuple[str, str, str]] = []
358
+ for verb, kind in verbs(lang).items():
359
+ out.append((verb, "verb", kind))
360
+ for symbol, words in connectives(lang).items():
361
+ for word in words:
362
+ out.append((word, "connective", symbol))
363
+ for name, words in markers(lang).items():
364
+ for word in words:
365
+ out.append((word, "marker", name))
366
+ for word in noise(lang):
367
+ out.append((word, "noise", ""))
368
+ out.sort(key=lambda item: (-len(item[0]), item[0]))
369
+ return out
370
+
371
+
372
+ # ---------------------------------------------------------------------------
373
+ # Presentation data
374
+ # ---------------------------------------------------------------------------
375
+ def labels(lang: str) -> Dict[str, str]:
376
+ return load(lang).get("labels", {})
377
+
378
+
379
+ def reading_labels(lang: str) -> Dict[str, str]:
380
+ return load(lang).get("reading", {})
381
+
382
+
383
+ def reason_texts(lang: str) -> Dict[str, str]:
384
+ return load(lang).get("reasons", {})
385
+
386
+
387
+ def examples(lang: str) -> List[str]:
388
+ return load(lang).get("examples", [])
389
+
390
+
391
+ def label(lang: str, key: str, fallback: str = "") -> str:
392
+ return labels(lang).get(key, fallback)
393
+
394
+
395
+ def translate_reason(lang: str, reason: str, **fields: Any) -> str:
396
+ """One reason in the language of the user, with the fields a template asks for."""
397
+ table = reason_texts(lang)
398
+ text = table.get(reason) or table.get("other") or reason
399
+ try:
400
+ return text.format(**fields)
401
+ except (KeyError, IndexError):
402
+ return text
403
+
404
+
405
+ def language_name(lang: str) -> str:
406
+ return load(lang).get("name", lang)
407
+
408
+
409
+ def find_by_hint(lang: str) -> Optional[str]:
410
+ """Resolve a ``--lang`` hint (a code or a name) to a language code, or ``None``."""
411
+ if lang in _available():
412
+ return lang
413
+ wanted = fold(lang)
414
+ for code in languages():
415
+ if fold(code) == wanted or fold(language_name(code)) == wanted:
416
+ return code
417
+ return None
418
+
419
+
420
+ def _available() -> List[str]:
421
+ return languages()
lgstratum/pipeline.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math stratum 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
+
23
+
24
+ def referee(decls: List[str], asserts: List[str]) -> str:
25
+ """Run the referee of the math stratum over one envelope claim, in this process."""
26
+ status = compare.smt_referee(decls, asserts)
27
+ return status if status in ("sat", "unsat", "unknown", "error") else "unknown"
28
+
29
+
30
+ def seed(question: str, lang: str) -> Dict[str, Any]:
31
+ """The envelope the arbiter node starts a session with: the question and its language."""
32
+ dossier = {"question": question, "lang": lang}
33
+ return {"payload": {"naturalLanguage": protocol.encode("question (%s): %s" % (lang, question), dossier)},
34
+ "sender": "arbiter", "turn": 0, "volatileState": {"internalTimeTick": 0}}
35
+
36
+
37
+ def ask(question: str, lang: str, active: Sequence[str] = ORDER, fault_spec: Optional[Sequence[str]] = None,
38
+ call_math: bool = True) -> Dict[str, Any]:
39
+ """One session, in memory: returns the dossier, the referee log, the verdict and the reply."""
40
+ faults.configure(fault_spec or ())
41
+ previous = os.environ.get("LGSTRATUM_MATH_BACKEND")
42
+ if not call_math:
43
+ os.environ["LGSTRATUM_MATH_BACKEND"] = "none"
44
+ current = seed(question, lang)
45
+ records: List[Dict[str, Any]] = []
46
+ turn = 0
47
+ try:
48
+ for name in ORDER:
49
+ if name not in active:
50
+ continue
51
+ turn += 1
52
+ incoming = {"sender": current["sender"], "turn": turn,
53
+ "volatileState": {"internalTimeTick": turn}, "payload": current["payload"]}
54
+ out = agents.run_step(name, incoming, name)
55
+ constraints = out["payload"]["smtConstraints"]
56
+ actual = referee(constraints["declarations"], constraints["assertions"])
57
+ records.append({"turn": turn, "sender": name, "claimed": constraints["z3Status"], "referee": actual})
58
+ current = out
59
+ finally:
60
+ if not call_math:
61
+ if previous is None:
62
+ os.environ.pop("LGSTRATUM_MATH_BACKEND", None)
63
+ else:
64
+ os.environ["LGSTRATUM_MATH_BACKEND"] = previous
65
+ dossier = protocol.decode(current["payload"]["naturalLanguage"])
66
+ final = checked_verdict(dossier, records, arbiter_expected="arbiter" in active)
67
+ reply = render.reply(dossier, final, records)
68
+ return {"dossier": dossier, "records": records, "final": final, "reply": reply,
69
+ "faults": sorted(faults.FIRED)}
70
+
71
+
72
+ def _unknown(reason: str) -> Dict[str, Any]:
73
+ return {"state": "NONE", "assurance": 0, "ceiling": 0, "math_assurance": 0, "math_status": None,
74
+ "answer": "", "reasons": [reason], "consulted_math": False, "detected": []}
75
+
76
+
77
+ def referee_adjusted(final: Dict[str, Any], records: List[Dict[str, Any]]) -> Dict[str, Any]:
78
+ """Zero the verdict when the referee disagrees with what a node claimed about its own envelope."""
79
+ bad = [record["sender"] for record in records if record["claimed"] != record["referee"]]
80
+ if bad:
81
+ final = dict(final)
82
+ final["assurance"] = 0
83
+ final["reasons"] = list(final.get("reasons", [])) + ["referee"]
84
+ final["detected"] = list(final.get("detected", [])) + bad
85
+ return final
86
+
87
+
88
+ def independent_echo(dossier: Dict[str, Any]) -> bool:
89
+ """Recompute the echo check from the transcript, without asking the node that wrote it."""
90
+ math_verdict = dossier.get("math") or {}
91
+ if not math_verdict.get("problem_math"):
92
+ return True
93
+ for key in ("reading_a", "reading_b", "reading_direct"):
94
+ reading = dossier.get(key) or {}
95
+ if reading.get("math") and not coverage.echo_matches(reading, math_verdict):
96
+ return False
97
+ return True
98
+
99
+
100
+ def checked_verdict(dossier: Dict[str, Any], records: List[Dict[str, Any]], arbiter_expected: bool = True) -> Dict[str, Any]:
101
+ """The verdict a user is shown: recomputed from the evidence, then the more cautious of the two."""
102
+ try:
103
+ evidence = dict(dossier)
104
+ evidence["echo_ok"] = independent_echo(dossier)
105
+ recomputed = referee_adjusted(decide.decide(evidence), records)
106
+ except (AttributeError, KeyError, TypeError, ValueError, IndexError, ArithmeticError) as error:
107
+ return _unknown("the decision rule could not read the evidence: %s" % error)
108
+ arbiter = dossier.get("final")
109
+ if not isinstance(arbiter, dict) or "state" not in arbiter or "assurance" not in arbiter:
110
+ return _unknown("the arbiter produced no verdict") if arbiter_expected else recomputed
111
+ if arbiter["state"] == recomputed["state"] and arbiter.get("answer") == recomputed.get("answer"):
112
+ return recomputed
113
+ final = dict(recomputed if recomputed["assurance"] <= int(arbiter.get("assurance", 0) or 0) else arbiter)
114
+ final["reasons"] = list(final.get("reasons", [])) + ["arbiter and recomputed decision disagree"]
115
+ final["detected"] = list(final.get("detected", [])) + ["arbiter"]
116
+ return final
lgstratum/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 math-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 math language handed to the math stratum
17
+ ``math`` the verdict the math stratum 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)
lgstratum/read_a.py ADDED
@@ -0,0 +1,334 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4
+ is written out in ``lexicon/<lang>.json`` with the mathematics in a slot. A pattern matches only
5
+ if every function word it names is present, in order, and if every verb and every marker the user
6
+ wrote is accounted for. That strictness is the point: when A produces a sentence it read one of
7
+ the documented shapes and nothing else.
8
+
9
+ Reader B (:mod:`lgstratum.read_b`) does something different with the same data -- it looks for the
10
+ marker *frame* of a kind in the sentence, ignoring where the verb stands -- and the topology only
11
+ trusts a reading the two agree on. What the two readers share is the lexicon and the atomiser in
12
+ :mod:`lgstratum.segment`, just as the two formalizers of the math 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 = re.compile(r"\{([TFVABM])\}")
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 variable, not the function 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, variable, or a lexicon phrase with its role and value.
48
+
49
+ One longest match per position decides between verb, connective, marker and noise, which is
50
+ why a data file must not give one phrase two roles. The comparison connectives are written in
51
+ long and short form side by side, so the longer reading of "at least" never degenerates into
52
+ the shorter reading of "greater than".
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(w, attached) for w in window)
84
+ if key in stripped_index:
85
+ hit = (stripped_index[key], key)
86
+ break
87
+ if hit:
88
+ (role, value), key = hit
89
+ # The item carries the atoms as the sentence wrote them; the lexicon key it matched is
90
+ # kept only to look the verb up, because Arabic writes a lexicon word with prefixes
91
+ # attached and the data file records it without them.
92
+ item = {"role": role, "value": value, "words": list(window), "surface": atom}
93
+ if role == "verb":
94
+ table = lexicon.verb_atoms_index(lang)
95
+ item["kinds"] = table.get(window) or table.get(key) or (value,)
96
+ items.append(item)
97
+ index += len(window)
98
+ continue
99
+ if word in lexicon.MATH_WORDS:
100
+ items.append({"role": "math", "value": word, "words": [], "surface": atom})
101
+ index += 1
102
+ continue
103
+ if atom and atom in lexicon.noise_chars(lang):
104
+ # A single character particle of a script written without spaces (Chinese particles).
105
+ # It carries its own atom as its words so that a pattern naming the particle can match
106
+ # it; it carries no value, so it never reaches the mathematics of a slot.
107
+ items.append({"role": "noise", "value": "", "words": [word], "surface": atom})
108
+ index += 1
109
+ continue
110
+ if word in lexicon.DOMAIN_LETTERS:
111
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom,
112
+ "reason": "domain_letter"})
113
+ index += 1
114
+ continue
115
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
116
+ index += 1
117
+ return items
118
+
119
+
120
+ def _text(item: Dict[str, Any]) -> str:
121
+ """The mathematics an item contributes to a slot: its symbols, its variable, its relation."""
122
+ if item["role"] == "connective":
123
+ return " %s " % item["value"]
124
+ return item["value"]
125
+
126
+
127
+ def _claim(words: List[str], chunk_slice: List[str], attached: List[str]) -> bool:
128
+ """Whether the atoms an item carries are the atoms a chunk of the pattern asks for.
129
+
130
+ Arabic writes a word with its article and its conjunctions attached to it, and the pattern in
131
+ the data file names the bare word. Stripping the attachment from both sides is what lets a
132
+ pattern name a word the sentence wrote in another form, and nothing else is forgiven: an item
133
+ that carries no atoms is mathematics, and mathematics is never a word of a pattern.
134
+ """
135
+ if not words:
136
+ return False
137
+ if list(words) == list(chunk_slice):
138
+ return True
139
+ if not attached:
140
+ return False
141
+ return ([lexicon.strip_prefix(word, attached) for word in words]
142
+ == [lexicon.strip_prefix(word, attached) for word in chunk_slice])
143
+
144
+
145
+ def _find(chunk: List[str], items: List[Dict[str, Any]], start: int,
146
+ attached: List[str]) -> Optional[Tuple[int, int]]:
147
+ """Where in the item stream the literal words of a pattern chunk appear, or ``None``.
148
+
149
+ A chunk is contiguous: it may not span a piece of mathematics, and no function word the
150
+ pattern did not name may sit inside it. That is what stops a pattern from swallowing a
151
+ sentence it does not describe.
152
+ """
153
+ for first in range(start, len(items) + 1):
154
+ cursor = first
155
+ taken = 0
156
+ ok = True
157
+ while taken < len(chunk):
158
+ if cursor >= len(items):
159
+ ok = False
160
+ break
161
+ words = items[cursor]["words"]
162
+ if not _claim(words, chunk[taken:taken + len(words)], attached):
163
+ ok = False
164
+ break
165
+ taken += len(words)
166
+ cursor += 1
167
+ if ok:
168
+ return first, cursor
169
+ return None
170
+
171
+
172
+ def _consume(items: List[Dict[str, Any]], start: int, stop: int) -> Optional[List[Dict[str, Any]]]:
173
+ """The mathematics held between two positions, or ``None`` when an unnamed word stands there."""
174
+ bucket: List[Dict[str, Any]] = []
175
+ for item in items[start:stop]:
176
+ if item["role"] in _CONTENT:
177
+ bucket.append(item)
178
+ elif item["role"] != "noise":
179
+ return None
180
+ return bucket
181
+
182
+
183
+ def _fill(group: List[str], bucket: List[Dict[str, Any]]) -> Optional[Dict[str, str]]:
184
+ """The values of the slots that one region of a sentence feeds.
185
+
186
+ Usually one slot, and the whole region is its value. A pattern may also put two slots side by
187
+ side, with no words between them -- Hindi writes the integrand and the lower bound one after
188
+ the other -- and then the region has to break into exactly one run per slot. A region that does
189
+ not break that way is a region the pattern cannot read, and guessing where one slot ends and the
190
+ other begins would be the reader inventing the problem it then reports.
191
+ """
192
+ if len(bucket) < len(group):
193
+ return None
194
+ if len(group) == 1:
195
+ joined = " ".join(_text(item) for item in bucket).strip()
196
+ if not joined:
197
+ return None
198
+ return {group[0]: canonical.tidy(joined)}
199
+ if len(bucket) != len(group):
200
+ return None
201
+ filled: Dict[str, str] = {}
202
+ for slot, item in zip(group, bucket):
203
+ value = canonical.tidy(_text(item))
204
+ if not value:
205
+ return None
206
+ filled[slot] = value
207
+ return filled
208
+
209
+
210
+ def match(chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]],
211
+ attached: List[str]) -> Optional[Dict[str, str]]:
212
+ """A value per slot name, or ``None`` when the pattern does not describe the items.
213
+
214
+ Every verb and every marker of the sentence has to be consumed by a chunk of the pattern, and
215
+ the mathematics left over falls into the slots in the order the pattern names them. A pattern
216
+ that ignores a marker the sentence carries is a pattern that misread the sentence, so it fails;
217
+ so does a pattern that leaves a piece of mathematics outside every slot.
218
+ """
219
+ filled: Dict[str, str] = {}
220
+ group = [slots[0]]
221
+ position = 0
222
+ if chunks[0]:
223
+ # Words before the first slot: a function word the pattern does not name is harmless there,
224
+ # because it carries no mathematics, but mathematics before it belongs to no slot of the
225
+ # pattern, and a verb or a marker before it is a joint the pattern does not describe.
226
+ found = _find(chunks[0], items, 0, attached)
227
+ if found is None or _consume(items, 0, found[0]) != []:
228
+ return None
229
+ position = found[1]
230
+ for index in range(1, len(slots)):
231
+ if not chunks[index]:
232
+ group.append(slots[index])
233
+ continue
234
+ found = _find(chunks[index], items, position, attached)
235
+ if found is None:
236
+ return None
237
+ bucket = _consume(items, position, found[0])
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
+ group = [slots[index]]
245
+ position = found[1]
246
+ tail = chunks[len(slots)]
247
+ if tail:
248
+ found = _find(tail, items, position, attached)
249
+ # Nothing but function words may follow the last words of the pattern: mathematics after
250
+ # the end of the shape belongs to no slot, so the shape does not describe the sentence.
251
+ if found is None or _consume(items, found[1], len(items)) != []:
252
+ return None
253
+ bucket = _consume(items, position, found[0])
254
+ else:
255
+ bucket = _consume(items, position, len(items))
256
+ if bucket is None:
257
+ return None
258
+ part = _fill(group, bucket)
259
+ if part is None:
260
+ return None
261
+ filled.update(part)
262
+ return filled
263
+
264
+
265
+ def _slot_problems(kind: str, slots: Dict[str, str]) -> List[Dict[str, str]]:
266
+ """A slot that is not the shape the kind promises: one variable, a matrix, closed brackets."""
267
+ problems: List[Dict[str, str]] = []
268
+ for name, value in sorted(slots.items()):
269
+ if name == "V" and canonical.variable(value) is None:
270
+ problems.append({"reason": "bad_variable", "slot": name})
271
+ if name == "M" and canonical.matrix(value) is None:
272
+ problems.append({"reason": "bad_matrix", "slot": name})
273
+ if not canonical.balanced(canonical.print_math(kind, slots)):
274
+ problems.append({"reason": "unbalanced"})
275
+ return problems
276
+
277
+
278
+ def read(lang: str, text: str) -> Dict[str, Any]:
279
+ """The reading reader A reaches in one variety, and why it abstained when it did."""
280
+ items = scan(lang, text)
281
+ result: Dict[str, Any] = {"reader": "reader_a", "lang": lang, "mode": "pattern",
282
+ "kind": None, "math": None, "slots": {}, "markers": [], "notes": []}
283
+ unknown = [item for item in items if item["role"] == "unknown"]
284
+ if unknown:
285
+ result["status"] = "NOT COVERED"
286
+ for item in unknown:
287
+ result["notes"].append({"reason": item.get("reason", "unknown_word"),
288
+ "word": item["surface"]})
289
+ return result
290
+ result["markers"] = [item["value"] for item in items if item["role"] == "marker"]
291
+ candidates, why = lexicon.announce(lang, items)
292
+ if not candidates:
293
+ result["status"] = "NOT COVERED"
294
+ result["notes"].append(why)
295
+ return result
296
+ result["announced"] = candidates
297
+ attached = lexicon.prefixes(lang)
298
+ found: List[Tuple[str, str, Dict[str, str]]] = []
299
+ for kind in candidates:
300
+ for pattern in lexicon.patterns(lang).get(kind, []):
301
+ chunks, slots = compile_pattern(pattern)
302
+ assigned = match(chunks, slots, items, attached)
303
+ if assigned is None:
304
+ continue
305
+ try:
306
+ math_str = canonical.print_math(kind, assigned)
307
+ except canonical.ReadingError as error:
308
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
309
+ continue
310
+ problems = _slot_problems(kind, assigned)
311
+ if problems:
312
+ result["notes"].extend(problems)
313
+ continue
314
+ if not any(entry[1] == math_str for entry in found):
315
+ found.append((kind, math_str, assigned))
316
+ if not found:
317
+ result["status"] = "NOT COVERED"
318
+ if not any(note["reason"] in ("bad_variable", "bad_matrix", "unbalanced")
319
+ for note in result["notes"]):
320
+ result["notes"].append({"reason": "no_pattern"})
321
+ return result
322
+ if len(found) > 1:
323
+ result["status"] = "AMBIGUOUS"
324
+ result["notes"].append({"reason": "multiple",
325
+ "first": found[0][1], "second": found[1][1]})
326
+ return result
327
+ kind, math_str, assigned = found[0]
328
+ result["status"] = "READ"
329
+ result["kind"] = kind
330
+ result["math"] = math_str
331
+ result["slots"] = assigned
332
+ result["literals"] = numeric_literals(text)
333
+ result["notes"] = []
334
+ return result
lgstratum/read_b.py ADDED
@@ -0,0 +1,306 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reader B: the frame reader, which never looks at a surface pattern.
2
+
3
+ Reader B finds the lexicon phrases in a sentence by searching for them -- longest phrase first,
4
+ over the whole sentence, instead of walking the sentence from left to right -- and then reads the
5
+ sentence by the **joints** of the math language: the markers the sentence carries, in the order it
6
+ carries them. Where the verb stands, which words surround it and whether the sentence puts the
7
+ mathematics first or last are all invisible to B. It asks one question: does the sentence hold the
8
+ joints of a form of the math language, with a piece of mathematics between each pair?
9
+
10
+ That is a different question from reader A's ("does this sentence have one of the shapes the
11
+ lexicon writes down?"), so the two reach different answers on real sentences, which is the point.
12
+ What they share is the lexicon, the atomiser and the templates of the math language -- the same
13
+ kind of sharing the two formalizers of the math topology accept, where one written grammar is the
14
+ specification both are checked against.
15
+ """
16
+
17
+ from typing import Any, Dict, List, Optional, Tuple
18
+
19
+ from . import canonical, lexicon
20
+ from .canonical import ReadingError
21
+ from .segment import atomize, fold, numeric_literals
22
+
23
+ _CONTENT = ("math", "var", "connective")
24
+
25
+
26
+ def _matches(window: List[str], phrase: Tuple[str, ...], attached: List[str]) -> bool:
27
+ """Whether a window of folded word atoms is a phrase, with or without attached prefixes.
28
+
29
+ The data file of Arabic writes "in the integers" without its article, and a sentence writes it
30
+ with one. The comparison then strips the attachment from both sides, which is what lets the
31
+ article of the sentence and the absence of it in the data file meet in the same written form.
32
+ """
33
+ if list(window) == list(phrase):
34
+ return True
35
+ if not attached:
36
+ return False
37
+ stripped = [lexicon.strip_prefix(atom, attached) for atom in window]
38
+ return stripped == list(phrase) or stripped == [lexicon.strip_prefix(a, attached) for a in phrase]
39
+
40
+
41
+ def find_spans(lang: str, atoms: List[Tuple[str, str]]) -> Tuple[List[Dict[str, Any]], List[bool]]:
42
+ """Every occurrence of every lexicon phrase, longest first, never overlapping.
43
+
44
+ Reader A resolves one position at a time by taking the longest phrase there. B enumerates the
45
+ whole phrase table, longest entries first, and lets each entry claim its occurrences wherever
46
+ they are. The two orderings disagree on purpose: a sentence whose phrases interleave gives the
47
+ two readers different chances, and a reading only counts when both take it.
48
+ """
49
+ folded = [fold(atom) if kind == "w" else "" for kind, atom in atoms]
50
+ attached = lexicon.prefixes(lang)
51
+ covered = [False] * len(atoms)
52
+ table = sorted(lexicon.phrase_index(lang).items(),
53
+ key=lambda entry: (-len(entry[0]), -len("".join(entry[0])), entry[0]))
54
+ spans: List[Dict[str, Any]] = []
55
+ for phrase, hit in table:
56
+ role, value = hit
57
+ if not phrase:
58
+ continue
59
+ start = 0
60
+ while start <= len(atoms) - len(phrase):
61
+ found = None
62
+ for position in range(start, len(atoms) - len(phrase) + 1):
63
+ if any(covered[position + step] or atoms[position + step][0] != "w"
64
+ for step in range(len(phrase))):
65
+ continue
66
+ if _matches(folded[position:position + len(phrase)], phrase, attached):
67
+ found = position
68
+ break
69
+ if found is None:
70
+ break
71
+ for step in range(len(phrase)):
72
+ covered[found + step] = True
73
+ spans.append({"start": found, "end": found + len(phrase), "role": role,
74
+ "value": value, "words": folded[found:found + len(phrase)],
75
+ "kinds": (lexicon.verb_atoms_index(lang).get(phrase, (value,))
76
+ if role == "verb" else (value,))})
77
+ start = found + len(phrase)
78
+ spans.sort(key=lambda span: span["start"])
79
+ return spans, covered
80
+
81
+
82
+ def _neighbours(atoms: List[Tuple[str, str]], index: int) -> Tuple[str, str]:
83
+ """The runs of mathematics standing on either side of an atom, empty where a word stands."""
84
+ before = atoms[index - 1][1] if index and atoms[index - 1][0] == "m" else ""
85
+ after = ""
86
+ if index + 1 < len(atoms) and atoms[index + 1][0] == "m":
87
+ after = atoms[index + 1][1]
88
+ return before, after
89
+
90
+
91
+ def classify(lang: str, atoms: List[Tuple[str, str]], spans: List[Dict[str, Any]],
92
+ covered: List[bool]) -> List[Dict[str, Any]]:
93
+ """Tag each atom from the spans, and name what no phrase claimed.
94
+
95
+ B is less suspicious than A about a single letter: it calls it a variable whenever no lexicon
96
+ phrase claimed it, because it has no operator adjacency to reason with. That is one of the ways
97
+ the two readers can part company, and a bare letter in the middle of an Italian phrase is
98
+ exactly where they do.
99
+ """
100
+ attached = lexicon.prefixes(lang)
101
+ particles = lexicon.load(lang).get("noise_chars", "")
102
+ starts = {span["start"]: span for span in spans}
103
+ items: List[Dict[str, Any]] = []
104
+ index = 0
105
+ while index < len(atoms):
106
+ kind, atom = atoms[index]
107
+ if kind == "m":
108
+ items.append({"role": "math", "value": atom, "words": [], "surface": atom})
109
+ index += 1
110
+ continue
111
+ if index in starts:
112
+ span = starts[index]
113
+ before, after = _neighbours(atoms, index)
114
+ if (span["role"] in ("connective", "marker", "verb")
115
+ and span["end"] == span["start"] + 1
116
+ and lexicon.operand(lang, fold(atom), before, after)):
117
+ # A phrase of one letter claimed a letter that stands against an operator: in the
118
+ # math language that letter is the unknown, and a reading that swaps it for the
119
+ # conjunction it spells changes the problem the user asked about.
120
+ items.append({"role": "var", "value": fold(atom), "words": [], "surface": atom})
121
+ index = span["end"]
122
+ continue
123
+ items.append({"role": span["role"], "value": span["value"], "words": span["words"],
124
+ "kinds": span.get("kinds", (span["value"],)), "surface": atom})
125
+ index = span["end"]
126
+ continue
127
+ word = fold(atom)
128
+ if atom and atom in particles:
129
+ items.append({"role": "noise", "value": "", "words": [], "surface": atom})
130
+ index += 1
131
+ continue
132
+ if len(word) == 1 and "a" <= word <= "z":
133
+ items.append({"role": "var", "value": word, "words": [], "surface": atom})
134
+ index += 1
135
+ continue
136
+ if word in lexicon.MATH_WORDS:
137
+ items.append({"role": "math", "value": word, "words": [], "surface": atom})
138
+ index += 1
139
+ continue
140
+ if word in lexicon.DOMAIN_LETTERS:
141
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom,
142
+ "reason": "domain_letter"})
143
+ index += 1
144
+ continue
145
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
146
+ index += 1
147
+ return items
148
+
149
+
150
+ def _text(item: Dict[str, Any]) -> str:
151
+ if item["role"] == "connective":
152
+ return " %s " % item["value"]
153
+ return item["value"]
154
+
155
+
156
+ def _regions_marked(items: List[Dict[str, Any]]) -> List[Tuple[Optional[str], str]]:
157
+ """The runs of mathematics of a sentence, each tagged with the joint standing before it.
158
+
159
+ A joint of the math language introduces the region that follows it, and the verb of a sentence
160
+ introduces nothing: it sits in the gap a form leaves without a joint. Tagging a region instead
161
+ of counting regions is what lets B read a frame written out of order, because English, Spanish,
162
+ Italian and Chinese front the variable ("for x solve ...") and a reader that filled the slots by
163
+ position would put the unknown where the formula belongs.
164
+
165
+ The atoms of a region are joined with a space on purpose. The atomiser cuts the mathematics of a
166
+ sentence into runs, and one run can be the whole expression while two runs can be the two ends
167
+ of one expression split by a word that is mathematics to the math stratum and a word to the
168
+ lexicon (``n mod 3 = 1``). Gluing the runs without a space invents a token that was never
169
+ written, and an invented token is a changed problem.
170
+ """
171
+ regions: List[Tuple[Optional[str], str]] = []
172
+ buffer: List[str] = []
173
+ joint: Optional[str] = None
174
+ for item in items:
175
+ if item["role"] in ("marker", "verb"):
176
+ regions.append((joint, canonical.tidy(" ".join(buffer))))
177
+ buffer = []
178
+ joint = item["value"] if item["role"] == "marker" else None
179
+ elif item["role"] in _CONTENT:
180
+ buffer.append(_text(item))
181
+ regions.append((joint, canonical.tidy(" ".join(buffer))))
182
+ return regions
183
+
184
+
185
+ def _assign_joints(marked: List[Tuple[Optional[str], str]], gaps: List[Optional[str]],
186
+ slots: Tuple[str, ...]) -> Optional[Dict[str, str]]:
187
+ """Fill the slots of a form from the regions a sentence offers, or fail.
188
+
189
+ A slot takes the region that stands after the joint the form puts before it, and a slot whose
190
+ gap carries no joint takes the one region of the sentence no joint claims. A region holding no
191
+ mathematics is never a candidate, and every region that does hold mathematics has to end up in a
192
+ slot: mathematics left over belongs to no slot of the form, so the form does not describe the
193
+ sentence. This is also how a joint the math language puts last (``over Z``) is policed -- the
194
+ region it introduces is empty, and anything written after it makes the form fail -- and why a
195
+ frame whose slots arrive in a rotated order still reads, because no slot is identified by its
196
+ position in the sentence.
197
+ """
198
+ introduced: Dict[str, List[int]] = {}
199
+ unclaimed: List[int] = []
200
+ for index, (joint, _) in enumerate(marked):
201
+ if joint is None:
202
+ unclaimed.append(index)
203
+ else:
204
+ introduced.setdefault(joint, []).append(index)
205
+ assigned: Dict[str, str] = {}
206
+ taken: set = set()
207
+ for position, slot in enumerate(slots):
208
+ joint = gaps[position]
209
+ if joint is None:
210
+ candidates = [index for index in unclaimed
211
+ if index not in taken and marked[index][1]]
212
+ else:
213
+ candidates = [index for index in introduced.get(joint, [])
214
+ if index not in taken and marked[index][1]]
215
+ if len(candidates) != 1:
216
+ return None
217
+ assigned[slot] = marked[candidates[0]][1]
218
+ taken.add(candidates[0])
219
+ last = gaps[len(slots)]
220
+ if last is not None and any(marked[index][1] for index in introduced.get(last, [])):
221
+ return None
222
+ if any(text for index, (_, text) in enumerate(marked) if text and index not in taken):
223
+ return None
224
+ return assigned
225
+
226
+
227
+ def _problems(kind: str, slots: Dict[str, str]) -> List[Dict[str, str]]:
228
+ problems: List[Dict[str, str]] = []
229
+ for name, value in sorted(slots.items()):
230
+ if name == "V" and canonical.variable(value) is None:
231
+ problems.append({"reason": "bad_variable", "slot": name})
232
+ if name == "M" and canonical.matrix(value) is None:
233
+ problems.append({"reason": "bad_matrix", "slot": name})
234
+ if not canonical.balanced(canonical.print_math(kind, slots)):
235
+ problems.append({"reason": "unbalanced"})
236
+ return problems
237
+
238
+
239
+ def read(lang: str, text: str) -> Dict[str, Any]:
240
+ """The reading reader B reaches in one variety, and why it abstained when it did."""
241
+ atoms = atomize(text)
242
+ spans, covered = find_spans(lang, atoms)
243
+ items = classify(lang, atoms, spans, covered)
244
+ result: Dict[str, Any] = {"reader": "reader_b", "lang": lang, "mode": "frame",
245
+ "kind": None, "math": None, "slots": {}, "markers": [], "notes": []}
246
+ unknown = [item for item in items if item["role"] == "unknown"]
247
+ if unknown:
248
+ result["status"] = "NOT COVERED"
249
+ for item in unknown:
250
+ result["notes"].append({"reason": item.get("reason", "unknown_word"),
251
+ "word": item["surface"]})
252
+ return result
253
+ markers = [item["value"] for item in items if item["role"] == "marker"]
254
+ result["markers"] = markers
255
+ candidates, why = lexicon.announce(lang, items)
256
+ if not candidates:
257
+ result["status"] = "NOT COVERED"
258
+ result["notes"].append(why)
259
+ return result
260
+ result["announced"] = candidates
261
+ regions = _regions_marked(items)
262
+ frame_table = lexicon.frames(lang)
263
+ found: List[Tuple[str, str, Dict[str, str]]] = []
264
+ for kind in candidates:
265
+ allowed = [list(sequence) for sequence in frame_table.get(kind, {}).get("sequences", [])]
266
+ if markers not in allowed:
267
+ result["notes"].append({"reason": "no_frame", "kind": kind,
268
+ "detail": " ".join(markers) or "none"})
269
+ continue
270
+ for variant in canonical.VARIANTS.get(kind, []):
271
+ if canonical.marker_sequence(kind, variant) != markers:
272
+ continue
273
+ assigned = _assign_joints(regions, canonical.gap_markers(kind, variant), variant)
274
+ if assigned is None:
275
+ result["notes"].append({"reason": "markers", "kind": kind,
276
+ "detail": " ".join(markers)})
277
+ continue
278
+ try:
279
+ math_str = canonical.print_math(kind, assigned)
280
+ except ReadingError as error:
281
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
282
+ continue
283
+ problems = _problems(kind, assigned)
284
+ if problems:
285
+ result["notes"].extend(problems)
286
+ continue
287
+ if not any(entry[1] == math_str for entry in found):
288
+ found.append((kind, math_str, assigned))
289
+ if not found:
290
+ result["status"] = "NOT COVERED"
291
+ if not result["notes"]:
292
+ result["notes"].append({"reason": "no_pattern"})
293
+ return result
294
+ if len(found) > 1:
295
+ result["status"] = "AMBIGUOUS"
296
+ result["notes"].append({"reason": "multiple",
297
+ "first": found[0][1], "second": found[1][1]})
298
+ return result
299
+ read_kind, math_str, assigned = found[0]
300
+ result["status"] = "READ"
301
+ result["kind"] = read_kind
302
+ result["math"] = math_str
303
+ result["slots"] = assigned
304
+ result["literals"] = numeric_literals(text)
305
+ result["notes"] = []
306
+ return result
lgstratum/render.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 mathematical content -- the canonical sentence the stratum understood and the answer the math
10
+ stratum 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
+ ``integral 3*x^2 from 0 to 2 wrt x`` can see which reading was used, and that is the whole point of
14
+ a 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("math") 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 math 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 math stratum."""
61
+ compare = dossier.get("compare") or {}
62
+ math_verdict = dossier.get("math") or {}
63
+ for source in (dossier.get("sent"), compare.get("left"), math_verdict.get("problem_math")):
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 reply(dossier: Dict[str, Any], final: Optional[Dict[str, Any]] = None,
82
+ records: Optional[List[Dict[str, Any]]] = None, lang: Optional[str] = None) -> Dict[str, Any]:
83
+ """Build the user-facing answer: one text block plus the machine-readable parts."""
84
+ lang = lang or str(dossier.get("lang") or "en")
85
+ if lang not in lexicon.codes():
86
+ lang = "en"
87
+ verdict = final or decide_module.decide(dossier)
88
+ labels = lexicon.labels(lang)
89
+ states = lexicon.reading_labels(lang)
90
+ fields = note_fields(dossier)
91
+
92
+ lines: List[str] = []
93
+ state = str(verdict.get("state", "NONE"))
94
+ lines.append("%s: %s" % (labels["status"], states.get(state, state)))
95
+ sentence = _sentence(dossier)
96
+ kind = _kind_understood(dossier)
97
+ if sentence and state not in ("NOT COVERED", "NONE"):
98
+ lines.append("%s (%s): %s" % (labels["understood"], kind, sentence))
99
+ if verdict.get("answer"):
100
+ lines.append("%s: %s" % (labels["answer"], verdict["answer"]))
101
+ lines.append(labels["assurance"].replace("{n}", str(verdict.get("assurance", 0))))
102
+ math_verdict = dossier.get("math") or {}
103
+ if math_verdict.get("status"):
104
+ # Which solver family the math stratum used is its own bookkeeping and nothing the reader
105
+ # of an answer asked for; what belongs in the reply is the verdict and, when the math
106
+ # stratum abstained, the reason it abstained.
107
+ tail = str(math_verdict["status"])
108
+ why = math_verdict.get("reason") or math_verdict.get("note") or ""
109
+ if not why and math_verdict.get("reasons"):
110
+ why = str(math_verdict["reasons"][0])
111
+ if why:
112
+ tail += " (" + why + ")"
113
+ lines.append("%s: %s" % (labels["math_layer"], tail))
114
+ reasons = [str(reason) for reason in verdict.get("reasons") or []]
115
+ if reasons:
116
+ math_verdict = dossier.get("math") or {}
117
+ fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])})
118
+ fields.setdefault("math_unknown", {"detail": str(math_verdict.get("reason")
119
+ or math_verdict.get("note") or "")})
120
+ texts = [_fill(lexicon.translate_reason(lang, reason, **(fields.get(reason) or {}))) for reason in reasons]
121
+ lines.append("%s: %s" % (labels["notes"], "; ".join(texts)))
122
+ check = _check_line(lang, records)
123
+ if check:
124
+ lines.append(check)
125
+ if state in ("NOT COVERED", "AMBIGUOUS", "NONE") and not verdict.get("answer"):
126
+ samples = lexicon.examples(lang)
127
+ if samples:
128
+ lines.append("%s: %s" % (labels["question"], " | ".join(samples[:5])))
129
+ return {
130
+ "lang": lang,
131
+ "language": lexicon.language_name(lang),
132
+ "state": state,
133
+ "assurance": verdict.get("assurance", 0),
134
+ "answer": verdict.get("answer", ""),
135
+ "sentence": sentence,
136
+ "kind": kind,
137
+ "reasons": reasons,
138
+ "lines": lines,
139
+ "text": "\n".join(lines),
140
+ }
lgstratum/segment.py ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
4
+ runs of *mathematics*, and it puts every digit in the shape the math language uses. The
5
+ mapping from a word to a role is the lexicon, in ``lexicon/<lang>.json`` and
6
+ :mod:`lgstratum.lexicon`.
7
+
8
+ Three normalisations happen here, and all three are testable on their own:
9
+
10
+ * digit scripts: Arabic-Indic, Extended Arabic-Indic and Devanagari digits become ASCII
11
+ digits, and compatibility normalisation turns the full width forms a Chinese keyboard
12
+ produces into their ASCII counterparts;
13
+ * separators that differ per language: the Arabic decimal sign, the Arabic and Devanagari
14
+ commas, the CJK full stop and question mark, and the bidi control characters disappear or
15
+ take their ASCII counterpart;
16
+ * context for ``.`` and ``,``: a dot is part of a number only between digits, a comma is part
17
+ of the mathematics only between two closed operands, which is what separates an Italian
18
+ sentence comma from the comma of a matrix literal.
19
+ """
20
+
21
+ import re
22
+ import unicodedata
23
+ from typing import List, Tuple
24
+
25
+ # ---------------------------------------------------------------------------
26
+ # Digits and separators
27
+ # ---------------------------------------------------------------------------
28
+ def _digits(start: int) -> dict:
29
+ return {chr(start + i): str(i) for i in range(10)}
30
+
31
+
32
+ DIGIT_MAP: dict = {}
33
+ DIGIT_MAP.update(_digits(0x0660)) # Arabic-Indic
34
+ DIGIT_MAP.update(_digits(0x06F0)) # Extended Arabic-Indic (Persian/Urdu)
35
+ DIGIT_MAP.update(_digits(0x0966)) # Devanagari
36
+ DIGIT_MAP.update(_digits(0x09E6)) # Bengali
37
+
38
+ SEPARATOR_MAP: dict = {
39
+ "\u060c": " ", # Arabic comma
40
+ "\u061b": " ", # Arabic semicolon
41
+ "\u061f": " ", # Arabic question mark
42
+ "\u066b": ".", # Arabic decimal sign
43
+ "\u066c": "", # Arabic thousands separator
44
+ "\u066d": " ", # Arabic date separator
45
+ "\u0964": " ", # Devanagari danda
46
+ "\u0965": " ", # Devanagari double danda
47
+ "\u3001": " ", # ideographic comma
48
+ "\u3002": " ", # ideographic full stop
49
+ "\uff1f": " ", # full width question mark
50
+ "\uff01": " ", # full width exclamation mark
51
+ "\u201e": " ",
52
+ "\u201f": " ",
53
+ "\u2018": " ",
54
+ "\u2019": "'", # the apostrophe of an elision is kept, and the elision is split apart
55
+ "\u201c": " ",
56
+ "\u201d": " ",
57
+ # The Italian copula would otherwise fold to the connective "e" (and), so it is not a word.
58
+ "\u00e8": " ",
59
+ "\u2013": "-",
60
+ "\u2014": "-",
61
+ "\u2212": "-", # minus sign
62
+ "\u00d7": "*", # multiplication sign
63
+ "\u00b7": "*", # middle dot
64
+ "\u00f7": "/", # division sign
65
+ "\u2265": ">=",
66
+ "\u2264": "<=",
67
+ "\u2260": "!=",
68
+ }
69
+
70
+ INVISIBLE = (
71
+ "\u200b\u200c\u200d\u200e\u200f\u061c\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\ufeff"
72
+ )
73
+
74
+ # The symbols of the math language, square brackets included: a matrix literal is the reason
75
+ # they are here, and they must be read as mathematics and not dropped as stray punctuation.
76
+ MATH_CHARS = set("0123456789+-*/^()[]<>=!|,:.")
77
+ CLOSED_CHARS = set("0123456789)]")
78
+ OPENING_CHARS = set("0123456789[(")
79
+
80
+ # The relation and operator symbols the math language accepts. Nothing else is mathematics.
81
+ OPERATORS = ("=>", "<=>", "<=", ">=", "!=", "+", "-", "*", "/", "^", "=", "<", ">", "|")
82
+
83
+
84
+ def normalize(text: str) -> str:
85
+ """Return the sentence in a canonical shape: ASCII digits, ASCII separators, one space."""
86
+ text = unicodedata.normalize("NFKC", text)
87
+ for ch in INVISIBLE:
88
+ text = text.replace(ch, "")
89
+ text = text.translate({ord(k): v for k, v in DIGIT_MAP.items()})
90
+ text = text.translate({ord(k): v for k, v in SEPARATOR_MAP.items()})
91
+ return re.sub(r"\s+", " ", text).strip()
92
+
93
+
94
+ def script_of(text: str) -> str:
95
+ """The dominant non Latin script of a sentence: cjk, arabic, devanagari, latin or none."""
96
+ counts = {"cjk": 0, "arabic": 0, "devanagari": 0, "latin": 0}
97
+ for ch in text:
98
+ if not ch.isalpha():
99
+ continue
100
+ name = unicodedata.name(ch, "")
101
+ if name.startswith("CJK") or name.startswith("IDEOGRAPHIC"):
102
+ counts["cjk"] += 1
103
+ elif name.startswith("ARABIC"):
104
+ counts["arabic"] += 1
105
+ elif name.startswith("DEVANAGARI"):
106
+ counts["devanagari"] += 1
107
+ elif name.startswith("LATIN"):
108
+ counts["latin"] += 1
109
+ best = max(counts, key=lambda k: counts[k])
110
+ return best if counts[best] else "none"
111
+
112
+
113
+ def _is_math_char(ch: str, text: str, index: int) -> bool:
114
+ if ch in MATH_CHARS:
115
+ if ch == ".":
116
+ return _neighbour(text, index, -1).isdigit() and _neighbour(text, index, 1).isdigit()
117
+ if ch == ",":
118
+ return _neighbour(text, index, -1) in CLOSED_CHARS and _neighbour(text, index, 1) in OPENING_CHARS
119
+ return True
120
+ return False
121
+
122
+
123
+ def _neighbour(text: str, index: int, step: int) -> str:
124
+ j = index + step
125
+ while 0 <= j < len(text) and text[j] == " ":
126
+ j += step
127
+ return text[j] if 0 <= j < len(text) else ""
128
+
129
+
130
+ _MARKS = ("Mn", "Mc", "Me")
131
+
132
+
133
+ def _word_char(ch: str) -> bool:
134
+ """A character of a word: a letter of any script, an apostrophe, or a combining mark.
135
+
136
+ The combining marks matter: the vowel signs of Devanagari and the Arabic diacritics are not
137
+ letters, and dropping them would break a word into pieces that no lexicon entry matches.
138
+ """
139
+ return ch.isalpha() or ch in "_'" or unicodedata.category(ch) in _MARKS
140
+
141
+
142
+ def pieces(run: str) -> List[str]:
143
+ """Split a word run at every apostrophe: an Italian elision is two words to the lexicon.
144
+
145
+ ``l'integrale`` is the article ``l`` and the noun ``integrale``, and only the second of the
146
+ two is a phrase of the lexicon. The lexicon patterns are written with the elision joined,
147
+ and compiled through this same function, so data and matching agree.
148
+ """
149
+ return [piece for piece in run.split("'") if piece]
150
+
151
+
152
+ def is_cjk(run: str) -> bool:
153
+ """Whether a run is written in Chinese characters."""
154
+ return any(unicodedata.name(ch, "").startswith(("CJK", "IDEOGRAPHIC")) for ch in run)
155
+
156
+
157
+ def word_pieces(run: str) -> List[str]:
158
+ """The atoms a word run offers the lexicon: characters for Chinese, pieces elsewhere.
159
+
160
+ Chinese is written without spaces, so the only reliable unit is the character, and a
161
+ multi character term of the lexicon is then a sequence of atoms -- which is how the lexicon
162
+ file writes it too, one space separated token per character group.
163
+ """
164
+ if is_cjk(run):
165
+ return list(run)
166
+ return pieces(run)
167
+
168
+
169
+ def atomize(text: str) -> List[Tuple[str, str]]:
170
+ """A normalized sentence as atoms: ``("m", run)`` mathematics, ``("w", word)`` word atoms.
171
+
172
+ Both readers start here. It is one of the two things they share -- the other is the lexicon --
173
+ and it is the counterpart of the shared token spec that the two formalizers of the math
174
+ topology share: sharing the atomiser buys agreement about *what the words are*, while the two
175
+ readers still disagree, productively, about what the sentence means.
176
+ """
177
+ out: List[Tuple[str, str]] = []
178
+ for kind, run in tokens(text):
179
+ if kind == "m":
180
+ out.append(("m", run))
181
+ else:
182
+ for piece in word_pieces(run):
183
+ out.append(("w", piece))
184
+ return out
185
+
186
+
187
+ def tokens(text: str) -> List[Tuple[str, str]]:
188
+ """Split a normalized sentence into ``("m", run)`` mathematics and ``("w", run)`` words.
189
+
190
+ Letters of every script open a word run, digits and the symbols of the math language open
191
+ a mathematics run. An ASCII letter run is returned as a word: :mod:`lgstratum.read_a` and
192
+ :mod:`lgstratum.read_b` decide between a variable and a function word through the lexicon.
193
+ """
194
+ text = normalize(text)
195
+ out: List[Tuple[str, str]] = []
196
+ index = 0
197
+ while index < len(text):
198
+ ch = text[index]
199
+ if ch.isspace():
200
+ index += 1
201
+ continue
202
+ if _word_char(ch):
203
+ start = index
204
+ while index < len(text) and _word_char(text[index]):
205
+ index += 1
206
+ out.append(("w", text[start:index]))
207
+ continue
208
+ if _is_math_char(ch, text, index):
209
+ start = index
210
+ while index < len(text) and _is_math_char(text[index], text, index):
211
+ index += 1
212
+ run = text[start:index].strip()
213
+ if run:
214
+ out.append(("m", run))
215
+ continue
216
+ index += 1
217
+ return out
218
+
219
+
220
+ def numeric_literals(text: str) -> List[str]:
221
+ """Every numeric literal of a sentence, in the order it appears, digits normalised."""
222
+ found: List[str] = []
223
+ for _kind, run in tokens(text):
224
+ for match in re.finditer(r"\d+(?:\.\d+)?", run):
225
+ found.append(match.group(0))
226
+ return found
227
+
228
+
229
+ def fold(word: str) -> str:
230
+ """Casefold a Latin word and drop its accents, so that one lexicon entry covers both cases.
231
+
232
+ Non Latin scripts are returned unchanged: casefolding and accent folding do not apply to
233
+ Chinese, Devanagari or Arabic, and the lexicon entries are written in the form the keyboard
234
+ produces.
235
+ """
236
+ if not any("a" <= ch.lower() <= "z" for ch in word):
237
+ return word
238
+ decomposed = unicodedata.normalize("NFD", word)
239
+ stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
240
+ return stripped.lower()
nodes/adversary/grammar.gf ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node adversary (adversary): Adversary: states the ceiling the reading layer can honestly claim and writes the inequality a raised assurance would break.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/adversary/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node arbiter (arbiter): Interface with the user: holds the question and its language, applies the decision rule, and answers in the language of the question.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/arbiter/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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): risolvi x^2 - 5*x + 6 = 0 per x\n@@DOSSIER@@{\"lang\":\"it\",\"question\":\"risolvi x^2 - 5*x + 6 = 0 per x\"}",
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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node boundary (boundary): Boundary: checks that the sentence the math topology says it solved is the sentence that was sent to it.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/boundary/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node coverage (coverage): Coverage: checks that the reading keeps every number written in the question and that the question is inside the coverage of its language.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/coverage/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node equivalence (equivalence): Equivalence: compares the two readings and says whether they state the same problem, with an SMT view when the text view is not enough.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/equivalence/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node invoker (invoker): Invoker: hands the agreed sentence to the math topology as a separate process and carries that verdict back untouched.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/invoker/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node reader_a (reader_a): First reader: turns a question written in one of the six user languages into a sentence of MathLang, without seeing the other reader.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/reader_a/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node reader_b (reader_b): Second reader: an independent reading of the same question, its own search over the same lexicon and the same templates.
2
+ -- MathLang: the controlled mathematical language this stratum writes, which is the input language of the math topology.
3
+ -- Reference implementation: the readers lgstratum/read_a.py and lgstratum/read_b.py, the printer lgstratum/canonical.py, the words lexicon/{lang}.json.
4
+ -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment.
5
+ -- In the abstractSyntaxTree string literals and variables are written bare (3, x) instead of (Lit 3), (V x),
6
+ -- an absent optional 'wrt' variable is omitted from the tree, matrix literals are written (Mat (Row 1 2) (Row 3 4)),
7
+ -- a column vector (Vec 5 6), and the optimization direction as the lower case word max or min.
8
+ abstract MathLang = {
9
+ cat
10
+ Problem ; Formula ; Term ; Var ; Dom ; Dir ; Mat ; Vec ; Names ;
11
+ fun
12
+ Evaluate : Term -> Problem ;
13
+ Prove, ProveZ : Formula -> Problem ;
14
+ Solve, SolveZ : Formula -> Var -> Problem ;
15
+ SolveSys : Formula -> Names -> Problem ;
16
+ Derivative, Antiderivative : Term -> Problem ;
17
+ DerivativeWrt, AntiderivativeWrt : Term -> Var -> Problem ;
18
+ Integral : Term -> Term -> Term -> Problem ;
19
+ IntegralWrt : Term -> Var -> Term -> Term -> Problem ;
20
+ Optimize : Dir -> Term -> Formula -> Problem ;
21
+ Max, Min : Dir ;
22
+ Det, Rank, Inverse, Nullspace : Mat -> Problem ;
23
+ Linsolve : Mat -> Vec -> Problem ;
24
+ Product : Mat -> Mat -> Problem ;
25
+ Power : Mat -> Term -> Problem ;
26
+ Maxflow : Mat -> Term -> Term -> Problem ;
27
+ Reduce : Mat -> Problem ;
28
+ Sos : Mat -> Problem ;
29
+ Dot : Vec -> Vec -> Term ;
30
+ Matvec : Mat -> Vec -> Vec ;
31
+ Eq, Ne, Lt, Le, Gt, Ge, Dvd : Term -> Term -> Formula ;
32
+ And, Or, Imp, Iff : Formula -> Formula -> Formula ;
33
+ Not : Formula -> Formula ;
34
+ Forall, Exists : Var -> Dom -> Formula -> Formula ;
35
+ True, False : Formula ;
36
+ Add, Sub, Mul, Div, Pow, Mod, Idiv : Term -> Term -> Term ;
37
+ Neg : Term -> Term ;
38
+ Lit : String -> Term ;
39
+ V : Var -> Term ;
40
+ MkVar : String -> Var ;
41
+ R, Z : Dom ;
42
+ }
43
+
44
+ concrete MathLangEng of MathLang = {
45
+ lincat
46
+ Problem, Formula, Term, Var, Dom, Dir, Mat, Vec, Names = Str ;
47
+ lin
48
+ Evaluate t = "evaluate" ++ t ;
49
+ Prove f = "prove" ++ f ;
50
+ ProveZ f = "prove" ++ f ++ "over" ++ "Z" ;
51
+ Solve f v = "solve" ++ f ++ "for" ++ v ;
52
+ SolveZ f v = "solve" ++ f ++ "for" ++ v ++ "over" ++ "Z" ;
53
+ SolveSys f ns = "solve" ++ f ++ "for" ++ ns ;
54
+ Derivative t = "derivative" ++ t ;
55
+ DerivativeWrt t v = "derivative" ++ t ++ "wrt" ++ v ;
56
+ Antiderivative t = "antiderivative" ++ t ;
57
+ AntiderivativeWrt t v = "antiderivative" ++ t ++ "wrt" ++ v ;
58
+ Integral t a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ;
59
+ IntegralWrt t v a b = "integral" ++ t ++ "from" ++ a ++ "to" ++ b ++ "wrt" ++ v ;
60
+ Optimize d t f = d ++ t ++ "subject" ++ "to" ++ f ;
61
+ Max = "maximize" ;
62
+ Min = "minimize" ;
63
+ Det m = "det" ++ m ;
64
+ Rank m = "rank" ++ m ;
65
+ Inverse m = "inverse" ++ m ;
66
+ Nullspace m = "nullspace" ++ m ;
67
+ Linsolve m v = "linsolve" ++ m ++ v ;
68
+ Product a b = "product" ++ a ++ b ;
69
+ Power m t = "power" ++ m ++ t ;
70
+ Maxflow m a b = "maxflow" ++ m ++ "from" ++ a ++ "to" ++ b ;
71
+ Reduce m = "reduce" ++ m ;
72
+ Sos m = "sos" ++ m ;
73
+ Dot a b = "dot(" ++ a ++ ", " ++ b ++ ")" ;
74
+ Matvec m v = "matvec(" ++ m ++ ", " ++ v ++ ")" ;
75
+ Eq a b = "(" ++ a ++ "=" ++ b ++ ")" ;
76
+ Ne a b = "(" ++ a ++ "!=" ++ b ++ ")" ;
77
+ Lt a b = "(" ++ a ++ "<" ++ b ++ ")" ;
78
+ Le a b = "(" ++ a ++ "<=" ++ b ++ ")" ;
79
+ Gt a b = "(" ++ a ++ ">" ++ b ++ ")" ;
80
+ Ge a b = "(" ++ a ++ ">=" ++ b ++ ")" ;
81
+ Dvd a b = "(" ++ a ++ "|" ++ b ++ ")" ;
82
+ And a b = "(" ++ a ++ "and" ++ b ++ ")" ;
83
+ Or a b = "(" ++ a ++ "or" ++ b ++ ")" ;
84
+ Imp a b = "(" ++ a ++ "=>" ++ b ++ ")" ;
85
+ Iff a b = "(" ++ a ++ "<=>" ++ b ++ ")" ;
86
+ Not a = "not" ++ a ;
87
+ Forall v d f = "(" ++ "forall" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
88
+ Exists v d f = "(" ++ "exists" ++ v ++ "in" ++ d ++ "." ++ f ++ ")" ;
89
+ True = "true" ;
90
+ False = "false" ;
91
+ Add a b = "(" ++ a ++ "+" ++ b ++ ")" ;
92
+ Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ;
93
+ Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ;
94
+ Div a b = "(" ++ a ++ "/" ++ b ++ ")" ;
95
+ Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ;
96
+ Mod a b = "(" ++ a ++ "mod" ++ b ++ ")" ;
97
+ Idiv a b = "(" ++ a ++ "div" ++ b ++ ")" ;
98
+ Neg a = "(" ++ "-" ++ a ++ ")" ;
99
+ Lit s = s.s ;
100
+ V v = v ;
101
+ MkVar s = s.s ;
102
+ R = "R" ;
103
+ Z = "Z" ;
104
+ }
nodes/reader_b/ontology.smt2 ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the math-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 of
4
+ ; this stratum are equalities over numerals, which Z3 decides in milliseconds.
5
+ (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,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "it-01", "lang": "it", "kind": "evaluate", "question": "quanto fa 1/2 + 1/3", "why": "evaluate verb phrase quanto fa; both readers know it, math answers 5/6", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}}
2
+ {"id": "it-02", "lang": "it", "kind": "prove", "question": "dimostra che x^2 + 1 > 0", "why": "prove verb dimostra with the complementiser che", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}}
3
+ {"id": "it-04", "lang": "it", "kind": "solve", "question": "risolvi x^2 - 5*x + 6 = 0 per x", "why": "solve verb risolvi with the for marker per; math answers the two roots", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}}
4
+ {"id": "it-05", "lang": "it", "kind": "det", "question": "il determinante di [[1, 2], [3, 4]]", "why": "noun-first construct pattern; math answers -2", "expect": {"state": "AGREED", "sentence": "det [[1, 2], [3, 4]]", "answer_contains": "-2", "min_assurance": 2, "referee_clean": true}}
5
+ {"id": "it-06", "lang": "it", "kind": "inverse", "question": "la matrice inversa di [[2, 0], [0, 2]]", "why": "inverse verb inversa inside the la matrice ... di frame, whose filler word matrice is a word of the variety because the pattern writes it", "expect": {"state": "AGREED", "sentence": "inverse [[2, 0], [0, 2]]", "min_assurance": 2, "referee_clean": true}}
6
+ {"id": "it-07", "lang": "it", "kind": "maximize", "question": "massimizza 3*x + 4*y sotto i vincoli x + y <= 10", "why": "maximize verb with the subject to variant sotto i vincoli; the math stratum reads the problem and answers that the objective improves without limit", "expect": {"state": "AGREED", "sentence": "maximize 3*x + 4*y subject to x + y <= 10", "min_assurance": 2, "referee_clean": true}}
7
+ {"id": "it-08", "lang": "it", "kind": "integral", "question": "l'integrale di 3*x^2 da 0 a 2", "why": "integral with the from marker da and the to marker a; math answers 8", "expect": {"state": "AGREED", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "min_assurance": 2, "referee_clean": true}}
8
+ {"id": "it-09", "lang": "it", "kind": "negative", "question": "glorifram zepivardo frumeta", "why": "latin gibberish: no announce verb and no known word, the layer must not guess", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
9
+ {"id": "it-10", "lang": "it", "kind": "negative", "question": "dimostra che x e uguale a y", "why": "the connective e for and collides with the equality phrase e uguale a in one gap", "expect": {"max_assurance": 2, "referee_clean": true}}
10
+ {"id": "it-11", "lang": "it", "kind": "negative", "question": "il determinante di [1, 2], [3, 4]", "why": "the det pattern is there but the matrix is not written in double brackets", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
11
+ {"id": "it-12", "lang": "it", "kind": "passthrough", "question": "solve x^2 - 5*x + 6 = 0 for x", "why": "the question is already a sentence of the math language: nothing is translated", "expect": {"state": "PASSTHROUGH", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}}
12
+ {"id": "en-01", "lang": "en", "kind": "evaluate", "question": "what is the value of 7/3 - 7/3 * 3", "why": "evaluate verb phrase what is the value of; math answers 0", "expect": {"state": "AGREED", "sentence": "evaluate 7/3 - 7/3 * 3", "min_assurance": 2, "referee_clean": true}}
13
+ {"id": "en-02", "lang": "en", "kind": "provez", "question": "show that x + x = 2*x over the integers", "why": "provez verb show that with the over Z phrase over the integers", "expect": {"state": "AGREED", "sentence": "prove x + x = 2*x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}}
14
+ {"id": "en-03", "lang": "en", "kind": "solve", "question": "for x solve 2*x + 3 = 11", "why": "fronted for marker: the variable is named before the verb, and both readers must rotate the frame rather than fill the slots by position", "expect": {"state": "AGREED", "sentence": "solve 2*x + 3 = 11 for x", "answer_contains": "{4}", "min_assurance": 2, "referee_clean": true}}
15
+ {"id": "en-04", "lang": "en", "kind": "solvez", "question": "solve n mod 3 = 1 for n over the integers", "why": "solvez frame: the same solve verb plus the integer domain", "expect": {"state": "AGREED", "sentence": "solve n mod 3 = 1 for n over Z", "min_assurance": 2, "referee_clean": true}}
16
+ {"id": "en-05", "lang": "en", "kind": "derivative", "question": "differentiate x^3 + 2*x with respect to x", "why": "derivative verb with the wrt phrase with respect to", "expect": {"state": "AGREED", "sentence": "derivative x^3 + 2*x wrt x", "min_assurance": 2, "referee_clean": true}}
17
+ {"id": "en-06", "lang": "en", "kind": "rank", "question": "what is the rank of [[1, 2, 3], [4, 5, 6]]", "why": "rank noun inside what is the rank of; math answers 2", "expect": {"state": "AGREED", "sentence": "rank [[1, 2, 3], [4, 5, 6]]", "answer_contains": "2", "min_assurance": 2, "referee_clean": true}}
18
+ {"id": "en-07", "lang": "en", "kind": "minimize", "question": "the minimum of 2*x + 3*y subject to x + y = 1", "why": "the minimum of pattern with the subject to marker: a canonical sentence would pass through untranslated, so this one must be read", "expect": {"state": "AGREED", "sentence": "minimize 2*x + 3*y subject to x + y = 1", "min_assurance": 2, "referee_clean": true}}
19
+ {"id": "en-08", "lang": "en", "kind": "integral", "question": "integrate x^2 from 0 to 3 with respect to x", "why": "integral frame with from, to and the wrt phrase; math answers 9", "expect": {"state": "AGREED", "sentence": "integral x^2 from 0 to 3 wrt x", "answer_contains": "9", "min_assurance": 2, "referee_clean": true}}
20
+ {"id": "en-09", "lang": "en", "kind": "negative", "question": "risolvi x^2 - 5*x + 6 = 0 for x", "why": "an Italian solve verb inside an English frame: the English reader must not read it", "expect": {"max_assurance": 2, "referee_clean": true}}
21
+ {"id": "en-10", "lang": "en", "kind": "passthrough", "question": "derivative x^3 wrt x", "why": "a canonical sentence using the wrt joint: pass through with nothing translated", "expect": {"state": "PASSTHROUGH", "sentence": "derivative x^3 wrt x", "min_assurance": 2, "referee_clean": true}}
22
+ {"id": "es-01", "lang": "es", "kind": "evaluate", "question": "cuánto vale 12345679 * 9", "why": "evaluate verb phrase cuanto vale; math answers 111111111", "expect": {"state": "AGREED", "sentence": "evaluate 12345679 * 9", "answer_contains": "111111111", "min_assurance": 2, "referee_clean": true}}
23
+ {"id": "es-02", "lang": "es", "kind": "prove", "question": "demuestra que x^2 + 1 > 0", "why": "prove verb demuestra with the complementiser que", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}}
24
+ {"id": "es-03", "lang": "es", "kind": "solve", "question": "para x resuelve 2*x + 3 = 11", "why": "fronted for marker para: the variable comes before the verb", "expect": {"state": "AGREED", "sentence": "solve 2*x + 3 = 11 for x", "min_assurance": 2, "referee_clean": true}}
25
+ {"id": "es-04", "lang": "es", "kind": "solvez", "question": "resuelve n mod 3 = 1 para n en los números enteros", "why": "solvez with the accented over Z variant", "expect": {"state": "AGREED", "sentence": "solve n mod 3 = 1 for n over Z", "min_assurance": 2, "referee_clean": true}}
26
+ {"id": "es-05", "lang": "es", "kind": "derivative", "question": "la derivada de 3*x^2 con respecto a x", "why": "noun-first derivative pattern with the wrt phrase con respecto a", "expect": {"state": "AGREED", "sentence": "derivative 3*x^2 wrt x", "min_assurance": 2, "referee_clean": true}}
27
+ {"id": "es-06", "lang": "es", "kind": "det", "question": "el determinante de [[3, 1], [2, 4]]", "why": "noun-first construct pattern; math answers 10", "expect": {"state": "AGREED", "sentence": "det [[3, 1], [2, 4]]", "answer_contains": "10", "min_assurance": 2, "referee_clean": true}}
28
+ {"id": "es-07", "lang": "es", "kind": "inverse", "question": "invierte [[1, 2], [3, 4]]", "why": "imperative of the inverse verb in the bare invierte M pattern", "expect": {"state": "AGREED", "sentence": "inverse [[1, 2], [3, 4]]", "min_assurance": 2, "referee_clean": true}}
29
+ {"id": "es-08", "lang": "es", "kind": "minimize", "question": "minimiza 2*x + 3*y sujeto a x + y = 1", "why": "minimize verb with the subject to marker sujeto a", "expect": {"state": "AGREED", "sentence": "minimize 2*x + 3*y subject to x + y = 1", "min_assurance": 2, "referee_clean": true}}
30
+ {"id": "zh-01", "lang": "zh", "kind": "evaluate", "question": "计算 1/2 + 1/3", "why": "evaluate verb in the verb then term pattern", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}}
31
+ {"id": "zh-02", "lang": "zh", "kind": "prove", "question": "证明 x^2 + 1 > 0", "why": "prove verb in the bare prove pattern", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}}
32
+ {"id": "zh-03", "lang": "zh", "kind": "provez", "question": "证明 x + x = 2*x 在整数上", "why": "provez with the over Z marker meaning over the integers", "expect": {"state": "AGREED", "sentence": "prove x + x = 2*x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}}
33
+ {"id": "zh-04", "lang": "zh", "kind": "solve", "question": "对 x 求解 x^2 - 5*x + 6 = 0", "why": "fronted for marker before the solve verb", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}}
34
+ {"id": "zh-05", "lang": "zh", "kind": "derivative", "question": "求 x^3 + 2*x 关于 x 的 导数", "why": "derivative noun with the wrt marker and the noise particle", "expect": {"state": "AGREED", "sentence": "derivative x^3 + 2*x wrt x", "min_assurance": 2, "referee_clean": true}}
35
+ {"id": "zh-06", "lang": "zh", "kind": "integral", "question": "求 3*x^2 从 0 到 2 的 积分", "why": "integral noun with the from and to markers; math answers 8", "expect": {"state": "AGREED", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "min_assurance": 2, "referee_clean": true}}
36
+ {"id": "zh-07", "lang": "zh", "kind": "rank", "question": "求 [[1, 2, 3], [4, 5, 6]] 的 秩", "why": "rank noun in the matrix then particle then rank pattern", "expect": {"state": "AGREED", "sentence": "rank [[1, 2, 3], [4, 5, 6]]", "answer_contains": "2", "min_assurance": 2, "referee_clean": true}}
37
+ {"id": "zh-08", "lang": "zh", "kind": "maximize", "question": "最大化 3*x + 4*y 约束 x + y <= 10", "why": "maximize verb with the short subject to marker; the math stratum answers unbounded", "expect": {"state": "AGREED", "sentence": "maximize 3*x + 4*y subject to x + y <= 10", "min_assurance": 2, "referee_clean": true}}
38
+ {"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}}
39
+ {"id": "zh-10", "lang": "zh", "kind": "negative", "question": "求 从 0 到 2 的 积分", "why": "the integral frame carries the from and to joints but the integrand slot is empty", "expect": {"max_assurance": 0, "no_answer": true, "referee_clean": true}}
40
+ {"id": "hi-01", "lang": "hi", "kind": "evaluate", "question": "गणना करें 1/2 + 1/3", "why": "evaluate verb in the verb first pattern", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}}
41
+ {"id": "hi-02", "lang": "hi", "kind": "prove", "question": "सिद्ध करें x^2 + 1 > 0", "why": "prove verb in the verb first prove pattern", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}}
42
+ {"id": "hi-03", "lang": "hi", "kind": "solve", "question": "x^2 - 5*x + 6 = 0 के लिए x हल करें", "why": "verb final solve order: formula, for marker, variable, verb", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}}
43
+ {"id": "hi-04", "lang": "hi", "kind": "solvez", "question": "हल करें n mod 3 = 1 के लिए n पूर्णांकों में", "why": "solvez with the for marker and the over Z variant", "expect": {"state": "AGREED", "sentence": "solve n mod 3 = 1 for n over Z", "min_assurance": 2, "referee_clean": true}}
44
+ {"id": "hi-05", "lang": "hi", "kind": "derivative", "question": "3*x^2 का x के सापेक्ष अवकलज", "why": "the genitive particle का separates the integrand from the variable without being a joint, so reader A reads the postpositional frame and reader B abstains: one reading only, so the assurance stops at 1 and the answer is still given", "expect": {"state": "SINGLE", "sentence": "derivative 3*x^2 wrt x", "answer_contains": "6*x", "max_assurance": 1, "referee_clean": true}}
45
+ {"id": "hi-06", "lang": "hi", "kind": "det", "question": "[[1, 2], [3, 4]] का सारणिक", "why": "det noun in the matrix then particle then rank pattern", "expect": {"state": "AGREED", "sentence": "det [[1, 2], [3, 4]]", "answer_contains": "-2", "min_assurance": 2, "referee_clean": true}}
46
+ {"id": "hi-07", "lang": "hi", "kind": "inverse", "question": "व्युत्क्रम बताइए [[2, 0], [0, 2]]", "why": "inverse noun with the tell me pattern", "expect": {"state": "AGREED", "sentence": "inverse [[2, 0], [0, 2]]", "min_assurance": 2, "referee_clean": true}}
47
+ {"id": "hi-08", "lang": "hi", "kind": "minimize", "question": "न्यूनतम करें 2*x + 3*y के अधीन x + y = 1", "why": "minimize verb with the subject to marker meaning subject to", "expect": {"state": "AGREED", "sentence": "minimize 2*x + 3*y subject to x + y = 1", "min_assurance": 2, "referee_clean": true}}
48
+ {"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}}
49
+ {"id": "hi-10", "lang": "hi", "kind": "integral", "question": "समाकलन करें 3*x^2 का 0 से 2 तक", "why": "postpositional from and to markers with the genitive particle: reader A knows this order, reader B abstains, so only one reading stands and the assurance stops at 1", "expect": {"state": "SINGLE", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "max_assurance": 1, "referee_clean": true}}
50
+ {"id": "ar-01", "lang": "ar", "kind": "evaluate", "question": "احسب قيمة 1/2 + 1/3", "why": "evaluate verb in the compute the value of pattern", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}}
51
+ {"id": "ar-02", "lang": "ar", "kind": "prove", "question": "أثبت أن x^2 + 1 > 0", "why": "prove verb with the that complementiser", "expect": {"state": "AGREED", "sentence": "prove x^2 + 1 > 0", "min_assurance": 2, "referee_clean": true}}
52
+ {"id": "ar-03", "lang": "ar", "kind": "provez", "question": "أثبت x + x = 2*x على أعداد صحيحة", "why": "provez with the over Z variant meaning over the integers", "expect": {"state": "AGREED", "sentence": "prove x + x = 2*x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}}
53
+ {"id": "ar-04", "lang": "ar", "kind": "solve", "question": "حل x^2 - 5*x + 6 = 0 إيجاد x", "why": "solve verb with the for marker: the same word also names the find verb, which is why the readers must agree here", "expect": {"state": "AGREED", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}}
54
+ {"id": "ar-05", "lang": "ar", "kind": "integral", "question": "تكامل 3*x^2 من 0 إلى 2", "why": "integral noun with the from and to markers; math answers 8", "expect": {"state": "AGREED", "sentence": "integral 3*x^2 from 0 to 2", "answer_contains": "8", "min_assurance": 2, "referee_clean": true}}
55
+ {"id": "ar-06", "lang": "ar", "kind": "rank", "question": "رتبة [[1, 2, 3], [4, 5, 6]]", "why": "rank noun in the bare construct pattern", "expect": {"state": "AGREED", "sentence": "rank [[1, 2, 3], [4, 5, 6]]", "answer_contains": "2", "min_assurance": 2, "referee_clean": true}}
56
+ {"id": "ar-07", "lang": "ar", "kind": "inverse", "question": "معاكسة [[1, 2], [3, 4]]", "why": "inverse noun in the bare construct pattern", "expect": {"state": "AGREED", "sentence": "inverse [[1, 2], [3, 4]]", "min_assurance": 2, "referee_clean": true}}
57
+ {"id": "ar-08", "lang": "ar", "kind": "maximize", "question": "عظم 3*x + 4*y شرط x + y <= 10", "why": "maximize verb with the short subject to marker; the math stratum answers unbounded", "expect": {"state": "AGREED", "sentence": "maximize 3*x + 4*y subject to x + y <= 10", "min_assurance": 2, "referee_clean": true}}
58
+ {"id": "ar-09", "lang": "ar", "kind": "negative", "question": "شقطبي ملموغ قلفوص", "why": "arabic gibberish: no announce verb and no known word", "expect": {"state": "NOT COVERED", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
59
+ {"id": "ar-10", "lang": "ar", "kind": "negative", "question": "احسب قيمة xrqt3 + 1/3", "why": "valid evaluate pattern but a latin gibberish symbol inside the math slot: the math layer refuses, so no answer", "expect": {"max_assurance": 0, "no_answer": true, "referee_clean": true}}
60
+ {"id": "ar-11", "lang": "ar", "kind": "evaluate", "question": "احسب ١/٢ + ١/٣", "why": "Arabic-Indic digits as the Arabic lexicon itself writes them: segment normalises them to ASCII, so this is the same problem as ar-01", "expect": {"state": "AGREED", "sentence": "evaluate 1/2 + 1/3", "answer_contains": "5/6", "min_assurance": 2, "referee_clean": true}}
61
+ {"id": "mixed-01", "lang": "en", "kind": "negative", "question": "solve 25 + x = 30 for x", "why": "full width digits inside a math sentence: normalisation turns them into ASCII, so the sentence is accepted", "expect": {"max_assurance": 2, "referee_clean": true}}
62
+ {"id": "mixed-02", "lang": "hi", "kind": "negative", "question": "solve x^2 - 5*x + 6 = 0 for x", "why": "an English math sentence asked in Hindi: it passes through without any Hindi word", "expect": {"state": "PASSTHROUGH", "sentence": "solve x^2 - 5*x + 6 = 0 for x", "answer_contains": "{2, 3}", "min_assurance": 2, "referee_clean": true}}
63
+ {"id": "mixed-03", "lang": "ar", "kind": "negative", "question": "حل x^2 - 5*x + 6 = 0 per x", "why": "an Italian for marker inside an Arabic solve frame: the joint is not Arabic, so the variable slot stays empty", "expect": {"max_assurance": 0, "no_answer": true, "referee_clean": true}}
64
+ {"id": "mixed-04", "lang": "zh", "kind": "negative", "question": "计算 1/2 + 1/3 hello world", "why": "a cjk evaluate frame followed by latin noise: the trailing words are not part of any pattern", "expect": {"max_assurance": 2, "referee_clean": true}}
65
+ {"id": "mixed-05", "lang": "es", "kind": "negative", "question": "demuestra que x^2 + 1 > 0حل", "why": "an Arabic verb glued to the end of a Spanish sentence with no space: no reader may invent a boundary", "expect": {"max_assurance": 2, "referee_clean": true}}
66
+ {"id": "it-03", "lang": "it", "kind": "provez", "question": "dimostra che 2*x = x + x sugli interi", "why": "provez frame: the over Z marker sugli interi selects the integer domain", "expect": {"state": "AGREED", "sentence": "prove 2*x = x + x over Z", "answer_contains": "proved", "min_assurance": 2, "referee_clean": true}}
67
+ {"id": "ar-12", "lang": "ar", "kind": "provez", "question": "أثبت n^2 + n = n*(n + 1) على أعداد صحيحة", "why": "agreed reading, refused by the math stratum: powers over the integers are outside its formalizer", "expect": {"state": "AGREED", "sentence": "prove n^2 + n = n*(n + 1) over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
68
+ {"id": "en-11", "lang": "en", "kind": "provez", "question": "show that x^2 - 1 = (x + 1)*(x - 1) over the integers", "why": "agreed reading, refused by the math stratum: powers over the integers are outside its formalizer, so the stratum withholds the verdict", "expect": {"state": "AGREED", "sentence": "prove x^2 - 1 = (x + 1)*(x - 1) over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
69
+ {"id": "en-12", "lang": "en", "kind": "minimize", "question": "the minimum of x^2 + y^2 subject to x + y = 1", "why": "agreed reading of a nonlinear objective: the math stratum says the problem is not linear, so the stratum lowers the assurance to match", "expect": {"state": "AGREED", "sentence": "minimize x^2 + y^2 subject to x + y = 1", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
70
+ {"id": "es-09", "lang": "es", "kind": "minimize", "question": "minimiza x^2 + y^2 sujeto a x + y = 1", "why": "agreed reading, nonlinear objective: the math stratum abstains and the stratum shows nothing", "expect": {"state": "AGREED", "sentence": "minimize x^2 + y^2 subject to x + y = 1", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
71
+ {"id": "hi-11", "lang": "hi", "kind": "minimize", "question": "न्यूनतम करें x^2 + y^2 के अधीन x + y = 1", "why": "agreed reading, nonlinear objective: the math stratum abstains and the stratum shows nothing", "expect": {"state": "AGREED", "sentence": "minimize x^2 + y^2 subject to x + y = 1", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
72
+ {"id": "it-13", "lang": "it", "kind": "provez", "question": "dimostra che x^2 + 2*x + 1 = (x + 1)^2 sugli interi", "why": "the reading is agreed by both readers, but the math stratum refuses powers over the integers, so the stratum shows no assurance and no answer: the reading ceiling is never what lifts the verdict", "expect": {"state": "AGREED", "sentence": "prove x^2 + 2*x + 1 = (x + 1)^2 over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}}
73
+ {"id": "zh-11", "lang": "zh", "kind": "provez", "question": "证明 n^2 + n = n*(n + 1) 在整数上", "why": "agreed reading, refused by the math stratum: powers over the integers are outside its formalizer", "expect": {"state": "AGREED", "sentence": "prove n^2 + n = n*(n + 1) over Z", "max_assurance": 0, "no_answer": true, "referee_clean": true}}