File size: 6,507 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 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 | #!/usr/bin/env python3
"""The Oracle7 kernel, v0 (KERNEL_SPEC.md steps K0-K1). Built on the head's own pieces, not beside them:
- declared faces = the physics organ's admitted formula parts, loaded by the head's own loader (grow60.load_parts):
inputs and output keyed (quantity noun, SI dimension in 7 base units incl. mol), each part's own program;
- the schedule = the head's Planner (grow60): backward chains up to depth 3 over keys that share BOTH noun and dimension;
an answer only when every plan agrees;
- receipts = one record per hop (part id, inputs in the part's own units, output), replayable.
K0: count faces and keys; list what does not parse. K1: every part's own recorded example, asked as a question, must come
back as its expected value through the kernel, and the kernel's answer must be identical to grow60.ask on the same question.
usage: kernel_v0.py <pack tree> <out.json>"""
from __future__ import annotations
import collections
import json
import math
import os
import sys
import time
from pathlib import Path
TREE = Path(os.environ.get("O7_KERNEL_TREE", Path(__file__).resolve().parents[2])) # the released pack the kernel reads
sys.path.insert(0, str(TREE / "workbench" / "swarm"))
os.environ.setdefault("O7_TREE", str(TREE))
import grow60 as G # noqa: E402
ORGAN = TREE / "root" / "organs10" / "physics"
class Kernel:
def __init__(self, organ=ORGAN):
t0 = time.time()
self.parts = G.load_parts(organ) # declared faces, the head's own loader
self.planner = G.Planner(self.parts) # the head's own schedule
self.keys = collections.Counter(k for p in self.parts.values() for k in p["in_keys"] + [p["out_key"]])
self.load_seconds = round(time.time() - t0, 2)
def ask_keys(self, want_noun, given, depth=3):
"""want noun + {(noun, dims): SI value} -> answer with receipts, or a hole"""
wkeys = [k for k in self.planner.by_out if k[0] == want_noun]
plans = []
for wk in wkeys:
plans += self.planner.plans(wk, set(given), depth)
if not plans:
return {"status": "declined", "hole": {"want": want_noun, "given": sorted(str(k) for k in given)},
"why": "no admitted part or chain gives the %s from those givens" % want_noun}
runs = []
for pl in plans:
have, receipts = dict(given), []
try:
for p in pl:
args = [have[k] / s for k, s in zip(p["in_keys"], p["scale_in"])]
y = float(p["fn"](*args))
v = y * p["scale_out"]
if not math.isfinite(v):
raise ValueError("not finite")
have[p["out_key"]] = v
receipts.append({"part": p["id"], "inputs": dict(zip(p["inputs"], args)), "output": {p["output"]: y}})
runs.append((have[pl[-1]["out_key"]], receipts))
except (ValueError, ZeroDivisionError, OverflowError, TypeError):
continue
if not runs:
return {"status": "declined", "why": "no plan could be run on those values"}
v0 = runs[0][0]
if any(abs(v - v0) > 1e-6 * max(abs(v0), 1e-300) for v, _ in runs):
return {"status": "declined", "why": "%d plans disagree" % len(runs), "check": "every plan agrees"}
return {"status": "answered", "value": v0, "plans": len(runs), "receipts": runs[0][1]}
def ask(self, q):
r, why = G.read(q)
if r is None:
return {"status": "declined", "why": why}
want, gs = r
return self.ask_keys(want, {(n, d): v for n, v, d in gs})
def example_questions(organ=ORGAN):
"""each admitted part's own first recorded point, written as the head reader's question form"""
qs = []
for pid in sorted(os.listdir(organ / "specialists")):
spec_p = organ / "specialists" / pid / "spec.json"
if not spec_p.exists():
continue
spec = json.loads(spec_p.read_text(encoding="utf-8"))
pts = spec.get("points") or []
if not pts or not spec.get("inputs"):
continue
pt = pts[0]
parts = []
for lab, v in zip(spec["inputs"], pt.get("in", [])):
unit = lab[lab.rfind("(") + 1:-1] if lab.endswith(")") else ""
parts.append("the %s is %r %s" % (G.noun(lab), float(v), "" if unit == "1" else unit))
if not parts or not isinstance(pt.get("out"), (int, float)):
continue
q = "What is the %s when %s?" % (G.noun(spec["output"]), ", ".join(x.strip() for x in parts[:-1]) +
(" and " if len(parts) > 1 else "") + parts[-1].strip())
qs.append({"part": pid, "q": q, "expect": float(pt["out"]), "out_unit": spec["output"]})
return qs
if __name__ == "__main__":
out = sys.argv[2] if len(sys.argv) > 2 else "kernel_v0.json"
k = Kernel()
rep = {"K0": {"faces_declared": len(k.parts), "keys": len(k.keys), "load_seconds": k.load_seconds,
"part_folders": len(os.listdir(ORGAN / "specialists"))}}
print("K0", rep["K0"], flush=True)
qs = example_questions()
st = collections.Counter()
diffs, wrong = [], []
for x in qs:
a = k.ask(x["q"])
b = G.ask(k.planner, x["q"])
same = (a["status"] == b["status"]) and (a["status"] != "answered" or abs(a["value"] - b["value"]) <= 1e-12 * max(1, abs(b["value"])))
if not same:
diffs.append({"q": x["q"], "kernel": a.get("value", a.get("why")), "grow60": b.get("value", b.get("why"))})
if a["status"] == "answered":
# the example's expected value is in the output label's own unit; the kernel's value is SI
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 and len(wrong) < 10:
wrong.append({"q": x["q"][:160], "got": v, "expect": x["expect"]})
else:
st["declined:" + a.get("why", "")[:40]] += 1
rep["K1"] = {"questions": len(qs), "tally": dict(st), "identical_to_grow60": len(qs) - len(diffs), "differences": diffs[:10],
"wrong_examples": wrong}
print("K1", json.dumps(rep["K1"], indent=1)[:2500], flush=True)
json.dump(rep, open(out, "w"), indent=1, default=str)
|