File size: 28,355 Bytes
e3be6f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
"""Reference controller for counter cell KC-3 (grocery sort, SO-101).

Staged loop (iteration skill): calibrate the counter height by touch-off, then per item
observe -> plan -> grasp with a force-limited close -> verify the lift -> carry -> place ->
verify after release and settle, going back to the first stage whose goal no longer holds.
Motion comes from the motion-planning skill: IK, plan_arm with the held item attached, and
plan_cartesian_stroke for every vertical move. Faults (critic rubric, T4): a dead gripper shows
as an applied gripper command that differs from ours, and frozen perception as a stamp that
stops advancing or readings that stop changing although the sensor is noisy.
"""
from __future__ import annotations

import math
import os
import sys

import numpy as np

# Item data from the parameter sheet: bin, radius (half-width across the jaws), half-height /
# rest height of the centre, TCP height above the counter for the grasp, squeeze past contact.
ITEMS = {
    "egg_cup": dict(bin="fresh_bin", r=0.016, h=0.017, gz=0.012, squeeze=0.02, box=False),
    "yogurt_pot": dict(bin="fresh_bin", r=0.017, h=0.020, gz=0.012, squeeze=0.06, box=False),
    "spice_jar": dict(bin="pantry_bin", r=0.014, h=0.020, gz=0.012, squeeze=0.06, box=False),
    "snack_bar": dict(bin="pantry_bin", r=0.011, h=0.008, gz=0.013, squeeze=0.06, box=True, half_len=0.026),
}
PUNNET = ("berry_punnet", 0.034, 0.032)
BINS = ("fresh_bin", "pantry_bin")
BIN_INNER = (0.055, 0.050)
FIXED_JAW = 0.0195        # fixed-jaw contact line from the TCP along the closing axis (m)
STANDOFF = 0.005          # fixed-jaw clearance from the item before closing (m)
TOUCH_Z_NOMINAL = 0.0036  # TCP height at which the touch-off trips on a nominal counter (m)
HOVERS = (0.066, 0.060, 0.054, 0.048)
GRIP_OPEN = 1.2
RETURNS_X = -0.10


class Fault(Exception):
  def __init__(self, fault):
    super().__init__(fault)
    self.fault = fault


class Retry(Exception):
  pass


def rz(a):
  c, s = math.cos(a), math.sin(a)
  return np.array([[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]])


def yaw_of(q):
  w, x, y, z = q
  return math.atan2(2 * (w * z + x * y), 1 - 2 * (y * y + z * z))


def tilt_deg(q):
  return math.degrees(math.acos(float(np.clip(1 - 2 * (q[1] ** 2 + q[2] ** 2), -1, 1))))


def wrap(a):
  return (a + math.pi) % (2 * math.pi) - math.pi


class Controller:
  def __init__(self, info):
    app = os.path.dirname(os.path.abspath(info["scene_xml"]))
    sys.path.insert(0, os.path.join(app, "skills", "motion-planning", "scripts"))
    import motion_planner as mp  # noqa: PLC0415
    self.mp = mp
    self.pl = mp.RobotArmPlanner(mjcf_path=os.path.join(app, "robot", "so101.xml"))
    self.hint = np.array(self.pl.gripper_frame_info()["top_down_rot_hint"], float)
    self.dt = float(info["control_dt_s"])
    self.lo = np.array(info["ctrl_low"], float)
    self.hi = np.array(info["ctrl_high"], float)
    self.max_step = float(info["max_command_step_frac"]) * (self.hi - self.lo)
    self.qmin, self.qmax = np.array(self.pl.q_min), np.array(self.pl.q_max)
    self.period = 1.0 / float(info["perception_hz"])
    # The planner's arm model leaves out the wrist camera mount; self-collision is checked again on the
    # robot's own MJCF (contacts reported from 3 mm out).
    import mujoco  # noqa: PLC0415
    self.mj = mujoco
    self.rm = mujoco.MjModel.from_xml_path(os.path.join(app, "robot", "so101.xml"))
    self.rm.geom_margin[:] = 0.003
    self.rd = mujoco.MjData(self.rm)
    self.r_qadr = [self.rm.jnt_qposadr[self.rm.joint(n).id] for n in
                   ("shoulder_pan", "shoulder_lift", "elbow_flex", "wrist_flex", "wrist_roll")]

  # ------------------------------------------------------------------ episode
  def reset(self, obs):
    self.obs = obs
    self.cmd = np.array(obs["ctrl"], float).copy()
    self.sent = None
    self.readings = []
    self.last_stamp = None
    self.last_new_time = obs["time"]
    self.same_count = 0
    self.noise_seen = False
    self.dz = 0.0
    self.gbias = 0.0
    self.placed = {}
    self.log = []
    self._ingest(obs)
    self.gen = self.run()

  def act(self, obs):
    self.obs = obs
    try:
      self._check_gripper(obs)
      self._ingest(obs)
      out = next(self.gen)
    except Fault as f:
      return {"status": "abort", "fault": f.fault}
    except StopIteration:
      return {"status": "done"}
    cmd = np.clip(np.asarray(out, float), self.lo, self.hi)
    cmd = np.clip(cmd, self.cmd - self.max_step, self.cmd + self.max_step)
    self.cmd = cmd
    self.sent = cmd.copy()
    return cmd

  def note(self, *a):
    self.log.append((round(float(self.obs["time"]), 2),) + a)

  # ------------------------------------------------------------- monitoring
  def _check_gripper(self, obs):
    # The applied command is echoed back; a dead gripper servo ignores ours.
    if self.sent is not None and abs(float(obs["ctrl"][5]) - float(self.sent[5])) > 1e-9:
      raise Fault("dead_gripper")

  def _ingest(self, obs):
    st, objs, t = obs["objects_stamp"], obs["objects"], obs["time"]
    if st is None or not objs:
      return
    if self.last_stamp is None or st != self.last_stamp:
      prev = self.readings[-1][1] if self.readings else None
      self.readings.append((t, {k: np.array(v, float) for k, v in objs.items()}))
      self.readings = self.readings[-300:]
      self.last_stamp = st
      self.last_new_time = t
      if prev is not None:
        if all(not np.array_equal(prev[b][:3], objs[b][:3]) for b in BINS):
          self.noise_seen = True     # bins never move: changing readings mean sensor noise
        same = all(np.array_equal(prev[k], objs[k]) for k in objs)
        self.same_count = self.same_count + 1 if same else 0
        if self.noise_seen and self.same_count >= 3:
          raise Fault("perception_freeze")
    elif t - self.last_new_time > 3.5 * self.period:
      raise Fault("perception_freeze")

  def noise(self):
    """Perception noise std estimated from the (static) bins."""
    if len(self.readings) < 4:
      return 0.003
    p = np.array([r[1][b][:3] for r in self.readings[-30:] for b in BINS[:1]])
    return float(np.mean(np.std(p, axis=0)))

  def est(self, name, since=None, n_max=25, extend=True):
    """Median pose over the readings since the item last moved: the most recent readings (or those
    after `since`), extended back while older readings stay consistent with the running median."""
    rs = self.readings[-n_max:]
    recent = [r for r in rs if since is not None and r[0] >= since]
    if len(recent) < 2:
      recent = rs[-2:]
    tol = max(0.005, 5.0 * self.noise())     # reading-to-median distance stays inside this ~99.9% of the time
    keep = [r[1][name][:3] for r in recent]
    m, out = np.median(keep, axis=0), 0
    for r in reversed(rs[:len(rs) - len(recent)] if extend else []):
      if np.linalg.norm(r[1][name][:3] - m) > tol:
        out += 1
        if out >= 3:      # three in a row: the item was somewhere else back then
          break
        continue
      out = 0
      keep.append(r[1][name][:3])
      m = np.median(keep, axis=0)
    return m, recent[-1][1][name][3:7]

  # ------------------------------------------------------------- primitives
  def q(self):
    return self.cmd[:5].copy()

  def hold(self, t):
    for _ in range(max(1, int(round(t / self.dt)))):
      yield self.cmd.copy()

  def ik(self, pos, psi, seed=None, restarts=2):
    """Top-down IK for TCP position pos and jaw yaw psi; seeded from the current (or given) joints,
    then from a canonical posture facing the target."""
    pos = np.asarray(pos, float)
    rot = rz(psi) @ self.hint
    r = self.pl.solve_ik(pos, rot, q_seed=self.q() if seed is None else seed, num_restarts=restarts)
    if not (r["pos_err_m"] < 0.003 and r["rot_err_rad"] < 0.05) and restarts > 1:
      a = math.atan2(pos[1], pos[0])
      canon = np.array([-a - 0.08, -0.2, 0.45, 1.36, wrap(-1.66 + (psi - a))])
      r = self.pl.solve_ik(pos, rot, q_seed=canon, num_restarts=restarts + 1)
    ok = r["pos_err_m"] < 0.003 and r["rot_err_rad"] < 0.05
    return np.asarray(r["q"], float), ok

  def goto(self, q_goal, vmax=1.2, grip=None, tmin=0.3):
    q0, g0 = self.q(), self.cmd[5]
    g1 = g0 if grip is None else grip
    T = max(tmin, float(np.max(np.abs(q_goal - q0))) / vmax * 1.6, abs(g1 - g0) / 2.0)
    n = max(1, int(round(T / self.dt)))
    for i in range(1, n + 1):
      s = 0.5 - 0.5 * math.cos(math.pi * i / n)
      yield np.r_[q0 + s * (q_goal - q0), g0 + s * (g1 - g0)]

  def grip_to(self, g, tmin=0.2):
    yield from self.goto(self.q(), grip=g, tmin=tmin)

  def retime(self, traj, vmax):
    """Re-times a joint path with a cosine speed profile whose peak joint speed is vmax."""
    pts = np.vstack([self.q(), np.asarray(traj, float)])
    seg = np.max(np.abs(np.diff(pts, axis=0)), axis=1)
    cum = np.r_[0.0, np.cumsum(seg)]
    if cum[-1] < 1e-6:
      return pts[-1:]
    n = max(2, int(math.ceil(math.pi / 2 * cum[-1] / vmax / self.dt)))
    s = cum[-1] * (0.5 - 0.5 * np.cos(np.pi * np.arange(1, n + 1) / n))
    return np.array([[np.interp(si, cum, pts[:, j]) for j in range(5)] for si in s])

  def stroke(self, pos, psi, vmax=0.8):
    r = self.pl.plan_cartesian_stroke(self.q(), np.asarray(pos, float), rz(psi) @ self.hint, num_waypoints=10,
                                      max_joint_vel_rad_s=vmax, control_dt_s=self.dt)
    traj = r.get("q_trajectory")
    if r["solved"] and traj is not None and len(traj):
      end, _ = self.pl.fk(np.asarray(traj[-1], float))
      if np.linalg.norm(np.asarray(end, float) - np.asarray(pos, float)) > 0.003:
        traj = None    # "solved" but short of the goal (near the reach limits)
    if not r["solved"] or traj is None or len(traj) == 0:
      # Fallback: straight line in Cartesian space, IK chained along it.
      p0 = self.fk()
      qs, q = [], self.q()
      for a in np.linspace(0.0, 1.0, 9)[1:]:
        q, ok = self.ik(p0 + a * (np.asarray(pos, float) - p0), psi, seed=q, restarts=2)
        if not ok:
          raise Retry("stroke ik")
        qs.append(q)
      for qa in qs:
        yield from self.goto(qa, vmax=vmax, tmin=0.04)
      return
    for qa in self.retime(traj, vmax):
      yield np.r_[qa, self.cmd[5]]

  def transit(self, qg, scene, vmax=2.2, grip=None):
    # Bounded by iterations, not wall time, so runs repeat exactly.
    r = self.pl.plan_arm(scene, self.q(), qg, max_joint_vel_rad_s=vmax, control_dt_s=self.dt,
                         safety_margin_m=0.006, max_time_ms=20000.0, max_iterations=4000)
    g0 = self.cmd[5]
    g1 = g0 if grip is None else grip
    if r["solved"] and r.get("q_trajectory") is not None and len(r["q_trajectory"]):
      traj = self.retime(r["q_trajectory"], vmax)
      for i, qa in enumerate(traj):
        yield np.r_[qa, g0 + (g1 - g0) * min(1.0, (i + 1) / max(1, len(traj) // 2))]
    else:
      self.note("plan_arm failed")
      yield from self.goto(qg, vmax=vmax * 0.6, grip=grip)

  def hover(self, xy, psi, seed=None, hovers=HOVERS):
    """Highest reachable hover above xy for gripper yaw psi: (z above the counter, q) or None."""
    for z in hovers:
      qh, ok = self.ik([xy[0], xy[1], z + self.Z(xy)], psi, seed=seed)
      if ok:
        return z, qh
    return None

  def self_clear(self, q):
    """True when no two robot links come within 3 mm of each other at joint angles q."""
    d = self.rd
    d.qpos[:] = 0.0
    d.qpos[self.r_qadr] = q
    d.qpos[self.rm.jnt_qposadr[self.rm.joint("gripper").id]] = 0.6
    self.mj.mj_forward(self.rm, d)
    return d.ncon == 0

  def fk(self):
    p, _ = self.pl.fk(self.q())
    return np.asarray(p, float)

  def current_psi(self):
    _, rot = self.pl.fk(self.q())
    y = np.asarray(rot, float) @ np.array([0.0, 0.0, 1.0])
    return math.atan2(y[0], -y[1])

  def gap(self):
    """True gripper position minus command: how far the jaw is held open by what it grips."""
    return float(self.obs["qpos"][5]) - self.gbias - float(self.cmd[5])

  # -------------------------------------------------------------- world model
  def footprint(self, name):
    it = ITEMS.get(name)
    return PUNNET[1] if it is None else it.get("half_len", it["r"])

  def scene(self, skip=(), sag=0.0):
    sc = self.mp.Scene3D()
    sc.add_aligned_box("counter", [0.015, 0.0, -0.02 + self.Z((0.015, 0.0))], [0.315, 0.34, 0.02], group="table")
    for b in BINS:   # hollow: floor plus four walls (rim at 38 mm)
      c, _ = self.est(b, n_max=60)
      z = self.Z(c)
      sc.add_aligned_box(b + "_floor", [c[0], c[1], z + 0.003], [0.061, 0.056, 0.003], group="table")
      sc.add_aligned_box(b + "_n", [c[0], c[1] + 0.053, z + 0.019], [0.061, 0.003, 0.019], group="bins")
      sc.add_aligned_box(b + "_s", [c[0], c[1] - 0.053, z + 0.019], [0.061, 0.003, 0.019], group="bins")
      sc.add_aligned_box(b + "_e", [c[0] + 0.058, c[1], z + 0.019], [0.003, 0.050, 0.019], group="bins")
      sc.add_aligned_box(b + "_w", [c[0] - 0.058, c[1], z + 0.019], [0.003, 0.050, 0.019], group="bins")
    for n in list(ITEMS) + [PUNNET[0]]:
      if n in skip:
        continue
      c, _ = self.est(n)
      if c[0] < RETURNS_X:
        continue
      top = c[2] + (PUNNET[2] / 2 if n == PUNNET[0] else ITEMS[n]["h"])
      sc.add_vertical_cylinder(n, [c[0], c[1], self.Z(c)], self.footprint(n) + 0.004, top + 0.004 + sag)
    return sc

  def others(self, skip):
    out = []
    for n in list(ITEMS) + [PUNNET[0]]:
      if n == skip:
        continue
      c, _ = self.est(n)
      if c[0] > RETURNS_X:
        out.append((c[:2], self.footprint(n)))
    return out

  def held_object(self, name, sh):
    obj = self.mp.MultiSphereObject(name=name)
    if sh.get("lying") or ITEMS[name]["box"]:
      obj.add_capsule_spheres([-sh["half_len"] + sh["r"] * 0.6, 0, 0], [sh["half_len"] - sh["r"] * 0.6, 0, 0],
                              sh["r"] * 0.8 if ITEMS[name]["box"] else sh["r"], num_spheres=4)
    else:
      h = ITEMS[name]["h"]
      obj.add_capsule_spheres([0, 0, -h + sh["r"] * 0.7], [0, 0, h - sh["r"] * 0.7], sh["r"], num_spheres=3)
    return obj

  # ---------------------------------------------------------------- stages
  def run(self):
    g = []
    for _ in range(20):
      g.append(float(self.obs["qpos"][5]) - float(self.cmd[5]))
      yield self.cmd.copy()
    self.gbias = float(np.mean(g[5:]))
    yield from self.touch_off()
    todo = [n for n in ITEMS if self.est(n)[0][0] > RETURNS_X]
    todo.sort(key=lambda n: (n != "egg_cup", -math.atan2(self.est(n)[0][1], self.est(n)[0][0])))
    attempts = {n: 0 for n in todo}
    queue = list(todo)
    while queue:
      if self.obs["time"] > 41.0:
        break
      name = queue.pop(0)
      attempts[name] += 1
      self.note("pick", name, attempts[name])
      try:
        yield from self.pick_place(name)
      except Retry as e:
        self.note("retry", name, str(e))
        if "on its side" in str(e):
          attempts[name] = 4
        yield from self.recover()
      ok = yield from self.verify(name)
      self.note("verified", name, ok)
      if ok:
        self.placed[name] = True
      elif attempts[name] < 4:
        queue.insert(0, name)
      for n in list(self.placed):       # a placed item that was knocked out goes back in the queue
        if not self.in_bin(n):
          del self.placed[n]
          if n not in queue and attempts[n] < 4:
            queue.insert(0, n)
    yield from self.hold(0.2)

  def touch_off(self):
    """Counter height under the arm: lower the TCP on a clear spot until the joints stall."""
    obst = self.others(skip=None)
    spots = [np.array([0.26 * math.cos(a), 0.26 * math.sin(a)]) for a in np.radians([0, 10, -10, 20, -20, 5, -5])]
    spot = max(spots, key=lambda s: min(np.linalg.norm(s - c) - r for c, r in obst))
    psi = math.atan2(spot[1], spot[0])
    qh, _ = self.ik([spot[0], spot[1], 0.062], psi)
    yield from self.transit(qh, self.scene())
    yield from self.hold(0.2)
    base, z, hits = [], 0.062, 0
    while z > -0.035:
      z -= 0.04 * self.dt
      qz, _ = self.ik([spot[0], spot[1], z], psi, restarts=1)
      yield np.r_[qz, self.cmd[5]]
      e = self.cmd[:5] - self.obs["qpos"][:5]
      if z > 0.059:
        continue
      if z > 0.049:
        base.append(e)
        continue
      hits = hits + 1 if float(np.linalg.norm((e - np.mean(base, axis=0))[1:4])) > 0.012 else 0
      if hits >= 2:
        break
    self.dz = z - TOUCH_Z_NOMINAL
    self.note("touch_dz", round(self.dz, 4))
    yield from self.stroke([spot[0], spot[1], 0.05 + self.dz], psi, vmax=0.8)

  def Z(self, xy):
    """Counter height offset at xy (one touch-off: a constant)."""
    return self.dz

  def shape(self, name, quat):
    """Graspable shape in the current pose: half-width across the jaws, half-length along them,
    TCP height above the item's bottom, and the jaw yaws worth trying."""
    it = ITEMS[name]
    if it["box"]:
      return dict(r=it["r"], half_len=it["half_len"], gz=it["gz"],
                  yaws=[wrap(yaw_of(quat) + k * math.pi) for k in (0, 1)])
    if tilt_deg(quat) > 50.0:   # a cylinder lying on its side: close across it
      w, x, y, z = quat
      a = math.atan2(2 * (y * z - w * x), 2 * (x * z + w * y))
      return dict(r=it["r"], half_len=it["h"], gz=max(0.007, it["r"] - 0.004),
                  yaws=[wrap(a + k * math.pi) for k in (0, 1)], lying=True, axis_yaw=a)
    return dict(r=it["r"], half_len=it["r"], gz=it["gz"], yaws=[math.radians(d) for d in range(-180, 180, 20)])

  def in_bin_xy(self, xy):
    """(bin centre, True) when xy lies inside a bin's outer footprint."""
    for b in BINS:
      bc, _ = self.est(b, n_max=60)
      if abs(xy[0] - bc[0]) < 0.061 and abs(xy[1] - bc[1]) < 0.056:
        return bc
    return None

  def open_margin(self, c):
    return 0.25 if self.in_bin_xy(c[:2]) is not None else 0.4

  def grasp_plan(self, name, c, sh):
    """Jaw yaw whose fixed jaw and moving-jaw sweep stay clearest of neighbours and bin walls, with a
    reachable hover and a grasp pose the planner finds collision-free."""
    others = self.others(skip=name)
    bc = self.in_bin_xy(c[:2])
    sweep = (0.0, 0.012, 0.024) if bc is not None else (0.0, 0.012, 0.024, 0.036)
    self.pl.set_gripper_opening(min(GRIP_OPEN, self.contact_q(sh["r"]) + self.open_margin(c)))
    scene = self.scene(skip=(name,))
    cands = []
    for psi in sh["yaws"]:
      yd = rz(psi)[:2, 1]
      pts = [c[:2] + yd * (sh["r"] + STANDOFF + d) for d in (0.0, 0.006)]
      pts += [c[:2] - yd * (sh["r"] + d) for d in sweep]
      clear = min(np.linalg.norm(p - oc) - orad for p in pts for oc, orad in others)
      if bc is not None:   # jaws must stay off the walls of the bin the item sits in
        clear = min(clear, min(min(BIN_INNER[0] - abs(p[0] - bc[0]), BIN_INNER[1] - abs(p[1] - bc[1])) for p in pts) - 0.004)
      radial = abs(wrap(psi - math.atan2(c[1], c[0])))
      cands.append((min(clear, 0.04) - 0.006 * radial, psi))
    cands.sort(key=lambda x: -x[0])
    for _, psi in cands[:8]:
      tcp = c[:2] + rz(psi)[:2, 1] * (sh["r"] + STANDOFF - FIXED_JAW)
      hv = self.hover(tcp, psi)
      if hv is None:
        continue
      qg, ok = self.ik(np.r_[tcp, sh["gz"] + self.Z(tcp)], psi, seed=hv[1])
      if not ok:
        continue
      chk = self.pl.check_arm_config(scene, qg, ignore_obstacles=("table",))
      if chk["valid"] and chk["min_clearance_m"] > 0.002 and self.self_clear(qg) and self.self_clear(hv[1]):
        return psi, tcp, hv
    raise Retry("no grasp pose")

  def place_plan(self, name, bin_c, sh, check=False):
    """Spot and jaw yaw in the bin: the item, both jaws and the opened moving jaw clear the walls and
    the items already there; hover and release poses both have IK solutions."""
    it = ITEMS[name]
    r, half_len = sh["r"], sh["half_len"]
    occupied = [(self.est(n)[0][:2], self.footprint(n)) for n in self.placed if ITEMS[n]["bin"] == it["bin"]]
    hx, hy = BIN_INNER[0] - 0.003, BIN_INNER[1] - 0.003
    cands = []
    for px in np.linspace(-0.035, 0.035, 8):
      for py in np.linspace(-0.03, 0.03, 5):
        c = bin_c[:2] + [px, py]
        for deg in range(-180, 180, 30):
          psi = math.radians(deg)
          yd, xd = rz(psi)[:2, 1], rz(psi)[:2, 0]
          pts = [c + yd * (r + 0.008), c - yd * (r + 0.020), c + xd * half_len, c - xd * half_len]
          wall = min(min(hx - abs(p[0] - bin_c[0]), hy - abs(p[1] - bin_c[1])) for p in pts)
          if wall < 0.0:
            continue
          occ = min([np.linalg.norm(p - oc) - orad for p in pts + [c] for oc, orad in occupied] + [0.05])
          if occ < 0.008:
            continue
          end = 0.0 if occupied else abs(abs(px) - 0.03)   # first item of a bin goes to one end
          cands.append((min(wall, 0.012) + min(occ, 0.03) - 0.02 * end - 0.04 * np.linalg.norm(c), c, psi))
    cands.sort(key=lambda x: -x[0])
    scene = self.scene(skip=(name,)) if check else None
    why = {}
    base = 0.012 + 2 * it["h"]   # fingertips clear the item after release
    # Carried over the items already in the bin: the held item's bottom must clear their tops.
    occ_top = max([0.006 + 2 * ITEMS[n]["h"] for n in self.placed if ITEMS[n]["bin"] == it["bin"]] + [0.0])
    need = max(base, occ_top + sh["gz"] + 0.014)
    hovers = [h for h in (0.080, 0.073) + HOVERS if h >= base]
    fallback = None
    for _, c, psi in cands[:30]:
      tcp = c + rz(psi)[:2, 1] * (r - FIXED_JAW)
      hv = self.hover(tcp, psi, hovers=hovers if need > base else [h for h in HOVERS if h >= base])
      if hv is None:
        why["hover"] = why.get("hover", 0) + 1
        continue
      if hv[0] < need and fallback is not None:
        continue
      qr, ok = self.ik(np.r_[tcp, sh["gz"] + 0.014 + self.Z(tcp)], psi, seed=hv[1])
      if not ok or not (self.self_clear(qr) and self.self_clear(hv[1])):
        continue
      if check:   # held item attached: hover and release poses must be clear of walls and items
        if not all(self.pl.check_arm_config(scene, qq, ignore_obstacles=("table",))["valid"] for qq in (hv[1], qr)):
          why["check"] = why.get("check", 0) + 1
          continue
      if hv[0] < need:
        fallback = (qr, (c, psi, tcp, hv))
        continue
      self.q_release = qr
      return c, psi, tcp, hv
    if fallback is not None:
      self.q_release = fallback[0]
      return fallback[1]
    self.note("place fail", len(cands), why)
    raise Retry("no place pose")

  def contact_q(self, r):
    # Moving-jaw angle at which the jaws span 2r (jaw geometry fit).
    return float(np.interp(2 * r, [0.015, 0.027, 0.039, 0.061], [0.0, 0.15, 0.30, 0.60]))

  def close_on(self, q_exp, rate):
    """Force-limited close: moderately fast to just outside the expected contact, then slow; stop
    at the first stall of the moving jaw and return the measured contact angle."""
    g, slow, k = float(self.cmd[5]), 0, 0
    while g > q_exp - 0.07:     # no stall by then: nothing between the jaws (and the jaws must not meet)
      r = (0.5 if rate < 0.2 else 0.8) if g > q_exp + 0.06 else rate
      g -= r * self.dt
      k += 1
      yield np.r_[self.cmd[:5], g]
      v = float(self.obs["qvel"][5])
      slow = slow + 1 if (k > 6 and v > -0.3 * r) else 0
      if slow >= 2:
        return float(self.obs["qpos"][5]) - self.gbias
    return None

  def pick_place(self, name):
    it = ITEMS[name]
    c, quat = self.est(name)
    sh = self.shape(name, quat)
    if name == "egg_cup" and sh.get("lying"):
      raise Retry("egg cup on its side")   # it must stand upright in the bin; the gripper cannot right it
    bin_c, _ = self.est(it["bin"], n_max=60)
    self.place_plan(name, bin_c, sh)                 # lookahead: never pick what cannot be placed
    psi, tcp, (hz, qh) = self.grasp_plan(name, c, sh)
    q_exp = self.contact_q(sh["r"])
    open_q = min(GRIP_OPEN, q_exp + self.open_margin(c))
    yield from self.transit(qh, self.scene(skip=(name,)), grip=open_q)
    # Re-observe from the hover: pushes and perception lag are absorbed here.
    t0 = self.obs["time"]
    yield from self.hold(0.4)
    c, quat = self.est(name, since=t0 + 0.15)
    if c[0] < RETURNS_X or c[2] < -0.05:
      raise Retry("item gone")
    sh2 = self.shape(name, quat)
    self.note("seen", name, [round(float(v), 4) for v in c], round(tilt_deg(quat)), [round(float(v), 4) for v in self.fk()])
    if len(sh2["yaws"]) != len(sh["yaws"]) or len(sh2["yaws"]) == 2:
      psi, tcp, (hz, qh) = self.grasp_plan(name, c, sh2)
      yield from self.transit(qh, self.scene(skip=(name,)))
    else:
      tcp_new = c[:2] + rz(psi)[:2, 1] * (sh2["r"] + STANDOFF - FIXED_JAW)
      if np.linalg.norm(tcp_new - tcp) > 0.003:   # item moved or estimate improved: re-centre the hover first
        qh2, ok = self.ik(np.r_[tcp_new, hz + self.Z(tcp_new)], psi)
        if not ok:
          raise Retry("hover moved")
        yield from self.goto(qh2, vmax=0.8, tmin=0.15)
      tcp = tcp_new
    sh = sh2
    yield from self.stroke(np.r_[tcp, sh["gz"] + self.Z(tcp)], psi, vmax=1.1)
    yield from self.hold(0.06)
    qc = yield from self.close_on(q_exp, rate=0.15 if name == "egg_cup" else 0.35)
    self.note("contact", name, None if qc is None else round(qc, 3), round(q_exp, 3))
    if qc is None or qc < q_exp - 0.045 or qc > q_exp + 0.06:
      yield from self.grip_to(open_q)
      yield from self.stroke(np.r_[tcp, hz + self.Z(tcp)], psi)
      raise Retry("bad contact")
    yield from self.grip_to(qc - it["squeeze"], tmin=0.2)
    yield from self.hold(0.1)
    gap0 = self.gap()
    q_grasp = self.q()
    pose6d = [c[0], c[1], c[2] + self.Z(c), sh.get("axis_yaw", yaw_of(quat)), 0.0, 0.0]
    yield from self.stroke(np.r_[tcp, hz + self.Z(tcp)], psi, vmax=1.1)
    t1 = self.obs["time"]
    yield from self.hold(0.3)
    cz = self.est(name, since=t1 + 0.05, extend=False)[0]
    lifted = cz[2] - c[2] > 0.5 * (hz - sh["gz"]) and self.gap() > 0.4 * gap0
    self.note("lift", name, round(float(cz[2]), 4), round(gap0, 4), round(self.gap(), 4))
    if not lifted:
      yield from self.grip_to(open_q)
      raise Retry("not lifted")
    # Carry with the item attached to the planner's arm model.
    bin_c, _ = self.est(it["bin"], n_max=60)
    self.pl.attach_object_at_world_pose(self.held_object(name, sh), q_grasp, pose6d)
    try:
      spot, psi_p, tcp_p, (hz_p, qh_p) = self.place_plan(name, bin_c, sh, check=True)
    except Retry:
      self.pl.detach_object()
      yield from self.stroke(np.r_[tcp, sh["gz"] + 0.004 + self.Z(tcp)], psi)   # put it back down
      yield from self.grip_to(min(GRIP_OPEN, qc + 0.12))
      yield from self.stroke(np.r_[tcp, hz + self.Z(tcp)], psi)
      raise
    try:
      # Items standing in the bins are padded upwards: a loaded arm sags below its plan.
      yield from self.transit(qh_p, self.scene(skip=(name,), sag=0.008), vmax=1.4 if name == "egg_cup" else 2.0)
    finally:
      self.pl.detach_object()
    if self.gap() < 0.4 * gap0:
      raise Retry("dropped in transit")
    try:
      yield from self.stroke(np.r_[tcp_p, sh["gz"] + 0.014 + self.Z(tcp_p)], psi_p, vmax=1.0)
    except Retry:
      yield from self.goto(self.q_release, vmax=0.8)
    yield from self.hold(0.06)
    yield from self.grip_to(min(qc + 0.12, GRIP_OPEN), tmin=0.12)
    yield from self.stroke(np.r_[tcp_p, hz_p + self.Z(tcp_p)], psi_p, vmax=1.6)   # clear before a knock lands

  def in_bin(self, name, since=None):
    it = ITEMS[name]
    c, quat = self.est(name, since=since)
    b, _ = self.est(it["bin"], n_max=60)
    rel = c - b
    ok = abs(rel[0]) < BIN_INNER[0] - 0.007 and abs(rel[1]) < BIN_INNER[1] - 0.007
    ok = ok and rel[2] < 0.006 + it["h"] + 0.016
    if name == "egg_cup":
      ok = ok and tilt_deg(quat) < 15.0
    return bool(ok)

  def verify(self, name):
    t0 = self.obs["time"]
    yield from self.hold(0.9 if name == "egg_cup" else 0.35)
    return self.in_bin(name, since=t0 + 0.3)

  def recover(self):
    """Open, rise straight up, and look again."""
    p = self.fk()
    yield from self.grip_to(min(GRIP_OPEN, self.cmd[5] + 0.12), tmin=0.2)
    try:
      yield from self.stroke([p[0], p[1], max(p[2], HOVERS[1] + self.Z(p))], self.current_psi(), vmax=0.6)
    except Retry:
      hv = self.hover(p[:2], self.current_psi())
      if hv is not None:
        yield from self.goto(hv[1], vmax=0.6)
    yield from self.hold(0.3)