tailot commited on
Commit
e65dba0
·
verified ·
1 Parent(s): 13a6b66

update struc-stratum bundle

Browse files
README.md CHANGED
@@ -49,11 +49,11 @@ Answer in the language of the question (italiano):
49
  ```
50
 
51
  This dataset is the `struc-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,
52
- code and data together, plus this card in place of their README. Only the standard library and
53
- `z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every
54
- command below is written from inside the folder. The structures are not part of this dataset: they live
55
- in the `struc` bundle, published at https://huggingface.co/datasets/tailot/lingologos-struc, and section
56
- 10 says how to point this folder at a copy of it.
57
 
58
  ## 1. What the stratum is, and what it refuses
59
 
@@ -83,9 +83,10 @@ assurance shown = min(assurance of the structures topology, ceiling of the readi
83
  Two is the top, and it is a shared top. The structures topology itself never shows more than two:
84
  `VERIFIED` at 2 when its own two readers and its checker agree, `SINGLE_PROVER` at 1, every refusal and
85
  every abstention at 0. So the minimum above can only ever lower what this layer shows -- a reading can
86
- lose a level by being alone, disputed, ambiguous or uncovered, and it can never buy one. The `math-stratum` bundle of this project, at
87
- https://huggingface.co/datasets/tailot/math-stratum, had a level three that no translation could
88
- reach; here there is no level to reach, and the rule still says what a person is shown.
 
89
 
90
  The ceiling is not the only thing that holds on its own. The count of numbers is checked on a lone
91
  reading too: a reading that no longer holds the numbers the person wrote is a different problem, not a
@@ -138,15 +139,15 @@ solved has to carry the numbers of the sentence the readers agreed on, otherwise
138
 
139
  | Variable | Meaning |
140
  |---|---|
141
- | `LGSTRATUM_STRUC_ROOT` | where the `struc` bundle is (default: the sibling folder `datasets/struc`) |
142
- | `LGSTRATUM_STRUC_BACKEND` | `in-process` (default), `orchestrated` or `none`: the first runs the thirteen nodes of the partner in one process, the second lets the partner run them its own way, the third refuses to call at all |
143
- | `LGSTRATUM_STRUC_TIMEOUT` | seconds to wait for the partner, 300 by default |
144
- | `LGSTRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only |
145
 
146
- The environment of the partner is left alone: `LGSTRUC_FAULTS` and `LGSTRUC_MATH_ROOT` belong to it,
147
- and the outcome it returns carries its own `math_status`, the verdict of the `math` bundle it consults
148
- in turn. This layer copies that field and does not read it: a translation layer that reached past the
149
- mechanics it consults would be deciding what they are allowed to prove.
150
 
151
  A disabled topology is not tampering: the reading stands, the assurance falls to zero because there is
152
  no structures assurance to take the minimum with, and no answer is shown.
@@ -163,13 +164,12 @@ another variety. Each line carries what the answer has to look like (`state`, `s
163
  says why, including the cases where the expected outcome is an abstention.
164
 
165
  Graded against the in-process pipeline: **72 of 72** rows agree with their gold
166
- (`lgstratum/corpus.py` grades one row, `tests/test_corpus.py` runs all of them). With the topology
167
- consulted the states come out 47 `AGREED`, 1 `SINGLE`, 6 `PASSTHROUGH`, 18 `NOT COVERED`;
168
- `tools/coverage_report.py` writes `results/coverage.json` and counts **54** questions read by
169
- `reader_a`, **53** by `reader_b` and **1** by `reader_a` alone. Two rows (`en-04`, `hi-05`) are agreed
170
- readings on which the structures topology abstains: assurance 0 and no answer, which is the layer
171
- refusing to add an availability it does not have. One row (`en-03`) stays `SINGLE`, assurance 1, for
172
- the reason in section 7.
173
 
174
  ## 6. Commands
175
 
@@ -221,17 +221,17 @@ python -m pytest -q datasets/struc-stratum/tests
221
  ```
222
 
223
  The suite is **288** tests: 120 on the two readers against every row of the corpus, 78 on the corpus
224
- itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 13 on the decision
225
- table, 10 on the lexicons and 2 end-to-end sessions. It checks the topology file against the node
226
- order, the shape and the completeness of the lexicons, both readers against the corpus, the decision
227
- table, the faults, and every gold answer of the corpus; `tests/test_pinned_invariant.py` runs the same questions through every node
228
- configuration and every fault and asserts that the verdict of the structures topology does not move,
229
- and that nothing is ever shown above it. `tests/test_orchestrator_e2e.py` runs two real sessions
230
- through the orchestrator and is skipped when `lingologos_orchestrator` is not importable. The corpus
231
- and the invariant tests call the tools of the structures topology as subprocesses, which here means a copy of the
232
- `struc` dataset named by `LGSTRATUM_STRUC_ROOT` (section 10); the suite passed in 2 minutes inside a
233
- LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is
234
- not importable.
235
 
236
  Real sessions, measured: `scegli la sezione rettangolo 1/5 2/5` comes back `AGREED` at assurance 2
237
  against a structures assurance of 2, with **8 of 8** envelope claims confirmed by the referee of the
@@ -243,7 +243,7 @@ the language of the question (36, 94 and 91 non-ASCII characters in the Chinese,
243
  replies).
244
 
245
  A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that
246
- `lgstruc` may be imported for its SMT plumbing by `lgstratum/compare.py` alone.
247
 
248
  ## 9. Language policy
249
 
@@ -256,25 +256,32 @@ the object this bundle measures.
256
 
257
  ## 10. Putting this dataset back into a LingoLOGOS checkout
258
 
259
- This dataset is 67 files plus this card: 72 questions in one corpus file, the six lexicons, the eight
260
- node definitions, the two readers, the decision rule of section 1, the corpus grading and fault results
261
- under `results/`, and the fault catalogue of section 6. To answer anything it needs the `struc` bundle:
262
- download https://huggingface.co/datasets/tailot/lingologos-struc somewhere, set
263
- `LGSTRATUM_STRUC_ROOT` to that copy, and the `invoker` node calls `tools/ask.py` there as a separate
264
- process, which is the only door through which this bundle ever reaches a solver. Inside a LingoLOGOS
265
- checkout the folder sits at `datasets/struc-stratum`, finds `datasets/struc` by itself, and needs
266
- `src/lingologos_orchestrator` importable for the two end to end sessions of section 8. This card keeps the wording and numbers of the README of
267
- the folder in its sections 1 to 10, and adds sections 11 to 14 for readers who met the bundle here
268
- rather than in a checkout: the fields of the corpus file, how to load it, rights and citation. Every
269
- file of the upload, this card among them, was compared by sha256 afterwards: the hub holds one object
270
- per file of the folder plus `.gitattributes`, so the remote count is one above the number the publisher
271
- prints. What the LingoLOGOS repository carries is the link to this
272
- dataset in the table of published resources at the top of its README; the documentation of the asset
273
- lives here, in this card, and not in the technical documentation of the project. `tools/publish_dataset.py`
274
- in the folder of the project republishes a changed working copy with the token taken from an environment
275
- variable. Republishing is a separate step,
276
- never a side effect of a test run: `tools/publish_dataset.py` does it with the token taken from an
277
- environment variable and verifies the tree by sha256.
 
 
 
 
 
 
 
278
 
279
  ## 11. The corpus file
280
 
@@ -334,9 +341,9 @@ rows = load_dataset("tailot/struc-stratum", "corpus", split="train")
334
  print(rows[0])
335
  ```
336
 
337
- This is the same file `tools/ask.py --corpus` walks over, and `lgstratum/corpus.py` plus
338
- `tests/test_corpus.py` read it to grade the stratum against the gold. Graded on the checkout this folder was published from: 72 of 72
339
- rows agree with what they expect.
340
 
341
  ## 13. Rights
342
 
 
49
  ```
50
 
51
  This dataset is the `struc-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,
52
+ code and data together, plus this card in place of their README. Only the standard library and `z3-solver`
53
+ are required, and `pytest` for the tests; both are named in `requirements.txt`. Every command below is
54
+ written from inside the folder. The structures are not part of this dataset: they live in the `struc`
55
+ bundle, published at https://huggingface.co/datasets/tailot/lingologos-struc, and section 10 says how to
56
+ point this folder at a copy of it.
57
 
58
  ## 1. What the stratum is, and what it refuses
59
 
 
83
  Two is the top, and it is a shared top. The structures topology itself never shows more than two:
84
  `VERIFIED` at 2 when its own two readers and its checker agree, `SINGLE_PROVER` at 1, every refusal and
85
  every abstention at 0. So the minimum above can only ever lower what this layer shows -- a reading can
86
+ lose a level by being alone, disputed, ambiguous or uncovered, and it can never buy one. The
87
+ `math-stratum` bundle of this project, at https://huggingface.co/datasets/tailot/math-stratum, had a level
88
+ three that no translation could reach; here there is no level to reach, and the rule still says what a
89
+ person is shown.
90
 
91
  The ceiling is not the only thing that holds on its own. The count of numbers is checked on a lone
92
  reading too: a reading that no longer holds the numbers the person wrote is a different problem, not a
 
139
 
140
  | Variable | Meaning |
141
  |---|---|
142
+ | `LINGOLOGOS_STRATUM_STRUC_ROOT` | where the `struc` bundle is (default: the sibling folder `datasets/struc`) |
143
+ | `LINGOLOGOS_STRATUM_STRUC_BACKEND` | `in-process` (default), `orchestrated` or `none`: the first runs the thirteen nodes of the partner in one process, the second lets the partner run them its own way, the third refuses to call at all |
144
+ | `LINGOLOGOS_STRATUM_STRUC_TIMEOUT` | seconds to wait for the partner, 300 by default |
145
+ | `LINGOLOGOS_STRATUM_FAULTS` | comma separated `node:fault` pairs, experiments only |
146
 
147
+ The environment of the partner is left alone: `LINGOLOGOS_STRUC_FAULTS` and `LINGOLOGOS_STRUC_MATH_ROOT`
148
+ belong to it, and the outcome it returns carries its own `math_status`, the verdict of the `math` bundle
149
+ it consults in turn. This layer copies that field and does not read it: a translation layer that reached
150
+ past the mechanics it consults would be deciding what they are allowed to prove.
151
 
152
  A disabled topology is not tampering: the reading stands, the assurance falls to zero because there is
153
  no structures assurance to take the minimum with, and no answer is shown.
 
164
  says why, including the cases where the expected outcome is an abstention.
165
 
166
  Graded against the in-process pipeline: **72 of 72** rows agree with their gold
167
+ (`lingologos_stratum/corpus.py` grades one row, `tests/test_corpus.py` runs all of them). With the
168
+ topology consulted the states come out 47 `AGREED`, 1 `SINGLE`, 6 `PASSTHROUGH`, 18 `NOT COVERED`;
169
+ `tools/coverage_report.py` writes `results/coverage.json` and counts **54** questions read by `reader_a`,
170
+ **53** by `reader_b` and **1** by `reader_a` alone. Two rows (`en-04`, `hi-05`) are agreed readings on
171
+ which the structures topology abstains: assurance 0 and no answer, which is the layer refusing to add an
172
+ availability it does not have. One row (`en-03`) stays `SINGLE`, assurance 1, for the reason in section 7.
 
173
 
174
  ## 6. Commands
175
 
 
221
  ```
222
 
223
  The suite is **288** tests: 120 on the two readers against every row of the corpus, 78 on the corpus
224
+ itself, 38 on the pinned invariant, 14 on the topology file, 13 on the faults, 13 on the decision table,
225
+ 10 on the lexicons and 2 end-to-end sessions. It checks the topology file against the node order, the
226
+ shape and the completeness of the lexicons, both readers against the corpus, the decision table, the
227
+ faults, and every gold answer of the corpus; `tests/test_pinned_invariant.py` runs the same questions
228
+ through every node configuration and every fault and asserts that the verdict of the structures topology
229
+ does not move, and that nothing is ever shown above it. `tests/test_orchestrator_e2e.py` runs two real
230
+ sessions through the orchestrator and is skipped when `lingologos_orchestrator` is not importable. The
231
+ corpus and the invariant tests call the tools of the structures topology as subprocesses, which here means
232
+ a copy of the `struc` dataset named by `LINGOLOGOS_STRATUM_STRUC_ROOT` (section 10); the suite passed in 2
233
+ minutes inside a LingoLOGOS checkout, and the two end to end tests skip on their own when
234
+ `lingologos_orchestrator` is not importable.
235
 
236
  Real sessions, measured: `scegli la sezione rettangolo 1/5 2/5` comes back `AGREED` at assurance 2
237
  against a structures assurance of 2, with **8 of 8** envelope claims confirmed by the referee of the
 
243
  replies).
244
 
245
  A gate in `tests/test_topology.py` keeps every Python source of this bundle ASCII only, and pins that
246
+ `lingologos_struc` may be imported for its SMT plumbing by `lingologos_stratum/compare.py` alone.
247
 
248
  ## 9. Language policy
249
 
 
256
 
257
  ## 10. Putting this dataset back into a LingoLOGOS checkout
258
 
259
+ This dataset is 67 files plus this card: 72 questions in one corpus file, the six lexicons, the eight node
260
+ definitions, the two readers, the decision rule of section 1, the corpus grading and fault results under
261
+ `results/`, and the fault catalogue of section 6. To answer anything it needs the `struc` bundle: download
262
+ https://huggingface.co/datasets/tailot/lingologos-struc somewhere, set `LINGOLOGOS_STRATUM_STRUC_ROOT` to
263
+ that copy, and the `invoker` node calls `tools/ask.py` there as a separate process, which is the only door
264
+ through which this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at
265
+ `datasets/struc-stratum`, finds `datasets/struc` by itself, and needs `src/lingologos_orchestrator`
266
+ importable for the two end to end sessions of section 8. This card keeps
267
+ the wording and numbers of the README of the folder in its sections 1 to 10, and adds sections 11 to 14
268
+ for readers who met the bundle here rather than in a checkout: the fields of the corpus file, how to load
269
+ it, rights and citation. Every file of the upload, this card among them, was compared by sha256
270
+ afterwards: the hub holds one object per file of the folder plus `.gitattributes`, so the remote count is
271
+ one above the number the publisher prints. What
272
+ the LingoLOGOS repository carries is the link to this dataset in the table of published resources at the
273
+ top of its README; the documentation of the asset lives here, in this card, and not in the technical
274
+ documentation of the project. `tools/publish_dataset.py` in the folder of the project republishes a
275
+ changed working copy with the token
276
+ taken from an environment variable. Republishing is a separate step, never a side effect of a test run:
277
+ `tools/publish_dataset.py` does it with the token taken from an environment variable and verifies the tree
278
+ by sha256.
279
+
280
+ An earlier published revision of this dataset held its library as `lgstratum/` and read its four handles
281
+ as `LGSTRATUM_FAULTS`, `LGSTRATUM_STRUC_ROOT`, `LGSTRATUM_STRUC_BACKEND` and `LGSTRATUM_STRUC_TIMEOUT`.
282
+ The names moved and nothing else: the 67 files, the 72 questions, the six lexicons, the eight node
283
+ definitions, the two readers, the decision rule of section 1 and the 288 tests are the ones that revision
284
+ published, and the structures bundle this stratum talks to left `lgstruc/` under the same rule.
285
 
286
  ## 11. The corpus file
287
 
 
341
  print(rows[0])
342
  ```
343
 
344
+ This is the same file `tools/ask.py --corpus` walks over, and `lingologos_stratum/corpus.py` plus
345
+ `tests/test_corpus.py` read it to grade the stratum against the gold. Graded on the checkout this folder
346
+ was published from: 72 of 72 rows agree with what they expect.
347
 
348
  ## 13. Rights
349
 
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 lgstratum import agents, faults # noqa: E402
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_stratum import agents, faults # noqa: E402
24
 
25
 
26
  def main() -> int:
lingologos_stratum/__init__.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The library of the struc-stratum topology.
2
+
3
+ The struc-stratum is the conversational stratum of the structures topology: it accepts a problem
4
+ written in one of six language varieties, reads it into one sentence of the structures language,
5
+ hands that sentence to the structures topology as a separate process, and presents the verdict of
6
+ that topology 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 is not
11
+ verifiable, because the space of natural language sentences is not. The stratum therefore never
12
+ raises the assurance the structures topology reported, and every stage of the reading can only take
13
+ verdicts away.
14
+ * **coverage**: the multilingual layer is a documented fragment, in the same spirit as the fragment of
15
+ the structures language. Anything outside it abstains with a question in the language of the user,
16
+ 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_stratum/agents.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The eight nodes of the stratum, one step function each.
2
+
3
+ Every node has exactly one job and one claim of its own, and no node is allowed to conclude what the
4
+ next one is supposed to check. The chain is the same shape the structures topology runs, only moved
5
+ one level up: two independent readers instead of two independent formalizers, an equivalence node
6
+ instead of the equivalence checker, a coverage node that counts the numbers the user wrote, an
7
+ invoker that hands the agreed sentence to the structures topology as a separate process, a boundary
8
+ where that verdict enters this stratum, an adversary that re-derives what the others asserted, and an
9
+ arbiter that decides and answers in the user's language.
10
+
11
+ reader_a surface reading: the words of the variety, in the order they appear
12
+ reader_b joint reading: which marker of the structures language sits in which gap of the frame
13
+ equivalence are the two readings one structure? SMT2 answers, text identity is a shortcut
14
+ coverage did the readings keep every number the user wrote?
15
+ invoker call the structures topology, in another process, on one sentence
16
+ boundary the structures 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 structures topology, ceiling of the reading)``, and the ceiling is never above
23
+ the top level of the partner. A node may lower what the user sees; none may raise it.
24
+ """
25
+
26
+ from typing import Any, Dict, List, Tuple
27
+
28
+ from . import canonical, compare, coverage, decide, faults, invoker, protocol, read_a, read_b, render
29
+
30
+ ORDER = ("reader_a", "reader_b", "equivalence", "coverage", "invoker", "boundary", "adversary", "arbiter")
31
+
32
+
33
+ def _ast(dossier: Dict[str, Any]) -> str:
34
+ """One ASCII line describing the shape of the dossier, for the abstractSyntaxTree field."""
35
+ def status_of(key: str) -> str:
36
+ part = dossier.get(key)
37
+ if not isinstance(part, dict):
38
+ return "absent"
39
+ return str(part.get("status") or part.get("state") or part.get("kind") or "present")
40
+
41
+ return "Stratum(lang=%s, a=%s, b=%s, equiv=%s, cover=%s, struc=%s, final=%s)" % (
42
+ dossier.get("lang", "?"), status_of("reading_a"), status_of("reading_b"),
43
+ "same" if (dossier.get("compare") or {}).get("same") else "no",
44
+ "ok" if (dossier.get("coverage") or {}).get("ok") else "no",
45
+ (dossier.get("struc") or {}).get("status", "absent"),
46
+ (dossier.get("final") or {}).get("state", "absent"),
47
+ )
48
+
49
+
50
+ def _cap_claim(shown: int, ceiling: int) -> Tuple[List[str], List[str], str]:
51
+ """SMT2 for ``this node raised nothing``: the strict excess over the ceiling is refuted."""
52
+ decls = ["(declare-const shown Real)", "(declare-const ceiling Real)"]
53
+ asserts = ["(assert (= shown %d))" % int(shown), "(assert (= ceiling %d))" % int(ceiling),
54
+ "(assert (> shown ceiling))"]
55
+ return decls, asserts, "unsat"
56
+
57
+
58
+ def _reader_claim(reading: Dict[str, Any], question: str) -> Tuple[List[str], List[str], str]:
59
+ """A reader claims one thing only: it dropped no number the user wrote."""
60
+ step = compare.keeps(reading, question)
61
+ return step["declarations"], step["assertions"], step["claimed"]
62
+
63
+
64
+ def _apply_reader_fault(agent: str, reading: Dict[str, Any]) -> None:
65
+ """Corrupt a reading on purpose, for the ablation experiments: never in a normal session."""
66
+ if not reading.get("kind") or reading.get("status") != "READ":
67
+ return
68
+ for kind in faults.READER_FAULTS:
69
+ if not faults.has(agent, kind):
70
+ continue
71
+ order = list(reading.get("variant") or []) or list(canonical.slots_for(str(reading["kind"])))
72
+ slots, changed = faults.mutate_reading(agent, str(reading["kind"]),
73
+ dict(reading.get("slots") or {}), order)
74
+ if not changed:
75
+ continue
76
+ faults.fire(agent, kind)
77
+ try:
78
+ reading["sentence"] = canonical.print_sentence(str(reading["kind"]), slots)
79
+ reading["slots"] = slots
80
+ reading["fault"] = kind
81
+ except canonical.ReadingError:
82
+ reading["sentence"] = ""
83
+ reading["status"] = "NOT COVERED"
84
+ reading["notes"].append({"reason": "broken_form", "kind": reading["kind"], "detail": kind})
85
+ return
86
+
87
+
88
+ def _reading_node(agent: str, reader: Any, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
89
+ """Shared body of the two reader nodes: read the question, keep the reading, claim the numbers."""
90
+ dossier, turn, tick, rcpt = protocol.start(incoming)
91
+ question = str(dossier.get("question", ""))
92
+ lang = str(dossier.get("lang") or "")
93
+ direct = canonical.direct(question)
94
+ if direct is not None:
95
+ dossier["reading_direct"] = direct
96
+ reading = direct
97
+ else:
98
+ reading = reader.read(lang, question)
99
+ _apply_reader_fault(node_id, reading)
100
+ dossier[agent] = reading
101
+ decls, asserts, claimed = _reader_claim(reading, question)
102
+ summary = "%s: %s %s" % (node_id, reading.get("status"), reading.get("sentence") or "")
103
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
104
+
105
+
106
+ def step_reader_a(incoming: Dict[str, Any], node_id: str = "reader_a") -> Dict[str, Any]:
107
+ """Reader A: surface patterns of the variety, reading left to right."""
108
+ return _reading_node("reading_a", read_a, incoming, node_id)
109
+
110
+
111
+ def step_reader_b(incoming: Dict[str, Any], node_id: str = "reader_b") -> Dict[str, Any]:
112
+ """Reader B: the frame of the problem kind and the markers of the language sitting in its gaps."""
113
+ return _reading_node("reading_b", read_b, incoming, node_id)
114
+
115
+
116
+ def step_equivalence(incoming: Dict[str, Any], node_id: str = "equivalence") -> Dict[str, Any]:
117
+ """Are the two readings one structure? The answer carries the SMT2 program that proves it."""
118
+ dossier, turn, tick, rcpt = protocol.start(incoming)
119
+ if faults.has(node_id, "rubber_stamp"):
120
+ faults.fire(node_id, "rubber_stamp")
121
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_a") or {}
122
+ else:
123
+ first, second = dossier.get("reading_a") or {}, dossier.get("reading_b") or {}
124
+ direct = dossier.get("reading_direct")
125
+ if direct is not None:
126
+ first, second = direct, dict(dossier.get("reading_b") or direct)
127
+ comparison = compare.equivalence(first, second)
128
+ dossier["compare"] = comparison
129
+ if first.get("sentence") and (comparison["same"] or not second.get("sentence")):
130
+ dossier["sent"] = comparison["left"] or str(first["sentence"])
131
+ elif second.get("sentence") and not first.get("sentence"):
132
+ dossier["sent"] = comparison["right"] or str(second["sentence"])
133
+ summary = "equivalence: %s (%s)" % ("same" if comparison["same"] else "not the same structure",
134
+ comparison["why"])
135
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
136
+ comparison["declarations"], comparison["assertions"], comparison["claimed"])
137
+
138
+
139
+ def step_coverage(incoming: Dict[str, Any], node_id: str = "coverage") -> Dict[str, Any]:
140
+ """Did the readings keep every number the user wrote, and in the same multiset?"""
141
+ dossier, turn, tick, rcpt = protocol.start(incoming)
142
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
143
+ if dossier.get("reading_direct") is not None:
144
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
145
+ if faults.has(node_id, "rubber_stamp"):
146
+ faults.fire(node_id, "rubber_stamp")
147
+ claim = {"ok": True, "wrote": [], "kept": [], "missing": [], "added": [],
148
+ "declarations": ["(declare-const wrote_0 Real)"], "assertions": ["(assert (= wrote_0 0))"],
149
+ "claimed": "sat"}
150
+ else:
151
+ claim = coverage.coverage_claim(str(dossier.get("question", "")), [r for r in readings if r])
152
+ dossier["coverage"] = claim
153
+ summary = "coverage: %s (%d numbers)" % ("kept" if claim["ok"] else "not kept", len(claim["wrote"]))
154
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
155
+ claim["declarations"], claim["assertions"], claim["claimed"])
156
+
157
+
158
+ def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]:
159
+ """Ask the structures topology, in its own process, about the sentence the readers agreed on."""
160
+ dossier, turn, tick, rcpt = protocol.start(incoming)
161
+ sentence = str(dossier.get("sent") or "")
162
+ if not sentence:
163
+ dossier["struc"] = invoker.unavailable("no sentence was agreed on")
164
+ summary = "invoker: nothing to ask the structures topology"
165
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
166
+ ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat")
167
+ verdict = invoker.solve(sentence)
168
+ dossier["struc"] = verdict
169
+ # Both sides counted after the partner's parse: the topology restates a problem in its own normal
170
+ # form, so a sentence and its echo are the same numbers when the parse says so, not when the two
171
+ # texts happen to be alike. The claim is the conjunction of those element equalities, and the
172
+ # status this node writes down is satisfiable exactly when those equalities hold.
173
+ wrote = compare.to_fractions(compare.problem_numbers(canonical.tidy(sentence)))
174
+ echo = compare.to_fractions(compare.problem_numbers(canonical.tidy(str(verdict.get("problem_struc") or ""))))
175
+ decls, asserts = compare.elementwise(wrote, echo, "asked")
176
+ ok = bool(wrote) and wrote == echo
177
+ if not decls:
178
+ asserts = ["(assert (= 1 1))"] if ok else ["(assert false)"]
179
+ summary = "invoker: %s (%s)" % (verdict.get("status"), verdict.get("answer_text") or "no answer")
180
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
181
+ decls, asserts, "sat" if ok else "unsat")
182
+
183
+
184
+ def step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]:
185
+ """The structures verdict enters this stratum here; the echo it carries is checked, not trusted."""
186
+ dossier, turn, tick, rcpt = protocol.start(incoming)
187
+ agreed = str(dossier.get("sent") or "")
188
+ # The echo is checked against the sentence that was agreed on, which may come from either reader:
189
+ # a single reading is still the sentence this stratum sent to the topology.
190
+ reading = {"sentence": agreed} if agreed else (dossier.get("reading_a") or dossier.get("reading_direct") or {})
191
+ struc_verdict = dict(dossier.get("struc") or {})
192
+ echo = str(struc_verdict.get("problem_struc") or "")
193
+ if echo:
194
+ matches = coverage.echo_matches(reading, struc_verdict)
195
+ asked = compare.to_fractions(compare.problem_numbers(canonical.tidy(agreed)))
196
+ echoed = compare.to_fractions(compare.problem_numbers(canonical.tidy(echo)))
197
+ decls, asserts = compare.elementwise(asked, echoed, "echo")
198
+ ok = bool(asked) and asked == echoed
199
+ if not decls:
200
+ asserts = ["(assert (= 1 1))"] if ok else ["(assert false)"]
201
+ claimed = "sat" if ok else "unsat"
202
+ else:
203
+ # The topology answered no sentence at all: there is nothing to compare, and the honest claim
204
+ # is the empty one, which is satisfiable. A node that wanted to look busy here would be
205
+ # asserting something it has no evidence about.
206
+ matches = True
207
+ decls, asserts, claimed = [], ["(assert (= 1 1))"], "sat"
208
+ if faults.has(node_id, "tamper_struc") and echo:
209
+ tampered, changed = faults.mutate_sentence(node_id, echo)
210
+ if changed:
211
+ faults.fire(node_id, "tamper_struc")
212
+ struc_verdict["problem_struc"] = tampered
213
+ struc_verdict["fault"] = "tamper_struc"
214
+ dossier["struc"] = struc_verdict
215
+ dossier["echo_ok"] = bool(matches)
216
+ summary = "boundary: %s echoed=%s" % (struc_verdict.get("status"), "yes" if matches else "no")
217
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier),
218
+ decls, asserts, claimed)
219
+
220
+
221
+ def step_adversary(incoming: Dict[str, Any], node_id: str = "adversary") -> Dict[str, Any]:
222
+ """Re-derive what the previous nodes asserted, and write the cap as an inequality to refute."""
223
+ dossier, turn, tick, rcpt = protocol.start(incoming)
224
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
225
+ if dossier.get("reading_direct") is not None:
226
+ readings = [dossier["reading_direct"], dossier.get("reading_b") or {}]
227
+ comparison = dossier.get("compare")
228
+ struc_verdict = dossier.get("struc") or {}
229
+ cover = dossier.get("coverage")
230
+ if faults.has(node_id, "rubber_stamp"):
231
+ faults.fire(node_id, "rubber_stamp")
232
+ echo_ok = True
233
+ else:
234
+ echo_ok = coverage.echo_matches(readings[0], struc_verdict) if struc_verdict.get("problem_struc") else True
235
+ for other in readings[1:]:
236
+ if other.get("sentence") and not coverage.echo_matches(other, struc_verdict):
237
+ echo_ok = False
238
+ dossier["echo_ok"] = bool(echo_ok)
239
+ state = decide.state_of(readings, comparison, cover,
240
+ struc_verdict if struc_verdict.get("status") else None,
241
+ dossier.get("reading_direct"), echo_ok)
242
+ ceiling = decide.CEILING[state]
243
+ shown = min(ceiling, int(struc_verdict.get("assurance", 0) or 0))
244
+ dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown,
245
+ "struc_assurance": int(struc_verdict.get("assurance", 0) or 0)}
246
+ decls, asserts, claimed = _cap_claim(shown, ceiling)
247
+ summary = "adversary: ceiling %d, shown %d, echo %s" % (ceiling, shown, "ok" if echo_ok else "mismatch")
248
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
249
+
250
+
251
+ def step_arbiter(incoming: Dict[str, Any], node_id: str = "arbiter") -> Dict[str, Any]:
252
+ """Decide, cap, and answer in the language the user wrote in."""
253
+ dossier, turn, tick, rcpt = protocol.start(incoming)
254
+ final = decide.decide(dossier)
255
+ if faults.has(node_id, "force_assurance"):
256
+ faults.fire(node_id, "force_assurance")
257
+ final = decide.raise_assurance(final, 3)
258
+ dossier["final"] = final
259
+ dossier["reply"] = render.reply(dossier, final)
260
+ ceiling = int(final.get("ceiling", 0) or 0)
261
+ decls, asserts, claimed = _cap_claim(int(final.get("assurance", 0) or 0), ceiling)
262
+ summary = "arbiter: %s (assurance %d) %s" % (final["state"], final["assurance"], final["answer"] or "")
263
+ return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
264
+
265
+
266
+ STEPS = {
267
+ "reader_a": step_reader_a,
268
+ "reader_b": step_reader_b,
269
+ "equivalence": step_equivalence,
270
+ "coverage": step_coverage,
271
+ "invoker": step_invoker,
272
+ "boundary": step_boundary,
273
+ "adversary": step_adversary,
274
+ "arbiter": step_arbiter,
275
+ }
276
+
277
+
278
+ def run_step(role: str, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]:
279
+ """Run one role, containing any unexpected exception as a crash entry in the dossier.
280
+
281
+ A node that crashes must not stop the session: the arbiter then reports the state NONE with zero
282
+ assurance, so the user is never left with a half-built answer and never with an invented one
283
+ either.
284
+ """
285
+ try:
286
+ return STEPS[role](incoming, node_id)
287
+ except Exception as exc: # noqa: BLE001 - containment is the whole point of this wrapper
288
+ dossier, turn, tick, rcpt = protocol.start(incoming)
289
+ dossier.setdefault("crash", {})[role] = "%s: %s" % (type(exc).__name__, str(exc)[:120])
290
+ return protocol.envelope(node_id, rcpt, turn, tick, "%s crashed" % role, "Crashed", dossier,
291
+ [], ["(assert true)"], "sat")
lingologos_stratum/canonical.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The canonical sentence of the stratum: one sentence of the structures language.
2
+
3
+ The two readers do not compare their own wording with each other. Each of them turns the sentence
4
+ of a human language into **one text of the language the structures topology speaks**, and the
5
+ equivalence node is what decides whether the two texts are the same problem. This module owns that
6
+ language: the eight kinds of question, the order of the slots of each kind, the six blocks of a
7
+ frame, the two spellings of a section, and the exact spelling of a number.
8
+
9
+ The language is not invented here. It is the language the sibling topology parses -- the same words
10
+ (``frame``, ``nodes``, ``supports``, ``udl``, ``vonmises``), the same block order, the same bracket
11
+ notation, the same rationals -- and this module is a *shape* check of it, not a second semantics: it
12
+ verifies that a sentence has the shape in which the structures topology reads a problem, and it
13
+ nothing about a structure. Deciding a structure belongs to those thirteen nodes.
14
+
15
+ Why the check exists at all: the sentence a reader prints is the sentence the stratum hands to the
16
+ structures topology, and the echo of that topology is compared with it. A reading that dropped a
17
+ bracket, reordered two blocks or wrote ``3`` where the block wanted four numbers would otherwise
18
+ travel as if it were a reading, and the answer it produced would look like an answer to the question
19
+ the person asked.
20
+
21
+ classify frame nodes [ 1 0 0 ; 2 2 0 ] members [ 1 1 2 ] props [ 1 210000000 1/5 2/1875 ]
22
+ supports [ 1 pin ; 2 roller 0 1 ] loads [ member 1 udl 0 -15 ]
23
+ cut member 1 at 1 <frame>
24
+ peak moment <frame>
25
+ deflect node 2 vertical <frame>
26
+ properties section rect 1/5 2/5
27
+ verify bending member 1 at 2 section rect 1/5 2/5 limit 16000 <frame>
28
+ euler ends pinned pinned length 21/10 modulus 210000000 section rect 1/10 1/10
29
+
30
+ Numbers are written the way the structures topology writes them: an exact rational, ``75/2`` and not
31
+ ``37.5``. That normalisation is the reason a person may write ``0.5`` in their own sentence and still
32
+ be read as the same problem: the value is what is kept, not the spelling.
33
+ """
34
+
35
+ import re
36
+ from fractions import Fraction
37
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
38
+
39
+ FRAME_WORD = "frame"
40
+ BLOCKS = ("nodes", "members", "props", "supports", "loads", "hinges")
41
+ SUPPORT_KINDS = ("fixed", "pin", "roller")
42
+ LOAD_OWNERS = ("node", "member")
43
+ LOAD_KINDS = ("force", "couple", "udl", "point")
44
+ VERIFY_MODES = ("bending", "shear", "vonmises")
45
+ DIRECTIONS = ("vertical", "horizontal", "rotation")
46
+ END_KINDS = ("pinned", "fixed", "free")
47
+ QUANTITIES = ("moment", "shear", "axial")
48
+ SECTION_FORMS = ("rect", "shapes")
49
+
50
+ # The five sets of end conditions the manual of the structures topology knows, and nothing else.
51
+ EULER_LENGTHS = (("pinned", "pinned"), ("fixed", "free"), ("fixed", "fixed"),
52
+ ("fixed", "pinned"), ("pinned", "fixed"))
53
+
54
+ KINDS = ("classify", "reactions", "cut", "peak", "deflect", "properties", "verify", "euler")
55
+
56
+ # One template per way of asking, with the slots in the order the structures language prints them.
57
+ # ``deflect`` has two shapes because the topology has two: a node moves, or a section of a member
58
+ # moves at an abscissa along it.
59
+ TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = {
60
+ "classify": [(("F",), "classify {F}")],
61
+ "reactions": [(("F",), "reactions {F}")],
62
+ "cut": [(("M", "P", "F"), "cut member {M} at {P} {F}")],
63
+ "peak": [(("Q", "F"), "peak {Q} {F}")],
64
+ "deflect": [(("N", "D", "F"), "deflect node {N} {D} {F}"),
65
+ (("M", "P", "D", "F"), "deflect member {M} at {P} {D} {F}")],
66
+ "properties": [(("S",), "properties section {S}")],
67
+ "verify": [(("V", "M", "P", "S", "L", "F"),
68
+ "verify {V} member {M} at {P} section {S} limit {L} {F}")],
69
+ "euler": [(("E1", "E2", "L", "MOD", "S"),
70
+ "euler ends {E1} {E2} length {L} modulus {MOD} section {S}")],
71
+ }
72
+
73
+ # Which slot of which kind holds what. ``num`` is a number, ``word`` is one of the closed sets of
74
+ # the language, ``frame`` and ``section`` are regions written in the bracket notation.
75
+ SLOT_KIND: Dict[str, Dict[str, str]] = {
76
+ "classify": {"F": "frame"},
77
+ "reactions": {"F": "frame"},
78
+ "cut": {"M": "num", "P": "num", "F": "frame"},
79
+ "peak": {"Q": "quantity", "F": "frame"},
80
+ "deflect": {"N": "num", "M": "num", "P": "num", "D": "direction", "F": "frame"},
81
+ "properties": {"S": "section"},
82
+ "verify": {"V": "mode", "M": "num", "P": "num", "S": "section", "L": "num", "F": "frame"},
83
+ "euler": {"E1": "end", "E2": "end", "L": "num", "MOD": "num", "S": "section"},
84
+ }
85
+
86
+ # The fixed words of the templates: the joints a sentence of this language is built out of, and the
87
+ # only way a reader can tell which number is the abscissa of a cut and which one is the limit of a
88
+ # check. test_readers checks that every fixed word of every template is listed here.
89
+ JOINTS = ("at", "ends", "length", "limit", "modulus", "node", "member", "section")
90
+
91
+ # Every word of the structures language, so that a sentence made only of these words and numbers is
92
+ # a sentence already written in it: the stratum calls that case PASSTHROUGH and translates nothing.
93
+ WORDS = frozenset(
94
+ (FRAME_WORD,) + BLOCKS + SUPPORT_KINDS + LOAD_OWNERS + LOAD_KINDS + VERIFY_MODES
95
+ + DIRECTIONS + END_KINDS + QUANTITIES + SECTION_FORMS + JOINTS + KINDS
96
+ )
97
+
98
+
99
+ class ReadingError(Exception):
100
+ """A sentence of the structures language that this bundle cannot write or cannot check."""
101
+
102
+
103
+ # ---------------------------------------------------------------------------
104
+ # Numbers
105
+ # ---------------------------------------------------------------------------
106
+ _NUMBER = re.compile(r"[-+]?(?:\d+(?:[.,]\d+)?(?:/[+-]?\d+(?:[.,]\d+)?)?|[.,]\d+)")
107
+
108
+
109
+ def tidy(text: str) -> str:
110
+ """Collapse every run of spaces and trim: two sentences are compared as texts, not as layout."""
111
+ return re.sub(r"\s+", " ", str(text or "")).strip()
112
+
113
+
114
+ def value(token: str) -> str:
115
+ """One number as the structures topology writes it: an exact rational, integers without denominator.
116
+
117
+ ``0.5`` and ``1/2`` reach the same text, and so do ``+3`` and ``3``, and so does the Italian ``1,5``,
118
+ which writes the same number with the comma its own notation uses. A token that is not a number is
119
+ an error, because a slot that wanted a number and got a word is a reading to refuse.
120
+ """
121
+ text = str(token).strip().replace(",", ".")
122
+ if not _NUMBER.fullmatch(text):
123
+ raise ReadingError("not a number: %r" % text)
124
+ try:
125
+ number = Fraction(text)
126
+ except ValueError:
127
+ raise ReadingError("not a number: %r" % text)
128
+ return str(number)
129
+
130
+
131
+ def numbers(text: str) -> List[str]:
132
+ """Every number of a sentence, in order, as a value.
133
+
134
+ Used to count what the person wrote against what a reading kept. Counting *values* and not digit
135
+ strings is what lets a sentence written ``0.5`` be kept as ``1/2`` without the count of literals
136
+ turning that into a dispute.
137
+ """
138
+ out: List[str] = []
139
+ for match in _NUMBER.finditer(str(text or "")):
140
+ try:
141
+ out.append(value(match.group(0)))
142
+ except ReadingError:
143
+ continue
144
+ return out
145
+
146
+
147
+ def sorted_numbers(text: str) -> List[str]:
148
+ """The same values ordered, so a reordering of slots is not read as a change of problem."""
149
+ return sorted(numbers(text), key=lambda item: (Fraction(item), item))
150
+
151
+
152
+ # ---------------------------------------------------------------------------
153
+ # Tokenising the bracket notation
154
+ # ---------------------------------------------------------------------------
155
+ _SPLIT = re.compile(r"(\[|\]|;)")
156
+ _TOKEN = re.compile(r"\[|\]|;|" + _NUMBER.pattern + r"|[^\s\[\];]+")
157
+
158
+
159
+ def tokens(text: str) -> List[str]:
160
+ """The bracket notation as tokens: brackets and semicolons alone, numbers and words as themselves."""
161
+ return _TOKEN.findall(tidy(text)) or []
162
+
163
+
164
+ def _want_number(part: Sequence[str], index: int, what: str) -> Tuple[str, int]:
165
+ if index >= len(part) or not _NUMBER.fullmatch(part[index]):
166
+ raise ReadingError("%s wants a number at %r" % (what, part[index:index + 2]))
167
+ return value(part[index]), index + 1
168
+
169
+
170
+ def _want_word(part: Sequence[str], index: int, allowed: Sequence[str], what: str) -> Tuple[str, int]:
171
+ if index >= len(part) or part[index] not in allowed:
172
+ raise ReadingError("%s wants one of %s, found %r"
173
+ % (what, "/".join(allowed), part[index:index + 1]))
174
+ return part[index], index + 1
175
+
176
+
177
+ # ---------------------------------------------------------------------------
178
+ # A frame
179
+ # ---------------------------------------------------------------------------
180
+ def _entry_tokens(block: str, piece: Sequence[str]) -> List[str]:
181
+ """One entry of one block, checked against the arity the structures language gives it."""
182
+ out: List[str] = []
183
+ index = 0
184
+ if block == "nodes":
185
+ for what in ("node id", "abscissa", "ordinate"):
186
+ out.append(_want_number(piece, index, what)[0])
187
+ index += 1
188
+ elif block == "members":
189
+ for what in ("member id", "first node", "second node"):
190
+ out.append(_want_number(piece, index, what)[0])
191
+ index += 1
192
+ elif block == "props":
193
+ for what in ("member id", "modulus", "area", "inertia"):
194
+ out.append(_want_number(piece, index, what)[0])
195
+ index += 1
196
+ elif block == "supports":
197
+ out.append(_want_number(piece, index, "node id")[0])
198
+ index += 1
199
+ kind, index = _want_word(piece, index, SUPPORT_KINDS, "a support")
200
+ out.append(kind)
201
+ if kind == "roller":
202
+ for what in ("normal abscissa", "normal ordinate"):
203
+ out.append(_want_number(piece, index, what)[0])
204
+ index += 1
205
+ elif block == "loads":
206
+ owner, index = _want_word(piece, index, LOAD_OWNERS, "a load")
207
+ out.append(owner)
208
+ out.append(_want_number(piece, index, "target id")[0])
209
+ index += 1
210
+ kind, index = _want_word(piece, index, LOAD_KINDS, "a load")
211
+ out.append(kind)
212
+ if (owner, kind) == ("node", "force"):
213
+ how = ("abscissa", "ordinate")
214
+ elif (owner, kind) == ("node", "couple"):
215
+ how = ("couple",)
216
+ elif (owner, kind) == ("member", "udl"):
217
+ how = ("abscissa", "ordinate")
218
+ elif (owner, kind) == ("member", "point"):
219
+ how = ("position", "abscissa", "ordinate")
220
+ else:
221
+ how = ("position", "couple")
222
+ for what in how:
223
+ out.append(_want_number(piece, index, what)[0])
224
+ index += 1
225
+ elif block == "hinges":
226
+ out.append(_want_number(piece, index, "hinged node")[0])
227
+ index += 1
228
+ else:
229
+ raise ReadingError("unknown block %s" % block)
230
+ if index != len(piece):
231
+ raise ReadingError("the %s entry %r has words or numbers left over" % (block, list(piece)))
232
+ return out
233
+
234
+
235
+ def frame(text: str) -> str:
236
+ """The frame of a problem, checked and written the way the structures topology writes it."""
237
+ parts = tokens(text)
238
+ if not parts or parts[0] != FRAME_WORD:
239
+ raise ReadingError("a frame starts with the word frame")
240
+ cursor = 1
241
+ seen: List[str] = []
242
+ for block in BLOCKS:
243
+ if cursor < len(parts) and parts[cursor] == block:
244
+ cursor += 1
245
+ if cursor >= len(parts) or parts[cursor] != "[":
246
+ raise ReadingError("the block %s has no brackets" % block)
247
+ close = _closing(parts, cursor)
248
+ entries: List[str] = []
249
+ for piece in _segments(parts, cursor + 1, close):
250
+ entries.append(" ".join(_entry_tokens(block, piece)))
251
+ if not entries and block != "hinges":
252
+ raise ReadingError("the block %s is empty" % block)
253
+ seen.append("%s [ %s ]" % (block, " ; ".join(entries)))
254
+ cursor = close + 1
255
+ elif block not in ("loads", "hinges"):
256
+ raise ReadingError("the frame has no %s block" % block)
257
+ if cursor != len(parts):
258
+ raise ReadingError("the frame ends with %r" % parts[cursor:cursor + 2])
259
+ return "%s %s" % (FRAME_WORD, " ".join(seen))
260
+
261
+
262
+ def section(text: str) -> str:
263
+ """The section of a problem, in one of the two spellings the structures language has."""
264
+ parts = tokens(text)
265
+ if not parts:
266
+ raise ReadingError("a section is missing")
267
+ if parts[0] == "rect":
268
+ if len(parts) != 3:
269
+ raise ReadingError("rect wants a width and a height")
270
+ return "rect %s %s" % (_want_number(parts, 1, "width")[0],
271
+ _want_number(parts, 2, "height")[0])
272
+ if parts[0] == "shapes":
273
+ if len(parts) < 2 or parts[1] != "[":
274
+ raise ReadingError("shapes has no brackets")
275
+ close = _closing(parts, 1)
276
+ shapes: List[str] = []
277
+ for piece in _segments(parts, 2, close):
278
+ if not piece or piece[0] != "rect" or len(piece) != 4:
279
+ raise ReadingError("a shape of the section must be rect with three numbers")
280
+ shapes.append("rect %s %s %s" % tuple(
281
+ _want_number(piece, at, what)[0]
282
+ for at, what in ((1, "width"), (2, "height"), (3, "centre"))))
283
+ if not shapes:
284
+ raise ReadingError("the section has no rectangle")
285
+ if close + 1 != len(parts):
286
+ raise ReadingError("the section ends with %r" % parts[close + 1:close + 3])
287
+ return "shapes [ %s ]" % " ; ".join(shapes)
288
+ raise ReadingError("a section is rect or shapes")
289
+
290
+
291
+ def _closing(parts: Sequence[str], at: int) -> int:
292
+ depth = 0
293
+ for index in range(at, len(parts)):
294
+ if parts[index] == "[":
295
+ depth += 1
296
+ elif parts[index] == "]" and depth == 1:
297
+ return index
298
+ raise ReadingError("a bracket is never closed")
299
+
300
+
301
+ def _segments(parts: Sequence[str], start: int, stop: int) -> List[List[str]]:
302
+ """The pieces between semicolons inside one pair of brackets."""
303
+ out: List[List[str]] = []
304
+ piece: List[str] = []
305
+ for index in range(start, stop):
306
+ if parts[index] == ";":
307
+ out.append(piece)
308
+ piece = []
309
+ else:
310
+ piece.append(parts[index])
311
+ if piece:
312
+ out.append(piece)
313
+ return [item for item in out if item]
314
+
315
+
316
+ # ---------------------------------------------------------------------------
317
+ # Printing and reading a whole sentence
318
+ # ---------------------------------------------------------------------------
319
+ def slots_for(kind: str) -> Tuple[str, ...]:
320
+ """The slots of the first template of a kind, in the order the language prints them."""
321
+ if kind not in TEMPLATES:
322
+ raise ReadingError("unknown kind %s" % kind)
323
+ return TEMPLATES[kind][0][0]
324
+
325
+
326
+ def template_for(kind: str, slots: Dict[str, str]) -> Tuple[Tuple[str, ...], str]:
327
+ """The template of a kind the filled slots fit, or a refusal naming the slots that are missing."""
328
+ if kind not in TEMPLATES:
329
+ raise ReadingError("unknown kind %s" % kind)
330
+ for names, text in TEMPLATES[kind]:
331
+ if all(str(slots.get(name, "")).strip() for name in names):
332
+ return names, text
333
+ raise ReadingError("%s is missing one of %s" % (kind, "/".join(TEMPLATES[kind][0][0])))
334
+
335
+
336
+ def fill(kind: str, slots: Dict[str, str]) -> str:
337
+ """Print one sentence of the structures language from the slots a reader filled."""
338
+ names, text = template_for(kind, slots)
339
+ filled: Dict[str, str] = {}
340
+ for name in names:
341
+ raw = tidy(str(slots.get(name, "")))
342
+ what = SLOT_KIND[kind][name]
343
+ if what == "num":
344
+ filled[name] = value(raw)
345
+ elif what == "frame":
346
+ filled[name] = frame(raw)
347
+ elif what == "section":
348
+ filled[name] = section(raw)
349
+ elif what == "quantity":
350
+ filled[name] = _checked(raw, QUANTITIES, "a quantity of the diagram")
351
+ elif what == "direction":
352
+ filled[name] = _checked(raw, DIRECTIONS, "a direction of the displacement")
353
+ elif what == "mode":
354
+ filled[name] = _checked(raw, VERIFY_MODES, "a check of strength")
355
+ elif what == "end":
356
+ filled[name] = _checked(END_FROM_VALUE.get(raw, raw), END_KINDS,
357
+ "a condition of the end of the column")
358
+ else:
359
+ raise ReadingError("slot %s of %s has no kind" % (name, kind))
360
+ if kind == "euler" and (filled["E1"], filled["E2"]) not in EULER_LENGTHS:
361
+ raise ReadingError("the ends %s %s are not one of the five of the manual"
362
+ % (filled["E1"], filled["E2"]))
363
+ return tidy(text.format(**filled))
364
+
365
+
366
+ def _checked(raw: str, allowed: Sequence[str], what: str) -> str:
367
+ if raw not in allowed:
368
+ raise ReadingError("%s must be one of %s, found %r" % (what, "/".join(allowed), raw))
369
+ return raw
370
+
371
+
372
+ def direct(text: str) -> Optional[Dict[str, Any]]:
373
+ """A sentence already written in the structures language, read without translating anything.
374
+
375
+ This is the only place the stratum parses its own language from end to end, and it exists for one
376
+ case: the person wrote the structures language themselves. Then there is no translation to check,
377
+ and the session says so (PASSTHROUGH) instead of pretending two readers worked. ``None`` means the
378
+ text is not that language, which is the normal case.
379
+ """
380
+ parts = tokens(text)
381
+ if not parts or parts[0] not in KINDS:
382
+ return None
383
+ if any(piece not in WORDS for piece in parts
384
+ if piece not in ("[", "]", ";") and not _NUMBER.fullmatch(piece)):
385
+ return None
386
+ kind = parts[0]
387
+ try:
388
+ slots = _slots_of(kind, parts[1:])
389
+ except ReadingError:
390
+ return None
391
+ if slots is None:
392
+ return None
393
+ try:
394
+ sentence = fill(kind, slots)
395
+ except ReadingError:
396
+ return None
397
+ if tidy(sentence) != tidy(text):
398
+ return None
399
+ return {"status": "READ", "kind": kind, "sentence": sentence, "slots": slots,
400
+ "notes": [], "literals": numbers(sentence), "direct": True}
401
+
402
+
403
+ def _slots_of(kind: str, parts: Sequence[str]) -> Optional[Dict[str, str]]:
404
+ """The slots of a kind, read out of the words of a sentence of the structures language.
405
+
406
+ Written as one branch per kind, the way the structures topology parses its own head. A template
407
+ loop would be shorter and would hide the one thing that has to be explicit here: where a frame or
408
+ a section stops, because the words of a block are also words of the language.
409
+ """
410
+ try:
411
+ if kind in ("classify", "reactions"):
412
+ return {"F": _region(parts, 0)[0]}
413
+ if kind == "cut":
414
+ at = _expect(parts, 0, "member")
415
+ member = parts[at]
416
+ at = _expect(parts, at + 1, "at")
417
+ place = parts[at]
418
+ region, end = _region(parts, at + 1)
419
+ if end != len(parts):
420
+ return None
421
+ return {"M": member, "P": place, "F": region}
422
+ if kind == "peak":
423
+ region, end = _region(parts, 1)
424
+ if end != len(parts):
425
+ return None
426
+ return {"Q": parts[0], "F": region}
427
+ if kind == "deflect":
428
+ if parts[:1] == ["node"]:
429
+ region, end = _region(parts, 3)
430
+ if end != len(parts):
431
+ return None
432
+ return {"N": parts[1], "D": parts[2], "F": region}
433
+ if parts[:1] == ["member"]:
434
+ at = _expect(parts, 2, "at")
435
+ region, end = _region(parts, at + 2)
436
+ if end != len(parts):
437
+ return None
438
+ return {"M": parts[1], "P": parts[at], "D": parts[at + 1], "F": region}
439
+ return None
440
+ if kind == "properties":
441
+ start = _expect(parts, 0, "section")
442
+ region, end = _region(parts, start)
443
+ if end != len(parts):
444
+ return None
445
+ return {"S": region}
446
+ if kind == "verify":
447
+ mode = parts[0]
448
+ at = _expect(parts, 1, "member")
449
+ member = parts[at]
450
+ at = _expect(parts, at + 1, "at")
451
+ place = parts[at]
452
+ at = _expect(parts, at + 1, "section")
453
+ region, end = _region(parts, at)
454
+ at = _expect(parts, end, "limit")
455
+ limit = parts[at]
456
+ frame_text, stop = _region(parts, at + 1)
457
+ if stop != len(parts):
458
+ return None
459
+ return {"V": mode, "M": member, "P": place, "S": region, "L": limit, "F": frame_text}
460
+ if kind == "euler":
461
+ at = _expect(parts, 0, "ends")
462
+ first, second = parts[at], parts[at + 1]
463
+ at = _expect(parts, at + 2, "length")
464
+ length = parts[at]
465
+ at = _expect(parts, at + 1, "modulus")
466
+ modulus = parts[at]
467
+ at = _expect(parts, at + 1, "section")
468
+ region, end = _region(parts, at)
469
+ if end != len(parts):
470
+ return None
471
+ return {"E1": first, "E2": second, "L": length, "MOD": modulus, "S": region}
472
+ except (ReadingError, IndexError):
473
+ return None
474
+ return None
475
+
476
+
477
+ def _expect(parts: Sequence[str], index: int, word: str) -> int:
478
+ """The position after the fixed word ``word``, which has to stand at ``index``."""
479
+ if index >= len(parts) or parts[index] != word:
480
+ raise ReadingError("%s is missing where the language wants it" % word)
481
+ return index + 1
482
+
483
+
484
+ def _region(parts: Sequence[str], start: int) -> Tuple[str, int]:
485
+ """The frame or the section that starts at ``start``, as text and as where it stops."""
486
+ if start >= len(parts) or parts[start] not in (FRAME_WORD, "rect", "shapes"):
487
+ raise ReadingError("a frame or a section is missing")
488
+ if parts[start] == "rect":
489
+ return "rect %s %s" % (parts[start + 1], parts[start + 2]), start + 3
490
+ if parts[start] == "shapes":
491
+ return " ".join(parts[start:_closing(parts, start + 1) + 1]), _closing(parts, start + 1) + 1
492
+ index = start + 1
493
+ while index < len(parts) and parts[index] in BLOCKS:
494
+ if index + 1 >= len(parts) or parts[index + 1] != "[":
495
+ raise ReadingError("the block %s has no brackets" % parts[index])
496
+ index = _closing(parts, index + 1) + 1
497
+ return " ".join(parts[start:index]), index
498
+
499
+
500
+ # ---------------------------------------------------------------------------
501
+ # Where a region of the bracket notation stands in a sentence of a human language
502
+ # ---------------------------------------------------------------------------
503
+ # The words a region of the notation is built from. A reader walks a sentence and stops the region
504
+ # at the first word outside this vocabulary: the region of a frame or of a section is bounded by its
505
+ # own words, and a reader that let "limit" or "the answer is" into it would carry a sentence fragment
506
+ # into the problem.
507
+ REGION_HEADS = (FRAME_WORD,) + SECTION_FORMS
508
+ FRAME_VALUES = (FRAME_WORD,) + BLOCKS + SUPPORT_KINDS + LOAD_OWNERS + LOAD_KINDS
509
+ SECTION_VALUES = SECTION_FORMS
510
+
511
+
512
+ def extent(values: Sequence[str], start: int) -> int:
513
+ """Where the frame or the section starting at ``start`` stops, over the values of an item stream.
514
+
515
+ A reader hands this the value of every item of its sentence: the canonical word a lexicon phrase
516
+ carried, the run of digits and brackets the atomiser cut, and the empty string for a word that is
517
+ neither. The answer is the position one past the region, or ``-1`` when what stands there is not a
518
+ region at all.
519
+
520
+ This is the shape of the notation and nothing else -- both readers ask it, just as both
521
+ formalizers of the topology read one written grammar -- and neither reader is told what the region
522
+ means. Whether the frame it names stands one node too far to the left belongs to the thirteen
523
+ nodes of structures, not to this bundle.
524
+ """
525
+ if start >= len(values) or values[start] not in REGION_HEADS:
526
+ return -1
527
+ if values[start] == "rect":
528
+ if start + 2 < len(values) and all(_NUMBER.fullmatch(piece or "")
529
+ for piece in values[start + 1:start + 3]):
530
+ return start + 3
531
+ return -1
532
+ if values[start] == "shapes":
533
+ return _bracket_end(values, start + 1, SECTION_VALUES)
534
+ index = start + 1
535
+ while index < len(values) and values[index] in BLOCKS:
536
+ closed = _bracket_end(values, index + 1, FRAME_VALUES)
537
+ if closed < 0:
538
+ return -1
539
+ index = closed
540
+ return index
541
+
542
+
543
+ def _bracket_end(values: Sequence[str], start: int, allowed: Sequence[str]) -> int:
544
+ """The position one past a run of brackets whose content is made of numbers and of ``allowed``."""
545
+ depth = 0
546
+ index = start
547
+ while index < len(values):
548
+ piece = values[index]
549
+ if not piece:
550
+ return -1
551
+ if piece == "[":
552
+ depth += 1
553
+ index += 1
554
+ continue
555
+ if piece == "]":
556
+ depth -= 1
557
+ index += 1
558
+ if depth == 0:
559
+ return index
560
+ if depth < 0:
561
+ return -1
562
+ continue
563
+ if _NUMBER.fullmatch(piece) or piece in allowed:
564
+ index += 1
565
+ continue
566
+ # A run of notation split by a word the atomiser read as words: pieces of brackets and
567
+ # numbers inside one notation run are checked as tokens, not as one atom.
568
+ pieces = tokens(piece)
569
+ if not pieces or any(not (_NUMBER.fullmatch(item) or item in allowed or item in "[];")
570
+ for item in pieces):
571
+ return -1
572
+ depth += piece.count("[") - piece.count("]")
573
+ if depth <= 0:
574
+ return index + 1
575
+ index += 1
576
+ return -1
577
+
578
+
579
+ def region_text(values: Sequence[str], start: int, stop: int) -> str:
580
+ """The words and the notation of a region, joined as one text of the structures language."""
581
+ return tidy(" ".join(piece for index in range(start, stop)
582
+ for piece in tokens(values[index] or "")))
583
+
584
+
585
+ # ---------------------------------------------------------------------------
586
+ # The joints of a kind, which is how reader B reads a sentence without a pattern
587
+ # ---------------------------------------------------------------------------
588
+ # A sequence of markers is a fact of the structures language: the joints it must hear, in order, and
589
+ # the placeholder ``{SLOT}`` where the language hears the *value* of a slot instead of a joint -- the
590
+ # quantity whose maximum is asked for, the direction of a displacement, the form of a section, the
591
+ # head word of a frame. A number is never a marker, so it never enters a sequence: it falls into the
592
+ # region the joint before it introduces.
593
+ VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [names for names, _ in list_]
594
+ for kind, list_ in TEMPLATES.items()}
595
+ _PLACEHOLDER = re.compile(r"^\{([A-Z][A-Z0-9]*)\}$")
596
+
597
+
598
+ def marker_sequence(kind: str, variant: Sequence[str]) -> List[str]:
599
+ """The markers a sentence of one form must carry, in order, with a placeholder per value slot."""
600
+ names, text = _template(kind, variant)
601
+ out: List[str] = []
602
+ for piece in tokens(text)[1:]:
603
+ match = _PLACEHOLDER.fullmatch(piece)
604
+ if match:
605
+ slot = match.group(1)
606
+ if SLOT_KIND[kind][slot] != "num":
607
+ out.append("{%s}" % slot)
608
+ elif piece not in ("[", "]", ";"):
609
+ out.append(piece)
610
+ return out
611
+
612
+
613
+ def gap_markers(kind: str, variant: Sequence[str]) -> List[Optional[str]]:
614
+ """The joint that introduces the numbers of each slot of a form, and ``None`` where there is none."""
615
+ names, text = _template(kind, variant)
616
+ gaps: List[Optional[str]] = []
617
+ joint: Optional[str] = None
618
+ for piece in tokens(text)[1:]:
619
+ match = _PLACEHOLDER.fullmatch(piece)
620
+ if match:
621
+ slot = match.group(1)
622
+ if slot in variant:
623
+ gaps.append(joint if SLOT_KIND[kind][slot] == "num" else None)
624
+ continue
625
+ if piece not in ("[", "]", ";"):
626
+ joint = piece
627
+ gaps.append(None)
628
+ return gaps
629
+
630
+
631
+ def print_sentence(kind: str, slots: Dict[str, str]) -> str:
632
+ """The sentence of the structures language for one kind and one set of slots.
633
+
634
+ The fault catalogue of ``faults.py`` needs this: a reading that has been damaged on purpose has
635
+ to stay a sentence the structures topology will accept, or the experiment would measure the
636
+ topology refusing to parse and nothing about the reading.
637
+ """
638
+ return fill(kind, slots)
639
+
640
+
641
+ def balanced(text: str) -> bool:
642
+ """Whether the brackets of a sentence of the structures language open and close in pairs."""
643
+ depth = 0
644
+ for piece in tokens(text):
645
+ if piece == "[":
646
+ depth += 1
647
+ elif piece == "]":
648
+ depth -= 1
649
+ if depth < 0:
650
+ return False
651
+ return depth == 0
652
+
653
+
654
+ def _template(kind: str, variant: Sequence[str]) -> Tuple[Tuple[str, ...], str]:
655
+ for names, text in TEMPLATES.get(kind, []):
656
+ if tuple(names) == tuple(variant):
657
+ return names, text
658
+ raise ReadingError("%s has no form %s" % (kind, " ".join(variant)))
659
+
660
+
661
+ # A language that has one word for a hinge says it both for the support of a structure and for the
662
+ # end of a column: Italian "cerniera", Spanish "articulacion". The structures language keeps the two
663
+ # apart, so a reader that filled an end slot with the word of a support says which one it meant.
664
+ END_FROM_VALUE = {"pin": "pinned", "fixed": "fixed", "free": "free"}
lingologos_stratum/compare.py ADDED
@@ -0,0 +1,360 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The equivalence of the two readings: do the two readers mean the same structure?
2
+
3
+ Reader A and reader B reach their sentence of the structures language by different routes -- surface
4
+ patterns and marker frames -- and the stratum only trusts the pair when the two sentences describe
5
+ one structure. Textual identity is the easy case. The interesting case is two *different* texts that
6
+ describe the same problem, and the only honest way to settle it is to ask what the structures
7
+ topology itself makes of the two texts, which is what this module does.
8
+
9
+ The parsing of the structures language is **not reimplemented here**. The ``struc`` bundle owns that
10
+ account, and a second copy of it inside the reading layer would be a third place where the meaning of
11
+ the language could be wrong without anyone noticing. So this module loads the structures bundle
12
+ (:envvar:`LINGOLOGOS_STRATUM_STRUC_ROOT`, sibling folder ``struc`` by default), has it parse both sentences,
13
+ and states the claim ``the readings differ`` as SMT2 over the numbers and the words of the two parses:
14
+ unsatisfiable means the two readings denote one structure under every assignment, the same
15
+ ``equiv: unsat`` discipline the structures topology applies between its own two solution roads.
16
+
17
+ Three consequences are deliberate and all of them are limits, not shortcuts:
18
+
19
+ * a sentence the structures topology will not parse has no fingerprint, and two readings that cannot
20
+ be put beside the topology's own view are reported ``unknown``: the stratum abstains rather than
21
+ assume two texts are equal;
22
+ * a spelling difference is not a difference. ``1,5`` and ``1/2`` and ``0.5`` are one number, so the
23
+ claim pins rationals, never character strings -- and the echo of the topology, which expands
24
+ ``supports [ 1 pin ]`` into ``pin 0 0``, is compared as a parse and not as a string;
25
+ * the Z3 claim of this module is *about the readings*, never about the user's structure. The problem
26
+ itself is never decided here: the sentence is handed to the structures topology, whose verdict is
27
+ shown as it arrived.
28
+ """
29
+
30
+ import sys
31
+ from fractions import Fraction
32
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
33
+
34
+ from . import canonical, invoker
35
+
36
+ _partner: Tuple[Any, Any] = ()
37
+ _PARTNER_LOOKUP_ERROR: Optional[str] = None
38
+
39
+
40
+ def _partner_modules() -> Tuple[Any, Any, Optional[str]]:
41
+ """The structures bundle's parser and its Z3 referee, or the reason they are not available."""
42
+ global _partner, _PARTNER_LOOKUP_ERROR
43
+ if _partner:
44
+ return _partner[0], _partner[1], None
45
+ if _PARTNER_LOOKUP_ERROR is not None:
46
+ return None, None, _PARTNER_LOOKUP_ERROR
47
+ root = invoker.struc_root()
48
+ if not (root / "lingologos_struc").is_dir():
49
+ _PARTNER_LOOKUP_ERROR = "no lingologos_struc package under %s" % root
50
+ return None, None, _PARTNER_LOOKUP_ERROR
51
+ text = str(root)
52
+ if text not in sys.path:
53
+ sys.path.insert(0, text)
54
+ try:
55
+ from lingologos_struc import parse_a, smt # noqa: PLC0415 - the import of the structures bundle is the point
56
+ except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently
57
+ _PARTNER_LOOKUP_ERROR = "the structures bundle could not be imported: %s" % type(exc).__name__
58
+ return None, None, _PARTNER_LOOKUP_ERROR
59
+ _partner = (parse_a, smt)
60
+ return _partner[0], _partner[1], None
61
+
62
+
63
+ ONTOLOGY = "(set-option :timeout 8000)\n"
64
+
65
+
66
+ def smt_referee(decls: List[str], asserts: List[str]) -> str:
67
+ """Run the referee of the structures topology over one claim, the way its orchestrator does.
68
+
69
+ The same code answers here and inside the thirteen nodes of the partner, so an envelope this
70
+ stratum writes is checked by the solver the project already trusts; the stratum adds no second
71
+ referee. When the partner is not on disk the answer is ``unknown``, which is what an unanswered
72
+ claim is worth.
73
+ """
74
+ _parser, smt, _reason = _partner_modules()
75
+ if smt is None:
76
+ return "unknown"
77
+ return str(smt.referee(ONTOLOGY, list(decls), list(asserts)))
78
+
79
+
80
+ # ---------------------------------------------------------------------------
81
+ # Numbers: one spelling everywhere
82
+ # ---------------------------------------------------------------------------
83
+ def numbers(text: str) -> List[Fraction]:
84
+ """Every number written in a sentence or in a question, in order, as exact rationals."""
85
+ out: List[Fraction] = []
86
+ for token in canonical.numbers(text):
87
+ try:
88
+ out.append(Fraction(canonical.value(token)))
89
+ except canonical.ReadingError:
90
+ continue
91
+ return out
92
+
93
+
94
+ def sorted_numbers(text: str) -> List[str]:
95
+ """The same numbers ordered by value and spelled as ratios, so a reordering is not a change."""
96
+ return [str(value) for value in sorted(numbers(text))]
97
+
98
+
99
+ def _pin(name: str, value: Fraction) -> Tuple[List[str], List[str]]:
100
+ """One real declared and fixed to an exact rational, in the partner's own literal syntax."""
101
+ value = Fraction(value)
102
+ return (["(declare-const %s Real)" % name],
103
+ ["(assert (= %s (/ %d %d)))" % (name, value.numerator, value.denominator)])
104
+
105
+
106
+ # ---------------------------------------------------------------------------
107
+ # The topology's own view of one canonical sentence
108
+ # ---------------------------------------------------------------------------
109
+ def formalize(sentence: str) -> Optional[Tuple[List[str], List[Fraction]]]:
110
+ """The structures bundle's parse of one canonical sentence, as words and exact numbers.
111
+
112
+ The parse is the partner's, and walking it is the only way this stratum learns what a sentence
113
+ says: the words it collects are the words the topology kept (the family, the direction, the kind
114
+ of a support, the form of a section) and the numbers are the values it read, so two sentences
115
+ with the same walk describe one structure whether or not they are spelled alike.
116
+ """
117
+ parse_a, _smt, _reason = _partner_modules()
118
+ if parse_a is None:
119
+ return None
120
+ try:
121
+ node = parse_a.parse(canonical.tidy(sentence))
122
+ except Exception: # noqa: BLE001 - a sentence the partner refuses is a sentence to report, not to guess
123
+ return None
124
+ words: List[str] = []
125
+ values: List[Fraction] = []
126
+ stack: List[Any] = [node]
127
+ while stack:
128
+ piece = stack.pop()
129
+ if isinstance(piece, (list, tuple)):
130
+ stack.extend(reversed(list(piece)))
131
+ elif isinstance(piece, bool):
132
+ words.append(str(piece))
133
+ elif isinstance(piece, int):
134
+ values.append(Fraction(piece))
135
+ elif isinstance(piece, float):
136
+ values.append(Fraction(str(piece)))
137
+ else:
138
+ text = str(piece).strip()
139
+ if not text:
140
+ continue
141
+ try:
142
+ values.append(Fraction(text.replace(",", ".")))
143
+ except ValueError:
144
+ words.append(text)
145
+ return words, values
146
+
147
+
148
+ def same_problem(left: str, right: str) -> Optional[bool]:
149
+ """Whether two sentences of the structures language describe one structure.
150
+
151
+ ``None`` means the question could not be asked, because the structures topology is not on disk or
152
+ refused one of the two sentences. That is reported, never read as agreement.
153
+ """
154
+ first, second = formalize(left), formalize(right)
155
+ if first is None or second is None:
156
+ return None
157
+ return first == second
158
+
159
+
160
+ def problem_numbers(text: str) -> List[str]:
161
+ """The numbers of a sentence as the structures topology sees them, ordered and spelled as ratios.
162
+
163
+ A sentence of the structures language and the echo of the topology are not the same text: the
164
+ topology writes every support in full, so ``pin`` comes back as ``pin 0 0``. Counting characters
165
+ would call that a change, so the count is taken after the partner's parse on both sides. When the
166
+ parse is not available the count falls back to the literals of the text, and the node says so.
167
+ """
168
+ parsed = formalize(text)
169
+ if parsed is None:
170
+ return sorted_numbers(text)
171
+ return [str(value) for value in sorted(parsed[1])]
172
+
173
+
174
+ def to_fractions(values: Sequence[str]) -> List[Fraction]:
175
+ """Ratios spelled by :func:`problem_numbers`, ready for an element by element claim.
176
+
177
+ A value that is not a ratio empties the list: a claim cannot be built over a number the stratum
178
+ did not read, and an empty claim is satisfiable in a way a wrong one is not.
179
+ """
180
+ out: List[Fraction] = []
181
+ for value in values:
182
+ try:
183
+ out.append(Fraction(value))
184
+ except ValueError:
185
+ return []
186
+ return out
187
+
188
+
189
+ def _codes(words: Sequence[str]) -> Dict[str, str]:
190
+ """An injective symbol for every word of the two parses, so the claim can compare them."""
191
+ table: Dict[str, str] = {}
192
+ for word in sorted(set(words)):
193
+ table[word] = str(len(table) + 1)
194
+ return table
195
+
196
+
197
+ def _differ_claim(left: Tuple[List[str], List[Fraction]],
198
+ right: Tuple[List[str], List[Fraction]]) -> Tuple[List[str], List[str], str]:
199
+ """SMT2 for ``the two readings differ``, and what the solver is expected to say.
200
+
201
+ The program pins one real per number of each parse and one integer per word of each parse, in
202
+ the order the topology's parse produced them, and then asserts that at least one aligned pair is
203
+ unequal. Unsatisfiable means every number and every word of the two parses is one value, which is
204
+ the same discipline the structures topology uses between its two solution roads: the claim that
205
+ travels in the envelope is the claim the referee of the orchestrator re-executes.
206
+ """
207
+ left_words, left_values = left
208
+ right_words, right_values = right
209
+ if len(left_words) != len(right_words) or len(left_values) != len(right_values):
210
+ return [], ["(assert false)"], "unsat"
211
+ table = _codes(list(left_words) + list(right_words))
212
+ decls: List[str] = []
213
+ asserts: List[str] = []
214
+ differences: List[str] = []
215
+ for index, value in enumerate(left_values):
216
+ step_decls, step_asserts = _pin("n%d" % index, value)
217
+ decls += step_decls
218
+ asserts += step_asserts
219
+ differences.append("(not (= n%d m%d))" % (index, index))
220
+ for index, value in enumerate(right_values):
221
+ step_decls, step_asserts = _pin("m%d" % index, value)
222
+ decls += step_decls
223
+ asserts += step_asserts
224
+ for index, word in enumerate(left_words):
225
+ decls.append("(declare-const w%d Int)" % index)
226
+ decls.append("(declare-const v%d Int)" % index)
227
+ asserts.append("(assert (= w%d %s))" % (index, table[word]))
228
+ asserts.append("(assert (= v%d %s))" % (index, table[right_words[index]]))
229
+ differences.append("(not (= w%d v%d))" % (index, index))
230
+ if not differences:
231
+ return decls, asserts, "unsat"
232
+ asserts.append("(assert (or %s))" % " ".join(differences))
233
+ return decls, asserts, "sat"
234
+
235
+
236
+ def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]:
237
+ """The slots one reading actually filled, in the order the structures language prints them."""
238
+ kind = str(reading.get("kind", ""))
239
+ slots = reading.get("slots") or {}
240
+ if kind not in canonical.TEMPLATES:
241
+ return ()
242
+ return tuple(name for name in canonical.slots_for(kind) if str(slots.get(name, "")).strip())
243
+
244
+
245
+ def equivalence(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]:
246
+ """Compare two readings: one verdict, the SMT claim behind it, and what differs."""
247
+ left = canonical.tidy(str(a.get("sentence", "")))
248
+ right = canonical.tidy(str(b.get("sentence", "")))
249
+ detail: List[str] = []
250
+ if sorted_numbers(left) != sorted_numbers(right):
251
+ detail.append("numbers %s vs %s" % (",".join(sorted_numbers(left)),
252
+ ",".join(sorted_numbers(right))))
253
+
254
+ if a.get("kind") != b.get("kind"):
255
+ detail.append("kinds %s vs %s" % (a.get("kind"), b.get("kind")))
256
+ return {"same": False, "why": "kind", "left": left, "right": right, "detail": detail,
257
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
258
+ if variant_of(a) != variant_of(b):
259
+ detail.append("slots %s vs %s" % (",".join(variant_of(a)), ",".join(variant_of(b))))
260
+ return {"same": False, "why": "variant", "left": left, "right": right, "detail": detail,
261
+ "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
262
+
263
+ if left and left == right:
264
+ return {"same": True, "why": "text", "left": left, "right": right, "detail": detail,
265
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None}
266
+
267
+ _parser, _smt, reason = _partner_modules()
268
+ first, second = formalize(left), formalize(right)
269
+ if first is None or second is None:
270
+ note = reason or "the structures topology gives no parse of one of the two readings"
271
+ detail.append(note)
272
+ return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail,
273
+ "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None,
274
+ "note": note}
275
+
276
+ decls, asserts, claimed = _differ_claim(first, second)
277
+ found = smt_referee(decls, asserts)
278
+ if found == "error" or found == "unknown":
279
+ detail.append("the solver gave no answer about the two readings")
280
+ return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail,
281
+ "declarations": decls, "assertions": asserts, "claimed": claimed, "model": None}
282
+ if found == "unsat":
283
+ return {"same": True, "why": "smt", "left": left, "right": right, "detail": detail,
284
+ "declarations": decls, "assertions": asserts, "claimed": claimed, "model": None}
285
+ detail.append("an assignment where the two readings disagree")
286
+ return {"same": False, "why": "smt", "left": left, "right": right, "detail": detail,
287
+ "declarations": decls, "assertions": asserts, "claimed": claimed, "model": None}
288
+
289
+
290
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
291
+ """Whether the reading kept every number the user wrote, and the SMT claim that says so."""
292
+ wrote = sorted_numbers(question)
293
+ kept = sorted_numbers(str(reading.get("sentence", "")))
294
+ decls, asserts = elementwise(numbers(question), numbers(str(reading.get("sentence", ""))), "keep")
295
+ ok = wrote == kept
296
+ return {
297
+ "ok": ok,
298
+ "wrote": wrote,
299
+ "kept": kept,
300
+ "missing": [value for value in wrote if value not in kept],
301
+ "added": [value for value in kept if value not in wrote],
302
+ "declarations": decls,
303
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
304
+ "claimed": "sat" if ok else "unsat",
305
+ }
306
+
307
+
308
+ def elementwise(left: List[Fraction], right: List[Fraction], prefix: str) -> Tuple[List[str], List[str]]:
309
+ """SMT2 declarations and assertions saying two lists of numbers are equal, item by item."""
310
+ if len(left) != len(right):
311
+ return [], ["(assert false)"]
312
+ decls: List[str] = []
313
+ asserts: List[str] = []
314
+ for index, (first, second) in enumerate(zip(left, right)):
315
+ left_decls, left_asserts = _pin("%s_%da" % (prefix, index), first)
316
+ right_decls, right_asserts = _pin("%s_%db" % (prefix, index), second)
317
+ decls += left_decls + right_decls
318
+ asserts += left_asserts + right_asserts
319
+ asserts.append("(assert (= %s_%sa %s_%sb))" % (prefix, index, prefix, index))
320
+ return decls, asserts
321
+
322
+
323
+ def agrees_with_struc(reading: Dict[str, Any], struc_verdict: Dict[str, Any]) -> bool:
324
+ """Did the structures topology solve the structure the readers agreed on?
325
+
326
+ The topology echoes the problem it understood, and that echo is an independent channel: a node
327
+ standing between the readers and the topology can rewrite its own record, but it cannot move the
328
+ echo without moving numbers that were counted upstream. The echo is not a copy of the sentence,
329
+ though: the topology writes ``supports`` entries in full, so a pin that was named ``pin`` comes
330
+ back as ``pin 0 0``. Comparing strings would call that a different problem, so the comparison
331
+ goes through the topology's own parse.
332
+ """
333
+ echo = canonical.tidy(str(struc_verdict.get("problem_struc", "")))
334
+ agreed = canonical.tidy(str(reading.get("sentence", "")))
335
+ if not agreed or not echo:
336
+ return False
337
+ judged = same_problem(echo, agreed)
338
+ if judged is not None:
339
+ return judged
340
+ return sorted_numbers(echo) == sorted_numbers(agreed)
341
+
342
+
343
+ def assurance_of(comparison: Dict[str, Any], readings: List[Dict[str, Any]],
344
+ coverage: Optional[Dict[str, Any]] = None) -> int:
345
+ """Reading assurance: how much of the answer the *reading* of the sentence warrants.
346
+
347
+ The scale is the one the structures topology uses, zero to three, and this function only ever
348
+ lowers it: two readings that agree and kept every number reach level two, a single reader reaches
349
+ level one, and no reading path reaches three, because reading a sentence written in a human
350
+ language is never the last word -- the structures topology reserves three for a road it did not
351
+ even finish, and the assurance the user sees is the minimum of the two.
352
+ """
353
+ present = [reading for reading in readings if reading.get("sentence")]
354
+ if not present:
355
+ return 0
356
+ if coverage is not None and not coverage.get("ok", False):
357
+ return 0
358
+ if len(present) < 2:
359
+ return 1
360
+ return 2 if comparison.get("same") else 0
lingologos_stratum/corpus.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The gold set of the stratum: sentences in six varieties and what each one must produce.
2
+
3
+ A corpus item is one line of JSON: a language, a question written by a speaker, and the expectation.
4
+ The expectation is deliberately narrow, because the stratum is not a solver -- it is the layer that
5
+ decides *which* sentence to hand to the solver and how much confidence to attach to it:
6
+
7
+ {"id": "it-cut-1", "lang": "it", "question": "taglia l'asta 1 al punto 1 telaio nodi [ 1 0 0 ; 2 4 0 ] ...",
8
+ "expect": {"state": "AGREED", "sentence": "cut member 1 at 1 frame nodes [ 1 0 0 ; 2 4 0 ] ...",
9
+ "min_assurance": 1}}
10
+
11
+ ``state`` is the only mandatory key. ``sentence`` is compared after tidying, ``answer_contains`` is
12
+ a substring test on the answer the structures topology returned, and ``max_assurance`` is the ceiling
13
+ a negative item insists on: an item that ends in DISPUTED, AMBIGUOUS or NOT COVERED must show no
14
+ answer at all.
15
+
16
+ The corpus is the only place a shared translation error can surface: the two readers agree by
17
+ construction whenever both descriptions of a language carry the same mistake, so the gold sentences
18
+ are written from the language and not from the lexicon.
19
+ """
20
+
21
+ import json
22
+ from pathlib import Path
23
+ from typing import Any, Dict, List, Optional
24
+
25
+ from . import canonical, pipeline
26
+
27
+ ROOT = Path(__file__).resolve().parents[1]
28
+ PATH = ROOT / "problems" / "corpus.jsonl"
29
+
30
+
31
+ def load(path: Optional[Path] = None) -> List[Dict[str, Any]]:
32
+ """The corpus, one dictionary per line, skipping blank lines and comments."""
33
+ where = Path(path) if path else PATH
34
+ items: List[Dict[str, Any]] = []
35
+ for line in where.read_text(encoding="utf-8").splitlines():
36
+ text = line.strip()
37
+ if not text or text.startswith("#"):
38
+ continue
39
+ items.append(json.loads(text))
40
+ return items
41
+
42
+
43
+ def grade(item: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]:
44
+ """Compare one corpus expectation against one run, and say exactly what did not match."""
45
+ expect = item.get("expect") or {}
46
+ final = result.get("final") or {}
47
+ problems: List[str] = []
48
+ state = str(final.get("state", ""))
49
+ if expect.get("state") and expect["state"] != state:
50
+ problems.append("state %s, expected %s" % (state, expect["state"]))
51
+ if "sentence" in expect:
52
+ wanted = canonical.tidy(str(expect["sentence"]))
53
+ got = canonical.tidy(str((result.get("dossier") or {}).get("sent", "")))
54
+ if got != wanted:
55
+ problems.append("sentence %r, expected %r" % (got, wanted))
56
+ if "answer_contains" in expect:
57
+ answer = str(final.get("answer", ""))
58
+ if str(expect["answer_contains"]) not in answer:
59
+ problems.append("answer %r does not contain %r" % (answer, expect["answer_contains"]))
60
+ if "min_assurance" in expect and int(final.get("assurance", 0) or 0) < int(expect["min_assurance"]):
61
+ problems.append("assurance %s below %s" % (final.get("assurance"), expect["min_assurance"]))
62
+ if "max_assurance" in expect and int(final.get("assurance", 0) or 0) > int(expect["max_assurance"]):
63
+ problems.append("assurance %s above %s" % (final.get("assurance"), expect["max_assurance"]))
64
+ if expect.get("no_answer") and final.get("answer"):
65
+ problems.append("an answer was shown for an item that must show none")
66
+ if expect.get("referee_clean") and any(record["claimed"] != record["referee"]
67
+ for record in result.get("records") or []):
68
+ problems.append("a claim did not survive the referee")
69
+ return {"id": item.get("id", "?"), "lang": item.get("lang", "?"), "state": state,
70
+ "assurance": final.get("assurance", 0), "ok": not problems, "problems": problems}
71
+
72
+
73
+ def outcome(item: Dict[str, Any], call_struc: bool = True,
74
+ fault_spec: Optional[List[str]] = None) -> Dict[str, Any]:
75
+ """Run one corpus item in memory and grade it."""
76
+ result = pipeline.ask(str(item.get("question", "")), str(item.get("lang", "")), fault_spec=fault_spec,
77
+ call_struc=call_struc)
78
+ verdict = grade(item, result)
79
+ verdict["records"] = result["records"]
80
+ verdict["dossier"] = result["dossier"]
81
+ verdict["reply"] = result["reply"]
82
+ return verdict
lingologos_stratum/coverage.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """What the reading kept, and what the structures topology says it solved.
2
+
3
+ Two bookkeeping checks stand between the readers and the answer, and both are stated as SMT2 so the
4
+ 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 structures language,
7
+ and no number appeared there that the user did not write. A reader that moved a number from one
8
+ slot to another or shifted a digit changes that multiset, and a sorted element by element equality
9
+ over declared reals says so;
10
+ * :func:`echo_matches` -- the structures topology echoes the problem it understood, and the echo is
11
+ compared with the structure the readers agreed on. The echo is an independent channel: a node
12
+ standing between the readers and the topology can rewrite its own record, but it cannot move the
13
+ echo without moving numbers that were counted upstream.
14
+
15
+ Neither check decides mechanics. They count tokens, and they hand the counting to a solver so that a
16
+ node claiming the numbers were kept is checked against that claim.
17
+ """
18
+
19
+ from fractions import Fraction
20
+ from typing import Any, Dict, List, Optional
21
+
22
+ from . import canonical, compare
23
+
24
+
25
+ def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]:
26
+ """Whether one reading kept every number the user wrote, with the SMT claim that says so."""
27
+ return compare.keeps(reading, question)
28
+
29
+
30
+ def echo_numbers(struc_verdict: Dict[str, Any]) -> List[str]:
31
+ """The numbers of the problem the structures topology says it solved, ordered by value."""
32
+ return compare.problem_numbers(canonical.tidy(str(struc_verdict.get("problem_struc", ""))))
33
+
34
+
35
+ def echo_matches(reading: Dict[str, Any], struc_verdict: Dict[str, Any]) -> bool:
36
+ """Did the structures topology solve the structure the readers agreed on?
37
+
38
+ A verdict that names no problem at all -- the backend was off, or the topology could not be
39
+ started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls to
40
+ zero because there is no mechanics assurance to take the minimum with, but nothing here may be
41
+ read as tampering. Only an echo that names a problem and names a different one is a mismatch.
42
+ """
43
+ if not str(struc_verdict.get("problem_struc", "")).strip():
44
+ return True
45
+ return compare.agrees_with_struc(reading, struc_verdict)
46
+
47
+
48
+ def coverage_claim(question: str, readings: List[Dict[str, Any]],
49
+ struc_verdict: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
50
+ """One SMT2 claim tying the user's numbers to the readings and, when known, to the echo.
51
+
52
+ Every reading that produced a sentence has to carry the user's numbers, and once the structures
53
+ topology has answered its echo has to carry the numbers of the agreed sentence too -- counted
54
+ after the partner's parse, because the echo is a normalized restatement and not a copy. The
55
+ assertion set is the conjunction of those element equalities: satisfiable exactly when all of
56
+ them hold, which is what the referee checks against the status the node claimed.
57
+ """
58
+ wrote = compare.sorted_numbers(question)
59
+ readings_present = [reading for reading in readings if reading.get("sentence")]
60
+ steps = [keeps(reading, question) for reading in readings_present]
61
+ ok = all(step["ok"] for step in steps)
62
+ decls: List[str] = []
63
+ asserts: List[str] = []
64
+ for step in steps:
65
+ decls = decls + list(step["declarations"])
66
+ asserts = asserts + list(step["assertions"])
67
+ if struc_verdict is not None and readings_present:
68
+ agreed = compare.problem_numbers(canonical.tidy(str(readings_present[0].get("sentence", ""))))
69
+ echo = echo_numbers(struc_verdict)
70
+ decls2, asserts2 = compare.elementwise(compare.to_fractions(agreed),
71
+ compare.to_fractions(echo), "echo")
72
+ decls = decls + decls2
73
+ asserts = asserts + asserts2
74
+ ok = ok and echo == agreed
75
+ if not wrote:
76
+ # Nothing was written, so there is nothing to keep: the claim is the empty conjunction,
77
+ # which is satisfiable, and the node says sat.
78
+ return {"ok": ok, "wrote": [], "kept": [], "declarations": [], "assertions": ["(assert (= 1 1))"],
79
+ "claimed": "sat"}
80
+ return {
81
+ "ok": ok,
82
+ "wrote": wrote,
83
+ "kept": [step["kept"] for step in steps],
84
+ "declarations": decls,
85
+ "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]),
86
+ "claimed": "sat" if ok else "unsat",
87
+ }
88
+
89
+
90
+ def _as_fractions(values: List[str]) -> List[Any]:
91
+ """Ratios spelled by :func:`compare.problem_numbers`, ready for an element by element claim."""
92
+ out: List[Any] = []
93
+ for value in values:
94
+ try:
95
+ out.append(Fraction(value))
96
+ except ValueError:
97
+ return []
98
+ return out
99
+
100
+
101
+ def summary(step: Dict[str, Any]) -> Dict[str, Any]:
102
+ """The part of a coverage step that belongs in the dossier and in front of the user."""
103
+ return {
104
+ "ok": step.get("ok", False),
105
+ "wrote": step.get("wrote", []),
106
+ "missing": step.get("missing", []),
107
+ "added": step.get("added", []),
108
+ }
lingologos_stratum/decide.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 structures topology 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 structures topology uses for its own decision.
8
+
9
+ The rule the whole module exists to enforce:
10
+
11
+ assurance(shown) = min(assurance(struc), assurance(reading))
12
+
13
+ and ``assurance(reading)`` is at most two: the two readers agreeing on one structure is the highest
14
+ level the conversational layer can claim on its own. Two is also the highest level the structures
15
+ topology reaches -- its two structural roads and the referee that agrees with them -- so the minimum
16
+ of the two can only ever lower what is shown. A sentence written in a human language carries one more
17
+ fallible step than a sentence the topology parses itself, and that step never lends an assurance the
18
+ mechanics did not give. A verdict is therefore never raised by the stratum; the only direction it can
19
+ move is down, and the adversary node writes the negation of that inequality as SMT2 so the referee of
20
+ the orchestrator refutes it.
21
+
22
+ The states, which are the eight the lexicon of every covered language names:
23
+
24
+ =========== ===================================================================
25
+ AGREED both readers produced the same structure, and the topology solved it
26
+ PASSTHROUGH the sentence was already written in the structures language: nothing was translated
27
+ SINGLE one reader understood the sentence and the other abstained: the topology was
28
+ consulted, and the assurance is capped by the missing witness
29
+ DISPUTED the two readers produced different structures, or a reading lost a number: the
30
+ topology is not consulted at all
31
+ AMBIGUOUS the sentence announces more than one kind of problem: the user has to choose
32
+ NOT COVERED neither reader found anything: the language does not say this in a covered way
33
+ TAMPERED the topology says it solved something other than the agreed sentence
34
+ NONE the session ended without a verdict: the arbiter node did not write one, or the
35
+ evidence it left was not readable
36
+ =========== ===================================================================
37
+ """
38
+
39
+ from typing import Any, Dict, List, Optional
40
+
41
+ AMBIGUOUS_REASONS = ("multiple", "two_frames")
42
+
43
+ STATES = ("AGREED", "PASSTHROUGH", "SINGLE", "DISPUTED", "AMBIGUOUS", "NOT COVERED", "TAMPERED", "NONE")
44
+
45
+ # The reading assurance of each state, on the scale the structures topology uses. The topology itself
46
+ # never goes above two, and no reading path can push it there from below.
47
+ CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0,
48
+ "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0}
49
+
50
+ # The two verdicts of the partner that come with an answer; everything else abstains.
51
+ ANSWERING = ("VERIFIED", "SINGLE_PROVER")
52
+
53
+
54
+ def reader_notes(readings: List[Dict[str, Any]]) -> List[str]:
55
+ """The reason keys the abstaining readers left behind, in reader order."""
56
+ notes: List[str] = []
57
+ for reading in readings:
58
+ for note in reading.get("notes") or []:
59
+ reason = note.get("reason") if isinstance(note, dict) else str(note)
60
+ if reason and reason not in notes:
61
+ notes.append(reason)
62
+ return notes
63
+
64
+
65
+ def state_of(readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
66
+ coverage: Optional[Dict[str, Any]], struc_verdict: Optional[Dict[str, Any]],
67
+ direct: Optional[Dict[str, Any]] = None, echo_ok: Optional[bool] = None) -> str:
68
+ """The state of a session, from the evidence the nodes collected."""
69
+ present = [reading for reading in readings if reading.get("sentence")]
70
+ notes = reader_notes(readings)
71
+ if direct is not None:
72
+ return "PASSTHROUGH"
73
+ if struc_verdict is not None and echo_ok is False:
74
+ return "TAMPERED"
75
+ if len(present) >= 2:
76
+ if comparison is None:
77
+ return "DISPUTED"
78
+ if coverage is not None and not coverage.get("ok", False):
79
+ return "DISPUTED"
80
+ return "AGREED" if comparison.get("same") else "DISPUTED"
81
+ if len(present) == 1:
82
+ # A lone witness has to hold the numbers the person wrote: a reading that lost one is not a
83
+ # weaker reading of the same structure, it is a different structure, and the ceiling of SINGLE
84
+ # is not a licence to answer it. This is the case the ablation of the topology uncovered: with
85
+ # one reader there is no second sentence to compare against, so the count of numbers is what
86
+ # stands between a shifted number and an answer the gold does not accept.
87
+ if coverage is not None and not coverage.get("ok", False):
88
+ return "DISPUTED"
89
+ return "SINGLE"
90
+ if any(reason in AMBIGUOUS_REASONS for reason in notes):
91
+ return "AMBIGUOUS"
92
+ return "NOT COVERED"
93
+
94
+
95
+ def reasons_for(state: str, readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]],
96
+ coverage: Optional[Dict[str, Any]], struc_verdict: Optional[Dict[str, Any]],
97
+ asked: bool = True) -> List[str]:
98
+ """The reason keys that explain a state, in the order a reader should read them."""
99
+ out: List[str] = []
100
+ for reason in reader_notes(readings):
101
+ if reason not in out:
102
+ out.append(reason)
103
+ if state == "DISPUTED":
104
+ if coverage is not None and not coverage.get("ok", False):
105
+ out.append("number_count")
106
+ if comparison is not None and not comparison.get("same"):
107
+ out.append("disagree")
108
+ if comparison is not None and comparison.get("why") == "unknown":
109
+ out.append("struc_unknown")
110
+ if comparison is not None and comparison.get("why") == "smt" and comparison.get("model"):
111
+ if "disagree" not in out:
112
+ out.append("disagree")
113
+ if state == "TAMPERED":
114
+ out.append("boundary")
115
+ if struc_verdict is not None and struc_verdict.get("referee_mismatch"):
116
+ out.append("referee")
117
+ if asked and struc_verdict is not None and struc_verdict.get("status") == "UNKNOWN":
118
+ out.append("struc_unknown")
119
+ if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"):
120
+ out.append("no_struc")
121
+ return out
122
+
123
+
124
+ def decide(dossier: Dict[str, Any]) -> Dict[str, Any]:
125
+ """One verdict for one session, with the assurance the user is allowed to see."""
126
+ readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}]
127
+ if dossier.get("reading_direct"):
128
+ readings = [dossier["reading_direct"]]
129
+ comparison = dossier.get("compare")
130
+ coverage = dossier.get("coverage")
131
+ struc_verdict = dossier.get("struc")
132
+ direct = dossier.get("reading_direct")
133
+ echo_ok = dossier.get("echo_ok")
134
+
135
+ state = state_of(readings, comparison, coverage, struc_verdict, direct, echo_ok)
136
+ ceiling = CEILING[state]
137
+ assurance = 0
138
+ answer_shown = ""
139
+ if state in ("AGREED", "SINGLE", "PASSTHROUGH") and struc_verdict is not None:
140
+ # The topology answers at level two when its two solution roads and its referee all agree, at
141
+ # level one when a single prover stands alone, and at level zero when it says UNKNOWN.
142
+ if struc_verdict.get("status") in ANSWERING:
143
+ assurance = min(ceiling, int(struc_verdict.get("assurance", 0) or 0))
144
+ else:
145
+ assurance = 0
146
+ answer_shown = struc_verdict.get("answer_text") or ""
147
+ if assurance == 0:
148
+ answer_shown = ""
149
+ reasons = reasons_for(state, readings, comparison, coverage, struc_verdict,
150
+ asked=bool(str(dossier.get("sent") or "")))
151
+ return {
152
+ "state": state,
153
+ "assurance": assurance,
154
+ "ceiling": ceiling,
155
+ "struc_assurance": int((struc_verdict or {}).get("assurance", 0) or 0),
156
+ "struc_status": (struc_verdict or {}).get("status"),
157
+ "answer": answer_shown,
158
+ "reasons": reasons,
159
+ "consulted_struc": struc_verdict is not None,
160
+ }
161
+
162
+
163
+ def raise_assurance(final: Dict[str, Any], claimed: int) -> Dict[str, Any]:
164
+ """The arbiter fault: an assurance above what the evidence supports (experiments only)."""
165
+ out = dict(final)
166
+ out["assurance"] = max(int(final.get("assurance", 0) or 0), int(claimed))
167
+ out["claimed_above_evidence"] = True
168
+ return out
lingologos_stratum/faults.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 reading is still a *grammatical*
8
+ sentence of the structures language: a reader that moves a number from one slot to another, or that
9
+ hears the wrong one of the three directions, must produce something the structures topology will
10
+ happily solve. Otherwise the fault would be caught by the topology refusing to parse, and the
11
+ experiment would measure nothing about the reading layer. The damage here is a wrong problem, not an
12
+ ill-formed one, and only the agreement of the two readers and the echo of the topology can see it.
13
+
14
+ Catalogue
15
+ ---------
16
+ reader_a / reader_b : shift_number, merge_slots, shift_word
17
+ equivalence : rubber_stamp (declares the two readings equal without comparing them)
18
+ coverage : rubber_stamp (declares every number kept without counting them)
19
+ boundary : tamper_struc (asks the structures topology a different question, reports the agreed one)
20
+ adversary : rubber_stamp (skips its own recomputation of the assurance bound)
21
+ arbiter : force_assurance (raises the assurance above what the evidence supports)
22
+ """
23
+
24
+ import os
25
+ import re
26
+ from typing import Any, Dict, Iterable, List, Optional, Set, Tuple
27
+
28
+ from . import canonical
29
+
30
+ _ACTIVE: Set[str] = set()
31
+ FIRED: List[str] = []
32
+
33
+ READER_FAULTS = ["shift_number", "merge_slots", "shift_word"]
34
+
35
+ CATALOG = {
36
+ "reader_a": READER_FAULTS,
37
+ "reader_b": READER_FAULTS,
38
+ "equivalence": ["rubber_stamp"],
39
+ "coverage": ["rubber_stamp"],
40
+ "boundary": ["tamper_struc"],
41
+ "adversary": ["rubber_stamp"],
42
+ "arbiter": ["force_assurance"],
43
+ }
44
+
45
+ _NUMBER = re.compile(r"\d+(?:\.\d+)?")
46
+
47
+
48
+ def configure(spec: Optional[Iterable[str]]) -> None:
49
+ _ACTIVE.clear()
50
+ del FIRED[:]
51
+ if spec is None:
52
+ return
53
+ if isinstance(spec, str):
54
+ spec = [s for s in spec.split(",") if s.strip()]
55
+ for item in spec:
56
+ _ACTIVE.add(item.strip())
57
+
58
+
59
+ def from_env() -> None:
60
+ configure(os.environ.get("LINGOLOGOS_STRATUM_FAULTS", ""))
61
+
62
+
63
+ def has(agent: str, kind: str) -> bool:
64
+ return "%s:%s" % (agent, kind) in _ACTIVE
65
+
66
+
67
+ def fire(agent: str, kind: str) -> None:
68
+ label = "%s:%s" % (agent, kind)
69
+ if label not in FIRED:
70
+ FIRED.append(label)
71
+
72
+
73
+ def fired(agent: str) -> List[str]:
74
+ return [item for item in FIRED if item.split(":", 1)[0] == agent]
75
+
76
+
77
+ # ---------------------------------------------------------------------------
78
+ # Reading mutations (reader faults)
79
+ # ---------------------------------------------------------------------------
80
+ def _slots_of(slots: Dict[str, str], order: List[str], kind: str, what: str) -> List[str]:
81
+ """The slots of one form that hold one kind of value, in the order the form puts them."""
82
+ return [name for name in order
83
+ if name in slots and canonical.SLOT_KIND.get(kind, {}).get(name) == what]
84
+
85
+
86
+ def _words_of(kind: str, slot: str) -> List[str]:
87
+ """The closed set a word slot reads, so that a fault can pick another member of the same set."""
88
+ what = canonical.SLOT_KIND.get(kind, {}).get(slot)
89
+ return {"quantity": list(canonical.QUANTITIES),
90
+ "direction": list(canonical.DIRECTIONS),
91
+ "mode": list(canonical.VERIFY_MODES),
92
+ "end": list(canonical.END_KINDS)}.get(what, [])
93
+
94
+
95
+ def mutate_reading(agent: str, kind: str, slots: Dict[str, str],
96
+ order: List[str]) -> Tuple[Dict[str, str], bool]:
97
+ """Return a damaged copy of one reading, and whether anything was actually damaged.
98
+
99
+ ``order`` is the slot order of the form the reader chose. A fault only touches slots of the type
100
+ it can damage -- a number for the two number faults, a word of a closed set for the third -- and
101
+ the copy is kept only if the structures language still accepts it as a sentence: damage that
102
+ makes the sentence impossible is not a reading error, and the topology would catch it for free.
103
+ """
104
+ slots = dict(slots)
105
+ for kind_fault in CATALOG.get(agent, []):
106
+ if not has(agent, kind_fault):
107
+ continue
108
+ candidate = dict(slots)
109
+ numbered = _slots_of(candidate, order, kind, "num")
110
+ if kind_fault == "shift_number":
111
+ if not numbered:
112
+ continue
113
+ owner = numbered[0]
114
+ match = _NUMBER.search(candidate[owner])
115
+ if match is None:
116
+ continue
117
+ candidate[owner] = (candidate[owner][:match.start()]
118
+ + str(_next_number(match.group(0))) + candidate[owner][match.end():])
119
+ elif kind_fault == "merge_slots":
120
+ if len(numbered) < 2:
121
+ continue
122
+ candidate[numbered[1]] = candidate[numbered[0]]
123
+ elif kind_fault == "shift_word":
124
+ words = [name for name in order
125
+ if name in candidate and _words_of(kind, name)]
126
+ moved = False
127
+ for name in words:
128
+ others = [other for other in _words_of(kind, name)
129
+ if other != candidate[name]]
130
+ if others:
131
+ candidate[name] = others[0]
132
+ moved = True
133
+ break
134
+ if not moved:
135
+ continue
136
+ else:
137
+ continue
138
+ if candidate == slots:
139
+ # Two slots that already carried the same value: copying one over the other damages
140
+ # nothing, and a fault that damaged nothing is not a fault the ablation may report.
141
+ continue
142
+ try:
143
+ canonical.print_sentence(kind, candidate)
144
+ except canonical.ReadingError:
145
+ continue
146
+ fire(agent, kind_fault)
147
+ return candidate, True
148
+ return slots, False
149
+
150
+
151
+ def _next_number(text: str) -> Any:
152
+ if "." in text:
153
+ return float(text) + 1.0
154
+ return int(text) + 1
155
+
156
+
157
+ # ---------------------------------------------------------------------------
158
+ # Sentence mutations (the boundary fault)
159
+ # ---------------------------------------------------------------------------
160
+ def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]:
161
+ """Change one number of a sentence of the structures language, leaving it grammatical.
162
+
163
+ This is the fault of the boundary node, and it is the one the reading layer cannot see from the
164
+ inside: the stratum asked a question, the topology answered a different one, and only comparing
165
+ the numbers the two of them name says which question was really answered.
166
+ """
167
+ if not has(agent, "tamper_struc"):
168
+ return sentence, False
169
+ match = _NUMBER.search(sentence)
170
+ if match is None:
171
+ return sentence, False
172
+ damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():]
173
+ fire(agent, "tamper_struc")
174
+ return damaged, True
lingologos_stratum/invoker.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The interface toward the structures topology: one subprocess call, no shared code.
2
+
3
+ The reading layer and the structures topology are separate topologies of the same orchestrator. This
4
+ module is the whole of their coupling: it starts ``tools/ask.py`` of the structures bundle as a
5
+ separate process with the canonical sentence as its argument, asks for the machine readable outcome,
6
+ and copies that outcome. Nothing here imports a module of the structures bundle, because a translation
7
+ layer that reaches inside the mechanics it consults is a translation layer that can silently change
8
+ the mechanics. The one exception in this bundle is ``compare.py``, which needs the partner's parser to
9
+ say that two readings are one structure; the verdict of a session always arrives through the process
10
+ started here.
11
+
12
+ Three settings matter, and all of them are environment variables so no value is hardcoded in a second
13
+ place:
14
+
15
+ ``LINGOLOGOS_STRATUM_STRUC_ROOT`` the folder of the structures bundle (default: ``struc``, sibling of this
16
+ bundle, which is ``datasets/struc`` inside the LingoLOGOS repository)
17
+ ``LINGOLOGOS_STRATUM_STRUC_BACKEND`` ``in-process`` (default), ``orchestrated`` or ``none``. The first runs
18
+ the thirteen nodes of the topology inside one process, which is what the
19
+ tests of this bundle use; the second lets the partner build the thirteen
20
+ node folders and run them as its own orchestrator does; ``none`` refuses
21
+ to call, so a coverage report can ask what the stratum *understood*
22
+ without starting a whole structures session
23
+ ``LINGOLOGOS_STRATUM_STRUC_TIMEOUT`` seconds to wait for the partner, 300 by default
24
+
25
+ The environment of the partner is left alone: ``LINGOLOGOS_STRUC_FAULTS`` and ``LINGOLOGOS_STRUC_MATH_ROOT`` are the
26
+ partner's own business, and a reading layer that rewrote them would be deciding what the mechanics
27
+ layer is allowed to prove.
28
+ """
29
+
30
+ import json
31
+ import os
32
+ import subprocess
33
+ import sys
34
+ from pathlib import Path
35
+ from typing import Any, Dict
36
+
37
+ ROOT = Path(__file__).resolve().parents[1]
38
+ DEFAULT_TIMEOUT = 300
39
+
40
+
41
+ def struc_root() -> Path:
42
+ override = os.environ.get("LINGOLOGOS_STRATUM_STRUC_ROOT", "").strip()
43
+ if override:
44
+ return Path(override)
45
+ return ROOT.parent / "struc"
46
+
47
+
48
+ def backend() -> str:
49
+ return (os.environ.get("LINGOLOGOS_STRATUM_STRUC_BACKEND", "in-process") or "in-process").strip().lower()
50
+
51
+
52
+ def timeout_seconds() -> int:
53
+ try:
54
+ return max(5, int(os.environ.get("LINGOLOGOS_STRATUM_STRUC_TIMEOUT", DEFAULT_TIMEOUT)))
55
+ except ValueError:
56
+ return DEFAULT_TIMEOUT
57
+
58
+
59
+ def unavailable(reason: str) -> Dict[str, Any]:
60
+ return {"ok": False, "error": reason, "status": "UNKNOWN", "assurance": 0, "answer": None,
61
+ "answer_text": "", "problem_struc": "", "reasons": [], "kind": None, "delegate": "",
62
+ "roads": {}, "states": {}, "readings_agree": False, "math_status": "NOT_ASKED",
63
+ "referee_mismatch": 0, "turns": None}
64
+
65
+
66
+ def solve(sentence: str) -> Dict[str, Any]:
67
+ """Ask the structures topology one sentence of the structures language, and return its verdict."""
68
+ mode = backend()
69
+ if mode == "none":
70
+ return unavailable("the structures backend is disabled by LINGOLOGOS_STRATUM_STRUC_BACKEND")
71
+ root = struc_root()
72
+ script = root / "tools" / "ask.py"
73
+ if not script.is_file():
74
+ return unavailable("no tools/ask.py under %s" % root)
75
+ command = [sys.executable, str(script), "--json"]
76
+ if mode != "orchestrated":
77
+ command.append("--in-process")
78
+ command.append(sentence)
79
+ try:
80
+ done = subprocess.run(command, cwd=str(root), capture_output=True, timeout=timeout_seconds())
81
+ except subprocess.TimeoutExpired:
82
+ return unavailable("the structures topology did not answer within %d seconds" % timeout_seconds())
83
+ except OSError as exc:
84
+ return unavailable("the structures topology could not be started: %s" % exc)
85
+ text = done.stdout.decode("utf-8", "replace")
86
+ if not text.strip():
87
+ # Exit 2 is the partner's own way of saying it abstained, and it prints the verdict before
88
+ # doing so; only a run that printed nothing at all is a run that did not answer.
89
+ return unavailable("the structures topology exited with %d and printed nothing: %s"
90
+ % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200]))
91
+ return outcome(text, done.returncode)
92
+
93
+
94
+ def outcome(text: str, returncode: int = 0) -> Dict[str, Any]:
95
+ """Extract the verdict of a structures session from the JSON the partner printed."""
96
+ try:
97
+ parsed = json.loads(text)
98
+ except ValueError:
99
+ return unavailable("the structures topology printed something that is not JSON (exit %d)" % returncode)
100
+ final = parsed.get("final") if isinstance(parsed, dict) else None
101
+ if not isinstance(final, dict):
102
+ return unavailable("the structures topology printed no verdict (exit %d)" % returncode)
103
+ referee = parsed.get("referee") if isinstance(parsed.get("referee"), list) else []
104
+ mismatched = [entry for entry in referee
105
+ if isinstance(entry, dict) and entry.get("claimed") != entry.get("referee")]
106
+ status = str(final.get("status") or "UNKNOWN")
107
+ return {
108
+ "ok": status != "UNKNOWN",
109
+ "status": status,
110
+ "assurance": int(final.get("assurance", 0) or 0),
111
+ "answer": final.get("answer"),
112
+ "answer_text": final.get("answer_text") or "",
113
+ "problem_struc": final.get("problem") or "",
114
+ "reasons": list(final.get("reasons") or []),
115
+ "kind": final.get("kind"),
116
+ "delegate": final.get("delegate") or "",
117
+ "roads": dict(final.get("roads") or {}),
118
+ "states": dict(final.get("states") or {}),
119
+ "readings_agree": bool(final.get("readings_agree")),
120
+ "math_status": final.get("math_status") or "NOT_ASKED",
121
+ "referee_mismatch": len(mismatched),
122
+ "turns": parsed.get("turns"),
123
+ "error": None if status != "UNKNOWN"
124
+ else "; ".join(str(reason) for reason in (final.get("reasons") or [])) or "unknown",
125
+ }
lingologos_stratum/lexicon.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The lexicon of the six language varieties, and the two routes that read a sentence.
2
+
3
+ Every variety lives in one JSON file ``lexicon/<lang>.json`` and carries, for every kind of question
4
+ the variety covers:
5
+
6
+ ``verbs``
7
+ the phrases that announce the kind;
8
+ ``patterns``
9
+ the surface patterns reader A matches (a slot string per accepted wording).
10
+
11
+ Reader B never looks at those patterns. It takes the verbs and the markers of this file, and the
12
+ sequence of joints it expects from ``lingologos_stratum.canonical``, which is the shape of the structures
13
+ language and nothing to do with how a variety words it. This mirrors the topology of structures, where
14
+ the two formalizers share one written specification (``nodes/*/grammar.gf``) and implement it twice.
15
+ The consequence is the same and is stated in the README: a translation error present in both routes of
16
+ one language is invisible to the topology, and only the gold sentences of the corpus can show it.
17
+
18
+ The data files are the object of study, not prose of this repository: they hold the words of six
19
+ languages, exactly as the structures bundle holds the bracket tokens it studies.
20
+ """
21
+
22
+ import json
23
+ import os
24
+ import re
25
+ from typing import Any, Dict, List, Optional, Tuple
26
+
27
+ from .segment import atomize, fold
28
+
29
+ BUNDLE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
30
+ LEXICON_DIR = os.path.join(BUNDLE, "lexicon")
31
+
32
+ # Marker names, the same in every variety: they are the words of the structures language a variety
33
+ # has to say something about, and the value each of them carries. The joints are what separate the
34
+ # abscissa of a cut from the limit of a check; the blocks and the closed sets of values are what the
35
+ # region of a frame or of a section is built from. The two readers and the canonical printer agree
36
+ # on these names and on nothing else.
37
+ MARKERS = ("at", "ends", "length", "limit", "modulus", "node", "member", "section",
38
+ "frame", "nodes", "members", "props", "supports", "loads", "hinges",
39
+ "pin", "pinned", "roller", "fixed", "free", "force", "couple", "udl", "point",
40
+ "moment", "shear", "axial", "vertical", "horizontal", "rotation",
41
+ "bending", "vonmises", "rect", "shapes")
42
+
43
+ _cache: Dict[str, Dict[str, Any]] = {}
44
+ _index_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
45
+ _stripped_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}
46
+ _verb_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, ...]]] = {}
47
+ _group_cache: Dict[str, Dict[str, Tuple[str, ...]]] = {}
48
+
49
+
50
+ def languages() -> List[str]:
51
+ """The language codes this bundle can read, in a stable order."""
52
+ return sorted(name[:-5] for name in os.listdir(LEXICON_DIR) if name.endswith(".json"))
53
+
54
+
55
+ def load(lang: str) -> Dict[str, Any]:
56
+ if lang not in _cache:
57
+ path = os.path.join(LEXICON_DIR, lang + ".json")
58
+ with open(path, "r", encoding="utf-8") as handle:
59
+ data = json.load(handle)
60
+ data["_code"] = lang
61
+ _cache[lang] = data
62
+ return _cache[lang]
63
+
64
+
65
+ def script(lang: str) -> str:
66
+ return load(lang).get("script", "latin")
67
+
68
+
69
+ def codes() -> List[str]:
70
+ return languages()
71
+
72
+
73
+ def kinds(lang: str) -> List[str]:
74
+ """The sentence kinds this variety covers."""
75
+ return sorted(load(lang).get("kinds", {}))
76
+
77
+
78
+ def supported_kinds() -> List[str]:
79
+ """The kinds at least one variety covers."""
80
+ seen = set()
81
+ for lang in languages():
82
+ seen.update(kinds(lang))
83
+ return sorted(seen)
84
+
85
+
86
+ def patterns(lang: str) -> Dict[str, List[str]]:
87
+ """Reader A's surface patterns per kind: ``{kind: [pattern, ...]}``."""
88
+ out = {}
89
+ for kind, spec in load(lang).get("kinds", {}).items():
90
+ out[kind] = list(spec.get("patterns", []))
91
+ return out
92
+
93
+
94
+ def verbs(lang: str) -> Dict[str, Tuple[Tuple[str, ...], ...]]:
95
+ """Every kind verb phrase of the variety, mapped to the kinds it announces.
96
+
97
+ One phrase can announce more than one kind, and that is a fact of the language, not a defect of
98
+ the data: a variety may use one verb for the check of a section and for the check of a whole
99
+ frame. Keeping the whole list here is what lets a reader try both forms of one sentence instead of
100
+ silently taking the last kind in the file.
101
+ """
102
+ out: Dict[str, Tuple[str, ...]] = {}
103
+ for kind, spec in load(lang).get("kinds", {}).items():
104
+ for verb in spec.get("verbs", []):
105
+ phrase = fold(verb)
106
+ out[phrase] = out.get(phrase, ()) + (kind,)
107
+ return out
108
+
109
+
110
+ def verb_atoms_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, ...]]:
111
+ """The verb phrases of a variety, keyed by their atoms, mapped to the kinds they announce."""
112
+ if lang in _verb_cache:
113
+ return _verb_cache[lang]
114
+ index = {phrase_atoms(verb): kinds for verb, kinds in verbs(lang).items()}
115
+ _verb_cache[lang] = index
116
+ return index
117
+
118
+
119
+ def verb_groups(lang: str) -> Dict[str, Tuple[str, ...]]:
120
+ """The kinds one verb phrase can open, merged into groups.
121
+
122
+ Two kinds belong to the same group when one phrase of the variety announces both of them. A
123
+ sentence whose verb lies in one group is one problem, read in one of two ways; a sentence whose
124
+ verbs lie in two groups is two problems, and no reader may pick one.
125
+ """
126
+ if lang in _group_cache:
127
+ return _group_cache[lang]
128
+ parent = {kind: kind for kind in load(lang).get("kinds", {})}
129
+
130
+ def root(kind: str) -> str:
131
+ while parent[kind] != kind:
132
+ parent[kind] = parent[parent[kind]]
133
+ kind = parent[kind]
134
+ return kind
135
+
136
+ for kinds in verbs(lang).values():
137
+ for other in kinds[1:]:
138
+ first, second = root(kinds[0]), root(other)
139
+ if first != second:
140
+ parent[second] = first
141
+ merged: Dict[str, set] = {}
142
+ for kind in parent:
143
+ merged.setdefault(root(kind), set()).add(kind)
144
+ groups = {kind: tuple(sorted(group)) for group in merged.values() for kind in group}
145
+ _group_cache[lang] = groups
146
+ return groups
147
+
148
+
149
+ def announce(lang: str, items: List[Dict[str, Any]]) -> Tuple[List[str], Optional[Dict[str, str]]]:
150
+ """The kinds the verbs of a sentence open, or the reason the sentence announces none.
151
+
152
+ Both readers ask this one question, in one place: which kind a sentence belongs to is a decision
153
+ about the structure, and a second implementation of the same rule in the second reader would be one
154
+ more place where the two of them can be wrong in the same way.
155
+ """
156
+ found: List[str] = []
157
+ for item in items:
158
+ if item.get("role") != "verb":
159
+ continue
160
+ for kind in item.get("kinds") or (item.get("value"),):
161
+ if kind and kind not in found:
162
+ found.append(kind)
163
+ if not found:
164
+ return [], {"reason": "no_verb"}
165
+ neutral = neutral_kinds(lang)
166
+ picked = [kind for kind in found if kind not in neutral] or found
167
+ groups = {frozenset(verb_groups(lang)[kind]) for kind in picked}
168
+ if len(groups) > 1:
169
+ return [], {"reason": "two_verbs", "kinds": ", ".join(sorted(picked))}
170
+ merged: set = set()
171
+ for group in groups:
172
+ merged |= group
173
+ return sorted(merged), None
174
+
175
+
176
+
177
+ def neutral_kinds(lang: str) -> set:
178
+ """Kinds whose verb is a request for an answer rather than a claim about the structure.
179
+
180
+ A variety may use one request verb for several kinds: in such a case the verb is neutral, the
181
+ reader that carries it steps aside, and the kind is decided by the words that name what is asked
182
+ about. A variety whose every verb names its kind covers none of these.
183
+ """
184
+ return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")}
185
+
186
+
187
+ def markers(lang: str) -> Dict[str, List[str]]:
188
+ return load(lang).get("markers", {})
189
+
190
+
191
+ def noise(lang: str) -> List[str]:
192
+ return load(lang).get("noise", [])
193
+
194
+
195
+ def noise_chars(lang: str) -> str:
196
+ """Single characters a word run may hold without being a coverage failure (Chinese particles)."""
197
+ return load(lang).get("noise_chars", "")
198
+
199
+
200
+ def prefixes(lang: str) -> List[str]:
201
+ """Attached prefixes an Arabic word run may carry (definite article, conjunctions)."""
202
+ return load(lang).get("prefixes", [])
203
+
204
+
205
+ def strip_prefix(word: str, prefixes: List[str]) -> str:
206
+ """Remove the longest attached prefix, so that a written form reaches the prefix-free entry.
207
+
208
+ Arabic attaches the definite article and the single letter conjunctions and prepositions in
209
+ front of the word, and the lexicon files record the word without them. The longest prefix wins,
210
+ because the article and a conjunction joined to it are one prefix and not two.
211
+ """
212
+ for prefix in sorted(prefixes, key=len, reverse=True):
213
+ if word.startswith(prefix) and len(word) > len(prefix):
214
+ return word[len(prefix):]
215
+ return word
216
+
217
+
218
+ def prefix_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
219
+ """The same index, keyed with every atom of every phrase written without its prefixes."""
220
+ if lang in _stripped_cache:
221
+ return _stripped_cache[lang]
222
+ attached = prefixes(lang)
223
+ stripped = {}
224
+ for window, hit in phrase_index(lang).items():
225
+ if attached:
226
+ key = tuple(strip_prefix(atom, attached) for atom in window)
227
+ stripped.setdefault(key, hit)
228
+ _stripped_cache[lang] = stripped
229
+ return stripped
230
+
231
+
232
+ # ---------------------------------------------------------------------------
233
+ # Phrase index (reader A) and phrase positions (reader B)
234
+ # ---------------------------------------------------------------------------
235
+ Phrase = Tuple[Tuple[str, ...], str, str]
236
+
237
+
238
+ def phrase_atoms(phrase: str) -> Tuple[str, ...]:
239
+ """The atoms a lexicon phrase is written with, through the same atomiser as a sentence.
240
+
241
+ A Chinese term in a data file is one token, and one token is not one atom: the atomiser cuts
242
+ it into characters, exactly as it cuts the sentence the user typed. Doing both sides the same
243
+ way is the only reason a data file and a sentence can be compared at all.
244
+ """
245
+ return tuple(fold(atom) for kind, atom in atomize(phrase) if kind == "w")
246
+
247
+
248
+ _SLOT_MARK = re.compile(r"\{[A-Z][A-Z0-9]*\}")
249
+
250
+
251
+ def pattern_literals(lang: str) -> List[Tuple[str, ...]]:
252
+ """The function words the written patterns of a variety spell out themselves, one atom each.
253
+
254
+ A pattern is part of the data of a variety, so every word it writes is a word of that variety by
255
+ definition. ``calcola le reazioni vincolari di {F}`` names ``reazioni`` and ``vincolari``, and a
256
+ reader that called those words unknown would refuse the very shape the data file documents. These
257
+ words carry no value, which is what makes them noise: they may stand in a sentence, they never
258
+ fill a slot.
259
+ """
260
+ words: List[Tuple[str, ...]] = []
261
+ for entries in patterns(lang).values():
262
+ for pattern in entries:
263
+ for chunk in _SLOT_MARK.split(pattern):
264
+ for atom in phrase_atoms(chunk):
265
+ words.append((atom,))
266
+ return words
267
+
268
+
269
+ def phrase_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]:
270
+ """Map a folded word sequence to ``(role, value)``: verb, marker or noise.
271
+
272
+ Verbs, markers and noise words of a variety share one index, because reader A has to decide
273
+ between them with a single longest match. The index is built once per variety.
274
+ """
275
+ if lang in _index_cache:
276
+ return _index_cache[lang]
277
+ index: Dict[Tuple[str, ...], Tuple[str, str]] = {}
278
+ for verb, kinds in verbs(lang).items():
279
+ index[phrase_atoms(verb)] = ("verb", kinds[0])
280
+ for name, words in markers(lang).items():
281
+ for word in words:
282
+ index[phrase_atoms(word)] = ("marker", name)
283
+ for word in noise(lang):
284
+ index.setdefault(phrase_atoms(word), ("noise", ""))
285
+ for atom in pattern_literals(lang):
286
+ index.setdefault(atom, ("noise", ""))
287
+ # A data file with an empty phrase would match at every position and read nothing: drop it.
288
+ index.pop((), None)
289
+ _index_cache[lang] = index
290
+ return index
291
+
292
+
293
+ def max_phrase_length(lang: str) -> int:
294
+ return max((len(key) for key in phrase_index(lang)), default=1)
295
+
296
+
297
+ # ---------------------------------------------------------------------------
298
+ # Presentation data
299
+ # ---------------------------------------------------------------------------
300
+ def labels(lang: str) -> Dict[str, str]:
301
+ return load(lang).get("labels", {})
302
+
303
+
304
+ def reading_labels(lang: str) -> Dict[str, str]:
305
+ return load(lang).get("reading", {})
306
+
307
+
308
+ def reason_texts(lang: str) -> Dict[str, str]:
309
+ return load(lang).get("reasons", {})
310
+
311
+
312
+ def examples(lang: str) -> List[str]:
313
+ return load(lang).get("examples", [])
314
+
315
+
316
+ def label(lang: str, key: str, fallback: str = "") -> str:
317
+ return labels(lang).get(key, fallback)
318
+
319
+
320
+ def translate_reason(lang: str, reason: str, **fields: Any) -> str:
321
+ """One reason in the language of the user, with the fields a template asks for."""
322
+ table = reason_texts(lang)
323
+ text = table.get(reason) or table.get("other") or reason
324
+ try:
325
+ return text.format(**fields)
326
+ except (KeyError, IndexError):
327
+ return text
328
+
329
+
330
+ def language_name(lang: str) -> str:
331
+ return load(lang).get("name", lang)
332
+
333
+
334
+ def find_by_hint(lang: str) -> Optional[str]:
335
+ """Resolve a ``--lang`` hint (a code or a name) to a language code, or ``None``."""
336
+ if lang in _available():
337
+ return lang
338
+ wanted = fold(lang)
339
+ for code in languages():
340
+ if fold(code) == wanted or fold(language_name(code)) == wanted:
341
+ return code
342
+ return None
343
+
344
+
345
+ def _available() -> List[str]:
346
+ return languages()
lingologos_stratum/pipeline.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One run of the topology in a single process, with every envelope re-checked.
2
+
3
+ The orchestrator runs the eight nodes as separate processes, one turn each. This module chains the
4
+ very same ``step_*`` functions in memory and runs the referee of the structures topology on every
5
+ envelope on the way, which is what the orchestrator does with each turn. It exists for the tests, for
6
+ the 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. The
12
+ tools print that verdict, not the one the arbiter wrote.
13
+ """
14
+
15
+ import os
16
+ from typing import Any, Dict, List, Optional, Sequence
17
+
18
+ from . import agents, compare, coverage, decide, faults, protocol, render
19
+
20
+ ORDER = agents.ORDER
21
+ ONTOLOGY = "(set-option :timeout 8000)\n"
22
+ BACKEND_VARIABLE = "LINGOLOGOS_STRATUM_STRUC_BACKEND"
23
+
24
+
25
+ def referee(decls: List[str], asserts: List[str]) -> str:
26
+ """Run the referee of the structures topology over one envelope claim, in this process."""
27
+ status = compare.smt_referee(decls, asserts)
28
+ return status if status in ("sat", "unsat", "unknown", "error") else "unknown"
29
+
30
+
31
+ def seed(question: str, lang: str) -> Dict[str, Any]:
32
+ """The envelope the arbiter node starts a session with: the question and its language."""
33
+ dossier = {"question": question, "lang": lang}
34
+ return {"payload": {"naturalLanguage": protocol.encode("question (%s): %s" % (lang, question), dossier)},
35
+ "sender": "arbiter", "turn": 0, "volatileState": {"internalTimeTick": 0}}
36
+
37
+
38
+ def ask(question: str, lang: str, active: Sequence[str] = ORDER, fault_spec: Optional[Sequence[str]] = None,
39
+ call_struc: bool = True) -> Dict[str, Any]:
40
+ """One session, in memory: returns the dossier, the referee log, the verdict and the reply."""
41
+ faults.configure(fault_spec or ())
42
+ previous = os.environ.get(BACKEND_VARIABLE)
43
+ if not call_struc:
44
+ os.environ[BACKEND_VARIABLE] = "none"
45
+ current = seed(question, lang)
46
+ records: List[Dict[str, Any]] = []
47
+ turn = 0
48
+ try:
49
+ for name in ORDER:
50
+ if name not in active:
51
+ continue
52
+ turn += 1
53
+ incoming = {"sender": current["sender"], "turn": turn,
54
+ "volatileState": {"internalTimeTick": turn}, "payload": current["payload"]}
55
+ out = agents.run_step(name, incoming, name)
56
+ constraints = out["payload"]["smtConstraints"]
57
+ actual = referee(constraints["declarations"], constraints["assertions"])
58
+ records.append({"turn": turn, "sender": name, "claimed": constraints["z3Status"], "referee": actual})
59
+ current = out
60
+ finally:
61
+ if not call_struc:
62
+ if previous is None:
63
+ os.environ.pop(BACKEND_VARIABLE, None)
64
+ else:
65
+ os.environ[BACKEND_VARIABLE] = previous
66
+ dossier = protocol.decode(current["payload"]["naturalLanguage"])
67
+ final = checked_verdict(dossier, records, arbiter_expected="arbiter" in active)
68
+ reply = render.reply(dossier, final, records)
69
+ return {"dossier": dossier, "records": records, "final": final, "reply": reply,
70
+ "faults": sorted(faults.FIRED)}
71
+
72
+
73
+ def _unknown(reason: str) -> Dict[str, Any]:
74
+ return {"state": "NONE", "assurance": 0, "ceiling": 0, "struc_assurance": 0, "struc_status": None,
75
+ "answer": "", "reasons": [reason], "consulted_struc": False, "detected": []}
76
+
77
+
78
+ def referee_adjusted(final: Dict[str, Any], records: List[Dict[str, Any]]) -> Dict[str, Any]:
79
+ """Zero the verdict when the referee disagrees with what a node claimed about its own envelope."""
80
+ bad = [record["sender"] for record in records if record["claimed"] != record["referee"]]
81
+ if bad:
82
+ final = dict(final)
83
+ final["assurance"] = 0
84
+ final["reasons"] = list(final.get("reasons", [])) + ["referee"]
85
+ final["detected"] = list(final.get("detected", [])) + bad
86
+ return final
87
+
88
+
89
+ def independent_echo(dossier: Dict[str, Any]) -> bool:
90
+ """Recompute the echo check from the transcript, without asking the node that wrote it."""
91
+ struc_verdict = dossier.get("struc") or {}
92
+ if not struc_verdict.get("problem_struc"):
93
+ return True
94
+ for key in ("reading_a", "reading_b", "reading_direct"):
95
+ reading = dossier.get(key) or {}
96
+ if reading.get("sentence") and not coverage.echo_matches(reading, struc_verdict):
97
+ return False
98
+ return True
99
+
100
+
101
+ def checked_verdict(dossier: Dict[str, Any], records: List[Dict[str, Any]],
102
+ arbiter_expected: bool = True) -> Dict[str, Any]:
103
+ """The verdict a user is shown: recomputed from the evidence, then the more cautious of the two."""
104
+ try:
105
+ evidence = dict(dossier)
106
+ evidence["echo_ok"] = independent_echo(dossier)
107
+ recomputed = referee_adjusted(decide.decide(evidence), records)
108
+ except (AttributeError, KeyError, TypeError, ValueError, IndexError, ArithmeticError) as error:
109
+ return _unknown("the decision rule could not read the evidence: %s" % error)
110
+ arbiter = dossier.get("final")
111
+ if not isinstance(arbiter, dict) or "state" not in arbiter or "assurance" not in arbiter:
112
+ return _unknown("the arbiter produced no verdict") if arbiter_expected else recomputed
113
+ if arbiter["state"] == recomputed["state"] and arbiter.get("answer") == recomputed.get("answer"):
114
+ return recomputed
115
+ final = dict(recomputed if recomputed["assurance"] <= int(arbiter.get("assurance", 0) or 0) else arbiter)
116
+ final["reasons"] = list(final.get("reasons", [])) + ["arbiter and recomputed decision disagree"]
117
+ final["detected"] = list(final.get("detected", [])) + ["arbiter"]
118
+ return final
lingologos_stratum/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 structures topology uses,
6
+ which is what lets one orchestrator run either topology without knowing the difference.
7
+
8
+ The dossier of a 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 structure, and on what grounds
15
+ ``coverage`` whether the agreed reading kept every number the user wrote
16
+ ``sent`` the sentence of the structures language handed to the structures topology
17
+ ``struc`` the verdict the structures topology returned, copied without any change
18
+ ``final`` the state, the assurance and the answer shown to the user
19
+ ``crash`` a role that failed, so the arbiter can report UNKNOWN instead of pretending
20
+ """
21
+
22
+ import json
23
+ from typing import Any, Dict, List, Optional
24
+
25
+ MARK = "@@DOSSIER@@"
26
+
27
+
28
+ def encode(summary: str, dossier: Dict[str, Any]) -> str:
29
+ return summary.replace("\n", " ") + "\n" + MARK + json.dumps(dossier, sort_keys=True, separators=(",", ":"))
30
+
31
+
32
+ def decode(text: str) -> Dict[str, Any]:
33
+ """Return the dossier, or a fresh one holding the raw text as the user question."""
34
+ if MARK in text:
35
+ return json.loads(text.split(MARK, 1)[1])
36
+ return {"v": 1, "question": text.strip(), "lang": "en"}
37
+
38
+
39
+ def summary_of(text: str) -> str:
40
+ return text.split("\n", 1)[0]
41
+
42
+
43
+ def envelope(
44
+ node_id: str,
45
+ recipient: Optional[str],
46
+ turn: int,
47
+ tick: int,
48
+ summary: str,
49
+ ast: str,
50
+ dossier: Dict[str, Any],
51
+ decls: List[str],
52
+ assertions: List[str],
53
+ claimed: str,
54
+ ) -> Dict[str, Any]:
55
+ out: Dict[str, Any] = {
56
+ "sender": node_id,
57
+ "turn": turn,
58
+ "volatileState": {"internalTimeTick": tick},
59
+ "payload": {
60
+ "naturalLanguage": encode(summary, dossier),
61
+ "abstractSyntaxTree": ast,
62
+ "smtConstraints": {"declarations": decls, "assertions": assertions, "z3Status": claimed},
63
+ },
64
+ }
65
+ if recipient:
66
+ out["recipient"] = recipient
67
+ return out
68
+
69
+
70
+ def start(incoming: Dict[str, Any]):
71
+ """Decode an incoming envelope into (dossier, turn, tick, sender)."""
72
+ dossier = decode(incoming["payload"]["naturalLanguage"])
73
+ tick = int(incoming.get("volatileState", {}).get("internalTimeTick", 0))
74
+ return dossier, int(incoming["turn"]), tick, incoming["sender"]
75
+
76
+
77
+ def out(node_id: str, rcpt: str, turn: int, tick: int, dossier: Dict[str, Any], summary: str, ast: str,
78
+ decls: List[str], asserts: List[str], claimed: str) -> Dict[str, Any]:
79
+ return envelope(node_id, rcpt, turn, tick, summary, ast, dossier, decls, asserts, claimed)
lingologos_stratum/read_a.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reader A: the strict reader, matching the surface patterns of the lexicon.
2
+
3
+ Reader A holds the sentence against the **patterns** of a language variety: each accepted shape is
4
+ written out in ``lexicon/<lang>.json`` with the values of the structures language in slots. A pattern
5
+ matches only if every function word it names is present, in order, and if every verb, every marker
6
+ and every number the user wrote is accounted for. That strictness is the point: when A produces a
7
+ sentence it read one of the documented shapes and nothing else.
8
+
9
+ Reader B (:mod:`lingologos_stratum.read_b`) does something different with the same data -- it looks for the
10
+ joints a kind of the structures language requires, wherever they stand, and fills the slots from the
11
+ regions those joints introduce -- and the topology only trusts a reading the two agree on. What the
12
+ two readers share is the lexicon, the atomiser in :mod:`lingologos_stratum.segment` and the shape of the
13
+ bracket notation in :mod:`lingologos_stratum.canonical`, just as the two formalizers of the structures
14
+ topology share one written grammar and one token spec.
15
+
16
+ A slot of this family is not one run of notation and this reader knows it: a number, a word of a
17
+ closed set, a frame and a section are four different things, and a slot that wants a frame takes one
18
+ and refuses a number. That typing is what keeps a sentence about a section from being read as a
19
+ sentence about a structure, which is the mistake this whole bundle exists to catch.
20
+ """
21
+
22
+ import re
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, word_pieces
28
+
29
+ _SLOT = re.compile(r"\{([A-Z][A-Z0-9]*)\}")
30
+
31
+
32
+ def compile_pattern(pattern: str) -> Tuple[List[List[str]], List[str]]:
33
+ """Split a surface pattern into its literal word chunks and its slot names, in order."""
34
+ parts = _SLOT.split(pattern)
35
+ chunks: List[List[str]] = []
36
+ slots: List[str] = []
37
+ index = 0
38
+ while index < len(parts):
39
+ chunks.append([fold(piece) for word in parts[index].split() for piece in word_pieces(word)])
40
+ index += 1
41
+ if index < len(parts):
42
+ slots.append(parts[index])
43
+ index += 1
44
+ return chunks, slots
45
+
46
+
47
+ def scan(lang: str, text: str) -> List[Dict[str, Any]]:
48
+ """Tag every atom: a run of the notation, or a lexicon phrase with its role and value.
49
+
50
+ One longest match per position decides between verb, marker and noise, which is why a data file
51
+ must not give one phrase two roles. A variety that writes "carichi" for the block of loads and
52
+ "carico" for a single load gets both, and the longest match is what keeps the two apart.
53
+ """
54
+ phrases = lexicon.phrase_index(lang)
55
+ attached = lexicon.prefixes(lang)
56
+ stripped_index = lexicon.prefix_index(lang) if attached else {}
57
+ longest = lexicon.max_phrase_length(lang)
58
+ atoms = atomize(text)
59
+ items: List[Dict[str, Any]] = []
60
+ index = 0
61
+ while index < len(atoms):
62
+ kind, atom = atoms[index]
63
+ if kind == "m":
64
+ items.append({"role": "num", "value": atom, "words": [], "surface": atom})
65
+ index += 1
66
+ continue
67
+ word = fold(atom)
68
+ hit = None
69
+ for span in range(min(longest, len(atoms) - index), 0, -1):
70
+ if any(atoms[index + step][0] != "w" for step in range(span)):
71
+ continue
72
+ window = tuple(fold(atoms[index + step][1]) for step in range(span))
73
+ if window in phrases:
74
+ hit = (phrases[window], window)
75
+ break
76
+ if attached:
77
+ key = tuple(lexicon.strip_prefix(w, attached) for w in window)
78
+ if key in stripped_index:
79
+ hit = (stripped_index[key], key)
80
+ break
81
+ if hit:
82
+ (role, value), key = hit
83
+ # The item carries the atoms as the sentence wrote them; the lexicon key it matched is
84
+ # kept only to look the verb up, because Arabic writes a lexicon word with prefixes
85
+ # attached and the data file records it without them.
86
+ item = {"role": role, "value": value, "words": list(window), "surface": atom}
87
+ if role == "verb":
88
+ table = lexicon.verb_atoms_index(lang)
89
+ item["kinds"] = table.get(window) or table.get(key) or (value,)
90
+ items.append(item)
91
+ index += len(window)
92
+ continue
93
+ if atom and atom in lexicon.noise_chars(lang):
94
+ # A single character particle of a script written without spaces (Chinese particles).
95
+ # It carries its own atom as its words so that a pattern naming the particle can match
96
+ # it; it carries no value, so it never reaches the value of a slot.
97
+ items.append({"role": "noise", "value": "", "words": [word], "surface": atom})
98
+ index += 1
99
+ continue
100
+ items.append({"role": "unknown", "value": word, "words": [word], "surface": atom})
101
+ index += 1
102
+ return items
103
+
104
+
105
+ def _claim(words: List[str], chunk_slice: List[str], attached: List[str]) -> bool:
106
+ """Whether the atoms an item carries are the atoms a chunk of the pattern asks for.
107
+
108
+ Arabic writes a word with its article and its conjunctions attached to it, and the pattern in the
109
+ data file names the bare word. Stripping the attachment from both sides is what lets a pattern
110
+ name a word the sentence wrote in another form, and nothing else is forgiven: an item that carries
111
+ no atoms is the notation, and a bracket is never a word of a pattern.
112
+ """
113
+ if not words:
114
+ return False
115
+ if list(words) == list(chunk_slice):
116
+ return True
117
+ if not attached:
118
+ return False
119
+ return ([lexicon.strip_prefix(word, attached) for word in words]
120
+ == [lexicon.strip_prefix(word, attached) for word in chunk_slice])
121
+
122
+
123
+ def _find(chunk: List[str], items: List[Dict[str, Any]], start: int,
124
+ attached: List[str]) -> Optional[Tuple[int, int]]:
125
+ """Where in the item stream the literal words of a pattern chunk appear, or ``None``.
126
+
127
+ A chunk is contiguous: it may not span a piece of the notation, and no function word the pattern
128
+ did not name may sit inside it. That is what stops a pattern from swallowing a sentence it does
129
+ not describe.
130
+ """
131
+ for first in range(start, len(items) + 1):
132
+ cursor = first
133
+ taken = 0
134
+ ok = True
135
+ while taken < len(chunk):
136
+ if cursor >= len(items):
137
+ ok = False
138
+ break
139
+ words = items[cursor]["words"]
140
+ if not _claim(words, chunk[taken:taken + len(words)], attached):
141
+ ok = False
142
+ break
143
+ taken += len(words)
144
+ cursor += 1
145
+ if ok:
146
+ return first, cursor
147
+ return None
148
+
149
+
150
+ def _empty(items: List[Dict[str, Any]], start: int, stop: int) -> bool:
151
+ """Whether the stretch between a slot and the next chunk of the pattern holds only function words.
152
+
153
+ A slot of this family takes exactly what its type asks for, so a number left standing between the
154
+ slot and the words that follow it is a number the pattern has no place for. Refusing it is the
155
+ honest answer; guessing which slot wanted it would be the reader inventing the problem.
156
+ """
157
+ return all(item["role"] == "noise" for item in items[start:stop])
158
+
159
+
160
+ def _values(items: List[Dict[str, Any]]) -> List[str]:
161
+ """The canonical value of every item, as the shape of the bracket notation wants to see them."""
162
+ return [item["value"] if item["role"] in ("num", "marker") else "" for item in items]
163
+
164
+
165
+ def _slot(kind: str, slot: str, items: List[Dict[str, Any]], position: int,
166
+ vals: List[str]) -> Optional[Tuple[str, int]]:
167
+ """The value of one slot taken from the stream, and where the stream continues.
168
+
169
+ Four kinds of value, four ways of taking it: a number is one run of digits the atomiser cut; a
170
+ word of a closed set is one marker whose value the lexicon already translated; a frame or a
171
+ section is a region of the notation, and its text is handed to the shape check of
172
+ :mod:`lingologos_stratum.canonical`, which is what says whether the region really is a frame.
173
+ """
174
+ what = canonical.SLOT_KIND[kind][slot]
175
+ while position < len(items) and items[position]["role"] == "noise":
176
+ # A function word may stand between the words of the pattern and the value of a slot --
177
+ # "verifica la flessione" says the article between the verb and the quantity -- and it is
178
+ # still the same pattern. A verb, a marker or a number is not skipped: those the pattern has
179
+ # to name, and a pattern that skipped one would be reading a sentence it did not describe.
180
+ position += 1
181
+ if what == "num":
182
+ if position >= len(items) or items[position]["role"] != "num":
183
+ return None
184
+ pieces = canonical.tokens(items[position]["value"])
185
+ if len(pieces) != 1:
186
+ return None
187
+ try:
188
+ return canonical.value(pieces[0]), position + 1
189
+ except ReadingError:
190
+ return None
191
+ if what in ("quantity", "direction", "mode", "end"):
192
+ if position >= len(items) or items[position]["role"] != "marker":
193
+ return None
194
+ return items[position]["value"], position + 1
195
+ end = canonical.extent(vals, position)
196
+ if end < 0:
197
+ return None
198
+ text = canonical.region_text(vals, position, end)
199
+ try:
200
+ checked = canonical.frame(text) if what == "frame" else canonical.section(text)
201
+ except ReadingError:
202
+ return None
203
+ return checked, end
204
+
205
+
206
+ def match(kind: str, chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]],
207
+ attached: List[str]) -> Optional[Dict[str, str]]:
208
+ """A value per slot name, or ``None`` when the pattern does not describe the items.
209
+
210
+ Every verb, every marker and every number of the sentence has to be consumed by the pattern, and
211
+ a pattern that leaves one out is a pattern that misread the sentence. The values come back as the
212
+ structures language writes them, because the slot types and the shape check of the notation ran
213
+ while they were taken.
214
+ """
215
+ vals = _values(items)
216
+ filled: Dict[str, str] = {}
217
+ position = 0
218
+ if chunks[0]:
219
+ found = _find(chunks[0], items, 0, attached)
220
+ if found is None or not _empty(items, 0, found[0]):
221
+ return None
222
+ position = found[1]
223
+ for index, slot in enumerate(slots):
224
+ got = _slot(kind, slot, items, position, vals)
225
+ if got is None:
226
+ return None
227
+ filled[slot], position = got
228
+ chunk = chunks[index + 1]
229
+ if chunk:
230
+ found = _find(chunk, items, position, attached)
231
+ if found is None or not _empty(items, position, found[0]):
232
+ return None
233
+ position = found[1]
234
+ if not _empty(items, position, len(items)):
235
+ return None
236
+ return filled
237
+
238
+
239
+ def read(lang: str, text: str) -> Dict[str, Any]:
240
+ """The reading reader A reaches in one variety, and why it abstained when it did."""
241
+ items = scan(lang, text)
242
+ result: Dict[str, Any] = {"reader": "reader_a", "lang": lang, "mode": "pattern",
243
+ "kind": None, "sentence": None, "slots": {}, "markers": [],
244
+ "notes": []}
245
+ unknown = [item for item in items if item["role"] == "unknown"]
246
+ if unknown:
247
+ result["status"] = "NOT COVERED"
248
+ for item in unknown:
249
+ result["notes"].append({"reason": "unknown_word", "word": item["surface"]})
250
+ return result
251
+ result["markers"] = [item["value"] for item in items if item["role"] == "marker"]
252
+ candidates, why = lexicon.announce(lang, items)
253
+ if not candidates:
254
+ result["status"] = "NOT COVERED"
255
+ result["notes"].append(why)
256
+ return result
257
+ attached = lexicon.prefixes(lang)
258
+ found: List[Tuple[str, str, Dict[str, str]]] = []
259
+ for kind in candidates:
260
+ for pattern in lexicon.patterns(lang).get(kind, []):
261
+ chunks, slots = compile_pattern(pattern)
262
+ filled = match(kind, chunks, slots, items, attached)
263
+ if filled is None:
264
+ continue
265
+ try:
266
+ sentence = canonical.fill(kind, filled)
267
+ except ReadingError as error:
268
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
269
+ continue
270
+ if not any(entry[1] == sentence for entry in found):
271
+ found.append((kind, sentence, filled))
272
+ if not found:
273
+ result["status"] = "NOT COVERED"
274
+ if not result["notes"]:
275
+ result["notes"].append({"reason": "no_pattern"})
276
+ return result
277
+ if len(found) > 1:
278
+ result["status"] = "AMBIGUOUS"
279
+ result["notes"].append({"reason": "multiple",
280
+ "first": found[0][1], "second": found[1][1]})
281
+ return result
282
+ read_kind, sentence, filled = found[0]
283
+ result["status"] = "READ"
284
+ result["kind"] = read_kind
285
+ result["variant"] = list(filled)
286
+ result["sentence"] = sentence
287
+ result["slots"] = filled
288
+ result["literals"] = canonical.numbers(text)
289
+ result["notes"] = []
290
+ return result
lingologos_stratum/read_b.py ADDED
@@ -0,0 +1,310 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Reader B: the reader of joints, which never looks at a surface pattern.
2
+
3
+ Reader B is built to fail in a different way from reader A. It does not know the patterns a language
4
+ variety writes down; it knows only which **joints** a kind of the structures language requires --
5
+ ``member``, ``at``, ``section``, ``limit``, ``ends``, ``length``, ``modulus``, ``node`` -- and where
6
+ the words of a closed set stand. A sentence is read when the joints it carries are exactly the joints
7
+ of one form of the kind, in the order the structures language puts them, and when the numbers fall
8
+ into the regions those joints introduce.
9
+
10
+ That is a different question from A's. A asks "does this sentence have the shape this variety
11
+ documents"; B asks "does this sentence carry the joints the structures language requires, and are the
12
+ numbers where those joints put them". A sentence can pass one and fail the other: a paraphrase that
13
+ keeps every joint but drops a documented word, or a sentence of a documented shape whose ``limit``
14
+ never arrives. The topology trusts a reading only when both arrive at the same problem, and that is
15
+ the whole purpose of the two readers.
16
+
17
+ Both readers fold the bracket notation with the same shape check, the one in
18
+ :mod:`lingologos_stratum.canonical`, and then B treats a frame as one region of the sentence rather than as a
19
+ hundred words: inside the brackets there are block names and support names, but they are not joints of
20
+ the question, and a reader that counted them as joints would ask the user for a frame inside a frame.
21
+ """
22
+
23
+ import re
24
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
25
+
26
+ from . import canonical, lexicon
27
+ from .canonical import ReadingError
28
+ from .segment import atomize, fold
29
+
30
+ # What a placeholder of a marker sequence accepts: the head word of a region, or a word of the closed
31
+ # set that slot reads. A number never appears in a sequence, so nothing here accepts digits.
32
+ _HEAD = {"frame": canonical.FRAME_WORD, "section": canonical.SECTION_FORMS}
33
+ _CLOSED = {"quantity": canonical.QUANTITIES, "direction": canonical.DIRECTIONS,
34
+ "mode": canonical.VERIFY_MODES,
35
+ "end": tuple(sorted(set(canonical.END_KINDS) | set(canonical.END_FROM_VALUE)))}
36
+ _REGION = ("frame", "section")
37
+ _PLACEHOLDER = re.compile(r"^\{([A-Z][A-Z0-9]*)\}$")
38
+
39
+
40
+ def find_spans(lang: str, atoms: Sequence[Tuple[str, str]]) -> Tuple[List[Tuple[int, int, str, str]],
41
+ List[bool]]:
42
+ """Claim the longest lexicon phrase at every position, never overlapping an earlier claim.
43
+
44
+ The inventory is the whole lexicon -- verbs, joints, block names, words of a closed set, function
45
+ words -- and the longest match wins, which is how a variety that says ``von Mises`` for one
46
+ quantity and ``Mises`` for nothing keeps the two apart.
47
+ """
48
+ phrases = lexicon.phrase_index(lang)
49
+ attached = lexicon.prefixes(lang)
50
+ stripped = lexicon.prefix_index(lang) if attached else {}
51
+ longest = lexicon.max_phrase_length(lang)
52
+ covered = [False] * len(atoms)
53
+ spans: List[Tuple[int, int, str, str]] = []
54
+ for width in range(longest, 0, -1):
55
+ for start in range(0, len(atoms) - width + 1):
56
+ if any(covered[start:start + width]):
57
+ continue
58
+ if any(atoms[start + step][0] != "w" for step in range(width)):
59
+ continue
60
+ window = tuple(fold(atoms[start + step][1]) for step in range(width))
61
+ hit = phrases.get(window)
62
+ key = window
63
+ if hit is None and attached:
64
+ key = tuple(lexicon.strip_prefix(word, attached) for word in window)
65
+ hit = stripped.get(key)
66
+ if hit is None:
67
+ continue
68
+ for position in range(start, start + width):
69
+ covered[position] = True
70
+ spans.append((start, start + width, hit[0], hit[1]))
71
+ return spans, covered
72
+
73
+
74
+ def classify(lang: str, atoms: Sequence[Tuple[str, str]],
75
+ spans: Sequence[Tuple[int, int, str, str]],
76
+ covered: Sequence[bool]) -> List[Dict[str, Any]]:
77
+ """One item per atom, with the role the lexicon gave it and the canonical value it carries."""
78
+ by_start = {span[0]: span for span in spans}
79
+ items: List[Dict[str, Any]] = []
80
+ index = 0
81
+ while index < len(atoms):
82
+ span = by_start.get(index)
83
+ if span is None and atoms[index][0] == "m":
84
+ items.append({"role": "num", "value": atoms[index][1], "words": [],
85
+ "surface": atoms[index][1]})
86
+ index += 1
87
+ continue
88
+ if span is None:
89
+ word = fold(atoms[index][1])
90
+ if atoms[index][1] and atoms[index][1] in lexicon.noise_chars(lang):
91
+ items.append({"role": "noise", "value": "", "words": [word],
92
+ "surface": atoms[index][1]})
93
+ else:
94
+ items.append({"role": "unknown", "value": word, "words": [word],
95
+ "surface": atoms[index][1]})
96
+ index += 1
97
+ continue
98
+ _, stop, role, value = span
99
+ item = {"role": role, "value": value,
100
+ "words": [fold(atoms[step][1]) for step in range(index, stop)],
101
+ "surface": atoms[index][1]}
102
+ if role == "verb":
103
+ item["kinds"] = (value,)
104
+ items.append(item)
105
+ index = stop
106
+ return items
107
+
108
+
109
+ def _values(items: Sequence[Dict[str, Any]]) -> List[str]:
110
+ """The canonical value of every item, as the shape of the bracket notation wants to see them."""
111
+ return [item["value"] if item["role"] in ("num", "marker") else "" for item in items]
112
+
113
+
114
+ def fold_regions(items: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, str]]]:
115
+ """Replace each region of the notation by a single item, and report what is not a region.
116
+
117
+ A region is a frame or a section: the head word followed by its blocks and brackets. B folds it
118
+ because it reads the sentence by joints, and inside the brackets stand words that name blocks and
119
+ supports, none of which is a joint of the question. The fold is where the notation is checked, so
120
+ an unterminated block or a block out of order is reported here and nowhere else in this reader.
121
+ """
122
+ vals = _values(items)
123
+ out: List[Dict[str, Any]] = []
124
+ notes: List[Dict[str, str]] = []
125
+ index = 0
126
+ while index < len(items):
127
+ item = items[index]
128
+ if item["role"] != "marker" or item["value"] not in canonical.REGION_HEADS:
129
+ out.append(item)
130
+ index += 1
131
+ continue
132
+ end = canonical.extent(vals, index)
133
+ if end < 0:
134
+ notes.append({"reason": "no_frame", "kind": item["value"],
135
+ "detail": "the notation that starts there is not a frame or a section"})
136
+ out.append(item)
137
+ index += 1
138
+ continue
139
+ text = canonical.region_text(vals, index, end)
140
+ try:
141
+ checked = (canonical.frame(text) if item["value"] == canonical.FRAME_WORD
142
+ else canonical.section(text))
143
+ except ReadingError as error:
144
+ notes.append({"reason": "no_frame", "kind": item["value"], "detail": str(error)})
145
+ out.append(item)
146
+ index += 1
147
+ continue
148
+ out.append({"role": "region", "value": item["value"], "text": checked, "words": []})
149
+ index = end
150
+ return out, notes
151
+
152
+
153
+ def _regions(items: Sequence[Dict[str, Any]]) -> List[Tuple[Optional[str], str]]:
154
+ """The stretches of numbers between the joints, each tagged with the joint before it.
155
+
156
+ A folded region is a boundary and not a stretch: the numbers inside a frame belong to the frame,
157
+ and B has already taken them as the value of its slot.
158
+ """
159
+ out: List[Tuple[Optional[str], str]] = []
160
+ joint: Optional[str] = None
161
+ buffer: List[str] = []
162
+ for item in items:
163
+ if item["role"] in ("verb", "region"):
164
+ if buffer:
165
+ out.append((joint, canonical.tidy(" ".join(buffer))))
166
+ buffer = []
167
+ joint = None
168
+ continue
169
+ if item["role"] in ("marker", "unknown"):
170
+ if buffer:
171
+ out.append((joint, canonical.tidy(" ".join(buffer))))
172
+ buffer = []
173
+ joint = item["value"] if item["role"] == "marker" else None
174
+ continue
175
+ if item["role"] == "num":
176
+ buffer.append(item["value"])
177
+ if buffer:
178
+ out.append((joint, canonical.tidy(" ".join(buffer))))
179
+ return out
180
+
181
+
182
+ def _agrees(expected: Sequence[str], carried: Sequence[Dict[str, Any]], kind: str,
183
+ variant: Sequence[str]) -> Optional[Dict[str, str]]:
184
+ """Match the joints of the sentence against the joints of one form, and take the values they carry.
185
+
186
+ A placeholder for a region of the notation takes the whole folded region, head word included, and
187
+ not the head word alone: the frame of a structure is its blocks, not the word that opens them.
188
+ """
189
+ if len(expected) != len(carried):
190
+ return None
191
+ filled: Dict[str, str] = {}
192
+ for want, item in zip(expected, carried):
193
+ got = item["value"]
194
+ match = _PLACEHOLDER.fullmatch(want)
195
+ if match is None:
196
+ if want != got:
197
+ return None
198
+ continue
199
+ slot = match.group(1)
200
+ what = canonical.SLOT_KIND[kind][slot]
201
+ if what in _REGION:
202
+ if got not in _HEAD[what]:
203
+ return None
204
+ if slot in variant:
205
+ filled[slot] = item.get("text") or got
206
+ elif got in _CLOSED.get(what, ()):
207
+ if slot in variant:
208
+ filled[slot] = got
209
+ else:
210
+ return None
211
+ return filled
212
+
213
+
214
+ def _numbers(regions: Sequence[Tuple[Optional[str], str]], kind: str,
215
+ variant: Sequence[str]) -> Optional[Dict[str, str]]:
216
+ """The number of each slot, taken from the region the joint before it introduces.
217
+
218
+ Every joint of the structures language that introduces a number introduces exactly one, and every
219
+ number of the sentence has to land in a slot: a number standing outside both the frame and any
220
+ slot is a number this form has no place for, and that is a reading to refuse rather than a number
221
+ to guess at.
222
+ """
223
+ gaps = canonical.gap_markers(kind, variant)
224
+ slots = list(variant)
225
+ used = set()
226
+ filled: Dict[str, str] = {}
227
+ for position, slot in enumerate(slots):
228
+ if canonical.SLOT_KIND[kind][slot] != "num":
229
+ continue
230
+ joint = gaps[position] if position < len(gaps) else None
231
+ if joint is None:
232
+ return None
233
+ hits = [index for index, (tag, _) in enumerate(regions)
234
+ if tag == joint and index not in used]
235
+ if len(hits) != 1:
236
+ return None
237
+ pieces = canonical.tokens(regions[hits[0]][1])
238
+ if len(pieces) != 1:
239
+ return None
240
+ try:
241
+ filled[slot] = canonical.value(pieces[0])
242
+ except ReadingError:
243
+ return None
244
+ used.add(hits[0])
245
+ for index, (_, text) in enumerate(regions):
246
+ if index not in used and canonical.tokens(text):
247
+ return None
248
+ return filled
249
+
250
+
251
+ def read(lang: str, text: str) -> Dict[str, Any]:
252
+ """The reading reader B reaches in one variety, and why it abstained when it did."""
253
+ atoms = atomize(text)
254
+ spans, covered = find_spans(lang, atoms)
255
+ items = classify(lang, atoms, spans, covered)
256
+ result: Dict[str, Any] = {"reader": "reader_b", "lang": lang, "mode": "joints",
257
+ "kind": None, "sentence": None, "slots": {}, "markers": [],
258
+ "notes": []}
259
+ unknown = [item for item in items if item["role"] == "unknown"]
260
+ if unknown:
261
+ result["status"] = "NOT COVERED"
262
+ for item in unknown:
263
+ result["notes"].append({"reason": "unknown_word", "word": item["surface"]})
264
+ return result
265
+ items, notes = fold_regions(items)
266
+ result["notes"].extend(notes)
267
+ carried = [item for item in items if item["role"] in ("marker", "region")]
268
+ result["markers"] = [item["value"] for item in carried]
269
+ candidates, why = lexicon.announce(lang, items)
270
+ if not candidates:
271
+ result["status"] = "NOT COVERED"
272
+ result["notes"].append(why)
273
+ return result
274
+ found: List[Tuple[str, List[str], str, Dict[str, str]]] = []
275
+ for kind in candidates:
276
+ for variant in canonical.VARIANTS.get(kind, []):
277
+ expected = canonical.marker_sequence(kind, variant)
278
+ filled = _agrees(expected, carried, kind, variant)
279
+ if filled is None:
280
+ continue
281
+ values = _numbers(_regions(items), kind, variant)
282
+ if values is None:
283
+ continue
284
+ filled.update(values)
285
+ try:
286
+ sentence = canonical.fill(kind, filled)
287
+ except ReadingError as error:
288
+ result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)})
289
+ continue
290
+ if not any(entry[2] == sentence for entry in found):
291
+ found.append((kind, list(variant), sentence, filled))
292
+ if not found:
293
+ result["status"] = "NOT COVERED"
294
+ if not result["notes"]:
295
+ result["notes"].append({"reason": "no_markers"})
296
+ return result
297
+ if len(found) > 1:
298
+ result["status"] = "AMBIGUOUS"
299
+ result["notes"].append({"reason": "multiple",
300
+ "first": found[0][2], "second": found[1][2]})
301
+ return result
302
+ read_kind, variant, sentence, filled = found[0]
303
+ result["status"] = "READ"
304
+ result["kind"] = read_kind
305
+ result["variant"] = list(variant)
306
+ result["sentence"] = sentence
307
+ result["slots"] = filled
308
+ result["literals"] = canonical.numbers(text)
309
+ result["notes"] = []
310
+ return result
lingologos_stratum/render.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 mechanics content -- the canonical sentence the stratum understood and the answer the structures
10
+ topology 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
+ ``cut member 1 at 1 frame nodes [ 1 0 0 ; 2 4 0 ] ...`` can see which reading was used, and that is
14
+ the whole point 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 a
18
+ 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("struc") 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 structures 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 structures topology."""
61
+ comparison = dossier.get("compare") or {}
62
+ struc_verdict = dossier.get("struc") or {}
63
+ for source in (dossier.get("sent"), comparison.get("left"), struc_verdict.get("problem_struc")):
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("sentence"):
69
+ return str(reading["sentence"])
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
+ struc_verdict = dossier.get("struc") or {}
103
+ if struc_verdict.get("status"):
104
+ # Which road of the topology proved what is its own bookkeeping and nothing the reader of an
105
+ # answer asked for; what belongs in the reply is the verdict and, when the topology abstained,
106
+ # the reason it abstained.
107
+ tail = str(struc_verdict["status"])
108
+ why = struc_verdict.get("reason") or struc_verdict.get("note") or ""
109
+ if not why and struc_verdict.get("reasons"):
110
+ why = str(struc_verdict["reasons"][0])
111
+ if why:
112
+ tail += " (" + why + ")"
113
+ lines.append("%s: %s" % (labels["struc_layer"], tail))
114
+ reasons = [str(reason) for reason in verdict.get("reasons") or []]
115
+ if reasons:
116
+ struc_verdict = dossier.get("struc") or {}
117
+ fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])})
118
+ fields.setdefault("struc_unknown", {"detail": str(struc_verdict.get("reason")
119
+ or struc_verdict.get("note") or "")})
120
+ texts = [_fill(lexicon.translate_reason(lang, reason, **(fields.get(reason) or {})))
121
+ for reason in reasons]
122
+ lines.append("%s: %s" % (labels["notes"], "; ".join(texts)))
123
+ check = _check_line(lang, records)
124
+ if check:
125
+ lines.append(check)
126
+ if state in ("NOT COVERED", "AMBIGUOUS", "NONE") and not verdict.get("answer"):
127
+ samples = lexicon.examples(lang)
128
+ if samples:
129
+ lines.append("%s: %s" % (labels["question"], " | ".join(samples[:5])))
130
+ return {
131
+ "lang": lang,
132
+ "language": lexicon.language_name(lang),
133
+ "state": state,
134
+ "assurance": verdict.get("assurance", 0),
135
+ "answer": verdict.get("answer", ""),
136
+ "sentence": sentence,
137
+ "kind": kind,
138
+ "reasons": reasons,
139
+ "lines": lines,
140
+ "text": "\n".join(lines),
141
+ }
lingologos_stratum/segment.py ADDED
@@ -0,0 +1,242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 *notation*, and it puts every digit in the shape the structures language uses. The
5
+ mapping from a word to a role is the lexicon, in ``lexicon/<lang>.json`` and
6
+ :mod:`lingologos_stratum.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 notation only between two closed operands, which is what separates an Italian
18
+ sentence comma from the comma of a list written between brackets.
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 bracket notation, square brackets and semicolons included: the blocks of a
75
+ # frame are written with them, so they have to be read as notation and not dropped as stray
76
+ # punctuation. The arithmetic symbols are here too, because a person who writes the abscissa of a
77
+ # cut as "2/1875" or as "-15" writes them inside their own sentence.
78
+ NOTATION_CHARS = set("0123456789+-*/^()[]<>=!|,:.;")
79
+ CLOSED_CHARS = set("0123456789)]")
80
+ OPENING_CHARS = set("0123456789[(")
81
+
82
+ # The relation and operator symbols the structures language accepts. Nothing else is a number.
83
+ OPERATORS = ("=>", "<=>", "<=", ">=", "!=", "+", "-", "*", "/", "^", "=", "<", ">", "|")
84
+
85
+
86
+ def normalize(text: str) -> str:
87
+ """Return the sentence in a canonical shape: ASCII digits, ASCII separators, one space."""
88
+ text = unicodedata.normalize("NFKC", text)
89
+ for ch in INVISIBLE:
90
+ text = text.replace(ch, "")
91
+ text = text.translate({ord(k): v for k, v in DIGIT_MAP.items()})
92
+ text = text.translate({ord(k): v for k, v in SEPARATOR_MAP.items()})
93
+ return re.sub(r"\s+", " ", text).strip()
94
+
95
+
96
+ def script_of(text: str) -> str:
97
+ """The dominant non Latin script of a sentence: cjk, arabic, devanagari, latin or none."""
98
+ counts = {"cjk": 0, "arabic": 0, "devanagari": 0, "latin": 0}
99
+ for ch in text:
100
+ if not ch.isalpha():
101
+ continue
102
+ name = unicodedata.name(ch, "")
103
+ if name.startswith("CJK") or name.startswith("IDEOGRAPHIC"):
104
+ counts["cjk"] += 1
105
+ elif name.startswith("ARABIC"):
106
+ counts["arabic"] += 1
107
+ elif name.startswith("DEVANAGARI"):
108
+ counts["devanagari"] += 1
109
+ elif name.startswith("LATIN"):
110
+ counts["latin"] += 1
111
+ best = max(counts, key=lambda k: counts[k])
112
+ return best if counts[best] else "none"
113
+
114
+
115
+ def _is_notation_char(ch: str, text: str, index: int) -> bool:
116
+ if ch in NOTATION_CHARS:
117
+ if ch == ".":
118
+ return _neighbour(text, index, -1).isdigit() and _neighbour(text, index, 1).isdigit()
119
+ if ch == ",":
120
+ return _neighbour(text, index, -1) in CLOSED_CHARS and _neighbour(text, index, 1) in OPENING_CHARS
121
+ return True
122
+ return False
123
+
124
+
125
+ def _neighbour(text: str, index: int, step: int) -> str:
126
+ j = index + step
127
+ while 0 <= j < len(text) and text[j] == " ":
128
+ j += step
129
+ return text[j] if 0 <= j < len(text) else ""
130
+
131
+
132
+ _MARKS = ("Mn", "Mc", "Me")
133
+
134
+
135
+ def _word_char(ch: str) -> bool:
136
+ """A character of a word: a letter of any script, an apostrophe, or a combining mark.
137
+
138
+ The combining marks matter: the vowel signs of Devanagari and the Arabic diacritics are not
139
+ letters, and dropping them would break a word into pieces that no lexicon entry matches.
140
+ """
141
+ return ch.isalpha() or ch in "_'" or unicodedata.category(ch) in _MARKS
142
+
143
+
144
+ def pieces(run: str) -> List[str]:
145
+ """Split a word run at every apostrophe: an Italian elision is two words to the lexicon.
146
+
147
+ ``l'integrale`` is the article ``l`` and the noun ``integrale``, and only the second of the
148
+ two is a phrase of the lexicon. The lexicon patterns are written with the elision joined,
149
+ and compiled through this same function, so data and matching agree.
150
+ """
151
+ return [piece for piece in run.split("'") if piece]
152
+
153
+
154
+ def is_cjk(run: str) -> bool:
155
+ """Whether a run is written in Chinese characters."""
156
+ return any(unicodedata.name(ch, "").startswith(("CJK", "IDEOGRAPHIC")) for ch in run)
157
+
158
+
159
+ def word_pieces(run: str) -> List[str]:
160
+ """The atoms a word run offers the lexicon: characters for Chinese, pieces elsewhere.
161
+
162
+ Chinese is written without spaces, so the only reliable unit is the character, and a
163
+ multi character term of the lexicon is then a sequence of atoms -- which is how the lexicon
164
+ file writes it too, one space separated token per character group.
165
+ """
166
+ if is_cjk(run):
167
+ return list(run)
168
+ return pieces(run)
169
+
170
+
171
+ def atomize(text: str) -> List[Tuple[str, str]]:
172
+ """A normalized sentence as atoms: ``("m", run)`` notation, ``("w", word)`` word atoms.
173
+
174
+ Both readers start here. It is one of the two things they share -- the other is the lexicon --
175
+ and it is the counterpart of the shared token spec that the two formalizers of the structures
176
+ topology share: sharing the atomiser buys agreement about *what the words are*, while the two
177
+ readers still disagree, productively, about what the sentence means.
178
+ """
179
+ out: List[Tuple[str, str]] = []
180
+ for kind, run in tokens(text):
181
+ if kind == "m":
182
+ out.append(("m", run))
183
+ else:
184
+ for piece in word_pieces(run):
185
+ out.append(("w", piece))
186
+ return out
187
+
188
+
189
+ def tokens(text: str) -> List[Tuple[str, str]]:
190
+ """Split a normalized sentence into ``("m", run)`` notation and ``("w", run)`` words.
191
+
192
+ Letters of every script open a word run, digits and the symbols of the structures language open
193
+ a notation run. An ASCII letter run is returned as a word: :mod:`lingologos_stratum.read_a` and
194
+ :mod:`lingologos_stratum.read_b` decide between a variable and a function word through the lexicon.
195
+ """
196
+ text = normalize(text)
197
+ out: List[Tuple[str, str]] = []
198
+ index = 0
199
+ while index < len(text):
200
+ ch = text[index]
201
+ if ch.isspace():
202
+ index += 1
203
+ continue
204
+ if _word_char(ch):
205
+ start = index
206
+ while index < len(text) and _word_char(text[index]):
207
+ index += 1
208
+ out.append(("w", text[start:index]))
209
+ continue
210
+ if _is_notation_char(ch, text, index):
211
+ start = index
212
+ while index < len(text) and _is_notation_char(text[index], text, index):
213
+ index += 1
214
+ run = text[start:index].strip()
215
+ if run:
216
+ out.append(("m", run))
217
+ continue
218
+ index += 1
219
+ return out
220
+
221
+
222
+ def numeric_literals(text: str) -> List[str]:
223
+ """Every numeric literal of a sentence, in the order it appears, digits normalised."""
224
+ found: List[str] = []
225
+ for _kind, run in tokens(text):
226
+ for match in re.finditer(r"\d+(?:\.\d+)?", run):
227
+ found.append(match.group(0))
228
+ return found
229
+
230
+
231
+ def fold(word: str) -> str:
232
+ """Casefold a Latin word and drop its accents, so that one lexicon entry covers both cases.
233
+
234
+ Non Latin scripts are returned unchanged: casefolding and accent folding do not apply to
235
+ Chinese, Devanagari or Arabic, and the lexicon entries are written in the form the keyboard
236
+ produces.
237
+ """
238
+ if not any("a" <= ch.lower() <= "z" for ch in word):
239
+ return word
240
+ decomposed = unicodedata.normalize("NFD", word)
241
+ stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch))
242
+ return stripped.lower()
nodes/adversary/grammar.gf CHANGED
@@ -1,8 +1,8 @@
1
  -- Node adversary (adversary): Adversary: states the ceiling the reading layer can honestly
2
  -- claim for the sentence it settled, and writes the inequality that a raised assurance would
3
  -- break, so that a claim above the ceiling is refuted instead of accepted.
4
- -- Reference implementation: the ceiling table in lgstratum/decide.py and lgstratum/agents.py
5
- -- (cap_claim, step_adversary), the injected faults in lgstratum/faults.py.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
 
1
  -- Node adversary (adversary): Adversary: states the ceiling the reading layer can honestly
2
  -- claim for the sentence it settled, and writes the inequality that a raised assurance would
3
  -- break, so that a claim above the ceiling is refuted instead of accepted.
4
+ -- Reference implementation: the ceiling table in lingologos_stratum/decide.py and lingologos_stratum/agents.py
5
+ -- (cap_claim, step_adversary), the injected faults in lingologos_stratum/faults.py.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
nodes/arbiter/grammar.gf CHANGED
@@ -1,8 +1,8 @@
1
  -- Node arbiter (arbiter): Arbiter: holds the question and its language, applies the decision
2
  -- rule of the stratum, and answers in the language of the question with no more assurance than
3
  -- the minimum of what the structures topology certifies and what the reading can support.
4
- -- Reference implementation: lgstratum/decide.py, the recomputation in lgstratum/pipeline.py
5
- -- (checked_verdict, referee_adjusted), the answer of lgstratum/render.py.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
 
1
  -- Node arbiter (arbiter): Arbiter: holds the question and its language, applies the decision
2
  -- rule of the stratum, and answers in the language of the question with no more assurance than
3
  -- the minimum of what the structures topology certifies and what the reading can support.
4
+ -- Reference implementation: lingologos_stratum/decide.py, the recomputation in lingologos_stratum/pipeline.py
5
+ -- (checked_verdict, referee_adjusted), the answer of lingologos_stratum/render.py.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
nodes/boundary/grammar.gf CHANGED
@@ -1,8 +1,8 @@
1
  -- Node boundary (boundary): Boundary: the place where the verdict of the structures topology
2
  -- enters this stratum, and the check that the sentence that topology says it solved is the
3
  -- sentence that was sent to it.
4
- -- Reference implementation: lgstratum/agents.py (step_boundary), lgstratum/coverage.py
5
- -- (echo_matches), lgstratum/compare.py for the numbers of both sides.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
 
1
  -- Node boundary (boundary): Boundary: the place where the verdict of the structures topology
2
  -- enters this stratum, and the check that the sentence that topology says it solved is the
3
  -- sentence that was sent to it.
4
+ -- Reference implementation: lingologos_stratum/agents.py (step_boundary), lingologos_stratum/coverage.py
5
+ -- (echo_matches), lingologos_stratum/compare.py for the numbers of both sides.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
nodes/coverage/grammar.gf CHANGED
@@ -1,6 +1,6 @@
1
  -- Node coverage (coverage): Coverage: checks that the reading keeps every number written in
2
  -- the question and that the question falls inside the coverage of the fragment of its language.
3
- -- Reference implementation: lgstratum/coverage.py, which counts the numbers of the question,
4
  -- of the reading and of the sentence the structures topology echoes back.
5
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
6
  -- structures topology. The language is stated here as it is stated in the folders of that
 
1
  -- Node coverage (coverage): Coverage: checks that the reading keeps every number written in
2
  -- the question and that the question falls inside the coverage of the fragment of its language.
3
+ -- Reference implementation: lingologos_stratum/coverage.py, which counts the numbers of the question,
4
  -- of the reading and of the sentence the structures topology echoes back.
5
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
6
  -- structures topology. The language is stated here as it is stated in the folders of that
nodes/equivalence/grammar.gf CHANGED
@@ -1,6 +1,6 @@
1
  -- Node equivalence (equivalence): Equivalence: compares the two readings and says whether they
2
  -- state one structure, with an SMT view of the numbers when the text view is not enough.
3
- -- Reference implementation: lgstratum/compare.py, which re-parses both sentences with the
4
  -- parser of the structures topology and pins the numbers it extracts from them.
5
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
6
  -- structures topology. The language is stated here as it is stated in the folders of that
 
1
  -- Node equivalence (equivalence): Equivalence: compares the two readings and says whether they
2
  -- state one structure, with an SMT view of the numbers when the text view is not enough.
3
+ -- Reference implementation: lingologos_stratum/compare.py, which re-parses both sentences with the
4
  -- parser of the structures topology and pins the numbers it extracts from them.
5
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
6
  -- structures topology. The language is stated here as it is stated in the folders of that
nodes/invoker/grammar.gf CHANGED
@@ -1,8 +1,8 @@
1
  -- Node invoker (invoker): Invoker: hands the agreed sentence to the structures topology as a
2
  -- separate process and carries that verdict back untouched, with the assurance the topology
3
  -- itself states.
4
- -- Reference implementation: lgstratum/invoker.py over tools/ask.py of the structures topology,
5
- -- the claim of the step in lgstratum/agents.py (step_invoker).
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
 
1
  -- Node invoker (invoker): Invoker: hands the agreed sentence to the structures topology as a
2
  -- separate process and carries that verdict back untouched, with the assurance the topology
3
  -- itself states.
4
+ -- Reference implementation: lingologos_stratum/invoker.py over tools/ask.py of the structures topology,
5
+ -- the claim of the step in lingologos_stratum/agents.py (step_invoker).
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
nodes/reader_a/grammar.gf CHANGED
@@ -1,9 +1,9 @@
1
  -- Node reader_a (reader_a): First reader: turns a question written in one of the six user
2
  -- languages into a sentence of StrucLang by its surface, the literals of the question and the
3
  -- typed slots between them, without seeing the reading of the second reader.
4
- -- Reference implementation: the surface reader lgstratum/read_a.py, the atomizer
5
- -- lgstratum/segment.py, the words of the language lexicon/{lang}.json, the printer
6
- -- lgstratum/canonical.py that fills the template of the kind.
7
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
8
  -- structures topology. The language is stated here as it is stated in the folders of that
9
  -- topology, so the sentence this node prints is a sentence that topology can parse.
 
1
  -- Node reader_a (reader_a): First reader: turns a question written in one of the six user
2
  -- languages into a sentence of StrucLang by its surface, the literals of the question and the
3
  -- typed slots between them, without seeing the reading of the second reader.
4
+ -- Reference implementation: the surface reader lingologos_stratum/read_a.py, the atomizer
5
+ -- lingologos_stratum/segment.py, the words of the language lexicon/{lang}.json, the printer
6
+ -- lingologos_stratum/canonical.py that fills the template of the kind.
7
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
8
  -- structures topology. The language is stated here as it is stated in the folders of that
9
  -- topology, so the sentence this node prints is a sentence that topology can parse.
nodes/reader_b/grammar.gf CHANGED
@@ -1,8 +1,8 @@
1
  -- Node reader_b (reader_b): Second reader: an independent reading of the same question, its
2
  -- own search over the same lexicon, this time following the joints and markers of the sentence
3
  -- and the order of the canonical form it expects.
4
- -- Reference implementation: the marker reader lgstratum/read_b.py, the atomizer
5
- -- lgstratum/segment.py, the joint words and templates lgstratum/canonical.py.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
 
1
  -- Node reader_b (reader_b): Second reader: an independent reading of the same question, its
2
  -- own search over the same lexicon, this time following the joints and markers of the sentence
3
  -- and the order of the canonical form it expects.
4
+ -- Reference implementation: the marker reader lingologos_stratum/read_b.py, the atomizer
5
+ -- lingologos_stratum/segment.py, the joint words and templates lingologos_stratum/canonical.py.
6
  -- StrucLang: the controlled language this stratum writes, which is the input language of the
7
  -- structures topology. The language is stated here as it is stated in the folders of that
8
  -- topology, so the sentence this node prints is a sentence that topology can parse.
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 lgstratum import canonical, corpus, lexicon
11
 
12
  ITEMS = corpus.load()
13
  IDS = [str(item["id"]) for item in ITEMS]
 
7
 
8
  import pytest
9
 
10
+ from lingologos_stratum 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 lgstratum import decide, pipeline
6
 
7
  SECTION = "properties section rect 1/5 2/5"
8
  OTHER = "properties section rect 1/5 3/5"
 
2
 
3
  import copy
4
 
5
+ from lingologos_stratum import decide, pipeline
6
 
7
  SECTION = "properties section rect 1/5 2/5"
8
  OTHER = "properties section rect 1/5 3/5"
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 lgstratum import agents, canonical, corpus, faults, pipeline
12
 
13
  ITEMS = {item["id"]: item for item in corpus.load()}
14
  ONE = "it-01"
 
8
 
9
  import pytest
10
 
11
+ from lingologos_stratum import agents, canonical, corpus, faults, pipeline
12
 
13
  ITEMS = {item["id"]: item for item in corpus.load()}
14
  ONE = "it-01"
tests/test_lexicon.py CHANGED
@@ -5,7 +5,7 @@ from pathlib import Path
5
 
6
  import pytest
7
 
8
- from lgstratum import canonical, decide, lexicon, segment
9
 
10
  ROOT = Path(__file__).resolve().parents[1]
11
  LANGS = lexicon.codes()
 
5
 
6
  import pytest
7
 
8
+ from lingologos_stratum 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 lgstratum import corpus, lexicon
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_stratum 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
@@ -12,7 +12,7 @@ from typing import Any, Dict, List, Tuple
12
 
13
  import pytest
14
 
15
- from lgstratum import agents, canonical, coverage, corpus, faults, pipeline
16
 
17
  ITEMS = {item["id"]: item for item in corpus.load()}
18
  PINS = ["it-01", "it-03"]
@@ -91,10 +91,10 @@ def test_the_structures_topology_is_reached_only_as_a_separate_process():
91
  # Nothing in this bundle may decide the mechanics: the only door toward the structures topology is
92
  # the invoker, and it launches the question tool of that bundle as a subprocess.
93
  import inspect
94
- from lgstratum import invoker
95
 
96
  source = inspect.getsource(invoker)
97
  assert "subprocess" in source
98
- assert "lgstruc" not in source
99
  for module in (agents, pipeline, faults):
100
- assert "lgstruc" not in inspect.getsource(module)
 
12
 
13
  import pytest
14
 
15
+ from lingologos_stratum import agents, canonical, coverage, corpus, faults, pipeline
16
 
17
  ITEMS = {item["id"]: item for item in corpus.load()}
18
  PINS = ["it-01", "it-03"]
 
91
  # Nothing in this bundle may decide the mechanics: the only door toward the structures topology is
92
  # the invoker, and it launches the question tool of that bundle as a subprocess.
93
  import inspect
94
+ from lingologos_stratum import invoker
95
 
96
  source = inspect.getsource(invoker)
97
  assert "subprocess" in source
98
+ assert "lingologos_struc" not in source
99
  for module in (agents, pipeline, faults):
100
+ assert "lingologos_struc" not in inspect.getsource(module)
tests/test_readers.py CHANGED
@@ -2,7 +2,7 @@
2
 
3
  import pytest
4
 
5
- from lgstratum import canonical, compare, corpus, read_a, read_b
6
 
7
  ITEMS = {item["id"]: item for item in corpus.load()}
8
  AGREED = [item_id for item_id, item in ITEMS.items() if (item.get("expect") or {}).get("state") == "AGREED"]
 
2
 
3
  import pytest
4
 
5
+ from lingologos_stratum import canonical, compare, corpus, read_a, read_b
6
 
7
  ITEMS = {item["id"]: item for item in corpus.load()}
8
  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 lgstratum import agents
10
 
11
  ROOT = Path(__file__).resolve().parents[1]
12
  TOPOLOGY = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))
@@ -56,7 +56,7 @@ def test_node_dataset_is_complete(node):
56
 
57
 
58
  def test_python_sources_are_ascii_only():
59
- paths = (list((ROOT / "lgstratum").glob("*.py")) + list((ROOT / "tools").glob("*.py"))
60
  + list((ROOT / "tests").glob("*.py")) + [ROOT / "agents" / "stratum_agent"])
61
  for path in paths:
62
  path.read_text(encoding="ascii")
@@ -68,7 +68,7 @@ def test_only_the_equivalence_referee_may_touch_the_structures_code():
68
  # and only for its own SMT plumbing: compare.py asks whether two readings of a question say the
69
  # same thing, which is a claim about the readings and never about the answer. The modules that
70
  # decide, route and invoke are checked to hold no reference to that package at all.
71
- for path in (ROOT / "lgstratum").glob("*.py"):
72
  tree = ast.parse(path.read_text(encoding="ascii"))
73
  for node in ast.walk(tree):
74
  if isinstance(node, ast.Import):
@@ -78,14 +78,14 @@ def test_only_the_equivalence_referee_may_touch_the_structures_code():
78
  else:
79
  continue
80
  for name in names:
81
- if name.startswith("lgstruc"):
82
  assert path.name == "compare.py", "%s imports %s" % (path.name, name)
83
  for name in ("decide.py", "pipeline.py", "agents.py", "invoker.py", "protocol.py", "coverage.py"):
84
- assert "lgstruc" not in (ROOT / "lgstratum" / name).read_text(encoding="ascii"), name
85
 
86
 
87
  def test_the_structures_bundle_is_reached_as_a_separate_process():
88
- source = (ROOT / "lgstratum" / "invoker.py").read_text(encoding="ascii")
89
  tree = ast.parse(source)
90
  calls = [ast.unparse(node) for node in ast.walk(tree) if isinstance(node, ast.Call)]
91
  assert any("subprocess.run" in call for call in calls)
 
6
 
7
  import pytest
8
 
9
+ from lingologos_stratum import agents
10
 
11
  ROOT = Path(__file__).resolve().parents[1]
12
  TOPOLOGY = json.loads((ROOT / "topology.json").read_text(encoding="utf-8"))
 
56
 
57
 
58
  def test_python_sources_are_ascii_only():
59
+ paths = (list((ROOT / "lingologos_stratum").glob("*.py")) + list((ROOT / "tools").glob("*.py"))
60
  + list((ROOT / "tests").glob("*.py")) + [ROOT / "agents" / "stratum_agent"])
61
  for path in paths:
62
  path.read_text(encoding="ascii")
 
68
  # and only for its own SMT plumbing: compare.py asks whether two readings of a question say the
69
  # same thing, which is a claim about the readings and never about the answer. The modules that
70
  # decide, route and invoke are checked to hold no reference to that package at all.
71
+ for path in (ROOT / "lingologos_stratum").glob("*.py"):
72
  tree = ast.parse(path.read_text(encoding="ascii"))
73
  for node in ast.walk(tree):
74
  if isinstance(node, ast.Import):
 
78
  else:
79
  continue
80
  for name in names:
81
+ if name.startswith("lingologos_struc"):
82
  assert path.name == "compare.py", "%s imports %s" % (path.name, name)
83
  for name in ("decide.py", "pipeline.py", "agents.py", "invoker.py", "protocol.py", "coverage.py"):
84
+ assert "lingologos_struc" not in (ROOT / "lingologos_stratum" / name).read_text(encoding="ascii"), name
85
 
86
 
87
  def test_the_structures_bundle_is_reached_as_a_separate_process():
88
+ source = (ROOT / "lingologos_stratum" / "invoker.py").read_text(encoding="ascii")
89
  tree = ast.parse(source)
90
  calls = [ast.unparse(node) for node in ast.walk(tree) if isinstance(node, ast.Call)]
91
  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
- (``lgstratum/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
 
@@ -32,7 +32,7 @@ from typing import Any, Dict, List, Tuple
32
  ROOT = Path(__file__).resolve().parents[1]
33
  sys.path.insert(0, str(ROOT))
34
 
35
- from lgstratum import agents, corpus, faults, pipeline # noqa: E402
36
 
37
  FULL = list(agents.ORDER)
38
  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_stratum/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
 
 
32
  ROOT = Path(__file__).resolve().parents[1]
33
  sys.path.insert(0, str(ROOT))
34
 
35
+ from lingologos_stratum import agents, corpus, faults, pipeline # noqa: E402
36
 
37
  FULL = list(agents.ORDER)
38
  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 lgstratum import corpus, pipeline, protocol, render # noqa: E402
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="lgstratum_"))
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("LGSTRATUM_FAULTS")
77
- os.environ["LGSTRATUM_FAULTS"] = faults_spec
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("LGSTRATUM_FAULTS", None)
89
  else:
90
- os.environ["LGSTRATUM_FAULTS"] = previous
91
  return _check(result)
92
  finally:
93
  if keep:
 
39
  sys.path.insert(0, str(_candidate))
40
  break
41
 
42
+ from lingologos_stratum 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_stratum_"))
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 lgstratum import corpus, lexicon, pipeline # noqa: E402
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_stratum import corpus, lexicon, pipeline # noqa: E402
26
 
27
  OUT = ROOT / "results" / "coverage.json"
28
 
tools/publish_dataset.py CHANGED
@@ -31,7 +31,7 @@ from typing import List, Tuple
31
  ROOT = Path(__file__).resolve().parents[1]
32
  sys.path.insert(0, str(ROOT))
33
 
34
- from lgstratum import corpus # noqa: E402 (after the path fix above)
35
 
36
  REPO = "tailot/struc-stratum"
37
  EXPECTED_FILES = 67 # the staged tree: this README is uploaded as the card under the same name
@@ -75,18 +75,20 @@ REPLACEMENTS: List[Tuple[str, str]] = [
75
  "sibling folder `datasets/struc`, which stays exactly as it is. Only the standard library and\n"
76
  "`z3-solver` are required; the tests need `pytest`.",
77
  "This dataset is the `struc-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,\n"
78
- "code and data together, plus this card in place of their README. Only the standard library and\n"
79
- "`z3-solver` are required, and `pytest` for the tests; both are named in `requirements.txt`. Every\n"
80
- "command below is written from inside the folder. The structures are not part of this dataset: they live\n"
81
- "in the `struc` bundle, published at https://huggingface.co/datasets/tailot/lingologos-struc, and section\n"
82
- "10 says how to point this folder at a copy of it.",
83
  ),
84
  (
85
- "The math\nstratum had a level three that no translation could reach; here there is no level to reach, and the\n"
 
86
  "rule still says what a person is shown.",
87
- "The `math-stratum` bundle of this project, at\n"
88
- "https://huggingface.co/datasets/tailot/math-stratum, had a level three that no translation could\n"
89
- "reach; here there is no level to reach, and the rule still says what a person is shown.",
 
90
  ),
91
  (
92
  "## 10. Using this folder as an external dataset",
@@ -97,40 +99,49 @@ REPLACEMENTS: List[Tuple[str, str]] = [
97
  "this content: 67 files (plus the card that replaces this README on the hub), 72 questions in one corpus\n"
98
  "file, the six lexicons, the eight node definitions, the two readers, the decision rule of section 1, the\n"
99
  "corpus grading and fault results under `results/`, and the fault catalogue of section 6.",
100
- "This dataset is 67 files plus this card: 72 questions in one corpus file, the six lexicons, the eight\n"
101
- "node definitions, the two readers, the decision rule of section 1, the corpus grading and fault results\n"
102
- "under `results/`, and the fault catalogue of section 6. To answer anything it needs the `struc` bundle:\n"
103
- "download https://huggingface.co/datasets/tailot/lingologos-struc somewhere, set\n"
104
- "`LGSTRATUM_STRUC_ROOT` to that copy, and the `invoker` node calls `tools/ask.py` there as a separate\n"
105
- "process, which is the only door through which this bundle ever reaches a solver. Inside a LingoLOGOS\n"
106
- "checkout the folder sits at `datasets/struc-stratum`, finds `datasets/struc` by itself, and needs\n"
107
- "`src/lingologos_orchestrator` importable for the two end to end sessions of section 8.",
108
  ),
109
  (
110
- "invariant tests call the tools of the structures topology as subprocesses, and the whole suite\n"
111
- "passed in 2 minutes on this checkout.",
112
- "invariant tests call the tools of the structures topology as subprocesses, which here means a copy of the\n"
113
- "`struc` dataset named by `LGSTRATUM_STRUC_ROOT` (section 10); the suite passed in 2 minutes inside a\n"
114
- "LingoLOGOS checkout, and the two end to end tests skip on their own when `lingologos_orchestrator` is\n"
115
- "not importable.",
116
  ),
117
  (
118
- "On the hub this\nREADME is rewritten as a dataset card whose sections 1 to 10 keep the wording and numbers of this file,\n"
119
- "and sections 11 to 14 are added there for readers who met the bundle on the hub rather than in a\n"
120
- "checkout: the fields of the corpus file, how to load it, rights and citation. Every file but this "
121
- "README was compared by sha256 after the upload: the hub holds one object\n"
122
- "per file of this folder plus `.gitattributes`, so the remote count is one above the number\n"
123
- "`tools/publish_dataset.py` prints here.",
124
- "This card keeps the wording and numbers of the README of\n"
125
- "the folder in its sections 1 to 10, and adds sections 11 to 14 for readers who met the bundle here\n"
126
- "rather than in a checkout: the fields of the corpus file, how to load it, rights and citation. Every\n"
127
- "file of the upload, this card among them, was compared by sha256 afterwards: the hub holds one object\n"
128
- "per file of the folder plus `.gitattributes`, so the remote count is one above the number the "
129
- "publisher\nprints.",
130
  ),
131
  (
132
- "Like the `struc` and `math-stratum` folders, this folder is\nignored by the git repository of the project: what the project carries is the link in the table of\npublished resources at the top of the repository README, and the documentation of the asset lives in\nthis README and in the card, not in `doc/TECHNICAL_DOCUMENTATION.md`.",
133
- "What the LingoLOGOS repository carries is the link to this\ndataset in the table of published resources at the top of its README; the documentation of the asset\nlives here, in this card, and not in the technical documentation of the project. `tools/publish_dataset.py`\nin the folder of the project republishes a changed working copy with the token taken from an environment\nvariable.",
 
 
 
 
 
 
 
 
 
134
  ),
135
  ]
136
 
@@ -193,9 +204,9 @@ rows = load_dataset("tailot/struc-stratum", "corpus", split="train")
193
  print(rows[0])
194
  ```
195
 
196
- This is the same file `tools/ask.py --corpus` walks over, and `lgstratum/corpus.py` plus
197
- `tests/test_corpus.py` read it to grade the stratum against the gold. Graded on the checkout this folder was published from: 72 of 72
198
- rows agree with what they expect.
199
 
200
  ## 13. Rights
201
 
@@ -232,7 +243,7 @@ def local_files() -> List[Path]:
232
  Whole path components named `.git`, `__pycache__` or `.pytest_cache` are cut at any depth, which is
233
  what keeps the compiled copies of the modules out of the published tree. A file whose own name
234
  starts with an underscore is working notes and is not published either, with one exception:
235
- `lgstratum/__init__.py`, the package marker, shares that prefix by the convention of Python rather
236
  than by being a note, and dropping it would publish a tree whose library cannot be imported as a
237
  package. A file named `.gitignore` is content for the same reason.
238
  """
@@ -245,7 +256,7 @@ def local_files() -> List[Path]:
245
  continue
246
  if ".git" in relative.parts:
247
  continue
248
- if path.name.startswith("_") and not (path.name == "__init__.py" and path.parent.name == "lgstratum"):
249
  continue
250
  out.append(path)
251
  return out
 
31
  ROOT = Path(__file__).resolve().parents[1]
32
  sys.path.insert(0, str(ROOT))
33
 
34
+ from lingologos_stratum import corpus # noqa: E402 (after the path fix above)
35
 
36
  REPO = "tailot/struc-stratum"
37
  EXPECTED_FILES = 67 # the staged tree: this README is uploaded as the card under the same name
 
75
  "sibling folder `datasets/struc`, which stays exactly as it is. Only the standard library and\n"
76
  "`z3-solver` are required; the tests need `pytest`.",
77
  "This dataset is the `struc-stratum/` folder of the LingoLOGOS project published as it stands: 67 files,\n"
78
+ "code and data together, plus this card in place of their README. Only the standard library and `z3-solver`\n"
79
+ "are required, and `pytest` for the tests; both are named in `requirements.txt`. Every command below is\n"
80
+ "written from inside the folder. The structures are not part of this dataset: they live in the `struc`\n"
81
+ "bundle, published at https://huggingface.co/datasets/tailot/lingologos-struc, and section 10 says how to\n"
82
+ "point this folder at a copy of it.",
83
  ),
84
  (
85
+ "The math\n"
86
+ "stratum had a level three that no translation could reach; here there is no level to reach, and the\n"
87
  "rule still says what a person is shown.",
88
+ "The\n"
89
+ "`math-stratum` bundle of this project, at https://huggingface.co/datasets/tailot/math-stratum, had a level\n"
90
+ "three that no translation could reach; here there is no level to reach, and the rule still says what a\n"
91
+ "person is shown.",
92
  ),
93
  (
94
  "## 10. Using this folder as an external dataset",
 
99
  "this content: 67 files (plus the card that replaces this README on the hub), 72 questions in one corpus\n"
100
  "file, the six lexicons, the eight node definitions, the two readers, the decision rule of section 1, the\n"
101
  "corpus grading and fault results under `results/`, and the fault catalogue of section 6.",
102
+ "This dataset is 67 files plus this card: 72 questions in one corpus file, the six lexicons, the eight node\n"
103
+ "definitions, the two readers, the decision rule of section 1, the corpus grading and fault results under\n"
104
+ "`results/`, and the fault catalogue of section 6. To answer anything it needs the `struc` bundle: download\n"
105
+ "https://huggingface.co/datasets/tailot/lingologos-struc somewhere, set `LINGOLOGOS_STRATUM_STRUC_ROOT` to\n"
106
+ "that copy, and the `invoker` node calls `tools/ask.py` there as a separate process, which is the only door\n"
107
+ "through which this bundle ever reaches a solver. Inside a LingoLOGOS checkout the folder sits at\n"
108
+ "`datasets/struc-stratum`, finds `datasets/struc` by itself, and needs `src/lingologos_orchestrator`\n"
109
+ "importable for the two end to end sessions of section 8.",
110
  ),
111
  (
112
+ "invariant tests call the tools of the structures topology as subprocesses, and the whole\n"
113
+ "suite passed in 2 minutes on this checkout.",
114
+ "invariant tests call the tools of the structures topology as subprocesses, which here means\n"
115
+ "a copy of the `struc` dataset named by `LINGOLOGOS_STRATUM_STRUC_ROOT` (section 10); the suite passed in 2\n"
116
+ "minutes inside a LingoLOGOS checkout, and the two end to end tests skip on their own when\n"
117
+ "`lingologos_orchestrator` is not importable.",
118
  ),
119
  (
120
+ "On the hub this\n"
121
+ "README is rewritten as a dataset card whose sections 1 to 10 keep the wording and numbers of this file,\n"
122
+ "and sections 11 to 14 are added there for readers who met the bundle on the hub rather than in a checkout:\n"
123
+ "the fields of the corpus file, how to load it, rights and citation. Every file but this README was\n"
124
+ "compared by sha256 after the upload: the hub holds one object per file of this folder plus\n"
125
+ "`.gitattributes`, so the remote count is one above the number `tools/publish_dataset.py` prints here.",
126
+ "This card keeps\n"
127
+ "the wording and numbers of the README of the folder in its sections 1 to 10, and adds sections 11 to 14\n"
128
+ "for readers who met the bundle here rather than in a checkout: the fields of the corpus file, how to load\n"
129
+ "it, rights and citation. Every file of the upload, this card among them, was compared by sha256\n"
130
+ "afterwards: the hub holds one object per file of the folder plus `.gitattributes`, so the remote count is\n"
131
+ "one above the number the publisher prints.",
132
  ),
133
  (
134
+ "Like\n"
135
+ "the `struc` and `math-stratum` folders, this folder is ignored by the git repository of the project: what\n"
136
+ "the project carries is the link in the table of published resources at the top of the repository README,\n"
137
+ "and the documentation of the asset lives in this README and in the card, not in\n"
138
+ "`doc/TECHNICAL_DOCUMENTATION.md`.",
139
+ "What\n"
140
+ "the LingoLOGOS repository carries is the link to this dataset in the table of published resources at the\n"
141
+ "top of its README; the documentation of the asset lives here, in this card, and not in the technical\n"
142
+ "documentation of the project. `tools/publish_dataset.py` in the folder of the project republishes a\n"
143
+ "changed working copy with the token\n"
144
+ "taken from an environment variable.",
145
  ),
146
  ]
147
 
 
204
  print(rows[0])
205
  ```
206
 
207
+ This is the same file `tools/ask.py --corpus` walks over, and `lingologos_stratum/corpus.py` plus
208
+ `tests/test_corpus.py` read it to grade the stratum against the gold. Graded on the checkout this folder
209
+ was published from: 72 of 72 rows agree with what they expect.
210
 
211
  ## 13. Rights
212
 
 
243
  Whole path components named `.git`, `__pycache__` or `.pytest_cache` are cut at any depth, which is
244
  what keeps the compiled copies of the modules out of the published tree. A file whose own name
245
  starts with an underscore is working notes and is not published either, with one exception:
246
+ `lingologos_stratum/__init__.py`, the package marker, shares that prefix by the convention of Python rather
247
  than by being a note, and dropping it would publish a tree whose library cannot be imported as a
248
  package. A file named `.gitignore` is content for the same reason.
249
  """
 
256
  continue
257
  if ".git" in relative.parts:
258
  continue
259
+ if path.name.startswith("_") and not (path.name == "__init__.py" and path.parent.name == "lingologos_stratum"):
260
  continue
261
  out.append(path)
262
  return out