File size: 7,232 Bytes
875f067
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
#!/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())