visloc-vision 0.5.0

Feature, matching, PnP, RANSAC, and pose-refinement building blocks for visloc-rs.
Documentation
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
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
//! Rectified-stereo VO frontend primitives.
//!
//! These helpers turn left/right [`FeatureSet`]s into metric 3D points in the
//! left camera's frame (via [`triangulate_stereo_features`]) and stitch
//! consecutive triangulations into a relative-pose hypothesis (via
//! [`build_stereo_temporal_correspondences`] + a caller-supplied PnP RANSAC).
//! Compared with monocular VO the recovered pose is in metric units — the
//! baseline anchors scale on every frame, so there is no per-pair scale
//! ambiguity to resolve later.
//!
//! The frontend is split so callers can plug in alternative feature
//! extractors and matchers, keep their own per-frame caches, or skip the PnP
//! step when they only need the triangulations themselves.

use std::collections::HashMap;

use nalgebra::{DMatrix, DVector, Matrix3, Point2, Point3, UnitQuaternion, Vector3};
use rand::rngs::SmallRng;
use rand::seq::SliceRandom;
use rand::SeedableRng;
use visloc_core::geometry::Pose;
use visloc_core::types::Camera;

use crate::features::{
    CornerFeatureConfig, CornerFeatureError, CornerFeatureExtractor, FeatureExtractor, FeatureSet,
    GrayscaleImage,
};
use crate::matching::{BruteForceMatcher, DescriptorMatch, Matcher};
use crate::pnp::Correspondence2D3D;
use crate::ransac::{PnPRansac, RobustPoseEstimator};
use crate::stereo::triangulate_stereo_pixel;

/// One triangulated stereo feature, anchored to its descriptor index in the
/// left [`FeatureSet`].
#[derive(Debug, Clone, PartialEq)]
pub struct StereoFeature {
    /// Index of the keypoint in the left [`FeatureSet`].
    pub left_index: usize,
    /// Index of the keypoint in the right [`FeatureSet`].
    pub right_index: usize,
    /// Disparity `u_l − u_r` (always positive, in pixels).
    pub disparity: f64,
    /// 3D point in the left camera's frame, in metric units derived from
    /// `baseline`.
    pub point_cam: Point3<f64>,
}

/// Runtime policy for the lower stereo-depth gate.
///
/// [`StereoDepthGate::Fixed`] preserves the historical
/// [`StereoFeatureConfig::min_depth_m`] behavior. The adaptive policy keeps
/// that fixed path available for A/B runs while letting production-style
/// frontends choose a per-frame lower bound from the observed stereo-depth
/// distribution.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum StereoDepthGate {
    Fixed,
    Adaptive(StereoAdaptiveDepthGateConfig),
}

impl StereoDepthGate {
    pub const fn fixed() -> Self {
        Self::Fixed
    }

    pub fn adaptive() -> Self {
        Self::Adaptive(StereoAdaptiveDepthGateConfig::default())
    }
}

impl Default for StereoDepthGate {
    fn default() -> Self {
        Self::Adaptive(StereoAdaptiveDepthGateConfig::default())
    }
}

/// Configuration for [`StereoDepthGate::Adaptive`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StereoAdaptiveDepthGateConfig {
    /// Minimum number of geometrically plausible stereo candidates required
    /// before the adaptive policy replaces the fixed lower-depth gate.
    pub min_candidate_count: usize,
    /// Lower quantile of the per-frame depth distribution used as the scene
    /// scale anchor. Values near 0.2 ignore sparse near-field outliers while
    /// still following close-approach scenes.
    pub depth_quantile: f64,
    /// Multiplier applied to `depth_quantile` before bounding. Values below
    /// one keep points slightly nearer than the robust scene-scale anchor.
    pub depth_quantile_scale: f64,
    /// Absolute safety floor for the effective lower-depth gate.
    pub min_depth_floor_m: f64,
    /// Absolute safety ceiling for the effective lower-depth gate. This keeps
    /// automotive/hall-scale scenes close to the historical 3 m behavior.
    pub max_adaptive_min_depth_m: f64,
    /// Assumed 1-sigma disparity noise. Combined with
    /// `max_relative_depth_uncertainty` to reject far-field samples whose
    /// stereo depth is dominated by disparity noise.
    pub disparity_noise_px: f64,
    /// Maximum accepted relative depth uncertainty implied by disparity noise:
    /// `sigma_z / z ~= sigma_disparity / disparity`.
    pub max_relative_depth_uncertainty: f64,
    /// Fractional hysteresis band around the previous effective gate. Proposed
    /// updates inside this band keep the prior gate to prevent frame-to-frame
    /// threshold chatter.
    pub hysteresis_ratio: f64,
}

impl Default for StereoAdaptiveDepthGateConfig {
    fn default() -> Self {
        Self {
            min_candidate_count: 20,
            depth_quantile: 0.20,
            depth_quantile_scale: 0.85,
            min_depth_floor_m: 0.35,
            max_adaptive_min_depth_m: 3.0,
            disparity_noise_px: 0.5,
            max_relative_depth_uncertainty: 0.5,
            hysteresis_ratio: 0.15,
        }
    }
}

/// Stateful memory for adaptive stereo-depth gating.
#[derive(Debug, Clone, Copy, PartialEq, Default)]
pub struct StereoDepthGateState {
    effective_min_depth_m: Option<f64>,
}

impl StereoDepthGateState {
    pub const fn reset(&mut self) {
        self.effective_min_depth_m = None;
    }

    pub const fn effective_min_depth_m(&self) -> Option<f64> {
        self.effective_min_depth_m
    }
}

/// Per-frame diagnostics emitted by the stereo-depth gate.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StereoDepthGateDiagnostics {
    pub adaptive: bool,
    pub candidate_count: usize,
    pub accepted_count: usize,
    pub effective_min_depth_m: f64,
    pub effective_max_depth_m: f64,
    pub depth_quantile_m: Option<f64>,
    pub disparity_uncertainty_min_px: Option<f64>,
}

/// Configuration for [`triangulate_stereo_features`]. Defaults are tuned for
/// rectified KITTI imagery.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct StereoFeatureConfig {
    /// Minimum acceptable disparity (`u_l − u_r`) in pixels. Sub-threshold
    /// matches indicate either a far-field point (numerically unstable) or
    /// a wrong correspondence (e.g., a sky pixel). Set on the same scale
    /// as the descriptor matcher's expected sub-pixel accuracy.
    pub min_disparity_px: f64,
    /// Maximum allowed `|v_l − v_r|` row residual in pixels. A non-zero
    /// row residual on rectified imagery means the match is wrong (or the
    /// rectification is imperfect); reject so triangulation does not blend
    /// in a Y-direction error.
    pub max_row_residual_px: f64,
    /// Fixed-policy minimum `Z` (depth) accepted in the left camera's frame,
    /// and the adaptive-policy fallback before enough candidates establish a
    /// scene scale. Points nearer than this disappear behind / below the
    /// camera within one frame on a moving vehicle; on room-scale datasets the
    /// adaptive gate can lower the effective value without changing this A/B
    /// baseline.
    pub min_depth_m: f64,
    /// Maximum `Z` (depth) accepted in the left camera's frame. KITTI sky
    /// pixels triangulate to `Z ≫ 100 m` because their disparity is at the
    /// matcher's noise floor — those points are useless for downstream
    /// pose estimation and inflate landmark counts.
    pub max_depth_m: f64,
    /// Lower-depth gate policy. Set to [`StereoDepthGate::Fixed`] to reproduce
    /// the historical `min_depth_m` behavior exactly.
    pub depth_gate: StereoDepthGate,
    /// Lowe's ratio threshold for the row-restricted L↔R descriptor search.
    /// `Some(0.85)` keeps matches whose best-distance / second-best-distance
    /// in the same row band is strictly below the threshold. `None`
    /// disables the ratio check (every left keypoint with a band candidate
    /// is matched).
    pub ratio: Option<f64>,
}

impl Default for StereoFeatureConfig {
    fn default() -> Self {
        Self {
            min_disparity_px: 1.0,
            max_row_residual_px: 1.5,
            min_depth_m: 3.0,
            max_depth_m: 80.0,
            depth_gate: StereoDepthGate::default(),
            ratio: Some(0.85),
        }
    }
}

/// Match the left and right [`FeatureSet`]s using the rectified-stereo
/// epipolar constraint and triangulate every accepted correspondence into a
/// metric 3D point. Returns one [`StereoFeature`] per match that passes the
/// [`StereoFeatureConfig`] gates.
///
/// Unlike a plain descriptor matcher, this routine restricts each left
/// keypoint's right-image search to the same row band (`|v_l − v_r| ≤
/// max_row_residual_px`) and to positive disparity (`u_r < u_l`). Without
/// the row gate, patch descriptors on KITTI-like imagery routinely match
/// across rows and produce 3D points consistent with the left view but
/// wildly wrong in 3D space — those points then poison the downstream PnP.
/// The gated matcher also runs Lowe's ratio test on the within-band best /
/// second-best descriptor distance.
///
/// The returned points live in the left-camera frame (positive `Z` ahead of
/// the camera). `baseline` is the rectified-stereo baseline magnitude in
/// metric units (same units the points come out in).
pub fn triangulate_stereo_features(
    left: &FeatureSet,
    right: &FeatureSet,
    camera: &Camera,
    baseline: f64,
    config: &StereoFeatureConfig,
) -> Vec<StereoFeature> {
    triangulate_stereo_features_with_depth_state(left, right, camera, baseline, config, None)
        .features
}

fn triangulate_stereo_features_with_depth_state(
    left: &FeatureSet,
    right: &FeatureSet,
    camera: &Camera,
    baseline: f64,
    config: &StereoFeatureConfig,
    state: Option<&mut StereoDepthGateState>,
) -> StereoDepthGateOutcome {
    if left.is_empty() || right.is_empty() {
        return empty_stereo_depth_gate_outcome(config);
    }
    let mut candidates: Vec<StereoFeature> = Vec::with_capacity(left.len() / 2);
    for (l_idx, l_kp) in left.keypoints.iter().enumerate() {
        let l_desc = &left.descriptors[l_idx];
        // Row-restricted descriptor search: only consider right keypoints
        // sharing the left's image row (within max_row_residual_px) and
        // with positive disparity (u_r < u_l).
        let mut best: Option<(usize, f64)> = None;
        let mut second_best: Option<f64> = None;
        for (r_idx, r_kp) in right.keypoints.iter().enumerate() {
            if (l_kp.y - r_kp.y).abs() > config.max_row_residual_px {
                continue;
            }
            let disparity = l_kp.x - r_kp.x;
            if disparity < config.min_disparity_px {
                continue;
            }
            let r_desc = &right.descriptors[r_idx];
            let dist = descriptor_distance(l_desc, r_desc);
            match best {
                None => best = Some((r_idx, dist)),
                Some((_, b_dist)) if dist < b_dist => {
                    second_best = Some(b_dist);
                    best = Some((r_idx, dist));
                }
                Some(_) => {
                    if second_best.is_none_or(|s| dist < s) {
                        second_best = Some(dist);
                    }
                }
            }
        }
        let Some((r_idx, b_dist)) = best else {
            continue;
        };
        // Lowe's ratio test (rectified-stereo variant: only if a runner-up
        // exists in the same band).
        if let (Some(s), Some(ratio)) = (second_best, config.ratio) {
            if s > 0.0 && b_dist / s > ratio {
                continue;
            }
        } else {
            // Suppress unused-variable warning when ratio is disabled.
            let _ = b_dist;
        }
        let r_kp = right.keypoints[r_idx];
        let disparity = l_kp.x - r_kp.x;
        let Some(point) = triangulate_stereo_pixel(
            camera,
            baseline,
            (l_kp.x, l_kp.y),
            (r_kp.x, r_kp.y),
            config.min_disparity_px,
        ) else {
            continue;
        };
        if !point.coords.iter().all(|v| v.is_finite()) {
            continue;
        }
        candidates.push(StereoFeature {
            left_index: l_idx,
            right_index: r_idx,
            disparity,
            point_cam: point,
        });
    }
    apply_stereo_depth_gate(candidates, config, state)
}

/// Triangulate explicit rectified-stereo matches into metric 3D points.
///
/// This is the file-backed / learned-frontend companion to
/// [`triangulate_stereo_features`]. It trusts the caller's matcher
/// (SuperPoint+LightGlue, ONNX, a remote service, etc.) for candidate
/// association, then applies the same stereo geometry gates: positive
/// disparity, row residual, finite 3D point, and depth range.
pub fn triangulate_stereo_feature_matches(
    left: &FeatureSet,
    right: &FeatureSet,
    matches: &[DescriptorMatch],
    camera: &Camera,
    baseline: f64,
    config: &StereoFeatureConfig,
) -> Vec<StereoFeature> {
    triangulate_stereo_feature_matches_with_depth_state(
        left, right, matches, camera, baseline, config, None,
    )
    .features
}

fn triangulate_stereo_feature_matches_with_depth_state(
    left: &FeatureSet,
    right: &FeatureSet,
    matches: &[DescriptorMatch],
    camera: &Camera,
    baseline: f64,
    config: &StereoFeatureConfig,
    state: Option<&mut StereoDepthGateState>,
) -> StereoDepthGateOutcome {
    if left.is_empty() || right.is_empty() || matches.is_empty() {
        return empty_stereo_depth_gate_outcome(config);
    }

    let mut candidates = Vec::with_capacity(matches.len());
    for descriptor_match in matches {
        let Some(l_kp) = left.keypoints.get(descriptor_match.query_index) else {
            continue;
        };
        let Some(r_kp) = right.keypoints.get(descriptor_match.train_index) else {
            continue;
        };
        if (l_kp.y - r_kp.y).abs() > config.max_row_residual_px {
            continue;
        }
        let disparity = l_kp.x - r_kp.x;
        if disparity < config.min_disparity_px {
            continue;
        }
        let Some(point) = triangulate_stereo_pixel(
            camera,
            baseline,
            (l_kp.x, l_kp.y),
            (r_kp.x, r_kp.y),
            config.min_disparity_px,
        ) else {
            continue;
        };
        if !point.coords.iter().all(|v| v.is_finite()) {
            continue;
        }
        candidates.push(StereoFeature {
            left_index: descriptor_match.query_index,
            right_index: descriptor_match.train_index,
            disparity,
            point_cam: point,
        });
    }
    apply_stereo_depth_gate(candidates, config, state)
}

struct StereoDepthGateOutcome {
    features: Vec<StereoFeature>,
    diagnostics: StereoDepthGateDiagnostics,
}

const fn empty_stereo_depth_gate_outcome(config: &StereoFeatureConfig) -> StereoDepthGateOutcome {
    StereoDepthGateOutcome {
        features: Vec::new(),
        diagnostics: StereoDepthGateDiagnostics {
            adaptive: false,
            candidate_count: 0,
            accepted_count: 0,
            effective_min_depth_m: config.min_depth_m,
            effective_max_depth_m: config.max_depth_m,
            depth_quantile_m: None,
            disparity_uncertainty_min_px: None,
        },
    }
}

fn apply_stereo_depth_gate(
    candidates: Vec<StereoFeature>,
    config: &StereoFeatureConfig,
    state: Option<&mut StereoDepthGateState>,
) -> StereoDepthGateOutcome {
    match config.depth_gate {
        StereoDepthGate::Fixed => apply_fixed_stereo_depth_gate(candidates, config),
        StereoDepthGate::Adaptive(adaptive) => {
            apply_adaptive_stereo_depth_gate(candidates, config, adaptive, state)
        }
    }
}

fn apply_fixed_stereo_depth_gate(
    candidates: Vec<StereoFeature>,
    config: &StereoFeatureConfig,
) -> StereoDepthGateOutcome {
    let candidate_count = candidates.len();
    let features: Vec<_> = candidates
        .into_iter()
        .filter(|feature| {
            feature.point_cam.z >= config.min_depth_m && feature.point_cam.z <= config.max_depth_m
        })
        .collect();
    let accepted_count = features.len();
    StereoDepthGateOutcome {
        features,
        diagnostics: StereoDepthGateDiagnostics {
            adaptive: false,
            candidate_count,
            accepted_count,
            effective_min_depth_m: config.min_depth_m,
            effective_max_depth_m: config.max_depth_m,
            depth_quantile_m: None,
            disparity_uncertainty_min_px: None,
        },
    }
}

fn apply_adaptive_stereo_depth_gate(
    candidates: Vec<StereoFeature>,
    config: &StereoFeatureConfig,
    adaptive: StereoAdaptiveDepthGateConfig,
    state: Option<&mut StereoDepthGateState>,
) -> StereoDepthGateOutcome {
    let candidate_count = candidates.len();
    let uncertainty_min_disparity_px = adaptive_uncertainty_min_disparity_px(config, &adaptive);
    let bounded_depths: Vec<f64> = candidates
        .iter()
        .filter(|feature| {
            stereo_candidate_passes_safety_gates(feature, config, uncertainty_min_disparity_px)
        })
        .map(|feature| feature.point_cam.z)
        .collect();
    let depth_quantile_m = if bounded_depths.len() >= adaptive.min_candidate_count {
        robust_quantile(&bounded_depths, adaptive.depth_quantile)
    } else {
        None
    };
    let previous_effective_min_depth_m = state
        .as_ref()
        .and_then(|state| state.effective_min_depth_m());
    let raw_effective_min_depth_m = depth_quantile_m
        .map(|depth| {
            let max_effective_min_depth_m = adaptive
                .max_adaptive_min_depth_m
                .min(config.max_depth_m)
                .max(adaptive.min_depth_floor_m);
            (depth * adaptive.depth_quantile_scale)
                .clamp(adaptive.min_depth_floor_m, max_effective_min_depth_m)
        })
        .or(previous_effective_min_depth_m)
        .unwrap_or(config.min_depth_m);
    let effective_min_depth_m = apply_depth_hysteresis(raw_effective_min_depth_m, adaptive, state);

    let features: Vec<_> = candidates
        .into_iter()
        .filter(|feature| {
            stereo_candidate_passes_safety_gates(feature, config, uncertainty_min_disparity_px)
                && feature.point_cam.z >= effective_min_depth_m
        })
        .collect();
    let accepted_count = features.len();
    StereoDepthGateOutcome {
        features,
        diagnostics: StereoDepthGateDiagnostics {
            adaptive: depth_quantile_m.is_some(),
            candidate_count,
            accepted_count,
            effective_min_depth_m,
            effective_max_depth_m: config.max_depth_m,
            depth_quantile_m,
            disparity_uncertainty_min_px: Some(uncertainty_min_disparity_px),
        },
    }
}

fn adaptive_uncertainty_min_disparity_px(
    config: &StereoFeatureConfig,
    adaptive: &StereoAdaptiveDepthGateConfig,
) -> f64 {
    let uncertainty_floor = if adaptive.disparity_noise_px.is_finite()
        && adaptive.disparity_noise_px > 0.0
        && adaptive.max_relative_depth_uncertainty.is_finite()
        && adaptive.max_relative_depth_uncertainty > 0.0
    {
        adaptive.disparity_noise_px / adaptive.max_relative_depth_uncertainty
    } else {
        config.min_disparity_px
    };
    config.min_disparity_px.max(uncertainty_floor)
}

fn stereo_candidate_passes_safety_gates(
    feature: &StereoFeature,
    config: &StereoFeatureConfig,
    uncertainty_min_disparity_px: f64,
) -> bool {
    feature.point_cam.z.is_finite()
        && feature.point_cam.z > 0.0
        && feature.point_cam.z <= config.max_depth_m
        && feature.disparity >= uncertainty_min_disparity_px
}

fn robust_quantile(values: &[f64], quantile: f64) -> Option<f64> {
    let mut sorted: Vec<f64> = values.iter().copied().filter(|v| v.is_finite()).collect();
    if sorted.is_empty() {
        return None;
    }
    sorted.sort_by(|a, b| a.total_cmp(b));
    let q = quantile.clamp(0.0, 1.0);
    let rank = ((sorted.len() - 1) as f64 * q).round() as usize;
    sorted.get(rank).copied()
}

fn apply_depth_hysteresis(
    proposed_min_depth_m: f64,
    adaptive: StereoAdaptiveDepthGateConfig,
    state: Option<&mut StereoDepthGateState>,
) -> f64 {
    let Some(state) = state else {
        return proposed_min_depth_m;
    };
    let Some(previous) = state.effective_min_depth_m else {
        state.effective_min_depth_m = Some(proposed_min_depth_m);
        return proposed_min_depth_m;
    };
    let ratio = adaptive.hysteresis_ratio.clamp(0.0, 0.95);
    let lower = previous * (1.0 - ratio);
    let upper = previous * (1.0 + ratio);
    let effective = if proposed_min_depth_m >= lower && proposed_min_depth_m <= upper {
        previous
    } else {
        proposed_min_depth_m
    };
    state.effective_min_depth_m = Some(effective);
    effective
}

/// One pair of metric 3D points (frame `a` and frame `b`) believed to be the
/// same physical scene point. Used by [`estimate_relative_pose_kabsch_ransac`].
#[derive(Debug, Clone, PartialEq)]
pub struct StereoPairCorrespondence {
    pub a: Point3<f64>,
    pub b: Point3<f64>,
    /// Optional temporal-match confidence. Deep matchers such as
    /// `MutualSoftmaxMatcher` populate this so Kabsch RANSAC can sample
    /// high-confidence 3D-3D pairs first; classical matchers leave it `None`.
    pub confidence: Option<f32>,
}

/// Configuration for [`estimate_relative_pose_kabsch_ransac`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct KabschRansacConfig {
    pub iterations: usize,
    /// Maximum allowed `|X_b − (R·X_a + t)|` per inlier (in metric units).
    pub inlier_threshold_m: f64,
    /// Minimum number of inliers for a pose to be accepted. Below this, the
    /// estimator returns `None`.
    pub min_inliers: usize,
    /// Discard correspondences with `Z` (in either frame) above this. Stereo
    /// noise scales as `Z² · σ_disp / (fx · b)`, so far-field samples are
    /// unreliable for the metric pose recovery.
    pub max_depth_m: f64,
    pub seed: u64,
}

impl Default for KabschRansacConfig {
    fn default() -> Self {
        Self {
            iterations: 256,
            inlier_threshold_m: 0.30,
            min_inliers: 12,
            max_depth_m: 25.0,
            seed: 7,
        }
    }
}

/// Output of [`estimate_relative_pose_kabsch_ransac`].
#[derive(Debug, Clone, PartialEq)]
pub struct KabschRansacReport {
    /// `T_a_to_b`: applies as `X_b = relative · X_a` for any matched scene
    /// point, with `world_to_camera.translation` carrying metric scale.
    pub relative_pose: Pose,
    /// Indices into the original `correspondences` slice that fit the
    /// recovered pose within [`KabschRansacConfig::inlier_threshold_m`].
    pub inliers: Vec<usize>,
    pub mean_residual_m: f64,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StereoRelativePoseSource {
    Pnp,
    PnpFallback,
    Kabsch,
    KabschFallback,
}

#[derive(Debug, Clone, PartialEq)]
pub struct StereoVoPairDiagnostics {
    pub from_frame: usize,
    pub to_frame: usize,
    pub source: StereoRelativePoseSource,
    pub temporal_match_count: usize,
    pub temporal_row_gate_px: Option<f64>,
    pub temporal_confidence_gate: Option<f32>,
    pub pnp_correspondence_count: usize,
    pub stereo_pair_correspondence_count: usize,
    pub inlier_count: usize,
    pub raw_translation_m: f64,
    pub raw_rotation_deg: f64,
    pub translation_m: f64,
    pub rotation_deg: f64,
    pub motion_scale_rescued: bool,
    pub stereo_vertical_aligned: bool,
    pub translation_direction_rescued: bool,
    pub rotation_spike_rescued: bool,
    pub rotation_vector_rescued: bool,
    pub pnp_mean_reprojection_error_px: Option<f64>,
    pub kabsch_mean_residual_m: Option<f64>,
}

/// 3D-3D Kabsch (Procrustes) registration with RANSAC.
///
/// Robust to the forward-motion degeneracy that breaks essential-matrix VO
/// on driving sequences. Each correspondence supplies the same physical
/// point's metric coordinates in two frames; the metric translation
/// magnitude is recovered directly from the data with no scale ambiguity.
///
/// Three correspondences are the minimum sample (one solves a 3D-3D
/// alignment up to a one-DoF reflection that the cheirality picker
/// resolves). 256 iterations find a clean inlier set even when the input
/// has 50 % outliers.
pub fn estimate_relative_pose_kabsch_ransac(
    correspondences: &[StereoPairCorrespondence],
    config: &KabschRansacConfig,
) -> Option<KabschRansacReport> {
    // Pre-filter to within-depth correspondences (stereo accuracy
    // degrades as Z²).
    let usable: Vec<usize> = (0..correspondences.len())
        .filter(|&i| {
            let c = &correspondences[i];
            c.a.z > 0.0 && c.b.z > 0.0 && c.a.z <= config.max_depth_m && c.b.z <= config.max_depth_m
        })
        .collect();
    if usable.len() < 3.max(config.min_inliers) {
        return None;
    }
    let mut rng = SmallRng::seed_from_u64(config.seed);
    let has_confidence = usable.iter().any(|&i| {
        correspondences[i]
            .confidence
            .is_some_and(|w| w.is_finite() && w > 0.0)
    });
    let mut ranked = usable.clone();
    if has_confidence {
        ranked.sort_by(|&left, &right| {
            let l = correspondences[left].confidence.unwrap_or(0.0);
            let r = correspondences[right].confidence.unwrap_or(0.0);
            r.total_cmp(&l)
        });
    }
    let mut indices = usable;
    let mut best: Option<(Pose, Vec<usize>, f64)> = None;
    let threshold_sq = config.inlier_threshold_m * config.inlier_threshold_m;
    for iter in 0..config.iterations {
        let sample_indices: Vec<usize> = if has_confidence {
            let span = ranked.len().saturating_sub(3);
            let subset_len = 3 + (span * (iter + 1) / config.iterations.max(1));
            ranked[..subset_len]
                .choose_multiple(&mut rng, 3)
                .copied()
                .collect()
        } else {
            indices.shuffle(&mut rng);
            indices.iter().take(3).copied().collect()
        };
        let sample: Vec<&StereoPairCorrespondence> = sample_indices
            .iter()
            .map(|&i| &correspondences[i])
            .collect();
        let Some(pose) = kabsch_3pt(&sample) else {
            continue;
        };
        let (inliers, sse) = score_pose_3d3d(&pose, correspondences, threshold_sq);
        let better = best.as_ref().is_none_or(|(_, b_inliers, b_sse)| {
            inliers.len() > b_inliers.len() || (inliers.len() == b_inliers.len() && sse < *b_sse)
        });
        if better {
            best = Some((pose, inliers, sse));
        }
    }
    let (_, best_inliers, _) = best?;
    if best_inliers.len() < config.min_inliers {
        return None;
    }
    // Refine on the full inlier set (Kabsch on N≥3 is the closed-form
    // least-squares solution, no iteration needed).
    let inlier_corrs: Vec<&StereoPairCorrespondence> =
        best_inliers.iter().map(|&i| &correspondences[i]).collect();
    let refined = kabsch_n(&inlier_corrs)?;
    let (final_inliers, sse) = score_pose_3d3d(&refined, correspondences, threshold_sq);
    let mean_residual_m = if final_inliers.is_empty() {
        f64::INFINITY
    } else {
        (sse / final_inliers.len() as f64).sqrt()
    };
    Some(KabschRansacReport {
        relative_pose: refined,
        inliers: final_inliers,
        mean_residual_m,
    })
}

fn kabsch_3pt(samples: &[&StereoPairCorrespondence]) -> Option<Pose> {
    if samples.len() < 3 {
        return None;
    }
    kabsch_n(samples)
}

/// Closed-form Kabsch / Procrustes least-squares pose from N matched 3D
/// pairs. Returns `T_a_to_b` such that `X_b ≈ R·X_a + t`.
fn kabsch_n(samples: &[&StereoPairCorrespondence]) -> Option<Pose> {
    let n = samples.len();
    if n < 3 {
        return None;
    }
    let mut centroid_a = Vector3::<f64>::zeros();
    let mut centroid_b = Vector3::<f64>::zeros();
    for c in samples {
        centroid_a += c.a.coords;
        centroid_b += c.b.coords;
    }
    centroid_a /= n as f64;
    centroid_b /= n as f64;
    let mut h = Matrix3::<f64>::zeros();
    for c in samples {
        let a = c.a.coords - centroid_a;
        let b = c.b.coords - centroid_b;
        h += a * b.transpose();
    }
    let svd = h.try_svd(true, true, f64::EPSILON * 5.0, 10_000)?;
    let u = svd.u?;
    let v_t = svd.v_t?;
    let v = v_t.transpose();
    let mut s = Matrix3::<f64>::identity();
    let det = (v * u.transpose()).determinant();
    if det < 0.0 {
        s[(2, 2)] = -1.0;
    }
    let r_mat = v * s * u.transpose();
    let translation = centroid_b - r_mat * centroid_a;
    let rotation = rotation_from_orthonormal(&r_mat);
    Some(Pose::from_world_to_camera(rotation, translation))
}

/// `UnitQuaternion::from_matrix(r_mat)` without its hang on a half-turn
/// RANSAC hypothesis; see [`visloc_core::geometry::rotation_from_matrix`].
fn rotation_from_orthonormal(r_mat: &Matrix3<f64>) -> UnitQuaternion<f64> {
    visloc_core::geometry::rotation_from_matrix(r_mat)
}

fn score_pose_3d3d(
    pose: &Pose,
    correspondences: &[StereoPairCorrespondence],
    threshold_sq: f64,
) -> (Vec<usize>, f64) {
    let r_mat = pose
        .world_to_camera
        .rotation
        .to_rotation_matrix()
        .into_inner();
    let t = pose.world_to_camera.translation;
    let mut inliers = Vec::new();
    let mut sse = 0.0;
    for (i, c) in correspondences.iter().enumerate() {
        let predicted = r_mat * c.a.coords + t;
        let residual = c.b.coords - predicted;
        let err_sq = residual.dot(&residual);
        if err_sq <= threshold_sq {
            inliers.push(i);
            sse += err_sq;
        }
    }
    (inliers, sse)
}

/// Build [`StereoPairCorrespondence`]s by joining the per-frame
/// triangulations on temporal descriptor matches: each match links a left
/// keypoint at frame `a` to a left keypoint at frame `b`; if both have a
/// stereo triangulation the pair contributes one 3D-3D correspondence.
pub fn stereo_pair_correspondences(
    a_features: &[StereoFeature],
    b_features: &[StereoFeature],
    temporal_matches: &[DescriptorMatch],
) -> Vec<StereoPairCorrespondence> {
    if a_features.is_empty() || b_features.is_empty() || temporal_matches.is_empty() {
        return Vec::new();
    }
    let a_lookup: HashMap<usize, &StereoFeature> =
        a_features.iter().map(|f| (f.left_index, f)).collect();
    let b_lookup: HashMap<usize, &StereoFeature> =
        b_features.iter().map(|f| (f.left_index, f)).collect();
    let mut out: Vec<StereoPairCorrespondence> = Vec::with_capacity(temporal_matches.len());
    for m in temporal_matches {
        let (Some(sa), Some(sb)) = (a_lookup.get(&m.query_index), b_lookup.get(&m.train_index))
        else {
            continue;
        };
        out.push(StereoPairCorrespondence {
            a: sa.point_cam,
            b: sb.point_cam,
            confidence: m.confidence,
        });
    }
    out
}

/// One observation contributed by a multi-frame [`StereoTrack`].
#[derive(Debug, Clone, PartialEq)]
pub struct StereoTrackObservation {
    pub frame_index: usize,
    pub left_index: usize,
    pub right_index: usize,
}

/// One multi-frame stereo track: a single landmark's world-frame position
/// (anchored from the seed frame's stereo triangulation, lifted into world
/// using the seed frame's pose) plus its observations across one or more
/// frames. Produced by [`extend_stereo_tracks_via_projection`].
#[derive(Debug, Clone, PartialEq)]
pub struct StereoTrack {
    pub landmark_world: Point3<f64>,
    pub observations: Vec<StereoTrackObservation>,
}

/// Configuration for [`extend_stereo_tracks_via_projection`]. Defaults are
/// tuned for KITTI-scale per-frame motion (~1 m/frame at stride 1, ~7 m/frame
/// at stride 8) and the project's `CornerFeatureExtractor` descriptor scale.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TrackExtensionConfig {
    /// Maximum image-pixel distance from the projected landmark within
    /// which to look for a matching keypoint at the next frame. Has to be
    /// generous enough to cover VO pose noise + reprojection error from
    /// per-frame stereo-triangulation inaccuracy, but small enough to keep
    /// the descriptor search discriminative — `25 px` works on KITTI 00.
    pub search_radius_px: f64,
    /// Lowe's ratio test on the within-radius descriptor search. The best
    /// match's descriptor distance must be below this fraction of the
    /// second best's, otherwise the track ends.
    pub ratio: f64,
    /// Tracks may extend by this many frames past their seed before being
    /// force-cut. Without a cap, tracks that follow distant landmarks can
    /// span ~all frames at the cost of a quadratic match. `30` is a
    /// reasonable upper bound for stride-1 KITTI windows.
    pub max_extension: usize,
    /// Each `(frame, left_kp_index)` is consumed by at most one track —
    /// once a feature has been added to a longer track its later
    /// re-seeding as a new track is suppressed. Set `false` to allow
    /// overlapping tracks (rarely useful).
    pub deduplicate: bool,
}

impl Default for TrackExtensionConfig {
    fn default() -> Self {
        Self {
            search_radius_px: 25.0,
            ratio: 0.8,
            max_extension: 30,
            deduplicate: true,
        }
    }
}

/// Build multi-frame stereo tracks by projecting each frame's stereo
/// triangulations forward through subsequent VO poses and searching for
/// descriptor-matching stereo features near the predicted pixel.
///
/// Why projection-guided rather than chained brute-force matching: KITTI's
/// per-frame motion takes individual features out of the camera's FOV
/// quickly (≤ 4 frames at stride 8), and the brute-force matcher between
/// `left_i ↔ left_(i+1)` does not transitively reuse the same `left_(i+1)`
/// keypoint across `(i → i+1)` and `(i+1 → i+2)`. Projecting the landmark
/// through the next pose narrows the search to a small image patch and
/// allows the same physical point to be re-identified across many frames,
/// which is what gives the bundle adjuster the long-baseline constraints
/// needed to attack rotation drift.
pub fn extend_stereo_tracks_via_projection(
    poses: &[Pose],
    left_features: &[FeatureSet],
    stereo_per_frame: &[Vec<StereoFeature>],
    camera: &Camera,
    config: &TrackExtensionConfig,
) -> Vec<StereoTrack> {
    let n = poses.len();
    if n < 2 || left_features.len() < n || stereo_per_frame.len() < n {
        return Vec::new();
    }
    // Per-frame: index every stereo triangulation by its left keypoint id
    // so projection-based extension can ask "is there a stereo feature at
    // keypoint k of frame j?" in O(1).
    let stereo_lookup: Vec<HashMap<usize, &StereoFeature>> = stereo_per_frame
        .iter()
        .map(|sf| sf.iter().map(|f| (f.left_index, f)).collect())
        .collect();
    let mut consumed: Vec<std::collections::HashSet<usize>> =
        (0..n).map(|_| std::collections::HashSet::new()).collect();
    let mut out: Vec<StereoTrack> = Vec::new();

    for seed_frame in 0..n - 1 {
        let pose_seed = &poses[seed_frame];
        let r_inv = pose_seed.world_to_camera.rotation.inverse();
        let t_seed = pose_seed.world_to_camera.translation;
        for stereo in &stereo_per_frame[seed_frame] {
            if config.deduplicate && consumed[seed_frame].contains(&stereo.left_index) {
                continue;
            }
            let landmark_w =
                nalgebra::Point3::from(r_inv.transform_vector(&(stereo.point_cam.coords - t_seed)));
            let descriptor = left_features[seed_frame].descriptors[stereo.left_index].clone();
            let mut observations: Vec<StereoTrackObservation> = vec![StereoTrackObservation {
                frame_index: seed_frame,
                left_index: stereo.left_index,
                right_index: stereo.right_index,
            }];
            let extension_cap = (seed_frame + config.max_extension).min(n - 1);
            for next_frame in seed_frame + 1..=extension_cap {
                let pose_next = &poses[next_frame];
                let xc = pose_next.transform_world_point(&landmark_w);
                if xc.z <= 0.0 {
                    break;
                }
                let Some(predicted) = camera.project(&xc) else {
                    break;
                };
                if predicted.x < 0.0
                    || predicted.x >= camera.width as f64
                    || predicted.y < 0.0
                    || predicted.y >= camera.height as f64
                {
                    break;
                }
                // Within-radius descriptor search constrained to keypoints
                // that have a stereo triangulation (otherwise the
                // landmark's BA observation is incomplete and the track
                // cannot contribute a stereo residual).
                let mut best: Option<(usize, f64)> = None;
                let mut second_best: Option<f64> = None;
                let radius_sq = config.search_radius_px * config.search_radius_px;
                for (kp_idx, kp) in left_features[next_frame].keypoints.iter().enumerate() {
                    let dx = kp.x - predicted.x;
                    let dy = kp.y - predicted.y;
                    if dx * dx + dy * dy > radius_sq {
                        continue;
                    }
                    if !stereo_lookup[next_frame].contains_key(&kp_idx) {
                        continue;
                    }
                    if config.deduplicate && consumed[next_frame].contains(&kp_idx) {
                        continue;
                    }
                    let dist = descriptor_distance(
                        &descriptor,
                        &left_features[next_frame].descriptors[kp_idx],
                    );
                    match best {
                        None => best = Some((kp_idx, dist)),
                        Some((_, b_dist)) if dist < b_dist => {
                            second_best = Some(b_dist);
                            best = Some((kp_idx, dist));
                        }
                        Some(_) => {
                            if second_best.is_none_or(|s| dist < s) {
                                second_best = Some(dist);
                            }
                        }
                    }
                }
                let Some((kp_idx, b_dist)) = best else {
                    break;
                };
                if let Some(s) = second_best {
                    if s > 0.0 && b_dist / s > config.ratio {
                        break;
                    }
                }
                let stereo_next = stereo_lookup[next_frame][&kp_idx];
                observations.push(StereoTrackObservation {
                    frame_index: next_frame,
                    left_index: kp_idx,
                    right_index: stereo_next.right_index,
                });
            }
            if observations.len() >= 2 {
                if config.deduplicate {
                    for obs in &observations {
                        consumed[obs.frame_index].insert(obs.left_index);
                    }
                }
                out.push(StereoTrack {
                    landmark_world: landmark_w,
                    observations,
                });
            }
        }
    }
    out
}

fn descriptor_distance(a: &[f32], b: &[f32]) -> f64 {
    let mut sum = 0.0;
    let len = a.len().min(b.len());
    for i in 0..len {
        let d = (a[i] - b[i]) as f64;
        sum += d * d;
    }
    sum
}

/// Build 2D-3D correspondences for PnP between two consecutive frames, using
/// frame-`a`'s stereo triangulations and frame-`b`'s left features.
///
/// `temporal_matches` is the descriptor matcher's output of `left_a → left_b`.
/// Only matches whose query keypoint also has a triangulated stereo feature
/// in `a_features` are kept; the resulting [`Correspondence2D3D`] pairs the
/// 3D point (in `a`'s left-camera frame) with the 2D pixel in `b`'s left
/// image.
///
/// The PnP solver then recovers `T_a_to_b` directly: feed the result into
/// `PnPRansac::estimate` with `b_left`'s keypoints as the 2D side.
pub fn build_stereo_temporal_correspondences(
    a_features: &[StereoFeature],
    b_left: &FeatureSet,
    temporal_matches: &[crate::matching::DescriptorMatch],
) -> Vec<Correspondence2D3D> {
    if a_features.is_empty() || b_left.is_empty() || temporal_matches.is_empty() {
        return Vec::new();
    }
    // Index a_features by their left-keypoint index for O(1) lookup.
    let mut a_by_left_idx: HashMap<usize, &StereoFeature> =
        HashMap::with_capacity(a_features.len());
    for f in a_features {
        a_by_left_idx.insert(f.left_index, f);
    }
    let mut out: Vec<Correspondence2D3D> = Vec::with_capacity(temporal_matches.len());
    for m in temporal_matches {
        let Some(stereo) = a_by_left_idx.get(&m.query_index) else {
            continue;
        };
        let b_kp = b_left.keypoints[m.train_index];
        out.push(Correspondence2D3D {
            point2d: b_kp,
            point3d: stereo.point_cam,
            confidence: m.confidence,
        });
    }
    out
}

#[derive(Debug, Clone, PartialEq)]
struct PnpSelectedReport {
    pose: Pose,
    inlier_count: usize,
    mean_reprojection_error: f64,
    correspondence_count: usize,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct PnpFullScore {
    inlier_count: usize,
    mean_error: f64,
}

#[derive(Debug, Clone, Copy, PartialEq)]
struct Pose3d3dScore {
    inlier_count: usize,
    mean_residual_m: f64,
}

// Each parameter is an independent PnP/depth-hypothesis knob; positional args
// stay closer to the math than an ad-hoc bundling struct would.
#[allow(clippy::too_many_arguments)]
fn estimate_pnp_with_depth_hypotheses(
    pnp: &PnPRansac,
    all_corrs: &[Correspondence2D3D],
    camera: &Camera,
    min_inliers: usize,
    primary_max_depth_m: Option<f64>,
    depth_hypotheses_m: &[f64],
    adaptive_depth_hypothesis_m: Option<f64>,
    adaptive_depth_min_primary_inlier_ratio: f64,
) -> Option<PnpSelectedReport> {
    let primary_depth = primary_max_depth_m.filter(|d| d.is_finite() && *d > 0.0);
    let mut best: Option<PnpSelectedReport> = None;
    let mut best_score: Option<PnpFullScore> = None;

    update_best_pnp_depth_candidate(
        pnp,
        all_corrs,
        camera,
        min_inliers,
        primary_depth,
        &mut best,
        &mut best_score,
    );

    let mut candidate_depths = pnp_candidate_depths(primary_max_depth_m, depth_hypotheses_m);
    if depth_hypotheses_m.is_empty()
        && should_try_adaptive_pnp_depth(
            best_score.as_ref(),
            all_corrs.len(),
            adaptive_depth_min_primary_inlier_ratio,
        )
    {
        if let Some(adaptive_depth_m) =
            adaptive_depth_hypothesis_m.filter(|d| d.is_finite() && *d > 0.0)
        {
            let candidate = Some(adaptive_depth_m);
            if !candidate_depths
                .iter()
                .any(|existing| same_optional_depth(*existing, candidate))
            {
                candidate_depths.push(candidate);
            }
        }
    }

    for max_depth_m in candidate_depths {
        if same_optional_depth(max_depth_m, primary_depth) {
            continue;
        }
        update_best_pnp_depth_candidate(
            pnp,
            all_corrs,
            camera,
            min_inliers,
            max_depth_m,
            &mut best,
            &mut best_score,
        );
    }
    best
}

fn update_best_pnp_depth_candidate(
    pnp: &PnPRansac,
    all_corrs: &[Correspondence2D3D],
    camera: &Camera,
    min_inliers: usize,
    max_depth_m: Option<f64>,
    best: &mut Option<PnpSelectedReport>,
    best_score: &mut Option<PnpFullScore>,
) {
    let corrs = pnp_correspondences_for_depth(all_corrs, max_depth_m);
    let weights: Vec<f32> = corrs.iter().map(|c| c.confidence.unwrap_or(0.0)).collect();
    let Some(report) = estimate_pnp_candidate(pnp, &corrs, camera, &weights) else {
        return;
    };
    if report.inliers.len() < min_inliers {
        return;
    }
    let full_score = score_pnp_pose_on_correspondences(
        &report.pose,
        all_corrs,
        camera,
        pnp.reprojection_threshold,
    );
    if full_score.inlier_count < min_inliers {
        return;
    }
    let better = best_score
        .as_ref()
        .is_none_or(|score| is_pnp_candidate_better(&full_score, score));
    if better {
        *best_score = Some(full_score);
        *best = Some(PnpSelectedReport {
            pose: report.pose,
            inlier_count: full_score.inlier_count,
            mean_reprojection_error: full_score.mean_error,
            correspondence_count: corrs.len(),
        });
    }
}

fn should_try_adaptive_pnp_depth(
    primary_score: Option<&PnpFullScore>,
    total_correspondences: usize,
    min_primary_inlier_ratio: f64,
) -> bool {
    if total_correspondences == 0
        || !min_primary_inlier_ratio.is_finite()
        || min_primary_inlier_ratio <= 0.0
    {
        return false;
    }
    let Some(primary_score) = primary_score else {
        return true;
    };
    let primary_ratio = primary_score.inlier_count as f64 / total_correspondences as f64;
    primary_ratio < min_primary_inlier_ratio
}

fn pnp_candidate_depths(
    primary_max_depth_m: Option<f64>,
    depth_hypotheses_m: &[f64],
) -> Vec<Option<f64>> {
    let mut depths = Vec::new();
    depths.push(primary_max_depth_m.filter(|d| d.is_finite() && *d > 0.0));
    for &depth in depth_hypotheses_m {
        if !depth.is_finite() || depth <= 0.0 {
            continue;
        }
        let candidate = Some(depth);
        if !depths
            .iter()
            .any(|existing| same_optional_depth(*existing, candidate))
        {
            depths.push(candidate);
        }
    }
    depths
}

fn same_optional_depth(a: Option<f64>, b: Option<f64>) -> bool {
    match (a, b) {
        (None, None) => true,
        (Some(a), Some(b)) => (a - b).abs() <= 1.0e-9,
        _ => false,
    }
}

fn pnp_correspondences_for_depth(
    all_corrs: &[Correspondence2D3D],
    max_depth_m: Option<f64>,
) -> Vec<Correspondence2D3D> {
    match max_depth_m {
        Some(max_depth_m) => all_corrs
            .iter()
            .filter(|corr| corr.point3d.z <= max_depth_m)
            .cloned()
            .collect(),
        None => all_corrs.to_vec(),
    }
}

fn estimate_pnp_candidate(
    pnp: &PnPRansac,
    corrs: &[Correspondence2D3D],
    camera: &Camera,
    weights: &[f32],
) -> Option<crate::ransac::RansacReport> {
    if weights.iter().any(|w| w.is_finite() && *w > 0.0) {
        pnp.estimate_with_weights(corrs, camera, weights)
    } else {
        pnp.estimate(corrs, camera)
    }
}

fn score_pnp_pose_on_correspondences(
    pose: &Pose,
    corrs: &[Correspondence2D3D],
    camera: &Camera,
    threshold_px: f64,
) -> PnpFullScore {
    let mut inlier_count = 0usize;
    let mut error_sum = 0.0;
    for corr in corrs {
        let projected_point = pose.transform_world_point(&corr.point3d);
        let Some(projected) = camera.project(&projected_point) else {
            continue;
        };
        let err = (projected - corr.point2d).norm();
        if err <= threshold_px {
            inlier_count += 1;
            error_sum += err;
        }
    }
    let mean_error = if inlier_count == 0 {
        f64::INFINITY
    } else {
        error_sum / inlier_count as f64
    };
    PnpFullScore {
        inlier_count,
        mean_error,
    }
}

fn is_pnp_candidate_better(candidate: &PnpFullScore, baseline: &PnpFullScore) -> bool {
    candidate.inlier_count > baseline.inlier_count
        || (candidate.inlier_count == baseline.inlier_count
            && candidate.mean_error + 1.0e-9 < baseline.mean_error)
}

fn score_pose_on_stereo_pairs(
    pose: &Pose,
    correspondences: &[StereoPairCorrespondence],
    inlier_threshold_m: f64,
) -> Pose3d3dScore {
    if correspondences.is_empty() || !inlier_threshold_m.is_finite() || inlier_threshold_m <= 0.0 {
        return Pose3d3dScore {
            inlier_count: 0,
            mean_residual_m: f64::INFINITY,
        };
    }
    let (inliers, sse) = score_pose_3d3d(pose, correspondences, inlier_threshold_m.powi(2));
    let mean_residual_m = if inliers.is_empty() {
        f64::INFINITY
    } else {
        (sse / inliers.len() as f64).sqrt()
    };
    Pose3d3dScore {
        inlier_count: inliers.len(),
        mean_residual_m,
    }
}

fn should_try_kabsch_challenger(
    pnp_report: &PnpSelectedReport,
    config: &StereoVoFrontendConfig,
) -> bool {
    if pnp_report.correspondence_count == 0 {
        return true;
    }
    if !config.pnp_kabsch_challenge_max_inlier_ratio.is_finite()
        || config.pnp_kabsch_challenge_max_inlier_ratio <= 0.0
    {
        return false;
    }
    let ratio = pnp_report.inlier_count as f64 / pnp_report.correspondence_count as f64;
    ratio < config.pnp_kabsch_challenge_max_inlier_ratio
}

fn is_kabsch_challenger_better(
    kabsch_report: &KabschRansacReport,
    pnp_stereo_score: Pose3d3dScore,
    config: &StereoVoFrontendConfig,
) -> bool {
    if kabsch_report.inliers.len()
        < pnp_stereo_score
            .inlier_count
            .saturating_add(config.pnp_kabsch_challenge_min_3d_inlier_gain)
    {
        return false;
    }
    if !pnp_stereo_score.mean_residual_m.is_finite() {
        return true;
    }
    kabsch_report.mean_residual_m
        <= pnp_stereo_score.mean_residual_m * config.pnp_kabsch_challenge_max_residual_ratio
}

fn filter_temporal_matches_by_row_delta(
    a_left: &FeatureSet,
    b_left: &FeatureSet,
    temporal_matches: &[DescriptorMatch],
    max_row_delta_px: f64,
) -> Vec<DescriptorMatch> {
    if !max_row_delta_px.is_finite() || max_row_delta_px <= 0.0 {
        return temporal_matches.to_vec();
    }
    temporal_matches
        .iter()
        .filter(|m| {
            let Some(a_kp) = a_left.keypoints.get(m.query_index) else {
                return false;
            };
            let Some(b_kp) = b_left.keypoints.get(m.train_index) else {
                return false;
            };
            (a_kp.y - b_kp.y).abs() <= max_row_delta_px
        })
        .cloned()
        .collect()
}

fn filter_temporal_matches_by_confidence(
    temporal_matches: &[DescriptorMatch],
    min_confidence: f32,
) -> Vec<DescriptorMatch> {
    if !min_confidence.is_finite() || min_confidence <= 0.0 {
        return temporal_matches.to_vec();
    }
    if !temporal_matches
        .iter()
        .any(|m| m.confidence.is_some_and(|c| c.is_finite()))
    {
        return temporal_matches.to_vec();
    }
    temporal_matches
        .iter()
        .filter(|m| {
            m.confidence
                .is_some_and(|confidence| confidence.is_finite() && confidence >= min_confidence)
        })
        .cloned()
        .collect()
}

fn effective_temporal_max_row_delta_px(
    translation_history_m: &[f64],
    config: &StereoVoFrontendConfig,
) -> Option<f64> {
    if let Some(max_row_delta_px) = config.temporal_max_row_delta_px {
        return finite_positive(max_row_delta_px);
    }
    let auto_max = finite_positive(config.temporal_auto_max_row_delta_px?)?;
    if translation_history_m.len() < config.temporal_auto_min_history {
        return None;
    }
    let recent_median =
        recent_translation_median(translation_history_m, config.temporal_auto_min_history)?;
    if recent_median >= config.temporal_auto_min_median_translation_m {
        Some(auto_max)
    } else {
        None
    }
}

fn effective_temporal_min_confidence(
    translation_history_m: &[f64],
    rotation_history_deg: &[f64],
    config: &StereoVoFrontendConfig,
) -> Option<f32> {
    let min_confidence = config.temporal_auto_min_confidence?;
    if !min_confidence.is_finite() || min_confidence <= 0.0 {
        return None;
    }
    if translation_history_m.len() < config.temporal_auto_confidence_min_history {
        return None;
    }
    let recent_translation_median = recent_translation_median(
        translation_history_m,
        config.temporal_auto_confidence_min_history,
    )?;
    let max_rotation_deg = config
        .temporal_auto_confidence_max_median_rotation_deg
        .and_then(finite_positive);
    let needs_rotation_median = max_rotation_deg.is_some()
        || config
            .temporal_auto_confidence_curve_min_median_translation_m
            .and_then(finite_positive)
            .is_some()
        || config
            .temporal_auto_confidence_curve_min_median_rotation_deg
            .and_then(finite_positive)
            .is_some();
    let recent_rotation_median = if needs_rotation_median {
        if rotation_history_deg.len() < config.temporal_auto_confidence_min_history {
            return None;
        }
        Some(recent_positive_median(
            rotation_history_deg,
            config.temporal_auto_confidence_min_history,
        )?)
    } else {
        None
    };
    if recent_translation_median >= config.temporal_auto_confidence_min_median_translation_m
        && max_rotation_deg
            .is_none_or(|max| recent_rotation_median.is_some_and(|rotation| rotation <= max))
    {
        return Some(min_confidence);
    }
    let curve_min_translation_m = config
        .temporal_auto_confidence_curve_min_median_translation_m
        .and_then(finite_positive)?;
    let curve_min_rotation_deg = config
        .temporal_auto_confidence_curve_min_median_rotation_deg
        .and_then(finite_positive)?;
    if recent_translation_median < curve_min_translation_m {
        return None;
    }
    let recent_rotation_median = recent_rotation_median?;
    if recent_rotation_median < curve_min_rotation_deg {
        return None;
    }
    if max_rotation_deg.is_some_and(|max| recent_rotation_median > max) {
        return None;
    }
    Some(min_confidence)
}

fn finite_positive(value: f64) -> Option<f64> {
    if value.is_finite() && value > 0.0 {
        Some(value)
    } else {
        None
    }
}

#[derive(Debug, Clone, PartialEq)]
struct StereoPoseObservation {
    point_prev: Point3<f64>,
    left_px: Point2<f64>,
    right_px: Point2<f64>,
}

// Stereo-temporal observation inputs (prev/current stereo, left/right features,
// matches, camera) are passed positionally to mirror `stereo_pose_observations`.
#[allow(clippy::too_many_arguments)]
fn refine_relative_pose_with_current_stereo(
    initial_pose: &Pose,
    prev_stereo: &[StereoFeature],
    current_stereo: &[StereoFeature],
    current_left: &FeatureSet,
    current_right: &FeatureSet,
    temporal_matches: &[DescriptorMatch],
    camera: &Camera,
    baseline: f64,
    max_initial_left_error_px: f64,
) -> Option<Pose> {
    let observations = stereo_pose_observations(
        initial_pose,
        prev_stereo,
        current_stereo,
        current_left,
        current_right,
        temporal_matches,
        camera,
        max_initial_left_error_px,
    );
    if observations.len() < 12 {
        return None;
    }
    refine_pose_stereo_reprojection(initial_pose, &observations, camera, baseline)
}

// Stereo-temporal observation inputs are passed positionally; bundling them
// would not group more cohesively than this single call site.
#[allow(clippy::too_many_arguments)]
fn stereo_pose_observations(
    initial_pose: &Pose,
    prev_stereo: &[StereoFeature],
    current_stereo: &[StereoFeature],
    current_left: &FeatureSet,
    current_right: &FeatureSet,
    temporal_matches: &[DescriptorMatch],
    camera: &Camera,
    max_initial_left_error_px: f64,
) -> Vec<StereoPoseObservation> {
    let prev_lookup: HashMap<usize, &StereoFeature> =
        prev_stereo.iter().map(|f| (f.left_index, f)).collect();
    let current_lookup: HashMap<usize, &StereoFeature> =
        current_stereo.iter().map(|f| (f.left_index, f)).collect();
    let mut observations = Vec::new();
    for m in temporal_matches {
        let (Some(prev), Some(curr)) = (
            prev_lookup.get(&m.query_index),
            current_lookup.get(&m.train_index),
        ) else {
            continue;
        };
        let left_px = current_left.keypoints[m.train_index];
        let right_px = current_right.keypoints[curr.right_index];
        let Some(projected) = camera.project(&initial_pose.transform_world_point(&prev.point_cam))
        else {
            continue;
        };
        if (projected - left_px).norm() > max_initial_left_error_px {
            continue;
        }
        observations.push(StereoPoseObservation {
            point_prev: prev.point_cam,
            left_px,
            right_px,
        });
    }
    observations
}

fn refine_pose_stereo_reprojection(
    initial_pose: &Pose,
    observations: &[StereoPoseObservation],
    camera: &Camera,
    baseline: f64,
) -> Option<Pose> {
    let mut pose = initial_pose.clone();
    let mut best_error =
        stereo_reprojection_mean_squared_error(&pose, observations, camera, baseline)?;
    for _ in 0..6 {
        let residual = stereo_reprojection_residual(&pose, observations, camera, baseline)?;
        let jacobian = stereo_translation_jacobian(&pose, observations, camera, baseline, 1.0e-6)?;
        let j_t = jacobian.transpose();
        let mut hessian = &j_t * &jacobian;
        for diagonal in 0..hessian.nrows().min(hessian.ncols()) {
            hessian[(diagonal, diagonal)] += 1.0e-5;
        }
        let gradient = &j_t * residual;
        let step = hessian.lu().solve(&(-gradient))?;
        if !step.iter().all(|value| value.is_finite()) {
            return Some(pose);
        }
        let candidate = perturb_stereo_translation(&pose, &step);
        let Some(candidate_error) =
            stereo_reprojection_mean_squared_error(&candidate, observations, camera, baseline)
        else {
            break;
        };
        if candidate_error + 1.0e-9 >= best_error {
            break;
        }
        pose = candidate;
        best_error = candidate_error;
    }
    Some(pose)
}

fn stereo_reprojection_mean_squared_error(
    pose: &Pose,
    observations: &[StereoPoseObservation],
    camera: &Camera,
    baseline: f64,
) -> Option<f64> {
    let residual = stereo_reprojection_residual(pose, observations, camera, baseline)?;
    Some(residual.norm_squared() / observations.len() as f64)
}

fn stereo_reprojection_residual(
    pose: &Pose,
    observations: &[StereoPoseObservation],
    camera: &Camera,
    baseline: f64,
) -> Option<DVector<f64>> {
    let mut residual = DVector::<f64>::zeros(observations.len() * 4);
    for (index, obs) in observations.iter().enumerate() {
        let point_left = pose.transform_world_point(&obs.point_prev);
        let left_projected = camera.project(&point_left)?;
        let right_projected = camera.project(&Point3::new(
            point_left.x - baseline,
            point_left.y,
            point_left.z,
        ))?;
        let offset = index * 4;
        residual[offset] = left_projected.x - obs.left_px.x;
        residual[offset + 1] = left_projected.y - obs.left_px.y;
        residual[offset + 2] = right_projected.x - obs.right_px.x;
        residual[offset + 3] = right_projected.y - obs.right_px.y;
    }
    Some(residual)
}

fn stereo_translation_jacobian(
    pose: &Pose,
    observations: &[StereoPoseObservation],
    camera: &Camera,
    baseline: f64,
    epsilon: f64,
) -> Option<DMatrix<f64>> {
    let base = stereo_reprojection_residual(pose, observations, camera, baseline)?;
    let mut jacobian = DMatrix::<f64>::zeros(base.len(), 3);
    for parameter_index in 0..3 {
        let mut delta = DVector::<f64>::zeros(3);
        delta[parameter_index] = epsilon;
        let perturbed_pose = perturb_stereo_translation(pose, &delta);
        let perturbed =
            stereo_reprojection_residual(&perturbed_pose, observations, camera, baseline)?;
        let column = (perturbed - &base) / epsilon;
        jacobian.set_column(parameter_index, &column);
    }
    Some(jacobian)
}

fn perturb_stereo_translation(pose: &Pose, delta: &DVector<f64>) -> Pose {
    let translation_delta = Vector3::new(delta[0], delta[1], delta[2]);
    Pose::from_world_to_camera(
        pose.world_to_camera.rotation,
        pose.world_to_camera.translation + translation_delta,
    )
}

/// Configuration for [`StereoVoFrontend`]. Defaults are tuned for KITTI-
/// scale rectified stereo with the project's `CornerFeatureExtractor`
/// patch descriptors at radius 9; tighter `kabsch.inlier_threshold_m` /
/// looser `stereo.max_depth_m` may be appropriate for sequences with
/// faster motion or longer-range structure.
#[derive(Debug, Clone, PartialEq)]
pub struct StereoVoFrontendConfig {
    pub feature: CornerFeatureConfig,
    pub stereo: StereoFeatureConfig,
    pub kabsch: KabschRansacConfig,
    /// Pixel threshold for the 2D-3D PnP RANSAC reprojection inlier test.
    /// Lower values reject descriptor-consistent but geometrically loose
    /// matches; higher values are more tolerant when features are noisy.
    pub pnp_reprojection_threshold_px: f64,
    /// Minimum accepted 2D-3D PnP inlier count. If PnP recovers fewer
    /// inliers, the frontend treats it as a failed primary estimate and
    /// falls back to the 3D-3D Kabsch path when available.
    pub pnp_min_inliers: usize,
    /// Optional maximum depth for 3D points passed into consecutive-frame
    /// PnP. Stereo depth noise grows quadratically with distance, so
    /// dropping very far landmarks can reduce rotation drift on driving
    /// sequences. `None` keeps every triangulated point accepted by the
    /// stereo frontend.
    pub pnp_max_depth_m: Option<f64>,
    /// Optional extra max-depth hypotheses for PnP. When populated, the
    /// frontend estimates PnP once with the primary `pnp_max_depth_m` setting
    /// and once for each extra depth cap, then selects the pose that scores
    /// best when reprojected against the full uncapped correspondence set.
    /// This lets far-field pruning act as a candidate generator without
    /// making a depth-capped pose eligible when it loses global consensus.
    pub pnp_depth_hypotheses_m: Vec<f64>,
    /// Optional automatic PnP max-depth candidate. Unlike
    /// `pnp_depth_hypotheses_m`, this candidate is tried only when the
    /// primary uncapped/depth-capped PnP estimate has weak consensus.
    pub pnp_adaptive_depth_hypothesis_m: Option<f64>,
    /// Primary PnP inlier ratio below which the adaptive depth candidate is
    /// evaluated. This is intentionally conservative so clean short windows
    /// keep the primary path unchanged.
    pub pnp_adaptive_depth_min_primary_inlier_ratio: f64,
    /// Number of prior relative-motion estimates required before the frontend
    /// can rescue a collapsed translation magnitude from recent motion scale.
    pub motion_scale_rescue_min_history: usize,
    /// Minimum recent median translation required before motion-scale rescue
    /// is considered. This keeps slow urban windows on the raw estimator path.
    pub motion_scale_rescue_min_median_translation_m: f64,
    /// Trigger rescue when the current translation magnitude is below this
    /// fraction of the recent median and the pose consensus is weak.
    pub motion_scale_rescue_min_translation_ratio: f64,
    /// Trigger rescue when the current translation magnitude is above this
    /// multiple of the recent median and the pose consensus is weak.
    pub motion_scale_rescue_max_translation_ratio: f64,
    /// Percentile of the recent translation history used as the replacement
    /// scale once motion-scale rescue triggers. Values above the median make
    /// the fast-motion guard less laggy on accelerating driving sequences.
    pub motion_scale_rescue_target_percentile: f64,
    /// Maximum PnP inlier ratio eligible for motion-scale rescue. Keeping
    /// this slightly above one lets the fast-motion scale guard smooth clean
    /// but laggy PnP pairs, while the median-translation gate keeps slow
    /// urban windows on the raw estimator path.
    pub motion_scale_rescue_max_pnp_inlier_ratio: f64,
    /// Release a motion-scale rescue that has rescued a whole history window
    /// (`motion_scale_rescue_min_history` pairs) in a row. The rescue judges
    /// each step against the recent rescued steps. After a full window of
    /// rescues that history holds only the rescue's own outputs, so a real,
    /// sustained slowdown locks in: every slower step counts as "collapsed"
    /// and is scaled back up to the old speed, for good (KITTI odometry 09:
    /// 1,312 pairs in a row; raw drive 2011_09_30_0020: 307). On release the
    /// streak's entries in the rescue's history are replaced by the
    /// estimator's raw step lengths and the current step is kept as
    /// estimated, so the median follows the real speed again. On by
    /// default. The short streaks the rescue exists for (at most 17 pairs on
    /// KITTI 01's highway slice) never reach it.
    pub motion_scale_rescue_release_full_window: bool,
    /// Number of prior relative-motion estimates required before translation
    /// direction rescue can clamp a weak-consensus lateral outlier.
    pub translation_direction_rescue_min_history: usize,
    /// Minimum recent median translation required before translation direction
    /// rescue is considered.
    pub translation_direction_rescue_min_median_translation_m: f64,
    /// Trigger translation direction rescue when the current translation vector
    /// deviates from the recent average direction by more than this angle.
    pub translation_direction_rescue_max_angle_deg: f64,
    /// Maximum PnP inlier ratio still considered weak enough for translation
    /// direction rescue. Kabsch fallbacks are considered weak.
    pub translation_direction_rescue_max_pnp_inlier_ratio: f64,
    /// Number of prior relative-motion estimates required before rotation
    /// spike rescue can clamp an implausibly large weak-consensus rotation.
    pub rotation_spike_rescue_min_history: usize,
    /// Minimum recent median translation required before rotation spike rescue
    /// is considered.
    pub rotation_spike_rescue_min_median_translation_m: f64,
    /// Minimum current relative-rotation angle before rotation spike rescue can
    /// trigger, even if the recent-median ratio is exceeded.
    pub rotation_spike_rescue_min_angle_deg: f64,
    /// Trigger rotation spike rescue when the current rotation angle exceeds
    /// this multiple of the recent median rotation angle.
    pub rotation_spike_rescue_max_angle_ratio: f64,
    /// Maximum PnP inlier ratio still considered weak enough for rotation
    /// spike rescue. Kabsch fallbacks are considered weak.
    pub rotation_spike_rescue_max_pnp_inlier_ratio: f64,
    /// Number of prior relative-motion estimates required before weak
    /// rotations can be clamped to the recent scaled-axis trend.
    pub rotation_vector_rescue_min_history: usize,
    /// Minimum recent median translation required before rotation-vector
    /// rescue is considered.
    pub rotation_vector_rescue_min_median_translation_m: f64,
    /// Trigger rotation-vector rescue when the current scaled-axis rotation
    /// differs from the recent average scaled-axis rotation by more than this
    /// angle.
    pub rotation_vector_rescue_max_delta_deg: f64,
    /// Maximum PnP inlier ratio still considered weak enough for
    /// rotation-vector rescue. Kabsch fallbacks are considered weak.
    pub rotation_vector_rescue_max_pnp_inlier_ratio: f64,
    /// Minimum PnP RANSAC trials before the high-consensus early-stop guard
    /// can terminate the search. This only applies when
    /// `pnp_early_stop_inlier_ratio` is `Some`.
    pub pnp_early_stop_min_iterations: usize,
    /// Optional high-consensus early-stop ratio for consecutive-frame PnP.
    /// KITTI-like stereo pairs often reach a very large inlier set quickly;
    /// stopping after that point avoids pathological long frames while
    /// preserving the full budget for lower-consensus pairs.
    pub pnp_early_stop_inlier_ratio: Option<f64>,
    /// When PnP technically succeeds but has a very low inlier ratio, also
    /// estimate a 3D-3D Kabsch pose and let it challenge the PnP pose.
    /// This targets highway windows where a small descriptor-consistent PnP
    /// consensus can carry a rotation/translation outlier even though the
    /// stereo pair set contains a stronger metric alignment.
    pub pnp_kabsch_challenge_max_inlier_ratio: f64,
    /// Minimum 3D-3D inlier-count gain required before the weak-PnP Kabsch
    /// challenger can replace PnP.
    pub pnp_kabsch_challenge_min_3d_inlier_gain: usize,
    /// Required residual improvement for the Kabsch challenger relative to
    /// scoring the PnP pose on the same 3D-3D stereo pairs.
    pub pnp_kabsch_challenge_max_residual_ratio: f64,
    /// If enabled, refine only the selected relative pose translation
    /// against current-frame left and right stereo reprojection residuals
    /// for temporal matches that have stereo triangulations in both frames.
    /// Rotation stays anchored to PnP/Kabsch so current-frame stereo
    /// disparity noise cannot pull the orientation estimate around.
    pub stereo_pose_refinement: bool,
    /// If enabled, align only the selected relative pose's vertical
    /// translation component against matched stereo 3D pairs. This keeps
    /// PnP's rotation and forward/lateral translation while using the
    /// current stereo triangulation as a robust vertical residual check.
    pub stereo_vertical_alignment: bool,
    /// Minimum matched stereo 3D pairs required before vertical-only
    /// alignment can run.
    pub stereo_vertical_alignment_min_pairs: usize,
    /// Maximum absolute per-pair vertical correction in meters.
    pub stereo_vertical_alignment_max_correction_m: f64,
    /// Number of prior relative-motion estimates required before automatic
    /// stereo pose refinement can run without the explicit
    /// `stereo_pose_refinement` override.
    pub stereo_pose_refinement_auto_min_history: usize,
    /// Minimum recent median translation required before automatic stereo
    /// pose refinement is considered.
    pub stereo_pose_refinement_auto_min_median_translation_m: f64,
    /// Maximum PnP inlier ratio eligible for automatic stereo pose
    /// refinement once the recent motion is fast enough. Kabsch fallbacks are
    /// considered eligible by construction.
    pub stereo_pose_refinement_auto_max_pnp_inlier_ratio: f64,
    /// Consecutive-frame relative-pose source. `PnpThenKabsch` preserves
    /// the default 2D-3D PnP path and uses 3D-3D Kabsch only as a fallback;
    /// `KabschThenPnp` is useful for driving/stereo ablations where metric
    /// 3D-3D alignment may reduce forward-motion PnP drift.
    pub relative_pose_mode: StereoRelativePoseMode,
    /// Lowe's ratio for the per-pair temporal `left_i ↔ left_(i+1)`
    /// descriptor matcher. Native to the project's `BruteForceMatcher`
    /// (`f32`), kept here as `Option<f32>` to avoid a lossy cast at
    /// every `process_pair`.
    pub temporal_ratio: Option<f32>,
    /// Optional row-motion gate for consecutive-frame temporal matches.
    /// Rectified automotive stereo has limited vertical frame-to-frame
    /// motion; setting this can remove descriptor-consistent but implausible
    /// temporal matches before PnP/Kabsch. `None` preserves unconstrained
    /// temporal matching.
    pub temporal_max_row_delta_px: Option<f64>,
    /// Optional automatic row-motion gate for faster recent motion. Unlike
    /// `temporal_max_row_delta_px`, this only activates after enough prior
    /// relative translations have been integrated and their recent median is
    /// above `temporal_auto_min_median_translation_m`.
    pub temporal_auto_max_row_delta_px: Option<f64>,
    pub temporal_auto_min_history: usize,
    pub temporal_auto_min_median_translation_m: f64,
    /// Optional automatic confidence floor for consecutive-frame temporal
    /// matches during faster recent motion. Matchers without confidence
    /// metadata are left unchanged, so this only affects deep-style matchers
    /// such as [`crate::matching::MutualSoftmaxMatcher`].
    pub temporal_auto_min_confidence: Option<f32>,
    pub temporal_auto_confidence_min_history: usize,
    pub temporal_auto_confidence_min_median_translation_m: f64,
    pub temporal_auto_confidence_curve_min_median_translation_m: Option<f64>,
    pub temporal_auto_confidence_curve_min_median_rotation_deg: Option<f64>,
    pub temporal_auto_confidence_max_median_rotation_deg: Option<f64>,
}

impl Default for StereoVoFrontendConfig {
    fn default() -> Self {
        Self {
            feature: CornerFeatureConfig {
                max_features: 1500,
                min_score: 0.02,
                descriptor_radius: 9,
            },
            stereo: StereoFeatureConfig {
                min_disparity_px: 1.0,
                max_row_residual_px: 2.0,
                min_depth_m: 3.0,
                max_depth_m: 80.0,
                depth_gate: StereoDepthGate::default(),
                ratio: Some(0.85),
            },
            kabsch: KabschRansacConfig {
                iterations: 4000,
                inlier_threshold_m: 2.0,
                min_inliers: 8,
                max_depth_m: 30.0,
                seed: 7,
            },
            pnp_reprojection_threshold_px: 3.32,
            pnp_min_inliers: 12,
            pnp_max_depth_m: None,
            pnp_depth_hypotheses_m: Vec::new(),
            pnp_adaptive_depth_hypothesis_m: Some(60.0),
            pnp_adaptive_depth_min_primary_inlier_ratio: 0.65,
            motion_scale_rescue_min_history: 20,
            motion_scale_rescue_min_median_translation_m: 1.5,
            motion_scale_rescue_min_translation_ratio: 0.97,
            motion_scale_rescue_max_translation_ratio: 1.6,
            motion_scale_rescue_target_percentile: 0.75,
            motion_scale_rescue_max_pnp_inlier_ratio: 1.05,
            motion_scale_rescue_release_full_window: true,
            translation_direction_rescue_min_history: 20,
            translation_direction_rescue_min_median_translation_m: 1.5,
            translation_direction_rescue_max_angle_deg: 10.0,
            translation_direction_rescue_max_pnp_inlier_ratio: 0.45,
            rotation_spike_rescue_min_history: 20,
            rotation_spike_rescue_min_median_translation_m: 1.5,
            rotation_spike_rescue_min_angle_deg: 1.0,
            rotation_spike_rescue_max_angle_ratio: 3.0,
            rotation_spike_rescue_max_pnp_inlier_ratio: 0.45,
            rotation_vector_rescue_min_history: 20,
            rotation_vector_rescue_min_median_translation_m: 1.5,
            rotation_vector_rescue_max_delta_deg: 0.4,
            rotation_vector_rescue_max_pnp_inlier_ratio: 0.45,
            pnp_early_stop_min_iterations: 100,
            pnp_early_stop_inlier_ratio: Some(0.85),
            pnp_kabsch_challenge_max_inlier_ratio: 0.0,
            pnp_kabsch_challenge_min_3d_inlier_gain: 8,
            pnp_kabsch_challenge_max_residual_ratio: 0.85,
            stereo_pose_refinement: false,
            stereo_vertical_alignment: false,
            stereo_vertical_alignment_min_pairs: 80,
            stereo_vertical_alignment_max_correction_m: 0.25,
            stereo_pose_refinement_auto_min_history: 20,
            stereo_pose_refinement_auto_min_median_translation_m: 1.5,
            stereo_pose_refinement_auto_max_pnp_inlier_ratio: 1.0,
            relative_pose_mode: StereoRelativePoseMode::PnpThenKabsch,
            temporal_ratio: Some(0.9),
            temporal_max_row_delta_px: None,
            temporal_auto_max_row_delta_px: None,
            temporal_auto_min_history: 20,
            temporal_auto_min_median_translation_m: 1.05,
            temporal_auto_min_confidence: Some(0.20),
            temporal_auto_confidence_min_history: 20,
            temporal_auto_confidence_min_median_translation_m: 1.45,
            temporal_auto_confidence_curve_min_median_translation_m: Some(0.95),
            temporal_auto_confidence_curve_min_median_rotation_deg: Some(0.26),
            temporal_auto_confidence_max_median_rotation_deg: Some(0.45),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StereoRelativePoseMode {
    PnpThenKabsch,
    KabschThenPnp,
}

/// Errors returned by [`StereoVoFrontend::process_pair`]. The feature
/// extractor's error is type-erased into a `Box<dyn Error>` so the same
/// `StereoVoError` type accepts any [`FeatureExtractor`] implementation
/// (classical `CornerFeatureExtractor`, learned `HogLikeFeatureExtractor`,
/// or a future ONNX-backed deep head).
#[derive(Debug)]
pub enum StereoVoError {
    Feature(Box<dyn std::error::Error + Send + Sync>),
    KabschFailed {
        pair_index: usize,
        correspondence_count: usize,
        min_inliers: usize,
    },
}

impl From<CornerFeatureError> for StereoVoError {
    fn from(value: CornerFeatureError) -> Self {
        StereoVoError::Feature(Box::new(value))
    }
}

impl std::fmt::Display for StereoVoError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StereoVoError::Feature(e) => write!(f, "feature extraction failed: {e}"),
            StereoVoError::KabschFailed {
                pair_index,
                correspondence_count,
                min_inliers,
            } => write!(
                f,
                "relative-pose RANSAC failed at pair {pair_index}→{}: {correspondence_count} \
                 correspondences (need ≥{min_inliers} inliers)",
                pair_index + 1,
            ),
        }
    }
}

impl std::error::Error for StereoVoError {}

/// Stateful rectified-stereo VO frontend. Each `process_pair` call extracts
/// features in both eyes, triangulates them, matches the previous frame's
/// left features against the new frame's, and recovers the relative pose via
/// 2D-3D PnP RANSAC with a 3D-3D Kabsch fallback. The first call seeds the
/// world frame at identity; subsequent calls compose the recovered relative
/// pose into the running world-frame trajectory.
///
/// Per-frame state (FeatureSets, stereo triangulations, world-frame poses)
/// is exposed via the public fields so a downstream BA orchestrator can
/// build multi-frame tracks across the trajectory and refine without
/// re-running the front-end.
#[derive(Debug)]
pub struct StereoVoFrontend<E = CornerFeatureExtractor, M = BruteForceMatcher>
where
    E: FeatureExtractor<Image = GrayscaleImage>,
    M: Matcher,
{
    pub camera: Camera,
    pub baseline: f64,
    pub config: StereoVoFrontendConfig,

    extractor: E,
    matcher: M,
    depth_gate_state: StereoDepthGateState,

    /// World-frame pose for every processed frame, beginning with the
    /// identity pose at the seed frame.
    pub poses: Vec<Pose>,
    pub left_features: Vec<FeatureSet>,
    pub right_features: Vec<FeatureSet>,
    pub stereo_per_frame: Vec<Vec<StereoFeature>>,
    /// Per-pair Kabsch translation magnitude in metric units (one entry
    /// per call after the first). Used by track-extension callers to
    /// adapt the projection search radius to the observed motion.
    pub per_pair_translation_m: Vec<f64>,
    /// Per-pair translation magnitudes before any frontend rescue (the
    /// estimator's own step lengths).
    pub per_pair_raw_translation_m: Vec<f64>,
    motion_scale_rescue: MotionScaleRescue,
    /// Per-pair relative translation vectors in the current camera frame,
    /// after any guarded frontend rescues have been applied.
    pub per_pair_translation_vectors: Vec<Vector3<f64>>,
    /// Per-pair relative-rotation magnitudes in degrees, after any guarded
    /// frontend rescues have been applied.
    pub per_pair_rotation_deg: Vec<f64>,
    /// Per-pair relative-rotation scaled-axis vectors in radians, after any
    /// guarded frontend rescues have been applied.
    pub per_pair_rotation_vectors: Vec<Vector3<f64>>,
    /// Per-pair relative-pose RANSAC inlier counts.
    pub kabsch_inlier_counts: Vec<usize>,
    /// Per-pair relative-pose diagnostics, including which estimator was
    /// actually selected. Kept separate from `kabsch_inlier_counts` because
    /// the latter is a legacy name used by existing examples.
    pub pair_diagnostics: Vec<StereoVoPairDiagnostics>,
    /// Per-frame lower-depth gate diagnostics. One entry is appended for
    /// every processed stereo frame, including the seed frame.
    pub stereo_depth_gate_diagnostics: Vec<StereoDepthGateDiagnostics>,
    /// Per-pair temporal matches actually used (after row-gate and
    /// confidence filters). One entry per pose pair, i.e. `poses.len() - 1`
    /// entries after the seed frame. Captured so downstream multi-frame BA
    /// refiners (e.g. `visloc_slam::refine_stereo_vo_with_ba`) can be driven
    /// online without re-running the matcher.
    pub temporal_matches_per_pair: Vec<Vec<DescriptorMatch>>,
}

impl StereoVoFrontend<CornerFeatureExtractor, BruteForceMatcher> {
    /// Build the classical Corner + brute-force frontend that the original
    /// stereo VO demos use. Equivalent to
    /// `new_with(camera, baseline, config, CornerFeatureExtractor::new(...),
    /// BruteForceMatcher { ratio: config.temporal_ratio })`.
    pub fn new(camera: Camera, baseline: f64, config: StereoVoFrontendConfig) -> Self {
        let extractor = CornerFeatureExtractor::new(config.feature.clone());
        let matcher = BruteForceMatcher {
            ratio: config.temporal_ratio,
        };
        Self::new_with(camera, baseline, config, extractor, matcher)
    }
}

impl<E, M> StereoVoFrontend<E, M>
where
    E: FeatureExtractor<Image = GrayscaleImage>,
    E::Error: std::error::Error + Send + Sync + 'static,
    M: Matcher,
{
    /// Build a stereo VO frontend with caller-provided feature extractor
    /// and matcher. Use this constructor to plug in a deep frontend
    /// (`HogLikeFeatureExtractor` + `MutualSoftmaxMatcher`) or a future
    /// ONNX-backed learned head — the rest of the pipeline (stereo
    /// triangulation, Kabsch RANSAC, world-frame composition) is shared.
    pub fn new_with(
        camera: Camera,
        baseline: f64,
        config: StereoVoFrontendConfig,
        extractor: E,
        matcher: M,
    ) -> Self {
        Self {
            camera,
            baseline,
            config,
            extractor,
            matcher,
            depth_gate_state: StereoDepthGateState::default(),
            poses: Vec::new(),
            left_features: Vec::new(),
            right_features: Vec::new(),
            stereo_per_frame: Vec::new(),
            per_pair_translation_m: Vec::new(),
            per_pair_raw_translation_m: Vec::new(),
            motion_scale_rescue: MotionScaleRescue::default(),
            per_pair_translation_vectors: Vec::new(),
            per_pair_rotation_deg: Vec::new(),
            per_pair_rotation_vectors: Vec::new(),
            kabsch_inlier_counts: Vec::new(),
            pair_diagnostics: Vec::new(),
            stereo_depth_gate_diagnostics: Vec::new(),
            temporal_matches_per_pair: Vec::new(),
        }
    }

    /// Number of frames processed so far.
    pub fn frame_count(&self) -> usize {
        self.poses.len()
    }

    /// Process a rectified stereo pair. The first call seeds the world
    /// frame at identity; each subsequent call extends the trajectory
    /// with one new pose and returns it.
    pub fn process_pair(
        &mut self,
        left: &GrayscaleImage,
        right: &GrayscaleImage,
    ) -> Result<Pose, StereoVoError> {
        let left_features = self
            .extractor
            .extract(left)
            .map_err(|e| StereoVoError::Feature(Box::new(e)))?;
        let right_features = self
            .extractor
            .extract(right)
            .map_err(|e| StereoVoError::Feature(Box::new(e)))?;
        self.process_feature_pair(left_features, right_features)
    }

    /// Process caller-provided left/right features using the frontend's
    /// configured descriptor matcher for stereo-temporal association.
    ///
    /// This is useful when feature extraction lives outside the frontend but
    /// descriptor matching should still use the Rust matcher.
    pub fn process_feature_pair(
        &mut self,
        left_features: FeatureSet,
        right_features: FeatureSet,
    ) -> Result<Pose, StereoVoError> {
        self.process_feature_pair_with_matches(left_features, right_features, None, None)
    }

    /// Process caller-provided left/right features and optional explicit
    /// matches.
    ///
    /// `stereo_matches` are interpreted as `left.query_index -> right.train_index`.
    /// `temporal_matches` are interpreted as
    /// `previous_left.query_index -> current_left.train_index`. When either
    /// argument is `None`, the frontend falls back to its configured internal
    /// matcher for that association.
    pub fn process_feature_pair_with_matches(
        &mut self,
        left_features: FeatureSet,
        right_features: FeatureSet,
        stereo_matches: Option<&[DescriptorMatch]>,
        temporal_matches: Option<&[DescriptorMatch]>,
    ) -> Result<Pose, StereoVoError> {
        let stereo_outcome = if let Some(stereo_matches) = stereo_matches {
            triangulate_stereo_feature_matches_with_depth_state(
                &left_features,
                &right_features,
                stereo_matches,
                &self.camera,
                self.baseline,
                &self.config.stereo,
                Some(&mut self.depth_gate_state),
            )
        } else {
            triangulate_stereo_features_with_depth_state(
                &left_features,
                &right_features,
                &self.camera,
                self.baseline,
                &self.config.stereo,
                Some(&mut self.depth_gate_state),
            )
        };
        let stereo_depth_gate_diagnostics = stereo_outcome.diagnostics;
        let stereo = stereo_outcome.features;

        let new_pose = if let (Some(prev_left), Some(prev_stereo)) =
            (self.left_features.last(), self.stereo_per_frame.last())
        {
            let temporal_matches_raw = temporal_matches.map_or_else(
                || {
                    self.matcher
                        .match_descriptors(&prev_left.descriptors, &left_features.descriptors)
                },
                |matches| matches.to_vec(),
            );
            let temporal_row_gate_px =
                effective_temporal_max_row_delta_px(&self.per_pair_translation_m, &self.config);
            let temporal_confidence_gate = effective_temporal_min_confidence(
                &self.per_pair_translation_m,
                &self.per_pair_rotation_deg,
                &self.config,
            );
            let temporal_matches = if let Some(max_row_delta_px) = temporal_row_gate_px {
                filter_temporal_matches_by_row_delta(
                    prev_left,
                    &left_features,
                    &temporal_matches_raw,
                    max_row_delta_px,
                )
            } else {
                temporal_matches_raw
            };
            let temporal_matches = if let Some(min_confidence) = temporal_confidence_gate {
                filter_temporal_matches_by_confidence(&temporal_matches, min_confidence)
            } else {
                temporal_matches
            };
            let pnp_corrs_all = build_stereo_temporal_correspondences(
                prev_stereo,
                &left_features,
                &temporal_matches,
            );
            let pnp = PnPRansac {
                iterations: self.config.kabsch.iterations,
                reprojection_threshold: self.config.pnp_reprojection_threshold_px,
                seed: self.config.kabsch.seed,
                early_stop_min_iterations: self.config.pnp_early_stop_min_iterations,
                early_stop_inlier_ratio: self.config.pnp_early_stop_inlier_ratio,
                ..PnPRansac::default()
            };
            let pnp_report = estimate_pnp_with_depth_hypotheses(
                &pnp,
                &pnp_corrs_all,
                &self.camera,
                self.config.pnp_min_inliers,
                self.config.pnp_max_depth_m,
                &self.config.pnp_depth_hypotheses_m,
                self.config.pnp_adaptive_depth_hypothesis_m,
                self.config.pnp_adaptive_depth_min_primary_inlier_ratio,
            );
            let pair_corrs = stereo_pair_correspondences(prev_stereo, &stereo, &temporal_matches);
            let (
                mut relative_pose,
                inlier_count,
                source,
                pnp_mean_reprojection_error_px,
                kabsch_mean_residual_m,
            ) = match self.config.relative_pose_mode {
                StereoRelativePoseMode::PnpThenKabsch => {
                    if let Some(report) = &pnp_report {
                        let kabsch_challenger =
                            if should_try_kabsch_challenger(report, &self.config) {
                                estimate_relative_pose_kabsch_ransac(
                                    &pair_corrs,
                                    &self.config.kabsch,
                                )
                            } else {
                                None
                            };
                        if let Some(kabsch_report) = &kabsch_challenger {
                            let pnp_stereo_score = score_pose_on_stereo_pairs(
                                &report.pose,
                                &pair_corrs,
                                self.config.kabsch.inlier_threshold_m,
                            );
                            if is_kabsch_challenger_better(
                                kabsch_report,
                                pnp_stereo_score,
                                &self.config,
                            ) {
                                (
                                    kabsch_report.relative_pose.clone(),
                                    kabsch_report.inliers.len(),
                                    StereoRelativePoseSource::Kabsch,
                                    Some(report.mean_reprojection_error),
                                    Some(kabsch_report.mean_residual_m),
                                )
                            } else {
                                (
                                    report.pose.clone(),
                                    report.inlier_count,
                                    StereoRelativePoseSource::Pnp,
                                    Some(report.mean_reprojection_error),
                                    kabsch_challenger.as_ref().map(|r| r.mean_residual_m),
                                )
                            }
                        } else {
                            (
                                report.pose.clone(),
                                report.inlier_count,
                                StereoRelativePoseSource::Pnp,
                                Some(report.mean_reprojection_error),
                                None,
                            )
                        }
                    } else {
                        let kabsch_report =
                            estimate_relative_pose_kabsch_ransac(&pair_corrs, &self.config.kabsch);
                        let report =
                            kabsch_report
                                .as_ref()
                                .ok_or_else(|| StereoVoError::KabschFailed {
                                    pair_index: self.poses.len() - 1,
                                    correspondence_count: pair_corrs.len().max(pnp_corrs_all.len()),
                                    min_inliers: self.config.kabsch.min_inliers,
                                })?;
                        (
                            report.relative_pose.clone(),
                            report.inliers.len(),
                            StereoRelativePoseSource::KabschFallback,
                            pnp_report.as_ref().map(|r| r.mean_reprojection_error),
                            Some(report.mean_residual_m),
                        )
                    }
                }
                StereoRelativePoseMode::KabschThenPnp => {
                    let kabsch_report =
                        estimate_relative_pose_kabsch_ransac(&pair_corrs, &self.config.kabsch);
                    if let Some(report) = &kabsch_report {
                        (
                            report.relative_pose.clone(),
                            report.inliers.len(),
                            StereoRelativePoseSource::Kabsch,
                            pnp_report.as_ref().map(|r| r.mean_reprojection_error),
                            Some(report.mean_residual_m),
                        )
                    } else {
                        let report =
                            pnp_report
                                .as_ref()
                                .ok_or_else(|| StereoVoError::KabschFailed {
                                    pair_index: self.poses.len() - 1,
                                    correspondence_count: pair_corrs.len().max(pnp_corrs_all.len()),
                                    min_inliers: self.config.kabsch.min_inliers,
                                })?;
                        (
                            report.pose.clone(),
                            report.inlier_count,
                            StereoRelativePoseSource::PnpFallback,
                            Some(report.mean_reprojection_error),
                            kabsch_report.as_ref().map(|r| r.mean_residual_m),
                        )
                    }
                }
            };
            if should_refine_current_stereo_pose(
                &self.per_pair_translation_m,
                pnp_report.as_ref(),
                source,
                &self.config,
            ) {
                if let Some(refined) = refine_relative_pose_with_current_stereo(
                    &relative_pose,
                    prev_stereo,
                    &stereo,
                    &left_features,
                    &right_features,
                    &temporal_matches,
                    &self.camera,
                    self.baseline,
                    self.config.pnp_reprojection_threshold_px * 2.0,
                ) {
                    relative_pose = refined;
                }
            }
            let raw_translation_m = relative_pose.world_to_camera.translation.norm();
            let raw_rotation_deg = relative_rotation_angle_deg(&relative_pose);
            let stereo_vertical_aligned = align_vertical_translation_to_stereo_pairs(
                &mut relative_pose,
                prev_stereo,
                &stereo,
                prev_left,
                &left_features,
                &temporal_matches,
                &self.camera,
                &self.config,
            );
            let motion_scale_rescued = self.motion_scale_rescue.apply(
                &mut relative_pose,
                pnp_report.as_ref(),
                source,
                &self.config,
            );
            let translation_direction_rescued = rescue_translation_direction(
                &mut relative_pose,
                &self.per_pair_translation_m,
                &self.per_pair_translation_vectors,
                pnp_report.as_ref(),
                source,
                &self.config,
            );
            let rotation_spike_rescued = rescue_rotation_spike(
                &mut relative_pose,
                &self.per_pair_translation_m,
                &self.per_pair_rotation_deg,
                pnp_report.as_ref(),
                source,
                &self.config,
            );
            let rotation_vector_rescued = rescue_rotation_vector(
                &mut relative_pose,
                &self.per_pair_translation_m,
                &self.per_pair_rotation_vectors,
                pnp_report.as_ref(),
                source,
                &self.config,
            );
            self.kabsch_inlier_counts.push(inlier_count);
            let translation_m = relative_pose.world_to_camera.translation.norm();
            let rotation_deg = relative_rotation_angle_deg(&relative_pose);
            let rotation_vector = relative_pose.world_to_camera.rotation.scaled_axis();
            self.per_pair_translation_m.push(translation_m);
            self.per_pair_raw_translation_m.push(raw_translation_m);
            self.motion_scale_rescue
                .record(raw_translation_m, translation_m);
            self.per_pair_translation_vectors
                .push(relative_pose.world_to_camera.translation);
            self.per_pair_rotation_deg.push(rotation_deg);
            self.per_pair_rotation_vectors.push(rotation_vector);
            self.temporal_matches_per_pair
                .push(temporal_matches.clone());
            self.pair_diagnostics.push(StereoVoPairDiagnostics {
                from_frame: self.poses.len() - 1,
                to_frame: self.poses.len(),
                source,
                temporal_match_count: temporal_matches.len(),
                temporal_row_gate_px,
                temporal_confidence_gate,
                pnp_correspondence_count: pnp_report
                    .as_ref()
                    .map_or_else(|| pnp_corrs_all.len(), |report| report.correspondence_count),
                stereo_pair_correspondence_count: pair_corrs.len(),
                inlier_count,
                raw_translation_m,
                raw_rotation_deg,
                translation_m,
                rotation_deg,
                motion_scale_rescued,
                stereo_vertical_aligned,
                translation_direction_rescued,
                rotation_spike_rescued,
                rotation_vector_rescued,
                pnp_mean_reprojection_error_px,
                kabsch_mean_residual_m,
            });
            let relative = relative_pose.world_to_camera;
            let last = self.poses.last().unwrap();
            Pose {
                world_to_camera: relative.compose(&last.world_to_camera),
            }
        } else {
            Pose::identity()
        };

        self.poses.push(new_pose.clone());
        self.left_features.push(left_features);
        self.right_features.push(right_features);
        self.stereo_per_frame.push(stereo);
        self.stereo_depth_gate_diagnostics
            .push(stereo_depth_gate_diagnostics);
        Ok(new_pose)
    }

    /// Adaptive projection-track search radius in pixels: scales with the
    /// observed median per-pair translation, with a 20 px floor that
    /// covers KITTI's patch-descriptor confusion band even when motion is
    /// small. Returns 25 px when no pairs have been processed yet.
    pub fn adaptive_track_search_radius_px(&self) -> f64 {
        if self.per_pair_translation_m.is_empty() {
            return 25.0;
        }
        let mut sorted = self.per_pair_translation_m.clone();
        sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
        let median = sorted[sorted.len() / 2];
        (12.0 + 2.0 * median).clamp(20.0, 35.0)
    }

    /// Sum of consecutive camera-center deltas in the recovered trajectory
    /// (in metric units).
    pub fn trajectory_length_m(&self) -> f64 {
        let centers: Vec<_> = self.poses.iter().map(|p| p.camera_center_world()).collect();
        centers.windows(2).map(|w| (w[1] - w[0]).norm()).sum()
    }
}

/// The motion-scale rescue's own history: the step lengths it judges
/// against (the rescued ones, except a released streak, whose entries are
/// the raw ones) and its current run of consecutive rescues
/// ([`StereoVoFrontendConfig::motion_scale_rescue_release_full_window`]).
#[derive(Debug, Clone, Default)]
struct MotionScaleRescue {
    history_m: Vec<f64>,
    raw_m: Vec<f64>,
    streak: usize,
}

impl MotionScaleRescue {
    /// Rescues `relative_pose`'s translation magnitude if it collapsed (or
    /// inflated) against the history, unless the rescue has just rescued a
    /// whole window in a row: then the streak is released instead and the
    /// pose is kept. Returns whether the pose was rescued.
    fn apply(
        &mut self,
        relative_pose: &mut Pose,
        pnp_report: Option<&PnpSelectedReport>,
        source: StereoRelativePoseSource,
        config: &StereoVoFrontendConfig,
    ) -> bool {
        let window = config.motion_scale_rescue_min_history;
        let rescued = if config.motion_scale_rescue_release_full_window
            && window > 0
            && self.streak >= window
        {
            // The window holds only the rescue's own outputs: hand the
            // streak back to the estimator's raw step lengths.
            let start = self.history_m.len() - self.streak;
            self.history_m[start..].copy_from_slice(&self.raw_m[start..]);
            false
        } else {
            rescue_collapsed_motion_scale(
                relative_pose,
                &self.history_m,
                pnp_report,
                source,
                config,
            )
        };
        self.streak = if rescued { self.streak + 1 } else { 0 };
        rescued
    }

    /// Records the pair's raw step length and the one it ended with.
    fn record(&mut self, raw_m: f64, final_m: f64) {
        self.raw_m.push(raw_m);
        self.history_m.push(final_m);
    }
}

fn rescue_collapsed_motion_scale(
    relative_pose: &mut Pose,
    translation_history_m: &[f64],
    pnp_report: Option<&PnpSelectedReport>,
    source: StereoRelativePoseSource,
    config: &StereoVoFrontendConfig,
) -> bool {
    if translation_history_m.len() < config.motion_scale_rescue_min_history {
        return false;
    }
    let Some(recent_median) = recent_translation_median(
        translation_history_m,
        config.motion_scale_rescue_min_history,
    ) else {
        return false;
    };
    if recent_median < config.motion_scale_rescue_min_median_translation_m {
        return false;
    }
    let current = relative_pose.world_to_camera.translation.norm();
    if !current.is_finite() || current <= 1.0e-9 {
        return false;
    }
    let collapsed = current < recent_median * config.motion_scale_rescue_min_translation_ratio;
    let inflated = current > recent_median * config.motion_scale_rescue_max_translation_ratio;
    if !collapsed && !inflated {
        return false;
    }
    if !is_weak_motion_scale_consensus(
        pnp_report,
        source,
        config.motion_scale_rescue_max_pnp_inlier_ratio,
    ) {
        return false;
    }
    let target_scale = recent_positive_percentile(
        translation_history_m,
        config.motion_scale_rescue_min_history,
        config.motion_scale_rescue_target_percentile,
    )
    .filter(|target| target.is_finite() && *target > 0.0)
    .unwrap_or(recent_median);
    relative_pose.world_to_camera.translation *= target_scale / current;
    true
}

fn rescue_rotation_spike(
    relative_pose: &mut Pose,
    translation_history_m: &[f64],
    rotation_history_deg: &[f64],
    pnp_report: Option<&PnpSelectedReport>,
    source: StereoRelativePoseSource,
    config: &StereoVoFrontendConfig,
) -> bool {
    if translation_history_m.len() < config.rotation_spike_rescue_min_history
        || rotation_history_deg.len() < config.rotation_spike_rescue_min_history
    {
        return false;
    }
    let Some(recent_translation_median) = recent_translation_median(
        translation_history_m,
        config.rotation_spike_rescue_min_history,
    ) else {
        return false;
    };
    if recent_translation_median < config.rotation_spike_rescue_min_median_translation_m {
        return false;
    }
    if !is_weak_motion_scale_consensus(
        pnp_report,
        source,
        config.rotation_spike_rescue_max_pnp_inlier_ratio,
    ) {
        return false;
    }
    let Some(recent_rotation_median) = recent_positive_median(
        rotation_history_deg,
        config.rotation_spike_rescue_min_history,
    ) else {
        return false;
    };
    let current_deg = relative_rotation_angle_deg(relative_pose);
    if !current_deg.is_finite()
        || current_deg < config.rotation_spike_rescue_min_angle_deg
        || current_deg < recent_rotation_median * config.rotation_spike_rescue_max_angle_ratio
    {
        return false;
    }
    let scaled_axis = relative_pose.world_to_camera.rotation.scaled_axis();
    let current_rad = scaled_axis.norm();
    if !current_rad.is_finite() || current_rad <= 1.0e-12 {
        return false;
    }
    let target_deg = recent_rotation_median.max(1.0e-6);
    let target_axis = scaled_axis * (target_deg.to_radians() / current_rad);
    relative_pose.world_to_camera.rotation = UnitQuaternion::from_scaled_axis(target_axis);
    true
}

fn rescue_rotation_vector(
    relative_pose: &mut Pose,
    translation_history_m: &[f64],
    rotation_vector_history: &[Vector3<f64>],
    pnp_report: Option<&PnpSelectedReport>,
    source: StereoRelativePoseSource,
    config: &StereoVoFrontendConfig,
) -> bool {
    if translation_history_m.len() < config.rotation_vector_rescue_min_history
        || rotation_vector_history.len() < config.rotation_vector_rescue_min_history
    {
        return false;
    }
    let Some(recent_translation_median) = recent_translation_median(
        translation_history_m,
        config.rotation_vector_rescue_min_history,
    ) else {
        return false;
    };
    if recent_translation_median < config.rotation_vector_rescue_min_median_translation_m {
        return false;
    }
    if !is_weak_motion_scale_consensus(
        pnp_report,
        source,
        config.rotation_vector_rescue_max_pnp_inlier_ratio,
    ) {
        return false;
    }
    let Some(recent_vector) = recent_rotation_vector(
        rotation_vector_history,
        config.rotation_vector_rescue_min_history,
    ) else {
        return false;
    };
    let current_vector = relative_pose.world_to_camera.rotation.scaled_axis();
    if !current_vector.iter().all(|v| v.is_finite()) {
        return false;
    }
    let delta_deg = (current_vector - recent_vector).norm().to_degrees();
    if !delta_deg.is_finite() || delta_deg <= config.rotation_vector_rescue_max_delta_deg {
        return false;
    }
    relative_pose.world_to_camera.rotation = UnitQuaternion::from_scaled_axis(recent_vector);
    true
}

fn rescue_translation_direction(
    relative_pose: &mut Pose,
    translation_history_m: &[f64],
    translation_vector_history: &[Vector3<f64>],
    pnp_report: Option<&PnpSelectedReport>,
    source: StereoRelativePoseSource,
    config: &StereoVoFrontendConfig,
) -> bool {
    if translation_history_m.len() < config.translation_direction_rescue_min_history
        || translation_vector_history.len() < config.translation_direction_rescue_min_history
    {
        return false;
    }
    let Some(recent_translation_median) = recent_translation_median(
        translation_history_m,
        config.translation_direction_rescue_min_history,
    ) else {
        return false;
    };
    if recent_translation_median < config.translation_direction_rescue_min_median_translation_m {
        return false;
    }
    if !is_weak_motion_scale_consensus(
        pnp_report,
        source,
        config.translation_direction_rescue_max_pnp_inlier_ratio,
    ) {
        return false;
    }
    let current = relative_pose.world_to_camera.translation;
    let current_norm = current.norm();
    if !current_norm.is_finite() || current_norm <= 1.0e-9 {
        return false;
    }
    let Some(recent_direction) = recent_translation_direction(
        translation_vector_history,
        config.translation_direction_rescue_min_history,
    ) else {
        return false;
    };
    let current_direction = current / current_norm;
    let cos_angle = current_direction.dot(&recent_direction).clamp(-1.0, 1.0);
    let angle_deg = cos_angle.acos().to_degrees();
    if !angle_deg.is_finite() || angle_deg <= config.translation_direction_rescue_max_angle_deg {
        return false;
    }
    relative_pose.world_to_camera.translation = recent_direction * current_norm;
    true
}

// Stereo-pair alignment inputs plus the frontend config; canonical positional
// signature shared in spirit with the other stereo-temporal helpers above.
#[allow(clippy::too_many_arguments)]
fn align_vertical_translation_to_stereo_pairs(
    relative_pose: &mut Pose,
    prev_stereo: &[StereoFeature],
    current_stereo: &[StereoFeature],
    prev_left: &FeatureSet,
    current_left: &FeatureSet,
    temporal_matches: &[DescriptorMatch],
    camera: &Camera,
    config: &StereoVoFrontendConfig,
) -> bool {
    if !config.stereo_vertical_alignment
        || temporal_matches.len() < config.stereo_vertical_alignment_min_pairs
        || !config
            .stereo_vertical_alignment_max_correction_m
            .is_finite()
        || config.stereo_vertical_alignment_max_correction_m <= 0.0
    {
        return false;
    }
    let rotation = relative_pose.world_to_camera.rotation;
    let current_ty = relative_pose.world_to_camera.translation.y;
    let prev_lookup: HashMap<usize, &StereoFeature> =
        prev_stereo.iter().map(|f| (f.left_index, f)).collect();
    let current_lookup: HashMap<usize, &StereoFeature> =
        current_stereo.iter().map(|f| (f.left_index, f)).collect();
    let lower_row = camera.height as f64 * 0.55;
    let mut residuals = Vec::with_capacity(temporal_matches.len());
    for m in temporal_matches {
        let (Some(prev), Some(curr)) = (
            prev_lookup.get(&m.query_index),
            current_lookup.get(&m.train_index),
        ) else {
            continue;
        };
        let (Some(prev_kp), Some(curr_kp)) = (
            prev_left.keypoints.get(m.query_index),
            current_left.keypoints.get(m.train_index),
        ) else {
            continue;
        };
        if prev_kp.y < lower_row || curr_kp.y < lower_row {
            continue;
        }
        if prev.point_cam.z > 45.0
            || curr.point_cam.z > 45.0
            || prev.point_cam.y < -0.5
            || curr.point_cam.y < -0.5
            || !prev.point_cam.coords.iter().all(|v| v.is_finite())
            || !curr.point_cam.coords.iter().all(|v| v.is_finite())
        {
            continue;
        }
        let rotated = rotation.transform_point(&prev.point_cam);
        let residual_y = curr.point_cam.y - (rotated.y + current_ty);
        if residual_y.is_finite() {
            residuals.push(residual_y);
        }
    }
    if residuals.len() < config.stereo_vertical_alignment_min_pairs {
        return false;
    }
    align_vertical_translation_from_residuals(
        relative_pose,
        residuals,
        config.stereo_vertical_alignment_max_correction_m,
    )
}

fn align_vertical_translation_from_residuals(
    relative_pose: &mut Pose,
    mut residuals: Vec<f64>,
    max_correction_m: f64,
) -> bool {
    residuals.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let correction = residuals[residuals.len() / 2].clamp(-max_correction_m, max_correction_m);
    if correction.abs() <= 1.0e-6 {
        return false;
    }
    relative_pose.world_to_camera.translation.y += correction;
    true
}

fn should_refine_current_stereo_pose(
    translation_history_m: &[f64],
    pnp_report: Option<&PnpSelectedReport>,
    source: StereoRelativePoseSource,
    config: &StereoVoFrontendConfig,
) -> bool {
    if config.stereo_pose_refinement {
        return true;
    }
    if translation_history_m.len() < config.stereo_pose_refinement_auto_min_history {
        return false;
    }
    let Some(recent_median) = recent_translation_median(
        translation_history_m,
        config.stereo_pose_refinement_auto_min_history,
    ) else {
        return false;
    };
    if recent_median < config.stereo_pose_refinement_auto_min_median_translation_m {
        return false;
    }
    is_weak_motion_scale_consensus(
        pnp_report,
        source,
        config.stereo_pose_refinement_auto_max_pnp_inlier_ratio,
    )
}

fn recent_translation_median(history: &[f64], window: usize) -> Option<f64> {
    recent_positive_median(history, window)
}

fn recent_positive_median(history: &[f64], window: usize) -> Option<f64> {
    recent_positive_percentile(history, window, 0.5)
}

fn recent_positive_percentile(history: &[f64], window: usize, percentile: f64) -> Option<f64> {
    if history.is_empty() || window == 0 {
        return None;
    }
    let start = history.len().saturating_sub(window);
    let mut values = history[start..]
        .iter()
        .copied()
        .filter(|v| v.is_finite() && *v > 0.0)
        .collect::<Vec<_>>();
    if values.is_empty() {
        return None;
    }
    values.sort_by(|a, b| a.partial_cmp(b).unwrap());
    let clamped = if percentile.is_finite() {
        percentile.clamp(0.0, 1.0)
    } else {
        0.5
    };
    let index = ((values.len() - 1) as f64 * clamped).round() as usize;
    Some(values[index])
}

fn relative_rotation_angle_deg(relative_pose: &Pose) -> f64 {
    relative_pose.world_to_camera.rotation.angle().to_degrees()
}

fn recent_translation_direction(history: &[Vector3<f64>], window: usize) -> Option<Vector3<f64>> {
    if history.is_empty() || window == 0 {
        return None;
    }
    let start = history.len().saturating_sub(window);
    let mut sum = Vector3::zeros();
    let mut count = 0usize;
    for t in &history[start..] {
        let norm = t.norm();
        if norm.is_finite() && norm > 1.0e-9 {
            sum += *t / norm;
            count += 1;
        }
    }
    if count == 0 {
        return None;
    }
    let norm = sum.norm();
    if !norm.is_finite() || norm <= 1.0e-9 {
        return None;
    }
    Some(sum / norm)
}

fn recent_rotation_vector(history: &[Vector3<f64>], window: usize) -> Option<Vector3<f64>> {
    if history.is_empty() || window == 0 {
        return None;
    }
    let start = history.len().saturating_sub(window);
    let mut sum = Vector3::zeros();
    let mut count = 0usize;
    for v in &history[start..] {
        if v.iter().all(|x| x.is_finite()) {
            sum += *v;
            count += 1;
        }
    }
    if count == 0 {
        return None;
    }
    let mean = sum / count as f64;
    if mean.iter().all(|v| v.is_finite()) {
        Some(mean)
    } else {
        None
    }
}

fn is_weak_motion_scale_consensus(
    pnp_report: Option<&PnpSelectedReport>,
    source: StereoRelativePoseSource,
    max_pnp_inlier_ratio: f64,
) -> bool {
    if source != StereoRelativePoseSource::Pnp {
        return true;
    }
    let Some(report) = pnp_report else {
        return true;
    };
    if report.correspondence_count == 0 {
        return true;
    }
    let ratio = report.inlier_count as f64 / report.correspondence_count as f64;
    ratio < max_pnp_inlier_ratio
}

#[cfg(test)]
// Tests build large `*Config` fixtures by tweaking a handful of fields off
// `Default::default()`; field-by-field assignment reads more clearly than a
// struct-update literal here and keeps each gate's relevant knobs together.
#[allow(clippy::field_reassign_with_default)]
mod tests {
    use super::*;
    use crate::features::FeatureSet;
    use crate::matching::{BruteForceMatcher, DescriptorMatch, Matcher};
    use nalgebra::{Point2, UnitQuaternion, Vector3};
    use visloc_core::geometry::{Pose, SE3};

    fn camera() -> Camera {
        Camera::pinhole(1, 1241, 376, 718.856, 718.856, 607.193, 185.216)
    }

    #[test]
    fn default_rescue_config_keeps_adopted_guardrails() {
        let config = StereoVoFrontendConfig::default();
        assert!(matches!(
            config.stereo.depth_gate,
            StereoDepthGate::Adaptive(_)
        ));
        assert_eq!(config.motion_scale_rescue_min_history, 20);
        assert_eq!(config.motion_scale_rescue_min_median_translation_m, 1.5);
        assert_eq!(config.motion_scale_rescue_min_translation_ratio, 0.97);
        assert_eq!(config.motion_scale_rescue_max_translation_ratio, 1.6);
        assert_eq!(config.motion_scale_rescue_target_percentile, 0.75);
        assert_eq!(config.motion_scale_rescue_max_pnp_inlier_ratio, 1.05);
        assert_eq!(config.translation_direction_rescue_min_history, 20);
        assert_eq!(
            config.translation_direction_rescue_min_median_translation_m,
            1.5
        );
        assert_eq!(config.translation_direction_rescue_max_angle_deg, 10.0);
        assert_eq!(
            config.translation_direction_rescue_max_pnp_inlier_ratio,
            0.45
        );
        assert_eq!(config.rotation_spike_rescue_min_history, 20);
        assert_eq!(config.rotation_spike_rescue_min_angle_deg, 1.0);
        assert_eq!(config.rotation_spike_rescue_max_angle_ratio, 3.0);
        assert_eq!(config.rotation_vector_rescue_min_history, 20);
        assert_eq!(config.rotation_vector_rescue_max_delta_deg, 0.4);
        assert_eq!(config.rotation_vector_rescue_max_pnp_inlier_ratio, 0.45);
        assert_eq!(config.pnp_kabsch_challenge_max_inlier_ratio, 0.0);
        assert_eq!(config.pnp_kabsch_challenge_min_3d_inlier_gain, 8);
        assert_eq!(config.pnp_kabsch_challenge_max_residual_ratio, 0.85);
        assert!(!config.stereo_vertical_alignment);
        assert_eq!(config.stereo_vertical_alignment_min_pairs, 80);
        assert_eq!(config.stereo_vertical_alignment_max_correction_m, 0.25);
        assert_eq!(config.stereo_pose_refinement_auto_min_history, 20);
        assert_eq!(config.stereo_pose_refinement_auto_max_pnp_inlier_ratio, 1.0);
        assert_eq!(config.temporal_max_row_delta_px, None);
        assert_eq!(config.temporal_auto_max_row_delta_px, None);
        assert_eq!(config.temporal_auto_min_history, 20);
        assert_eq!(config.temporal_auto_min_median_translation_m, 1.05);
        assert_eq!(config.temporal_auto_min_confidence, Some(0.20));
        assert_eq!(config.temporal_auto_confidence_min_history, 20);
        assert_eq!(
            config.temporal_auto_confidence_min_median_translation_m,
            1.45
        );
        assert_eq!(
            config.temporal_auto_confidence_curve_min_median_translation_m,
            Some(0.95)
        );
        assert_eq!(
            config.temporal_auto_confidence_curve_min_median_rotation_deg,
            Some(0.26)
        );
        assert_eq!(
            config.temporal_auto_confidence_max_median_rotation_deg,
            Some(0.45)
        );
    }

    #[test]
    fn fixed_depth_gate_preserves_legacy_min_depth_behavior() {
        let camera = camera();
        let baseline = 0.5;
        let (left, right) = stereo_feature_sets_for_depths(&camera, baseline, &[1.5, 1.7, 2.0]);
        let stereo = triangulate_stereo_features(
            &left,
            &right,
            &camera,
            baseline,
            &StereoFeatureConfig {
                depth_gate: StereoDepthGate::fixed(),
                ratio: None,
                ..StereoFeatureConfig::default()
            },
        );
        assert!(
            stereo.is_empty(),
            "fixed 3 m min-depth gate should reject room-scale points"
        );
    }

    #[test]
    fn adaptive_depth_gate_lowers_min_depth_for_room_scale_frames() {
        let camera = camera();
        let baseline = 0.5;
        let depths: Vec<f64> = (0..30).map(|i| 1.5 + (i as f64) * 0.02).collect();
        let (left, right) = stereo_feature_sets_for_depths(&camera, baseline, &depths);
        let mut state = StereoDepthGateState::default();
        let outcome = triangulate_stereo_features_with_depth_state(
            &left,
            &right,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
            Some(&mut state),
        );

        assert!(outcome.diagnostics.adaptive);
        assert!(
            outcome.diagnostics.effective_min_depth_m < 3.0,
            "room-scale effective min depth should drop below the legacy 3 m gate, got {}",
            outcome.diagnostics.effective_min_depth_m
        );
        assert_eq!(outcome.features.len(), depths.len());
    }

    #[test]
    fn adaptive_depth_gate_keeps_far_scene_floor_against_near_outlier() {
        let camera = camera();
        let baseline = 0.5;
        let mut depths = vec![0.8];
        depths.extend((0..29).map(|i| 12.0 + (i as f64) * 0.1));
        let (left, right) = stereo_feature_sets_for_depths(&camera, baseline, &depths);
        let outcome = triangulate_stereo_features_with_depth_state(
            &left,
            &right,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
            None,
        );

        assert!(outcome.diagnostics.adaptive);
        assert_eq!(outcome.diagnostics.effective_min_depth_m, 3.0);
        assert_eq!(outcome.features.len(), depths.len() - 1);
        assert!(
            outcome
                .features
                .iter()
                .all(|feature| feature.point_cam.z >= 3.0),
            "near outlier should not pass the hall-scale adaptive gate"
        );
    }

    #[test]
    fn adaptive_depth_gate_hysteresis_keeps_small_updates_stable() {
        let camera = camera();
        let baseline = 0.5;
        let far_depths: Vec<f64> = (0..30).map(|i| 12.0 + (i as f64) * 0.1).collect();
        let (far_left, far_right) = stereo_feature_sets_for_depths(&camera, baseline, &far_depths);
        let mid_depths: Vec<f64> = (0..30).map(|i| 3.35 + (i as f64) * 0.01).collect();
        let (mid_left, mid_right) = stereo_feature_sets_for_depths(&camera, baseline, &mid_depths);
        let mut state = StereoDepthGateState::default();
        let config = StereoFeatureConfig {
            ratio: None,
            ..StereoFeatureConfig::default()
        };

        let first = triangulate_stereo_features_with_depth_state(
            &far_left,
            &far_right,
            &camera,
            baseline,
            &config,
            Some(&mut state),
        );
        let second = triangulate_stereo_features_with_depth_state(
            &mid_left,
            &mid_right,
            &camera,
            baseline,
            &config,
            Some(&mut state),
        );

        assert_eq!(first.diagnostics.effective_min_depth_m, 3.0);
        assert_eq!(
            second.diagnostics.effective_min_depth_m, 3.0,
            "mid-scale proposal is inside the hysteresis band and should keep the prior gate"
        );
    }

    #[test]
    fn temporal_row_gate_prefers_explicit_override() {
        let mut config = StereoVoFrontendConfig::default();
        config.temporal_max_row_delta_px = Some(4.0);
        config.temporal_auto_max_row_delta_px = Some(8.0);
        config.temporal_auto_min_history = 3;
        config.temporal_auto_min_median_translation_m = 10.0;
        assert_eq!(
            effective_temporal_max_row_delta_px(&[0.1, 0.2, 0.3], &config),
            Some(4.0)
        );
    }

    #[test]
    fn temporal_row_gate_activates_only_for_fast_recent_motion() {
        let mut config = StereoVoFrontendConfig::default();
        config.temporal_max_row_delta_px = None;
        config.temporal_auto_max_row_delta_px = Some(8.0);
        config.temporal_auto_min_history = 3;
        config.temporal_auto_min_median_translation_m = 0.9;

        assert_eq!(
            effective_temporal_max_row_delta_px(&[0.8, 0.85], &config),
            None
        );
        assert_eq!(
            effective_temporal_max_row_delta_px(&[0.7, 0.8, 0.85], &config),
            None
        );
        assert_eq!(
            effective_temporal_max_row_delta_px(&[0.7, 0.95, 1.1], &config),
            Some(8.0)
        );
    }

    #[test]
    fn temporal_confidence_gate_activates_only_for_fast_recent_motion() {
        let mut config = StereoVoFrontendConfig::default();
        config.temporal_auto_min_confidence = Some(0.20);
        config.temporal_auto_confidence_min_history = 3;
        config.temporal_auto_confidence_min_median_translation_m = 0.8;

        assert_eq!(
            effective_temporal_min_confidence(&[0.7, 0.75], &[0.2, 0.2], &config),
            None
        );
        assert_eq!(
            effective_temporal_min_confidence(&[0.65, 0.7, 0.75], &[0.2, 0.2, 0.2], &config),
            None
        );
        assert_eq!(
            effective_temporal_min_confidence(&[0.7, 0.85, 0.9], &[0.2, 0.2, 0.2], &config),
            Some(0.20)
        );
        assert_eq!(
            effective_temporal_min_confidence(&[0.7, 0.85, 0.9], &[0.6, 0.7, 0.8], &config),
            None
        );
    }

    #[test]
    fn temporal_confidence_gate_activates_for_medium_curved_motion() {
        let mut config = StereoVoFrontendConfig::default();
        config.temporal_auto_min_confidence = Some(0.20);
        config.temporal_auto_confidence_min_history = 3;
        config.temporal_auto_confidence_min_median_translation_m = 1.5;
        config.temporal_auto_confidence_curve_min_median_translation_m = Some(0.9);
        config.temporal_auto_confidence_curve_min_median_rotation_deg = Some(0.18);
        config.temporal_auto_confidence_max_median_rotation_deg = Some(0.45);

        assert_eq!(
            effective_temporal_min_confidence(&[0.8, 0.95, 1.0], &[0.15, 0.16, 0.17], &config),
            None
        );
        assert_eq!(
            effective_temporal_min_confidence(&[0.8, 0.95, 1.0], &[0.18, 0.22, 0.24], &config),
            Some(0.20)
        );
        assert_eq!(
            effective_temporal_min_confidence(&[0.8, 0.95, 1.0], &[0.4, 0.5, 0.6], &config),
            None
        );
    }

    #[test]
    fn temporal_confidence_filter_preserves_matchers_without_confidence() {
        let matches = vec![
            DescriptorMatch {
                query_index: 0,
                train_index: 1,
                distance: 0.1,
                second_best_distance: None,
                ratio: None,
                confidence: None,
            },
            DescriptorMatch {
                query_index: 2,
                train_index: 3,
                distance: 0.2,
                second_best_distance: None,
                ratio: None,
                confidence: None,
            },
        ];

        assert_eq!(
            filter_temporal_matches_by_confidence(&matches, 0.20),
            matches
        );
    }

    #[test]
    fn temporal_confidence_filter_drops_low_confidence_deep_matches() {
        let matches = vec![
            DescriptorMatch {
                query_index: 0,
                train_index: 1,
                distance: 0.1,
                second_best_distance: None,
                ratio: None,
                confidence: Some(0.19),
            },
            DescriptorMatch {
                query_index: 2,
                train_index: 3,
                distance: 0.2,
                second_best_distance: None,
                ratio: None,
                confidence: Some(0.20),
            },
        ];

        let filtered = filter_temporal_matches_by_confidence(&matches, 0.20);

        assert_eq!(filtered.len(), 1);
        assert_eq!(filtered[0].query_index, 2);
    }

    #[test]
    fn stereo_vertical_alignment_uses_median_y_residual_only() {
        let mut config = StereoVoFrontendConfig::default();
        config.stereo_vertical_alignment = true;
        config.stereo_vertical_alignment_min_pairs = 3;
        config.stereo_vertical_alignment_max_correction_m = 0.25;
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.5, 0.0, -1.0)),
        };
        assert!(align_vertical_translation_from_residuals(
            &mut pose,
            vec![0.2, 0.2, 0.2],
            config.stereo_vertical_alignment_max_correction_m,
        ));
        assert!((pose.world_to_camera.translation.x - 0.5).abs() < 1.0e-12);
        assert!((pose.world_to_camera.translation.y - 0.2).abs() < 1.0e-12);
        assert!((pose.world_to_camera.translation.z + 1.0).abs() < 1.0e-12);
    }

    #[test]
    fn stereo_vertical_alignment_clamps_large_corrections() {
        let mut config = StereoVoFrontendConfig::default();
        config.stereo_vertical_alignment = true;
        config.stereo_vertical_alignment_min_pairs = 3;
        config.stereo_vertical_alignment_max_correction_m = 0.25;
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::zeros()),
        };
        assert!(align_vertical_translation_from_residuals(
            &mut pose,
            vec![1.0, 1.0, 1.0],
            config.stereo_vertical_alignment_max_correction_m,
        ));
        assert!((pose.world_to_camera.translation.y - 0.25).abs() < 1.0e-12);
    }

    #[test]
    fn weak_pnp_triggers_kabsch_challenger_only_below_ratio_gate() {
        let mut config = StereoVoFrontendConfig::default();
        config.pnp_kabsch_challenge_max_inlier_ratio = 0.20;
        let weak = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 19,
            correspondence_count: 100,
            mean_reprojection_error: 1.0,
        };
        let strong = PnpSelectedReport {
            inlier_count: 20,
            ..weak.clone()
        };

        assert!(should_try_kabsch_challenger(&weak, &config));
        assert!(!should_try_kabsch_challenger(&strong, &config));
    }

    #[test]
    fn kabsch_challenger_needs_inlier_gain_and_residual_gain() {
        let config = StereoVoFrontendConfig::default();
        let pnp_score = Pose3d3dScore {
            inlier_count: 20,
            mean_residual_m: 1.0,
        };
        let better = KabschRansacReport {
            relative_pose: Pose::identity(),
            inliers: (0..30).collect(),
            mean_residual_m: 0.7,
        };
        let too_few_extra_inliers = KabschRansacReport {
            inliers: (0..27).collect(),
            ..better.clone()
        };
        let too_noisy = KabschRansacReport {
            mean_residual_m: 0.9,
            ..better.clone()
        };

        assert!(is_kabsch_challenger_better(&better, pnp_score, &config));
        assert!(!is_kabsch_challenger_better(
            &too_few_extra_inliers,
            pnp_score,
            &config
        ));
        assert!(!is_kabsch_challenger_better(&too_noisy, pnp_score, &config));
    }

    /// Project a world-frame point through `pose` and the camera. Used by
    /// the round-trip test below.
    fn project(camera: &Camera, pose: &Pose, x_world: &Point3<f64>) -> Point2<f64> {
        let xc = pose.transform_world_point(x_world);
        camera.project(&xc).expect("point in front of camera")
    }

    /// Build a synthetic FeatureSet at the given pixel locations. Each
    /// keypoint gets a 1-D descriptor encoding its `landmark id`, so a
    /// brute-force matcher can recover the unique correspondence.
    fn synthetic_feature_set(keypoints: &[(usize, Point2<f64>)]) -> FeatureSet {
        let kps: Vec<Point2<f64>> = keypoints.iter().map(|(_, p)| *p).collect();
        let descriptors: Vec<Vec<f32>> = keypoints.iter().map(|(id, _)| vec![*id as f32]).collect();
        FeatureSet::new(kps, descriptors).expect("synthetic FeatureSet")
    }

    fn stereo_feature_sets_for_depths(
        camera: &Camera,
        baseline: f64,
        depths: &[f64],
    ) -> (FeatureSet, FeatureSet) {
        let (fx, _, _, _) = camera.intrinsics().unwrap();
        let pose = Pose::identity();
        let mut left_kps = Vec::with_capacity(depths.len());
        let mut right_kps = Vec::with_capacity(depths.len());
        for (id, depth) in depths.iter().copied().enumerate() {
            let x = ((id % 7) as f64 - 3.0) * 0.04;
            let y = ((id / 7) as f64 - 2.0) * 0.03;
            let point = Point3::new(x, y, depth);
            let left = project(camera, &pose, &point);
            let right = Point2::new(left.x - fx * baseline / depth, left.y);
            left_kps.push((id, left));
            right_kps.push((id, right));
        }
        (
            synthetic_feature_set(&left_kps),
            synthetic_feature_set(&right_kps),
        )
    }

    fn descriptor_match(query_index: usize, train_index: usize) -> DescriptorMatch {
        DescriptorMatch {
            query_index,
            train_index,
            distance: 0.0,
            second_best_distance: None,
            ratio: None,
            confidence: Some(0.95),
        }
    }

    #[test]
    fn triangulate_stereo_features_round_trips_metric_points() {
        let camera = camera();
        let baseline = 0.537150888;
        let (fx, _, _, _) = camera.intrinsics().unwrap();
        // Choose a few world-frame points in front of the camera.
        let truth: Vec<(usize, Point3<f64>)> = vec![
            (0, Point3::new(-1.5, 0.2, 12.0)),
            (1, Point3::new(0.5, -0.4, 8.0)),
            (2, Point3::new(2.0, 0.0, 25.0)),
            (3, Point3::new(-0.5, 0.5, 5.0)),
        ];
        let pose = Pose::identity();
        let mut left_kps: Vec<(usize, Point2<f64>)> = Vec::new();
        let mut right_kps: Vec<(usize, Point2<f64>)> = Vec::new();
        for (id, p) in &truth {
            let l = project(&camera, &pose, p);
            // Right pixel: apply `u_r = u_l − fx · b / Z`, same row.
            let right = Point2::new(l.x - fx * baseline / p.z, l.y);
            left_kps.push((*id, l));
            right_kps.push((*id, right));
        }
        let left = synthetic_feature_set(&left_kps);
        let right = synthetic_feature_set(&right_kps);
        let stereo = triangulate_stereo_features(
            &left,
            &right,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
        );
        assert_eq!(stereo.len(), truth.len());
        for f in &stereo {
            // The "id" field is the same for left and right since we made
            // the descriptor encode it; verify the matcher actually paired
            // by id and that the recovered point matches truth.
            let id = left.descriptors[f.left_index][0] as usize;
            let expected = truth.iter().find(|(i, _)| *i == id).unwrap().1;
            let err = (f.point_cam - expected).norm();
            assert!(err < 1.0e-9, "stereo triangulation error {err} for id {id}");
        }
    }

    #[test]
    fn triangulate_stereo_features_rejects_row_mismatched_pairs() {
        let camera = camera();
        let baseline = 0.5;
        // Row mismatch by 5 px should be rejected (default max 1.5 px).
        let left = synthetic_feature_set(&[(0, Point2::new(700.0, 200.0))]);
        let right = synthetic_feature_set(&[(0, Point2::new(680.0, 205.0))]);
        let stereo = triangulate_stereo_features(
            &left,
            &right,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
        );
        assert!(stereo.is_empty(), "row-mismatched pair must be rejected");
    }

    #[test]
    fn triangulate_stereo_features_rejects_far_field_points() {
        let camera = camera();
        let baseline = 0.5;
        // Disparity = 0.4 < default 1.0 px threshold.
        let left = synthetic_feature_set(&[(0, Point2::new(700.0, 200.0))]);
        let right = synthetic_feature_set(&[(0, Point2::new(699.6, 200.0))]);
        let stereo = triangulate_stereo_features(
            &left,
            &right,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
        );
        assert!(
            stereo.is_empty(),
            "sub-threshold disparity must be rejected"
        );
    }

    #[test]
    fn triangulate_stereo_feature_matches_uses_explicit_pairs() {
        let camera = camera();
        let baseline = 0.5;
        let left = FeatureSet::new(vec![Point2::new(700.0, 200.0)], vec![vec![0.0]]).unwrap();
        let right = FeatureSet::new(
            vec![Point2::new(699.0, 210.0), Point2::new(670.0, 200.0)],
            vec![vec![0.0], vec![0.0]],
        )
        .unwrap();
        let matches = vec![descriptor_match(0, 1), descriptor_match(0, 0)];

        let stereo = triangulate_stereo_feature_matches(
            &left,
            &right,
            &matches,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
        );

        assert_eq!(stereo.len(), 1);
        assert_eq!(stereo[0].left_index, 0);
        assert_eq!(stereo[0].right_index, 1);
        assert!((stereo[0].disparity - 30.0).abs() < 1.0e-9);
    }

    #[test]
    fn build_stereo_temporal_correspondences_links_3d_with_b_pixels() {
        // Three triangulated stereo features in frame A, and a temporal
        // matcher that pairs each one with a known frame-B pixel.
        let a_features = vec![
            StereoFeature {
                left_index: 5,
                right_index: 6,
                disparity: 10.0,
                point_cam: Point3::new(0.0, 0.0, 5.0),
            },
            StereoFeature {
                left_index: 7,
                right_index: 8,
                disparity: 5.0,
                point_cam: Point3::new(1.0, 0.5, 10.0),
            },
            StereoFeature {
                left_index: 9,
                right_index: 10,
                disparity: 4.0,
                point_cam: Point3::new(-2.0, 0.5, 15.0),
            },
        ];
        let b_left = synthetic_feature_set(&[
            (0, Point2::new(100.0, 100.0)),
            (1, Point2::new(200.0, 200.0)),
            (2, Point2::new(300.0, 300.0)),
        ]);
        let temporal_matches = vec![
            DescriptorMatch {
                query_index: 5,
                train_index: 0,
                distance: 0.1,
                second_best_distance: None,
                ratio: None,
                confidence: None,
            },
            DescriptorMatch {
                query_index: 7,
                train_index: 1,
                distance: 0.1,
                second_best_distance: None,
                ratio: None,
                confidence: None,
            },
            // This match's query index has no triangulation in A → drop.
            DescriptorMatch {
                query_index: 99,
                train_index: 2,
                distance: 0.1,
                second_best_distance: None,
                ratio: None,
                confidence: None,
            },
        ];
        let pairs = build_stereo_temporal_correspondences(&a_features, &b_left, &temporal_matches);
        assert_eq!(pairs.len(), 2);
        assert_eq!(pairs[0].point2d, Point2::new(100.0, 100.0));
        assert_eq!(pairs[0].point3d, Point3::new(0.0, 0.0, 5.0));
        assert_eq!(pairs[1].point2d, Point2::new(200.0, 200.0));
        assert_eq!(pairs[1].point3d, Point3::new(1.0, 0.5, 10.0));
    }

    #[test]
    fn adaptive_pnp_depth_triggers_only_on_weak_primary_consensus() {
        assert!(!should_try_adaptive_pnp_depth(
            Some(&PnpFullScore {
                inlier_count: 65,
                mean_error: 1.0,
            }),
            100,
            0.65,
        ));
        assert!(should_try_adaptive_pnp_depth(
            Some(&PnpFullScore {
                inlier_count: 64,
                mean_error: 1.0,
            }),
            100,
            0.65,
        ));
        assert!(should_try_adaptive_pnp_depth(None, 100, 0.65));
        assert!(!should_try_adaptive_pnp_depth(None, 0, 0.65));
        assert!(!should_try_adaptive_pnp_depth(
            Some(&PnpFullScore {
                inlier_count: 1,
                mean_error: 1.0,
            }),
            100,
            f64::NAN,
        ));
    }

    /// A vehicle that cruises at 2 m/frame, then slows to 1 m/frame, through
    /// the motion-scale rescue with the default settings (every PnP pose
    /// counts as weak consensus). Returns the steps the frontend keeps.
    fn decelerate_through_rescue(release: bool) -> Vec<f64> {
        let config = StereoVoFrontendConfig {
            motion_scale_rescue_release_full_window: release,
            ..StereoVoFrontendConfig::default()
        };
        let mut rescue = MotionScaleRescue::default();
        (0..160)
            .map(|frame| {
                let step = match frame {
                    0..40 => 2.0,
                    40..60 => 2.0 - 0.05 * f64::from(frame - 39),
                    _ => 1.0,
                };
                let mut pose = Pose {
                    world_to_camera: SE3::new(
                        UnitQuaternion::identity(),
                        Vector3::new(0.0, 0.0, step),
                    ),
                };
                rescue.apply(&mut pose, None, StereoRelativePoseSource::Pnp, &config);
                let kept = pose.world_to_camera.translation.norm();
                rescue.record(step, kept);
                kept
            })
            .collect()
    }

    #[test]
    fn rotation_from_orthonormal_matches_from_matrix_and_survives_the_half_turn() {
        // An ordinary rotation: bit-identical to nalgebra's unbounded call.
        let ordinary = UnitQuaternion::from_euler_angles(0.3, -0.2, 1.1)
            .to_rotation_matrix()
            .into_inner();
        let expected = UnitQuaternion::from_matrix(&ordinary);
        let actual = rotation_from_orthonormal(&ordinary);
        assert_eq!(actual.coords.as_slice(), expected.coords.as_slice());

        // The half turn KITTI 01 produced at pair ~326 (column-major). The
        // unbounded projection cycles forever on it; capped, it does not
        // converge, and the matrix itself is returned.
        let half_turn = Matrix3::from_column_slice(&[
            -0.9954361201834596,
            0.0954302396208945,
            0.0,
            0.09543023962089417,
            0.9954361201834596,
            0.0,
            0.0,
            0.0,
            -1.0,
        ]);
        let capped = nalgebra::Rotation3::from_matrix_eps(
            &half_turn,
            f64::EPSILON,
            visloc_core::geometry::ROTATION_FROM_MATRIX_MAX_ITERATIONS,
            nalgebra::Rotation3::identity(),
        );
        assert!((capped.matrix() - half_turn).norm() > 1.0e-6);
        let rotation = rotation_from_orthonormal(&half_turn);
        assert!((rotation.to_rotation_matrix().into_inner() - half_turn).norm() < 1.0e-12);
    }

    #[test]
    fn motion_scale_rescue_releases_after_a_full_window_of_rescues() {
        // Without the release the rescued steps keep the median at the old
        // speed and every slower step is scaled back up, for good.
        let locked = decelerate_through_rescue(false);
        assert!(locked[60..].iter().all(|&step| step > 1.9), "{locked:?}");
        // With it the streak ends after one window (20 pairs), the history
        // takes the raw steps, and the rescue stays off at the new speed.
        let released = decelerate_through_rescue(true);
        let first_kept = (40..160)
            .find(|&frame| (released[frame] - 1.0).abs() < 1e-12)
            .expect("the rescue never released");
        assert!(first_kept <= 62, "released only at frame {first_kept}");
        assert!(
            released[first_kept..]
                .iter()
                .all(|&step| (step - 1.0).abs() < 1e-12),
            "{released:?}"
        );
        // A single collapsed step during the cruise is still rescued.
        let mut rescue = MotionScaleRescue::default();
        let config = StereoVoFrontendConfig::default();
        for _ in 0..30 {
            rescue.record(2.0, 2.0);
        }
        let mut collapsed = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, 0.5)),
        };
        assert!(rescue.apply(&mut collapsed, None, StereoRelativePoseSource::Pnp, &config));
        assert!((collapsed.world_to_camera.translation.norm() - 2.0).abs() < 1e-12);
    }

    #[test]
    fn motion_scale_rescue_requires_fast_history_and_weak_consensus() {
        let mut config = StereoVoFrontendConfig::default();
        config.motion_scale_rescue_min_history = 4;
        config.motion_scale_rescue_min_median_translation_m = 1.5;
        config.motion_scale_rescue_min_translation_ratio = 0.35;
        config.motion_scale_rescue_max_translation_ratio = 1.6;
        config.motion_scale_rescue_max_pnp_inlier_ratio = 0.25;

        let history = [2.2, 2.5, 2.7, 2.6];
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0)),
        };
        assert!(rescue_collapsed_motion_scale(
            &mut pose,
            &history,
            None,
            StereoRelativePoseSource::KabschFallback,
            &config,
        ));
        assert!((pose.world_to_camera.translation.norm() - 2.6).abs() < 1.0e-9);

        let slow_history = [0.6, 0.7, 0.8, 0.7];
        let mut slow_pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0)),
        };
        assert!(!rescue_collapsed_motion_scale(
            &mut slow_pose,
            &slow_history,
            None,
            StereoRelativePoseSource::KabschFallback,
            &config,
        ));

        let strong_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 80,
            correspondence_count: 100,
            mean_reprojection_error: 1.0,
        };
        let mut strong_pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 0.0)),
        };
        assert!(!rescue_collapsed_motion_scale(
            &mut strong_pose,
            &history,
            Some(&strong_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));

        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 20,
            correspondence_count: 100,
            mean_reprojection_error: 1.0,
        };
        let mut inflated_pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(5.0, 0.0, 0.0)),
        };
        assert!(rescue_collapsed_motion_scale(
            &mut inflated_pose,
            &history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!((inflated_pose.world_to_camera.translation.norm() - 2.6).abs() < 1.0e-9);
    }

    #[test]
    fn motion_scale_rescue_uses_configured_target_percentile() {
        let mut config = StereoVoFrontendConfig::default();
        config.motion_scale_rescue_min_history = 5;
        config.motion_scale_rescue_min_median_translation_m = 1.5;
        config.motion_scale_rescue_min_translation_ratio = 0.65;
        config.motion_scale_rescue_target_percentile = 0.75;

        let history = [2.0, 2.1, 2.2, 2.8, 3.0];
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.0, 0.0, 0.0)),
        };
        assert!(rescue_collapsed_motion_scale(
            &mut pose,
            &history,
            None,
            StereoRelativePoseSource::KabschFallback,
            &config,
        ));
        assert!((pose.world_to_camera.translation.norm() - 2.8).abs() < 1.0e-9);
    }

    #[test]
    fn stereo_pose_refinement_auto_requires_fast_history_and_weak_consensus() {
        let mut config = StereoVoFrontendConfig::default();
        config.stereo_pose_refinement = false;
        config.stereo_pose_refinement_auto_min_history = 4;
        config.stereo_pose_refinement_auto_min_median_translation_m = 1.5;
        config.stereo_pose_refinement_auto_max_pnp_inlier_ratio = 0.65;
        let history = [1.9, 2.0, 2.1, 2.2];
        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 12,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        assert!(should_refine_current_stereo_pose(
            &history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));

        let strong_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 32,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        assert!(!should_refine_current_stereo_pose(
            &history,
            Some(&strong_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!(!should_refine_current_stereo_pose(
            &[0.6, 0.7, 0.8, 0.9],
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!(should_refine_current_stereo_pose(
            &history,
            Some(&strong_report),
            StereoRelativePoseSource::KabschFallback,
            &config,
        ));

        config.stereo_pose_refinement = true;
        assert!(should_refine_current_stereo_pose(
            &[],
            Some(&strong_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
    }

    #[test]
    fn translation_direction_rescue_requires_fast_history_and_weak_consensus() {
        let mut config = StereoVoFrontendConfig::default();
        config.translation_direction_rescue_min_history = 4;
        config.translation_direction_rescue_min_median_translation_m = 1.5;
        config.translation_direction_rescue_max_angle_deg = 12.0;
        config.translation_direction_rescue_max_pnp_inlier_ratio = 0.45;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let direction_history = [
            Vector3::new(0.0, 0.0, 2.1),
            Vector3::new(0.02, 0.0, 2.2),
            Vector3::new(-0.01, 0.0, 2.3),
            Vector3::new(0.0, 0.0, 2.4),
        ];
        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 10,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
        };
        let original_norm = pose.world_to_camera.translation.norm();
        assert!(rescue_translation_direction(
            &mut pose,
            &translation_history,
            &direction_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!((pose.world_to_camera.translation.norm() - original_norm).abs() < 1.0e-9);
        assert!(pose.world_to_camera.translation.x.abs() < 0.02);
        assert!(pose.world_to_camera.translation.z > 0.0);

        let strong_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 30,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut strong_pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
        };
        assert!(!rescue_translation_direction(
            &mut strong_pose,
            &translation_history,
            &direction_history,
            Some(&strong_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));

        let mut slow_pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
        };
        assert!(!rescue_translation_direction(
            &mut slow_pose,
            &[0.7, 0.8, 0.9, 0.8],
            &direction_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));

        let mut aligned_pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.1, 0.0, 2.0)),
        };
        assert!(!rescue_translation_direction(
            &mut aligned_pose,
            &translation_history,
            &direction_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
    }

    #[test]
    fn translation_direction_rescue_requires_vector_history_window() {
        let mut config = StereoVoFrontendConfig::default();
        config.translation_direction_rescue_min_history = 4;
        config.translation_direction_rescue_min_median_translation_m = 1.5;
        config.translation_direction_rescue_max_angle_deg = 10.0;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let short_direction_history = [
            Vector3::new(0.0, 0.0, 2.1),
            Vector3::new(0.0, 0.0, 2.2),
            Vector3::new(0.0, 0.0, 2.3),
        ];
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(1.2, 0.0, 2.0)),
        };
        let before = pose.world_to_camera.translation;

        assert!(!rescue_translation_direction(
            &mut pose,
            &translation_history,
            &short_direction_history,
            None,
            StereoRelativePoseSource::KabschFallback,
            &config,
        ));
        assert_eq!(pose.world_to_camera.translation, before);
    }

    #[test]
    fn translation_direction_rescue_handles_kabsch_fallback_without_pnp_report() {
        let mut config = StereoVoFrontendConfig::default();
        config.translation_direction_rescue_min_history = 4;
        config.translation_direction_rescue_min_median_translation_m = 1.5;
        config.translation_direction_rescue_max_angle_deg = 10.0;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let direction_history = [
            Vector3::new(0.0, 0.0, 2.1),
            Vector3::new(0.0, 0.0, 2.2),
            Vector3::new(0.0, 0.0, 2.3),
            Vector3::new(0.0, 0.0, 2.4),
        ];
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(-1.5, 0.0, 1.5)),
        };
        let original_norm = pose.world_to_camera.translation.norm();

        assert!(rescue_translation_direction(
            &mut pose,
            &translation_history,
            &direction_history,
            None,
            StereoRelativePoseSource::KabschFallback,
            &config,
        ));
        assert!((pose.world_to_camera.translation.norm() - original_norm).abs() < 1.0e-9);
        assert!(pose.world_to_camera.translation.x.abs() < 1.0e-9);
        assert!((pose.world_to_camera.translation.z - original_norm).abs() < 1.0e-9);
    }

    #[test]
    fn translation_direction_rescue_clamps_backward_outlier_but_keeps_magnitude() {
        let mut config = StereoVoFrontendConfig::default();
        config.translation_direction_rescue_min_history = 4;
        config.translation_direction_rescue_min_median_translation_m = 1.5;
        config.translation_direction_rescue_max_angle_deg = 10.0;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let direction_history = [
            Vector3::new(0.0, 0.0, 2.1),
            Vector3::new(0.0, 0.0, 2.2),
            Vector3::new(0.0, 0.0, 2.3),
            Vector3::new(0.0, 0.0, 2.4),
        ];
        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 10,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut pose = Pose {
            world_to_camera: SE3::new(UnitQuaternion::identity(), Vector3::new(0.0, 0.0, -2.4)),
        };

        assert!(rescue_translation_direction(
            &mut pose,
            &translation_history,
            &direction_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!(pose.world_to_camera.translation.x.abs() < 1.0e-9);
        assert!(pose.world_to_camera.translation.y.abs() < 1.0e-9);
        assert!((pose.world_to_camera.translation.z - 2.4).abs() < 1.0e-9);
    }

    #[test]
    fn recent_translation_direction_uses_recent_window_and_ignores_bad_vectors() {
        let history = [
            Vector3::new(3.0, 0.0, 0.0),
            Vector3::new(f64::NAN, 0.0, 0.0),
            Vector3::zeros(),
            Vector3::new(0.0, 0.0, 2.0),
            Vector3::new(0.0, 0.0, 3.0),
        ];
        let direction = recent_translation_direction(&history, 4).expect("recent direction");
        assert!(direction.x.abs() < 1.0e-9);
        assert!(direction.y.abs() < 1.0e-9);
        assert!((direction.z - 1.0).abs() < 1.0e-9);

        assert!(recent_translation_direction(
            &[Vector3::new(1.0, 0.0, 0.0), Vector3::new(-1.0, 0.0, 0.0)],
            2,
        )
        .is_none());
        assert!(recent_translation_direction(&history, 0).is_none());
    }

    #[test]
    fn rotation_spike_rescue_requires_fast_history_and_weak_consensus() {
        let mut config = StereoVoFrontendConfig::default();
        config.rotation_spike_rescue_min_history = 4;
        config.rotation_spike_rescue_min_median_translation_m = 1.5;
        config.rotation_spike_rescue_min_angle_deg = 1.0;
        config.rotation_spike_rescue_max_angle_ratio = 3.0;
        config.rotation_spike_rescue_max_pnp_inlier_ratio = 0.45;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let rotation_history = [0.2, 0.3, 0.4, 0.3];
        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 10,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut pose = Pose {
            world_to_camera: SE3::new(
                UnitQuaternion::from_euler_angles(0.0, 0.0, 3.0_f64.to_radians()),
                Vector3::new(2.0, 0.0, 0.0),
            ),
        };
        assert!(rescue_rotation_spike(
            &mut pose,
            &translation_history,
            &rotation_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!((relative_rotation_angle_deg(&pose) - 0.3).abs() < 1.0e-9);

        let strong_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 30,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut strong_pose = Pose {
            world_to_camera: SE3::new(
                UnitQuaternion::from_euler_angles(0.0, 0.0, 3.0_f64.to_radians()),
                Vector3::new(2.0, 0.0, 0.0),
            ),
        };
        assert!(!rescue_rotation_spike(
            &mut strong_pose,
            &translation_history,
            &rotation_history,
            Some(&strong_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));

        let mut slow_pose = Pose {
            world_to_camera: SE3::new(
                UnitQuaternion::from_euler_angles(0.0, 0.0, 3.0_f64.to_radians()),
                Vector3::new(2.0, 0.0, 0.0),
            ),
        };
        assert!(!rescue_rotation_spike(
            &mut slow_pose,
            &[0.7, 0.8, 0.9, 0.8],
            &rotation_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
    }

    #[test]
    fn rotation_vector_rescue_clamps_weak_rotation_to_recent_trend() {
        let mut config = StereoVoFrontendConfig::default();
        config.rotation_vector_rescue_min_history = 4;
        config.rotation_vector_rescue_min_median_translation_m = 1.5;
        config.rotation_vector_rescue_max_delta_deg = 0.4;
        config.rotation_vector_rescue_max_pnp_inlier_ratio = 0.45;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let rotation_history = [
            Vector3::new(0.0, 0.0, 0.2_f64.to_radians()),
            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
            Vector3::new(0.0, 0.0, 0.4_f64.to_radians()),
            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
        ];
        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 10,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut pose = Pose {
            world_to_camera: SE3::new(
                UnitQuaternion::from_euler_angles(0.0, 0.0, 1.1_f64.to_radians()),
                Vector3::new(2.0, 0.0, 0.0),
            ),
        };

        assert!(rescue_rotation_vector(
            &mut pose,
            &translation_history,
            &rotation_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
        assert!((relative_rotation_angle_deg(&pose) - 0.3).abs() < 1.0e-9);
    }

    #[test]
    fn rotation_vector_rescue_requires_fast_history_and_weak_consensus() {
        let mut config = StereoVoFrontendConfig::default();
        config.rotation_vector_rescue_min_history = 4;
        config.rotation_vector_rescue_min_median_translation_m = 1.5;
        config.rotation_vector_rescue_max_delta_deg = 0.4;
        config.rotation_vector_rescue_max_pnp_inlier_ratio = 0.45;
        let translation_history = [2.1, 2.2, 2.3, 2.4];
        let rotation_history = [
            Vector3::new(0.0, 0.0, 0.2_f64.to_radians()),
            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
            Vector3::new(0.0, 0.0, 0.4_f64.to_radians()),
            Vector3::new(0.0, 0.0, 0.3_f64.to_radians()),
        ];
        let strong_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 30,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut strong_pose = Pose {
            world_to_camera: SE3::new(
                UnitQuaternion::from_euler_angles(0.0, 0.0, 1.1_f64.to_radians()),
                Vector3::new(2.0, 0.0, 0.0),
            ),
        };
        assert!(!rescue_rotation_vector(
            &mut strong_pose,
            &translation_history,
            &rotation_history,
            Some(&strong_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));

        let weak_report = PnpSelectedReport {
            pose: Pose::identity(),
            inlier_count: 10,
            correspondence_count: 40,
            mean_reprojection_error: 1.0,
        };
        let mut slow_pose = Pose {
            world_to_camera: SE3::new(
                UnitQuaternion::from_euler_angles(0.0, 0.0, 1.1_f64.to_radians()),
                Vector3::new(2.0, 0.0, 0.0),
            ),
        };
        assert!(!rescue_rotation_vector(
            &mut slow_pose,
            &[0.7, 0.8, 0.9, 0.8],
            &rotation_history,
            Some(&weak_report),
            StereoRelativePoseSource::Pnp,
            &config,
        ));
    }

    /// 3D-3D Kabsch round-trip: synthesize matched 3D points in two
    /// frames with known relative pose plus 3 outliers, run RANSAC,
    /// confirm pose recovery and outlier rejection.
    #[test]
    fn kabsch_ransac_recovers_metric_pose_and_rejects_outliers() {
        let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.1)
            * UnitQuaternion::from_axis_angle(&Vector3::x_axis(), -0.05);
        let truth_t = Vector3::new(0.3, -0.05, 1.5);
        let r_mat = r.to_rotation_matrix().into_inner();
        let inliers: Vec<Point3<f64>> = vec![
            Point3::new(-1.0, 0.0, 8.0),
            Point3::new(1.5, 0.5, 12.0),
            Point3::new(0.0, -0.3, 6.0),
            Point3::new(2.0, 0.5, 15.0),
            Point3::new(-2.5, -0.4, 10.0),
            Point3::new(0.5, 0.6, 5.0),
            Point3::new(-1.5, 0.2, 9.0),
            Point3::new(1.0, -0.2, 7.0),
            Point3::new(-0.5, 0.0, 11.0),
            Point3::new(2.5, -0.5, 14.0),
            Point3::new(-2.0, 0.4, 8.5),
            Point3::new(0.0, 0.5, 6.5),
        ];
        let mut corrs: Vec<StereoPairCorrespondence> = inliers
            .iter()
            .map(|p| StereoPairCorrespondence {
                a: *p,
                b: Point3::from(r_mat * p.coords + truth_t),
                confidence: None,
            })
            .collect();
        // Three gross outliers (random offsets).
        corrs.push(StereoPairCorrespondence {
            a: Point3::new(0.0, 0.0, 10.0),
            b: Point3::new(8.0, 0.0, 4.0),
            confidence: None,
        });
        corrs.push(StereoPairCorrespondence {
            a: Point3::new(1.0, 0.0, 12.0),
            b: Point3::new(-4.0, 0.0, 6.0),
            confidence: None,
        });
        corrs.push(StereoPairCorrespondence {
            a: Point3::new(0.5, 0.5, 9.0),
            b: Point3::new(0.5, -3.5, 3.0),
            confidence: None,
        });
        let report = estimate_relative_pose_kabsch_ransac(&corrs, &KabschRansacConfig::default())
            .expect("Kabsch RANSAC must succeed on mostly-inlier data");
        let recovered_t = report.relative_pose.world_to_camera.translation;
        assert!(
            (recovered_t - truth_t).norm() < 1.0e-6,
            "translation err {:?}",
            recovered_t,
        );
        let recovered_r = report
            .relative_pose
            .world_to_camera
            .rotation
            .to_rotation_matrix()
            .into_inner();
        assert!(
            (recovered_r - r_mat).norm() < 1.0e-6,
            "rotation err {:?}",
            recovered_r,
        );
        // All 12 inliers should be recovered, the 3 outliers rejected.
        assert!(
            report.inliers.len() >= 12,
            "should keep all inliers: {}",
            report.inliers.len()
        );
        assert!(report.inliers.len() <= 12, "should reject outliers");
    }

    /// `StereoVoFrontend` round-trip on a synthetic 4-frame KITTI-like
    /// stereo sequence. Verifies that (a) the first frame seeds at
    /// identity, (b) the last frame's recovered camera center matches
    /// truth in metric units, and (c) the per-call state collections
    /// stay in lockstep.
    #[test]
    fn stereo_vo_frontend_recovers_synthetic_metric_trajectory() {
        // Pack a synthetic image so CornerFeatureExtractor returns
        // exactly the keypoints / descriptors we want — i.e., construct
        // a frontend that doesn't actually depend on the FAST detector.
        // Simpler path: use the lower-level helpers directly to validate
        // the frontend's state-tracking is correct on synthesized inputs.
        let camera = camera();
        let baseline = 0.537150888;
        let (fx, _, _, _) = camera.intrinsics().unwrap();
        let landmarks: Vec<Point3<f64>> = vec![
            Point3::new(-2.0, 0.5, 12.0),
            Point3::new(1.5, -0.3, 9.0),
            Point3::new(0.0, 0.0, 18.0),
            Point3::new(-1.0, 0.6, 7.0),
            Point3::new(2.0, 0.0, 14.0),
            Point3::new(-3.0, -0.2, 11.0),
        ];
        let mut poses_truth: Vec<Pose> = Vec::new();
        for i in 0..3 {
            let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.03 * i as f64);
            let center = Vector3::new(0.05 * i as f64, 0.0, 1.2 * i as f64);
            poses_truth.push(Pose::from_world_to_camera(
                r,
                -(r.transform_vector(&center)),
            ));
        }
        let mut frontend = StereoVoFrontend::new(
            camera.clone(),
            baseline,
            StereoVoFrontendConfig {
                kabsch: KabschRansacConfig {
                    iterations: 64,
                    inlier_threshold_m: 0.01,
                    min_inliers: 4,
                    max_depth_m: 30.0,
                    seed: 7,
                },
                ..StereoVoFrontendConfig::default()
            },
        );
        // Inject synthetic state directly: skip the image-extractor
        // path (which the test doesn't aim to exercise) and validate
        // only the per-pair Kabsch + composition logic.
        for pose in &poses_truth {
            let mut kps: Vec<Point2<f64>> = Vec::new();
            let mut descs: Vec<Vec<f32>> = Vec::new();
            let mut sf: Vec<StereoFeature> = Vec::new();
            for (id, p) in landmarks.iter().enumerate() {
                let xc = pose.transform_world_point(p);
                let l = camera.project(&xc).unwrap();
                let u_r = l.x - fx * baseline / xc.z;
                let kp_idx = kps.len();
                kps.push(l);
                descs.push(vec![id as f32]);
                sf.push(StereoFeature {
                    left_index: kp_idx,
                    right_index: kp_idx,
                    disparity: l.x - u_r,
                    point_cam: Point3::from(xc.coords),
                });
            }
            let lf = FeatureSet::new(kps.clone(), descs.clone()).unwrap();
            let rf = FeatureSet::new(kps, descs).unwrap();
            // Manually advance frontend state, mimicking process_pair
            // without invoking the FAST extractor on a synthetic image.
            let new_pose = if let (Some(prev_left), Some(prev_stereo)) = (
                frontend.left_features.last(),
                frontend.stereo_per_frame.last(),
            ) {
                let temporal_matches = frontend
                    .matcher
                    .match_descriptors(&prev_left.descriptors, &lf.descriptors);
                let pair_corrs = stereo_pair_correspondences(prev_stereo, &sf, &temporal_matches);
                let report =
                    estimate_relative_pose_kabsch_ransac(&pair_corrs, &frontend.config.kabsch)
                        .expect("kabsch should succeed on synthetic data");
                frontend.kabsch_inlier_counts.push(report.inliers.len());
                frontend
                    .per_pair_translation_m
                    .push(report.relative_pose.world_to_camera.translation.norm());
                frontend
                    .per_pair_translation_vectors
                    .push(report.relative_pose.world_to_camera.translation);
                let relative = report.relative_pose.world_to_camera.clone();
                let last = frontend.poses.last().unwrap();
                Pose {
                    world_to_camera: relative.compose(&last.world_to_camera),
                }
            } else {
                Pose::identity()
            };
            frontend.poses.push(new_pose);
            frontend.left_features.push(lf);
            frontend.right_features.push(rf);
            frontend.stereo_per_frame.push(sf);
        }
        assert_eq!(frontend.frame_count(), 3);
        assert_eq!(frontend.left_features.len(), 3);
        assert_eq!(frontend.stereo_per_frame.len(), 3);
        assert_eq!(frontend.per_pair_translation_m.len(), 2);
        assert_eq!(frontend.per_pair_translation_vectors.len(), 2);
        assert_eq!(frontend.kabsch_inlier_counts.len(), 2);
        for (magnitude, vector) in frontend
            .per_pair_translation_m
            .iter()
            .zip(frontend.per_pair_translation_vectors.iter())
        {
            assert!((vector.norm() - magnitude).abs() < 1.0e-9);
        }
        // Frame 0 should be identity, last-frame center should match truth.
        let center_0 = frontend.poses[0].camera_center_world();
        assert!(center_0.coords.norm() < 1.0e-9);
        let recovered_last = frontend.poses[2].camera_center_world();
        let truth_last = -poses_truth[2]
            .world_to_camera
            .rotation
            .inverse()
            .transform_vector(&poses_truth[2].world_to_camera.translation);
        assert!(
            (recovered_last.coords - truth_last).norm() < 1.0e-6,
            "recovered {recovered_last:?} truth {truth_last:?}",
        );
        // Trajectory length should be ≈ sum of per-pair translations.
        let len_traj = frontend.trajectory_length_m();
        let len_pairs: f64 = frontend.per_pair_translation_m.iter().sum();
        assert!((len_traj - len_pairs).abs() < 1.0e-6);
        // Adaptive search radius respects the floor.
        assert!(frontend.adaptive_track_search_radius_px() >= 20.0);
    }

    #[test]
    fn stereo_vo_frontend_accepts_external_features_and_matches() {
        let camera = camera();
        let baseline = 0.537150888;
        let (fx, _, _, _) = camera.intrinsics().unwrap();
        let landmarks: Vec<Point3<f64>> = vec![
            Point3::new(-2.0, 0.5, 12.0),
            Point3::new(1.5, -0.3, 9.0),
            Point3::new(0.0, 0.0, 18.0),
            Point3::new(-1.0, 0.6, 7.0),
            Point3::new(2.0, 0.0, 14.0),
            Point3::new(-3.0, -0.2, 11.0),
        ];
        let mut poses_truth: Vec<Pose> = Vec::new();
        for i in 0..3 {
            let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.03 * i as f64);
            let center = Vector3::new(0.05 * i as f64, 0.0, 1.2 * i as f64);
            poses_truth.push(Pose::from_world_to_camera(
                r,
                -(r.transform_vector(&center)),
            ));
        }
        let mut frontend = StereoVoFrontend::new(
            camera.clone(),
            baseline,
            StereoVoFrontendConfig {
                kabsch: KabschRansacConfig {
                    iterations: 64,
                    inlier_threshold_m: 0.01,
                    min_inliers: 4,
                    max_depth_m: 30.0,
                    seed: 7,
                },
                relative_pose_mode: StereoRelativePoseMode::KabschThenPnp,
                ..StereoVoFrontendConfig::default()
            },
        );

        for (frame_index, pose) in poses_truth.iter().enumerate() {
            let mut left_keypoints = Vec::new();
            let mut right_keypoints = Vec::new();
            let mut left_descriptors = Vec::new();
            let mut right_descriptors = Vec::new();
            let mut stereo_matches = Vec::new();

            for (id, point_world) in landmarks.iter().enumerate() {
                let point_cam = pose.transform_world_point(point_world);
                let left = camera.project(&point_cam).unwrap();
                let right = Point2::new(left.x - fx * baseline / point_cam.z, left.y);
                left_keypoints.push(left);
                right_keypoints.push(right);
                // All descriptors are deliberately identical. The explicit
                // LightGlue-style matches below, not the internal matcher,
                // are what make this sequence trackable.
                left_descriptors.push(vec![0.0]);
                right_descriptors.push(vec![0.0]);
                stereo_matches.push(descriptor_match(id, id));
            }

            let left_features = FeatureSet::new(left_keypoints, left_descriptors).unwrap();
            let right_features = FeatureSet::new(right_keypoints, right_descriptors).unwrap();
            let temporal_matches = if frame_index == 0 {
                None
            } else {
                Some(
                    (0..landmarks.len())
                        .map(|id| descriptor_match(id, id))
                        .collect::<Vec<_>>(),
                )
            };

            frontend
                .process_feature_pair_with_matches(
                    left_features,
                    right_features,
                    Some(&stereo_matches),
                    temporal_matches.as_deref(),
                )
                .unwrap();
        }

        assert_eq!(frontend.frame_count(), 3);
        assert_eq!(frontend.stereo_per_frame[0].len(), landmarks.len());
        assert_eq!(frontend.pair_diagnostics.len(), 2);
        for diagnostics in &frontend.pair_diagnostics {
            assert_eq!(diagnostics.source, StereoRelativePoseSource::Kabsch);
            assert_eq!(diagnostics.temporal_match_count, landmarks.len());
            assert_eq!(
                diagnostics.stereo_pair_correspondence_count,
                landmarks.len()
            );
        }
        let recovered_last = frontend.poses[2].camera_center_world();
        let truth_last = -poses_truth[2]
            .world_to_camera
            .rotation
            .inverse()
            .transform_vector(&poses_truth[2].world_to_camera.translation);
        assert!(
            (recovered_last.coords - truth_last).norm() < 1.0e-6,
            "recovered {recovered_last:?} truth {truth_last:?}",
        );
    }

    /// Projection-guided extension: synthesize a 4-frame world-frame
    /// trajectory plus 5 fixed world-frame landmarks. Each frame's
    /// FeatureSet contains the projected pixels (left + right with
    /// rectified-stereo offset). Run extension, confirm tracks span all
    /// 4 frames and consume each (frame, kp) at most once.
    #[test]
    fn extend_stereo_tracks_via_projection_finds_long_chains() {
        let camera = camera();
        let baseline = 0.537150888;
        let (fx, _, _, _) = camera.intrinsics().unwrap();
        let landmarks: Vec<Point3<f64>> = vec![
            Point3::new(-2.0, 0.5, 12.0),
            Point3::new(1.5, -0.3, 9.0),
            Point3::new(0.0, 0.0, 18.0),
            Point3::new(-1.0, 0.6, 7.0),
            Point3::new(2.0, 0.0, 14.0),
        ];
        // Forward camera motion of 0.8 m / frame, slight yaw rotation.
        let mut poses: Vec<Pose> = Vec::new();
        for i in 0..4 {
            let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.02 * i as f64);
            let center = Vector3::new(0.0, 0.0, 0.8 * i as f64);
            let t = -(r.transform_vector(&center));
            poses.push(Pose::from_world_to_camera(r, t));
        }
        // Build per-frame FeatureSets and stereo features.
        let mut left_features: Vec<FeatureSet> = Vec::new();
        let mut stereo_per_frame: Vec<Vec<StereoFeature>> = Vec::new();
        for pose in &poses {
            let mut kps: Vec<Point2<f64>> = Vec::new();
            let mut descs: Vec<Vec<f32>> = Vec::new();
            let mut sf: Vec<StereoFeature> = Vec::new();
            for (id, p) in landmarks.iter().enumerate() {
                let xc = pose.transform_world_point(p);
                let l = camera.project(&xc).unwrap();
                let u_r = l.x - fx * baseline / xc.z;
                let kp_idx = kps.len();
                kps.push(l);
                descs.push(vec![id as f32]);
                sf.push(StereoFeature {
                    left_index: kp_idx,
                    right_index: kp_idx,
                    disparity: l.x - u_r,
                    point_cam: Point3::from(xc.coords),
                });
            }
            left_features.push(FeatureSet::new(kps, descs).unwrap());
            stereo_per_frame.push(sf);
        }
        let tracks = extend_stereo_tracks_via_projection(
            &poses,
            &left_features,
            &stereo_per_frame,
            &camera,
            &TrackExtensionConfig::default(),
        );
        // Each landmark should produce exactly one 4-frame track (with
        // deduplication on, the same physical point isn't re-seeded).
        assert_eq!(tracks.len(), 5, "got {} tracks", tracks.len());
        for track in &tracks {
            assert_eq!(track.observations.len(), 4, "track len {:?}", track);
        }
    }

    /// End-to-end PnP round-trip: synthesize a metric scene, triangulate
    /// stereo features at frame A, build correspondences against frame B
    /// (with a known relative pose), run PnP, and verify the recovered
    /// pose matches truth in metric units.
    #[test]
    fn stereo_vo_pnp_round_trips_metric_relative_pose() {
        use crate::pnp::{DltPnP, PoseEstimator};
        let camera = camera();
        let baseline = 0.5;
        let (fx, _, _, _) = camera.intrinsics().unwrap();
        let truth_t_a_to_b = Vector3::new(0.4, 0.0, 1.2);
        let r = UnitQuaternion::from_axis_angle(&Vector3::y_axis(), 0.05);
        let pose_a = Pose::identity();
        let pose_b = Pose::from_world_to_camera(r, -(r.transform_vector(&truth_t_a_to_b)));

        let world_points: Vec<Point3<f64>> = vec![
            Point3::new(-1.0, -0.3, 6.0),
            Point3::new(1.0, 0.3, 8.0),
            Point3::new(0.0, 0.0, 10.0),
            Point3::new(-1.5, 0.2, 4.0),
            Point3::new(2.0, -0.5, 12.0),
            Point3::new(0.5, 0.6, 5.5),
        ];
        let mut left_a: Vec<(usize, Point2<f64>)> = Vec::new();
        let mut right_a: Vec<(usize, Point2<f64>)> = Vec::new();
        let mut left_b: Vec<(usize, Point2<f64>)> = Vec::new();
        for (id, p) in world_points.iter().enumerate() {
            let xa = pose_a.transform_world_point(p);
            let xb = pose_b.transform_world_point(p);
            let la = camera.project(&xa).unwrap();
            let lb = camera.project(&xb).unwrap();
            let ra = Point2::new(la.x - fx * baseline / xa.z, la.y);
            left_a.push((id, la));
            right_a.push((id, ra));
            left_b.push((id, lb));
        }
        let left_a_fs = synthetic_feature_set(&left_a);
        let right_a_fs = synthetic_feature_set(&right_a);
        let left_b_fs = synthetic_feature_set(&left_b);
        let stereo_a = triangulate_stereo_features(
            &left_a_fs,
            &right_a_fs,
            &camera,
            baseline,
            &StereoFeatureConfig {
                ratio: None,
                ..StereoFeatureConfig::default()
            },
        );
        let matcher = BruteForceMatcher { ratio: None };
        let temporal_matches =
            matcher.match_descriptors(&left_a_fs.descriptors, &left_b_fs.descriptors);
        let corrs = build_stereo_temporal_correspondences(&stereo_a, &left_b_fs, &temporal_matches);
        assert_eq!(corrs.len(), world_points.len());
        let estimator = DltPnP::default();
        let recovered = estimator
            .estimate_pose(&corrs, &camera)
            .expect("DLT must succeed on noise-free input");
        // PnP recovers T_a_to_b directly because the 3D points were given
        // in frame-a's camera frame and the 2D pixels are in frame-b.
        let recovered_center = recovered.camera_center_world();
        let truth_center = -(pose_b
            .world_to_camera
            .rotation
            .inverse()
            .transform_vector(&pose_b.world_to_camera.translation));
        let err = (recovered_center.coords - truth_center).norm();
        assert!(
            err < 1.0e-9,
            "stereo VO PnP center error {err}: recovered {recovered_center:?} truth {truth_center:?}"
        );
    }
}