File size: 24,253 Bytes
0dfbce2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
"""make_kong controller.

Wait for the opponent (franka) to knock one back-row tile face-up, push the matching
front-row group face-up, then pick the face-down pile tile with the left arm, hand it
to the right arm, stand it upright and place it at the right end of the row.

Everything that varies (which tile is knocked, whether pushes/grasps worked) is read
from cam_high and the measured robot state. Scene constants are static config facts
(task config make_kong.yml, mahjong asset metadata), see scene.py.
"""
import os
import sys
import json
import time
import traceback

import numpy as np

HERE = os.path.dirname(os.path.abspath(__file__))
if HERE not in sys.path:
    sys.path.insert(0, HERE)

import robodojo_toolkit as tk  # noqa: E402
from scene import *  # noqa: E402,F401,F403
import vision  # noqa: E402

ARM_I = {"left": 0, "right": 1}
JSL = {"left": slice(0, 6), "right": slice(7, 13)}
GJ = {"left": 6, "right": 13}      # gripper column in 14-D joint rows
GE = {"left": 7, "right": 15}      # gripper column in 16-D native EEF rows


def qmul(a, b):
    w1, x1, y1, z1 = a
    w2, x2, y2, z2 = b
    return np.array([w1 * w2 - x1 * x2 - y1 * y2 - z1 * z2,
                     w1 * x2 + x1 * w2 + y1 * z2 - z1 * y2,
                     w1 * y2 - x1 * z2 + y1 * w2 + z1 * x2,
                     w1 * z2 + x1 * y2 - y1 * x2 + z1 * w2])


def qaxis(axis, ang):
    axis = np.asarray(axis, float) / np.linalg.norm(axis)
    return np.r_[np.cos(ang / 2), np.sin(ang / 2) * axis]


def qrot(q, v):
    """Rotate vector v by wxyz quaternion q."""
    p = np.r_[0.0, v]
    qc = np.array([q[0], -q[1], -q[2], -q[3]])
    return qmul(qmul(q, p), qc)[1:]


def push_quat(pitch_deg):
    """Home orientation (fingers forward +y, closing along x) pitched down."""
    return qmul(qaxis([1, 0, 0], -np.radians(pitch_deg)), Q_HOME)


def push_link6(x, ytip, ztip, pitch_deg):
    th = np.radians(pitch_deg)
    return np.array([x, ytip - TIP_LEN * np.cos(th), ztip + TIP_LEN * np.sin(th)])


class EpisodeOver(Exception):
    pass


class Bot:
    def __init__(self, ctx):
        self.ctx = ctx
        self.out = getattr(ctx, "output_dir", None) or "/tmp/make_kong_out"
        os.makedirs(self.out, exist_ok=True)
        self.logf = open(os.path.join(self.out, "controller_log.txt"), "a")
        self.t0 = time.time()
        self.planner = tk.shared_planner()
        self.meta, self.img = None, {}
        self.observe()
        self.jcmd = np.array(self.meta["states"], float)   # last commanded joint row
        self.g = {"left": float(self.jcmd[6]), "right": float(self.jcmd[13])}

    # ------------------------------------------------------------------ basics
    def log(self, *a):
        s = "[%6.1fs step %s] " % (time.time() - self.t0, self.meta.get("step_id") if self.meta else "?") + \
            " ".join(str(x) for x in a)
        print(s, flush=True)
        try:
            self.logf.write(s + "\n")
            self.logf.flush()
        except Exception:
            pass

    def save(self, tag, cams=("cam_high",)):
        try:
            from PIL import Image
            for c in cams:
                if c in self.img:
                    Image.fromarray(self.img[c]).save(os.path.join(self.out, "%03d_%s_%s.png" % (self.step, tag, c)))
        except Exception as e:  # never let logging break control
            self.log("save failed", e)

    @property
    def step(self):
        return int(self.meta.get("step_id") or 0)

    @property
    def states(self):
        return np.array(self.meta["states"], float)

    def pos(self, arm):
        return np.array(self.meta["eef_positions"][ARM_I[arm]], float)

    def quat(self, arm):
        return np.array(self.meta["eef_quaternions_wxyz"][ARM_I[arm]], float)

    def grip_meas(self, arm):
        return float(self.meta["states"][GJ[arm]])

    def _update(self, reply):
        meta, img = tk.parse_reply(reply)
        self.meta, self.img = meta, img
        if tk.episode_ended(reply):
            raise EpisodeOver()

    def observe(self):
        self._update(self.ctx.call("robodojo_observe"))

    def _send(self, rows):
        rows = np.asarray(rows, float)
        if self.step + len(rows) > STEP_LIMIT:
            rows = rows[:max(0, STEP_LIMIT - self.step)]
            if not len(rows):
                raise EpisodeOver()
        tool = "robodojo_step" if rows.shape[1] == 14 else "robodojo_step_ee"
        for s in range(0, len(rows), 50):
            self._update(self.ctx.call(tool, actions=rows[s:s + 50].tolist()))

    # --------------------------------------------------------------- joint rows
    def run_joint(self, rows, ramp=None):
        """rows: N x 14. Gripper columns are forced to the commanded openings;
        ramp = {arm: target} ramps that gripper linearly over the rows."""
        rows = np.array(rows, float).reshape(-1, 14)
        n = len(rows)
        for arm in ("left", "right"):
            if ramp and arm in ramp:
                rows[:, GJ[arm]] = np.linspace(self.g[arm], ramp[arm], n + 1)[1:]
                self.g[arm] = float(ramp[arm])
            else:
                rows[:, GJ[arm]] = self.g[arm]
        rows[:, [6, 13]] = np.clip(rows[:, [6, 13]], 0.0, 1.0)
        self._send(rows)
        self.jcmd = rows[-1].copy()

    def arm_rows(self, arm, joint_list):
        """Joint rows moving one arm through joint_list, the other arm holding its command."""
        rows = []
        for j in joint_list:
            r = self.jcmd.copy()
            r[JSL[arm]] = j
            rows.append(r)
        return np.array(rows)

    def hold(self, n=1):
        self.run_joint(np.repeat(self.jcmd[None], n, axis=0))

    def gripper(self, arm, opening, n=8):
        self.run_joint(np.repeat(self.jcmd[None], n, axis=0), ramp={arm: opening})

    # ----------------------------------------------------------------- planner
    def plan(self, arm, p, q, grip=None, tries=None):
        """Collision-aware (robot + table only) free-space move; tries fallback waypoints."""
        targets = [(p, q)] if tries is None else tries
        for (pp, qq) in targets:
            state = self.jcmd.copy()
            state[JSL[arm]] = self.states[JSL[arm]]
            state[GJ[arm]] = self.g[arm]
            try:
                r = self.planner.plan(arm, state.tolist(), {"position": list(map(float, pp)),
                                                            "quaternion_wxyz": list(map(float, qq))},
                                      gripper_opening=grip)
            except Exception as e:
                self.log("plan exception", e)
                continue
            if r.get("status") != "Success":
                self.log("plan failed", arm, np.round(pp, 3), r.get("reason"))
                continue
            acts = np.array(r["actions"], float)
            other = "right" if arm == "left" else "left"
            acts[:, JSL[other]] = self.jcmd[JSL[other]]
            self.run_joint(acts, ramp=None if grip is None else {arm: grip})
            err = tk.pose_error(self.meta, arm, {"position": list(pp), "quaternion_wxyz": list(qq)})
            self.log("plan ok", arm, np.round(pp, 3), "rows", len(acts), "err", np.round(err, 4))
            return True
        return False

    def plan_rows(self, arm, tries):
        """Plan (without executing) through fallback targets; returns this arm's joint rows or None."""
        for (pp, qq) in tries:
            state = self.jcmd.copy()
            state[JSL[arm]] = self.states[JSL[arm]]
            state[GJ[arm]] = self.g[arm]
            try:
                r = self.planner.plan(arm, state.tolist(), {"position": list(map(float, pp)),
                                                            "quaternion_wxyz": list(map(float, qq))})
            except Exception as e:
                self.log("plan exception", e)
                continue
            if r.get("status") == "Success":
                self.log("planned", arm, np.round(pp, 3), "rows", len(r["actions"]))
                return np.array(r["actions"], float)[:, JSL[arm]]
            self.log("plan failed", arm, np.round(pp, 3), r.get("reason"))
        return None

    def run_parallel(self, arm_joint_rows, ramp=None):
        """Execute per-arm joint trajectories simultaneously (shorter ones hold their last row)."""
        n = max(len(v) for v in arm_joint_rows.values())
        rows = np.repeat(self.jcmd[None], n, axis=0)
        for arm, js in arm_joint_rows.items():
            js = np.asarray(js, float)
            rows[:, JSL[arm]] = np.vstack([js, np.repeat(js[-1:], n - len(js), axis=0)])
        self.run_joint(rows, ramp=ramp)

    def plan_joint_goal(self, arm, pp, qq, grip=None):
        """Plan to a pose and return (rows, final_joints) without executing."""
        state = self.jcmd.copy()
        state[JSL[arm]] = self.states[JSL[arm]]
        state[GJ[arm]] = self.g[arm]
        r = self.planner.plan(arm, state.tolist(), {"position": list(map(float, pp)),
                                                    "quaternion_wxyz": list(map(float, qq))},
                              gripper_opening=grip)
        if r.get("status") != "Success":
            return None, None
        acts = np.array(r["actions"], float)
        return acts, acts[-1][JSL[arm]].copy()

    # -------------------------------------------------------------- native EEF
    def ee_path(self, arm, poses, grip=None, ramp_rows=None):
        """Native IK path for one arm through [(p, q), ...]; other arm keeps its measured pose."""
        wps = [{arm: {"position": list(map(float, p)), "quaternion_wxyz": list(map(float, q))}} for p, q in poses]
        rows = np.array(tk.ee_rows(self.meta, wps), float)
        other = "right" if arm == "left" else "left"
        rows[:, GE[other]] = self.g[other]
        if grip is None:
            rows[:, GE[arm]] = self.g[arm]
        else:
            n = len(rows) if ramp_rows is None else min(ramp_rows, len(rows))
            ramp = np.full(len(rows), float(grip))
            ramp[:n] = np.linspace(self.g[arm], grip, n + 1)[1:]
            rows[:, GE[arm]] = ramp
            self.g[arm] = float(grip)
        rows[:, [7, 15]] = np.clip(rows[:, [7, 15]], 0.0, 1.0)
        self._send(rows)
        self.jcmd[JSL[arm]] = self.states[JSL[arm]]
        self.jcmd[JSL[other]] = self.states[JSL[other]]
        self.jcmd[6], self.jcmd[13] = self.g["left"], self.g["right"]

    def ee_line(self, arm, p_to, q=None, step=0.01, extra=0, grip=None):
        p0 = self.pos(arm)
        p1 = np.asarray(p_to, float)
        q = self.quat(arm) if q is None else np.asarray(q, float)
        n = max(1, int(np.ceil(np.linalg.norm(p1 - p0) / step)))
        poses = [(p0 + min(1.0, k / n) * (p1 - p0), q) for k in range(1, n + 1 + extra)]
        self.ee_path(arm, poses, grip=grip)
        err = tk.pose_error(self.meta, arm, {"position": list(p1), "quaternion_wxyz": list(q)})
        return err


# ============================================================================ phases
def wait_for_discard(bot):
    """Hold at home while the franka discards; return the knocked back-tile index."""
    img0 = bot.img["cam_high"]
    g0 = vision.back_green(img0)
    bot.log("initial back-tile green", np.round(g0, 2))
    bot.save("start", ("cam_high",))
    last, stable, cand = None, 0, None
    while bot.step < WAIT_MAX_STEPS:
        bot.hold(WAIT_POLL)
        im = bot.img["cam_high"]
        g = vision.back_green(im)
        fr = vision.franka_change(img0, im)
        ratio = g / np.maximum(g0, 0.05)
        order = np.argsort(ratio)
        cand = int(order[0])
        ok = ratio[cand] < 0.35 and ratio[order[1]] > 0.6 and fr < FRANKA_BACK_FRAC
        bot.log("wait g", np.round(g, 2), "franka", round(fr, 4), "cand", cand, "ok", ok)
        if ok and cand == last:
            stable += 1
        else:
            stable = 1 if ok else 0
        last = cand if ok else None
        if stable >= 2:
            break
    if cand is None:
        cand = 0
    bot.save("discarded", ("cam_high",))
    bot.log("knocked back tile", cand, "x", BACK_X[cand], "-> group", BACK_GROUP[cand])
    return BACK_GROUP[cand]


def push_candidates(arm, group):
    if arm == "left":
        return [20, 30, 12] if group == 0 else [12, 20, 30]
    return [12, 20, 30]


def densify(start, js, max_jump=MAX_ROW_JUMP):
    """Insert joint-space interpolation rows so no joint moves more than max_jump per row."""
    out, prev = [], np.asarray(start, float)
    for j in js:
        n = max(1, int(np.ceil(np.max(np.abs(j - prev)) / max_jump)))
        for k in range(1, n + 1):
            out.append(prev + (j - prev) * k / n)
        prev = j
    return out


def build_push(bot, arm, xs, pitch, seed, deep=0.0):
    """IK joint lists for pushing each tile in xs. Returns per-tile dict or None."""
    q = push_quat(pitch)
    out = []
    s = np.array(seed, float)
    prev_x = None
    for x in xs:
        seg = {}
        lat = []
        if prev_x is not None:
            for k in range(1, PUSH_LAT_ROWS + 1):
                xx = prev_x + (x - prev_x) * k / PUSH_LAT_ROWS
                lat.append(push_link6(xx, PUSH_Y0, PUSH_ZTIP, pitch))
        fwd = [push_link6(x, y, PUSH_ZTIP, pitch)
               for y in np.arange(PUSH_Y0 + PUSH_DY_FWD, PUSH_Y1 + deep + 1e-9, PUSH_DY_FWD)]
        ys_back = np.linspace(PUSH_Y1 + deep, PUSH_Y0, int(np.ceil((PUSH_Y1 + deep - PUSH_Y0) / PUSH_DY_BACK)) + 1)[1:]
        back = [push_link6(x, y, PUSH_ZTIP, pitch) for y in ys_back]
        for name, pts in (("lat", lat), ("fwd", fwd), ("back", back)):
            seg_start = s.copy()
            js = []
            for p in pts:
                j, info = tk.ik(arm, s.tolist(), {"position": list(map(float, p)), "quaternion_wxyz": list(q)})
                j = np.array(j, float)
                if not info.get("converged") or np.max(np.abs(j - s)) > IK_MAX_JUMP:
                    return None
                js.append(j)
                s = j
            seg[name] = densify(seg_start, js)
        seg["x"] = x
        out.append(seg)
        prev_x = x
    return out


def tile_fallen(bot, x):
    return vision.front_fallen_score(bot.img["cam_high"], x)


def find_push(bot, arm, group, xs):
    """First pitch whose plan to the pre pose, descent and push path are all feasible.
    Returns (pitch, plan_rows, descend_joints, segments) or None."""
    for pitch in push_candidates(arm, group):
        q = push_quat(pitch)
        pre = push_link6(xs[0], PUSH_Y0, PUSH_ZTIP + PUSH_PRE_DZ, pitch)
        rows, jf = bot.plan_joint_goal(arm, pre, q)
        if rows is None:
            bot.log("push pre-plan failed pitch", pitch)
            continue
        # descend from the pre pose (PUSH_PRE_DZ above) to the push height
        s = jf
        down = []
        for k in range(1, 4):
            p = push_link6(xs[0], PUSH_Y0, PUSH_ZTIP + PUSH_PRE_DZ * (1 - k / 3), pitch)
            j, info = tk.ik(arm, s.tolist(), {"position": list(map(float, p)), "quaternion_wxyz": list(q)})
            j = np.array(j, float)
            if not info.get("converged") or np.max(np.abs(j - s)) > IK_MAX_JUMP:
                down = None
                break
            down.append(j)
            s = j
        if down is None:
            bot.log("push descend IK failed pitch", pitch)
            continue
        segs = build_push(bot, arm, xs, pitch, s)
        if segs is None:
            bot.log("push path IK failed pitch", pitch)
            continue
        return pitch, rows, down, segs
    return None


def push_group(bot, group):
    xs = list(GROUP_X[group])
    arm = "left" if group in (0, 1) else "right"
    if arm == "right":
        xs = xs[::-1]
    before = [tile_fallen(bot, x) for x in xs]
    bot.log("push group", group, "arm", arm, "xs", xs, "white-before", np.round(before, 2))
    found = find_push(bot, arm, group, xs)
    if found is None:
        bot.log("NO push plan found")
        return None
    pitch, plan_rows, down, segs = found
    bot.log("push pitch", pitch)
    other = "right" if arm == "left" else "left"
    plan_rows[:, JSL[other]] = bot.jcmd[JSL[other]]
    # known-feasible way back: joints before the approach, the approach rows, the pre-pose joints
    bot.push_return = {"arm": arm, "start": bot.jcmd[JSL[arm]].copy(),
                       "approach": plan_rows[:, JSL[arm]].copy()}
    bot.run_joint(plan_rows, ramp={arm: 0.0})
    bot.run_joint(bot.arm_rows(arm, down))
    for i, seg in enumerate(segs):
        if seg["lat"]:
            bot.run_joint(bot.arm_rows(arm, seg["lat"]))
        bot.run_joint(bot.arm_rows(arm, seg["fwd"]))
        bot.run_joint(bot.arm_rows(arm, seg["back"]))
        sc = tile_fallen(bot, seg["x"])
        bot.log("pushed x", seg["x"], "white", round(sc, 2))
        if sc < FALLEN_WHITE:
            bot.log("tile not down; retry deeper")
            redo = build_push(bot, arm, [seg["x"]], pitch, bot.jcmd[JSL[arm]], deep=PUSH_RETRY_DEEP)
            if redo:
                bot.run_joint(bot.arm_rows(arm, redo[0]["fwd"]))
                bot.run_joint(bot.arm_rows(arm, redo[0]["back"]))
                bot.log("retry white", round(tile_fallen(bot, seg["x"]), 2))
    bot.save("pushed", ("cam_high",))
    # lift the pushing arm clear of the row before any free-space planning
    s = bot.jcmd[JSL[arm]].copy()
    q = push_quat(pitch)
    lift = []
    x_last = segs[-1]["x"]
    for k in range(1, 5):
        p = push_link6(x_last, PUSH_Y0 - 0.01 * k, PUSH_ZTIP + PUSH_LIFT * k / 4, pitch)
        j, info = tk.ik(arm, s.tolist(), {"position": list(map(float, p)), "quaternion_wxyz": list(q)})
        j = np.array(j, float)
        if not info.get("converged"):
            break
        lift.append(j)
        s = j
    if lift:
        bot.run_joint(bot.arm_rows(arm, lift))
    res = [round(tile_fallen(bot, x), 2) for x in GROUP_X[group]]
    bot.log("group white after", res)
    allx = [x for gg in GROUP_X for x in gg]
    bot.log("all front white", [round(tile_fallen(bot, x), 2) for x in allx])
    return arm


def retreat_rows(bot):
    """Pushing arm back to its pre-push joints: interpolate to the push pre pose, then the approach reversed."""
    pr = getattr(bot, "push_return", None)
    if pr is None:
        return None, None
    arm = pr["arm"]
    back = pr["approach"][::-1]
    rows = densify(bot.jcmd[JSL[arm]], [back[0]]) + list(back[1:]) + [pr["start"]]
    return arm, np.array(rows)


def pick_target(bot, push_arm):
    approach = [([PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L),
                ([PILE_X + 0.05, PILE_Y - 0.05, PICK_APPROACH_Z + 0.08], Q_DOWN_L)]
    rarm, rrows = retreat_rows(bot)
    if rarm == "left":
        bot.run_joint(bot.arm_rows("left", rrows))
        bot.log("left retreated", np.round(bot.pos("left"), 3))
    left = bot.plan_rows("left", approach)
    if left is None:
        bot.plan("left", None, None, tries=[(HOME_POSE["left"], Q_HOME)])
        left = bot.plan_rows("left", approach)
    if left is None:
        bot.log("pick approach plan failed")
        return False
    moves = {"left": left}
    if rarm == "right":
        moves["right"] = rrows
    bot.run_parallel(moves, ramp={"left": 1.0})
    bot.log("pick approach done; left", np.round(bot.pos("left"), 3), "right", np.round(bot.pos("right"), 3))
    if np.linalg.norm(bot.pos("left")[:2] - [PILE_X, PILE_Y]) > 0.01:
        bot.ee_line("left", [PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L, step=0.01, extra=2)
    bot.save("pick_above", ("cam_high", "cam_left_wrist"))
    for attempt in range(2):
        z = PICK_GRASP_Z - 0.004 * attempt
        err = bot.ee_line("left", [PILE_X, PILE_Y, z], Q_DOWN_L, step=0.0045, extra=1)
        bot.log("pick descended err", np.round(err, 4), "pos", np.round(bot.pos("left"), 4))
        bot.gripper("left", 0.0, n=8)
        bot.hold(2)
        gm = bot.grip_meas("left")
        bot.log("pick grip measured", round(gm, 3))
        bot.save("pick_closed", ("cam_left_wrist",))
        if gm > GRIP_HOLD_MIN_LEN:
            bot.ee_line("left", [PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L, step=0.0045)
            gm = bot.grip_meas("left")
            bot.log("lifted, grip", round(gm, 3))
            if gm > GRIP_HOLD_MIN_LEN:
                return True
        bot.log("grasp miss; reopening")
        bot.gripper("left", 1.0, n=6)
        bot.ee_line("left", [PILE_X, PILE_Y, PICK_APPROACH_Z], Q_DOWN_L, step=0.01)
    return False


def handover(bot):
    ok = bot.plan("left", HO_LEFT, Q_DOWN_L, grip=0.0,
                  tries=[(HO_LEFT, Q_DOWN_L), ([HO_LEFT[0] - 0.05, HO_LEFT[1], HO_LEFT[2] + 0.05], Q_DOWN_L)])
    if not ok:
        return False
    if np.linalg.norm(bot.pos("left") - HO_LEFT) > 0.005:
        bot.ee_line("left", HO_LEFT, Q_DOWN_L, step=0.01, extra=2)
    tile_z = bot.pos("left")[2] - GRASP_CENTER_BELOW_L6
    tile_x = bot.pos("left")[0]
    tile_y = bot.pos("left")[1]
    pre = [tile_x + HO_RIGHT_PRE_DX, tile_y, tile_z + HO_RIGHT_DZ]
    fin = [tile_x + HO_RIGHT_DX, tile_y, tile_z + HO_RIGHT_DZ]
    ok = bot.plan("right", pre, Q_MX, grip=1.0,
                  tries=[(pre, Q_MX), ([pre[0] + 0.05, pre[1] - 0.05, pre[2] + 0.05], Q_MX)])
    if not ok:
        return False
    bot.ee_line("right", fin, Q_MX, step=0.004, extra=1)
    bot.save("ho_right_in", ("cam_high", "cam_right_wrist"))
    bot.gripper("right", 0.0, n=8)
    bot.hold(1)
    gm = bot.grip_meas("right")
    bot.log("handover right grip", round(gm, 3))
    if gm < GRIP_HOLD_MIN_WID:
        bot.log("right grasp miss")
        return False
    bot.gripper("left", 1.0, n=6)
    lp = bot.pos("left")
    bot.ee_line("left", [lp[0], lp[1], lp[2] + 0.06], Q_DOWN_L, step=0.01)
    gm = bot.grip_meas("right")
    bot.log("after left release, right grip", round(gm, 3))
    bot.save("ho_done", ("cam_high", "cam_right_wrist"))
    ok = bot.plan("left", LEFT_PARK, Q_DOWN_L, grip=1.0,
                  tries=[(LEFT_PARK, Q_DOWN_L), ([-0.2, -0.3, 1.15], Q_DOWN_L), ([-0.25, -0.35, 1.0], Q_HOME)])
    if not ok:
        bot.log("left park failed; lifting left instead")
        lp = bot.pos("left")
        bot.ee_line("left", [lp[0] - 0.10, lp[1] - 0.05, lp[2] + 0.02], Q_DOWN_L, step=0.01)
    return gm >= GRIP_HOLD_MIN_WID


def rotate_and_place(bot):
    p6 = bot.pos("right")
    q6 = bot.quat("right")
    xaxis = qrot(q6, [1.0, 0.0, 0.0])
    tip = p6 + TIP_LEN * xaxis
    bot.log("rotate about tip", np.round(tip, 4))
    poses = []
    for k in range(1, ROT_ROWS + 1):
        phi = np.radians(90.0 * k / ROT_ROWS)
        pos = tip + TIP_LEN * np.array([np.cos(phi), 0.0, np.sin(phi)]) + np.array([0, 0, ROT_LIFT * k / ROT_ROWS])
        poses.append((pos, qmul(qaxis([0, 1, 0], -phi), Q_MX)))
    poses += [poses[-1]] * 2
    bot.ee_path("right", poses)
    gm = bot.grip_meas("right")
    bot.log("rotated; right grip", round(gm, 3), "pos", np.round(bot.pos("right"), 4))
    bot.save("rotated", ("cam_high", "cam_right_wrist"))
    place_x = GOAL_X + PLACE_DX
    bot.ee_line("right", [place_x, GOAL_Y, PLACE_ABOVE_Z], Q_DOWN_R, step=0.015, extra=1)
    err = bot.ee_line("right", [place_x, GOAL_Y, PLACE_Z], Q_DOWN_R, step=0.005, extra=2)
    bot.log("placed err", np.round(err, 4), "pos", np.round(bot.pos("right"), 4))
    bot.save("placed", ("cam_high", "cam_right_wrist"))
    bot.gripper("right", 1.0, n=6)
    rp = bot.pos("right")
    bot.ee_line("right", [rp[0], rp[1], rp[2] + 0.03], Q_DOWN_R, step=0.01)
    bot.save("released", ("cam_high", "cam_right_wrist"))
    return True


def run_task(bot):
    group = wait_for_discard(bot)
    push_arm = push_group(bot, group)
    if not pick_target(bot, push_arm):
        bot.log("pick failed")
        return
    if not handover(bot):
        bot.log("handover failed")
        return
    rotate_and_place(bot)
    bot.hold(5)
    bot.log("done")


def main(ctx):
    bot = None
    try:
        bot = Bot(ctx)
        run_task(bot)
    except EpisodeOver:
        if bot:
            bot.log("episode over")
    except Exception:
        msg = traceback.format_exc()
        if bot:
            bot.log("EXCEPTION", msg)
        else:
            print(msg, flush=True)
    finally:
        if bot:
            bot.log("final step", bot.step)