File size: 6,711 Bytes
a6dcf69
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Validate the perturbed (DART) teacher against the plain teacher on the same scenes.

Each scene (episode seed, drawn as generate_dataset.py draws them) runs twice without
cameras: plain (the teacher as used for baseline_v1) and perturbed with probability 1
(Expert.perturb_pick). A perturbed run that fails is retried with fresh offsets, as the
generator does, up to --retries times. Reported per condition: success, the executed offset,
frames in which the arm touched the target before the jaws close, and arm contacts with other
pieces during the approach and descent.

Run:  PHASE2_PROFILE=baseline,dart .venv/bin/python sim/validate_dart.py --episodes 100
"""
from __future__ import annotations

import argparse
import json
import multiprocessing as mp
import sys
import time
from pathlib import Path

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


def worker(k, seeds, cfg, retries, queue):
    import numpy as np

    from episode import EpisodeRunner
    from piece_sets import sample_piece_set

    cfg["expert"]["dart_probability"] = 1.0
    runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([0, k]), cfg, f"validate{k}"))

    def one(seed, attempt):
        task = runner.setup(np.random.default_rng(seed))
        t0 = time.time()
        r = runner.run(task, seed, dart_attempt=attempt)
        near = {key: n for key, n in r.stray_contacts.items() if key.split(":")[0] in ("approach", "descend")}
        return dict(success=bool(r.success), reason=r.reason, offset_mm=r.dart_offset_mm,
                    pre_close_touch=int(r.pre_close_touch), near_contacts=near, seconds=round(time.time() - t0, 1),
                    move=f"{task.source}-{task.dest.square}", piece=runner.w.kind[task.target])

    for seed in seeds:
        plain = one(seed, -1)
        tries = [one(seed, a) for a in range(1 + retries)]
        first_ok = next((i for i, t in enumerate(tries) if t["success"]), None)
        queue.put(dict(seed=seed, move=plain["move"], piece=plain["piece"], plain=plain, dart=tries[0],
                       dart_ok_within=first_ok, tries=tries))
    queue.put(None)


def main():
    import numpy as np

    from episode import load_config

    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--episodes", type=int, default=100)
    ap.add_argument("--workers", type=int, default=8)
    ap.add_argument("--seed", type=int, default=5_000_003)
    ap.add_argument("--retries", type=int, default=2)
    ap.add_argument("--out", default=str(HERE / "reports" / "dart_teacher"))
    args = ap.parse_args()
    cfg = load_config()
    assert cfg["expert"].get("dart_radius_mm"), "run with PHASE2_PROFILE=baseline,dart"
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    rng = np.random.default_rng(args.seed)
    seeds = [int(rng.integers(2**62)) for _ in range(args.episodes)]
    ctx = mp.get_context("spawn")
    queue = ctx.Queue()
    procs = [ctx.Process(target=worker, args=(k, seeds[k::args.workers], cfg, args.retries, queue))
             for k in range(args.workers)]
    for p in procs:
        p.start()
    rows, finished, t0 = [], 0, time.time()
    while finished < len(procs):
        r = queue.get()
        if r is None:
            finished += 1
            continue
        rows.append(r)
        print(f"{len(rows)}/{args.episodes} {r['piece']} {r['move']}: plain {'ok' if r['plain']['success'] else 'FAIL'}, "
              f"dart {'ok' if r['dart']['success'] else 'FAIL ' + r['dart']['reason']} offset {r['dart']['offset_mm']} "
              f"touch {r['plain']['pre_close_touch']}/{r['dart']['pre_close_touch']}", flush=True)
    for p in procs:
        p.join()

    def pct(a, b):
        return f"{a}/{b} ({100 * a / max(b, 1):.1f}%)"

    n = len(rows)
    perturbed = [r for r in rows if r["dart"]["offset_mm"] is not None]
    radii = np.array([np.hypot(*r["dart"]["offset_mm"]) for r in perturbed]) if perturbed else np.zeros(0)
    summary = dict(
        episodes=n, minutes=round((time.time() - t0) / 60, 1),
        plain_success=sum(r["plain"]["success"] for r in rows),
        dart_success_first=sum(r["dart"]["success"] for r in rows),
        dart_success_within_retries=sum(r["dart_ok_within"] is not None for r in rows),
        perturbation_found=len(perturbed),
        radius_mm=dict(median=round(float(np.median(radii)), 2), min=round(float(radii.min()), 2),
                       max=round(float(radii.max()), 2)) if len(radii) else None,
        plain_touch_episodes=sum(r["plain"]["pre_close_touch"] > 0 for r in rows),
        dart_touch_episodes=sum(r["dart"]["pre_close_touch"] > 0 for r in rows),
        plain_near_contact_episodes=sum(bool(r["plain"]["near_contacts"]) for r in rows),
        dart_near_contact_episodes=sum(bool(r["dart"]["near_contacts"]) for r in rows),
        dart_failures=[dict(seed=r["seed"], move=r["move"], reason=r["dart"]["reason"], offset_mm=r["dart"]["offset_mm"])
                       for r in rows if not r["dart"]["success"]])
    (out / "validation.json").write_text(json.dumps(dict(summary=summary, config=cfg["expert"], episodes=rows), indent=1))
    lines = ["# Perturbed (DART) teacher: validation", "",
             f"{n} scenes of the baseline profile (seed {args.seed}), each run plain and perturbed "
             f"(offset {cfg['expert']['dart_radius_mm']} mm, back on the plan {cfg['expert']['dart_clear_mm']} mm above "
             f"the target, return over {cfg['expert']['dart_return_s']} s). No cameras.", "",
             "| | plain teacher | perturbed teacher |", "|---|---|---|",
             f"| success | {pct(summary['plain_success'], n)} | {pct(summary['dart_success_first'], n)} "
             f"(within {args.retries} retries: {pct(summary['dart_success_within_retries'], n)}) |",
             f"| arm touched the target before closing | {pct(summary['plain_touch_episodes'], n)} | "
             f"{pct(summary['dart_touch_episodes'], n)} |",
             f"| arm touched another piece during approach/descent | {pct(summary['plain_near_contact_episodes'], n)} | "
             f"{pct(summary['dart_near_contact_episodes'], n)} |",
             f"| perturbation found (collision-free) | - | {pct(summary['perturbation_found'], n)} |",
             "", f"Executed offset: {summary['radius_mm']} mm.", ""]
    if summary["dart_failures"]:
        lines += ["Perturbed failures (first try):", ""] + [f"- {f['move']} offset {f['offset_mm']} mm: {f['reason']}"
                                                            for f in summary["dart_failures"]]
    (out / "validation.md").write_text("\n".join(lines) + "\n")
    print("\n".join(lines))


if __name__ == "__main__":
    main()