File size: 10,084 Bytes
33c14d6
 
9ffd3e8
 
 
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
33c14d6
 
 
 
 
 
9ffd3e8
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
 
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9ffd3e8
 
33c14d6
 
 
 
 
 
9ffd3e8
 
33c14d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Grasp validation: the scripted expert on every piece type on every square.

For each layout (its own piece set, board size, border, thickness and tray size)
and each piece type, the piece is put on each of the 64 squares with all its
neighbouring squares occupied by random pieces, and moved to a random square at least
two squares away whose neighbours are also occupied, or into the tray every
`bin_every`th trial. Every trial draws its own board pose (either colour facing the
robot), tray and table placement, as the dataset does. Success: the piece
rests within `success_center_mm` of the destination centre (or in the tray), upright,
and no other piece moved more than `disturb_mm`. Arm-to-piece contacts outside the
intended grasp are counted separately. Physics randomisation stays on.

Run:  .venv/bin/python sim/validate_expert.py            (writes sim/reports/)
"""
from __future__ import annotations

import argparse
import json
import multiprocessing as mp
import sys
import time
from collections import Counter, defaultdict
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
REPORTS = HERE / "reports"


def trials(cfg, seed):
    import numpy as np

    from chess_world import KINDS, SQUARES

    v = cfg["validation"]
    out = []
    for p in range(v["layouts"]):
        pose = None                     # drawn per trial by the randomiser
        for kind in KINDS:
            for s, sq in enumerate(SQUARES):
                i = len(out)
                out.append(dict(index=i, pose=p, board_pose=pose, piece_set=p % v["piece_sets"], kind=kind,
                                square=sq, bin=(i % v["bin_every"] == v["bin_every"] - 1), seed=seed * 100000 + i))
    return out


def neighbours(sq):
    f, r = ord(sq[0]) - 97, int(sq[1]) - 1
    return [f"{chr(97 + f + df)}{r + 1 + dr}" for df in (-1, 0, 1) for dr in (-1, 0, 1)
            if (df or dr) and 0 <= f + df < 8 and 0 <= r + dr < 8]


def chebyshev(a, b):
    return max(abs(ord(a[0]) - ord(b[0])), abs(int(a[1]) - int(b[1])))


def build_task(runner, t, rng):
    from chess_world import SQUARES
    from episode import Destination, Task

    w = runner.w
    bodies = list(rng.permutation(w.pieces))
    target = next(n for n in bodies if w.kind[n] == t["kind"])
    bodies.remove(target)
    squares = {t["square"]: target}
    for sq in neighbours(t["square"]):
        squares[sq] = bodies.pop()
    if t["bin"]:
        dest = Destination("bin", None)
    else:
        options = [s for s in SQUARES if chebyshev(s, t["square"]) >= 2]
        dst = options[rng.integers(len(options))]
        dest = Destination("square", None, dst)
        for sq in neighbours(dst):
            if sq not in squares and bodies:
                squares[sq] = bodies.pop()
    return Task(target, t["square"], dest, squares, [], "", "validation")


def worker(k, n, cfg, all_trials, queue):
    import warnings

    warnings.filterwarnings("ignore")
    import numpy as np

    from episode import EpisodeRunner
    from piece_sets import reference_set, sample_piece_set

    sets = [reference_set()] + [sample_piece_set(np.random.default_rng(1000 + j), cfg, f"validation_set{j}")
                                for j in range(1, cfg["validation"]["piece_sets"])]
    runners = {}
    for t in all_trials[k::n]:
        j = t["piece_set"]
        if j not in runners:
            runners[j] = EpisodeRunner(cfg, sets[j])
        runner = runners[j]
        rng = np.random.default_rng(t["seed"])
        task = build_task(runner, t, rng)
        runner.setup(rng, task=task, board_pose=t["board_pose"])
        info = runner.episode_info
        t0 = time.time()
        res = runner.run(task, t["seed"])
        queue.put(dict(t, board_pose=None, success=res.success, reason=res.reason,
                       destination=task.dest.square or "bin", centre_error_mm=res.centre_error_mm,
                       tilt_deg=res.tilt_deg, max_disturbance_mm=res.max_disturbance_mm,
                       stray_contacts=res.stray_contacts, jaw_yaw_deg=res.yaw_deg,
                       piece_set_name=sets[j].name, robot_plays=info["board"]["robot_plays"],
                       board=info["board"], tray=info["tray"], seconds=round(time.time() - t0, 2)))
    queue.put(None)


def summarise(results, cfg, minutes):
    ok = [r for r in results if r["success"]]
    rate = lambda rs: round(100 * sum(r["success"] for r in rs) / max(len(rs), 1), 2)
    by = lambda key: {str(k): rate([r for r in results if key(r) == k]) for k in sorted({key(r) for r in results})}
    stage = Counter()
    for r in results:
        if not r["success"]:
            reason = r["reason"]
            stage["planning (no collision-free grasp or path)" if reason.startswith("plan")
                  else "grasp" if reason.startswith("grasp")
                  else "placement" if "placement" in reason or "tray" in reason
                  else "disturbed a neighbour" if "disturbed" in reason else "other"] += 1
    stray = [r for r in results if r["stray_contacts"]]
    stray_kinds = Counter(key.split(":")[0] for r in stray for key in r["stray_contacts"])
    errors = [r["centre_error_mm"] for r in ok if r["centre_error_mm"] is not None]
    return dict(trials=len(results), success_percent=rate(results), target_percent=99.0,
                passed=rate(results) >= 99.0, by_piece=by(lambda r: r["kind"]),
                by_source_rank=by(lambda r: r["square"][1]), by_layout=by(lambda r: r["pose"]),
                by_robot_side=by(lambda r: r["robot_plays"]),
                by_destination=by(lambda r: "bin" if r["bin"] else "square"),
                failures_by_stage=dict(stage),
                trials_with_unintended_arm_piece_contact=len(stray),
                unintended_contact_phases=dict(stray_kinds),
                placement_error_mm=dict(mean=round(sum(errors) / max(len(errors), 1), 2),
                                        max=round(max(errors, default=0), 2)),
                max_neighbour_motion_mm_in_successes=max((r["max_disturbance_mm"] for r in ok), default=0),
                minutes=round(minutes, 1))


def write_report(summary, results, cfg):
    REPORTS.mkdir(exist_ok=True)
    (REPORTS / "grasp_validation.json").write_text(json.dumps(dict(summary=summary, trials=results), indent=1))
    lines = ["# Grasp validation", "",
             f"{summary['trials']} trials: every piece type on every square with all neighbours present, "
             f"{cfg['validation']['layouts']} layouts (board and tray size, piece set), each trial with its own "
             f"board pose, tray and table placement.", "",
             f"**Success: {summary['success_percent']}%** (target above {summary['target_percent']}%) "
             f"- {'PASS' if summary['passed'] else 'FAIL'}", "",
             f"Success = centre within {cfg['validation']['success_center_mm']} mm of the destination square "
             f"(or in the tray), tilt under {cfg['validation']['success_tilt_deg']} deg, "
             f"no other piece moved more than {cfg['validation']['disturb_mm']} mm.", ""]
    for title, key in (("By piece", "by_piece"), ("By source rank", "by_source_rank"),
                       ("By layout", "by_layout"), ("By robot side", "by_robot_side"),
                       ("By destination", "by_destination")):
        lines += [f"## {title}", "", "| | success % |", "|---|---|"]
        lines += [f"| {k} | {v} |" for k, v in summary[key].items()] + [""]
    lines += ["## Failures", "", "| stage | trials |", "|---|---|"]
    lines += [f"| {k} | {v} |" for k, v in summary["failures_by_stage"].items()] + [""]
    lines += [f"Trials with any arm-to-piece contact outside the intended grasp: "
              f"{summary['trials_with_unintended_arm_piece_contact']} "
              f"(by phase: {summary['unintended_contact_phases'] or 'none'}).", "",
              f"Placement error in successes: mean {summary['placement_error_mm']['mean']} mm, "
              f"max {summary['placement_error_mm']['max']} mm.", ""]
    fails = [r for r in results if not r["success"]]
    if fails:
        lines += ["## Failed trials", "", "| piece | from | to | pose | reason |", "|---|---|---|---|---|"]
        lines += [f"| {r['kind']} | {r['square']} | {r['destination']} | {r['pose']} | {r['reason'][:140]} |"
                  for r in fails] + [""]
    (REPORTS / "grasp_validation.md").write_text("\n".join(lines))


def main():
    from episode import load_config

    cfg = load_config()
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--workers", type=int, default=cfg["validation"]["workers"])
    ap.add_argument("--seed", type=int, default=7)
    ap.add_argument("--limit", type=int, default=0, help="run only every nth trial (quick check)")
    args = ap.parse_args()
    all_trials = trials(cfg, args.seed)
    if args.limit:
        all_trials = all_trials[::args.limit]
    ctx = mp.get_context("spawn")
    queue = ctx.Queue()
    procs = [ctx.Process(target=worker, args=(k, args.workers, cfg, all_trials, queue)) for k in range(args.workers)]
    for p in procs:
        p.start()
    t0, results, finished = time.time(), [], 0
    while finished < len(procs):
        r = queue.get()
        if r is None:
            finished += 1
            continue
        results.append(r)
        if len(results) % 50 == 0:
            print(f"{len(results)}/{len(all_trials)} trials, {100 * sum(x['success'] for x in results) / len(results):.1f}% success", flush=True)
    for p in procs:
        p.join()
    results.sort(key=lambda r: r["index"])
    summary = summarise(results, cfg, (time.time() - t0) / 60)
    write_report(summary, results, cfg)
    print(json.dumps(summary, indent=1))
    by_fail = defaultdict(list)
    for r in results:
        if not r["success"]:
            by_fail[r["reason"][:60]].append(f"{r['kind']}@{r['square']}")
    for reason, where in sorted(by_fail.items(), key=lambda x: -len(x[1]))[:15]:
        print(len(where), reason, where[:6])


if __name__ == "__main__":
    main()