File size: 47,092 Bytes
602054e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""FT-2 reference controller (SO-101): load the board under test, run the test, unload.

A staged generator, one command per 20 ms tick. Kinematics and the nominal fixture geometry come from /app/scene.xml.
The layout (fixture nest, header revision, plug and parking-socket poses) comes from the overhead camera, registered on
the cable duct. The robot mount is levelled from three touch-off probes on the bench. The jack contact and the test result
come from the fixture I/O.
"""
from __future__ import annotations

import math
import os

import mujoco
import numpy as np

ARM = ["robot/shoulder_pan", "robot/shoulder_lift", "robot/elbow_flex", "robot/wrist_flex", "robot/wrist_roll"]
GRIP = "robot/gripper"
HOME = np.array([0.0, -1.6, -1.45, 1.0, 0.0, 0.2])
KP = 998.22
DT = 0.02

FIX_FACE = -0.0205        # fixed-jaw face a held part settles against, along the TCP closing axis (TCP z)
GRASP_GAP = 0.001         # fixed-jaw clearance on approach (its tip pads stand 1 mm proud of the face)
# where a part ends up in the hand (TCP frame), measured on the bench: the jaw arc draws it down a little
HDR_IN_HAND = (0.01646, -0.0006, -0.01595)     # header plug bottom centre, grasped 16 mm up across its length
DC_HAND_CORR = np.array([0.00065, 0.0, 0.0002])
TOUCH_TIP = 0.00648       # closed jaws: lowest point below the TCP, including the touch-detection lag
G_OPEN, G_CLOSED = 0.30, -0.17
G_DC, G_HDR, G_LATCH = -0.12, -0.12, -0.14

DC_REST_Z = 0.0045        # DC plug housing centre when it lies on the bench
DC_HALF_W = 0.0045
DC_TIP = 0.0225
HDR_GRASP_Z = 0.016       # grasp height above the header plug's bottom
HDR_H = 0.020
HDR_SET_Z = 0.0082        # plug bottom at the top of the shroud lead-ins (8 mm)
HDR_AIM = np.array([-0.00015, 0.00045, 0.0])   # board frame: mean lean of the held plug's bottom, measured
HDR_DROP_Z = 0.0055       # let go here: the bottom 1.5 mm inside the walls, so a plug leaning in the pads cannot tip out
HDR_PRESS_Z = 0.0004      # commanded plug bottom after the press (lands near 1.0 mm: seated below 1.6, stop at 0.4)
DC_GRASP_Z = 0.0085       # TCP height for the DC plug grasp (fixed-jaw tip clears the bench)
PRESS_Z = -0.0228         # closed jaws: the lowest point's offset along the TCP closing axis
BUTTON_CAP = 0.005        # button cap top above its body
DC_PAD = (0.205, 0.13)
HDR_PARK = (0.112, -0.065)
HDR_HALF = (0.005, 0.0035)
HDR_REVS = (-0.012, 0.0, 0.012)
SHROUD = np.array([0.006, -0.020, 0.0016])   # board frame, revision B
SOCKET_FLOOR = 0.002
TARGETS_XY = ((0.33, -0.16), (0.33, 0.0), (0.33, 0.16))
TARGET_Z = 0.0244
SHROUD_TOP_Z = 0.0206     # top of the header shroud walls on the board
HOLDER_HALF = (0.013, 0.011)
HOLDER_TOP = 0.008
PROBE_XY = ((0.105, 0.065), (0.115, -0.030), (0.270, -0.100))   # bench touch-off probes (cell drawing)
PROBE_YAW = (0.0, -math.pi / 2, math.pi)  # jaw orientation per probe: reachable from 0 to 45 mm, clear of the nest
PROBE_TOP, PROBE_TRIP = 0.021, 0.001   # plunger top at rest; the switch closes 1 mm down
PROBE_LAG = 0.00017                 # commanded-vs-actual height at the slow touch speed
SAFE_Z = 0.055           # transit height (TCP) over the fixture


def rotz(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 roty(a):
  c, s = math.cos(a), math.sin(a)
  return np.array([[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]])


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


def topdown_R(yaw):
  """TCP frame: x = approach (down), z = closing axis at `yaw` (the fixed jaw sits on the -z side)."""
  z = np.array([math.cos(yaw), math.sin(yaw), 0.0])
  x = np.array([0.0, 0.0, -1.0])
  y = np.cross(z, x)
  return np.column_stack([x, y, z])


def rot_err(R, Rc):
  """Rotation vector (world) taking Rc to R; correct up to a half turn."""
  q = np.zeros(4)
  mujoco.mju_mat2Quat(q, (R @ Rc.T).flatten())
  if q[0] < 0:
    q = -q
  v = np.zeros(3)
  mujoco.mju_quat2Vel(v, q, 1.0)
  return v


def tcp_for(c, yaw, w):
  """TCP that puts the fixed-jaw face w/2 from the part centre c, on the -closing-axis side."""
  return c - topdown_R(yaw) @ np.array([0.0, 0.0, FIX_FACE + w / 2])


class Kin:
  def __init__(self, scene_xml):
    self.m = mujoco.MjModel.from_xml_path(scene_xml)
    self.d = mujoco.MjData(self.m)
    m = self.m
    self.qadr = np.array([m.jnt_qposadr[m.joint(n).id] for n in ARM + [GRIP]])
    self.dadr = np.array([m.jnt_dofadr[m.joint(n).id] for n in ARM + [GRIP]])
    self.site = m.site("robot/gripperframe").id
    self.lo = np.array([m.jnt_range[m.joint(n).id, 0] for n in ARM + [GRIP]])
    self.hi = np.array([m.jnt_range[m.joint(n).id, 1] for n in ARM + [GRIP]])
    self.jp = np.zeros((3, m.nv)); self.jr = np.zeros((3, m.nv))
    self.robot_geom = np.array([m.body(m.geom_bodyid[g]).name.startswith("robot/") for g in range(m.ngeom)])
    m.geom_margin[self.robot_geom] = 0.005    # self-contact checks keep 5 mm between links (servo overshoot)
    mujoco.mj_kinematics(m, self.d)
    mujoco.mj_camlight(m, self.d)

  def set(self, q):
    self.d.qpos[self.qadr] = q
    mujoco.mj_kinematics(self.m, self.d)
    mujoco.mj_comPos(self.m, self.d)

  def fk(self, q):
    self.set(q)
    return self.d.site_xpos[self.site].copy(), self.d.site_xmat[self.site].reshape(3, 3).copy()

  def jac(self, q):
    self.set(q)
    mujoco.mj_jacSite(self.m, self.d, self.jp, self.jr, self.site)
    return self.jp[:, self.dadr[:5]].copy(), self.jr[:, self.dadr[:5]].copy()

  def gravity(self, q):
    self.set(q)
    self.d.qvel[:] = 0
    mujoco.mj_rne(self.m, self.d, 0, self.d.qfrc_bias)
    return self.d.qfrc_bias[self.dadr].copy()

  def ik(self, p, R, q_seed, iters=60, tol_p=2e-5, tol_r=2e-3):
    q = np.array(q_seed, float).copy()
    for _ in range(iters):
      pos, Rc = self.fk(q)
      ep = p - pos
      er = rot_err(R, Rc)
      if np.linalg.norm(ep) < tol_p and np.linalg.norm(er) < tol_r:
        break
      Jp, Jr = self.jac(q)
      J = np.vstack([Jp, 0.3 * Jr]); e = np.concatenate([ep, 0.3 * er])
      dq = J.T @ np.linalg.solve(J @ J.T + 1e-6 * np.eye(6), e)
      n = np.linalg.norm(dq)
      if n > 0.3:
        dq *= 0.3 / n
      q[:5] = np.clip(q[:5] + dq, self.lo[:5] + 1e-3, self.hi[:5] - 1e-3)
      if n < 2e-6:
        break                         # settled on the closest reachable pose (5 joints cannot match every frame)
    pos, Rc = self.fk(q)
    err_p = float(np.linalg.norm(p - pos))
    err_r = float(np.linalg.norm(rot_err(R, Rc)))
    return q, err_p, err_r

  def self_contact(self, q):
    """True if the arm touches itself at q (the scene's own collision geometry)."""
    self.set(q)
    mujoco.mj_collision(self.m, self.d)
    for i in range(self.d.ncon):
      c = self.d.contact[i]
      if self.robot_geom[c.geom1] and self.robot_geom[c.geom2]:
        return True
    return False

  def rel_nest(self, body):
    """Nominal pose of a fixture body in the nest frame (from the scene file)."""
    m, d = self.m, self.d
    n = m.body("nest").id
    b = m.body(body).id
    Rn = d.xmat[n].reshape(3, 3)
    return Rn.T @ (d.xpos[b] - d.xpos[n]), Rn.T @ d.xmat[b].reshape(3, 3)


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


class PlugLost(Exception):
  """The DC plug slipped out of the jaws on the way to the jack (a stiff cable pulls on it)."""


class Controller:
  def __init__(self, model_info: dict):
    self.info = model_info
    self.kin = Kin(model_info.get("scene_xml", "/app/scene.xml"))
    names = model_info["joint_names"]
    self.jidx = [names.index(n) for n in ARM + [GRIP]]
    anames = model_info["actuator_names"]
    self.aidx = [anames.index(n) for n in ARM + [GRIP]]
    self.lo = np.array(model_info["ctrl_low"]); self.hi = np.array(model_info["ctrl_high"])
    self.nu = len(anames)
    k = self.kin
    self.jack_n, Rj = k.rel_nest("dc_jack")
    self.jack_ax_n = Rj[:, 0]                       # out of the bore
    self.shroud_n, _ = k.rel_nest("hdr_shroud")     # revision B
    self.button_n, _ = k.rel_nest("button")
    cid = k.m.camera("overhead").id
    self.ocam = Cam(k.d.cam_xpos[cid].copy(), k.d.cam_xmat[cid].reshape(3, 3).copy(),
                    float(k.m.cam_fovy[cid]), 480, 360)
    self.log = os.environ.get("FT2_LOG") is not None

  def say(self, *a):
    if self.log:
      print(f"[{self.obs['time']:.2f}]", *a, flush=True)

  # ------------------------------------------------------------------ plumbing
  def reset(self, obs):
    self.obs = obs
    self.qd = HOME.copy()
    self.gen = self.main()
    self.done = None
    self.tau, self.dz = 0.0, 0.0        # robot mount tilt about y and height offset (touch-off probes)
    self.last_stamp, self.last_img, self.noisy, self.g_bad, self.pending = None, None, False, 0, None
    self.same_n = 0
    self.g_bias = 0.0
    self.diagnosing = False

  def act(self, obs):
    self.obs = obs
    if self.done is not None:
      return self.done
    try:
      self.monitor(obs)
      out = next(self.gen)
    except StopIteration:
      self.done = {"status": "done"}
      return self.done
    except Abort as a:
      self.done = {"status": "abort", "fault": a.fault}
      return self.done
    except Exception as e:  # noqa: BLE001
      if self.diagnosing:
        raise
      # a step that failed may be a sensor or gripper gone bad: check both before giving up
      self.diagnosing = True
      self.gen = self.diagnose(e)
      return self.ctrl()
    return out

  def diagnose(self, err):
    """Hold still, take fresh frames (a frozen feed shows up as the same frame or no frame), then open the jaws (a
    dead gripper does not follow). Either raises Abort; if both are fine the original error stands."""
    for _ in range(3):
      yield from self.fresh()
      yield from self.wait(0.2)
    yield from self.grip_to(G_OPEN, 0.2)
    yield from self.opened(G_OPEN)
    raise err

  def monitor(self, obs):
    """A camera that stops answering or repeats its frame, and a gripper that does not follow its command."""
    t, st = obs["time"], obs.get("camera_stamp")
    if st is not None and st != self.last_stamp:
      img = obs["images"].get("overhead")
      if self.last_img is not None and img is not None:
        same = np.array_equal(img, self.last_img)
        self.same_n = self.same_n + 1 if same else 0
        if self.same_n >= 2 and self.noisy:
          raise Abort("perception_freeze")          # new stamps on the very same noisy frame, twice running
        if not np.array_equal(img[:20], self.last_img[:20]):
          self.noisy = True                         # the far bench strip differs: the sensor shows noise
      self.last_stamp, self.last_img = st, img
      if self.pending is not None and st >= self.pending - 1e-9:
        self.pending = None
    if self.pending is not None and t - self.pending > 1.0:
      raise Abort("perception_freeze")              # a requested frame never came
    g_cmd, g_m = float(self.qd[5]), float(self.qm()[5])
    if g_cmd - g_m > 0.12 or (g_cmd < -0.05 and g_m > 0.15):
      self.g_bad += 1
    else:
      self.g_bad = 0
    if self.g_bad > 30:
      raise Abort("dead_gripper")

  def ctrl(self):
    q = self.qd.copy()
    g = self.kin.gravity(q)
    cmd = np.zeros(self.nu)
    for k in range(6):
      cmd[self.aidx[k]] = q[k] + (g[k] / KP if k < 5 else 0.0)
    return np.clip(cmd, self.lo, self.hi)

  def qm(self):
    q = np.asarray(self.obs["qpos"], float)[self.jidx].copy()
    q[5] -= self.g_bias                 # the gripper encoder's offset, read with the jaws open and unloaded
    return q

  def wait(self, s):
    for _ in range(max(1, int(round(s / DT)))):
      yield self.ctrl()

  # ------------------------------------------------------------------ frames
  def w2r(self, p):
    return roty(self.tau) @ (np.asarray(p, float) + [0.0, 0.0, self.dz])

  def r2w(self, p):
    return roty(self.tau).T @ np.asarray(p, float) - [0.0, 0.0, self.dz]

  def tcp(self, q=None):
    p, R = self.kin.fk(self.qd if q is None else q)
    return self.r2w(p), roty(self.tau).T @ R

  def tcp_vz(self):
    """Measured TCP vertical speed (world), from the exact joint velocities."""
    Jp, _ = self.kin.jac(self.qd)
    v = Jp @ np.asarray(self.obs["qvel"])[self.jidx[:5]]
    return float((roty(self.tau).T @ v)[2])

  # ------------------------------------------------------------------ motion
  def path_clear(self, q0, q1, n=10):
    """True if the straight joint-space path from q0 to q1 keeps the arm off itself."""
    return not any(self.kin.self_contact(q0 + (q1 - q0) * (k / n)) for k in range(1, n))

  def move_q(self, qt, vmax=1.5, grip=None):
    qt = np.array(qt, float).copy()
    if grip is not None:
      qt[5] = grip
    if not self.path_clear(self.qd.copy(), qt):
      via = np.array(HOME, float)
      via[0], via[5] = qt[0], qt[5]             # fold the arm on the target's bearing, then go out again
      if self.path_clear(self.qd.copy(), via) and self.path_clear(via, qt):
        yield from self.move_q(via, vmax)
    q0 = self.qd.copy()
    dq = qt - q0
    T = max(0.1, float(np.max(np.abs(dq[:5]))) / vmax * 1.6, abs(dq[5]) / (0.6 if dq[5] < 0 else 3.0))
    n = max(1, int(math.ceil(T / DT)))
    for i in range(1, n + 1):
      s = 0.5 - 0.5 * math.cos(math.pi * i / n)
      self.qd = q0 + dq * s
      yield self.ctrl()

  def ik(self, p, yaw, flip=True):
    """Joint target for a world TCP position and a top-down closing-axis yaw (or yaw + pi when flip is allowed)."""
    best = None
    pr = self.w2r(p)
    for y2 in ((yaw, yaw + math.pi) if flip else (yaw,)):
      Rr = roty(self.tau) @ topdown_R(y2)
      pan = math.atan2(pr[1], pr[0])
      seeds = [self.qd] + [np.array([pan, -0.3, 0.6, 1.3, wrap(y2 - pan), self.qd[5]])]
      for s in seeds:
        q, ep, er = self.kin.ik(pr, Rr, s, iters=120)
        cost = ep * 100 + er * 10 + 0.05 * abs(q[4] - self.qd[4]) + (5.0 if self.kin.self_contact(q) else 0.0)
        if best is None or cost < best[0]:
          best = (cost, q, ep, er, wrap(y2))
    _, q, ep, er, y2 = best
    q[5] = self.qd[5]
    self.ik_err = ep + er * 0.05
    if ep > 1e-3 or er > 0.01:
      self.say("ik miss", round(ep * 1000, 2), "mm", round(er, 3), "rad at", np.round(p, 4), "yaw", round(y2, 2))
    return q, y2

  def goto(self, p, yaw, vmax=2.0, flip=True, hi=None):
    """Transit: up to the safe height, across in joint space, down a straight line to p."""
    p = np.asarray(p, float)
    cur, _ = self.tcp()
    for hi in ((max(hi, p[2]),) if hi is not None else ()) + (max(SAFE_Z, p[2]), max(0.045, p[2]), p[2] + 0.012):
      q, y2 = self.ik(np.array([p[0], p[1], hi]), yaw, flip)
      if self.ik_err < 5e-4:
        break
    if cur[2] < hi - 0.002:
      yield from self.line(np.array([cur[0], cur[1], hi]), self.yaw_now(), 0.10)
      q, y2 = self.ik(np.array([p[0], p[1], hi]), yaw, flip)
    yield from self.move_q(q, vmax)
    if hi - p[2] > 0.001:
      yield from self.line(p, y2, 0.08)
    return y2

  def yaw_now(self):
    _, R = self.tcp()
    return math.atan2(R[1, 2], R[0, 2])

  def line(self, p1, yaw, speed=0.05):
    """Straight TCP line (world) from the current pose to p1 at a fixed top-down yaw."""
    p0, _ = self.tcp()
    p1 = np.asarray(p1, float)
    dist = float(np.linalg.norm(p1 - p0))
    n = max(1, int(math.ceil(dist / (speed * DT))))
    Rr = roty(self.tau) @ topdown_R(yaw)
    q = self.qd.copy()
    for i in range(1, n + 1):
      s = 0.5 - 0.5 * math.cos(math.pi * i / n) if n > 3 else i / n
      q, ep, er = self.kin.ik(self.w2r(p0 + (p1 - p0) * s), Rr, q)
      yield from self.joint_step(q)

  def joint_step(self, q):
    """Command q (arm joints), spread over several ticks if any joint would move more than 0.024 rad in one."""
    q = np.array(q, float)
    q[5] = self.qd[5]
    k = max(1, int(math.ceil(float(np.max(np.abs(q[:5] - self.qd[:5]))) / 0.024)))
    q0 = self.qd.copy()
    for j in range(1, k + 1):
      self.qd = q0 + (q - q0) * j / k
      yield self.ctrl()

  def step_to(self, p, yaw):
    """One tick of a slow guarded move: IK for p, no profile (rate-limited)."""
    q, ep, er = self.kin.ik(self.w2r(p), roty(self.tau) @ topdown_R(yaw), self.qd)
    q[5] = self.qd[5]
    q[:5] = self.qd[:5] + np.clip(q[:5] - self.qd[:5], -0.024, 0.024)
    self.qd = q
    return self.ctrl()

  def grip_to(self, g, t=0.4):
    q = self.qd.copy(); q[5] = g
    yield from self.move_q(q)
    yield from self.wait(t)

  def opened(self, g, t=1.0):
    """Wait until the jaw has opened to about g before the arm moves. A gripper that stays shut while it holds a
    seated plug is dead: stop where we are (moving would lever the plug and lift the board) and report it."""
    for _ in range(int(t / DT)):
      if float(self.qm()[5]) > g - 0.08:
        return
      yield self.ctrl()
    raise Abort("dead_gripper")

  def release_and_lift(self, yaw, up=0.03):
    """Let go slowly (the finger pads are soft and spring back), back the fixed jaw off, lift."""
    g = float(self.qd[5])
    while g < 0.0:
      g = min(0.0, g + 0.25 * DT)
      self.qd[5] = g
      yield self.ctrl()
    yield from self.grip_to(G_OPEN, 0.2)
    yield from self.opened(G_OPEN)
    zc = topdown_R(yaw)[:, 2]
    yield from self.line(self.tcp()[0] - zc * 0.002, yaw, 0.01)
    yield from self.line(self.tcp()[0] + [0, 0, up], yaw, 0.05)

  # ------------------------------------------------------------------ perception
  def fresh(self):
    """Triggers the cameras and waits for that frame; returns the overhead image."""
    t0 = self.obs["time"]
    self.pending = t0
    yield {"ctrl": self.ctrl(), "capture": True}
    while True:
      st = self.obs.get("camera_stamp")
      if st is not None and st >= t0 - 1e-9:
        return self.obs["images"]["overhead"]
      yield self.ctrl()

  def look(self, what):
    """Fresh overhead frame, parsed for the board and `what` (a tuple of item names)."""
    for _ in range(3):
      img = yield from self.fresh()
      ov = Overhead(self.ocam)
      if not ov.register(img):
        continue
      b = ov.board(img)
      if b is None:
        continue
      out = {"board": b[0]}
      if "shroud" in what:
        out["shroud"] = ov.shroud(img, b[0])
      if "dc" in what:
        out["dc"] = ov.dc_plug(img, b[0], self.tcp()[0][:2])
      if "holder" in what:
        out["holder"] = ov.holder(img, b[0])
      if all(out.get(k) is not None for k in what):
        return out
      yield from self.wait(0.3)
    raise RuntimeError(f"layout not found: {what}")

  # ------------------------------------------------------------------ cell geometry
  def layout(self, L):
    b = L["board"]
    self.nest_xy, self.nest_yaw = np.array(b[:2]), float(b[2])
    Rn = rotz(self.nest_yaw)
    self.Rn = Rn
    nest = np.array([b[0], b[1], 0.0])
    self.jack = nest + Rn @ self.jack_n
    self.jack_ax = Rn @ self.jack_ax_n
    sx = L["shroud"]
    near = min(HDR_REVS, key=lambda r: abs(self.shroud_n[0] + r - sx))
    if abs(self.shroud_n[0] + near - sx) < 0.0003:     # a released revision; engineering samples sit anywhere
      sx = self.shroud_n[0] + near
    self.shroud = nest + Rn @ np.array([sx, self.shroud_n[1], self.shroud_n[2]])
    self.button = nest + Rn @ self.button_n
    self.say("layout nest", np.round(b, 4), "shroud x", round(sx, 4), "jack", np.round(self.jack, 4))

  # ------------------------------------------------------------------ steps
  def probe(self, k, z0):
    """Touch off on bench probe k with the closed jaws' lowest point: fast to the switch, back up, slow to it again.
    Returns the commanded height of that point when the switch closed (current robot-to-bench estimate)."""
    px, py = PROBE_XY[k]
    yaw = PROBE_YAW[k]
    at = lambda z: self.press_tcp(np.array([px, py, z]), yaw)
    yield from self.goto(at(z0 + 0.008), yaw, 2.0, flip=False, hi=0.05)
    yield from self.line(at(z0), yaw, 0.03)
    z, hit = z0, None
    for speed, back in ((0.008, 0.0015), (0.0005, None)):
      while not self.obs["io"]["probe"][k]:
        z -= speed * DT
        if z < z0 - 0.05:
          raise RuntimeError("probe not found")
        yield self.step_to(at(z), yaw)
      if back is None:
        hit = z
        break
      z += back
      yield from self.line(at(z), yaw, 0.01)
      yield from self.wait(0.15)
    yield from self.line(at(hit + 0.006), yaw, 0.02)
    self.say("probe", k, "hit tip z", round(hit * 1000, 2), "yaw", round(yaw, 2), "ik err", getattr(self, "ik_err", None))
    return hit

  def calibrate(self):
    """Touch off on the three bench probes; fit the mount height and tilt."""
    yield from self.grip_to(G_CLOSED, 0.1)
    pts = []
    z0 = PROBE_TOP + 0.022            # the mount height is only known to about +-20 mm
    for k in range(len(PROBE_XY)):
      hit = yield from self.probe(k, z0)
      p_r = self.w2r(np.array([PROBE_XY[k][0], PROBE_XY[k][1], hit]))
      pts.append((p_r[0], p_r[1], p_r[2] - (PROBE_TOP - PROBE_TRIP) + PROBE_LAG))
      z0 = hit + 0.009                # the next probes are within the mount tilt of this one
    A = np.array([[1.0, p[0], p[1]] for p in pts])
    a, bx, by = np.linalg.solve(A, np.array([p[2] for p in pts]))
    self.tau = math.atan(-bx)
    self.dz = a * math.cos(self.tau)
    self.say("bench plane a", round(a * 1000, 2), "mm, slope x", round(bx, 5), "y", round(by, 5),
             "-> tilt deg", round(math.degrees(self.tau), 3))

  def press_tcp(self, pt, yaw):
    """TCP that puts the closed jaws' lowest point (the fixed-jaw tip) at world point pt."""
    return pt - topdown_R(yaw) @ np.array([TOUCH_TIP, 0.0, PRESS_Z])

  def close_on(self, light=0.012, rate=0.3):
    """Close until the jaw stops on the part (measured angle lags the command), then hold a light squeeze."""
    g = float(self.qd[5])
    stall, n = None, 0
    while g > G_CLOSED:
      g -= rate * DT
      self.qd[5] = g
      yield self.ctrl()
      qm = float(self.qm()[5])
      n = n + 1 if qm - g > 0.03 else 0
      if n >= 3:
        stall = qm
        break
    if stall is None:
      return None
    self.qd[5] = stall - light
    yield from self.wait(0.3)
    return stall

  def pick_dc(self, p):
    """Grasp the DC plug across its body. A miss (the plug was knocked, or the estimate was off) sends the arm out of
    the overhead camera's view for a fresh look before the next try."""
    for attempt in range(4):
      if attempt:
        yield from self.grip_to(G_OPEN, 0.05)
        yield from self.opened(G_OPEN)
        yield from self.move_q(HOME, 2.0)
        yield from self.wait(0.4)
        L = yield from self.look(("dc",))
        p = L["dc"]
      ax = np.array([math.cos(p[2]), math.sin(p[2]), 0.0])
      ctr = np.array([p[0], p[1], DC_REST_Z])
      c = ctr - ax * 0.003
      c[2] = DC_GRASP_Z
      w = 2 * DC_HALF_W + 2 * GRASP_GAP
      _, yaw = self.ik(tcp_for(c, p[2] + math.pi / 2, w) + [0, 0, 0.02], p[2] + math.pi / 2)
      T = tcp_for(c, yaw, w)
      yield from self.grip_to(G_OPEN, 0.05)
      yield from self.opened(G_OPEN)
      yield from self.goto(T + [0, 0, 0.03], yaw, 2.0, flip=False)
      yield from self.line(T, yaw, 0.05)
      yield from self.grip_to(self.g_dc, 0.4)
      if self.qm()[5] < self.g_dc + 0.012:
        self.say("dc grasp missed")
        yield from self.grip_to(G_OPEN, 0.1)
        yield from self.opened(G_OPEN)
        yield from self.line(T + [0, 0, 0.04], yaw, 0.08)
        continue
      R = topdown_R(yaw)
      off = R.T @ (ctr - T)
      off[2] = FIX_FACE + DC_HALF_W
      off += DC_HAND_CORR
      self.dc_off, self.dc_yaw, self.dc_ax_h = off, yaw, R.T @ ax
      yield from self.line(T + [0, 0, 0.03], yaw, 0.05)
      return
    raise RuntimeError("dc plug pick failed")

  def insert_dc(self):
    jax = self.jack_ax
    want = math.atan2(-jax[1], -jax[0])                 # plug +x (barrel) into the bore
    have_v = topdown_R(self.dc_yaw) @ self.dc_ax_h
    yaw = wrap(self.dc_yaw + wrap(want - math.atan2(have_v[1], have_v[0])))
    off = self.dc_off
    def tcp_at(s, lat=np.zeros(3)):
      return self.jack + lat + jax * (s + 0.003) - topdown_R(yaw) @ off
    side = np.cross([0, 0, 1.0], jax)
    for lat in (np.zeros(3), side * 0.0008, -side * 0.0008, np.array([0, 0, 0.0006])):
      yield from self.goto(tcp_at(0.035, lat) + [0, 0, 0.02], yaw, 1.5, flip=False)
      g = []
      for _ in range(5):                                # still in the jaws? an empty jaw closes onto its command
        yield self.ctrl()
        g.append(float(self.qm()[5]))
      if np.mean(g) < self.g_dc + 0.006:
        raise PlugLost()
      yield from self.line(tcp_at(0.035, lat), yaw, 0.03)
      s = 0.035
      while s > 0.004:
        s -= 0.005 * DT
        yield self.step_to(tcp_at(s, lat), yaw)
        if self.obs["io"]["power"]:
          break
      if self.obs["io"]["power"]:
        self.say("dc power at", round(s, 4))
        yield from self.wait(0.3)
        self.dc_hold = (self.tcp()[0], yaw)             # the fixed jaw touches the plug here: come back to it
        yield from self.release_and_lift(yaw)
        return
      self.say("dc no power, retry")
      yield from self.line(tcp_at(0.035, lat), yaw, 0.02)
    raise RuntimeError("dc insert failed")

  def pick_hdr(self):
    L = yield from self.look(("holder",))
    h = L["holder"]
    self.holder = h
    org = np.array([h[0], h[1], SOCKET_FLOOR])
    c = org + [0, 0, HDR_GRASP_Z]
    w = 2 * HDR_HALF[0] + 2 * GRASP_GAP
    # pick it so that the matching insertion pose (jaws turned the same way relative to the plug) is reachable
    best = None
    for flipped in (False, True):
      yaw = wrap(h[2] + (math.pi if flipped else 0.0))
      ins = wrap(self.nest_yaw + (math.pi if flipped else 0.0))
      cost = 0.0
      for p_, y_ in ((tcp_for(c, yaw, w) + [0, 0, 0.03], yaw), (tcp_for(c, yaw, w), yaw),
                     (self.shroud + [0, 0, HDR_DROP_Z] - topdown_R(ins) @ HDR_IN_HAND, ins),
                     (self.shroud + [0, 0, 0.025] - topdown_R(ins) @ HDR_IN_HAND, ins)):
        self.ik(p_, y_, flip=False)
        cost += self.ik_err
      if best is None or cost < best[0] - 1e-4:
        best = (cost, yaw, flipped)
    _, yaw, flipped = best
    T = tcp_for(c, yaw, w)
    yield from self.grip_to(G_OPEN, 0.05)
    yield from self.opened(G_OPEN)
    yield from self.goto(T + [0, 0, 0.03], yaw, 2.0, flip=False)
    yield from self.line(T, yaw, 0.04)
    yield from self.grip_to(G_HDR, 0.4)
    self.h_off, self.h_flip = np.array(HDR_IN_HAND), flipped
    if flipped:
      self.h_off[1] = -self.h_off[1]            # the plug's key side faces the other way along the jaws
    yield from self.line(T + [0, 0, 0.03], yaw, 0.04)

  def insert_hdr(self):
    """Set the plug into the shroud mouth, let go, and press it home from the top (it centres in the lead-ins)."""
    yaw = wrap(self.nest_yaw + (math.pi if self.h_flip else 0.0))
    off = self.h_off
    aim = self.shroud + self.Rn @ HDR_AIM               # the plug leans a little in the pads: aim off for it
    def tcp_at(zb):
      return aim + [0, 0, zb] - topdown_R(yaw) @ off
    yield from self.goto(tcp_at(0.025), yaw, 1.5, flip=False)
    yield from self.line(tcp_at(0.0095), yaw, 0.02)
    yield from self.line(tcp_at(HDR_SET_Z), yaw, 0.005)
    yield from self.line(tcp_at(HDR_DROP_Z), yaw, 0.003)          # the lead-ins centre it; the pads give
    yield from self.wait(0.2)
    yield from self.release_and_lift(yaw, 0.012)
    # press on the plug top with the closed jaws
    yield from self.grip_to(G_CLOSED, 0.1)
    pyaw = wrap(self.nest_yaw + math.pi / 2)
    top = self.shroud + [0, 0, HDR_H]
    _, pyaw = self.ik(self.press_tcp(top + [0, 0, HDR_PRESS_Z], pyaw), pyaw)
    yield from self.goto(self.press_tcp(top + [0, 0, HDR_SET_Z + 0.006], pyaw), pyaw, 2.0, flip=False)
    yield from self.line(self.press_tcp(top + [0, 0, HDR_SET_Z + 0.001], pyaw), pyaw, 0.01)
    zb = HDR_SET_Z + 0.001
    while zb > HDR_PRESS_Z:
      zb -= 0.003 * DT
      yield self.step_to(self.press_tcp(top + [0, 0, zb], pyaw), pyaw)
    yield from self.wait(0.3)
    yield from self.line(self.press_tcp(top + [0, 0, 0.012], pyaw), pyaw, 0.02)

  def run_test(self):
    yaw = self.nest_yaw + math.pi / 2
    cap = self.button + [0, 0, BUTTON_CAP]
    yield from self.grip_to(G_CLOSED, 0.1)
    _, yaw = self.ik(self.press_tcp(cap - [0, 0, 0.002], yaw), yaw)     # pick the wrist side that stays clear
    yield from self.goto(self.press_tcp(cap + [0, 0, 0.015], yaw), yaw, 2.0, flip=False)
    yield from self.line(self.press_tcp(cap + [0, 0, 0.001], yaw), yaw, 0.03)
    dz = 0.001
    while dz > -0.0042 and self.obs["io"]["lamp"] != "testing":
      dz -= 0.004 * DT
      yield self.step_to(self.press_tcp(cap + [0, 0, dz], yaw), yaw)
    yield from self.line(self.press_tcp(cap + [0, 0, 0.015], yaw), yaw, 0.03)
    t0 = self.obs["time"]
    while self.obs["io"]["lamp"] == "testing" and self.obs["time"] - t0 < 6.0:
      yield self.ctrl()
    self.say("test", self.obs["io"])

  def unplug_dc(self):
    T, yaw = self.dc_hold
    jax = self.jack_ax
    zc = topdown_R(yaw)[:, 2]
    # T held the plug with the pads squeezed: come down with the fixed jaw 1.5 mm off its side, then set it against
    # the plug (pads unloaded) before closing, so the jaws do not lever the plug sideways in its jack
    yield from self.grip_to(0.0, 0.05)              # wide open would swing the moving jaw tip down onto the plug
    yield from self.opened(0.0)
    yield from self.goto(T - zc * 0.0015 + [0, 0, 0.03], yaw, 2.0, flip=False)
    yield from self.line(T - zc * 0.0015 + [0, 0, 0.0003], yaw, 0.03)
    yield from self.line(T - zc * 0.0007 + [0, 0, 0.0003], yaw, 0.005)
    yield from self.grip_to(-0.105, 0.4)
    yield from self.line(T + jax * 0.025, yaw, 0.01)
    self.say("dc pulled", self.obs["io"])
    yield from self.line(self.tcp()[0] + [0, 0, 0.02], yaw, 0.04)
    # lay it down on the rest pad, off the fixture
    Td = np.array([DC_PAD[0], DC_PAD[1], 0.0]) - topdown_R(yaw) @ (self.dc_off * [0, 1, 1])
    Td[2] = DC_GRASP_Z + 0.001
    yield from self.goto(Td + [0, 0, 0.02], yaw, 1.5, flip=False)
    yield from self.line(Td, yaw, 0.03)
    yield from self.release_and_lift(yaw)

  def unplug_hdr(self):
    """Jaws across the plug's y: the moving jaw presses the latch with a light squeeze, the plug comes up, then a
    full squeeze once it is clear of the shroud."""
    yaw = wrap(self.nest_yaw + math.pi / 2)
    org = self.shroud + [0, 0, HDR_PRESS_Z]
    c = org + [0, 0, HDR_GRASP_Z]
    w = 2 * HDR_HALF[1] + 0.0016
    T = tcp_for(c, yaw, w)
    yield from self.grip_to(G_OPEN, 0.05)
    yield from self.opened(G_OPEN)
    yield from self.goto(T + [0, 0, 0.03], yaw, 2.0, flip=False)
    yield from self.line(T, yaw, 0.03)
    stall = yield from self.close_on(0.015)
    self.say("hdr unplug stall", stall)
    yield from self.line(T + [0, 0, 0.012], yaw, 0.008)
    yield from self.grip_to(G_LATCH, 0.3)
    yield from self.line(T + [0, 0, 0.03], yaw, 0.03)
    off = topdown_R(yaw).T @ (org - T)
    # on the bench beside its socket, on the side away from the fixture nest
    best = None
    for dx, dy in ((0.0, -0.035), (-0.035, 0.0), (0.035, 0.0)):
      dest = np.array([self.holder[0] + dx, self.holder[1] + dy, 0.001])
      Td = dest - topdown_R(yaw) @ off
      self.ik(Td, yaw, flip=False)
      if self.ik_err > 0.001:
        continue
      gap = np.linalg.norm(dest[:2] - self.nest_xy)
      if best is None or gap > best[0]:
        best = (gap, Td)
    Td = best[1]
    yield from self.goto(Td + [0, 0, 0.02], yaw, 1.5, flip=False)
    yield from self.line(Td, yaw, 0.03)
    yield from self.release_and_lift(yaw)

  def main(self):
    yield from self.wait(0.3)
    g = []
    for _ in range(15):                 # gripper at rest and unloaded: its reading minus the command is the offset
      yield self.ctrl()
      g.append(float(np.asarray(self.obs["qpos"])[self.jidx[5]]) - float(self.qd[5]))
    self.g_bias = float(np.mean(g))
    yield from self.fresh()                          # a second frame at rest: tells sensor noise from a freeze
    L0 = yield from self.look(("shroud", "dc"))
    self.layout(L0)
    yield from self.calibrate()
    self.g_dc = G_DC
    p = L0["dc"]
    for k in range(3):
      yield from self.pick_dc(p)
      try:
        yield from self.insert_dc()
        break
      except PlugLost:
        if k == 2:
          raise RuntimeError("dc plug keeps slipping out")
        self.say("dc plug lost in transport, regrip harder")
        self.g_dc -= 0.01
        yield from self.grip_to(G_OPEN, 0.05)
        yield from self.opened(G_OPEN)
        yield from self.move_q(HOME, 2.0)
        yield from self.wait(0.4)
        p = (yield from self.look(("dc",)))["dc"]
    yield from self.pick_hdr()
    yield from self.insert_hdr()
    yield from self.run_test()
    yield from self.unplug_dc()
    yield from self.unplug_hdr()
    yield from self.move_q(HOME, 2.0)
    yield from self.fresh()                          # the camera is still live at the end of the cycle
    yield from self.wait(0.3)


# ====================================================================================================== perception
class Cam:
  """Pinhole model of a MuJoCo camera (image row 0 at the top)."""

  def __init__(self, pos, R, fovy_deg, w, h):
    self.p, self.R, self.w, self.h = np.asarray(pos, float), np.asarray(R, float), w, h
    self.f = (h / 2) / math.tan(math.radians(fovy_deg) / 2)

  def project(self, pts):
    pc = (np.atleast_2d(pts) - self.p) @ self.R
    u = self.w / 2 + self.f * pc[:, 0] / (-pc[:, 2]) - 0.5
    v = self.h / 2 - self.f * pc[:, 1] / (-pc[:, 2]) - 0.5
    return np.stack([u, v], 1)

  def ray(self, u, v):
    d = np.stack([(np.asarray(u, float) + 0.5 - self.w / 2) / self.f, -(np.asarray(v, float) + 0.5 - self.h / 2) / self.f,
                  -np.ones_like(np.asarray(u, float))], -1)
    return d @ self.R.T

  def to_plane(self, u, v, z):
    r = self.ray(u, v)
    s = (z - self.p[2]) / r[..., 2]
    return self.p + r * s[..., None]


def hull(pts):
  """Convex hull (monotone chain) of 2-D points, counter-clockwise."""
  pts = sorted(set(map(tuple, np.asarray(pts, float))))
  if len(pts) < 3:
    return np.array(pts)
  def cross(o, a, b):
    return (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0])
  lower, upper = [], []
  for p in pts:
    while len(lower) >= 2 and cross(lower[-2], lower[-1], p) <= 0:
      lower.pop()
    lower.append(p)
  for p in reversed(pts):
    while len(upper) >= 2 and cross(upper[-2], upper[-1], p) <= 0:
      upper.pop()
    upper.append(p)
  return np.array(lower[:-1] + upper[:-1])


def poly_moments(P):
  """Area, centroid and central second moments of a simple polygon (vertices CCW)."""
  x, y = P[:, 0], P[:, 1]
  x1, y1 = np.roll(x, -1), np.roll(y, -1)
  c = x * y1 - x1 * y
  A = c.sum() / 2
  cx = ((x + x1) * c).sum() / (6 * A)
  cy = ((y + y1) * c).sum() / (6 * A)
  Ixx = ((x * x + x * x1 + x1 * x1) * c).sum() / 12 - A * cx * cx
  Iyy = ((y * y + y * y1 + y1 * y1) * c).sum() / 12 - A * cy * cy
  Ixy = ((x * y1 + 2 * x * y + 2 * x1 * y1 + x1 * y) * c).sum() / 24 - A * cx * cy
  return A, np.array([cx, cy]), Ixx, Iyy, Ixy


BOARD_TH = (35, 25)
BOARD_K = 1


def box_mean(a, k):
  """Mean over a (2k+1)^2 window, edge-padded."""
  n = 2 * k + 1
  p = np.pad(np.pad(a, k, mode="edge").cumsum(0).cumsum(1), ((1, 0), (1, 0)))
  return (p[n:, n:] - p[:-n, n:] - p[n:, :-n] + p[:-n, :-n]) / (n * n)


def blobs(mask, min_px=4):
  """Connected components (4-neighbour) of a boolean mask: list of (rows, cols) arrays, largest first."""
  h, w = mask.shape
  lab = np.zeros((h, w), np.int32)
  out = []
  ys, xs = np.nonzero(mask)
  nxt = 1
  for y0, x0 in zip(ys, xs):
    if lab[y0, x0]:
      continue
    stack = [(y0, x0)]
    lab[y0, x0] = nxt
    pr, pc = [], []
    while stack:
      y, x = stack.pop()
      pr.append(y); pc.append(x)
      for yy, xx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
        if 0 <= yy < h and 0 <= xx < w and mask[yy, xx] and not lab[yy, xx]:
          lab[yy, xx] = nxt
          stack.append((yy, xx))
    if len(pr) >= min_px:
      out.append((np.array(pr), np.array(pc)))
    nxt += 1
  out.sort(key=lambda b: -len(b[0]))
  return out


class Overhead:
  """Layout from the overhead camera: register on the cable clamp bar, then board, plugs, shroud."""

  BAR = (0.31, 0.35, 0.24, 0.024)        # front x, back x, half length, top z of the harness clamp bar

  def __init__(self, cam: Cam):
    self.cam = cam
    self.shift = np.zeros(2)

  @staticmethod
  def hsv(img):
    f = img.astype(np.float32)
    mx, mn = f.max(2), f.min(2)
    return f, mx, mn

  def register(self, img):
    """Overhead camera mount error from the three white discs on the duct cover: fit the camera's position offset
    and its tilt about the image x axis (a plain image shift would carry the discs' parallax onto the fixture)."""
    f, mx, mn = self.hsv(img)
    white = mn > 150
    obs, pts = [], []
    for xy in TARGETS_XY:
      P = np.array([xy[0], xy[1], TARGET_Z])
      u, v = self.cam.project(P[None])[0]
      r0, c0 = int(round(v)) - 14, int(round(u)) - 14
      win = white[max(0, r0):r0 + 29, max(0, c0):c0 + 29]
      # the disc: a compact blob clear of the window edge (bright floor tiles above the duct can reach into it)
      bl = [b for b in blobs(win, 30) if b[0].min() > 0 and b[1].min() > 0
            and b[0].max() < win.shape[0] - 1 and b[1].max() < win.shape[1] - 1 and len(b[0]) < 200]
      if not bl:
        continue
      rr, cc = min(bl, key=lambda b: (b[0].mean() - 14) ** 2 + (b[1].mean() - 14) ** 2)
      obs.append((cc.mean() + max(0, c0), rr.mean() + max(0, r0)))
      pts.append(P)
    if len(obs) < 2:
      return False
    obs, pts = np.array(obs), np.array(pts)
    p0, R0 = self.cam.p.copy(), self.cam.R.copy()

    def model(x):
      c, s_ = math.cos(x[3]), math.sin(x[3])
      k = Cam.__new__(Cam)
      k.p, k.R, k.f, k.w, k.h = p0 + x[:3], R0 @ np.array([[1, 0, 0], [0, c, -s_], [0, s_, c]]), self.cam.f, self.cam.w, self.cam.h
      return k

    x = np.zeros(4)
    for _ in range(6):
      r = (model(x).project(pts) - obs).ravel()
      J = np.zeros((r.size, 4))
      for i, h in enumerate((1e-4, 1e-4, 1e-4, 1e-4)):
        dx = np.zeros(4); dx[i] = h
        J[:, i] = ((model(x + dx).project(pts) - obs).ravel() - r) / h
      # damped: the discs are in a row, so the offset along the camera axis is held near zero unless needed
      x = x - np.linalg.solve(J.T @ J + np.diag([1e-2, 1e-2, 1e-1, 1e-2]) * 1e3, J.T @ r)
    self.cam = model(x)
    self.shift = np.zeros(2)
    return True

  def px_to_world(self, rows, cols, z):
    u = np.asarray(cols, float) - self.shift[0]
    v = np.asarray(rows, float) - self.shift[1]
    return self.cam.to_plane(u, v, z)

  def board(self, img):
    """Board centre (x, y) and yaw from the green PCB's convex hull.

    Find the board on a 5x5-smoothed green mask (sensor noise speckles the raw one), then take the
    raw green pixels near that blob, hull them, and read yaw from the hull edges modulo 90 degrees."""
    f, mx, mn = self.hsv(img)
    s = np.stack([box_mean(f[..., i], 2) for i in range(3)], -1)
    g = (s[..., 1] > s[..., 0] + 35) & (s[..., 1] > s[..., 2] + 25)
    bl = blobs(g, 50)
    if not bl:
      return None
    core = np.zeros(g.shape, np.float32)
    core[bl[0]] = 1.0
    near = box_mean(core, 3) > 0
    k = BOARD_K
    s1 = np.stack([box_mean(f[..., i], k) for i in range(3)], -1) if k else f
    r, cpx = np.nonzero(near & (s1[..., 1] > s1[..., 0] + BOARD_TH[0]) & (s1[..., 1] > s1[..., 2] + BOARD_TH[1]))
    # hull on pixel corners, so the polygon covers whole pixels
    pts = np.concatenate([np.stack([cpx + dx, r + dy], 1) for dx in (-0.5, 0.5) for dy in (-0.5, 0.5)])
    H = hull(pts)
    W = self.px_to_world(H[:, 1], H[:, 0], 0.0136)[:, :2]
    if poly_moments(W)[0] < 0:
      W = W[::-1]
    A, cxy, Ixx, Iyy, Ixy = poly_moments(W)
    e = np.roll(W, -1, 0) - W
    ln = np.hypot(e[:, 0], e[:, 1])
    a4 = 4 * np.arctan2(e[:, 1], e[:, 0])
    yaw = 0.25 * math.atan2((ln * np.sin(a4)).sum(), (ln * np.cos(a4)).sum())   # in (-45, 45] degrees
    return np.array([cxy[0], cxy[1], yaw]), A

  def cream(self, f, mx, mn):
    """Top faces of the cream nylon parts (sides are darker and left out)."""
    return (f[..., 0] > 195) & (f[..., 0] - f[..., 2] > 18) & (f[..., 1] - f[..., 2] > 12)

  def shroud(self, img, board):
    """Header shroud position along the board (board-frame x) from the bright, non-green pixels in its band."""
    f, mx, mn = self.hsv(img)
    m = (f[..., 0] > 150) & (f[..., 1] > 140) & (f[..., 1] < f[..., 0] + 10)
    r, cc = np.nonzero(m)
    if len(r) == 0:
      return None
    P = self.px_to_world(r, cc, 0.0136 + 0.004)[:, :2]
    c, s_ = math.cos(board[2]), math.sin(board[2])
    loc = (P - board[:2]) @ np.array([[c, -s_], [s_, c]])
    sel = (np.abs(loc[:, 1] - SHROUD[1]) < 0.0055) & (np.abs(loc[:, 0]) < 0.026)
    if sel.sum() < 5:
      return None
    xs = loc[sel, 0]
    # trim to the 13 mm window around the median (shroud outer width 12 mm)
    med = float(np.median(xs))
    xs = xs[np.abs(xs - med) < 0.0065]
    sx0 = float(xs.mean())
    # refine: coverage-weighted centroid of the shroud's top in a window around the rough position (sub-pixel; the
    # edge pixels count by how much of them the cream top covers)
    w0 = board[:2] + np.array([[c, -s_], [s_, c]]) @ np.array([sx0, SHROUD[1]])
    u, v = self.cam.project(np.array([[w0[0], w0[1], SHROUD_TOP_Z]]))[0]
    u, v = u + self.shift[0], v + self.shift[1]
    hw = 9
    r0, c0 = int(round(v)) - hw, int(round(u)) - hw
    if r0 < 0 or c0 < 0 or r0 + 2 * hw + 1 > img.shape[0] or c0 + 2 * hw + 1 > img.shape[1]:
      return sx0
    ch = f[r0:r0 + 2 * hw + 1, c0:c0 + 2 * hw + 1, 0]
    bg, fg = np.percentile(ch, 20), np.percentile(ch, 92)
    wgt = np.clip((ch - bg) / max(fg - bg, 1.0), 0.0, 1.0)
    rr, cc = np.mgrid[0:ch.shape[0], 0:ch.shape[1]]
    vr = (wgt * rr).sum() / wgt.sum() + r0
    uc = (wgt * cc).sum() / wgt.sum() + c0
    W = self.px_to_world(np.array([vr]), np.array([uc]), SHROUD_TOP_Z)[0, :2]
    return float(np.array([c, s_]) @ (W - board[:2]))

  def dc_plug(self, img, board=None, avoid=None):
    """DC plug housing centre and barrel-direction yaw. The yellow band (6 mm from the housing centre toward the
    barrel) anchors it; the dark housing pixels near the band give the axis."""
    f, mx, mn = self.hsv(img)
    dark = mx < 75
    yel = (f[..., 0] > 120) & (f[..., 1] > 100) & (f[..., 2] < 0.55 * f[..., 1])
    best = None
    for r, cc in blobs(yel, 2):
      B = self.px_to_world(r, cc, 0.009)[:, :2].mean(0)
      if not (0.12 < B[0] < 0.32 and -0.30 < B[1] < 0.30):
        continue
      if avoid is not None and np.linalg.norm(B - avoid) < 0.045:
        continue                                  # the yellow marks on the gripper
      if board is not None:
        cb, sb = math.cos(board[2]), math.sin(board[2])
        loc = np.array([[cb, sb], [-sb, cb]]) @ (B - board[:2])
        if abs(loc[0]) < 0.07 and abs(loc[1]) < 0.05:
          continue
      dr, dc = np.nonzero(dark)
      D = self.px_to_world(dr, dc, 0.009)[:, :2]
      near = np.linalg.norm(D - B, axis=1) < 0.017
      if near.sum() < 6:
        continue
      P = D[near]
      ctr = P.mean(0)
      ext = P - ctr
      ev, evec = np.linalg.eigh(ext.T @ ext / len(P))
      axis = evec[:, 1]
      if (B - ctr) @ axis < 0:
        axis = -axis
      score = -near.sum()
      if best is None or score < best[0]:
        best = (score, B, axis)
    if best is None:
      return None
    _, B, axis = best
    c = B - axis * 0.006
    return np.array([c[0], c[1], math.atan2(axis[1], axis[0])])

  def hdr_plug(self, img, near=None):
    """Header plug top centre and yaw of its +x axis (latch side +y from the red half of the top)."""
    f, mx, mn = self.hsv(img)
    cr = self.cream(f, mx, mn)
    red = (f[..., 0] > 140) & (f[..., 1] < 0.45 * f[..., 0]) & (f[..., 2] < 0.45 * f[..., 0])
    m = cr | red
    best = None
    for r, cc in blobs(m, 4):
      P = self.px_to_world(r, cc, 0.0201)[:, :2]
      ctr = P.mean(0)
      if near is not None and np.linalg.norm(ctr - near) > 0.05:
        continue
      if not (0.10 < ctr[0] < 0.30 and ctr[1] < -0.06):
        continue
      if len(r) > 200:
        continue
      if best is None or len(r) > best[0]:
        best = (len(r), ctr, r, cc, P)
    if best is None:
      return None
    _, ctr, r, cc, P = best
    isred = red[r, cc]
    ext = P - ctr
    ev, evec = np.linalg.eigh(ext.T @ ext / len(P))
    xax = evec[:, 1]
    if isred.sum() >= 2 and (~isred).sum() >= 2:
      d = P[isred].mean(0) - P[~isred].mean(0)        # toward +y (latch side)
      yd = d / (np.linalg.norm(d) + 1e-9)
      x2 = np.array([yd[1], -yd[0]])
      if x2 @ xax < 0:
        xax = -xax
      xax = xax + x2
      xax /= np.linalg.norm(xax)
    return np.array([ctr[0], ctr[1], math.atan2(xax[1], xax[0])])

  def holder(self, img, board=None):
    """Parking socket (blue block): centre and yaw of its long (x) side from the hull of its top face."""
    f, mx, mn = self.hsv(img)
    msk = (f[..., 2] > f[..., 0] + 35) & (f[..., 2] > f[..., 1] + 15) & (f[..., 2] > 60)
    best = None
    for r, cc in blobs(msk, 20):
      P = self.px_to_world(r, cc, HOLDER_TOP)[:, :2]
      ctr = P.mean(0)
      if not (0.09 < ctr[0] < 0.25 and ctr[1] < -0.05):
        continue
      if board is not None and np.linalg.norm(ctr - board[:2]) < 0.05:
        continue
      if best is None or len(r) > len(best[0]):
        best = (r, cc)
    if best is None:
      return None
    r, cc = best
    lum = f[r, cc].sum(1)
    top = lum > 0.8 * np.percentile(lum, 90)          # the lit top face; the shaded side faces are left out
    r, cc = r[top], cc[top]
    pts = np.concatenate([np.stack([cc + dx, r + dy], 1) for dx in (-0.5, 0.5) for dy in (-0.5, 0.5)])
    H = hull(pts)
    W = self.px_to_world(H[:, 1], H[:, 0], HOLDER_TOP)[:, :2]
    pose = self._pose_of(W)
    # yaw from the hull's edge directions (modulo 90 degrees, length weighted): steadier than the moments of a
    # nearly square outline
    e = np.roll(W, -1, axis=0) - W
    ln = np.linalg.norm(e, axis=1)
    a4 = 4 * np.arctan2(e[:, 1], e[:, 0])
    pose[2] = wrap(math.atan2((ln * np.sin(a4)).sum(), (ln * np.cos(a4)).sum()) / 4)
    return pose

  @staticmethod
  def _pose_of(W):
    if poly_moments(W)[0] < 0:
      W = W[::-1]
    A, cxy, Ixx, Iyy, Ixy = poly_moments(W)
    ang = 0.5 * math.atan2(2 * Ixy, Ixx - Iyy)
    if ang > math.pi / 2:
      ang -= math.pi
    return np.array([cxy[0], cxy[1], ang])

  def _silhouette(self, pose):
    hx, hy = HOLDER_HALF
    R = rotz(pose[2])
    corners = [np.array([pose[0], pose[1], z]) + R @ np.array([sx * hx, sy * hy, 0.0])
               for z in (0.0, HOLDER_TOP) for sx in (-1, 1) for sy in (-1, 1)]
    uv = self.cam.project(np.array(corners))
    H = hull(uv)
    return self.cam.to_plane(H[:, 0], H[:, 1], HOLDER_TOP)[:, :2]