File size: 15,245 Bytes
d9b105f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
#!/usr/bin/env python3
"""network_glue_v1 - the specialist network with GLUE instead of hand adapters (11.5 test, 2026-11-05).

network_v2 reaches each specialist through a hand-written typed adapter (ops_for: phrasing template, typed slots, reply
unit pattern; 11 of them) and plans at most 2 specialist hops. This version removes every hand adapter:

FACES ARE LEARNED from each specialist's own dev panel. For a dev item (q, expect): the givens reader types the numbers in
q (dimension, role, surface span); the specialist is asked q, and the number in its reply that equals `expect` gives the
output's unit, hence its dimension. The face = template (q with each given's span replaced by a typed slot that remembers
its surface unit) + output dimension. EXAMINED: a face is kept only if, rendered with the givens of ANOTHER dev item of the
same specialist and slot signature, the specialist returns that item's expected value. Nothing is written per specialist.

THE MEDIUM is a pool of typed quantities (SI value, dimension, role, source). Specialists never address each other: a face
reads quantities of its slot types from the pool and writes its output back (the residual-stream analogue). Normalisation
is the SI pool itself (every value in base units, so any face can read any write).

THE SELECTOR (the attention step) decides which faces may read the question at all: fit = IDF-weighted share of the face's
template words present in the question (IDF over all learned faces), eligible at fit >= FIT_MIN. The schedule: rounds of
face applications (depth <= MAX_HOPS, derived inputs from core math allowed as in v2), and after any round the remaining
quantities must reach the goal by CORE_MATH using every one of them (v2's rule). Checks unchanged: validity of givens, all
numbers read, multi-step only, no echo. No checked path -> decline.
usage: network_glue_v1.py <standing.txt> <spec_root> <combo_code> [question ...]"""
from __future__ import annotations

import collections
import itertools
import json
import math
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
from network_v2 import (DIMLESS, TEMP, Q, Registry, core_math, g, normalise, read_givens, read_goal,  # noqa: E402
                        unit_lookup, valid_given)

FIT_MIN = 0.5
MAX_HOPS = 2
STOP = set("a an the of to in on at for and or is are was were be by with from what how much many does do it its this that "
           "you your we our their there if then than per each into as which who whom whose".split())
WORD = re.compile(r"[a-z][a-z\-']+")
NUMU = re.compile(r"(-?\d[\d,]*(?:\.\d+)?(?:e[+-]?\d+)?)\s*([A-Za-z°/%$²³^0-9\-\.]*(?:\s(?:per|a|an)\s\w+)?)")


def words(text):
    return {w for w in WORD.findall(str(text).lower()) if w not in STOP and not unit_lookup(w)}


class Face:
    def __init__(self, sid, kind, template, slots, out_dim, out_factor, out_unit, src_q):
        self.sid, self.kind, self.template, self.slots = sid, kind, template, slots
        self.out_dim, self.out_factor, self.out_unit, self.src_q = out_dim, out_factor, out_unit, src_q
        self.words = words(re.sub(r"\{\d+\}", " ", template))

    def signature(self):
        return tuple((s["dim"], s["role"]) for s in self.slots)

    def render(self, qs):
        text = self.template
        for i, (s, q) in enumerate(zip(self.slots, qs)):
            if s["dim"] == TEMP:
                raw = q.v - s["offset"] if s["scale"] == 1 else (q.v - 273.15) * 9 / 5 + 32
            else:
                raw = q.v / s["factor"]
            text = text.replace("{%d}" % i, s["prefix"] + g(raw) + s["suffix"], 1)
        return text

    def public(self):
        return {"sid": self.sid, "kind": self.kind, "template": self.template, "out_unit": self.out_unit,
                "slots": [[str(s["dim"]), s["role"]] for s in self.slots], "from": self.src_q}


def _slot(q):
    """a slot remembers how its surface span writes a number: prefix, raw number, suffix; factor raw -> SI"""
    m = re.search(r"-?\d[\d,]*(?:\.\d+)?", q.text)
    if not m:
        return None
    raw = float(m.group(0).replace(",", ""))
    s = {"dim": q.dim, "role": q.role, "prefix": q.text[:m.start()], "suffix": q.text[m.end():]}
    if q.dim == TEMP:
        unit = q.text[m.end():].strip().lower()
        if unit.startswith("f"):
            s.update(scale=9 / 5, offset=0.0)
        else:
            s.update(scale=1, offset=q.v - raw)
        return s
    if raw == 0:
        return None
    s["factor"] = q.v / raw
    return s


def reply_value(resp, expect):
    """the number in the reply equal to the expected value, with the unit written after it"""
    for m in NUMU.finditer(resp or ""):
        try:
            v = float(m.group(1).replace(",", ""))
        except ValueError:
            continue
        if abs(v - expect) <= 0.01 * max(abs(expect), 1e-12):
            unit = m.group(2).strip().rstrip(".,;")
            for cut in (unit, unit.split(" ")[0]):
                u = unit_lookup(cut) if cut else None
                if u:
                    return v, u, cut
            return v, None, unit
    return None


def parse_out(resp, face):
    for m in NUMU.finditer(resp or ""):
        unit = m.group(2).strip().rstrip(".,;")
        for cut in (unit, unit.split(" ")[0]):
            if cut and cut == face.out_unit:
                try:
                    return float(m.group(1).replace(",", ""))
                except ValueError:
                    return None
    return None


class GlueNetwork:
    def __init__(self, standing, spec_root, combo_code, log=print):
        self.reg = Registry(standing, spec_root, combo_code)
        self.root = spec_root
        self.log = log
        self.faces, self.report = self._learn()
        df = collections.Counter(w for f in self.faces for w in f.words)
        n = max(1, len(self.faces))
        self.idf = {w: math.log(1 + n / c) for w, c in df.items()}

    # ------------------------------------------------------------ learning faces from each specialist's own dev panel
    def _panel(self, sid):
        try:
            man = json.load(open(os.path.join(self.root, sid, "manifest.json")))
            p = man.get("panel", {}).get("path", "")
            local = os.path.join(self.root, sid, os.path.basename(p))
            items = json.load(open(local if os.path.exists(local) else p))
        except Exception:  # noqa: BLE001
            return []
        return [it for it in items if isinstance(it, dict) and it.get("split") == "dev" and it.get("valid", True)
                and isinstance(it.get("expect"), (int, float)) and not isinstance(it.get("expect"), bool)]

    def _ask(self, sid, text):
        try:
            r = self.reg.ask(sid, text)
        except Exception:  # noqa: BLE001
            return None
        if not r or r.get("declined"):
            return None
        return r.get("response", "")

    def _learn(self):
        faces, rep = [], {"specialists": 0, "with_panel": 0, "candidates": 0, "examined_ok": 0, "unexamined": 0, "failed": 0,
                          "by_specialist": {}}
        for sid in self.reg.ids:
            rep["specialists"] += 1
            items = self._panel(sid)
            if not items:
                continue
            rep["with_panel"] += 1
            cands = []
            for it in items[:60]:
                q = normalise(it["q"])
                givens, flags = read_givens(q)
                if not givens or flags.get("unread_numbers") or len(givens) > 4:
                    continue
                if any(q.find(x.text) < 0 for x in givens):
                    continue
                resp = self._ask(sid, it["q"])
                hit = reply_value(resp, float(it["expect"])) if resp else None
                if not hit or not hit[1]:
                    continue
                v, (factor, dim), unit = hit
                template, slots, ok = q, [], True
                for i, x in enumerate(givens):
                    s = _slot(x)
                    if s is None:
                        ok = False
                        break
                    template = template.replace(x.text, "{%d}" % i, 1)
                    slots.append(s)
                if ok and all("{%d}" % i in template for i in range(len(slots))):
                    cands.append((Face(sid, it.get("kind", ""), template, slots, dim, factor, unit, it["q"]), givens, it))
            rep["candidates"] += len(cands)
            kept = 0
            by_sig = collections.defaultdict(list)
            for c in cands:
                by_sig[(c[0].kind, c[0].signature())].append(c)
            for sig, group in by_sig.items():
                seen_templates = set()
                for f, _g, _it in group:
                    if f.template in seen_templates:
                        continue
                    others = [(gv, it) for ff, gv, it in group if ff is not f and ff.src_q != f.src_q]
                    if not others:
                        rep["unexamined"] += 1
                        continue
                    passed = False
                    for gv, it in others[:3]:
                        resp = self._ask(sid, f.render(gv))
                        out = parse_out(resp, f) if resp else None
                        if out is not None and abs(out - float(it["expect"])) <= 0.01 * max(abs(float(it["expect"])), 1e-12):
                            passed = True
                            break
                    if passed:
                        faces.append(f)
                        seen_templates.add(f.template)
                        kept += 1
                        rep["examined_ok"] += 1
                    else:
                        rep["failed"] += 1
            rep["by_specialist"][sid] = kept
            if kept:
                self.log("faces %-22s %d" % (sid, kept))
        return faces, rep

    # ------------------------------------------------------------ the selector and the medium
    def fit(self, face, qwords):
        tot = sum(self.idf.get(w, 0) for w in face.words)
        if tot <= 0:
            return 0.0
        return sum(self.idf.get(w, 0) for w in face.words & qwords) / tot

    def _fillers(self, pool, used, slot):
        out = [i for i, q in enumerate(pool) if i not in used and q.dim == slot["dim"] and q.role == slot["role"]]
        if slot["dim"] != TEMP:
            for i, j in itertools.combinations([k for k in range(len(pool)) if k not in used and not pool[k].temp_point], 2):
                cm = core_math([pool[i], pool[j]], slot["dim"])
                if cm and slot["role"] == "":
                    out.append(("d", (i, j)))
        return out

    def _apply(self, face, pool, used, trace):
        """every way this face can read the pool; yields (new pool, new used, new trace)"""
        fills = [self._fillers(pool, used, s) for s in face.slots]
        for combo in itertools.product(*fills):
            idx = set()
            for sp in combo:
                ix = set(sp[1]) if isinstance(sp, tuple) else {sp}
                if idx & ix:
                    break
                idx |= ix
            else:
                args, tr = [], list(trace)
                for sp, s in zip(combo, face.slots):
                    if isinstance(sp, tuple):
                        cm = core_math([pool[i] for i in sp[1]], s["dim"])
                        tr.append({"node": "core_math", "op": "derive", "formula": cm[1], "value": cm[0]})
                        args.append(Q(cm[0], s["dim"], "(%s)" % cm[1], ""))
                    else:
                        args.append(pool[sp])
                text = face.render(args)
                resp = self._ask(face.sid, text)
                val = parse_out(resp, face) if resp else None
                tr.append({"node": face.sid, "kind": face.kind, "asked": text, "reply": resp, "value": val})
                if val is None or not math.isfinite(val):
                    continue
                out = Q(val * face.out_factor, face.out_dim, "%s(%s)" % (face.kind or face.sid, ", ".join(a.text for a in args)),
                        "", src=face.sid)
                yield pool + [out], used | idx, tr

    def solve(self, text):
        text = normalise(text)
        givens, flags = read_givens(text)
        goal = read_goal(text)
        base = {"question": text, "givens": [repr(q) for q in givens], "goal": str(goal)}
        if goal is None or goal[0] != "dim":
            return dict(base, status="declined", reason="no numeric goal I can reach")
        if not givens:
            return dict(base, status="declined", reason="no quantities to work from")
        for q in givens:
            bad = valid_given(q)
            if bad:
                return dict(base, status="declined", reason=bad, check="validity")
        if flags.get("unread_numbers"):
            return dict(base, status="declined", reason="numbers I could not read", check="all numbers read")
        qw = words(text)
        eligible = [f for f in self.faces if self.fit(f, qw) >= FIT_MIN]
        eligible.sort(key=lambda f: -self.fit(f, qw))
        frontier = [(list(givens), set(), [], 0)]
        for depth in range(MAX_HOPS + 1):
            nxt = []
            for pool, used, trace, hops in frontier:
                rest = [q for i, q in enumerate(pool) if i not in used]
                done = self._finish(base, givens, rest, goal, trace, hops)
                if done:
                    return done
                if hops < MAX_HOPS:
                    for f in eligible:
                        for p2, u2, t2 in self._apply(f, pool, used, trace):
                            nxt.append((p2, u2, t2, hops + 1))
            frontier = nxt[:200]
        return dict(base, status="declined", reason="no checked path from the givens to what is asked",
                    eligible=[f.sid + ":" + f.kind for f in eligible[:6]])

    def _finish(self, base, givens, rest, goal, trace, hops):
        cm = core_math(rest, goal[1])
        if not cm:
            return None
        val = cm[0] / goal[3]
        if not math.isfinite(val) or val < 0:
            return None
        if hops == 0 and len(givens) == 1:
            return dict(base, status="declined", reason="single conversion (the core's own operator)", check="multi-step only")
        if hops == 0 and any(abs(cm[0] - q.v) <= 1e-9 * max(1.0, abs(q.v)) and q.dim == goal[1] for q in givens):
            return None
        unit = goal[2]
        say = ("$%.2f" % val) if unit == "$" else "%s %s" % (g(round(val, 6)), unit)
        trace = trace + [{"node": "core_math", "op": "dimensional", "formula": cm[1], "value": val, "unit": unit}]
        nodes = [t["node"] for t in trace]
        return dict(base, status="answered", answer=say, response="The answer is %s. (path: %s)" % (say, " → ".join(nodes)),
                    trace=trace, hops=hops)


if __name__ == "__main__":
    net = GlueNetwork(open(sys.argv[1]).read().split(), sys.argv[2], sys.argv[3])
    print(json.dumps({k: v for k, v in net.report.items() if k != "by_specialist"}))
    for q in sys.argv[4:]:
        print(json.dumps(net.solve(q), indent=1, ensure_ascii=False)[:1500])