File size: 49,800 Bytes
a8f90d0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
"""CL-2 capping cell controller (reference).

Staged loop, every stage closed on a measurement:
- height reference from a guarded touch on the station base plate (load cell);
- camera check against the fixture datum dots, then pens, caps and the standing pen's neck from the overhead RGB-D
  image;
- cap pick with a tray-floor touch and a quarter-turn centring regrasp, cap-in-hand offset from both finger readings;
- guarded put-on over the neck the camera sees, spiral search when the cap lands high, lateral give while the mouth
  chamfer leads it on;
- press with the closed fingertips along the pen axis under load-cell feedback until the click, then on through the
  ring travel, seat confirmed by two light touches, ceiling well under the nib limit;
- regrip of the seated cap with sideways compliance, lift-out, rack insertion with a tracking-error guard;
- gripper echo and camera stamp checks for the two faults.
"""
import math
import os
import sys

import mujoco
import numpy as np

# ---- cell data (CELL_SHEET.md, CAP_FIT_SPEC.md) ----
BARREL_R, SHOULDER_Z, NIB_END = 0.0070, 0.110, 0.131
NEST_FLOOR, NEST_TOP, NEST_PLATE = 0.005, 0.040, 0.003      # puck floor and top, station plate top
PUCK_PITCH, PUCK_N = 0.040, 3
RACK_FLOOR, RACK_TOP, RACK_PITCH, RACK_HOLES = 0.004, 0.030, 0.036, 4
FEEDER_FLOOR = 0.004
CAP_LEN = 0.025
INK_HUE = {"red": 3.0, "yellow": 50.0, "green": 132.0, "blue": 224.0}
DATUM_HUE = 307.0
DATUMS = {
    "puck_station": ((0.015, 0.064), (-0.015, -0.064)),
    "cap_feeder": ((0.081, 0.061), (-0.081, -0.061)),
    "ship_rack": ((0.0, 0.084), (0.0, -0.084)),
}
OPEN_MARKER, HOLD_MARKER = 0.0165, 0.0015
OPEN_CAP, HOLD_CAP = 0.0150, 0.0005      # firm hold: the cap must not slide in the pads at the peak seating force
PRESS_CEILING_N = 11.5          # stop short of the 12 N nib limit; stiff caps peak at up to 10.0 N
E_RING = 0.0045                 # cap mouth above the shoulder when it rests on the detent ring
E_SEAT_C = 0.0006               # ... and when seated
PAD_TIP = 0.0097                # closed fingertip faces below the grasp point
CLOSED_TIPS = -0.001            # gripper command that closes the fingertips together
CARRY_Z = 0.185
TRAVEL_TAIL_Z = 0.160          # lowest tail height when carrying a capped marker over the rack
DEBUG = bool(os.environ.get("CL2_DEBUG"))


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


class Done(Exception):
  pass


class Retry(Exception):
  pass


class Lost(Retry):
  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 quat_yaw(q):
  return math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] ** 2 + q[3] ** 2))


def minjerk(s):
  s = min(max(s, 0.0), 1.0)
  return s * s * s * (10 - 15 * s + 6 * s * s)


def rot_down(yaw):
  """Tool pointing straight down, fingers closing along the horizontal direction at `yaw`."""
  z = np.array([0.0, 0.0, -1.0]); y = np.array([math.cos(yaw), math.sin(yaw), 0.0]); x = np.cross(y, z)
  return np.stack([x, y, z], 1)


def tilt_to(u):
  """Smallest rotation taking world +z to the unit vector u."""
  z = np.array([0.0, 0.0, 1.0]); v = np.cross(z, u); c = float(z @ u); sv = float(np.linalg.norm(v))
  if sv < 1e-9:
    return np.eye(3)
  k = v / sv; K = np.array([[0, -k[2], k[1]], [k[2], 0, -k[0]], [-k[1], k[0], 0]])
  return np.eye(3) + sv * K + (1 - c) * K @ K


def rot_along(axis):
  """Tool approaching along -axis (a reclined marker's tail-to-tip direction), fingers closing horizontally."""
  z = -np.asarray(axis, float) / np.linalg.norm(axis)
  y = np.cross(np.array([0.0, 0.0, 1.0]), z); y /= np.linalg.norm(y)
  x = np.cross(y, z)
  return np.stack([x, y, z], 1)


class Arm:
  def __init__(self, xml):
    self.m = mujoco.MjModel.from_xml_path(xml)
    self.d = mujoco.MjData(self.m)
    self.jid = [self.m.joint(f"robot/joint{i}").id for i in range(1, 7)]
    self.qadr = np.array([self.m.jnt_qposadr[j] for j in self.jid])
    self.vadr = np.array([self.m.jnt_dofadr[j] for j in self.jid])
    self.lo = np.array([self.m.jnt_range[j, 0] for j in self.jid]) + 0.03
    self.hi = np.array([self.m.jnt_range[j, 1] for j in self.jid]) - 0.03
    self.sid = self.m.site("robot/grasp_site").id
    self.jp = np.zeros((3, self.m.nv)); self.jr = np.zeros((3, self.m.nv))
    self.kp = np.array([self.m.actuator_gainprm[self.m.actuator(f"robot/joint{i}").id, 0] for i in range(1, 7)])
    # how far the fingertips reach past the grasp point along the approach axis
    self.fk(np.array([0.0, 1.6, 1.5, -1.45, 0.0, 0.0]))
    p, r = self.d.site_xpos[self.sid].copy(), self.d.site_xmat[self.sid].reshape(3, 3).copy()
    ext = 0.0
    for g in range(self.m.ngeom):
      bn = self.m.body(self.m.geom_bodyid[g]).name or ""
      if bn in ("robot/left_finger", "robot/right_finger", "robot/left_pad", "robot/right_pad") and self.m.geom_contype[g]:
        gp = self.d.geom_xpos[g]; gr = self.d.geom_xmat[g].reshape(3, 3); sz = self.m.geom_size[g]
        for sx in (-1, 1):
          for sy in (-1, 1):
            for szz in (-1, 1):
              c = gp + gr @ (np.array([sx, sy, szz]) * sz)
              ext = max(ext, float((c - p) @ r[:, 2]))
    self.tip_ext = ext

  def fk(self, q):
    self.d.qpos[self.qadr] = q
    mujoco.mj_kinematics(self.m, self.d)
    mujoco.mj_comPos(self.m, self.d)
    return self.d.site_xpos[self.sid].copy(), self.d.site_xmat[self.sid].reshape(3, 3).copy()

  def jac(self, q):
    self.fk(q)
    mujoco.mj_jacSite(self.m, self.d, self.jp, self.jr, self.sid)
    return np.vstack([self.jp[:, self.vadr], self.jr[:, self.vadr]])

  def ik(self, pos, rot, q0, iters=80, tol=2e-4):
    q = np.clip(np.array(q0, float), self.lo, self.hi)
    err = 1.0
    for _ in range(iters):
      p, rc = self.fk(q)
      ep = pos - p
      qe = np.zeros(4); mujoco.mju_mat2Quat(qe, (rot @ rc.T).flatten())
      er = np.zeros(3); mujoco.mju_quat2Vel(er, qe, 1.0)
      err = max(float(np.linalg.norm(ep)), 0.1 * float(np.linalg.norm(er)))
      if err < tol:
        return q, True
      mujoco.mj_jacSite(self.m, self.d, self.jp, self.jr, self.sid)
      j = np.vstack([self.jp[:, self.vadr], self.jr[:, self.vadr]])
      e = np.concatenate([ep, er])
      dq = j.T @ np.linalg.solve(j @ j.T + 1e-5 * np.eye(6), e)
      n = float(np.linalg.norm(dq))
      if n > 0.3:
        dq *= 0.3 / n
      q = np.clip(q + dq, self.lo, self.hi)
    return q, err < 5 * tol


class Controller:
  def __init__(self, model_info):
    self.info = model_info
    self.dt = float(model_info["control_dt_s"])
    self.arm = Arm(model_info["scene_xml"])
    names = model_info["joint_names"]
    self.qi = [names.index(f"robot/joint{i}") for i in range(1, 7)]
    self.fi = names.index("robot/left_finger")
    self.fri = names.index("robot/right_finger")
    cam = next(c for c in model_info["cameras"] if c["name"] == "overhead")
    self.W, self.H = cam["width"], cam["height"]
    m = self.arm.m
    cid = m.camera("overhead").id
    self.cam_pos = m.cam_pos[cid].copy()
    r = np.zeros(9); mujoco.mju_quat2Mat(r, m.cam_quat[cid]); self.cam_rot = r.reshape(3, 3)
    f = (self.H / 2) / math.tan(math.radians(cam["fovy_deg"]) / 2)
    u, v = np.meshgrid(np.arange(self.W) + 0.5, np.arange(self.H) + 0.5)
    self.ray_c = np.stack([(u - self.W / 2) / f, -(v - self.H / 2) / f, -np.ones_like(u)], -1)
    self.ray_w = self.ray_c @ self.cam_rot.T

  # ------------------------------------------------------------------ protocol
  def reset(self, obs):
    self.obs = obs
    self.q_cmd = np.array(obs["qpos"])[self.qi].copy()
    self.g_cmd = float(obs["ctrl"][6])
    self.last_sent = np.array(obs["ctrl"], float).copy()
    self.gen = self.main()
    self.stamp_prev = obs.get("camera_stamp")
    self.stamp_changes = 0
    self.cam_shift = np.zeros(2)
    self.z_off = 0.0
    self.integ = np.zeros(6)
    self.fix = {}
    self.fix_n = 0
    self.tip_ext = self.arm.tip_ext
    self.frame_id = 0
    self.load_bias = 0.0
    self.finger_bias = 0.0
    self.rfinger_bias = 0.0
    self.cap_off_t = np.zeros(2)
    self.xy_seat = None
    self.tail_off = np.zeros(2)

  def act(self, obs):
    self.obs = obs
    try:
      self.check_faults(obs)
      self.track_fixtures(obs)
      next(self.gen)
    except Abort as a:
      return {"status": "abort", "fault": a.fault}
    except (Done, StopIteration):
      return {"status": "done"}
    out = np.concatenate([self.q_cmd + self.integ, [self.g_cmd]])
    lo, hi = np.array(self.info["ctrl_low"]), np.array(self.info["ctrl_high"])
    out = np.clip(out, lo, hi)
    self.last_sent = out.copy()
    return out

  def check_faults(self, obs):
    if abs(float(obs["ctrl"][6]) - float(self.last_sent[6])) > 1e-6:
      raise Abort("dead_gripper")
    st = obs.get("camera_stamp")
    if st is not None:
      if self.stamp_prev is not None and st != self.stamp_prev:
        self.stamp_changes += 1
        self.frame_id += 1
      else:
        self.stamp_changes = 0
      self.stamp_prev = st
      if self.stamp_changes >= 3 or obs["time"] - st > 1.6:
        raise Abort("perception_freeze")

  def track_fixtures(self, obs):
    st = obs.get("objects_stamp")
    if st is None or st == getattr(self, "_fix_stamp", None):
      return
    self._fix_stamp = st
    self.fix_n += 1
    a = 1.0 / min(self.fix_n, 12)
    for k, p in obs["objects"].items():
      v = np.array([p[0], p[1], quat_yaw(p[3:7])])
      if k not in self.fix:
        self.fix[k] = v
      else:
        d = v - self.fix[k]
        d[2] = (d[2] + math.pi) % (2 * math.pi) - math.pi
        self.fix[k] = self.fix[k] + a * d

  # ------------------------------------------------------------------ helpers
  def log(self, *a):
    if DEBUG:
      print(f"[{self.obs['time']:6.2f}]", *a, file=sys.stderr, flush=True)

  def q_meas(self):
    return np.array(self.obs["qpos"])[self.qi]

  def finger(self):
    return float(self.obs["qpos"][self.fi]) - self.finger_bias

  def finger_r(self):
    return float(self.obs["qpos"][self.fri]) - self.rfinger_bias

  def mean_centre(self, n=8):
    """Where the pads hold a part along their closing line (tool y), from both finger readings: the right finger
    follows the driven left one through a soft coupling and lags it under load."""
    acc = 0.0
    for _ in range(n):
      yield
      acc += 0.5 * (self.finger() - self.finger_r())
    return acc / n

  def mean_finger(self, n=8):
    acc = 0.0
    for _ in range(n):
      yield
      acc += self.finger()
    return acc / n

  def tool(self):
    return self.arm.fk(self.q_meas())

  def load(self):
    return float(self.obs["io"]["nest_load_n"]) - self.load_bias

  def mean_load(self, n):
    acc = 0.0
    for _ in range(n):
      yield
      acc += self.load()
    return acc / n

  def wz(self, h):
    """Commanded tool height for world height h (height reference from the touch-off)."""
    return h + self.z_off

  def fix_frame(self, name):
    x, y, yaw = self.fix[name]
    return np.array([x, y, 0.0]), rz(yaw)

  def solve(self, pos, rot, seed=None):
    seeds = [self.q_cmd] if seed is None else [seed, self.q_cmd]
    az = math.atan2(pos[1], pos[0])
    seeds += [np.array([az, 1.6, 1.5, -1.4, 0.0, 0.0]), np.array([az, 1.4, 1.0, -0.7, 0.0, 0.0])]
    best = None
    for s in seeds:
      q, ok = self.arm.ik(pos, rot, s)
      if ok:
        return q
      if best is None:
        best = q
    return best

  def best_yaw(self, pos, yaw):
    """Of the two equivalent closing directions, the one that keeps the wrist roll nearer the middle."""
    out = None
    for y in (yaw, yaw + math.pi):
      q = self.solve(pos, rot_down(y))
      c = abs(q[5]) + 0.3 * abs(q[4])
      p, _ = self.arm.fk(q)
      c += 100.0 * float(np.linalg.norm(p - pos))
      if out is None or c < out[0]:
        out = (c, y, q)
    return out[1], out[2]

  def hold(self, t, grip=None, integ=False):
    n = max(1, round(t / self.dt))
    g0 = self.g_cmd
    for i in range(n):
      if grip is not None:
        self.g_cmd = g0 + (grip - g0) * (i + 1) / n
      if integ:
        self.integrate()
      yield

  def integrate(self):
    e = self.q_cmd - self.q_meas()
    self.integ = np.clip(self.integ + 0.06 * e, -0.06, 0.06)

  def move_q(self, q_goal, t=None, vmax=1.6):
    q0 = self.q_cmd.copy()
    dq = q_goal - q0
    if t is None:
      t = max(0.35, 1.9 * float(np.max(np.abs(dq))) / vmax)
    n = max(1, round(t / self.dt))
    i0 = self.integ.copy()
    for i in range(n):
      s = minjerk((i + 1) / n)
      self.q_cmd = q0 + s * dq
      self.integ = i0 * (1 - s)
      yield

  def move_pose(self, pos, rot, t=None, vmax=1.6):
    yield from self.move_q(self.solve(np.asarray(pos, float), rot), t, vmax)

  def line(self, pos, rot, speed=0.10, tmin=0.3):
    """Straight tool path from the commanded pose to pos (orientation rot at the end)."""
    p0, r0 = self.arm.fk(self.q_cmd)
    pos = np.asarray(pos, float)
    t = max(tmin, 1.9 * float(np.linalg.norm(pos - p0)) / speed)
    n = max(1, round(t / self.dt))
    q = self.q_cmd.copy()
    q0 = np.zeros(4); mujoco.mju_mat2Quat(q0, r0.flatten())
    q1 = np.zeros(4); mujoco.mju_mat2Quat(q1, np.asarray(rot, float).flatten())
    dv = np.zeros(3); mujoco.mju_subQuat(dv, q1, q0)          # rotation from r0 to rot, turned in step with the path
    for i in range(n):
      s = minjerk((i + 1) / n)
      qs = q0.copy(); mujoco.mju_quatIntegrate(qs, dv, s)
      rs = np.zeros(9); mujoco.mju_quat2Mat(rs, qs)
      q, _ = self.arm.ik(p0 + s * (pos - p0), rs.reshape(3, 3), q, iters=12)
      self.q_cmd = q
      yield

  # ------------------------------------------------------------------ vision
  def fresh_frame(self, n=1, max_wait=2.5):
    """Waits for n new overhead frames taken after now."""
    t0 = self.obs["time"]
    got = 0
    last = self.obs.get("camera_stamp")
    for _ in range(round(max_wait / self.dt)):
      st = self.obs.get("camera_stamp")
      if st is not None and st != last and st >= t0 - 1e-9:
        got += 1
        last = st
        if got >= n:
          return
      yield

  def cloud(self):
    img = self.obs["images"]["overhead"].astype(np.float32)
    dep = self.obs["depth"]["overhead"].astype(np.float64)
    pts = self.cam_pos + self.ray_w * dep[..., None]
    pts[..., :2] += self.cam_shift
    mx = img.max(-1); mn = img.min(-1)
    sat = (mx - mn) / np.maximum(mx, 1.0)
    r, g, b = img[..., 0], img[..., 1], img[..., 2]
    hue = np.degrees(np.arctan2(math.sqrt(3.0) * (g - b), 2 * r - g - b)) % 360.0
    return pts, hue, sat, mx / 255.0, dep > 0.05

  @staticmethod
  def hue_dist(h, ref):
    return np.abs((h - ref + 180.0) % 360.0 - 180.0)

  def classify(self, hue):
    best, bd = None, 1e9
    for k, h in INK_HUE.items():
      d = float(self.hue_dist(np.array(hue), h))
      if d < bd:
        best, bd = k, d
    return best

  @staticmethod
  def label(mask):
    """Connected components (8-neighbour) by label propagation."""
    lab = np.where(mask, np.arange(1, mask.size + 1).reshape(mask.shape), 0)
    for _ in range(400):
      p = np.pad(lab, 1)
      nb = np.maximum.reduce([p[1:-1, 1:-1], p[:-2, 1:-1], p[2:, 1:-1], p[1:-1, :-2], p[1:-1, 2:],
                              p[:-2, :-2], p[:-2, 2:], p[2:, :-2], p[2:, 2:]])
      new = np.where(mask, nb, 0)
      if np.array_equal(new, lab):
        break
      lab = new
    return lab

  def calibrate_camera(self):
    """Shift of the back-projected image against the tracked fixtures, from the magenta datum dots."""
    self.cam_shift = np.zeros(2)
    pts, hue, sat, val, ok = self.cloud()
    mask = ok & (sat > 0.4) & (self.hue_dist(hue, DATUM_HUE) < 28) & (pts[..., 2] < 0.03 + abs(self.z_off) + 0.03)
    lab = self.label(mask)
    cents = []
    for l in np.unique(lab[lab > 0]):
      sel = lab == l
      if 3 <= int(sel.sum()) <= 60:
        cents.append(pts[sel][:, :2].mean(0))
    diffs = []
    for name, dots in DATUMS.items():
      if name not in self.fix:
        continue
      o, r = self.fix_frame(name)
      for dx, dy in dots:
        pw = (o + r @ np.array([dx, dy, 0.0]))[:2]
        if cents:
          dd = [float(np.linalg.norm(c - pw)) for c in cents]
          i = int(np.argmin(dd))
          if dd[i] < 0.025:
            diffs.append(pw - cents[i])
    if len(diffs) >= 3:
      self.cam_shift = np.median(np.array(diffs), axis=0)
    return len(diffs)

  def puck(self, j):
    """World position of puck j's bore centre at the bench (from the tracked station pose)."""
    o, r = self.fix_frame("puck_station")
    return o + r @ np.array([0.0, (j - (PUCK_N - 1) / 2) * PUCK_PITCH, 0.0])

  def find_pens(self):
    """Ink of the pen standing in each puck (None for an empty puck), from the collar and barrel seen from above."""
    pts, hue, sat, val, ok = self.cloud()
    out = []
    for j in range(PUCK_N):
      c = self.puck(j)
      d = np.hypot(pts[..., 0] - c[0], pts[..., 1] - c[1])
      sel = ok & (d < 0.013) & (pts[..., 2] > NEST_FLOOR + 0.045) & (pts[..., 2] < NEST_FLOOR + 0.112) & (sat > 0.5) & (val > 0.15) \
          & (self.hue_dist(hue, DATUM_HUE) > 30)
      if int(sel.sum()) < 8:
        out.append(None)
        continue
      hs = hue[sel]
      hmed = float(np.degrees(np.arctan2(np.sin(np.radians(hs)).mean(), np.cos(np.radians(hs)).mean())) % 360.0)
      out.append(self.classify(hmed))
    return out

  def find_caps(self):
    pts, hue, sat, val, ok = self.cloud()
    o, r = self.fix_frame("cap_feeder")
    loc = (pts - o) @ r
    zt = FEEDER_FLOOR + CAP_LEN
    region = ok & (np.abs(loc[..., 0]) < 0.066) & (np.abs(loc[..., 1]) < 0.066) & (loc[..., 2] > zt - 0.005) & (loc[..., 2] < zt + 0.007)
    base = region & (sat > 0.5) & (val > 0.15)
    out = []
    for ink, h in INK_HUE.items():
      lab = self.label(base & (self.hue_dist(hue, h) < 30))
      for l in np.unique(lab[lab > 0]):
        sel = lab == l
        if int(sel.sum()) < 8:
          continue
        c = loc[sel].mean(0)
        out.append({"ink": ink, "loc": c[:2], "xy": (o + r @ np.array([c[0], c[1], 0.0]))[:2], "n": int(sel.sum())})
    return out

  def find_neck(self, j):
    """Top of the pen standing in puck j: xy of its white neck and nib, from above."""
    pts, hue, sat, val, ok = self.cloud()
    o = self.puck(j)
    d = np.hypot(pts[..., 0] - o[0], pts[..., 1] - o[1])
    sel = ok & (d < 0.016) & (pts[..., 2] > NEST_FLOOR + SHOULDER_Z + 0.004) & (pts[..., 2] < NEST_FLOOR + NIB_END + 0.012)
    if int(sel.sum()) < 4:
      return None
    return pts[sel][:, :2].mean(0)

  # ------------------------------------------------------------------ job
  def main(self):
    # the gripper stands open and still at its command: the difference is the finger reading's offset
    g = self.g_cmd
    acc = np.zeros(2)
    for _ in range(10):
      yield
      acc += [float(self.obs["qpos"][self.fi]), float(self.obs["qpos"][self.fri])]
    self.finger_bias, self.rfinger_bias = acc / 10 - g
    yield from self.touch_off()
    yield from self.look()
    self.calibrate_camera()
    pens = self.find_pens()
    self.log('pens', pens, 'shift', self.cam_shift.round(4))
    hole = 0
    # one pen at a time; a pen that cannot be finished is left and the next one is done
    for j in range(PUCK_N):
      ink = pens[j]
      if ink is None or hole >= RACK_HOLES:
        continue
      for attempt in range(2):
        self.pressed = False
        try:
          yield from self.look()
          caps = [c for c in self.find_caps() if c["ink"] == ink]
          self.log('pen', j, ink, 'caps', [(c['ink'], c['loc'].round(3).tolist(), c['n']) for c in self.find_caps()])
          if not caps:
            break
          yield from self.pick_cap(caps, j)
          yield from self.press_cap(j)
          ok = yield from self.rack(hole, j)
          if ok == "left":
            # the cap came away without the pen: it was not home. Put it on again and press it home
            self.log('pen stayed in the puck: capping again')
            oc = yield from self.mean_centre(6)
            self.cap_off_t = np.array([0.0, oc])
            yield from self.press_cap(j)
            ok = yield from self.rack(hole, j)
          if ok is not True:
            raise Retry("cap did not take")
          hole += 1
          break
        except Retry as e:
          self.log('RETRY', j, e)
          yield from self.recover()
          if self.pressed:
            break                                   # a cap is on (or jammed on) this pen: leave it, go on
    yield from self.park()
    raise Done()

  def park(self):
    p, _ = self.arm.fk(self.q_cmd)
    yield from self.move_pose(np.array([0.20, 0.0, self.wz(0.17)]), rot_down(0.0))
    yield from self.hold(0.2)

  def recover(self):
    """Lets go of whatever is held, clear of the fixtures, and backs up."""
    p, r = self.arm.fk(self.q_cmd)
    yield from self.line(p + np.array([0.0, 0.0, max(0.0, self.wz(CARRY_Z) - p[2])]), r, speed=0.12)
    yield from self.hold(0.2, grip=OPEN_MARKER)

  def look(self):
    """Arm out of the camera's view of the fixtures, then a fresh frame."""
    p, r = self.arm.fk(self.q_cmd)
    if p[2] < self.wz(0.21) and float(np.hypot(p[0], p[1])) > 0.18:
      yield from self.line(np.array([p[0], p[1], self.wz(0.21)]), r, speed=0.15)   # up clear of the standing pens first
    yield from self.move_q(np.array([0.0, 0.55, 0.50, -1.05, 0.0, 0.0]))
    yield from self.fresh_frame(1)

  def view_pose(self, name):
    return
    yield

  def touch_off(self):
    """Guarded touch on the nest base plate: sets the height reference for the whole job."""
    for _ in range(40):
      if "puck_station" in self.fix:
        break
      yield
    o, r = self.fix_frame("puck_station")
    # the plate end farther from the shipping rack (the loose finished rack stands behind it)
    rk = self.fix["ship_rack"][:2] if "ship_rack" in self.fix else np.array([0.17, -0.24])
    best = None
    for sy in (-1.0, 1.0):                    # the plate ends, clear of the pucks
      p = o + r @ np.array([0.0, sy * 0.090, 0.0])
      dr = float(np.linalg.norm(p[:2] - rk))
      if best is None or dr > best[0]:
        best = (dr, p, self.fix["puck_station"][2])
    _, p, a = best
    # fingers close across the plate, pads along it; of the two such wrist turns, the one that keeps the wrist
    # camera housing out over the plate end, away from the pens standing in the pucks
    gid = self.arm.m.geom("robot/d405").id
    far = None
    for a2 in (a, a + math.pi):
      q2 = self.solve(np.array([p[0], p[1], 0.02]), rot_down(a2))
      self.arm.fk(q2)
      gp = self.arm.d.geom_xpos[gid][:2]
      dc = min(float(np.linalg.norm(gp - o[:2])), float(np.linalg.norm(gp - rk)) - 0.05)
      if far is None or dc > far[0]:
        far = (dc, a2)
    a = far[1]
    rot = rot_down(a)
    top = np.array([p[0], p[1], 0.075])
    yield from self.move_pose(np.array([p[0], p[1], 0.20]), rot)      # from above: pens stand 0.14 m tall
    yield from self.line(top, rot, speed=0.12)
    yield from self.hold(0.15, grip=0.003)
    self.load_bias = 0.0
    self.load_bias = yield from self.mean_load(8)
    z = top[2]
    q = self.q_cmd.copy()
    hit = None
    ld = [0.0, 0.0, 0.0]
    while z > -0.045:
      z -= 0.0012 if z > 0.035 else 0.0008
      q, _ = self.arm.ik(np.array([p[0], p[1], z]), rot, q, iters=10)
      self.q_cmd = q
      yield
      ld = ld[1:] + [self.load()]
      if min(ld) > 0.5 and sum(ld) > 3.0:      # three readings in a row: one noisy sample is not a touch
        hit = True
        break
    for _ in range(8):
      yield
    zs = []
    for _ in range(6):
      zs.append(self.tool()[0][2])
      yield
    # tool height that puts the fingertips on the plate, versus the nominal one
    self.z_off = (float(np.mean(zs)) - self.tip_ext) - NEST_PLATE if hit else 0.0
    self.log('touch_off raw', round(self.z_off, 4), [round(x, 4) for x in zs])
    if abs(self.z_off) > 0.025:               # far more than base height and joint-reading errors: not the plate
      self.z_off = 0.0
    self.log('touch_off hit', hit, 'z_off', round(self.z_off, 4), 'tip_ext', round(self.tip_ext, 4))
    pc, _ = self.arm.fk(self.q_cmd)
    yield from self.line(np.array([p[0], p[1], pc[2] + 0.06]), rot, speed=0.15)
    yield from self.hold(0.05, grip=OPEN_MARKER)

  def pick_cap(self, caps, j):
    o, r = self.fix_frame("cap_feeder")
    allc = self.find_caps()
    cap = sorted(caps, key=lambda c: float(np.hypot(*c["loc"])))[0]
    # closing direction with the most room: away from neighbours and rims
    best = None
    for k in range(12):
      a = k * math.pi / 12
      dirv = np.array([math.cos(a), math.sin(a)])
      room = 1.0
      for c2 in allc:
        dv = c2["loc"] - cap["loc"]
        if float(np.linalg.norm(dv)) < 1e-4:
          continue
        along = abs(float(dv @ dirv)); across = abs(float(dv[0] * dirv[1] - dv[1] * dirv[0]))
        if across < 0.022:
          room = min(room, along - 0.028)
      for sgn in (-1, 1):
        for dv2 in (dirv, np.array([-dirv[1], dirv[0]])):   # both closing lines of the centring regrasp
          tip = cap["loc"] + sgn * 0.024 * dv2
          room = min(room, 0.064 - abs(tip[0]), 0.064 - abs(tip[1]))
      if best is None or room > best[0]:
        best = (room, a)
    yaw_w = best[1] + self.fix["cap_feeder"][2]
    xy = cap["xy"]
    top = np.array([xy[0], xy[1], self.wz(FEEDER_FLOOR + CAP_LEN + 0.030)])
    yaw_w, q = self.best_yaw(top, yaw_w)
    rot = rot_down(yaw_w)
    yield from self.hold(0.02, grip=OPEN_CAP)
    yield from self.move_q(q)
    yield from self.fresh_frame(1)       # arm over the feeder: the nest is in view
    self.neck = self.find_neck(j)
    self.log('neck', self.neck, 'puck', self.puck(j)[:2].round(4))
    if self.neck is None:
      raise Lost("no marker standing in the nest")
    yield from self.hold(0.1, integ=True)
    # the bench height under the tray can differ from the one found at the station by a few millimetres (base
    # tilt, joint-reading offsets): touch the tray floor with the open pads on either side of the cap, then take
    # the cap at a known height above its mouth (it stands on the floor)
    zg = self.wz(FEEDER_FLOOR + 0.0130)
    za = zg + 0.012
    yield from self.line(np.array([xy[0], xy[1], za]), rot, speed=0.10)
    yield from self.hold(0.25, integ=True)
    z = za
    qq = self.q_cmd.copy()
    hit = None
    lags = []
    while z > zg - 0.0090:
      z -= 0.0002
      qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
      self.q_cmd = qq
      yield
      lag = float(self.tool()[0][2]) - z        # how far the tool trails its command (steady while moving freely)
      lags.append(lag)
      # joint readings are noisy: judge on the mean of the last four readings against a long baseline
      if len(lags) > 24 and float(np.mean(lags[-4:])) - float(np.mean(lags[6:20])) > 0.0010:
        hit = float(np.mean([z + l for l in lags[-4:]]))
        break
    if hit is not None and abs(hit - self.wz(FEEDER_FLOOR + PAD_TIP)) > 0.006:
      self.log('tray touch implausible', round(hit - self.wz(FEEDER_FLOOR + PAD_TIP), 4))
      hit = None                              # a pad on a neighbouring cap or a noisy reading, not the floor
    if hit is not None:
      zg = hit + (0.0130 - PAD_TIP)          # the measured blocking height is the pad tip on the floor
    self.log('tray touch', None if hit is None else round(hit - self.wz(FEEDER_FLOOR + PAD_TIP), 4), 'steps', len(lags))
    yield from self.line(np.array([xy[0], xy[1], zg]), rot, speed=0.03, tmin=0.4)
    yield from self.hold(0.2, integ=True)
    yield from self.hold(0.3, grip=HOLD_CAP)
    yield from self.hold(0.04)
    fg = yield from self.mean_finger(6)
    o1 = yield from self.mean_centre(6)
    p1, r1 = self.tool()
    c_w = p1[:2] + o1 * r1[:2, 1]                 # cap centre (world) as the first grasp left it
    self.log('cap grasp finger', round(fg, 4), 'centre', round(o1, 4))
    if fg < 0.0040 or fg > 0.0116:
      yield from self.hold(0.15, grip=OPEN_CAP)
      yield from self.line(top, rot, speed=0.15)
      raise Retry("missed cap")
    # the pads centre the cap only along their closing line: let go, turn the wrist a quarter turn and close
    # again, so the cap ends up on the tool axis both ways (it is put on a 10 mm neck with < 1 mm clearance). The
    # fingers open wide for the turn: a pad edge dragged round the cap pushes it across the tray
    pm, _ = self.tool()
    self.log('cap grasp height', round(float(pm[2]), 4), 'commanded', round(zg, 4))
    yield from self.hold(0.25, grip=OPEN_CAP)
    yaw2, _ = self.best_yaw(np.array([xy[0], xy[1], zg]), yaw_w + math.pi / 2)
    rot = rot_down(yaw2)
    yield from self.line(np.array([xy[0], xy[1], zg]), rot, speed=0.05, tmin=0.8)
    yield from self.hold(0.1, integ=True)
    yield from self.hold(0.3, grip=HOLD_CAP)
    yield from self.hold(0.04)
    o2 = yield from self.mean_centre(6)
    p2, r2 = self.tool()
    self.cap_off_t = np.array([float((c_w - p2[:2]) @ r2[:2, 0]), o2])   # cap axis from the tool axis, tool x/y
    self.log('cap in hand (tool x, y)', (self.cap_off_t * 1000).round(2))
    self.cap_grasp_h = 0.0130           # tool point above the cap mouth
    yield from self.line(np.array([xy[0], xy[1], self.wz(CARRY_Z)]), rot, speed=0.16)
    self.holding = "cap"

  def press_cap(self, j):
    neck = self.neck
    o = self.puck(j)
    xy0 = np.array(neck if neck is not None else o[:2], float)
    if float(np.linalg.norm(xy0 - o[:2])) > 0.012:
      xy0 = o[:2].copy()
    cam_xy = xy0.copy()
    yaw = math.atan2(o[1], o[0]) + math.pi / 2
    z_sh = self.wz(NEST_FLOOR + SHOULDER_Z)                 # tool height that puts the grasp point at the shoulder
    z_top = z_sh + (NIB_END - SHOULDER_Z) + self.cap_grasp_h + 0.008
    top = np.array([xy0[0], xy0[1], z_top])
    yaw, q = self.best_yaw(top, yaw)
    rot = rot_down(yaw)
    # over the pen at carrying height first, then straight down: a joint-space move dips on the way and the cap
    # would clip the nib of the pen or its neighbour
    yield from self.move_pose(np.array([xy0[0], xy0[1], max(z_top + 0.02, self.wz(CARRY_Z))]), rot, vmax=1.8)
    yield from self.line(top, rot, speed=0.10)
    yield from self.hold(0.3, integ=True)
    # the cap axis sits off the tool axis by what the two grasps measured (tool x, y)
    offw = rot[:2, :2] @ self.cap_off_t
    if True:
      # bring the measured cap axis, not the commanded tool position, over the neck
      off = -offw.copy()
      qq = self.q_cmd.copy()
      for i in range(14):
        pm, _ = self.tool()
        off += 0.25 * (xy0 - (pm[:2] + offw))
        off = np.clip(off, -0.010, 0.010)
        qq, _ = self.arm.ik(np.array([xy0[0] + off[0], xy0[1] + off[1], z_top]), rot, qq, iters=10)
        self.q_cmd = qq
        yield
      xy0 = xy0 + off
      self.log('press xy', xy0.round(4), 'cam', cam_xy.round(4), 'off', off.round(4), 'cap in hand', (offw * 1000).round(2))
    pm, _ = self.tool()
    d0 = pm[:2] - self.arm.fk(self.q_cmd)[0][:2]           # measured minus commanded tool position, free
    base = yield from self.mean_load(4)
    base += self.load_bias
    h = self.cap_grasp_h
    z_engage = z_sh + h + 0.0080             # cap mouth 8 mm above the shoulder: the bore is on the neck
    z_ring = z_sh + h + 0.0050               # mouth on the detent ring
    seated = False
    spiral0 = 0
    for put in range(3):
      # 1) put the cap on the neck: guarded descent; a cap that lands on the nib or the neck top is lifted and the
      #    next point of a spiral around the measured axis is tried
      on = False
      xy = xy0.copy()
      for attempt in range(spiral0, spiral0 + 10):
        rad = 0.0 if attempt == 0 else 0.0010 + 0.0006 * attempt
        xy = xy0 + rad * np.array([math.cos(2.4 * attempt), math.sin(2.4 * attempt)])
        z = z_top
        qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, self.q_cmd.copy(), iters=20)
        self.q_cmd = qq
        yield from self.hold(0.15)
        high = False
        while z > z_engage:
          z -= 0.0008 if z > z_engage + 0.012 else 0.0003
          qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
          self.q_cmd = qq
          yield
          xy = self.yield_aside(xy, base, d0)
          if float(self.obs["io"]["nest_load_n"]) - base > 1.0:
            # within a few mm of the engage height the mouth is already round the neck (on the ring, or dragging on
            # a leaning neck); well above it the rim sits on the nib. Judge by the measured tool height: the
            # commanded one runs ahead of the arm
            pm, _ = self.tool()
            high = max(z, float(pm[2])) > z_engage + 0.003
            break
        if not high:
          # go on down to the detent ring: a bore that is round the neck slides down freely to it; a cap whose
          # mouth sits on the rounded neck end stops some 4 mm above it
          z_set = z_sh + h + E_RING + 0.0007
          while z > z_set:
            z -= 0.0003
            qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
            self.q_cmd = qq
            yield
            xy = self.yield_aside(xy, base, d0)
            if float(self.obs["io"]["nest_load_n"]) - base > 2.0:
              break
          yield from self.hold(0.1)
          pm, _ = self.tool()
          self.log('set check: tool above set height by', round(float(pm[2]) - z_set, 4), 'command', round(z - z_set, 4))
          if float(pm[2]) <= z_set + 0.0042:
            on = True
            # the cap axis is now the neck's (the mouth chamfer led it on): where the cap stands, in commanded
            # coordinates, including how far the lead-in pushed the arm aside
            xyc = xy + offw + ((pm[:2] - self.arm.fk(self.q_cmd)[0][:2]) - d0)
            break
          self.log('stopped on the neck end at', round(z, 4), 'set', round(z_set, 4))
          high = True
        if not on:
          self.log('landed high at', round(z, 4), 'engage', round(z_engage, 4))
        for _ in range(10):
          z += 0.0012
          qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
          self.q_cmd = qq
          yield
      if not on:
        raise Retry("cap would not go on the neck")
      # 2) the cap sits loosely on the detent ring: let go, the neck holds it upright
      yield from self.hold(0.1)
      yield from self.hold(0.25, grip=OPEN_CAP)
      self.holding = None
      self.pressed = True
      z_clear = z_sh + CAP_LEN + E_RING + PAD_TIP + 0.010
      yield from self.line(np.array([xy[0], xy[1], z_clear]), rot, speed=0.05)
      yield from self.hold(0.3, grip=CLOSED_TIPS)
      # the fingertips must be shut before they touch the cap: half-open pads ride on the cap top under the press
      # load and snap shut onto it when the load comes off
      for _ in range(3):
        fg = yield from self.mean_finger(5)
        if fg < 0.0015:
          break
        self.log('fingertips not shut', round(fg, 4))
        yield from self.line(np.array([xy[0], xy[1], z_clear + 0.008]), rot, speed=0.05)
        yield from self.hold(0.3, grip=OPEN_CAP)
        yield from self.hold(0.4, grip=CLOSED_TIPS)
      # 3) press on the cap top with the closed fingertips under load-cell feedback, along the pen's own axis: the
      #    pen leans a little in the bore, and a vertical push on a leaning cap top rolls the cap off the fingertips
      tail = o[:2].copy() + (xy0 + offw - cam_xy)
      z_neck = z_sh + 0.005
      lean = (xyc - tail) / (z_neck - (z_sh - SHOULDER_Z))
      if float(np.linalg.norm(lean)) > math.tan(math.radians(5.0)):
        lean = lean / float(np.linalg.norm(lean)) * math.tan(math.radians(5.0))
      axis = lambda zz: xyc + lean * (zz - z_neck)
      u = np.array([lean[0], lean[1], 1.0]); u /= np.linalg.norm(u)
      rot_ax = tilt_to(u) @ rot
      self.log('lean deg', round(math.degrees(math.atan(float(np.linalg.norm(lean)))), 2))
      zc = z_sh + CAP_LEN + E_RING + PAD_TIP + 0.006
      yield from self.line(np.array([*axis(zc), zc]), rot_ax, speed=0.04)
      # the seat is judged by where the cap top stands after the press against where the loose cap stood (the
      # ring travel is 3.9 mm), both found by the same light touch, not by the click alone
      z_probe = z_sh + CAP_LEN + E_RING + PAD_TIP + 0.0025
      self.press_corr = np.zeros(2)
      z_loose = yield from self.touch_top(axis, rot_ax, z_probe)
      seated = over = False
      z_now = z_loose
      depth = None
      for go in range(4):
        if z_loose is None:
          break
        # a cap that went most of the way is pressed again only to 8 N: if it was home it does not move (it is
        # held by the click), if it was not it runs on through the drag
        confirm = depth is not None and depth > 0.0012
        clicked, over, peak = yield from self.tip_press(axis, rot_ax, z_sh, ceiling=8.0 if confirm else PRESS_CEILING_N)
        z_now = yield from self.touch_top(axis, rot_ax, z_probe)
        prev, depth = depth, (None if z_now is None else z_loose - z_now)
        seated = depth is not None and (0.0020 < depth < 0.0090 or (confirm and depth > 0.0012 and abs(depth - prev) < 0.0004))
        self.log('press', go, 'clicked', clicked, 'peak', round(peak, 2), 'over', over, 'depth', None if depth is None else round(depth, 4), 'confirm', confirm)
        if seated or (over and not confirm and (depth is None or depth < 0.0012)):
          break
      if seated:
        break
      # jammed on the neck (the ceiling came without a click): take the cap back, lift it clear, try again
      self.log('cap jammed, taking it off again')
      zt_cap = z_now if z_now is not None else z_sh + CAP_LEN + E_RING + PAD_TIP
      z_g = zt_cap - PAD_TIP - CAP_LEN + h
      yield from self.line(np.array([*axis(z_clear), z_clear]), rot_ax, speed=0.05)
      yield from self.line(np.array([xy[0], xy[1], z_clear]), rot, speed=0.05)
      yield from self.hold(0.25, grip=OPEN_CAP)
      yield from self.line(np.array([xyc[0], xyc[1], z_g]), rot, speed=0.04)
      yield from self.hold(0.3, grip=HOLD_CAP)
      self.holding = "cap"
      oc = yield from self.mean_centre(6)
      self.cap_off_t = np.array([0.0, oc])
      offw = rot[:2, :2] @ self.cap_off_t
      xy0 = xyc - offw
      yield from self.line(np.array([xy0[0], xy0[1], z_top]), rot, speed=0.04)
      spiral0 += 3
    if not seated:
      yield from self.hold(0.2, grip=OPEN_CAP)
      raise Retry("cap would not seat")
    # 4) take hold of the seated cap again to lift the pen out by it
    yield from self.line(np.array([*axis(z_clear), z_clear]), rot_ax, speed=0.05)
    yield from self.line(np.array([xy[0], xy[1], z_clear]), rot, speed=0.05)
    yield from self.hold(0.25, grip=OPEN_CAP)
    z_grip = z_sh + E_SEAT_C + h
    yield from self.line(np.array([xyc[0], xyc[1], z_grip]), rot, speed=0.04)
    yield from self.hold(0.15, integ=True)
    # free-motion deflection of the tool here (sag, joint offsets): what the arm reads with nothing pushing on it
    acc = np.zeros(2)
    for _ in range(5):
      yield
      acc += self.tool()[0][:2] - self.arm.fk(self.q_cmd)[0][:2]
    self.d0_grip = acc / 5
    # close on the cap while letting the arm give way sideways: the pads centre the cap, and a stiff arm would
    # bend the pen against its snug puck bore
    yield from self.comply_xy(round(0.3 / self.dt), rot, grip=HOLD_CAP)
    yield from self.comply_xy(round(0.1 / self.dt), rot)
    self.holding = "cap"
    self.press_rot = rot
    self.press_yaw = yaw
    self.press_seated = seated
    # the marker leans in the bore and is now held at that lean: its tail stays where the seat put it, off the tool axis
    tail = o[:2]
    self.tail_off = np.asarray(tail, float) - self.tool()[0][:2]
    if float(np.linalg.norm(self.tail_off)) > 0.012:
      self.tail_off = np.zeros(2)

  def on_axis(self, axis, rot, z, qq, corr):
    """Commands tool height z on the pen axis, steering the measured tool position onto it: under a vertical push
    the YAM's joints give and the fingertips would otherwise walk sideways across the cap top."""
    pm, _ = self.tool()
    corr += 0.12 * (axis(pm[2]) - pm[:2])
    np.clip(corr, -0.003, 0.003, out=corr)
    qq, _ = self.arm.ik(np.array([*(axis(z) + corr), z]), rot, qq, iters=10)
    self.q_cmd = qq
    return qq

  def comply_xy(self, n, rot, grip=None, z_to=None, speed=0.05, gain=0.35):
    """Holds (n ticks) or rises to z_to while the commanded tool position follows the sideways deflection the
    arm reads against its free-motion value self.d0_grip: an admittance in x and y."""
    p0, _ = self.arm.fk(self.q_cmd)
    xy, z = p0[:2].copy(), float(p0[2])
    qq = self.q_cmd.copy()
    g0 = self.g_cmd
    d0 = getattr(self, "d0_grip", np.zeros(2))
    i = 0
    while True:
      if z_to is None:
        if i >= n:
          break
        if grip is not None:
          self.g_cmd = g0 + (grip - g0) * (i + 1) / n
      else:
        if z >= z_to:
          break
        z = min(z_to, z + speed * self.dt)
      i += 1
      pm, _ = self.tool()
      dfl = pm[:2] - self.arm.fk(qq)[0][:2] - d0
      xy = xy + gain * np.clip(dfl, -0.002, 0.002)
      qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
      self.q_cmd = qq
      yield

  def yield_aside(self, xy, base, d0):
    """While the cap mouth bears on the neck, let the arm give way sideways: the commanded position follows where
    the mouth chamfer has pushed the tool, so the chamfer, not the arm's stiffness, sets where the cap goes."""
    if float(self.obs["io"]["nest_load_n"]) - base > 0.4:
      pm, _ = self.tool()
      dfl = (pm[:2] - self.arm.fk(self.q_cmd)[0][:2]) - d0
      if float(np.linalg.norm(dfl)) > 0.0002:
        xy = xy + 0.4 * np.clip(dfl, -0.001, 0.001)
    return xy

  def touch_top(self, axis, rot, z0):
    """Light touch on the cap top along the pen axis from tool height z0 down: the tool height where the load
    cell first reads 0.8 N (two readings in a row), then back up. None if nothing is there."""
    qq, _ = self.arm.ik(np.array([*axis(z0), z0]), rot, self.q_cmd.copy(), iters=20)
    self.q_cmd = qq
    yield from self.hold(0.15)
    base = (yield from self.mean_load(4)) + self.load_bias
    z = z0
    z_touch = None
    zs, hits = [], 0
    corr = self.press_corr
    for i in range(140):
      ld = float(self.obs["io"]["nest_load_n"]) - base
      zs.append(float(self.tool()[0][2]))
      hits = hits + 1 if ld > 0.8 else 0
      if hits >= 2:
        z_touch = float(np.mean(zs[-3:]))
        break
      z -= 0.0002
      qq = self.on_axis(axis, rot, z, qq, corr)
      yield
    pm, _ = self.tool()
    qq, _ = self.arm.ik(np.array([*(axis(pm[2] + 0.003) + corr), pm[2] + 0.003]), rot, qq, iters=20)
    self.q_cmd = qq
    yield from self.hold(0.15)
    return z_touch

  def tip_press(self, axis, rot, z_sh, ceiling=PRESS_CEILING_N):
    """One press on the cap top with the closed fingertips. Returns (clicked, over, peak)."""
    base = yield from self.mean_load(5)
    base += self.load_bias
    z = z_sh + CAP_LEN + E_RING + PAD_TIP + 0.004
    qq, _ = self.arm.ik(np.array([*axis(z), z]), rot, self.q_cmd.copy(), iters=20)
    self.q_cmd = qq
    yield from self.hold(0.15)
    z_first = None
    i_first = 0
    peak = 0.0
    hist = []
    corr = self.press_corr
    clicked = over = False
    for i in range(1500):
      hist.append(float(self.obs["io"]["nest_load_n"]) - base)
      ld = float(np.mean(hist[-3:]))                # the cell is noisy: judge on a three-reading mean
      zt = float(self.tool()[0][2])
      if z_first is None and ld > 0.4:
        z_first = zt
        i_first = i
      peak = max(peak, ld)
      settled = z_first is not None and i - i_first > 8
      # the click: the load gives way well below its peak (the bead is passing)
      if settled and peak > 4.0 and ld < 0.72 * peak:
        clicked = True
        # the servos store several millimetres of push at this load: take it out at once (command the measured
        # height) or the cap slams home through the nib; then follow the cap down through the drag until the
        # load comes back up (home on the shoulder)
        z = zt - 0.0005
        qq = self.on_axis(axis, rot, z, qq, corr)
        yield from self.hold(0.06)
        for _ in range(120):
          hist.append(float(self.obs["io"]["nest_load_n"]) - base)
          gone = zt - float(self.tool()[0][2])
          # home on the shoulder: the load comes back, and the cap has gone the rest of the ring travel (a
          # stick-slip drop part way up the rise is not the click)
          if float(np.mean(hist[-2:])) > 0.75 * peak and gone > 0.0018:
            break
          if float(np.mean(hist[-2:])) > ceiling:
            break
          z -= 0.0002 if float(np.mean(hist[-2:])) < 0.75 * peak else 0.00008
          qq = self.on_axis(axis, rot, z, qq, corr)
          yield
        break
      if ld > ceiling:
        over = True
        break
      if z_first is not None and z < z_first - 0.035:
        break
      if z_first is None:
        if z < z_sh + PAD_TIP + CAP_LEN - 0.004:
          break                                     # nothing under the fingertips
        step = 0.0002
      else:
        step = 0.00025 if ld < 3.0 else (0.00015 if ld < ceiling - 3.0 else 0.00008)
      z -= step
      qq = self.on_axis(axis, rot, z, qq, corr)
      yield
    # take the stored push out of the arm at once
    pm, _ = self.tool()
    qq, _ = self.arm.ik(np.array([*(axis(pm[2] + 0.002) + corr), pm[2] + 0.002]), rot, qq, iters=20)
    self.q_cmd = qq
    yield from self.hold(0.3)
    return clicked, over, peak

  def rack(self, hole, j):
    """Lifts the capped marker out of the nest by its cap and stands it in a rack hole."""
    rot = self.press_rot
    pc, _ = self.arm.fk(self.q_cmd)
    z_hold = pc[2]
    lift = self.wz(NEST_TOP + SHOULDER_Z + self.cap_grasp_h + 0.014)
    yield from self.line(np.array([pc[0], pc[1], lift]), rot, speed=0.05)
    # out of the row of pucks towards the arm before travelling, clear of the pens still standing
    so, sr = self.fix_frame("puck_station")
    away = sr @ np.array([-0.055, 0.0, 0.0])
    yield from self.line(np.array([pc[0] + away[0], pc[1] + away[1], lift]), rot, speed=0.10)
    yield from self.fresh_frame(1)
    if self.find_neck(j) is not None:
      return "left"                                     # the pen is still standing in its puck
    o, r = self.fix_frame("ship_rack")
    # fill the holes farthest from the nest first, so the hanging marker never passes over a filled hole
    on = self.fix_frame("puck_station")[0]
    ys = [(h - (RACK_HOLES - 1) / 2) * RACK_PITCH for h in range(RACK_HOLES)]
    order = sorted(range(RACK_HOLES), key=lambda h: -float(np.linalg.norm((o + r @ np.array([0.0, ys[h], 0.0]) - on)[:2])))
    hy = ys[order[hole]]
    hp = o + r @ np.array([0.0, hy, 0.0])
    yaw = self.fix["ship_rack"][2] + math.pi / 2        # fingers close along the row: the finger struts stay clear of the neighbours
    top = np.array([hp[0], hp[1], lift])
    yaw, q = self.best_yaw(top, yaw)
    # put the hanging tail, not the tool, over the hole: the tail offset turns with the wrist
    da = yaw - self.press_yaw
    c, sn = math.cos(da), math.sin(da)
    toff = np.array([c * self.tail_off[0] - sn * self.tail_off[1], sn * self.tail_off[0] + c * self.tail_off[1]])
    top = np.array([hp[0] - toff[0], hp[1] - toff[1], lift])
    rot = rot_down(yaw)
    self.log('rack tail off', (toff * 1000).round(1))
    yield from self.line(top, rot, speed=0.12)          # straight across at a low height, clear of the rack top
    yield from self.hold(0.5, integ=True)               # let the hanging marker stop swinging
    yield from self.fresh_frame(1)                      # arm over the rack: the nest is in view
    if self.find_neck(j) is not None:
      return False                                      # the marker stayed behind: the cap did not take
    yield from self.hold(0.1, integ=True)
    z_goal = self.wz(RACK_FLOOR + SHOULDER_Z + self.cap_grasp_h) - 0.0015
    for go in range(4):
      xy0 = top[:2] + (0.0 if go == 0 else 0.0012) * np.array([math.cos(1.9 * go), math.sin(1.9 * go)])
      xy = xy0.copy()
      z = top[2]
      qq = self.q_cmd.copy()
      tries = 0
      e0 = None
      ne = 0
      while z > z_goal:
        z -= 0.0010
        ne += 1
        qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
        self.q_cmd = qq
        yield
        pm, _ = self.tool()
        pcmd, _ = self.arm.fk(self.q_cmd + self.integ)
        if ne == 7:
          e0 = pm[2] - pcmd[2]
        if e0 is not None and pm[2] - pcmd[2] - e0 > 0.0040 and z > z_goal + 0.004 and tries < 6:
          tries += 1
          ang = 2.4 * tries
          rad = 0.0015 + 0.0008 * tries
          xy = xy0 + rad * np.array([math.cos(ang), math.sin(ang)])
          for _ in range(8):
            z += 0.0012
            qq, _ = self.arm.ik(np.array([xy[0], xy[1], z]), rot, qq, iters=10)
            self.q_cmd = qq
            yield
          ne = 0
          e0 = None
      yield from self.hold(0.15)
      pm, _ = self.tool()
      self.log('rack hole', hole, 'tries', tries, 'z', round(z, 4), 'tool z', round(pm[2], 4), 'goal', round(z_goal, 4))
      if pm[2] <= z_goal + 0.0045 or go == 3:
        break
      # hung up on the chamfer or a wall: back up to the top and come down again from another point
      yield from self.line(top, rot, speed=0.06)
      yield from self.hold(0.4, integ=True)
    yield from self.hold(0.25, grip=OPEN_CAP)
    pc, _ = self.arm.fk(self.q_cmd)
    yield from self.line(np.array([pc[0], pc[1], pc[2] + 0.080]), rot, speed=0.16)
    self.holding = None
    return True