Datasets:
Modalities:
Text
Formats:
json
Size:
< 1K
Tags:
multilingual
geometry
theorem-proving
natural-language-to-formal-language
multi-agent-systems
benchmark
update geometry-stratum bundle
Browse files- README.md +64 -57
- agents/stratum_agent +1 -1
- lingologos_geostratum/__init__.py +20 -0
- lingologos_geostratum/agents.py +364 -0
- lingologos_geostratum/canonical.py +662 -0
- lingologos_geostratum/compare.py +313 -0
- lingologos_geostratum/corpus.py +84 -0
- lingologos_geostratum/coverage.py +93 -0
- lingologos_geostratum/decide.py +166 -0
- lingologos_geostratum/faults.py +188 -0
- lingologos_geostratum/invoker.py +103 -0
- lingologos_geostratum/lexicon.py +462 -0
- lingologos_geostratum/pipeline.py +116 -0
- lingologos_geostratum/protocol.py +79 -0
- lingologos_geostratum/read_a.py +402 -0
- lingologos_geostratum/read_b.py +338 -0
- lingologos_geostratum/render.py +140 -0
- lingologos_geostratum/segment.py +240 -0
- nodes/adversary/grammar.gf +1 -1
- nodes/arbiter/grammar.gf +1 -1
- nodes/boundary/grammar.gf +1 -1
- nodes/coverage/grammar.gf +1 -1
- nodes/equivalence/grammar.gf +1 -1
- nodes/invoker/grammar.gf +1 -1
- nodes/reader_a/grammar.gf +1 -1
- nodes/reader_b/grammar.gf +1 -1
- tests/test_corpus.py +1 -1
- tests/test_decide.py +1 -1
- tests/test_faults.py +1 -1
- tests/test_lexicon.py +1 -1
- tests/test_orchestrator_e2e.py +1 -1
- tests/test_pinned_invariant.py +2 -2
- tests/test_readers.py +1 -1
- tests/test_topology.py +5 -5
- tools/ablation.py +2 -2
- tools/ask.py +6 -6
- tools/coverage_report.py +1 -1
- tools/geometry_runner.py +2 -2
- tools/publish_dataset.py +31 -23
README.md
CHANGED
|
@@ -54,12 +54,11 @@ echo the boundary node checks. A person who asked in Chinese reads the labels in
|
|
| 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 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
folder at a copy of it.
|
| 63 |
|
| 64 |
## 1. What the stratum is, and what it refuses
|
| 65 |
|
|
@@ -163,17 +162,17 @@ the assurance goes down, never up: `DISPUTED` does not even consult the geometry
|
|
| 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 `
|
| 167 |
-
that bundle, maps the session's verdict onto the small shape this layer copies, and re-runs the
|
| 168 |
-
of every envelope that session wrote with the bundle's own solver, so that a verdict reported
|
| 169 |
-
checked against the same query the session believed it had discharged.
|
| 170 |
|
| 171 |
| Variable | Meaning |
|
| 172 |
|---|---|
|
| 173 |
-
| `
|
| 174 |
-
| `
|
| 175 |
-
| `
|
| 176 |
-
| `
|
| 177 |
|
| 178 |
The assurance the runner reports, read off the evidence the bundle itself recorded:
|
| 179 |
|
|
@@ -202,17 +201,17 @@ question already written in that language. Each line carries what the answer has
|
|
| 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
|
| 206 |
-
grades one row, `tests/test_corpus.py` runs all of them). The states
|
| 207 |
-
`PASSTHROUGH` and 6 `NOT COVERED`; `tools/coverage_report.py` writes
|
| 208 |
-
**46** questions read by both readers, **3** by `reader_a` alone and
|
| 209 |
-
`PASSTHROUGH` row was never read at all, because there was nothing to translate.
|
| 210 |
-
`line-en`, `circle-en`, `circle-it`, `assume-en`, `centroid-en`, `centroid-it`,
|
| 211 |
-
`intersect-en`, `image-en`, `mid-en-def`) are agreed readings on which the geometry
|
| 212 |
-
figure of definitions with no claim in it, or a `find the image` with no transformation
|
| 213 |
-
assurance is 0 and no answer appears, which is the layer refusing to add an availability it
|
| 214 |
-
have. Three rows (`mid-zh-single`, `mid-hi-single`, `findintersect-es`) stay at `SINGLE`,
|
| 215 |
-
the reason in section 7.
|
| 216 |
|
| 217 |
## 6. Commands
|
| 218 |
|
|
@@ -237,18 +236,19 @@ the rule of section 1, and the tool exits 1 if any happened. A `caught` cell is
|
|
| 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
|
| 241 |
-
takes hold in **720** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 1`, `caught
|
| 242 |
-
`abstained 561`, `masked 126` -- under four minutes. Nothing was ever raised above the honest
|
| 243 |
-
The 32 `caught` cells all sit in the two configurations that are missing one reader, where a
|
| 244 |
-
stamped node cannot buy back the level that the missing witness costs. The shape of the columns
|
| 245 |
-
from the arithmetic stratum of the same project: in a figure a damaged reading almost never
|
| 246 |
-
a weaker answer, because what the readers produce has to stay a parseable problem with every
|
| 247 |
-
kept, so 561 cells end with no answer at all rather than a lower one. The one `silent_error` is
|
| 248 |
-
spot of section 3 shown in numbers: with `merge_slots` fired in both readers at once, the
|
| 249 |
-
congruence row turns into `segment A-B is congruent to segment A-B` -- both readers merged the
|
| 250 |
-
of names, so the two readings agree, the claim is trivially provable, the bundle certifies it,
|
| 251 |
-
session answers at level 2 about a question nobody asked. The only witness against it is the
|
|
|
|
| 252 |
|
| 253 |
## 7. Limits that are written down, not hidden
|
| 254 |
|
|
@@ -294,10 +294,10 @@ and asserts that the verdict of the geometry layer does not move, and that nothi
|
|
| 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
|
| 298 |
-
`geometry` dataset named by `
|
| 299 |
-
LingoLOGOS checkout, and the two end to end tests skip on their own when
|
| 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
|
|
@@ -306,9 +306,9 @@ comes back the same way -- `AGREED`, assurance 2, the geometry layer `VERIFIED`,
|
|
| 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 `
|
| 310 |
-
plumbing of its own equivalence claim; the modules that decide, route and invoke hold no reference
|
| 311 |
-
and the session is reached as a separate process.
|
| 312 |
|
| 313 |
## 9. Language policy
|
| 314 |
|
|
@@ -321,26 +321,33 @@ 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 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
`
|
| 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 |
-
|
| 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 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
## 11. The corpus file
|
| 346 |
|
|
@@ -402,7 +409,7 @@ 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 `
|
| 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 |
|
|
|
|
| 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 `z3-solver`
|
| 58 |
+
are required, and `pytest` for the tests; both are named in `requirements.txt`. Every command below is
|
| 59 |
+
written from inside the folder. The geometry layer is not part of this dataset: it lives in the `geometry`
|
| 60 |
+
bundle, published at https://huggingface.co/datasets/tailot/lingologos-geometry, and section 10 says how
|
| 61 |
+
to point this folder at a copy of it.
|
|
|
|
| 62 |
|
| 63 |
## 1. What the stratum is, and what it refuses
|
| 64 |
|
|
|
|
| 162 |
`python tools/geometry_runner.py --json <figure>` -- a script of this folder -- and reads its JSON verdict
|
| 163 |
back; nothing in this folder imports the geometry bundle to decide anything here. That runner is the only
|
| 164 |
place in the bundle where `geometry` is loaded: it finds the bundle in the sibling folder
|
| 165 |
+
`datasets/geometry`, or in the copy named by `LINGOLOGOS_STRATUM_GEOMETRY_ROOT`, starts the seven agent
|
| 166 |
+
session of that bundle, maps the session's verdict onto the small shape this layer copies, and re-runs the
|
| 167 |
+
SMT claim of every envelope that session wrote with the bundle's own solver, so that a verdict reported
|
| 168 |
+
here is checked against the same query the session believed it had discharged.
|
| 169 |
|
| 170 |
| Variable | Meaning |
|
| 171 |
|---|---|
|
| 172 |
+
| `LINGOLOGOS_STRATUM_GEOMETRY_ROOT` | where the `geometry` bundle is (default: the sibling folder `datasets/geometry`) |
|
| 173 |
+
| `LINGOLOGOS_STRATUM_GEOMETRY_BACKEND` | `subprocess` (default), or `none` to disable the geometry layer entirely |
|
| 174 |
+
| `LINGOLOGOS_STRATUM_GEOMETRY_TIMEOUT` | seconds that session may take (default 180) |
|
| 175 |
+
| `LINGOLOGOS_STRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only |
|
| 176 |
|
| 177 |
The assurance the runner reports, read off the evidence the bundle itself recorded:
|
| 178 |
|
|
|
|
| 201 |
`sentence`, `answer_contains`, `min_assurance`, `max_assurance`, `no_answer`, `referee_clean`) and a `why`
|
| 202 |
that says why, including the cases where the expected outcome is an abstention.
|
| 203 |
|
| 204 |
+
Graded against the in-process pipeline: **56 of 56** rows agree with their gold
|
| 205 |
+
(`lingologos_geostratum/corpus.py` grades one row, `tests/test_corpus.py` runs all of them). The states
|
| 206 |
+
come out 46 `AGREED`, 3 `SINGLE`, 1 `PASSTHROUGH` and 6 `NOT COVERED`; `tools/coverage_report.py` writes
|
| 207 |
+
`results/coverage.json` and counts **46** questions read by both readers, **3** by `reader_a` alone and
|
| 208 |
+
**6** by neither -- the `PASSTHROUGH` row was never read at all, because there was nothing to translate.
|
| 209 |
+
Eleven rows (`point-en`, `line-en`, `circle-en`, `circle-it`, `assume-en`, `centroid-en`, `centroid-it`,
|
| 210 |
+
`circumcentre-en`, `intersect-en`, `image-en`, `mid-en-def`) are agreed readings on which the geometry
|
| 211 |
+
layer abstains: a figure of definitions with no claim in it, or a `find the image` with no transformation
|
| 212 |
+
named. The assurance is 0 and no answer appears, which is the layer refusing to add an availability it
|
| 213 |
+
does not have. Three rows (`mid-zh-single`, `mid-hi-single`, `findintersect-es`) stay at `SINGLE`,
|
| 214 |
+
assurance 1, for the reason in section 7.
|
| 215 |
|
| 216 |
## 6. Commands
|
| 217 |
|
|
|
|
| 236 |
shown that the gold does not accept, but the session said so itself -- a claim fell to the referee of its
|
| 237 |
node, or the assurance sits below the honest one because the configuration lost a node.
|
| 238 |
|
| 239 |
+
On this checkout `--probe 6` (one question per variety) fills **147 cells** and **882 sessions**, the
|
| 240 |
+
fault takes hold in **720** of them, and the totals are `raised 0`, `lowered 0`, `silent_error 1`, `caught
|
| 241 |
+
32`, `abstained 561`, `masked 126` -- under four minutes. Nothing was ever raised above the honest
|
| 242 |
+
assurance. The 32 `caught` cells all sit in the two configurations that are missing one reader, where a
|
| 243 |
+
rubber stamped node cannot buy back the level that the missing witness costs. The shape of the columns
|
| 244 |
+
differs from the arithmetic stratum of the same project: in a figure a damaged reading almost never
|
| 245 |
+
survives as a weaker answer, because what the readers produce has to stay a parseable problem with every
|
| 246 |
+
coordinate kept, so 561 cells end with no answer at all rather than a lower one. The one `silent_error` is
|
| 247 |
+
the blind spot of section 3 shown in numbers: with `merge_slots` fired in both readers at once, the
|
| 248 |
+
Spanish congruence row turns into `segment A-B is congruent to segment A-B` -- both readers merged the
|
| 249 |
+
same pair of names, so the two readings agree, the claim is trivially provable, the bundle certifies it,
|
| 250 |
+
and the session answers at level 2 about a question nobody asked. The only witness against it is the
|
| 251 |
+
person.
|
| 252 |
|
| 253 |
## 7. Limits that are written down, not hidden
|
| 254 |
|
|
|
|
| 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
|
| 298 |
+
copy of the `geometry` dataset named by `LINGOLOGOS_STRATUM_GEOMETRY_ROOT` (section 10); the suite took 57
|
| 299 |
+
seconds inside a LingoLOGOS checkout, and the two end to end tests skip on their own when
|
| 300 |
+
`lingologos_orchestrator` is 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
|
|
|
|
| 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 `lingologos_geostratum/compare.py` may import the `geometry` package, and only for
|
| 310 |
+
the SMT plumbing of its own equivalence claim; the modules that decide, route and invoke hold no reference
|
| 311 |
+
to it, and the session is reached as a separate process.
|
| 312 |
|
| 313 |
## 9. Language policy
|
| 314 |
|
|
|
|
| 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 node
|
| 325 |
+
definitions, the two readers, the decision rule of section 1, the corpus grading and fault results under
|
| 326 |
+
`results/`, and the fault catalogue of section 6. To decide a figure it needs the `geometry` bundle:
|
| 327 |
+
download https://huggingface.co/datasets/tailot/lingologos-geometry somewhere, set
|
| 328 |
+
`LINGOLOGOS_STRATUM_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 `src/lingologos_orchestrator`
|
| 332 |
+
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 dataset in the table of published resources at
|
| 340 |
+
the top of its README; the documentation of the asset lives here, in this card, and not in the technical
|
| 341 |
+
documentation of the project. Republishing is a separate step, never a side effect of a test run:
|
| 342 |
+
`tools/publish_dataset.py` in the folder of the project does it with the token taken from an environment
|
| 343 |
+
variable and verifies the tree by sha256.
|
| 344 |
+
|
| 345 |
+
An earlier published revision of this dataset held its library as `lggeostratum/` and read its four
|
| 346 |
+
handles as `LGSTRATUM_FAULTS`, `LGSTRATUM_GEOMETRY_ROOT`, `LGSTRATUM_GEOMETRY_BACKEND` and
|
| 347 |
+
`LGSTRATUM_GEOMETRY_TIMEOUT`. The names moved and nothing else: the 68 files, the 56 questions, the six
|
| 348 |
+
lexicons, the eight node definitions, the two readers, the decision rule of section 1 and the 255 tests
|
| 349 |
+
are the ones that revision published. The geometry layer this stratum talks to never carried the prefix,
|
| 350 |
+
so none of its names moved.
|
| 351 |
|
| 352 |
## 11. The corpus file
|
| 353 |
|
|
|
|
| 409 |
print(rows[0])
|
| 410 |
```
|
| 411 |
|
| 412 |
+
This is the same file `tools/ask.py --corpus` walks over, and `lingologos_geostratum/corpus.py` plus
|
| 413 |
`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 56 of 56
|
| 414 |
rows agree with what they expect.
|
| 415 |
|
agents/stratum_agent
CHANGED
|
@@ -20,7 +20,7 @@ import sys
|
|
| 20 |
|
| 21 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 22 |
|
| 23 |
-
from
|
| 24 |
|
| 25 |
|
| 26 |
def main() -> int:
|
|
|
|
| 20 |
|
| 21 |
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 22 |
|
| 23 |
+
from lingologos_geostratum import agents, faults # noqa: E402
|
| 24 |
|
| 25 |
|
| 26 |
def main() -> int:
|
lingologos_geostratum/__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"]
|
lingologos_geostratum/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")
|
lingologos_geostratum/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)}
|
lingologos_geostratum/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:`LINGOLOGOS_STRATUM_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
|
lingologos_geostratum/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
|
lingologos_geostratum/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 |
+
}
|
lingologos_geostratum/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
|
lingologos_geostratum/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 LINGOLOGOS_STRATUM_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("LINGOLOGOS_STRATUM_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
|
lingologos_geostratum/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 |
+
``LINGOLOGOS_STRATUM_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 |
+
``LINGOLOGOS_STRATUM_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("LINGOLOGOS_STRATUM_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("LINGOLOGOS_STRATUM_GEOMETRY_BACKEND", "subprocess") or "subprocess").strip().lower()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def timeout_seconds() -> int:
|
| 45 |
+
try:
|
| 46 |
+
return max(5, int(os.environ.get("LINGOLOGOS_STRATUM_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 LINGOLOGOS_STRATUM_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 |
+
}
|
lingologos_geostratum/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()
|
lingologos_geostratum/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("LINGOLOGOS_STRATUM_GEOMETRY_BACKEND")
|
| 42 |
+
if not call_geometry:
|
| 43 |
+
os.environ["LINGOLOGOS_STRATUM_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("LINGOLOGOS_STRATUM_GEOMETRY_BACKEND", None)
|
| 63 |
+
else:
|
| 64 |
+
os.environ["LINGOLOGOS_STRATUM_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
|
lingologos_geostratum/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)
|
lingologos_geostratum/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:`lingologos_geostratum.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:`lingologos_geostratum.segment` and the templates of the geometry language in
|
| 13 |
+
:mod:`lingologos_geostratum.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
|
lingologos_geostratum/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
|
lingologos_geostratum/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 |
+
}
|
lingologos_geostratum/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:`lingologos_geostratum.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:`lingologos_geostratum.read_a`
|
| 192 |
+
and :mod:`lingologos_geostratum.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
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/arbiter/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/boundary/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/coverage/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/equivalence/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/invoker/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/reader_a/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
nodes/reader_b/grammar.gf
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 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
|
| 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
|
|
|
|
| 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 lingologos_geostratum/read_a.py and lingologos_geostratum/read_b.py, the printer lingologos_geostratum/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
|
tests/test_corpus.py
CHANGED
|
@@ -7,7 +7,7 @@ to the topology and visible only here, in a sentence a person wrote and checked.
|
|
| 7 |
|
| 8 |
import pytest
|
| 9 |
|
| 10 |
-
from
|
| 11 |
|
| 12 |
ITEMS = corpus.load()
|
| 13 |
IDS = [str(item["id"]) for item in ITEMS]
|
|
|
|
| 7 |
|
| 8 |
import pytest
|
| 9 |
|
| 10 |
+
from lingologos_geostratum import canonical, corpus, lexicon
|
| 11 |
|
| 12 |
ITEMS = corpus.load()
|
| 13 |
IDS = [str(item["id"]) for item in ITEMS]
|
tests/test_decide.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
|
| 3 |
import copy
|
| 4 |
|
| 5 |
-
from
|
| 6 |
|
| 7 |
|
| 8 |
def _reading(sentence, kind="collinear", slots=None, notes=()):
|
|
|
|
| 2 |
|
| 3 |
import copy
|
| 4 |
|
| 5 |
+
from lingologos_geostratum import decide, pipeline
|
| 6 |
|
| 7 |
|
| 8 |
def _reading(sentence, kind="collinear", slots=None, notes=()):
|
tests/test_faults.py
CHANGED
|
@@ -8,7 +8,7 @@ did the reason name the node that fell short?
|
|
| 8 |
|
| 9 |
import pytest
|
| 10 |
|
| 11 |
-
from
|
| 12 |
|
| 13 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
| 14 |
ONE = "perp-it-true"
|
|
|
|
| 8 |
|
| 9 |
import pytest
|
| 10 |
|
| 11 |
+
from lingologos_geostratum import agents, canonical, corpus, faults, pipeline
|
| 12 |
|
| 13 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
| 14 |
ONE = "perp-it-true"
|
tests/test_lexicon.py
CHANGED
|
@@ -5,7 +5,7 @@ from pathlib import Path
|
|
| 5 |
|
| 6 |
import pytest
|
| 7 |
|
| 8 |
-
from
|
| 9 |
|
| 10 |
ROOT = Path(__file__).resolve().parents[1]
|
| 11 |
LANGS = lexicon.codes()
|
|
|
|
| 5 |
|
| 6 |
import pytest
|
| 7 |
|
| 8 |
+
from lingologos_geostratum import canonical, decide, lexicon, segment
|
| 9 |
|
| 10 |
ROOT = Path(__file__).resolve().parents[1]
|
| 11 |
LANGS = lexicon.codes()
|
tests/test_orchestrator_e2e.py
CHANGED
|
@@ -12,7 +12,7 @@ from pathlib import Path
|
|
| 12 |
|
| 13 |
import pytest
|
| 14 |
|
| 15 |
-
from
|
| 16 |
|
| 17 |
ROOT = Path(__file__).resolve().parent.parent
|
| 18 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
|
|
|
| 12 |
|
| 13 |
import pytest
|
| 14 |
|
| 15 |
+
from lingologos_geostratum import corpus, lexicon
|
| 16 |
|
| 17 |
ROOT = Path(__file__).resolve().parent.parent
|
| 18 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
tests/test_pinned_invariant.py
CHANGED
|
@@ -11,7 +11,7 @@ from typing import Any, Dict, List, Tuple
|
|
| 11 |
|
| 12 |
import pytest
|
| 13 |
|
| 14 |
-
from
|
| 15 |
|
| 16 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
| 17 |
PINS = ["perp-it-true", "circumcircle-it"]
|
|
@@ -96,7 +96,7 @@ def test_the_geometry_layer_is_reached_only_as_a_separate_process():
|
|
| 96 |
# Nothing in this bundle may decide a geometric verdict: the only door toward the geometry layer is
|
| 97 |
# the invoker, and it launches the solver of that bundle as a subprocess.
|
| 98 |
import inspect
|
| 99 |
-
from
|
| 100 |
|
| 101 |
source = inspect.getsource(invoker)
|
| 102 |
assert "subprocess" in source
|
|
|
|
| 11 |
|
| 12 |
import pytest
|
| 13 |
|
| 14 |
+
from lingologos_geostratum import agents, canonical, coverage, corpus, faults, pipeline
|
| 15 |
|
| 16 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
| 17 |
PINS = ["perp-it-true", "circumcircle-it"]
|
|
|
|
| 96 |
# Nothing in this bundle may decide a geometric verdict: the only door toward the geometry layer is
|
| 97 |
# the invoker, and it launches the solver of that bundle as a subprocess.
|
| 98 |
import inspect
|
| 99 |
+
from lingologos_geostratum import invoker
|
| 100 |
|
| 101 |
source = inspect.getsource(invoker)
|
| 102 |
assert "subprocess" in source
|
tests/test_readers.py
CHANGED
|
@@ -8,7 +8,7 @@ reading is assembled, rather than at the output of one reader over the whole tex
|
|
| 8 |
|
| 9 |
import pytest
|
| 10 |
|
| 11 |
-
from
|
| 12 |
|
| 13 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
| 14 |
AGREED = [item_id for item_id, item in ITEMS.items() if (item.get("expect") or {}).get("state") == "AGREED"]
|
|
|
|
| 8 |
|
| 9 |
import pytest
|
| 10 |
|
| 11 |
+
from lingologos_geostratum import canonical, compare, corpus, pipeline, read_a, read_b
|
| 12 |
|
| 13 |
ITEMS = {item["id"]: item for item in corpus.load()}
|
| 14 |
AGREED = [item_id for item_id, item in ITEMS.items() if (item.get("expect") or {}).get("state") == "AGREED"]
|
tests/test_topology.py
CHANGED
|
@@ -6,7 +6,7 @@ from pathlib import Path
|
|
| 6 |
|
| 7 |
import pytest
|
| 8 |
|
| 9 |
-
from
|
| 10 |
|
| 11 |
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
TOPOLOGY = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))
|
|
@@ -52,7 +52,7 @@ def test_node_dataset_is_complete(node):
|
|
| 52 |
|
| 53 |
|
| 54 |
def test_python_sources_are_ascii_only():
|
| 55 |
-
paths = (list((ROOT / "
|
| 56 |
+ list((ROOT / "tests").glob("*.py")) + [ROOT / "agents" / "stratum_agent"])
|
| 57 |
for path in paths:
|
| 58 |
path.read_text(encoding="ascii")
|
|
@@ -64,7 +64,7 @@ def test_only_the_equivalence_referee_may_touch_the_geometry_code():
|
|
| 64 |
# for its own SMT plumbing: compare.py asks whether two readings of a question say the same
|
| 65 |
# thing, which is a claim about the readings and never about the answer. The modules that
|
| 66 |
# decide, route and invoke are checked to hold no reference to that package at all.
|
| 67 |
-
for path in (ROOT / "
|
| 68 |
tree = ast.parse(path.read_text(encoding="ascii"))
|
| 69 |
for node in ast.walk(tree):
|
| 70 |
if isinstance(node, ast.Import):
|
|
@@ -77,13 +77,13 @@ def test_only_the_equivalence_referee_may_touch_the_geometry_code():
|
|
| 77 |
if name == "geometry" or name.startswith("geometry."):
|
| 78 |
assert path.name == "compare.py", "%s imports %s" % (path.name, name)
|
| 79 |
for name in ("decide.py", "pipeline.py", "agents.py", "invoker.py", "protocol.py", "coverage.py"):
|
| 80 |
-
text = (ROOT / "
|
| 81 |
assert "import geometry" not in text, name
|
| 82 |
assert "from geometry" not in text, name
|
| 83 |
|
| 84 |
|
| 85 |
def test_the_geometry_bundle_is_reached_as_a_separate_process():
|
| 86 |
-
source = (ROOT / "
|
| 87 |
tree = ast.parse(source)
|
| 88 |
calls = [ast.unparse(node) for node in ast.walk(tree) if isinstance(node, ast.Call)]
|
| 89 |
assert any("subprocess.run" in call for call in calls)
|
|
|
|
| 6 |
|
| 7 |
import pytest
|
| 8 |
|
| 9 |
+
from lingologos_geostratum import agents
|
| 10 |
|
| 11 |
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
TOPOLOGY = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))
|
|
|
|
| 52 |
|
| 53 |
|
| 54 |
def test_python_sources_are_ascii_only():
|
| 55 |
+
paths = (list((ROOT / "lingologos_geostratum").glob("*.py")) + list((ROOT / "tools").glob("*.py"))
|
| 56 |
+ list((ROOT / "tests").glob("*.py")) + [ROOT / "agents" / "stratum_agent"])
|
| 57 |
for path in paths:
|
| 58 |
path.read_text(encoding="ascii")
|
|
|
|
| 64 |
# for its own SMT plumbing: compare.py asks whether two readings of a question say the same
|
| 65 |
# thing, which is a claim about the readings and never about the answer. The modules that
|
| 66 |
# decide, route and invoke are checked to hold no reference to that package at all.
|
| 67 |
+
for path in (ROOT / "lingologos_geostratum").glob("*.py"):
|
| 68 |
tree = ast.parse(path.read_text(encoding="ascii"))
|
| 69 |
for node in ast.walk(tree):
|
| 70 |
if isinstance(node, ast.Import):
|
|
|
|
| 77 |
if name == "geometry" or name.startswith("geometry."):
|
| 78 |
assert path.name == "compare.py", "%s imports %s" % (path.name, name)
|
| 79 |
for name in ("decide.py", "pipeline.py", "agents.py", "invoker.py", "protocol.py", "coverage.py"):
|
| 80 |
+
text = (ROOT / "lingologos_geostratum" / name).read_text(encoding="ascii")
|
| 81 |
assert "import geometry" not in text, name
|
| 82 |
assert "from geometry" not in text, name
|
| 83 |
|
| 84 |
|
| 85 |
def test_the_geometry_bundle_is_reached_as_a_separate_process():
|
| 86 |
+
source = (ROOT / "lingologos_geostratum" / "invoker.py").read_text(encoding="ascii")
|
| 87 |
tree = ast.parse(source)
|
| 88 |
calls = [ast.unparse(node) for node in ast.walk(tree) if isinstance(node, ast.Call)]
|
| 89 |
assert any("subprocess.run" in call for call in calls)
|
tools/ablation.py
CHANGED
|
@@ -2,7 +2,7 @@
|
|
| 2 |
"""Fault injection: how many conversational nodes does the assurance ceiling need?
|
| 3 |
|
| 4 |
For every configuration (a subset of the eight nodes) and every fault of the catalogue
|
| 5 |
-
(``
|
| 6 |
the orchestrator runs. A run is *activated* when the injected fault really changed a node. Each
|
| 7 |
activated run is then measured against the honest result of the same item, and ends in one of:
|
| 8 |
|
|
@@ -31,7 +31,7 @@ from typing import Any, Dict, List, Tuple
|
|
| 31 |
ROOT = Path(__file__).resolve().parents[1]
|
| 32 |
sys.path.insert(0, str(ROOT))
|
| 33 |
|
| 34 |
-
from
|
| 35 |
|
| 36 |
FULL = list(agents.ORDER)
|
| 37 |
OUT = ROOT / "results" / "ablation.json"
|
|
|
|
| 2 |
"""Fault injection: how many conversational nodes does the assurance ceiling need?
|
| 3 |
|
| 4 |
For every configuration (a subset of the eight nodes) and every fault of the catalogue
|
| 5 |
+
(``lingologos_geostratum/faults.py``) a probe set of the corpus is run in memory with the very same node code
|
| 6 |
the orchestrator runs. A run is *activated* when the injected fault really changed a node. Each
|
| 7 |
activated run is then measured against the honest result of the same item, and ends in one of:
|
| 8 |
|
|
|
|
| 31 |
ROOT = Path(__file__).resolve().parents[1]
|
| 32 |
sys.path.insert(0, str(ROOT))
|
| 33 |
|
| 34 |
+
from lingologos_geostratum import agents, corpus, faults, pipeline # noqa: E402
|
| 35 |
|
| 36 |
FULL = list(agents.ORDER)
|
| 37 |
OUT = ROOT / "results" / "ablation.json"
|
tools/ask.py
CHANGED
|
@@ -39,7 +39,7 @@ for _parent in ROOT.parents:
|
|
| 39 |
sys.path.insert(0, str(_candidate))
|
| 40 |
break
|
| 41 |
|
| 42 |
-
from
|
| 43 |
|
| 44 |
|
| 45 |
def _launcher(directory: Path) -> Path:
|
|
@@ -59,7 +59,7 @@ def ask(question: str, lang: str, faults_spec: str = "", keep: bool = False) ->
|
|
| 59 |
from lingologos_orchestrator.orchestrator import MultiInstanceOrchestrator
|
| 60 |
from lingologos_orchestrator.schema import OrchestratorError
|
| 61 |
|
| 62 |
-
workspace = Path(tempfile.mkdtemp(prefix="
|
| 63 |
try:
|
| 64 |
datasets = workspace / "datasets"
|
| 65 |
shutil.copytree(ROOT / "nodes", datasets)
|
|
@@ -73,8 +73,8 @@ def ask(question: str, lang: str, faults_spec: str = "", keep: bool = False) ->
|
|
| 73 |
instance["executable"] = str(launcher)
|
| 74 |
topology_path = workspace / "topology.json"
|
| 75 |
topology_path.write_text(json.dumps(topology), encoding="utf-8")
|
| 76 |
-
previous = os.environ.get("
|
| 77 |
-
os.environ["
|
| 78 |
try:
|
| 79 |
orchestrator = MultiInstanceOrchestrator.from_config_file(
|
| 80 |
config_path=topology_path, datasets_dir=datasets,
|
|
@@ -85,9 +85,9 @@ def ask(question: str, lang: str, faults_spec: str = "", keep: bool = False) ->
|
|
| 85 |
"records": [], "reply": None}
|
| 86 |
finally:
|
| 87 |
if previous is None:
|
| 88 |
-
os.environ.pop("
|
| 89 |
else:
|
| 90 |
-
os.environ["
|
| 91 |
return _check(result)
|
| 92 |
finally:
|
| 93 |
if keep:
|
|
|
|
| 39 |
sys.path.insert(0, str(_candidate))
|
| 40 |
break
|
| 41 |
|
| 42 |
+
from lingologos_geostratum import corpus, pipeline, protocol, render # noqa: E402
|
| 43 |
|
| 44 |
|
| 45 |
def _launcher(directory: Path) -> Path:
|
|
|
|
| 59 |
from lingologos_orchestrator.orchestrator import MultiInstanceOrchestrator
|
| 60 |
from lingologos_orchestrator.schema import OrchestratorError
|
| 61 |
|
| 62 |
+
workspace = Path(tempfile.mkdtemp(prefix="lingologos_geostratum_"))
|
| 63 |
try:
|
| 64 |
datasets = workspace / "datasets"
|
| 65 |
shutil.copytree(ROOT / "nodes", datasets)
|
|
|
|
| 73 |
instance["executable"] = str(launcher)
|
| 74 |
topology_path = workspace / "topology.json"
|
| 75 |
topology_path.write_text(json.dumps(topology), encoding="utf-8")
|
| 76 |
+
previous = os.environ.get("LINGOLOGOS_STRATUM_FAULTS")
|
| 77 |
+
os.environ["LINGOLOGOS_STRATUM_FAULTS"] = faults_spec
|
| 78 |
try:
|
| 79 |
orchestrator = MultiInstanceOrchestrator.from_config_file(
|
| 80 |
config_path=topology_path, datasets_dir=datasets,
|
|
|
|
| 85 |
"records": [], "reply": None}
|
| 86 |
finally:
|
| 87 |
if previous is None:
|
| 88 |
+
os.environ.pop("LINGOLOGOS_STRATUM_FAULTS", None)
|
| 89 |
else:
|
| 90 |
+
os.environ["LINGOLOGOS_STRATUM_FAULTS"] = previous
|
| 91 |
return _check(result)
|
| 92 |
finally:
|
| 93 |
if keep:
|
tools/coverage_report.py
CHANGED
|
@@ -22,7 +22,7 @@ from typing import Any, Dict, List
|
|
| 22 |
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
sys.path.insert(0, str(ROOT))
|
| 24 |
|
| 25 |
-
from
|
| 26 |
|
| 27 |
OUT = ROOT / "results" / "coverage.json"
|
| 28 |
|
|
|
|
| 22 |
ROOT = Path(__file__).resolve().parents[1]
|
| 23 |
sys.path.insert(0, str(ROOT))
|
| 24 |
|
| 25 |
+
from lingologos_geostratum import corpus, lexicon, pipeline # noqa: E402
|
| 26 |
|
| 27 |
OUT = ROOT / "results" / "coverage.json"
|
| 28 |
|
tools/geometry_runner.py
CHANGED
|
@@ -7,7 +7,7 @@
|
|
| 7 |
|
| 8 |
Run from this folder (it is ``datasets/geometry-stratum`` inside the LingoLOGOS repository, and the
|
| 9 |
bundle root when the dataset is cloned on its own). The geometry bundle it consults is the sibling
|
| 10 |
-
folder ``geometry``, or the copy named by ``
|
| 11 |
|
| 12 |
The reading layer never imports the geometry bundle: the invoker node of the stratum starts this
|
| 13 |
script as a separate process, and this script is the only place in the bundle where ``geometry`` is
|
|
@@ -42,7 +42,7 @@ from typing import Any, Dict, List, Optional, Tuple
|
|
| 42 |
ROOT = Path(__file__).resolve().parents[1]
|
| 43 |
sys.path.insert(0, str(ROOT))
|
| 44 |
|
| 45 |
-
from
|
| 46 |
|
| 47 |
_LAYER_STATUS = {"CERTIFIED", "REFUTED", "OBJECTION", "INCONCLUSIVE", "REJECTED"}
|
| 48 |
|
|
|
|
| 7 |
|
| 8 |
Run from this folder (it is ``datasets/geometry-stratum`` inside the LingoLOGOS repository, and the
|
| 9 |
bundle root when the dataset is cloned on its own). The geometry bundle it consults is the sibling
|
| 10 |
+
folder ``geometry``, or the copy named by ``LINGOLOGOS_STRATUM_GEOMETRY_ROOT``.
|
| 11 |
|
| 12 |
The reading layer never imports the geometry bundle: the invoker node of the stratum starts this
|
| 13 |
script as a separate process, and this script is the only place in the bundle where ``geometry`` is
|
|
|
|
| 42 |
ROOT = Path(__file__).resolve().parents[1]
|
| 43 |
sys.path.insert(0, str(ROOT))
|
| 44 |
|
| 45 |
+
from lingologos_geostratum import corpus, invoker # noqa: E402 - the bundle is importable from this folder
|
| 46 |
|
| 47 |
_LAYER_STATUS = {"CERTIFIED", "REFUTED", "OBJECTION", "INCONCLUSIVE", "REJECTED"}
|
| 48 |
|
tools/publish_dataset.py
CHANGED
|
@@ -32,7 +32,7 @@ from typing import List, Tuple
|
|
| 32 |
ROOT = Path(__file__).resolve().parents[1]
|
| 33 |
sys.path.insert(0, str(ROOT))
|
| 34 |
|
| 35 |
-
from
|
| 36 |
|
| 37 |
REPO = "tailot/geometry-stratum"
|
| 38 |
EXPECTED_FILES = 68 # the staged tree: this README is uploaded as the card under the same name
|
|
@@ -77,12 +77,11 @@ REPLACEMENTS: List[Tuple[str, str]] = [
|
|
| 77 |
"sibling folder `datasets/geometry`, which stays exactly as it is. Only the standard library and\n"
|
| 78 |
"`z3-solver` are required; the tests need `pytest`.",
|
| 79 |
"This dataset is the `geometry-stratum/` folder of the LingoLOGOS project published as it stands: 68 files,\n"
|
| 80 |
-
"code and data together, plus this card in place of their README. Only the standard library and\n"
|
| 81 |
-
"
|
| 82 |
-
"
|
| 83 |
-
"
|
| 84 |
-
"
|
| 85 |
-
"folder at a copy of it.",
|
| 86 |
),
|
| 87 |
(
|
| 88 |
"## 10. Using this folder as an external dataset",
|
|
@@ -93,27 +92,36 @@ REPLACEMENTS: List[Tuple[str, str]] = [
|
|
| 93 |
"this content: 68 files (plus the card that replaces this README on the hub), 56 questions in one corpus\n"
|
| 94 |
"file, the six lexicons, the eight node definitions, the two readers, the decision rule of section 1, the\n"
|
| 95 |
"corpus grading and fault results under `results/`, and the fault catalogue of section 6.",
|
| 96 |
-
"This dataset is 68 files plus this card: 56 questions in one corpus file, the six lexicons, the eight\n"
|
| 97 |
-
"
|
| 98 |
-
"
|
| 99 |
-
"
|
| 100 |
-
"`
|
| 101 |
"`tools/geometry_runner.py`, which loads that copy in a separate process -- the only door through which\n"
|
| 102 |
"this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at\n"
|
| 103 |
-
"`datasets/geometry-stratum`, finds `datasets/geometry` by itself, and needs\n"
|
| 104 |
-
"
|
| 105 |
),
|
| 106 |
(
|
| 107 |
"invariant tests call the solver of the geometry layer as subprocesses, and the whole suite\n"
|
| 108 |
"took 57 seconds on this checkout.",
|
| 109 |
-
"invariant tests call the solver of the geometry layer as subprocesses, which here means a
|
| 110 |
-
"`geometry` dataset named by `
|
| 111 |
-
"LingoLOGOS checkout, and the two end to end tests skip on their own when
|
| 112 |
-
"not importable.",
|
| 113 |
),
|
| 114 |
(
|
| 115 |
-
"Like the `geometry` folder, this folder is ignored by the git repository of the project: what the project\
|
| 116 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
),
|
| 118 |
]
|
| 119 |
|
|
@@ -178,7 +186,7 @@ rows = load_dataset("tailot/geometry-stratum", "corpus", split="train")
|
|
| 178 |
print(rows[0])
|
| 179 |
```
|
| 180 |
|
| 181 |
-
This is the same file `tools/ask.py --corpus` walks over, and `
|
| 182 |
`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 56 of 56
|
| 183 |
rows agree with what they expect.
|
| 184 |
|
|
@@ -217,7 +225,7 @@ def local_files() -> List[Path]:
|
|
| 217 |
Whole path components named `.git`, `__pycache__` or `.pytest_cache` are cut at any depth, which is
|
| 218 |
what keeps the compiled copies of the modules out of the published tree. A file whose own name
|
| 219 |
starts with an underscore is working notes and is not published either, with one exception:
|
| 220 |
-
`
|
| 221 |
than by being a note, and dropping it would publish a tree whose library cannot be imported as a
|
| 222 |
package. A file named `.gitignore` is content for the same reason.
|
| 223 |
"""
|
|
@@ -230,7 +238,7 @@ def local_files() -> List[Path]:
|
|
| 230 |
continue
|
| 231 |
if ".git" in relative.parts:
|
| 232 |
continue
|
| 233 |
-
if path.name.startswith("_") and not (path.name == "__init__.py" and path.parent.name == "
|
| 234 |
continue
|
| 235 |
out.append(path)
|
| 236 |
return out
|
|
|
|
| 32 |
ROOT = Path(__file__).resolve().parents[1]
|
| 33 |
sys.path.insert(0, str(ROOT))
|
| 34 |
|
| 35 |
+
from lingologos_geostratum import corpus # noqa: E402 (after the path fix above)
|
| 36 |
|
| 37 |
REPO = "tailot/geometry-stratum"
|
| 38 |
EXPECTED_FILES = 68 # the staged tree: this README is uploaded as the card under the same name
|
|
|
|
| 77 |
"sibling folder `datasets/geometry`, which stays exactly as it is. Only the standard library and\n"
|
| 78 |
"`z3-solver` are required; the tests need `pytest`.",
|
| 79 |
"This dataset is the `geometry-stratum/` folder of the LingoLOGOS project published as it stands: 68 files,\n"
|
| 80 |
+
"code and data together, plus this card in place of their README. Only the standard library and `z3-solver`\n"
|
| 81 |
+
"are required, and `pytest` for the tests; both are named in `requirements.txt`. Every command below is\n"
|
| 82 |
+
"written from inside the folder. The geometry layer is not part of this dataset: it lives in the `geometry`\n"
|
| 83 |
+
"bundle, published at https://huggingface.co/datasets/tailot/lingologos-geometry, and section 10 says how\n"
|
| 84 |
+
"to point this folder at a copy of it.",
|
|
|
|
| 85 |
),
|
| 86 |
(
|
| 87 |
"## 10. Using this folder as an external dataset",
|
|
|
|
| 92 |
"this content: 68 files (plus the card that replaces this README on the hub), 56 questions in one corpus\n"
|
| 93 |
"file, the six lexicons, the eight node definitions, the two readers, the decision rule of section 1, the\n"
|
| 94 |
"corpus grading and fault results under `results/`, and the fault catalogue of section 6.",
|
| 95 |
+
"This dataset is 68 files plus this card: 56 questions in one corpus file, the six lexicons, the eight node\n"
|
| 96 |
+
"definitions, the two readers, the decision rule of section 1, the corpus grading and fault results under\n"
|
| 97 |
+
"`results/`, and the fault catalogue of section 6. To decide a figure it needs the `geometry` bundle:\n"
|
| 98 |
+
"download https://huggingface.co/datasets/tailot/lingologos-geometry somewhere, set\n"
|
| 99 |
+
"`LINGOLOGOS_STRATUM_GEOMETRY_ROOT` to that copy, and the `invoker` node of this folder starts\n"
|
| 100 |
"`tools/geometry_runner.py`, which loads that copy in a separate process -- the only door through which\n"
|
| 101 |
"this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at\n"
|
| 102 |
+
"`datasets/geometry-stratum`, finds `datasets/geometry` by itself, and needs `src/lingologos_orchestrator`\n"
|
| 103 |
+
"importable for the two end to end sessions of section 8.",
|
| 104 |
),
|
| 105 |
(
|
| 106 |
"invariant tests call the solver of the geometry layer as subprocesses, and the whole suite\n"
|
| 107 |
"took 57 seconds on this checkout.",
|
| 108 |
+
"invariant tests call the solver of the geometry layer as subprocesses, which here means a\n"
|
| 109 |
+
"copy of the `geometry` dataset named by `LINGOLOGOS_STRATUM_GEOMETRY_ROOT` (section 10); the suite took 57\n"
|
| 110 |
+
"seconds inside a LingoLOGOS checkout, and the two end to end tests skip on their own when\n"
|
| 111 |
+
"`lingologos_orchestrator` is not importable.",
|
| 112 |
),
|
| 113 |
(
|
| 114 |
+
"Like the `geometry` folder, this folder is ignored by the git repository of the project: what the project\n"
|
| 115 |
+
"carries is the link in the table of published resources at the top of the repository README, and the\n"
|
| 116 |
+
"documentation of the asset lives in this README and in the card, not in\n"
|
| 117 |
+
"`doc/TECHNICAL_DOCUMENTATION.md`. Republishing is a separate step, never a side effect of a test run:\n"
|
| 118 |
+
"`tools/publish_dataset.py` does it with the token taken from an environment variable and verifies the\n"
|
| 119 |
+
"tree by sha256.",
|
| 120 |
+
"What the LingoLOGOS repository carries is the link to this dataset in the table of published resources at\n"
|
| 121 |
+
"the top of its README; the documentation of the asset lives here, in this card, and not in the technical\n"
|
| 122 |
+
"documentation of the project. Republishing is a separate step, never a side effect of a test run:\n"
|
| 123 |
+
"`tools/publish_dataset.py` in the folder of the project does it with the token taken from an environment\n"
|
| 124 |
+
"variable and verifies the tree by sha256.",
|
| 125 |
),
|
| 126 |
]
|
| 127 |
|
|
|
|
| 186 |
print(rows[0])
|
| 187 |
```
|
| 188 |
|
| 189 |
+
This is the same file `tools/ask.py --corpus` walks over, and `lingologos_geostratum/corpus.py` plus
|
| 190 |
`tests/test_corpus.py` read it to grade the stratum against the gold. Graded on this checkout: 56 of 56
|
| 191 |
rows agree with what they expect.
|
| 192 |
|
|
|
|
| 225 |
Whole path components named `.git`, `__pycache__` or `.pytest_cache` are cut at any depth, which is
|
| 226 |
what keeps the compiled copies of the modules out of the published tree. A file whose own name
|
| 227 |
starts with an underscore is working notes and is not published either, with one exception:
|
| 228 |
+
`lingologos_geostratum/__init__.py`, the package marker, shares that prefix by the convention of Python rather
|
| 229 |
than by being a note, and dropping it would publish a tree whose library cannot be imported as a
|
| 230 |
package. A file named `.gitignore` is content for the same reason.
|
| 231 |
"""
|
|
|
|
| 238 |
continue
|
| 239 |
if ".git" in relative.parts:
|
| 240 |
continue
|
| 241 |
+
if path.name.startswith("_") and not (path.name == "__init__.py" and path.parent.name == "lingologos_geostratum"):
|
| 242 |
continue
|
| 243 |
out.append(path)
|
| 244 |
return out
|