File size: 63,851 Bytes
fa01d00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
"""KT-8 kitting controller (reference).

Reads the pick list (substitutions included), checks the camera against the bench dots and the arm height against
the camera, finds the tote, the tray and the pieces in the overhead RGB-D image, tells the look-alikes apart by size
and shape (sleeve length, washer diameter, which hand a bracket is), moves a nut that lies on a piece it needs,
takes each piece from above with a grasp whose fingers clear its neighbours, places it in its pocket from a fresh
fix of the tray, checks the seat in the image, and puts right a piece that slipped back, a tray that was nudged and
a piece that popped out of its pocket. Answers a dead gripper or a frozen camera with a set-down and an abort.
"""
import math
import os
import re
import sys

import mujoco
import numpy as np

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
try:
  import picklist as P
except Exception:  # pragma: no cover
  sys.path.insert(0, "/app")
  import picklist as P

# ---- options (variants of this controller flip these) ----
OPT = {
    "handle_upsets": True,      # check the seat after placing, re-fix the tray before placing, retry a lost piece
                                # (False: the tray from the first look only, a placed or lost line taken as done)
    "handle_faults": True,      # gripper and camera fault detection
    "subs": True,               # apply the substitutions of the note column
    "stale_drawing": False,     # use the pocket table of drawing rev B
    "move_covers": True,        # move a nut lying on a piece before taking the piece
    "stop_after": -1,           # hold still for good after this many lines (-1: never)
    "easy_first": False,        # do the lines whose piece lies free first (for "easy stages then hold")
    "idle": False,              # do nothing at all
    "grab_hold": False,         # take the first piece and hold it for good
    "look_only": False,         # dev: look once, report, stop
    "press": False,             # push each piece down onto the pocket floor before letting go
    "ignore_covers": False,     # take a piece whether or not something lies on it
}

# ---- cell data (CELL_SHEET.md, PARTS_SHEET.md, TRAY_DRAWING.md) ----
BENCH_DOTS = np.array(((0.26, 0.37), (0.76, 0.37), (0.76, -0.40)))
TOTE_IN = (0.125, 0.095)
FLOOR_Z = 0.006                   # tote floor and pocket floors
RIB_Z = 0.012
POCKETS = {k: v for k, v in P.POCKETS.items()}
REV_B = {"A2": (0.052, 0.031), "B2": (-0.052, 0.026)}      # drawing rev B (stale table) for the two washer pockets
TRAY_DOTS = np.array(P.TRAY_DOTS)
GRIP_K = 3500.0
TOP_BIAS = -0.0076                # the camera sees the arm's top this much below the highest mesh point (from T0 runs)
TRANSIT_Z = 0.150
TUCK = np.array([0.0, -1.3, 0.0, -2.9, 0.0, 1.6, 0.785])
Q_PREF = np.array([0.0, -0.3, 0.0, -2.2, 0.0, 1.95, 0.785])
# per family: half grasp width, tcp height above the support at the grasp, squeeze per finger (N), piece height
GRASP = {
    "sleeve": (P.SLEEVE_R, 0.0105, 10.0, 2 * P.SLEEVE_R),
    "bar": (P.BAR[1], 0.0105, 9.0, P.BAR[2]),
    "washer": (None, 0.0110, 10.0, P.WASHER_T),
    "nut": (P.NUT_R, 0.0110, 10.0, P.NUT_H),
    "block": (P.BLOCK[0], 0.0120, 18.0, P.BLOCK[2]),
    "bracket": (0.002, 0.0160, 9.0, P.BR_T + P.BR_TAB[4]),
}
FAMILY = {pn: f for pn, (f, _d, _b) in {**P.PARTS, **P.CLUTTER}.items()}
HEIGHT = {pn: P.height_of(pn) for pn in FAMILY}


def cross3(a, b):
  return np.array([a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]])


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


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


def wrap_half(a):
  return (a + math.pi / 2) % math.pi - math.pi / 2


TRUTH = None                      # dev runs only (tools/dev_run.py): the cell process, for the log


def truth_note(xy):
  """Dev log only: the true piece nearest xy, its yaw and offset."""
  if TRUTH is None:
    return ""
  pr = TRUTH.get("proc")
  if pr is None:
    return ""
  d = pr._d
  best = min(pr.ib, key=lambda b: float(np.linalg.norm(d.xpos[pr.ib[b]][:2] - xy)))
  R = d.xmat[pr.ib[best]].reshape(3, 3)
  return f"| truth {best} off_mm={np.round(1000 * (d.xpos[pr.ib[best]][:2] - xy), 1)} yaw={math.atan2(R[1, 0], R[0, 0]):.3f} z={d.xpos[pr.ib[best]][2]:.4f}"


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


class Lost(Exception):
  pass


class Controller:
  def __init__(self, info):
    self.info = info
    self.dt = float(info["control_dt_s"])
    self.m = mujoco.MjModel.from_xml_path(info.get("scene_xml", "/app/scene.xml"))
    self.m.opt.disableflags |= int(mujoco.mjtDisableBit.mjDSBL_CONTACT)
    self.d = mujoco.MjData(self.m)
    jn = list(info["joint_names"])
    self.arm_obs = [jn.index(f"robot/joint{i}") for i in range(1, 8)]
    self.fin_obs = [jn.index("robot/finger_joint1"), jn.index("robot/finger_joint2")]
    self.qadr = [int(self.m.jnt_qposadr[self.m.joint(f"robot/joint{i}").id]) for i in range(1, 8)]
    self.vadr = [int(self.m.jnt_dofadr[self.m.joint(f"robot/joint{i}").id]) for i in range(1, 8)]
    self.jlo = np.array([self.m.jnt_range[self.m.joint(f"robot/joint{i}").id, 0] for i in range(1, 8)]) + 0.06
    self.jhi = np.array([self.m.jnt_range[self.m.joint(f"robot/joint{i}").id, 1] for i in range(1, 8)]) - 0.06
    self.kp = np.array([float(self.m.actuator_gainprm[a, 0]) for a in range(7)])
    self.site = self.m.site("robot/tcp").id
    self.nu = len(info["actuator_names"])
    cam = [c for c in info["cameras"] if c["name"] == "overhead"][0]
    self.W, self.Hh = int(cam["width"]), int(cam["height"])
    self.f = (self.Hh / 2) / math.tan(math.radians(cam["fovy_deg"]) / 2)
    cid = self.m.camera("overhead").id
    self.cam_pos = self.m.cam_pos[cid].copy()
    u = (np.arange(self.W) + 0.5 - self.W / 2) / self.f
    v = (np.arange(self.Hh) + 0.5 - self.Hh / 2) / self.f
    self.uu, self.vv = np.meshgrid(u, v)
    self.period = 1.0 / float(info.get("perception_hz", 1.0))
    rb = [g for g in range(self.m.ngeom) if (self.m.body(int(self.m.geom_bodyid[g])).name or "").startswith("robot/")
          and int(self.m.geom_type[g]) == int(mujoco.mjtGeom.mjGEOM_MESH) and int(self.m.geom_group[g]) <= 2]
    self.vis_geoms = rb
    self.gen = None

  # ------------------------------------------------------------------ protocol
  def reset(self, obs):
    self.obs = obs
    self.t = float(obs["time"])
    q = np.asarray(obs["qpos"], float)
    self.q_cmd = q[self.arm_obs].copy()
    self.g_cmd = 0.04
    self.jams = []
    self.dz = 0.0
    self.fin_hist = []
    self.fin_cal = []
    self.fin_bias = 0.0
    self.last_stamp = None
    self.stamp_change_t = self.t
    self.tick_changes = 0
    self.frozen = False
    self.holding = None
    self.in_abort = False
    self.reg = (np.eye(2), np.zeros(2))
    self.plane = np.zeros(3)
    self.tray = None
    self.tote = None
    self.w = None
    self.plan_dest = None
    self.done_lines = set()
    self.moved_to = []
    self.text = str((obs.get("io") or {}).get("pick_list", ""))
    self.limit = float((obs.get("io") or {}).get("cycle_limit_s", 200.0))
    self.gen = self.main()
    self.final = None

  def act(self, obs):
    self.obs = obs
    self.t = float(obs["time"])
    self._ingest(obs)
    if self.final is not None:
      return self.final
    try:
      next(self.gen)
    except StopIteration as e:
      self.final = e.value if isinstance(e.value, dict) else {"status": "done"}
      return self.final
    except Exception as e:  # never raise: hold still and stop
      self.say("error", repr(e))
      import traceback
      if os.environ.get("KT8_DEBUG"):
        traceback.print_exc()
      self.final = {"status": "done"}
      return self.final
    return self.command()

  def say(self, *a):
    if os.environ.get("KT8_DEBUG"):
      print(f"[{self.t:7.2f}]", *a, file=sys.stderr, flush=True)

  def command(self):
    out = np.zeros(self.nu)
    out[:7] = self.q_cmd + self.grav(self.q_cmd) / self.kp
    out[7] = self.g_cmd
    return out

  def _ingest(self, obs):
    q = np.asarray(obs["qpos"], float)
    self.q_meas = q[self.arm_obs]
    fr = float(np.mean(q[self.fin_obs]))
    if self.t < 1.5:                                 # the gripper starts open at its stop: the reading there is the offset
      self.fin_cal.append(fr - 0.04)
      self.fin_bias = float(np.mean(self.fin_cal))
    self.fin_hist.append(fr - self.fin_bias)
    self.fin_hist = self.fin_hist[-12:]
    st = obs.get("camera_stamp")
    if st is not None:
      if self.last_stamp is None or st != self.last_stamp:
        self.tick_changes = self.tick_changes + 1 if (self.last_stamp is not None and self.t - self.stamp_change_t < 1.5 * self.dt) else 0
        self.stamp_change_t = self.t
        self.last_stamp = st
      if OPT["handle_faults"] and self.t > 3.0:
        if self.tick_changes >= 4 or self.t - float(st) > 3.0 * self.period + 0.3:
          self.frozen = True

  def fin(self, n=5):
    return float(np.mean(self.fin_hist[-n:]))

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

  def grav(self, q):
    d = self.d
    d.qpos[self.qadr] = q
    d.qvel[:] = 0
    mujoco.mj_forward(self.m, d)
    return d.qfrc_bias[self.vadr].copy()

  def ik(self, pos, yaw, q0, iters=3):
    """Top-down pose: tcp at pos (robot frame), finger axis at angle yaw about the vertical."""
    m, d = self.m, self.d
    q = np.array(q0, float)
    yv = np.array([math.cos(yaw), math.sin(yaw), 0.0])
    zv = np.array([0.0, 0.0, -1.0])
    xv = cross3(yv, zv)
    jp, jr = np.zeros((3, m.nv)), np.zeros((3, m.nv))
    for _ in range(iters):
      d.qpos[self.qadr] = q
      mujoco.mj_kinematics(m, d)
      mujoco.mj_comPos(m, d)
      p = d.site_xpos[self.site]
      r = d.site_xmat[self.site].reshape(3, 3)
      e = np.zeros(6)
      e[:3] = pos - p
      e[3:] = 0.5 * (cross3(r[:, 0], xv) + cross3(r[:, 1], yv) + cross3(r[:, 2], zv))
      mujoco.mj_jacSite(m, d, jp, jr, self.site)
      J = np.vstack([jp[:, self.vadr], jr[:, self.vadr]])
      JJ = J @ J.T + 1e-4 * np.eye(6)
      dq = J.T @ np.linalg.solve(JJ, e)
      null = (np.eye(7) - J.T @ np.linalg.solve(JJ, J)) @ (0.08 * (Q_PREF - q))
      q = np.clip(q + dq + null, self.jlo, self.jhi)
    return q

  def tcp_cmd(self):
    p, r = self.fk(self.q_cmd)
    return p, math.atan2(r[1, 1], r[0, 1])

  def reachable(self, pos, yaw):
    """Whether a top-down pose at pos with finger axis yaw (exact, not modulo pi) solves within the joint limits."""
    q = self.ik(np.array(pos) + np.array([0, 0, self.dz]), yaw, self.q_cmd, iters=60)
    p, r = self.fk(q)
    y = math.atan2(r[1, 1], r[0, 1])
    return float(np.linalg.norm(p - np.array(pos) - np.array([0, 0, self.dz]))) < 0.003 and abs(wrap_pi(y - yaw)) < 0.03

  def yaw_choice(self, pos, yaw, exact, q_from=None, y_from=None):
    """The finger yaw to turn to for a pose at pos (cell coordinates): yaw, or yaw + pi unless exact, taken the
    shorter way round unless that runs the last wrist joint into its stop. Returns (yaw, end joints or None)."""
    q_from = self.q_cmd if q_from is None else q_from
    if y_from is None:
      r = self.fk(q_from)[1]
      y_from = math.atan2(r[1, 1], r[0, 1])
    if not hasattr(self, "s7"):
      qa = self.ik(self.fk(q_from)[0], y_from + 0.05, q_from, iters=30)
      self.s7 = -1.0 if qa[6] < q_from[6] else 1.0
    step = 2 * math.pi if exact else math.pi
    base = y_from + wrap_pi(yaw - y_from)
    if not exact and abs(wrap_pi(yaw + math.pi - y_from)) < abs(base - y_from):
      base = y_from + wrap_pi(yaw + math.pi - y_from)
    cands = sorted((base + k * step for k in range(-2, 3)), key=lambda c: abs(c - y_from))
    tgt = np.array(pos, float) + np.array([0.0, 0.0, self.dz])
    p_from = self.fk(q_from)[0]
    turn_base = math.atan2(tgt[1], tgt[0]) - math.atan2(p_from[1], p_from[0])
    for c in cands:
      if abs(c - y_from) > 2 * math.pi - 0.3:
        break
      seed = q_from.copy()
      seed[0] = q_from[0] + turn_base
      seed[6] = q_from[6] + self.s7 * (c - y_from - turn_base)
      if not (self.jlo[6] < seed[6] < self.jhi[6]):
        continue
      seed = np.clip(seed, self.jlo, self.jhi)
      q = self.ik(tgt, c, seed, iters=60)
      pe, re = self.fk(q)
      ye = math.atan2(re[1, 1], re[0, 1])
      if float(np.linalg.norm(pe - tgt)) < 0.003 and abs(wrap_pi(ye - c)) < 0.03 and min(q[6] - self.jlo[6], self.jhi[6] - q[6]) > 0.02:
        return c, q
    return base, None

  # ------------------------------------------------------------------ motion primitives (generators)
  def tick(self):
    if self.frozen and OPT["handle_faults"] and not self.in_abort:
      raise Abort("perception_freeze")
    yield

  def wait(self, s):
    for _ in range(max(1, int(round(s / self.dt)))):
      yield from self.tick()

  def go(self, pos, yaw=None, v=0.30, w=1.6, exact=False):
    """Straight line of the tcp to pos (cell coordinates; the height offset of the arm is added here). The finger
    axis turns to yaw, or to yaw + pi when that is nearer, unless exact."""
    p0, y0 = self.tcp_cmd()
    p1 = np.array(pos, float) + np.array([0.0, 0.0, self.dz])
    if yaw is None:
      y1 = y0
    else:
      y1, _q = self.yaw_choice(pos, yaw, exact)
      if os.environ.get("KT8_YDBG") and abs(y1 - y0) > 0.2 and pos[2] < 0.06:
        self.say("low turn", round(y0, 3), "->", round(y1, 3), "asked", round(yaw, 3), exact, np.round(pos, 4))
    dist = float(np.linalg.norm(p1 - p0))
    T = max(1.6 * dist / v, 1.6 * abs(y1 - y0) / w, 0.24)
    n = max(2, int(math.ceil(T / self.dt)))
    k = 0.0
    while k < n:
      step = 1.0
      while True:
        s = min(1.0, (k + step) / n)
        a = 3 * s * s - 2 * s ** 3
        q = self.ik(p0 + a * (p1 - p0), y0 + a * (y1 - y0), self.q_cmd)
        if float(np.max(np.abs(q - self.q_cmd))) <= 0.03 or step < 0.1:
          break
        step *= 0.5
      dq = np.clip(q - self.q_cmd, -0.04, 0.04)
      self.q_cmd = self.q_cmd + dq
      k += step
      yield from self.tick()
    for _ in range(40):
      q = self.ik(p1, y1, self.q_cmd)
      dq = np.clip(q - self.q_cmd, -0.02, 0.02)
      if float(np.max(np.abs(dq))) < 2e-4:
        break
      self.q_cmd = self.q_cmd + dq
      yield from self.tick()

  def joint_go(self, q1, speed=1.1):
    q0 = self.q_cmd.copy()
    T = max(0.3, 1.7 * float(np.max(np.abs(q1 - q0))) / speed)
    n = max(2, int(math.ceil(T / self.dt)))
    for k in range(1, n + 1):
      s = k / n
      a = 3 * s * s - 2 * s ** 3
      self.q_cmd = q0 + a * (q1 - q0)
      yield from self.tick()

  def grip(self, g, wait=0.35):
    self.g_cmd = float(np.clip(g, 0.0, 0.04))
    yield from self.wait(wait)

  def up(self, z=TRANSIT_Z, v=0.30):
    p, _ = self.tcp_cmd()
    if p[2] - self.dz < z - 0.005:
      yield from self.go((p[0], p[1], z), v=v)

  def to_tuck(self):
    yield from self.up()
    yield from self.joint_go(TUCK, speed=1.4 if self.holding is not None else 2.4)

  def over(self, xy, yaw, exact=False):
    """From anywhere to transit height over xy (from the tuck in one joint move)."""
    if float(np.max(np.abs(self.q_cmd - TUCK))) < 0.05:
      q_mid = self.ik(np.array([0.36, 0.0, TRANSIT_Z + self.dz]), 0.0, Q_PREF, iters=60)
      _y, q = self.yaw_choice((xy[0], xy[1], TRANSIT_Z + 0.03), yaw, exact, q_from=q_mid, y_from=0.0)
      yield from self.joint_go(q if q is not None else q_mid, speed=1.4 if self.holding is not None else 2.4)
    yield from self.up()
    yield from self.go((xy[0], xy[1], TRANSIT_Z), yaw, v=0.6, exact=exact)

  # ------------------------------------------------------------------ perception
  def frame(self):
    """(rgb, depth) of the current frame, or the average of the frames taken by `frames`."""
    if getattr(self, "avg", None) is not None:
      return self.avg
    return self.obs["images"]["overhead"].astype(np.float64), self.obs["depth"]["overhead"].astype(np.float64)

  def frames(self, n):
    """Averages n fresh frames (depth only where every frame has a reading)."""
    self.avg = None
    rs, ds = [], []
    for k in range(n):
      yield from self.fresh_frame()
      rs.append(self.obs["images"]["overhead"].astype(np.float64))
      ds.append(self.obs["depth"]["overhead"].astype(np.float64))
    D = np.stack(ds)
    good = D > 0.05
    cnt = good.sum(0)
    dep = np.where(cnt > 0, (D * good).sum(0) / np.maximum(cnt, 1), 0.0)
    self.avg = (np.mean(rs, 0), dep)

  def cloud(self):
    dep = self.frame()[1]
    ok = dep > 0.05
    x = self.cam_pos[0] - self.vv * dep
    y = self.cam_pos[1] - self.uu * dep
    z = self.cam_pos[2] - dep
    A, t = self.reg
    xr = A[0, 0] * x + A[0, 1] * y + t[0]
    yr = A[1, 0] * x + A[1, 1] * y + t[1]
    return xr, yr, z, ok

  def fresh_frame(self, margin=0.06):
    """Waits for an image taken after now."""
    t0 = self.t + margin
    while True:
      st = self.obs.get("camera_stamp")
      if st is not None and float(st) >= t0:
        return
      yield from self.tick()

  @staticmethod
  def label(mask, min_px=6):
    """Connected components of a boolean image (8-neighbour): list of (rows, cols)."""
    out = []
    todo = mask.copy()
    hh, ww = mask.shape
    ys, xs = np.nonzero(todo)
    for y0, x0 in zip(ys, xs):
      if not todo[y0, x0]:
        continue
      stack = [(y0, x0)]
      todo[y0, x0] = False
      comp = []
      while stack:
        y, x = stack.pop()
        comp.append((y, x))
        for yy in (y - 1, y, y + 1):
          for xx in (x - 1, x, x + 1):
            if 0 <= yy < hh and 0 <= xx < ww and todo[yy, xx]:
              todo[yy, xx] = False
              stack.append((yy, xx))
      if len(comp) >= min_px:
        a = np.array(comp)
        out.append((a[:, 0], a[:, 1]))
    return out

  @staticmethod
  def median3(a):
    p = np.pad(a, 1, mode="edge")
    st = np.stack([p[i:i + a.shape[0], j:j + a.shape[1]] for i in range(3) for j in range(3)])
    return np.median(st, 0)

  def magenta(self):
    rgb = self.frame()[0]
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    return (r - g > 60) & (b - g > 50)

  def register(self):
    """Camera against the three surveyed bench dots: a 2-D similarity applied to every point."""
    self.reg = (np.eye(2), np.zeros(2))
    x, y, z, ok = self.cloud()
    mag = self.magenta() & ok & (np.abs(z) < 0.008)
    seen = []
    for c in self.label(mag, 5):
      seen.append(np.array([x[c].mean(), y[c].mean()]))
    pairs = []
    for k, dot in enumerate(BENCH_DOTS):
      if not seen:
        break
      j = int(np.argmin([np.linalg.norm(s - dot) for s in seen]))
      if np.linalg.norm(seen[j] - dot) < 0.04:
        pairs.append((seen[j], dot))
    if len(pairs) < 2:
      self.say("register: dots not found", len(pairs))
      return False
    S = np.array([p[0] for p in pairs])
    D = np.array([p[1] for p in pairs])
    ms, md = S.mean(0), D.mean(0)
    Sc, Dc = S - ms, D - md
    H = Sc.T @ Dc
    U, sv, Vt = np.linalg.svd(H)
    R = Vt.T @ U.T
    if np.linalg.det(R) < 0:
      Vt[1] *= -1
      R = Vt.T @ U.T
    sc = float(np.sum(sv) / max(1e-9, np.sum(Sc ** 2)))
    A = sc * R
    t = md - A @ ms
    self.reg = (A, t)
    self.say("register: scale", round(sc, 4), "rot deg", round(math.degrees(math.atan2(R[1, 0], R[0, 0])), 3),
             "shift mm", np.round(1000 * (t + (A - np.eye(2)) @ np.array([0.5, 0.0])), 2))
    return True

  def find_tray(self, x, y, h, ok):
    mag = self.magenta() & ok & (h > 0.008) & (h < 0.024)
    pts = []
    for c in self.label(mag, 4):
      pts.append(np.array([x[c].mean(), y[c].mean()]))
    if len(pts) < 3:
      return None
    best = None
    import itertools
    for tri in itertools.combinations(range(len(pts)), 3):
      Q = [pts[i] for i in tri]
      dd = {(i, j): np.linalg.norm(Q[i] - Q[j]) for i in range(3) for j in range(i + 1, 3)}
      ref = sorted([0.274, 0.184, 0.3301])
      err = sum(abs(a - b) for a, b in zip(sorted(dd.values()), ref))
      if best is None or err < best[0]:
        best = (err, Q)
    err, Q = best
    if err > 0.02:
      return None
    # dot 0 is the one not on the longest side; dot 1 is 0.244 from dot 0
    dd = {(i, j): np.linalg.norm(Q[i] - Q[j]) for i in range(3) for j in range(3) if i != j}
    longest = max(((i, j) for i in range(3) for j in range(i + 1, 3)), key=lambda k: dd[k])
    i0 = [k for k in range(3) if k not in longest][0]
    a, b = longest
    i1, i2 = (a, b) if abs(dd[(i0, a)] - 0.274) < abs(dd[(i0, b)] - 0.274) else (b, a)
    S = np.array([Q[i0], Q[i1], Q[i2]])
    D = TRAY_DOTS
    ms, md = S.mean(0), D.mean(0)
    Hm = (D - md).T @ (S - ms)
    U, _sv, Vt = np.linalg.svd(Hm)
    R = Vt.T @ U.T
    if np.linalg.det(R) < 0:
      Vt[1] *= -1
      R = Vt.T @ U.T
    yaw = math.atan2(R[1, 0], R[0, 0])
    c = ms - R @ md
    return np.array([c[0], c[1], yaw])

  def find_tote(self, x, y, h, ok):
    wall = ok & (h > 0.034) & (h < 0.056) & (y > 0.03) & (x > 0.30) & (x < 0.72)
    px, py = x[wall], y[wall]
    if len(px) < 200:
      return None
    best = None
    for a in np.radians(np.arange(-15, 15.01, 0.5)):
      c, s = math.cos(a), math.sin(a)
      u1, v1 = c * px + s * py, -s * px + c * py
      lo1, hi1, lo2, hi2 = np.percentile(u1, 0.5), np.percentile(u1, 99.5), np.percentile(v1, 0.5), np.percentile(v1, 99.5)
      area = (hi1 - lo1) * (hi2 - lo2)
      if best is None or area < best[0]:
        cu, cv = 0.5 * (lo1 + hi1), 0.5 * (lo2 + hi2)
        best = (area, c * cu - s * cv, s * cu + c * cv, a)
    return np.array(best[1:])

  def tray_to_world(self, p, tray=None):
    tr = self.tray if tray is None else tray
    return tr[:2] + rz2(tr[2]) @ np.asarray(p)

  def world_to_tray(self, w, tray=None):
    tr = self.tray if tray is None else tray
    return rz2(-tr[2]) @ (np.asarray(w) - tr[:2])

  def pocket_xy(self, pk):
    fam, cx, cy, hx, hy = POCKETS[pk]
    if OPT["stale_drawing"] and pk in REV_B:
      cx, cy = REV_B[pk]
    return np.array([cx, cy])

  def see(self):
    """One frame: bench plane, tray and tote poses, height image and pixel classes."""
    x, y, z, ok = self.cloud()
    zf = self.median3(np.where(ok, z, np.nan))
    okf = np.isfinite(zf)
    zf = np.where(okf, zf, 0.0)
    rgb = self.frame()[0]
    # bench plane: pixels near zero height away from the tote and the tray
    bare = okf & (np.abs(zf) < 0.004)
    if self.tray is not None:
      lt = rz2(-self.tray[2]) @ np.stack([x[bare] - self.tray[0], y[bare] - self.tray[1]])
      keep = (np.abs(lt[0]) > 0.125) | (np.abs(lt[1]) > 0.170)
      idx = np.nonzero(bare)
      sub = np.zeros_like(bare)
      sub[idx[0][keep], idx[1][keep]] = True
      bare = sub
    if bare.sum() > 1000:
      A = np.stack([x[bare], y[bare], np.ones(int(bare.sum()))], 1)
      coef = np.linalg.lstsq(A, zf[bare], rcond=None)[0]
      self.plane = coef
    h = zf - (self.plane[0] * x + self.plane[1] * y + self.plane[2])
    arm = okf & (h > 0.075)
    hidden = arm.copy()
    for _ in range(8):
      hd = hidden.copy()
      hd[1:, :] |= hidden[:-1, :]; hd[:-1, :] |= hidden[1:, :]; hd[:, 1:] |= hidden[:, :-1]; hd[:, :-1] |= hidden[:, 1:]
      hidden = hd
    vis = okf & ~hidden
    tr = self.find_tray(x, y, h, vis)
    to = self.find_tote(x, y, h, vis)
    r, g, b = rgb[..., 0], rgb[..., 1], rgb[..., 2]
    mx = np.maximum(np.maximum(r, g), b)
    mn = np.minimum(np.minimum(r, g), b)
    cls = np.zeros(h.shape, np.int8)                # 0 none, 1 brass, 2 grey, 3 black, 4 blue
    cls[(r - b > 55) & (g - b > 20) & (r >= g)] = 1
    cls[((mx - mn) < 0.22 * np.maximum(mx, 1)) & (mx >= 85)] = 2
    cls[mx < 70] = 3
    cls[(b - r > 60) & (b - g > 25)] = 4
    return {"xyz": (x, y, h), "vis": vis, "hidden": hidden, "tray": tr, "tote": to, "cls": cls}

  def pieces(self, sc, region="tote"):
    """Pieces seen inside the tote: list of dicts with pn (part number guess), xy, yaw, top height, cover flag."""
    x, y, h = sc["xyz"]
    vis, cls = sc["vis"], sc["cls"]
    to = self.tote
    lx, ly = rz2(-to[2]) @ np.stack([(x - to[0]).ravel(), (y - to[1]).ravel()])
    lx, ly = lx.reshape(x.shape), ly.reshape(x.shape)
    inside = (np.abs(lx) < TOTE_IN[0] - 0.003) & (np.abs(ly) < TOTE_IN[1] - 0.003)
    above = vis & inside & (h > FLOOR_Z + 0.0025) & (h < 0.06)
    out = []
    # brass: sleeves
    for c in self.label(above & (cls == 1), 25):
      pc = self._shape(x[c], y[c], h[c])
      if pc is None:
        continue
      L = pc["major"]
      pn = "SL-30" if L < 0.0375 else "SL-45"
      out.append({**pc, "pn": pn, "fam": "sleeve", "cover": pc["top"] > FLOOR_Z + 2 * P.SLEEVE_R + 0.004})
    # grey: washers, nuts, the flat bar
    for c in self.label(above & (cls == 2), 20):
      pc = self._shape(x[c], y[c], h[c])
      if pc is None:
        continue
      if pc["major"] > 0.030 and pc["major"] > 2.3 * pc["minor"]:
        out.append({**pc, "pn": "FB-40", "fam": "bar", "cover": pc["top"] > FLOOR_Z + P.BAR[2] + 0.004})
        continue
      dia = 0.5 * (pc["tmajor"] + pc["tminor"])
      # a round piece: centre from the outline (the bore is dark)
      if dia < 0.0215:
        pn = "NT-12"
      elif dia < 0.027:
        pn = "W-24"
      else:
        pn = "W-30"
      fam = FAMILY[pn]
      cover = pc["top"] > FLOOR_Z + HEIGHT[pn] + 0.0025
      out.append({**pc, "pn": pn, "fam": fam, "cover": cover})
    # blue: the block (it may show only as corners round a nut lying on it)
    blue = above & (cls == 4)
    comps = self.label(blue, 3)
    groups = []
    for c in comps:
      cxy = np.array([x[c].mean(), y[c].mean()])
      for gq in groups:
        if np.linalg.norm(gq["c"] - cxy) < 0.025:
          gq["rows"].append(c)
          break
      else:
        groups.append({"c": cxy, "rows": [c]})
    for gq in groups:
      rr = np.concatenate([c[0] for c in gq["rows"]])
      cc = np.concatenate([c[1] for c in gq["rows"]])
      if len(rr) < 12:
        continue
      px, py, pz = x[rr, cc], y[rr, cc], h[rr, cc]
      yaw = self._rect_yaw(px, py)
      cxy = np.array([0.5 * (px.min() + px.max()), 0.5 * (py.min() + py.max())])
      R = rz2(-yaw)
      u = R @ np.stack([px, py])
      ctr = rz2(yaw) @ np.array([0.5 * (np.percentile(u[0], 2) + np.percentile(u[0], 98)),
                                 0.5 * (np.percentile(u[1], 2) + np.percentile(u[1], 98))])
      out.append({"xy": ctr, "yaw": yaw, "top": float(np.percentile(pz, 90)), "major": 0.02, "minor": 0.02,
                  "n": len(px), "pn": "SB-20", "fam": "block", "cover": False})
    # black: brackets (a nut lying on the base can cut the outline in two: base pieces join the nearest tab)
    comps = self.label(above & (cls == 3), 8)
    tabs, rest = [], []
    for c in comps:
      pz = h[c]
      (tabs if np.sum(pz > FLOOR_Z + P.BR_T + 0.009) >= 6 else rest).append(c)
    for c in tabs:
      rr, cc = [c[0]], [c[1]]
      ct = np.array([x[c].mean(), y[c].mean()])
      for q in rest:
        if np.linalg.norm(np.array([x[q].mean(), y[q].mean()]) - ct) < 0.035:
          rr.append(q[0]); cc.append(q[1])
      rr, cc = np.concatenate(rr), np.concatenate(cc)
      px, py, pz = x[rr, cc], y[rr, cc], h[rr, cc]
      ttop = float(np.percentile(pz, 97))
      tab = pz > max(FLOOR_Z + P.BR_T + 0.009, ttop - 0.004)
      base = (pz < FLOOR_Z + P.BR_T + 0.004)
      if tab.sum() < 4 or base.sum() < 10:
        continue
      tx, ty = px[tab], py[tab]
      ctab = np.array([tx.mean(), ty.mean()])
      Pm = np.stack([tx - ctab[0], ty - ctab[1]], 1)
      ev, evec = np.linalg.eigh(Pm.T @ Pm / len(Pm))
      major = np.array([evec[0, 1], evec[1, 1]])           # along the tab = body y
      nrm = np.array([-major[1], major[0]])
      cbase = np.array([px[base].mean(), py[base].mean()])
      if float(nrm @ (cbase - ctab)) < 0:
        nrm = -nrm
      yaw = math.atan2(nrm[1], nrm[0])                      # body +x
      tab_c = 0.5 * (P.BR_TAB[0] + P.BR_TAB[1])
      ctr = ctab - nrm * tab_c
      # which hand: base pixels in the +x half on the +y side (right hand) or the -y side (left hand)
      R = rz2(-yaw)
      bl = R @ np.stack([px[base] - ctr[0], py[base] - ctr[1]])
      sel = (bl[0] > 0.006) & (bl[0] < 0.018)
      npos = int(np.sum(sel & (bl[1] > 0.002) & (bl[1] < 0.012)))
      nneg = int(np.sum(sel & (bl[1] < -0.002) & (bl[1] > -0.012)))
      pn = "BR-L" if nneg > npos else "BR-R"
      out.append({"xy": ctr, "yaw": yaw, "top": ttop, "major": 0.04, "minor": 0.028,
                  "n": len(px), "pn": pn, "fam": "bracket", "cover": False, "hand_votes": (nneg, npos)})
    # what lies on what: a cover is a piece raised off the floor; the piece under it is the one whose outline holds it
    for o in out:
      o["under"] = None
      if o["fam"] in ("nut", "washer") and not o["cover"]:
        # a round piece whose middle lies over a block or a bracket base rests on it, even if it reads a little low
        for q in out:
          if q["fam"] in ("block", "bracket"):
            loc = rz2(-q["yaw"]) @ (o["xy"] - q["xy"])
            hq = (0.008, 0.008) if q["fam"] == "block" else (0.018, 0.012)
            if abs(loc[0]) < hq[0] and abs(loc[1]) < hq[1] and o["top"] > FLOOR_Z + HEIGHT[o["pn"]] + 0.0012:
              o["cover"] = True
    for o in out:
      if not o["cover"]:
        continue
      for q in out:
        if q is o or q["fam"] not in ("block", "bracket", "sleeve", "washer", "bar"):
          continue
        loc = rz2(-q["yaw"]) @ (o["xy"] - q["xy"])
        half = {"block": (0.012, 0.012), "bracket": (0.022, 0.016), "sleeve": (0.025, 0.009),
                "washer": (0.016, 0.016), "bar": (0.022, 0.006)}[q["fam"]]
        if abs(loc[0]) < half[0] + 0.004 and abs(loc[1]) < half[1] + 0.004:
          q["covered_by"] = o
          o["on"] = q
    return out

  def _shape(self, px, py, pz):
    top = float(np.percentile(pz, 92))
    sel = pz > top - 0.005
    if sel.sum() < 6:
      return None
    cx, cy = float(px[sel].mean()), float(py[sel].mean())
    Pm = np.stack([px - cx, py - cy], 1)
    ev, evec = np.linalg.eigh(Pm.T @ Pm / len(Pm))
    yaw = math.atan2(evec[1, 1], evec[0, 1])
    u = Pm @ np.array([math.cos(yaw), math.sin(yaw)])
    v = Pm @ np.array([-math.sin(yaw), math.cos(yaw)])
    px_m = 0.0017
    lo, hi = np.percentile(u, 1), np.percentile(u, 99)
    vlo, vhi = np.percentile(v, 1), np.percentile(v, 99)
    ctr = np.array([cx, cy]) + rz2(yaw) @ np.array([0.5 * (lo + hi), 0.5 * (vlo + vhi)])
    ut, vt = u[sel], v[sel]
    tmaj = float(np.percentile(ut, 99) - np.percentile(ut, 1) + px_m) if sel.sum() > 8 else float(hi - lo)
    tmin = float(np.percentile(vt, 99) - np.percentile(vt, 1) + px_m) if sel.sum() > 8 else float(vhi - vlo)
    return {"xy": ctr, "yaw": yaw, "top": top, "major": float(hi - lo + px_m), "minor": float(vhi - vlo + px_m),
            "tmajor": tmaj, "tminor": tmin, "n": int(len(px))}

  @staticmethod
  def _rect_yaw(px, py):
    best = None
    for a in np.radians(np.arange(0, 90, 2.0)):
      c, s = math.cos(a), math.sin(a)
      u, v = c * px + s * py, -s * px + c * py
      area = (u.max() - u.min()) * (v.max() - v.min())
      if best is None or area < best[0]:
        best = (area, a)
    a0 = best[1]
    for a in np.radians(np.arange(-2, 2.01, 0.25)) + a0:
      c, s = math.cos(a), math.sin(a)
      u, v = c * px + s * py, -s * px + c * py
      area = (u.max() - u.min()) * (v.max() - v.min())
      if area < best[0]:
        best = (area, a)
    return float(best[1])

  def look(self, tuck=True):
    """A full look: camera registration on the first, tray and tote poses, pieces in the tote."""
    if tuck:
      yield from self.to_tuck()
      yield from self.wait(0.1)
    yield from self.frames(2)
    if self.tote is None:
      self.register()
    sc = self.see()
    if sc["tray"] is not None and (self.tray is None or OPT["handle_upsets"]):
      self.tray = sc["tray"]
    if sc["tote"] is not None:
      self.tote = sc["tote"]
    if self.tote is None or self.tray is None:
      self.say("look: tote or tray not found", sc["tote"], sc["tray"])
      return None
    pcs = self.pieces(sc)
    self.w = {"sc": sc, "pieces": pcs}
    self.avg = None
    self.say("look: tray", np.round(self.tray, 4), "tote", np.round(self.tote, 4), "pieces",
             [(p["pn"], np.round(p["xy"], 3).tolist(), round(math.degrees(p["yaw"])), round(p["top"], 4),
               "C" if p["cover"] else "") for p in pcs])
    return self.w

  # ------------------------------------------------------------------ main
  def main(self):
    if OPT["idle"]:
      while True:
        yield from self.tick()
    try:
      yield from self.job()
    except Abort as a:
      self.say("abort", a.fault, "holding", self.holding)
      self.in_abort = True
      if a.fault == "perception_freeze" and self.holding is not None:
        # nothing can be checked any more: finish the set-down that was planned, or put it back where it was taken
        try:
          if self.plan_dest is not None and self.plan_dest[0] == "pocket":
            yield from self.place_in_blind(self.plan_dest[1])
          else:
            hd = self.holding
            p, y = self.tcp_cmd()
            xy = hd["from"]
            yield from self.go((xy[0], xy[1], TRANSIT_Z), y, v=0.3, exact=True)
            yield from self.go((xy[0], xy[1], hd["support"] + hd["gz"] + 0.003), y, v=0.10, exact=True)
            yield from self.wait(0.2)
            yield from self.release()
            yield from self.up()
        except (Lost, Abort):
          pass
      yield
      return {"status": "abort", "fault": a.fault}
    self.say("done")
    return {"status": "done"}

  # ------------------------------------------------------------------ the pick list
  def parse(self):
    """Lines of the pick list: pocket, part number on the line, part to fit (after a substitution)."""
    out = []
    subs = [re.escape(t).replace(r"\{sub\}", r"(?P<sub>[A-Z]{1,2}-[A-Z0-9]+)").replace(r"\{pn\}", r"[A-Z]{1,2}-[A-Z0-9]+")
            .replace(r"\{ecn\}", r"\d+").replace(r"\{hold\}", r"QN-\d+") for t in P.SUB_NOTES]
    for line in self.text.splitlines():
      m = re.match(r"^\s*(\d+)\s+([AB][1-4])\s+([A-Z]{1,2}-[A-Z0-9]+)\s+(.*)$", line)
      if not m:
        continue
      _n, pk, pn, rest = m.groups()
      note = rest.split("  1  ", 1)[1].strip() if "  1  " in rest else re.sub(r"^.*?\s1\s+", "", rest).strip()
      want = pn
      if OPT["subs"]:
        for rx in subs:
          mm = re.fullmatch(rx, note)
          if mm:
            want = mm.group("sub")
            break
      out.append({"pocket": pk, "pn": pn, "want": want, "note": note})
    return out

  # ------------------------------------------------------------------ the arm against the camera
  def robot_top(self, q):
    m, d = self.m, self.d
    d.qpos[self.qadr] = q
    mujoco.mj_kinematics(m, d)
    best = -1.0
    for g in self.vis_geoms:
      mid = int(m.geom_dataid[g])
      v = m.mesh_vert[m.mesh_vertadr[mid]:m.mesh_vertadr[mid] + m.mesh_vertnum[mid]]
      w = d.geom_xpos[g] + v @ d.geom_xmat[g].reshape(3, 3).T
      w = w[w[:, 0] > 0.22]
      if len(w):
        best = max(best, float(np.max(w[:, 2])))
    return best

  def calib_height(self):
    """Height offset of the arm against the camera: the top of the arm in the depth image against the model."""
    q = self.ik(np.array([0.36, 0.0, 0.30]), 0.0, Q_PREF, iters=80)
    yield from self.joint_go(q, speed=1.8)
    yield from self.wait(0.4)
    est = []
    for _ in range(2):
      yield from self.fresh_frame()
      x, y, z, ok = self.cloud()
      arm = ok & (z > 0.30) & (x > 0.22)
      if arm.sum() > 50:
        # heights against the bench plane, as every other height the controller uses (the camera's own height
        # error is already in the plane)
        zb = z[arm] - (self.plane[0] * x[arm] + self.plane[1] * y[arm] + self.plane[2])
        zs = np.sort(zb)
        est.append(self.robot_top(self.q_cmd) - float(np.mean(zs[-12:-2])))
    self.dz = float(np.mean(est)) + TOP_BIAS if est else 0.0
    self.say("height offset", round(self.dz, 4), est)

  # ------------------------------------------------------------------ grasps
  def occupied(self, sc, xy, yaw, half, own=None, margin=0.0, floor=None):
    """Pixels above the floor in a rectangle (world centre xy, yaw, half extents), not counting the piece `own`."""
    x, y, h = sc["xyz"]
    loc = rz2(-yaw) @ np.stack([(x - xy[0]).ravel(), (y - xy[1]).ravel()])
    inr = (np.abs(loc[0]) < half[0] + margin) & (np.abs(loc[1]) < half[1] + margin)
    inr = inr.reshape(x.shape) & sc["vis"]
    hit = inr & (h > (FLOOR_Z if floor is None else floor) + 0.003)
    if own is not None:
      lo = rz2(-own["yaw"]) @ np.stack([(x - own["xy"][0]).ravel(), (y - own["xy"][1]).ravel()])
      oh = self.half_of(own)
      if FAMILY[own["pn"]] in ("washer", "nut"):
        mine = (np.hypot(lo[0], lo[1]) < oh[0] + 0.0015).reshape(x.shape)
      else:
        mine = ((np.abs(lo[0]) < oh[0] + 0.002) & (np.abs(lo[1]) < oh[1] + 0.002)).reshape(x.shape)
      hit &= ~mine
    return int(hit.sum())

  @staticmethod
  def half_of(pc):
    pn = pc["pn"]
    fam = FAMILY[pn]
    if fam == "sleeve":
      return (P.SLEEVE_LEN[pn] / 2, P.SLEEVE_R)
    if fam == "washer":
      return (P.WASHER_R[pn], P.WASHER_R[pn])
    if fam == "nut":
      return (P.NUT_R, P.NUT_R)
    if fam == "bar":
      return P.BAR[:2]
    if fam == "block":
      return P.BLOCK[:2]
    return (0.020, 0.014)

  def grasps(self, pc):
    """Candidate grasps of a piece in the tote: list of (tcp xy, finger yaw, half width)."""
    fam, pn = pc["fam"], pc["pn"]
    c, yaw = pc["xy"], pc["yaw"]
    out = []
    base = pc.get("on")
    if fam in ("washer", "nut") and base is not None and base["fam"] == "bracket":
      # on a bracket: close across the bracket, clear of its tab
      r = P.WASHER_R[pn] if fam == "washer" else P.NUT_R
      return [(c.copy(), base["yaw"] + math.pi / 2 + d_, r) for d_ in (0.0, -0.15, 0.15, -0.35, 0.35, -0.55, 0.55)]
    ax = np.array([math.cos(yaw), math.sin(yaw)])
    if fam in ("sleeve", "bar"):
      L = P.SLEEVE_LEN[pn] / 2 if fam == "sleeve" else P.BAR[0]
      for s_ in (0.0, -0.004, 0.004, -0.008, 0.008):
        if L - abs(s_) >= 0.009:
          out.append((c + s_ * ax, yaw + math.pi / 2, P.SLEEVE_R if fam == "sleeve" else P.BAR[1]))
    elif fam in ("washer", "nut"):
      r = P.WASHER_R[pn] if fam == "washer" else P.NUT_R
      for k in range(12):
        out.append((c.copy(), k * math.pi / 12, r))
    elif fam == "block":
      out += [(c.copy(), yaw, P.BLOCK[0]), (c.copy(), yaw + math.pi / 2, P.BLOCK[1])]
    elif fam == "bracket":
      tab_c = 0.5 * (P.BR_TAB[0] + P.BR_TAB[1])
      out.append((c + tab_c * ax, yaw, 0.5 * (P.BR_TAB[1] - P.BR_TAB[0])))
    return out

  def clear_grasp(self, sc, pc, others=(), floor=None):
    """The first grasp whose fingers clear the walls and the neighbours, or None."""
    best = None
    tip = (FLOOR_Z if floor is None else floor) + GRASP[pc["fam"]][1] - 0.0089   # finger tips at the grasp
    for g in self.grasps(pc):
      xy, yaw, half = g
      ax = np.array([math.cos(yaw), math.sin(yaw)])
      n_hit, inside = 0, True
      for s_ in (-1, 1):
        fc = xy + s_ * ax * (half + 0.012)            # lower 19 mm of the open finger: 4 to 20 mm out from the piece
        # the whole open finger, up to its upper part 31 mm out from the piece, 21 mm wide, inside the walls
        nrm = np.array([-ax[1], ax[0]])
        for u_ in (half + 0.004, half + 0.031):
          for v_ in (-0.0105, 0.0105):
            c_ = rz2(-self.tote[2]) @ (xy + s_ * ax * u_ + v_ * nrm - self.tote[:2])
            if abs(c_[0]) > TOTE_IN[0] - 0.002 or abs(c_[1]) > TOTE_IN[1] - 0.002:
              inside = False
        lt = rz2(-self.tote[2]) @ (fc - self.tote[:2])
        if abs(lt[0]) > TOTE_IN[0] - 0.010 or abs(lt[1]) > TOTE_IN[1] - 0.010:
          inside = False
        n_hit += self.occupied(sc, fc, yaw, (0.0085, 0.011), own=pc, floor=tip - 0.001, margin=0.001)
      if not inside:
        continue
      if best is None or n_hit < best[0]:
        best = (n_hit, g)
      if n_hit == 0:
        break
    # a nut on a bracket: the fingers go down beside the bracket base, whose edge reads a little high in the
    # depth image, so a few more pixels are allowed there
    limit = 6 if (pc["fam"] == "nut" and pc.get("on") is not None and pc["on"]["fam"] == "bracket") else 3
    if best is None or best[0] > limit:
      if os.environ.get("KT8_CDBG"):
        self.say("no clear grasp for", pc["pn"], np.round(pc["xy"], 4), "best", None if best is None else (best[0], np.round(best[1][0], 4), round(best[1][1], 2)))
      return None
    return best[1]

  # ------------------------------------------------------------------ pick and place
  def pick(self, pc, g, support_z, yaw_exact=None):
    """Takes piece pc with grasp g = (xy, yaw, half) from a support at height support_z."""
    xy, yaw, half = g
    fam = pc["fam"]
    self.say("pick", pc["pn"], "est xy", np.round(pc["xy"], 4), "yaw", round(pc["yaw"], 3), "grasp", np.round(xy, 4), round(yaw, 3), truth_note(pc["xy"]))
    gz = GRASP[fam][1]
    force = GRASP[fam][2]
    if yaw_exact is not None:
      yaw = yaw_exact
    exact = yaw_exact is not None
    yield from self.over(xy, yaw, exact=exact)
    yield from self.grip(min(0.04, half + 0.004), 0.05)
    z_g = support_z + gz
    if any(np.hypot(*(xy - j)) < 0.006 for j in self.jams):
      z_g += 0.0015                                   # the fingertips stuck on the floor here last time
    yield from self.go((xy[0], xy[1], z_g + 0.035), yaw, v=0.40, exact=exact)
    yield from self.wait(0.10)
    if OPT["handle_faults"] and abs(self.fin(4) - self.g_cmd) > 0.0025:
      # open fingers in the air that do not reach their command: the gripper does not answer
      yield from self.wait(0.3)
      if abs(self.fin(4) - self.g_cmd) > 0.0025:
        self.say("gripper did not open: dead", round(self.fin(4), 4), round(self.g_cmd, 4))
        yield from self.up(v=0.2)
        raise Abort("dead_gripper")
    yield from self.go((xy[0], xy[1], z_g), yaw, v=0.12, exact=exact)
    yield from self.wait(0.15)
    g0 = self.fin(4)
    g_t = half - force / GRIP_K
    g = self.g_cmd
    while g > g_t:
      g = max(g_t, g - (0.06 if g > half + 0.004 else 0.006) * self.dt)
      self.g_cmd = g
      yield from self.tick()
    yield from self.wait(0.3)
    width = self.fin(6)
    self.say("gripped", pc["pn"], "width", round(width, 4), "half", round(half, 4), "at", np.round(xy, 4),
             "yaw", round(yaw, 2), "z", round(z_g, 4))
    if OPT["handle_faults"] and abs(width - g0) < 0.002 and g0 - g_t > 0.006:
      # fingers held by something (a neighbour, or the floor under the tips): lift a little and open; a dead
      # gripper does not open again
      yield from self.go((xy[0], xy[1], z_g + 0.004), yaw, v=0.05, exact=exact)
      width = self.fin(4)
      self.g_cmd = min(0.04, width + 0.006)
      yield from self.wait(0.4)
      if abs(self.fin(4) - width) < 0.002:
        self.say("gripper did not close: dead")
        yield from self.up(v=0.2)
        raise Abort("dead_gripper")
      self.jams.append(np.array(xy, float))
      self.say("fingers blocked closing on", pc["pn"], round(width, 4))
      yield from self.up()
      return False
    if width < half - 0.002:
      self.say("pick missed", pc["pn"], round(width, 4))
      yield from self.grip(min(0.04, half + 0.011), 0.25)
      yield from self.up()
      return False
    p_tcp, y_tcp = self.tcp_cmd()
    rel = rz2(-y_tcp) @ (pc["xy"] - xy)
    self.holding = {"pn": pc["pn"], "fam": fam, "half": half, "g": g_t, "rel": rel, "yaw_off": wrap_pi(pc["yaw"] - y_tcp),
                    "gz": gz, "support": support_z, "from": xy.copy()}
    if OPT["grab_hold"]:
      while True:
        yield from self.tick()
    yield from self.go((xy[0], xy[1], z_g + 0.035), None, v=0.09)      # straight up, the wrist kept still
    yield from self.wait(0.15)
    if not self.still_held():
      self.say("slipped at lift-off", pc["pn"])
      self.holding = None
      yield from self.grip(min(0.04, half + 0.004), 0.1)   # not wide open: the fingers are still low in the tote
      yield from self.up()
      yield from self.grip(0.04, 0.1)
      return False
    yield from self.up()
    return True

  def still_held(self):
    hd = self.holding
    return hd is not None and self.fin(8) > hd["half"] - 0.0020

  def release(self):
    """Opens the gripper and checks that it did; a gripper that stays shut is a fault."""
    hd = self.holding
    g_before = self.fin(4)
    self.g_cmd = min(0.04, max((hd["half"] if hd else 0.01), g_before) + 0.003)
    yield from self.wait(0.45)
    self.say("release: fin before", round(g_before, 4), "after", round(self.fin(4), 4), "cmd", round(self.g_cmd, 4))
    if OPT["handle_faults"] and self.fin(4) < g_before + 0.0012:
      yield from self.wait(0.3)
      if self.fin(4) < g_before + 0.0012:
        # fingers held by a rib or a neighbour open once lifted a little; a dead gripper does not
        p, _y = self.tcp_cmd()
        yield from self.go((p[0], p[1], p[2] - self.dz + 0.005), None, v=0.03)
        yield from self.wait(0.3)
        if self.fin(4) < g_before + 0.0012:
          yield from self.go((p[0], p[1], p[2] - self.dz), None, v=0.03)
          yield from self.dead_gripper_stop()
    self.holding = None

  def dead_gripper_stop(self):
    """The gripper does not answer with the piece just above its seat: let the arm sink it the last 2 mm, then
    report. After an abort the cell holds the joints without this controller's gravity feed-forward, so the hand
    sinks by the servo deflection; leave the piece that far up, less what it is above the floor."""
    p, y = self.tcp_cmd()
    self.in_abort = True
    sag = p[2] - float(self.fk(self.q_cmd - self.grav(self.q_cmd) / self.kp)[0][2])
    self.say("dead gripper: sag after abort", round(sag, 4))
    yield from self.go((p[0], p[1], p[2] - self.dz - 0.002 + max(0.0, sag) - 0.0015), v=0.01, exact=True)
    yield from self.wait(0.2)
    raise Abort("dead_gripper")

  def refix_tray(self):
    """A fresh fix of the tray from one frame (the arm is over the tote): returns how far it moved."""
    yield from self.fresh_frame()
    sc = self.see()
    if sc["tray"] is None or self.tray is None:
      return 0.0
    mv = float(np.linalg.norm(sc["tray"][:2] - self.tray[:2])) + 0.15 * abs(wrap_pi(sc["tray"][2] - self.tray[2]))
    if mv > 0.0015:
      self.say("tray moved", round(1000 * mv, 1), "mm")
    self.tray = sc["tray"]
    return mv

  def place_yaw(self, pk):
    """Finger yaw for placing the held piece in pocket pk, and the tcp xy."""
    hd = self.holding
    ty = self.tray[2]
    if hd["fam"] == "bracket":
      yaw = ty - hd["yaw_off"]                       # body x of the bracket along tray x
    elif hd["fam"] in ("sleeve", "bar"):
      yaw = ty + math.pi / 2                         # piece axis along tray x
      _p, y0 = self.tcp_cmd()
      if abs(wrap_pi(yaw - y0)) > math.pi / 2:
        yaw += math.pi
    else:
      yaw = ty + math.pi / 2
      _p, y0 = self.tcp_cmd()
      if abs(wrap_pi(yaw - y0)) > math.pi / 2:
        yaw += math.pi
    rel = hd["rel"].copy()
    if hd["fam"] in ("washer", "nut", "block"):
      rel[:] = 0.0                                   # centred by the fingers
    elif hd["fam"] in ("sleeve", "bar"):
      rel[0] = 0.0                                   # centred across its axis by the fingers
    tgt = self.tray_to_world(self.pocket_xy(pk))
    tcp = tgt - rz2(yaw) @ rel
    return wrap_pi(yaw), tcp

  def place_in(self, pk):
    hd = self.holding
    yield from self.up()
    if OPT["handle_upsets"]:
      yield from self.refix_tray()
    yaw, tcp = self.place_yaw(pk)
    exact = hd["fam"] in ("bracket", "sleeve", "bar")  # the in-hand offset is tied to the yaw chosen
    self.plan_dest = ("pocket", pk)
    yield from self.go((tcp[0], tcp[1], TRANSIT_Z), yaw, v=0.55, w=1.6, exact=exact)
    if not self.still_held():
      raise Lost()
    yield from self.wait(0.2)
    z_rel = hd["gz"]                                 # tcp above the piece's underside
    yield from self.go((tcp[0], tcp[1], FLOOR_Z + z_rel + 0.030), yaw, v=0.25, exact=exact)
    if not self.still_held():
      raise Lost()
    yield from self.go((tcp[0], tcp[1], FLOOR_Z + z_rel + (-0.004 if OPT["press"] else 0.0035)), yaw, v=0.08, exact=exact)
    yield from self.wait(0.15)
    self.say("releasing", hd["pn"], "in", pk, "at", np.round(tcp, 4), "yaw", round(yaw, 3))
    yield from self.release()
    self.plan_dest = None
    yield from self.go((tcp[0], tcp[1], FLOOR_Z + z_rel + 0.040), yaw, v=0.20, exact=exact)
    yield from self.up()

  def free_spot(self, sc, half=0.0095, avoid=()):
    """A bare patch of tote floor for a held piece of half width `half`, away from the walls and from everything,
    and the finger yaw whose open fingers keep furthest from the neighbours there: (world xy, yaw) or None."""
    x, y, h = sc["xyz"]
    to = self.tote
    occ = sc["vis"] & (h > FLOOR_Z + 0.0025)
    lx, ly = rz2(-to[2]) @ np.stack([(x - to[0]).ravel(), (y - to[1]).ravel()])
    sel = (occ.ravel()) & (np.abs(lx) < TOTE_IN[0] + 0.01) & (np.abs(ly) < TOTE_IN[1] + 0.01)
    ox, oy = lx[sel], ly[sel]
    spots = []
    wm = 0.038                                       # the open fingers and their upper part clear the walls
    for cx in np.arange(-TOTE_IN[0] + wm, TOTE_IN[0] - wm + 1e-6, 0.004):
      for cy in np.arange(-TOTE_IN[1] + wm, TOTE_IN[1] - wm + 1e-6, 0.004):
        if any(np.hypot(cx - a, cy - b) < 0.03 for a, b in self.moved_to):
          continue
        dmin = float(np.min(np.hypot(ox - cx, oy - cy))) if len(ox) else 1.0
        da = min([float(np.hypot(cx - a, cy - b)) for a, b in avoid] + [1.0])
        if dmin > 0.016:
          spots.append((da > 0.065, min(da, 0.09), dmin, cx, cy))
    spots.sort(reverse=True)
    spots = [sp[2:] for sp in spots]
    best = None
    for dmin, cx, cy in spots[:40]:
      near = np.hypot(ox - cx, oy - cy) < 0.06
      px, py = ox[near] - cx, oy[near] - cy
      for k in range(12):
        fy = k * math.pi / 12 + to[2] * 0                # finger axis in the tote frame
        u, v = px * math.cos(fy) + py * math.sin(fy), -px * math.sin(fy) + py * math.cos(fy)
        # distance outside the finger footprints: |u| from half+3 mm to half+33 mm, |v| up to 11.5 mm
        du = np.maximum(0.0, np.maximum((half + 0.003) - np.abs(u), np.abs(u) - (half + 0.033)))
        dv = np.maximum(0.0, np.abs(v) - 0.0115)
        clr = float(np.min(np.hypot(du, dv))) if len(u) else 1.0
        clr = min(clr, dmin - half)
        if best is None or clr > best[0]:
          best = (clr, cx, cy, fy)
    if best is None:
      return None
    self.say("set-aside spot clearance", round(best[0], 4))
    return to[:2] + rz2(to[2]) @ np.array([best[1], best[2]]), wrap_pi(best[3] + to[2])

  def set_aside(self, sc):
    """Puts the held piece (a nut) on a bare patch of the tote floor."""
    hd = self.holding
    avoid = []
    for q in getattr(self, "needed_now", ()):           # the needed pieces and where their fingers will go
      avoid.append(tuple(rz2(-self.tote[2]) @ (q["xy"] - self.tote[:2])))
      if q["fam"] == "bracket":
        avoid.append(tuple(rz2(-self.tote[2]) @ (self.grasps(q)[0][0] - self.tote[:2])))
    fs = self.free_spot(sc, hd["half"], avoid)
    if fs is None:
      spot, yaw = self.tote[:2].copy(), self.tcp_cmd()[1]
    else:
      spot, yaw = fs
    self.moved_to.append(tuple(rz2(-self.tote[2]) @ (spot - self.tote[:2])))
    self.plan_dest = ("tote", spot)
    yield from self.go((spot[0], spot[1], TRANSIT_Z), yaw, v=0.55)
    yield from self.go((spot[0], spot[1], FLOOR_Z + hd["gz"] + 0.002), yaw, v=0.15)
    yield from self.wait(0.2)
    yield from self.release()
    self.plan_dest = None
    yield from self.up()

  # ------------------------------------------------------------------ the tray as seen
  def pocket_state(self, sc, pk, pn):
    """'seated', 'proud', 'empty' for the piece pn expected in pocket pk, from the height image."""
    x, y, h = sc["xyz"]
    fam, cx, cy, hx, hy = POCKETS[pk]
    c = self.pocket_xy(pk)
    loc = rz2(-self.tray[2]) @ np.stack([(x - self.tray[0]).ravel(), (y - self.tray[1]).ravel()])
    lx, ly = (loc[0] - c[0]).reshape(x.shape), (loc[1] - c[1]).reshape(x.shape)
    vis = sc["vis"]
    inner = vis & (np.abs(lx) < hx - 0.0015) & (np.abs(ly) < hy - 0.0015)
    ring = vis & (np.abs(lx) < hx + 0.022) & (np.abs(ly) < hy + 0.022) & ~((np.abs(lx) < hx + 0.0025) & (np.abs(ly) < hy + 0.0025))
    top = FLOOR_Z + HEIGHT[pn]
    piece = inner & (h > FLOOR_Z + 0.003)
    high_ring = ring & (h > RIB_Z + 0.0035)
    high_in = inner & (h > top + 0.003)
    if int(high_ring.sum()) > 6 or int(high_in.sum()) > 6:
      return "proud"
    if int(piece.sum()) < 10:
      return "empty"
    if FAMILY[pn] != "bracket":
      # a piece lying in a finger relief beside the pocket rather than in it: its middle is off the pocket's
      cls_want = {"sleeve": 1, "bar": 2, "washer": 2, "nut": 2, "block": 4}[FAMILY[pn]]
      wide = vis & (np.abs(lx) < hx + 0.016) & (np.abs(ly) < hy + 0.016) & (h > FLOOR_Z + 0.003) & (sc["cls"] == cls_want)
      if pk == "A4" and os.environ.get("KT8_PDBG"):
        self.say("A4 dbg", int(wide.sum()), int(piece.sum()), np.round(1000 * np.percentile(ly[wide], [2, 50, 98]), 1) if wide.sum() else None)
      if int(wide.sum()) > 15:
        hl = self.half_of({"pn": pn})
        du = 0.5 * (np.percentile(lx[wide], 98) + np.percentile(lx[wide], 2))
        dv = 0.5 * (np.percentile(ly[wide], 98) + np.percentile(ly[wide], 2))
        if abs(du) > hx - hl[0] + 0.0015 or abs(dv) > hy - hl[1] + 0.0015:
          self.say("pocket", pk, "piece off centre mm", round(1000 * du, 1), round(1000 * dv, 1))
          return "proud"
    return "seated"

  def tray_piece(self, sc, pk, pn):
    """A proud piece near pocket pk seen in the height image: dict like `pieces` with its local support height."""
    x, y, h = sc["xyz"]
    fam, cx, cy, hx, hy = POCKETS[pk]
    c = self.pocket_xy(pk)
    loc = rz2(-self.tray[2]) @ np.stack([(x - self.tray[0]).ravel(), (y - self.tray[1]).ravel()])
    lx, ly = (loc[0] - c[0]).reshape(x.shape), (loc[1] - c[1]).reshape(x.shape)
    cls_want = {"sleeve": 1, "bar": 2, "washer": 2, "nut": 2, "block": 4, "bracket": 3}[FAMILY[pn]]
    sel = sc["vis"] & (np.abs(lx) < hx + 0.025) & (np.abs(ly) < hy + 0.015) & (h > FLOOR_Z + 0.003) & (sc["cls"] == cls_want)
    if sel.sum() < 15:
      return None
    px, py, pz = x[sel], y[sel], h[sel]
    fam_p = FAMILY[pn]
    if fam_p == "bracket":
      ttop = float(np.percentile(pz, 97))
      tab = pz > ttop - 0.005
      ctab = np.array([px[tab].mean(), py[tab].mean()])
      # the bracket keeps its yaw in the pocket: body x along tray x
      yaw = self.tray[2]
      tab_c = 0.5 * (P.BR_TAB[0] + P.BR_TAB[1])
      ctr = ctab - np.array([math.cos(yaw), math.sin(yaw)]) * tab_c
      g = (ctab, yaw, 0.5 * (P.BR_TAB[1] - P.BR_TAB[0]))
      tz = float(np.median(pz[tab]))
      support = tz - (P.BR_T + P.BR_TAB[4]) + 0.001
      return {"pn": pn, "fam": fam_p, "xy": ctr, "yaw": yaw, "grasp": g, "support": support}
    yaw = self.tray[2]
    ax = np.array([math.cos(yaw), math.sin(yaw)])
    u = (np.stack([px, py], 1) - self.tray_to_world(c)) @ ax
    lo, hi = np.percentile(u, 2), np.percentile(u, 98)
    nv = np.array([-ax[1], ax[0]])
    v = (np.stack([px, py], 1) - self.tray_to_world(c)) @ nv
    ctr = self.tray_to_world(c) + ax * 0.5 * (lo + hi) + nv * 0.5 * (np.percentile(v, 98) + np.percentile(v, 2))
    # grasp at the point of the piece nearest the pocket centre, inside the finger reliefs
    half_len = self.half_of({"pn": pn})[0]
    s_ = float(np.clip(-0.5 * (lo + hi), -(half_len - 0.009), half_len - 0.009)) if fam_p in ("sleeve", "bar") else 0.0
    gxy = ctr + ax * s_
    near = np.hypot(px - gxy[0], py - gxy[1]) < 0.006
    tz = float(np.median(pz[near])) if near.sum() > 3 else float(np.median(pz))
    support = tz - HEIGHT[pn] + 0.002
    half = self.half_of({"pn": pn})[1]
    return {"pn": pn, "fam": fam_p, "xy": ctr, "yaw": yaw, "grasp": (gxy, yaw + math.pi / 2, half), "support": support}

  # ------------------------------------------------------------------ the job
  def job(self):
    yield from self.look()
    if OPT["look_only"]:
      return
    lines = self.parse()
    self.say("lines", [(ln["pocket"], ln["pn"], ln["want"]) for ln in lines])
    yield from self.calib_height()
    placed = {}                                      # pocket -> True once placed (checked at every look)
    fails = {}
    n_done_hold = 0
    while True:
      if self.t > min(self.limit - 6.0, 192.0):        # nothing met after the cycle limit counts; the cell stops at 210 s
        break
      w = yield from self.look()
      if w is None:
        yield from self.wait(0.5)
        continue
      sc = w["sc"]
      if OPT["handle_upsets"]:
        state = {ln["pocket"]: self.pocket_state(sc, ln["pocket"], ln["want"]) if placed.get(ln["pocket"]) else "empty"
                 for ln in lines}
      else:                                          # a placed line is taken as done
        state = {ln["pocket"]: "seated" if placed.get(ln["pocket"]) else "empty" for ln in lines}
      done = [ln for ln in lines if state[ln["pocket"]] == "seated"]
      self.say("pockets", state)
      if OPT["stop_after"] >= 0 and len(done) >= OPT["stop_after"]:
        while True:
          yield from self.tick()
      if len(done) == len(lines):
        break
      # a placed piece standing proud: seat it again first
      proud = [ln for ln in lines if state[ln["pocket"]] == "proud"]
      if proud and OPT["handle_upsets"]:
        ln = proud[0]
        tp = self.tray_piece(sc, ln["pocket"], ln["want"])
        key = ("proud", ln["pocket"])
        fails[key] = fails.get(key, 0) + 1
        if tp is not None and fails[key] <= 3:
          try:
            ok = yield from self.pick(tp, tp["grasp"], tp["support"] + 0.002, yaw_exact=tp["grasp"][1] if tp["fam"] == "bracket" else None)
            if ok:
              yield from self.place_in(ln["pocket"])
          except Lost:
            self.say("lost the piece on the way")
            self.holding = None
            yield from self.grip(0.04, 0.2)
          continue
      todo = [ln for ln in lines if state[ln["pocket"]] == "empty"]
      if not todo:
        yield from self.wait(0.3)
        continue
      pcs = [p for p in w["pieces"]]
      action = None
      order = sorted(todo, key=lambda ln: fails.get(ln["pocket"], 0))
      for ln in order:
        cands = [p for p in pcs if p["pn"] == ln["want"]]       # one lying on another piece is taken from there
        free_c = sorted([p for p in cands if OPT["ignore_covers"] or not p.get("covered_by")], key=lambda p: p["cover"])
        for p in free_c:
          g = self.clear_grasp(sc, p, floor=self.support_of(p))
          if g is not None:
            action = ("pick", ln, p, g)
            break
        if action is None and OPT["move_covers"]:
          for p in cands:
            cv = p.get("covered_by")
            if cv is not None:
              cv["on"] = p
              g = self.clear_grasp(sc, cv, floor=cv["top"] - HEIGHT[cv["pn"]])
              if g is not None:
                action = ("cover", ln, cv, g)
                break
        if action is None and free_c and OPT["move_covers"] and fails.get("moved", 0) < 6:
          # every grasp of the part is blocked by a neighbour: set the nearest neighbour that can be taken aside
          best = None
          for p in free_c:
            for q in pcs:
              if q is p or q.get("covered_by") or q["fam"] == "bracket":
                continue
              dq = float(np.hypot(*(q["xy"] - p["xy"])))
              if dq > 0.06 or (best is not None and dq >= best[0]):
                continue
              fl = q["top"] - HEIGHT[q["pn"]] if q["cover"] else None
              gq = self.clear_grasp(sc, q, floor=fl)
              if gq is not None:
                best = (dq, q, gq)
          if best is not None:
            fails["moved"] = fails.get("moved", 0) + 1
            self.say("moving", best[1]["pn"], "out of the way of", ln["want"])
            action = ("cover", ln, best[1], best[2])
        if action is None and free_c and OPT["easy_first"] is False:
          p = free_c[0]
          action = ("pick", ln, p, self.grasps(p)[0])
        if action is not None:
          break
      if action is None:
        self.say("nothing to do for", [ln["pocket"] for ln in todo])
        key = "idle"
        fails[key] = fails.get(key, 0) + 1
        if fails[key] > 4:
          break
        yield from self.wait(0.5)
        continue
      kind, ln, p, g = action
      self.needed_now = [q for q in pcs if q is not p and any(q["pn"] == l2["want"] for l2 in todo)]
      try:
        if kind == "cover":
          ok = yield from self.pick(p, g, p["top"] - HEIGHT[p["pn"]])
          if ok:
            yield from self.set_aside(sc)
          continue
        if p["fam"] == "bracket":
          yaw_pick = self.bracket_pick_yaw(p, g, ln["pocket"])
          ok = yield from self.pick(p, g, FLOOR_Z, yaw_exact=yaw_pick)
        else:
          ok = yield from self.pick(p, g, self.support_of(p) or FLOOR_Z)
        if not ok:
          fails[ln["pocket"]] = fails.get(ln["pocket"], 0) + 1
          continue
        yield from self.place_in(ln["pocket"])
        placed[ln["pocket"]] = True
      except Lost:
        self.say("lost the piece on the way")
        self.holding = None
        yield from self.grip(0.04, 0.2)
        fails[ln["pocket"]] = fails.get(ln["pocket"], 0) + 1
        if not OPT["handle_upsets"]:
          placed[ln["pocket"]] = True
    self.say("job finished")

  @staticmethod
  def support_of(p):
    """Height of what a piece seen in the tote rests on: None for the tote floor."""
    if not p["cover"]:
      return None
    return max(FLOOR_Z, p["top"] - HEIGHT[p["pn"]])

  def bracket_pick_yaw(self, p, g, pk):
    """Finger yaw for taking a bracket by its tab (body x or body x + pi) so that the wrist can then turn it to its
    place yaw without reaching a joint stop."""
    best = None
    q_over = self.ik(np.array([0.36, 0.0, TRANSIT_Z + self.dz]), 0.0, Q_PREF, iters=60)
    tgt = self.tray_to_world(self.pocket_xy(pk))
    for yaw in (p["yaw"], p["yaw"] + math.pi):
      yaw_off = wrap_pi(p["yaw"] - yaw)
      place_yaw = wrap_pi(self.tray[2] - yaw_off)
      y_p, q_p = self.yaw_choice((g[0][0], g[0][1], TRANSIT_Z), yaw, True, q_from=q_over, y_from=0.0)
      if q_p is None:
        continue
      y_l, q_l = self.yaw_choice((tgt[0], tgt[1], TRANSIT_Z), place_yaw, True, q_from=q_p, y_from=y_p)
      if q_l is None:
        continue
      cost = abs(y_l - y_p) + 0.3 * abs(y_p)
      if best is None or cost < best[0]:
        best = (cost, wrap_pi(yaw))
    self.say("bracket pick yaw", None if best is None else round(best[1], 3))
    return best[1] if best is not None else wrap_pi(p["yaw"])

  def place_in_blind(self, pk):
    """Finishes a placement without the camera (after a camera fault)."""
    hd = self.holding
    yaw, tcp = self.place_yaw(pk)
    exact = hd["fam"] == "bracket"
    yield from self.go((tcp[0], tcp[1], FLOOR_Z + hd["gz"] + 0.030), yaw, v=0.25, exact=exact)
    yield from self.go((tcp[0], tcp[1], FLOOR_Z + hd["gz"] + 0.0025), yaw, v=0.06, exact=exact)
    yield from self.wait(0.2)
    yield from self.release()
    yield from self.up()