#!/usr/bin/env python3 """Write the eleven node folders of the physics topology. Three files per node, the same shape the math dataset has: ``grammar.gf`` the controlled language, as documentation. The reference implementations are ``lgphys/parse_a.py`` and ``lgphys/parse_b.py``; the file states the language and the role this node plays in it. ``ontology.smt2`` what Z3 is told before this node is checked: a timeout and the physical constants, because a claim about a regime compares against the speed of light. ``seed_payload.json`` the envelope this node starts with. Only the arbiter starts with a problem, because the arbiter is the node the first arc points at; the others are idle. Run it after changing the constant table or the language:: python physics/tools/make_nodes.py """ import json import sys from pathlib import Path ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT)) from lgphys import consts # noqa: E402 NODES = ROOT / "nodes" # The question the topology ships with. tools/ask.py replaces it with the question being measured. SAMPLE_PROBLEM = "convert 3 km to m" ROLE = { "reader_a": "First reader: reads the sentence along road A, number first, and reports the single " "number its reading depends on.", "reader_b": "Second reader: reads the same sentence along road B, structure first, and reports the " "same number by a different route.", "domain_a": "Physics of the situation: decides which regime the sentence belongs to and states the " "guard that keeps the idealisation legitimate as a number.", "domain_b": "Physics of the dimensions: works out the dimensions of every quantity in the sentence " "and the monomial the guard should be.", "equivalence": "Comparator: says whether the two readings of the sentence are the same reading, and " "what the dimension analysis says about the equation.", "coverage": "Coverer: lists every number the sentence contains, checks that each one is accounted " "for, and writes the sentence mathematics is asked to settle.", "invoker": "Invoker: asks mathematics the question the family decided to delegate, records the " "answer, and says whether the answer is the number the question asked for.", "boundary": "Boundary: recomputes the answer without looking at it, compares the constant table of " "the code with the constant table of the ontology, and refuses the questions physics " "does not answer.", "verifier": "Verifier: rebuilds the conjunction of every claim the constructive nodes closed with " "and reports whether that conjunction is consistent.", "adversary": "Adversary: puts one deliberate mistake into the answer and reports whether the chain " "would have noticed it.", "arbiter": "Arbiter: holds the question, applies the decision rule of this dataset, and states the " "status, the assurance and the answer.", } GRAMMAR_HEAD = """-- Node %s (%s): %s -- PhysLang: abstract syntax of the controlled physical language of the physics topology. -- It documents the language; the reference parsers are lgphys/parse_a.py (road A, number first) -- and lgphys/parse_b.py (road B, structure first). Both roads have to reach the same reading. -- NOTE: this specification has not been compiled with the GF toolchain in the authoring environment. -- In the abstractSyntaxTree string literals and numbers are written bare (3, 1/10) instead of (Lit 3), -- a bracketed list of rows is written (Rows (Row 1 2 10) (Row 2 3 20)), and the leading keyword 'pi' -- of a dimensional-analysis question is optional in English. abstract PhysLang = { cat Problem ; Qty ; Num ; Unit ; Eq ; Side ; Names ; Rows ; Ratio ; fun Convert : Qty -> Unit -> Problem ; Audit : Eq -> Problem ; Pi : Names -> Names -> Problem ; Potential : Num -> Num -> Rows -> Rows -> Ratio -> Ratio -> Problem ; MkQty : Num -> Unit -> Qty ; Add, Sub, Mul, Div, Pow : Side -> Side -> Side ; Neg : Side -> Side ; Q : Unit -> Unit ; Row : Num -> Num -> Num -> Rows ; Nil : Rows ; One : Names ; And : Names -> Names -> Names ; MkNum : String -> Num ; Slash : Num -> Num -> Ratio ; } concrete PhysLangEng of PhysLang = { lincat Problem, Qty, Num, Unit, Eq, Side, Names, Rows, Ratio = Str ; lin Convert q u = "convert" ++ q ++ "to" ++ u ; Audit e = "audit" ++ e ; Pi t ns = "pi" ++ t ++ "from" ++ ns ; Potential n k r s z f = "potential" ++ "node" ++ n ++ "circuit" ++ k ++ "resistors" ++ r ++ "sources" ++ s ++ "size" ++ z ++ "frequency" ++ f ; MkQty n u = n ++ u ; Add a b = "(" ++ a ++ "+" ++ b ++ ")" ; Sub a b = "(" ++ a ++ "-" ++ b ++ ")" ; Mul a b = "(" ++ a ++ "*" ++ b ++ ")" ; Div a b = "(" ++ a ++ "/" ++ b ++ ")" ; Pow a b = "(" ++ a ++ "^" ++ b ++ ")" ; Neg a = "(" ++ "-" ++ a ++ ")" ; Q u = u ; Row a b c = "[" ++ a ++ b ++ c ++ "]" ; Nil = "" ; One n = n ; And a b = a ++ "," ++ b ; MkNum s = s.s ; Slash n d = n ++ "/" ++ d ; } """ def grammar(node: str) -> str: return (GRAMMAR_HEAD % (node, node, ROLE[node])) + "\n" def ontology(node: str) -> str: return """; SMT-LIB 2 ontology for the physics topology node %s. ; Real arithmetic is built into Z3, so the ontology fixes two things only: a timeout, because one ; hard nonlinear query must not block a whole session, and the physical constants. A claim about a ; regime compares a monomial of the sentence against a threshold that contains the speed of light, ; so the constant has to be in the ontology the claim is checked against, not in the claim. (set-option :timeout 8000) %s """ % (node, consts.ontology_block().rstrip()) + "\n" def seed(node: str, idle: bool) -> str: payload = { "sender": node, "turn": 0, "volatileState": {"internalTimeTick": 0}, "payload": { "naturalLanguage": "Idle until the problem arrives." if idle else SAMPLE_PROBLEM, "abstractSyntaxTree": "Idle" if idle else "Convert (MkQty 3 km) m", "smtConstraints": { "declarations": [], "assertions": ["(assert true)"], "z3Status": "sat", }, }, } return json.dumps(payload, indent=2) + "\n" def main() -> int: written = 0 for node in ROLE: folder = NODES / node folder.mkdir(parents=True, exist_ok=True) (folder / "grammar.gf").write_text(grammar(node), encoding="utf-8") (folder / "ontology.smt2").write_text(ontology(node), encoding="utf-8") (folder / "seed_payload.json").write_text(seed(node, idle=node != "arbiter"), encoding="utf-8") written += 3 print("wrote %s" % folder.relative_to(ROOT.parent)) print("%d files, ontology block of %d lines, sample problem: %s" % (written, len(consts.ontology_block().splitlines()), SAMPLE_PROBLEM)) return 0 if __name__ == "__main__": sys.exit(main())