File size: 108,984 Bytes
8a5716b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
"""Reference controller for the AS-4 changeover (I2RT YAM): product A out, product B in, two first-off parts.

A generator state machine; every stage is closed on the overhead RGB-D image or on the joint readings:
  1. watch for faults on every tick (gripper echo, frozen camera); with something in the hand, put it back where
     it came from before reporting the fault;
  2. check the camera against the arm (two views of the gripper), then look at the cell with the arm folded away:
     fixture and shelf from their dots, nests from their end bands, parts and trays by colour and height;
  3. swing the clamp open with the handle peg between the open fingers, lift nest A off its pins, park it;
  4. fetch nest B (the orange-banded one), hold it over the pins, line its far band up against the fixture dot in
     the image, lower it, press each end through its pin detent (press until the end drops);
  5. close the clamp by feel: find where the swing torque starts to rise and stop a set angle past that point;
  6. look again: clamp still shut, far nest end still down, else put it right;
  7. per first-off part: pick, place, press through the detent (stop at the drop), wait, touch the part to see it
     stayed down, press again if it popped, then take it to the outfeed tray.
"""
from __future__ import annotations

import math
import os
import time

import mujoco
import numpy as np

CAM_POS = np.array([0.24, 0.0, 0.90])     # 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
TIP_BELOW_SITE = 0.0118
HOME = np.array([0.0, 1.20, 1.15, -1.25, 0.0, 0.0])
VIEW = np.array([2.9, 0.3, 0.9, 0.2, 0.0, 0.0])       # arm folded up behind its base, out of the camera view
Z_SAFE = 0.15
OPEN = 0.0475
DEBUG = bool(os.environ.get("AS4_DEBUG"))

# ---------------------------------------------------------------------------------------------- cell figures
# From CELL_SHEET.md, CHANGEOVER_SHEET.md and PRODUCT_B.md (positions are nominal: the cell is found by camera).
FIX_NOM = (0.395, 0.0)
SHELF_NOM = (0.335, math.radians(-55.0))      # radius, bearing
INFEED_NOM = (0.300, math.radians(50.0))
OUT_NOM = (0.265, math.radians(95.5))
SEAT_Z = 0.022
NEST_T, NEST_W = 0.012, 0.060
PIN_Y = 0.045
PIVOT = (0.0, 0.092)
PEG_AT = 0.060
HANDLE_DEG = 220.0
FID_FIX = ((-0.043, -0.072), (0.043, 0.060))
FID_SHELF = ((-0.128, -0.056), (0.128, 0.056))
BAY_X = (-0.085, 0.0, 0.085)
RAIL_TOP = 0.024
STRIPE = (0.048, 0.060)
TRAY_TOP = 0.004
PLATE_T = 0.006
PART_H, PART_R = 0.032, 0.014
INFEED_HALF = (0.100, 0.030)

# ---------------------------------------------------------------------------------------------- settings
FAULT_CHECKS = True
CALIBRATE = True
CAM_FIT = True
VERIFY = True              # look and touch after clamping and after each press; put right what moved
SERVO_NEST = True          # line the nest up over the pins in the image before lowering
CLAMP = True
NOMINAL = False            # go by the sheet's nominal places instead of the camera
TOUCH_CHECK = True
PICK_LOOKALIKE = False
PRESS_OPEN_LOOP = False
STOP_AFTER = ""
PROFILE = False            # dev: time the act calls and print where the time went when the run ends
N_PARTS = 2
CLAMP_PAST_DEG = 20.0      # 0.40 N·m at 0.02 N·m per degree past contact (PRODUCT_B.md)
FORK_GIVE = 1.14           # hand angle travelled per degree of clamp angle under load (the fingers give; public seeds)
LEVEL_RAD = 0.006
CLAMP_STOP_N = 7.0          # push on the peg that goes with 0.42 N m: never more, whatever the fit says
FORK_LEAD_DEG = 18.4       # hand angle minus clamp angle while pushing (public seeds)
TRACE = False
FEEL_RATE = 6.0            # deg/s while feeling for the pad
PLAY_DEG = 14.3            # play of the peg between the open fingers, as an angle at the pivot
FORK_OPEN = 0.020
NEST_OPEN = 0.0475         # per finger, the full opening
PEG_Z = 0.068
PRESS_SPEED = 0.006
PRESS_HOLD_XY = True
RELAX_GRASP = True
PLACE_GIVE = 0.00012       # m of sideways give per newton per tick while a part goes into the pocket
TOUCH_OFF = 0.0030         # a touch with the closed fingertips reads this much low (public seeds)
END_DROP, END_CAP = 0.0021, 7.0
PART_DROP, PART_CAP = 0.0035, 10.6
PART_OPEN = 0.030
PLACE_OFF = (0.0, 0.0)     # test only: part put into the pocket this far off centre (fixture frame, m)
DWELL_WAIT = 2.5
OPEN_LOOP_DEPTH = 0.004
CENTRE_PART = True         # close low on a tray part first so it sits in the middle of the hand
LET_GO_ON_PINS = True      # a nest held up a little over the pins is let go to settle, not circled in the hand
FINGER_TEST_MM = 6.0       # finger test motion with the hand empty (0 = none)
NEST_OUTLINE = True        # line the nest up over the pins by its whole outline in the depth picture (False: by its far band)
FIX_OUTLINE = True         # place the bare fixture by its outline in the depth picture before nest B is fetched
NEST_DUMP = False          # dev: print the outline fit's picture
# Sideways and turning give while the nest goes down on the pins, as a share of the part-placing give. Both are
# off: the side force read from the joints while the hand descends is wrong by a newton or more with noisy joint
# readings and the give then carried a nest that was lined up to 1 mm as far as 5 mm off the pins. Lined up by its
# outline the nest either goes down or stops on the pin noses a millimetre out, and is let go there to centre itself.
NEST_SIDE_GIVE = 0.0
NEST_TURN_GIVE = 0.0
PLACE_SEARCH = True        # a part stopped on the pocket lead-in is circled into the pocket
NEST_GIVE = True           # lower the nest onto the pins with the hand giving way sideways and in turn

# ---------------------------------------------------------------------------------------------- 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

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


class Suspect(Exception):
  """The fingers look as if they had not followed a command: to be settled by a test motion."""
  def __init__(self, way):
    super().__init__(way)
    self.way = way


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.fa = np.array([m.jnt_qposadr[m.joint(f"robot/{k}_finger").id] for k in ("left", "right")])
    self.jp = np.zeros((3, m.nv))
    self.jr = np.zeros((3, m.nv))
    self.kp = np.array([m.actuator_gainprm[m.actuator(f"robot/joint{i}").id, 0] for i in range(1, 7)])
    for j in range(m.njnt):                     # loose things out of the way
      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)

  def jac(self, q):
    self.d.qpos[self.qa] = q
    mujoco.mj_kinematics(self.m, self.d)
    mujoco.mj_comPos(self.m, self.d)
    mujoco.mj_jacSite(self.m, self.d, self.jp, self.jr, self.sid)
    return self.jp[:, self.va].copy()

  def jac6(self, q):
    self.d.qpos[self.qa] = q
    mujoco.mj_kinematics(self.m, self.d)
    mujoco.mj_comPos(self.m, self.d)
    mujoco.mj_jacSite(self.m, self.d, self.jp, self.jr, self.sid)
    return np.vstack([self.jp[:, self.va], self.jr[:, self.va]])

  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
    self.model_cam = CAM_POS.copy()

  # -------------------------------------------------------------------------------------- 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 = [], []
    # feeling for a stop: the slow servo correction is held, or it would wind a push up against whatever stops the hand
    held = self.freeze_bias
    if guard is not None:
      self.freeze_bias = True
    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.freeze_bias = held
        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
    self.freeze_bias = held
    return True

  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

  # -------------------------------------------------------------------------------------- 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. A pixel is 3-4 mm at the arm, so the model outline is
    slid over the measured one in quarter-pixel steps and the best fit refined. (Counting the pixels that agree
    for a few trial turns was good to a pixel at best: with a noisy depth image it read turns of 0.3-0.4 degrees
    that were not there, 4-6 mm on the bench.)"""
    global CAM_X, CAM_Y, CAM_Z
    K = self.K
    grp = np.array([0, 0, 1, 0, 0, 0], np.uint8)
    rise = float(self.zcal[0])
    cam = CAM_POS + np.array([0.0, 0.0, rise])       # the arm stands `rise` lower than the model arm
    W, M = 24, 3
    found = []
    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()

      def proj(X, Y, Z):
        rel = site - cam
        dp = -float(rel @ Z)
        return np.array([-float(rel @ Y) / dp * f + h / 2 - 0.5, float(rel @ X) / dp * f + w / 2 - 0.5])

      r0, c0 = (int(round(v)) for v in self.project(site + np.array([0, 0, 0.04])))
      if r0 - W < 0 or r0 + W >= h or c0 - W < 0 or c0 + W >= w:
        self.log("camera fit: gripper too near the image edge", r0, c0)
        continue
      rr, cc = np.meshgrid(np.arange(r0 - W, r0 + W + 1), np.arange(c0 - W, c0 + W + 1), indexing="ij")
      uu = (cc + 0.5 - w / 2) / f
      vv = -(rr + 0.5 - h / 2) / f
      vec = uu[..., None] * CAM_X0 + vv[..., None] * CAM_Y0 - CAM_Z0
      d = dep[r0 - W:r0 + W + 1, c0 - W:c0 + W + 1].astype(np.float64)
      ok = (d > 0.2) & (d < 1.5)
      # the gripper is held 140 mm up, clear of the bench and of the fixture
      seen = (ok & (CAM_POS[2] + d * vec[..., 2] > 0.118)).astype(np.float64)
      flat = vec.reshape(-1, 3)
      model = np.zeros(len(flat))
      for s0 in range(0, len(flat), 500):               # spread over control ticks (each act call is timed)
        chunk = flat[s0:s0 + 500]
        k = len(chunk)
        dist, gid = np.zeros(k), np.zeros(k, np.int32)
        K.d.qpos[K.qa] = q
        mujoco.mj_kinematics(K.m, K.d)
        mujoco.mj_multiRay(K.m, K.d, cam, chunk.ravel().copy(), grp, 0, -1, gid, dist, None, k, 3.0)
        model[s0:s0 + k] = (dist > 0) & (cam[2] + dist * chunk[:, 2] > 0.118 + rise)
        yield
      model = model.reshape(seen.shape)
      n1 = seen.shape[0]
      lo, hi = M + 1, n1 - (M + 1)
      wgt, tgt = ok[lo:hi, lo:hi].astype(np.float64), seen[lo:hi, lo:hi]

      def score(dv, du):                                 # model outline moved by dv rows, du columns
        iy, ix = int(math.floor(dv)), int(math.floor(du))
        fy, fx = dv - iy, du - ix
        acc = 0.0
        for oy, wy in ((iy, 1.0 - fy), (iy + 1, fy)):
          for ox, wx in ((ix, 1.0 - fx), (ix + 1, fx)):
            if wy * wx > 0.0:
              acc = acc + wy * wx * model[lo - oy:hi - oy, lo - ox:hi - ox]
        return float(np.sum(wgt * (1.0 - np.abs(tgt - acc))))

      grid = np.arange(-M, M + 0.01, 0.25)
      sc = np.array([[score(dv, du) for du in grid] for dv in grid])
      yield
      bi, bj = np.unravel_index(int(np.argmax(sc)), sc.shape)
      if bi in (0, len(grid) - 1) or bj in (0, len(grid) - 1):
        self.log("camera fit: best at the edge of the search", grid[bi], grid[bj])
        continue                                         # best fit at the edge of the search: not trusted

      def peak(a, b, c):                                 # vertex of the parabola through three neighbours
        den = a - 2.0 * b + c
        return 0.0 if den >= -1e-9 else float(np.clip(0.5 * (a - c) / den, -0.5, 0.5))

      dv = grid[bi] + 0.25 * peak(sc[bi - 1, bj], sc[bi, bj], sc[bi + 1, bj])
      du = grid[bj] + 0.25 * peak(sc[bi, bj - 1], sc[bi, bj], sc[bi, bj + 1])
      # the turn (about the camera's two image axes) that moves the model outline by that much
      p0, e = proj(CAM_X0, CAM_Y0, CAM_Z0), math.radians(0.2)
      Ra, Rb = rotvec(CAM_X0, e), rotvec(CAM_Y0, e)
      J = np.column_stack([(proj(Ra @ CAM_X0, Ra @ CAM_Y0, Ra @ CAM_Z0) - p0) / 0.2,
                           (proj(Rb @ CAM_X0, Rb @ CAM_Y0, Rb @ CAM_Z0) - p0) / 0.2])
      ab = np.linalg.solve(J, np.array([dv, du]))
      # Sliding one outline over the other resolves whole pixels only (a pixel is on the arm or it is not). For
      # the fraction, the model arm is cast again along the rays of the pixels beside the outline for trial turns
      # a quarter of a pixel apart: the count of pixels that disagree falls and rises in a V around the true turn
      edge = np.zeros(seen.shape, bool)
      edge[1:-1, 1:-1] = ((seen[1:-1, 1:-1] != seen[:-2, 1:-1]) | (seen[1:-1, 1:-1] != seen[2:, 1:-1])
                          | (seen[1:-1, 1:-1] != seen[1:-1, :-2]) | (seen[1:-1, 1:-1] != seen[1:-1, 2:]))
      band = edge.copy()
      band[1:-1, 1:-1] |= edge[:-2, 1:-1] | edge[2:, 1:-1] | edge[1:-1, :-2] | edge[1:-1, 2:]
      band &= ok
      band[:2, :] = band[-2:, :] = False
      band[:, :2] = band[:, -2:] = False
      bu, bv, want = uu[band], vv[band], seen[band] > 0.5
      nb = int(band.sum())
      if nb < 60:
        found.append(ab)
        continue

      def differ(a, b):
        R = rotvec(CAM_X0, math.radians(a)) @ rotvec(CAM_Y0, math.radians(b))
        vecs = bu[:, None] * (R @ CAM_X0) + bv[:, None] * (R @ CAM_Y0) - (R @ CAM_Z0)
        dist, gid = np.zeros(nb), np.zeros(nb, np.int32)
        K.d.qpos[K.qa] = q
        mujoco.mj_kinematics(K.m, K.d)
        mujoco.mj_multiRay(K.m, K.d, cam, vecs.ravel().copy(), grp, 0, -1, gid, dist, None, nb, 3.0)
        return int(np.sum(((dist > 0) & (cam[2] + dist * vecs[:, 2] > 0.118 + rise)) != want))

      def vee(x, y):
        """Vertex of the V (c + k |x - x0|, k >= 0) that fits the counts best."""
        best = (1e18, float(x[int(np.argmin(y))]))
        for x0 in np.arange(x[0], x[-1] + 1e-9, 0.004):
          A = np.column_stack([np.ones(len(x)), np.abs(x - x0)])
          coef, res = np.linalg.lstsq(A, y, rcond=None)[:2]
          r = float(np.sum((A @ coef - y) ** 2))
          if coef[1] > 0 and r < best[0]:
            best = (r, float(x0))
        return best[1]

      step = 0.06                                        # degrees: about a quarter of a pixel
      a, b = float(ab[0]), float(ab[1])
      for axis in (0, 1, 0, 1):
        xs = (a if axis == 0 else b) + step * np.arange(-4, 5)
        ys = []
        for x in xs:
          ys.append(differ(x, b) if axis == 0 else differ(a, x))
          yield
        x0 = vee(xs, np.array(ys, float))
        a, b = (x0, b) if axis == 0 else (a, x0)
      self.log("camera fit: outline off by", round(dv, 2), round(du, 2), "px ->", np.round(ab, 3), "deg; refined", round(a, 3), round(b, 3), "; edge px", nb, "left differing", differ(a, b))
      found.append(np.array([a, b]))
    if not found:
      return None
    # the second view is taken beside the fixture, where the placing has to be right
    ab = found[0] if len(found) == 1 else 0.35 * found[0] + 0.65 * found[1]
    a, b = (float(np.clip(v, -1.2, 1.2)) for v in ab)
    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")
    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)
      dep = self.obs["depth"]["overhead"].copy()
      qs = [self.qm().copy()]
      for _ in range(12):                              # the arm is still: the joint readings' noise averages out
        yield
        qs.append(self.qm().copy())
      views.append((dep, np.mean(qs, axis=0)))
    # the model arm is compared with the depth image: its fingers stand as open as the real ones
    self.K.d.qpos[self.K.fa] = max(0.0, self.finger())
    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
      b = float(np.clip(b, -LEVEL_RAD, LEVEL_RAD))          # the station is shimmed level (CELL_SHEET.md)
      a = -0.5 * (e1 + e2) - b * 0.5 * (x1 + x2)
      self.zcal = (float(np.clip(a, -0.04, 0.04)), b)
    elif len(meas) == 1:
      self.zcal = (float(np.clip(-meas[0][1], -0.04, 0.04)), 0.0)
    self.log("zcal", self.zcal)
    if CAM_FIT:
      yield from self.fit_camera_tilt(views)


  # -------------------------------------------------------------------------------------- runtime
  def reset(self, obs):
    self.obs = obs
    self.q_des = np.asarray(obs["qpos"], float)[self.ia].copy()
    self.q_cmd_last = self.q_des.copy()
    self.grip = float(obs["ctrl"][6])
    self.bias = np.zeros(6)
    self.freeze_bias = False
    self.sent_grip = [self.grip] * 4
    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.finger_bias = 0.0
    self.fing_h, self.gcmd_h, self.anchor = [], [], None
    self.grip_testing = False
    self.zcal = (0.0, 0.0)
    self.folded = False
    self.carry = None                 # where the thing in the hand came from: (site position, R, opening)
    self.setting_down = False
    self.gen = self.main()
    self.done = None

  def act(self, obs):
    if PROFILE:
      import cProfile, pstats, sys
      if not hasattr(self, "_prof"):
        self._prof = cProfile.Profile()
      self._prof.enable()
      try:
        out = self.act_inner(obs)
      finally:
        self._prof.disable()
      if isinstance(out, dict) and not getattr(self, "_prof_done", False):
        self._prof_done = True
        pstats.Stats(self._prof, stream=sys.stderr).sort_stats("cumulative").print_stats(45)
      return out
    return self.act_inner(obs)

  def act_inner(self, obs):
    self.obs = obs
    try:
      try:
        if FAULT_CHECKS and not self.setting_down:
          self.check_faults(obs)
        if self.done is not None:
          return self.done
        return self.compose(next(self.gen))
      except Suspect as e:
        self.grip_testing = True
        self.gen = self.grip_check(self.gen, e.way)
        return self.compose(next(self.gen))
      except Abort as e:
        # a dead gripper shows only when the fingers are told to move, so with something in the hand it is found
        # at the release: the item is then resting where it was being put down, and the safe state is to stay there
        if self.carry is not None and not self.setting_down and e.fault != "dead_gripper":
          self.log(e.fault, "with something in the hand: putting it back first")
          self.setting_down = True
          self.freeze_bias = False
          self.gen = self.set_down_then_abort(e.fault)
          return self.compose(next(self.gen))
        self.done = {"status": "abort", "fault": e.fault}
        return self.done
    except Abort as e:
      self.done = {"status": "abort", "fault": e.fault}
      return self.done
    except (StopIteration, Finished):
      self.done = {"status": "done"}
      return self.done
    except Exception:
      if DEBUG:
        import traceback
        traceback.print_exc()
      self.done = {"status": "done"}      # never raise: stop where we are
      return self.done

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

  def compose(self, _):
    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
    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])]
    self.q_cmd_last = cmd[:6].copy()
    return cmd

  def check_faults(self, obs):
    # a dead gripper still echoes its commands: it shows only in the finger readings.
    # Opening (nothing can block it): over 0.8 s the command rose by 6 mm or more and the fingers did not move.
    # Closing: the fingers had settled on a steady command (the anchor), the command has then been 6 mm or more
    # lower for 0.6 s and the fingers are still within 1.5 mm of the anchor. Fingers that stop part-way are on
    # something and are not judged. Readings are averaged over 10 ticks: with the noisier readings (2 mm a tick) a
    # 5-tick mean within 0.6 mm of the anchor happened by chance during a healthy, slightly late close.
    q = obs["qpos"]
    if self.grip_testing:
      self.fing_h, self.gcmd_h, self.anchor = [], [], None
    self.fing_h.append(0.5 * (float(q[self.ifl]) + float(q[self.ifr])) - self.finger_bias)
    self.gcmd_h.append(self.sent_grip[-1])
    if len(self.fing_h) > 50:
      self.fing_h.pop(0)
      self.gcmd_h.pop(0)
      f0, f1 = float(np.mean(self.fing_h[:10])), float(np.mean(self.fing_h[-10:]))
      c0 = max(self.gcmd_h[:10])
      steady = max(self.gcmd_h[-12:]) - min(self.gcmd_h[-12:]) < 1e-5
      if steady and abs(f1 - self.gcmd_h[-1]) < 0.0015:
        self.anchor = (f1, self.gcmd_h[-1])
      c1 = min(self.gcmd_h[-30:])                  # the command has been up for the last 0.6 s
      opening = c1 - c0 > 0.006 and c1 > f1 + 0.004 and abs(f1 - f0) < 0.0015
      an = getattr(self, "anchor", None)
      closing = (an is not None and an[1] - max(self.gcmd_h[-30:]) > 0.006 and abs(f1 - an[0]) < 0.0015)
      if (opening or closing) and not self.grip_testing:
        self.log("fingers did not follow (%s): commands" % ("opening" if opening else "closing"), np.round(self.gcmd_h[::5], 4).tolist(), "readings", np.round(self.fing_h[::5], 4).tolist())
        raise Suspect("opening" if opening else "closing")
    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")

  def grip_check(self, then, way):
    yield from self.grip_probe(way)
    yield from then

  def let_go(self, opening, secs=0.4):
    """Open the fingers and see them open before the hand moves off. A gripper that has stopped answering still
    holds the item, which has just been stood on what is under it: the report is made from there, not after the
    hand has lifted the item again."""
    f0 = self.finger()
    yield from self.grip_to(opening, secs)
    self.carry = None
    if not FAULT_CHECKS or opening - f0 < 0.008:
      return
    seen = []
    for _ in range(30):
      seen.append(self.finger())
      if len(seen) >= 3 and float(np.mean(seen[-3:])) > f0 + 0.004:
        return
      yield
    self.log("fingers did not open: at", round(float(np.mean(seen[-3:])), 4), "from", round(f0, 4), "told", opening)
    self.grip_testing = True
    yield from self.grip_probe("opening")

  def grip_probe(self, way):
    """Fingers that stay put when told to close may be dead or may be on something after a millimetre or two
    (the foot of a part, a tray wall), and with noisy readings the two look alike. Told to move the other way
    nothing can hold them: 6 mm that way settles it. The work goes on from where it was if they move."""
    keep = self.grip
    f0 = []
    for _ in range(10):
      f0.append(self.finger())
      yield
    f0 = float(np.mean(f0))
    tgt = float(np.clip(f0 + (0.006 if way == "closing" else -0.006), 0.0, 0.0475))
    if abs(tgt - f0) < 0.004:
      tgt = float(np.clip(f0 - (0.006 if way == "closing" else -0.006), 0.0, 0.0475))
    self.grip = f0
    yield from self.grip_to(tgt, 0.15)
    yield from self.wait(0.3)
    f1 = []
    for _ in range(10):
      f1.append(self.finger())
      yield
    moved = abs(float(np.mean(f1)) - f0)
    self.log("finger check after a doubt: told", round(1000 * (tgt - f0), 1), "mm, moved", round(1000 * moved, 2), "mm")
    if moved < 0.5 * abs(tgt - f0):
      raise Abort("dead_gripper")
    self.grip = keep
    yield from self.wait(0.2)
    self.grip_testing = False

  def finger_test(self):
    """With the hand empty and clear: move the fingers 5 mm and back and see that they follow. A gripper that
    has stopped answering shows only when it is told to move, and the report has a deadline (CHANGEOVER_SHEET.md),
    so the stretches without finger work (seating, clamping, pressing) are broken up with this."""
    if not FAULT_CHECKS or FINGER_TEST_MM <= 0 or self.carry is not None:
      return
    g0 = self.grip
    g1 = g0 + 0.001 * FINGER_TEST_MM if g0 + 0.001 * FINGER_TEST_MM <= 0.0465 else g0 - 0.001 * FINGER_TEST_MM
    f0 = []
    for _ in range(15):
      f0.append(self.finger())
      yield
    yield from self.grip_to(g1, 0.2)
    yield from self.wait(0.15)
    f1 = []
    for _ in range(15):
      f1.append(self.finger())
      yield
    yield from self.grip_to(g0, 0.2)
    moved = abs(float(np.mean(f1)) - float(np.mean(f0)))
    if moved < 0.0005 * FINGER_TEST_MM:
      self.log("finger test: commanded", FINGER_TEST_MM, "mm, moved", round(1000 * moved, 2), "mm")
      raise Abort("dead_gripper")

  def set_down_then_abort(self, fault):
    p, R, opening = self.carry
    yield from self.travel(np.asarray(p) + np.array([0, 0, 0.002]), R, speed=0.06)
    if fault != "dead_gripper":                      # a dead gripper cannot let go: the item rests where it came from
      yield from self.grip_to(opening, 0.5)
      yield from self.wait(0.2)
      yield from self.line(np.asarray(p) + np.array([0, 0, 0.06]), R, speed=0.10)
    else:
      yield from self.wait(0.3)
    raise Abort(fault)

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

  def m2w(self, p):
    p = np.array(p, float)
    a, b = self.zcal
    z = p[2] - a - b * p[0]
    p[0] = p[0] + b * z
    p[2] = z
    return p

  def tool_world(self, measured=True):
    p, R = self.K.fk(self.qm() if measured else self.q_des)
    return self.m2w(p), R

  def fold(self):
    """Fold the arm up where it stands (the hand rises), ready to swing round."""
    if not self.folded:
      q = np.array([self.q_des[0], 0.3, 0.9, 0.2, 0.0, 0.0])
      yield from self.move_q(q, 1.6)
      self.folded = True

  def go_view(self):
    yield from self.fold()
    yield from self.move_q(VIEW, 1.8)

  def travel(self, p, R, vmax=2.2, z_safe=Z_SAFE, speed=0.18, seed=None):
    """Up to the safe height, across, then straight down to (p, R)."""
    p = np.asarray(p, float)
    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 self.folded:
      yield from self.move_q(np.array([q1[0], 0.3, 0.9, 0.2, 0.0, 0.0]), 2.2)
      self.folded = False
    else:
      pw, Rm = self.tool_world(False)
      if pw[2] < z_safe - 0.01:
        yield from self.line(np.array([pw[0], pw[1], z_safe]), Rm, speed=speed)
      # a joint move between two raised poses can dip: go through a raised middle pose when it would
      za = self.K.fk(self.q_des)[0][2]
      zb = self.K.fk(q1)[0][2]
      dip = min(self.K.fk(self.q_des + (q1 - self.q_des) * s)[0][2] for s in (0.25, 0.5, 0.75))
      if dip < min(za, zb) - 0.02:
        mid = (pw + above) / 2
        mid[2] = max(pw[2], above[2]) + 0.04
        q_via, _okv = self.solve(mid, R, q1)
        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 force_est(self):
    """Force of the surroundings on the tool (N, model frame), from the joint servo errors."""
    q = self.qm()
    J = self.K.jac(q)
    tau = self.K.kp * (self.q_cmd_last - q)
    F, *_ = np.linalg.lstsq(J.T, tau, rcond=None)
    return -F

  def wrench_est(self):
    """Force (N) and moment about the tool point (N m) of the surroundings on the tool, model frame, from the
    joint servo errors (six joints, six unknowns)."""
    q = self.qm()
    tau = self.K.kp * (self.q_cmd_last - q)
    try:
      W = np.linalg.solve(self.K.jac6(q).T, tau)
    except np.linalg.LinAlgError:
      W = np.linalg.lstsq(self.K.jac6(q).T, tau, rcond=None)[0]
    return -W

  def best_yaw(self, xy, axis_yaw):
    """Of the two top-down headings along an axis, the one that keeps the wrist nearer mid-range."""
    bearing = math.atan2(xy[1], xy[0])
    def off(y):
      return abs((bearing + math.pi - y + math.pi) % (2 * math.pi) - math.pi)
    return axis_yaw if off(axis_yaw) <= off(axis_yaw + math.pi) else axis_yaw + math.pi

  def tray_yaw(self, xy, axis_yaw):
    """Heading for a pick from the infeed tray. The wrist camera's housing stands 75 mm behind the hand and
    its underside is lower than the top of the clamp's handle peg when the fingers are down at a part: of the two
    headings, not the one that puts the housing within the peg's sweep (60 mm round the clamp pivot)."""
    y0 = self.best_yaw(xy, axis_yaw)
    piv = self.fix["xy"] + rz(self.fix["yaw"])[:2, :2] @ np.array([0.0, 0.092])
    d0, d1 = (float(np.linalg.norm(np.asarray(xy) - 0.0753 * np.array([math.cos(y), math.sin(y)]) - piv)) for y in (y0, y0 + math.pi))
    if d0 < 0.135 and d1 > d0:
      self.log("tray pick: hand turned round to keep the wrist camera off the clamp handle", round(d0, 3), round(d1, 3))
      return y0 + math.pi
    return y0

  # -------------------------------------------------------------------------------------- seeing
  def hsv(self, img=None):
    a = (self.obs["images"]["overhead"] if img is None else img).astype(np.float32)
    mx, mn = a.max(2), a.min(2)
    c = mx - mn
    sat = c / np.maximum(mx, 1.0)
    r, g, b = a[..., 0], a[..., 1], a[..., 2]
    hue = np.zeros_like(mx)
    m = c > 1e-3
    cs = np.where(m, c, 1.0)
    rc = (mx == r) & m
    gc = (mx == g) & m & ~rc
    bc = m & ~rc & ~gc
    hue[rc] = (60.0 * ((g - b) / cs))[rc] % 360.0
    hue[gc] = (60.0 * ((b - r) / cs) + 120.0)[gc]
    hue[bc] = (60.0 * ((r - g) / cs) + 240.0)[bc]
    return hue, sat, mx

  def blobs(self, mask, min_px=8):
    """Connected patches of a mask: world centre (rays at the patch's median depth), size, pixel lists."""
    dep = self.obs["depth"]["overhead"].astype(np.float64)
    self.cloud()
    _, uu, vv = self._ray_cache
    lab, n = label(mask)
    out = []
    for k in range(1, n + 1):
      rr, cc = np.nonzero(lab == k)
      if len(rr) < min_px:
        continue
      dd = dep[rr, cc]
      dd = dd[(dd > 0.2) & (dd < 1.5)]
      if len(dd) < 3:
        continue
      dm = float(np.median(dd))
      pts = CAM_POS[None, :] + (uu[rr, cc] * dm)[:, None] * CAM_X + (vv[rr, cc] * dm)[:, None] * CAM_Y - dm * CAM_Z
      out.append({"xy": pts[:, :2].mean(0), "z": float(pts[:, 2].mean()), "n": len(rr), "pts": pts[:, :2], "rc": (rr, cc)})
    return out

  def near_mask(self, pts, xy, radius):
    return np.linalg.norm(pts[..., :2] - np.asarray(xy)[None, None, :], axis=2) < radius

  def find_pair(self, mask, pts, near, radius, local_a, local_b, min_px=10):
    """Two dots of a fixture or shelf -> (origin xy, yaw), or None."""
    bl = self.blobs(mask & self.near_mask(pts, near, radius), min_px)
    if len(bl) < 2:
      self.log("dots: found", len(bl), "of 2; mask px", int((mask & self.near_mask(pts, near, radius)).sum()))
      return None
    bl = sorted(bl, key=lambda b: -b["n"])[:3]
    la, lb = np.array(local_a), np.array(local_b)
    want = float(np.linalg.norm(lb - la))
    best = None
    for i in range(len(bl)):
      for j in range(len(bl)):
        if i == j:
          continue
        v = bl[j]["xy"] - bl[i]["xy"]
        yaw = math.atan2(v[1], v[0]) - math.atan2(lb[1] - la[1], lb[0] - la[0])
        yaw = (yaw + math.pi) % (2 * math.pi) - math.pi
        err = abs(float(np.linalg.norm(v)) - want)
        if best is None or err < best[0]:
          best = (err, i, j, yaw)
    err, i, j, yaw = best
    # of the two orderings, keep the one nearer the expected heading
    cands = [(i, j, yaw), (j, i, (yaw + 2 * math.pi) % (2 * math.pi) - math.pi)]
    def dev(c):
      return abs((c[2] - self._expect_yaw + math.pi) % (2 * math.pi) - math.pi)
    i, j, yaw = min(cands, key=dev)
    rot = rz(yaw)[:2, :2]
    org = 0.5 * ((bl[i]["xy"] - rot @ la) + (bl[j]["xy"] - rot @ lb))
    return org, yaw, err

  def look_cell(self):
    """With the arm folded away: fixture, shelf, nests, trays and parts."""
    pts, valid = yield from self.fresh_frame(0.4)
    if NOMINAL:                                    # by the sheet alone: nominal places, nest B in the middle bay
      self.fix = {"xy": np.array(FIX_NOM), "yaw": 0.0}
      self.fix_cam = np.array(FIX_NOM)
      sxy = SHELF_NOM[0] * np.array([math.cos(SHELF_NOM[1]), math.sin(SHELF_NOM[1])])
      syaw = SHELF_NOM[1] - math.pi / 2
      self.shelf = {"xy": sxy, "yaw": syaw}
      rot = rz(syaw)[:2, :2]
      self.nest_b = {"xy": sxy + rot @ np.array([BAY_X[1], 0.0]), "axis": syaw + math.pi / 2, "hue": 30.0}
      self.nest_c = {"xy": sxy + rot @ np.array([BAY_X[2], 0.0]), "axis": syaw + math.pi / 2, "hue": 56.0}
      self.park = sxy + rot @ np.array([BAY_X[0], 0.0])
      ixy = INFEED_NOM[0] * np.array([math.cos(INFEED_NOM[1]), math.sin(INFEED_NOM[1])])
      iyaw = INFEED_NOM[1] - math.pi / 2
      self.infeed = {"xy": ixy, "yaw": iyaw}
      self.parts = [{"xy": ixy + rz(iyaw)[:2, :2] @ np.array([x, 0.0]), "kind": "B"} for x in (-0.072, -0.024)]
      self.outfeed = {"xy": OUT_NOM[0] * np.array([math.cos(OUT_NOM[1]), math.sin(OUT_NOM[1])])}
      return
    hue, sat, val = self.hsv()
    bright = val > 70
    # fixture: two magenta dots
    self._expect_yaw = 0.0
    fx = self.find_pair((hue > 265) & (hue < 345) & (sat > 0.4) & bright, pts, FIX_NOM, 0.20, FID_FIX[0], FID_FIX[1])
    if fx is None:
      fx = (np.array(FIX_NOM), 0.0, 9.0)
    self.fix = {"xy": np.array(fx[0]), "yaw": float(fx[1])}
    self.fix_cam = self.fix["xy"].copy()               # as seen: self.fix may be corrected by touch later
    self.log("fixture", np.round(self.fix["xy"], 4), round(math.degrees(self.fix["yaw"]), 2), "pair err", round(fx[2], 4))
    # shelf: two cyan dots
    sx, sy = SHELF_NOM[0] * math.cos(SHELF_NOM[1]), SHELF_NOM[0] * math.sin(SHELF_NOM[1])
    self._expect_yaw = SHELF_NOM[1] - math.pi / 2
    sh = self.find_pair((hue > 140) & (hue < 222) & (sat > 0.3) & (val > 50), pts, (sx, sy), 0.24, FID_SHELF[0], FID_SHELF[1])
    if sh is None:
      # dots half hidden by a turned nest: two small patches the right distance apart are still the two dots
      sh = self.find_pair((hue > 140) & (hue < 222) & (sat > 0.3) & (val > 50), pts, (sx, sy), 0.24, FID_SHELF[0], FID_SHELF[1], min_px=4)
      if sh is not None and sh[2] > 0.008:
        sh = None
      elif sh is not None:
        self.log("shelf from two partly hidden dots")
    one_dot = None
    if sh is None:
      # one dot seen: take the nominal heading and the dot nearer its nominal place
      org0, yaw0 = np.array([sx, sy]), self._expect_yaw
      one = self.blobs((hue > 140) & (hue < 222) & (sat > 0.3) & (val > 50) & self.near_mask(pts, (sx, sy), 0.24), 5)
      if one:
        rot0 = rz(yaw0)[:2, :2]
        dot = max(one, key=lambda b: b["n"])["xy"]
        cand = [dot - rot0 @ np.array(l) for l in FID_SHELF]
        org0 = min(cand, key=lambda c: float(np.linalg.norm(c - np.array([sx, sy]))))
        one_dot = dot
        # the other dot is hidden: the bare rail of the free bay gives the heading, the dot the place
        rail = self.blobs(valid & (np.abs(pts[..., 2] - RAIL_TOP) < 0.004) & self.near_mask(pts, org0, 0.22), 60)
        if rail:
          rp = max(rail, key=lambda b: b["n"])["pts"]
          c = rp.mean(0)
          w, v = np.linalg.eigh(np.cov((rp - c).T))
          ax = math.atan2(v[1, 1], v[0, 1]) - math.pi / 2
          yaw0 = yaw0 + ((ax - yaw0 + math.pi / 2) % math.pi) - math.pi / 2
          rot0 = rz(yaw0)[:2, :2]
          def misfit(org):
            l = rot0.T @ (c - org)
            return min(abs(l[0] - bx) for bx in BAY_X) + abs(l[1])
          org0 = min([dot - rot0 @ np.array(l) for l in FID_SHELF], key=misfit)
          self.log("shelf from one dot and the free rail: rail px", len(rp), "elong", round(float(w[1] / max(w[0], 1e-12)), 1))
      sh = (org0, yaw0, 9.0)
    self.shelf = {"xy": np.array(sh[0]), "yaw": float(sh[1])}
    self.log("shelf", np.round(self.shelf["xy"], 4), round(math.degrees(self.shelf["yaw"]), 2), "pair err", round(sh[2], 4))
    # nests on the shelf: end bands (orange, yellow), paired 108 mm apart
    warm = ((hue < 85) | (hue > 345)) & (sat > 0.45) & (val > 110)
    zok = valid & (pts[..., 2] > RAIL_TOP + NEST_T - 0.010) & (pts[..., 2] < RAIL_TOP + NEST_T + 0.012)
    wm = warm & zok & self.near_mask(pts, self.shelf["xy"], 0.20)
    # Two nests in neighbouring bays can stand with their bands a pixel apart, and the two bands then read as one
    # patch of the wrong size in the wrong place. The two colours are told apart first (the hues fall in two
    # groups, wherever the lighting has moved them) and each colour's patches are found on their own.
    hw = np.where(hue > 180, hue - 360, hue)
    hv = np.sort(hw[wm])
    parts_ = [wm]
    if len(hv) > 40:
      gaps = np.diff(hv)
      k = int(np.argmax(gaps[10:-10])) + 10 if len(gaps) > 30 else 0
      if k and gaps[k] > 6.0:
        cut = 0.5 * (hv[k] + hv[k + 1])
        parts_ = [wm & (hw < cut), wm & (hw >= cut)]
    bl = [b for part in parts_ for b in self.blobs(part, 10)]
    for b in bl:
      rr, cc = b["rc"]
      h = hue[rr, cc]
      b["hue"] = float(np.median(np.where(h > 180, h - 360, h)))
    nests = []
    used = set()
    # the two bands of one nest: same colour, 108 mm apart
    cand = []
    for i in range(len(bl)):
      for j in range(i + 1, len(bl)):
        dist = float(np.linalg.norm(bl[i]["xy"] - bl[j]["xy"]))
        dh = abs(bl[i]["hue"] - bl[j]["hue"])
        if abs(dist - (STRIPE[0] + STRIPE[1])) <= 0.012 and dh < 10.0:
          cand.append((dh + 1000.0 * abs(dist - (STRIPE[0] + STRIPE[1])), i, j))
    for _cost, i, j in sorted(cand):
      if i in used or j in used:
        continue
      used.update((i, j))
      v = bl[j]["xy"] - bl[i]["xy"]
      nests.append({"xy": 0.5 * (bl[i]["xy"] + bl[j]["xy"]), "axis": math.atan2(v[1], v[0]),
                    "hue": 0.5 * (bl[i]["hue"] + bl[j]["hue"])})
    nests.sort(key=lambda n: n["hue"])
    self.log("bands", [(np.round(b["xy"], 3).tolist(), round(b["hue"], 1), b["n"]) for b in bl])
    self.log("nests on the shelf", [(np.round(n["xy"], 4).tolist(), round(math.degrees(n["axis"]), 1), round(n["hue"], 1)) for n in nests])
    if len(nests) == 1:
      # One nest made out from its two bands, and a band of a redder colour left over: the nest made out is C and
      # B shows one band only (the other is hidden or ran into C's). B is then placed from that band and the
      # shelf's own heading: a nest lies across its bay with a band 54 mm either side of the bay's middle line.
      lone = [bl[i] for i in range(len(bl)) if i not in used and bl[i]["hue"] < nests[0]["hue"] - 12.0 and bl[i]["n"] >= 25]
      if lone:
        b1 = max(lone, key=lambda b: b["n"])
        rot_s = rz(self.shelf["yaw"])[:2, :2]
        ly = float((rot_s.T @ (b1["xy"] - self.shelf["xy"]))[1])
        yv = rot_s @ np.array([0.0, 1.0])
        nests.insert(0, {"xy": b1["xy"] - math.copysign(0.5 * (STRIPE[0] + STRIPE[1]), ly) * yv,
                         "axis": math.atan2(yv[1], yv[0]), "hue": b1["hue"]})
        self.log("nest B from one band and the shelf heading", np.round(nests[0]["xy"], 4))
    self.nest_b = nests[0] if nests else None            # the orange band is nearer red than the yellow one
    self.nest_c = nests[-1] if len(nests) > 1 else None
    # free bay: the bay centre with no nest near it
    rot = rz(self.shelf["yaw"])[:2, :2]
    bays = [self.shelf["xy"] + rot @ np.array([bx, 0.0]) for bx in BAY_X]
    free = [b for b in bays if all(np.linalg.norm(b - n["xy"]) > 0.045 for n in nests)]
    self.park = free[0] if free else bays[0]
    # infeed tray (violet) and the parts on it (tall, white tops for product B)
    ix, iy = INFEED_NOM[0] * math.cos(INFEED_NOM[1]), INFEED_NOM[0] * math.sin(INFEED_NOM[1])
    tb = self.blobs((hue > 235) & (hue < 300) & (sat > 0.3) & bright & self.near_mask(pts, (ix, iy), 0.17), 20)
    if tb:
      allp = np.concatenate([b["pts"] for b in tb])
      c = allp.mean(0)
      w, v = np.linalg.eigh(np.cov((allp - c).T))
      ax = v[:, 1]
      self.infeed = {"xy": c, "yaw": math.atan2(ax[1], ax[0])}
    else:
      self.infeed = {"xy": np.array([ix, iy]), "yaw": INFEED_NOM[1] - math.pi / 2}
    ri = rz(self.infeed["yaw"])[:2, :2]
    loc = (pts[..., :2] - self.infeed["xy"]) @ ri
    tall = valid & (pts[..., 2] > TRAY_TOP + PART_H - 0.008) & (pts[..., 2] < TRAY_TOP + PART_H + 0.010)
    tall &= (np.abs(loc[..., 0]) < INFEED_HALF[0] + 0.015) & (np.abs(loc[..., 1]) < INFEED_HALF[1] + 0.012)
    self.parts = []
    for b in self.blobs(tall, 12):
      rr, cc = b["rc"]
      b["sat"] = float(np.median(sat[rr, cc]))
      b["kind"] = "B" if b["sat"] < 0.30 else "A"
      self.parts.append(b)
    self.log("infeed", np.round(self.infeed["xy"], 4), round(math.degrees(self.infeed["yaw"]), 1),
             "parts", [(np.round(b["xy"], 4).tolist(), b["kind"], round(b["sat"], 2), b["n"]) for b in self.parts])
    # outfeed tray (green)
    ox, oy = OUT_NOM[0] * math.cos(OUT_NOM[1]), OUT_NOM[0] * math.sin(OUT_NOM[1])
    ob = self.blobs((hue > 95) & (hue < 170) & (sat > 0.4) & (val > 50) & self.near_mask(pts, (ox, oy), 0.17), 30)
    if ob:
      allp = np.concatenate([b["pts"] for b in ob])
      lo, hi = allp.min(0), allp.max(0)
      self.outfeed = {"xy": allp.mean(0)}
    else:
      self.outfeed = {"xy": np.array([ox, oy])}
    self.log("outfeed", np.round(self.outfeed["xy"], 4))

  def f2w(self, local):
    return self.fix["xy"] + rz(self.fix["yaw"])[:2, :2] @ np.asarray(local, float)

  def clamp_angle_seen(self):
    """Clamp angle from the blue arm in the image (deg; 0 open, 90 over the nest), or None."""
    pts, valid = yield from self.fresh_frame(0.3)
    hue, sat, val = self.hsv()
    piv = self.f2w(PIVOT)
    m = (hue > 200) & (hue < 255) & (sat > 0.45) & (val > 60) & self.near_mask(pts, piv, 0.085)
    bl = self.blobs(m, 6)
    if not bl:
      return None
    allp = np.concatenate([b["pts"] for b in bl])
    c = allp.mean(0)
    _w, vec = np.linalg.eigh(np.cov((allp - c).T))
    v = vec[:, 1] if float(vec[:, 1] @ (c - piv)) > 0 else -vec[:, 1]      # the arm's long axis, pointing away from the pivot
    ang = math.degrees(math.atan2(v[1], v[0]) - self.fix["yaw"])
    th = (-ang + 180.0) % 360.0 - 180.0          # the arm points along +x when open and swings towards -y
    self.log("clamp seen at", round(th, 1), "deg from", len(allp), "px")
    return th

  def look_station(self):
    """From beside the fixture: clamp angle, height of the nest's far end above the plate dot beside it, and
    height of whatever stands in the pocket above the nest top (None where not seen)."""
    lp = self.f2w((-0.02, -0.14))
    yield from self.travel(np.array([lp[0], lp[1], 0.17]), R_topdown(self.best_yaw(lp, 0.0)))
    yield from self.finger_test()
    th = yield from self.clamp_angle_seen()
    ends, tops, near = [], [], []
    for _ in range(2):
      pts, valid = yield from self.fresh_frame(0.0)
      hue, sat, val = self.hsv()
      z = pts[..., 2]
      warm = ((hue < 85) | (hue > 345)) & (sat > 0.45) & (val > 110) & valid & self.near_mask(pts, self.f2w((0.0, -0.054)), 0.022)
      dot = (hue > 265) & (hue < 345) & (sat > 0.4) & (val > 70) & valid & self.near_mask(pts, self.f2w(FID_FIX[0]), 0.016)
      if warm.sum() >= 15:
        zb = float(np.median(z[warm]))
        if dot.sum() >= 12:
          ends.append(zb - float(np.median(z[dot])))
        warm1 = ((hue < 85) | (hue > 345)) & (sat > 0.45) & (val > 110) & valid & self.near_mask(pts, self.f2w((0.0, 0.054)), 0.022)
        dot1 = (hue > 265) & (hue < 345) & (sat > 0.4) & (val > 70) & valid & self.near_mask(pts, self.f2w(FID_FIX[1]), 0.016)
        if warm1.sum() >= 15 and dot1.sum() >= 12:
          near.append(float(np.median(z[warm1])) - float(np.median(z[dot1])))
        top = valid & self.near_mask(pts, self.fix["xy"], 0.009) & (z > zb + 0.02) & (z < zb + 0.05)
        if top.sum() >= 8:
          tops.append(float(np.median(z[top])) - zb)
      yield
    end = float(np.mean(ends)) if ends else None
    top = float(np.mean(tops)) if tops else None
    self.end_near = float(np.mean(near)) if near else None
    self.log("station: clamp", None if th is None else round(th, 1), "far end above dot (mm)",
             None if end is None else round(1000 * end, 1), "near end", None if self.end_near is None else round(1000 * self.end_near, 1),
             "part above nest (mm)", None if top is None else round(1000 * top, 1))
    return th, end, top

  # -------------------------------------------------------------------------------------- clamp
  def peg_pose(self, th_deg):
    a = self.fix["yaw"] + math.radians(HANDLE_DEG - th_deg)
    p = self.f2w(PIVOT) + PEG_AT * np.array([math.cos(a), math.sin(a)])
    return np.array([p[0], p[1], PEG_Z]), R_topdown(a)

  def fork_angle(self):
    p, _R = self.tool_world(True)
    v = p[:2] - self.f2w(PIVOT)
    a = math.degrees(math.atan2(v[1], v[0]) - self.fix["yaw"])
    return (HANDLE_DEG - a + 180.0) % 360.0 - 180.0

  def fork_to(self, th):
    p, R = self.peg_pose(th)
    q, _ep, _er = self.K.ik(self.w2m(p), R, self.q_des, 30)
    self.q_des = self.q_des + np.clip(q - self.q_des, -0.06, 0.06)

  def fork_on(self, th):
    p, R = self.peg_pose(th)
    yield from self.grip_to(FORK_OPEN, 0.3)
    yield from self.travel(p, R, speed=0.15)

  def fork_off(self):
    p, R = self.tool_world(False)
    yield from self.line(np.array([p[0], p[1], Z_SAFE]), R, speed=0.18)

  def open_clamp(self):
    yield from self.fork_on(88.0)
    th = 88.0
    while th > -7.0:
      th -= 22.0 * self.dt
      self.fork_to(th)
      yield
    for _ in range(100):
      if self.fork_angle() < -4.0:
        break
      yield
    self.fork_to(self.fork_angle() + 6.0)       # take the push off the peg
    yield from self.wait(0.3)
    yield from self.fork_off()

  def close_clamp(self, th_now, past_deg, knee_known=None):
    """Swing the clamp shut by feel: find the angle where the swing torque starts to rise (pad on the nest) and
    stop `past_deg` beyond it. Returns the angle past contact reached, or None."""
    yield from self.fork_on(float(np.clip(th_now, -5.0, 60.0)))
    th = float(np.clip(th_now, -5.0, 60.0))
    feel_from = 45.0 + PLAY_DEG
    while th < feel_from:
      th += 25.0 * self.dt
      self.fork_to(th)
      yield
    yield from self.wait(0.25)
    self.freeze_bias = True
    samples = []
    rf = thf = None
    base = None
    knee = knee_known
    slope = 0.0
    result = None
    t0 = self.obs["time"]
    while th < 122.0:
      th += FEEL_RATE * self.dt
      self.fork_to(th)
      yield
      _p, R = self.tool_world(True)
      r = -float(self.force_est() @ R[:, 1])        # resistance against the swing (tangent = hand y axis)
      a = self.fork_angle()
      rf = r if rf is None else rf + 0.25 * (r - rf)
      thf = a if thf is None else thf + 0.25 * (a - thf)
      samples.append((thf, rf))
      el = self.obs["time"] - t0
      if knee_known is None and (el < 1.2 or len(samples) % 2):
        continue
      if knee_known is not None:
        base = float(np.median([x[1] for x in samples[:15]]))
        if thf >= knee + past_deg * FORK_GIVE:
          result = (thf - knee) / FORK_GIVE
          break
        if rf - base > CLAMP_STOP_N:
          break
        continue
      # free swing (the reading may drift with the arm's pose), then a steady rise once the pad bears on the nest:
      # least-squares fit of r = c0 + k0 a + k max(0, a - knee) over every knee position
      aa = np.array(samples[10:])
      if len(aa) < 40:
        continue
      base = float(np.median(aa[:30, 1]))
      if rf - base > CLAMP_STOP_N:                  # never past the torque limit, knee or no knee
        break
      if rf - base < 1.2 and knee is None:
        continue
      best = None
      A = np.ones((len(aa), 3))
      A[:, 1] = aa[:, 0]
      for kn in np.arange(aa[8, 0], aa[-6, 0], 0.3):
        A[:, 2] = np.maximum(0.0, aa[:, 0] - kn)
        sol, res, _rk, _sv = np.linalg.lstsq(A, aa[:, 1], rcond=None)
        err = float(res[0]) if len(res) else float(np.sum((A @ sol - aa[:, 1]) ** 2))
        if best is None or err < best[0]:
          best = (err, float(kn), float(sol[2]))
      if best is not None and best[2] > 0.08 and thf - best[1] > 3.0:
        knee, slope = best[1], best[2]
      if knee is not None and thf >= knee + past_deg * FORK_GIVE:
        result = (thf - knee) / FORK_GIVE
        break
      if rf - base > CLAMP_STOP_N:
        break
    self.log("clamp: base", None if base is None else round(base, 2), "knee", None if knee is None else round(knee, 1), "slope", round(slope, 3),
             "stopped at", None if thf is None else round(thf, 1), "past", None if result is None else round(result, 1))
    self.q_des = self.qm().copy()                 # take the push off
    yield from self.wait(0.15)
    self.freeze_bias = False
    loaded = thf if thf is not None else self.fork_angle()      # hand angle where the push ended, under load
    stop = self.fork_angle()
    back = stop - 6.0
    for _ in range(20):
      self.fork_to(back)
      yield
    if result is not None and VERIFY:
      # stand by with the fork round the peg: if the clamp springs back it is caught here; then come up to the
      # same hand angle again (nothing moves if the clamp stayed put)
      yield from self.wait(1.1)
      self.freeze_bias = True
      th2, f0, touch, hits = back, None, None, 0
      for _ in range(400):
        th2 += FEEL_RATE * self.dt
        self.fork_to(th2)
        yield
        _p, R = self.K.fk(self.qm())
        r = -float(self.force_est() @ R[:, 1])
        f0 = r if f0 is None else f0
        now = self.fork_angle()
        hits = hits + 1 if r - f0 > 1.5 else 0
        if touch is None and hits >= 3:             # three ticks running: one noisy reading is not the peg
          touch = now
          if touch > stop - 3.0:                    # the peg is where it was left: nothing to do
            break
        # a clamp that sprang back is brought to the hand angle the first push ended at, and no further: that is
        # the same clamp angle, so the same torque (going past it took the clamp out of its window)
        if now >= loaded or r - f0 > CLAMP_STOP_N + 1.0 or th2 > loaded + 10.0:
          break
      self.log("clamp: second approach met the peg at", None if touch is None else round(touch, 1), "ended at", round(self.fork_angle(), 1), "of", round(loaded, 1))
      self.q_des = self.qm().copy()
      yield from self.wait(0.15)
      self.freeze_bias = False
      back = self.fork_angle() - 6.0
      for _ in range(20):
        self.fork_to(back)
        yield
    yield from self.fork_off()
    return result, knee, thf

  # -------------------------------------------------------------------------------------- pressing
  def press(self, xy, z_top, drop, cap, probe=False, label_=""):
    """Closed fingertips straight down on a point. Returns (contact height, lowest height, dropped):
    `probe` stops at first touch; otherwise it pushes until the surface drops by `drop` (a detent giving way)
    or the push reaches `cap` newtons (estimated from the joint servos)."""
    yaw = self.best_yaw(xy, math.atan2(xy[1], xy[0]))
    R = R_topdown(yaw)
    yield from self.grip_to(0.0, 0.3)
    start = np.array([xy[0], xy[1], z_top + 0.007 + TIP_BELOW_SITE])
    yield from self.travel(start, R, speed=0.16)
    yield from self.wait(0.2)
    self.freeze_bias = True
    z = start[2]
    q = self.q_des.copy()
    fz, zs = [], []
    base = None
    z_contact = z_low = None
    hit = 0
    side = np.zeros(2)
    peak = 0.0
    dropped = False
    n = 0
    while z > start[2] - 0.045:
      z -= PRESS_SPEED * self.dt
      q, _ep, _er = self.K.ik(self.w2m(np.array([xy[0] + side[0], xy[1] + side[1], z])), R, q, 20)
      self.q_des = q
      yield
      n += 1
      f = float(self.force_est()[2])
      pm = self.tool_world(True)[0]
      zt = float(pm[2]) - TIP_BELOW_SITE
      # under a push the servos give sideways as well (a few mm at 10 N): a fingertip that drifts drags the part's
      # top with it and wedges the part in its pocket. Hold the measured fingertip over the point
      if PRESS_HOLD_XY:
        side = np.clip(side + 0.2 * (np.asarray(xy[:2]) - pm[:2]), -0.008, 0.008)
      fz.append(f)
      zs.append(zt)
      if n < 4:
        continue
      if base is None:
        if n >= 13:
          base = float(np.median(fz[4:]))
        continue
      ff = float(np.mean(fz[-3:])) - base
      zf = float(np.mean(zs[-8:]))
      peak = max(peak, ff)
      if z_contact is None:
        hit = hit + 1 if ff > 1.5 else 0
        if hit >= 2:
          z_contact = z_low = float(np.mean(zs[-4:]))
          if probe:
            break
        continue
      z_low = min(z_low, zf)
      if z_contact - zf > drop:
        dropped = True
        break
      if ff > cap:
        break
    self.q_des = self.qm().copy()                 # take the push off at once
    yield from self.wait(0.1)
    if dropped:
      z_low = min(z_low, float(self.tool_world(True)[0][2]) - TIP_BELOW_SITE)
    self.freeze_bias = False
    self.log("press", label_, "probe" if probe else "", "contact", None if z_contact is None else round(z_contact, 4),
             "low", None if z_low is None else round(z_low, 4), "dropped", dropped,
             "peak", round(max(fz) - (base or 0.0), 1) if fz else None,
             "trace", [(round(self.obs["time"] - (len(fz) - i) * self.dt, 2), round(fz[i] - (base or 0.0), 1)) for i in range(0, len(fz), 10)] if TRACE else "")
    p, _R = self.tool_world(False)
    yield from self.line(np.array([xy[0], xy[1], z_top + 0.02 + TIP_BELOW_SITE]), R, speed=0.12)
    return z_contact, z_low, dropped

  def press_open_loop(self, xy, z_seated):
    """The careless way: drive the fingertips to a fixed depth below where the top should end up."""
    yaw = self.best_yaw(xy, math.atan2(xy[1], xy[0]))
    R = R_topdown(yaw)
    yield from self.grip_to(0.0, 0.3)
    yield from self.travel(np.array([xy[0], xy[1], z_seated + 0.02 + TIP_BELOW_SITE]), R, speed=0.10)
    yield from self.line(np.array([xy[0], xy[1], z_seated - OPEN_LOOP_DEPTH + TIP_BELOW_SITE]), R, speed=0.03)
    yield from self.wait(0.5)
    yield from self.line(np.array([xy[0], xy[1], z_seated + 0.02 + TIP_BELOW_SITE]), R, speed=0.08)
    return z_seated, z_seated, True

  # -------------------------------------------------------------------------------------- nests
  def take_nest(self, centre, axis, z_top, offset=0.0, slow_lift=0.03):
    yaw = self.best_yaw(centre, axis)
    R = R_topdown(yaw)
    ax = np.array([math.cos(yaw), math.sin(yaw)])
    g = np.asarray(centre) - offset * ax
    p = np.array([g[0], g[1], z_top - NEST_T / 2 + 0.0015])
    # wide open the fingers can come down on the nest in the next bay (bays 85 mm apart, nests turned a few
    # degrees): if the hand is held up short of the grasp height, lift and come down again less far open
    for opening in (NEST_OPEN, 0.040, 0.036):
      yield from self.grip_to(opening, 0.3)
      yield from self.travel(p + np.array([0, 0, 0.022]), R, speed=0.12)
      yield from self.line(p, R, speed=0.035, guard=0.004)     # slow enough that servo lag is not read as a stop
      yield from self.wait(0.15)
      up = float(self.tool_world(True)[0][2]) - p[2]
      if up < 0.0025:
        break
      self.log("hand held up", round(1000 * up, 1), "mm short of the nest's grasp height at opening", opening)
      yield from self.line(p + np.array([0, 0, 0.022]), R, speed=0.08)
    # the hand is never exactly over the nest (camera to arm, 1-3 mm): the closing fingers pull the nest sideways
    # against whatever locates it (the pins), the servos' slow correction keeps adding to that push, and a nest
    # lifted with a side load binds on the pins and then jumps free into the fingers (50 N and more). So: hold the
    # correction while closing, then let the arm go to where the nest has put the hand, and lift from there
    bias0 = self.bias.copy()
    self.freeze_bias = True
    yield from self.grip_to(NEST_W / 2 - 0.010, 0.6)
    yield from self.wait(0.25)
    if RELAX_GRASP:
      self.q_des = self.qm().copy()
      self.bias = bias0
      yield from self.wait(0.1)
      self.q_des = self.qm().copy()
    # closing on the nest can pull the hand down a little while the nest stays where it rests: how far the hand
    # now sits below where it was sent is how far the nest rides high in it
    self.grip_dz = float(np.clip(float(self.tool_world(True)[0][2]) - p[2], -0.005, 0.003))
    self.log("nest in the hand: hand", round(1000 * self.grip_dz, 2), "mm off its grasp height")
    self.carry = (p, R, NEST_OPEN)
    if RELAX_GRASP and slow_lift > 0.014:
      ph, Rh = self.tool_world(False)
      yield from self.line(np.array([ph[0], ph[1], p[2] + 0.014]), Rh, speed=0.03)     # clear of the pins, no side pull
    self.freeze_bias = False
    yield from self.line(p + np.array([0, 0, slow_lift]), R, speed=0.03)
    return p, R, yaw

  def rest_item(self, R, depth=0.006):
    """Before letting go: lower slowly until the item in the hand stands on what is under it. An item let go a
    millimetre or two up drops the rest of the way, which is fine while the fingers open; with a gripper that has
    stopped answering it would hang there, and the report has to find it resting (CHANGEOVER_SHEET.md, Faults)."""
    ph, _R = self.tool_world(False)
    yield from self.line(np.array([ph[0], ph[1], ph[2] - depth]), R, speed=0.012, guard=0.0008)

  def put_nest(self, centre, yaw, z_top, offset=0.0):
    R = R_topdown(yaw)
    ax = np.array([math.cos(yaw), math.sin(yaw)])
    g = np.asarray(centre) - offset * ax
    p = np.array([g[0], g[1], z_top - NEST_T / 2 + 0.0015 + 0.002])
    yield from self.travel(p + np.array([0, 0, 0.03]), R, speed=0.15)
    yield from self.line(p, R, speed=0.03, guard=0.004)
    yield from self.rest_item(R)
    yield from self.let_go(NEST_OPEN, 0.5)
    yield from self.wait(0.15)
    yield from self.line(p + np.array([0, 0, 0.06]), R, speed=0.18)

  def seat_nest(self, nest, z_top=None):
    """Nest from the shelf (or from where it lies on the fixture, `z_top` given) onto the pins: hold it over
    them, line its far band up with the fixture dot in the image, lower, let go."""
    off = 0.020
    if FIX_OUTLINE and z_top is None and not getattr(self, "fix_fitted", False):
      self.fix_fitted = True
      yield from self.fixture_fit()
    _p, _R, yaw0 = yield from self.take_nest(nest["xy"], nest["axis"], RAIL_TOP + NEST_T if z_top is None else z_top, off)
    yaw = self.fix["yaw"] + math.pi / 2                 # hand x along the pin line, towards pin 1
    R = R_topdown(yaw)
    ax = np.array([math.cos(yaw), math.sin(yaw)])
    centre = self.fix["xy"].copy()
    z_hover = SEAT_Z + 0.016 + NEST_T / 2 + 0.0015
    for attempt in range(4):
      g = centre - off * ax
      yield from self.travel(np.array([g[0], g[1], z_hover]), R, speed=0.12)
      if SERVO_NEST:
        # One reading is good to a millimetre or two (a pixel is 3.4 mm) and now and then 2.5 mm out. Each reading
        # says where the hand should be; the hand goes to the median of what the readings so far say, so one bad
        # reading cannot walk the nest off the pins.
        said = []
        for it in range(5):
          fit = (yield from self.nest_error(ax, yaw, SEAT_Z + 0.016 + NEST_T)) if NEST_OUTLINE else None
          if fit is not None:
            err = fit[0]
            self.log("nest over the pins: off by", np.round(1000 * err, 2), "mm, turned", round(math.degrees(fit[1]), 2), "deg")
          else:
            err = yield from self.band_error(ax, SEAT_Z + 0.016 + NEST_T)
            if err is None:
              break
            self.log("nest over the pins: band off by", np.round(1000 * err, 2), "mm")
          said.append(centre - np.clip(err, -0.008, 0.008))
          new = np.median(np.array(said), axis=0)
          step = float(np.linalg.norm(new - centre))
          if step < 0.0005 and it >= 1:
            break
          centre = new
          g = centre - off * ax
          yield from self.line(np.array([g[0], g[1], z_hover]), R, speed=0.04)
      z_down = SEAT_Z + 0.0030 + NEST_T / 2 + 0.0015 + self.grip_dz
      yield from self.wait(0.15)
      f_free = float(np.mean([self.force_est()[2] for _ in range(1)]))
      if NEST_GIVE:
        ok, side, turn = yield from self.lower_with_give(g, z_hover, z_down, yaw)
        centre, g, R = centre + side, g + side, R_topdown(yaw + turn)
      else:
        ok = yield from self.line(np.array([g[0], g[1], z_down]), R, speed=0.012, guard=0.003)
      zt = float(self.tool_world(True)[0][2])
      self.log("nest lowered: hand at", round(zt, 4), "wanted", round(z_down, 4), "free" if ok else "held up")
      if zt < z_down + 0.0012 or attempt == 3:
        break
      if LET_GO_ON_PINS and zt < z_down + 0.0085:
        # Held up by a few millimetres with the band lined up and nothing pushing sideways: the holes are over
        # the pins. The far end has gone down to its detent, the nest has tipped in the pads (they hold it like a
        # hinge, off its middle) and the near bushing, tipped 3 degrees, will not start on its pin. Let go: each
        # end is pressed home and checked after this, and a nest found not on the pins is taken up again.
        # (Circling with the nest in the hand took 20-70 s here and often found nothing.)
        self.log("held up", round(1000 * (zt - z_down), 1), "mm over the pins: letting the nest go to settle on its detents")
        break
      # resting on the pin noses: push down lightly and circle outwards until the holes find the pins
      # (a fixed 4 mm of lead, about 2 N, with the slow servo correction held: when the holes find the pins the nest
      # drops to its detents and the push is gone, instead of a wound-up arm driving it through them)
      z_push = zt - 0.004
      self.freeze_bias = True
      q = self.q_des.copy()
      found = False
      lvl, low, i0 = [], 0, 0
      for i in range(1, 420):
        rad, ang = 0.0042 * i / 420.0, 0.5 * i
        c = centre + rad * np.array([math.cos(ang), math.sin(ang)])
        Rs = R_topdown(yaw + math.radians(2.0) * math.sin(0.13 * i) * min(1.0, i / 60.0))
        gg = c - off * ax
        q, _ep, _er = self.K.ik(self.w2m(np.array([gg[0], gg[1], z_push])), Rs, q, 20)
        self.q_des = q
        yield
        f = float(self.force_est()[2]) - f_free
        if i - i0 <= 14:
          if i - i0 > 6 and i0 == 0:
            lvl.append(f)
          continue
        push = float(np.median(lvl))
        if push < 1.2:                              # not bearing on anything: nothing to feel for
          break
        low = low + 1 if f < 0.35 * push else 0
        if low >= 3:
          # the push has gone. Over the pins the nest goes down to its detents, 5 mm below the pin noses; on the
          # noses it does not, so try: the hand has to follow it down
          self.q_des = self.qm().copy()
          yield from self.wait(0.1)
          _pw, Rnow = self.tool_world(False)
          yield from self.line(np.array([gg[0], gg[1], z_down]), Rnow, speed=0.012, guard=0.003)
          z2 = float(self.tool_world(True)[0][2])
          self.log("search: push gone at", round(1000 * rad, 2), "mm; hand then at", round(z2, 4), "wanted", round(z_down, 4))
          if z2 < z_down + 0.0015:
            found = True
            centre, g = c, gg
            break
          yield from self.line(np.array([gg[0], gg[1], z_push]), Rs, speed=0.02)
          q = self.q_des.copy()
          low, i0 = 0, i
      self.q_des = self.qm().copy()
      self.freeze_bias = False
      yield from self.wait(0.1)
      self.log("search over the pins:", "found at" if found else "nothing within", round(1000 * rad, 2), "mm")
      if found:
        break
      if zt < z_down + 0.0030 and rad > 0.004:
        # held up by less than 3 mm and the push never went: the nest is on its detents, not on the pin noses
        # (the end presses that follow check it)
        self.log("nothing found and the hand is", round(1000 * (zt - z_down), 1), "mm up: taken as on the detents")
        break
      yield from self.line(np.array([g[0], g[1], z_hover]), R, speed=0.05)
    yield from self.let_go(NEST_OPEN, 0.5)
    yield from self.wait(0.2)
    p, _R2 = self.tool_world(False)
    yield from self.line(np.array([p[0], p[1], Z_SAFE]), R, speed=0.18)

  def lower_with_give(self, g, z0, z1, yaw):
    """Lower the nest onto the pins with the hand giving way to what the pin noses push on it: sideways to the
    side force and round its own axis to the twisting moment (the two noses push opposite ways when the nest is
    turned a little against the pin line). The hand never leads the nest by more than 3 mm, about 1.5 N of push,
    and the slow servo correction is held. Held stiffly, a nest a degree askew hangs on one nose and does not go
    down. Returns (down, sideways give, turn)."""
    held = self.freeze_bias
    self.freeze_bias = True
    yield from self.wait(0.1)
    q = self.q_des.copy()
    side, turn, ws = np.zeros(2), 0.0, None
    # what the joints read as a load while the hand goes down through free air at this speed (the servos lag
    # a moving command; it read as 1.6 N sideways here): taken over 2 to 5 mm of the way down and subtracted
    base = []
    zc = z0
    while zc > z0 - 0.005:
      zc -= 0.012 * self.dt
      q, _ep, _er = self.K.ik(self.w2m(np.array([g[0], g[1], zc])), R_topdown(yaw), q, 20)
      self.q_des = q
      yield
      if zc < z0 - 0.002:
        base.append(self.wrench_est())
    w0 = np.mean(base, axis=0)
    z0 = zc
    k_turn = 0.08 / float(self.K.kp[5])                # rad per N m per tick: a tenth of the wrist's own stiffness
    zc, t_stuck, n, down = z0, 0, 0, False
    zs = []
    while n < 400:
      n += 1
      zm = float(self.tool_world(True)[0][2])
      zs.append(zm)
      if zm < z1 + 0.0010:
        down = True
        break
      zc = max(z1, zc - 0.012 * self.dt, zm - 0.003)
      q, _ep, _er = self.K.ik(self.w2m(np.array([g[0] + side[0], g[1] + side[1], zc])), R_topdown(yaw + turn), q, 20)
      self.q_des = q
      yield
      w = self.wrench_est() - w0
      ws = w if ws is None else ws + 0.3 * (w - ws)
      fl = ws[:2] * max(0.0, 1.0 - 0.5 / max(float(np.linalg.norm(ws[:2])), 1e-6))     # 0.5 N dead band
      side = np.clip(side + NEST_SIDE_GIVE * PLACE_GIVE * fl, -0.005, 0.005)
      mz = float(ws[5])
      mz = 0.0 if abs(mz) < 0.015 else mz - math.copysign(0.015, mz)
      turn = float(np.clip(turn + NEST_TURN_GIVE * k_turn * mz, -math.radians(4.0), math.radians(4.0)))
      # held up and no longer going down: give it 2 s of this, then leave it to the caller
      if len(zs) > 30 and float(np.mean(zs[-30:-20]) - np.mean(zs[-10:])) < 0.0003 and zm - zc > 0.002:
        t_stuck += 1
        if t_stuck > 75:
          break
      else:
        t_stuck = max(0, t_stuck - 2)
    self.q_des = self.qm().copy()
    self.freeze_bias = held
    self.log("nest lowered with give: sideways", np.round(1000 * side, 2), "mm, turn", round(math.degrees(turn), 2), "deg, moment at the end", None if ws is None else round(float(ws[5]), 3), "N m, side push", None if ws is None else np.round(ws[:2], 2))
    return down, side, turn

  def outline_fit(self, sl, seen, use, cast, c0, th0, axes, turns=True):
    """Lay a model outline over the depth picture: `cast(sel, c, th)` gives the model's label for the selected
    pixels with the model at place c, heading th; `seen` holds the picture's labels. The pixels that disagree
    are counted at trial places either side of the start, and the count falls to a V at the true place (a pixel
    is 3.4 mm; some hundred outline pixels at different phases place the V to a few tenths of a millimetre).
    Returns (c, th, edge pixels, pixels left differing) or None."""
    full = np.ones_like(use)
    p0 = np.zeros(use.shape, np.int32)
    p0[full] = cast(full, c0, th0)
    # only pixels the outline can cross within the trial range are cast again
    edge = np.zeros_like(use)
    edge[1:] |= p0[1:] != p0[:-1]; edge[:-1] |= p0[1:] != p0[:-1]
    edge[:, 1:] |= p0[:, 1:] != p0[:, :-1]; edge[:, :-1] |= p0[:, 1:] != p0[:, :-1]
    for _ in range(2):
      g2 = edge.copy()
      g2[1:] |= edge[:-1]; g2[:-1] |= edge[1:]; g2[:, 1:] |= edge[:, :-1]; g2[:, :-1] |= edge[:, 1:]
      edge = g2
    edge &= use
    want = seen[edge]
    if int(edge.sum()) < 60:
      return None

    def vee(x, y):
      best = (1e18, float(x[int(np.argmin(y))]))
      for x0 in np.arange(x[0], x[-1] + 1e-9, (x[1] - x[0]) / 12.0):
        A = np.column_stack([np.ones(len(x)), np.abs(x - x0)])
        co, *_ = np.linalg.lstsq(A, y, rcond=None)
        if co[1] <= 0:
          continue
        r = float(np.sum((A @ co - y) ** 2))
        if r < best[0]:
          best = (r, float(x0))
      return best[1]

    c, th = np.asarray(c0, float).copy(), th0
    for span, step in ((0.006, 0.0012), (0.0024, 0.0006)):
      for u in axes:
        xs = np.arange(-span, span + 1e-9, step)
        ys = np.array([float(np.sum(cast(edge, c + x * u, th) != want)) for x in xs])
        c = c + vee(xs, ys) * u
      if turns and span > 0.003:
        xs = np.radians(np.arange(-2.0, 2.01, 0.5))
        ys = np.array([float(np.sum(cast(edge, c, th + x) != want)) for x in xs])
        th = th + vee(xs, ys)
    left = int(np.sum(cast(edge, c, th) != want))
    return c, th, int(edge.sum()), left

  def _window(self, c0, z, W):
    h, w = self.obs["depth"]["overhead"].shape
    r0, q0 = (int(round(v)) for v in self.project(np.array([c0[0], c0[1], z])))
    if r0 - W < 0 or r0 + W >= h or q0 - W < 0 or q0 + W >= w:
      return None
    sl = (slice(r0 - W, r0 + W + 1), slice(q0 - W, q0 + W + 1))
    self.cloud()
    _, uu, vv = self._ray_cache
    return sl, uu[sl][..., None] * CAM_X + vv[sl][..., None] * CAM_Y - CAM_Z

  @staticmethod
  def _grown(mask):
    out = mask.copy()
    out[1:] |= mask[:-1]; out[:-1] |= mask[1:]; out[:, 1:] |= mask[:, :-1]; out[:, :-1] |= mask[:, 1:]
    return out

  def nest_error(self, ax, yaw, z_top):
    """Where the nest held over the pins is against the fixture, from its whole outline in the depth picture
    (the station model's nest laid over the picture, `outline_fit`). The band alone (50 pixels, one end often
    behind the hand) read up to 3 mm out. Returns (offset xy, turn) or None."""
    pts, valid = yield from self.fresh_frame(0.45)
    K = self.K
    m = K.m
    if not hasattr(self, "_nest_rays"):
      b = m.body("nest_b").id
      gs = [g for g in range(m.ngeom) if m.geom_bodyid[g] == b and m.geom_group[g] == 0]
      m.geom_group[gs] = 5
      self._nest_rays = (int(m.jnt_qposadr[m.body_jntadr[b]]), np.array([0, 0, 0, 0, 0, 1], np.uint8))
    qa, grp = self._nest_rays
    c0 = np.asarray(self.tool_world(True)[0][:2]) + 0.020 * ax          # the nest's middle, by the hand
    win = self._window(c0, z_top, 24)
    if win is None:
      return None
    sl, vec = win
    z = pts[..., 2][sl]
    ok = valid[sl]
    rel = pts[..., :2][sl] - c0[None, None, :]
    along, side_ = np.abs(rel @ ax), np.abs(rel @ np.array([-ax[1], ax[0]]))
    flat = ok & (along > 0.030) & (along < 0.052) & (side_ < 0.022)        # the flat ends, clear of the collar and the hand
    top = flat & (np.abs(z - z_top) < 0.008)
    if int(top.sum()) < 12:
      self.log("nest outline: top face not seen,", int(top.sum()), "px of", int(flat.sum()))
      return None
    zt = float(np.median(z[top]))                                       # the nest's top face as the camera has it
    seen = (ok & (z > zt - NEST_T - 0.004) & (z < zt + 0.005)).astype(np.int32)
    use = ok & ~self._grown(ok & (z >= zt + 0.005))                     # not the hand, the fingers, the nest's own collar
    keep = K.d.qpos[qa:qa + 7].copy()

    def cast(sel, c, th):
      K.d.qpos[qa:qa + 7] = (c[0], c[1], zt - NEST_T, math.cos(th / 2), 0.0, 0.0, math.sin(th / 2))
      mujoco.mj_kinematics(m, K.d)
      n = int(sel.sum())
      dist, gid = np.zeros(n), np.zeros(n, np.int32)
      mujoco.mj_multiRay(m, K.d, CAM_POS, np.ascontiguousarray(vec[sel]).ravel(), grp, 0, -1, gid, dist, None, n, 3.0)
      return (gid >= 0).astype(np.int32)

    th0 = yaw - math.pi / 2                                             # the nest's long side lies along the hand's x
    try:
      fit = self.outline_fit(sl, seen, use, cast, c0, th0, (np.array([-ax[1], ax[0]]), ax))
      if DEBUG and NEST_DUMP and fit is not None:
        full = np.ones_like(use)
        pm = np.zeros(use.shape, np.int32)
        pm[full] = cast(full, fit[0], fit[1])
        relc = pts[..., :2][sl] - fit[0][None, None, :]
        uu_, vv_ = relc @ ax, relc @ np.array([-ax[1], ax[0]])
        bad = use & (pm != seen)
        self.log("nest dump: differing", [(round(1000 * float(uu_[i, j])), round(1000 * float(vv_[i, j])), int(seen[i, j]), round(1000 * float(z[i, j]), 1)) for i, j in zip(*np.nonzero(bad)) if not seen[i, j]][::9][:40])
        for name_, msk in (("seen", seen == 1), ("model", pm == 1), ("unused", ~use)):
          self.log("nest dump:", name_, "px", int(msk.sum()), "u range", round(1000 * float(uu_[msk].min()), 1), round(1000 * float(uu_[msk].max()), 1), "v range", round(1000 * float(vv_[msk].min()), 1), round(1000 * float(vv_[msk].max()), 1))
        rows_ = ["".join("#" if (seen[i, j] and pm[i, j]) else "s" if seen[i, j] else "m" if pm[i, j] else ("x" if not use[i, j] else ".") for j in range(use.shape[1])) for i in range(use.shape[0])]
        self.log("nest dump map\n" + "\n".join(r_ for r_ in rows_ if set(r_) - {"."}))
    finally:
      K.d.qpos[qa:qa + 7] = keep
      mujoco.mj_kinematics(m, K.d)
    if fit is None:
      self.log("nest outline: too little outline")
      return None
    c, th, n_edge, left = fit
    if DEBUG:
      self.log("nest outline: edge px", n_edge, "left differing", left, "top at", round(zt, 4), "by the hand", np.round(c0, 4).tolist(),
               "seen", np.round(c, 4).tolist(), "turn", round(math.degrees(th - th0), 2))
    if left > 0.35 * n_edge:
      return None
    return c - self.fix_cam, th - th0

  def fixture_fit(self):
    """The bare fixture (nest A gone, hand away) from its outline in the depth picture: base plate, seat block
    and pins of the station model laid over the picture (`outline_fit`). The two dots place it to a millimetre or
    two (each is 30 pixels); the nest has to come down on pins with 0.15 mm of play, and it is lined up against
    this."""
    pts, valid = yield from self.fresh_frame(0.3)
    K = self.K
    m = K.m
    b = m.body("fixture").id
    if not hasattr(self, "_fix_rays"):
      gs = [g for g in range(m.ngeom) if m.geom_bodyid[g] == b and m.geom_group[g] == 0]
      m.geom_group[gs] = 4
      self._fix_rays = np.array([0, 0, 0, 0, 1, 0], np.uint8)
    grp = self._fix_rays
    c0, th0 = self.fix["xy"].copy(), self.fix["yaw"]
    win = self._window(c0, SEAT_Z, 36)
    if win is None:
      return
    sl, vec = win
    z = pts[..., 2][sl]
    ok = valid[sl]
    mid = ok & (np.linalg.norm(pts[..., :2][sl] - c0[None, None, :], axis=2) < 0.012) & (np.abs(z - SEAT_Z) < 0.008)
    if int(mid.sum()) < 8:
      self.log("fixture outline: seat block not seen bare,", int(mid.sum()), "px")
      return
    zs = float(np.median(z[mid]))                                       # the seat block's top as the camera has it
    seen = np.where(z > zs - 0.008, 2, np.where(z > zs - 0.019, 1, 0)).astype(np.int32)
    use = ok & ~self._grown(ok & (z > zs + 0.014))                      # not the clamp, not the arm
    pos0, quat0 = m.body_pos[b].copy(), m.body_quat[b].copy()

    def cast(sel, c, th):
      m.body_pos[b] = (c[0], c[1], 0.0)
      m.body_quat[b] = (math.cos(th / 2), 0.0, 0.0, math.sin(th / 2))
      mujoco.mj_kinematics(m, K.d)
      n = int(sel.sum())
      dist, gid = np.zeros(n), np.zeros(n, np.int32)
      v = np.ascontiguousarray(vec[sel])
      mujoco.mj_multiRay(m, K.d, CAM_POS, v.ravel(), grp, 1, -1, gid, dist, None, n, 3.0)
      zh = CAM_POS[2] + dist * v[:, 2] - (zs - SEAT_Z)                   # heights as the model has them
      return np.where(gid < 0, 0, np.where(zh > 0.014, 2, 1)).astype(np.int32)

    ax = np.array([-math.sin(th0), math.cos(th0)])
    try:
      fit = self.outline_fit(sl, seen, use, cast, c0, th0, (np.array([ax[1], -ax[0]]), ax))
    finally:
      m.body_pos[b], m.body_quat[b] = pos0, quat0
      mujoco.mj_kinematics(m, K.d)
    if fit is None:
      self.log("fixture outline: too little outline")
      return
    c, th, n_edge, left = fit
    self.log("fixture outline: edge px", n_edge, "left differing", left, "seat top at", round(zs, 4), "moved", np.round(1000 * (c - c0), 2), "mm,",
             round(math.degrees(th - th0), 2), "deg from the dots")
    if left > 0.35 * n_edge or float(np.linalg.norm(c - c0)) > 0.006:
      return
    self.fix["xy"], self.fix["yaw"] = c.copy(), float(th)
    self.fix_cam = c.copy()
    self.fix_good = True

  def band_error(self, ax, z_top):
    """Where the nest's far end band is in the image, against where it belongs relative to the fixture dot."""
    pts, valid = yield from self.fresh_frame(0.45)
    hue, sat, val = self.hsv()
    # Against the fixture as the camera saw it at the start, with nothing over it. (The dot beside the band was
    # found afresh here before: the nest held over the pins hides the near edge of that dot from a camera that
    # looks at the fixture at a slant, the dot reads a few millimetres further out, the hand follows it out and
    # hides more of it. On the mount further from the camera that ran away by 5 mm.)
    org = self.fix_cam
    want = org + ax * (STRIPE[0] + STRIPE[1]) / 2
    warm = ((hue < 85) | (hue > 345)) & (sat > 0.45) & (val > 110) & valid & (np.abs(pts[..., 2] - z_top) < 0.012)
    sb = self.blobs(warm & self.near_mask(pts, want, 0.03), 14)
    if not sb:
      self.log("band not seen")
      return None
    b = max(sb, key=lambda b: b["n"])
    if b["n"] < 28:
      self.log("band partly hidden:", b["n"], "px")
      return None
    if DEBUG:
      rr, cc = b["rc"]
      self.log("band blob", b["n"], "px of", [x["n"] for x in sb], "rows", int(rr.min()), int(rr.max()), "cols", int(cc.min()), int(cc.max()),
               "per col", np.bincount(cc - cc.min()).tolist(), "per row", np.bincount(rr - rr.min()).tolist(), "want", np.round(want, 4).tolist(), "xy", np.round(b["xy"], 4).tolist())
    return b["xy"] - want

  # -------------------------------------------------------------------------------------- parts
  def pick_part(self, xy, z_top, axis_yaw, lift=0.05, slow=False, below=0.0045, centre=False):
    yaw = self.tray_yaw(xy, axis_yaw) if centre else self.best_yaw(xy, axis_yaw)
    R = R_topdown(yaw)
    p = np.array([xy[0], xy[1], z_top - below])
    yield from self.grip_to(PART_OPEN, 0.3)
    if centre and CENTRE_PART:
      # A part standing free on the tray is seen 2-4 mm off with a noisy camera. Fingers closing high on it then
      # push it over before the second finger arrives (it tips when pushed above radius / friction = 17 mm) and
      # it is carried tilted. So the fingers first close low on it, where it slides to the middle of the hand,
      # let go, and take it at the carrying height.
      low = np.array([xy[0], xy[1], z_top - PART_H + 0.0105])
      yield from self.travel(low, R, speed=0.14)
      yield from self.grip_to(PART_R - 0.0005, 0.6)
      yield from self.wait(0.1)
      yield from self.let_go(PART_OPEN, 0.3)             # seen open before the hand rises: it must not lift the part
      yield from self.line(p, R, speed=0.08)
    else:
      yield from self.travel(p, R, speed=0.14)
    yield from self.grip_to(PART_R - 0.008, 0.5)
    yield from self.wait(0.2)
    self.carry = (p, R, PART_OPEN)
    yield from self.line(p + np.array([0, 0, lift]), R, speed=0.03 if slow else 0.12)
    return p, R

  def place_part(self):
    yaw = self.fix["yaw"] + math.pi / 2
    R = R_topdown(yaw)
    c = self.fix["xy"] + rz(self.fix["yaw"])[:2, :2] @ np.array(PLACE_OFF)
    z = SEAT_Z + NEST_T + 0.0065 + PART_H - 0.006 + 0.0015
    yield from self.travel(np.array([c[0], c[1], z + 0.028]), R, speed=0.16)
    # The hand is 1-3 mm off the pocket (camera to arm), more with sensor noise: a part lowered stiffly rides down
    # the lead-in, loads the arm sideways and is left on the rim or tilted when the fingers open. So the last 26 mm
    # go down slowly with the hand giving way sideways to whatever pushes on the part (the lead-in centres it), the
    # slow servo correction held, and stopping if the part is held up (never push a held part into the pocket)
    yield from self.wait(0.2)
    self.freeze_bias = True
    f0 = np.mean([self.force_est() for _ in range(1)], axis=0)
    q = self.q_des.copy()
    side = np.zeros(2)
    # down to 3 mm under where the part meets its detent: the hand then leads by up to 3 mm (1.5 N, the detent
    # gives at 8 N or more) and the part stands on the detent while the fingers still hold it. Let go 2 mm above the
    # detent it dropped onto it, and hung there in a gripper that had stopped answering.
    zz, z_end, fs = z + 0.028, z - 0.0018 - 0.003, None
    z_on = z - 0.0018                                  # the hand's height with the part on its detent
    for attempt in range(2):
      zm, zc = [], []
      while zz > z_end:
        zz -= 0.010 * self.dt
        q, _ep, _er = self.K.ik(self.w2m(np.array([c[0] + side[0], c[1] + side[1], zz])), R, q, 20)
        self.q_des = q
        yield
        f = self.force_est() - f0
        fs = f if fs is None else fs + 0.3 * (f - fs)
        if PLACE_GIVE:
          fl = fs[:2] * max(0.0, 1.0 - 0.5 / max(float(np.linalg.norm(fs[:2])), 1e-6))    # 0.5 N dead band
          side = np.clip(side + PLACE_GIVE * fl, -0.005, 0.005)
        zm.append(float(self.tool_world(True)[0][2])); zc.append(zz)
        if len(zm) > 12 and zc[0] - zc[-1] > 0.003 and zm[-1] - zc[-1] > 0.003 and zm[-10] - zm[-1] < 0.0004:
          break
      z_now = float(np.mean(zm[-5:])) if zm else zz
      if z_now < z_on + 0.0025 or attempt == 1 or not PLACE_SEARCH:
        if z_now >= z_on + 0.0025:
          self.log("place: part held up at", round(z_now, 4), "of", round(z_on, 4))
        break
      # Stopped well above the detent: the part's foot is on the pocket's lead-in, a millimetre or two out, and
      # with a dry surface it does not slide down it. Circle outwards under a light push (the hand leads by 2 mm)
      # until the part drops into the pocket (1 mm of play all round), then go on down from there.
      self.log("place: part held up at", round(z_now, 4), "of", round(z_on, 4), ": circling for the pocket")
      a, s_, found = 0.00013, 0.0, False
      zr = []
      while s_ < 0.045:
        s_ += 0.00024
        th = math.sqrt(2.0 * s_ / a)
        off = a * th * np.array([math.cos(th), math.sin(th)])
        zh = float(self.tool_world(True)[0][2])
        zr.append(zh)
        zz = max(z_end, float(np.mean(zr[-5:])) - 0.002)
        q, _ep, _er = self.K.ik(self.w2m(np.array([c[0] + side[0] + off[0], c[1] + side[1] + off[1], zz])), R, q, 20)
        self.q_des = q
        yield
        if len(zr) > 10 and float(np.mean(zr[-5:])) < z_now - 0.003:
          found = True
          break
      self.log("place: circled to", np.round(1000 * off, 2), "mm,", "the part dropped" if found else "nothing found")
      if not found:
        break
      side = side + off
      zz = float(np.mean(zr[-5:]))
    self.log("place: gave", np.round(1000 * side, 2), "mm sideways; side push at the end", None if fs is None else np.round(fs[:2], 2))
    self.q_des = self.qm().copy()
    yield from self.let_go(PART_OPEN, 0.4)
    yield from self.wait(0.15)
    self.freeze_bias = False
    if float(np.linalg.norm(side)) > 0.001 and not getattr(self, "fix_good", False):
      # where the pocket took the part is where the pocket is: the press and the next part use it
      # (not when the fixture was placed by its outline: what is left is then the part's own offset in the hand)
      self.fix["xy"] = self.fix["xy"] + side
      self.log("pocket found", np.round(1000 * side, 2), "mm from where the camera put it: fixture position corrected")
    ph, _Rh = self.tool_world(False)
    yield from self.line(np.array([ph[0], ph[1], z + 0.04]), R, speed=0.16)

  def out_part(self, k):
    yaw0 = self.fix["yaw"] + math.pi / 2
    c = self.fix["xy"]
    for _try in range(3):
      # high on the part: the fingertips stay above the rim of the pocket's lead-in
      yield from self.pick_part(c, SEAT_Z + NEST_T + PART_H, yaw0, lift=0.04, slow=True, below=0.0015)
      yield from self.wait(0.1)
      if self.finger() > PART_R - 0.0035:
        break
      self.log("part not in the hand after the lift (fingers at", round(self.finger(), 4), "): taking it again")
      self.carry = None
    o = self.outfeed["xy"] + np.array([0.0, 0.022 if k % 2 else -0.022])
    yaw = self.best_yaw(o, 0.0)
    R = R_topdown(yaw)
    z = 0.004 + 0.004 + PART_H - 0.006 + 0.0015
    yield from self.travel(np.array([o[0], o[1], z + 0.002]), R, speed=0.12)
    yield from self.rest_item(R, 0.011)                # the tray floor is 5.5 mm under the part here
    yield from self.let_go(PART_OPEN, 0.4)
    yield from self.wait(0.15)
    yield from self.line(np.array([o[0], o[1], z + 0.06]), R, speed=0.18)

  def first_off(self, k, part):
    yield from self.pick_part(part["xy"], TRAY_TOP + PART_H, self.infeed["yaw"], centre=True)
    yield from self.place_part()
    c = self.fix["xy"]
    z_rest = SEAT_Z + NEST_T + 0.0047 + PART_H
    z_seated = SEAT_Z + NEST_T + PART_H
    if PRESS_OPEN_LOOP:
      yield from self.press_open_loop(c, z_seated)
      yield from self.wait(DWELL_WAIT)
    else:
      _zc, _zl, went = yield from self.press(c, z_rest, PART_DROP, PART_CAP, label_=f"part {k + 1}")
      down = not VERIFY
      for again in range(3):
        if not VERIFY:
          yield from self.wait(DWELL_WAIT)
          break
        t_rel = self.obs["time"]
        _th, _end, top = yield from self.look_station()
        # down: not standing proud on its detent, and either a press felt the detent give or the camera has the
        # top at its pressed height. (A part jammed askew in the lead-in also reads low, 3 mm lower than a pressed
        # one, and no press ever felt it go: that one went to the outfeed tray unpressed before this was asked.)
        if (top is None and went) or (top is not None and top <= PART_H + 0.0022 and (went or top >= PART_H - 0.0015)):
          down = True
          yield from self.wait(max(0.02, DWELL_WAIT - (self.obs["time"] - t_rel)))
          break
        if again < 2:
          self.log("part is not down (camera", None if top is None else round(1000 * top, 1), "mm, press felt a drop:", went, "): pressing again")
          _zc, _zl, w2 = yield from self.press(c, z_rest, PART_DROP, PART_CAP, label_=f"part {k + 1} again")
          went = went or w2
      if not down:
        # only pressed parts go to the outfeed tray (CHANGEOVER_SHEET.md): this one goes back where it came from
        self.log("part would not go down: back to the infeed tray")
        yield from self.pick_part(c, SEAT_Z + NEST_T + PART_H + 0.005, self.fix["yaw"] + math.pi / 2, lift=0.04, slow=True, below=0.0045)
        yaw = self.tray_yaw(part["xy"], self.infeed["yaw"])
        R = R_topdown(yaw)
        z = TRAY_TOP + PART_H - 0.0045 + 0.002
        yield from self.travel(np.array([part["xy"][0], part["xy"][1], z + 0.03]), R, speed=0.14)
        yield from self.line(np.array([part["xy"][0], part["xy"][1], z]), R, speed=0.03)
        yield from self.rest_item(R)
        yield from self.let_go(PART_OPEN, 0.4)
        yield from self.wait(0.15)
        yield from self.line(np.array([part["xy"][0], part["xy"][1], z + 0.05]), R, speed=0.16)
        return False
    yield from self.out_part(k)
    return True

  # -------------------------------------------------------------------------------------- main
  def main(self):
    yield
    yield from self.measure_finger_bias()
    if CALIBRATE:
      yield from self.calibrate()
    yield from self.go_view()
    yield from self.look_cell()
    if STOP_AFTER == "look_end":
      return
    if STOP_AFTER == "hover":                      # dev: hold the hand over where the fixture was seen, then end
      yield from self.travel(np.array([self.fix["xy"][0], self.fix["xy"][1], 0.11]), R_topdown(self.fix["yaw"] + math.pi / 2), speed=0.16)
      yield from self.wait(1.5)
      return
    if STOP_AFTER == "look":
      yield from self.hold_forever()
    # 1. clamp open, nest A to the shelf
    if STOP_AFTER == "grab_only":                  # a watcher: take hold of nest A as it stands and wait
      yield from self.take_nest(self.fix["xy"], self.fix["yaw"] + math.pi / 2, SEAT_Z + NEST_T, slow_lift=0.0)
      yield from self.hold_forever()
    yield from self.open_clamp()
    if STOP_AFTER == "unclamp":
      yield from self.hold_forever()
    if not TOUCH_CHECK:
      zc = None
    else:
      zc, _zl, _d = yield from self.press(self.fix["xy"], SEAT_Z + NEST_T, 9.0, 99.0, probe=True, label_="height check")
    # the top of nest A: its height is known, so this sets the height of everything in the cell
    if zc is not None:
      dz = float(np.clip(zc - (SEAT_Z + NEST_T - TOUCH_OFF), -0.008, 0.008))
      self.zcal = (self.zcal[0] + dz, self.zcal[1])
      self.log("height check: surfaces read", round(1000 * dz, 2), "mm high; corrected")
    fyaw = self.fix["yaw"]
    yield from self.take_nest(self.fix["xy"], fyaw + math.pi / 2, SEAT_Z + NEST_T)
    if STOP_AFTER == "grab":
      yield from self.hold_forever()
    pyaw = self.best_yaw(self.park, self.shelf["yaw"] + math.pi / 2)
    yield from self.put_nest(self.park, pyaw, RAIL_TOP + NEST_T)
    if STOP_AFTER == "park":
      yield from self.travel(np.array([0.24, 0.0, 0.20]), R_topdown(math.pi))
      return
    # 2. nest B onto the pins
    nest = self.nest_c if (PICK_LOOKALIKE and self.nest_c is not None) else self.nest_b
    if nest is None:
      return
    yield from self.seat_nest(nest)
    if STOP_AFTER == "seat":
      return
    ends = [self.f2w((0.0, PIN_Y)), self.f2w((0.0, -PIN_Y))]
    z_rest = SEAT_Z + 0.0032 + NEST_T
    low = [None, None]
    for seat_try in range(3):
      on_pins = True
      for k in (0, 1):
        if PRESS_OPEN_LOOP:
          yield from self.press_open_loop(ends[k], SEAT_Z + NEST_T)
        else:
          zc, low[k], _d = yield from self.press(ends[k], z_rest, END_DROP, END_CAP, label_=f"nest end {k + 1}")
          # an end on its detent is met 3.6 mm under z_rest by this touch, an end already down 3.5 mm lower;
          # an end met well above the first or below the second is on a pin nose or off its pin
          if SERVO_NEST and zc is not None and (zc > z_rest - 0.0004 or zc < z_rest - 0.0086):
            on_pins = False
            break
      if on_pins or seat_try == 2 or PICK_LOOKALIKE:
        break
      self.log("nest end", k + 1, "met at", round(zc, 4), ": the nest is not on the pins; taking it up and seating it again")
      yield from self.seat_nest({"xy": self.fix["xy"], "axis": self.fix["yaw"] + math.pi / 2}, z_top=SEAT_Z + NEST_T + 0.004)
    th_seen = None
    if VERIFY and not PRESS_OPEN_LOOP:
      for _round in range(2):
        th_seen, far, _top = yield from self.look_station()
        want = SEAT_Z + NEST_T - PLATE_T + 0.0015
        up = [k for k, e in ((0, self.end_near), (1, far)) if e is not None and e > want]
        if not up:
          break
        for k in up:
          self.log("nest end", k + 1, "is not down: pressing it again")
          yield from self.press(ends[k], z_rest, END_DROP, END_CAP, label_=f"nest end {k + 1} again")
    # 3. clamp
    if CLAMP:
      # the clamp is not always where it was left open (a nest end can nudge its arm): start from where it is seen
      th, knee = (6.0 if th_seen is None else float(np.clip(th_seen, -3.0, 40.0))), None
      for attempt in range(3):
        _res, kn, stop = yield from self.close_clamp(th, CLAMP_PAST_DEG, knee)
        knee = kn if kn is not None else knee
        if not VERIFY:
          break
        seen, end, _top = yield from self.look_station()
        for again in range(3):
          if end is None or end <= SEAT_Z + NEST_T - PLATE_T + 0.0015:
            break
          # a push that stops at its cap has not put the end down: look again, and push a little harder (the limit
          # on a nest is 10 N; the first cap leaves room for the estimate's error)
          self.log("far nest end is up: pressing it down again")
          yield from self.press(ends[1], z_rest, END_DROP, END_CAP + (1.0 if again else 0.0), label_="nest end 2 again")
          seen, end, _top = yield from self.look_station()
        self.log("clamp: seen", None if seen is None else round(seen, 1), "hand stopped at", None if stop is None else round(stop, 1))
        if seen is None or seen > 40.0:
          break
        self.log("clamp is open again: closing it again")
        th = seen
    # 4. first-off parts
    todo = [p for p in self.parts if p["kind"] == "B"]
    todo.sort(key=lambda p: float(np.linalg.norm(p["xy"])))
    queue, done, tries = list(todo), 0, 0
    while queue and done < N_PARTS and tries < N_PARTS + 2:
      part = queue.pop(0)
      tries += 1
      ok = yield from self.first_off(done, part)
      if ok:
        done += 1
      else:
        queue.append(part)
    # 5. clear
    yield from self.grip_to(0.040, 0.3)
    yield from self.travel(np.array([0.24, 0.0, 0.20]), R_topdown(math.pi))
    yield from self.wait(0.3)

  def hold_forever(self):
    while True:
      yield