File size: 5,385 Bytes
69151bd
 
 
 
 
 
 
 
 
 
 
 
c0b76d1
 
 
 
 
 
69151bd
 
c0b76d1
69151bd
c0b76d1
 
 
 
 
 
 
69151bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0b76d1
69151bd
 
 
c0b76d1
 
69151bd
c0b76d1
69151bd
 
c0b76d1
69151bd
 
c0b76d1
69151bd
 
 
 
 
c0b76d1
69151bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0b76d1
 
 
 
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
"""Rebuild board.json from the dataset: bodies/*.yaml, tasks/*/card.yaml, tasks/*/results/*.json.

    python scripts/board.py          (needs pyyaml)

board.json holds:
  bodies        the body registry (carrier, rigs with their hand count, status, the goal predicates it runs)
  tasks         per task: its results ranked, the best per (body, world) on the reference simulator
  matrix        task x body: one cell per pair, the best score if any, else whether the body could run it
                (runs: unscored / missing: the predicates it lacks / needs 2 hands / coming)
  skills        predicate x body: which body runs which goal predicate, and how many cards use each predicate
Only results on the reference simulator compete for best (see cablepilot.cardrun.REFERENCE_SIM).
"""
from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

import yaml

ROOT = Path(__file__).resolve().parents[1]
TWO_HANDS = {"left_hand", "right_hand", "other_hand"}


def rank_key(r: dict):
    s = r["score"]
    return (-s["done_frac"], s.get("furniture_contact_ticks", 0), s.get("s_per_item") or 1e9)


def card_needs(card: dict) -> dict:
    """The goal predicates a card's stages and done test use, and how many hands it needs."""
    preds = set()
    for st in card.get("stages") or []:
        for g in st.get("goals") or []:
            preds |= set(g) - {"tol"}
    if card.get("done"):
        preds |= set(card["done"]) - {"tol"}
    hands = 2 if TWO_HANDS & set(card.get("roles") or []) else 1
    return {"predicates": sorted(preds), "hands": hands}


def load_results(task_dir: Path) -> list[dict]:
    out = []
    for f in sorted((task_dir / "results").glob("*.json")):
        r = json.loads(f.read_text())
        if r.get("format") != "pilot-result/1":
            continue
        env = r.get("env") or {}
        out.append({"id": f.stem, "body": r["body"], "world": r["world"], "seed": r["seed"], "episodes": r["episodes"],
                    "score": r["score"], "compute": r["compute"], "card_sha": r["card_sha"],
                    "tuning_sha": r.get("tuning_sha"), "lineage": r.get("lineage"), "by": r["by"], "date": r["date"],
                    "sim": env.get("mujoco"), "reference_sim": bool(env.get("reference_sim")),
                    "result": f"tasks/{task_dir.name}/results/{f.name}",
                    "media": f"tasks/{task_dir.name}/media/{f.stem}.mp4"
                    if (task_dir / "media" / f"{f.stem}.mp4").exists() else None})
    return sorted(out, key=rank_key)


def cell(task: dict, body: dict) -> dict:
    best = [r for r in task["best"] if r["body"] == body["body"]]
    if best:
        b = best[0]
        return {"state": "scored", "done": b["score"]["done"], "of": b["score"]["of"], "world": b["world"],
                "result": b["result"]}
    if body["status"] != "open":
        return {"state": "coming"}
    max_hands = max((rg["hands"] for rg in body.get("rigs", []) if rg.get("status") == "open"), default=0)
    if task["needs"]["hands"] > max_hands:
        return {"state": "gap", "missing": [f"{task['needs']['hands']} hands"]}
    missing = [p for p in task["needs"]["predicates"] if p not in set(body.get("predicates") or [])]
    return {"state": "gap", "missing": missing} if missing else {"state": "runs"}


def main():
    bodies = [yaml.safe_load(p.read_text()) for p in sorted((ROOT / "bodies").glob("*.yaml"))]
    order = {"open": 0, "coming": 1}
    bodies.sort(key=lambda b: (order.get(b["status"], 2), b["body"]))
    tasks = {}
    for task_dir in sorted((ROOT / "tasks").iterdir()):
        if not (task_dir / "card.yaml").exists():
            continue
        card = yaml.safe_load((task_dir / "card.yaml").read_text())
        results = load_results(task_dir)
        best = {}
        for r in results:
            if r["reference_sim"]:
                best.setdefault(f"{r['body']}|{r['world']}", r)
        tasks[task_dir.name] = {"needs": card_needs(card), "lineage": card.get("lineage"),
                                "tunings": sorted(p.stem for p in (task_dir / "tuning").glob("*.yaml")),
                                "results": results, "best": list(best.values())}
    matrix = {t: {b["body"]: cell(v, b) for b in bodies} for t, v in tasks.items()}
    used = {}
    for t, v in tasks.items():
        for p in v["needs"]["predicates"]:
            used.setdefault(p, []).append(t)
    skills = {p: {"cards": sorted(ts), "bodies": [b["body"] for b in bodies if p in set(b.get("predicates") or [])]}
              for p, ts in sorted(used.items())}
    board = {"format": "pilot-board/2", "built": datetime.now(timezone.utc).isoformat(timespec="seconds"),
             "bodies": bodies, "tasks": tasks, "matrix": matrix, "skills": skills}
    (ROOT / "board.json").write_text(json.dumps(board, indent=1))
    w = max(len(t) for t in tasks) + 2
    print(" " * w + "".join(f"{b['body']:<14}" for b in bodies))
    for t, row in matrix.items():
        txt = []
        for b in bodies:
            c = row[b["body"]]
            txt.append({"scored": lambda: f"{c['done']}/{c['of']}", "coming": lambda: "coming", "runs": lambda: "runs",
                        "gap": lambda: "-" + ",".join(c["missing"])}[c["state"]]()[:13])
        print(f"{t:<{w}}" + "".join(f"{x:<14}" for x in txt))


if __name__ == "__main__":
    main()