Ali-Uraish commited on
Commit
a6dcf69
·
verified ·
1 Parent(s): 26952f4

Add files using upload-large-folder tool

Browse files
Files changed (1) hide show
  1. chess-sim/code/sim/validate_dart.py +131 -0
chess-sim/code/sim/validate_dart.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Validate the perturbed (DART) teacher against the plain teacher on the same scenes.
2
+
3
+ Each scene (episode seed, drawn as generate_dataset.py draws them) runs twice without
4
+ cameras: plain (the teacher as used for baseline_v1) and perturbed with probability 1
5
+ (Expert.perturb_pick). A perturbed run that fails is retried with fresh offsets, as the
6
+ generator does, up to --retries times. Reported per condition: success, the executed offset,
7
+ frames in which the arm touched the target before the jaws close, and arm contacts with other
8
+ pieces during the approach and descent.
9
+
10
+ Run: PHASE2_PROFILE=baseline,dart .venv/bin/python sim/validate_dart.py --episodes 100
11
+ """
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import json
16
+ import multiprocessing as mp
17
+ import sys
18
+ import time
19
+ from pathlib import Path
20
+
21
+ HERE = Path(__file__).resolve().parent
22
+ sys.path.insert(0, str(HERE))
23
+
24
+
25
+ def worker(k, seeds, cfg, retries, queue):
26
+ import numpy as np
27
+
28
+ from episode import EpisodeRunner
29
+ from piece_sets import sample_piece_set
30
+
31
+ cfg["expert"]["dart_probability"] = 1.0
32
+ runner = EpisodeRunner(cfg, sample_piece_set(np.random.default_rng([0, k]), cfg, f"validate{k}"))
33
+
34
+ def one(seed, attempt):
35
+ task = runner.setup(np.random.default_rng(seed))
36
+ t0 = time.time()
37
+ r = runner.run(task, seed, dart_attempt=attempt)
38
+ near = {key: n for key, n in r.stray_contacts.items() if key.split(":")[0] in ("approach", "descend")}
39
+ return dict(success=bool(r.success), reason=r.reason, offset_mm=r.dart_offset_mm,
40
+ pre_close_touch=int(r.pre_close_touch), near_contacts=near, seconds=round(time.time() - t0, 1),
41
+ move=f"{task.source}-{task.dest.square}", piece=runner.w.kind[task.target])
42
+
43
+ for seed in seeds:
44
+ plain = one(seed, -1)
45
+ tries = [one(seed, a) for a in range(1 + retries)]
46
+ first_ok = next((i for i, t in enumerate(tries) if t["success"]), None)
47
+ queue.put(dict(seed=seed, move=plain["move"], piece=plain["piece"], plain=plain, dart=tries[0],
48
+ dart_ok_within=first_ok, tries=tries))
49
+ queue.put(None)
50
+
51
+
52
+ def main():
53
+ import numpy as np
54
+
55
+ from episode import load_config
56
+
57
+ ap = argparse.ArgumentParser(description=__doc__)
58
+ ap.add_argument("--episodes", type=int, default=100)
59
+ ap.add_argument("--workers", type=int, default=8)
60
+ ap.add_argument("--seed", type=int, default=5_000_003)
61
+ ap.add_argument("--retries", type=int, default=2)
62
+ ap.add_argument("--out", default=str(HERE / "reports" / "dart_teacher"))
63
+ args = ap.parse_args()
64
+ cfg = load_config()
65
+ assert cfg["expert"].get("dart_radius_mm"), "run with PHASE2_PROFILE=baseline,dart"
66
+ out = Path(args.out)
67
+ out.mkdir(parents=True, exist_ok=True)
68
+ rng = np.random.default_rng(args.seed)
69
+ seeds = [int(rng.integers(2**62)) for _ in range(args.episodes)]
70
+ ctx = mp.get_context("spawn")
71
+ queue = ctx.Queue()
72
+ procs = [ctx.Process(target=worker, args=(k, seeds[k::args.workers], cfg, args.retries, queue))
73
+ for k in range(args.workers)]
74
+ for p in procs:
75
+ p.start()
76
+ rows, finished, t0 = [], 0, time.time()
77
+ while finished < len(procs):
78
+ r = queue.get()
79
+ if r is None:
80
+ finished += 1
81
+ continue
82
+ rows.append(r)
83
+ print(f"{len(rows)}/{args.episodes} {r['piece']} {r['move']}: plain {'ok' if r['plain']['success'] else 'FAIL'}, "
84
+ f"dart {'ok' if r['dart']['success'] else 'FAIL ' + r['dart']['reason']} offset {r['dart']['offset_mm']} "
85
+ f"touch {r['plain']['pre_close_touch']}/{r['dart']['pre_close_touch']}", flush=True)
86
+ for p in procs:
87
+ p.join()
88
+
89
+ def pct(a, b):
90
+ return f"{a}/{b} ({100 * a / max(b, 1):.1f}%)"
91
+
92
+ n = len(rows)
93
+ perturbed = [r for r in rows if r["dart"]["offset_mm"] is not None]
94
+ radii = np.array([np.hypot(*r["dart"]["offset_mm"]) for r in perturbed]) if perturbed else np.zeros(0)
95
+ summary = dict(
96
+ episodes=n, minutes=round((time.time() - t0) / 60, 1),
97
+ plain_success=sum(r["plain"]["success"] for r in rows),
98
+ dart_success_first=sum(r["dart"]["success"] for r in rows),
99
+ dart_success_within_retries=sum(r["dart_ok_within"] is not None for r in rows),
100
+ perturbation_found=len(perturbed),
101
+ radius_mm=dict(median=round(float(np.median(radii)), 2), min=round(float(radii.min()), 2),
102
+ max=round(float(radii.max()), 2)) if len(radii) else None,
103
+ plain_touch_episodes=sum(r["plain"]["pre_close_touch"] > 0 for r in rows),
104
+ dart_touch_episodes=sum(r["dart"]["pre_close_touch"] > 0 for r in rows),
105
+ plain_near_contact_episodes=sum(bool(r["plain"]["near_contacts"]) for r in rows),
106
+ dart_near_contact_episodes=sum(bool(r["dart"]["near_contacts"]) for r in rows),
107
+ dart_failures=[dict(seed=r["seed"], move=r["move"], reason=r["dart"]["reason"], offset_mm=r["dart"]["offset_mm"])
108
+ for r in rows if not r["dart"]["success"]])
109
+ (out / "validation.json").write_text(json.dumps(dict(summary=summary, config=cfg["expert"], episodes=rows), indent=1))
110
+ lines = ["# Perturbed (DART) teacher: validation", "",
111
+ f"{n} scenes of the baseline profile (seed {args.seed}), each run plain and perturbed "
112
+ f"(offset {cfg['expert']['dart_radius_mm']} mm, back on the plan {cfg['expert']['dart_clear_mm']} mm above "
113
+ f"the target, return over {cfg['expert']['dart_return_s']} s). No cameras.", "",
114
+ "| | plain teacher | perturbed teacher |", "|---|---|---|",
115
+ f"| success | {pct(summary['plain_success'], n)} | {pct(summary['dart_success_first'], n)} "
116
+ f"(within {args.retries} retries: {pct(summary['dart_success_within_retries'], n)}) |",
117
+ f"| arm touched the target before closing | {pct(summary['plain_touch_episodes'], n)} | "
118
+ f"{pct(summary['dart_touch_episodes'], n)} |",
119
+ f"| arm touched another piece during approach/descent | {pct(summary['plain_near_contact_episodes'], n)} | "
120
+ f"{pct(summary['dart_near_contact_episodes'], n)} |",
121
+ f"| perturbation found (collision-free) | - | {pct(summary['perturbation_found'], n)} |",
122
+ "", f"Executed offset: {summary['radius_mm']} mm.", ""]
123
+ if summary["dart_failures"]:
124
+ lines += ["Perturbed failures (first try):", ""] + [f"- {f['move']} offset {f['offset_mm']} mm: {f['reason']}"
125
+ for f in summary["dart_failures"]]
126
+ (out / "validation.md").write_text("\n".join(lines) + "\n")
127
+ print("\n".join(lines))
128
+
129
+
130
+ if __name__ == "__main__":
131
+ main()