tailot commited on
Commit
bbfee07
·
verified ·
1 Parent(s): 81c6f7a

add geometry-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 +434 -0
  3. agents/stratum_agent +39 -0
  4. lexicon/ar.json +275 -0
  5. lexicon/en.json +229 -0
  6. lexicon/es.json +224 -0
  7. lexicon/hi.json +281 -0
  8. lexicon/it.json +245 -0
  9. lexicon/zh.json +159 -0
  10. lggeostratum/__init__.py +20 -0
  11. lggeostratum/agents.py +364 -0
  12. lggeostratum/canonical.py +662 -0
  13. lggeostratum/compare.py +313 -0
  14. lggeostratum/corpus.py +84 -0
  15. lggeostratum/coverage.py +93 -0
  16. lggeostratum/decide.py +166 -0
  17. lggeostratum/faults.py +188 -0
  18. lggeostratum/invoker.py +103 -0
  19. lggeostratum/lexicon.py +462 -0
  20. lggeostratum/pipeline.py +116 -0
  21. lggeostratum/protocol.py +79 -0
  22. lggeostratum/read_a.py +402 -0
  23. lggeostratum/read_b.py +338 -0
  24. lggeostratum/render.py +140 -0
  25. lggeostratum/segment.py +240 -0
  26. nodes/adversary/grammar.gf +76 -0
  27. nodes/adversary/ontology.smt2 +6 -0
  28. nodes/adversary/seed_payload.json +18 -0
  29. nodes/arbiter/grammar.gf +76 -0
  30. nodes/arbiter/ontology.smt2 +6 -0
  31. nodes/arbiter/seed_payload.json +18 -0
  32. nodes/boundary/grammar.gf +76 -0
  33. nodes/boundary/ontology.smt2 +6 -0
  34. nodes/boundary/seed_payload.json +18 -0
  35. nodes/coverage/grammar.gf +76 -0
  36. nodes/coverage/ontology.smt2 +6 -0
  37. nodes/coverage/seed_payload.json +18 -0
  38. nodes/equivalence/grammar.gf +76 -0
  39. nodes/equivalence/ontology.smt2 +6 -0
  40. nodes/equivalence/seed_payload.json +18 -0
  41. nodes/invoker/grammar.gf +76 -0
  42. nodes/invoker/ontology.smt2 +6 -0
  43. nodes/invoker/seed_payload.json +18 -0
  44. nodes/reader_a/grammar.gf +76 -0
  45. nodes/reader_a/ontology.smt2 +6 -0
  46. nodes/reader_a/seed_payload.json +18 -0
  47. nodes/reader_b/grammar.gf +76 -0
  48. nodes/reader_b/ontology.smt2 +6 -0
  49. nodes/reader_b/seed_payload.json +18 -0
  50. problems/corpus.jsonl +56 -0
.gitignore ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ __pycache__/
2
+ *.py[cod]
3
+ .pytest_cache/
README.md ADDED
@@ -0,0 +1,434 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ language:
3
+ - it
4
+ - en
5
+ - es
6
+ - zh
7
+ - hi
8
+ - ar
9
+ tags:
10
+ - multilingual
11
+ - geometry
12
+ - theorem-proving
13
+ - natural-language-to-formal-language
14
+ - multi-agent-systems
15
+ - benchmark
16
+ - conversational-interfaces
17
+ - formal-verification
18
+ - semantic-parsing
19
+ pretty_name: "LingoLOGOS geometry-stratum: a question in six written varieties, the answer of the geometry layer, and an assurance that includes the reading"
20
+ configs:
21
+ - config_name: corpus
22
+ data_files:
23
+ - split: train
24
+ path: problems/corpus.jsonl
25
+ size_categories:
26
+ - n<1K
27
+ ---
28
+
29
+ # LingoLOGOS geometry-stratum topology
30
+
31
+ A conversational layer over the `geometry` topology: a person draws a figure in words and asks about it
32
+ in one of six written varieties, and gets the verdict of the geometry layer back in that same language,
33
+ at an assurance that includes the fallibility of the reading. The layer never decides a figure and never
34
+ raises a verdict; the only direction it can move the assurance of the geometry layer is down.
35
+
36
+ ```
37
+ python tools/ask.py --lang zh "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。证明 A, B 和 C 共线。"
38
+ Reading state : AGREED
39
+ Assurance shown : 2 (reading ceiling 2, geometry assurance 3)
40
+ Geometry layer status : VERIFIED
41
+ Orchestrator Z3 check : 8 of 8 envelopes confirmed
42
+
43
+ Answer in the language of the question (中文):
44
+ 状态: 一致:两位独立读者加上 SMT 约束
45
+ 这种变体理解的问题 (problem): Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear.
46
+ 答案: the claim holds: A, B and C are collinear
47
+ 三级中的第 2 级
48
+ 几何层: VERIFIED
49
+ 几何层的 SMT 检查:8 个信封中有 8 个得到确认
50
+ ```
51
+
52
+ The answer line is the geometry layer's own sentence, carried unchanged: restating it would break the
53
+ echo the boundary node checks. A person who asked in Chinese reads the labels in Chinese and the verdict
54
+ in the language the formal layer writes.
55
+
56
+ This dataset is the `geometry-stratum/` folder of the LingoLOGOS project published as it stands: 68 files,
57
+ code and data together, plus this card in place of their README. Only the standard library and
58
+ `z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every
59
+ command below is written from inside the folder. The geometry layer is not part of this dataset: it
60
+ lives in the `geometry` bundle, published at
61
+ https://huggingface.co/datasets/tailot/lingologos-geometry, and section 10 says how to point this
62
+ folder at a copy of it.
63
+
64
+ ## 1. What the stratum is, and what it refuses
65
+
66
+ The certainty of a translation cannot be verified the way the certainty of a proof can: there is no SMT
67
+ check that says that a sentence of Hindi was read correctly. That is the definition this bundle works
68
+ with, and it is why the topology is built the way it is: two readers that reach their sentence by
69
+ different roads, an SMT claim about what each reading kept, a referee that rechecks every envelope, and a
70
+ decision that is re-derived from the transcript instead of being trusted from the arbiter.
71
+
72
+ The rule the whole bundle exists to enforce:
73
+
74
+ ```
75
+ assurance shown = min(assurance of the geometry layer, ceiling of the reading)
76
+ ```
77
+
78
+ | Reading state | ceiling | when |
79
+ |---|---|---|
80
+ | `AGREED` | 2 | both readers produced the same figure, and the geometry layer is what decides it |
81
+ | `PASSTHROUGH` | 2 | the question was already a text of the geometry language: nothing was translated |
82
+ | `SINGLE` | 1 | one reader understood it and the other abstained: no witness, one level less |
83
+ | `DISPUTED` | 0 | the two readers produced different sentences, or a reading lost a number: the geometry layer is not even asked |
84
+ | `AMBIGUOUS` | 0 | a reader reports that the question announces more than one figure, or leaves a slot with several readings: the person has to choose |
85
+ | `NOT COVERED` | 0 | neither reader found anything: this variety does not say it in a covered way |
86
+ | `TAMPERED` | 0 | the geometry layer says it solved something other than the agreed sentence |
87
+
88
+ Three is never shown. Level three belongs to the geometry layer, whose parser, kernel and critics work on
89
+ a text they were built for; a sentence in a human language adds one fallible step before that, and this
90
+ layer is that step.
91
+
92
+ The ceiling is not the only thing that holds on its own. The count of literals is checked on a lone
93
+ reading too, and in a figure that weighs more than it does in an equation: the coordinates are the
94
+ problem, so a reading that no longer holds the numbers the person wrote is a different figure and not a
95
+ weaker reading of the same one, and it ends `DISPUTED` even when it is the only reader that understood
96
+ the question. A single witness therefore answers at level one only when it kept every number.
97
+
98
+ ## 2. The eight nodes
99
+
100
+ The session runs through the orchestrator (`src/lingologos_orchestrator`) with the same envelope protocol
101
+ as the `geometry` topology: a marker `@@DOSSIER@@` inside `payload.naturalLanguage`, and
102
+ `payload.smtConstraints` carrying what each node claims about its own output, which the referee of every
103
+ node recomputes with Z3. The seed sits in the `arbiter`; `maxTurns` is the number of arcs.
104
+
105
+ | Node | What it does | The claim it carries |
106
+ |---|---|---|
107
+ | `reader_a` | reads the question against the frames written in the lexicon | the numerals of the question are still in my sentence |
108
+ | `reader_b` | reads it by following the joints of the geometry language (`through`, `with center ... and`, `of the triangle ... and`, `perpendicular to`, the postpositions) | the same, independently |
109
+ | `equivalence` | proves the two sentences the same: the numbers first, then the slots with SMT | `not (A = B)` is unsatisfiable |
110
+ | `coverage` | counts that every literal the person wrote survived into the sentence | conjunction of the element equalities |
111
+ | `invoker` | asks the geometry layer, in a separate process, the agreed figure | the sentence I sent equals the one that came back |
112
+ | `boundary` | checks the echo of the geometry layer instead of trusting it | elementwise on the echo, or the empty claim |
113
+ | `adversary` | re-derives the bound and writes its negation | `shown > ceiling` is unsatisfiable |
114
+ | `arbiter` | runs the decision and renders the answer in the language of the question | the same inequality |
115
+
116
+ The echo here is the geometry bundle's own record: the runner hands back the text that bundle parsed,
117
+ next to its verdict, and the boundary node compares that text with the sentence the readers agreed on,
118
+ atom by atom. A figure that comes back different is `TAMPERED`, however strong the verdict on it looks.
119
+
120
+ ## 3. Two readers, one lexicon
121
+
122
+ `read_a.py` matches the shapes stored in `lexicon/<lang>.json` (`patterns`: one template per kind of
123
+ statement, with slots). `read_b.py` never looks at those shapes: it finds the verb that announces a
124
+ statement, then walks the joints of the geometry language and cuts the slots out of the gaps between them,
125
+ in whatever order the variety puts them. They share only the lexicon, the atomizer (`segment.py`) and the
126
+ templates of the geometry language (`canonical.py`).
127
+
128
+ How much of the 19 statement kinds each variety describes, and with how much material:
129
+
130
+ | Variety | Kinds | Patterns | Verb phrases | Connectives | Markers | Noise words |
131
+ |---|---|---|---|---|---|---|
132
+ | `en` | 19 | 33 | 14 | 3 | 43 | 53 |
133
+ | `it` | 18 | 42 | 23 | 4 | 46 | 72 |
134
+ | `es` | 19 | 27 | 16 | 3 | 43 | 64 |
135
+ | `zh` | 13 | 18 | 9 | 4 | 21 | 20 |
136
+ | `hi` | 11 | 18 | 11 | 3 | 23 | 33 |
137
+ | `ar` | 11 | 13 | 10 | 3 | 30 | 31 |
138
+
139
+ A question in this corpus is a whole figure: the points, the lines and the circle defined first, then the
140
+ claim about them, in one text -- and the geometry language requires the definitions before the claim that
141
+ uses them. `agents.py` therefore splits the question at the sentence markers (the full stop, `。`, the
142
+ danda), reads every part with the reader in question, and re-assembles the parts into one text of the
143
+ geometry language in the order the bundle expects. The compound reading carries `compound: true` and the
144
+ list of its parts, and it stands at the worst status of its parts. Its literals are re-read from the
145
+ question itself (`compare.sorted_numbers`) rather than trusted from the reading.
146
+
147
+ Every stored shape has to name the verb of its own kind, and `tests/test_lexicon.py` checks it for all
148
+ six varieties. That is a deliberate cost: it means a pattern can never open on a bare noun phrase, and so
149
+ the verbless nominal phrasing of a figure -- `the point A, coordinates (0, 0)` -- is not read and ends
150
+ `no_verb`. The Italian shapes carry no copula, because the atomizer folds the accented `è` of
151
+ `è perpendicolare` into a space; a person who writes that copula plain is read the same way, which is
152
+ why a missing accent costs nothing here while it costs a reading in the arithmetic stratum of the same
153
+ project.
154
+
155
+ That sharing of one lexicon is deliberate and it is also the known blind spot: a wrong description of a
156
+ variety is a wrong description for both readers, and the topology cannot see it. What shows it is the
157
+ corpus of section 5, whose questions were written and checked by a person. When the two readers disagree
158
+ the assurance goes down, never up: `DISPUTED` does not even consult the geometry layer.
159
+
160
+ ## 4. Talking to the geometry layer
161
+
162
+ `invoker.py` is the only door, and it is a subprocess and a set of environment variables. It launches
163
+ `python tools/geometry_runner.py --json <figure>` -- a script of this folder -- and reads its JSON verdict
164
+ back; nothing in this folder imports the geometry bundle to decide anything here. That runner is the only
165
+ place in the bundle where `geometry` is loaded: it finds the bundle in the sibling folder
166
+ `datasets/geometry`, or in the copy named by `LGSTRATUM_GEOMETRY_ROOT`, starts the seven agent session of
167
+ that bundle, maps the session's verdict onto the small shape this layer copies, and re-runs the SMT claim
168
+ of every envelope that session wrote with the bundle's own solver, so that a verdict reported here is
169
+ checked against the same query the session believed it had discharged.
170
+
171
+ | Variable | Meaning |
172
+ |---|---|
173
+ | `LGSTRATUM_GEOMETRY_ROOT` | where the `geometry` bundle is (default: the sibling folder `datasets/geometry`) |
174
+ | `LGSTRATUM_GEOMETRY_BACKEND` | `subprocess` (default), or `none` to disable the geometry layer entirely |
175
+ | `LGSTRATUM_GEOMETRY_TIMEOUT` | seconds that session may take (default 180) |
176
+ | `LGSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only |
177
+
178
+ The assurance the runner reports, read off the evidence the bundle itself recorded:
179
+
180
+ ```
181
+ 3 VERIFIED every obligation of the problem discharged, each by at least two engines of the
182
+ bundle that work differently -- the real closed field solver and the Groebner or
183
+ Wu-Ritts elimination -- over hypotheses the solver witnessed as realizable; for a
184
+ computed answer, the certificate of the kernel result came out as expected and its
185
+ non vacuity was witnessed
186
+ 2 SINGLE_PROVER the bundle certified the problem but only one engine confirmed each obligation; a
187
+ refutation with a witnessed counterexample stands here too, because it is decisive
188
+ even though only the solver produced it
189
+ 0 anything else the bundle refused the text, objected to the model, or stopped without discharging
190
+ the obligation; a zero is reported as it is, and this layer then shows no answer
191
+ ```
192
+
193
+ A disabled geometry layer is not tampering: the reading stands, the assurance falls to zero because there
194
+ is no geometry assurance to take the minimum with, and no answer is shown.
195
+
196
+ ## 5. The corpus
197
+
198
+ `problems/corpus.jsonl` holds 56 questions: 19 kinds of statement in 6 written varieties (English 20 rows,
199
+ Italian 12, Spanish, Chinese, Hindi and Arabic 6 each), 6 questions that must not be read -- an area, an
200
+ inscribed rectangle, a bisector: objects the geometry language of the bundle does not name -- and one
201
+ question already written in that language. Each line carries what the answer has to look like (`state`,
202
+ `sentence`, `answer_contains`, `min_assurance`, `max_assurance`, `no_answer`, `referee_clean`) and a `why`
203
+ that says why, including the cases where the expected outcome is an abstention.
204
+
205
+ Graded against the in-process pipeline: **56 of 56** rows agree with their gold (`lggeostratum/corpus.py`
206
+ grades one row, `tests/test_corpus.py` runs all of them). The states come out 46 `AGREED`, 3 `SINGLE`, 1
207
+ `PASSTHROUGH` and 6 `NOT COVERED`; `tools/coverage_report.py` writes `results/coverage.json` and counts
208
+ **46** questions read by both readers, **3** by `reader_a` alone and **6** by neither -- the
209
+ `PASSTHROUGH` row was never read at all, because there was nothing to translate. Eleven rows (`point-en`,
210
+ `line-en`, `circle-en`, `circle-it`, `assume-en`, `centroid-en`, `centroid-it`, `circumcentre-en`,
211
+ `intersect-en`, `image-en`, `mid-en-def`) are agreed readings on which the geometry layer abstains: a
212
+ figure of definitions with no claim in it, or a `find the image` with no transformation named. The
213
+ assurance is 0 and no answer appears, which is the layer refusing to add an availability it does not
214
+ have. Three rows (`mid-zh-single`, `mid-hi-single`, `findintersect-es`) stay at `SINGLE`, assurance 1, for
215
+ the reason in section 7.
216
+
217
+ ## 6. Commands
218
+
219
+ ```
220
+ python tools/ask.py --lang zh "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。证明 A, B 和 C 共线。"
221
+ python tools/ask.py --lang it --json "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."
222
+ python tools/ask.py --lang ar --corpus problems/corpus.jsonl --limit 6
223
+ python tools/coverage_report.py --out results/coverage.json # which frames each variety carries
224
+ python tools/ablation.py --probe 6 --out results/ablation.json
225
+ ```
226
+
227
+ The first line is one session through the orchestrator, eight processes; the second is the same shape
228
+ with a question that needs no translation, and ends `PASSTHROUGH`.
229
+
230
+ `tools/ask.py` prints the verdict it re-derives from the transcript, not the one the arbiter wrote, and
231
+ exits with code 3 when that re-derivation disagrees with a node about its own envelope, with code 2 when
232
+ the assurance is zero, and with code 1 in corpus mode when a gold expectation fails.
233
+ `tools/ablation.py` walks the configurations of the topology one node at a time, injects every fault of
234
+ the catalogue singly and in pairs, and reports each cell as
235
+ `raised | lowered | masked | caught | abstained | silent_error`: a cell counted `raised` is a violation of
236
+ the rule of section 1, and the tool exits 1 if any happened. A `caught` cell is one where an answer was
237
+ shown that the gold does not accept, but the session said so itself -- a claim fell to the referee of its
238
+ node, or the assurance sits below the honest one because the configuration lost a node.
239
+
240
+ On this checkout `--probe 6` (one question per variety) fills **147 cells** and **882 sessions**, the fault
241
+ takes hold in **720** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 1`, `caught 32`,
242
+ `abstained 561`, `masked 126` -- under four minutes. Nothing was ever raised above the honest assurance.
243
+ The 32 `caught` cells all sit in the two configurations that are missing one reader, where a rubber
244
+ stamped node cannot buy back the level that the missing witness costs. The shape of the columns differs
245
+ from the arithmetic stratum of the same project: in a figure a damaged reading almost never survives as
246
+ a weaker answer, because what the readers produce has to stay a parseable problem with every coordinate
247
+ kept, so 561 cells end with no answer at all rather than a lower one. The one `silent_error` is the blind
248
+ spot of section 3 shown in numbers: with `merge_slots` fired in both readers at once, the Spanish
249
+ congruence row turns into `segment A-B is congruent to segment A-B` -- both readers merged the same pair
250
+ of names, so the two readings agree, the claim is trivially provable, the bundle certifies it, and the
251
+ session answers at level 2 about a question nobody asked. The only witness against it is the person.
252
+
253
+ ## 7. Limits that are written down, not hidden
254
+
255
+ * Three rows are cut by `reader_a` alone, because one clause of the figure puts its joint after the names
256
+ instead of between them: `设 M 平分 线段 A B` in Chinese, `मान लें M, A और B का मध्यबिंदु है` in Hindi,
257
+ where the postposition closes the clause, and `Halle el punto en comun de la recta r y la recta s` in
258
+ Spanish, where both line names follow the words for the common point. `reader_b` cannot cut the slots
259
+ there, so those rows stay at `SINGLE`, assurance 1 (`mid-zh-single`, `mid-hi-single`,
260
+ `findintersect-es`), and `tools/coverage_report.py` shows them as read by one of two readers.
261
+ * `lexicon/it.json` describes 18 of the 19 kinds: the image of a figure under a named transformation has
262
+ no Italian surface here, and Chinese, Hindi and Arabic stop at 13, 11 and 11 kinds. What a variety
263
+ does not describe ends `NOT COVERED` with assurance 0: the stratum says it did not read it, and does
264
+ not guess.
265
+ * The verbless nominal phrasing of a figure is not read in any variety, because every stored shape has to
266
+ name the verb of its own kind (section 3). A person who writes `the point A, coordinates (0, 0)` is
267
+ asked to say it as a definition.
268
+ * The fragment of the geometry bundle is unchanged here: a figure with definitions and no claim, or a
269
+ `find the image` with no transformation named, ends `INCONCLUSIVE` in that bundle and assurance 0 here,
270
+ even when the reading is agreed. The corpus keeps those eleven rows as probes of the ceiling.
271
+ * The two readers share their data, so a systematic error in the description of a variety is invisible to
272
+ the topology and can only be found in the corpus. Section 6 counts the one case the ablation managed to
273
+ produce, and it is an answer, not a refusal.
274
+ * `equivalence` never spends a solver call on two readings whose numbers differ: it compares the
275
+ multisets of literals, says `numbers`, and stops (section 1). A veto, not a heuristic: the equivalence
276
+ claim of that node is then a failed claim, and it is still rechecked by its referee.
277
+
278
+ ## 8. Tests
279
+
280
+ From the repository root:
281
+
282
+ ```
283
+ python -m pytest -q datasets/geometry-stratum/tests
284
+ ```
285
+
286
+ The suite is **255** tests: 103 on the two readers against every row of the corpus, 62 on the corpus
287
+ itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 13 on the decision table,
288
+ 10 on the lexicons and 2 end-to-end sessions. It checks the topology file against the node order, the
289
+ shape and the completeness of the lexicons -- including that every pattern of every variety is announced
290
+ by a verb of its own kind, and that the six sets of reason sentences ask for the same fillers -- both
291
+ readers against the corpus, the decision table, the faults, and every gold answer of the corpus;
292
+ `tests/test_pinned_invariant.py` runs the same questions through every node configuration and every fault
293
+ and asserts that the verdict of the geometry layer does not move, and that nothing is ever shown above
294
+ it. `tests/test_orchestrator_e2e.py` runs two real sessions through the orchestrator, one honest and one
295
+ in which the arbiter is forced to raise its own assurance -- which the referee of that node undoes, and
296
+ which the tool reports -- and the test is skipped when `lingologos_orchestrator` is not importable. The
297
+ corpus and the invariant tests call the solver of the geometry layer as subprocesses, which here means a copy of the
298
+ `geometry` dataset named by `LGSTRATUM_GEOMETRY_ROOT` (section 10); the suite took 57 seconds inside a
299
+ LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is
300
+ not importable.
301
+
302
+ Real sessions, measured: the Chinese session at the top of this file comes back `AGREED` at assurance 2
303
+ against a geometry assurance of 3, with **8 of 8** envelope claims confirmed by the referee of the
304
+ session. The Italian perpendicularity row (`perp-it-true`: four points, then a claim about two lines)
305
+ comes back the same way -- `AGREED`, assurance 2, the geometry layer `VERIFIED`, 8 of 8 claims confirmed,
306
+ nothing detected.
307
+
308
+ A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that
309
+ inside the library only `lggeostratum/compare.py` may import the `geometry` package, and only for the SMT
310
+ plumbing of its own equivalence claim; the modules that decide, route and invoke hold no reference to it,
311
+ and the session is reached as a separate process.
312
+
313
+ ## 9. Language policy
314
+
315
+ The prose of this folder -- code, docstrings, comments, tool output, test messages -- is English, and the
316
+ Python sources are ASCII, as the repository requires. The exception is the language under study, and it is
317
+ confined to data: `lexicon/*.json` (the words, frames, joints and labels of the six varieties),
318
+ `problems/corpus.jsonl` (the questions and their gold answers), and the answer block that `tools/ask.py`
319
+ shows a person, which is written in the language of the question because that block is the object this
320
+ bundle measures.
321
+
322
+ ## 10. Putting this dataset back into a LingoLOGOS checkout
323
+
324
+ This dataset is 68 files plus this card: 56 questions in one corpus file, the six lexicons, the eight
325
+ node definitions, the two readers, the decision rule of section 1, the corpus grading and fault
326
+ results under `results/`, and the fault catalogue of section 6. To decide a figure it needs the
327
+ `geometry` bundle: download https://huggingface.co/datasets/tailot/lingologos-geometry somewhere, set
328
+ `LGSTRATUM_GEOMETRY_ROOT` to that copy, and the `invoker` node of this folder starts
329
+ `tools/geometry_runner.py`, which loads that copy in a separate process -- the only door through which
330
+ this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at
331
+ `datasets/geometry-stratum`, finds `datasets/geometry` by itself, and needs
332
+ `src/lingologos_orchestrator` importable for the two end to end sessions of section 8. On the hub this
333
+ README is rewritten as a dataset card whose sections 1 to 10 keep the wording and numbers of this file,
334
+ and sections 11 to 14 are added there for readers who met the bundle on the hub rather than in a
335
+ checkout: the fields of the corpus file, how to load it, rights and citation. Every file of this folder is
336
+ compared by sha256 after the upload, the card that replaces this README among them: the hub holds one
337
+ object per file of this folder plus `.gitattributes`, so the remote count is one above the number
338
+ `tools/publish_dataset.py` prints here.
339
+ What the LingoLOGOS repository carries is the link to this
340
+ dataset in the table of published resources at the top of its README; the documentation of the asset
341
+ lives here, in this card, and not in the technical documentation of the project. Republishing is a
342
+ separate step, never a side effect of a test run: `tools/publish_dataset.py` in the folder of the
343
+ project does it with the token taken from an environment variable and verifies the tree by sha256.
344
+
345
+ ## 11. The corpus file
346
+
347
+ `problems/corpus.jsonl` holds 56 questions, one JSON object per line, written and checked by a person.
348
+ It is a benchmark for the stratum: there is no prompt, no response pair and nothing to fine tune on.
349
+ Each row says what the session has to end like, including the rows whose expected outcome is a refusal
350
+ to answer, and a `why` that says why.
351
+
352
+ | Field | Type | Meaning |
353
+ |---|---|---|
354
+ | `id` | string | unique; `<what the row tests>-<variety>`, sometimes with a third part (`-true`, `-false`, `-single`, `-unknown`, `-def`) |
355
+ | `lang` | string | one of `it`, `en`, `es`, `zh`, `hi`, `ar`: the variety the question is written in |
356
+ | `kind` | string | one of the 19 statement kinds of the geometry language, or `negative` (6 rows that must not be read) |
357
+ | `question` | string | the question, between 18 and 306 characters, in the script of its variety: a whole figure, the definitions first and the claim about them last |
358
+ | `why` | string | the reason the row behaves as it does, written by the person who wrote the row |
359
+ | `expect` | object | the expectation, described below |
360
+
361
+ | Variety (`lang`) | `en` | `it` | `es` | `zh` | `hi` | `ar` |
362
+ |---|---|---|---|---|---|---|
363
+ | Rows | 20 | 12 | 6 | 6 | 6 | 6 |
364
+
365
+ | Kind | Rows | Kind | Rows | Kind | Rows |
366
+ |---|---|---|---|---|---|
367
+ | `collinear` | 13 | `find_circumcircle` | 3 | `between` | 1 |
368
+ | `perp` | 6 | `find_intersect` | 3 | `assume` | 1 |
369
+ | `negative` | 6 | `centroid` | 2 | `mid` | 1 |
370
+ | `par` | 4 | `define_circle` | 2 | `intersect` | 1 |
371
+ | `find_tangents` | 4 | `oncircle` | 2 | `define_line` | 1 |
372
+ | `right` | 2 | `circumcentre` | 1 | `cong` | 1 |
373
+ | | | `find_image` | 1 | `define_point` | 1 |
374
+
375
+ The fields of `expect` are optional except `state` and `referee_clean`, which are present on every row.
376
+
377
+ | Field | Rows | Meaning |
378
+ |---|---|---|
379
+ | `state` | 56 | the reading state the session must end in: `AGREED` 46, `SINGLE` 3, `PASSTHROUGH` 1, `NOT COVERED` 6 |
380
+ | `sentence` | 50 | the text of the geometry language both readers have to produce, exactly: the whole figure, in the order the bundle expects it |
381
+ | `answer_contains` | 36 | a substring the answer has to contain: a sentence of the geometry layer, or the certificate of a computed answer |
382
+ | `min_assurance` | 39 | the lowest assurance that is acceptable, on the scale of section 1 |
383
+ | `max_assurance` | 20 | the highest assurance that is acceptable: this is what pins the probes that must not rise |
384
+ | `no_answer` | 17 | `true` where the row is graded by the refusal: no answer may be shown at all |
385
+ | `referee_clean` | 56 | every envelope claim of the session must match what the referee of its node recomputed |
386
+
387
+ The six rows with no `sentence` are exactly the six negative rows, where the reading itself has to fail.
388
+ The 17 rows with `no_answer` split in two: 6 are those negative rows, and 11 are agreed readings of a
389
+ figure that carries no claim the geometry layer can decide (`point-en`, `line-en`, `circle-en`,
390
+ `circle-it`, `assume-en`, `centroid-en`, `centroid-it`, `circumcentre-en`, `intersect-en`, `image-en`,
391
+ `mid-en-def`); on those eleven the assurance must be 0 and no answer may appear, which is the stratum
392
+ refusing to add an availability it does not have.
393
+
394
+ ## 12. Loading it
395
+
396
+ Load the file with the `datasets` library, or with one `json.loads` per line, which needs no
397
+ dependency:
398
+
399
+ ```python
400
+ from datasets import load_dataset
401
+ rows = load_dataset("tailot/geometry-stratum", "corpus", split="train")
402
+ print(rows[0])
403
+ ```
404
+
405
+ This is the same file `tools/ask.py --corpus` walks over, and `lggeostratum/corpus.py` plus
406
+ `tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 56 of 56
407
+ rows agree with what they expect.
408
+
409
+ ## 13. Rights
410
+
411
+ No license is declared for this dataset, its lexicons, its corpus or its code: reuse is not granted by
412
+ this page. The six lexicons, the 56 questions with their gold expectations, the grammar specifications,
413
+ the node data and the Python sources were written by hand as part of the LingoLOGOS project. Ask before
414
+ redistributing or building on them, and expect the answer to be yes for academic work with attribution.
415
+ Z3 is a separate product with its own license and is not redistributed here; `z3-solver` is only named
416
+ as a dependency in `requirements.txt`. The lexicons of Hindi, Arabic and Chinese describe written
417
+ varieties as this project needs them for questions about a figure drawn in words: they are not a general
418
+ purpose dictionary of those languages.
419
+
420
+ ## 14. Citation
421
+
422
+ ```
423
+ @misc{lingologos_geometry_stratum,
424
+ title = {LingoLOGOS geometry-stratum: a question in six written varieties, the answer of the geometry layer, and an assurance that includes the reading},
425
+ author = {LingoLOGOS project},
426
+ year = {2026},
427
+ url = {https://huggingface.co/datasets/tailot/geometry-stratum},
428
+ note = {bundle of the geometry-stratum folder of the LingoLOGOS repository: 56 questions about a
429
+ figure drawn in words, in six written varieties, over the 19 statement kinds of the geometry
430
+ language, with six lexicons, two independent readers, eight node definitions with SMT claims,
431
+ the assurance rule min(geometry, reading) with the reading capped at 2, fault catalogue and
432
+ ablation over the node configurations, 255 tests}
433
+ }
434
+ ```
agents/stratum_agent ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Node executable of the geometry-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 geometry 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 geometry 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 lggeostratum import agents, faults # noqa: E402
24
+
25
+
26
+ def main() -> int:
27
+ parser = argparse.ArgumentParser(description="geometry-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,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "ar",
3
+ "name": "العربية",
4
+ "script": "arabic",
5
+ "noise_chars": "",
6
+ "prefixes": ["ال", "وال", "بال", "فال", "لل", "و", "ب", "ل", "ف"],
7
+ "kinds": {
8
+ "define_point": {
9
+ "verbs": [
10
+ "لتكن",
11
+ "خذ",
12
+ "ضع"
13
+ ],
14
+ "patterns": [
15
+ "لتكن النقطة {P} إحداثياتها {V}"
16
+ ],
17
+ "frame": {
18
+ "sequences": [
19
+ [
20
+ "eq"
21
+ ]
22
+ ]
23
+ }
24
+ },
25
+ "define_line": {
26
+ "verbs": [
27
+ "ارسم",
28
+ "رسم"
29
+ ],
30
+ "patterns": [
31
+ "ارسم المستقيم {E} المار بالنقطتين {P} و {Q}"
32
+ ],
33
+ "frame": {
34
+ "sequences": [
35
+ [
36
+ "through"
37
+ ]
38
+ ]
39
+ }
40
+ },
41
+ "define_circle": {
42
+ "verbs": [
43
+ "ارسم",
44
+ "رسم"
45
+ ],
46
+ "patterns": [
47
+ "ارسم الدائرة {E} مركزها {P} مربع نصف القطر {V}",
48
+ "ارسم الدائرة {E} المارة بالنقاط {X}"
49
+ ],
50
+ "frame": {
51
+ "sequences": [
52
+ [
53
+ "center",
54
+ "radius_squared"
55
+ ],
56
+ [
57
+ "through"
58
+ ]
59
+ ]
60
+ }
61
+ },
62
+ "mid": {
63
+ "verbs": [
64
+ "لتكن",
65
+ "خذ",
66
+ "ضع"
67
+ ],
68
+ "patterns": [
69
+ "خذ {T} منتصف {P} و {Q}",
70
+ "لتكن {T} منتصف {P} و {Q}"
71
+ ],
72
+ "frame": {
73
+ "sequences": [
74
+ [
75
+ "let_mid"
76
+ ]
77
+ ]
78
+ }
79
+ },
80
+ "collinear": {
81
+ "verbs": [
82
+ "أثبت",
83
+ "برهن",
84
+ "أظهر"
85
+ ],
86
+ "patterns": [
87
+ "أثبت أن {X} على استقامة واحدة"
88
+ ],
89
+ "frame": {
90
+ "sequences": [
91
+ [
92
+ "collinear"
93
+ ]
94
+ ]
95
+ }
96
+ },
97
+ "perp": {
98
+ "verbs": [
99
+ "أثبت",
100
+ "برهن",
101
+ "أظهر"
102
+ ],
103
+ "patterns": [
104
+ "أثبت أن المستقيم {L} عمودي على المستقيم {K}"
105
+ ],
106
+ "frame": {
107
+ "sequences": [
108
+ [
109
+ "perp"
110
+ ]
111
+ ]
112
+ }
113
+ },
114
+ "par": {
115
+ "verbs": [
116
+ "أثبت",
117
+ "برهن",
118
+ "أظهر"
119
+ ],
120
+ "patterns": [
121
+ "أثبت أن المستقيم {L} موازٍ للمستقيم {K}"
122
+ ],
123
+ "frame": {
124
+ "sequences": [
125
+ [
126
+ "par"
127
+ ]
128
+ ]
129
+ }
130
+ },
131
+ "cong": {
132
+ "verbs": [
133
+ "أثبت",
134
+ "برهن",
135
+ "أظهر"
136
+ ],
137
+ "patterns": [
138
+ "أثبت أن القطعة {L} تساوي القطعة {K}"
139
+ ],
140
+ "frame": {
141
+ "sequences": [
142
+ [
143
+ "cong"
144
+ ]
145
+ ]
146
+ }
147
+ },
148
+ "right": {
149
+ "verbs": [
150
+ "أثبت",
151
+ "برهن",
152
+ "أظهر"
153
+ ],
154
+ "patterns": [
155
+ "أثبت أن الزاوية {A} قائمة"
156
+ ],
157
+ "frame": {
158
+ "sequences": [
159
+ [
160
+ "right"
161
+ ]
162
+ ]
163
+ }
164
+ },
165
+ "find_circumcircle": {
166
+ "neutral": true,
167
+ "verbs": [
168
+ "أوجد",
169
+ "احسب"
170
+ ],
171
+ "patterns": [
172
+ "أوجد الدائرة المحيطة بالمثلث {X}"
173
+ ],
174
+ "frame": {
175
+ "sequences": [
176
+ []
177
+ ]
178
+ }
179
+ },
180
+ "find_tangents": {
181
+ "neutral": true,
182
+ "verbs": [
183
+ "أوجد",
184
+ "احسب"
185
+ ],
186
+ "patterns": [
187
+ "أوجد المماسات من {P} إلى الدائرة {E}"
188
+ ],
189
+ "frame": {
190
+ "sequences": [
191
+ [
192
+ "to_entity"
193
+ ]
194
+ ]
195
+ }
196
+ }
197
+ },
198
+ "connectives": {
199
+ "and": ["و"],
200
+ "or": ["أو"],
201
+ "not": ["ليس"]
202
+ },
203
+ "markers": {
204
+ "eq": ["إحداثياتها", "إحداثيات هي", "إحداثيات"],
205
+ "through": ["المار بالنقطتين", "المارة بالنقاط", "المار ب", "يمر ب", "يمر بالنقطتين"],
206
+ "center": ["مركزها", "مركزه هو", "مركزه"],
207
+ "radius_squared": ["مربع نصف القطر", "ومربع نصف القطر"],
208
+ "let_mid": ["منتصف", "نقطة منتصف"],
209
+ "collinear": ["على استقامة واحدة", "متساوية الاستقامة"],
210
+ "perp": ["عمودي على", "عمود على", "متعامد على"],
211
+ "par": ["موازٍ للمستقيم", "موازٍ ل", "موازي ل", "المتوازي مع"],
212
+ "cong": ["تساوي", "متساوية مع"],
213
+ "right": ["قائمة", "زاوية قائمة"],
214
+ "to_entity": ["إلى الدائرة", "إلى"]
215
+ },
216
+ "noise": [
217
+ "نقطة", "نقاط", "نقطتين", "مستقيم", "دائرة", "قطعة", "زاوية", "مثلث",
218
+ "مركز", "نصف", "قطر", "إحداثيات", "منتصف", "استقامة", "عمودي", "متعامد",
219
+ "مماس", "مماسات", "محيط", "محيطة", "المارة", "أن", "في", "على", "من",
220
+ "إلى", "هي", "ذلك", "هذا", "كل", "بين"
221
+ ],
222
+ "labels": {
223
+ "understood": "فُهم السؤال بهذه الصيغ",
224
+ "status": "الحالة",
225
+ "assurance": "المستوى {n} من 3",
226
+ "answer": "الجواب",
227
+ "reading": "القراءة",
228
+ "math_layer": "طبقة الهندسة",
229
+ "notes": "ملاحظات",
230
+ "examples": "تفهم الطبقة السؤال بهذه الصيغ",
231
+ "question": "اكتب السؤال بإحدى هذه الصيغ",
232
+ "check": "فحص SMT للطبقة : تأكيد {a} من {b} ظرف",
233
+ "kind_of": "النوع"
234
+ },
235
+ "reading": {
236
+ "AGREED": "قرأ القارئان الجملة نفسها",
237
+ "PASSTHROUGH": "كان السؤال بلغة الطبقة نفسها",
238
+ "DISPUTED": "قرأ القارئان جملتين مختلفتين",
239
+ "NOT COVERED": "لم يفهم أي قارئ السؤال",
240
+ "AMBIGUOUS": "للسؤال قراءتان محتملتان",
241
+ "SINGLE": "قرأ قارئ واحد السؤال",
242
+ "TAMPERED": "الجملة لا تطابق السؤال",
243
+ "NONE": "لم يصل السؤال إلى الطبقة الرسمية"
244
+ },
245
+ "reasons": {
246
+ "unknown_word": "كلمة غير معجمية : {word}",
247
+ "no_verb": "لا فعل في الجملة يعلن نوع الطلب",
248
+ "two_verbs": "يفعلان نوعين في الجملة : {kinds}",
249
+ "no_pattern": "الجملة لا تطابق أي صيغة في هذه اللغة",
250
+ "no_frame": "روابط الجملة لا تطابق صيغة النوع {kind}",
251
+ "multiple": "قراءتان للجملة : {first} و {second}",
252
+ "disagree": "اختلفت الجملتان اللتان قرأهما القارئان",
253
+ "markers": "روابط الجملة لا تناسب هذا النوع",
254
+ "bad_point": "الحقل {slot} لا يحتوي النقطة المطلوبة",
255
+ "bad_line": "الحقل {slot} لا يحتوي مستقيما",
256
+ "bad_angle": "الحقل {slot} لا يحتوي زاوية بثلاث نقاط",
257
+ "bad_entity": "الحقل {slot} لا يحتوي اسما لشكل",
258
+ "bad_value": "الحقل {slot} لا يحتوي قيمة",
259
+ "bad_slot": "الحقل {slot} الذي ينص عليه القواعد فارغ",
260
+ "unbalanced": "قوس لم يغلق",
261
+ "literal_count": "أعداد السؤال ليست في القراءة",
262
+ "geometry_unknown": "لم تجب طبقة الهندسة : {detail}",
263
+ "no_geometry": "السؤال الهندسي ليس بلغة الهندسة",
264
+ "boundary": "الجملة الرسمية المرسلة ليست القراءة المتفق عليها",
265
+ "referee": "لم يؤكد محكم SMT : {detail}",
266
+ "other": "لم تخرج من القراءة جملة رسمية"
267
+ },
268
+ "examples": [
269
+ "النقطة A إحداثياتها (0, 0)",
270
+ "أثبت أن A و B و C على استقامة واحدة",
271
+ "خذ M منتصف A و B",
272
+ "أثبت أن المستقيم A-B عمودي على المستقيم C-D",
273
+ "أوجد المماسات من P إلى الدائرة c"
274
+ ]
275
+ }
lexicon/en.json ADDED
@@ -0,0 +1,229 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "en",
3
+ "name": "English",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "define_point": {
9
+ "verbs": ["let", "place", "mark", "take", "has"],
10
+ "patterns": [
11
+ "let {P} be the point with coordinates {V}",
12
+ "place the point {P} at {V}",
13
+ "the point {P} has coordinates {V}"
14
+ ],
15
+ "frame": {"sequences": [["eq"]]}
16
+ },
17
+ "define_line": {
18
+ "verbs": ["draw", "let"],
19
+ "patterns": [
20
+ "draw the line {E} through the points {P} and {Q}",
21
+ "let the line {E} pass through {P} and {Q}"
22
+ ],
23
+ "frame": {"sequences": [["through"]]}
24
+ },
25
+ "define_circle": {
26
+ "verbs": ["draw", "let"],
27
+ "patterns": [
28
+ "draw the circle {E} with center {P} and radius squared {V}",
29
+ "draw the circle {E} through {X}"
30
+ ],
31
+ "frame": {"sequences": [["center", "radius_squared"], ["through"]]}
32
+ },
33
+ "mid": {
34
+ "verbs": ["let", "take"],
35
+ "patterns": ["let {T} be the midpoint of {P} and {Q}"],
36
+ "frame": {"sequences": [["let_mid"]]}
37
+ },
38
+ "centroid": {
39
+ "verbs": ["let", "take"],
40
+ "patterns": ["let {T} be the centroid of the triangle {X}"],
41
+ "frame": {"sequences": [["let_centroid"]]}
42
+ },
43
+ "circumcentre": {
44
+ "verbs": ["let", "take"],
45
+ "patterns": ["let {T} be the circumcenter of the triangle {X}"],
46
+ "frame": {"sequences": [["let_circumcentre"]]}
47
+ },
48
+ "intersect": {
49
+ "verbs": ["let", "take"],
50
+ "patterns": ["let {T} be the intersection of the line {L} and the line {K}"],
51
+ "frame": {"sequences": [["let_intersect"]]}
52
+ },
53
+ "assume": {
54
+ "verbs": ["suppose", "assume"],
55
+ "patterns": [
56
+ "suppose {X} are not collinear",
57
+ "suppose {Y} are distinct"
58
+ ],
59
+ "frame": {"sequences": [["not_collinear"], ["distinct"]]}
60
+ },
61
+ "collinear": {
62
+ "verbs": ["prove", "show", "verify"],
63
+ "patterns": [
64
+ "prove that {X} are collinear",
65
+ "prove that the points {X} are collinear"
66
+ ],
67
+ "frame": {"sequences": [["collinear"]]}
68
+ },
69
+ "perp": {
70
+ "verbs": ["prove", "show", "verify"],
71
+ "patterns": [
72
+ "prove that the line {L} is perpendicular to the line {K}",
73
+ "prove that the line {L} is perpendicular to {K}",
74
+ "prove that line {L} is perpendicular to line {K}"
75
+ ],
76
+ "frame": {"sequences": [["perp"]]}
77
+ },
78
+ "par": {
79
+ "verbs": ["prove", "show", "verify"],
80
+ "patterns": [
81
+ "prove that the line {L} is parallel to the line {K}",
82
+ "prove that the line {L} is parallel to {K}",
83
+ "prove that line {L} is parallel to line {K}"
84
+ ],
85
+ "frame": {"sequences": [["par"]]}
86
+ },
87
+ "cong": {
88
+ "verbs": ["prove", "show", "verify"],
89
+ "patterns": [
90
+ "prove that the segment {L} is congruent to the segment {K}",
91
+ "prove that segment {L} is congruent to segment {K}"
92
+ ],
93
+ "frame": {"sequences": [["cong"]]}
94
+ },
95
+ "right": {
96
+ "verbs": ["prove", "show", "verify"],
97
+ "patterns": ["prove that the angle {A} is a right angle"],
98
+ "frame": {"sequences": [["right"]]}
99
+ },
100
+ "between": {
101
+ "verbs": ["prove", "show", "verify"],
102
+ "patterns": ["prove that {P} lies between {Q} and {R}"],
103
+ "frame": {"sequences": [["between"]]}
104
+ },
105
+ "oncircle": {
106
+ "verbs": ["prove", "show", "verify"],
107
+ "patterns": [
108
+ "prove that {P} lies on the circle with center {Q} through {R}"
109
+ ],
110
+ "frame": {"sequences": [["oncircle", "through"]]}
111
+ },
112
+ "find_circumcircle": {
113
+ "neutral": true,
114
+ "verbs": ["find", "compute", "determine"],
115
+ "patterns": ["find the circumcircle of the triangle {X}"],
116
+ "frame": {"sequences": [[]]}
117
+ },
118
+ "find_tangents": {
119
+ "neutral": true,
120
+ "verbs": ["find", "compute", "determine"],
121
+ "patterns": ["find the tangents from {P} to the circle {E}",
122
+ "find the tangents from {P} to circle {E}"],
123
+ "frame": {"sequences": [["to_entity"]]}
124
+ },
125
+ "find_image": {
126
+ "neutral": true,
127
+ "verbs": ["find", "compute", "determine"],
128
+ "patterns": ["find the image of {P} under the transformation {E}"],
129
+ "frame": {"sequences": [["under"]]}
130
+ },
131
+ "find_intersect": {
132
+ "neutral": true,
133
+ "verbs": ["find", "compute", "determine"],
134
+ "patterns": ["find the intersection of the line {L} and the line {K}",
135
+ "find the intersection of line {L} and line {K}",
136
+ "find where the line {L} and the line {K} meet"],
137
+ "frame": {"sequences": [[]]}
138
+ }
139
+ },
140
+ "connectives": {
141
+ "and": ["and"],
142
+ "or": ["or"],
143
+ "not": ["not"]
144
+ },
145
+ "markers": {
146
+ "eq": ["with coordinates", "has coordinates", "coordinates", "at"],
147
+ "through": ["through the points", "pass through", "through"],
148
+ "center": ["with center", "center of"],
149
+ "radius_squared": ["and radius squared", "radius squared"],
150
+ "not_collinear": ["are not collinear", "not collinear", "do not lie on one line"],
151
+ "distinct": ["are distinct", "distinct"],
152
+ "let_mid": ["the midpoint of", "midpoint of"],
153
+ "let_centroid": ["the centroid of the triangle", "centroid of the triangle"],
154
+ "let_circumcentre": ["the circumcenter of the triangle", "circumcenter of the triangle"],
155
+ "let_intersect": ["the intersection of", "point of intersection of"],
156
+ "to_entity": ["to the circle", "to circle"],
157
+ "under": ["under the transformation", "under"],
158
+ "collinear": ["are collinear", "lie on one line", "are on one line"],
159
+ "perp": ["is perpendicular to", "perpendicular to"],
160
+ "par": ["is parallel to", "parallel to"],
161
+ "cong": ["is congruent to", "congruent to"],
162
+ "right": ["is a right angle", "right angle"],
163
+ "between": ["lies between", "is between"],
164
+ "oncircle": ["lies on the circle with center", "is on the circle with center"]
165
+ },
166
+ "noise": [
167
+ "the", "a", "an", "of", "to", "on", "with", "that", "be", "is", "are",
168
+ "one", "its", "given", "known",
169
+ "point", "points", "line", "lines", "circle", "circles", "segment", "segments",
170
+ "angle", "angles", "triangle", "triangles", "transformation", "transformations",
171
+ "center", "centers", "coordinates", "radius", "squared", "image", "intersection",
172
+ "tangent", "tangents", "circumcircle", "circumference", "perpendicular", "parallel",
173
+ "congruent", "collinear", "between", "lie", "lies", "midpoint", "centroid",
174
+ "circumcenter", "distinct", "right", "same"
175
+ ],
176
+ "labels": {
177
+ "understood": "The question was understood in these varieties",
178
+ "status": "state",
179
+ "assurance": "level {n} of 3",
180
+ "answer": "answer",
181
+ "reading": "reading",
182
+ "math_layer": "geometry layer",
183
+ "notes": "notes",
184
+ "examples": "examples",
185
+ "question": "question",
186
+ "check": "Stratum SMT check: {a} of {b} envelopes confirmed",
187
+ "kind_of": "kind"
188
+ },
189
+ "reading": {
190
+ "AGREED": "the two readers agree",
191
+ "PASSTHROUGH": "the question was already written in the formal language",
192
+ "DISPUTED": "the two readers disagree",
193
+ "NOT COVERED": "no reader understood the question",
194
+ "AMBIGUOUS": "the question allows two readings",
195
+ "TAMPERED": "the sentence does not match the question",
196
+ "SINGLE": "one reader understood the question",
197
+ "NONE": "the question does not reach the formal layer"
198
+ },
199
+ "reasons": {
200
+ "unknown_word": "word outside the lexicon: {word}",
201
+ "no_verb": "no verb of the lexicon in the sentence",
202
+ "two_verbs": "verbs of two different groups in the sentence: {kinds}",
203
+ "no_pattern": "no pattern of the grammar recognised",
204
+ "no_frame": "the joints of the sentence follow no frame: {kind}",
205
+ "multiple": "the sentence matches two different readings: {first} and {second}",
206
+ "disagree": "the two readings do not coincide",
207
+ "markers": "the joints of the sentence are not enough to fill the frame",
208
+ "bad_point": "the slot of the points does not hold the points asked for: {slot}",
209
+ "bad_line": "the slot of the line does not hold a line: {slot}",
210
+ "bad_angle": "the slot of the angle does not hold three points: {slot}",
211
+ "bad_entity": "the slot of the entity does not hold a name: {slot}",
212
+ "bad_value": "the slot of the value does not hold a value: {slot}",
213
+ "bad_slot": "the slot {slot} of the grammar is not filled",
214
+ "unbalanced": "the sentence of the reading is not balanced",
215
+ "literal_count": "the numbers of the question are not all in the reading",
216
+ "geometry_unknown": "the geometry layer did not answer: {detail}",
217
+ "no_geometry": "the geometry question was not written in the language of geometry",
218
+ "boundary": "the question leaves the domain of the stratum",
219
+ "referee": "envelope discarded by the SMT referee: {detail}",
220
+ "other": "reading discarded"
221
+ },
222
+ "examples": [
223
+ "place the point A at (0, 0)",
224
+ "prove that the points A, B and C are collinear",
225
+ "let M be the midpoint of A and B",
226
+ "prove that the line AB is perpendicular to the line CD",
227
+ "find the tangents from P to the circle c"
228
+ ]
229
+ }
lexicon/es.json ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "es",
3
+ "name": "español",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "define_point": {
9
+ "verbs": ["sea", "fije", "marque", "tome", "tiene"],
10
+ "patterns": [
11
+ "sea {P} el punto con coordenadas {V}",
12
+ "fije el punto {P} en {V}",
13
+ "el punto {P} tiene coordenadas {V}"
14
+ ],
15
+ "frame": {"sequences": [["eq"]]}
16
+ },
17
+ "define_line": {
18
+ "verbs": ["trace", "dibuje", "sea"],
19
+ "patterns": [
20
+ "trace la recta {E} por los puntos {P} y {Q}",
21
+ "sea la recta {E} que pasa por {P} y {Q}"
22
+ ],
23
+ "frame": {"sequences": [["through"]]}
24
+ },
25
+ "define_circle": {
26
+ "verbs": ["trace", "dibuje", "sea"],
27
+ "patterns": [
28
+ "trace la circunferencia {E} con centro {P} y radio al cuadrado {V}",
29
+ "trace la circunferencia {E} que pasa por {X}"
30
+ ],
31
+ "frame": {"sequences": [["center", "radius_squared"], ["through"]]}
32
+ },
33
+ "mid": {
34
+ "verbs": ["sea", "tome"],
35
+ "patterns": ["sea {T} el punto medio de {P} y {Q}"],
36
+ "frame": {"sequences": [["let_mid"]]}
37
+ },
38
+ "centroid": {
39
+ "verbs": ["sea", "tome"],
40
+ "patterns": ["sea {T} el baricentro del triangulo {X}"],
41
+ "frame": {"sequences": [["let_centroid"]]}
42
+ },
43
+ "circumcentre": {
44
+ "verbs": ["sea", "tome"],
45
+ "patterns": ["sea {T} el circocentro del triangulo {X}"],
46
+ "frame": {"sequences": [["let_circumcentre"]]}
47
+ },
48
+ "intersect": {
49
+ "verbs": ["sea", "tome"],
50
+ "patterns": ["sea {T} la interseccion de la recta {L} y la recta {K}"],
51
+ "frame": {"sequences": [["let_intersect"]]}
52
+ },
53
+ "assume": {
54
+ "verbs": ["suponga", "admita"],
55
+ "patterns": [
56
+ "suponga que {X} no son colineales",
57
+ "suponga que {Y} son distintos"
58
+ ],
59
+ "frame": {"sequences": [["not_collinear"], ["distinct"]]}
60
+ },
61
+ "collinear": {
62
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
63
+ "patterns": [
64
+ "demuestre que {X} son colineales",
65
+ "demuestre que los puntos {X} son colineales"
66
+ ],
67
+ "frame": {"sequences": [["collinear"]]}
68
+ },
69
+ "perp": {
70
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
71
+ "patterns": [
72
+ "demuestre que la recta {L} es perpendicular a la recta {K}",
73
+ "demuestre que la recta {L} es perpendicular a {K}"
74
+ ],
75
+ "frame": {"sequences": [["perp"]]}
76
+ },
77
+ "par": {
78
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
79
+ "patterns": [
80
+ "demuestre que la recta {L} es paralela a la recta {K}",
81
+ "demuestre que la recta {L} es paralela a {K}"
82
+ ],
83
+ "frame": {"sequences": [["par"]]}
84
+ },
85
+ "cong": {
86
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
87
+ "patterns": [
88
+ "demuestre que el segmento {L} es congruente con el segmento {K}"
89
+ ],
90
+ "frame": {"sequences": [["cong"]]}
91
+ },
92
+ "right": {
93
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
94
+ "patterns": ["demuestre que el angulo {A} es un angulo recto"],
95
+ "frame": {"sequences": [["right"]]}
96
+ },
97
+ "between": {
98
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
99
+ "patterns": ["demuestre que {P} esta entre {Q} y {R}"],
100
+ "frame": {"sequences": [["between"]]}
101
+ },
102
+ "oncircle": {
103
+ "verbs": ["demuestre", "pruebe", "verifique", "muestre"],
104
+ "patterns": [
105
+ "demuestre que {P} esta en la circunferencia con centro {Q} que pasa por {R}"
106
+ ],
107
+ "frame": {"sequences": [["oncircle", "through"]]}
108
+ },
109
+ "find_circumcircle": {
110
+ "neutral": true,
111
+ "verbs": ["halle", "calcule", "determine"],
112
+ "patterns": ["halle la circunferencia circunscrita al triangulo {X}"],
113
+ "frame": {"sequences": [[]]}
114
+ },
115
+ "find_tangents": {
116
+ "neutral": true,
117
+ "verbs": ["halle", "calcule", "determine"],
118
+ "patterns": ["halle las tangentes desde {P} a la circunferencia {E}"],
119
+ "frame": {"sequences": [["to_entity"]]}
120
+ },
121
+ "find_image": {
122
+ "neutral": true,
123
+ "verbs": ["halle", "calcule", "determine"],
124
+ "patterns": ["halle la imagen de {P} bajo la transformacion {E}"],
125
+ "frame": {"sequences": [["under"]]}
126
+ },
127
+ "find_intersect": {
128
+ "neutral": true,
129
+ "verbs": ["halle", "calcule", "determine"],
130
+ "patterns": ["halle el punto en comun de la recta {L} y la recta {K}"],
131
+ "frame": {"sequences": [[]]}
132
+ }
133
+ },
134
+ "connectives": {
135
+ "and": ["y"],
136
+ "or": ["o"],
137
+ "not": ["no"]
138
+ },
139
+ "markers": {
140
+ "eq": ["con coordenadas", "tiene coordenadas", "coordenadas", "en"],
141
+ "through": ["que pasa por", "pasa por", "por los puntos", "por"],
142
+ "center": ["con centro"],
143
+ "radius_squared": ["y radio al cuadrado", "radio al cuadrado"],
144
+ "not_collinear": ["no son colineales", "no colineales", "no yacen en una recta"],
145
+ "distinct": ["son distintos", "distintos"],
146
+ "let_mid": ["el punto medio de", "punto medio de"],
147
+ "let_centroid": ["el baricentro del triangulo", "baricentro del triangulo"],
148
+ "let_circumcentre": ["el circocentro del triangulo", "circocentro del triangulo"],
149
+ "let_intersect": ["la interseccion de", "el punto de interseccion de"],
150
+ "to_entity": ["a la circunferencia", "al circulo"],
151
+ "under": ["bajo la transformacion", "bajo"],
152
+ "collinear": ["son colineales", "estan en una recta", "yacen en una recta"],
153
+ "perp": ["es perpendicular a", "perpendicular a"],
154
+ "par": ["es paralela a", "paralela a"],
155
+ "cong": ["es congruente con", "congruente con"],
156
+ "right": ["es un angulo recto", "angulo recto"],
157
+ "between": ["esta entre", "se encuentra entre"],
158
+ "oncircle": ["esta en la circunferencia con centro", "se encuentra en la circunferencia con centro"]
159
+ },
160
+ "noise": [
161
+ "el", "la", "los", "las", "un", "una", "unos", "unas", "de", "del", "al", "con",
162
+ "que", "es", "son", "esta", "se", "encuentra", "su", "dado", "dada", "conocido",
163
+ "punto", "puntos", "recta", "rectas", "circunferencia", "circunferencias", "circulo",
164
+ "circulos", "segmento", "segmentos", "angulo", "angulos", "triangulo", "triangulos",
165
+ "transformacion", "transformaciones", "centro", "centros", "coordenadas", "radio",
166
+ "cuadrado", "imagen", "interseccion", "tangente", "tangentes", "circunscrita",
167
+ "perpendicular", "paralela", "congruente", "colineales", "colineal", "entre",
168
+ "yace", "yacen", "esta", "punto", "medio", "baricentro", "circocentro", "distintos",
169
+ "recto", "misma"
170
+ ],
171
+ "labels": {
172
+ "understood": "La pregunta se entendio en estas variantes",
173
+ "status": "estado",
174
+ "assurance": "nivel {n} de 3",
175
+ "answer": "respuesta",
176
+ "reading": "lectura",
177
+ "math_layer": "capa de geometria",
178
+ "notes": "notas",
179
+ "examples": "ejemplos",
180
+ "question": "pregunta",
181
+ "check": "Comprobacion SMT de la capa : {a} de {b} sobres confirmados",
182
+ "kind_of": "tipo"
183
+ },
184
+ "reading": {
185
+ "AGREED": "los dos lectores estan de acuerdo",
186
+ "PASSTHROUGH": "la pregunta ya estaba escrita en el lenguaje formal",
187
+ "DISPUTED": "los dos lectores no estan de acuerdo",
188
+ "NOT COVERED": "ningun lector entendio la pregunta",
189
+ "AMBIGUOUS": "la pregunta admite dos lecturas",
190
+ "TAMPERED": "la frase no corresponde a la pregunta",
191
+ "SINGLE": "un solo lector entendio la pregunta",
192
+ "NONE": "la pregunta no llega a la capa formal"
193
+ },
194
+ "reasons": {
195
+ "unknown_word": "palabra fuera del lexicon : {word}",
196
+ "no_verb": "ningun verbo del lexicon en la frase",
197
+ "two_verbs": "verbos de dos grupos distintos en la frase : {kinds}",
198
+ "no_pattern": "ningun modelo de la gramatica reconocido",
199
+ "no_frame": "los conectores de la frase no siguen ningun esquema : {kind}",
200
+ "multiple": "la frase corresponde a dos lecturas diferentes : {first} y {second}",
201
+ "disagree": "las dos lecturas no coinciden",
202
+ "markers": "los conectores de la frase no bastan para rellenar el esquema",
203
+ "bad_point": "el hueco de los puntos no contiene los puntos pedidos : {slot}",
204
+ "bad_line": "el hueco de la recta no contiene una recta : {slot}",
205
+ "bad_angle": "el hueco del angulo no contiene tres puntos : {slot}",
206
+ "bad_entity": "el hueco de la entidad no contiene un nombre : {slot}",
207
+ "bad_value": "el hueco del valor no contiene un valor : {slot}",
208
+ "bad_slot": "el hueco {slot} de la gramatica no esta rellenado",
209
+ "unbalanced": "la frase de la lectura no esta equilibrada",
210
+ "literal_count": "los numeros de la pregunta no estan todos en la lectura",
211
+ "geometry_unknown": "la capa de geometria no ha respondido : {detail}",
212
+ "no_geometry": "la pregunta geometrica no esta escrita en el lenguaje de la geometria",
213
+ "boundary": "la pregunta sale del dominio de la capa",
214
+ "referee": "sobre descartado por el referee SMT : {detail}",
215
+ "other": "lectura descartada"
216
+ },
217
+ "examples": [
218
+ "fije el punto A en (0, 0)",
219
+ "demuestre que los puntos A, B y C son colineales",
220
+ "sea M el punto medio de A y B",
221
+ "demuestre que la recta AB es perpendicular a la recta CD",
222
+ "halle las tangentes desde P a la circunferencia c"
223
+ ]
224
+ }
lexicon/hi.json ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "hi",
3
+ "name": "हिन्दी",
4
+ "script": "devanagari",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "define_point": {
9
+ "verbs": [
10
+ "मान लें",
11
+ "दिया गया है",
12
+ "लीजिए",
13
+ "लिखिए"
14
+ ],
15
+ "patterns": [
16
+ "मान लें बिंदु {P} के निर्देशांक {V} हैं"
17
+ ],
18
+ "frame": {
19
+ "sequences": [
20
+ [
21
+ "eq"
22
+ ]
23
+ ]
24
+ }
25
+ },
26
+ "define_line": {
27
+ "verbs": [
28
+ "खींचिए",
29
+ "बनाइए"
30
+ ],
31
+ "patterns": [
32
+ "खींचिए रेखा {E} बिंदु {P} और {Q} से गुजरती है",
33
+ "बनाइए रेखा {E} जो गुजरती है {P} और {Q} से"
34
+ ],
35
+ "frame": {
36
+ "sequences": [
37
+ [
38
+ "through"
39
+ ]
40
+ ]
41
+ }
42
+ },
43
+ "define_circle": {
44
+ "verbs": [
45
+ "खींचिए",
46
+ "बनाइए"
47
+ ],
48
+ "patterns": [
49
+ "बनाइए वृत्त {E} का केंद्र {P} त्रिज्या का वर्ग {V} है",
50
+ "खींचिए वृत्त {E} केंद्र {P} त्रिज्या वर्ग {V}",
51
+ "बनाइए वृत्त {E} जो गुजरता है {X} से"
52
+ ],
53
+ "frame": {
54
+ "sequences": [
55
+ [
56
+ "center",
57
+ "radius_squared"
58
+ ],
59
+ [
60
+ "through"
61
+ ]
62
+ ]
63
+ }
64
+ },
65
+ "mid": {
66
+ "verbs": [
67
+ "मान लें",
68
+ "दिया गया है",
69
+ "लीजिए"
70
+ ],
71
+ "patterns": [
72
+ "मान लें {T} रेखाखंड {P} और {Q} का मध्यबिंदु है",
73
+ "मान लें {T} {P} और {Q} का मध्यबिंदु है"
74
+ ],
75
+ "frame": {
76
+ "sequences": [
77
+ [
78
+ "let_mid"
79
+ ]
80
+ ]
81
+ }
82
+ },
83
+ "collinear": {
84
+ "verbs": [
85
+ "सिद्ध कीजिए",
86
+ "सिद्ध",
87
+ "बताइए"
88
+ ],
89
+ "patterns": [
90
+ "सिद्ध कीजिए कि {X} संरेख हैं"
91
+ ],
92
+ "frame": {
93
+ "sequences": [
94
+ [
95
+ "collinear"
96
+ ]
97
+ ]
98
+ }
99
+ },
100
+ "perp": {
101
+ "verbs": [
102
+ "सिद्ध कीजिए",
103
+ "सिद्ध",
104
+ "बताइए"
105
+ ],
106
+ "patterns": [
107
+ "सिद्ध कीजिए कि रेखा {L} रेखा {K} के लंब है",
108
+ "सिद्ध कीजिए कि रेखा {L} लंब है रेखा {K} पर"
109
+ ],
110
+ "frame": {
111
+ "sequences": [
112
+ [
113
+ "perp"
114
+ ]
115
+ ]
116
+ }
117
+ },
118
+ "par": {
119
+ "verbs": [
120
+ "सिद्ध कीजिए",
121
+ "सिद्ध",
122
+ "बताइए"
123
+ ],
124
+ "patterns": [
125
+ "सिद्ध कीजिए कि रेखा {L} रेखा {K} के समानांतर है",
126
+ "सिद्ध कीजिए कि रेखा {L} समानांतर है रेखा {K} के"
127
+ ],
128
+ "frame": {
129
+ "sequences": [
130
+ [
131
+ "par"
132
+ ]
133
+ ]
134
+ }
135
+ },
136
+ "cong": {
137
+ "verbs": [
138
+ "सिद्ध कीजिए",
139
+ "सिद्ध",
140
+ "बताइए"
141
+ ],
142
+ "patterns": [
143
+ "सिद्ध कीजिए कि रेखाखंड {L} रेखाखंड {K} के बराबर है",
144
+ "सिद्ध कीजिए कि रेखाखंड {L} बराबर है रेखाखंड {K} के"
145
+ ],
146
+ "frame": {
147
+ "sequences": [
148
+ [
149
+ "cong"
150
+ ]
151
+ ]
152
+ }
153
+ },
154
+ "right": {
155
+ "verbs": [
156
+ "सिद्ध कीजिए",
157
+ "सिद्ध",
158
+ "बताइए"
159
+ ],
160
+ "patterns": [
161
+ "सिद्ध कीजिए कि कोण {A} समकोण है"
162
+ ],
163
+ "frame": {
164
+ "sequences": [
165
+ [
166
+ "right"
167
+ ]
168
+ ]
169
+ }
170
+ },
171
+ "find_circumcircle": {
172
+ "neutral": true,
173
+ "verbs": [
174
+ "ज्ञात कीजिए",
175
+ "गणना कीजिए"
176
+ ],
177
+ "patterns": [
178
+ "ज्ञात कीजिए त्रिभुज {X} का परिवृत्त"
179
+ ],
180
+ "frame": {
181
+ "sequences": [
182
+ []
183
+ ]
184
+ }
185
+ },
186
+ "find_tangents": {
187
+ "neutral": true,
188
+ "verbs": [
189
+ "ज्ञात कीजिए",
190
+ "गणना कीजिए"
191
+ ],
192
+ "patterns": [
193
+ "ज्ञात कीजिए {P} से वृत्त {E} की स्पर्शरेखाएँ"
194
+ ],
195
+ "frame": {
196
+ "sequences": [
197
+ [
198
+ "to_entity"
199
+ ]
200
+ ]
201
+ }
202
+ }
203
+ },
204
+ "connectives": {
205
+ "and": ["और"],
206
+ "or": ["या"],
207
+ "not": ["नहीं"]
208
+ },
209
+ "markers": {
210
+ "eq": ["के निर्देशांक", "निर्देशांक"],
211
+ "through": ["से गुजरती", "से गुजरता", "गुजरती", "गुजरता"],
212
+ "center": ["का केंद्र", "के केंद्र"],
213
+ "radius_squared": ["त्रिज्या का वर्ग"],
214
+ "let_mid": ["का मध्यबिंदु", "मध्यबिंदु"],
215
+ "collinear": ["संरेख हैं", "संरेख"],
216
+ "perp": ["के लंब", "लंब है"],
217
+ "par": ["के समानांतर", "समानांतर है"],
218
+ "cong": ["के बराबर", "बराबर है"],
219
+ "right": ["समकोण है", "समकोण"],
220
+ "to_entity": ["से वृत्त की", "से वृत्त"]
221
+ },
222
+ "noise": [
223
+ "बिंदु", "रेखा", "वृत्त", "रेखाखंड", "कोण", "त्रिभुज", "केंद्र", "त्रिज्या", "वर्ग",
224
+ "निर्देशांक", "समकोण", "लंब", "समानांतर", "बराबर", "मध्यबिंदु", "परिवृत्त",
225
+ "स्पर्शरेखा", "स्पर्शरेखाएँ", "कि", "हैं", "है", "से", "का", "की", "के", "में",
226
+ "यह", "वह", "दिया", "गया", "हुआ", "पर", "तथा"
227
+ ],
228
+ "labels": {
229
+ "understood": "इन रूपों में प्रश्न समझा गया",
230
+ "status": "स्थिति",
231
+ "assurance": "3 में से स्तर {n}",
232
+ "answer": "उत्तर",
233
+ "reading": "पठन",
234
+ "math_layer": "ज्यामितीय परत",
235
+ "notes": "टिप्पणियाँ",
236
+ "examples": "इन रूपों में परत प्रश्न समझती है",
237
+ "question": "प्रश्न इन रूपों में से किसी में लिखिए",
238
+ "check": "परत की SMT जाँच : {b} लिफाफों में से {a} पुष्ट",
239
+ "kind_of": "प्रकार"
240
+ },
241
+ "reading": {
242
+ "AGREED": "दोनों पाठकों ने एक ही वाक्य बनाया",
243
+ "PASSTHROUGH": "प्रश्न पहले से औपचारिक भाषा में था",
244
+ "DISPUTED": "दोनों पाठकों ने भिन्न वाक्य बनाए",
245
+ "NOT COVERED": "कोई पाठक प्रश्न नहीं समझा",
246
+ "AMBIGUOUS": "प्रश्न के दो पठन बनते हैं",
247
+ "SINGLE": "एक ही पाठक ने प्रश्न समझा",
248
+ "TAMPERED": "वाक्य प्रश्न से मेल नहीं खाता",
249
+ "NONE": "प्रश्न औपचारिक परत तक नहीं पहुँचा"
250
+ },
251
+ "reasons": {
252
+ "unknown_word": "शब्द कोश में नहीं : {word}",
253
+ "no_verb": "वाक्य में कोई क्रिया प्रकार नहीं बताती",
254
+ "two_verbs": "वाक्य दो प्रकार घोषित करते हैं : {kinds}",
255
+ "no_pattern": "वाक्य इस भाषा के किसी रूप से मेल नहीं खाता",
256
+ "no_frame": "संबंधक प्रकार {kind} के किसी रूप से मेल नहीं खाते",
257
+ "multiple": "एक ही वाक्य के दो पठन : {first} और {second}",
258
+ "disagree": "दोनों पाठकों के वाक्य भिन्न हैं",
259
+ "markers": "वाक्य के संबंधक इस प्रकार के अपेक्षित नहीं हैं",
260
+ "bad_point": "{slot} में अपेक्षित बिंदु नहीं हैं",
261
+ "bad_line": "{slot} में रेखा नहीं है",
262
+ "bad_angle": "{slot} में तीन बिंदुओं का कोण नहीं है",
263
+ "bad_entity": "{slot} में आकृति का नाम नहीं है",
264
+ "bad_value": "{slot} में मान नहीं है",
265
+ "bad_slot": "व्याकरण का {slot} खाली है",
266
+ "unbalanced": "कोई कोष्ठक बंद नहीं है",
267
+ "literal_count": "प्रश्न की संख्याएँ पठन में नहीं हैं",
268
+ "geometry_unknown": "ज्यामितीय परत ने उत्तर नहीं दिया : {detail}",
269
+ "no_geometry": "ज्यामितीय प्रश्न ज्यामिति की भाषा में नहीं लिखा गया",
270
+ "boundary": "औपचारिक परत को भेजा गया वाक्य सहमत पठन नहीं है",
271
+ "referee": "SMT रेफरी ने पुष्टि नहीं की : {detail}",
272
+ "other": "पठन से औपचारिक वाक्य नहीं मिला"
273
+ },
274
+ "examples": [
275
+ "बिंदु A के निर्देशांक (0, 0) हैं",
276
+ "सिद्ध कीजिए कि A, B और C संरेख हैं",
277
+ "मान लें M, A और B का मध्यबिंदु है",
278
+ "सिद्ध कीजिए कि रेखा A-B लंब है रेखा C-D पर",
279
+ "ज्ञात कीजिए P से वृत्त c की स्पर्शरेखाएँ"
280
+ ]
281
+ }
lexicon/it.json ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "it",
3
+ "name": "italiano",
4
+ "script": "latin",
5
+ "noise_chars": "",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "define_point": {
9
+ "verbs": ["sia", "siano", "sia dato", "siano date", "sia data", "consideriamo", "prendiamo"],
10
+ "patterns": [
11
+ "sia {P} il punto di coordinate {V}",
12
+ "siano {P} e {Q} i punti di coordinate {V} e {W}",
13
+ "consideriamo il punto {P} di coordinate {V}"
14
+ ],
15
+ "frame": {"sequences": [["eq"]]}
16
+ },
17
+ "assume": {
18
+ "verbs": ["supponiamo", "ipotizziamo", "sia noto", "dato che", "assumiamo"],
19
+ "patterns": [
20
+ "supponiamo che i punti {X} non siano allineati",
21
+ "supponiamo che i punti {Y} siano distinti"
22
+ ],
23
+ "frame": {"sequences": [["not_collinear"], ["distinct"]]}
24
+ },
25
+ "define_line": {
26
+ "verbs": ["disegna", "traccia", "considera", "sia"],
27
+ "patterns": [
28
+ "disegna la retta {E} per i punti {P} e {Q}",
29
+ "sia {E} la retta per i punti {P} e {Q}"
30
+ ],
31
+ "frame": {"sequences": [["through"]]}
32
+ },
33
+ "define_circle": {
34
+ "verbs": ["disegna", "traccia", "considera", "sia"],
35
+ "patterns": [
36
+ "disegna la circonferenza {E} con centro {P} e raggio al quadrato {V}",
37
+ "sia {E} la circonferenza con centro {P} e raggio al quadrato {V}",
38
+ "disegna la circonferenza {E} per i punti {X}"
39
+ ],
40
+ "frame": {"sequences": [["center", "radius_squared"], ["through"]]}
41
+ },
42
+ "mid": {
43
+ "verbs": ["sia", "sia dato", "consideriamo", "prendiamo"],
44
+ "patterns": [
45
+ "sia {T} il punto medio di {P} e {Q}",
46
+ "sia {T} il punto medio del segmento {P} e {Q}"
47
+ ],
48
+ "frame": {"sequences": [["let_mid"]]}
49
+ },
50
+ "centroid": {
51
+ "verbs": ["sia", "sia dato", "consideriamo"],
52
+ "patterns": ["sia {T} il baricentro del triangolo {X}"],
53
+ "frame": {"sequences": [["let_centroid"]]}
54
+ },
55
+ "circumcentre": {
56
+ "verbs": ["sia", "sia dato", "consideriamo"],
57
+ "patterns": ["sia {T} il circocentro del triangolo {X}"],
58
+ "frame": {"sequences": [["let_circumcentre"]]}
59
+ },
60
+ "intersect": {
61
+ "verbs": ["sia", "sia dato", "consideriamo", "sia noto"],
62
+ "patterns": [
63
+ "sia {T} l intersezione di {L} e {K}",
64
+ "sia {T} un punto di intersezione di {L} e {K}"
65
+ ],
66
+ "frame": {"sequences": [["let_intersect"]]}
67
+ },
68
+ "find_circumcircle": {
69
+ "neutral": true,
70
+ "verbs": ["trova", "calcola", "determina"],
71
+ "patterns": ["trova la circonferenza circoscritta al triangolo {X}"],
72
+ "frame": {"sequences": [[]]}
73
+ },
74
+ "find_tangents": {
75
+ "neutral": true,
76
+ "verbs": ["trova", "calcola", "determina"],
77
+ "patterns": [
78
+ "trova le tangenti da {P} alla circonferenza {E}",
79
+ "trova le rette tangenti da {P} alla circonferenza {E}"
80
+ ],
81
+ "frame": {"sequences": [["to_entity"]]}
82
+ },
83
+ "find_intersect": {
84
+ "neutral": true,
85
+ "verbs": ["trova", "calcola", "determina"],
86
+ "patterns": [
87
+ "trova il punto in comune tra la retta {L} e la retta {K}"
88
+ ],
89
+ "frame": {"sequences": [[]]}
90
+ },
91
+ "collinear": {
92
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"],
93
+ "patterns": [
94
+ "dimostra che {X} sono collineari",
95
+ "dimostra che i punti {X} sono collineari",
96
+ "dimostra che {X} sono allineati",
97
+ "dimostra che i punti {X} sono allineati"
98
+ ],
99
+ "frame": {"sequences": [["collinear"]]}
100
+ },
101
+ "perp": {
102
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"],
103
+ "patterns": [
104
+ "dimostra che {L} e perpendicolare a {K}",
105
+ "dimostra che la retta {L} e perpendicolare alla retta {K}",
106
+ "dimostra che la retta {L} perpendicolare alla retta {K}",
107
+ "dimostra che {L} perpendicolare a {K}",
108
+ "dimostra che {L} e ortogonale a {K}"
109
+ ],
110
+ "frame": {"sequences": [["perp"]]}
111
+ },
112
+ "par": {
113
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"],
114
+ "patterns": [
115
+ "dimostra che {L} e parallela a {K}",
116
+ "dimostra che la retta {L} e parallela alla retta {K}",
117
+ "dimostra che la retta {L} parallela alla retta {K}",
118
+ "dimostra che {L} parallela a {K}"
119
+ ],
120
+ "frame": {"sequences": [["par"]]}
121
+ },
122
+ "cong": {
123
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"],
124
+ "patterns": [
125
+ "dimostra che {L} e congruente a {K}",
126
+ "dimostra che il segmento {L} e congruente al segmento {K}",
127
+ "dimostra che il segmento {L} congruente al segmento {K}",
128
+ "dimostra che {L} congruente a {K}"
129
+ ],
130
+ "frame": {"sequences": [["cong"]]}
131
+ },
132
+ "right": {
133
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica", "mostra"],
134
+ "patterns": [
135
+ "dimostra che l angolo {A} e un angolo retto",
136
+ "dimostra che l angolo {A} e retto"
137
+ ],
138
+ "frame": {"sequences": [["right"]]}
139
+ },
140
+ "between": {
141
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica"],
142
+ "patterns": ["dimostra che {P} e compreso fra {Q} e {R}"],
143
+ "frame": {"sequences": [["between"]]}
144
+ },
145
+ "oncircle": {
146
+ "verbs": ["dimostra", "dimostrare", "prova", "verifica"],
147
+ "patterns": [
148
+ "dimostra che {P} giace sulla circonferenza di centro {Q} e passante per {R}",
149
+ "dimostra che {P} sta sulla circonferenza di centro {Q} e passante per {R}"
150
+ ],
151
+ "frame": {"sequences": [["oncircle", "through"]]}
152
+ }
153
+ },
154
+ "connectives": {
155
+ "and": ["e", "ed"],
156
+ "or": ["o"],
157
+ "not": ["non"]
158
+ },
159
+ "markers": {
160
+ "eq": ["coordinate", "di coordinate", "le coordinate"],
161
+ "not_collinear": ["non sono allineati", "non sono collineari"],
162
+ "distinct": ["sono distinti", "sono diversi"],
163
+ "let_mid": ["punto medio", "punto medio di"],
164
+ "let_centroid": ["baricentro", "baricentro di"],
165
+ "let_circumcentre": ["circocentro", "circocentro di"],
166
+ "let_intersect": ["intersezione", "punto di intersezione"],
167
+ "through": ["passante per", "per i punti", "per"],
168
+ "center": ["centro", "con centro"],
169
+ "radius_squared": ["raggio al quadrato", "quadrato del raggio"],
170
+ "to_entity": ["alla circonferenza", "al cerchio"],
171
+ "collinear": ["sono collineari", "risultano collineari", "sono allineati",
172
+ "risultano allineati", "giacciono sulla stessa retta"],
173
+ "perp": ["perpendicolare a", "perpendicolare alla", "ortogonale a"],
174
+ "par": ["parallela a", "parallelo a", "parallela alla", "parallelo alla"],
175
+ "cong": ["congruente a", "congruente con", "congruente al", "congruente alla"],
176
+ "right": ["angolo retto", "e retto"],
177
+ "between": ["e compreso fra", "sta fra"],
178
+ "oncircle": ["giace sulla circonferenza di centro", "sta sulla circonferenza di centro"]
179
+ },
180
+ "noise": [
181
+ "la", "lo", "l", "i", "gli", "il", "un", "una", "uno", "dello", "della", "degli",
182
+ "dei", "del", "l'", "a", "al", "alla", "ai", "alle", "da", "dal", "dalla", "di",
183
+ "in", "con", "su", "sul", "sulla", "fra", "tra", "che", "di coordinate",
184
+ "punto", "punti", "retta", "rette", "segmento", "segmenti", "circonferenza",
185
+ "cerchio", "angolo", "angoli", "triangolo", "triangoli", "piano", "figura",
186
+ "intersezione", "tangente", "tangenti", "rette tangenti", "semiretta", "lunghezza",
187
+ "quadrato", "raggio", "coordinate", "circonferenza circoscritta", "compreso",
188
+ "passante", "giace", "sta", "ortogonale", "parallel", "parallela", "perpendicolare",
189
+ "congruente", "collineari", "allineati", "retto", "distincti", "su cui", "tale che"
190
+ ],
191
+ "labels": {
192
+ "understood": "domanda capita in queste forme",
193
+ "status": "stato",
194
+ "assurance": "livello {n} di 3",
195
+ "answer": "risposta",
196
+ "reading": "lettura",
197
+ "math_layer": "strato geometrico",
198
+ "notes": "note",
199
+ "examples": "lo strato capisce la domanda in queste forme",
200
+ "question": "riformula la domanda in una di queste forme",
201
+ "check": "controllo SMT dello strato : {a} di {b} buste confermate",
202
+ "kind_of": "tipo"
203
+ },
204
+ "reading": {
205
+ "AGREED": "i due lettori hanno letto la stessa frase",
206
+ "PASSTHROUGH": "la domanda era gia nella lingua dello strato",
207
+ "DISPUTED": "i due lettori hanno letto frasi diverse",
208
+ "NOT COVERED": "nessun lettore ha capito la domanda",
209
+ "AMBIGUOUS": "la domanda ha due letture possibili",
210
+ "SINGLE": "un solo lettore ha capito la domanda",
211
+ "TAMPERED": "la frase non corrisponde alla domanda",
212
+ "NONE": "la domanda non e arrivata allo strato formale"
213
+ },
214
+ "reasons": {
215
+ "unknown_word": "parola non nel lessico : {word}",
216
+ "no_verb": "nessun verbo nella frase annuncia il tipo di richiesta",
217
+ "two_verbs": "due verbi annunciano due tipi : {kinds}",
218
+ "no_pattern": "la frase non corrisponde a nessuna forma di questa lingua",
219
+ "no_frame": "i connettivi della frase non corrispondono a nessuna forma del tipo {kind}",
220
+ "multiple": "la frase ha due letture : {first} e {second}",
221
+ "disagree": "diversa la frase dei due lettori",
222
+ "markers": "i connettivi della frase non sono quelli attesi per questo tipo",
223
+ "bad_point": "lo slot {slot} non contiene un punto",
224
+ "bad_line": "lo slot {slot} non contiene una retta",
225
+ "bad_angle": "lo slot {slot} non contiene un angolo di tre punti",
226
+ "bad_entity": "lo slot {slot} non contiene una figura",
227
+ "bad_value": "lo slot {slot} non contiene un valore",
228
+ "bad_slot": "lo slot {slot} previsto dalla grammatica e vuoto",
229
+ "unbalanced": "una parentesi non e chiusa",
230
+ "literal_count": "i numeri della domanda non sono nella lettura",
231
+ "geometry_unknown": "lo strato geometrico non ha risposto : {detail}",
232
+ "no_geometry": "la domanda geometrica non e scritta nella lingua della geometria",
233
+ "boundary": "la frase formale inviata non e la lettura concordata",
234
+ "referee": "il referee SMT non ha confermato : {detail}",
235
+ "other": "la lettura non produce una frase formale"
236
+ },
237
+ "examples": [
238
+ "Sia A il punto di coordinate (0, 0).",
239
+ "Dimostra che i punti A, B e C sono collineari.",
240
+ "Sia M il punto medio di A e B.",
241
+ "Disegna la retta r per i punti A e B.",
242
+ "Dimostra che la retta AB e perpendicolare alla retta CD.",
243
+ "Trova le tangenti da P alla circonferenza c."
244
+ ]
245
+ }
lexicon/zh.json ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "lang": "zh",
3
+ "name": "中文",
4
+ "script": "cjk",
5
+ "noise_chars": "的了之把被给吧呢吗也则该是在为于其此各两上再经和与或不是",
6
+ "prefixes": [],
7
+ "kinds": {
8
+ "define_point": {
9
+ "verbs": ["设", "取", "标出"],
10
+ "patterns": [
11
+ "设 点 {P} 的 坐标 为 {V}",
12
+ "设 {P} 的 坐标 为 {V}"
13
+ ],
14
+ "frame": {"sequences": [["eq"]]}
15
+ },
16
+ "define_line": {
17
+ "verbs": ["作", "画"],
18
+ "patterns": ["作 直线 {E} 经过 点 {P} 和 {Q}"],
19
+ "frame": {"sequences": [["through"]]}
20
+ },
21
+ "define_circle": {
22
+ "verbs": ["作", "画"],
23
+ "patterns": [
24
+ "作 圆 {E} 的 圆心 为 {P} 半径 的 平方 为 {V}",
25
+ "作 圆 {E} 经过 {X}"
26
+ ],
27
+ "frame": {"sequences": [["center", "radius_squared"], ["through"]]}
28
+ },
29
+ "mid": {
30
+ "verbs": ["设", "取"],
31
+ "patterns": ["设 {T} 为 {P} 和 {Q} 的 中点", "设 {T} 平分 {P} {Q}"],
32
+ "frame": {"sequences": [["let_mid"]]}
33
+ },
34
+ "collinear": {
35
+ "verbs": ["证明", "求证"],
36
+ "patterns": ["证明 {X} 共线", "证明 点 {X} 共线"],
37
+ "frame": {"sequences": [["collinear"]]}
38
+ },
39
+ "perp": {
40
+ "verbs": ["证明", "求证"],
41
+ "patterns": ["证明 直线 {L} 垂直于 直线 {K}"],
42
+ "frame": {"sequences": [["perp"]]}
43
+ },
44
+ "par": {
45
+ "verbs": ["证明", "求证"],
46
+ "patterns": ["证明 直线 {L} 平行于 直线 {K}"],
47
+ "frame": {"sequences": [["par"]]}
48
+ },
49
+ "cong": {
50
+ "verbs": ["证明", "求证"],
51
+ "patterns": ["证明 线段 {L} 全等于 线段 {K}"],
52
+ "frame": {"sequences": [["cong"]]}
53
+ },
54
+ "right": {
55
+ "verbs": ["证明", "求证"],
56
+ "patterns": ["证明 角 {A} 为 直角"],
57
+ "frame": {"sequences": [["right"]]}
58
+ },
59
+ "between": {
60
+ "verbs": ["证明", "求证"],
61
+ "patterns": ["证明 {P} 在 {Q} 和 {R} 之间"],
62
+ "frame": {"sequences": [["between"]]}
63
+ },
64
+ "oncircle": {
65
+ "verbs": ["证明", "求证"],
66
+ "patterns": ["证明 {P} 在 圆心 为 {Q} 经过 {R} 的 圆 上", "证明 {P} 属于 圆心 为 {Q} 经过 {R} 的 圆"],
67
+ "frame": {"sequences": [["oncircle", "through"]]}
68
+ },
69
+ "find_circumcircle": {
70
+ "neutral": true,
71
+ "verbs": ["求", "计算"],
72
+ "patterns": ["求 三角形 {X} 的 外接圆"],
73
+ "frame": {"sequences": [[]]}
74
+ },
75
+ "find_tangents": {
76
+ "neutral": true,
77
+ "verbs": ["求", "计算"],
78
+ "patterns": ["求 从 {P} 到 圆 {E} 的 切线"],
79
+ "frame": {"sequences": [["to_entity"]]}
80
+ }
81
+ },
82
+ "connectives": {
83
+ "and": ["和", "与"],
84
+ "or": ["或"],
85
+ "not": ["不"]
86
+ },
87
+ "markers": {
88
+ "eq": ["的坐标为", "坐标为"],
89
+ "through": ["经过", "过"],
90
+ "center": ["的圆心为", "圆心为"],
91
+ "radius_squared": ["半径的平方为", "半径平方为", "的平方为"],
92
+ "let_mid": ["的中点", "中点", "平分"],
93
+ "collinear": ["共线"],
94
+ "perp": ["垂直于"],
95
+ "par": ["平行于"],
96
+ "cong": ["全等于"],
97
+ "right": ["为直角", "是直角"],
98
+ "between": ["在"],
99
+ "oncircle": ["圆心为"],
100
+ "to_entity": ["到圆"]
101
+ },
102
+ "noise": [
103
+ "点", "直线", "圆", "圆周", "线段", "角", "三角形", "半径", "平方", "中点",
104
+ "切线", "外接圆", "圆心", "坐标", "变换", "从", "到", "直角", "之间", "属于"
105
+ ],
106
+ "labels": {
107
+ "understood": "这种变体理解的问题",
108
+ "status": "状态",
109
+ "assurance": "三级中的第 {n} 级",
110
+ "answer": "答案",
111
+ "reading": "读法",
112
+ "math_layer": "几何层",
113
+ "notes": "备注",
114
+ "examples": "这一层能理解的句子",
115
+ "question": "请用下列形式之一重述问题",
116
+ "check": "几何层的 SMT 检查:{b} 个信封中有 {a} 个得到确认",
117
+ "kind_of": "类型"
118
+ },
119
+ "reading": {
120
+ "AGREED": "一致:两位独立读者加上 SMT 约束",
121
+ "PASSTHROUGH": "句子已用几何语言写成,未作翻译",
122
+ "DISPUTED": "有分歧:两位读者给出不同的句子",
123
+ "NOT COVERED": "不在这种语言变体所覆盖的范围之内",
124
+ "AMBIGUOUS": "有歧义:可以有不止一种读法",
125
+ "SINGLE": "只有一种读法:另一位读者没有认出这个句子",
126
+ "TAMPERED": "被篡改:送往几何层的句子不是那个一致的读法",
127
+ "NONE": "没有读法"
128
+ },
129
+ "reasons": {
130
+ "unknown_word": "{word} 不属于这种中文所覆盖的词",
131
+ "no_verb": "没有词宣布问题的类型",
132
+ "two_verbs": "句子宣布了不止一种问题类型:{kinds}",
133
+ "no_pattern": "句子的形状不匹配这种中文所覆盖的任何形状",
134
+ "no_frame": "连接词不匹配类型 {kind} 的任何形状",
135
+ "multiple": "同一句子有两种不同的读法:{first} 和 {second}",
136
+ "disagree": "两位读者给出两个不同的几何语言句子",
137
+ "markers": "句子的连接词不是该类型所期待的��些",
138
+ "bad_point": "{slot} 不是几何语言中所要求的点",
139
+ "bad_line": "{slot} 不是几何语言中的一条直线",
140
+ "bad_angle": "{slot} 不是三个点组成的角",
141
+ "bad_entity": "{slot} 不是图形的名字",
142
+ "bad_value": "{slot} 不是一个数值",
143
+ "bad_slot": "语法中的 {slot} 没有被填满",
144
+ "unbalanced": "有个圆括号或方括号没有闭合",
145
+ "literal_count": "句子中的数字在两位读者那里并不相同",
146
+ "geometry_unknown": "几何层不接受这个句子:{detail}",
147
+ "no_geometry": "这道几何题没有用几何语言书写",
148
+ "boundary": "送往几何层的句子不是那个一致的读法",
149
+ "referee": "SMT 裁判没有确认 {detail}",
150
+ "other": "读法没有得到几何语言中的一个句子"
151
+ },
152
+ "examples": [
153
+ "设点A的坐标为 (0, 0)",
154
+ "证明点A、B和C共线",
155
+ "设M为A和B的中点",
156
+ "证明直线AB垂直于直线CD",
157
+ "求从P到圆c的切线"
158
+ ]
159
+ }
lggeostratum/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The library of the geometry-stratum topology.
2
+
3
+ The geometry-stratum is the conversational stratum of the geometry topology: it accepts a problem
4
+ written in one of six language varieties, reads it into one sentence of the geometry language,
5
+ hands that sentence to the geometry layer as a separate process, and presents the verdict of
6
+ the geometry layer 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 geometry layer 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 geometry 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"]
lggeostratum/agents.py ADDED
@@ -0,0 +1,364 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 reading layer of the geometry
5
+ experiment runs, only moved one level up: two independent readers instead of two independent
6
+ formalizers, an equivalence node instead of the equivalence checker, a coverage node that counts
7
+ the numbers the user wrote, an invoker that hands the agreed text to the geometry bundle as a
8
+ separate process, a boundary where that verdict enters this stratum, an adversary that re-derives
9
+ what the others asserted, and an arbiter that decides and answers in the user's language.
10
+
11
+ reader_a surface reading: the words of the variety, in the order they appear
12
+ reader_b frame reading: which marker phrase sits in which gap of the frame
13
+ equivalence are the two readings the same problem? SMT2 answers, text identity is a shortcut
14
+ coverage did the readings keep every number the user wrote?
15
+ invoker call the geometry bundle, in another process, on one text
16
+ boundary the geometry 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 geometry bundle, ceiling of the reading)``, and the ceiling is below the top
23
+ level of the bundle. A node may lower what the user sees; none may raise it.
24
+
25
+ A figure problem is stated over several sentences -- the points and their coordinates, then the
26
+ claim -- so each reader node reads sentence by sentence and hands on the text those sentences form
27
+ together. That joining is a property of this layer, not of the readers: a reader sees one sentence
28
+ of one language, exactly as the grammar of its variety describes one sentence.
29
+ """
30
+
31
+ from typing import Any, Dict, List, Optional, Tuple
32
+
33
+ from . import canonical, compare, coverage, decide, faults, invoker, protocol, read_a, read_b, render
34
+
35
+ ORDER = ("reader_a", "reader_b", "equivalence", "coverage", "invoker", "boundary", "adversary", "arbiter")
36
+
37
+ WORST = ("NOT COVERED", "AMBIGUOUS", "READ")
38
+
39
+
40
+ def _ast(dossier: Dict[str, Any]) -> str:
41
+ """One ASCII line describing the shape of the dossier, for the abstractSyntaxTree field."""
42
+ def status_of(key: str) -> str:
43
+ part = dossier.get(key)
44
+ if not isinstance(part, dict):
45
+ return "absent"
46
+ return str(part.get("status") or part.get("state") or part.get("kind") or "present")
47
+
48
+ return "Stratum(lang=%s, a=%s, b=%s, equiv=%s, cover=%s, math=%s, final=%s)" % (
49
+ dossier.get("lang", "?"), status_of("reading_a"), status_of("reading_b"),
50
+ "same" if (dossier.get("compare") or {}).get("same") else "no",
51
+ "ok" if (dossier.get("coverage") or {}).get("ok") else "no",
52
+ (dossier.get("math") or {}).get("status", "absent"),
53
+ (dossier.get("final") or {}).get("state", "absent"),
54
+ )
55
+
56
+
57
+ def _cap_claim(shown: int, ceiling: int) -> Tuple[List[str], List[str], str]:
58
+ """SMT2 for ``this node raised nothing``: the strict excess over the ceiling is refuted."""
59
+ decls = ["(declare-const shown Real)", "(declare-const ceiling Real)"]
60
+ asserts = ["(assert (= shown %d))" % int(shown), "(assert (= ceiling %d))" % int(ceiling),
61
+ "(assert (> shown ceiling))"]
62
+ return decls, asserts, "unsat"
63
+
64
+
65
+ def _reader_claim(reading: Dict[str, Any], question: str) -> Tuple[List[str], List[str], str]:
66
+ """A reader claims one thing only: it dropped no number the user wrote."""
67
+ step = compare.keeps(reading, question)
68
+ return step["declarations"], step["assertions"], step["claimed"]
69
+
70
+
71
+ def _read(lang: str, reader: Any, question: str) -> Dict[str, Any]:
72
+ """One reading of a whole question: each sentence on its own, then the text they build together.
73
+
74
+ The geometry language states a figure problem as a sequence of commands, and a speaker states it
75
+ the same way -- the coordinates first, the claim last. Each sentence is read by the reader of
76
+ that variety, so a reading is still a reading of one sentence at a time; what the node adds is
77
+ the joining, and the state of the joined reading is the worst state among its parts. A reading
78
+ that lost one of the sentences of the figure is therefore never better than the reading that
79
+ read all of them.
80
+ """
81
+ sentences = [item for item in canonical.split_sentences(question) if str(item).strip()]
82
+ if len(sentences) <= 1:
83
+ return reader.read(lang, question)
84
+ parts: List[Dict[str, Any]] = []
85
+ notes: List[Dict[str, Any]] = []
86
+ for sentence in sentences:
87
+ part = reader.read(lang, sentence)
88
+ parts.append(part)
89
+ for note in part.get("notes") or []:
90
+ if isinstance(note, dict):
91
+ notes.append(note)
92
+ state = "READ"
93
+ for part in parts:
94
+ if part.get("status") in WORST:
95
+ if WORST.index(str(part.get("status"))) < WORST.index(state):
96
+ state = str(part["status"])
97
+ read_parts = [part for part in parts if part.get("math")]
98
+ text = " ".join("%s." % str(part["math"]).rstrip(".") for part in read_parts if str(part.get("math", "")).strip())
99
+ kinds = [str(part["kind"]) for part in parts if part.get("kind")]
100
+ kind = kinds[0] if len(set(kinds)) == 1 and kinds else ("problem" if kinds else None)
101
+ reading: Dict[str, Any] = {
102
+ "status": state,
103
+ "kind": kind,
104
+ "math": text if state == "READ" else "",
105
+ "slots": {},
106
+ "notes": notes,
107
+ "compound": True,
108
+ "parts": [{"kind": part.get("kind"), "slots": dict(part.get("slots") or {}),
109
+ "math": str(part.get("math") or ""), "status": part.get("status")} for part in parts],
110
+ }
111
+ reading["literals"] = compare.sorted_numbers(question)
112
+ return reading
113
+
114
+
115
+ def _apply_reader_fault(agent: str, reading: Dict[str, Any]) -> None:
116
+ """Corrupt a reading on purpose, for the ablation experiments: never in a normal session."""
117
+ if not reading.get("kind") or reading.get("status") != "READ":
118
+ return
119
+ for kind in ("rename_slot", "merge_slots", "shift_number"):
120
+ if not faults.has(agent, kind):
121
+ continue
122
+ parts: List[Tuple[Dict[str, Any], Optional[Dict[str, Any]]]] = []
123
+ if reading.get("compound"):
124
+ parts = [(part, part) for part in reading.get("parts") or [] if part.get("kind")]
125
+ else:
126
+ parts = [(reading, reading)]
127
+ for holder, part in parts:
128
+ if not part.get("kind"):
129
+ continue
130
+ order = canonical.slots_for(str(part["kind"]))
131
+ slots, changed = faults.mutate_reading(agent, str(part["kind"]),
132
+ dict(part.get("slots") or {}), order)
133
+ if not changed:
134
+ continue
135
+ faults.fire(agent, kind)
136
+ try:
137
+ printed = canonical.print_geometry(str(part["kind"]), slots)
138
+ except canonical.ReadingError:
139
+ reading["math"] = ""
140
+ reading["status"] = "NOT COVERED"
141
+ reading["notes"].append({"reason": "no_frame", "kind": part["kind"], "detail": kind})
142
+ return
143
+ holder["slots"] = slots
144
+ holder["math"] = printed
145
+ reading["fault"] = kind
146
+ if reading.get("compound"):
147
+ reading["math"] = " ".join("%s." % str(item.get("math") or "").rstrip(".")
148
+ for item in reading.get("parts") or []
149
+ if str(item.get("math") or "").strip())
150
+ return
151
+ return
152
+
153
+
154
+ def _reading_node(agent: str, reader: Any, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
155
+ """Shared body of the two reader nodes: read the question, keep the reading, claim the numbers."""
156
+ dossier, turn, tick, rcpt = protocol.start(incoming)
157
+ question = str(dossier.get("question", ""))
158
+ lang = str(dossier.get("lang") or "")
159
+ direct = canonical.direct(question)
160
+ if direct is not None:
161
+ dossier["reading_direct"] = direct
162
+ reading = direct
163
+ else:
164
+ reading = _read(lang, reader, question)
165
+ _apply_reader_fault(node_id, reading)
166
+ dossier[agent] = reading
167
+ decls, asserts, claimed = _reader_claim(reading, question)
168
+ summary = "%s: %s %s" % (node_id, reading.get("status"), reading.get("math") or "")
169
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
170
+
171
+
172
+ def step_reader_a(incoming: Dict[str, Any], node_id: str = "reader_a") -> Dict[str, Any]:
173
+ """Reader A: surface patterns of the variety, reading left to right."""
174
+ return _reading_node("reading_a", read_a, incoming, node_id)
175
+
176
+
177
+ def step_reader_b(incoming: Dict[str, Any], node_id: str = "reader_b") -> Dict[str, Any]:
178
+ """Reader B: the frame of the problem kind and the marker phrases sitting in its gaps."""
179
+ return _reading_node("reading_b", read_b, incoming, node_id)
180
+
181
+
182
+ def step_equivalence(incoming: Dict[str, Any], node_id: str = "equivalence") -> Dict[str, Any]:
183
+ """Are the two readings one problem? The answer carries the SMT2 program that proves it."""
184
+ dossier, turn, tick, rcpt = protocol.start(incoming)
185
+ if faults.has(node_id, "rubber_stamp"):
186
+ faults.fire(node_id, "rubber_stamp")
187
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_a") or {}
188
+ else:
189
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_b") or {}
190
+ direct = dossier.get("reading_direct")
191
+ if direct is not None:
192
+ first, second = direct, dict(dossier.get("reading_b") or direct)
193
+ comparison = compare.equivalence(first, second)
194
+ dossier["compare"] = comparison
195
+ if first.get("math") and (comparison["same"] or not second.get("math")):
196
+ dossier["sent"] = comparison["left"] or str(first["math"])
197
+ elif second.get("math") and not first.get("math"):
198
+ dossier["sent"] = comparison["right"] or str(second["math"])
199
+ summary = "equivalence: %s (%s)" % ("same" if comparison["same"] else "not the same problem",
200
+ comparison["why"])
201
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
202
+ comparison["declarations"], comparison["assertions"], comparison["claimed"])
203
+
204
+
205
+ def step_coverage(incoming: Dict[str, Any], node_id: str = "coverage") -> Dict[str, Any]:
206
+ """Did the readings keep every number the user wrote, and in the same multiset?"""
207
+ dossier, turn, tick, rcpt = protocol.start(incoming)
208
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
209
+ if dossier.get("reading_direct") is not None:
210
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
211
+ if faults.has(node_id, "rubber_stamp"):
212
+ faults.fire(node_id, "rubber_stamp")
213
+ claim = {"ok": True, "wrote": [], "kept": [], "missing": [], "added": [],
214
+ "declarations": ["(declare-const wrote_0 Real)"], "assertions": ["(assert (= wrote_0 0))"],
215
+ "claimed": "sat"}
216
+ else:
217
+ claim = coverage.coverage_claim(str(dossier.get("question", "")), [r for r in readings if r])
218
+ dossier["coverage"] = claim
219
+ summary = "coverage: %s (%d numbers)" % ("kept" if claim["ok"] else "not kept", len(claim["wrote"]))
220
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
221
+ claim["declarations"], claim["assertions"], claim["claimed"])
222
+
223
+
224
+ def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]:
225
+ """Ask the geometry bundle, in its own process, about the text the readers agreed on."""
226
+ dossier, turn, tick, rcpt = protocol.start(incoming)
227
+ sentence = str(dossier.get("sent") or "")
228
+ if not sentence:
229
+ dossier["math"] = invoker.unavailable("no text was agreed on")
230
+ summary = "invoker: nothing to ask the geometry bundle"
231
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
232
+ ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat")
233
+ verdict = invoker.solve(sentence)
234
+ dossier["math"] = verdict
235
+ wrote = compare.sorted_numbers(sentence)
236
+ echo = compare.sorted_numbers(str(verdict.get("problem_math") or ""))
237
+ decls, asserts = compare.elementwise(wrote, echo, "asked")
238
+ summary = "invoker: %s (%s)" % (verdict.get("status"), verdict.get("answer_text") or "no answer")
239
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
240
+ decls, asserts + ["(assert (= 1 1))"] if not decls else asserts,
241
+ "sat" if wrote == echo else "unsat")
242
+
243
+
244
+ def _agreed_reading(dossier: Dict[str, Any]) -> Dict[str, Any]:
245
+ """The reading whose sentence this stratum sent to the geometry bundle.
246
+
247
+ The echo of the bundle is a statement about one sentence, so it is checked against that
248
+ sentence and not against a reader that abstained. When only one of the two readers read the
249
+ question, the reading that carried the sentence is the one with standing here; a reading with
250
+ no sentence at all has nothing to be echoed and never vetoes.
251
+ """
252
+ sent = str(dossier.get("sent") or "")
253
+ for key in ("reading_direct", "reading_a", "reading_b"):
254
+ item = dossier.get(key) or {}
255
+ if sent and str(item.get("math") or "") == sent:
256
+ return item
257
+ for key in ("reading_a", "reading_b", "reading_direct"):
258
+ item = dossier.get(key) or {}
259
+ if item.get("math"):
260
+ return item
261
+ return {}
262
+
263
+
264
+ def step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]:
265
+ """The geometry verdict enters this stratum here; the echo it carries is checked, not trusted."""
266
+ dossier, turn, tick, rcpt = protocol.start(incoming)
267
+ reading = _agreed_reading(dossier)
268
+ math_verdict = dict(dossier.get("math") or {})
269
+ agreed = str(dossier.get("sent") or "")
270
+ echo = str(math_verdict.get("problem_math") or "")
271
+ if echo:
272
+ matches = coverage.echo_matches(reading, math_verdict)
273
+ decls, asserts = compare.elementwise(compare.sorted_numbers(agreed), compare.sorted_numbers(echo), "echo")
274
+ claimed = "sat" if matches else "unsat"
275
+ else:
276
+ # The bundle answered no text at all: there is nothing to compare, and the honest claim is
277
+ # the empty one, which is satisfiable. A node that wanted to look busy here would be
278
+ # asserting something it has no evidence about.
279
+ matches = True
280
+ decls, asserts, claimed = [], ["(assert (= 1 1))"], "sat"
281
+ if faults.has(node_id, "tamper_math") and echo:
282
+ tampered, changed = faults.mutate_sentence(node_id, echo)
283
+ if changed:
284
+ faults.fire(node_id, "tamper_math")
285
+ math_verdict["problem_math"] = tampered
286
+ math_verdict["fault"] = "tamper_math"
287
+ dossier["math"] = math_verdict
288
+ dossier["echo_ok"] = bool(matches)
289
+ summary = "boundary: %s echoed=%s" % (math_verdict.get("status"), "yes" if matches else "no")
290
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
291
+ decls, asserts, claimed)
292
+
293
+
294
+ def step_adversary(incoming: Dict[str, Any], node_id: str = "adversary") -> Dict[str, Any]:
295
+ """Re-derive what the previous nodes asserted, and write the cap as an inequality to refute."""
296
+ dossier, turn, tick, rcpt = protocol.start(incoming)
297
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
298
+ if dossier.get("reading_direct") is not None:
299
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
300
+ comparison = dossier.get("compare")
301
+ math_verdict = dossier.get("math") or {}
302
+ cover = dossier.get("coverage")
303
+ if faults.has(node_id, "rubber_stamp"):
304
+ faults.fire(node_id, "rubber_stamp")
305
+ echo_ok = True
306
+ else:
307
+ echo_ok = True
308
+ if math_verdict.get("problem_math"):
309
+ for item in [_agreed_reading(dossier)] + [one for one in readings if one.get("math")]:
310
+ if item.get("math") and not coverage.echo_matches(item, math_verdict):
311
+ echo_ok = False
312
+ dossier["echo_ok"] = bool(echo_ok)
313
+ state = decide.state_of(readings, comparison, cover, math_verdict if math_verdict.get("status") else None,
314
+ dossier.get("reading_direct"), echo_ok)
315
+ ceiling = decide.CEILING[state]
316
+ shown = min(ceiling, int(math_verdict.get("assurance", 0) or 0))
317
+ dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown,
318
+ "math_assurance": int(math_verdict.get("assurance", 0) or 0)}
319
+ decls, asserts, claimed = _cap_claim(shown, ceiling)
320
+ summary = "adversary: ceiling %d, shown %d, echo %s" % (ceiling, shown, "ok" if echo_ok else "mismatch")
321
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
322
+
323
+
324
+ def step_arbiter(incoming: Dict[str, Any], node_id: str = "arbiter") -> Dict[str, Any]:
325
+ """Decide, cap, and answer in the language the user wrote in."""
326
+ dossier, turn, tick, rcpt = protocol.start(incoming)
327
+ final = decide.decide(dossier)
328
+ if faults.has(node_id, "force_assurance"):
329
+ faults.fire(node_id, "force_assurance")
330
+ final = decide.raise_assurance(final, 3)
331
+ dossier["final"] = final
332
+ dossier["reply"] = render.reply(dossier, final)
333
+ ceiling = int(final.get("ceiling", 0) or 0)
334
+ decls, asserts, claimed = _cap_claim(int(final.get("assurance", 0) or 0), ceiling)
335
+ summary = "arbiter: %s (assurance %d) %s" % (final["state"], final["assurance"], final["answer"] or "")
336
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
337
+
338
+
339
+ STEPS = {
340
+ "reader_a": step_reader_a,
341
+ "reader_b": step_reader_b,
342
+ "equivalence": step_equivalence,
343
+ "coverage": step_coverage,
344
+ "invoker": step_invoker,
345
+ "boundary": step_boundary,
346
+ "adversary": step_adversary,
347
+ "arbiter": step_arbiter,
348
+ }
349
+
350
+
351
+ def run_step(role: str, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
352
+ """Run one role, containing any unexpected exception as a crash entry in the dossier.
353
+
354
+ A node that crashes must not stop the session: the arbiter then reports the state NONE with
355
+ zero assurance, so the user is never left with a half-built answer and never with an invented
356
+ one either.
357
+ """
358
+ try:
359
+ return STEPS[role](incoming, node_id)
360
+ except Exception as exc: # noqa: BLE001 - containment is the whole point of this wrapper
361
+ dossier, turn, tick, rcpt = protocol.start(incoming)
362
+ dossier.setdefault("crash", {})[role] = "%s: %s" % (type(exc).__name__, str(exc)[:120])
363
+ return protocol.envelope(node_id, rcpt, turn, tick, "%s crashed" % role, "Crashed", dossier,
364
+ [], ["(assert true)"], "sat")
lggeostratum/canonical.py ADDED
@@ -0,0 +1,662 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The canonical sentence: one printer for the geometry language, shared by both readers.
2
+
3
+ A reading is a mapping from a surface sentence to **one sentence of the geometry language**,
4
+ which is what the geometry layer is handed. The printers here are deliberately small and
5
+ exhaustive: each covered kind has a fixed template, so the only freedom a reader has is how it
6
+ decided the 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 sentence forms of the
9
+ geometry language: the Euclidean track, with declared points, lines and circles, the classic
10
+ constructions (midpoint, centroid, circumcenter, intersection) and the coordinate predicates
11
+ (collinearity, perpendicularity, parallelism, congruence, right angle, betweenness, incidence on
12
+ a circle). The rest of the geometry language -- conics, the spherical and the hyperbolic track,
13
+ the exact predicates over the rational plane -- stays available through the direct mode: a
14
+ sentence already written in the geometry language is passed through untouched, declarations
15
+ included.
16
+
17
+ A geometry problem is a sequence of sentences, each ending with a full stop. This module always
18
+ prints the terminating full stop, and only this module writes it: a reader that lost the stop has
19
+ lost the shape of the language, and the coverage node counts it.
20
+ """
21
+
22
+ import re
23
+ from typing import Any, Dict, List, Optional, Tuple
24
+
25
+ KINDS = ("define_point", "define_line", "define_circle", "assume", "mid", "centroid",
26
+ "circumcentre", "intersect", "find_circumcircle", "find_intersect", "find_tangents",
27
+ "find_image", "collinear", "perp", "par", "cong", "right", "between", "oncircle")
28
+
29
+ # For each kind, the accepted slot sets and the template each one prints to. A kind with two
30
+ # forms (the circle given by a center and a radius, or by three points; the assumption about
31
+ # three points not being collinear, or about two points being distinct) has two entries, and a
32
+ # reader that cannot tell which one the sentence describes reports the pair as ambiguous. The slots
33
+ # X and Y hold a list of point names: the geometry language states a collinearity, a circumcircle
34
+ # and an assumption about a list it writes in one breath ("A, B and C"), so the list arrives from a
35
+ # reader as one region and is printed as one list.
36
+ TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = {
37
+ "define_point": [(("P", "V"), "Point {P} = {V}")],
38
+ "define_line": [(("E", "P", "Q"), "Line {E} through {P} and {Q}")],
39
+ "define_circle": [(("E", "P", "V"), "Circle {E} with center {P} and radius squared {V}"),
40
+ (("E", "X"), "Circle {E} through {X}")],
41
+ "assume": [(("X",), "Assume {X} are not collinear"),
42
+ (("Y",), "Assume {Y} are distinct")],
43
+ "mid": [(("T", "P", "Q"), "Let {T} be the midpoint of {P} and {Q}")],
44
+ "centroid": [(("T", "X"), "Let {T} be the centroid of triangle {X}")],
45
+ "circumcentre": [(("T", "X"), "Let {T} be the circumcenter of triangle {X}")],
46
+ "intersect": [(("T", "L", "K"), "Let {T} be the intersection of {L} and {K}")],
47
+ "find_circumcircle": [(("X",), "Find the circumcircle of {X}")],
48
+ "find_intersect": [(("L", "K"), "Find the intersection of {L} and {K}")],
49
+ "find_tangents": [(("P", "E"), "Find the tangents from {P} to circle {E}")],
50
+ "find_image": [(("P", "E"), "Find the image of {P} under {E}")],
51
+ "collinear": [(("X",), "Prove that {X} are collinear")],
52
+ "perp": [(("L", "K"), "Prove that {L} is perpendicular to {K}")],
53
+ "par": [(("L", "K"), "Prove that {L} is parallel to {K}")],
54
+ "cong": [(("L", "K"), "Prove that {L} is congruent to {K}")],
55
+ "right": [(("A",), "Prove that angle {A} is a right angle")],
56
+ "between": [(("P", "Q", "R"), "Prove that {P} lies between {Q} and {R}")],
57
+ "oncircle": [(("P", "Q", "R"), "Prove that {P} lies on the circle with center {Q} through {R}")],
58
+ }
59
+
60
+ SLOT_ORDER = {kind: [slot for slot, _template in variants]
61
+ for kind, variants in TEMPLATES.items()}
62
+
63
+ VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [slots for slots, _ in variants]
64
+ for kind, variants in TEMPLATES.items()}
65
+
66
+ _POINT = re.compile(r"[A-Z][A-Za-z0-9_]*")
67
+
68
+ # A line or an angle written as one word: "AB" is the line through A and B, "ABC" is the angle at
69
+ # B. The split is exact -- two names, three names -- so a name that is not exactly that many names
70
+ # stays the name it is.
71
+ _GLUED_PAIR = re.compile(r"([A-Z][a-z0-9_]*)([A-Z][a-z0-9_]*)")
72
+ _GLUED_TRIPLE = re.compile(r"([A-Z][a-z0-9_]*)([A-Z][a-z0-9_]*)([A-Z][a-z0-9_]*)")
73
+
74
+
75
+ class ReadingError(ValueError):
76
+ """A reading cannot be printed as a sentence of the geometry language."""
77
+
78
+
79
+ def print_geometry(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (),
80
+ keywords: Tuple[str, ...] = ()) -> str:
81
+ """Print one reading as a sentence of the geometry language, full stop included.
82
+
83
+ The slot values arrive as the two readers wrote them, and the two of them write the same
84
+ value differently: reader A cuts a slot between the words of a surface pattern, reader B reads
85
+ the whole region between two joints of the language, keyword and conjunctions included. The
86
+ normalisation here is where that difference is settled, and it is shared for exactly the same
87
+ reason the two formalizers of the geometry topology share one grammar: a value the two readings
88
+ print to different sentences is not one reading, and a value that is not a name of the
89
+ geometry language is refused out loud rather than carried into the geometry layer.
90
+
91
+ ``joins`` are the conjunctions of the variety (Italian ``e``, Chinese ``he``) and ``keywords``
92
+ the words with which that variety says *line*, *circle*, *angle*, *segment*: both lists come
93
+ from the lexicon of the variety, because a name of a figure written by a person in their own
94
+ language arrives together with the words around it.
95
+ """
96
+ values = normalize_slots(kind, slots, joins, keywords)
97
+ wanted = tuple(name for name in _order(kind) if name in values and values[name] != "")
98
+ for slots_set, template in TEMPLATES[kind]:
99
+ if set(slots_set) == set(wanted):
100
+ missing = [name for name in slots_set if not values.get(name, "").strip()]
101
+ if missing:
102
+ raise ReadingError("the %s reading has no value for %s" % (kind, ", ".join(missing)))
103
+ extra = [name for name in values if name not in slots_set]
104
+ if extra:
105
+ raise ReadingError("the %s reading has no slot %s" % (kind, ", ".join(extra)))
106
+ body = template.format(**{name: values[name] for name in slots_set})
107
+ return tidy(body) + "."
108
+ raise ReadingError("the %s reading fills the slots %s, which is not a form of the kind"
109
+ % (kind, ", ".join(sorted(wanted))))
110
+
111
+
112
+ # The sibling bundle of this project is printed by a function named print_math; the geometry layer
113
+ # is printed by this one, and the alias keeps the readers of the two bundles interchangeable.
114
+ print_math = print_geometry
115
+
116
+
117
+ def is_name(token: str) -> bool:
118
+ """Whether a token is a point name of the geometry language."""
119
+ return bool(_POINT.fullmatch(token))
120
+
121
+
122
+ # The rule table of the geometry bundle names a line, a circle, a transformation with a small
123
+ # letter. The atomiser of a variety sees that letter on its own, and the only thing telling it
124
+ # from a word of the variety is that no phrase of the lexicon claims it: both readers use this.
125
+ _ENTITY = re.compile(r"[a-z]")
126
+
127
+
128
+ def is_entity_name(token: str) -> bool:
129
+ """Whether a token is the name of a line, of a circle, of a transformation."""
130
+ return bool(_ENTITY.fullmatch(token))
131
+
132
+
133
+ def split_units(text: str, joins: Tuple[str, ...] = (),
134
+ keywords: Tuple[str, ...] = ()) -> List[List[str]]:
135
+ """The entities a slot region holds, as groups of tokens, in the order they were written.
136
+
137
+ A region of a geometry sentence is a string the reader cut out of the sentence, and inside it
138
+ the entities are separated by commas and by the conjunctions of the variety: ``the circle c
139
+ with center O`` and ``la circonferenza c con centro O`` cut to the same two entities once the
140
+ comma, the conjunction and the keyword of the entity are accounted for. A keyword of the
141
+ language opens the entity it introduces, and two names joined by a hyphen are one entity --
142
+ the line ``A-B`` and the angle ``A-B-C`` are written as single names by the geometry language
143
+ itself. A relation word (=, <, >) opens a unit too: no slot of the geometry language holds an
144
+ operator, so an operator always stands between two values of a region.
145
+ """
146
+ tokens: List[str] = []
147
+ for token in tidy(text).split(" "):
148
+ if token and token != "-":
149
+ tokens.append(token)
150
+ cut = {",", "and"}
151
+ separators = {fold_join(word) for word in joins} | cut
152
+ openers = set(keywords) | {fold_join(word) for word in keywords}
153
+ groups: List[List[str]] = []
154
+ current: List[str] = []
155
+ for token in tokens:
156
+ low = token.lower()
157
+ if token == "," or low == "and" or low in separators:
158
+ if current:
159
+ groups.append(current)
160
+ current = []
161
+ continue
162
+ if token and all(character in "=<>!" for character in token):
163
+ if current:
164
+ groups.append(current)
165
+ current = []
166
+ continue
167
+ if (low in keywords or fold_join(low) in openers) and not (
168
+ current and current[-1].lower() in openers):
169
+ if current:
170
+ groups.append(current)
171
+ current = []
172
+ current.append(token)
173
+ continue
174
+ current.append(token)
175
+ if current:
176
+ groups.append(current)
177
+ return groups
178
+
179
+
180
+ _JOIN_FOLD_CACHE: Dict[str, str] = {}
181
+
182
+
183
+ def fold_join(word: str) -> str:
184
+ """The comparison form of a conjunction of a variety (``fold`` from the atomiser)."""
185
+ if word not in _JOIN_FOLD_CACHE:
186
+ from .segment import fold
187
+ _JOIN_FOLD_CACHE[word] = fold(word)
188
+ return _JOIN_FOLD_CACHE[word]
189
+
190
+
191
+ def _unit_is_hyphenated(unit: List[str]) -> bool:
192
+ return len(unit) > 1 and all("-" in token and _POINT.fullmatch(part)
193
+ for token in unit for part in token.split("-"))
194
+
195
+
196
+ # Which keyword of the geometry language names the entity held by the entity slot of each kind:
197
+ # a tangency is taken to a *circle*, the image of a point is taken under a *transformation*, and
198
+ # the declaration of a line or of a circle names that line or circle.
199
+ ENTITY_KEYWORD_FOR = {"define_line": "line", "define_circle": "circle",
200
+ "find_tangents": "circle", "find_image": "transformation"}
201
+
202
+
203
+ def kind_entity_keyword(kind: str, slot: str = "E") -> str:
204
+ """The figure the entity slot of a kind names, so that the word of the variety can be read off."""
205
+ keyword = ENTITY_KEYWORD_FOR.get(kind)
206
+ if keyword is None:
207
+ raise ReadingError("the kind %s has no entity slot" % kind)
208
+ return keyword
209
+
210
+
211
+ # Which word of the geometry language introduces a line slot: a congruence is stated of two
212
+ # *segments*, a perpendicularity and a parallelism of two *lines*, and the rule of the language
213
+ # asks for that word, so the slot carries it.
214
+ LINE_WORD_FOR = {"cong": "segment"}
215
+
216
+
217
+ def normalize_slot(kind: str, name: str, text: str, joins: Tuple[str, ...] = (),
218
+ keywords: Tuple[str, ...] = ()) -> str:
219
+ """One slot value, printed in the shape the geometry language wants for that slot.
220
+
221
+ A value that is not a name of the language -- a lowercase word standing where a point should
222
+ be, a bare letter that is not a name, an unbalanced expression -- is refused here, in one
223
+ place, by both readers.
224
+ """
225
+ slot_type = SLOT_TYPES.get(name)
226
+ if slot_type is None:
227
+ raise ReadingError("the kind %s has no slot %s" % (kind, name))
228
+ units = split_units(text, joins, keywords)
229
+ if slot_type == "value":
230
+ if len(units) != 1:
231
+ raise ReadingError("the value of %s %s holds %d entities"
232
+ % (kind, name, len(units)))
233
+ cleaned = value(" ".join(units[0]))
234
+ if cleaned is None:
235
+ raise ReadingError("the value of %s %s is not an expression of the language: %r"
236
+ % (kind, name, text))
237
+ return cleaned
238
+ if slot_type in ("points2", "points3"):
239
+ need = 2 if slot_type == "points2" else 3
240
+ names = point_names(text)
241
+ if len(names) == 1:
242
+ # One word holding the whole list: Chinese writes "ABC" for the three points of a
243
+ # triangle, and so does a person in Rome who types fast. The expansion is exact, so a
244
+ # run that is not exactly the number of names the slot holds stays one name.
245
+ glued = (_GLUED_TRIPLE if need == 3 else _GLUED_PAIR).fullmatch(names[0])
246
+ if glued:
247
+ names = list(glued.groups())
248
+ if len(names) != need:
249
+ raise ReadingError("the list slot %s of %s holds %d point names, not %d: %r"
250
+ % (name, kind, len(names), need, text))
251
+ return point_list(", ".join(names), need)
252
+ if slot_type == "point":
253
+ if len(units) != 1:
254
+ raise ReadingError("the point slot %s of %s holds %d entities"
255
+ % (name, kind, len(units)))
256
+ unit = units[0]
257
+ if _unit_is_hyphenated(unit):
258
+ return "-".join(unit)
259
+ # A variety says "the point A", and Chinese writes one character per morpheme, so the unit
260
+ # of a point slot is the name plus the words that introduce it. The name is what the
261
+ # geometry language wants, and a second name in the same unit is a second point, which the
262
+ # slot cannot hold.
263
+ names = [token for token in unit if is_name(token)]
264
+ if len(names) == 1:
265
+ return names[0]
266
+ raise ReadingError("the value of %s %s is not a point name: %r" % (kind, name, text))
267
+ if slot_type == "entity":
268
+ found = _entity_name(text, keywords)
269
+ if found is None:
270
+ raise ReadingError("the entity slot %s of %s is not a named entity: %r"
271
+ % (kind, name, text))
272
+ # The word of the figure belongs to the template, not to the slot: the geometry language
273
+ # has one rule per shape ("Circle c through ...", "to circle c", "under t"), so a slot that
274
+ # carried the word too would print it twice and stop matching its rule.
275
+ return found
276
+ if slot_type == "line":
277
+ word = LINE_WORD_FOR.get(kind, "line")
278
+ names = point_names(text)
279
+ if len(names) == 2:
280
+ return "%s %s-%s" % (word, names[0], names[1])
281
+ if len(names) == 1:
282
+ glued = _GLUED_PAIR.fullmatch(names[0])
283
+ if glued:
284
+ # The people who write geometry glue the two names of a line together: "AB" is the
285
+ # line through A and B, and it is the shape every variety puts in front of its word
286
+ # for line. A run that is not two names exactly stays a name, and the geometry
287
+ # layer decides whether it knows that line.
288
+ return "%s %s-%s" % (word, glued.group(1), glued.group(2))
289
+ else:
290
+ named = _entity_name(text, keywords)
291
+ if named is not None:
292
+ return "%s %s" % (word, named)
293
+ raise ReadingError("the value of %s %s is not a line of the language: %r"
294
+ % (kind, name, text))
295
+ if slot_type == "angle":
296
+ names = point_names(text)
297
+ if len(names) == 1:
298
+ glued = _GLUED_TRIPLE.fullmatch(names[0])
299
+ if glued:
300
+ names = list(glued.groups())
301
+ if len(names) == 3:
302
+ return "%s-%s-%s" % tuple(names)
303
+ raise ReadingError("the value of %s %s is not an angle of the language: %r"
304
+ % (kind, name, text))
305
+ raise ReadingError("the slot type %s is not one of the shapes of the language" % slot_type)
306
+
307
+
308
+ _WORD_NAME = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
309
+
310
+
311
+ def _entity_name(text: str, keywords: Tuple[str, ...] = ()) -> Optional[str]:
312
+ """The name of the figure an entity region holds, written as the geometry language writes it.
313
+
314
+ The name of a line, of a circle or of a transformation is the last word of the region a reader
315
+ found: a variety puts its own word for the figure in front of the name ("la retta r", the
316
+ characters for line and then the letter), and those words are words of its lexicon, which the
317
+ lexicon also lists as the words that introduce an entity, while the name is not one of them.
318
+ """
319
+ openers = set(keywords) | {fold_join(word) for word in keywords}
320
+ for token in reversed(tidy(text).split()):
321
+ if not _WORD_NAME.fullmatch(token):
322
+ continue
323
+ if token.lower() in openers or fold_join(token) in openers:
324
+ continue
325
+ return token.lower()
326
+ return None
327
+
328
+
329
+ def normalize_slots(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (),
330
+ keywords: Tuple[str, ...] = ()) -> Dict[str, str]:
331
+ """Every slot of a reading, normalised to the shape of the geometry language."""
332
+ return {name: normalize_slot(kind, name, text, joins, keywords)
333
+ for name, text in sorted(slots.items()) if text and text.strip()}
334
+
335
+
336
+ def _order(kind: str) -> List[str]:
337
+ if kind not in TEMPLATES:
338
+ raise ReadingError("the kind %s is not one of the kinds the reading layer covers" % kind)
339
+ seen: List[str] = []
340
+ for slots in VARIANTS[kind]:
341
+ for name in slots:
342
+ if name not in seen:
343
+ seen.append(name)
344
+ return seen
345
+
346
+
347
+ def slots_for(kind: str) -> List[str]:
348
+ return _order(kind)
349
+
350
+
351
+ # The words the geometry language itself uses to hold a slot in place. Reader B reads a sentence
352
+ # by these joints, so it needs them as names, not as text inside a template.
353
+ _MARKER_PHRASE = {
354
+ "eq": "=",
355
+ "not_collinear": "are not collinear",
356
+ "distinct": "are distinct",
357
+ "let_mid": "be the midpoint of",
358
+ "let_centroid": "be the centroid of triangle",
359
+ "let_orthocentre": "be the orthocenter of triangle",
360
+ "let_circumcentre": "be the circumcenter of triangle",
361
+ "let_intersect": "be the intersection of",
362
+ "find_circumcircle": "the circumcircle of",
363
+ "find_intersect": "the intersection of",
364
+ "find_tangents": "the tangents from",
365
+ "to_entity": "to circle",
366
+ "find_image": "the image of",
367
+ "under": "under",
368
+ "collinear": "are collinear",
369
+ "perp": "is perpendicular to",
370
+ "par": "is parallel to",
371
+ "cong": "is congruent to",
372
+ "right": "is a right angle",
373
+ "between": "lies between",
374
+ "oncircle": "lies on the circle with center",
375
+ "through": "through",
376
+ "center": "with center",
377
+ "radius_squared": "and radius squared",
378
+ }
379
+ # The conjunction that lists entities is deliberately absent here: it is a connective of the
380
+ # variety, not a joint of a form, and the gap it sits in is read as no joint at all.
381
+ _PHRASE_MARKER = {phrase: name for name, phrase in _MARKER_PHRASE.items()}
382
+
383
+ # The joint names, exported so that the lexicon and the two readers can share one list.
384
+ MARKER_NAMES = tuple(sorted(_MARKER_PHRASE))
385
+
386
+ # What kind of value each slot of the geometry language takes. A slot letter is a type here, and
387
+ # this is the one place where the two readers and the corpus can check a slot against the same
388
+ # shape: the reading layer never accepts a value that is not a name of the language.
389
+ SLOT_TYPES = {"P": "point", "Q": "point", "R": "point", "S": "point", "T": "point",
390
+ "E": "entity", "L": "line", "K": "line", "A": "angle", "V": "value",
391
+ "X": "points3", "Y": "points2"}
392
+
393
+ # The reason a reader reports when a slot holds something that is not a value of the language. A
394
+ # list of points is reported as a point problem, so that the lexicon of a variety has one word for
395
+ # what went wrong with a name and not one per list shape.
396
+ SLOT_REASON = {"points3": "point", "points2": "point"}
397
+
398
+
399
+ def slot_reason(name: str) -> str:
400
+ """The name of the shape a slot of this name expects, as a reader reports it."""
401
+ shape = SLOT_TYPES.get(name, "slot")
402
+ return SLOT_REASON.get(shape, shape)
403
+
404
+
405
+ def template_for(kind: str, variant: Tuple[str, ...]) -> str:
406
+ """The template a kind prints for one slot set."""
407
+ for slots, template in TEMPLATES[kind]:
408
+ if tuple(slots) == tuple(variant):
409
+ return template
410
+ raise ReadingError("the kind %s has no form with the slots %s" % (kind, " ".join(variant)))
411
+
412
+
413
+ _SLOT_LETTERS = "PQRSTKELOGYAXV"
414
+
415
+
416
+ def gap_markers(kind: str, variant: Tuple[str, ...]) -> List[Optional[str]]:
417
+ """The joints a form of the geometry language puts around its slots, in order.
418
+
419
+ The list has one entry per gap: before the first slot, between consecutive slots, after the
420
+ last one. ``None`` marks a gap with no joint, which is where the verb of the sentence sits in
421
+ every language. This is reader B's skeleton: the slots of a reading are the entities that
422
+ fall between those joints, and a joint may not be missing or out of order.
423
+ """
424
+ parts = re.split(r"\{([%s])\}" % _SLOT_LETTERS, template_for(kind, variant))
425
+ gaps: List[Optional[str]] = []
426
+ for index in range(0, len(parts), 2):
427
+ literal = parts[index]
428
+ if index == 0:
429
+ # The words the geometry language puts before its first slot are the claim of the
430
+ # problem ("Prove that", "Let", "Find"), never a joint: a reader is expected to find
431
+ # them as the verb of the sentence, in whatever order the variety writes them.
432
+ gaps.append(None)
433
+ continue
434
+ phrase = literal.strip().rstrip(".")
435
+ if not phrase or phrase in (",", "and"):
436
+ # Neither a comma nor the conjunction that lists the entities of a slot is a joint of
437
+ # the geometry language: both separate two entities inside one region, and reader B
438
+ # breaks that region with the same rule it uses on a run of names written with no word
439
+ # between them. The conjunction is a connective of the variety, listed with the words
440
+ # of "and", and never a marker of a frame.
441
+ gaps.append(None)
442
+ elif phrase in _PHRASE_MARKER:
443
+ gaps.append(_PHRASE_MARKER[phrase])
444
+ else:
445
+ raise ReadingError("the template of %s holds the words %r, which are not a joint "
446
+ "of the geometry language" % (kind, phrase))
447
+ return gaps
448
+
449
+
450
+ def marker_sequence(kind: str, variant: Tuple[str, ...]) -> List[str]:
451
+ """The joints of one form, named in the order the geometry language prints them."""
452
+ return [gap for gap in gap_markers(kind, variant) if gap is not None]
453
+
454
+
455
+ _HYPHEN_BETWEEN_NAMES = re.compile(r"(?<=[A-Za-z0-9_])\s*-\s*(?=[A-Za-z0-9_])")
456
+ _SPACE_BEFORE_CLOSE = re.compile(r"\s+(?=[,).])")
457
+ _SPACE_AFTER_OPEN = re.compile(r"\(\s+")
458
+ _SPACE_BEFORE_OPEN = re.compile(r"\s+(?=\()")
459
+
460
+
461
+ def tidy(text: str) -> str:
462
+ """One space between the words, none inside a coordinate, none around a name hyphen.
463
+
464
+ The geometry language tolerates whitespace anywhere between its words -- verified against the
465
+ geometry bundle itself, whose rules join the words of a keyword with spaces and collapse the
466
+ expressions inside a pair of parentheses -- so tidying never changes what the geometry layer
467
+ reads. It gives the two readers one normal form to compare, which matters because the two of
468
+ them glue the atoms of a slot differently: reader A joins what it found with spaces, reader B
469
+ reads the text between two joints as it stands.
470
+
471
+ What the normal form may not do is let two words fuse: ``line A - B`` is the line reference
472
+ ``A-B`` of the geometry language, and ``line AB`` would be another line, named ``AB``, so
473
+ every rule here removes spaces or leaves them, never moves a letter across a word boundary.
474
+ """
475
+ out = re.sub(r"\s+", " ", text).strip()
476
+ out = _HYPHEN_BETWEEN_NAMES.sub("-", out)
477
+ out = _SPACE_BEFORE_CLOSE.sub("", out)
478
+ out = _SPACE_AFTER_OPEN.sub("", out)
479
+ out = _SPACE_BEFORE_OPEN.sub(" ", out)
480
+ return out
481
+
482
+
483
+ def point_name(text: str) -> Optional[str]:
484
+ """A slot value that is exactly one point name of the geometry language, or ``None``."""
485
+ cleaned = tidy(text)
486
+ return cleaned if _POINT.fullmatch(cleaned) else None
487
+
488
+
489
+ _NAME_RUN = re.compile(r"[A-Z][A-Za-z0-9_]*(?:-[A-Z][A-Za-z0-9_]*)*")
490
+
491
+
492
+ def point_names(text: str) -> List[str]:
493
+ """The point names a region holds, in the order the sentence says them.
494
+
495
+ A list of points arrives with the words of a variety around it -- "i punti A, B e C", the
496
+ characters for triangle in front of the three names -- and those words are lowercase or written
497
+ in another script, so the names of the geometry language are picked out by their shape: a
498
+ capital letter, and a run of them joined by a hyphen when the reader found the names of a line
499
+ written together.
500
+ """
501
+ names: List[str] = []
502
+ for run in _NAME_RUN.findall(tidy(text)):
503
+ names.extend(part for part in run.split("-") if part)
504
+ return names
505
+
506
+
507
+ def point_list(text: str, count: Optional[int] = None) -> Optional[str]:
508
+ """A slot value that is a list of point names, printed the way the language writes them.
509
+
510
+ The geometry language writes a list of names as ``A, B and C`` and a pair as ``A and B``: the
511
+ reader collects the names it found, separated by commas or by the translated conjunction, and
512
+ this function prints the one list the language accepts. A pair joined by a hyphen is not a
513
+ list, it is a line, and it belongs to ``line_ref``.
514
+ """
515
+ names = [part for part in re.split(r"\s*(?:,|\band\b)\s*", tidy(text)) if part.strip()]
516
+ if not names or not all(_POINT.fullmatch(name) for name in names):
517
+ return None
518
+ if count is not None and len(names) != count:
519
+ return None
520
+ if len(names) == 1:
521
+ return names[0]
522
+ head = ", ".join(names[:-2])
523
+ tail = "%s and %s" % (names[-2], names[-1])
524
+ return "%s, %s" % (head, tail) if head else tail
525
+
526
+
527
+ _LINE_REF = re.compile(r"(?:line\s+)?([A-Z][A-Za-z0-9_]*)\s*-\s*([A-Z][A-Za-z0-9_]*)")
528
+ _NAMED_LINE = re.compile(r"line\s+([a-z][A-Za-z0-9_]*)")
529
+
530
+
531
+ def line_ref(text: str) -> Optional[str]:
532
+ """A slot value that is a line reference of the geometry language, or ``None``.
533
+
534
+ The language knows two forms: a named line ``line l`` and the line through two named points
535
+ ``line A-B``. The second one is how the geometry bundle writes the line of a side of a
536
+ triangle, and it is what a person says in every language they speak, so the readers hand it
537
+ over already shaped.
538
+ """
539
+ cleaned = tidy(text)
540
+ match = _LINE_REF.fullmatch(cleaned)
541
+ if match:
542
+ return "line %s-%s" % (match.group(1), match.group(2))
543
+ match = _NAMED_LINE.fullmatch(cleaned)
544
+ if match:
545
+ return "line %s" % match.group(1)
546
+ return None
547
+
548
+
549
+ def entity_name(text: str, keyword: str = "circle") -> Optional[str]:
550
+ """A slot value that is a named entity (circle, transformation), keyword included, or ``None``."""
551
+ match = re.fullmatch(r"%s\s+([a-z][A-Za-z0-9_]*)" % keyword, tidy(text))
552
+ if match:
553
+ return "%s %s" % (keyword, match.group(1))
554
+ return None
555
+
556
+
557
+ _ANGLE_REF = re.compile(r"([A-Z][A-Za-z0-9_]*)-([A-Z][A-Za-z0-9_]*)-([A-Z][A-Za-z0-9_]*)")
558
+
559
+
560
+ def angle_ref(text: str) -> Optional[str]:
561
+ """A slot value that is an angle reference ``A-B-C`` of the geometry language, or ``None``."""
562
+ match = _ANGLE_REF.fullmatch(tidy(text))
563
+ if match:
564
+ return "%s-%s-%s" % (match.group(1), match.group(2), match.group(3))
565
+ return None
566
+
567
+
568
+ def value(text: str) -> Optional[str]:
569
+ """A slot value that is a number or an expression of the geometry language, or ``None``.
570
+
571
+ Coordinates and radii are rational expressions over the parameters of a generic triangle:
572
+ ``9``, ``3/2``, ``u1`` and ``u2*u2 + u3*u3`` are all values the geometry bundle parses. The
573
+ check here is on the shape only -- brackets balanced, no stray character -- because the
574
+ meaning of an expression is decided by the geometry layer, not by the reading layer.
575
+ """
576
+ cleaned = tidy(text)
577
+ if not cleaned or not re.fullmatch(r"[A-Za-z0-9_+\-*/^()., ]+", cleaned):
578
+ return None
579
+ return cleaned if balanced(cleaned) else None
580
+
581
+
582
+ def balanced(text: str) -> bool:
583
+ """Every bracket of a sentence closed, and no doubled operator at the edges."""
584
+ depth = {"(": 0, "[": 0}
585
+ for ch in text:
586
+ if ch in depth:
587
+ depth[ch] += 1
588
+ elif ch == ")":
589
+ depth["("] -= 1
590
+ elif ch == "]":
591
+ depth["["] -= 1
592
+ if any(value < 0 for value in depth.values()):
593
+ return False
594
+ return all(value == 0 for value in depth.values())
595
+
596
+
597
+ # The leading words of the geometry language, copied from the rule table of the geometry bundle.
598
+ # The reading layer covers only part of them; the rest stays reachable through the direct mode.
599
+ GEOMETRY_COMMANDS = (
600
+ "point", "line", "circle", "rotation", "translation", "scaling", "reflection",
601
+ "transformation", "let", "assume", "find", "prove", "conic", "spherical", "hyperbolic",
602
+ )
603
+
604
+ # The words the geometry language itself uses, copied from the same rule table. A sentence that
605
+ # carries a lowercase word outside this list is not written in the geometry language, whatever
606
+ # else it looks like. This is the third copy of that spec (the geometry bundle parses with it,
607
+ # its grammar names it), and the direct mode is where the copies can disagree out loud.
608
+ GEOMETRY_WORDS = frozenset("""
609
+ point points line lines circle circles through with center radius squared rotation by about
610
+ translation scaling reflection across transformation is then let be the midpoint centroid
611
+ orthocenter circumcenter intersection assume are not collinear distinct find circumcircle
612
+ tangents from to power respect secant products along image under prove that perpendicular
613
+ parallel segment congruent lies on circle lies between angle right angles orientation whether
614
+ inside convex hull conic kind decomposition tangent polar at and or of triangle triangles
615
+ incenter excenters nine-point lemoine contact cosine cosines foot altitude sides spherical
616
+ hyperbolic law sines cosines duality sum exceeds pi less than two similar but congruent
617
+ between intersections parallels for as given a an over rational plane unit great the
618
+ """.split())
619
+
620
+ _NOT_GEOMETRY_CHARACTER = re.compile(r"[^A-Za-z0-9\s+\-*/^()\[\]<>=!|,.]")
621
+
622
+ # A problem text is a run of commands, and each command is one sentence: the premises of the
623
+ # figure first, the claim last. Chinese writes its full stop as its own character, and the
624
+ # atomiser folds that character to a space, so the split has to see it in the text itself.
625
+ _SENTENCE_SPLIT = re.compile(r"\.(?=\s|$)|\u3002|\u0964|\u0965")
626
+
627
+
628
+ def split_sentences(text: str) -> List[str]:
629
+ """The sentences of a geometry problem text, each without its terminating full stop."""
630
+ return [part.strip() for part in _SENTENCE_SPLIT.split(text) if part.strip()]
631
+
632
+
633
+ def direct(text: str) -> Optional[Dict[str, Any]]:
634
+ """A problem text already written in the geometry language, or ``None``.
635
+
636
+ The direct mode is the only way a user reaches the kinds the reading layer does not cover --
637
+ conics, the spherical and the hyperbolic track, the exact predicates -- and the only way an
638
+ untranslated text reaches the geometry layer: it fires only when the text ends with a full
639
+ stop, every one of its sentences starts with a keyword of the geometry language and carries
640
+ no lowercase word outside the vocabulary of that language. Declared points and named lines
641
+ are the reason single letter words are allowed: ``l`` and ``c`` are names, not prose. Nothing
642
+ is translated here, and the text is shown to the user as it arrived.
643
+ """
644
+ cleaned = tidy(text)
645
+ if not cleaned or not cleaned.endswith(".") or not cleaned[0].isupper():
646
+ return None
647
+ if _NOT_GEOMETRY_CHARACTER.search(cleaned):
648
+ return None
649
+ sentences = split_sentences(cleaned)
650
+ if not sentences:
651
+ return None
652
+ kinds: List[str] = []
653
+ for sentence in sentences:
654
+ words = re.findall(r"[A-Za-z]+", sentence)
655
+ if not words or words[0].lower() not in GEOMETRY_COMMANDS:
656
+ return None
657
+ kinds.append(words[0].lower())
658
+ for word in words[1:]:
659
+ if len(word) > 1 and word.lower() not in GEOMETRY_WORDS:
660
+ return None
661
+ return {"mode": "direct", "kind": kinds[0] if len(set(kinds)) == 1 else "problem",
662
+ "math": cleaned, "slots": {}, "sentences": len(sentences)}
lggeostratum/compare.py ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 text of the geometry language by different routes -- surface
4
+ patterns and marker frames -- and the topology only trusts the pair when the two texts are the same
5
+ 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 geometry bundle itself does between its independent provers.
8
+
9
+ The translation of the geometry language into algebra and into SMT2 is **not reimplemented here**.
10
+ The geometry bundle owns that account, and a second copy of it inside the reading layer would be a
11
+ third place where the meaning of the geometry language could be wrong without anyone noticing. So
12
+ this module loads the geometry bundle (:envvar:`LGSTRATUM_GEOMETRY_ROOT`, sibling folder
13
+ ``geometry`` by default), parses both texts with its parser, builds both algebraic models with its
14
+ model builder, and then states the claim ``the readings differ`` as SMT2 over the union of the two
15
+ models' variables: unsatisfiable means the two readings denote the same problem under every
16
+ assignment of the coordinates, which is the same ``unsat`` discipline the bundle applies to its own
17
+ provers when it asks whether a theorem holds.
18
+
19
+ Two consequences are deliberate and both are limits, not shortcuts:
20
+
21
+ * a text the geometry bundle cannot turn into a model (a sentence it refuses to parse, a
22
+ construction whose non degeneracy it cannot state) is reported ``unknown`` and the session treats
23
+ it as a dispute: the reading layer would rather abstain than assume two texts are equal;
24
+ * the SMT claim of this module is *about the readings*, never about the user's problem. The problem
25
+ itself is never decided here: the text is handed to the geometry bundle, whose verdict is shown
26
+ as it arrived.
27
+ """
28
+
29
+ import re
30
+ import sys
31
+ from typing import Any, Dict, List, Optional, Tuple
32
+
33
+ from . import canonical, invoker, segment
34
+
35
+ _geometry: Optional[Tuple[Any, Any, Any]] = None
36
+ _GEOMETRY_LOOKUP_ERROR: Optional[str] = None
37
+
38
+
39
+ def _geometry_modules() -> Tuple[Optional[Any], Optional[Any], Optional[Any], Optional[str]]:
40
+ """The geometry bundle's parser, model builder and SMT layer, or the reason they are absent.
41
+
42
+ The bundle is a package, so its parent folder goes on the import path and the package is
43
+ imported by the name it has on disk: this module reaches it the way a reader of the repository
44
+ would, never by copying a file of it into the reading layer.
45
+ """
46
+ global _geometry, _GEOMETRY_LOOKUP_ERROR
47
+ if _geometry is not None:
48
+ return _geometry[0], _geometry[1], _geometry[2], None
49
+ if _GEOMETRY_LOOKUP_ERROR is not None:
50
+ return None, None, None, _GEOMETRY_LOOKUP_ERROR
51
+ root = invoker.geometry_root()
52
+ if not (root / "__init__.py").is_file():
53
+ _GEOMETRY_LOOKUP_ERROR = "no geometry package at %s" % root
54
+ return None, None, None, _GEOMETRY_LOOKUP_ERROR
55
+ parent = str(root.parent)
56
+ if parent not in sys.path:
57
+ sys.path.insert(0, parent)
58
+ try:
59
+ from geometry import language, model # noqa: PLC0415 - importing the bundle is the point
60
+ from geometry.logic import smt
61
+ except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently
62
+ _GEOMETRY_LOOKUP_ERROR = "the geometry bundle could not be imported: %s" % type(exc).__name__
63
+ return None, None, None, _GEOMETRY_LOOKUP_ERROR
64
+ _geometry = (language, model, smt)
65
+ return language, model, smt, None
66
+
67
+
68
+ ONTOLOGY = "(set-option :timeout 8000)\n"
69
+
70
+ _DECLARED = re.compile(r"\(declare-(?:const|fun|sort)\s+([^\s()]+)")
71
+
72
+
73
+ def smt_referee(decls: List[str], asserts: List[str]) -> str:
74
+ """Re-run one claim of an envelope the way the orchestrator does, ontology first.
75
+
76
+ The geometry bundle exposes no referee of its own, so the reading layer runs the plain solver
77
+ over the same text the envelope carries: the declarations and assertions it printed, with a
78
+ declaration never repeated. The claim of an envelope is linear arithmetic about counters and
79
+ assurance levels, which needs no nonlinear engine; the problem itself is decided by the
80
+ geometry bundle, and this function never sees it.
81
+ """
82
+ try:
83
+ import z3 # noqa: PLC0415 - the referee of the orchestrator is the solver, not a copy of one
84
+ except ImportError:
85
+ return "unknown"
86
+ declared = set(_DECLARED.findall(ONTOLOGY))
87
+ kept: List[str] = []
88
+ for decl in decls:
89
+ match = _DECLARED.search(decl)
90
+ if match:
91
+ if match.group(1) in declared:
92
+ continue
93
+ declared.add(match.group(1))
94
+ kept.append(decl)
95
+ try:
96
+ solver = z3.Solver()
97
+ solver.from_string("\n".join([ONTOLOGY] + kept + list(asserts)))
98
+ result = solver.check()
99
+ return "sat" if result == z3.sat else "unsat" if result == z3.unsat else "unknown"
100
+ except Exception: # noqa: BLE001 - a claim the solver cannot read is reported, never guessed
101
+ return "error"
102
+
103
+
104
+ def numbers(text: str) -> List[str]:
105
+ """Every number written in a text, in order, digits normalised."""
106
+ return segment.numeric_literals(text)
107
+
108
+
109
+ def sorted_numbers(text: str) -> List[str]:
110
+ """The same numbers ordered by value, so a reordering of slots is not read as a change."""
111
+ return sorted(numbers(text), key=lambda value: (float(value), value))
112
+
113
+
114
+ def formalize(sentence: str) -> Optional[Dict[str, Any]]:
115
+ """The geometry bundle's own algebraic view of one canonical text, or ``None``.
116
+
117
+ The bundle states a problem as the conjunction of its hypotheses -- the coordinates, the
118
+ constructions, the non degeneracy of the figure -- and of the conditions of its goals. That
119
+ conjunction is what this function returns, as bare SMT2 expressions, together with the names of
120
+ the coordinates it speaks about. Nothing here computes a polynomial: the two calls to the
121
+ bundle are its parser and its model builder, the same two the provers of the bundle run.
122
+ """
123
+ language, model, _smt, _reason = _geometry_modules()
124
+ if language is None or model is None:
125
+ return None
126
+ try:
127
+ node = language.parse_problem(sentence)
128
+ built = model.build_model(node)
129
+ cond = built.hypothesis_cond()
130
+ for goal in getattr(built, "goals", []) or []:
131
+ cond = cond + goal.cond
132
+ names = [str(name) for name in (built.variable_names() or [])]
133
+ for name in cond.variables():
134
+ if name not in names:
135
+ names.append(name)
136
+ return {"conjuncts": cond.conjuncts(), "vars": names}
137
+ except Exception: # noqa: BLE001 - a text this module cannot formalize is a text to report
138
+ return None
139
+
140
+
141
+ def _formula(side: Dict[str, Any]) -> str:
142
+ """One SMT2 expression for the conjunction a side of the comparison stands on."""
143
+ parts = list(side.get("conjuncts") or [])
144
+ if not parts:
145
+ return "true"
146
+ if len(parts) == 1:
147
+ return parts[0]
148
+ return "(and %s)" % " ".join(parts)
149
+
150
+
151
+ def _smt_claim(smt: Any, left: Dict[str, Any], right: Dict[str, Any]) -> Tuple[List[str], List[str], str, str, Any]:
152
+ """SMT2 for ``the two readings differ``, and what the solver says about it.
153
+
154
+ The declarations and the assertion are one plain SMT2 program: an assignment of the coordinates
155
+ that satisfies one reading's problem and not the other's, in either direction. Unsatisfiable
156
+ means the two readings denote the same problem under every assignment, which is the discipline
157
+ the geometry bundle applies when it asks whether its own theorems hold. The program is what
158
+ travels in the envelope, so the referee of the orchestrator re-runs exactly this query and
159
+ cannot be told something else.
160
+ """
161
+ names: List[str] = []
162
+ for side in (left, right):
163
+ for name in side.get("vars", []):
164
+ if name not in names:
165
+ names.append(name)
166
+ decls = ["(declare-const %s Real)" % name for name in names]
167
+ first, second = _formula(left), _formula(right)
168
+ assertions = ["(assert (or (and %s (not %s)) (and %s (not %s))))" % (first, second, second, first)]
169
+ if smt is None:
170
+ return decls, assertions, "unknown", "unknown", None
171
+ try:
172
+ result = smt.check_smt(decls, assertions, SMT_TIMEOUT_MS)
173
+ except Exception: # noqa: BLE001 - a query the bundle cannot run is a query to report
174
+ return decls, assertions, "unknown", "unknown", None
175
+ status = str(getattr(result, "status", "unknown"))
176
+ if status == "unsat":
177
+ return decls, assertions, "unsat", "equivalent", None
178
+ if status == "sat":
179
+ return decls, assertions, "sat", "different", getattr(result, "model", None)
180
+ return decls, assertions, "unknown", "unknown", None
181
+
182
+
183
+ SMT_TIMEOUT_MS = 20000
184
+
185
+
186
+ def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]:
187
+ """The slots one reading actually filled, in the order the geometry language prints them."""
188
+ kind = str(reading.get("kind", ""))
189
+ slots = reading.get("slots") or {}
190
+ if kind not in canonical.TEMPLATES:
191
+ return ()
192
+ return tuple(name for name in canonical.slots_for(kind) if str(slots.get(name, "")).strip())
193
+
194
+
195
+ def equivalence(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:
196
+ """Compare two readings: one verdict, the SMT claim behind it, and what differs.
197
+
198
+ The numbers are looked at before the solver, and they are a veto: a problem with other numbers is
199
+ another problem, even when the two claims it states are both true.
200
+ """
201
+ left = canonical.tidy(str(a.get("math", "")))
202
+ right = canonical.tidy(str(b.get("math", "")))
203
+ detail: List[str] = []
204
+ wrote, kept = sorted_numbers(left), sorted_numbers(right)
205
+ if wrote != kept:
206
+ # A geometry problem is its figure, and the figure is written in numbers: two readings that
207
+ # wrote different numbers describe two different figures, and no solver query turns that into
208
+ # one problem stated twice. The query below compares claims, and two concrete claims can be
209
+ # equally true while speaking of different triangles, so the numbers are a veto here and not
210
+ # a note next to the solver's answer.
211
+ return {"same": False, "why": "numbers", "left": left, "right": right,
212
+ "detail": ["numbers %s vs %s" % (",".join(wrote), ",".join(kept))],
213
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
214
+
215
+ if a.get("kind") != b.get("kind"):
216
+ detail.append("kinds %s vs %s" % (a.get("kind"), b.get("kind")))
217
+ return {"same": False, "why": "kind", "left": left, "right": right, "detail": detail,
218
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
219
+ if variant_of(a) != variant_of(b):
220
+ detail.append("slots %s vs %s" % (",".join(variant_of(a)), ",".join(variant_of(b))))
221
+ return {"same": False, "why": "variant", "left": left, "right": right, "detail": detail,
222
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
223
+
224
+ if left and left == right:
225
+ return {"same": True, "why": "text", "left": left, "right": right, "detail": detail,
226
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None}
227
+
228
+ _language, _model, smt, reason = _geometry_modules()
229
+ first, second = formalize(left), formalize(right)
230
+ if first is None or second is None:
231
+ note = reason or "the geometry bundle gives no algebraic view of this text"
232
+ detail.append(note)
233
+ return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail,
234
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None,
235
+ "note": note}
236
+
237
+ decls, assertions, claimed, label, model = _smt_claim(smt, first, second)
238
+ if claimed == "unknown":
239
+ detail.append("the solver gave no answer about the two readings")
240
+ if label == "different":
241
+ detail.append("an assignment of the coordinates where the two readings disagree")
242
+ return {"same": label == "equivalent", "why": "smt" if label != "unknown" else "unknown",
243
+ "left": left, "right": right, "detail": detail,
244
+ "declarations": decls, "assertions": assertions, "claimed": claimed,
245
+ "model": ({key: str(value) for key, value in model.items()} if model else None)}
246
+
247
+
248
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
249
+ """Whether the reading kept every number the user wrote, and the SMT claim that says so."""
250
+ wrote = sorted_numbers(question)
251
+ kept = sorted_numbers(str(reading.get("math", "")))
252
+ decls, asserts = elementwise(wrote, kept, "keep")
253
+ ok = wrote == kept
254
+ return {
255
+ "ok": ok,
256
+ "wrote": wrote,
257
+ "kept": kept,
258
+ "missing": [value for value in wrote if value not in kept],
259
+ "added": [value for value in kept if value not in wrote],
260
+ "declarations": decls,
261
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
262
+ "claimed": "sat" if ok else "unsat",
263
+ }
264
+
265
+
266
+ def elementwise(left: List[str], right: List[str], prefix: str) -> Tuple[List[str], List[str]]:
267
+ """SMT2 declarations and assertions saying two lists of numbers are equal, item by item."""
268
+ if len(left) != len(right):
269
+ return [], ["(assert false)"]
270
+ decls: List[str] = []
271
+ asserts: List[str] = []
272
+ for index, (first, second) in enumerate(zip(left, right)):
273
+ name = "%s_%d" % (prefix, index)
274
+ decls.append("(declare-const %sa Real)" % name)
275
+ decls.append("(declare-const %sb Real)" % name)
276
+ asserts.append("(assert (= %sa %s))" % (name, first))
277
+ asserts.append("(assert (= %sb %s))" % (name, second))
278
+ asserts.append("(assert (= %sa %sb))" % (name, name))
279
+ return decls, asserts
280
+
281
+
282
+ def agrees_with_layer(reading: Dict[str, Any], geometry_verdict: Dict[str, Any]) -> bool:
283
+ """Did the geometry bundle answer the text the readers agreed on?
284
+
285
+ The geometry bundle echoes the problem it understood. That echo is an independent channel: a
286
+ node standing between the readers and the geometry layer can rewrite its own record, but it
287
+ cannot move the echo without moving numbers that were counted upstream.
288
+ """
289
+ echo = canonical.tidy(str(geometry_verdict.get("problem_math", "")))
290
+ agreed = canonical.tidy(str(reading.get("math", "")))
291
+ if not agreed or not echo:
292
+ return False
293
+ return echo == agreed and sorted_numbers(echo) == sorted_numbers(agreed)
294
+
295
+
296
+ def assurance_of(comparison: Dict[str, Any], readings: List[Dict[str, Any]],
297
+ coverage: Optional[Dict[str, Any]] = None) -> int:
298
+ """Reading assurance: how much of the answer the *reading* of the text warrants.
299
+
300
+ The scale is the one the geometry bundle uses, zero to three, and this function only ever
301
+ lowers it: two readings that agree and kept every number reach level two, a single reader
302
+ reaches level one, and no reading path reaches three, because reading a text written in a human
303
+ language is never the last word -- the geometry bundle holds level three for the theorem it
304
+ proved by two independent routes, and the assurance the user sees is the minimum of the two.
305
+ """
306
+ present = [reading for reading in readings if reading.get("math")]
307
+ if not present:
308
+ return 0
309
+ if coverage is not None and not coverage.get("ok", False):
310
+ return 0
311
+ if len(present) < 2:
312
+ return 1
313
+ return 2 if comparison.get("same") else 0
lggeostratum/corpus.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 prover -- it is the layer that
5
+ decides *which* sentence to hand to the geometry bundle and how much confidence to attach to it:
6
+
7
+ {"id": "it-collinear-1", "lang": "it",
8
+ "question": "A=(0,0), B=(2,0), C=(1,0). Dimostra che A, B e C sono allineati",
9
+ "expect": {"state": "AGREED", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). "
10
+ "Prove that A, B and C are collinear.",
11
+ "min_assurance": 1}}
12
+
13
+ ``state`` is the only mandatory key. ``sentence`` is compared after tidying, ``answer_contains`` is
14
+ a substring test on the answer the geometry bundle returned, and ``max_assurance`` is the ceiling a
15
+ negative item insists on: an item that ends in DISPUTED, AMBIGUOUS or NOT COVERED must show no
16
+ answer at all.
17
+
18
+ The corpus is the only place a shared translation error can surface: the two readers agree by
19
+ construction whenever both descriptions of a language carry the same mistake, so the gold sentences
20
+ are written from the language and not from the lexicon.
21
+ """
22
+
23
+ import json
24
+ from pathlib import Path
25
+ from typing import Any, Dict, List, Optional
26
+
27
+ from . import canonical, pipeline
28
+
29
+ ROOT = Path(__file__).resolve().parents[1]
30
+ PATH = ROOT / "problems" / "corpus.jsonl"
31
+
32
+
33
+ def load(path: Optional[Path] = None) -> List[Dict[str, Any]]:
34
+ """The corpus, one dictionary per line, skipping blank lines and comments."""
35
+ where = Path(path) if path else PATH
36
+ items: List[Dict[str, Any]] = []
37
+ for line in where.read_text(encoding="utf-8").splitlines():
38
+ text = line.strip()
39
+ if not text or text.startswith("#"):
40
+ continue
41
+ items.append(json.loads(text))
42
+ return items
43
+
44
+
45
+ def grade(item: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]:
46
+ """Compare one corpus expectation against one run, and say exactly what did not match."""
47
+ expect = item.get("expect") or {}
48
+ final = result.get("final") or {}
49
+ problems: List[str] = []
50
+ state = str(final.get("state", ""))
51
+ if expect.get("state") and expect["state"] != state:
52
+ problems.append("state %s, expected %s" % (state, expect["state"]))
53
+ if "sentence" in expect:
54
+ wanted = canonical.tidy(str(expect["sentence"]))
55
+ got = canonical.tidy(str((result.get("dossier") or {}).get("sent", "")))
56
+ if got != wanted:
57
+ problems.append("sentence %r, expected %r" % (got, wanted))
58
+ if "answer_contains" in expect:
59
+ answer = str(final.get("answer", ""))
60
+ if str(expect["answer_contains"]) not in answer:
61
+ problems.append("answer %r does not contain %r" % (answer, expect["answer_contains"]))
62
+ if "min_assurance" in expect and int(final.get("assurance", 0) or 0) < int(expect["min_assurance"]):
63
+ problems.append("assurance %s below %s" % (final.get("assurance"), expect["min_assurance"]))
64
+ if "max_assurance" in expect and int(final.get("assurance", 0) or 0) > int(expect["max_assurance"]):
65
+ problems.append("assurance %s above %s" % (final.get("assurance"), expect["max_assurance"]))
66
+ if expect.get("no_answer") and final.get("answer"):
67
+ problems.append("an answer was shown for an item that must show none")
68
+ if expect.get("referee_clean") and any(record["claimed"] != record["referee"]
69
+ for record in result.get("records") or []):
70
+ problems.append("a claim did not survive the referee")
71
+ return {"id": item.get("id", "?"), "lang": item.get("lang", "?"), "state": state,
72
+ "assurance": final.get("assurance", 0), "ok": not problems, "problems": problems}
73
+
74
+
75
+ def outcome(item: Dict[str, Any], call_geometry: bool = True,
76
+ fault_spec: Optional[List[str]] = None) -> Dict[str, Any]:
77
+ """Run one corpus item in memory and grade it."""
78
+ result = pipeline.ask(str(item.get("question", "")), str(item.get("lang", "")), fault_spec=fault_spec,
79
+ call_geometry=call_geometry)
80
+ verdict = grade(item, result)
81
+ verdict["records"] = result["records"]
82
+ verdict["dossier"] = result["dossier"]
83
+ verdict["reply"] = result["reply"]
84
+ return verdict
lggeostratum/coverage.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the reading kept, and what the geometry bundle says it settled.
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 geometry language,
7
+ and no number appeared there that the user did not write. A reader that merged two slots or
8
+ shifted a digit changes that multiset, and a sorted element by element equality over declared
9
+ reals says so;
10
+ * :func:`echo_matches` -- the geometry bundle 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 geometry layer can rewrite its own record, but it cannot
13
+ move the echo without moving numbers that were counted upstream.
14
+
15
+ Neither check decides geometry. 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(geometry_verdict: Dict[str, Any]) -> List[str]:
30
+ """The numbers of the problem the geometry bundle says it settled, ordered by value."""
31
+ return compare.sorted_numbers(canonical.tidy(str(geometry_verdict.get("problem_math", ""))))
32
+
33
+
34
+ def echo_matches(reading: Dict[str, Any], geometry_verdict: Dict[str, Any]) -> bool:
35
+ """Did the geometry bundle settle the sentence the readers agreed on?
36
+
37
+ A verdict that names no sentence at all -- the backend was off, or the geometry bundle 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 geometry 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(geometry_verdict.get("problem_math", "")).strip():
43
+ return True
44
+ return compare.agrees_with_layer(reading, geometry_verdict)
45
+
46
+
47
+ def coverage_claim(question: str, readings: List[Dict[str, Any]],
48
+ geometry_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 geometry
52
+ bundle 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 geometry_verdict is not None:
66
+ echo = echo_numbers(geometry_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
+ }
lggeostratum/decide.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 the
4
+ coverage node counted and what the geometry 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 geometry stratum uses for its own decision.
8
+
9
+ The rule the whole module exists to enforce:
10
+
11
+ assurance(shown) = min(assurance(geometry), 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 text the geometry bundle parses
15
+ itself, and the reading layer is where that step lives. A verdict is therefore never raised by the
16
+ stratum; the only direction it can move is down, and the adversary node writes the negation of that
17
+ 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 geometry bundle settled it
23
+ PASSTHROUGH the text was already written in the geometry language: nothing was translated
24
+ SINGLE one reader understood the sentence and the other abstained: the geometry bundle 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 geometry
27
+ bundle 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 geometry bundle says it settled 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 geometry bundle uses. Three is not in this
41
+ # table: it belongs to the geometry bundle alone.
42
+ CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0,
43
+ "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0}
44
+
45
+ # The verdicts of the bundle that carry an answer: the obligation was discharged, or the claim was
46
+ # shown false on a figure of the problem itself. Anything else -- a refusal, an objection, a session
47
+ # that stopped short -- is a verdict with no answer to show.
48
+ ANSWERING = ("VERIFIED", "SINGLE_PROVER", "REFUTED")
49
+
50
+
51
+ def reader_notes(readings: List[Dict[str, Any]]) -> List[str]:
52
+ """The reason keys the abstaining readers left behind, in reader order."""
53
+ notes: List[str] = []
54
+ for reading in readings:
55
+ for note in reading.get("notes") or []:
56
+ reason = note.get("reason") if isinstance(note, dict) else str(note)
57
+ if reason and reason not in notes:
58
+ notes.append(reason)
59
+ return notes
60
+
61
+
62
+ def state_of(readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
63
+ coverage: Optional[Dict[str, Any]], geometry_verdict: Optional[Dict[str, Any]],
64
+ direct: Optional[Dict[str, Any]] = None, echo_ok: Optional[bool] = None) -> str:
65
+ """The state of a session, from the evidence the nodes collected."""
66
+ present = [reading for reading in readings if reading.get("math")]
67
+ notes = reader_notes(readings)
68
+ if direct is not None:
69
+ return "PASSTHROUGH"
70
+ if geometry_verdict is not None and echo_ok is False:
71
+ return "TAMPERED"
72
+ if len(present) >= 2:
73
+ if comparison is None:
74
+ return "DISPUTED"
75
+ if coverage is not None and not coverage.get("ok", False):
76
+ return "DISPUTED"
77
+ return "AGREED" if comparison.get("same") else "DISPUTED"
78
+ if len(present) == 1:
79
+ # A lone witness has to hold the numbers the person wrote: a reading that lost one is not a
80
+ # weaker reading of the same problem, it is a different problem, and the ceiling of SINGLE is
81
+ # not a licence to answer it. This is the case the ablation of the topology uncovered: with
82
+ # one reader there is no second sentence to compare against, so the count of literals is what
83
+ # stands between a shifted number and an answer the gold does not accept.
84
+ if coverage is not None and not coverage.get("ok", False):
85
+ return "DISPUTED"
86
+ return "SINGLE"
87
+ if any(reason in AMBIGUOUS_REASONS for reason in notes):
88
+ return "AMBIGUOUS"
89
+ return "NOT COVERED"
90
+
91
+
92
+ def reasons_for(state: str, readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
93
+ coverage: Optional[Dict[str, Any]], geometry_verdict: Optional[Dict[str, Any]],
94
+ asked: bool = True) -> List[str]:
95
+ """The reason keys that explain a state, in the order a reader should read them."""
96
+ out: List[str] = []
97
+ for reason in reader_notes(readings):
98
+ if reason not in out:
99
+ out.append(reason)
100
+ if state == "DISPUTED":
101
+ if coverage is not None and not coverage.get("ok", False):
102
+ out.append("literal_count")
103
+ if comparison is not None and not comparison.get("same"):
104
+ out.append("disagree")
105
+ if comparison is not None and comparison.get("why") == "unknown":
106
+ out.append("geometry_unknown")
107
+ if comparison is not None and comparison.get("why") == "smt" and comparison.get("model"):
108
+ if "disagree" not in out:
109
+ out.append("disagree")
110
+ if state == "TAMPERED":
111
+ out.append("boundary")
112
+ if geometry_verdict is not None and geometry_verdict.get("referee_mismatch"):
113
+ out.append("referee")
114
+ if asked and geometry_verdict is not None and geometry_verdict.get("status") == "UNKNOWN":
115
+ out.append("geometry_unknown")
116
+ if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"):
117
+ out.append("no_geometry")
118
+ return out
119
+
120
+
121
+ def decide(dossier: Dict[str, Any]) -> Dict[str, Any]:
122
+ """One verdict for one session, with the assurance the user is allowed to see."""
123
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
124
+ if dossier.get("reading_direct"):
125
+ readings = [dossier["reading_direct"]]
126
+ comparison = dossier.get("compare")
127
+ coverage = dossier.get("coverage")
128
+ geometry_verdict = dossier.get("math")
129
+ direct = dossier.get("reading_direct")
130
+ echo_ok = dossier.get("echo_ok")
131
+
132
+ state = state_of(readings, comparison, coverage, geometry_verdict, direct, echo_ok)
133
+ ceiling = CEILING[state]
134
+ assurance = 0
135
+ answer_shown = ""
136
+ if state in ("AGREED", "SINGLE", "PASSTHROUGH") and geometry_verdict is not None:
137
+ # The geometry bundle answers at level three when two engines of its own and a witnessed
138
+ # figure stand behind every obligation, at level two when one prover stands alone or a
139
+ # counterexample refutes the claim, and at level zero when it refuses or stops short.
140
+ if geometry_verdict.get("status") in ANSWERING:
141
+ assurance = min(ceiling, int(geometry_verdict.get("assurance", 0) or 0))
142
+ else:
143
+ assurance = 0
144
+ answer_shown = geometry_verdict.get("answer_text") or ""
145
+ if assurance == 0:
146
+ answer_shown = ""
147
+ reasons = reasons_for(state, readings, comparison, coverage, geometry_verdict,
148
+ asked=bool(str(dossier.get("sent") or "")))
149
+ return {
150
+ "state": state,
151
+ "assurance": assurance,
152
+ "ceiling": ceiling,
153
+ "math_assurance": int((geometry_verdict or {}).get("assurance", 0) or 0),
154
+ "math_status": (geometry_verdict or {}).get("status"),
155
+ "answer": answer_shown,
156
+ "reasons": reasons,
157
+ "consulted_math": geometry_verdict is not None,
158
+ }
159
+
160
+
161
+ def raise_assurance(final: Dict[str, Any], claimed: int) -> Dict[str, Any]:
162
+ """The arbiter fault: an assurance above what the evidence supports (experiments only)."""
163
+ out = dict(final)
164
+ out["assurance"] = max(int(final.get("assurance", 0) or 0), int(claimed))
165
+ out["claimed_above_evidence"] = True
166
+ return out
lggeostratum/faults.py ADDED
@@ -0,0 +1,188 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 geometry language: a reader that writes another name or a shifted number must
9
+ produce something the geometry layer will happily solve. Otherwise the fault would be caught by the
10
+ geometry layer refusing to parse, and the experiment would measure nothing about the reading layer.
11
+
12
+ Catalogue
13
+ ---------
14
+ reader_a / reader_b : rename_slot, 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 geometry layer 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 = ["rename_slot", "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
+ # The geometry language has no slot a sentence could do without: every name sits in the frame that
42
+ # requires it. What a reader can do to a reading without leaving the language is therefore to write
43
+ # another name, to write one name where two stood, or to write another number.
44
+ _NAME = re.compile(r"[A-Z]")
45
+ _NUMBER = re.compile(r"\d+(?:\.\d+)?")
46
+ _ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
47
+
48
+
49
+ def configure(spec: Optional[Iterable[str]]) -> None:
50
+ _ACTIVE.clear()
51
+ del FIRED[:]
52
+ if spec is None:
53
+ return
54
+ if isinstance(spec, str):
55
+ spec = [s for s in spec.split(",") if s.strip()]
56
+ for item in spec:
57
+ _ACTIVE.add(item.strip())
58
+
59
+
60
+ def from_env() -> None:
61
+ configure(os.environ.get("LGSTRATUM_FAULTS", ""))
62
+
63
+
64
+ def has(agent: str, kind: str) -> bool:
65
+ return "%s:%s" % (agent, kind) in _ACTIVE
66
+
67
+
68
+ def fire(agent: str, kind: str) -> None:
69
+ label = "%s:%s" % (agent, kind)
70
+ if label not in FIRED:
71
+ FIRED.append(label)
72
+
73
+
74
+ def fired(agent: str) -> List[str]:
75
+ return [item for item in FIRED if item.split(":", 1)[0] == agent]
76
+
77
+
78
+ # ---------------------------------------------------------------------------
79
+ # Reading mutations (reader faults)
80
+ # ---------------------------------------------------------------------------
81
+ def _slots_with_numbers(slots: Dict[str, str], order: List[str]) -> List[str]:
82
+ return [name for name in order if _NUMBER.search(slots.get(name, ""))]
83
+
84
+
85
+ def _names(value: str) -> List[str]:
86
+ return [ch for ch in value if ch.isascii() and ch.isupper()]
87
+
88
+
89
+ def _rename_name(slots: Dict[str, str], order: List[str]) -> Optional[Dict[str, str]]:
90
+ """Write in the first slot that holds one a name the reading never used.
91
+
92
+ The letter is chosen among those absent from every slot, so the damaged sentence speaks of a
93
+ point the question never named: it stays inside the language, and it is no longer the figure the
94
+ person described.
95
+ """
96
+ used = set()
97
+ for value in slots.values():
98
+ used.update(_names(value))
99
+ fresh = ""
100
+ for letter in _ALPHABET:
101
+ if letter not in used:
102
+ fresh = letter
103
+ break
104
+ if not fresh:
105
+ return None
106
+ for name in order:
107
+ value = slots.get(name, "")
108
+ match = _NAME.search(value)
109
+ if match is None:
110
+ continue
111
+ changed = dict(slots)
112
+ changed[name] = value[:match.start()] + fresh + value[match.end():]
113
+ return changed
114
+ return None
115
+
116
+
117
+ def _twins(slots: Dict[str, str], order: List[str]) -> Optional[Tuple[str, str]]:
118
+ """The last two slots that hold a name: a reader that collapses them names one figure twice."""
119
+ holders = [name for name in order if _names(slots.get(name, ""))]
120
+ if len(holders) < 2:
121
+ return None
122
+ return holders[-2], holders[-1]
123
+
124
+
125
+ def mutate_reading(agent: str, kind: str, slots: Dict[str, str], order: List[str]) -> Tuple[Dict[str, str], bool]:
126
+ """Return a damaged copy of one reading, and whether anything was actually damaged.
127
+
128
+ ``order`` is the slot order of the form the reader chose, so the fault knows which slot holds a
129
+ name of a figure and which one holds the coordinates or the number the sentence is about.
130
+ """
131
+ from . import canonical
132
+
133
+ slots = dict(slots)
134
+ for kind_fault in CATALOG.get(agent, []):
135
+ if not has(agent, kind_fault):
136
+ continue
137
+ candidate = dict(slots)
138
+ if kind_fault == "rename_slot":
139
+ renamed = _rename_name(candidate, order)
140
+ if renamed is None:
141
+ continue
142
+ candidate = renamed
143
+ elif kind_fault == "merge_slots":
144
+ twins = _twins(candidate, order)
145
+ if twins is None:
146
+ continue
147
+ first, second = twins
148
+ candidate[second] = candidate[first]
149
+ elif kind_fault == "shift_number":
150
+ numbered = _slots_with_numbers(candidate, order)
151
+ if not numbered:
152
+ continue
153
+ owner = numbered[0]
154
+ match = _NUMBER.search(candidate[owner])
155
+ if match is None:
156
+ continue
157
+ bumped = _NUMBER.sub(lambda m: str(_next_number(m.group(0))), candidate[owner], count=1)
158
+ candidate[owner] = bumped
159
+ else:
160
+ continue
161
+ try:
162
+ canonical.print_math(kind, candidate)
163
+ except canonical.ReadingError:
164
+ continue
165
+ fire(agent, kind_fault)
166
+ return candidate, True
167
+ return slots, False
168
+
169
+
170
+ def _next_number(text: str) -> Any:
171
+ if "." in text:
172
+ return float(text) + 1.0
173
+ return int(text) + 1
174
+
175
+
176
+ # ---------------------------------------------------------------------------
177
+ # Sentence mutations (the boundary fault)
178
+ # ---------------------------------------------------------------------------
179
+ def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]:
180
+ """Change one number of a sentence of the geometry language, leaving it grammatical."""
181
+ if not has(agent, "tamper_math"):
182
+ return sentence, False
183
+ match = _NUMBER.search(sentence)
184
+ if match is None:
185
+ return sentence, False
186
+ damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():]
187
+ fire(agent, "tamper_math")
188
+ return damaged, True
lggeostratum/invoker.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The interface toward the geometry stratum: one subprocess call, no shared code.
2
+
3
+ The reading layer and the geometry layer are separate topologies of the same orchestrator. This
4
+ module is the whole of their coupling: it starts ``tools/geometry_runner.py`` of this bundle as a
5
+ separate process with the canonical text as its argument, asks for the machine readable outcome,
6
+ and copies that outcome. Nothing here imports a module of the geometry bundle, because a
7
+ translation layer that reaches inside the geometry it consults is a translation layer that can
8
+ silently change the geometry. The runner is a thin adapter, and the only place in this bundle
9
+ where the package ``geometry`` is loaded.
10
+
11
+ Two settings matter, and both are environment variables so no value is hardcoded in a second
12
+ place:
13
+
14
+ ``LGSTRATUM_GEOMETRY_ROOT`` the folder of the geometry bundle (default: ``geometry``, sibling
15
+ of this bundle, which is ``datasets/geometry`` inside the LingoLOGOS
16
+ repository)
17
+ ``LGSTRATUM_GEOMETRY_BACKEND`` ``subprocess`` (default) or ``none``; ``none`` refuses to call and
18
+ is what the reading layer tests use, so they can check the reading
19
+ without starting a whole geometry session
20
+ """
21
+
22
+ import json
23
+ import os
24
+ import subprocess
25
+ import sys
26
+ from pathlib import Path
27
+ from typing import Any, Dict, Optional
28
+
29
+ ROOT = Path(__file__).resolve().parents[1]
30
+ DEFAULT_TIMEOUT = 180
31
+
32
+
33
+ def geometry_root() -> Path:
34
+ override = os.environ.get("LGSTRATUM_GEOMETRY_ROOT", "").strip()
35
+ if override:
36
+ return Path(override)
37
+ return ROOT.parent / "geometry"
38
+
39
+
40
+ def backend() -> str:
41
+ return (os.environ.get("LGSTRATUM_GEOMETRY_BACKEND", "subprocess") or "subprocess").strip().lower()
42
+
43
+
44
+ def timeout_seconds() -> int:
45
+ try:
46
+ return max(5, int(os.environ.get("LGSTRATUM_GEOMETRY_TIMEOUT", DEFAULT_TIMEOUT)))
47
+ except ValueError:
48
+ return DEFAULT_TIMEOUT
49
+
50
+
51
+ def unavailable(reason: str) -> Dict[str, Any]:
52
+ return {"ok": False, "error": reason, "status": "UNKNOWN", "assurance": 0, "answer": None,
53
+ "answer_text": "", "problem_math": "", "reasons": [], "solver": None, "detected": []}
54
+
55
+
56
+ def solve(text: str) -> Dict[str, Any]:
57
+ """Ask the geometry bundle one text of the geometry language, and return its verdict unchanged."""
58
+ if backend() == "none":
59
+ return unavailable("the geometry backend is disabled by LGSTRATUM_GEOMETRY_BACKEND")
60
+ script = ROOT / "tools" / "geometry_runner.py"
61
+ if not script.is_file():
62
+ return unavailable("no tools/geometry_runner.py in this bundle")
63
+ try:
64
+ done = subprocess.run(
65
+ [sys.executable, str(script), "--json", text],
66
+ cwd=str(ROOT), capture_output=True, timeout=timeout_seconds())
67
+ except subprocess.TimeoutExpired:
68
+ return unavailable("the geometry bundle did not answer within %d seconds" % timeout_seconds())
69
+ except OSError as exc:
70
+ return unavailable("the geometry bundle could not be started: %s" % exc)
71
+ text_out = done.stdout.decode("utf-8", "replace")
72
+ if done.returncode != 0 and not text_out.strip():
73
+ return unavailable("the geometry bundle exited with %d: %s"
74
+ % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200]))
75
+ return outcome(text_out, done.returncode)
76
+
77
+
78
+ def outcome(text: str, returncode: int = 0) -> Dict[str, Any]:
79
+ """Extract the verdict of a geometry session from the JSON the runner printed."""
80
+ try:
81
+ parsed = json.loads(text)
82
+ except ValueError:
83
+ return unavailable("the geometry bundle printed something that is not JSON (exit %d)" % returncode)
84
+ final = parsed.get("final") if isinstance(parsed, dict) else None
85
+ if not isinstance(final, dict):
86
+ return unavailable("the geometry bundle printed no verdict (exit %d)" % returncode)
87
+ referee = parsed.get("referee") if isinstance(parsed.get("referee"), list) else []
88
+ mismatched = [entry for entry in referee
89
+ if isinstance(entry, dict) and entry.get("claimed") != entry.get("referee")]
90
+ return {
91
+ "ok": final.get("status") != "UNKNOWN",
92
+ "status": final.get("status", "UNKNOWN"),
93
+ "assurance": int(final.get("assurance", 0) or 0),
94
+ "answer": final.get("answer"),
95
+ "answer_text": final.get("answer_text") or "",
96
+ "problem_math": final.get("problem_math") or "",
97
+ "reasons": list(final.get("reasons") or []),
98
+ "solver": final.get("solver"),
99
+ "detected": list(final.get("detected") or []),
100
+ "referee_mismatch": len(mismatched),
101
+ "turns": parsed.get("turns"),
102
+ "error": None if final.get("status") != "UNKNOWN" else "; ".join(final.get("reasons") or []) or "unknown",
103
+ }
lggeostratum/lexicon.py ADDED
@@ -0,0 +1,462 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 joints of the geometry language must appear, and in
10
+ which order).
11
+
12
+ This mirrors the geometry bundle, 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 geometry bundle holds the polynomials it studies.
19
+
20
+ One rule of the geometry language shapes every data file here: the *names* of a figure are not
21
+ translated. A person writing in any of the six varieties writes the points of a figure as the
22
+ capitalised names of the language of the geometry layer -- ``A``, ``B``, ``M``, ``P1`` -- because
23
+ that is what stands on the figure, and only the words around them belong to the variety.
24
+ """
25
+
26
+ import json
27
+ import os
28
+ import re
29
+ from typing import Any, Dict, List, Optional, Tuple
30
+
31
+ from .segment import atomize, fold
32
+
33
+ BUNDLE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
34
+ LEXICON_DIR = os.path.join(BUNDLE, "lexicon")
35
+
36
+ # Joint names, the same in every variety. The variety supplies the words; the names are how the
37
+ # two readers and the canonical printer agree, and they are the names the frame sequences of
38
+ # reader B are written with. They come from the templates of the geometry language.
39
+ from .canonical import MARKER_NAMES as MARKERS
40
+
41
+ # The keywords of the geometry language that introduce a named entity. A variety translates the
42
+ # keyword -- Italian "retta", the Chinese word for line -- and the name that follows it stays written in the
43
+ # ASCII names of the geometry language, because that is how a person copies a point from a figure.
44
+ ENTITY_KEYWORDS = ("line", "circle", "angle", "segment")
45
+ # Words of the geometry language that appear in a sentence without introducing an entity, and
46
+ # therefore never count as a coverage failure when a reading has already explained them.
47
+ EXTRA_WORDS = ("triangle",)
48
+
49
+ # A word run that is not in the lexicon is a coverage failure, unless it is one of these.
50
+ MATH_WORDS = EXTRA_WORDS
51
+
52
+ # A point is named by one capitalised word in the geometry language, and only a capitalised word
53
+ # that is not a word of the variety is one: the readers never guess a name out of lowercase prose.
54
+ NAME_START = re.compile(r"[A-Z]")
55
+
56
+ # The mnemonic names a data file may use for a connective, and what it prints as.
57
+ CONNECTIVE_TEXT = {"and": "and", "or": "or", "not": "not",
58
+ "eq": "=", "ne": "!=", "lt": "<", "le": "<=", "gt": ">", "ge": ">="}
59
+
60
+ _cache: Dict[str, Dict[str, Any]] = {}
61
+ _index_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
62
+ _stripped_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
63
+ _verb_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, ...]]] = {}
64
+ _group_cache: Dict[str, Dict[str, Tuple[str, ...]]] = {}
65
+
66
+
67
+ def languages() -> List[str]:
68
+ """The language codes this bundle can read, in a stable order."""
69
+ return sorted(name[:-5] for name in os.listdir(LEXICON_DIR) if name.endswith(".json"))
70
+
71
+
72
+ def load(lang: str) -> Dict[str, Any]:
73
+ if lang not in _cache:
74
+ path = os.path.join(LEXICON_DIR, lang + ".json")
75
+ with open(path, "r", encoding="utf-8") as handle:
76
+ data = json.load(handle)
77
+ data["_code"] = lang
78
+ _cache[lang] = data
79
+ return _cache[lang]
80
+
81
+
82
+ def script(lang: str) -> str:
83
+ return load(lang).get("script", "latin")
84
+
85
+
86
+ def codes() -> List[str]:
87
+ return languages()
88
+
89
+
90
+ def kinds(lang: str) -> List[str]:
91
+ """The sentence kinds this variety covers."""
92
+ return sorted(load(lang).get("kinds", {}))
93
+
94
+
95
+ def supported_kinds() -> List[str]:
96
+ """The kinds at least one variety covers."""
97
+ seen = set()
98
+ for lang in languages():
99
+ seen.update(kinds(lang))
100
+ return sorted(seen)
101
+
102
+
103
+ def patterns(lang: str) -> Dict[str, List[str]]:
104
+ """Reader A's surface patterns per kind: ``{kind: [pattern, ...]}``."""
105
+ out = {}
106
+ for kind, spec in load(lang).get("kinds", {}).items():
107
+ out[kind] = list(spec.get("patterns", []))
108
+ return out
109
+
110
+
111
+ def frames(lang: str) -> Dict[str, Dict[str, Any]]:
112
+ """Reader B's marker frames per kind."""
113
+ out = {}
114
+ for kind, spec in load(lang).get("kinds", {}).items():
115
+ frame = spec.get("frame")
116
+ if frame is not None:
117
+ out[kind] = frame
118
+ return out
119
+
120
+
121
+ def verbs(lang: str) -> Dict[str, Tuple[Tuple[str, ...], ...]]:
122
+ """Every kind verb phrase of the variety, mapped to the kinds it announces.
123
+
124
+ One phrase announces more than one kind, and that is a fact of the language, not a defect of
125
+ the data: Italian "dimostra" opens both ``prove`` and ``provez``, which differ only by the
126
+ marker for the domain. Keeping the whole list here is what lets a reader try both forms of
127
+ one sentence instead of silently taking the last kind in the file.
128
+ """
129
+ out: Dict[str, Tuple[str, ...]] = {}
130
+ for kind, spec in load(lang).get("kinds", {}).items():
131
+ for verb in spec.get("verbs", []):
132
+ phrase = fold(verb)
133
+ out[phrase] = out.get(phrase, ()) + (kind,)
134
+ return out
135
+
136
+
137
+ def verb_atoms_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, ...]]:
138
+ """The verb phrases of a variety, keyed by their atoms, mapped to the kinds they announce."""
139
+ if lang in _verb_cache:
140
+ return _verb_cache[lang]
141
+ index = {phrase_atoms(verb): kinds for verb, kinds in verbs(lang).items()}
142
+ _verb_cache[lang] = index
143
+ return index
144
+
145
+
146
+ def verb_groups(lang: str) -> Dict[str, Tuple[str, ...]]:
147
+ """The kinds a verb phrase can open: ``prove`` and ``provez`` are one group, ``det`` another.
148
+
149
+ Two kinds belong to the same group when one phrase of the variety announces both of them.
150
+ A sentence whose verb lies in one group is one problem, read in one of two ways; a sentence
151
+ whose verbs lie in two groups is two problems, and no reader may pick one.
152
+ """
153
+ if lang in _group_cache:
154
+ return _group_cache[lang]
155
+ parent = {kind: kind for kind in load(lang).get("kinds", {})}
156
+
157
+ def root(kind: str) -> str:
158
+ while parent[kind] != kind:
159
+ parent[kind] = parent[parent[kind]]
160
+ kind = parent[kind]
161
+ return kind
162
+
163
+ for kinds in verbs(lang).values():
164
+ for other in kinds[1:]:
165
+ first, second = root(kinds[0]), root(other)
166
+ if first != second:
167
+ parent[second] = first
168
+ merged: Dict[str, set] = {}
169
+ for kind in parent:
170
+ merged.setdefault(root(kind), set()).add(kind)
171
+ groups = {kind: tuple(sorted(group)) for group in merged.values() for kind in group}
172
+ _group_cache[lang] = groups
173
+ return groups
174
+
175
+
176
+ def announce(lang: str, items: List[Dict[str, Any]]) -> Tuple[List[str], Optional[Dict[str, str]]]:
177
+ """The kinds the verbs **and the joints** of a sentence open, or the reason it announces none.
178
+
179
+ Both readers ask this one question, in one place: a kind is a decision about the geometry, and
180
+ a second implementation of the same rule in the second reader would be one more place where
181
+ the two of them can be wrong in the same way.
182
+
183
+ In the geometry language the claim of a problem is very often carried by the joint itself --
184
+ "A, B e C **sono allineati**", "AB **perpendicolare a** CD", "ABC **un angolo retto**" --
185
+ and a reader that only listened to verbs would call those sentences unannounced. A joint whose
186
+ name is the name of a kind announces that kind, which is why the joint names of the data file
187
+ are the names of the forms of the geometry language.
188
+ """
189
+ found: List[str] = []
190
+ kinds_of = load(lang).get("kinds", {})
191
+ for item in items:
192
+ role = item.get("role")
193
+ if role == "verb":
194
+ candidates = item.get("kinds") or (item.get("value"),)
195
+ elif role == "marker":
196
+ value = item.get("value")
197
+ candidates = (value,) if value in kinds_of else ()
198
+ else:
199
+ candidates = ()
200
+ for kind in candidates:
201
+ if kind and kind in kinds_of and kind not in found:
202
+ found.append(kind)
203
+ if not found:
204
+ return [], {"reason": "no_verb"}
205
+ neutral = neutral_kinds(lang)
206
+ picked = [kind for kind in found if kind not in neutral] or found
207
+ groups = {frozenset(verb_groups(lang)[kind]) for kind in picked}
208
+ if len(groups) > 1:
209
+ return [], {"reason": "two_verbs", "kinds": ", ".join(sorted(picked))}
210
+ merged: set = set()
211
+ for group in groups:
212
+ merged |= group
213
+ return sorted(merged), None
214
+
215
+
216
+
217
+ def connectives(lang: str) -> Dict[str, List[str]]:
218
+ """The connective phrases of a variety, keyed by what they print as in the geometry language.
219
+
220
+ The data may key a connective by a mnemonic name (``ge``) or by the symbol itself; both are
221
+ accepted, because the mnemonic is easier to read in a data file and the symbol is what the
222
+ geometry language needs. The logic connectives are words in the geometry language, so they stay words.
223
+ """
224
+ out: Dict[str, List[str]] = {}
225
+ for name, words in load(lang).get("connectives", {}).items():
226
+ out[CONNECTIVE_TEXT.get(name, name)] = list(words)
227
+ return out
228
+
229
+
230
+ def neutral_kinds(lang: str) -> set:
231
+ """Kinds whose verb is a request for an answer rather than a claim about the configuration.
232
+
233
+ ``trova il circocentro di A, B e C`` announces a request, and the sentence that follows it in
234
+ the same problem announces the claim the geometry layer has to certify: the request verb is
235
+ neutral, so the reader that carries it steps aside when the two verbs meet in one sentence.
236
+ """
237
+ return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")}
238
+
239
+
240
+ def conjunction_words(lang: str) -> List[str]:
241
+ """The words a variety uses to join the names of a list, and the comma it writes.
242
+
243
+ The canonical printer of the geometry language needs these to cut ``A, B e C`` into three
244
+ points: a conjunction of the variety standing inside a slot is not part of a name, and the
245
+ comma that the atomiser leaves as a word between two names is listed with them, because in a
246
+ geometry sentence a comma between names is exactly the conjunction the language prints.
247
+ """
248
+ out: List[str] = []
249
+ for word in connectives(lang).get("and", []):
250
+ if word not in out:
251
+ out.append(word)
252
+ return out
253
+
254
+
255
+ def entity_keyword_words(lang: str) -> List[str]:
256
+ """The words with which a variety names a line, a circle, an angle, a segment.
257
+
258
+ Reader B and the canonical printer meet here: a region of a sentence may carry the noun of
259
+ the variety in front of the name -- ``la retta AB``, ``the circle c`` -- and that noun has to
260
+ be recognised as the keyword of the geometry language, not as a word of prose, before the
261
+ slot can be printed as ``line A-B`` or as ``circle c``.
262
+ """
263
+ out: List[str] = []
264
+ for word in noise(lang):
265
+ for piece in word.split():
266
+ if piece and piece not in out:
267
+ out.append(piece)
268
+ for words in markers(lang).values():
269
+ for word in words:
270
+ for piece in word.split():
271
+ if piece and piece not in out:
272
+ out.append(piece)
273
+ return out
274
+
275
+
276
+ def markers(lang: str) -> Dict[str, List[str]]:
277
+ return load(lang).get("markers", {})
278
+
279
+
280
+ def noise(lang: str) -> List[str]:
281
+ return load(lang).get("noise", [])
282
+
283
+
284
+ def noise_chars(lang: str) -> str:
285
+ """Single characters a word run may hold without being a coverage failure (Chinese particles)."""
286
+ return load(lang).get("noise_chars", "")
287
+
288
+
289
+ def prefixes(lang: str) -> List[str]:
290
+ """Attached prefixes an Arabic word run may carry (definite article, conjunctions)."""
291
+ return load(lang).get("prefixes", [])
292
+
293
+
294
+ def strip_prefix(word: str, prefixes: List[str]) -> str:
295
+ """Remove the longest attached prefix, so that a written form reaches the prefix-free entry.
296
+
297
+ Arabic attaches the definite article and the single letter conjunctions and prepositions in
298
+ front of the word, and the lexicon files record the word without them. The longest prefix wins,
299
+ because the article and a conjunction joined to it are one prefix and not two.
300
+ """
301
+ for prefix in sorted(prefixes, key=len, reverse=True):
302
+ if word.startswith(prefix) and len(word) > len(prefix):
303
+ return word[len(prefix):]
304
+ return word
305
+
306
+
307
+ def prefix_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
308
+ """The same index, keyed with every atom of every phrase written without its prefixes."""
309
+ if lang in _stripped_cache:
310
+ return _stripped_cache[lang]
311
+ attached = prefixes(lang)
312
+ stripped = {}
313
+ for window, hit in phrase_index(lang).items():
314
+ if attached:
315
+ key = tuple(strip_prefix(atom, attached) for atom in window)
316
+ stripped.setdefault(key, hit)
317
+ _stripped_cache[lang] = stripped
318
+ return stripped
319
+
320
+
321
+ # ---------------------------------------------------------------------------
322
+ # Phrase index (reader A) and phrase positions (reader B)
323
+ # ---------------------------------------------------------------------------
324
+ Phrase = Tuple[Tuple[str, ...], str, str]
325
+
326
+
327
+ def phrase_atoms(phrase: str) -> Tuple[str, ...]:
328
+ """The atoms a lexicon phrase is written with, through the same atomiser as a sentence.
329
+
330
+ A Chinese term in a data file is one token, and one token is not one atom: the atomiser cuts
331
+ it into characters, exactly as it cuts the sentence the user typed. Doing both sides the same
332
+ way is the only reason a data file and a sentence can be compared at all.
333
+ """
334
+ return tuple(fold(atom) for kind, atom in atomize(phrase) if kind == "w")
335
+
336
+
337
+ _SLOT_MARK = re.compile(r"\{[A-Z]\}")
338
+
339
+
340
+ def pattern_literals(lang: str) -> List[Tuple[str, ...]]:
341
+ """The function words the written patterns of a variety spell out themselves, one atom each.
342
+
343
+ A pattern is part of the data of a variety, so every word it writes is a word of that variety
344
+ by definition. ``sia M il punto medio di A e B`` names ``punto`` and ``medio``, and a reader
345
+ that called those words unknown would refuse the very shape the data file documents. These
346
+ words carry no value, which is what makes them noise: they may stand in a sentence, they
347
+ never fill a slot. A single ASCII letter is skipped, because a capital letter is the name of
348
+ a point and a lowercase letter of a pattern is an article or a preposition written apart.
349
+ """
350
+ words: List[Tuple[str, ...]] = []
351
+ for entries in patterns(lang).values():
352
+ for pattern in entries:
353
+ for chunk in _SLOT_MARK.split(pattern):
354
+ for atom in phrase_atoms(chunk):
355
+ if len(atom) == 1 and "a" <= atom <= "z":
356
+ continue
357
+ words.append((atom,))
358
+ return words
359
+
360
+
361
+ def phrase_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
362
+ """Map a folded word sequence to ``(role, value)``: verb, connective, marker or noise.
363
+
364
+ Verbs, connectives, markers and noise words of a variety share one index, because reader A
365
+ has to decide between them with a single longest match. The index is built once per variety.
366
+ """
367
+ if lang in _index_cache:
368
+ return _index_cache[lang]
369
+ index: Dict[Tuple[str, ...], Tuple[str, str]] = {}
370
+ for verb, kinds in verbs(lang).items():
371
+ index[phrase_atoms(verb)] = ("verb", kinds[0])
372
+ for symbol, words in connectives(lang).items():
373
+ for word in words:
374
+ index[phrase_atoms(word)] = ("connective", symbol)
375
+ for name, words in markers(lang).items():
376
+ for word in words:
377
+ index[phrase_atoms(word)] = ("marker", name)
378
+ for word in noise(lang):
379
+ index.setdefault(phrase_atoms(word), ("noise", ""))
380
+ for atom in pattern_literals(lang):
381
+ index.setdefault(atom, ("noise", ""))
382
+ # A data file with an empty phrase would match at every position and read nothing: drop it.
383
+ index.pop((), None)
384
+ _index_cache[lang] = index
385
+ return index
386
+
387
+
388
+ def max_phrase_length(lang: str) -> int:
389
+ return max((len(key) for key in phrase_index(lang)), default=1)
390
+
391
+
392
+ def phrase_spans(lang: str) -> List[Tuple[str, str, str]]:
393
+ """``(phrase, role, value)`` for every phrase of the variety, longest phrase first.
394
+
395
+ Reader B walks these against the sentence text itself, which is a different mechanism from
396
+ the token by token longest match of reader A.
397
+ """
398
+ out: List[Tuple[str, str, str]] = []
399
+ for verb, kind in verbs(lang).items():
400
+ out.append((verb, "verb", kind))
401
+ for symbol, words in connectives(lang).items():
402
+ for word in words:
403
+ out.append((word, "connective", symbol))
404
+ for name, words in markers(lang).items():
405
+ for word in words:
406
+ out.append((word, "marker", name))
407
+ for word in noise(lang):
408
+ out.append((word, "noise", ""))
409
+ out.sort(key=lambda item: (-len(item[0]), item[0]))
410
+ return out
411
+
412
+
413
+ # ---------------------------------------------------------------------------
414
+ # Presentation data
415
+ # ---------------------------------------------------------------------------
416
+ def labels(lang: str) -> Dict[str, str]:
417
+ return load(lang).get("labels", {})
418
+
419
+
420
+ def reading_labels(lang: str) -> Dict[str, str]:
421
+ return load(lang).get("reading", {})
422
+
423
+
424
+ def reason_texts(lang: str) -> Dict[str, str]:
425
+ return load(lang).get("reasons", {})
426
+
427
+
428
+ def examples(lang: str) -> List[str]:
429
+ return load(lang).get("examples", [])
430
+
431
+
432
+ def label(lang: str, key: str, fallback: str = "") -> str:
433
+ return labels(lang).get(key, fallback)
434
+
435
+
436
+ def translate_reason(lang: str, reason: str, **fields: Any) -> str:
437
+ """One reason in the language of the user, with the fields a template asks for."""
438
+ table = reason_texts(lang)
439
+ text = table.get(reason) or table.get("other") or reason
440
+ try:
441
+ return text.format(**fields)
442
+ except (KeyError, IndexError):
443
+ return text
444
+
445
+
446
+ def language_name(lang: str) -> str:
447
+ return load(lang).get("name", lang)
448
+
449
+
450
+ def find_by_hint(lang: str) -> Optional[str]:
451
+ """Resolve a ``--lang`` hint (a code or a name) to a language code, or ``None``."""
452
+ if lang in _available():
453
+ return lang
454
+ wanted = fold(lang)
455
+ for code in languages():
456
+ if fold(code) == wanted or fold(language_name(code)) == wanted:
457
+ return code
458
+ return None
459
+
460
+
461
+ def _available() -> List[str]:
462
+ return languages()
lggeostratum/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 stratum on every envelope on
5
+ 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 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_geometry: 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_GEOMETRY_BACKEND")
42
+ if not call_geometry:
43
+ os.environ["LGSTRATUM_GEOMETRY_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_geometry:
61
+ if previous is None:
62
+ os.environ.pop("LGSTRATUM_GEOMETRY_BACKEND", None)
63
+ else:
64
+ os.environ["LGSTRATUM_GEOMETRY_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
+ geometry_verdict = dossier.get("math") or {}
91
+ if not geometry_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, geometry_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
lggeostratum/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 geometry layer uses,
6
+ which is what lets one orchestrator run either topology without knowing the difference.
7
+
8
+ The dossier of a geometry-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 geometry language handed to the geometry layer
17
+ ``math`` the verdict the geometry layer 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)
lggeostratum/read_a.py ADDED
@@ -0,0 +1,402 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 entities of the figure in a slot. A pattern
5
+ matches only if every function word it names is present, in order, and if every verb and every
6
+ joint the user wrote is accounted for. That strictness is the point: when A produces a sentence
7
+ it read one of the documented shapes and nothing else.
8
+
9
+ Reader B (:mod:`lggeostratum.read_b`) does something different with the same data -- it looks for
10
+ the joint *frame* of a kind in the sentence, ignoring where the verb stands -- and the topology
11
+ only trusts a reading the two agree on. What the two readers share is the lexicon, the atomiser
12
+ in :mod:`lggeostratum.segment` and the templates of the geometry language in
13
+ :mod:`lggeostratum.canonical`, just as the two formalizers of the geometry topology share one written
14
+ grammar and one token spec.
15
+
16
+ One difference against the geometry bundle runs through this whole module: the values of the slots of
17
+ a geometry sentence are not expressions, they are **names** -- the capitalised names of the
18
+ points of a figure, the small letter name of a line or of a circle -- and a name is not a word of
19
+ any variety. A capitalised atom that no lexicon phrase claims is therefore a name, and that is
20
+ the rule both readers use to tell a point from prose.
21
+ """
22
+
23
+ import re
24
+ from typing import Any, Dict, List, Optional, Tuple
25
+
26
+ from . import canonical, lexicon
27
+ from .segment import atomize, fold, numeric_literals, word_pieces
28
+
29
+ _SLOT = re.compile(r"\{([A-Z])\}")
30
+ _NAME = re.compile(r"[A-Z][A-Za-z0-9_]*")
31
+ _ENTITY_LETTER = re.compile(r"[a-z]")
32
+ _CONTENT = ("math", "name", "connective")
33
+
34
+
35
+ def compile_pattern(pattern: str) -> Tuple[List[List[str]], List[str]]:
36
+ """Split a surface pattern into its literal word chunks and its slot names, in order."""
37
+ parts = _SLOT.split(pattern)
38
+ chunks: List[List[str]] = []
39
+ slots: List[str] = []
40
+ index = 0
41
+ while index < len(parts):
42
+ chunks.append([fold(piece) for word in parts[index].split() for piece in word_pieces(word)])
43
+ index += 1
44
+ if index < len(parts):
45
+ slots.append(parts[index])
46
+ index += 1
47
+ return chunks, slots
48
+
49
+
50
+ def is_name(atom: str) -> bool:
51
+ """Whether an atom as written is a point name of the geometry language."""
52
+ return bool(_NAME.fullmatch(atom))
53
+
54
+
55
+ def is_entity_name(atom: str) -> bool:
56
+ """Whether an atom no variety claims is the name of a line, a circle, a transformation.
57
+
58
+ The geometry language names its points with a capital letter and its other entities with one
59
+ small letter, and only the points look like names to a reader of a variety: *r* and *c* are
60
+ ordinary letters. A small letter that no phrase of the variety claims is therefore the name of
61
+ an entity of the figure -- the one shape the formal language contributes to the atomiser, next
62
+ to the capitalised point names, and the spec of both is the naming rule of the bundle. A word
63
+ of two or more letters is never treated that way: the bundle names its entities with a single
64
+ letter, and a longer unknown word stays what it is.
65
+ """
66
+ return canonical.is_entity_name(atom)
67
+
68
+
69
+ def _shadowed_by_name(window: Tuple[str, ...], atom: str) -> bool:
70
+ """Whether a one letter word of the variety is really the name of a point.
71
+
72
+ Italian writes the preposition *a* and the article *l* with the same letters the geometry
73
+ language uses for the points A and L, and the data of a variety has to name those prepositions
74
+ somewhere. The atomiser folds case, so the two are the same atom once they reach the lexicon:
75
+ what tells them apart is the case the sentence wrote, and the convention the six varieties of
76
+ this bundle keep -- a name of the figure is always written with its capital letter, in every
77
+ language, and a word of the variety never starts with one. A single letter entry of the
78
+ lexicon therefore loses to a capitalised atom, and a multi letter word never does, which is
79
+ why *Il* at the head of a sentence stays an article and *A* stays a point.
80
+ """
81
+ return len(window) == 1 and len(window[0]) == 1 and is_name(atom)
82
+
83
+
84
+ def scan(lang: str, text: str) -> List[Dict[str, Any]]:
85
+ """Tag every atom: mathematics, a name of the figure, or a lexicon phrase with its role.
86
+
87
+ One longest match per position decides between verb, joint, connective and noise, which is
88
+ why a data file must not give one phrase two roles. Only after the lexicon has had its turn
89
+ does a capitalised atom become a name: the lexicon of a variety claims its own words first,
90
+ and a data file that wrote a word twice would be a data file that reads the same sentence two
91
+ ways.
92
+ """
93
+ phrases = lexicon.phrase_index(lang)
94
+ attached = lexicon.prefixes(lang)
95
+ stripped_index = lexicon.prefix_index(lang) if attached else {}
96
+ longest = lexicon.max_phrase_length(lang)
97
+ atoms = atomize(text)
98
+ items: List[Dict[str, Any]] = []
99
+ index = 0
100
+ while index < len(atoms):
101
+ kind, atom = atoms[index]
102
+ if kind == "m":
103
+ items.append({"role": "math", "value": atom, "words": [], "surface": atom})
104
+ index += 1
105
+ continue
106
+ word = fold(atom)
107
+ hit = None
108
+ for span in range(min(longest, len(atoms) - index), 0, -1):
109
+ if any(atoms[index + step][0] != "w" for step in range(span)):
110
+ continue
111
+ window = tuple(fold(atoms[index + step][1]) for step in range(span))
112
+ if window in phrases:
113
+ hit = (phrases[window], window)
114
+ break
115
+ if attached:
116
+ key = tuple(lexicon.strip_prefix(w, attached) for w in window)
117
+ if key in stripped_index:
118
+ hit = (stripped_index[key], key)
119
+ break
120
+ if hit and _shadowed_by_name(window, atom):
121
+ hit = None
122
+ if hit:
123
+ (role, value), key = hit
124
+ # The item carries the atoms as the sentence wrote them; the lexicon key it matched is
125
+ # kept only to look the verb up, because Arabic writes a lexicon word with prefixes
126
+ # attached and the data file records it without them.
127
+ item = {"role": role, "value": value, "words": list(window), "surface": atom}
128
+ if role == "verb":
129
+ table = lexicon.verb_atoms_index(lang)
130
+ item["kinds"] = table.get(window) or table.get(key) or (value,)
131
+ items.append(item)
132
+ index += len(window)
133
+ continue
134
+ if is_name(atom):
135
+ # A name of the figure: it carries its value as written, and no words, so it can never
136
+ # be claimed by a literal chunk of a pattern.
137
+ items.append({"role": "name", "value": atom, "words": [], "surface": atom})
138
+ index += 1
139
+ continue
140
+ if is_entity_name(word):
141
+ # The small letter the geometry language gives to a line, to a circle, to a
142
+ # transformation. A variety never writes that letter as a word -- the article and the
143
+ # preposition of Italian are claimed by the lexicon before this line is reached -- so a
144
+ # small letter standing on its own is the name of an entity of the figure.
145
+ items.append({"role": "name", "value": word, "words": [], "surface": atom})
146
+ index += 1
147
+ continue
148
+ if word in lexicon.MATH_WORDS:
149
+ items.append({"role": "math", "value": word, "words": [], "surface": atom})
150
+ index += 1
151
+ continue
152
+ if atom and atom in lexicon.noise_chars(lang):
153
+ # A single character particle of a script written without spaces (Chinese particles).
154
+ # It carries its own atom as its words so that a pattern naming the particle can match
155
+ # it; it carries no value, so it never reaches a slot of a reading.
156
+ items.append({"role": "noise", "value": "", "words": [word], "surface": atom})
157
+ index += 1
158
+ continue
159
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
160
+ index += 1
161
+ return items
162
+
163
+
164
+ def _text(item: Dict[str, Any]) -> str:
165
+ """What an item contributes to a slot: a name, an expression, a relation word."""
166
+ if item["role"] == "connective":
167
+ return " %s " % item["value"]
168
+ return item["value"]
169
+
170
+
171
+ def _claim(words: List[str], chunk_slice: List[str], attached: List[str]) -> bool:
172
+ """Whether the atoms an item carries are the atoms a chunk of the pattern asks for.
173
+
174
+ Arabic writes a word with its article and its conjunctions attached to it, and the pattern in
175
+ the data file names the bare word. Stripping the attachment from both sides is what lets a
176
+ pattern name a word the sentence wrote in another form, and nothing else is forgiven: an item
177
+ that carries no atoms is a name or a piece of mathematics, and neither is ever a word of a
178
+ pattern.
179
+ """
180
+ if not words:
181
+ return False
182
+ if list(words) == list(chunk_slice):
183
+ return True
184
+ if not attached:
185
+ return False
186
+ return ([lexicon.strip_prefix(word, attached) for word in words]
187
+ == [lexicon.strip_prefix(word, attached) for word in chunk_slice])
188
+
189
+
190
+ def _find(chunk: List[str], items: List[Dict[str, Any]], start: int,
191
+ attached: List[str]) -> Optional[Tuple[int, int]]:
192
+ """Where in the item stream the literal words of a pattern chunk appear, or ``None``.
193
+
194
+ A chunk is contiguous: it may not span a name or a piece of mathematics, and no function word
195
+ the pattern did not name may sit inside it. That is what stops a pattern from swallowing a
196
+ sentence it does not describe.
197
+ """
198
+ for first in range(start, len(items) + 1):
199
+ cursor = first
200
+ taken = 0
201
+ ok = True
202
+ while taken < len(chunk):
203
+ if cursor >= len(items):
204
+ ok = False
205
+ break
206
+ words = items[cursor]["words"]
207
+ if not _claim(words, chunk[taken:taken + len(words)], attached):
208
+ ok = False
209
+ break
210
+ taken += len(words)
211
+ cursor += 1
212
+ if ok:
213
+ return first, cursor
214
+ return None
215
+
216
+
217
+ def _consume(items: List[Dict[str, Any]], start: int, stop: int) -> Optional[List[Dict[str, Any]]]:
218
+ """The entities held between two positions, or ``None`` when an unnamed word stands there.
219
+
220
+ The conjunction a variety uses to list the entities of a slot -- the "e" of "A, B e C" -- is a
221
+ connective in this layer, exactly as the "and" it prints as, so it belongs to the region like a
222
+ comma does and says where one entity stops and the next begins. A marker of the geometry
223
+ language is a joint the pattern did not name, and it stops the region.
224
+ """
225
+ bucket: List[Dict[str, Any]] = []
226
+ for item in items[start:stop]:
227
+ if item["role"] in _CONTENT:
228
+ bucket.append(item)
229
+ elif item["role"] != "noise":
230
+ return None
231
+ return bucket
232
+
233
+
234
+ def _fill(group: List[str], bucket: List[Dict[str, Any]], joins: Tuple[str, ...] = (),
235
+ keywords: Tuple[str, ...] = ()) -> Optional[Dict[str, str]]:
236
+ """The values of the slots that one region of a sentence feeds.
237
+
238
+ Usually one slot, and the whole region is its value. A pattern may also put two slots side by
239
+ side, with no words between them -- Italian writes the two endpoints of a line one after the
240
+ other, ``il punto medio di A e B`` -- and then the region has to break into exactly one entity
241
+ per slot. One entity per item is the first try, because the atomiser hands a region over as
242
+ items and the items of ``A, B`` are already two; when the items do not line up with the slots,
243
+ the text of the region is asked for its entities, which is where a conjunction of the variety
244
+ and a coordinate pair are accounted for. A region that does not break that way is a region the
245
+ pattern cannot read, and guessing where one slot ends and the other begins would be the reader
246
+ inventing the problem it then reports.
247
+ """
248
+ if len(bucket) < len(group):
249
+ return None
250
+ if len(group) == 1:
251
+ joined = " ".join(_text(item) for item in bucket).strip()
252
+ if not joined:
253
+ return None
254
+ return {group[0]: canonical.tidy(joined)}
255
+ if len(bucket) == len(group):
256
+ filled: Dict[str, str] = {}
257
+ for slot, item in zip(group, bucket):
258
+ value = canonical.tidy(_text(item))
259
+ if not value:
260
+ return None
261
+ filled[slot] = value
262
+ return filled
263
+ joined = canonical.tidy(" ".join(_text(item) for item in bucket).strip())
264
+ units = canonical.split_units(joined, joins, keywords)
265
+ if len(units) != len(group):
266
+ return None
267
+ filled = {}
268
+ for slot, unit in zip(group, units):
269
+ value = canonical.tidy(" ".join(unit))
270
+ if not value:
271
+ return None
272
+ filled[slot] = value
273
+ return filled
274
+
275
+
276
+ def match(chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]],
277
+ attached: List[str], joins: Tuple[str, ...] = (),
278
+ keywords: Tuple[str, ...] = ()) -> Optional[Dict[str, str]]:
279
+ """A value per slot name, or ``None`` when the pattern does not describe the items.
280
+
281
+ Every verb and every joint of the sentence has to be consumed by a chunk of the pattern, and
282
+ the names and expressions left over fall into the slots in the order the pattern names them.
283
+ A pattern that ignores a joint the sentence carries is a pattern that misread the sentence, so
284
+ it fails; so does a pattern that leaves a name outside every slot.
285
+ """
286
+ filled: Dict[str, str] = {}
287
+ group = [slots[0]]
288
+ position = 0
289
+ if chunks[0]:
290
+ # Words before the first slot: a function word the pattern does not name is harmless there,
291
+ # because it carries no entity, but a name before it belongs to no slot of the pattern, and
292
+ # a verb or a joint before it is a joint the pattern does not describe.
293
+ found = _find(chunks[0], items, 0, attached)
294
+ if found is None or _consume(items, 0, found[0]) != []:
295
+ return None
296
+ position = found[1]
297
+ for index in range(1, len(slots)):
298
+ if not chunks[index]:
299
+ group.append(slots[index])
300
+ continue
301
+ found = _find(chunks[index], items, position, attached)
302
+ if found is None:
303
+ return None
304
+ bucket = _consume(items, position, found[0])
305
+ if bucket is None:
306
+ return None
307
+ part = _fill(group, bucket, joins, keywords)
308
+ if part is None:
309
+ return None
310
+ filled.update(part)
311
+ group = [slots[index]]
312
+ position = found[1]
313
+ tail = chunks[len(slots)]
314
+ if tail:
315
+ found = _find(tail, items, position, attached)
316
+ # Nothing but function words may follow the last words of the pattern: a name after the
317
+ # end of the shape belongs to no slot, so the shape does not describe the sentence.
318
+ if found is None or _consume(items, found[1], len(items)) != []:
319
+ return None
320
+ bucket = _consume(items, position, found[0])
321
+ else:
322
+ bucket = _consume(items, position, len(items))
323
+ if bucket is None:
324
+ return None
325
+ part = _fill(group, bucket, joins, keywords)
326
+ if part is None:
327
+ return None
328
+ filled.update(part)
329
+ return filled
330
+
331
+
332
+ def _slot_problems(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (),
333
+ keywords: Tuple[str, ...] = ()) -> List[Dict[str, str]]:
334
+ """A slot that is not the shape the kind promises: a name where a line belongs, a stray word."""
335
+ problems: List[Dict[str, str]] = []
336
+ for name, value in sorted(slots.items()):
337
+ try:
338
+ canonical.normalize_slot(kind, name, value, joins, keywords)
339
+ except canonical.ReadingError as error:
340
+ problems.append({"reason": "bad_" + canonical.slot_reason(name),
341
+ "slot": name, "detail": str(error)})
342
+ return problems
343
+
344
+
345
+ def read(lang: str, text: str) -> Dict[str, Any]:
346
+ """The reading reader A reaches in one variety, and why it abstained when it did."""
347
+ items = scan(lang, text)
348
+ result: Dict[str, Any] = {"reader": "reader_a", "lang": lang, "mode": "pattern",
349
+ "kind": None, "math": None, "slots": {}, "markers": [], "notes": []}
350
+ unknown = [item for item in items if item["role"] == "unknown"]
351
+ if unknown:
352
+ result["status"] = "NOT COVERED"
353
+ for item in unknown:
354
+ result["notes"].append({"reason": item.get("reason", "unknown_word"),
355
+ "word": item["surface"]})
356
+ return result
357
+ result["markers"] = [item["value"] for item in items if item["role"] == "marker"]
358
+ candidates, why = lexicon.announce(lang, items)
359
+ if not candidates:
360
+ result["status"] = "NOT COVERED"
361
+ result["notes"].append(why)
362
+ return result
363
+ result["announced"] = candidates
364
+ attached = lexicon.prefixes(lang)
365
+ joins = tuple(lexicon.conjunction_words(lang))
366
+ keywords = tuple(lexicon.entity_keyword_words(lang))
367
+ found: List[Tuple[str, str, Dict[str, str]]] = []
368
+ for kind in candidates:
369
+ for pattern in lexicon.patterns(lang).get(kind, []):
370
+ chunks, slots = compile_pattern(pattern)
371
+ assigned = match(chunks, slots, items, attached, joins, keywords)
372
+ if assigned is None:
373
+ continue
374
+ problems = _slot_problems(kind, assigned, joins, keywords)
375
+ if problems:
376
+ result["notes"].extend(problems)
377
+ continue
378
+ try:
379
+ math_str = canonical.print_geometry(kind, assigned, joins, keywords)
380
+ except canonical.ReadingError as error:
381
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
382
+ continue
383
+ if not any(entry[1] == math_str for entry in found):
384
+ found.append((kind, math_str, assigned))
385
+ if not found:
386
+ result["status"] = "NOT COVERED"
387
+ if not any(note["reason"].startswith("bad_") for note in result["notes"]):
388
+ result["notes"].append({"reason": "no_pattern"})
389
+ return result
390
+ if len(found) > 1:
391
+ result["status"] = "AMBIGUOUS"
392
+ result["notes"].append({"reason": "multiple",
393
+ "first": found[0][1], "second": found[1][1]})
394
+ return result
395
+ kind, math_str, assigned = found[0]
396
+ result["status"] = "READ"
397
+ result["kind"] = kind
398
+ result["math"] = math_str
399
+ result["slots"] = assigned
400
+ result["literals"] = numeric_literals(text)
401
+ result["notes"] = []
402
+ return result
lggeostratum/read_b.py ADDED
@@ -0,0 +1,338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 geometry language: the markers the sentence carries, in the
6
+ order it carries them. Where the verb stands, which words surround it and whether the sentence
7
+ names the points before or after the claim are all invisible to B. It asks one question: does the
8
+ sentence hold the joints of a form of the geometry language, with an entity of the figure between
9
+ each pair?
10
+
11
+ That is a different question from reader A's ("does this sentence have one of the shapes the
12
+ lexicon writes down?"), so the two reach different answers on real sentences, which is the point.
13
+ What they share is the lexicon, the atomiser and the templates of the geometry language -- the
14
+ same kind of sharing the two formalizers of the geometry topology accept, where one written grammar
15
+ is the specification both are checked against.
16
+
17
+ In a geometry sentence the joints are mostly prepositional phrases -- "with center", "lies
18
+ between", "is perpendicular to" -- and the verb of the kind is often one of them: the frame is
19
+ then the order of those phrases alone, and the entity the claim is about stands in the gap the
20
+ form leaves without a joint.
21
+ """
22
+
23
+ from typing import Any, Dict, List, Optional, Tuple
24
+
25
+ from . import canonical, lexicon
26
+ from .canonical import ReadingError
27
+ from .segment import atomize, fold, numeric_literals
28
+
29
+ _CONTENT = ("math", "name", "connective")
30
+ _NAME = canonical.is_name
31
+
32
+
33
+ def _matches(window: List[str], phrase: Tuple[str, ...], attached: List[str]) -> bool:
34
+ """Whether a window of folded word atoms is a phrase, with or without attached prefixes.
35
+
36
+ The data file of Arabic writes "on the straight line" without its article, and a sentence
37
+ writes it with one. The comparison then strips the attachment from both sides, which is what
38
+ lets the article of the sentence and the absence of it in the data file meet in the same
39
+ written form.
40
+ """
41
+ if list(window) == list(phrase):
42
+ return True
43
+ if not attached:
44
+ return False
45
+ stripped = [lexicon.strip_prefix(atom, attached) for atom in window]
46
+ return stripped == list(phrase) or stripped == [lexicon.strip_prefix(a, attached) for a in phrase]
47
+
48
+
49
+ def find_spans(lang: str, atoms: List[Tuple[str, str]]) -> Tuple[List[Dict[str, Any]], List[bool]]:
50
+ """Every occurrence of every lexicon phrase, longest first, never overlapping.
51
+
52
+ Reader A resolves one position at a time by taking the longest phrase there. B enumerates the
53
+ whole phrase table, longest entries first, and lets each entry claim its occurrences wherever
54
+ they are. The two orderings disagree on purpose: a sentence whose phrases interleave gives the
55
+ two readers different chances, and a reading only counts when both take it.
56
+ """
57
+ folded = [fold(atom) if kind == "w" else "" for kind, atom in atoms]
58
+ attached = lexicon.prefixes(lang)
59
+ covered = [False] * len(atoms)
60
+ table = sorted(lexicon.phrase_index(lang).items(),
61
+ key=lambda entry: (-len(entry[0]), -len("".join(entry[0])), entry[0]))
62
+ spans: List[Dict[str, Any]] = []
63
+ for phrase, hit in table:
64
+ role, value = hit
65
+ if not phrase:
66
+ continue
67
+ start = 0
68
+ while start <= len(atoms) - len(phrase):
69
+ found = None
70
+ for position in range(start, len(atoms) - len(phrase) + 1):
71
+ if any(covered[position + step] or atoms[position + step][0] != "w"
72
+ for step in range(len(phrase))):
73
+ continue
74
+ if len(phrase) == 1 and len(phrase[0]) == 1 and _NAME(atoms[position][1]):
75
+ # A one letter word of the variety and a point of the figure are the same
76
+ # letters once the case is folded: the capital the sentence wrote is what
77
+ # tells them apart, and the name wins. See reader A for the same convention.
78
+ continue
79
+ if _matches(folded[position:position + len(phrase)], phrase, attached):
80
+ found = position
81
+ break
82
+ if found is None:
83
+ break
84
+ for step in range(len(phrase)):
85
+ covered[found + step] = True
86
+ spans.append({"start": found, "end": found + len(phrase), "role": role,
87
+ "value": value, "words": folded[found:found + len(phrase)],
88
+ "kinds": (lexicon.verb_atoms_index(lang).get(phrase, (value,))
89
+ if role == "verb" else (value,))})
90
+ start = found + len(phrase)
91
+ spans.sort(key=lambda span: span["start"])
92
+ return spans, covered
93
+
94
+
95
+ def classify(lang: str, atoms: List[Tuple[str, str]], spans: List[Dict[str, Any]],
96
+ covered: List[bool]) -> List[Dict[str, Any]]:
97
+ """Tag each atom from the spans, and name what no phrase claimed.
98
+
99
+ B has no left to right walk to reason with, so an atom no phrase of the variety claimed is
100
+ judged by its shape alone: a capitalised atom is a name of the figure -- names are not
101
+ translated, in any variety -- and anything else that is not a particle of the script is an
102
+ unknown word. Reader A, which reads a phrase table position by position, gives its lexicon the
103
+ first chance at the same atom: that is one of the ways the two readers can part company, and a
104
+ capitalised word a variety also uses as a noun is exactly where they do.
105
+ """
106
+ particles = lexicon.load(lang).get("noise_chars", "")
107
+ starts = {span["start"]: span for span in spans}
108
+ items: List[Dict[str, Any]] = []
109
+ index = 0
110
+ while index < len(atoms):
111
+ kind, atom = atoms[index]
112
+ if kind == "m":
113
+ items.append({"role": "math", "value": atom, "words": [], "surface": atom})
114
+ index += 1
115
+ continue
116
+ if index in starts:
117
+ span = starts[index]
118
+ items.append({"role": span["role"], "value": span["value"], "words": span["words"],
119
+ "kinds": span.get("kinds", (span["value"],)), "surface": atom})
120
+ index = span["end"]
121
+ continue
122
+ word = fold(atom)
123
+ if atom and atom in particles:
124
+ items.append({"role": "noise", "value": "", "words": [], "surface": atom})
125
+ index += 1
126
+ continue
127
+ if _NAME(atom):
128
+ items.append({"role": "name", "value": atom, "words": [], "surface": atom})
129
+ index += 1
130
+ continue
131
+ if canonical.is_entity_name(word):
132
+ # The one small letter the geometry language gives to a line, to a circle, to a
133
+ # transformation. No phrase of the lexicon reached it, so it is a name of the figure:
134
+ # reader A states the same convention where it walks the sentence itself.
135
+ items.append({"role": "name", "value": word, "words": [], "surface": atom})
136
+ index += 1
137
+ continue
138
+ if word in lexicon.MATH_WORDS:
139
+ items.append({"role": "math", "value": word, "words": [], "surface": atom})
140
+ index += 1
141
+ continue
142
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
143
+ index += 1
144
+ return items
145
+
146
+
147
+ def _text(item: Dict[str, Any]) -> str:
148
+ if item["role"] == "connective":
149
+ return " %s " % item["value"]
150
+ return item["value"]
151
+
152
+
153
+ def _regions_marked(items: List[Dict[str, Any]]) -> List[Tuple[Optional[str], str]]:
154
+ """The runs of entities of a sentence, each tagged with the joint standing before it.
155
+
156
+ A joint of the geometry language introduces the region that follows it, and the verb of a
157
+ sentence introduces nothing: it sits in the gap a form leaves without a joint. Tagging a
158
+ region instead of counting regions is what lets B read a frame written out of order, because
159
+ a variety may put the points before the claim ("A, B e C sono allineati") or after it
160
+ ("sono allineati A, B e C") and a reader that filled the slots by position would put the
161
+ subject of the claim where its object belongs.
162
+
163
+ The atoms of a region are joined with a space on purpose. The atomiser cuts a sentence into
164
+ runs, and one run can be the whole coordinate pair while two runs can be the two ends of one
165
+ line reference split by nothing but a hyphen ("A-B"). Gluing the runs without a space invents
166
+ a token that was never written, and an invented token is a changed problem.
167
+ """
168
+ regions: List[Tuple[Optional[str], str]] = []
169
+ buffer: List[str] = []
170
+ joint: Optional[str] = None
171
+ for item in items:
172
+ if item["role"] in ("marker", "verb"):
173
+ regions.append((joint, canonical.tidy(" ".join(buffer))))
174
+ buffer = []
175
+ joint = item["value"] if item["role"] == "marker" else None
176
+ elif item["role"] in _CONTENT:
177
+ buffer.append(_text(item))
178
+ regions.append((joint, canonical.tidy(" ".join(buffer))))
179
+ return regions
180
+
181
+
182
+ def _groups(slots: Tuple[str, ...], gaps: List[Optional[str]]) -> List[List[Tuple[int, str]]]:
183
+ """The slots a form fills from one region each, run together where it leaves no joint.
184
+
185
+ The geometry language writes the three points of a collinearity with a joint only before the
186
+ last of them ("A, B and C"), so the first two slots of that form share one region of the
187
+ sentence, and the pair has to be taken apart by the entities it holds -- the same rule reader
188
+ A applies to a pattern with two slots side by side.
189
+ """
190
+ out: List[List[Tuple[int, str]]] = []
191
+ for position, slot in enumerate(slots):
192
+ if gaps[position] is not None or not out:
193
+ out.append([(position, slot)])
194
+ else:
195
+ out[-1].append((position, slot))
196
+ return out
197
+
198
+
199
+ def _candidates(marked: List[Tuple[Optional[str], str]], joint: Optional[str],
200
+ taken: set) -> List[int]:
201
+ if joint is None:
202
+ return [index for index, (before, text) in enumerate(marked)
203
+ if before is None and text and index not in taken]
204
+ return [index for index, (before, text) in enumerate(marked)
205
+ if before == joint and text and index not in taken]
206
+
207
+
208
+ def _assign_joints(marked: List[Tuple[Optional[str], str]], gaps: List[Optional[str]],
209
+ slots: Tuple[str, ...], joins: Tuple[str, ...] = (),
210
+ keywords: Tuple[str, ...] = ()) -> Optional[Dict[str, str]]:
211
+ """Fill the slots of a form from the regions a sentence offers, or fail.
212
+
213
+ A slot takes the region that stands after the joint the form puts before it, and a slot whose
214
+ gap carries no joint takes one of the regions of the sentence no joint claims. A region
215
+ holding no entity is never a candidate, and every region that does hold one has to end up in a
216
+ slot: an entity left over belongs to no slot of the form, so the form does not describe the
217
+ sentence. This is also how a joint the geometry language puts last is policed -- the region it
218
+ introduces is empty, and anything written after it makes the form fail -- and why a frame whose
219
+ slots arrive in a rotated order still reads, because no slot is identified by its position in
220
+ the sentence.
221
+ """
222
+ assigned: Dict[str, str] = {}
223
+ taken: set = set()
224
+ for group in _groups(slots, gaps):
225
+ joint = gaps[group[0][0]]
226
+ candidates = _candidates(marked, joint, taken)
227
+ if len(group) == 1:
228
+ if len(candidates) != 1:
229
+ return None
230
+ assigned[group[0][1]] = marked[candidates[0]][1]
231
+ taken.add(candidates[0])
232
+ continue
233
+ if len(candidates) == len(group):
234
+ for (position, slot), index in zip(group, candidates):
235
+ assigned[slot] = marked[index][1]
236
+ taken.add(index)
237
+ continue
238
+ if len(candidates) != 1:
239
+ return None
240
+ units = canonical.split_units(marked[candidates[0]][1], joins, keywords)
241
+ if len(units) != len(group):
242
+ return None
243
+ for (position, slot), unit in zip(group, units):
244
+ assigned[slot] = canonical.tidy(" ".join(unit))
245
+ taken.add(candidates[0])
246
+ last = gaps[len(slots)]
247
+ if last is not None and any(text for before, text in marked if before == last and text):
248
+ return None
249
+ if any(text for index, (_, text) in enumerate(marked) if text and index not in taken):
250
+ return None
251
+ return assigned
252
+
253
+
254
+ def _problems(kind: str, slots: Dict[str, str], joins: Tuple[str, ...] = (),
255
+ keywords: Tuple[str, ...] = ()) -> List[Dict[str, str]]:
256
+ problems: List[Dict[str, str]] = []
257
+ for name, value in sorted(slots.items()):
258
+ try:
259
+ canonical.normalize_slot(kind, name, value, joins, keywords)
260
+ except ReadingError as error:
261
+ problems.append({"reason": "bad_" + canonical.slot_reason(name),
262
+ "slot": name, "detail": str(error)})
263
+ if not canonical.balanced(canonical.print_geometry(kind, slots, joins, keywords)):
264
+ problems.append({"reason": "unbalanced"})
265
+ return problems
266
+
267
+
268
+ def read(lang: str, text: str) -> Dict[str, Any]:
269
+ """The reading reader B reaches in one variety, and why it abstained when it did."""
270
+ atoms = atomize(text)
271
+ spans, covered = find_spans(lang, atoms)
272
+ items = classify(lang, atoms, spans, covered)
273
+ result: Dict[str, Any] = {"reader": "reader_b", "lang": lang, "mode": "frame",
274
+ "kind": None, "math": None, "slots": {}, "markers": [], "notes": []}
275
+ unknown = [item for item in items if item["role"] == "unknown"]
276
+ if unknown:
277
+ result["status"] = "NOT COVERED"
278
+ for item in unknown:
279
+ result["notes"].append({"reason": item.get("reason", "unknown_word"),
280
+ "word": item["surface"]})
281
+ return result
282
+ markers = [item["value"] for item in items if item["role"] == "marker"]
283
+ result["markers"] = markers
284
+ candidates, why = lexicon.announce(lang, items)
285
+ if not candidates:
286
+ result["status"] = "NOT COVERED"
287
+ result["notes"].append(why)
288
+ return result
289
+ result["announced"] = candidates
290
+ regions = _regions_marked(items)
291
+ frame_table = lexicon.frames(lang)
292
+ joins = tuple(lexicon.conjunction_words(lang))
293
+ keywords = tuple(lexicon.entity_keyword_words(lang))
294
+ found: List[Tuple[str, str, Dict[str, str]]] = []
295
+ for kind in candidates:
296
+ allowed = [list(sequence) for sequence in frame_table.get(kind, {}).get("sequences", [])]
297
+ if markers not in allowed:
298
+ result["notes"].append({"reason": "no_frame", "kind": kind,
299
+ "detail": " ".join(markers) or "none"})
300
+ continue
301
+ for variant in canonical.VARIANTS.get(kind, []):
302
+ if canonical.marker_sequence(kind, variant) != markers:
303
+ continue
304
+ assigned = _assign_joints(regions, canonical.gap_markers(kind, variant), variant,
305
+ joins, keywords)
306
+ if assigned is None:
307
+ result["notes"].append({"reason": "markers", "kind": kind,
308
+ "detail": " ".join(markers)})
309
+ continue
310
+ try:
311
+ math_str = canonical.print_geometry(kind, assigned, joins, keywords)
312
+ except ReadingError as error:
313
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
314
+ continue
315
+ problems = _problems(kind, assigned, joins, keywords)
316
+ if problems:
317
+ result["notes"].extend(problems)
318
+ continue
319
+ if not any(entry[1] == math_str for entry in found):
320
+ found.append((kind, math_str, assigned))
321
+ if not found:
322
+ result["status"] = "NOT COVERED"
323
+ if not result["notes"]:
324
+ result["notes"].append({"reason": "no_pattern"})
325
+ return result
326
+ if len(found) > 1:
327
+ result["status"] = "AMBIGUOUS"
328
+ result["notes"].append({"reason": "multiple",
329
+ "first": found[0][1], "second": found[1][1]})
330
+ return result
331
+ read_kind, math_str, assigned = found[0]
332
+ result["status"] = "READ"
333
+ result["kind"] = read_kind
334
+ result["math"] = math_str
335
+ result["slots"] = assigned
336
+ result["literals"] = numeric_literals(text)
337
+ result["notes"] = []
338
+ return result
lggeostratum/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 formal content -- the canonical sentence the stratum understood and the answer the
10
+ geometry bundle 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
+ ``Prove that A, B and C are collinear.`` can see which reading was used, and that is the whole point
14
+ of 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 geometry 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 geometry bundle."""
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 engine of the bundle settled which obligation is its own bookkeeping and nothing
105
+ # the reader of an answer asked for; what belongs in the reply is the verdict and, when the
106
+ # bundle 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("geometry_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
+ }
lggeostratum/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 geometry language uses. The
5
+ mapping from a word to a role is the lexicon, in ``lexicon/<lang>.json`` and
6
+ :mod:`lggeostratum.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 geometryematics only between two closed operands, which is what separates the comma of a
18
+ coordinate pair ``(0, 0)`` from the comma that lists the three points of a triangle.
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 geometry language, parentheses included: a coordinate pair 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 geometry 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 geometry
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 geometry language
191
+ open a mathematics run. An ASCII letter run is returned as a word: :mod:`lggeostratum.read_a`
192
+ and :mod:`lggeostratum.read_b` decide between a name 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,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node adversary (adversary): Adversary: states the ceiling the reading layer can honestly claim and writes the inequality a raised assurance would break.
2
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/adversary/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node adversary.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/adversary/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "adversary",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/arbiter/grammar.gf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/arbiter/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node arbiter.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/arbiter/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "arbiter",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "question (it): dato il punto A = (0, 0), il punto B = (2, 0) e il punto C = (1, 1), dimostra che A, B e C sono collineari\n@@DOSSIER@@{\"lang\":\"it\",\"question\":\"dato il punto A = (0, 0), il punto B = (2, 0) e il punto C = (1, 1), dimostra che A, B e C sono collineari\"}",
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,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node boundary (boundary): Boundary: checks that the sentence the geometry topology says it solved is the sentence that was sent to it.
2
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/boundary/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node boundary.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/boundary/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "boundary",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/coverage/grammar.gf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node coverage (coverage): Coverage: checks that the reading keeps every number and every name written in the question and that the question is inside the coverage of its language.
2
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/coverage/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node coverage.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/coverage/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "coverage",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/equivalence/grammar.gf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node equivalence (equivalence): Equivalence: compares the two readings and says whether they state the same figure and the same claim, with an SMT view when the text view is not enough.
2
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/equivalence/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node equivalence.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/equivalence/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "equivalence",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/invoker/grammar.gf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node invoker (invoker): Invoker: hands the agreed sentence to the geometry topology as a separate process and carries that verdict back untouched.
2
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/invoker/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node invoker.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/invoker/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "invoker",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/reader_a/grammar.gf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ -- Node reader_a (reader_a): First reader: turns a question written in one of the six user languages into a sentence of GeoLang, without seeing the other reader.
2
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/reader_a/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node reader_a.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/reader_a/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "reader_a",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
nodes/reader_b/grammar.gf ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ -- GeoLang: the controlled geometric language this stratum writes, which is the input language of the geometry topology.
3
+ -- Reference implementation: the readers lggeostratum/read_a.py and lggeostratum/read_b.py, the printer lggeostratum/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 are written bare (A, c, 3) instead of (PName "A"), (EName "c"), (Number "3"),
6
+ -- a list of point names is written (Names A B C), and a reference to a line, a segment or an angle is written
7
+ -- (LineOf A B), (SegmentOf A B), (AngleOf A B C), which is how the geometry language names the same object in one word.
8
+ abstract GeoLang = {
9
+ cat
10
+ Problem ; Decl ; Goal ; Name ; Ent ; Ref ; Names ; Num ;
11
+ fun
12
+ Point : Name -> Num -> Num -> Decl ;
13
+ Line : Ent -> Name -> Name -> Decl ;
14
+ CircleCentre : Ent -> Name -> Num -> Decl ;
15
+ CircleThree : Ent -> Names -> Decl ;
16
+ Midpoint : Name -> Name -> Name -> Decl ;
17
+ Centroid : Name -> Names -> Decl ;
18
+ Circumcentre : Name -> Names -> Decl ;
19
+ Intersection : Name -> Ref -> Ref -> Decl ;
20
+ NotCollinear : Names -> Decl ;
21
+ Distinct : Names -> Decl ;
22
+ FindCircumcircle : Names -> Problem ;
23
+ FindIntersection : Ref -> Ref -> Problem ;
24
+ FindTangents : Name -> Ent -> Problem ;
25
+ FindImage : Name -> Ent -> Problem ;
26
+ Prove : Goal -> Problem ;
27
+ Collinear : Names -> Goal ;
28
+ Perpendicular : Ref -> Ref -> Goal ;
29
+ Parallel : Ref -> Ref -> Goal ;
30
+ Congruent : Ref -> Ref -> Goal ;
31
+ RightAngle : Ref -> Goal ;
32
+ Between : Name -> Name -> Name -> Goal ;
33
+ OnCircle : Name -> Name -> Ref -> Goal ;
34
+ PName : String -> Name ;
35
+ EName : String -> Ent ;
36
+ Number : String -> Num ;
37
+ LineOf : Name -> Name -> Ref ;
38
+ SegmentOf : Name -> Name -> Ref ;
39
+ AngleOf : Name -> Name -> Name -> Ref ;
40
+ CircleNamed : Ent -> Ref ;
41
+ }
42
+
43
+ concrete GeoLangEng of GeoLang = {
44
+ lincat
45
+ Problem, Decl, Goal, Name, Ent, Ref, Names, Num = Str ;
46
+ lin
47
+ Point n x y = "Point " ++ n ++ " = (" ++ x ++ ", " ++ y ++ ")" ;
48
+ Line e a b = "Line " ++ e ++ " through " ++ a ++ " and " ++ b ;
49
+ CircleCentre e c r = "Circle " ++ e ++ " with center " ++ c ++ " and radius squared " ++ r ;
50
+ CircleThree e xs = "Circle " ++ e ++ " through " ++ xs ;
51
+ Midpoint t a b = "Let " ++ t ++ " be the midpoint of " ++ a ++ " and " ++ b ;
52
+ Centroid t xs = "Let " ++ t ++ " be the centroid of triangle " ++ xs ;
53
+ Circumcentre t xs = "Let " ++ t ++ " be the circumcenter of triangle " ++ xs ;
54
+ Intersection t l k = "Let " ++ t ++ " be the intersection of " ++ l ++ " and " ++ k ;
55
+ NotCollinear xs = "Assume " ++ xs ++ " are not collinear" ;
56
+ Distinct xs = "Assume " ++ xs ++ " are distinct" ;
57
+ FindCircumcircle xs = "Find the circumcircle of " ++ xs ;
58
+ FindIntersection l k = "Find the intersection of " ++ l ++ " and " ++ k ;
59
+ FindTangents p e = "Find the tangents from " ++ p ++ " to circle " ++ e ;
60
+ FindImage p e = "Find the image of " ++ p ++ " under " ++ e ;
61
+ Prove g = "Prove that " ++ g ;
62
+ Collinear xs = xs ++ " are collinear" ;
63
+ Perpendicular l k = l ++ " is perpendicular to " ++ k ;
64
+ Parallel l k = l ++ " is parallel to " ++ k ;
65
+ Congruent l k = l ++ " is congruent to " ++ k ;
66
+ RightAngle a = "angle " ++ a ++ " is a right angle" ;
67
+ Between p q r = p ++ " lies between " ++ q ++ " and " ++ r ;
68
+ OnCircle p q c = p ++ " lies on the circle with center " ++ q ++ " through " ++ c ;
69
+ PName s = s.s ;
70
+ EName s = s.s ;
71
+ Number s = s.s ;
72
+ LineOf a b = "line " ++ a ++ "-" ++ b ;
73
+ SegmentOf a b = "segment " ++ a ++ "-" ++ b ;
74
+ AngleOf a b c = "angle " ++ a ++ "-" ++ b ++ "-" ++ c ;
75
+ CircleNamed e = "circle " ++ e ;
76
+ }
nodes/reader_b/ontology.smt2 ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ ; SMT-LIB 2 ontology for the geometry-stratum topology node reader_b.
2
+ ; The claims this stratum hands to its referee are equalities over numerals: coordinates, squared
3
+ ; radii and squared distances, which the theory of real arithmetic built into Z3 decides in
4
+ ; milliseconds. The ontology fixes one solver option, because the geometry bundle also answers
5
+ ; constructed objects, and without a timeout one nonlinear configuration could block the session.
6
+ (set-option :timeout 8000)
nodes/reader_b/seed_payload.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "sender": "reader_b",
3
+ "turn": 0,
4
+ "volatileState": {
5
+ "internalTimeTick": 0
6
+ },
7
+ "payload": {
8
+ "naturalLanguage": "Idle until the question arrives.",
9
+ "abstractSyntaxTree": "Idle",
10
+ "smtConstraints": {
11
+ "declarations": [],
12
+ "assertions": [
13
+ "(assert true)"
14
+ ],
15
+ "z3Status": "sat"
16
+ }
17
+ }
18
+ }
problems/corpus.jsonl ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {"id": "collinear-en-true", "lang": "en", "kind": "collinear", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Prove that A, B and C are collinear.", "why": "Three points on the x axis: the claim is true and both readers build the same sentence.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}}
2
+ {"id": "collinear-en-false", "lang": "en", "kind": "collinear", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Prove that A, B and C are collinear.", "why": "The third point leaves the line, so the bundle must answer with a counterexample.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim does not hold: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Prove that A, B and C are collinear."}}
3
+ {"id": "perp-en-true", "lang": "en", "kind": "perp", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Let D be the point with coordinates (1, 2). Prove that line A-B is perpendicular to line C-D.", "why": "A vertical line against a horizontal one, written with the line reference of the formal language.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}}
4
+ {"id": "tangent-en", "lang": "en", "kind": "find_tangents", "question": "Let O be the point with coordinates (0, 0). Draw the circle c with center O and radius squared 4. Let P be the point with coordinates (4, 0). Find the tangents from P to circle c.", "why": "A point outside a circle: the bundle answers the computation, not a proof.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}}
5
+ {"id": "mid-en", "lang": "en", "kind": "perp", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (4, 0). Let M be the midpoint of A and B. Let C be the point with coordinates (2, 2). Prove that line A-B is perpendicular to line M-C.", "why": "The midpoint is defined, then used in a claim about two perpendicular lines.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line M-C", "sentence": "Point A = (0, 0). Point B = (4, 0). Let M be the midpoint of A and B. Point C = (2, 2). Prove that line A-B is perpendicular to line M-C."}}
6
+ {"id": "collinear-it-true", "lang": "it", "kind": "collinear", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 0). Dimostra che i punti A, B e C sono collineari.", "why": "Italian with the copula of the definition spelled out and the claim carried by the joint.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}}
7
+ {"id": "collinear-it-false", "lang": "it", "kind": "collinear", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 1). Dimostra che i punti A, B e C sono allineati.", "why": "The same Italian sentence with a point off the line.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim does not hold: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Prove that A, B and C are collinear."}}
8
+ {"id": "perp-it-true", "lang": "it", "kind": "perp", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 0). Sia D il punto di coordinate (1, 2). Dimostra che la retta A-B è perpendicolare alla retta C-D.", "why": "Italian contracted preposition, perpendicolare alla retta, on both sides of the relation.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}}
9
+ {"id": "circumcircle-it", "lang": "it", "kind": "find_circumcircle", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 1). Trova la circonferenza circoscritta al triangolo A, B e C.", "why": "A find problem in Italian: the request has no marker, so the frame is empty.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"center\":[\"1\",\"0\"]", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Find the circumcircle of A, B and C."}}
10
+ {"id": "tangent-it", "lang": "it", "kind": "find_tangents", "question": "Sia O il punto di coordinate (0, 0). Disegna la circonferenza c con centro O e raggio al quadrato 4. Sia P il punto di coordinate (4, 0). Trova le tangenti da P alla circonferenza c.", "why": "A tangent request in Italian: the circle is named with its article and the point of departure with its preposition.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}}
11
+ {"id": "bisector-it-unknown", "lang": "it", "kind": "negative", "question": "Traccia la bisettrice dell angolo B in A e C.", "why": "A bisector is not in the lexicon of any variety: the layer must refuse and show no answer.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}}
12
+ {"id": "passthrough-it", "lang": "it", "kind": "collinear", "question": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear.", "why": "The question is already the formal language, so it is handed over unread.", "expect": {"state": "PASSTHROUGH", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}}
13
+ {"id": "cong-es-true", "lang": "es", "kind": "cong", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (4, 0). Demuestre que el segmento A-B es congruente con el segmento B-C.", "why": "Spanish congruence of two segments on one line.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: segment A-B is congruent to segment B-C", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (4, 0). Prove that segment A-B is congruent to segment B-C."}}
14
+ {"id": "collinear-es-false", "lang": "es", "kind": "collinear", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (1, 1). Demuestre que los puntos A, B y C son colineales.", "why": "Spanish with a point off the line, so the answer is a counterexample.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim does not hold: A, B and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Prove that A, B and C are collinear."}}
15
+ {"id": "mid-es-true", "lang": "es", "kind": "collinear", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea M el punto medio de A y B. Sea C el punto con coordenadas (1, 0). Demuestre que los puntos A, M y C son colineales.", "why": "Spanish midpoint, then a collinearity claim that uses the defined point.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, M and C are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Point C = (1, 0). Prove that A, M and C are collinear."}}
16
+ {"id": "circumcircle-es", "lang": "es", "kind": "find_circumcircle", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (1, 1). Halle la circunferencia circunscrita al triangulo A, B y C.", "why": "A Spanish find problem with the circumscribed circle named in the variety.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"center\":[\"1\",\"0\"]", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Find the circumcircle of A, B and C."}}
17
+ {"id": "collinear-zh-true", "lang": "zh", "kind": "collinear", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。证明 A, B 和 C 共线。", "why": "Chinese written with spaces between the atoms of the figure.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}}
18
+ {"id": "perp-zh-true", "lang": "zh", "kind": "perp", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 0)。设 D 的坐标为 (1, 2)。证明 直线 A-B 垂直于 直线 C-D。", "why": "Chinese perpendicularity with the line reference of the formal language.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}}
19
+ {"id": "circumcircle-zh", "lang": "zh", "kind": "find_circumcircle", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (1, 1)。求 三角形 A, B 和 C 的 外接圆。", "why": "A Chinese find problem whose request is a two character sequence recognised as one atom.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"center\":[\"1\",\"0\"]", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Find the circumcircle of A, B and C."}}
20
+ {"id": "mid-zh-single", "lang": "zh", "kind": "collinear", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 M 平分 线段 A B。证明 A, M 和 B 共线。", "why": "The Chinese form glues the two endpoints into one region, so only one reader builds a sentence.", "expect": {"state": "SINGLE", "referee_clean": true, "min_assurance": 1, "max_assurance": 1, "answer_contains": "the claim holds: A, M and B are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Prove that A, M and B are collinear."}}
21
+ {"id": "collinear-hi-true", "lang": "hi", "kind": "collinear", "question": "मान लें बिंदु A के निर्देशांक (0, 0) हैं। मान लें बिंदु B के निर्देशांक (2, 0) हैं। मान लें बिंदु C के निर्देशांक (1, 0) हैं। सिद्ध कीजिए कि A, B और C संरेख हैं।", "why": "Hindi with the coordinate marker before the value and the claim carried by the joint.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}}
22
+ {"id": "perp-hi-true", "lang": "hi", "kind": "perp", "question": "मान लें बिंदु A के निर्देशांक (0, 0) हैं। मान लें बिंदु B के निर्देशांक (2, 0) हैं। मान लें बिंदु C के निर्देशांक (1, 0) हैं। मान लें बिंदु D के निर्देशांक (1, 2) हैं। सिद्ध कीजिए कि रेखा A-B लंब है रेखा C-D पर।", "why": "Hindi puts the verb of the relation before the second line, which the frame of the kind accepts.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}}
23
+ {"id": "mid-hi-single", "lang": "hi", "kind": "collinear", "question": "मान लें बिंदु A के निर्देशांक (0, 0) हैं। मान लें बिंदु B के निर्देशांक (2, 0) हैं। मान लें M, A और B का मध्यबिंदु है। सिद्ध कीजिए कि A, M और B संरेख हैं।", "why": "Hindi closes the sentence with the midpoint marker, after the two endpoints, so the frame of the kind is not met.", "expect": {"state": "SINGLE", "referee_clean": true, "min_assurance": 1, "max_assurance": 1, "answer_contains": "the claim holds: A, M and B are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Prove that A, M and B are collinear."}}
24
+ {"id": "tangent-hi", "lang": "hi", "kind": "find_tangents", "question": "मान लें बिंदु O के निर्देशांक (0, 0) हैं। बनाइए वृत्त c का केंद्र O त्रिज्या का वर्ग 4 है। मान लें बिंदु P के निर्देशांक (4, 0) हैं। ज्ञात कीजिए P से वृत्त c की स्पर्शरेखाएँ।", "why": "A Hindi find problem with the circle of the figure named in the variety.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}}
25
+ {"id": "collinear-ar-true", "lang": "ar", "kind": "collinear", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). لتكن النقطة C إحداثياتها (1, 0). أثبت أن A و B و C على استقامة واحدة.", "why": "Arabic with the conjunction written as its own atom between the names.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that A, B and C are collinear."}}
26
+ {"id": "perp-ar-true", "lang": "ar", "kind": "perp", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). لتكن النقطة C إحداثياتها (1, 0). لتكن النقطة D إحداثياتها (1, 2). أثبت أن المستقيم A-B عمودي على المستقيم C-D.", "why": "Arabic perpendicularity with the article attached to the word for line.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is perpendicular to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Prove that line A-B is perpendicular to line C-D."}}
27
+ {"id": "tangent-ar", "lang": "ar", "kind": "find_tangents", "question": "لتكن النقطة O إحداثياتها (0, 0). ارسم الدائرة c مركزها O مربع نصف القطر 4. لتكن النقطة P إحداثياتها (4, 0). أوجد المماسات من P إلى الدائرة c.", "why": "An Arabic find problem: the circle is named with its article and the point of departure with its preposition.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"tangent_length2\":\"12\"", "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4. Point P = (4, 0). Find the tangents from P to circle c."}}
28
+ {"id": "mid-ar-true", "lang": "ar", "kind": "collinear", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). خذ M منتصف A و B. أثبت أن A و M و B على استقامة واحدة.", "why": "Arabic midpoint written with the imperative of the definition and the two endpoints in order.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: A, M and B are collinear", "sentence": "Point A = (0, 0). Point B = (2, 0). Let M be the midpoint of A and B. Prove that A, M and B are collinear."}}
29
+ {"id": "point-en", "lang": "en", "kind": "define_point", "question": "Let A be the point with coordinates (0, 0). Let P be the point with coordinates (2, 3).", "why": "A definition with nothing to prove: both readers write the points, and the layer has no question to answer, so no assurance is shown.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point P = (2, 3)."}}
30
+ {"id": "line-en", "lang": "en", "kind": "define_line", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Draw the line r through the points A and B.", "why": "A line through two named points, with the article of the variety before the word for line; the figure is built and nothing is claimed.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Line r through A and B."}}
31
+ {"id": "circle-en", "lang": "en", "kind": "define_circle", "question": "Let O be the point with coordinates (0, 0). Draw the circle c with center O and radius squared 4.", "why": "A circle given by its centre and its squared radius, read by both readers.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4."}}
32
+ {"id": "assume-en", "lang": "en", "kind": "assume", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Suppose A, B and C are not collinear.", "why": "The question states a premise and asks nothing: the assumption is carried into the sentence and the layer stays silent.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Assume A, B and C are not collinear."}}
33
+ {"id": "centroid-en", "lang": "en", "kind": "centroid", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Let G be the centroid of the triangle A, B and C.", "why": "The centroid of a named triangle, with the article that the pattern of English asks for.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Let G be the centroid of triangle A, B and C."}}
34
+ {"id": "circumcentre-en", "lang": "en", "kind": "circumcentre", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 1). Let G be the circumcenter of the triangle A, B and C.", "why": "The circumcenter of a named triangle, one joint of the frame per reader.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Let G be the circumcenter of triangle A, B and C."}}
35
+ {"id": "intersect-en", "lang": "en", "kind": "intersect", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Let D be the point with coordinates (1, 2). Let X be the intersection of the line A-B and the line C-D.", "why": "The intersection point of two lines given by their endpoints, defined but not asked about.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Let X be the intersection of line A-B and line C-D."}}
36
+ {"id": "right-en", "lang": "en", "kind": "right", "question": "Let A be the point with coordinates (2, 0). Let B be the point with coordinates (0, 0). Let C be the point with coordinates (0, 2). Prove that the angle A-B-C is a right angle.", "why": "A right angle named by its three letters, dashed the way the formal language writes an angle reference.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: angle A-B-C is a right angle", "sentence": "Point A = (2, 0). Point B = (0, 0). Point C = (0, 2). Prove that angle A-B-C is a right angle."}}
37
+ {"id": "between-en", "lang": "en", "kind": "between", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Prove that C lies between A and B.", "why": "Betweenness of three points on one line, the relation named after the point that lies in the middle.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: C lies between A and B", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Prove that C lies between A and B."}}
38
+ {"id": "oncircle-en", "lang": "en", "kind": "oncircle", "question": "Let O be the point with coordinates (0, 0). Let A be the point with coordinates (2, 0). Let P be the point with coordinates (0, 2). Prove that P lies on the circle with center O through A.", "why": "A point on a circle described by its centre and by a point the circle passes through.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: P lies on the circle with center O through A", "sentence": "Point O = (0, 0). Point A = (2, 0). Point P = (0, 2). Prove that P lies on the circle with center O through A."}}
39
+ {"id": "par-en", "lang": "en", "kind": "par", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (0, 1). Let D be the point with coordinates (2, 1). Prove that line A-B is parallel to line C-D.", "why": "Two horizontal lines: parallelism written with the line reference of the formal language.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}}
40
+ {"id": "image-en", "lang": "en", "kind": "find_image", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Draw the line r through the points A and B. Let P be the point with coordinates (1, 1). Find the image of P under the transformation r.", "why": "The transformation is named with the word of the variety but never defined, so the layer cannot answer and the stratum shows no result even though both readers agree.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Line r through A and B. Point P = (1, 1). Find the image of P under r."}}
41
+ {"id": "findintersect-en", "lang": "en", "kind": "find_intersect", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (2, 0). Let C be the point with coordinates (1, 0). Let D be the point with coordinates (1, 2). Draw the line r through the points A and B. Draw the line s through the points C and D. Find where the line r and the line s meet.", "why": "A find problem with no marker at all: a verb and two line references, and both readers build the same sentence.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"kind\":\"intersection\"", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Line r through A and B. Line s through C and D. Find the intersection of line r and line s."}}
42
+ {"id": "bisector-en", "lang": "en", "kind": "negative", "question": "Find the bisector of the angle A-B-C.", "why": "A bisector is outside the lexicon of every variety, so the stratum refuses and answers nothing.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}}
43
+ {"id": "par-it", "lang": "it", "kind": "par", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (0, 1). Sia D il punto di coordinate (2, 1). Dimostra che la retta A-B è parallela alla retta C-D.", "why": "Italian parallelism with the contracted preposition on both sides of the relation.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}}
44
+ {"id": "circle-it", "lang": "it", "kind": "define_circle", "question": "Sia O il punto di coordinate (0, 0). Disegna la circonferenza c con centro O e raggio al quadrato 4.", "why": "An Italian circle with centre and squared radius, the conjunction of the frame inside one chunk of the pattern.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point O = (0, 0). Circle c with center O and radius squared 4."}}
45
+ {"id": "findintersect-it", "lang": "it", "kind": "find_intersect", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 0). Sia D il punto di coordinate (1, 2). Disegna la retta r per i punti A e B. Disegna la retta s per i punti C e D. Trova il punto in comune tra la retta r e la retta s.", "why": "The same request in Italian, with the point in common named in the variety.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "\"kind\":\"intersection\"", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Line r through A and B. Line s through C and D. Find the intersection of line r and line s."}}
46
+ {"id": "centroid-it", "lang": "it", "kind": "centroid", "question": "Sia A il punto di coordinate (0, 0). Sia B il punto di coordinate (2, 0). Sia C il punto di coordinate (1, 1). Sia G il baricentro del triangolo A, B e C.", "why": "An Italian definition of the centroid of a triangle, with no claim attached.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 1). Let G be the centroid of triangle A, B and C."}}
47
+ {"id": "oncircle-it", "lang": "it", "kind": "oncircle", "question": "Sia O il punto di coordinate (0, 0). Sia A il punto di coordinate (2, 0). Sia P il punto di coordinate (0, 2). Dimostra che P giace sulla circonferenza di centro O e passante per A.", "why": "Italian: the circle is named by its centre and by the point it passes through.", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: P lies on the circle with center O through A", "sentence": "Point O = (0, 0). Point A = (2, 0). Point P = (0, 2). Prove that P lies on the circle with center O through A."}}
48
+ {"id": "findintersect-es", "lang": "es", "kind": "find_intersect", "question": "Sea A el punto con coordenadas (0, 0). Sea B el punto con coordenadas (2, 0). Sea C el punto con coordenadas (1, 0). Sea D el punto con coordenadas (1, 2). Trace la recta r por los puntos A y B. Trace la recta s por los puntos C y D. Halle el punto en comun de la recta r y la recta s.", "why": "Spanish meets it with one reader only: reader A follows the pattern, while reader B finds a marker where the kind expects none.", "expect": {"state": "SINGLE", "referee_clean": true, "min_assurance": 1, "max_assurance": 1, "answer_contains": "\"kind\":\"intersection\"", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (1, 0). Point D = (1, 2). Line r through A and B. Line s through C and D. Find the intersection of line r and line s."}}
49
+ {"id": "negative-es", "lang": "es", "kind": "negative", "question": "Halle el area del triangulo A, B y C.", "why": "The area of a figure is not a request of this language: the layer refuses it.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}}
50
+ {"id": "par-zh", "lang": "zh", "kind": "par", "question": "设 A 的坐标为 (0, 0)。设 B 的坐标为 (2, 0)。设 C 的坐标为 (0, 1)。设 D 的坐标为 (2, 1)。证明 直线 A-B 平行于 直线 C-D。", "why": "", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}}
51
+ {"id": "negative-zh", "lang": "zh", "kind": "negative", "question": "求 A, B 和 C 的 内接矩形。", "why": "Chinese names a figure that no variety of this stratum has a word for.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}}
52
+ {"id": "right-hi", "lang": "hi", "kind": "right", "question": "मान लें बिंदु A के निर्देशांक (2, 0) हैं। मान लें बिंदु B के निर्देशांक (0, 0) हैं। मान ��ें बिंदु C के निर्देशांक (0, 2) हैं। सिद्ध कीजिए कि कोण A-B-C समकोण है", "why": "", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: angle A-B-C is a right angle", "sentence": "Point A = (2, 0). Point B = (0, 0). Point C = (0, 2). Prove that angle A-B-C is a right angle."}}
53
+ {"id": "negative-hi", "lang": "hi", "kind": "negative", "question": "ज्ञात कीजिए त्रिभुज A, B और C का क्षेत्रफल", "why": "Hindi asks for a quantity the geometry layer does not compute.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}}
54
+ {"id": "par-ar", "lang": "ar", "kind": "par", "question": "لتكن النقطة A إحداثياتها (0, 0). لتكن النقطة B إحداثياتها (2, 0). لتكن النقطة C إحداثياتها (0, 1). لتكن النقطة D إحداثياتها (2, 1). أثبت أن المستقيم A-B موازٍ للمستقيم C-D.", "why": "", "expect": {"state": "AGREED", "referee_clean": true, "min_assurance": 2, "answer_contains": "the claim holds: line A-B is parallel to line C-D", "sentence": "Point A = (0, 0). Point B = (2, 0). Point C = (0, 1). Point D = (2, 1). Prove that line A-B is parallel to line C-D."}}
55
+ {"id": "negative-ar", "lang": "ar", "kind": "negative", "question": "أوجد مساحة المثلث A و B و C", "why": "Arabic asks for an area, which lies outside the controlled language.", "expect": {"state": "NOT COVERED", "referee_clean": true, "max_assurance": 0, "no_answer": true}}
56
+ {"id": "mid-en-def", "lang": "en", "kind": "mid", "question": "Let A be the point with coordinates (0, 0). Let B be the point with coordinates (4, 0). Let M be the midpoint of A and B.", "why": "The midpoint of two points, defined on its own: the sentence is read and the layer has nothing to answer.", "expect": {"state": "AGREED", "referee_clean": true, "max_assurance": 0, "no_answer": true, "sentence": "Point A = (0, 0). Point B = (4, 0). Let M be the midpoint of A and B."}}