File size: 4,274 Bytes
2419253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""The Oracle7 kernel, v1: v0 plus SYSTEM-AWARE LINKING (found by K1: 9 of the head's own part examples had plans that
disagree, because a noun like "height", "radius" or "volume" is shared by different shapes - a cone formula's height was
chained into a cylinder formula's; the every-plan-agrees law caught all 9, but a question with ONE such plan would have
nothing to disagree with).
Each part belongs to a system: its defining formula's Wikidata item (from its title), else its own equation set. A link
(one part's output feeding another's input through a key) is allowed across systems only when that key is produced by
parts of exactly ONE system; a key produced by several systems links only within one system.
K1 again: every part's own example; the kernel must still answer it (a part alone is always in its own system), with 0
wrong; every answer that changes against grow60 is listed with the reason.
usage: kernel_v1.py <pack tree> <out.json>"""
from __future__ import annotations

import collections
import hashlib
import json
import re
import sys

from kernel_v0 import ORGAN, G, Kernel, example_questions


def system_of(pid, organ=ORGAN):
    try:
        spec = json.loads((organ / "specialists" / pid / "spec.json").read_text(encoding="utf-8"))
    except Exception:  # noqa: BLE001
        return "part:" + pid
    q = re.findall(r"Wikidata (Q\d+)", spec.get("title", ""))
    if q:
        return q[-1]
    eqs = (spec.get("system") or {}).get("equations")
    if eqs:
        return "eq:" + hashlib.sha256(json.dumps(sorted(eqs)).encode()).hexdigest()[:12]
    return "part:" + pid


class Kernel1(Kernel):
    def __init__(self, organ=ORGAN):
        super().__init__(organ)
        self.sys = {pid: system_of(pid, organ) for pid in self.parts}
        prod = collections.defaultdict(set)
        for p in self.parts.values():
            prod[p["out_key"]].add(self.sys[p["id"]])
        self.multi = {k for k, s in prod.items() if len(s) > 1}      # keys several systems produce

    def linked_ok(self, plan, given):
        """every internal link either crosses through a single-system key or stays inside one system"""
        producer = {}
        for p in plan:
            producer[p["out_key"]] = p
        for c in plan:
            for k in c["in_keys"]:
                if k in given or k not in producer:
                    continue
                p = producer[k]
                if k in self.multi and self.sys[p["id"]] != self.sys[c["id"]]:
                    return False
        return True

    def ask_keys(self, want_noun, given, depth=3):
        orig = self.planner.plans
        self.planner.plans = lambda wk, gk, d=depth: [pl for pl in orig(wk, gk, d) if self.linked_ok(pl, gk)]
        try:
            return super().ask_keys(want_noun, given, depth)
        finally:
            self.planner.plans = orig


if __name__ == "__main__":
    out = sys.argv[2] if len(sys.argv) > 2 else "kernel_v1.json"
    k = Kernel1()
    print("systems", len(set(k.sys.values())), "| keys produced by several systems", len(k.multi), flush=True)
    st, changed, wrong = collections.Counter(), [], []
    for x in example_questions():
        a = k.ask(x["q"])
        b = G.ask(k.planner, x["q"])
        if a["status"] == "answered":
            dims = G.ldims(x["out_unit"])
            v = a["value"] / dims[1] if dims else a["value"]
            ok = abs(v - x["expect"]) <= 1e-6 * max(abs(x["expect"]), 1e-12)
            st["right" if ok else "wrong"] += 1
            if not ok:
                wrong.append({"part": x["part"], "got": v, "expect": x["expect"]})
        else:
            st["declined"] += 1
        if (a["status"], round(a.get("value", 0) or 0, 9)) != (b["status"], round(b.get("value", 0) or 0, 9)):
            changed.append({"part": x["part"], "kernel": a.get("value", a.get("why")), "grow60": b.get("value", b.get("why"))})
    rep = {"tally": dict(st), "changed_vs_grow60": changed, "wrong": wrong, "multi_system_keys": sorted(map(str, k.multi))[:40]}
    print(json.dumps({"tally": rep["tally"], "changed": len(changed), "wrong": len(wrong)}), flush=True)
    for c in changed[:15]:
        print("  CHANGED", c, flush=True)
    json.dump(rep, open(out, "w"), indent=1, default=str)