Datasets:
Modalities:
Text
Formats:
json
Size:
< 1K
Tags:
multilingual
structural-engineering
natural-language-to-formal-language
multi-agent-systems
benchmark
conversational-interfaces
drop removed files
Browse filesFiles changed (16)
- lgstratum/__init__.pyDeleted-20
- lgstratum/agents.pyDeleted-291
- lgstratum/canonical.pyDeleted-664
- lgstratum/compare.pyDeleted-360
- lgstratum/corpus.pyDeleted-82
- lgstratum/coverage.pyDeleted-108
- lgstratum/decide.pyDeleted-168
- lgstratum/faults.pyDeleted-174
- lgstratum/invoker.pyDeleted-125
- lgstratum/lexicon.pyDeleted-346
- lgstratum/pipeline.pyDeleted-118
- lgstratum/protocol.pyDeleted-79
- lgstratum/read_a.pyDeleted-290
- lgstratum/read_b.pyDeleted-310
- lgstratum/render.pyDeleted-141
- lgstratum/segment.pyDeleted-242
1234567891011121314151617181920"""The library of the struc-stratum topology.
The struc-stratum is the conversational stratum of the structures topology: it accepts a problemwritten in one of six language varieties, reads it into one sentence of the structures language,hands that sentence to the structures topology as a separate process, and presents the verdict ofthat topology back in the language the user wrote in.
Two words carry the whole design:
* **reading**: what the stratum does is a reading, never a proof. The certainty of a reading is not verifiable, because the space of natural language sentences is not. The stratum therefore never raises the assurance the structures topology reported, and every stage of the reading can only take verdicts away.* **coverage**: the multilingual layer is a documented fragment, in the same spirit as the fragment of the structures language. Anything outside it abstains with a question in the language of the user, and never guesses."""
__all__ = ["agents", "canonical", "compare", "corpus", "coverage", "decide", "faults", "invoker", "lexicon", "pipeline", "protocol", "read_a", "read_b", "render", "segment"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291"""The eight nodes of the stratum, one step function each.
Every node has exactly one job and one claim of its own, and no node is allowed to conclude what thenext one is supposed to check. The chain is the same shape the structures topology runs, only movedone level up: two independent readers instead of two independent formalizers, an equivalence nodeinstead of the equivalence checker, a coverage node that counts the numbers the user wrote, aninvoker that hands the agreed sentence to the structures topology as a separate process, a boundarywhere that verdict enters this stratum, an adversary that re-derives what the others asserted, and anarbiter that decides and answers in the user's language.
reader_a surface reading: the words of the variety, in the order they appear reader_b joint reading: which marker of the structures language sits in which gap of the frame equivalence are the two readings one structure? SMT2 answers, text identity is a shortcut coverage did the readings keep every number the user wrote? invoker call the structures topology, in another process, on one sentence boundary the structures verdict enters this stratum here, and only here adversary re-derive the cross-channel checks and the cap the previous nodes implied arbiter decide, cap the assurance, answer in the language of the user
The invariant every node here obeys, and which the last three nodes each write down as SMT2 so thereferee of the orchestrator refutes its negation: the assurance this stratum shows is``min(assurance of the structures topology, ceiling of the reading)``, and the ceiling is never abovethe top level of the partner. A node may lower what the user sees; none may raise it."""
from typing import Any, Dict, List, Tuple
from . import canonical, compare, coverage, decide, faults, invoker, protocol, read_a, read_b, render
ORDER = ("reader_a", "reader_b", "equivalence", "coverage", "invoker", "boundary", "adversary", "arbiter")
def _ast(dossier: Dict[str, Any]) -> str: """One ASCII line describing the shape of the dossier, for the abstractSyntaxTree field.""" def status_of(key: str) -> str: part = dossier.get(key) if not isinstance(part, dict): return "absent" return str(part.get("status") or part.get("state") or part.get("kind") or "present")
return "Stratum(lang=%s, a=%s, b=%s, equiv=%s, cover=%s, struc=%s, final=%s)" % ( dossier.get("lang", "?"), status_of("reading_a"), status_of("reading_b"), "same" if (dossier.get("compare") or {}).get("same") else "no", "ok" if (dossier.get("coverage") or {}).get("ok") else "no", (dossier.get("struc") or {}).get("status", "absent"), (dossier.get("final") or {}).get("state", "absent"), )
def _cap_claim(shown: int, ceiling: int) -> Tuple[List[str], List[str], str]: """SMT2 for ``this node raised nothing``: the strict excess over the ceiling is refuted.""" decls = ["(declare-const shown Real)", "(declare-const ceiling Real)"] asserts = ["(assert (= shown %d))" % int(shown), "(assert (= ceiling %d))" % int(ceiling), "(assert (> shown ceiling))"] return decls, asserts, "unsat"
def _reader_claim(reading: Dict[str, Any], question: str) -> Tuple[List[str], List[str], str]: """A reader claims one thing only: it dropped no number the user wrote.""" step = compare.keeps(reading, question) return step["declarations"], step["assertions"], step["claimed"]
def _apply_reader_fault(agent: str, reading: Dict[str, Any]) -> None: """Corrupt a reading on purpose, for the ablation experiments: never in a normal session.""" if not reading.get("kind") or reading.get("status") != "READ": return for kind in faults.READER_FAULTS: if not faults.has(agent, kind): continue order = list(reading.get("variant") or []) or list(canonical.slots_for(str(reading["kind"]))) slots, changed = faults.mutate_reading(agent, str(reading["kind"]), dict(reading.get("slots") or {}), order) if not changed: continue faults.fire(agent, kind) try: reading["sentence"] = canonical.print_sentence(str(reading["kind"]), slots) reading["slots"] = slots reading["fault"] = kind except canonical.ReadingError: reading["sentence"] = "" reading["status"] = "NOT COVERED" reading["notes"].append({"reason": "broken_form", "kind": reading["kind"], "detail": kind}) return
def _reading_node(agent: str, reader: Any, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]: """Shared body of the two reader nodes: read the question, keep the reading, claim the numbers.""" dossier, turn, tick, rcpt = protocol.start(incoming) question = str(dossier.get("question", "")) lang = str(dossier.get("lang") or "") direct = canonical.direct(question) if direct is not None: dossier["reading_direct"] = direct reading = direct else: reading = reader.read(lang, question) _apply_reader_fault(node_id, reading) dossier[agent] = reading decls, asserts, claimed = _reader_claim(reading, question) summary = "%s: %s %s" % (node_id, reading.get("status"), reading.get("sentence") or "") return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
def step_reader_a(incoming: Dict[str, Any], node_id: str = "reader_a") -> Dict[str, Any]: """Reader A: surface patterns of the variety, reading left to right.""" return _reading_node("reading_a", read_a, incoming, node_id)
def step_reader_b(incoming: Dict[str, Any], node_id: str = "reader_b") -> Dict[str, Any]: """Reader B: the frame of the problem kind and the markers of the language sitting in its gaps.""" return _reading_node("reading_b", read_b, incoming, node_id)
def step_equivalence(incoming: Dict[str, Any], node_id: str = "equivalence") -> Dict[str, Any]: """Are the two readings one structure? The answer carries the SMT2 program that proves it.""" dossier, turn, tick, rcpt = protocol.start(incoming) if faults.has(node_id, "rubber_stamp"): faults.fire(node_id, "rubber_stamp") first, second = dossier.get("reading_a") or {}, dossier.get("reading_a") or {} else: first, second = dossier.get("reading_a") or {}, dossier.get("reading_b") or {} direct = dossier.get("reading_direct") if direct is not None: first, second = direct, dict(dossier.get("reading_b") or direct) comparison = compare.equivalence(first, second) dossier["compare"] = comparison if first.get("sentence") and (comparison["same"] or not second.get("sentence")): dossier["sent"] = comparison["left"] or str(first["sentence"]) elif second.get("sentence") and not first.get("sentence"): dossier["sent"] = comparison["right"] or str(second["sentence"]) summary = "equivalence: %s (%s)" % ("same" if comparison["same"] else "not the same structure", comparison["why"]) return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), comparison["declarations"], comparison["assertions"], comparison["claimed"])
def step_coverage(incoming: Dict[str, Any], node_id: str = "coverage") -> Dict[str, Any]: """Did the readings keep every number the user wrote, and in the same multiset?""" dossier, turn, tick, rcpt = protocol.start(incoming) readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}] if dossier.get("reading_direct") is not None: readings = [dossier["reading_direct"], dossier.get("reading_b") or {}] if faults.has(node_id, "rubber_stamp"): faults.fire(node_id, "rubber_stamp") claim = {"ok": True, "wrote": [], "kept": [], "missing": [], "added": [], "declarations": ["(declare-const wrote_0 Real)"], "assertions": ["(assert (= wrote_0 0))"], "claimed": "sat"} else: claim = coverage.coverage_claim(str(dossier.get("question", "")), [r for r in readings if r]) dossier["coverage"] = claim summary = "coverage: %s (%d numbers)" % ("kept" if claim["ok"] else "not kept", len(claim["wrote"])) return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), claim["declarations"], claim["assertions"], claim["claimed"])
def step_invoker(incoming: Dict[str, Any], node_id: str = "invoker") -> Dict[str, Any]: """Ask the structures topology, in its own process, about the sentence the readers agreed on.""" dossier, turn, tick, rcpt = protocol.start(incoming) sentence = str(dossier.get("sent") or "") if not sentence: dossier["struc"] = invoker.unavailable("no sentence was agreed on") summary = "invoker: nothing to ask the structures topology" return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), ["(declare-const asked Real)"], ["(assert (= asked 0))"], "sat") verdict = invoker.solve(sentence) dossier["struc"] = verdict # Both sides counted after the partner's parse: the topology restates a problem in its own normal # form, so a sentence and its echo are the same numbers when the parse says so, not when the two # texts happen to be alike. The claim is the conjunction of those element equalities, and the # status this node writes down is satisfiable exactly when those equalities hold. wrote = compare.to_fractions(compare.problem_numbers(canonical.tidy(sentence))) echo = compare.to_fractions(compare.problem_numbers(canonical.tidy(str(verdict.get("problem_struc") or "")))) decls, asserts = compare.elementwise(wrote, echo, "asked") ok = bool(wrote) and wrote == echo if not decls: asserts = ["(assert (= 1 1))"] if ok else ["(assert false)"] summary = "invoker: %s (%s)" % (verdict.get("status"), verdict.get("answer_text") or "no answer") return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, "sat" if ok else "unsat")
def step_boundary(incoming: Dict[str, Any], node_id: str = "boundary") -> Dict[str, Any]: """The structures verdict enters this stratum here; the echo it carries is checked, not trusted.""" dossier, turn, tick, rcpt = protocol.start(incoming) agreed = str(dossier.get("sent") or "") # The echo is checked against the sentence that was agreed on, which may come from either reader: # a single reading is still the sentence this stratum sent to the topology. reading = {"sentence": agreed} if agreed else (dossier.get("reading_a") or dossier.get("reading_direct") or {}) struc_verdict = dict(dossier.get("struc") or {}) echo = str(struc_verdict.get("problem_struc") or "") if echo: matches = coverage.echo_matches(reading, struc_verdict) asked = compare.to_fractions(compare.problem_numbers(canonical.tidy(agreed))) echoed = compare.to_fractions(compare.problem_numbers(canonical.tidy(echo))) decls, asserts = compare.elementwise(asked, echoed, "echo") ok = bool(asked) and asked == echoed if not decls: asserts = ["(assert (= 1 1))"] if ok else ["(assert false)"] claimed = "sat" if ok else "unsat" else: # The topology answered no sentence at all: there is nothing to compare, and the honest claim # is the empty one, which is satisfiable. A node that wanted to look busy here would be # asserting something it has no evidence about. matches = True decls, asserts, claimed = [], ["(assert (= 1 1))"], "sat" if faults.has(node_id, "tamper_struc") and echo: tampered, changed = faults.mutate_sentence(node_id, echo) if changed: faults.fire(node_id, "tamper_struc") struc_verdict["problem_struc"] = tampered struc_verdict["fault"] = "tamper_struc" dossier["struc"] = struc_verdict dossier["echo_ok"] = bool(matches) summary = "boundary: %s echoed=%s" % (struc_verdict.get("status"), "yes" if matches else "no") return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
def step_adversary(incoming: Dict[str, Any], node_id: str = "adversary") -> Dict[str, Any]: """Re-derive what the previous nodes asserted, and write the cap as an inequality to refute.""" dossier, turn, tick, rcpt = protocol.start(incoming) readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}] if dossier.get("reading_direct") is not None: readings = [dossier["reading_direct"], dossier.get("reading_b") or {}] comparison = dossier.get("compare") struc_verdict = dossier.get("struc") or {} cover = dossier.get("coverage") if faults.has(node_id, "rubber_stamp"): faults.fire(node_id, "rubber_stamp") echo_ok = True else: echo_ok = coverage.echo_matches(readings[0], struc_verdict) if struc_verdict.get("problem_struc") else True for other in readings[1:]: if other.get("sentence") and not coverage.echo_matches(other, struc_verdict): echo_ok = False dossier["echo_ok"] = bool(echo_ok) state = decide.state_of(readings, comparison, cover, struc_verdict if struc_verdict.get("status") else None, dossier.get("reading_direct"), echo_ok) ceiling = decide.CEILING[state] shown = min(ceiling, int(struc_verdict.get("assurance", 0) or 0)) dossier["adversary"] = {"echo_ok": bool(echo_ok), "ceiling": ceiling, "shown": shown, "struc_assurance": int(struc_verdict.get("assurance", 0) or 0)} decls, asserts, claimed = _cap_claim(shown, ceiling) summary = "adversary: ceiling %d, shown %d, echo %s" % (ceiling, shown, "ok" if echo_ok else "mismatch") return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
def step_arbiter(incoming: Dict[str, Any], node_id: str = "arbiter") -> Dict[str, Any]: """Decide, cap, and answer in the language the user wrote in.""" dossier, turn, tick, rcpt = protocol.start(incoming) final = decide.decide(dossier) if faults.has(node_id, "force_assurance"): faults.fire(node_id, "force_assurance") final = decide.raise_assurance(final, 3) dossier["final"] = final dossier["reply"] = render.reply(dossier, final) ceiling = int(final.get("ceiling", 0) or 0) decls, asserts, claimed = _cap_claim(int(final.get("assurance", 0) or 0), ceiling) summary = "arbiter: %s (assurance %d) %s" % (final["state"], final["assurance"], final["answer"] or "") return protocol.out(node_id, rcpt, turn, tick, dossier, summary, _ast(dossier), decls, asserts, claimed)
STEPS = { "reader_a": step_reader_a, "reader_b": step_reader_b, "equivalence": step_equivalence, "coverage": step_coverage, "invoker": step_invoker, "boundary": step_boundary, "adversary": step_adversary, "arbiter": step_arbiter,}
def run_step(role: str, incoming: Dict[str, Any], node_id: str) -> Dict[str, Any]: """Run one role, containing any unexpected exception as a crash entry in the dossier.
A node that crashes must not stop the session: the arbiter then reports the state NONE with zero assurance, so the user is never left with a half-built answer and never with an invented one either. """ try: return STEPS[role](incoming, node_id) except Exception as exc: # noqa: BLE001 - containment is the whole point of this wrapper dossier, turn, tick, rcpt = protocol.start(incoming) dossier.setdefault("crash", {})[role] = "%s: %s" % (type(exc).__name__, str(exc)[:120]) return protocol.envelope(node_id, rcpt, turn, tick, "%s crashed" % role, "Crashed", dossier, [], ["(assert true)"], "sat")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664"""The canonical sentence of the stratum: one sentence of the structures language.
The two readers do not compare their own wording with each other. Each of them turns the sentenceof a human language into **one text of the language the structures topology speaks**, and theequivalence node is what decides whether the two texts are the same problem. This module owns thatlanguage: the eight kinds of question, the order of the slots of each kind, the six blocks of aframe, the two spellings of a section, and the exact spelling of a number.
The language is not invented here. It is the language the sibling topology parses -- the same words(``frame``, ``nodes``, ``supports``, ``udl``, ``vonmises``), the same block order, the same bracketnotation, the same rationals -- and this module is a *shape* check of it, not a second semantics: itverifies that a sentence has the shape in which the structures topology reads a problem, and itnothing about a structure. Deciding a structure belongs to those thirteen nodes.
Why the check exists at all: the sentence a reader prints is the sentence the stratum hands to thestructures topology, and the echo of that topology is compared with it. A reading that dropped abracket, reordered two blocks or wrote ``3`` where the block wanted four numbers would otherwisetravel as if it were a reading, and the answer it produced would look like an answer to the questionthe person asked.
classify frame nodes [ 1 0 0 ; 2 2 0 ] members [ 1 1 2 ] props [ 1 210000000 1/5 2/1875 ] supports [ 1 pin ; 2 roller 0 1 ] loads [ member 1 udl 0 -15 ] cut member 1 at 1 <frame> peak moment <frame> deflect node 2 vertical <frame> properties section rect 1/5 2/5 verify bending member 1 at 2 section rect 1/5 2/5 limit 16000 <frame> euler ends pinned pinned length 21/10 modulus 210000000 section rect 1/10 1/10
Numbers are written the way the structures topology writes them: an exact rational, ``75/2`` and not``37.5``. That normalisation is the reason a person may write ``0.5`` in their own sentence and stillbe read as the same problem: the value is what is kept, not the spelling."""
import refrom fractions import Fractionfrom typing import Any, Dict, List, Optional, Sequence, Tuple
FRAME_WORD = "frame"BLOCKS = ("nodes", "members", "props", "supports", "loads", "hinges")SUPPORT_KINDS = ("fixed", "pin", "roller")LOAD_OWNERS = ("node", "member")LOAD_KINDS = ("force", "couple", "udl", "point")VERIFY_MODES = ("bending", "shear", "vonmises")DIRECTIONS = ("vertical", "horizontal", "rotation")END_KINDS = ("pinned", "fixed", "free")QUANTITIES = ("moment", "shear", "axial")SECTION_FORMS = ("rect", "shapes")
# The five sets of end conditions the manual of the structures topology knows, and nothing else.EULER_LENGTHS = (("pinned", "pinned"), ("fixed", "free"), ("fixed", "fixed"), ("fixed", "pinned"), ("pinned", "fixed"))
KINDS = ("classify", "reactions", "cut", "peak", "deflect", "properties", "verify", "euler")
# One template per way of asking, with the slots in the order the structures language prints them.# ``deflect`` has two shapes because the topology has two: a node moves, or a section of a member# moves at an abscissa along it.TEMPLATES: Dict[str, List[Tuple[Tuple[str, ...], str]]] = { "classify": [(("F",), "classify {F}")], "reactions": [(("F",), "reactions {F}")], "cut": [(("M", "P", "F"), "cut member {M} at {P} {F}")], "peak": [(("Q", "F"), "peak {Q} {F}")], "deflect": [(("N", "D", "F"), "deflect node {N} {D} {F}"), (("M", "P", "D", "F"), "deflect member {M} at {P} {D} {F}")], "properties": [(("S",), "properties section {S}")], "verify": [(("V", "M", "P", "S", "L", "F"), "verify {V} member {M} at {P} section {S} limit {L} {F}")], "euler": [(("E1", "E2", "L", "MOD", "S"), "euler ends {E1} {E2} length {L} modulus {MOD} section {S}")],}
# Which slot of which kind holds what. ``num`` is a number, ``word`` is one of the closed sets of# the language, ``frame`` and ``section`` are regions written in the bracket notation.SLOT_KIND: Dict[str, Dict[str, str]] = { "classify": {"F": "frame"}, "reactions": {"F": "frame"}, "cut": {"M": "num", "P": "num", "F": "frame"}, "peak": {"Q": "quantity", "F": "frame"}, "deflect": {"N": "num", "M": "num", "P": "num", "D": "direction", "F": "frame"}, "properties": {"S": "section"}, "verify": {"V": "mode", "M": "num", "P": "num", "S": "section", "L": "num", "F": "frame"}, "euler": {"E1": "end", "E2": "end", "L": "num", "MOD": "num", "S": "section"},}
# The fixed words of the templates: the joints a sentence of this language is built out of, and the# only way a reader can tell which number is the abscissa of a cut and which one is the limit of a# check. test_readers checks that every fixed word of every template is listed here.JOINTS = ("at", "ends", "length", "limit", "modulus", "node", "member", "section")
# Every word of the structures language, so that a sentence made only of these words and numbers is# a sentence already written in it: the stratum calls that case PASSTHROUGH and translates nothing.WORDS = frozenset( (FRAME_WORD,) + BLOCKS + SUPPORT_KINDS + LOAD_OWNERS + LOAD_KINDS + VERIFY_MODES + DIRECTIONS + END_KINDS + QUANTITIES + SECTION_FORMS + JOINTS + KINDS)
class ReadingError(Exception): """A sentence of the structures language that this bundle cannot write or cannot check."""
# ---------------------------------------------------------------------------# Numbers# ---------------------------------------------------------------------------_NUMBER = re.compile(r"[-+]?(?:\d+(?:[.,]\d+)?(?:/[+-]?\d+(?:[.,]\d+)?)?|[.,]\d+)")
def tidy(text: str) -> str: """Collapse every run of spaces and trim: two sentences are compared as texts, not as layout.""" return re.sub(r"\s+", " ", str(text or "")).strip()
def value(token: str) -> str: """One number as the structures topology writes it: an exact rational, integers without denominator.
``0.5`` and ``1/2`` reach the same text, and so do ``+3`` and ``3``, and so does the Italian ``1,5``, which writes the same number with the comma its own notation uses. A token that is not a number is an error, because a slot that wanted a number and got a word is a reading to refuse. """ text = str(token).strip().replace(",", ".") if not _NUMBER.fullmatch(text): raise ReadingError("not a number: %r" % text) try: number = Fraction(text) except ValueError: raise ReadingError("not a number: %r" % text) return str(number)
def numbers(text: str) -> List[str]: """Every number of a sentence, in order, as a value.
Used to count what the person wrote against what a reading kept. Counting *values* and not digit strings is what lets a sentence written ``0.5`` be kept as ``1/2`` without the count of literals turning that into a dispute. """ out: List[str] = [] for match in _NUMBER.finditer(str(text or "")): try: out.append(value(match.group(0))) except ReadingError: continue return out
def sorted_numbers(text: str) -> List[str]: """The same values ordered, so a reordering of slots is not read as a change of problem.""" return sorted(numbers(text), key=lambda item: (Fraction(item), item))
# ---------------------------------------------------------------------------# Tokenising the bracket notation# ---------------------------------------------------------------------------_SPLIT = re.compile(r"(\[|\]|;)")_TOKEN = re.compile(r"\[|\]|;|" + _NUMBER.pattern + r"|[^\s\[\];]+")
def tokens(text: str) -> List[str]: """The bracket notation as tokens: brackets and semicolons alone, numbers and words as themselves.""" return _TOKEN.findall(tidy(text)) or []
def _want_number(part: Sequence[str], index: int, what: str) -> Tuple[str, int]: if index >= len(part) or not _NUMBER.fullmatch(part[index]): raise ReadingError("%s wants a number at %r" % (what, part[index:index + 2])) return value(part[index]), index + 1
def _want_word(part: Sequence[str], index: int, allowed: Sequence[str], what: str) -> Tuple[str, int]: if index >= len(part) or part[index] not in allowed: raise ReadingError("%s wants one of %s, found %r" % (what, "/".join(allowed), part[index:index + 1])) return part[index], index + 1
# ---------------------------------------------------------------------------# A frame# ---------------------------------------------------------------------------def _entry_tokens(block: str, piece: Sequence[str]) -> List[str]: """One entry of one block, checked against the arity the structures language gives it.""" out: List[str] = [] index = 0 if block == "nodes": for what in ("node id", "abscissa", "ordinate"): out.append(_want_number(piece, index, what)[0]) index += 1 elif block == "members": for what in ("member id", "first node", "second node"): out.append(_want_number(piece, index, what)[0]) index += 1 elif block == "props": for what in ("member id", "modulus", "area", "inertia"): out.append(_want_number(piece, index, what)[0]) index += 1 elif block == "supports": out.append(_want_number(piece, index, "node id")[0]) index += 1 kind, index = _want_word(piece, index, SUPPORT_KINDS, "a support") out.append(kind) if kind == "roller": for what in ("normal abscissa", "normal ordinate"): out.append(_want_number(piece, index, what)[0]) index += 1 elif block == "loads": owner, index = _want_word(piece, index, LOAD_OWNERS, "a load") out.append(owner) out.append(_want_number(piece, index, "target id")[0]) index += 1 kind, index = _want_word(piece, index, LOAD_KINDS, "a load") out.append(kind) if (owner, kind) == ("node", "force"): how = ("abscissa", "ordinate") elif (owner, kind) == ("node", "couple"): how = ("couple",) elif (owner, kind) == ("member", "udl"): how = ("abscissa", "ordinate") elif (owner, kind) == ("member", "point"): how = ("position", "abscissa", "ordinate") else: how = ("position", "couple") for what in how: out.append(_want_number(piece, index, what)[0]) index += 1 elif block == "hinges": out.append(_want_number(piece, index, "hinged node")[0]) index += 1 else: raise ReadingError("unknown block %s" % block) if index != len(piece): raise ReadingError("the %s entry %r has words or numbers left over" % (block, list(piece))) return out
def frame(text: str) -> str: """The frame of a problem, checked and written the way the structures topology writes it.""" parts = tokens(text) if not parts or parts[0] != FRAME_WORD: raise ReadingError("a frame starts with the word frame") cursor = 1 seen: List[str] = [] for block in BLOCKS: if cursor < len(parts) and parts[cursor] == block: cursor += 1 if cursor >= len(parts) or parts[cursor] != "[": raise ReadingError("the block %s has no brackets" % block) close = _closing(parts, cursor) entries: List[str] = [] for piece in _segments(parts, cursor + 1, close): entries.append(" ".join(_entry_tokens(block, piece))) if not entries and block != "hinges": raise ReadingError("the block %s is empty" % block) seen.append("%s [ %s ]" % (block, " ; ".join(entries))) cursor = close + 1 elif block not in ("loads", "hinges"): raise ReadingError("the frame has no %s block" % block) if cursor != len(parts): raise ReadingError("the frame ends with %r" % parts[cursor:cursor + 2]) return "%s %s" % (FRAME_WORD, " ".join(seen))
def section(text: str) -> str: """The section of a problem, in one of the two spellings the structures language has.""" parts = tokens(text) if not parts: raise ReadingError("a section is missing") if parts[0] == "rect": if len(parts) != 3: raise ReadingError("rect wants a width and a height") return "rect %s %s" % (_want_number(parts, 1, "width")[0], _want_number(parts, 2, "height")[0]) if parts[0] == "shapes": if len(parts) < 2 or parts[1] != "[": raise ReadingError("shapes has no brackets") close = _closing(parts, 1) shapes: List[str] = [] for piece in _segments(parts, 2, close): if not piece or piece[0] != "rect" or len(piece) != 4: raise ReadingError("a shape of the section must be rect with three numbers") shapes.append("rect %s %s %s" % tuple( _want_number(piece, at, what)[0] for at, what in ((1, "width"), (2, "height"), (3, "centre")))) if not shapes: raise ReadingError("the section has no rectangle") if close + 1 != len(parts): raise ReadingError("the section ends with %r" % parts[close + 1:close + 3]) return "shapes [ %s ]" % " ; ".join(shapes) raise ReadingError("a section is rect or shapes")
def _closing(parts: Sequence[str], at: int) -> int: depth = 0 for index in range(at, len(parts)): if parts[index] == "[": depth += 1 elif parts[index] == "]" and depth == 1: return index raise ReadingError("a bracket is never closed")
def _segments(parts: Sequence[str], start: int, stop: int) -> List[List[str]]: """The pieces between semicolons inside one pair of brackets.""" out: List[List[str]] = [] piece: List[str] = [] for index in range(start, stop): if parts[index] == ";": out.append(piece) piece = [] else: piece.append(parts[index]) if piece: out.append(piece) return [item for item in out if item]
# ---------------------------------------------------------------------------# Printing and reading a whole sentence# ---------------------------------------------------------------------------def slots_for(kind: str) -> Tuple[str, ...]: """The slots of the first template of a kind, in the order the language prints them.""" if kind not in TEMPLATES: raise ReadingError("unknown kind %s" % kind) return TEMPLATES[kind][0][0]
def template_for(kind: str, slots: Dict[str, str]) -> Tuple[Tuple[str, ...], str]: """The template of a kind the filled slots fit, or a refusal naming the slots that are missing.""" if kind not in TEMPLATES: raise ReadingError("unknown kind %s" % kind) for names, text in TEMPLATES[kind]: if all(str(slots.get(name, "")).strip() for name in names): return names, text raise ReadingError("%s is missing one of %s" % (kind, "/".join(TEMPLATES[kind][0][0])))
def fill(kind: str, slots: Dict[str, str]) -> str: """Print one sentence of the structures language from the slots a reader filled.""" names, text = template_for(kind, slots) filled: Dict[str, str] = {} for name in names: raw = tidy(str(slots.get(name, ""))) what = SLOT_KIND[kind][name] if what == "num": filled[name] = value(raw) elif what == "frame": filled[name] = frame(raw) elif what == "section": filled[name] = section(raw) elif what == "quantity": filled[name] = _checked(raw, QUANTITIES, "a quantity of the diagram") elif what == "direction": filled[name] = _checked(raw, DIRECTIONS, "a direction of the displacement") elif what == "mode": filled[name] = _checked(raw, VERIFY_MODES, "a check of strength") elif what == "end": filled[name] = _checked(END_FROM_VALUE.get(raw, raw), END_KINDS, "a condition of the end of the column") else: raise ReadingError("slot %s of %s has no kind" % (name, kind)) if kind == "euler" and (filled["E1"], filled["E2"]) not in EULER_LENGTHS: raise ReadingError("the ends %s %s are not one of the five of the manual" % (filled["E1"], filled["E2"])) return tidy(text.format(**filled))
def _checked(raw: str, allowed: Sequence[str], what: str) -> str: if raw not in allowed: raise ReadingError("%s must be one of %s, found %r" % (what, "/".join(allowed), raw)) return raw
def direct(text: str) -> Optional[Dict[str, Any]]: """A sentence already written in the structures language, read without translating anything.
This is the only place the stratum parses its own language from end to end, and it exists for one case: the person wrote the structures language themselves. Then there is no translation to check, and the session says so (PASSTHROUGH) instead of pretending two readers worked. ``None`` means the text is not that language, which is the normal case. """ parts = tokens(text) if not parts or parts[0] not in KINDS: return None if any(piece not in WORDS for piece in parts if piece not in ("[", "]", ";") and not _NUMBER.fullmatch(piece)): return None kind = parts[0] try: slots = _slots_of(kind, parts[1:]) except ReadingError: return None if slots is None: return None try: sentence = fill(kind, slots) except ReadingError: return None if tidy(sentence) != tidy(text): return None return {"status": "READ", "kind": kind, "sentence": sentence, "slots": slots, "notes": [], "literals": numbers(sentence), "direct": True}
def _slots_of(kind: str, parts: Sequence[str]) -> Optional[Dict[str, str]]: """The slots of a kind, read out of the words of a sentence of the structures language.
Written as one branch per kind, the way the structures topology parses its own head. A template loop would be shorter and would hide the one thing that has to be explicit here: where a frame or a section stops, because the words of a block are also words of the language. """ try: if kind in ("classify", "reactions"): return {"F": _region(parts, 0)[0]} if kind == "cut": at = _expect(parts, 0, "member") member = parts[at] at = _expect(parts, at + 1, "at") place = parts[at] region, end = _region(parts, at + 1) if end != len(parts): return None return {"M": member, "P": place, "F": region} if kind == "peak": region, end = _region(parts, 1) if end != len(parts): return None return {"Q": parts[0], "F": region} if kind == "deflect": if parts[:1] == ["node"]: region, end = _region(parts, 3) if end != len(parts): return None return {"N": parts[1], "D": parts[2], "F": region} if parts[:1] == ["member"]: at = _expect(parts, 2, "at") region, end = _region(parts, at + 2) if end != len(parts): return None return {"M": parts[1], "P": parts[at], "D": parts[at + 1], "F": region} return None if kind == "properties": start = _expect(parts, 0, "section") region, end = _region(parts, start) if end != len(parts): return None return {"S": region} if kind == "verify": mode = parts[0] at = _expect(parts, 1, "member") member = parts[at] at = _expect(parts, at + 1, "at") place = parts[at] at = _expect(parts, at + 1, "section") region, end = _region(parts, at) at = _expect(parts, end, "limit") limit = parts[at] frame_text, stop = _region(parts, at + 1) if stop != len(parts): return None return {"V": mode, "M": member, "P": place, "S": region, "L": limit, "F": frame_text} if kind == "euler": at = _expect(parts, 0, "ends") first, second = parts[at], parts[at + 1] at = _expect(parts, at + 2, "length") length = parts[at] at = _expect(parts, at + 1, "modulus") modulus = parts[at] at = _expect(parts, at + 1, "section") region, end = _region(parts, at) if end != len(parts): return None return {"E1": first, "E2": second, "L": length, "MOD": modulus, "S": region} except (ReadingError, IndexError): return None return None
def _expect(parts: Sequence[str], index: int, word: str) -> int: """The position after the fixed word ``word``, which has to stand at ``index``.""" if index >= len(parts) or parts[index] != word: raise ReadingError("%s is missing where the language wants it" % word) return index + 1
def _region(parts: Sequence[str], start: int) -> Tuple[str, int]: """The frame or the section that starts at ``start``, as text and as where it stops.""" if start >= len(parts) or parts[start] not in (FRAME_WORD, "rect", "shapes"): raise ReadingError("a frame or a section is missing") if parts[start] == "rect": return "rect %s %s" % (parts[start + 1], parts[start + 2]), start + 3 if parts[start] == "shapes": return " ".join(parts[start:_closing(parts, start + 1) + 1]), _closing(parts, start + 1) + 1 index = start + 1 while index < len(parts) and parts[index] in BLOCKS: if index + 1 >= len(parts) or parts[index + 1] != "[": raise ReadingError("the block %s has no brackets" % parts[index]) index = _closing(parts, index + 1) + 1 return " ".join(parts[start:index]), index
# ---------------------------------------------------------------------------# Where a region of the bracket notation stands in a sentence of a human language# ---------------------------------------------------------------------------# The words a region of the notation is built from. A reader walks a sentence and stops the region# at the first word outside this vocabulary: the region of a frame or of a section is bounded by its# own words, and a reader that let "limit" or "the answer is" into it would carry a sentence fragment# into the problem.REGION_HEADS = (FRAME_WORD,) + SECTION_FORMSFRAME_VALUES = (FRAME_WORD,) + BLOCKS + SUPPORT_KINDS + LOAD_OWNERS + LOAD_KINDSSECTION_VALUES = SECTION_FORMS
def extent(values: Sequence[str], start: int) -> int: """Where the frame or the section starting at ``start`` stops, over the values of an item stream.
A reader hands this the value of every item of its sentence: the canonical word a lexicon phrase carried, the run of digits and brackets the atomiser cut, and the empty string for a word that is neither. The answer is the position one past the region, or ``-1`` when what stands there is not a region at all.
This is the shape of the notation and nothing else -- both readers ask it, just as both formalizers of the topology read one written grammar -- and neither reader is told what the region means. Whether the frame it names stands one node too far to the left belongs to the thirteen nodes of structures, not to this bundle. """ if start >= len(values) or values[start] not in REGION_HEADS: return -1 if values[start] == "rect": if start + 2 < len(values) and all(_NUMBER.fullmatch(piece or "") for piece in values[start + 1:start + 3]): return start + 3 return -1 if values[start] == "shapes": return _bracket_end(values, start + 1, SECTION_VALUES) index = start + 1 while index < len(values) and values[index] in BLOCKS: closed = _bracket_end(values, index + 1, FRAME_VALUES) if closed < 0: return -1 index = closed return index
def _bracket_end(values: Sequence[str], start: int, allowed: Sequence[str]) -> int: """The position one past a run of brackets whose content is made of numbers and of ``allowed``.""" depth = 0 index = start while index < len(values): piece = values[index] if not piece: return -1 if piece == "[": depth += 1 index += 1 continue if piece == "]": depth -= 1 index += 1 if depth == 0: return index if depth < 0: return -1 continue if _NUMBER.fullmatch(piece) or piece in allowed: index += 1 continue # A run of notation split by a word the atomiser read as words: pieces of brackets and # numbers inside one notation run are checked as tokens, not as one atom. pieces = tokens(piece) if not pieces or any(not (_NUMBER.fullmatch(item) or item in allowed or item in "[];") for item in pieces): return -1 depth += piece.count("[") - piece.count("]") if depth <= 0: return index + 1 index += 1 return -1
def region_text(values: Sequence[str], start: int, stop: int) -> str: """The words and the notation of a region, joined as one text of the structures language.""" return tidy(" ".join(piece for index in range(start, stop) for piece in tokens(values[index] or "")))
# ---------------------------------------------------------------------------# The joints of a kind, which is how reader B reads a sentence without a pattern# ---------------------------------------------------------------------------# A sequence of markers is a fact of the structures language: the joints it must hear, in order, and# the placeholder ``{SLOT}`` where the language hears the *value* of a slot instead of a joint -- the# quantity whose maximum is asked for, the direction of a displacement, the form of a section, the# head word of a frame. A number is never a marker, so it never enters a sequence: it falls into the# region the joint before it introduces.VARIANTS: Dict[str, List[Tuple[str, ...]]] = {kind: [names for names, _ in list_] for kind, list_ in TEMPLATES.items()}_PLACEHOLDER = re.compile(r"^\{([A-Z][A-Z0-9]*)\}$")
def marker_sequence(kind: str, variant: Sequence[str]) -> List[str]: """The markers a sentence of one form must carry, in order, with a placeholder per value slot.""" names, text = _template(kind, variant) out: List[str] = [] for piece in tokens(text)[1:]: match = _PLACEHOLDER.fullmatch(piece) if match: slot = match.group(1) if SLOT_KIND[kind][slot] != "num": out.append("{%s}" % slot) elif piece not in ("[", "]", ";"): out.append(piece) return out
def gap_markers(kind: str, variant: Sequence[str]) -> List[Optional[str]]: """The joint that introduces the numbers of each slot of a form, and ``None`` where there is none.""" names, text = _template(kind, variant) gaps: List[Optional[str]] = [] joint: Optional[str] = None for piece in tokens(text)[1:]: match = _PLACEHOLDER.fullmatch(piece) if match: slot = match.group(1) if slot in variant: gaps.append(joint if SLOT_KIND[kind][slot] == "num" else None) continue if piece not in ("[", "]", ";"): joint = piece gaps.append(None) return gaps
def print_sentence(kind: str, slots: Dict[str, str]) -> str: """The sentence of the structures language for one kind and one set of slots.
The fault catalogue of ``faults.py`` needs this: a reading that has been damaged on purpose has to stay a sentence the structures topology will accept, or the experiment would measure the topology refusing to parse and nothing about the reading. """ return fill(kind, slots)
def balanced(text: str) -> bool: """Whether the brackets of a sentence of the structures language open and close in pairs.""" depth = 0 for piece in tokens(text): if piece == "[": depth += 1 elif piece == "]": depth -= 1 if depth < 0: return False return depth == 0
def _template(kind: str, variant: Sequence[str]) -> Tuple[Tuple[str, ...], str]: for names, text in TEMPLATES.get(kind, []): if tuple(names) == tuple(variant): return names, text raise ReadingError("%s has no form %s" % (kind, " ".join(variant)))
# A language that has one word for a hinge says it both for the support of a structure and for the# end of a column: Italian "cerniera", Spanish "articulacion". The structures language keeps the two# apart, so a reader that filled an end slot with the word of a support says which one it meant.END_FROM_VALUE = {"pin": "pinned", "fixed": "fixed", "free": "free"}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360"""The equivalence of the two readings: do the two readers mean the same structure?
Reader A and reader B reach their sentence of the structures language by different routes -- surfacepatterns and marker frames -- and the stratum only trusts the pair when the two sentences describeone structure. Textual identity is the easy case. The interesting case is two *different* texts thatdescribe the same problem, and the only honest way to settle it is to ask what the structurestopology itself makes of the two texts, which is what this module does.
The parsing of the structures language is **not reimplemented here**. The ``struc`` bundle owns thataccount, and a second copy of it inside the reading layer would be a third place where the meaning ofthe language could be wrong without anyone noticing. So this module loads the structures bundle(:envvar:`LGSTRATUM_STRUC_ROOT`, sibling folder ``struc`` by default), has it parse both sentences,and states the claim ``the readings differ`` as SMT2 over the numbers and the words of the two parses:unsatisfiable means the two readings denote one structure under every assignment, the same``equiv: unsat`` discipline the structures topology applies between its own two solution roads.
Three consequences are deliberate and all of them are limits, not shortcuts:
* a sentence the structures topology will not parse has no fingerprint, and two readings that cannot be put beside the topology's own view are reported ``unknown``: the stratum abstains rather than assume two texts are equal;* a spelling difference is not a difference. ``1,5`` and ``1/2`` and ``0.5`` are one number, so the claim pins rationals, never character strings -- and the echo of the topology, which expands ``supports [ 1 pin ]`` into ``pin 0 0``, is compared as a parse and not as a string;* the Z3 claim of this module is *about the readings*, never about the user's structure. The problem itself is never decided here: the sentence is handed to the structures topology, whose verdict is shown as it arrived."""
import sysfrom fractions import Fractionfrom typing import Any, Dict, List, Optional, Sequence, Tuple
from . import canonical, invoker
_partner: Tuple[Any, Any] = ()_PARTNER_LOOKUP_ERROR: Optional[str] = None
def _partner_modules() -> Tuple[Any, Any, Optional[str]]: """The structures bundle's parser and its Z3 referee, or the reason they are not available.""" global _partner, _PARTNER_LOOKUP_ERROR if _partner: return _partner[0], _partner[1], None if _PARTNER_LOOKUP_ERROR is not None: return None, None, _PARTNER_LOOKUP_ERROR root = invoker.struc_root() if not (root / "lgstruc").is_dir(): _PARTNER_LOOKUP_ERROR = "no lgstruc package under %s" % root return None, None, _PARTNER_LOOKUP_ERROR text = str(root) if text not in sys.path: sys.path.insert(0, text) try: from lgstruc import parse_a, smt # noqa: PLC0415 - the import of the structures bundle is the point except Exception as exc: # noqa: BLE001 - any import failure is reported, never retried silently _PARTNER_LOOKUP_ERROR = "the structures bundle could not be imported: %s" % type(exc).__name__ return None, None, _PARTNER_LOOKUP_ERROR _partner = (parse_a, smt) return _partner[0], _partner[1], None
ONTOLOGY = "(set-option :timeout 8000)\n"
def smt_referee(decls: List[str], asserts: List[str]) -> str: """Run the referee of the structures topology over one claim, the way its orchestrator does.
The same code answers here and inside the thirteen nodes of the partner, so an envelope this stratum writes is checked by the solver the project already trusts; the stratum adds no second referee. When the partner is not on disk the answer is ``unknown``, which is what an unanswered claim is worth. """ _parser, smt, _reason = _partner_modules() if smt is None: return "unknown" return str(smt.referee(ONTOLOGY, list(decls), list(asserts)))
# ---------------------------------------------------------------------------# Numbers: one spelling everywhere# ---------------------------------------------------------------------------def numbers(text: str) -> List[Fraction]: """Every number written in a sentence or in a question, in order, as exact rationals.""" out: List[Fraction] = [] for token in canonical.numbers(text): try: out.append(Fraction(canonical.value(token))) except canonical.ReadingError: continue return out
def sorted_numbers(text: str) -> List[str]: """The same numbers ordered by value and spelled as ratios, so a reordering is not a change.""" return [str(value) for value in sorted(numbers(text))]
def _pin(name: str, value: Fraction) -> Tuple[List[str], List[str]]: """One real declared and fixed to an exact rational, in the partner's own literal syntax.""" value = Fraction(value) return (["(declare-const %s Real)" % name], ["(assert (= %s (/ %d %d)))" % (name, value.numerator, value.denominator)])
# ---------------------------------------------------------------------------# The topology's own view of one canonical sentence# ---------------------------------------------------------------------------def formalize(sentence: str) -> Optional[Tuple[List[str], List[Fraction]]]: """The structures bundle's parse of one canonical sentence, as words and exact numbers.
The parse is the partner's, and walking it is the only way this stratum learns what a sentence says: the words it collects are the words the topology kept (the family, the direction, the kind of a support, the form of a section) and the numbers are the values it read, so two sentences with the same walk describe one structure whether or not they are spelled alike. """ parse_a, _smt, _reason = _partner_modules() if parse_a is None: return None try: node = parse_a.parse(canonical.tidy(sentence)) except Exception: # noqa: BLE001 - a sentence the partner refuses is a sentence to report, not to guess return None words: List[str] = [] values: List[Fraction] = [] stack: List[Any] = [node] while stack: piece = stack.pop() if isinstance(piece, (list, tuple)): stack.extend(reversed(list(piece))) elif isinstance(piece, bool): words.append(str(piece)) elif isinstance(piece, int): values.append(Fraction(piece)) elif isinstance(piece, float): values.append(Fraction(str(piece))) else: text = str(piece).strip() if not text: continue try: values.append(Fraction(text.replace(",", "."))) except ValueError: words.append(text) return words, values
def same_problem(left: str, right: str) -> Optional[bool]: """Whether two sentences of the structures language describe one structure.
``None`` means the question could not be asked, because the structures topology is not on disk or refused one of the two sentences. That is reported, never read as agreement. """ first, second = formalize(left), formalize(right) if first is None or second is None: return None return first == second
def problem_numbers(text: str) -> List[str]: """The numbers of a sentence as the structures topology sees them, ordered and spelled as ratios.
A sentence of the structures language and the echo of the topology are not the same text: the topology writes every support in full, so ``pin`` comes back as ``pin 0 0``. Counting characters would call that a change, so the count is taken after the partner's parse on both sides. When the parse is not available the count falls back to the literals of the text, and the node says so. """ parsed = formalize(text) if parsed is None: return sorted_numbers(text) return [str(value) for value in sorted(parsed[1])]
def to_fractions(values: Sequence[str]) -> List[Fraction]: """Ratios spelled by :func:`problem_numbers`, ready for an element by element claim.
A value that is not a ratio empties the list: a claim cannot be built over a number the stratum did not read, and an empty claim is satisfiable in a way a wrong one is not. """ out: List[Fraction] = [] for value in values: try: out.append(Fraction(value)) except ValueError: return [] return out
def _codes(words: Sequence[str]) -> Dict[str, str]: """An injective symbol for every word of the two parses, so the claim can compare them.""" table: Dict[str, str] = {} for word in sorted(set(words)): table[word] = str(len(table) + 1) return table
def _differ_claim(left: Tuple[List[str], List[Fraction]], right: Tuple[List[str], List[Fraction]]) -> Tuple[List[str], List[str], str]: """SMT2 for ``the two readings differ``, and what the solver is expected to say.
The program pins one real per number of each parse and one integer per word of each parse, in the order the topology's parse produced them, and then asserts that at least one aligned pair is unequal. Unsatisfiable means every number and every word of the two parses is one value, which is the same discipline the structures topology uses between its two solution roads: the claim that travels in the envelope is the claim the referee of the orchestrator re-executes. """ left_words, left_values = left right_words, right_values = right if len(left_words) != len(right_words) or len(left_values) != len(right_values): return [], ["(assert false)"], "unsat" table = _codes(list(left_words) + list(right_words)) decls: List[str] = [] asserts: List[str] = [] differences: List[str] = [] for index, value in enumerate(left_values): step_decls, step_asserts = _pin("n%d" % index, value) decls += step_decls asserts += step_asserts differences.append("(not (= n%d m%d))" % (index, index)) for index, value in enumerate(right_values): step_decls, step_asserts = _pin("m%d" % index, value) decls += step_decls asserts += step_asserts for index, word in enumerate(left_words): decls.append("(declare-const w%d Int)" % index) decls.append("(declare-const v%d Int)" % index) asserts.append("(assert (= w%d %s))" % (index, table[word])) asserts.append("(assert (= v%d %s))" % (index, table[right_words[index]])) differences.append("(not (= w%d v%d))" % (index, index)) if not differences: return decls, asserts, "unsat" asserts.append("(assert (or %s))" % " ".join(differences)) return decls, asserts, "sat"
def variant_of(reading: Dict[str, Any]) -> Tuple[str, ...]: """The slots one reading actually filled, in the order the structures language prints them.""" kind = str(reading.get("kind", "")) slots = reading.get("slots") or {} if kind not in canonical.TEMPLATES: return () return tuple(name for name in canonical.slots_for(kind) if str(slots.get(name, "")).strip())
def equivalence(a: Dict[str, Any], b: Dict[str, Any]) -> Dict[str, Any]: """Compare two readings: one verdict, the SMT claim behind it, and what differs.""" left = canonical.tidy(str(a.get("sentence", ""))) right = canonical.tidy(str(b.get("sentence", ""))) detail: List[str] = [] if sorted_numbers(left) != sorted_numbers(right): detail.append("numbers %s vs %s" % (",".join(sorted_numbers(left)), ",".join(sorted_numbers(right))))
if a.get("kind") != b.get("kind"): detail.append("kinds %s vs %s" % (a.get("kind"), b.get("kind"))) return {"same": False, "why": "kind", "left": left, "right": right, "detail": detail, "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None} if variant_of(a) != variant_of(b): detail.append("slots %s vs %s" % (",".join(variant_of(a)), ",".join(variant_of(b)))) return {"same": False, "why": "variant", "left": left, "right": right, "detail": detail, "declarations": [], "assertions": ["(assert false)"], "claimed": "unsat", "model": None}
if left and left == right: return {"same": True, "why": "text", "left": left, "right": right, "detail": detail, "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None}
_parser, _smt, reason = _partner_modules() first, second = formalize(left), formalize(right) if first is None or second is None: note = reason or "the structures topology gives no parse of one of the two readings" detail.append(note) return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail, "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat", "model": None, "note": note}
decls, asserts, claimed = _differ_claim(first, second) found = smt_referee(decls, asserts) if found == "error" or found == "unknown": detail.append("the solver gave no answer about the two readings") return {"same": False, "why": "unknown", "left": left, "right": right, "detail": detail, "declarations": decls, "assertions": asserts, "claimed": claimed, "model": None} if found == "unsat": return {"same": True, "why": "smt", "left": left, "right": right, "detail": detail, "declarations": decls, "assertions": asserts, "claimed": claimed, "model": None} detail.append("an assignment where the two readings disagree") return {"same": False, "why": "smt", "left": left, "right": right, "detail": detail, "declarations": decls, "assertions": asserts, "claimed": claimed, "model": None}
def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]: """Whether the reading kept every number the user wrote, and the SMT claim that says so.""" wrote = sorted_numbers(question) kept = sorted_numbers(str(reading.get("sentence", ""))) decls, asserts = elementwise(numbers(question), numbers(str(reading.get("sentence", ""))), "keep") ok = wrote == kept return { "ok": ok, "wrote": wrote, "kept": kept, "missing": [value for value in wrote if value not in kept], "added": [value for value in kept if value not in wrote], "declarations": decls, "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]), "claimed": "sat" if ok else "unsat", }
def elementwise(left: List[Fraction], right: List[Fraction], prefix: str) -> Tuple[List[str], List[str]]: """SMT2 declarations and assertions saying two lists of numbers are equal, item by item.""" if len(left) != len(right): return [], ["(assert false)"] decls: List[str] = [] asserts: List[str] = [] for index, (first, second) in enumerate(zip(left, right)): left_decls, left_asserts = _pin("%s_%da" % (prefix, index), first) right_decls, right_asserts = _pin("%s_%db" % (prefix, index), second) decls += left_decls + right_decls asserts += left_asserts + right_asserts asserts.append("(assert (= %s_%sa %s_%sb))" % (prefix, index, prefix, index)) return decls, asserts
def agrees_with_struc(reading: Dict[str, Any], struc_verdict: Dict[str, Any]) -> bool: """Did the structures topology solve the structure the readers agreed on?
The topology echoes the problem it understood, and that echo is an independent channel: a node standing between the readers and the topology can rewrite its own record, but it cannot move the echo without moving numbers that were counted upstream. The echo is not a copy of the sentence, though: the topology writes ``supports`` entries in full, so a pin that was named ``pin`` comes back as ``pin 0 0``. Comparing strings would call that a different problem, so the comparison goes through the topology's own parse. """ echo = canonical.tidy(str(struc_verdict.get("problem_struc", ""))) agreed = canonical.tidy(str(reading.get("sentence", ""))) if not agreed or not echo: return False judged = same_problem(echo, agreed) if judged is not None: return judged return sorted_numbers(echo) == sorted_numbers(agreed)
def assurance_of(comparison: Dict[str, Any], readings: List[Dict[str, Any]], coverage: Optional[Dict[str, Any]] = None) -> int: """Reading assurance: how much of the answer the *reading* of the sentence warrants.
The scale is the one the structures topology uses, zero to three, and this function only ever lowers it: two readings that agree and kept every number reach level two, a single reader reaches level one, and no reading path reaches three, because reading a sentence written in a human language is never the last word -- the structures topology reserves three for a road it did not even finish, and the assurance the user sees is the minimum of the two. """ present = [reading for reading in readings if reading.get("sentence")] if not present: return 0 if coverage is not None and not coverage.get("ok", False): return 0 if len(present) < 2: return 1 return 2 if comparison.get("same") else 012345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""The gold set of the stratum: sentences in six varieties and what each one must produce.
A corpus item is one line of JSON: a language, a question written by a speaker, and the expectation.The expectation is deliberately narrow, because the stratum is not a solver -- it is the layer thatdecides *which* sentence to hand to the solver and how much confidence to attach to it:
{"id": "it-cut-1", "lang": "it", "question": "taglia l'asta 1 al punto 1 telaio nodi [ 1 0 0 ; 2 4 0 ] ...", "expect": {"state": "AGREED", "sentence": "cut member 1 at 1 frame nodes [ 1 0 0 ; 2 4 0 ] ...", "min_assurance": 1}}
``state`` is the only mandatory key. ``sentence`` is compared after tidying, ``answer_contains`` isa substring test on the answer the structures topology returned, and ``max_assurance`` is the ceilinga negative item insists on: an item that ends in DISPUTED, AMBIGUOUS or NOT COVERED must show noanswer at all.
The corpus is the only place a shared translation error can surface: the two readers agree byconstruction whenever both descriptions of a language carry the same mistake, so the gold sentencesare written from the language and not from the lexicon."""
import jsonfrom pathlib import Pathfrom typing import Any, Dict, List, Optional
from . import canonical, pipeline
ROOT = Path(__file__).resolve().parents[1]PATH = ROOT / "problems" / "corpus.jsonl"
def load(path: Optional[Path] = None) -> List[Dict[str, Any]]: """The corpus, one dictionary per line, skipping blank lines and comments.""" where = Path(path) if path else PATH items: List[Dict[str, Any]] = [] for line in where.read_text(encoding="utf-8").splitlines(): text = line.strip() if not text or text.startswith("#"): continue items.append(json.loads(text)) return items
def grade(item: Dict[str, Any], result: Dict[str, Any]) -> Dict[str, Any]: """Compare one corpus expectation against one run, and say exactly what did not match.""" expect = item.get("expect") or {} final = result.get("final") or {} problems: List[str] = [] state = str(final.get("state", "")) if expect.get("state") and expect["state"] != state: problems.append("state %s, expected %s" % (state, expect["state"])) if "sentence" in expect: wanted = canonical.tidy(str(expect["sentence"])) got = canonical.tidy(str((result.get("dossier") or {}).get("sent", ""))) if got != wanted: problems.append("sentence %r, expected %r" % (got, wanted)) if "answer_contains" in expect: answer = str(final.get("answer", "")) if str(expect["answer_contains"]) not in answer: problems.append("answer %r does not contain %r" % (answer, expect["answer_contains"])) if "min_assurance" in expect and int(final.get("assurance", 0) or 0) < int(expect["min_assurance"]): problems.append("assurance %s below %s" % (final.get("assurance"), expect["min_assurance"])) if "max_assurance" in expect and int(final.get("assurance", 0) or 0) > int(expect["max_assurance"]): problems.append("assurance %s above %s" % (final.get("assurance"), expect["max_assurance"])) if expect.get("no_answer") and final.get("answer"): problems.append("an answer was shown for an item that must show none") if expect.get("referee_clean") and any(record["claimed"] != record["referee"] for record in result.get("records") or []): problems.append("a claim did not survive the referee") return {"id": item.get("id", "?"), "lang": item.get("lang", "?"), "state": state, "assurance": final.get("assurance", 0), "ok": not problems, "problems": problems}
def outcome(item: Dict[str, Any], call_struc: bool = True, fault_spec: Optional[List[str]] = None) -> Dict[str, Any]: """Run one corpus item in memory and grade it.""" result = pipeline.ask(str(item.get("question", "")), str(item.get("lang", "")), fault_spec=fault_spec, call_struc=call_struc) verdict = grade(item, result) verdict["records"] = result["records"] verdict["dossier"] = result["dossier"] verdict["reply"] = result["reply"] return verdict123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108"""What the reading kept, and what the structures topology says it solved.
Two bookkeeping checks stand between the readers and the answer, and both are stated as SMT2 so thereferee of the orchestrator recomputes them instead of trusting a node:
* :func:`keeps` -- every number the user wrote is still in the sentence of the structures language, and no number appeared there that the user did not write. A reader that moved a number from one slot to another or shifted a digit changes that multiset, and a sorted element by element equality over declared reals says so;* :func:`echo_matches` -- the structures topology echoes the problem it understood, and the echo is compared with the structure the readers agreed on. The echo is an independent channel: a node standing between the readers and the topology can rewrite its own record, but it cannot move the echo without moving numbers that were counted upstream.
Neither check decides mechanics. They count tokens, and they hand the counting to a solver so that anode claiming the numbers were kept is checked against that claim."""
from fractions import Fractionfrom typing import Any, Dict, List, Optional
from . import canonical, compare
def keeps(reading: Dict[str, Any], question: str) -> Dict[str, Any]: """Whether one reading kept every number the user wrote, with the SMT claim that says so.""" return compare.keeps(reading, question)
def echo_numbers(struc_verdict: Dict[str, Any]) -> List[str]: """The numbers of the problem the structures topology says it solved, ordered by value.""" return compare.problem_numbers(canonical.tidy(str(struc_verdict.get("problem_struc", ""))))
def echo_matches(reading: Dict[str, Any], struc_verdict: Dict[str, Any]) -> bool: """Did the structures topology solve the structure the readers agreed on?
A verdict that names no problem at all -- the backend was off, or the topology could not be started -- leaves nothing to contradict, so it is not a mismatch: the assurance still falls to zero because there is no mechanics assurance to take the minimum with, but nothing here may be read as tampering. Only an echo that names a problem and names a different one is a mismatch. """ if not str(struc_verdict.get("problem_struc", "")).strip(): return True return compare.agrees_with_struc(reading, struc_verdict)
def coverage_claim(question: str, readings: List[Dict[str, Any]], struc_verdict: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: """One SMT2 claim tying the user's numbers to the readings and, when known, to the echo.
Every reading that produced a sentence has to carry the user's numbers, and once the structures topology has answered its echo has to carry the numbers of the agreed sentence too -- counted after the partner's parse, because the echo is a normalized restatement and not a copy. The assertion set is the conjunction of those element equalities: satisfiable exactly when all of them hold, which is what the referee checks against the status the node claimed. """ wrote = compare.sorted_numbers(question) readings_present = [reading for reading in readings if reading.get("sentence")] steps = [keeps(reading, question) for reading in readings_present] ok = all(step["ok"] for step in steps) decls: List[str] = [] asserts: List[str] = [] for step in steps: decls = decls + list(step["declarations"]) asserts = asserts + list(step["assertions"]) if struc_verdict is not None and readings_present: agreed = compare.problem_numbers(canonical.tidy(str(readings_present[0].get("sentence", "")))) echo = echo_numbers(struc_verdict) decls2, asserts2 = compare.elementwise(compare.to_fractions(agreed), compare.to_fractions(echo), "echo") decls = decls + decls2 asserts = asserts + asserts2 ok = ok and echo == agreed if not wrote: # Nothing was written, so there is nothing to keep: the claim is the empty conjunction, # which is satisfiable, and the node says sat. return {"ok": ok, "wrote": [], "kept": [], "declarations": [], "assertions": ["(assert (= 1 1))"], "claimed": "sat"} return { "ok": ok, "wrote": wrote, "kept": [step["kept"] for step in steps], "declarations": decls, "assertions": asserts + (["(assert (= 1 1))"] if ok else ["(assert false)"]), "claimed": "sat" if ok else "unsat", }
def _as_fractions(values: List[str]) -> List[Any]: """Ratios spelled by :func:`compare.problem_numbers`, ready for an element by element claim.""" out: List[Any] = [] for value in values: try: out.append(Fraction(value)) except ValueError: return [] return out
def summary(step: Dict[str, Any]) -> Dict[str, Any]: """The part of a coverage step that belongs in the dossier and in front of the user.""" return { "ok": step.get("ok", False), "wrote": step.get("wrote", []), "missing": step.get("missing", []), "added": step.get("added", []), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168"""The decision: pure, and never raising anything.
One function, no I/O: given what the readers understood, what the equivalence node proved, what thecoverage node counted and what the structures topology answered, it states the state of the session,the assurance the user sees, and whether an answer may be shown at all. The arbiter runs it, thetools run it again on the transcript, and a test pins it, so the same rules are checked in threeplaces -- the same shape the structures topology uses for its own decision.
The rule the whole module exists to enforce:
assurance(shown) = min(assurance(struc), assurance(reading))
and ``assurance(reading)`` is at most two: the two readers agreeing on one structure is the highestlevel the conversational layer can claim on its own. Two is also the highest level the structurestopology reaches -- its two structural roads and the referee that agrees with them -- so the minimumof the two can only ever lower what is shown. A sentence written in a human language carries one morefallible step than a sentence the topology parses itself, and that step never lends an assurance themechanics did not give. A verdict is therefore never raised by the stratum; the only direction it canmove is down, and the adversary node writes the negation of that inequality as SMT2 so the referee ofthe orchestrator refutes it.
The states, which are the eight the lexicon of every covered language names:
=========== ===================================================================AGREED both readers produced the same structure, and the topology solved itPASSTHROUGH the sentence was already written in the structures language: nothing was translatedSINGLE one reader understood the sentence and the other abstained: the topology was consulted, and the assurance is capped by the missing witnessDISPUTED the two readers produced different structures, or a reading lost a number: the topology is not consulted at allAMBIGUOUS the sentence announces more than one kind of problem: the user has to chooseNOT COVERED neither reader found anything: the language does not say this in a covered wayTAMPERED the topology says it solved something other than the agreed sentenceNONE the session ended without a verdict: the arbiter node did not write one, or the evidence it left was not readable=========== ==================================================================="""
from typing import Any, Dict, List, Optional
AMBIGUOUS_REASONS = ("multiple", "two_frames")
STATES = ("AGREED", "PASSTHROUGH", "SINGLE", "DISPUTED", "AMBIGUOUS", "NOT COVERED", "TAMPERED", "NONE")
# The reading assurance of each state, on the scale the structures topology uses. The topology itself# never goes above two, and no reading path can push it there from below.CEILING = {"AGREED": 2, "PASSTHROUGH": 2, "SINGLE": 1, "DISPUTED": 0, "AMBIGUOUS": 0, "NOT COVERED": 0, "TAMPERED": 0, "NONE": 0}
# The two verdicts of the partner that come with an answer; everything else abstains.ANSWERING = ("VERIFIED", "SINGLE_PROVER")
def reader_notes(readings: List[Dict[str, Any]]) -> List[str]: """The reason keys the abstaining readers left behind, in reader order.""" notes: List[str] = [] for reading in readings: for note in reading.get("notes") or []: reason = note.get("reason") if isinstance(note, dict) else str(note) if reason and reason not in notes: notes.append(reason) return notes
def state_of(readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]], coverage: Optional[Dict[str, Any]], struc_verdict: Optional[Dict[str, Any]], direct: Optional[Dict[str, Any]] = None, echo_ok: Optional[bool] = None) -> str: """The state of a session, from the evidence the nodes collected.""" present = [reading for reading in readings if reading.get("sentence")] notes = reader_notes(readings) if direct is not None: return "PASSTHROUGH" if struc_verdict is not None and echo_ok is False: return "TAMPERED" if len(present) >= 2: if comparison is None: return "DISPUTED" if coverage is not None and not coverage.get("ok", False): return "DISPUTED" return "AGREED" if comparison.get("same") else "DISPUTED" if len(present) == 1: # A lone witness has to hold the numbers the person wrote: a reading that lost one is not a # weaker reading of the same structure, it is a different structure, and the ceiling of SINGLE # is not a licence to answer it. This is the case the ablation of the topology uncovered: with # one reader there is no second sentence to compare against, so the count of numbers is what # stands between a shifted number and an answer the gold does not accept. if coverage is not None and not coverage.get("ok", False): return "DISPUTED" return "SINGLE" if any(reason in AMBIGUOUS_REASONS for reason in notes): return "AMBIGUOUS" return "NOT COVERED"
def reasons_for(state: str, readings: List[Dict[str, Any]], comparison: Optional[Dict[str, Any]], coverage: Optional[Dict[str, Any]], struc_verdict: Optional[Dict[str, Any]], asked: bool = True) -> List[str]: """The reason keys that explain a state, in the order a reader should read them.""" out: List[str] = [] for reason in reader_notes(readings): if reason not in out: out.append(reason) if state == "DISPUTED": if coverage is not None and not coverage.get("ok", False): out.append("number_count") if comparison is not None and not comparison.get("same"): out.append("disagree") if comparison is not None and comparison.get("why") == "unknown": out.append("struc_unknown") if comparison is not None and comparison.get("why") == "smt" and comparison.get("model"): if "disagree" not in out: out.append("disagree") if state == "TAMPERED": out.append("boundary") if struc_verdict is not None and struc_verdict.get("referee_mismatch"): out.append("referee") if asked and struc_verdict is not None and struc_verdict.get("status") == "UNKNOWN": out.append("struc_unknown") if not asked and state in ("AGREED", "SINGLE", "PASSTHROUGH"): out.append("no_struc") return out
def decide(dossier: Dict[str, Any]) -> Dict[str, Any]: """One verdict for one session, with the assurance the user is allowed to see.""" readings = [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}] if dossier.get("reading_direct"): readings = [dossier["reading_direct"]] comparison = dossier.get("compare") coverage = dossier.get("coverage") struc_verdict = dossier.get("struc") direct = dossier.get("reading_direct") echo_ok = dossier.get("echo_ok")
state = state_of(readings, comparison, coverage, struc_verdict, direct, echo_ok) ceiling = CEILING[state] assurance = 0 answer_shown = "" if state in ("AGREED", "SINGLE", "PASSTHROUGH") and struc_verdict is not None: # The topology answers at level two when its two solution roads and its referee all agree, at # level one when a single prover stands alone, and at level zero when it says UNKNOWN. if struc_verdict.get("status") in ANSWERING: assurance = min(ceiling, int(struc_verdict.get("assurance", 0) or 0)) else: assurance = 0 answer_shown = struc_verdict.get("answer_text") or "" if assurance == 0: answer_shown = "" reasons = reasons_for(state, readings, comparison, coverage, struc_verdict, asked=bool(str(dossier.get("sent") or ""))) return { "state": state, "assurance": assurance, "ceiling": ceiling, "struc_assurance": int((struc_verdict or {}).get("assurance", 0) or 0), "struc_status": (struc_verdict or {}).get("status"), "answer": answer_shown, "reasons": reasons, "consulted_struc": struc_verdict is not None, }
def raise_assurance(final: Dict[str, Any], claimed: int) -> Dict[str, Any]: """The arbiter fault: an assurance above what the evidence supports (experiments only).""" out = dict(final) out["assurance"] = max(int(final.get("assurance", 0) or 0), int(claimed)) out["claimed_above_evidence"] = True return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174"""Fault injection for the redundancy experiments (tools/ablation.py).
A fault is "<agent>:<kind>". Faults are off unless LGSTRATUM_FAULTS (or :func:`configure`) namesthem, so production runs never take these branches. ``FIRED`` records the faults that reallychanged something, which separates dormant faults from activated ones.
The faults of the reading layer are chosen so that the damaged reading is still a *grammatical*sentence of the structures language: a reader that moves a number from one slot to another, or thathears the wrong one of the three directions, must produce something the structures topology willhappily solve. Otherwise the fault would be caught by the topology refusing to parse, and theexperiment would measure nothing about the reading layer. The damage here is a wrong problem, not anill-formed one, and only the agreement of the two readers and the echo of the topology can see it.
Catalogue---------reader_a / reader_b : shift_number, merge_slots, shift_wordequivalence : rubber_stamp (declares the two readings equal without comparing them)coverage : rubber_stamp (declares every number kept without counting them)boundary : tamper_struc (asks the structures topology a different question, reports the agreed one)adversary : rubber_stamp (skips its own recomputation of the assurance bound)arbiter : force_assurance (raises the assurance above what the evidence supports)"""
import osimport refrom typing import Any, Dict, Iterable, List, Optional, Set, Tuple
from . import canonical
_ACTIVE: Set[str] = set()FIRED: List[str] = []
READER_FAULTS = ["shift_number", "merge_slots", "shift_word"]
CATALOG = { "reader_a": READER_FAULTS, "reader_b": READER_FAULTS, "equivalence": ["rubber_stamp"], "coverage": ["rubber_stamp"], "boundary": ["tamper_struc"], "adversary": ["rubber_stamp"], "arbiter": ["force_assurance"],}
_NUMBER = re.compile(r"\d+(?:\.\d+)?")
def configure(spec: Optional[Iterable[str]]) -> None: _ACTIVE.clear() del FIRED[:] if spec is None: return if isinstance(spec, str): spec = [s for s in spec.split(",") if s.strip()] for item in spec: _ACTIVE.add(item.strip())
def from_env() -> None: configure(os.environ.get("LGSTRATUM_FAULTS", ""))
def has(agent: str, kind: str) -> bool: return "%s:%s" % (agent, kind) in _ACTIVE
def fire(agent: str, kind: str) -> None: label = "%s:%s" % (agent, kind) if label not in FIRED: FIRED.append(label)
def fired(agent: str) -> List[str]: return [item for item in FIRED if item.split(":", 1)[0] == agent]
# ---------------------------------------------------------------------------# Reading mutations (reader faults)# ---------------------------------------------------------------------------def _slots_of(slots: Dict[str, str], order: List[str], kind: str, what: str) -> List[str]: """The slots of one form that hold one kind of value, in the order the form puts them.""" return [name for name in order if name in slots and canonical.SLOT_KIND.get(kind, {}).get(name) == what]
def _words_of(kind: str, slot: str) -> List[str]: """The closed set a word slot reads, so that a fault can pick another member of the same set.""" what = canonical.SLOT_KIND.get(kind, {}).get(slot) return {"quantity": list(canonical.QUANTITIES), "direction": list(canonical.DIRECTIONS), "mode": list(canonical.VERIFY_MODES), "end": list(canonical.END_KINDS)}.get(what, [])
def mutate_reading(agent: str, kind: str, slots: Dict[str, str], order: List[str]) -> Tuple[Dict[str, str], bool]: """Return a damaged copy of one reading, and whether anything was actually damaged.
``order`` is the slot order of the form the reader chose. A fault only touches slots of the type it can damage -- a number for the two number faults, a word of a closed set for the third -- and the copy is kept only if the structures language still accepts it as a sentence: damage that makes the sentence impossible is not a reading error, and the topology would catch it for free. """ slots = dict(slots) for kind_fault in CATALOG.get(agent, []): if not has(agent, kind_fault): continue candidate = dict(slots) numbered = _slots_of(candidate, order, kind, "num") if kind_fault == "shift_number": if not numbered: continue owner = numbered[0] match = _NUMBER.search(candidate[owner]) if match is None: continue candidate[owner] = (candidate[owner][:match.start()] + str(_next_number(match.group(0))) + candidate[owner][match.end():]) elif kind_fault == "merge_slots": if len(numbered) < 2: continue candidate[numbered[1]] = candidate[numbered[0]] elif kind_fault == "shift_word": words = [name for name in order if name in candidate and _words_of(kind, name)] moved = False for name in words: others = [other for other in _words_of(kind, name) if other != candidate[name]] if others: candidate[name] = others[0] moved = True break if not moved: continue else: continue if candidate == slots: # Two slots that already carried the same value: copying one over the other damages # nothing, and a fault that damaged nothing is not a fault the ablation may report. continue try: canonical.print_sentence(kind, candidate) except canonical.ReadingError: continue fire(agent, kind_fault) return candidate, True return slots, False
def _next_number(text: str) -> Any: if "." in text: return float(text) + 1.0 return int(text) + 1
# ---------------------------------------------------------------------------# Sentence mutations (the boundary fault)# ---------------------------------------------------------------------------def mutate_sentence(agent: str, sentence: str) -> Tuple[str, bool]: """Change one number of a sentence of the structures language, leaving it grammatical.
This is the fault of the boundary node, and it is the one the reading layer cannot see from the inside: the stratum asked a question, the topology answered a different one, and only comparing the numbers the two of them name says which question was really answered. """ if not has(agent, "tamper_struc"): return sentence, False match = _NUMBER.search(sentence) if match is None: return sentence, False damaged = sentence[:match.start()] + str(_next_number(match.group(0))) + sentence[match.end():] fire(agent, "tamper_struc") return damaged, True123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125"""The interface toward the structures topology: one subprocess call, no shared code.
The reading layer and the structures topology are separate topologies of the same orchestrator. Thismodule is the whole of their coupling: it starts ``tools/ask.py`` of the structures bundle as aseparate process with the canonical sentence as its argument, asks for the machine readable outcome,and copies that outcome. Nothing here imports a module of the structures bundle, because a translationlayer that reaches inside the mechanics it consults is a translation layer that can silently changethe mechanics. The one exception in this bundle is ``compare.py``, which needs the partner's parser tosay that two readings are one structure; the verdict of a session always arrives through the processstarted here.
Three settings matter, and all of them are environment variables so no value is hardcoded in a secondplace:
``LGSTRATUM_STRUC_ROOT`` the folder of the structures bundle (default: ``struc``, sibling of this bundle, which is ``datasets/struc`` inside the LingoLOGOS repository)``LGSTRATUM_STRUC_BACKEND`` ``in-process`` (default), ``orchestrated`` or ``none``. The first runs the thirteen nodes of the topology inside one process, which is what the tests of this bundle use; the second lets the partner build the thirteen node folders and run them as its own orchestrator does; ``none`` refuses to call, so a coverage report can ask what the stratum *understood* without starting a whole structures session``LGSTRATUM_STRUC_TIMEOUT`` seconds to wait for the partner, 300 by default
The environment of the partner is left alone: ``LGSTRUC_FAULTS`` and ``LGSTRUC_MATH_ROOT`` are thepartner's own business, and a reading layer that rewrote them would be deciding what the mechanicslayer is allowed to prove."""
import jsonimport osimport subprocessimport sysfrom pathlib import Pathfrom typing import Any, Dict
ROOT = Path(__file__).resolve().parents[1]DEFAULT_TIMEOUT = 300
def struc_root() -> Path: override = os.environ.get("LGSTRATUM_STRUC_ROOT", "").strip() if override: return Path(override) return ROOT.parent / "struc"
def backend() -> str: return (os.environ.get("LGSTRATUM_STRUC_BACKEND", "in-process") or "in-process").strip().lower()
def timeout_seconds() -> int: try: return max(5, int(os.environ.get("LGSTRATUM_STRUC_TIMEOUT", DEFAULT_TIMEOUT))) except ValueError: return DEFAULT_TIMEOUT
def unavailable(reason: str) -> Dict[str, Any]: return {"ok": False, "error": reason, "status": "UNKNOWN", "assurance": 0, "answer": None, "answer_text": "", "problem_struc": "", "reasons": [], "kind": None, "delegate": "", "roads": {}, "states": {}, "readings_agree": False, "math_status": "NOT_ASKED", "referee_mismatch": 0, "turns": None}
def solve(sentence: str) -> Dict[str, Any]: """Ask the structures topology one sentence of the structures language, and return its verdict.""" mode = backend() if mode == "none": return unavailable("the structures backend is disabled by LGSTRATUM_STRUC_BACKEND") root = struc_root() script = root / "tools" / "ask.py" if not script.is_file(): return unavailable("no tools/ask.py under %s" % root) command = [sys.executable, str(script), "--json"] if mode != "orchestrated": command.append("--in-process") command.append(sentence) try: done = subprocess.run(command, cwd=str(root), capture_output=True, timeout=timeout_seconds()) except subprocess.TimeoutExpired: return unavailable("the structures topology did not answer within %d seconds" % timeout_seconds()) except OSError as exc: return unavailable("the structures topology could not be started: %s" % exc) text = done.stdout.decode("utf-8", "replace") if not text.strip(): # Exit 2 is the partner's own way of saying it abstained, and it prints the verdict before # doing so; only a run that printed nothing at all is a run that did not answer. return unavailable("the structures topology exited with %d and printed nothing: %s" % (done.returncode, done.stderr.decode("utf-8", "replace").strip()[:200])) return outcome(text, done.returncode)
def outcome(text: str, returncode: int = 0) -> Dict[str, Any]: """Extract the verdict of a structures session from the JSON the partner printed.""" try: parsed = json.loads(text) except ValueError: return unavailable("the structures topology printed something that is not JSON (exit %d)" % returncode) final = parsed.get("final") if isinstance(parsed, dict) else None if not isinstance(final, dict): return unavailable("the structures topology printed no verdict (exit %d)" % returncode) referee = parsed.get("referee") if isinstance(parsed.get("referee"), list) else [] mismatched = [entry for entry in referee if isinstance(entry, dict) and entry.get("claimed") != entry.get("referee")] status = str(final.get("status") or "UNKNOWN") return { "ok": status != "UNKNOWN", "status": status, "assurance": int(final.get("assurance", 0) or 0), "answer": final.get("answer"), "answer_text": final.get("answer_text") or "", "problem_struc": final.get("problem") or "", "reasons": list(final.get("reasons") or []), "kind": final.get("kind"), "delegate": final.get("delegate") or "", "roads": dict(final.get("roads") or {}), "states": dict(final.get("states") or {}), "readings_agree": bool(final.get("readings_agree")), "math_status": final.get("math_status") or "NOT_ASKED", "referee_mismatch": len(mismatched), "turns": parsed.get("turns"), "error": None if status != "UNKNOWN" else "; ".join(str(reason) for reason in (final.get("reasons") or [])) or "unknown", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346"""The lexicon of the six language varieties, and the two routes that read a sentence.
Every variety lives in one JSON file ``lexicon/<lang>.json`` and carries, for every kind of questionthe variety covers:
``verbs`` the phrases that announce the kind;``patterns`` the surface patterns reader A matches (a slot string per accepted wording).
Reader B never looks at those patterns. It takes the verbs and the markers of this file, and thesequence of joints it expects from ``lgstratum.canonical``, which is the shape of the structureslanguage and nothing to do with how a variety words it. This mirrors the topology of structures, wherethe two formalizers share one written specification (``nodes/*/grammar.gf``) and implement it twice.The consequence is the same and is stated in the README: a translation error present in both routes ofone language is invisible to the topology, and only the gold sentences of the corpus can show it.
The data files are the object of study, not prose of this repository: they hold the words of sixlanguages, exactly as the structures bundle holds the bracket tokens it studies."""
import jsonimport osimport refrom typing import Any, Dict, List, Optional, Tuple
from .segment import atomize, fold
BUNDLE = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))LEXICON_DIR = os.path.join(BUNDLE, "lexicon")
# Marker names, the same in every variety: they are the words of the structures language a variety# has to say something about, and the value each of them carries. The joints are what separate the# abscissa of a cut from the limit of a check; the blocks and the closed sets of values are what the# region of a frame or of a section is built from. The two readers and the canonical printer agree# on these names and on nothing else.MARKERS = ("at", "ends", "length", "limit", "modulus", "node", "member", "section", "frame", "nodes", "members", "props", "supports", "loads", "hinges", "pin", "pinned", "roller", "fixed", "free", "force", "couple", "udl", "point", "moment", "shear", "axial", "vertical", "horizontal", "rotation", "bending", "vonmises", "rect", "shapes")
_cache: Dict[str, Dict[str, Any]] = {}_index_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}_stripped_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, str]]] = {}_verb_cache: Dict[str, Dict[Tuple[str, ...], Tuple[str, ...]]] = {}_group_cache: Dict[str, Dict[str, Tuple[str, ...]]] = {}
def languages() -> List[str]: """The language codes this bundle can read, in a stable order.""" return sorted(name[:-5] for name in os.listdir(LEXICON_DIR) if name.endswith(".json"))
def load(lang: str) -> Dict[str, Any]: if lang not in _cache: path = os.path.join(LEXICON_DIR, lang + ".json") with open(path, "r", encoding="utf-8") as handle: data = json.load(handle) data["_code"] = lang _cache[lang] = data return _cache[lang]
def script(lang: str) -> str: return load(lang).get("script", "latin")
def codes() -> List[str]: return languages()
def kinds(lang: str) -> List[str]: """The sentence kinds this variety covers.""" return sorted(load(lang).get("kinds", {}))
def supported_kinds() -> List[str]: """The kinds at least one variety covers.""" seen = set() for lang in languages(): seen.update(kinds(lang)) return sorted(seen)
def patterns(lang: str) -> Dict[str, List[str]]: """Reader A's surface patterns per kind: ``{kind: [pattern, ...]}``.""" out = {} for kind, spec in load(lang).get("kinds", {}).items(): out[kind] = list(spec.get("patterns", [])) return out
def verbs(lang: str) -> Dict[str, Tuple[Tuple[str, ...], ...]]: """Every kind verb phrase of the variety, mapped to the kinds it announces.
One phrase can announce more than one kind, and that is a fact of the language, not a defect of the data: a variety may use one verb for the check of a section and for the check of a whole frame. Keeping the whole list here is what lets a reader try both forms of one sentence instead of silently taking the last kind in the file. """ out: Dict[str, Tuple[str, ...]] = {} for kind, spec in load(lang).get("kinds", {}).items(): for verb in spec.get("verbs", []): phrase = fold(verb) out[phrase] = out.get(phrase, ()) + (kind,) return out
def verb_atoms_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, ...]]: """The verb phrases of a variety, keyed by their atoms, mapped to the kinds they announce.""" if lang in _verb_cache: return _verb_cache[lang] index = {phrase_atoms(verb): kinds for verb, kinds in verbs(lang).items()} _verb_cache[lang] = index return index
def verb_groups(lang: str) -> Dict[str, Tuple[str, ...]]: """The kinds one verb phrase can open, merged into groups.
Two kinds belong to the same group when one phrase of the variety announces both of them. A sentence whose verb lies in one group is one problem, read in one of two ways; a sentence whose verbs lie in two groups is two problems, and no reader may pick one. """ if lang in _group_cache: return _group_cache[lang] parent = {kind: kind for kind in load(lang).get("kinds", {})}
def root(kind: str) -> str: while parent[kind] != kind: parent[kind] = parent[parent[kind]] kind = parent[kind] return kind
for kinds in verbs(lang).values(): for other in kinds[1:]: first, second = root(kinds[0]), root(other) if first != second: parent[second] = first merged: Dict[str, set] = {} for kind in parent: merged.setdefault(root(kind), set()).add(kind) groups = {kind: tuple(sorted(group)) for group in merged.values() for kind in group} _group_cache[lang] = groups return groups
def announce(lang: str, items: List[Dict[str, Any]]) -> Tuple[List[str], Optional[Dict[str, str]]]: """The kinds the verbs of a sentence open, or the reason the sentence announces none.
Both readers ask this one question, in one place: which kind a sentence belongs to is a decision about the structure, and a second implementation of the same rule in the second reader would be one more place where the two of them can be wrong in the same way. """ found: List[str] = [] for item in items: if item.get("role") != "verb": continue for kind in item.get("kinds") or (item.get("value"),): if kind and kind not in found: found.append(kind) if not found: return [], {"reason": "no_verb"} neutral = neutral_kinds(lang) picked = [kind for kind in found if kind not in neutral] or found groups = {frozenset(verb_groups(lang)[kind]) for kind in picked} if len(groups) > 1: return [], {"reason": "two_verbs", "kinds": ", ".join(sorted(picked))} merged: set = set() for group in groups: merged |= group return sorted(merged), None
def neutral_kinds(lang: str) -> set: """Kinds whose verb is a request for an answer rather than a claim about the structure.
A variety may use one request verb for several kinds: in such a case the verb is neutral, the reader that carries it steps aside, and the kind is decided by the words that name what is asked about. A variety whose every verb names its kind covers none of these. """ return {kind for kind, spec in load(lang).get("kinds", {}).items() if spec.get("neutral")}
def markers(lang: str) -> Dict[str, List[str]]: return load(lang).get("markers", {})
def noise(lang: str) -> List[str]: return load(lang).get("noise", [])
def noise_chars(lang: str) -> str: """Single characters a word run may hold without being a coverage failure (Chinese particles).""" return load(lang).get("noise_chars", "")
def prefixes(lang: str) -> List[str]: """Attached prefixes an Arabic word run may carry (definite article, conjunctions).""" return load(lang).get("prefixes", [])
def strip_prefix(word: str, prefixes: List[str]) -> str: """Remove the longest attached prefix, so that a written form reaches the prefix-free entry.
Arabic attaches the definite article and the single letter conjunctions and prepositions in front of the word, and the lexicon files record the word without them. The longest prefix wins, because the article and a conjunction joined to it are one prefix and not two. """ for prefix in sorted(prefixes, key=len, reverse=True): if word.startswith(prefix) and len(word) > len(prefix): return word[len(prefix):] return word
def prefix_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]: """The same index, keyed with every atom of every phrase written without its prefixes.""" if lang in _stripped_cache: return _stripped_cache[lang] attached = prefixes(lang) stripped = {} for window, hit in phrase_index(lang).items(): if attached: key = tuple(strip_prefix(atom, attached) for atom in window) stripped.setdefault(key, hit) _stripped_cache[lang] = stripped return stripped
# ---------------------------------------------------------------------------# Phrase index (reader A) and phrase positions (reader B)# ---------------------------------------------------------------------------Phrase = Tuple[Tuple[str, ...], str, str]
def phrase_atoms(phrase: str) -> Tuple[str, ...]: """The atoms a lexicon phrase is written with, through the same atomiser as a sentence.
A Chinese term in a data file is one token, and one token is not one atom: the atomiser cuts it into characters, exactly as it cuts the sentence the user typed. Doing both sides the same way is the only reason a data file and a sentence can be compared at all. """ return tuple(fold(atom) for kind, atom in atomize(phrase) if kind == "w")
_SLOT_MARK = re.compile(r"\{[A-Z][A-Z0-9]*\}")
def pattern_literals(lang: str) -> List[Tuple[str, ...]]: """The function words the written patterns of a variety spell out themselves, one atom each.
A pattern is part of the data of a variety, so every word it writes is a word of that variety by definition. ``calcola le reazioni vincolari di {F}`` names ``reazioni`` and ``vincolari``, and a reader that called those words unknown would refuse the very shape the data file documents. These words carry no value, which is what makes them noise: they may stand in a sentence, they never fill a slot. """ words: List[Tuple[str, ...]] = [] for entries in patterns(lang).values(): for pattern in entries: for chunk in _SLOT_MARK.split(pattern): for atom in phrase_atoms(chunk): words.append((atom,)) return words
def phrase_index(lang: str) -> Dict[Tuple[str, ...], Tuple[str, str]]: """Map a folded word sequence to ``(role, value)``: verb, marker or noise.
Verbs, markers and noise words of a variety share one index, because reader A has to decide between them with a single longest match. The index is built once per variety. """ if lang in _index_cache: return _index_cache[lang] index: Dict[Tuple[str, ...], Tuple[str, str]] = {} for verb, kinds in verbs(lang).items(): index[phrase_atoms(verb)] = ("verb", kinds[0]) for name, words in markers(lang).items(): for word in words: index[phrase_atoms(word)] = ("marker", name) for word in noise(lang): index.setdefault(phrase_atoms(word), ("noise", "")) for atom in pattern_literals(lang): index.setdefault(atom, ("noise", "")) # A data file with an empty phrase would match at every position and read nothing: drop it. index.pop((), None) _index_cache[lang] = index return index
def max_phrase_length(lang: str) -> int: return max((len(key) for key in phrase_index(lang)), default=1)
# ---------------------------------------------------------------------------# Presentation data# ---------------------------------------------------------------------------def labels(lang: str) -> Dict[str, str]: return load(lang).get("labels", {})
def reading_labels(lang: str) -> Dict[str, str]: return load(lang).get("reading", {})
def reason_texts(lang: str) -> Dict[str, str]: return load(lang).get("reasons", {})
def examples(lang: str) -> List[str]: return load(lang).get("examples", [])
def label(lang: str, key: str, fallback: str = "") -> str: return labels(lang).get(key, fallback)
def translate_reason(lang: str, reason: str, **fields: Any) -> str: """One reason in the language of the user, with the fields a template asks for.""" table = reason_texts(lang) text = table.get(reason) or table.get("other") or reason try: return text.format(**fields) except (KeyError, IndexError): return text
def language_name(lang: str) -> str: return load(lang).get("name", lang)
def find_by_hint(lang: str) -> Optional[str]: """Resolve a ``--lang`` hint (a code or a name) to a language code, or ``None``.""" if lang in _available(): return lang wanted = fold(lang) for code in languages(): if fold(code) == wanted or fold(language_name(code)) == wanted: return code return None
def _available() -> List[str]: return languages()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""One run of the topology in a single process, with every envelope re-checked.
The orchestrator runs the eight nodes as separate processes, one turn each. This module chains thevery same ``step_*`` functions in memory and runs the referee of the structures topology on everyenvelope on the way, which is what the orchestrator does with each turn. It exists for the tests, forthe coverage report over the corpus, and for the ablation experiments, where thousands of runs areneeded and a process per node would dominate the time.
``checked_verdict`` is the part that matters outside this module: it recomputes the verdict from theevidence the transcript carries, so a node that rewrote its own record is answered by the same rulesthe arbiter was supposed to follow, and the answer shown is whichever of the two is more cautious. Thetools print that verdict, not the one the arbiter wrote."""
import osfrom typing import Any, Dict, List, Optional, Sequence
from . import agents, compare, coverage, decide, faults, protocol, render
ORDER = agents.ORDERONTOLOGY = "(set-option :timeout 8000)\n"BACKEND_VARIABLE = "LGSTRATUM_STRUC_BACKEND"
def referee(decls: List[str], asserts: List[str]) -> str: """Run the referee of the structures topology over one envelope claim, in this process.""" status = compare.smt_referee(decls, asserts) return status if status in ("sat", "unsat", "unknown", "error") else "unknown"
def seed(question: str, lang: str) -> Dict[str, Any]: """The envelope the arbiter node starts a session with: the question and its language.""" dossier = {"question": question, "lang": lang} return {"payload": {"naturalLanguage": protocol.encode("question (%s): %s" % (lang, question), dossier)}, "sender": "arbiter", "turn": 0, "volatileState": {"internalTimeTick": 0}}
def ask(question: str, lang: str, active: Sequence[str] = ORDER, fault_spec: Optional[Sequence[str]] = None, call_struc: bool = True) -> Dict[str, Any]: """One session, in memory: returns the dossier, the referee log, the verdict and the reply.""" faults.configure(fault_spec or ()) previous = os.environ.get(BACKEND_VARIABLE) if not call_struc: os.environ[BACKEND_VARIABLE] = "none" current = seed(question, lang) records: List[Dict[str, Any]] = [] turn = 0 try: for name in ORDER: if name not in active: continue turn += 1 incoming = {"sender": current["sender"], "turn": turn, "volatileState": {"internalTimeTick": turn}, "payload": current["payload"]} out = agents.run_step(name, incoming, name) constraints = out["payload"]["smtConstraints"] actual = referee(constraints["declarations"], constraints["assertions"]) records.append({"turn": turn, "sender": name, "claimed": constraints["z3Status"], "referee": actual}) current = out finally: if not call_struc: if previous is None: os.environ.pop(BACKEND_VARIABLE, None) else: os.environ[BACKEND_VARIABLE] = previous dossier = protocol.decode(current["payload"]["naturalLanguage"]) final = checked_verdict(dossier, records, arbiter_expected="arbiter" in active) reply = render.reply(dossier, final, records) return {"dossier": dossier, "records": records, "final": final, "reply": reply, "faults": sorted(faults.FIRED)}
def _unknown(reason: str) -> Dict[str, Any]: return {"state": "NONE", "assurance": 0, "ceiling": 0, "struc_assurance": 0, "struc_status": None, "answer": "", "reasons": [reason], "consulted_struc": False, "detected": []}
def referee_adjusted(final: Dict[str, Any], records: List[Dict[str, Any]]) -> Dict[str, Any]: """Zero the verdict when the referee disagrees with what a node claimed about its own envelope.""" bad = [record["sender"] for record in records if record["claimed"] != record["referee"]] if bad: final = dict(final) final["assurance"] = 0 final["reasons"] = list(final.get("reasons", [])) + ["referee"] final["detected"] = list(final.get("detected", [])) + bad return final
def independent_echo(dossier: Dict[str, Any]) -> bool: """Recompute the echo check from the transcript, without asking the node that wrote it.""" struc_verdict = dossier.get("struc") or {} if not struc_verdict.get("problem_struc"): return True for key in ("reading_a", "reading_b", "reading_direct"): reading = dossier.get(key) or {} if reading.get("sentence") and not coverage.echo_matches(reading, struc_verdict): return False return True
def checked_verdict(dossier: Dict[str, Any], records: List[Dict[str, Any]], arbiter_expected: bool = True) -> Dict[str, Any]: """The verdict a user is shown: recomputed from the evidence, then the more cautious of the two.""" try: evidence = dict(dossier) evidence["echo_ok"] = independent_echo(dossier) recomputed = referee_adjusted(decide.decide(evidence), records) except (AttributeError, KeyError, TypeError, ValueError, IndexError, ArithmeticError) as error: return _unknown("the decision rule could not read the evidence: %s" % error) arbiter = dossier.get("final") if not isinstance(arbiter, dict) or "state" not in arbiter or "assurance" not in arbiter: return _unknown("the arbiter produced no verdict") if arbiter_expected else recomputed if arbiter["state"] == recomputed["state"] and arbiter.get("answer") == recomputed.get("answer"): return recomputed final = dict(recomputed if recomputed["assurance"] <= int(arbiter.get("assurance", 0) or 0) else arbiter) final["reasons"] = list(final.get("reasons", [])) + ["arbiter and recomputed decision disagree"] final["detected"] = list(final.get("detected", [])) + ["arbiter"] return final12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879"""Envelope helpers: the dossier travels inside payload.naturalLanguage.
The orchestrator forwards only the payload of the previous message, so the growing record of asession (the dossier) is serialised as JSON after a marker line in ``naturalLanguage``. The textbefore the marker is a one line human summary. This is the same contract the structures topology uses,which is what lets one orchestrator run either topology without knowing the difference.
The dossier of a stratum session holds, in the order the nodes write it:
``question`` the sentence as the user wrote it, in the user's own language``lang`` the variety the answer must be written back in``reading_a`` what reader A (surface patterns) understood, with its notes``reading_b`` what reader B (marker frames) understood, with its notes``compare`` whether the two readings are the same structure, and on what grounds``coverage`` whether the agreed reading kept every number the user wrote``sent`` the sentence of the structures language handed to the structures topology``struc`` the verdict the structures topology returned, copied without any change``final`` the state, the assurance and the answer shown to the user``crash`` a role that failed, so the arbiter can report UNKNOWN instead of pretending"""
import jsonfrom typing import Any, Dict, List, Optional
MARK = "@@DOSSIER@@"
def encode(summary: str, dossier: Dict[str, Any]) -> str: return summary.replace("\n", " ") + "\n" + MARK + json.dumps(dossier, sort_keys=True, separators=(",", ":"))
def decode(text: str) -> Dict[str, Any]: """Return the dossier, or a fresh one holding the raw text as the user question.""" if MARK in text: return json.loads(text.split(MARK, 1)[1]) return {"v": 1, "question": text.strip(), "lang": "en"}
def summary_of(text: str) -> str: return text.split("\n", 1)[0]
def envelope( node_id: str, recipient: Optional[str], turn: int, tick: int, summary: str, ast: str, dossier: Dict[str, Any], decls: List[str], assertions: List[str], claimed: str,) -> Dict[str, Any]: out: Dict[str, Any] = { "sender": node_id, "turn": turn, "volatileState": {"internalTimeTick": tick}, "payload": { "naturalLanguage": encode(summary, dossier), "abstractSyntaxTree": ast, "smtConstraints": {"declarations": decls, "assertions": assertions, "z3Status": claimed}, }, } if recipient: out["recipient"] = recipient return out
def start(incoming: Dict[str, Any]): """Decode an incoming envelope into (dossier, turn, tick, sender).""" dossier = decode(incoming["payload"]["naturalLanguage"]) tick = int(incoming.get("volatileState", {}).get("internalTimeTick", 0)) return dossier, int(incoming["turn"]), tick, incoming["sender"]
def out(node_id: str, rcpt: str, turn: int, tick: int, dossier: Dict[str, Any], summary: str, ast: str, decls: List[str], asserts: List[str], claimed: str) -> Dict[str, Any]: return envelope(node_id, rcpt, turn, tick, summary, ast, dossier, decls, asserts, claimed)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290"""Reader A: the strict reader, matching the surface patterns of the lexicon.
Reader A holds the sentence against the **patterns** of a language variety: each accepted shape iswritten out in ``lexicon/<lang>.json`` with the values of the structures language in slots. A patternmatches only if every function word it names is present, in order, and if every verb, every markerand every number the user wrote is accounted for. That strictness is the point: when A produces asentence it read one of the documented shapes and nothing else.
Reader B (:mod:`lgstratum.read_b`) does something different with the same data -- it looks for thejoints a kind of the structures language requires, wherever they stand, and fills the slots from theregions those joints introduce -- and the topology only trusts a reading the two agree on. What thetwo readers share is the lexicon, the atomiser in :mod:`lgstratum.segment` and the shape of thebracket notation in :mod:`lgstratum.canonical`, just as the two formalizers of the structurestopology share one written grammar and one token spec.
A slot of this family is not one run of notation and this reader knows it: a number, a word of aclosed set, a frame and a section are four different things, and a slot that wants a frame takes oneand refuses a number. That typing is what keeps a sentence about a section from being read as asentence about a structure, which is the mistake this whole bundle exists to catch."""
import refrom typing import Any, Dict, List, Optional, Tuple
from . import canonical, lexiconfrom .canonical import ReadingErrorfrom .segment import atomize, fold, word_pieces
_SLOT = re.compile(r"\{([A-Z][A-Z0-9]*)\}")
def compile_pattern(pattern: str) -> Tuple[List[List[str]], List[str]]: """Split a surface pattern into its literal word chunks and its slot names, in order.""" parts = _SLOT.split(pattern) chunks: List[List[str]] = [] slots: List[str] = [] index = 0 while index < len(parts): chunks.append([fold(piece) for word in parts[index].split() for piece in word_pieces(word)]) index += 1 if index < len(parts): slots.append(parts[index]) index += 1 return chunks, slots
def scan(lang: str, text: str) -> List[Dict[str, Any]]: """Tag every atom: a run of the notation, or a lexicon phrase with its role and value.
One longest match per position decides between verb, marker and noise, which is why a data file must not give one phrase two roles. A variety that writes "carichi" for the block of loads and "carico" for a single load gets both, and the longest match is what keeps the two apart. """ phrases = lexicon.phrase_index(lang) attached = lexicon.prefixes(lang) stripped_index = lexicon.prefix_index(lang) if attached else {} longest = lexicon.max_phrase_length(lang) atoms = atomize(text) items: List[Dict[str, Any]] = [] index = 0 while index < len(atoms): kind, atom = atoms[index] if kind == "m": items.append({"role": "num", "value": atom, "words": [], "surface": atom}) index += 1 continue word = fold(atom) hit = None for span in range(min(longest, len(atoms) - index), 0, -1): if any(atoms[index + step][0] != "w" for step in range(span)): continue window = tuple(fold(atoms[index + step][1]) for step in range(span)) if window in phrases: hit = (phrases[window], window) break if attached: key = tuple(lexicon.strip_prefix(w, attached) for w in window) if key in stripped_index: hit = (stripped_index[key], key) break if hit: (role, value), key = hit # The item carries the atoms as the sentence wrote them; the lexicon key it matched is # kept only to look the verb up, because Arabic writes a lexicon word with prefixes # attached and the data file records it without them. item = {"role": role, "value": value, "words": list(window), "surface": atom} if role == "verb": table = lexicon.verb_atoms_index(lang) item["kinds"] = table.get(window) or table.get(key) or (value,) items.append(item) index += len(window) continue if atom and atom in lexicon.noise_chars(lang): # A single character particle of a script written without spaces (Chinese particles). # It carries its own atom as its words so that a pattern naming the particle can match # it; it carries no value, so it never reaches the value of a slot. items.append({"role": "noise", "value": "", "words": [word], "surface": atom}) index += 1 continue items.append({"role": "unknown", "value": word, "words": [word], "surface": atom}) index += 1 return items
def _claim(words: List[str], chunk_slice: List[str], attached: List[str]) -> bool: """Whether the atoms an item carries are the atoms a chunk of the pattern asks for.
Arabic writes a word with its article and its conjunctions attached to it, and the pattern in the data file names the bare word. Stripping the attachment from both sides is what lets a pattern name a word the sentence wrote in another form, and nothing else is forgiven: an item that carries no atoms is the notation, and a bracket is never a word of a pattern. """ if not words: return False if list(words) == list(chunk_slice): return True if not attached: return False return ([lexicon.strip_prefix(word, attached) for word in words] == [lexicon.strip_prefix(word, attached) for word in chunk_slice])
def _find(chunk: List[str], items: List[Dict[str, Any]], start: int, attached: List[str]) -> Optional[Tuple[int, int]]: """Where in the item stream the literal words of a pattern chunk appear, or ``None``.
A chunk is contiguous: it may not span a piece of the notation, and no function word the pattern did not name may sit inside it. That is what stops a pattern from swallowing a sentence it does not describe. """ for first in range(start, len(items) + 1): cursor = first taken = 0 ok = True while taken < len(chunk): if cursor >= len(items): ok = False break words = items[cursor]["words"] if not _claim(words, chunk[taken:taken + len(words)], attached): ok = False break taken += len(words) cursor += 1 if ok: return first, cursor return None
def _empty(items: List[Dict[str, Any]], start: int, stop: int) -> bool: """Whether the stretch between a slot and the next chunk of the pattern holds only function words.
A slot of this family takes exactly what its type asks for, so a number left standing between the slot and the words that follow it is a number the pattern has no place for. Refusing it is the honest answer; guessing which slot wanted it would be the reader inventing the problem. """ return all(item["role"] == "noise" for item in items[start:stop])
def _values(items: List[Dict[str, Any]]) -> List[str]: """The canonical value of every item, as the shape of the bracket notation wants to see them.""" return [item["value"] if item["role"] in ("num", "marker") else "" for item in items]
def _slot(kind: str, slot: str, items: List[Dict[str, Any]], position: int, vals: List[str]) -> Optional[Tuple[str, int]]: """The value of one slot taken from the stream, and where the stream continues.
Four kinds of value, four ways of taking it: a number is one run of digits the atomiser cut; a word of a closed set is one marker whose value the lexicon already translated; a frame or a section is a region of the notation, and its text is handed to the shape check of :mod:`lgstratum.canonical`, which is what says whether the region really is a frame. """ what = canonical.SLOT_KIND[kind][slot] while position < len(items) and items[position]["role"] == "noise": # A function word may stand between the words of the pattern and the value of a slot -- # "verifica la flessione" says the article between the verb and the quantity -- and it is # still the same pattern. A verb, a marker or a number is not skipped: those the pattern has # to name, and a pattern that skipped one would be reading a sentence it did not describe. position += 1 if what == "num": if position >= len(items) or items[position]["role"] != "num": return None pieces = canonical.tokens(items[position]["value"]) if len(pieces) != 1: return None try: return canonical.value(pieces[0]), position + 1 except ReadingError: return None if what in ("quantity", "direction", "mode", "end"): if position >= len(items) or items[position]["role"] != "marker": return None return items[position]["value"], position + 1 end = canonical.extent(vals, position) if end < 0: return None text = canonical.region_text(vals, position, end) try: checked = canonical.frame(text) if what == "frame" else canonical.section(text) except ReadingError: return None return checked, end
def match(kind: str, chunks: List[List[str]], slots: List[str], items: List[Dict[str, Any]], attached: List[str]) -> Optional[Dict[str, str]]: """A value per slot name, or ``None`` when the pattern does not describe the items.
Every verb, every marker and every number of the sentence has to be consumed by the pattern, and a pattern that leaves one out is a pattern that misread the sentence. The values come back as the structures language writes them, because the slot types and the shape check of the notation ran while they were taken. """ vals = _values(items) filled: Dict[str, str] = {} position = 0 if chunks[0]: found = _find(chunks[0], items, 0, attached) if found is None or not _empty(items, 0, found[0]): return None position = found[1] for index, slot in enumerate(slots): got = _slot(kind, slot, items, position, vals) if got is None: return None filled[slot], position = got chunk = chunks[index + 1] if chunk: found = _find(chunk, items, position, attached) if found is None or not _empty(items, position, found[0]): return None position = found[1] if not _empty(items, position, len(items)): return None return filled
def read(lang: str, text: str) -> Dict[str, Any]: """The reading reader A reaches in one variety, and why it abstained when it did.""" items = scan(lang, text) result: Dict[str, Any] = {"reader": "reader_a", "lang": lang, "mode": "pattern", "kind": None, "sentence": None, "slots": {}, "markers": [], "notes": []} unknown = [item for item in items if item["role"] == "unknown"] if unknown: result["status"] = "NOT COVERED" for item in unknown: result["notes"].append({"reason": "unknown_word", "word": item["surface"]}) return result result["markers"] = [item["value"] for item in items if item["role"] == "marker"] candidates, why = lexicon.announce(lang, items) if not candidates: result["status"] = "NOT COVERED" result["notes"].append(why) return result attached = lexicon.prefixes(lang) found: List[Tuple[str, str, Dict[str, str]]] = [] for kind in candidates: for pattern in lexicon.patterns(lang).get(kind, []): chunks, slots = compile_pattern(pattern) filled = match(kind, chunks, slots, items, attached) if filled is None: continue try: sentence = canonical.fill(kind, filled) except ReadingError as error: result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)}) continue if not any(entry[1] == sentence for entry in found): found.append((kind, sentence, filled)) if not found: result["status"] = "NOT COVERED" if not result["notes"]: result["notes"].append({"reason": "no_pattern"}) return result if len(found) > 1: result["status"] = "AMBIGUOUS" result["notes"].append({"reason": "multiple", "first": found[0][1], "second": found[1][1]}) return result read_kind, sentence, filled = found[0] result["status"] = "READ" result["kind"] = read_kind result["variant"] = list(filled) result["sentence"] = sentence result["slots"] = filled result["literals"] = canonical.numbers(text) result["notes"] = [] return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310"""Reader B: the reader of joints, which never looks at a surface pattern.
Reader B is built to fail in a different way from reader A. It does not know the patterns a languagevariety writes down; it knows only which **joints** a kind of the structures language requires --``member``, ``at``, ``section``, ``limit``, ``ends``, ``length``, ``modulus``, ``node`` -- and wherethe words of a closed set stand. A sentence is read when the joints it carries are exactly the jointsof one form of the kind, in the order the structures language puts them, and when the numbers fallinto the regions those joints introduce.
That is a different question from A's. A asks "does this sentence have the shape this varietydocuments"; B asks "does this sentence carry the joints the structures language requires, and are thenumbers where those joints put them". A sentence can pass one and fail the other: a paraphrase thatkeeps every joint but drops a documented word, or a sentence of a documented shape whose ``limit``never arrives. The topology trusts a reading only when both arrive at the same problem, and that isthe whole purpose of the two readers.
Both readers fold the bracket notation with the same shape check, the one in:mod:`lgstratum.canonical`, and then B treats a frame as one region of the sentence rather than as ahundred words: inside the brackets there are block names and support names, but they are not joints ofthe question, and a reader that counted them as joints would ask the user for a frame inside a frame."""
import refrom typing import Any, Dict, List, Optional, Sequence, Tuple
from . import canonical, lexiconfrom .canonical import ReadingErrorfrom .segment import atomize, fold
# What a placeholder of a marker sequence accepts: the head word of a region, or a word of the closed# set that slot reads. A number never appears in a sequence, so nothing here accepts digits._HEAD = {"frame": canonical.FRAME_WORD, "section": canonical.SECTION_FORMS}_CLOSED = {"quantity": canonical.QUANTITIES, "direction": canonical.DIRECTIONS, "mode": canonical.VERIFY_MODES, "end": tuple(sorted(set(canonical.END_KINDS) | set(canonical.END_FROM_VALUE)))}_REGION = ("frame", "section")_PLACEHOLDER = re.compile(r"^\{([A-Z][A-Z0-9]*)\}$")
def find_spans(lang: str, atoms: Sequence[Tuple[str, str]]) -> Tuple[List[Tuple[int, int, str, str]], List[bool]]: """Claim the longest lexicon phrase at every position, never overlapping an earlier claim.
The inventory is the whole lexicon -- verbs, joints, block names, words of a closed set, function words -- and the longest match wins, which is how a variety that says ``von Mises`` for one quantity and ``Mises`` for nothing keeps the two apart. """ phrases = lexicon.phrase_index(lang) attached = lexicon.prefixes(lang) stripped = lexicon.prefix_index(lang) if attached else {} longest = lexicon.max_phrase_length(lang) covered = [False] * len(atoms) spans: List[Tuple[int, int, str, str]] = [] for width in range(longest, 0, -1): for start in range(0, len(atoms) - width + 1): if any(covered[start:start + width]): continue if any(atoms[start + step][0] != "w" for step in range(width)): continue window = tuple(fold(atoms[start + step][1]) for step in range(width)) hit = phrases.get(window) key = window if hit is None and attached: key = tuple(lexicon.strip_prefix(word, attached) for word in window) hit = stripped.get(key) if hit is None: continue for position in range(start, start + width): covered[position] = True spans.append((start, start + width, hit[0], hit[1])) return spans, covered
def classify(lang: str, atoms: Sequence[Tuple[str, str]], spans: Sequence[Tuple[int, int, str, str]], covered: Sequence[bool]) -> List[Dict[str, Any]]: """One item per atom, with the role the lexicon gave it and the canonical value it carries.""" by_start = {span[0]: span for span in spans} items: List[Dict[str, Any]] = [] index = 0 while index < len(atoms): span = by_start.get(index) if span is None and atoms[index][0] == "m": items.append({"role": "num", "value": atoms[index][1], "words": [], "surface": atoms[index][1]}) index += 1 continue if span is None: word = fold(atoms[index][1]) if atoms[index][1] and atoms[index][1] in lexicon.noise_chars(lang): items.append({"role": "noise", "value": "", "words": [word], "surface": atoms[index][1]}) else: items.append({"role": "unknown", "value": word, "words": [word], "surface": atoms[index][1]}) index += 1 continue _, stop, role, value = span item = {"role": role, "value": value, "words": [fold(atoms[step][1]) for step in range(index, stop)], "surface": atoms[index][1]} if role == "verb": item["kinds"] = (value,) items.append(item) index = stop return items
def _values(items: Sequence[Dict[str, Any]]) -> List[str]: """The canonical value of every item, as the shape of the bracket notation wants to see them.""" return [item["value"] if item["role"] in ("num", "marker") else "" for item in items]
def fold_regions(items: List[Dict[str, Any]]) -> Tuple[List[Dict[str, Any]], List[Dict[str, str]]]: """Replace each region of the notation by a single item, and report what is not a region.
A region is a frame or a section: the head word followed by its blocks and brackets. B folds it because it reads the sentence by joints, and inside the brackets stand words that name blocks and supports, none of which is a joint of the question. The fold is where the notation is checked, so an unterminated block or a block out of order is reported here and nowhere else in this reader. """ vals = _values(items) out: List[Dict[str, Any]] = [] notes: List[Dict[str, str]] = [] index = 0 while index < len(items): item = items[index] if item["role"] != "marker" or item["value"] not in canonical.REGION_HEADS: out.append(item) index += 1 continue end = canonical.extent(vals, index) if end < 0: notes.append({"reason": "no_frame", "kind": item["value"], "detail": "the notation that starts there is not a frame or a section"}) out.append(item) index += 1 continue text = canonical.region_text(vals, index, end) try: checked = (canonical.frame(text) if item["value"] == canonical.FRAME_WORD else canonical.section(text)) except ReadingError as error: notes.append({"reason": "no_frame", "kind": item["value"], "detail": str(error)}) out.append(item) index += 1 continue out.append({"role": "region", "value": item["value"], "text": checked, "words": []}) index = end return out, notes
def _regions(items: Sequence[Dict[str, Any]]) -> List[Tuple[Optional[str], str]]: """The stretches of numbers between the joints, each tagged with the joint before it.
A folded region is a boundary and not a stretch: the numbers inside a frame belong to the frame, and B has already taken them as the value of its slot. """ out: List[Tuple[Optional[str], str]] = [] joint: Optional[str] = None buffer: List[str] = [] for item in items: if item["role"] in ("verb", "region"): if buffer: out.append((joint, canonical.tidy(" ".join(buffer)))) buffer = [] joint = None continue if item["role"] in ("marker", "unknown"): if buffer: out.append((joint, canonical.tidy(" ".join(buffer)))) buffer = [] joint = item["value"] if item["role"] == "marker" else None continue if item["role"] == "num": buffer.append(item["value"]) if buffer: out.append((joint, canonical.tidy(" ".join(buffer)))) return out
def _agrees(expected: Sequence[str], carried: Sequence[Dict[str, Any]], kind: str, variant: Sequence[str]) -> Optional[Dict[str, str]]: """Match the joints of the sentence against the joints of one form, and take the values they carry.
A placeholder for a region of the notation takes the whole folded region, head word included, and not the head word alone: the frame of a structure is its blocks, not the word that opens them. """ if len(expected) != len(carried): return None filled: Dict[str, str] = {} for want, item in zip(expected, carried): got = item["value"] match = _PLACEHOLDER.fullmatch(want) if match is None: if want != got: return None continue slot = match.group(1) what = canonical.SLOT_KIND[kind][slot] if what in _REGION: if got not in _HEAD[what]: return None if slot in variant: filled[slot] = item.get("text") or got elif got in _CLOSED.get(what, ()): if slot in variant: filled[slot] = got else: return None return filled
def _numbers(regions: Sequence[Tuple[Optional[str], str]], kind: str, variant: Sequence[str]) -> Optional[Dict[str, str]]: """The number of each slot, taken from the region the joint before it introduces.
Every joint of the structures language that introduces a number introduces exactly one, and every number of the sentence has to land in a slot: a number standing outside both the frame and any slot is a number this form has no place for, and that is a reading to refuse rather than a number to guess at. """ gaps = canonical.gap_markers(kind, variant) slots = list(variant) used = set() filled: Dict[str, str] = {} for position, slot in enumerate(slots): if canonical.SLOT_KIND[kind][slot] != "num": continue joint = gaps[position] if position < len(gaps) else None if joint is None: return None hits = [index for index, (tag, _) in enumerate(regions) if tag == joint and index not in used] if len(hits) != 1: return None pieces = canonical.tokens(regions[hits[0]][1]) if len(pieces) != 1: return None try: filled[slot] = canonical.value(pieces[0]) except ReadingError: return None used.add(hits[0]) for index, (_, text) in enumerate(regions): if index not in used and canonical.tokens(text): return None return filled
def read(lang: str, text: str) -> Dict[str, Any]: """The reading reader B reaches in one variety, and why it abstained when it did.""" atoms = atomize(text) spans, covered = find_spans(lang, atoms) items = classify(lang, atoms, spans, covered) result: Dict[str, Any] = {"reader": "reader_b", "lang": lang, "mode": "joints", "kind": None, "sentence": None, "slots": {}, "markers": [], "notes": []} unknown = [item for item in items if item["role"] == "unknown"] if unknown: result["status"] = "NOT COVERED" for item in unknown: result["notes"].append({"reason": "unknown_word", "word": item["surface"]}) return result items, notes = fold_regions(items) result["notes"].extend(notes) carried = [item for item in items if item["role"] in ("marker", "region")] result["markers"] = [item["value"] for item in carried] candidates, why = lexicon.announce(lang, items) if not candidates: result["status"] = "NOT COVERED" result["notes"].append(why) return result found: List[Tuple[str, List[str], str, Dict[str, str]]] = [] for kind in candidates: for variant in canonical.VARIANTS.get(kind, []): expected = canonical.marker_sequence(kind, variant) filled = _agrees(expected, carried, kind, variant) if filled is None: continue values = _numbers(_regions(items), kind, variant) if values is None: continue filled.update(values) try: sentence = canonical.fill(kind, filled) except ReadingError as error: result["notes"].append({"reason": "no_frame", "kind": kind, "detail": str(error)}) continue if not any(entry[2] == sentence for entry in found): found.append((kind, list(variant), sentence, filled)) if not found: result["status"] = "NOT COVERED" if not result["notes"]: result["notes"].append({"reason": "no_markers"}) return result if len(found) > 1: result["status"] = "AMBIGUOUS" result["notes"].append({"reason": "multiple", "first": found[0][2], "second": found[1][2]}) return result read_kind, variant, sentence, filled = found[0] result["status"] = "READ" result["kind"] = read_kind result["variant"] = list(variant) result["sentence"] = sentence result["slots"] = filled result["literals"] = canonical.numbers(text) result["notes"] = [] return result123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141"""The answer the user reads, in the language the user wrote in.
Nothing here decides anything: the text is built from the verdict ``decide`` produced and from thewords the lexicon of that language provides. Two kinds of text meet in one reply, and the boundarybetween them is deliberate:
* every label, state name and reason is taken from ``lexicon/<lang>.json``, so the framing of the answer belongs to the user's language;* the mechanics content -- the canonical sentence the stratum understood and the answer the structures topology returned -- is passed through byte for byte, because it is a value and not prose.
The sentence the stratum understood is always shown. A user who wrote in Italian and gets back``cut member 1 at 1 frame nodes [ 1 0 0 ; 2 4 0 ] ...`` can see which reading was used, and that isthe whole point of a stratum: the interpretation is inspectable, not hidden inside a model.
When no answer can be shown, the reply says so in the user's language and lists the forms thislanguage variety does understand, from ``lexicon.examples``, so the failure is a correction and not adead end."""
import refrom typing import Any, Dict, List, Optional
from . import decide as decide_modulefrom . import lexicon
FIELDS = ("word", "kind", "detail", "left", "right", "slot")_PLACEHOLDER = re.compile(r"\{[a-z_]+\}")
def _fill(text: str) -> str: """Drop a placeholder the template kept: an unfilled brace must never reach the user.""" return _PLACEHOLDER.sub("", text).replace(" ", " ").strip(" ;,:")
def note_fields(dossier: Dict[str, Any]) -> Dict[str, Dict[str, Any]]: """The fields each reason carries, collected from the notes the readers left behind.""" out: Dict[str, Dict[str, Any]] = {} for reading in [dossier.get("reading_a") or {}, dossier.get("reading_b") or {}, dossier.get("reading_direct") or {}]: for note in reading.get("notes") or []: if isinstance(note, dict) and note.get("reason"): fields = {key: note[key] for key in FIELDS if key in note} out.setdefault(str(note["reason"]), fields) for reason, fields in ((dossier.get("struc") or {}).get("reason_fields") or {}).items(): out.setdefault(str(reason), dict(fields)) return out
def _kind_understood(dossier: Dict[str, Any]) -> str: """The kind of problem the stratum solved, as the identifier the structures language uses.""" for key in ("reading_a", "reading_b", "reading_direct"): reading = dossier.get(key) or {} if reading.get("kind"): return str(reading["kind"]) return ""
def _sentence(dossier: Dict[str, Any]) -> str: """The canonical sentence that was, or would have been, handed to the structures topology.""" comparison = dossier.get("compare") or {} struc_verdict = dossier.get("struc") or {} for source in (dossier.get("sent"), comparison.get("left"), struc_verdict.get("problem_struc")): if source: return str(source) for key in ("reading_a", "reading_b", "reading_direct"): reading = dossier.get(key) or {} if reading.get("sentence"): return str(reading["sentence"]) return ""
def _check_line(lang: str, records: Optional[List[Dict[str, Any]]]) -> str: """How many envelopes of the run the referee of the orchestrator confirmed.""" if not records: return "" good = sum(1 for record in records if record.get("claimed") == record.get("referee")) return lexicon.labels(lang)["check"].format(a=good, b=len(records))
def reply(dossier: Dict[str, Any], final: Optional[Dict[str, Any]] = None, records: Optional[List[Dict[str, Any]]] = None, lang: Optional[str] = None) -> Dict[str, Any]: """Build the user-facing answer: one text block plus the machine-readable parts.""" lang = lang or str(dossier.get("lang") or "en") if lang not in lexicon.codes(): lang = "en" verdict = final or decide_module.decide(dossier) labels = lexicon.labels(lang) states = lexicon.reading_labels(lang) fields = note_fields(dossier)
lines: List[str] = [] state = str(verdict.get("state", "NONE")) lines.append("%s: %s" % (labels["status"], states.get(state, state))) sentence = _sentence(dossier) kind = _kind_understood(dossier) if sentence and state not in ("NOT COVERED", "NONE"): lines.append("%s (%s): %s" % (labels["understood"], kind, sentence)) if verdict.get("answer"): lines.append("%s: %s" % (labels["answer"], verdict["answer"])) lines.append(labels["assurance"].replace("{n}", str(verdict.get("assurance", 0)))) struc_verdict = dossier.get("struc") or {} if struc_verdict.get("status"): # Which road of the topology proved what is its own bookkeeping and nothing the reader of an # answer asked for; what belongs in the reply is the verdict and, when the topology abstained, # the reason it abstained. tail = str(struc_verdict["status"]) why = struc_verdict.get("reason") or struc_verdict.get("note") or "" if not why and struc_verdict.get("reasons"): why = str(struc_verdict["reasons"][0]) if why: tail += " (" + why + ")" lines.append("%s: %s" % (labels["struc_layer"], tail)) reasons = [str(reason) for reason in verdict.get("reasons") or []] if reasons: struc_verdict = dossier.get("struc") or {} fields.setdefault("referee", {"detail": ", ".join(str(item) for item in verdict.get("detected") or [])}) fields.setdefault("struc_unknown", {"detail": str(struc_verdict.get("reason") or struc_verdict.get("note") or "")}) texts = [_fill(lexicon.translate_reason(lang, reason, **(fields.get(reason) or {}))) for reason in reasons] lines.append("%s: %s" % (labels["notes"], "; ".join(texts))) check = _check_line(lang, records) if check: lines.append(check) if state in ("NOT COVERED", "AMBIGUOUS", "NONE") and not verdict.get("answer"): samples = lexicon.examples(lang) if samples: lines.append("%s: %s" % (labels["question"], " | ".join(samples[:5]))) return { "lang": lang, "language": lexicon.language_name(lang), "state": state, "assurance": verdict.get("assurance", 0), "answer": verdict.get("answer", ""), "sentence": sentence, "kind": kind, "reasons": reasons, "lines": lines, "text": "\n".join(lines), }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242"""Script aware tokenisation and digit normalisation of a natural language sentence.
This module knows nothing about the languages: it splits a sentence into runs of *words* andruns of *notation*, and it puts every digit in the shape the structures language uses. Themapping from a word to a role is the lexicon, in ``lexicon/<lang>.json`` and:mod:`lgstratum.lexicon`.
Three normalisations happen here, and all three are testable on their own:
* digit scripts: Arabic-Indic, Extended Arabic-Indic and Devanagari digits become ASCII digits, and compatibility normalisation turns the full width forms a Chinese keyboard produces into their ASCII counterparts;* separators that differ per language: the Arabic decimal sign, the Arabic and Devanagari commas, the CJK full stop and question mark, and the bidi control characters disappear or take their ASCII counterpart;* context for ``.`` and ``,``: a dot is part of a number only between digits, a comma is part of the notation only between two closed operands, which is what separates an Italian sentence comma from the comma of a list written between brackets."""
import reimport unicodedatafrom typing import List, Tuple
# ---------------------------------------------------------------------------# Digits and separators# ---------------------------------------------------------------------------def _digits(start: int) -> dict: return {chr(start + i): str(i) for i in range(10)}
DIGIT_MAP: dict = {}DIGIT_MAP.update(_digits(0x0660)) # Arabic-IndicDIGIT_MAP.update(_digits(0x06F0)) # Extended Arabic-Indic (Persian/Urdu)DIGIT_MAP.update(_digits(0x0966)) # DevanagariDIGIT_MAP.update(_digits(0x09E6)) # Bengali
SEPARATOR_MAP: dict = { "\u060c": " ", # Arabic comma "\u061b": " ", # Arabic semicolon "\u061f": " ", # Arabic question mark "\u066b": ".", # Arabic decimal sign "\u066c": "", # Arabic thousands separator "\u066d": " ", # Arabic date separator "\u0964": " ", # Devanagari danda "\u0965": " ", # Devanagari double danda "\u3001": " ", # ideographic comma "\u3002": " ", # ideographic full stop "\uff1f": " ", # full width question mark "\uff01": " ", # full width exclamation mark "\u201e": " ", "\u201f": " ", "\u2018": " ", "\u2019": "'", # the apostrophe of an elision is kept, and the elision is split apart "\u201c": " ", "\u201d": " ", # The Italian copula would otherwise fold to the connective "e" (and), so it is not a word. "\u00e8": " ", "\u2013": "-", "\u2014": "-", "\u2212": "-", # minus sign "\u00d7": "*", # multiplication sign "\u00b7": "*", # middle dot "\u00f7": "/", # division sign "\u2265": ">=", "\u2264": "<=", "\u2260": "!=",}
INVISIBLE = ( "\u200b\u200c\u200d\u200e\u200f\u061c\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069\ufeff")
# The symbols of the bracket notation, square brackets and semicolons included: the blocks of a# frame are written with them, so they have to be read as notation and not dropped as stray# punctuation. The arithmetic symbols are here too, because a person who writes the abscissa of a# cut as "2/1875" or as "-15" writes them inside their own sentence.NOTATION_CHARS = set("0123456789+-*/^()[]<>=!|,:.;")CLOSED_CHARS = set("0123456789)]")OPENING_CHARS = set("0123456789[(")
# The relation and operator symbols the structures language accepts. Nothing else is a number.OPERATORS = ("=>", "<=>", "<=", ">=", "!=", "+", "-", "*", "/", "^", "=", "<", ">", "|")
def normalize(text: str) -> str: """Return the sentence in a canonical shape: ASCII digits, ASCII separators, one space.""" text = unicodedata.normalize("NFKC", text) for ch in INVISIBLE: text = text.replace(ch, "") text = text.translate({ord(k): v for k, v in DIGIT_MAP.items()}) text = text.translate({ord(k): v for k, v in SEPARATOR_MAP.items()}) return re.sub(r"\s+", " ", text).strip()
def script_of(text: str) -> str: """The dominant non Latin script of a sentence: cjk, arabic, devanagari, latin or none.""" counts = {"cjk": 0, "arabic": 0, "devanagari": 0, "latin": 0} for ch in text: if not ch.isalpha(): continue name = unicodedata.name(ch, "") if name.startswith("CJK") or name.startswith("IDEOGRAPHIC"): counts["cjk"] += 1 elif name.startswith("ARABIC"): counts["arabic"] += 1 elif name.startswith("DEVANAGARI"): counts["devanagari"] += 1 elif name.startswith("LATIN"): counts["latin"] += 1 best = max(counts, key=lambda k: counts[k]) return best if counts[best] else "none"
def _is_notation_char(ch: str, text: str, index: int) -> bool: if ch in NOTATION_CHARS: if ch == ".": return _neighbour(text, index, -1).isdigit() and _neighbour(text, index, 1).isdigit() if ch == ",": return _neighbour(text, index, -1) in CLOSED_CHARS and _neighbour(text, index, 1) in OPENING_CHARS return True return False
def _neighbour(text: str, index: int, step: int) -> str: j = index + step while 0 <= j < len(text) and text[j] == " ": j += step return text[j] if 0 <= j < len(text) else ""
_MARKS = ("Mn", "Mc", "Me")
def _word_char(ch: str) -> bool: """A character of a word: a letter of any script, an apostrophe, or a combining mark.
The combining marks matter: the vowel signs of Devanagari and the Arabic diacritics are not letters, and dropping them would break a word into pieces that no lexicon entry matches. """ return ch.isalpha() or ch in "_'" or unicodedata.category(ch) in _MARKS
def pieces(run: str) -> List[str]: """Split a word run at every apostrophe: an Italian elision is two words to the lexicon.
``l'integrale`` is the article ``l`` and the noun ``integrale``, and only the second of the two is a phrase of the lexicon. The lexicon patterns are written with the elision joined, and compiled through this same function, so data and matching agree. """ return [piece for piece in run.split("'") if piece]
def is_cjk(run: str) -> bool: """Whether a run is written in Chinese characters.""" return any(unicodedata.name(ch, "").startswith(("CJK", "IDEOGRAPHIC")) for ch in run)
def word_pieces(run: str) -> List[str]: """The atoms a word run offers the lexicon: characters for Chinese, pieces elsewhere.
Chinese is written without spaces, so the only reliable unit is the character, and a multi character term of the lexicon is then a sequence of atoms -- which is how the lexicon file writes it too, one space separated token per character group. """ if is_cjk(run): return list(run) return pieces(run)
def atomize(text: str) -> List[Tuple[str, str]]: """A normalized sentence as atoms: ``("m", run)`` notation, ``("w", word)`` word atoms.
Both readers start here. It is one of the two things they share -- the other is the lexicon -- and it is the counterpart of the shared token spec that the two formalizers of the structures topology share: sharing the atomiser buys agreement about *what the words are*, while the two readers still disagree, productively, about what the sentence means. """ out: List[Tuple[str, str]] = [] for kind, run in tokens(text): if kind == "m": out.append(("m", run)) else: for piece in word_pieces(run): out.append(("w", piece)) return out
def tokens(text: str) -> List[Tuple[str, str]]: """Split a normalized sentence into ``("m", run)`` notation and ``("w", run)`` words.
Letters of every script open a word run, digits and the symbols of the structures language open a notation run. An ASCII letter run is returned as a word: :mod:`lgstratum.read_a` and :mod:`lgstratum.read_b` decide between a variable and a function word through the lexicon. """ text = normalize(text) out: List[Tuple[str, str]] = [] index = 0 while index < len(text): ch = text[index] if ch.isspace(): index += 1 continue if _word_char(ch): start = index while index < len(text) and _word_char(text[index]): index += 1 out.append(("w", text[start:index])) continue if _is_notation_char(ch, text, index): start = index while index < len(text) and _is_notation_char(text[index], text, index): index += 1 run = text[start:index].strip() if run: out.append(("m", run)) continue index += 1 return out
def numeric_literals(text: str) -> List[str]: """Every numeric literal of a sentence, in the order it appears, digits normalised.""" found: List[str] = [] for _kind, run in tokens(text): for match in re.finditer(r"\d+(?:\.\d+)?", run): found.append(match.group(0)) return found
def fold(word: str) -> str: """Casefold a Latin word and drop its accents, so that one lexicon entry covers both cases.
Non Latin scripts are returned unchanged: casefolding and accent folding do not apply to Chinese, Devanagari or Arabic, and the lexicon entries are written in the form the keyboard produces. """ if not any("a" <= ch.lower() <= "z" for ch in word): return word decomposed = unicodedata.normalize("NFD", word) stripped = "".join(ch for ch in decomposed if not unicodedata.combining(ch)) return stripped.lower()lgstratum/__init__.pyDeleted-20
lgstratum/agents.pyDeleted-291
lgstratum/canonical.pyDeleted-664
lgstratum/compare.pyDeleted-360
lgstratum/corpus.pyDeleted-82
lgstratum/coverage.pyDeleted-108
lgstratum/decide.pyDeleted-168
lgstratum/faults.pyDeleted-174
lgstratum/invoker.pyDeleted-125
lgstratum/lexicon.pyDeleted-346
lgstratum/pipeline.pyDeleted-118
lgstratum/protocol.pyDeleted-79
lgstratum/read_a.pyDeleted-290
lgstratum/read_b.pyDeleted-310
lgstratum/render.pyDeleted-141
lgstratum/segment.pyDeleted-242