File size: 77,842 Bytes
e3be6f4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
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
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
"""Reference controller for the FP-2 fruit-prep station (I2RT YAM).

Staged loop, every stage closed on the overhead depth image, the fixture tracker or the joint readings:
  1. watch for faults (gripper echo, frozen camera) on every tick;
  2. touch the bench at two free spots to measure the arm mount height and lean;
  3. per piece: view the crate with the arm parked, pick the piece that is easiest to reach with a top-down,
     force-limited grasp (close to the measured width minus a few millimetres), carry it over the tub, lower it
     to the rim and let go; check the hand is empty and the crate count went down;
  4. take the tub by its grip block from the handle side, lift it, carry it over the bowl, tip it about its own
     axis with the pouring lip held over the bowl centre, hold, set it upright;
  5. set the tub down on the drying mat, let go, back out, report done.
Joint servos are soft under load, so every joint target carries an integral correction learnt from the joint
readings while the arm is held still.
"""
from __future__ import annotations

import math
import time
import os

import mujoco
import numpy as np

# ---------------------------------------------------------------------------------------------- cell constants
CAM_POS = np.array([0.25, 0.0, 1.15])     # overhead camera (scene.xml); the model's value is used when it loads
CAM_X = np.array([0.0, -1.0, 0.0])
CAM_Y = np.array([1.0, 0.0, 0.0])
CAM_Z = np.cross(CAM_X, CAM_Y)
CAM_X0, CAM_Y0, CAM_Z0 = CAM_X.copy(), CAM_Y.copy(), CAM_Z.copy()   # as drawn; the fitted mount tilt turns these
CRATE_IN = (0.135, 0.092)
CRATE_OUT = (0.143, 0.100)
CRATE_FLOOR, CRATE_WALL_H = 0.008, 0.045
TUB_R_IN, TUB_R_TOP, TUB_H = 0.062, 0.078, 0.100   # inner radius at the floor and at the rim
TUB_R_OUT, TUB_R_BASE = 0.084, 0.068
TUB_GRIP = np.array([-0.096, 0.0, 0.060])
BOWL_TOP_Z, BOWL_TOP_R = 0.080, 0.118
MAT_TOP = 0.005
TUB_OPEN = 0.040                   # finger opening for the tub's 60 mm grip block
CROWD_M = 0.004                    # fingers this far into a neighbour's outline: roll the pieces apart first
DEBUG_PARK = bool(os.environ.get('FP2_DEBUG'))
TIP_BELOW_SITE = 0.0118
HOME = np.array([0.0, 1.20, 1.15, -1.25, 0.0, 0.0])
VIEW = np.array([-1.4, 0.3, 0.9, 0.2, 0.0, 0.0])      # arm folded up beside its base, out of the camera view
Z_SAFE = 0.15
# behaviour switches (all on in the reference)
CALIBRATE = True        # camera check of the arm height, finger reading offset
CAM_FIT = True         # fit the overhead camera's mount tilt from the arm's outline
MEASURE_HELD = True     # measure how the tub sits in the grip before pouring
NUDGE = True           # roll a piece out from a crate wall when no grasp reaches it
ROCK = True             # rock the tub at full tilt
FAULT_CHECKS = True     # gripper echo and camera stamp checks
PARK = True             # set the empty tub on its mat
GENTLE = True           # close a set distance past the measured width (False: close fully)
PICK_LIFT_Z = 0.14                 # site height for lifting a piece clear of the crate walls
SELF_GAP = 0.001                   # least clearance between the upper arm and the hand on a planned pour
SQUEEZE_MM = 0.0065                # close this far past the measured width (each finger): a few newtons per pad
VIEW_SEED = np.array([0.0, 1.2, 1.2, -1.2, 0.0, 0.0])
OPEN = 0.0475


# ---------------------------------------------------------------------------------------------- small helpers
def yaw_of(q):
  return math.atan2(2 * (q[0] * q[3] + q[1] * q[2]), 1 - 2 * (q[2] ** 2 + q[3] ** 2))


def rotvec(axis, ang):
  a = np.asarray(axis, float)
  n = float(np.linalg.norm(a))
  if n < 1e-9 or abs(ang) < 1e-12:
    return np.eye(3)
  a = a / n
  K = np.array([[0, -a[2], a[1]], [a[2], 0, -a[0]], [-a[1], a[0], 0]])
  return np.eye(3) + math.sin(ang) * K + (1 - math.cos(ang)) * K @ K


def rot_err(Rc, R):
  """Rotation vector that takes Rc to R (world frame); correct for any angle, including near 180 deg."""
  quat = np.zeros(4)
  mujoco.mju_mat2Quat(quat, (R @ Rc.T).flatten())
  if quat[0] < 0:
    quat = -quat
  v = quat[1:]
  n = float(np.linalg.norm(v))
  if n < 1e-12:
    return np.zeros(3)
  return 2.0 * math.atan2(n, quat[0]) * v / n


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


def R_topdown(yaw):
  z = np.array([0, 0, -1.0])
  x = np.array([math.cos(yaw), math.sin(yaw), 0.0])
  return np.stack([x, np.cross(z, x), z], 1)


def R_approach(yaw, pitch):
  z = np.array([math.cos(yaw) * math.cos(pitch), math.sin(yaw) * math.cos(pitch), -math.sin(pitch)])
  y = np.array([-math.sin(yaw), math.cos(yaw), 0.0])
  return np.stack([np.cross(y, z), y, z], 1)


def to_local(xy, cx, cy, yaw):
  c, s = math.cos(yaw), math.sin(yaw)
  d = xy - np.array([cx, cy])
  return np.stack([c * d[..., 0] + s * d[..., 1], -s * d[..., 0] + c * d[..., 1]], -1)


def label(mask):
  h, w = mask.shape
  lab = np.zeros((h, w), np.int32)
  n = 0
  ys, xs = np.nonzero(mask)
  for y0, x0 in zip(ys, xs):
    if lab[y0, x0]:
      continue
    n += 1
    stack = [(y0, x0)]
    lab[y0, x0] = n
    while stack:
      y, x = stack.pop()
      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] = n
          stack.append((yy, xx))
  return lab, n


def fit_circle_r(xy, r, c0, iters=20):
  c = np.array(c0, float)
  for _ in range(iters):
    d = xy - c
    dist = np.linalg.norm(d, axis=1) + 1e-9
    res = dist - r
    J = -d / dist[:, None]
    step, *_ = np.linalg.lstsq(J, -res, rcond=None)
    c += np.clip(step, -0.02, 0.02)
    if np.linalg.norm(step) < 1e-5:
      break
  return c


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


class Finished(Exception):
  pass


# ---------------------------------------------------------------------------------------------- kinematics
class Kin:
  def __init__(self, xml):
    self.m = mujoco.MjModel.from_xml_path(xml)
    self.d = mujoco.MjData(self.m)
    m = self.m
    self.arm = [m.joint(f"robot/joint{i}").id for i in range(1, 7)]
    self.qa = np.array([m.jnt_qposadr[j] for j in self.arm])
    self.va = np.array([m.jnt_dofadr[j] for j in self.arm])
    self.lo = m.jnt_range[self.arm, 0] + 0.03
    self.hi = m.jnt_range[self.arm, 1] - 0.03
    self.sid = m.site("robot/grasp_site").id
    self.jp = np.zeros((3, m.nv))
    self.jr = np.zeros((3, m.nv))
    self.fing = [m.jnt_qposadr[m.joint(f"robot/{n}_finger").id] for n in ("left", "right")]
    self.crate = m.body("crate").id
    self.crate_geoms = set(g for g in range(m.ngeom) if m.geom_bodyid[g] == self.crate)
    self.robot_bodies = set(b for b in range(m.nbody) if m.body(b).name.startswith("robot/"))
    # loose things out of the way: only the arm and the fixed fixtures take part in clash checks
    for j in range(m.njnt):
      if m.jnt_type[j] == mujoco.mjtJoint.mjJNT_FREE:
        a = m.jnt_qposadr[j]
        self.d.qpos[a:a + 7] = (-2.0 - 0.3 * j, 2.0, 0.5, 1, 0, 0, 0)

    # pairs of arm parts that can meet when the wrist folds back under a load
    def geoms(names):
      ids = [m.body(n).id for n in names]
      return [g for g in range(m.ngeom) if m.geom_bodyid[g] in ids and m.geom_contype[g] + m.geom_conaffinity[g] > 0]
    upper = geoms(["robot/arm", "robot/link_2", "robot/link_3"])
    hand = geoms(["robot/link_5", "robot/link_6", "robot/left_finger", "robot/right_finger", "robot/left_pad",
                  "robot/right_pad", "robot/wrist_camera"])
    self.self_pairs = [(a, b) for a in upper for b in hand]
    self.hand_idx = np.array(hand)
    self.crate_idx = np.array(sorted(self.crate_geoms))
    self.tub_adr = m.jnt_qposadr[m.body_jntadr[m.body("tub").id]]
    self.bowl_adr = m.jnt_qposadr[m.body_jntadr[m.body("bowl").id]]
    tub_g = [g for g in range(m.ngeom) if m.geom_bodyid[g] == m.body("tub").id and m.geom_contype[g] + m.geom_conaffinity[g] > 0]
    bowl_g = [g for g in range(m.ngeom) if m.geom_bodyid[g] == m.body("bowl").id and m.geom_contype[g] + m.geom_conaffinity[g] > 0]
    self.tub_bowl_idx = (np.array(tub_g), np.array(bowl_g))
    self.arm_idx = np.array([g for g in range(m.ngeom) if m.geom_bodyid[g] in self.robot_bodies
                             and m.geom_contype[g] + m.geom_conaffinity[g] > 0])
    self._ft = np.zeros(6)

  def self_gap(self, q, cap=0.05):
    """Smallest distance between the upper arm and the hand at joint angles q (m, capped at `cap`)."""
    self.d.qpos[self.qa] = q
    mujoco.mj_kinematics(self.m, self.d)
    best = cap
    for a, b in self.self_pairs:
      best = min(best, mujoco.mj_geomDistance(self.m, self.d, a, b, cap, self._ft))
    return best

  def tub_bowl_gap(self, pt, Rt, bowl_xy, cap=0.05):
    """Smallest distance between the tub at (pt, Rt) and the bowl standing at bowl_xy."""
    q = np.zeros(4)
    mujoco.mju_mat2Quat(q, np.asarray(Rt, float).flatten())
    self.d.qpos[self.tub_adr:self.tub_adr + 3] = pt
    self.d.qpos[self.tub_adr + 3:self.tub_adr + 7] = q
    self.d.qpos[self.bowl_adr:self.bowl_adr + 7] = (bowl_xy[0], bowl_xy[1], 0.0, 1, 0, 0, 0)
    mujoco.mj_kinematics(self.m, self.d)
    best = cap
    ta, ba = self.tub_bowl_idx
    xp, rb = self.d.geom_xpos, self.m.geom_rbound
    near = (np.linalg.norm(xp[ta][:, None, :] - xp[ba][None, :, :], axis=2) - rb[ta][:, None] - rb[ba][None, :]) < best
    for i, j in zip(*np.nonzero(near)):
      best = min(best, mujoco.mj_geomDistance(self.m, self.d, int(ta[i]), int(ba[j]), cap, self._ft))
    self.d.qpos[self.tub_adr:self.tub_adr + 7] = (-3.0, 2.0, 0.5, 1, 0, 0, 0)
    self.d.qpos[self.bowl_adr:self.bowl_adr + 7] = (-3.5, 2.0, 0.5, 1, 0, 0, 0)
    return best

  def arm_bowl_gap(self, q, finger, bowl_xyz, cap=0.05):
    """Smallest distance between the arm at joint angles q (fingers at `finger`) and the bowl standing at
    bowl_xyz (model frame)."""
    self.d.qpos[self.qa] = q
    self.d.qpos[self.fing] = finger
    self.d.qpos[self.bowl_adr:self.bowl_adr + 7] = (bowl_xyz[0], bowl_xyz[1], bowl_xyz[2], 1, 0, 0, 0)
    mujoco.mj_kinematics(self.m, self.d)
    ha, ba = self.arm_idx, self.tub_bowl_idx[1]
    xp, rb = self.d.geom_xpos, self.m.geom_rbound
    near = (np.linalg.norm(xp[ha][:, None, :] - xp[ba][None, :, :], axis=2) - rb[ha][:, None] - rb[ba][None, :]) < cap
    best = cap
    for i, j in zip(*np.nonzero(near)):
      best = min(best, mujoco.mj_geomDistance(self.m, self.d, int(ha[i]), int(ba[j]), cap, self._ft))
    self.d.qpos[self.bowl_adr:self.bowl_adr + 7] = (-3.5, 2.0, 0.5, 1, 0, 0, 0)
    return best

  def place_crate(self, x, y, yaw, z=0.0):
    self.m.body_pos[self.crate] = (x, y, z)
    self.m.body_quat[self.crate] = (math.cos(yaw / 2), 0, 0, math.sin(yaw / 2))

  def clash_crate(self, q, finger, margin=0.003):
    """How far (m) the hand comes inside `margin` of the crate at joint angles q, fingers at `finger` (> 0: too
    close or touching)."""
    self.d.qpos[self.qa] = q
    self.d.qpos[self.fing] = finger
    mujoco.mj_kinematics(self.m, self.d)
    ha, ca = self.hand_idx, self.crate_idx
    xp, rb = self.d.geom_xpos, self.m.geom_rbound
    near = (np.linalg.norm(xp[ha][:, None, :] - xp[ca][None, :, :], axis=2) - rb[ha][:, None] - rb[ca][None, :]) < margin
    best = margin
    for i, j in zip(*np.nonzero(near)):
      best = min(best, mujoco.mj_geomDistance(self.m, self.d, int(ha[i]), int(ca[j]), margin, self._ft))
    return margin - best

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

  def ik(self, pos, R, q0, iters=150, wrot=0.35, tol=3e-4):
    q = np.array(q0, float)
    ep = er = np.zeros(3)
    m, d, sid, va = self.m, self.d, self.sid, self.va
    J = np.empty((6, len(va)))
    e = np.empty(6)
    quat = np.empty(4)
    reg = 2e-4 * np.eye(6)
    tol2, rtol2 = tol * tol, 9e-6
    for _ in range(iters):
      d.qpos[self.qa] = q
      mujoco.mj_kinematics(m, d)
      mujoco.mj_comPos(m, d)
      ep = pos - d.site_xpos[sid]
      # rotation vector taking the current hand to R (any angle)
      mujoco.mju_mat2Quat(quat, (R @ d.site_xmat[sid].reshape(3, 3).T).ravel())
      if quat[0] < 0:
        quat *= -1
      v = quat[1:]
      n = math.sqrt(float(v @ v))
      er = (2.0 * math.atan2(n, quat[0]) / n) * v if n > 1e-12 else np.zeros(3)
      if float(ep @ ep) < tol2 and float(er @ er) < rtol2:
        break
      mujoco.mj_jacSite(m, d, self.jp, self.jr, sid)
      J[:3] = self.jp[:, va]
      J[3:] = self.jr[:, va]
      J[3:] *= wrot
      e[:3] = ep
      e[3:] = er
      e[3:] *= wrot
      dq = J.T @ np.linalg.solve(J @ J.T + reg, e)
      q = np.minimum(np.maximum(q + np.minimum(np.maximum(dq, -0.2), 0.2), self.lo), self.hi)
    return q, math.sqrt(float(ep @ ep)), math.sqrt(float(er @ er))

  def ik_multi(self, pos, R, q0, seeds=()):
    best = self.ik(pos, R, q0)
    if best[1] < 1e-3 and best[2] < 1e-2:
      return best
    for s in seeds:
      s = np.array(s, float)
      s[0] = math.atan2(pos[1], pos[0])
      c = self.ik(pos, R, s, 250)
      if c[1] + 0.05 * c[2] < best[1] + 0.05 * best[2]:
        best = c
      if best[1] < 1e-3 and best[2] < 1e-2:
        break
    return best


SEEDS = ([0, 1.2, 1.2, -1.2, 0, 0], [0, 1.5, 1.0, 0.5, 0, 0], [0, 1.0, 0.5, 1.0, 0, 1.5], [0, 0.6, 0.4, 0.3, 0, 0],
         [0, 1.2, 0.8, 0.5, 1.0, -1.0], [0, 1.2, 0.8, 0.5, -1.0, 1.0], [0, 1.8, 1.4, -0.6, 0, 0])


# ---------------------------------------------------------------------------------------------- controller
class Controller:
  def __init__(self, model_info: dict):
    self.info = model_info
    xml = model_info.get("scene_xml", "/app/scene.xml")
    if not os.path.isfile(xml):
      xml = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scene.xml")
    self.K = Kin(xml)
    global CAM_POS, CAM_X, CAM_Y, CAM_Z
    try:
      CAM_POS = np.array(self.K.m.cam_pos[self.K.m.camera("overhead").id], float)
    except Exception:
      pass
    CAM_X, CAM_Y, CAM_Z = CAM_X0.copy(), CAM_Y0.copy(), CAM_Z0.copy()
    self.dt = float(model_info["control_dt_s"])
    self.jn = list(model_info["joint_names"])
    self.ia = [self.jn.index(f"robot/joint{i}") for i in range(1, 7)]
    self.ifl = self.jn.index("robot/left_finger")
    self.ifr = self.jn.index("robot/right_finger")
    cams = {c["name"]: c for c in model_info.get("cameras", [])}
    self.fovy = float(cams.get("overhead", {}).get("fovy_deg", 46.0))
    self._ray_cache = None

  # -------------------------------------------------------------------------------------- runtime
  def reset(self, obs):
    self.obs = obs
    self.q_des = np.asarray(obs["qpos"], float)[self.ia].copy()
    self.grip = float(obs["ctrl"][6])
    self.bias = np.zeros(6)
    self.freeze_bias = False
    self.sent_grip = [self.grip] * 4       # the last few gripper commands (the echo may be a tick or two old)
    self.cam_stamp = obs.get("camera_stamp")
    self.cam_stamp_t = obs["time"]
    self.last_img = None
    self.noise_seen = False
    self.same_count = 0
    self.frames = 0
    self.tub = self.bowl = None
    self.finger_bias = 0.0
    self.failed = []                  # (xy, yaw, why) of picks that did not come up with the piece
    self.nudged = []                  # where pieces were rolled away from a wall
    self.fail_kind = "miss"
    self.zcal = (0.0, 0.0)            # arm mount: model z error = a + b * x (metres)
    self.gen = self.main()
    self.done = None

  def act(self, obs):
    self.obs = obs
    try:
      if FAULT_CHECKS:
        self.check_faults(obs)
      if self.done is not None:
        return self.done
      t0 = time.perf_counter()
      try:
        out = self.compose(next(self.gen))
      finally:
        dt = time.perf_counter() - t0
        self.cpu_s = getattr(self, "cpu_s", 0.0) + dt
      if dt > 1.0:
        self.log("slow tick", round(dt, 2), "s")
      return out
    except Abort as e:
      self.done = {"status": "abort", "fault": e.fault}
      return self.done
    except (StopIteration, Finished):
      self.log("controller time", round(getattr(self, "cpu_s", 0.0), 1), "s")
      self.done = {"status": "done"}
      return self.done
    except Exception:
      if os.environ.get("FP2_DEBUG"):
        import traceback
        traceback.print_exc()
      raise

  def log(self, *a):
    if os.environ.get("FP2_DEBUG"):
      import sys
      print(f"[{self.obs['time']:6.2f}]", *a, file=sys.stderr, flush=True)

  def compose(self, _):
    if os.environ.get("FP2_SNAP") and self.frames % 25 == 0:
      from PIL import Image
      Image.fromarray(self.obs["images"]["overhead"]).save(f"{os.environ['FP2_SNAP']}/f{int(self.obs['time']*10):05d}.png")
    q = np.asarray(self.obs["qpos"], float)[self.ia]
    if not self.freeze_bias:
      self.bias = np.clip(self.bias + 0.05 * (self.q_des - q), -0.25, 0.25)
    cmd = np.zeros(7)
    cmd[:6] = self.q_des + self.bias
    # the station limits how far a command may move per tick: stay inside it so the echo check stays exact
    cmd[6] = self.sent_grip[-1] + float(np.clip(self.grip - self.sent_grip[-1], -0.012, 0.012))
    lo, hi = np.asarray(self.info["ctrl_low"]), np.asarray(self.info["ctrl_high"])
    cmd = np.clip(cmd, lo, hi)
    self.sent_grip = self.sent_grip[1:] + [float(cmd[6])]
    return cmd

  # -------------------------------------------------------------------------------------- faults
  def check_faults(self, obs):
    # dead gripper: the echoed gripper command differs from what we sent
    echo = float(obs["ctrl"][6])
    if self.frames > 4 and min(abs(echo - g) for g in self.sent_grip) > 1e-6:
      self.log("gripper echo", echo, "sent", self.sent_grip)
      raise Abort("dead_gripper")
    self.frames += 1
    st = obs.get("camera_stamp")
    img = obs.get("images", {}).get("overhead")
    if st is None or img is None:
      return
    if st != self.cam_stamp:
      if self.last_img is not None:
        same = np.array_equal(img, self.last_img)
        if not same:
          self.noise_seen = True
          self.same_count = 0
        elif self.noise_seen:
          self.same_count += 1
          if self.same_count >= 2:
            raise Abort("perception_freeze")
      self.last_img = img
      self.cam_stamp, self.cam_stamp_t = st, obs["time"]
    elif obs["time"] - self.cam_stamp_t > 1.6:
      raise Abort("perception_freeze")

  # -------------------------------------------------------------------------------------- motion
  def qm(self):
    return np.asarray(self.obs["qpos"], float)[self.ia]

  def finger(self):
    """Finger opening (m per finger), both fingers averaged, less the reading offset found at the start."""
    q = self.obs["qpos"]
    return 0.5 * (float(q[self.ifl]) + float(q[self.ifr])) - self.finger_bias

  def measure_finger_bias(self):
    """With the hand empty and still, the fingers sit where they were sent: what the readings add to that is
    their offset."""
    vals = []
    for _ in range(10):
      q = self.obs["qpos"]
      vals.append(0.5 * (float(q[self.ifl]) + float(q[self.ifr])) - self.grip)
      yield
    self.finger_bias = float(np.clip(np.median(vals), -0.012, 0.012))
    self.log("finger bias", round(self.finger_bias, 4))

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

  def move_q(self, q1, vmax=1.2, tmin=0.4):
    q0 = self.q_des.copy()
    q1 = np.clip(q1, self.K.lo, self.K.hi)
    T = max(tmin, float(np.max(np.abs(q1 - q0))) / vmax * 1.875)
    n = max(1, int(round(T / self.dt)))
    for i in range(1, n + 1):
      s = i / n
      s = 10 * s ** 3 - 15 * s ** 4 + 6 * s ** 5
      self.q_des = q0 + (q1 - q0) * s
      yield

  def w2m(self, p):
    """World target -> model target, with the measured mount height and lean."""
    p = np.array(p, float)
    p[2] += self.zcal[0] + self.zcal[1] * p[0]
    return p

  def solve(self, p, R, q0=None):
    q, ep, er = self.K.ik_multi(self.w2m(p), R, self.q_des if q0 is None else q0, SEEDS)
    return q, ep < 2e-3 and er < 2e-2

  def move_pose(self, p, R, vmax=1.0, tmin=0.4):
    q, ok = self.solve(p, R)
    yield from self.move_q(q, vmax, tmin)
    return ok

  def plan_line(self, p1, R1, speed=0.08, tmin=0.25, q0=None, quiet=False, strict=False):
    """Joint path for a straight tool path from q0 (default: the commanded pose) to (p1, R1), or None if it
    leaves the reachable set or jumps between arm branches."""
    q0 = self.q_des if q0 is None else q0
    p0m, R0 = self.K.fk(q0)
    p1m = self.w2m(p1)
    L = float(np.linalg.norm(p1m - p0m))
    T = max(tmin, L / speed * 1.875)
    n = max(1, int(round(T / self.dt)))
    # orientation interpolation by axis-angle
    Rd = R1 @ R0.T
    ang = math.acos(float(np.clip((np.trace(Rd) - 1) / 2, -1, 1)))
    if ang > 1e-6:
      ax = np.array([Rd[2, 1] - Rd[1, 2], Rd[0, 2] - Rd[2, 0], Rd[1, 0] - Rd[0, 1]]) / (2 * math.sin(ang))
    else:
      ax = np.array([0, 0, 1.0])
    q = np.array(q0, float)
    path = []
    for i in range(1, n + 1):
      s = i / n
      s = 10 * s ** 3 - 15 * s ** 4 + 6 * s ** 5
      pm = p0m + (p1m - p0m) * s
      Rm = rotvec(ax, ang * s) @ R0
      q2, ep, er = self.K.ik(pm, Rm, q, 40)
      jump = float(np.max(np.abs(q2 - q)))
      if strict and (ep > 3e-3 or er > 0.03):
        if not quiet:
          self.log("line: off the path at step", i, "of", n, "ep", round(ep, 4), "er", round(er, 3))
        return None
      if jump > 0.35:
        if not quiet:
          self.log("line: step", i, "of", n, "ep", round(ep, 4), "er", round(er, 3), "jump", round(jump, 3))
        return None
      path.append(q2)
      q = q2
    return path

  def straight_ok(self, p1, R1, speed=0.12, q0=None):
    return self.plan_line(p1, R1, speed, q0=q0, quiet=True) is not None

  def line(self, p1, R1, speed=0.08, tmin=0.25, guard=None, strict=False):
    """Straight tool path from the current commanded pose to (p1, R1). With `guard`, stop where the tool is
    held up by something below it and return False."""
    # plan the whole path first; if it leaves the reachable set or jumps between arm branches, go in joint space
    path = self.plan_line(p1, R1, speed, tmin, strict=strict)
    if path is None:
      qf, ok = self.solve(p1, R1)
      self.log("line: no straight path, joint move instead", ok)
      yield from self.move_q(qf, 1.0)
      return
    zm, zc = [], []
    for q2 in path:
      self.q_des = self.q_des + np.clip(q2 - self.q_des, -0.05, 0.05)
      yield
      if guard is not None:
        zm.append(float(self.K.fk(self.qm())[0][2]))
        zc.append(float(self.K.fk(self.q_des)[0][2]))
      # held up: the command went down by `guard` over the last 5 ticks while the tool barely moved
      if guard is not None and len(zm) > 8 and zc[-6] - zc[-1] > guard and zm[-6] - zm[-1] < 0.25 * (zc[-6] - zc[-1]) \
          and zm[-1] - zc[-1] > guard:
        self.q_des = self.qm()
        self.log("line: blocked at", np.round(self.K.fk(self.qm())[0], 3), "zm", np.round(zm, 4).tolist(), "zc", np.round(zc, 4).tolist())
        return False
    for _ in range(25):
      if float(np.max(np.abs(path[-1] - self.q_des))) < 1e-4:
        break
      self.q_des = self.q_des + np.clip(path[-1] - self.q_des, -0.05, 0.05)
      yield
    return True

  def clear_z(self, xy):
    """Lowest safe tool height over a bench point: above the tub rim with a piece hanging below the fingers."""
    z = 0.0
    if self.tub is not None and float(np.linalg.norm(np.asarray(xy) - self.tub["xy"])) < 0.14:
      z = max(z, TUB_H + 0.045)
    if self.bowl is not None and float(np.linalg.norm(np.asarray(xy) - self.bowl["xy"])) < 0.15:
      z = max(z, BOWL_TOP_Z + 0.075)
    return z

  def path_clear(self, qa, qb):
    """Joint-space move from qa to qb keeps the tool above the vessels and does not dip below its ends."""
    za = self.K.fk(qa)[0][2]
    zb = self.K.fk(qb)[0][2]
    for s in np.linspace(0.1, 0.9, 9):
      p, _ = self.K.fk(qa + (qb - qa) * s)
      if p[2] < min(za, zb) - 0.015 or p[2] < self.clear_z(p[:2]) - 0.01:
        return False
    return True

  def travel(self, p, R, vmax=1.8, z_safe=Z_SAFE, speed=0.15, seed=None):
    """Up to the safe height where we are, across at the safe height (through a raised via point), then
    straight down to (p, R). `seed` picks the arm branch for the end pose."""
    pm, Rm = self.K.fk(self.q_des)
    pw = pm - np.array([0, 0, self.zcal[0] + self.zcal[1] * pm[0]])
    if pw[2] < z_safe - 0.01:
      yield from self.line(np.array([pw[0], pw[1], z_safe]), Rm, speed=speed)
      pw[2] = z_safe
    above = np.array([p[0], p[1], max(z_safe, p[2])])
    if seed is None:
      seed = np.array(SEEDS[0], float)
      seed[0] = math.atan2(p[1], p[0])
    q_end, ok = self.solve(p, R, seed)
    q1, ok1 = self.solve(above, R, q_end) if p[2] < above[2] - 1e-4 else (q_end, ok)
    if not self.path_clear(self.q_des, q1):
      mid = (pw + above) / 2
      mid[2] = max(pw[2], above[2], self.clear_z(mid[:2])) + 0.03
      q_via, okv = self.solve(mid, R, q1)
      self.log("travel via", np.round(mid, 3), okv)
      yield from self.move_q(q_via, vmax)
    yield from self.move_q(q1, vmax)
    if p[2] < above[2] - 1e-4:
      yield from self.line(p, R, speed=speed)
    return ok

  def grip_to(self, target, secs=0.4):
    g0 = self.grip
    n = max(1, int(round(secs / self.dt)))
    for i in range(1, n + 1):
      self.grip = g0 + (target - g0) * i / n
      yield

  # -------------------------------------------------------------------------------------- perception
  def fresh_frame(self, settle=0.25):
    """Wait until a camera frame taken after now (and after the arm stopped) has arrived."""
    yield from self.wait(settle)
    t0 = self.obs["time"]
    for _ in range(200):
      st = self.obs.get("camera_stamp")
      if st is not None and st > t0 + 1e-6:
        break
      yield
    return self.cloud()

  def cloud(self, dep=None):
    dep = (self.obs["depth"]["overhead"] if dep is None else dep).astype(np.float64)
    h, w = dep.shape
    if self._ray_cache is None or self._ray_cache[0] != (h, w):
      f = (h / 2) / math.tan(math.radians(self.fovy) / 2)
      u = (np.arange(w) + 0.5 - w / 2) / f
      v = -(np.arange(h) + 0.5 - h / 2) / f
      uu, vv = np.meshgrid(u, v)
      self._ray_cache = ((h, w), uu, vv)
    _, uu, vv = self._ray_cache
    pts = CAM_POS[None, None, :] + (uu * dep)[..., None] * CAM_X + (vv * dep)[..., None] * CAM_Y - dep[..., None] * CAM_Z
    valid = (dep > 0.2) & (dep < 1.5)
    return pts, valid

  def crate_pose(self):
    c = self.obs["objects"]["crate"]
    return float(c[0]), float(c[1]), yaw_of(c[3:7])

  def mat_pose(self):
    c = self.obs["objects"]["mat"]
    return float(c[0]), float(c[1]), yaw_of(c[3:7])

  def find_fruit(self, pts, valid):
    cx, cy, cyaw = self.crate_pose()
    loc = to_local(pts[..., :2], cx, cy, cyaw)
    # keep 10 mm off the walls: a camera a little off its mount sees the wall tops inside the crate outline
    inside = (np.abs(loc[..., 0]) < CRATE_IN[0] - 0.010) & (np.abs(loc[..., 1]) < CRATE_IN[1] - 0.010)
    mask = valid & inside & (pts[..., 2] > CRATE_FLOOR + 0.014) & (pts[..., 2] < 0.12)
    lab, n = label(mask)
    out = []
    blobs = []
    for i in range(1, n + 1):
      sel = lab == i
      if sel.sum() < 10:
        continue
      p = pts[sel]
      # two pieces touching make one blob, longer than any single piece: split it in two along its length
      xy = p[:, :2] - p[:, :2].mean(0)
      ev, evec = np.linalg.eigh(np.cov(xy.T))
      t = xy @ evec[:, 1]
      if float(np.ptp(t)) / 2 > 0.047:
        c1, c2 = float(t.min()), float(t.max())
        for _ in range(10):
          a = np.abs(t - c1) < np.abs(t - c2)
          if a.all() or (~a).all():
            break
          c1, c2 = float(t[a].mean()), float(t[~a].mean())
        blobs += [p[a], p[~a]]
      else:
        blobs.append(p)
    for p in blobs:
      if len(p) < 10:
        continue
      top = float(np.percentile(p[:, 2], 90))
      xy = p[:, :2]
      up = p[:, 2] > top - 0.6 * (top - CRATE_FLOOR)
      c = xy[up].mean(0) if up.sum() >= 3 else xy.mean(0)
      cov = np.cov((xy - c).T)
      ev, evec = np.linalg.eigh(cov)
      major = evec[:, 1]
      ext_major = float(np.ptp((xy - c) @ major)) / 2 + 0.003
      ext_minor = float(np.ptp((xy - c) @ evec[:, 0])) / 2 + 0.003
      hh = (top - CRATE_FLOOR) / 2 + 0.001
      if hh < 0.012 or ext_minor < 0.012:     # too flat or too thin for a piece of fruit
        continue
      out.append({"xy": c, "top": top, "half_h": hh, "z": CRATE_FLOOR + hh,
                  "yaw_major": math.atan2(major[1], major[0]), "ext_major": ext_major, "ext_minor": ext_minor,
                  "elong": ext_major - ext_minor, "npx": int(len(p))})
    return out

  def find_vessels(self, pts, valid):
    cx, cy, cyaw = self.crate_pose()
    loc = to_local(pts[..., :2], cx, cy, cyaw)
    in_crate = (np.abs(loc[..., 0]) < CRATE_OUT[0] + 0.02) & (np.abs(loc[..., 1]) < CRATE_OUT[1] + 0.02)
    near_base = np.hypot(pts[..., 0], pts[..., 1]) < 0.16
    z = pts[..., 2]
    img = self.obs["images"]["overhead"].astype(np.float64)
    mx, mn = img.max(axis=2), img.min(axis=2)
    grey = (mx - mn) < 0.18 * np.maximum(mx, 1.0)
    mask = valid & ~in_crate & ~near_base & (z > 0.03) & (z < 0.125) & (pts[..., 0] > -0.08)
    lab, n = label(mask)
    res = {"tub": None, "bowl": None}
    for i in range(1, n + 1):
      sel = lab == i
      if sel.sum() < 15:
        continue
      p = pts[sel]
      g = grey[sel]
      xy = p[:, :2]
      span = float(np.max(np.ptp(xy, axis=0)))
      zmax = float(np.percentile(p[:, 2], 95))
      if 0.18 < span < 0.32 and 0.06 < zmax < 0.095:
        rim = xy[p[:, 2] > 0.06]
        res["bowl"] = {"xy": fit_circle_r(rim, 0.121, xy.mean(0))}
      elif 0.09 < span < 0.26 and zmax > 0.085:
        rimsel = (p[:, 2] > 0.088) & g
        if rimsel.sum() < 6:
          rimsel = p[:, 2] > 0.088
        rim = p[rimsel]
        c = rim[:, :2].mean(0)
        for _ in range(3):
          dd = np.linalg.norm(rim[:, :2] - c, axis=1)
          use = (dd > 0.058) & (dd < 0.098)
          if use.sum() < 6:
            break
          c = fit_circle_r(rim[use, :2], 0.081, c)
        dd = np.linalg.norm(xy - c, axis=1)
        hp = p[(dd > 0.089) & (dd < 0.116) & (p[:, 2] > 0.035) & (p[:, 2] < 0.092)]
        hyaw = None
        if len(hp) >= 4:
          v = hp[:, :2].mean(0) - c
          hyaw = math.atan2(v[1], v[0])
        res["tub"] = {"xy": c, "handle_dir": hyaw, "nhandle": len(hp)}
    return res

  # -------------------------------------------------------------------------------------- calibration
  def project(self, p):
    """World point -> (row, col) in the overhead image."""
    h, w = self.obs["depth"]["overhead"].shape
    f = (h / 2) / math.tan(math.radians(self.fovy) / 2)
    rel = np.asarray(p, float) - CAM_POS
    dep = -float(rel @ CAM_Z)
    col = float(rel @ CAM_X) / dep * f + w / 2 - 0.5
    row = -float(rel @ CAM_Y) / dep * f + h / 2 - 0.5
    return row, col

  def arm_height_error(self, pts, valid, q=None):
    """Height of the arm as seen by the depth camera minus its height in the model (same joint angles):
    cast the camera rays at the model arm and compare with the measured points around the gripper."""
    K = self.K
    K.d.qpos[K.qa] = self.qm() if q is None else q
    mujoco.mj_kinematics(K.m, K.d)
    site = K.d.site_xpos[K.sid].copy()
    r0, c0 = self.project(site + np.array([0, 0, 0.06]))
    h, w = pts.shape[:2]
    f = (h / 2) / math.tan(math.radians(self.fovy) / 2)
    grp = np.array([0, 0, 1, 0, 0, 0], np.uint8)
    gid = np.zeros(1, np.int32)
    diffs = []
    for r in range(max(0, int(r0) - 22), min(h, int(r0) + 23), 2):
      for c in range(max(0, int(c0) - 22), min(w, int(c0) + 23), 2):
        if not valid[r, c]:
          continue
        uu = (c + 0.5 - w / 2) / f
        vv = -(r + 0.5 - h / 2) / f
        vec = uu * CAM_X + vv * CAM_Y - CAM_Z
        dist = mujoco.mj_ray(K.m, K.d, CAM_POS, vec, grp, 0, -1, gid)
        if dist < 0:
          continue
        zp = CAM_POS[2] + dist * vec[2]
        dz = float(pts[r, c, 2]) - zp
        if abs(dz) < 0.05:
          diffs.append(dz)
    if len(diffs) < 25:
      return None
    return float(np.median(diffs)), len(diffs)

  def fit_camera_tilt(self, views):
    """Small turn of the overhead camera on its mount, from where the gripper's outline falls in the depth
    image compared with the model arm at the same joint angles (pixels on the arm in one and not the other)."""
    global CAM_X, CAM_Y, CAM_Z
    K = self.K
    grp = np.array([0, 0, 1, 0, 0, 0], np.uint8)
    data = []
    for dep, q in views:
      h, w = dep.shape
      f = (h / 2) / math.tan(math.radians(self.fovy) / 2)
      K.d.qpos[K.qa] = q
      mujoco.mj_kinematics(K.m, K.d)
      site = K.d.site_xpos[K.sid].copy()
      r0, c0 = self.project(site + np.array([0, 0, 0.04]))
      rr, cc = np.meshgrid(np.arange(max(0, int(r0) - 20), min(h, int(r0) + 21)),
                           np.arange(max(0, int(c0) - 20), min(w, int(c0) + 21)), indexing="ij")
      rr, cc = rr.ravel(), cc.ravel()
      d = dep[rr, cc].astype(np.float64)
      ok = (d > 0.2) & (d < 1.5)
      rr, cc, d = rr[ok], cc[ok], d[ok]
      uu = (cc + 0.5 - w / 2) / f
      vv = -(rr + 0.5 - h / 2) / f
      data.append((q, uu, vv, d))
    if not data or sum(len(x[3]) for x in data) < 200:
      return None
    yield

    def score(R):
      X, Y, Z = R @ CAM_X0, R @ CAM_Y0, R @ CAM_Z0
      tot = 0.0
      for q, uu, vv, d in data:
        K.d.qpos[K.qa] = q
        mujoco.mj_kinematics(K.m, K.d)
        vec = uu[:, None] * X + vv[:, None] * Y - Z
        n = len(d)
        dist = np.zeros(n)
        gid = np.zeros(n, np.int32)
        mujoco.mj_multiRay(K.m, K.d, CAM_POS, vec.ravel().copy(), grp, 0, -1, gid, dist, None, n, 3.0)
        # the gripper is held 140 mm up, clear of the bench and of the tub rim
        hit = (dist > 0) & (CAM_POS[2] + dist * vec[:, 2] > 0.118)
        on_arm = CAM_POS[2] + d * vec[:, 2] > 0.118
        tot += float(np.sum(hit == on_arm))
      return tot

    best = (score(np.eye(3)), 0.0, 0.0)
    base = best[0]
    for step, span in ((0.25, 2), (0.1, 1)):
      a0, b0 = best[1], best[2]
      for i in range(-span, span + 1):
        for j in range(-span, span + 1):
          a, b = a0 + i * step, b0 + j * step
          if (i, j) == (0, 0) or abs(a) > 1.2 or abs(b) > 1.2:
            continue
          R = rotvec(CAM_X0, math.radians(a)) @ rotvec(CAM_Y0, math.radians(b))
          sc = score(R)
          yield                          # spread the search over control ticks (each act call is timed)
          if sc > best[0] + 0.5 or (abs(sc - best[0]) <= 0.5 and abs(a) + abs(b) < abs(best[1]) + abs(best[2])):
            best = (sc, a, b)
    sc, a, b = best
    R = rotvec(CAM_X0, math.radians(a)) @ rotvec(CAM_Y0, math.radians(b))
    CAM_X, CAM_Y, CAM_Z = R @ CAM_X0, R @ CAM_Y0, R @ CAM_Z0
    self.log("camera tilt", round(a, 2), round(b, 2), "deg, agreement", int(base), "->", int(sc))
    return a, b

  def calibrate(self):
    """Mount height and lean from two views of the gripper (the camera is fixed to the station)."""
    meas = []
    views = []
    for x, y in ((0.22, -0.10), (0.40, -0.06)):
      R = R_topdown(math.atan2(y, x) + math.pi)
      q, _ = self.solve(np.array([x, y, 0.14]), R)
      yield from self.move_q(q, 1.8)
      yield from self.fresh_frame(0.35)
      views.append((self.obs["depth"]["overhead"].copy(), self.qm().copy()))
    if CAM_FIT:
      yield from self.fit_camera_tilt(views)
    for (x, y), (dep, q) in zip(((0.22, -0.10), (0.40, -0.06)), views):
      pts, valid = self.cloud(dep)
      e = self.arm_height_error(pts, valid, q)
      self.log("calib", (x, y), e)
      if e is not None:
        meas.append((x, e[0]))
    if len(meas) == 2:
      (x1, e1), (x2, e2) = meas
      b = -(e2 - e1) / (x2 - x1)
      a = -e1 - b * x1
      self.zcal = (float(np.clip(a, -0.04, 0.04)), float(np.clip(b, -0.06, 0.06)))
    elif len(meas) == 1:
      self.zcal = (float(np.clip(-meas[0][1], -0.04, 0.04)), 0.0)
    self.log("zcal", self.zcal)

  # -------------------------------------------------------------------------------------- main
  def main(self):
    yield
    self.pieces = int(self.obs.get("io", {}).get("pieces", 6))
    # park the arm high and to the side and take a picture of the station
    self.view_q = VIEW.copy()
    yield from self.move_q(self.view_q, 1.8)
    pts, valid = yield from self.fresh_frame(0.3)
    ves = self.find_vessels(pts, valid)
    self.tub, self.bowl = ves["tub"], ves["bowl"]
    self.log("vessels", ves)
    if CALIBRATE:
      yield from self.measure_finger_bias()
    if not os.environ.get("FP2_SKIP_PACK"):
      if CALIBRATE:
        yield from self.calibrate()
    yield from self.move_q(self.view_q, 1.8)
    # ---- pack
    packed = 0
    k_release = 0
    for attempt in range(0 if os.environ.get("FP2_SKIP_PACK") else self.pieces * 3):
      pts, valid = yield from self.fresh_frame(0.1)
      fruit = self.find_fruit(pts, valid)
      if not fruit:
        break
      if self.tub is None:
        ves = self.find_vessels(pts, valid)
        self.tub = ves["tub"]
        if self.tub is None:
          yield from self.go_view()
          continue
      choice = self.choose_fruit(fruit)
      # a piece that keeps failing, or that no grasp can reach (against a wall): roll it out into the bay
      stuck = [g for g in fruit if self.n_failed(g, "blocked") + self.n_failed(g, "slip") + self.n_failed(g, "miss") >= 2]
      if choice is not None and self.last_clash > 0 and self.n_failed(choice[0], "blocked") >= 1:
        stuck.append(choice[0])          # the only grasp left grazes the crate and has been blocked once
      if NUDGE and choice is None and self.crowded is not None:
        g, away = self.crowded
        self.log("fruit", [(np.round(f['xy'], 3).tolist(), round(f['half_h'], 3), round(f['elong'], 3)) for f in fruit])
        yield from self.nudge(g, away)
        self.failed = [x for x in self.failed if float(np.linalg.norm(x[0] - g["xy"])) >= 0.02]
        yield from self.go_view()
        continue
      if choice is None or any(choice[0] is g for g in stuck):
        cand = stuck or fruit
        g = min(cand, key=lambda g: self.n_nudged(g))
        if NUDGE and self.n_nudged(g) < 2:
          self.log("fruit", [(np.round(f['xy'], 3).tolist(), round(f['half_h'], 3), round(f['elong'], 3)) for f in fruit])
          yield from self.nudge(g)
          self.failed = [x for x in self.failed if float(np.linalg.norm(x[0] - g["xy"])) >= 0.02]
          yield from self.go_view()
          continue
      if choice is None and self.failed:
        self.failed = []                  # nothing new left to try: allow the grasps that failed before
        choice = self.choose_fruit(fruit)
      self.log("fruit", [(np.round(f['xy'], 3).tolist(), round(f['half_h'], 3), round(f['elong'], 3)) for f in fruit])
      if choice is None:
        break
      f, yaw = choice
      ok = yield from self.pick(f, yaw)
      self.log("pick", np.round(f['xy'], 3), round(math.degrees(yaw)), "ok", ok, "finger", round(self.finger(), 4), "grip", round(self.grip, 4))
      if not ok:
        self.failed.append((np.array(f["xy"], float), yaw, self.fail_kind))
      if ok:
        yield from self.drop_in_tub(f, k_release)
        k_release += 1
        packed += 1
      else:
        yield from self.go_view()
    # ---- tub: grasp, pour, park (look again with the arm out of the view: the drops may have nudged the tub)
    yield from self.move_q(self.view_q, 1.8)
    pts, valid = yield from self.fresh_frame(0.2)
    ves = self.find_vessels(pts, valid)
    self.log("vessels", ves)
    self.tub = ves["tub"] or self.tub
    self.bowl = ves["bowl"] or self.bowl
    if self.tub is None or self.bowl is None:
      raise Finished()
    used = []
    for attempt in range(2):
      key, pivot = yield from self.grasp_tub(tuple(used))
      used.append(key)
      if attempt == 1 or pivot is None or abs(pivot) < math.radians(10):
        break
      # the tub hangs askew in the grip: a pour and a set-down planned on it would go wrong; set it down and
      # take it again another way
      self.log("tub askew in the grip", round(math.degrees(pivot)), "deg: regrasp")
      yield from self.release_tub_here()
      yield from self.move_q(self.view_q, 1.8)
      pts, valid = yield from self.fresh_frame(0.2)
      ves = self.find_vessels(pts, valid)
      self.tub = ves["tub"] or self.tub
    yield from self.pour()
    if PARK:
      yield from self.park_tub()
    else:
      yield from self.leave_tub()
    yield from self.move_q(HOME, 1.2)
    self.log("home", np.round(self.qm() - self.q_des, 3))
    yield from self.wait(0.2)
    raise Finished()

  def go_view(self):
    pm, Rm = self.K.fk(self.q_des)
    if pm[2] < Z_SAFE - 0.01:
      yield from self.line(np.array([pm[0], pm[1], Z_SAFE]), Rm, speed=0.15)
    yield from self.move_q(self.view_q, 1.8)

  # -------------------------------------------------------------------------------------- pick and pack
  def choose_fruit(self, fruit):
    self.open_trim = 0.0
    self.last_clash = 0.0
    cx, cy, cyaw = self.crate_pose()
    cands = []
    nb_best = {}              # per piece: the most room any heading leaves the fingers from the neighbours
    nb_of = {}                # per piece and heading: room left from the neighbours
    self.crowded = None
    for i, f in enumerate(fruit):
      others = [g for j, g in enumerate(fruit) if j != i]
      if f["elong"] > 0.004:
        # across the short axis first; along the long axis or diagonally when the walls leave no room
        yaws = [f["yaw_major"] + math.radians(d) for d in (0, 15, -15, 45, -45, 90)]
        # then any other heading, for a piece lying against a wall
        yaws += [f["yaw_major"] + math.radians(d) for d in range(30, 180, 15) if d not in (45, 90, 135, 165)]
      else:
        yaws = [math.radians(a) for a in range(0, 180, 15)]
      pref = yaws[:6]
      tried = [fy for fxy, fy, kind in self.failed if kind == "blocked" and float(np.linalg.norm(fxy - f["xy"])) < 0.02]
      yaws = [y for y in yaws if all(abs(math.remainder(y - fy, math.pi)) > math.radians(25) for fy in tried)] or yaws
      for yaw in yaws:
        # closing axis (tool y) is perpendicular to the tool x = yaw
        u = np.array([-math.sin(yaw), math.cos(yaw)])
        half_open = self.open_for(f, yaw)
        clear = 1.0
        nb = 1.0
        for s in (-1, 1):
          tipc = f["xy"] + s * u * (half_open + 0.006)
          loc = to_local(tipc, cx, cy, cyaw)
          clear = min(clear, CRATE_IN[0] - abs(loc[0]) - 0.008, CRATE_IN[1] - abs(loc[1]) - 0.010)
          for g in others:
            nb = min(nb, float(np.linalg.norm(tipc - g["xy"])) - max(g["ext_major"], g["ext_minor"]) - 0.012)
        clear = min(clear, nb)
        nb_best[i] = max(nb_best.get(i, -1.0), nb)
        nb_of[(i, yaw)] = nb
        r = float(np.hypot(*f["xy"]))
        score = clear - 0.05 * max(0.0, r - 0.45)
        if f["elong"] > 0.004:
          score -= 0.02 * abs(math.sin(yaw - f["yaw_major"]))
          if not any(abs(yaw - p) < 1e-9 for p in pref):
            score -= 0.03
        cands.append((score, i, f, yaw))
    cands.sort(key=lambda c: -c[0])
    self.K.place_crate(cx, cy, cyaw, self.w2m(np.array([cx, cy, 0.0]))[2])   # in the model's frame, like the IK targets
    # pieces with room for the fingers between them and their neighbours first (a piece rolled against another
    # one is rolled apart, below, unless nothing else is left)
    free = [c for c in cands if nb_of[(c[1], c[3])] > -CROWD_M]
    if free:
      fallback = None
      for self.open_trim in (0.0, 0.003, 0.005):
        got = self._choose_pass(free)
        if got is not None and got[0] <= 0:
          self.last_clash = 0.0
          return got[1], got[2]
        if got is not None and (fallback is None or got[0] < fallback[0]):
          fallback = got + (self.open_trim,)
      if fallback is not None and fallback[0] < 0.003:
        self.open_trim = fallback[3]
        self.last_clash = fallback[0]
        return fallback[1], fallback[2]
    crowded = sorted({c[1] for c in cands if nb_of[(c[1], c[3])] <= -CROWD_M}, key=lambda i: -nb_best[i])
    if crowded:
      self.log("crowded", [np.round(fruit[i]["xy"], 3).tolist() for i in crowded])
      for i in crowded:
        if self.n_nudged(fruit[i]) < 2:
          f = fruit[i]
          g = min((g for j, g in enumerate(fruit) if j != i), key=lambda g: float(np.linalg.norm(g["xy"] - f["xy"])))
          self.crowded = (f, np.asarray(f["xy"], float) - np.asarray(g["xy"], float))
          self.open_trim = 0.0
          return None
    fallback = None
    # a piece against a wall or a neighbour: open the hand a little less than usual
    for self.open_trim in (0.0, 0.003, 0.005):
      got = self._choose_pass(cands)
      if got is not None and got[0] <= 0:
        self.last_clash = 0.0
        return got[1], got[2]
      if got is not None and (fallback is None or got[0] < fallback[0]):
        fallback = got + (self.open_trim,)
    if fallback is not None and fallback[0] < 0.005:
      self.open_trim = fallback[3]
      self.last_clash = fallback[0]
      return fallback[1], fallback[2]
    self.open_trim = 0.0
    return None

  def _choose_pass(self, cands):
    """First candidate whose open hand clears the crate (clash <= 0), else the least clashing one."""
    fallback = None
    for score, i, f, yaw in cands:
      gz = max(f["z"], CRATE_FLOOR + TIP_BELOW_SITE + 0.006)
      az = math.atan2(f["xy"][1], f["xy"][0])
      # of the two equivalent tool headings, try first the one that points back at the base (the reachable one
      # for a top-down hand)
      opts = sorted((yaw, yaw + math.pi), key=lambda a: abs(math.remainder(a - az - math.pi, 2 * math.pi)))
      for yy in opts:
        seed = np.array(SEEDS[0], float)
        seed[0] = az
        q1, ok1 = self.solve(np.array([f["xy"][0], f["xy"][1], gz]), R_topdown(yy), seed)
        if not ok1:
          continue
        q2, ok2 = self.solve(np.array([f["xy"][0], f["xy"][1], PICK_LIFT_Z]), R_topdown(yy), q1)
        if not ok2:
          continue
        # the open hand must go down past the crate walls without touching them
        half_open = self.open_for(f, yy) + 0.002
        clash = max([self.K.clash_crate(q1, half_open)] +
                    [self.K.clash_crate(self.solve(np.array([f["xy"][0], f["xy"][1], gz + dz]), R_topdown(yy), q1)[0],
                                        half_open) for dz in (0.012, 0.025, 0.04)])
        self.log("cand", np.round(f["xy"], 3), round(math.degrees(yy)), "clash", round(clash * 1000, 1),
                 "crate", np.round(self.crate_pose(), 3), "zcal", np.round(self.zcal, 4))
        if clash <= 0:
          return (clash, f, yy)
        if fallback is None or clash < fallback[0]:
          fallback = (clash, f, yy)
    return fallback

  @staticmethod
  def width_of(f, yaw=None):
    """Measured width of a piece across the jaws, the tool x axis at `yaw` (a sphere: its height; a lying
    ellipsoid: its outline across the closing line, the short axis when the jaws close across it)."""
    if f["elong"] <= 0.004:
      return float(np.clip(2 * f["half_h"], 0.036, 0.066))
    d = 0.0 if yaw is None else yaw - f["yaw_major"]
    a, b = f["ext_major"], min(f["ext_minor"], f["half_h"] + 0.004)
    w = math.sqrt((a * math.sin(d)) ** 2 + (b * math.cos(d)) ** 2)
    return float(np.clip(2 * w, 0.036, 0.076))

  def open_for(self, f, yaw=None):
    n_fail = self.n_failed(f, "blocked")
    return -getattr(self, "open_trim", 0.0) + min(OPEN, self.width_of(f, yaw) / 2 + 0.011 + 0.005 * min(n_fail, 2))

  def n_failed(self, f, kind):
    return sum(1 for fxy, _, k in self.failed if k == kind and float(np.linalg.norm(fxy - f["xy"])) < 0.02)

  def squeeze_for(self, f):
    """Squeeze depth: gentle (the peach bruises), a little firmer each time this piece slipped out."""
    return SQUEEZE_MM + 0.0015 * min(self.n_failed(f, "slip"), 2)

  def n_nudged(self, f):
    return sum(1 for xy in self.nudged if float(np.linalg.norm(xy - f["xy"])) < 0.03)

  def nudge(self, f, away_world=None):
    """Roll a piece away from the crate walls: rest the closed fingertips lightly on its top, behind the
    centre, and draw them towards the middle of the bay (a ball rolls half as far as the hand moves)."""
    self.nudged.append(np.array(f["xy"], float))
    cx, cy, cyaw = self.crate_pose()
    loc = to_local(f["xy"], cx, cy, cyaw)
    away = np.array([-math.copysign(max(0.0, abs(loc[0]) - (CRATE_IN[0] - 0.07)), loc[0]),
                     -math.copysign(max(0.0, abs(loc[1]) - (CRATE_IN[1] - 0.07)), loc[1])])
    if np.linalg.norm(away) < 1e-6:
      away = -np.asarray(loc, float)
    c, s_ = math.cos(cyaw), math.sin(cyaw)
    u = np.array([c * away[0] - s_ * away[1], s_ * away[0] + c * away[1]])
    if away_world is not None:
      # away from a neighbour, but not into a wall: drop the part of the push that heads into a near wall
      u = np.asarray(away_world, float) / (np.linalg.norm(away_world) + 1e-9)
      ul = np.array([c * u[0] + s_ * u[1], -s_ * u[0] + c * u[1]])
      for k in (0, 1):
        if abs(loc[k]) > CRATE_IN[k] - 0.05 and ul[k] * loc[k] > 0:
          ul[k] = 0.0
      if np.linalg.norm(ul) < 0.3:
        ul = -np.asarray(loc, float)
      u = np.array([c * ul[0] - s_ * ul[1], s_ * ul[0] + c * ul[1]])
    u /= np.linalg.norm(u) + 1e-9
    top = float(f.get("top", CRATE_FLOOR + 2 * f["half_h"]))
    p0 = np.asarray(f["xy"], float) - 0.008 * u
    az = math.atan2(p0[1], p0[0])
    R = None
    for yaw in (az + math.pi, az + math.pi + 0.5, az + math.pi - 0.5):
      q1, ok1 = self.solve(np.array([p0[0], p0[1], top]), R_topdown(yaw))
      q2, ok2 = self.solve(np.array([*(p0 + 0.035 * u), top]), R_topdown(yaw), q1)
      if ok1 and ok2:
        R = R_topdown(yaw)
        break
    if R is None:
      self.log("nudge: out of reach", np.round(f["xy"], 3))
      return
    self.log("nudge", np.round(f["xy"], 3), "towards", np.round(u, 2))
    yield from self.grip_to(0.0, 0.3)
    yield from self.travel(np.array([p0[0], p0[1], top + 0.05]), R, vmax=2.0, speed=0.2)
    yield from self.line(np.array([p0[0], p0[1], top + 0.012]), R, speed=0.1)
    # fingertips are TIP_BELOW_SITE under the tool point
    touched = yield from self.line(np.array([p0[0], p0[1], top + TIP_BELOW_SITE - 0.012]), R, speed=0.02, guard=0.002)
    pm, _ = self.K.fk(self.qm())
    zc = (pm[2] - self.zcal[0] - self.zcal[1] * pm[0]) if touched is False else top + TIP_BELOW_SITE - 0.004
    zc = max(zc, CRATE_WALL_H + TIP_BELOW_SITE + 0.004)
    p1 = p0 + 0.035 * u
    yield from self.line(np.array([p1[0], p1[1], zc]), R, speed=0.03)
    yield from self.line(np.array([p1[0], p1[1], zc + 0.06]), R, speed=0.1)

  def pick(self, f, yaw):
    """Top-down, force-limited grasp of one piece; True if the piece is in the hand above the crate."""
    R = R_topdown(yaw)
    width = self.width_of(f, yaw)
    half_open = self.open_for(f, yaw)
    xy = f["xy"]
    gz = max(f["z"], CRATE_FLOOR + TIP_BELOW_SITE + 0.006)
    above = np.array([xy[0], xy[1], PICK_LIFT_Z])
    yield from self.grip_to(half_open, 0.2)
    seed = np.array(SEEDS[0], float)
    seed[0] = math.atan2(xy[1], xy[0])
    q_g, _ = self.solve(np.array([xy[0], xy[1], gz]), R, seed)
    q_a, _ = self.solve(above, R, q_g)
    yield from self.travel(above, R, vmax=2.2, speed=0.25, seed=q_a)
    yield from self.line(np.array([xy[0], xy[1], gz + 0.035]), R, speed=0.22)
    yield from self.wait(0.3)
    down = yield from self.line(np.array([xy[0], xy[1], gz]), R, speed=0.08, guard=0.004)
    if down is False:
      # something under the fingers (a piece that moved): back off and look again
      self.fail_kind = "blocked"
      yield from self.grip_to(half_open, 0.1)
      yield from self.line(above, R, speed=0.18)
      return False
    yield from self.wait(0.1)
    # close a set distance past the measured width: a few newtons per pad on a piece of the measured size
    sq = self.squeeze_for(f)
    target = width / 2 - sq if GENTLE else -0.005
    if GENTLE:
      # never more than the squeeze past where the pads actually are: a piece pushed off centre meets one pad
      # early, and a set close would then press it into the wall or a neighbour
      g0 = self.grip
      n = int(round(0.3 / self.dt))
      for i in range(1, n + 1):
        self.grip = max(g0 + (target - g0) * i / n, self.finger() - sq - 0.001)
        yield
      for _ in range(int(round(0.2 / self.dt))):
        self.grip = max(target, self.finger() - sq - 0.001)
        yield
    else:
      yield from self.grip_to(target, 0.3)
    yield from self.wait(0.25)
    q_f = self.finger()
    holding = q_f > target + 0.0015 and q_f > 0.012
    pm, _ = self.K.fk(self.qm())
    self.log("grasp", "width", round(width, 4), "target", round(target, 4), "finger", round(q_f, 4), "gz", round(gz, 4), "site z model", round(pm[2], 4))
    # a piece wider than measured (the pads stopped early): back the command off to the same squeeze
    if holding and q_f - target > sq + 0.002:
      yield from self.grip_to(q_f - sq, 0.1)
      yield from self.wait(0.1)
    yield from self.line(above, R, speed=0.18)
    yield from self.wait(0.1)
    q_f = self.finger()
    if not (q_f > self.grip + 0.0015 and q_f > 0.012):
      self.fail_kind = "slip" if holding else "miss"
      yield from self.grip_to(half_open, 0.2)
      return False
    return True

  def drop_in_tub(self, f, k):
    c = np.asarray(self.tub["xy"], float)
    # release points a little in from the tub axis on the base side (inside the reach), spread round so the
    # pieces do not stack on one spot
    inward = math.atan2(-c[1], -c[0])
    ang = inward + math.radians((0, 55, -55, 25, -25, 80)[k % 6])
    rel = c + 0.024 * np.array([math.cos(ang), math.sin(ang)])
    az = math.atan2(rel[1], rel[0])
    hz = TUB_H + f["half_h"] + 0.008          # piece's underside just above the rim
    over_z = max(hz + 0.015, Z_SAFE)
    seed = np.array(SEEDS[0], float)
    seed[0] = az
    plan = None
    for yaw in (az + math.pi, az + math.pi + 0.6, az + math.pi - 0.6, az):
      R = R_topdown(yaw)
      q1, ok1 = self.solve(np.array([rel[0], rel[1], hz]), R, seed)
      q2, ok2 = self.solve(np.array([rel[0], rel[1], over_z]), R, q1)
      if ok1 and ok2:
        plan = (R, q2)
        break
    if plan is None:
      rel = c + 0.02 * np.array([math.cos(inward), math.sin(inward)])
      R = R_topdown(math.atan2(rel[1], rel[0]) + math.pi)
      q2, _ = self.solve(np.array([rel[0], rel[1], over_z]), R, seed)
      plan = (R, q2)
    R, q2 = plan
    over = np.array([rel[0], rel[1], over_z])
    yield from self.travel(over, R, vmax=1.6, speed=0.2, seed=q2)
    yield from self.line(np.array([rel[0], rel[1], hz]), R, speed=0.15)
    yield from self.wait(0.15)
    yield from self.grip_to(min(OPEN, self.finger() + 0.010), 0.15)
    yield from self.wait(0.3)
    yield from self.line(over, R, speed=0.2)

  # -------------------------------------------------------------------------------------- tub
  def tub_frame(self):
    c = np.asarray(self.tub["xy"], float)
    hd = self.tub["handle_dir"]
    if hd is None:
      hd = math.atan2(-c[1], -c[0])
    tub_yaw = hd + math.pi            # tub +x points from the handle to the axis
    return c, tub_yaw

  def bowl_gap_path(self, qs, finger=OPEN):
    """Least clearance between the hand (fingers at `finger`) and the bowl over a list of joint poses (no bowl
    seen: large)."""
    if self.bowl is None:
      return 1.0
    bxyz = self.w2m(np.array([self.bowl["xy"][0], self.bowl["xy"][1], 0.0]))
    return min(self.K.arm_bowl_gap(q, finger, bxyz) for q in qs)

  def park_reachable(self, R_grasp, tyaw):
    """Whether a tub held with the hand at R_grasp (tub yaw tyaw) can be set down upright on the mat with the
    handle within 60 deg of the base direction, and the hand withdrawn."""
    mx, my, _ = self.mat_pose()
    az = math.atan2(my, mx)
    R_rel = R_grasp.T @ rz(tyaw)
    for dh in (0, 30, -30, 60, -60):
      Rt = rz(az + math.radians(dh))
      Rp = Rt @ R_rel.T
      pp = np.array([mx, my, MAT_TOP + 0.006]) + Rt @ TUB_GRIP
      q1, ok1 = self.solve(pp, Rp, self.q_des)
      if ok1 and self.solve(pp + np.array([0, 0, 0.06]), Rp, q1)[1] and self.solve(pp - 0.10 * Rp[:, 2], Rp, q1)[1]:
        return True
    return False

  def grasp_tub(self, exclude=()):
    """Take the tub by its handle; returns the grasp used and the pivot of the tub in the grip as measured from
    above after the lift (None when not measured)."""
    c, tyaw = self.tub_frame()
    gp = np.array([c[0], c[1], 0.0]) + rz(tyaw) @ TUB_GRIP
    # jaws close across the block's flats; either way round
    # approach down the handle, pitched; the shallowest pitch that reaches the grip, the approach and the lift
    best = None
    combos = [(p_, 0.0) for p_ in (25.0, 35.0, 45.0, 15.0, 55.0, 65.0)]
    for pitch, dyaw in combos:
      R0 = R_approach(tyaw + math.radians(dyaw), math.radians(pitch))
      for roll in (0.0, math.pi):
        Rr = R0 @ rz(roll)
        qg, okg = self.solve(gp, Rr)
        _, okl = self.solve(gp + np.array([0, 0, 0.14]), Rr, qg)
        # come in along the handle from 10 cm back, or less where the arm cannot fold that far
        for back in (0.10, 0.075, 0.055):
          pre_r = gp - back * Rr[:, 2] + np.array([0, 0, 0.02])
          qp, okp = self.solve(pre_r + np.array([0, 0, 0.06]), Rr, qg)
          if okp:
            break
        cost = float(np.max(np.abs(qp - self.q_des))) + (0 if okg and okp and okl else 10) 
        # the hand comes in past the bowl: keep the open fingers and the wrist off its rim
        qpre, _ = self.solve(pre_r, Rr, qg)
        gap = self.bowl_gap_path([qp, qpre, qg, qpre + 0.5 * (qg - qpre)], TUB_OPEN)
        if gap < 0.012:
          cost += 3
        # the tub must also go down upright on its mat with this grip (the wrist's turn is limited)
        if not self.park_reachable(Rr, tyaw):
          cost += 5
        yield
        if DEBUG_PARK:
          self.log("tub grasp cand", pitch, roll, okg, okp, okl, back, "bowl gap", round(gap, 3), round(cost, 2))
        if (pitch, roll) in exclude:
          cost += 20
        if best is None or cost < best[0]:
          best = (cost, Rr, qp, pre_r, (pitch, roll))
      if best[0] < 3:
        break
    _, R, q1, pre, key = best
    self.tub_grasp = (gp, R, pre)
    # open only so far as the 60 mm block needs: wide-open fingers reach out sideways towards the bowl
    yield from self.grip_to(TUB_OPEN, 0.3)
    yield from self.move_q(q1, 1.2)
    yield from self.line(pre, R, speed=0.15)
    yield from self.line(gp, R, speed=0.08)
    yield from self.wait(0.2)
    # quickly to just short of the 60 mm block, then slowly onto it (a fast close knocks the fingers into it)
    yield from self.grip_to(0.036, 0.15)
    yield from self.grip_to(-0.005, 1.6)
    yield from self.wait(0.4)
    # grasp transform: tub frame in the tool frame (nominal)
    Rt = rz(tyaw)
    pt = np.array([c[0], c[1], 0.0])
    self.T_tool_tub = (R.T @ (pt - gp), R.T @ Rt)
    self.T_nom = self.T_tool_tub
    yield from self.line(gp + np.array([0, 0, 0.05]), R, speed=0.06)
    yield from self.wait(0.4)
    yield from self.line(gp + np.array([0, 0, 0.14]), R, speed=0.10)
    pts, valid = yield from self.fresh_frame(0.4)
    if MEASURE_HELD:
      got = self.measure_held_tub(pts, valid)
      return key, (None if got is None else got[0])
    return key, None

  def release_tub_here(self):
    """Put the tub back down where it was taken (the grip let it swing), open and back out."""
    gp, R, pre = self.tub_grasp
    yield from self.line(gp + np.array([0, 0, 0.004]), R, speed=0.05)
    yield from self.wait(0.4)
    yield from self.grip_to(OPEN, 0.5)
    yield from self.wait(0.3)
    yield from self.line(pre, R, speed=0.10)
    yield from self.line(pre + np.array([0, 0, 0.08]), R, speed=0.12)

  def tool_world(self):
    pm, Rm = self.K.fk(self.q_des)
    return pm - np.array([0, 0, self.zcal[0] + self.zcal[1] * pm[0]]), Rm

  def measure_held_tub(self, pts, valid):
    """The tub pivots and slides a little in the grip under its load. Find the rotation about the jaw axis and
    the vertical slip that best explain the rim heights seen from above, and update the grasp transform."""
    p_tool, R_tool = self.tool_world()
    p_rel, R_rel = self.T_tool_tub
    c_nom = p_tool + R_tool @ p_rel
    R_nom = R_tool @ R_rel
    h = R_nom[:, 0].copy(); h[2] = 0; h /= np.linalg.norm(h) + 1e-9
    img = self.obs["images"]["overhead"].astype(np.float64)
    mx, mn = img.max(axis=2), img.min(axis=2)
    grey = ((mx - mn) < 0.18 * np.maximum(mx, 1.0)) & (mx > 120)
    d = pts[..., :2] - p_tool[None, None, :2]
    u = d @ h[:2]
    w = d @ np.array([-h[1], h[0]])
    sel = valid & grey & (u > 0.07) & (u < 0.20) & (np.abs(w) < 0.085) & (pts[..., 2] > c_nom[2] - 0.05)
    if sel.sum() < 20:
      self.log("held tub: too few points", int(sel.sum()))
      return None
    us, zs = u[sel], pts[..., 2][sel]
    edges = np.arange(0.07, 0.201, 0.01)
    obs_z, mids = [], []
    for a, b in zip(edges[:-1], edges[1:]):
      m = (us >= a) & (us < b)
      if m.sum() >= 3:
        obs_z.append(float(np.percentile(zs[m], 90)))
        mids.append((a, b))
    if len(obs_z) < 4:
      return None
    obs_z = np.array(obs_z)
    phi = np.linspace(0, 2 * math.pi, 96, endpoint=False)
    rim_local = np.stack([TUB_R_OUT * np.cos(phi), TUB_R_OUT * np.sin(phi), np.full_like(phi, TUB_H)], 1)
    ay = R_tool[:, 1]
    best = None
    for th in np.radians(np.arange(-55, 55.1, 1.0)):
      Rr = rotvec(ay, th)
      Rt = Rr @ R_nom
      ct = p_tool + Rr @ (c_nom - p_tool)
      rim = ct + rim_local @ Rt.T
      ru = (rim[:, :2] - p_tool[:2]) @ h[:2]
      pred = []
      for a, b in mids:
        m = (ru >= a) & (ru < b)
        pred.append(rim[m, 2].max() if m.any() else np.nan)
      pred = np.array(pred)
      ok = ~np.isnan(pred)
      if ok.sum() < 3:
        continue
      dz = float(np.median(obs_z[ok] - pred[ok]))
      dz = float(np.clip(dz, -0.05, 0.015))
      err = float(np.mean((obs_z[ok] - pred[ok] - dz) ** 2)) + 1e-4 * (len(mids) - ok.sum())
      if best is None or err < best[0]:
        best = (err, th, dz, Rt, ct)
    if best is None:
      return None
    err, th, dz, Rt, ct = best
    if math.sqrt(err) > 0.009 or abs(th) > math.radians(50):
      self.log("held tub: fit rejected", round(math.degrees(th), 1), round(math.sqrt(err), 4))
      return None
    if os.environ.get("FP2_DUMP"):
      np.savez(f"{os.environ['FP2_DUMP']}_{int(self.obs['time'])}.npz", pts=pts, valid=valid, sel=sel, img=img, p_tool=p_tool,
               R_tool=R_tool, h=h, obs_z=obs_z, mids=np.array(mids), th=th, dz=dz, c_nom=c_nom, R_nom=R_nom)
    ct = ct + np.array([0, 0, dz])
    self.T_tool_tub = (R_tool.T @ (ct - p_tool), R_tool.T @ Rt)
    self.log("held tub: pivot", round(math.degrees(th), 1), "deg, slip", round(dz, 4), "rms", round(math.sqrt(err), 4))
    return th, dz

  def tool_for_tub(self, pt, Rt):
    """Tool pose that puts the held tub at (pt, Rt)."""
    p_rel, R_rel = self.T_tool_tub
    Rtool = Rt @ R_rel.T
    return pt - Rtool @ p_rel, Rtool

  def pour_plan(self):
    """Choose the tub heading over the bowl, the tipping side and the deepest tilt for which the whole pour
    is reachable."""
    b = np.asarray(self.bowl["xy"], float)
    base_heading = math.atan2(b[1], b[0])
    for gap_min, shift in ((SELF_GAP, 0.0), (SELF_GAP, 0.03), (SELF_GAP, 0.055), (-1.0, 0.0), (-1.0, 0.055)):
      for tmax in (132.0, 118.0, 105.0):
        best = None
        for dh in (0, 20, -20, 40, -40, 60, -60, 80, -80, 100, -100):
          heading = base_heading + math.radians(dh)
          for sign in (1, -1):
            yield                        # one candidate per control tick (each act call is timed)
            lip_dz = None
            for dz in (0.035, 0.05, 0.065, 0.08):
              tubs = self.pour_waypoints(b, heading, sign, n=8, tilt_max=tmax, lip_dz=dz, tub_poses=True, shift=shift)
              if (min(self.K.tub_bowl_gap(pt, Rt, b) for pt, Rt in tubs) >= 0.015 and
                  min(self.K.tub_bowl_gap(*self.sagged(pt, Rt), b) for pt, Rt in tubs[:3]) >= 0.0):
                lip_dz = dz
                break
            if lip_dz is None:
              continue
            seq = self.pour_waypoints(b, heading, sign, tilt_max=tmax, lip_dz=lip_dz, shift=shift)
            q = self.q_des.copy()
            okall, cost = True, 0.0
            for p, R in seq:
              q2, ok = self.solve(p, R, q)
              gap = self.K.self_gap(q2) if ok else 0.0
              if not ok or gap < gap_min:
                okall = False
                break
              cost += float(np.max(np.abs(q2 - q))) + 60.0 * max(0.0, 0.008 - gap)
              q = q2
            cost += 10.0 * (lip_dz - 0.035)
            if okall and (best is None or cost < best[0]):
              # and the loaded tub can be carried there on a straight path (a joint move would swing it)
              yield
              if self.straight_ok(seq[0][0] + np.array([0, 0, 0.04]), seq[0][1]):
                best = (cost, heading, sign, tmax, lip_dz, shift)
          if best is not None and best[0] < 6:
            break
        if best is not None:
          return best
    return None

  def sagged(self, pt, Rt, deg=10.0):
    """The tub pose at (pt, Rt) after it has swung a further `deg` in the jaws under its load (a heavy batch
    creeps round the grip while it is carried), the way that lowers its centre."""
    p_tool, R_tool = self.tool_for_tub(pt, Rt)
    best = None
    for sgn in (1, -1):
      Rr = rotvec(R_tool[:, 1], sgn * math.radians(deg))
      pt2, Rt2 = p_tool + Rr @ (pt - p_tool), Rr @ Rt
      zc = (pt2 + Rt2 @ np.array([0, 0, 0.05]))[2]
      if best is None or zc < best[0]:
        best = (zc, pt2, Rt2)
    return best[1], best[2]

  def pour_waypoints(self, b, heading, sign, n=7, tilt_max=118.0, lip_dz=0.035, tub_poses=False, shift=0.0):
    # tub upright, heading = direction of its +x axis; it tips about +x, the lip on the -sign*y side goes down
    lip_local = np.array([0.0, -sign * TUB_R_TOP, TUB_H])
    Rh = rz(heading)
    ax = Rh[:, 0]
    # pieces leave over the lip moving towards the lip side: hold the lip a little back from the bowl centre
    v = Rh @ np.array([0.0, -sign, 0.0])
    target = np.array([b[0], b[1], BOWL_TOP_Z + lip_dz]) - 0.05 * v
    # a far bowl: pour over its near half (`shift` towards the arm)
    target[:2] -= shift * np.asarray(b, float) / (np.linalg.norm(b) + 1e-9)
    out = []
    for i in range(n + 1):
      s = i / n
      ang = math.radians(tilt_max) * s
      Rt = rotvec(ax, sign * ang) @ Rh
      lip = target + np.array([0, 0, 0.10 * (1 - s) ** 1.5])   # the base clears the bowl rim while upright
      pt = lip - Rt @ lip_local
      out.append((pt, Rt) if tub_poses else self.tool_for_tub(pt, Rt))
    return out

  def pour(self):
    plan = yield from self.pour_plan()
    b = np.asarray(self.bowl["xy"], float)
    if plan is None:
      heading, sign, tmax, lip_dz, shift = math.atan2(b[1], b[0]), 1, 118.0, 0.065, 0.0
    else:
      _, heading, sign, tmax, lip_dz, shift = plan
    self.log("pour plan", plan, "bowl", np.round(b, 3), "tub", np.round(self.tub["xy"], 3))
    seq = self.pour_waypoints(b, heading, sign, n=12, tilt_max=tmax, lip_dz=lip_dz, shift=shift)
    p0, R0 = seq[0]
    # carry high to above the start of the pour, on a straight tool path (no swing of the loaded tub); where the
    # arm has no straight path, climb first so that a joint move swings the tub well above the bowl
    pw, Rw = self.tool_world()
    z_hi = max(pw[2], p0[2] + 0.04, 0.27)
    if not self.straight_ok(np.array([p0[0], p0[1], p0[2] + 0.04]), R0):
      yield from self.line(np.array([pw[0], pw[1], z_hi]), Rw, speed=0.10)
      yield from self.line(np.array([p0[0], p0[1], z_hi]), R0, speed=0.12)
    yield from self.line(p0 + np.array([0, 0, 0.04]), R0, speed=0.12)
    self.log("pour start", np.round(self.q_des, 2), np.round(self.K.fk(self.q_des)[0], 3))
    # a full tub can swing round the grip on the way: look again, and plan the pour afresh if it has
    pts, valid = yield from self.fresh_frame(0.5)
    if MEASURE_HELD:
      got = self.measure_held_tub(pts, valid)
      if got is not None and abs(got[0]) > math.radians(4):
        plan2 = yield from self.pour_plan()
        self.log("pour re-plan", plan2)
        if plan2 is not None:
          _, heading, sign, tmax, lip_dz, shift = plan2
          seq = self.pour_waypoints(b, heading, sign, n=12, tilt_max=tmax, lip_dz=lip_dz, shift=shift)
          p0, R0 = seq[0]
          yield from self.line(p0 + np.array([0, 0, 0.04]), R0, speed=0.08)
    yield from self.line(p0, R0, speed=0.08)
    yield from self.wait(0.4)
    q = self.q_des.copy()
    for i, (p, R) in enumerate(seq[1:], 1):
      q2, ok = self.solve(p, R, q)
      # slow once past half tilt, where the pieces start to roll out over the lip
      slow = i > len(seq) // 2
      yield from self.move_q(q2, 0.3 if slow else 0.9, tmin=0.5 if slow else 0.2)
      q = q2
    yield from self.wait(0.5)
    # a few short rocks of the wrist free pieces wedged against each other
    q_a, _ = self.solve(*seq[-2], self.q_des)
    q_b = self.q_des.copy()
    for _ in range(1 if ROCK else 0):
      yield from self.move_q(q_a, 1.0, tmin=0.35)
      yield from self.move_q(q_b, 1.0, tmin=0.35)
    # then jolt the tub sideways on the last two wrist joints: pieces wedged across the tub shake loose
    q_end = self.q_des.copy()
    p_rel, R_rel = self.T_tool_tub
    lip_local = np.array([0.0, -sign * TUB_R_TOP, TUB_H])
    for jnt, a in (((5, 0.14), (5, -0.14)) * 2 + ((4, 0.12), (4, -0.12)) * 2 if ROCK else ()):
      for aa in (a, 0.6 * a, 0.3 * a):
        q2 = q_end.copy()
        q2[jnt] += aa
        if not (self.K.lo[jnt] <= q2[jnt] <= self.K.hi[jnt]):
          continue
        pw, Rw = self.K.fk(q2)
        pw = pw - np.array([0, 0, self.zcal[0] + self.zcal[1] * pw[0]])     # model -> world
        pt, Rt = pw + Rw @ p_rel, Rw @ R_rel
        lip_off = float(np.linalg.norm((pt + Rt @ lip_local)[:2] - b))
        gap = min(self.K.self_gap(q2), self.K.tub_bowl_gap(pt, Rt, b) - 0.01, 0.07 + shift - lip_off)
        self.log("swing", jnt, round(aa, 2), round(gap, 4), "lip", round(lip_off, 3))
        if gap >= SELF_GAP:
          # short sharp jolts: the jam breaks on the jerk, not on a slow swing
          yield from self.move_q(q2, 2.0, tmin=0.15)
          yield from self.move_q(q_end, 2.0, tmin=0.15)
          break
    yield from self.move_q(q_end, 1.2, tmin=0.3)
    yield from self.wait(0.5)
    pe, Re = seq[-1]
    q_up, ok_up = self.solve(pe + np.array([0, 0, 0.06]), Re, self.q_des)
    if ok_up:
      yield from self.move_q(q_up, 0.8, tmin=0.4)
    # back upright along the same path but higher: the emptied tub may have swung round the grip while tipped,
    # and then hangs lower than planned on the way back over the bowl rim
    for i, (p, R) in enumerate(reversed(seq[:-1])):
      q2, ok = self.solve(p + np.array([0, 0, 0.06]), R, self.q_des)
      if not ok:
        q2, ok = self.solve(p + np.array([0, 0, 0.03]), R, self.q_des)
      if not ok:
        q2, ok = self.solve(p, R, self.q_des)
      self.log("pour back", np.round(q2, 2), ok, round(float(np.max(np.abs(q2 - self.q_des))), 2))
      yield from self.move_q(q2, 1.0, tmin=0.15)
    yield from self.wait(0.3)
    self.pour_heading = heading

  def set_down(self, p_put, R_put):
    """Lower the held tub onto its base at p_put, a little past it if need be, and stop where the arm is held
    up (the measured tool height falls behind the command by more than it did on the way down)."""
    path = self.plan_line(p_put - np.array([0, 0, 0.008]), R_put, speed=0.03)
    if path is None:
      yield from self.line(p_put, R_put, speed=0.05)
      return
    lag = []
    for q2 in path:
      self.q_des = self.q_des + np.clip(q2 - self.q_des, -0.05, 0.05)
      yield
      lag.append(float(self.K.fk(self.qm())[0][2] - self.K.fk(self.q_des)[0][2]))
      if len(lag) > 10 and lag[-1] - float(np.median(lag[:8])) > 0.004:
        self.q_des = self.qm()
        self.log("set down: on the mat", round(lag[-1] - float(np.median(lag[:8])), 4))
        return

  def leave_tub(self):
    """Set the empty tub back down where it was picked up (used when no mat park is wanted)."""
    c, tyaw = self.tub_frame()
    pt = np.array([c[0], c[1], 0.006])
    p_put, R_put = self.tool_for_tub(pt, rz(tyaw))
    pw, Rm = self.tool_world()
    yield from self.line(pw + np.array([0, 0, 0.06]), Rm, speed=0.10)
    yield from self.line(p_put + np.array([0, 0, 0.08]), R_put, speed=0.14)
    yield from self.set_down(p_put, R_put)
    yield from self.grip_to(OPEN, 0.3)
    yield from self.wait(0.4)
    yield from self.line(p_put - 0.10 * R_put[:, 2], R_put, speed=0.10)

  def park_tub(self):
    mx, my, _ = self.mat_pose()
    stage_c = np.array([mx, my, 0.0])

    def put_pose(R_put, cxy, zlow):
      p_rel, R_rel = self.T_tool_tub
      Rtub = R_put @ R_rel
      phi = np.linspace(0, 2 * math.pi, 48, endpoint=False)
      base = np.stack([TUB_R_BASE * np.cos(phi), TUB_R_BASE * np.sin(phi), np.zeros_like(phi)], 1) @ Rtub.T
      c = np.array([cxy[0], cxy[1], zlow - float(base[:, 2].min())])
      return c - R_put @ p_rel

    # the emptied tub may have swung round the grip while it was tipped: look at it again; a large swing is
    # taken out by turning the hand, so that the tub comes down upright
    R_rel_put = self.T_nom[1]
    if MEASURE_HELD:
      pts, valid = yield from self.fresh_frame(0.3)
      got = self.measure_held_tub(pts, valid)
      if got is not None and abs(got[0]) > math.radians(6):
        R_rel_put = self.T_tool_tub[1]
    # handle towards the arm if that pose is reachable; otherwise turn the tub on the mat until it is
    R_put = None
    for dh in (0, 30, -30, 60, -60, 90, -90):
      Rp = rz(math.atan2(my, mx) + math.radians(dh)) @ R_rel_put.T
      pp = put_pose(Rp, (mx, my), MAT_TOP + 0.006)
      q1, ok1 = self.solve(pp, Rp, self.q_des)
      q2, ok2 = self.solve(pp + np.array([0, 0, 0.06]), Rp, q1)
      q3, ok3 = self.solve(pp - 0.10 * Rp[:, 2], Rp, q1)
      if DEBUG_PARK:
        self.log("park try", dh, ok1, ok2, ok3, np.round(pp, 3), "mat", np.round([mx, my], 3), "Trel", np.round(R_rel_put, 2).tolist(), np.round(self.T_tool_tub[0], 3))
      if ok1 and ok2 and ok3:
        R_put = Rp
        break
    if R_put is None:
      R_put = rz(math.atan2(my, mx)) @ R_rel_put.T
    self.log("park: dh", None if R_put is None else round(math.degrees(math.atan2(R_put[1, 0], R_put[0, 0])), 1),
             "tilt put", round(math.degrees(math.acos(np.clip((R_put @ self.T_tool_tub[1])[2, 2], -1, 1))), 1),
             "tilt now", round(math.degrees(math.acos(np.clip((self.tool_world()[1] @ self.T_tool_tub[1])[2, 2], -1, 1))), 1))
    # lift clear of the bowl rim and carry the tub to above the mat
    pw, Rm = self.tool_world()
    yield from self.line(pw + np.array([0, 0, 0.08]), Rm, speed=0.10)
    pw, _ = self.tool_world()
    p_stage = put_pose(R_put, stage_c, MAT_TOP + 0.07)
    # as high as the hand can hold the tub upright there, up to the height it is carried at
    z_lo = p_stage[2]
    q_stage = None
    for z in np.arange(max(z_lo, pw[2]), z_lo - 1e-6, -0.02):
      qz, okz = self.solve(np.array([p_stage[0], p_stage[1], z]), R_put, self.q_des)
      if okz:
        p_stage[2] = z
        q_stage = qz
        break
    self.log("park: stage", np.round(p_stage, 3), "from", np.round(pw, 3))
    # away from the bowl first with the hand as it is, then turn it over the mat (should a straight path not
    # exist and the arm go in joint space, the tub is then clear of the bowl)
    p_mid = np.array([p_stage[0], p_stage[1], pw[2]])
    q_mid = None
    path = self.plan_line(p_mid, Rm, 0.14, strict=True)
    if path is not None and self.plan_line(p_stage, R_put, 0.14, q0=path[-1], strict=True) is not None:
      yield from self.line(p_mid, Rm, speed=0.14)
    else:
      self.log("park: no away-first path")
    if self.plan_line(p_stage, R_put, 0.14, strict=True, quiet=True) is not None or q_stage is None:
      yield from self.line(p_stage, R_put, speed=0.14)
    else:
      self.log("park: joint move to the stage")
      yield from self.move_q(q_stage, 1.0)
    # set the tub down by its lowest point (the grasp transform as last measured)
    yield from self.wait(0.3)
    if DEBUG_PARK:
      for nm, qq in (("cmd", self.q_des), ("meas", self.qm()), ("stage", q_stage)):
        if qq is not None:
          Rq = self.K.fk(qq)[1]
          self.log("park:", nm, np.round(qq, 3), "tilt", round(math.degrees(math.acos(np.clip((Rq @ self.T_tool_tub[1])[2, 2], -1, 1))), 1))
    p_put = put_pose(R_put, (mx, my), MAT_TOP + 0.006)
    p_above = p_put + np.array([0, 0, 0.06])
    yield from self.line(p_above, R_put, speed=0.08)
    yield from self.wait(0.4)
    yield from self.set_down(p_put, R_put)
    yield from self.wait(0.3)
    yield from self.grip_to(OPEN, 0.3)
    yield from self.wait(0.5)
    app = R_put[:, 2]
    yield from self.line(p_put - 0.10 * app, R_put, speed=0.10)
    self.log("park released", np.round(self.qm() - self.q_des, 3))
    yield from self.line(p_put - 0.10 * app + np.array([0, 0, 0.10]), R_put, speed=0.12)
    self.log("park retracted", np.round(self.qm() - self.q_des, 3))