File size: 11,156 Bytes
fad6045
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
"""Marker-dependence test: does the policy go where the red square is?

Each scene is set up once (rebuilt from a dataset's phase2_episodes.jsonl with
--scenes, or drawn at random) and its state saved. The red square is then drawn over
--placements different pieces in turn: the recorded source first, then pieces spread
over the board. Everything else stays identical: the same start state, the same
webcam look and calibration error, and the blue square on the same destination. For
each placement the policy drives for --seconds from the same start, and the gripper's
path is recorded.

Per placement: how close the gripper came to the marked piece, and which of the
placements' pieces it came closest to while down near the board (within 6 cm). The
policy follows the markers if that is the marked one. Per scene: how far apart the gripper's lowest points are across
placements, against how far apart the marked pieces are (near 1 if it follows the
markers, near 0 if it goes to the same place whatever is marked).

Writes marker_report.md, marker_results.json and one image per scene: the gripper
paths drawn over the overhead view, one colour per placement, with a ring on the
piece that was marked.

Run:  MUJOCO_GL=egl .venv/bin/python sim/marker_test.py --policy Machanize/chess_phase_smolvla \
          --scenes data/varied_2000_notes.jsonl --count 6 --out sim/reports/diagnose/marker_test
"""
from __future__ import annotations

import argparse
import json
import multiprocessing as mp
import os
import sys
import time
from pathlib import Path
from queue import Empty

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))

COLOURS = [(255, 60, 40), (40, 200, 255), (255, 210, 0), (170, 90, 255), (60, 220, 90), (255, 120, 200)]


def pixels(cam, pts):
    """Pinhole projection of world points (all in front of the camera)."""
    import numpy as np

    local = (np.asarray(pts) - cam.pos) @ cam.rot
    f = cam.height / 2 / np.tan(np.radians(cam.fovy_deg) / 2)
    return np.stack([cam.width / 2 + f * local[:, 0] / -local[:, 2], cam.height / 2 - f * local[:, 1] / -local[:, 2]], 1)


def spread_squares(first: str, occupied: list[str], w, n: int) -> list[str]:
    """`first`, then the occupied squares farthest from those already chosen."""
    import numpy as np

    chosen = [first]
    pos = {s: w.square_center(s)[:2] for s in occupied}
    while len(chosen) < min(n, len(occupied)):
        best = max((s for s in occupied if s not in chosen),
                   key=lambda s: min(np.linalg.norm(pos[s] - pos[c]) for c in chosen))
        chosen.append(best)
    return chosen


def worker(k, n, args, jobs, queue):
    import warnings

    warnings.filterwarnings("ignore")
    import copy

    import mujoco
    import numpy as np
    import torch
    from PIL import Image, ImageDraw

    from episode import EpisodeRunner, load_config
    from eval_policy import drive, load_policy, piece_set_from_record
    from piece_sets import sample_piece_set

    torch.set_num_threads(2)
    cfg = load_config()
    policy, pre, post, device = load_policy(args.policy)
    rng = np.random.default_rng([args.seed, k])
    for i in range(k, len(jobs), n):
        job = jobs[i]
        if "seed" in job and "piece_set_dims" in job:
            runner = EpisodeRunner(cfg, piece_set_from_record(job), render=True)
            seed, label = job["seed"], f"training episode {job['episode_index']}"
        else:
            runner = EpisodeRunner(cfg, sample_piece_set(rng, cfg, f"marker{i}"), render=True)
            seed, label = int(rng.integers(2**62)), "random scene"
        m, d, w = runner.m, runner.d, runner.w
        base = runner.setup(np.random.default_rng(seed))
        saved = (d.qpos.copy(), d.qvel.copy(), d.act.copy(), d.ctrl.copy(), d.time)
        squares = spread_squares(base.source, sorted(base.squares), w, args.placements)
        centres = {s: w.square_center(s) for s in squares}
        background = runner.render("overhead")
        cam = runner.camera("overhead")
        runs = []
        for j, s in enumerate(squares):
            d.qpos[:], d.qvel[:], d.act[:], d.ctrl[:] = saved[:4]
            d.time = saved[4]
            mujoco.mj_forward(m, d)
            task = copy.copy(base)
            task.source, task.target = s, base.squares[s]
            r, met = drive(runner, task, policy, pre, post, device, cfg, args.seconds, seed ^ 0x5EED,
                           stop_when_done=False)
            path = met.pop("path")
            # Where it went down: path points within 6 cm of the board (else the lowest point).
            low_pts = path[path[:, 2] < w.board_top + 0.06]
            if not len(low_pts):
                low_pts = path[[int(np.argmin(path[:, 2]))]]
            near = {c: round(1000 * float(np.linalg.norm(low_pts[:, :2] - centres[c][:2], axis=1).min()), 1) for c in squares}
            low = path[int(np.argmin(path[:, 2]))]
            runs.append(dict(marked=s, piece=w.kind[task.target], closest_mm=met["closest_mm"],
                             closest_to=min(near, key=near.get), follows=min(near, key=near.get) == s,
                             lifted=met["lifted"], lowest_square=met["lowest_square"], lowest_mm=met["lowest_mm"],
                             lowest_xy=[round(float(x), 4) for x in low[:2]], closest_by_square=near))
            # Path over the overhead view.
            if j == 0:
                img = Image.fromarray(background)
            pen = ImageDraw.Draw(img)
            col = COLOURS[j % len(COLOURS)]
            pen.line([tuple(p) for p in pixels(cam, path)], fill=col, width=2)
            x, y = pixels(cam, centres[s][None])[0]
            pen.ellipse([x - 9, y - 9, x + 9, y + 9], outline=col, width=3)
        img.save(Path(args.out) / f"marker_scene_{i:02d}.png")
        lows = np.array([r["lowest_xy"] for r in runs])
        marks = np.array([centres[s][:2] for s in squares])
        pair = lambda a: np.mean([np.linalg.norm(a[p] - a[q]) for p in range(len(a)) for q in range(p + 1, len(a))])
        queue.put(dict(index=i, label=label, seed=seed, board=runner.episode_info["board"],
                       overhead=runner.episode_info["overhead"], placements=runs,
                       follow_rate=round(float(np.mean([r["follows"] for r in runs])), 2),
                       spread_ratio=round(float(pair(lows) / max(pair(marks), 1e-6)), 2)))
        runner.close()
    queue.put(None)


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--policy", required=True)
    ap.add_argument("--scenes", help="phase2_episodes.jsonl: rebuild these training episodes")
    ap.add_argument("--count", type=int, default=6, help="scenes")
    ap.add_argument("--placements", type=int, default=5, help="red-square positions per scene")
    ap.add_argument("--seconds", type=float, default=8.0, help="per placement: long enough to reach and grasp")
    ap.add_argument("--workers", type=int, default=6)
    ap.add_argument("--seed", type=int, default=2_000_003)
    ap.add_argument("--out", default=str(HERE / "reports" / "marker_test"))
    args = ap.parse_args()
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    if args.scenes:
        from eval_policy import pick_scenes

        jobs = pick_scenes(args.scenes, args.count)
    else:
        jobs = [{} for _ in range(args.count)]
    ctx = mp.get_context("spawn")
    queue = ctx.Queue()
    procs = [ctx.Process(target=worker, args=(k, args.workers, args, jobs, queue)) for k in range(min(args.workers, len(jobs)))]
    for p in procs:
        p.start()
    t0, results, finished = time.time(), [], 0
    while finished < len(procs):
        try:
            r = queue.get(timeout=60)
        except Empty:
            if not any(p.is_alive() for p in procs):      # a worker crashed without reporting
                print(f"{sum(p.exitcode != 0 for p in procs)} worker(s) crashed; reporting what finished", flush=True)
                break
            continue
        if r is None:
            finished += 1
            continue
        results.append(r)
        print(f"scene {r['index']} ({r['label']}): follows {r['follow_rate']:.0%}, spread ratio {r['spread_ratio']}; "
              + ", ".join(f"{p['marked']}->{p['closest_to']} ({p['closest_mm']} mm)" for p in r["placements"]), flush=True)
    for p in procs:
        p.join()
    results.sort(key=lambda r: r["index"])
    import numpy as np

    runs = [p for r in results for p in r["placements"]]
    summary = dict(policy=args.policy, profile=os.environ.get("PHASE2_PROFILE"), scenes=len(results),
                   placements=len(runs), follow_percent=round(100 * float(np.mean([p["follows"] for p in runs])), 1),
                   chance_percent=round(100 / args.placements, 1),
                   median_closest_mm=round(float(np.median([p["closest_mm"] for p in runs])), 1),
                   median_spread_ratio=round(float(np.median([r["spread_ratio"] for r in results])), 2),
                   seconds_per_placement=args.seconds, minutes=round((time.time() - t0) / 60, 1))
    (out / "marker_results.json").write_text(json.dumps(dict(summary=summary, scenes=results), indent=1))
    lines = ["# Marker-dependence test", "",
             f"Policy `{args.policy}`. {len(results)} scenes"
             + (f" rebuilt from the training data (`{Path(args.scenes).name}`)" if args.scenes else "")
             + (f", settings profile `{summary['profile']}`" if summary["profile"] else "")
             + f". In each scene the red square was moved over {args.placements} different pieces in turn, "
             f"with everything else identical, and the policy drove for {args.seconds:.0f} s from the same start.", "",
             f"- **The gripper went closest to the marked piece in {summary['follow_percent']}% of placements** "
             f"(chance: {summary['chance_percent']}%).",
             f"- Median closest approach to the marked piece: {summary['median_closest_mm']} mm.",
             f"- Spread ratio (how far apart the gripper's lowest points are, over how far apart the marked "
             f"pieces are): median {summary['median_spread_ratio']}. Near 1 means it follows the markers; "
             f"near 0 means it goes to the same place whatever is marked.", "",
             "Images `marker_scene_NN.png`: gripper paths over the overhead view, one colour per placement, "
             "ring on the marked piece.", ""]
    for r in results:
        lines += [f"## Scene {r['index']}: {r['label']}", "",
                  f"Follows {r['follow_rate']:.0%}, spread ratio {r['spread_ratio']}.", "",
                  "| marked | piece | closest to marked (mm) | went closest to | lifted | lowest over |",
                  "|---|---|---|---|---|---|"]
        lines += [f"| {p['marked']} | {p['piece']} | {p['closest_mm']} | {p['closest_to']} | "
                  f"{'yes' if p['lifted'] else 'no'} | {p['lowest_square'] or '-'} |" for p in r["placements"]] + [""]
    (out / "marker_report.md").write_text("\n".join(lines) + "\n")
    print(json.dumps(summary, indent=1))


if __name__ == "__main__":
    main()