Files
threshing-atlas/planner/build_policy.py
kschianoandClaude Opus 5.5 e457f89b40 Game-rule checks for runs answered through "Report a run"
Reported and Reddit-comment runs now get the checks the community form
gets in core/atlas/coding.py, as data_flags (the run is kept):
- first dragon outside the documented pool for the company/direction
- a bond or burn by a dragon the encounter does not have (new
  encounter_colours table in core/spec/form.yaml; Orange/Brown after the
  two Greens allowed, as a Green's rescue)
- a Green on a valley run
- a cadet outcome off its scream path, fight answers or a post-fight path
  on a run that did not help, a second fight move without assessing
- died before the hour, yet reached the tree/valley or an encounter

planner/policy.yaml drop_flagged: flagged runs of sources read from free
text (reddit comment) stay out of the route model; provenance notes do not
count as flags. No effect today: the source is not in `sources` yet.

On the first 82 scraped runs: 6 flagged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 08:46:13 -05:00

100 lines
4.3 KiB
Python
Raw Permalink 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, from the runs and rules in planner/policy.yaml: every run, and a low-bias sample (bot runs, bulk logs,
and 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 model, solver # noqa: E402
from atlas import runs as runs_io # noqa: E402
import yaml # noqa: E402
# which runs the model learns from, and the low-bias sample (planner/policy.yaml)
with open(ROOT / "planner/policy.yaml", encoding="utf-8") as _f:
CONFIG = yaml.safe_load(_f)
SOURCES = CONFIG["sources"]
def low_bias(r, lb=CONFIG["low_bias"]):
"""Kept in the low-bias sample: every run of an always-kept source, bulk logs, and riders not chasing a rare dragon."""
if r["source"] in lb["always"]:
return True
if r["source"] == "reddit spreadsheet" and "bulk" in lb["entries_kept"] and r["entry"] not in (None, "Form"):
return True
return r["goal"] not in lb["rare_goals"]
def drop_flagged(runs, cfg=CONFIG.get("drop_flagged") or {}):
"""Without the flagged runs of the sources read automatically from free text (planner/policy.yaml drop_flagged)."""
sources, keep = set(cfg.get("sources") or ()), tuple(cfg.get("except") or ())
def problems(r):
return [f for f in (r.get("data_flags") or "").split("; ") if f and not f.startswith(keep)] if keep else [f for f in (r.get("data_flags") or "").split("; ") if f]
return [r for r in runs if r["source"] not in sources or not problems(r)]
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 main(argv=None):
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--draws", type=int, default=200)
ap.add_argument("--data", default=str(runs_io.PATH))
ap.add_argument("--out", default=str(ROOT / "data/public/policy.json"))
a = ap.parse_args(argv)
runs = drop_flagged(runs_io.read(a.data, sources=SOURCES))
rows = len(runs)
samples = {
"all": runs,
"lowBias": [r for r in runs if low_bias(r)],
}
t0 = time.time()
by_source = {}
for r in runs:
by_source[r["source"]] = by_source.get(r["source"], 0) + 1
out = {"schema": 1, "source": {"form_rows": by_source.get("reddit spreadsheet", 0), "runs": rows, "by_source": by_source},
"samples": {}}
for name, rs in samples.items():
out["samples"][name] = clean(solver.build_policy(rs, draws=a.draws, bias_config=CONFIG.get("reporting_bias")))
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()