Files
threshing-atlas/planner/build_policy.py
T
cc86343668 Core: the route model in Python, built from a declarative game.yaml (#10)
Step 2 of the Python-first, declarative core.

- core/spec/game.yaml: the game as data: every decision and its options, every roll and the
  earlier steps its odds may depend on, every bonding encounter, and the flow of a run from the
  entrance to the dragons (set / keep / drop / go / end / encounter). Also how the form's coded
  answers map onto the game.
- core/atlas/model.py: what each coded run reveals about each step, count tables, empirical-Bayes
  shrinkage, and the posterior draws (same random numbers as before, reproducible from the seed).
- core/atlas/solver.py: one interpreter of game.yaml used three ways (solve, evaluate a fixed
  policy, export the published tree) instead of the tree written out five times. Vectorised
  over the 200 posterior draws: the build takes about 2 minutes instead of 4, with no memory flag.
- planner/build_policy.py and policy_report.py replace the JS build and report.

Checked against the JavaScript model: every number in policy.json agrees to within 4e-12
(last-digit differences in log/cos). Three "still best" shares differ by one draw in 200, at
near-ties under the "eventually" objective. POLICY.md is otherwise identical.
tests/parity/compare_solver.py keeps checking JS against Python in CI until the site's JS advisor
replaces solver.js; tests/core/test_game.py checks game.yaml is complete and consistent.


Claude-Session: https://claude.ai/code/session_01UCzTd31GphpMXDhQqWrCMQ

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 21:04:21 +00:00

75 lines
3.1 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Build data/public/policy.json: the best decisions for every dragon colour, under both objectives.
python planner/build_policy.py [--draws 200] [--out data/public/policy.json]
Two samples: every run, and a low-bias sample (bulk logs plus form runs from riders not chasing a rare dragon).
The output has a content id, so each bot run can record which policy it followed.
"""
import argparse
import hashlib
import json
import math
import sys
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "core"))
from atlas import coding, model, solver # noqa: E402
def clean(o):
"""JSON-safe: numpy numbers to floats, infinities and NaN to null (as JavaScript's JSON.stringify does)."""
if isinstance(o, dict):
return {str(k): clean(v) for k, v in o.items()}
if isinstance(o, (list, tuple)):
return [clean(v) for v in o]
if hasattr(o, "item"):
o = o.item()
if isinstance(o, float) and (math.isinf(o) or math.isnan(o)):
return None
return o
def coded_runs(path):
df, _ = coding.load(path)
runs = df.drop(columns=["run_id"]).astype(object).where(df.drop(columns=["run_id"]).notna(), None).to_dict("records")
return runs
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--draws", type=int, default=200)
ap.add_argument("--data", default=str(ROOT / "data/public/form_responses.json"))
ap.add_argument("--out", default=str(ROOT / "data/public/policy.json"))
a = ap.parse_args(argv)
rows = len(json.load(open(a.data, encoding="utf-8"))["rows"])
runs = coded_runs(a.data)
samples = {
"all": runs,
"lowBias": [r for r in runs if r["source"] != "Form" or r["goal"] not in model.RARE_GOALS],
}
t0 = time.time()
out = {"schema": 1, "source": {"form_rows": rows}, "samples": {}}
for name, rs in samples.items():
out["samples"][name] = clean(solver.build_policy(rs, draws=a.draws))
print(f"{name}: {len(rs)} runs, {time.time() - t0:.1f} s")
# a content id (no timestamps: the build is reproducible)
out["id"] = hashlib.sha1(json.dumps(out["samples"], separators=(",", ":"), sort_keys=True).encode()).hexdigest()[:12]
Path(a.out).write_text(json.dumps(out, separators=(",", ":")), encoding="utf-8")
print("policy id", out["id"])
pct = lambda p: "–" if p is None else f"{100 * p:.{2 if p < 0.01 else 1}f}%" # noqa: E731
for name, s in out["samples"].items():
print(f"\n{name} alphas {json.dumps(s['model']['alphas'])}")
for X, t in s["targets"].items():
x, e = t["thisAttempt"], t["eventually"]
att = e["expectedAttempts"]["mean"]
print(f" {X:<6} this attempt {pct(x['pX']['mean'])} [{pct(x['pX']['lo'])}, {pct(x['pX']['hi'])}] other bond {pct(x['pOther']['mean'])}"
f" | eventually: ratio {pct(e['ratio']['mean'])}, P(X) {pct(e['pX']['mean'])}, ~{'–' if att is None else round(att)} attempts"
f" | cross-fit {pct(t['crossFit']['inSample'])} -> held-out {pct(t['crossFit']['heldOut'])}")
if __name__ == "__main__":
main()