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
//! Lazy-cache layer — port of
//! `Algorithm/IpIpoptCalculatedQuantities.{hpp,cpp}`.
//!
//! Upstream's CQ object exposes ~80 cached quantities (`curr_f`,
//! `curr_grad_f`, `curr_jac_c`, `curr_grad_lag_x`, `curr_compl_*`,
//! `curr_nlp_error`, etc.). All of them are pure derivations from
//! `(x, s, y_c, y_d, z_l, z_u, v_l, v_u)` and the NLP function
//! evaluations.
//!
//! Phase 5 ships the priority subset needed by the KKT layer
//! (Phase 6) and the convergence check / line search (Phase 7).
//! Caching is intentionally deferred — every accessor recomputes its
//! value on each call. Tag-based invalidation lands once the inner
//! loop benchmarks justify the bookkeeping; correctness does not
//! depend on it.
//!
//! All accessors take `&self` and return `Rc<dyn Vector>`. NLP
//! evaluations require a brief `borrow_mut()` on the Nlp handle;
//! callers must not hold an outstanding `borrow()` across an
//! accessor call.
use crate::ipopt_data::IpoptDataHandle;
use crate::ipopt_nlp::IpoptNlp;
use crate::iterates_vector::IteratesVector;
use pounce_common::cached::Cache;
use pounce_common::types::Number;
use pounce_linalg::dense_vector::DenseVector;
use pounce_linalg::{Matrix, SymMatrix, Vector};
use std::cell::RefCell;
use std::rc::Rc;
/// Safety factor on the per-row noise floor of
/// [`IpoptCalculatedQuantities::row_noise_floor`]. The floor prices one
/// component of `x` at `eps · ‖x‖_∞` and passes it through the row at
/// `max_j |a_ij|`; the row's residual accumulates that over all of its
/// nonzeros, and the linear solve's conditioning widens it further, so the
/// bare product is short by a problem-dependent factor. `64` covers a typical
/// sparse row without reaching far enough to swallow a declared magnitude a
/// model could have meant: at the `‖x‖_∞ ~ 1` of a well-posed problem the
/// floor sits near
/// `1.4e-14`, still nine orders under `constr_viol_tol`'s default. Rows it
/// silences fall back on the absolute feasibility test, which is already
/// scale-invariant on a row whose declared magnitude is numerically zero.
///
/// Measured, and not a knife edge: over gh #446's 15 problems plus the
/// infeasibility-detection suites (`false_local_infeasibility`,
/// `infeasible_status_tol_invariance`, `issue_390_nonlinear_equality_scale`),
/// every value from `8` to `1024` gives the same verdicts. `1` is too small —
/// QSCSD1's rows are wide enough that the missing nonzero-count factor still
/// leaves its `2^-53` RHS above the bound — so `64` sits an order of magnitude
/// inside the band from either edge.
const ROW_NOISE_KAPPA: Number = 64.0;
/// Calculated-quantities object. Holds shared handles on data and the
/// NLP; per-quantity caches live in `RefCell`s here.
pub struct IpoptCalculatedQuantities {
data: IpoptDataHandle,
nlp: Rc<RefCell<dyn IpoptNlp>>,
/// Optimality scaling cap from `IpOptErrorConvCheck` defaults.
pub s_max: Number,
/// Damping coefficient for the bound-multiplier complementarity
/// term (`kappa_d` in upstream's RegisterOptions).
pub kappa_d: Number,
/// Correction size for very small slacks (`slack_move` option,
/// default `mach_eps^{3/4}`). Drives `calculate_safe_slack`'s
/// upper cap on the moved bound — port of upstream's `slack_move_`
/// (`IpIpoptCalculatedQuantities.cpp:525`).
pub slack_move: Number,
// Per-iterate caches for the hot accessors used by the KKT solver
// dependency-tag check. Without these the PdFullSpaceSolver sees a
// fresh tag on every solve (each `curr_slack_*` / `curr_sigma_*`
// allocates a new vector with a fresh `TaggedCell`), which forces
// an MA57 refactor on every SOC step even though the matrix data
// is unchanged. Caches are keyed on the input iterate-vector tag
// and survive across calls but are naturally invalidated when the
// outer iterate advances (curr.x bump).
curr_slack_x_l_cache: RefCell<Cache<Rc<dyn Vector>>>,
curr_slack_x_u_cache: RefCell<Cache<Rc<dyn Vector>>>,
curr_slack_s_l_cache: RefCell<Cache<Rc<dyn Vector>>>,
curr_slack_s_u_cache: RefCell<Cache<Rc<dyn Vector>>>,
curr_sigma_x_cache: RefCell<Cache<Rc<dyn Vector>>>,
curr_sigma_s_cache: RefCell<Cache<Rc<dyn Vector>>>,
}
/// Helper: convert `Box<dyn Vector>` to `Rc<dyn Vector>`. Cheap; the
/// box is unwrapped without copying.
fn rc_from(v: Box<dyn Vector>) -> Rc<dyn Vector> {
Rc::from(v)
}
/// Max-norm of `v` after dividing each entry by its per-row scale factor
/// (`max_i |v_i / scale_i|`). `scale == None` means "no row scaling" and
/// returns the plain `v.amax()`; a zero factor for an entry is treated as
/// the identity (no divide) so a degenerate scale never yields infinities.
/// Falls back to `v.amax()` for a non-dense backing — POUNCE is dense-only,
/// so that branch is defensive.
///
/// Public because `pounce-restoration`'s locally-infeasible gates compare a
/// constraint violation against absolute floors (`1e-4` / `1e-3`) and so must
/// measure it in the same user-facing units this produces — see
/// `resto_inner_solver::eval_orig_inf_pr_at_inner_curr`. One definition, so
/// the two call sites cannot drift.
pub fn unscaled_block_amax(v: &dyn Vector, scale: Option<&[Number]>) -> Number {
let Some(s) = scale else {
return v.amax();
};
match v.as_any().downcast_ref::<DenseVector>() {
Some(d) => d
.values()
.iter()
.zip(s.iter())
.map(|(&x, &f)| if f == 0.0 { x.abs() } else { (x / f).abs() })
.fold(0.0, Number::max),
None => v.amax(),
}
}
/// `‖v‖_∞` over the components that clear their own entry of `floor`;
/// components at or below it contribute `0`. Used by
/// [`IpoptCalculatedQuantities::curr_primal_infeasibility_above_noise`], which
/// documents what the floor means.
///
/// A vector that is not dense, is uninitialized, or whose length disagrees
/// with `floor` falls back to the plain `‖v‖_∞` — no floor can be attributed
/// component-wise, and over-reporting the residual is the safe direction.
fn amax_above_floor(v: &dyn Vector, floor: &[Number]) -> Number {
let Some(d) = v.as_any().downcast_ref::<DenseVector>() else {
return v.amax();
};
if !d.is_initialized() {
return v.amax();
}
let values = d.expanded_values();
if values.len() != floor.len() {
return v.amax();
}
values
.iter()
.zip(floor.iter())
.map(|(&x, &f)| if x.abs() > f { x.abs() } else { 0.0 })
.fold(0.0, Number::max)
}
/// Result of [`IpoptCalculatedQuantities::adjusted_trial_bounds`]: the
/// new `x_L / x_U / d_L / d_U` to install on the NLP when one or more
/// trial slacks were corrected by the safe-slack mechanism.
pub struct AdjustedBounds {
/// Total number of slack components corrected across all four blocks.
pub adjusted: usize,
pub x_l: Box<dyn Vector>,
pub x_u: Box<dyn Vector>,
pub d_l: Box<dyn Vector>,
pub d_u: Box<dyn Vector>,
}
impl IpoptCalculatedQuantities {
pub fn new(data: IpoptDataHandle, nlp: Rc<RefCell<dyn IpoptNlp>>) -> Self {
Self {
data,
nlp,
s_max: 100.0,
kappa_d: 1e-5,
slack_move: f64::EPSILON.powf(0.75),
curr_slack_x_l_cache: RefCell::new(Cache::new(1)),
curr_slack_x_u_cache: RefCell::new(Cache::new(1)),
curr_slack_s_l_cache: RefCell::new(Cache::new(1)),
curr_slack_s_u_cache: RefCell::new(Cache::new(1)),
curr_sigma_x_cache: RefCell::new(Cache::new(1)),
curr_sigma_s_cache: RefCell::new(Cache::new(1)),
}
}
pub fn data(&self) -> &IpoptDataHandle {
&self.data
}
pub fn nlp(&self) -> &Rc<RefCell<dyn IpoptNlp>> {
&self.nlp
}
pub(crate) fn curr_iv(&self) -> IteratesVector {
let Some(iv) = self.data.borrow().curr.as_ref().cloned() else {
unreachable!("IpoptCalculatedQuantities: curr iterate not set");
};
iv
}
fn trial_iv(&self) -> IteratesVector {
let Some(iv) = self.data.borrow().trial.as_ref().cloned() else {
unreachable!("IpoptCalculatedQuantities: trial iterate not set");
};
iv
}
// --------------------------------------------------------------
// Slacks: s_L = P_L^T x - x_L, s_U = x_U - P_U^T x.
// Mirror of `CalcSlack_L` / `CalcSlack_U`
// (`IpIpoptCalculatedQuantities.cpp:238-266`).
// --------------------------------------------------------------
fn calc_slack_l_box(p: &dyn Matrix, x: &dyn Vector, x_bound: &dyn Vector) -> Box<dyn Vector> {
let mut result = x_bound.make_new();
result.copy(x_bound);
// result = -1*result + 1*P^T x ⇒ P^T x - x_bound.
p.trans_mult_vector(1.0, x, -1.0, &mut *result);
result
}
fn calc_slack_u_box(p: &dyn Matrix, x: &dyn Vector, x_bound: &dyn Vector) -> Box<dyn Vector> {
let mut result = x_bound.make_new();
result.copy(x_bound);
// result = 1*result + (-1)*P^T x ⇒ x_bound - P^T x.
p.trans_mult_vector(-1.0, x, 1.0, &mut *result);
result
}
/// Floor a freshly computed slack against machine precision and,
/// where it falls below `eps*min(1,mu)`, raise it to a representable
/// positive value, returning the number of corrected components.
/// Faithful port of `IpoptCalculatedQuantities::CalculateSafeSlack`
/// (`IpIpoptCalculatedQuantities.cpp:455-537`): the corrected slack
/// is `min(max(mu/multiplier, s_min), slack_move*max(1,|bound|)+slack)`.
/// `multiplier` and `mu` are taken from the *current* iterate, exactly
/// as upstream does even for trial slacks.
fn calculate_safe_slack(
&self,
slack: &mut dyn Vector,
bound: &dyn Vector,
multiplier: &dyn Vector,
mu: Number,
) -> usize {
if slack.dim() == 0 {
return 0;
}
let min_slack = slack.min();
// s_min = eps * min(1, mu); if mu drove it to 0, keep it strictly
// positive (upstream #212) so the strict `slack < s_min` test and
// the barrier term stay well-defined.
let mut s_min = f64::EPSILON * mu.min(1.0);
if s_min == 0.0 {
s_min = f64::MIN_POSITIVE;
}
if min_slack >= s_min {
return 0;
}
// t = sign(slack - s_min); then collapse to 1 where slack < s_min,
// 0 elsewhere.
let mut t = slack.make_new();
t.copy(&*slack);
t.add_scalar(-s_min);
t.element_wise_sgn();
let mut zero_vec = t.make_new();
zero_vec.set(0.0);
t.element_wise_min(&*zero_vec); // -1 if slack < s_min, else 0
t.scal(-1.0); // 1 if slack < s_min, else 0
let retval = t.asum().round() as usize;
// Clamp the raw slack to be non-negative before forming the target
// (upstream's AW fix for negative slacks producing 0).
slack.element_wise_max(&*zero_vec);
// t2 = max(mu/multiplier, s_min) - slack.
let mut t2 = t.make_new();
let mut s_min_vec = t2.make_new();
s_min_vec.set(s_min);
if mu != 0.0 {
// mu/0 → +inf here, intentionally capped by t_max below.
t2.set(mu);
t2.element_wise_divide(multiplier);
t2.element_wise_max(&*s_min_vec);
} else {
// mu == 0: max(0/multiplier, s_min) is s_min everywhere, but a 0/0
// (zero multiplier at μ=0) would seed the slack target with NaN and
// poison the bound move — pin straight to s_min instead.
t2.copy(&*s_min_vec);
}
t2.axpy(-1.0, &*slack);
// t = max(mu/multiplier, s_min) where flagged, else slack.
t.element_wise_select(&*t2);
t.axpy(1.0, &*slack);
// t_max = slack_move*max(1,|bound|) + slack.
let mut t_max = t2; // reuse buffer
t_max.set(1.0);
let mut abs_bound = bound.make_new();
abs_bound.copy(bound);
abs_bound.element_wise_abs();
t_max.element_wise_max(&*abs_bound);
// t_max = 1.0*slack + slack_move*t_max.
t_max.add_one_vector(1.0, &*slack, self.slack_move);
// new slack = min(target, t_max) where flagged, else slack.
t.element_wise_min(&*t_max);
slack.copy(&*t);
retval
}
/// `calc_slack_l` followed by `calculate_safe_slack`, returning the
/// (floored) slack plus the number of corrected components. The
/// multiplier and `mu` come from the current iterate.
fn safe_slack_l(
&self,
p: &dyn Matrix,
x: &dyn Vector,
bound: &dyn Vector,
multiplier: &dyn Vector,
) -> (Rc<dyn Vector>, usize) {
let mu = self.data.borrow().curr_mu;
let mut result = Self::calc_slack_l_box(p, x, bound);
let n = self.calculate_safe_slack(&mut *result, bound, multiplier, mu);
(rc_from(result), n)
}
fn safe_slack_u(
&self,
p: &dyn Matrix,
x: &dyn Vector,
bound: &dyn Vector,
multiplier: &dyn Vector,
) -> (Rc<dyn Vector>, usize) {
let mu = self.data.borrow().curr_mu;
let mut result = Self::calc_slack_u_box(p, x, bound);
let n = self.calculate_safe_slack(&mut *result, bound, multiplier, mu);
(rc_from(result), n)
}
pub fn curr_slack_x_l(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
{
let cache = self.curr_slack_x_l_cache.borrow();
if let Some(v) = cache.get(&[iv.x.as_tagged()], &[]) {
return v;
}
}
let nlp = self.nlp.borrow();
let (v, _) = self.safe_slack_l(&*nlp.px_l(), &*iv.x, nlp.x_l(), &*iv.z_l);
self.curr_slack_x_l_cache
.borrow_mut()
.add(v.clone(), &[iv.x.as_tagged()], &[]);
v
}
pub fn curr_slack_x_u(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
{
let cache = self.curr_slack_x_u_cache.borrow();
if let Some(v) = cache.get(&[iv.x.as_tagged()], &[]) {
return v;
}
}
let nlp = self.nlp.borrow();
let (v, _) = self.safe_slack_u(&*nlp.px_u(), &*iv.x, nlp.x_u(), &*iv.z_u);
self.curr_slack_x_u_cache
.borrow_mut()
.add(v.clone(), &[iv.x.as_tagged()], &[]);
v
}
pub fn curr_slack_s_l(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
{
let cache = self.curr_slack_s_l_cache.borrow();
if let Some(v) = cache.get(&[iv.s.as_tagged()], &[]) {
return v;
}
}
let nlp = self.nlp.borrow();
let (v, _) = self.safe_slack_l(&*nlp.pd_l(), &*iv.s, nlp.d_l(), &*iv.v_l);
self.curr_slack_s_l_cache
.borrow_mut()
.add(v.clone(), &[iv.s.as_tagged()], &[]);
v
}
pub fn curr_slack_s_u(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
{
let cache = self.curr_slack_s_u_cache.borrow();
if let Some(v) = cache.get(&[iv.s.as_tagged()], &[]) {
return v;
}
}
let nlp = self.nlp.borrow();
let (v, _) = self.safe_slack_u(&*nlp.pd_u(), &*iv.s, nlp.d_u(), &*iv.v_u);
self.curr_slack_s_u_cache
.borrow_mut()
.add(v.clone(), &[iv.s.as_tagged()], &[]);
v
}
pub fn trial_slack_x_l(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mult = self.curr_iv();
let nlp = self.nlp.borrow();
self.safe_slack_l(&*nlp.px_l(), &*iv.x, nlp.x_l(), &*mult.z_l)
.0
}
pub fn trial_slack_x_u(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mult = self.curr_iv();
let nlp = self.nlp.borrow();
self.safe_slack_u(&*nlp.px_u(), &*iv.x, nlp.x_u(), &*mult.z_u)
.0
}
pub fn trial_slack_s_l(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mult = self.curr_iv();
let nlp = self.nlp.borrow();
self.safe_slack_l(&*nlp.pd_l(), &*iv.s, nlp.d_l(), &*mult.v_l)
.0
}
pub fn trial_slack_s_u(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mult = self.curr_iv();
let nlp = self.nlp.borrow();
self.safe_slack_u(&*nlp.pd_u(), &*iv.s, nlp.d_u(), &*mult.v_u)
.0
}
/// Compute the four trial slacks with safe-slack flooring and, if any
/// component was corrected, the adjusted variable bounds that make the
/// trial slacks exactly representable. Port of the bound-adjustment
/// block in `IpoptAlgorithm::AcceptTrialPoint`
/// (`IpIpoptAlg.cpp:664-706`): `new_x_L = Px_L^T x - safe_slack_x_L`,
/// `new_x_U = Px_U^T x + safe_slack_x_U`, likewise for `s`/`d`.
/// Returns `None` when no slack needed correcting.
pub fn adjusted_trial_bounds(&self) -> Option<AdjustedBounds> {
let iv = self.trial_iv();
let mult = self.curr_iv();
let nlp = self.nlp.borrow();
let (s_x_l, n_x_l) = self.safe_slack_l(&*nlp.px_l(), &*iv.x, nlp.x_l(), &*mult.z_l);
let (s_x_u, n_x_u) = self.safe_slack_u(&*nlp.px_u(), &*iv.x, nlp.x_u(), &*mult.z_u);
let (s_s_l, n_s_l) = self.safe_slack_l(&*nlp.pd_l(), &*iv.s, nlp.d_l(), &*mult.v_l);
let (s_s_u, n_s_u) = self.safe_slack_u(&*nlp.pd_u(), &*iv.s, nlp.d_u(), &*mult.v_u);
let adjusted = n_x_l + n_x_u + n_s_l + n_s_u;
if adjusted == 0 {
return None;
}
// new_x_L = Px_L^T x - safe_slack_x_L
let mut new_x_l = nlp.x_l().make_new();
nlp.px_l()
.trans_mult_vector(1.0, &*iv.x, 0.0, &mut *new_x_l);
new_x_l.axpy(-1.0, &*s_x_l);
// new_x_U = Px_U^T x + safe_slack_x_U
let mut new_x_u = nlp.x_u().make_new();
nlp.px_u()
.trans_mult_vector(1.0, &*iv.x, 0.0, &mut *new_x_u);
new_x_u.axpy(1.0, &*s_x_u);
// new_d_L = Pd_L^T s - safe_slack_s_L
let mut new_d_l = nlp.d_l().make_new();
nlp.pd_l()
.trans_mult_vector(1.0, &*iv.s, 0.0, &mut *new_d_l);
new_d_l.axpy(-1.0, &*s_s_l);
// new_d_U = Pd_U^T s + safe_slack_s_U
let mut new_d_u = nlp.d_u().make_new();
nlp.pd_u()
.trans_mult_vector(1.0, &*iv.s, 0.0, &mut *new_d_u);
new_d_u.axpy(1.0, &*s_s_u);
Some(AdjustedBounds {
adjusted,
x_l: new_x_l,
x_u: new_x_u,
d_l: new_d_l,
d_u: new_d_u,
})
}
// --------------------------------------------------------------
// NLP function evaluations.
// --------------------------------------------------------------
pub fn curr_grad_f(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let mut nlp = self.nlp.borrow_mut();
let mut g = iv.x.make_new();
nlp.eval_grad_f(&*iv.x, &mut *g);
rc_from(g)
}
pub fn trial_grad_f(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mut nlp = self.nlp.borrow_mut();
let mut g = iv.x.make_new();
nlp.eval_grad_f(&*iv.x, &mut *g);
rc_from(g)
}
pub fn curr_c(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let m = self.nlp.borrow().m_eq();
let mut nlp = self.nlp.borrow_mut();
let mut c = iv.y_c.make_new();
debug_assert_eq!(c.dim(), m);
nlp.eval_c(&*iv.x, &mut *c);
rc_from(c)
}
pub fn trial_c(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mut nlp = self.nlp.borrow_mut();
let mut c = iv.y_c.make_new();
nlp.eval_c(&*iv.x, &mut *c);
rc_from(c)
}
pub fn curr_d(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let mut nlp = self.nlp.borrow_mut();
let mut d = iv.s.make_new();
nlp.eval_d(&*iv.x, &mut *d);
rc_from(d)
}
pub fn trial_d(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mut nlp = self.nlp.borrow_mut();
let mut d = iv.s.make_new();
nlp.eval_d(&*iv.x, &mut *d);
rc_from(d)
}
pub fn curr_jac_c(&self) -> Rc<dyn Matrix> {
let iv = self.curr_iv();
self.nlp.borrow_mut().eval_jac_c(&*iv.x)
}
pub fn curr_jac_d(&self) -> Rc<dyn Matrix> {
let iv = self.curr_iv();
self.nlp.borrow_mut().eval_jac_d(&*iv.x)
}
pub fn curr_exact_hessian(&self) -> Rc<dyn SymMatrix> {
let iv = self.curr_iv();
self.nlp
.borrow_mut()
.eval_h(&*iv.x, 1.0, &*iv.y_c, &*iv.y_d)
}
/// `curr_d - s` — port of `IpIpoptCalculatedQuantities.cpp:1185-1206`.
pub fn curr_d_minus_s(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let d = self.curr_d();
let mut tmp = iv.s.make_new();
// tmp = 0*tmp + 1*d + (-1)*s
tmp.add_two_vectors(1.0, &*d, -1.0, &*iv.s, 0.0);
rc_from(tmp)
}
pub fn trial_d_minus_s(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let d = self.trial_d();
let mut tmp = iv.s.make_new();
tmp.add_two_vectors(1.0, &*d, -1.0, &*iv.s, 0.0);
rc_from(tmp)
}
/// `J_c^T y_c` — for a generic `vec` argument
/// (`IpIpoptCalculatedQuantities.cpp:1373-1404`).
pub fn curr_jac_c_t_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let jac_c = self.curr_jac_c();
let mut tmp = iv.x.make_new();
jac_c.trans_mult_vector(1.0, vec, 0.0, &mut *tmp);
rc_from(tmp)
}
/// `J_d^T y_d` for arbitrary `vec`.
pub fn curr_jac_d_t_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let jac_d = self.curr_jac_d();
let mut tmp = iv.x.make_new();
jac_d.trans_mult_vector(1.0, vec, 0.0, &mut *tmp);
rc_from(tmp)
}
pub fn curr_jac_c_t_times_curr_y_c(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
self.curr_jac_c_t_times_vec(&*iv.y_c)
}
pub fn curr_jac_d_t_times_curr_y_d(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
self.curr_jac_d_t_times_vec(&*iv.y_d)
}
/// `J_c v` — `IpIpoptCalculatedQuantities.cpp:1303-1321`.
pub fn curr_jac_c_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let jac_c = self.curr_jac_c();
let mut tmp = iv.y_c.make_new();
jac_c.mult_vector(1.0, vec, 0.0, &mut *tmp);
rc_from(tmp)
}
/// `J_d v` — `IpIpoptCalculatedQuantities.cpp:1323-1343`.
pub fn curr_jac_d_times_vec(&self, vec: &dyn Vector) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let jac_d = self.curr_jac_d();
let mut tmp = iv.s.make_new();
jac_d.mult_vector(1.0, vec, 0.0, &mut *tmp);
rc_from(tmp)
}
// --------------------------------------------------------------
// Lagrangian gradients
// --------------------------------------------------------------
/// `∇_x L = ∇f(x) + J_c^T y_c + J_d^T y_d - P_L z_L + P_U z_U`
/// per `IpIpoptCalculatedQuantities.cpp:1993-2030`.
pub fn curr_grad_lag_x(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let grad_f = self.curr_grad_f();
let jc_t_y_c = self.curr_jac_c_t_times_curr_y_c();
let jd_t_y_d = self.curr_jac_d_t_times_curr_y_d();
let mut tmp = iv.x.make_new();
tmp.copy(&*grad_f);
tmp.add_two_vectors(1.0, &*jc_t_y_c, 1.0, &*jd_t_y_d, 1.0);
let nlp = self.nlp.borrow();
nlp.px_l().mult_vector(-1.0, &*iv.z_l, 1.0, &mut *tmp);
nlp.px_u().mult_vector(1.0, &*iv.z_u, 1.0, &mut *tmp);
rc_from(tmp)
}
/// `∇_s L = -y_d - P_L v_L + P_U v_U`
/// (`IpIpoptCalculatedQuantities.cpp:2069-2098`).
pub fn curr_grad_lag_s(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let mut tmp = iv.y_d.make_new();
let nlp = self.nlp.borrow();
// tmp = P_U v_U
nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp);
// tmp = tmp - P_L v_L
nlp.pd_l().mult_vector(-1.0, &*iv.v_l, 1.0, &mut *tmp);
// tmp = tmp - y_d
tmp.axpy(-1.0, &*iv.y_d);
rc_from(tmp)
}
// --------------------------------------------------------------
// Complementarity (slack ⊙ multiplier)
// --------------------------------------------------------------
fn calc_compl(slack: &dyn Vector, mult: &dyn Vector) -> Rc<dyn Vector> {
let mut result = slack.make_new();
result.copy(slack);
result.element_wise_multiply(mult);
rc_from(result)
}
pub fn curr_compl_x_l(&self) -> Rc<dyn Vector> {
let slack = self.curr_slack_x_l();
let z_l = self.curr_iv().z_l;
Self::calc_compl(&*slack, &*z_l)
}
pub fn curr_compl_x_u(&self) -> Rc<dyn Vector> {
let slack = self.curr_slack_x_u();
let z_u = self.curr_iv().z_u;
Self::calc_compl(&*slack, &*z_u)
}
pub fn curr_compl_s_l(&self) -> Rc<dyn Vector> {
let slack = self.curr_slack_s_l();
let v_l = self.curr_iv().v_l;
Self::calc_compl(&*slack, &*v_l)
}
pub fn curr_compl_s_u(&self) -> Rc<dyn Vector> {
let slack = self.curr_slack_s_u();
let v_u = self.curr_iv().v_u;
Self::calc_compl(&*slack, &*v_u)
}
/// `s_L .* z_L - mu` — relaxed complementarity used in the KKT
/// RHS. `IpIpoptCalculatedQuantities.cpp:2406-2430`.
pub fn curr_relaxed_compl_x_l(&self) -> Rc<dyn Vector> {
let mu = self.data.borrow().curr_mu;
let mut r = self.curr_compl_x_l().make_new();
r.copy(&*self.curr_compl_x_l());
r.add_scalar(-mu);
rc_from(r)
}
pub fn curr_relaxed_compl_x_u(&self) -> Rc<dyn Vector> {
let mu = self.data.borrow().curr_mu;
let mut r = self.curr_compl_x_u().make_new();
r.copy(&*self.curr_compl_x_u());
r.add_scalar(-mu);
rc_from(r)
}
pub fn curr_relaxed_compl_s_l(&self) -> Rc<dyn Vector> {
let mu = self.data.borrow().curr_mu;
let mut r = self.curr_compl_s_l().make_new();
r.copy(&*self.curr_compl_s_l());
r.add_scalar(-mu);
rc_from(r)
}
pub fn curr_relaxed_compl_s_u(&self) -> Rc<dyn Vector> {
let mu = self.data.borrow().curr_mu;
let mut r = self.curr_compl_s_u().make_new();
r.copy(&*self.curr_compl_s_u());
r.add_scalar(-mu);
rc_from(r)
}
// --------------------------------------------------------------
// Σ_x / Σ_s (barrier-Hessian diagonals fed to the augmented system)
// `IpIpoptCalculatedQuantities.cpp:3501-3551`.
//
// Σ_x = P_L · diag(z_L / s_L) · P_L^T + P_U · diag(z_U / s_U) · P_U^T
// Σ_s = P_L · diag(v_L / s_L) · P_L^T + P_U · diag(v_U / s_U) · P_U^T
// --------------------------------------------------------------
pub fn curr_sigma_x(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
{
let cache = self.curr_sigma_x_cache.borrow();
if let Some(v) = cache.get(
&[iv.x.as_tagged(), iv.z_l.as_tagged(), iv.z_u.as_tagged()],
&[],
) {
return v;
}
}
let slack_l = self.curr_slack_x_l();
let slack_u = self.curr_slack_x_u();
let mut sigma = iv.x.make_new();
sigma.set(0.0);
let nlp = self.nlp.borrow();
nlp.px_l()
.add_m_sinv_z(1.0, &*slack_l, &*iv.z_l, &mut *sigma);
nlp.px_u()
.add_m_sinv_z(1.0, &*slack_u, &*iv.z_u, &mut *sigma);
let v = rc_from(sigma);
self.curr_sigma_x_cache.borrow_mut().add(
v.clone(),
&[iv.x.as_tagged(), iv.z_l.as_tagged(), iv.z_u.as_tagged()],
&[],
);
v
}
pub fn curr_sigma_s(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
{
let cache = self.curr_sigma_s_cache.borrow();
if let Some(v) = cache.get(
&[iv.s.as_tagged(), iv.v_l.as_tagged(), iv.v_u.as_tagged()],
&[],
) {
return v;
}
}
let slack_l = self.curr_slack_s_l();
let slack_u = self.curr_slack_s_u();
let mut sigma = iv.s.make_new();
sigma.set(0.0);
let nlp = self.nlp.borrow();
nlp.pd_l()
.add_m_sinv_z(1.0, &*slack_l, &*iv.v_l, &mut *sigma);
nlp.pd_u()
.add_m_sinv_z(1.0, &*slack_u, &*iv.v_u, &mut *sigma);
let v = rc_from(sigma);
self.curr_sigma_s_cache.borrow_mut().add(
v.clone(),
&[iv.s.as_tagged(), iv.v_l.as_tagged(), iv.v_u.as_tagged()],
&[],
);
v
}
// --------------------------------------------------------------
// Objective f and barrier objective phi
// (`IpIpoptCalculatedQuantities.cpp:CalcBarrierTerm`,
// lines 870-1042 in upstream).
//
// phi(x,s) = f(x)
// − μ · [Σ ln(s_x_L) + Σ ln(s_x_U)
// + Σ ln(s_s_L) + Σ ln(s_s_U)]
// + κ_d · μ · [s_x_L · 1_singly_x_L
// + s_x_U · 1_singly_x_U
// + s_s_L · 1_singly_s_L
// + s_s_U · 1_singly_s_U]
//
// The damping piece vanishes when `kappa_d == 0` (default).
// --------------------------------------------------------------
pub fn curr_f(&self) -> Number {
let iv = self.curr_iv();
let mut nlp = self.nlp.borrow_mut();
nlp.eval_f(&*iv.x)
}
/// Unscaled objective at the current iterate. `curr_f` returns the
/// internally scaled value (`f · df_`); upstream IPOPT prints the
/// unscaled objective in its iteration log, so this divides the
/// scaling back out. Mirrors `IpoptCalculatedQuantities::
/// unscaled_curr_f`. A zero factor (scaling never determined) is
/// treated as the identity.
pub fn unscaled_curr_f(&self) -> Number {
let scaled = self.curr_f();
let factor = self.nlp.borrow().obj_scaling_factor();
if factor == 0.0 {
scaled
} else {
scaled / factor
}
}
/// Max-norm dual infeasibility in the **unscaled** (user-original)
/// space. [`Self::curr_dual_infeasibility_max`] is evaluated in the
/// internally-scaled NLP space (objective × `df`, constraints × `dc`);
/// because POUNCE applies no variable scaling, every term of the
/// Lagrangian gradient `∇f + Jᵀy − z` carries the same objective
/// factor `df`, so the unscaling is a single divide by
/// `df = obj_scaling_factor`. A zero or unit factor returns the scaled
/// value unchanged — the common no-scaling path stays division-free.
pub fn curr_unscaled_dual_infeasibility_max(&self) -> Number {
let df = self.nlp.borrow().obj_scaling_factor();
let scaled = self.curr_dual_infeasibility_max();
// `df` is SIGNED — `obj_scaling_factor = -1` is the documented way to
// pose a maximization — while `scaled` is a max-norm. Dividing by the
// signed factor returned a NEGATIVE "max-norm", which then sailed under
// every `<= tol` comparison: it disabled the gh #200 veto on
// maximization, and defeated the unscaled residual gate added for
// pounce#173 there as well. Magnitude is what the unscaling means.
let df = df.abs();
if df == 0.0 || df == 1.0 {
scaled
} else {
scaled / df
}
}
/// Max-norm complementarity in the **unscaled** space. Each bound block
/// `s · z` scales uniformly by `df`: the slack's `dc`/`dd` factor and
/// the multiplier's `df/dc` (`df/dd`) factor cancel in the product,
/// leaving `df`. So this is the scaled max-norm divided by `df`. See
/// [`Self::curr_unscaled_dual_infeasibility_max`].
pub fn curr_unscaled_complementarity_max(&self) -> Number {
let df = self.nlp.borrow().obj_scaling_factor();
let scaled = self.curr_complementarity_max();
// `df` is SIGNED — `obj_scaling_factor = -1` is the documented way to
// pose a maximization — while `scaled` is a max-norm. Dividing by the
// signed factor returned a NEGATIVE "max-norm", which then sailed under
// every `<= tol` comparison: it disabled the gh #200 veto on
// maximization, and defeated the unscaled residual gate added for
// pounce#173 there as well. Magnitude is what the unscaling means.
let df = df.abs();
if df == 0.0 || df == 1.0 {
scaled
} else {
scaled / df
}
}
/// Max-norm primal infeasibility in the **unscaled** space. Unlike the
/// dual/complementarity terms the constraint scaling is per-row
/// (`c_scaled = dc ⊙ c_user`, `(d−s)_scaled = dd ⊙ (d−s)_user`), so each
/// block is unscaled element-by-element before the max-norm. When no row
/// scaling is active (`c_scale_vec`/`d_scale_vec` both `None` — the
/// common case) this is exactly [`Self::curr_primal_infeasibility_max`].
pub fn curr_unscaled_primal_infeasibility_max(&self) -> Number {
let (dc, dd) = {
let nlp = self.nlp.borrow();
(nlp.c_scale_vec(), nlp.d_scale_vec())
};
if dc.is_none() && dd.is_none() {
return self.curr_primal_infeasibility_max();
}
let c_max = unscaled_block_amax(&*self.curr_c(), dc.as_deref());
let dms_max = unscaled_block_amax(&*self.curr_d_minus_s(), dd.as_deref());
c_max.max(dms_max)
}
/// Max-norm constraint violation of the **original** NLP, in user units:
/// `|c_i|` over the equality block and `max(0, d_l_i − d_i, d_i − d_u_i)`
/// over the inequality block. This is what upstream's
/// `inf_pr_output = original` — its *default* — prints in the `inf_pr`
/// column, and what its end-of-run "Constraint violation" line reports.
/// Mirrors `IpIpoptCalculatedQuantities.cpp:unscaled_curr_nlp_constraint_violation`.
///
/// Deliberately **not** [`Self::curr_primal_infeasibility_max`], which is
/// `max(‖c‖_∞, ‖d − s‖_∞)` — the violation of the *internal* slack
/// reformulation. The two diverge whenever the slack drifts from `d(x)`:
/// `s` is confined to `[d_l, d_u]`, so `d = s + (d − s)` with `d − s > 0`
/// clears a lower bound however large that gap grows. On a model that is
/// all inequalities the gap *is* the whole number — on Mittelmann's
/// `robot_a` POUNCE reported 2.79e4 at an iterate where Ipopt reported
/// `0.00e+00` and every original row was in fact satisfied (pounce#476).
///
/// Display only. The filter's `theta`, the barrier-parameter strategies
/// and the convergence test all stay on the internal measure — that split
/// is upstream's, not a shortcut.
///
/// Judged against the **declared** bounds where the NLP tracks them, so
/// the `bound_relax_factor` widening cannot forgive a violation the user
/// would still see (same reasoning as
/// [`Self::relative_d_infeasibility_max`]).
pub fn curr_unscaled_nlp_constraint_violation_max(&self) -> Number {
let (dc, dd) = {
let nlp = self.nlp.borrow();
(nlp.c_scale_vec(), nlp.d_scale_vec())
};
let c_max = unscaled_block_amax(&*self.curr_c(), dc.as_deref());
let d = self.curr_d();
if d.dim() == 0 {
return c_max;
}
let (lo, hi, mask_l, mask_u) = {
let nlp = self.nlp.borrow();
let (mut cl, mut cu) = (nlp.d_l().make_new(), nlp.d_u().make_new());
match nlp.declared_d_bounds() {
Some((dl, du)) => {
let (Some(cld), Some(cud)) = (
cl.as_any_mut().downcast_mut::<DenseVector>(),
cu.as_any_mut().downcast_mut::<DenseVector>(),
) else {
return c_max;
};
cld.set_values(&dl);
cud.set_values(&du);
}
None => {
cl.copy(nlp.d_l());
cu.copy(nlp.d_u());
}
}
let mut lo = d.make_new();
lo.set(0.0);
nlp.pd_l().mult_vector(1.0, &*cl, 0.0, &mut *lo);
let mut hi = d.make_new();
hi.set(0.0);
nlp.pd_u().mult_vector(1.0, &*cu, 0.0, &mut *hi);
// A projected 0 is ambiguous — "no bound on this side" and "a
// declared zero bound" both read 0 — so project an all-ones
// vector through the same expansion to get presence masks.
let mut ones_l = nlp.d_l().make_new();
ones_l.set(1.0);
let mut mask_l = d.make_new();
mask_l.set(0.0);
nlp.pd_l().mult_vector(1.0, &*ones_l, 0.0, &mut *mask_l);
let mut ones_u = nlp.d_u().make_new();
ones_u.set(1.0);
let mut mask_u = d.make_new();
mask_u.set(0.0);
nlp.pd_u().mult_vector(1.0, &*ones_u, 0.0, &mut *mask_u);
(lo, hi, mask_l, mask_u)
};
let (Some(dv), Some(lo), Some(hi), Some(ml), Some(mu)) = (
d.as_any().downcast_ref::<DenseVector>(),
lo.as_any().downcast_ref::<DenseVector>(),
hi.as_any().downcast_ref::<DenseVector>(),
mask_l.as_any().downcast_ref::<DenseVector>(),
mask_u.as_any().downcast_ref::<DenseVector>(),
) else {
return c_max;
};
if !(dv.is_initialized()
&& lo.is_initialized()
&& hi.is_initialized()
&& ml.is_initialized()
&& mu.is_initialized())
{
return c_max;
}
let (dv, lov, hiv, mlv, muv) = (
dv.expanded_values(),
lo.expanded_values(),
hi.expanded_values(),
ml.expanded_values(),
mu.expanded_values(),
);
let mut worst = c_max;
for i in 0..dv.len() {
let mut viol = 0.0_f64;
if mlv[i] > 0.5 {
viol = viol.max(lov[i] - dv[i]);
}
if muv[i] > 0.5 {
viol = viol.max(dv[i] - hiv[i]);
}
if viol <= 0.0 || !viol.is_finite() {
continue;
}
// Row scaling is per-row (`d_scaled = dd ⊙ d_user`), so the
// violation unscales by the same factor. A zero factor is treated
// as the identity, matching `unscaled_block_amax`.
let viol = match dd.as_deref() {
Some(s) if s[i] != 0.0 => viol / s[i],
_ => viol,
};
worst = worst.max(viol);
}
worst
}
/// Largest primal infeasibility of a constraint row **relative to that
/// row's own magnitude** — `|c_i| / |b_i|` over the equality block and
/// `dist(d_i, [d_l_i, d_u_i]) / max(|d_l_i|, |d_u_i|)` over the
/// inequality block, whichever is worse.
///
/// See [`Self::relative_d_infeasibility_max`] and
/// [`Self::relative_c_infeasibility_max`] for the two blocks; both use
/// the row's **declared** magnitude, never a live or relaxed stand-in,
/// and both abstain (contribute nothing) on a row that has no declared
/// magnitude to be relative to.
pub fn curr_relative_primal_infeasibility_max(&self) -> Number {
self.relative_d_infeasibility_max()
.max(self.relative_c_infeasibility_max())
}
/// The equality-block half of
/// [`Self::curr_relative_primal_infeasibility_max`]: `max_i |c_i| / |b_i|`,
/// where `b_i` is the row's declared right-hand side
/// ([`IpoptNlp::declared_c_rhs`]).
///
/// POUNCE folds `g_i(x) == b_i` into `c_i(x) = 0`, so `|c_i|` *is* the
/// violation and by itself carries no magnitude to be judged against —
/// which is why every runtime feasibility decision on an equality row was
/// an absolute one, and why down-scaling such a row shrank `|c_i|` under
/// the absolute tolerance and flipped a true infeasibility verdict to
/// `Solve_Succeeded` (gh #390, residual of #387). Dividing by the pre-fold
/// RHS restores it: `s·g(x) == s·b` has residual `s·(g(x) − b)` and RHS
/// `s·b`, so the ratio is the same at every `s` — the point.
///
/// Both numerator and denominator are taken in the internally-scaled
/// space, so the solver's own row scaling `dc_i` cancels too.
///
/// A **homogeneous** row (`b_i = 0`) contributes nothing. It has no
/// declared magnitude to be relative to, and needs none: `s·g(x) == 0` is
/// the same row at every `s`, so the absolute test is already invariant
/// there. Dividing by zero — or by a fabricated floor — would turn
/// float-noise residuals into 100% "violations" on the single most common
/// equality row there is. Non-finite entries likewise contribute nothing:
/// an unjudgeable row must not fabricate a relative verdict. When the NLP
/// does not track the RHS at all (`declared_c_rhs` is `None` — e.g. the
/// restoration NLP, whose `c` block is not the user's rows), the whole
/// block abstains.
///
/// "Homogeneous" is judged **numerically**, not by `b_i == 0` exactly: a
/// row abstains once `|b_i|` sinks under its own
/// [noise floor](`Self::row_noise_floor`). An exact-zero test is the
/// right idea measured with the wrong instrument — a converter that emits
/// `2^-53` where the model says `0` (Maros-Mészáros `QSC*`/`QSCFXM*`, and
/// every one of the 15 problems in gh #446, carry equality rows with an
/// RHS at `1e-17`–`1e-16`) declares a magnitude that is pure rounding
/// residue — a target no iterate could be positioned finely enough to hit.
/// `|c_i|` cannot be driven below the same floor either, so the
/// ratio was noise over noise: QSCSD1 read 81× violated at a converged KKT
/// point whose absolute violation was `9.2e-15`, which vetoed its success
/// certificate and then armed the rapid-infeasibility pre-filter — a
/// feasible convex QP reported `Converged to a point of local
/// infeasibility`. Comparing against the row's own noise floor keeps the
/// scale invariance that is the whole point of the measure (both sides
/// carry `dc_i`), which an absolute cutoff on `|b_i|` would have thrown
/// away.
pub fn relative_c_infeasibility_max(&self) -> Number {
let c = self.curr_c();
if c.dim() == 0 {
return 0.0;
}
let Some(rhs) = self.nlp.borrow().declared_c_rhs() else {
return 0.0;
};
let noise = self.row_noise_floor(&*self.curr_jac_c(), &*c);
let Some(c) = c.as_any().downcast_ref::<DenseVector>() else {
return 0.0;
};
if !c.is_initialized() {
return 0.0;
}
let cv = c.expanded_values();
if cv.len() != rhs.len() {
return 0.0;
}
let mut worst = 0.0_f64;
for (i, (&ci, &bi)) in cv.iter().zip(rhs.iter()).enumerate() {
let mag = bi.abs();
// `0.0` when no floor could be computed, which reproduces the
// former `mag > 0.0` gate exactly.
let floor = noise.as_ref().map_or(0.0, |n| n[i]);
if mag > floor && mag.is_finite() && ci.is_finite() {
worst = worst.max(ci.abs() / mag);
}
}
worst
}
/// Per-row noise floor of a constraint block: the finest residual the
/// solver could drive that row to, in the same internally scaled units as
/// the block's residual and declared bounds. `jac` is the block's Jacobian
/// and `template` any vector in the block's space.
///
/// The quantity being modelled is **how finely the solver can place `x`**,
/// not how accurately a row evaluates. A Newton step comes from a linear
/// solve whose backward error is norm-wise, so every component of `x` is
/// positioned to roughly `eps · ‖x‖_∞` in absolute terms — a variable at
/// `1e-8` inside a vector of norm `2.7` is still only resolved to
/// `~6e-16`, not to `~2e-24`. A row responds to `x` at rate
/// `max_j |∂g_i/∂x_j|`, so the finest residual it can be driven to is
/// `max_j |∂g_i/∂x_j| · eps · ‖x‖_∞`, with [`ROW_NOISE_KAPPA`] covering
/// accumulation across the row's nonzeros and conditioning slop. A
/// declared magnitude under that is a target the solver could not hit even
/// in exact arithmetic on the model as written.
///
/// `‖x‖_∞` is global, and that is the point rather than a compromise: `x`
/// is one vector solved for jointly, so a large variable anywhere really
/// does coarsen the resolution of every other. The per-row alternative,
/// the exact term sum `Σ_j |a_ij x_j|` via `|J|·|x|`, was implemented and
/// measured, and it is strictly worse — it models the row's *evaluation*
/// error, which is not what limits the residual. It regressed QETAMACR,
/// QSCORPIO and QPILOTNO of gh #446's 15: QSCORPIO's row 93 has all its
/// variables parked near a zero bound at `~1e-8`, giving a term sum of
/// `6e-8` and a floor of `8.5e-22`, so its `−5.6e-17` of rounding residue
/// read as real data again — while the iterate it is judging is only
/// resolved to `~6e-16`. Do not "improve" this to the term sum without
/// re-running those three.
///
/// Scale-invariant by construction. Under a row scaling `dc_i` the
/// Jacobian row carries `dc_i` exactly as the residual and the declared
/// bounds do (the scaling is applied in `eval_jac_c`/`eval_jac_d`), so the
/// floor moves with the quantities it gates and the abstention verdict is
/// the same at every `s`.
///
/// A row with an **empty** Jacobian gets an infinite floor, so it always
/// abstains. Every variable it mentions has been fixed and substituted
/// out, which leaves a constant row `0 = b` that no iterate can move: it
/// is a statement about the *model*, and judging the *iterate* by it is a
/// category error. That is presolve's question, answered up front by
/// `presolve_infeasibility_proof` with a certificate, not a residual. The
/// runtime measure abstaining costs no detection that matters — the
/// absolute `constr_viol_tol` arm still sees the row, and an empty row
/// violated by anything a caller would recognise as infeasible is orders
/// above it. QPILOTNO is why: five variables fixed at `0` reduce row 150
/// to `0 = −2.22e-16`, its own rounding residue, and a measure that
/// insists the iterate is 100% in violation of it will never let any
/// iterate succeed (gh #446).
///
/// `None` — meaning "no floor", i.e. only an exactly-zero magnitude
/// abstains — when the reference cannot be formed: `x = 0` (every term is
/// exactly zero, so the row carries no rounding error to speak of), a
/// non-finite iterate, or a vector type that is not dense.
fn row_noise_floor(&self, jac: &dyn Matrix, template: &dyn Vector) -> Option<Vec<Number>> {
let x_amax = self.curr_iv().x.amax();
if x_amax <= 0.0 || !x_amax.is_finite() {
return None;
}
let mut rows = template.make_new();
jac.compute_row_amax(&mut *rows, true);
let rows = rows.as_any().downcast_ref::<DenseVector>()?;
if !rows.is_initialized() {
return None;
}
Some(
rows.expanded_values()
.iter()
.map(|&a| {
if a > 0.0 {
ROW_NOISE_KAPPA * Number::EPSILON * a * x_amax
} else {
Number::INFINITY
}
})
.collect(),
)
}
/// [`Self::curr_primal_infeasibility_max`] — `max(‖c‖_∞, ‖d − s‖_∞)` —
/// counting each row only where its residual rises above the finest value
/// that residual can take in floating point (gh #528).
///
/// Both residuals are *differences of quantities the row's own size*:
/// `c_i = g_i(x) − b_i` and `d_i − s_i` with `s_i` confined to `d_i`'s
/// bounds. A difference of doubles of magnitude `m` is quantised in units
/// of `eps · m`, so no iterate can place either residual strictly between
/// `0` and `eps · m_i` — it lands on an exact `0` or on a multiple of the
/// quantum, and which of the two is arithmetic luck. Once `eps · m_i`
/// exceeds `tol` that luck decides whether a fully converged solve gets a
/// certificate: on gh #528's LPs (`|b| ~ 1e8`, so one ulp is `1.5e-8`
/// against the default `tol = 1e-8`) the KKT error was pinned one ulp
/// above the tolerance at the exact optimum, the solve kept iterating at a
/// point it could not improve, and it exited
/// `Search_Direction_Becomes_Too_Small` with the right answer in hand.
///
/// The floor per row is the larger of two irreducible effects, both
/// carrying [`ROW_NOISE_KAPPA`] for the same reason
/// [`Self::row_noise_floor`] does (accumulation over the row's nonzeros
/// and the linear solve's conditioning):
///
/// * **Placing `x`** — [`Self::row_noise_floor`], `eps · ‖x‖_∞` passed
/// through the row at `max_j |∂g_i/∂x_j|`. A row whose Jacobian is
/// empty gets `INFINITY` there, meaning "abstain", which is the safe
/// direction for the *relative* measures that floor was written for and
/// the unsafe one here — silencing a constant row `0 = b` would forgive
/// a genuine infeasibility outright. Non-finite floors are therefore
/// read as `0`: such a row is judged on its residual alone.
/// * **Forming the residual** — `eps · m_i`, with `m_i` the magnitude of
/// the quantities subtracted: the declared right-hand side `|b_i|` on
/// the equality block (the value `c_i` was formed against), and
/// `max(|d_i|, |s_i|)` on the inequality block. A block with no declared
/// magnitude to hand (the restoration NLP's `c`, whose rows are not the
/// user's) contributes nothing here and is left to the placement floor.
///
/// A row's residual is counted in full or not at all, matching how
/// [`Self::relative_c_infeasibility_max`] and
/// [`Self::relative_d_infeasibility_max`] use their floors: the question
/// is whether the row says anything, not how much of it to subtract.
pub fn curr_primal_infeasibility_above_noise(&self, kappa: Number) -> Number {
let c = self.curr_c();
let dms = self.curr_d_minus_s();
let c_above = if c.dim() == 0 {
0.0
} else {
let mag = self
.nlp
.borrow()
.declared_c_rhs()
.map(|rhs| rhs.iter().map(|b| b.abs()).collect::<Vec<_>>());
let floor = self.primal_residual_noise_floor(
&*self.curr_jac_c(),
&*c,
mag.as_deref(),
c.dim() as usize,
kappa,
);
amax_above_floor(&*c, &floor)
};
let d_above = if dms.dim() == 0 {
0.0
} else {
let d = self.curr_d();
let s = self.curr_iv().s;
let mag = match (
d.as_any().downcast_ref::<DenseVector>(),
s.as_any().downcast_ref::<DenseVector>(),
) {
(Some(d), Some(s)) if d.is_initialized() && s.is_initialized() => {
let (dv, sv) = (d.expanded_values(), s.expanded_values());
(dv.len() == sv.len()).then(|| {
dv.iter()
.zip(&sv)
.map(|(a, b)| a.abs().max(b.abs()))
.collect::<Vec<_>>()
})
}
_ => None,
};
let floor = self.primal_residual_noise_floor(
&*self.curr_jac_d(),
&*dms,
mag.as_deref(),
dms.dim() as usize,
kappa,
);
amax_above_floor(&*dms, &floor)
};
c_above.max(d_above)
}
/// Per-row floor for [`Self::curr_primal_infeasibility_above_noise`]:
/// `max(placement floor, ROW_NOISE_KAPPA · eps · magnitude_i)`, with a
/// finite value on every row (`0` where nothing can be said, so that row
/// is judged on its residual alone). See that method for the derivation.
fn primal_residual_noise_floor(
&self,
jac: &dyn Matrix,
residual: &dyn Vector,
magnitude: Option<&[Number]>,
dim: usize,
kappa: Number,
) -> Vec<Number> {
// `row_noise_floor` bakes in `ROW_NOISE_KAPPA`; rescale it so both
// contributions carry the caller's `kappa` and nothing else changes
// for the relative measures that share that helper.
let rescale = kappa / ROW_NOISE_KAPPA;
let placement = self.row_noise_floor(jac, residual);
let finite_or_zero = |v: Number| if v.is_finite() && v > 0.0 { v } else { 0.0 };
(0..dim)
.map(|i| {
let from_placement = placement
.as_ref()
.and_then(|p| p.get(i))
.copied()
.unwrap_or(0.0);
let from_placement = from_placement * rescale;
let from_formation = magnitude
.and_then(|m| m.get(i))
.map_or(0.0, |&m| kappa * Number::EPSILON * m);
finite_or_zero(from_placement).max(finite_or_zero(from_formation))
})
.collect()
}
/// The inequality-block half of
/// [`Self::curr_relative_primal_infeasibility_max`]:
/// `max_i |d_i − s_i| / max(|d_i|, |d_l_i|, |d_u_i|)`.
///
/// This is the scale-free companion to
/// [`Self::curr_unscaled_primal_infeasibility_max`]. An absolute violation
/// measure cannot tell "satisfied" from "violated by 10% of everything the
/// row is" once the row's numbers are small — `x >= 0.7` written as
/// `1e-12·x >= 0.7e-12` has an absolute violation of `1e-13` at `x = 0.6`,
/// under every absolute tolerance, while the row is violated by a seventh
/// of its own right-hand side. The ratio is `0.14` at every writing of the
/// row.
///
/// Computed entirely in the internally-scaled space: numerator and
/// denominator both carry the row scaling `dd_i`, so it cancels and the
/// ratio is invariant under it — which is the point.
///
/// The magnitude comes from the row's **declared bounds only** — the
/// current value `d_i` is deliberately excluded. On an *active* row the
/// value converges to the bound, so for a zero-bound row (`g(x) >= 0`,
/// ubiquitous) both the violation and `|d_i|` go to zero together and
/// their ratio hovers near 1 at a perfectly converged point — including
/// `|d_i|` made HS13's genuine solution read as 100% violated and vetoed
/// its certificate. A zero bound also needs no relative treatment in the
/// first place: `s·g >= 0` is the same row at every `s`, so the absolute
/// test is already invariant there. Rows whose bounds are all zero or
/// non-finite therefore contribute nothing (the relative measure
/// abstains) — "zero" measured against the row's own
/// [noise floor](`Self::row_noise_floor`) rather than exactly, for the
/// reason spelled out on [`Self::relative_c_infeasibility_max`]: a
/// converter that writes `2^-53` where the model says `0` otherwise hands
/// a bound made of rounding residue to a measure that then reads the row
/// as 100% violated. QPILOTNO carries 43 such inequality bounds at
/// `1e-17`–`1e-15`, and one of them — a row sitting at exactly `d(x) = 0`
/// against a declared bound of `1.1e-16` — pinned `rel_viol` at `1.0` for
/// the whole run and drove the gh #446 local-infeasibility verdict from
/// this block. Equality rows are judged by
/// [`Self::relative_c_infeasibility_max`], which plumbs the pre-fold RHS
/// back to supply the magnitude the fold into `c(x) = 0` erased.
///
/// The violation judged is the **distance of `d(x)` outside the declared
/// box** — NOT the lifted residual `|d − s|` the absolute measure uses.
/// `|d − s|` only bounds the true violation from above: mid-solve the
/// slack lags `d` while `d` is comfortably inside its bounds, so a
/// slack-lag of 1% of a small row's magnitude read as "violated" at
/// points that are genuinely feasible. That armed the rapid-infeasibility
/// pre-filter at degenerate QP endgames, where the no-descent
/// confirmation is vacuous (the violation is already ~0, so no materially
/// less-violating point exists) — and 18 feasible CUTEr QPs were reported
/// locally infeasible. Measured, not hypothetical.
pub fn relative_d_infeasibility_max(&self) -> Number {
let dms = self.curr_d_minus_s();
if dms.dim() == 0 {
return 0.0;
}
let d = self.curr_d();
let (lo, hi, mask_l, mask_u) = {
let nlp = self.nlp.borrow();
// The *declared* bounds where the NLP tracks them: the live
// `d_l`/`d_u` carry the `bound_relax_factor` widening, under which
// a declared-zero bound reads as `~1e-8` — a fabricated magnitude
// for a row that has none (that misread both vetoed HS13's genuine
// solution and manufactured "relative" verdicts out of thin air).
let (mut cl, mut cu) = (nlp.d_l().make_new(), nlp.d_u().make_new());
match nlp.declared_d_bounds() {
Some((dl, du)) => {
let (Some(cld), Some(cud)) = (
cl.as_any_mut().downcast_mut::<DenseVector>(),
cu.as_any_mut().downcast_mut::<DenseVector>(),
) else {
return 0.0;
};
cld.set_values(&dl);
cud.set_values(&du);
}
None => {
cl.copy(nlp.d_l());
cu.copy(nlp.d_u());
}
}
let mut lo = dms.make_new();
lo.set(0.0);
nlp.pd_l().mult_vector(1.0, &*cl, 0.0, &mut *lo);
let mut hi = dms.make_new();
hi.set(0.0);
nlp.pd_u().mult_vector(1.0, &*cu, 0.0, &mut *hi);
// A projected 0 is ambiguous — "no bound on this side" and "a
// declared zero bound" both read 0 — so project an all-ones
// vector through the same expansion to get presence masks.
let mut ones_l = nlp.d_l().make_new();
ones_l.set(1.0);
let mut mask_l = dms.make_new();
mask_l.set(0.0);
nlp.pd_l().mult_vector(1.0, &*ones_l, 0.0, &mut *mask_l);
let mut ones_u = nlp.d_u().make_new();
ones_u.set(1.0);
let mut mask_u = dms.make_new();
mask_u.set(0.0);
nlp.pd_u().mult_vector(1.0, &*ones_u, 0.0, &mut *mask_u);
(lo, hi, mask_l, mask_u)
};
let noise = self.row_noise_floor(&*self.curr_jac_d(), &*dms);
let (Some(d), Some(lo), Some(hi), Some(mask_l), Some(mask_u)) = (
d.as_any().downcast_ref::<DenseVector>(),
lo.as_any().downcast_ref::<DenseVector>(),
hi.as_any().downcast_ref::<DenseVector>(),
mask_l.as_any().downcast_ref::<DenseVector>(),
mask_u.as_any().downcast_ref::<DenseVector>(),
) else {
return 0.0;
};
if !(d.is_initialized()
&& lo.is_initialized()
&& hi.is_initialized()
&& mask_l.is_initialized()
&& mask_u.is_initialized())
{
return 0.0;
}
let dv = d.expanded_values();
let lov = lo.expanded_values();
let hiv = hi.expanded_values();
let mlv = mask_l.expanded_values();
let muv = mask_u.expanded_values();
let mut worst = 0.0_f64;
for i in 0..dv.len() {
let (has_l, has_u) = (mlv[i] > 0.5, muv[i] > 0.5);
let mut viol = 0.0_f64;
let mut mag = 0.0_f64;
if has_l {
viol = viol.max(lov[i] - dv[i]);
mag = mag.max(lov[i].abs());
}
if has_u {
viol = viol.max(dv[i] - hiv[i]);
mag = mag.max(hiv[i].abs());
}
// `0.0` when no floor could be computed, which reproduces the
// former `mag > 0.0` gate exactly.
let floor = noise.as_ref().map_or(0.0, |n| n[i]);
if mag > floor && mag.is_finite() && viol.is_finite() && viol > 0.0 {
worst = worst.max(viol / mag);
}
}
worst
}
/// The objective scaling factor `df` currently in force (`1.0` when no
/// objective scaling is active).
///
/// Exposed because the termination logic must be able to tell an honest
/// certificate from one an extreme scale has masked (gh #200): the scale
/// factor itself is the discriminating signal, not the error.
pub fn obj_scaling_factor(&self) -> Number {
self.nlp.borrow().obj_scaling_factor()
}
/// The solver-computed part of the objective scale — see
/// [`IpoptNlp::computed_obj_scaling_factor`]. The masked-certificate test
/// keys on this, not on the product, so a user who deliberately scales a
/// well-conditioned objective down is not second-guessed.
pub fn computed_obj_scaling_factor(&self) -> Number {
self.nlp.borrow().computed_obj_scaling_factor()
}
/// Overall **unscaled** max-norm KKT error — `max` of the unscaled dual
/// infeasibility, primal infeasibility, and complementarity. This is the
/// honest "distance from a KKT point in the user's own units", as
/// opposed to [`Self::curr_nlp_error`], which additionally applies the
/// `s_d`/`s_c` optimality scaling. Used by the status-fidelity gate and
/// surfaced to callers that must independently verify a returned
/// certificate (pounce#173).
pub fn curr_unscaled_nlp_error(&self) -> Number {
self.curr_unscaled_dual_infeasibility_max()
.max(self.curr_unscaled_primal_infeasibility_max())
.max(self.curr_unscaled_complementarity_max())
}
pub fn trial_f(&self) -> Number {
let iv = self.trial_iv();
let mut nlp = self.nlp.borrow_mut();
nlp.eval_f(&*iv.x)
}
fn barrier_obj_at(
&self,
f: Number,
s_x_l: &dyn Vector,
s_x_u: &dyn Vector,
s_s_l: &dyn Vector,
s_s_u: &dyn Vector,
) -> Number {
let mu = self.data.borrow().curr_mu;
let log_sum = s_x_l.sum_logs() + s_x_u.sum_logs() + s_s_l.sum_logs() + s_s_u.sum_logs();
let mut phi = f - mu * log_sum;
if self.kappa_d > 0.0 {
let di = self.damping_indicators();
phi += self.kappa_d * mu * s_x_l.dot(&*di.x_l);
phi += self.kappa_d * mu * s_x_u.dot(&*di.x_u);
phi += self.kappa_d * mu * s_s_l.dot(&*di.s_l);
phi += self.kappa_d * mu * s_s_u.dot(&*di.s_u);
}
phi
}
pub fn curr_barrier_obj(&self) -> Number {
let f = self.curr_f();
let s_x_l = self.curr_slack_x_l();
let s_x_u = self.curr_slack_x_u();
let s_s_l = self.curr_slack_s_l();
let s_s_u = self.curr_slack_s_u();
self.barrier_obj_at(f, &*s_x_l, &*s_x_u, &*s_s_l, &*s_s_u)
}
pub fn trial_barrier_obj(&self) -> Number {
let f = self.trial_f();
let s_x_l = self.trial_slack_x_l();
let s_x_u = self.trial_slack_x_u();
let s_s_l = self.trial_slack_s_l();
let s_s_u = self.trial_slack_s_u();
self.barrier_obj_at(f, &*s_x_l, &*s_x_u, &*s_s_l, &*s_s_u)
}
/// Gradient of the barrier objective wrt `x`:
/// ∇_x φ = ∇f(x) − μ · [P_L · (1/s_L) − P_U · (1/s_U)] + damping
/// Mirrors `IpIpoptCalculatedQuantities.cpp:CalcGradBarrierObjectiveX`.
pub fn curr_grad_barrier_obj_x(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let mu = self.data.borrow().curr_mu;
let s_l = self.curr_slack_x_l();
let s_u = self.curr_slack_x_u();
let mut inv_s_l = s_l.make_new();
inv_s_l.copy(&*s_l);
inv_s_l.element_wise_reciprocal();
let mut inv_s_u = s_u.make_new();
inv_s_u.copy(&*s_u);
inv_s_u.element_wise_reciprocal();
let grad_f = self.curr_grad_f();
let mut tmp = iv.x.make_new();
tmp.copy(&*grad_f);
let nlp = self.nlp.borrow();
// tmp -= μ · P_L · inv_s_l
nlp.px_l().mult_vector(-mu, &*inv_s_l, 1.0, &mut *tmp);
// tmp += μ · P_U · inv_s_u
nlp.px_u().mult_vector(mu, &*inv_s_u, 1.0, &mut *tmp);
if self.kappa_d > 0.0 {
let di = self.damping_indicators();
// + κ_d μ · P_L · 1_singly_x_L
nlp.px_l()
.mult_vector(self.kappa_d * mu, &*di.x_l, 1.0, &mut *tmp);
// − κ_d μ · P_U · 1_singly_x_U
nlp.px_u()
.mult_vector(-self.kappa_d * mu, &*di.x_u, 1.0, &mut *tmp);
}
rc_from(tmp)
}
/// Gradient of the barrier objective wrt `s`:
/// ∇_s φ = − μ · [P_L · (1/s_s_L) − P_U · (1/s_s_U)] + damping
pub fn curr_grad_barrier_obj_s(&self) -> Rc<dyn Vector> {
let iv = self.curr_iv();
let mu = self.data.borrow().curr_mu;
let s_l = self.curr_slack_s_l();
let s_u = self.curr_slack_s_u();
let mut inv_s_l = s_l.make_new();
inv_s_l.copy(&*s_l);
inv_s_l.element_wise_reciprocal();
let mut inv_s_u = s_u.make_new();
inv_s_u.copy(&*s_u);
inv_s_u.element_wise_reciprocal();
let mut tmp = iv.s.make_new();
tmp.set(0.0);
let nlp = self.nlp.borrow();
nlp.pd_l().mult_vector(-mu, &*inv_s_l, 1.0, &mut *tmp);
nlp.pd_u().mult_vector(mu, &*inv_s_u, 1.0, &mut *tmp);
if self.kappa_d > 0.0 {
let di = self.damping_indicators();
nlp.pd_l()
.mult_vector(self.kappa_d * mu, &*di.s_l, 1.0, &mut *tmp);
nlp.pd_u()
.mult_vector(-self.kappa_d * mu, &*di.s_u, 1.0, &mut *tmp);
}
rc_from(tmp)
}
// --------------------------------------------------------------
// Step-aware quadratic-model quantities — used by the penalty
// line-search acceptor's pred/ared test and by the quality-
// function mu oracle's q(σ) evaluator.
// --------------------------------------------------------------
/// Directional derivative of the barrier objective along `(δx, δs)`:
/// `gradBarrTDelta = ∇_x φ · δx + ∇_s φ · δs`. Port of
/// `IpIpoptCalculatedQuantities.cpp:CurrGradBarrTDelta` (called
/// `IpCq().curr_gradBarrTDelta()` in upstream after the search dir
/// has been computed).
pub fn curr_grad_barr_t_delta(&self, delta_x: &dyn Vector, delta_s: &dyn Vector) -> Number {
let g_x = self.curr_grad_barrier_obj_x();
let g_s = self.curr_grad_barrier_obj_s();
g_x.dot(delta_x) + g_s.dot(delta_s)
}
/// `δᵀ(W + Σ_x + δ_pert_x I)δ_x + δ_sᵀ(Σ_s + δ_pert_s I)δ_s` —
/// the quadratic-model term used by `IpPenaltyLSAcceptor.cpp:
/// InitThisLineSearch:101-129`. Reads `W` and the active PD
/// perturbations from [`crate::ipopt_data::IpoptData`].
/// Returns 0 if the result would be negative (matching upstream's
/// `if dWd <= 0 then dWd = 0` guard at line 133).
pub fn curr_dwd(&self, delta_x: &dyn Vector, delta_s: &dyn Vector) -> Number {
let mut dwd: Number = 0.0;
// δ_xᵀ W δ_x.
if let Some(w) = self.data.borrow().w.clone() {
let mut wd = delta_x.make_new();
w.mult_vector(1.0, delta_x, 0.0, &mut *wd);
dwd += wd.dot(delta_x);
}
// δ_xᵀ Σ_x δ_x.
let sigma_x = self.curr_sigma_x();
let mut tmp_x = delta_x.make_new();
tmp_x.copy(delta_x);
tmp_x.element_wise_multiply(&*sigma_x);
dwd += tmp_x.dot(delta_x);
// δ_sᵀ Σ_s δ_s.
let sigma_s = self.curr_sigma_s();
let mut tmp_s = delta_s.make_new();
tmp_s.copy(delta_s);
tmp_s.element_wise_multiply(&*sigma_s);
dwd += tmp_s.dot(delta_s);
// PD perturbations.
let pert = self.data.borrow().perturbations;
if pert.delta_x != 0.0 {
let nx = delta_x.nrm2();
dwd += pert.delta_x * nx * nx;
}
if pert.delta_s != 0.0 {
let ns = delta_s.nrm2();
dwd += pert.delta_s * ns * ns;
}
dwd.max(0.0)
}
// --------------------------------------------------------------
// Constraint violation theta — port of
// `IpIpoptCalculatedQuantities.cpp:CurrConstraintViolation`.
// Default norm is 1-norm (option `constraint_violation_norm`,
// default "1-norm" upstream); we hardwire 1-norm in v1.0.
// --------------------------------------------------------------
pub fn curr_constraint_violation(&self) -> Number {
let c = self.curr_c();
let dms = self.curr_d_minus_s();
c.asum() + dms.asum()
}
/// Number of constraint rows backing the 1-norm above, i.e.
/// `dim(c) + dim(d - s)`. Upstream never needs this because it
/// treats `theta` as a bare scalar, but any threshold expressed in
/// `theta` units is a *sum* over this many rows — a `theta` of `T`
/// is a mean per-row residual of `T / rows`. The filter acceptor
/// uses it to floor the `theta_max` reference so the ceiling means
/// the same thing on a 10-row and a 50 000-row model.
pub fn constraint_violation_rows(&self) -> usize {
let c = self.curr_c();
let dms = self.curr_d_minus_s();
(c.dim() as usize) + (dms.dim() as usize)
}
pub fn trial_constraint_violation(&self) -> Number {
let c = self.trial_c();
let dms = self.trial_d_minus_s();
c.asum() + dms.asum()
}
/// Max-norm primal infeasibility — `max(||c||_∞, ||d − s||_∞)`. Used
/// by the iteration output's `inf_pr` column when
/// `inf_pr_output == INTERNAL`. Mirrors
/// `IpIpoptCalculatedQuantities.cpp:CurrPrimalInfeasibility(NORM_MAX)`.
pub fn curr_primal_infeasibility_max(&self) -> Number {
let c = self.curr_c();
let dms = self.curr_d_minus_s();
c.amax().max(dms.amax())
}
/// Max-norm dual infeasibility — `max(||∇_x L||_∞, ||∇_s L||_∞)`.
/// Mirrors `IpIpoptCalculatedQuantities.cpp:CurrDualInfeasibility(NORM_MAX)`.
pub fn curr_dual_infeasibility_max(&self) -> Number {
let glx = self.curr_grad_lag_x();
let gls = self.curr_grad_lag_s();
glx.amax().max(gls.amax())
}
/// Magnitude of the largest **term** the Lagrangian gradient is assembled
/// from — the scale [`Self::curr_dual_infeasibility_max`] is a residual
/// *of* (gh #532).
///
/// ```text
/// D = max( ‖∇f‖_∞ , ‖J_cᵀ y_c‖_∞ , ‖J_dᵀ y_d‖_∞ ,
/// ‖P_L z_L‖_∞ , ‖P_U z_U‖_∞ ,
/// ‖y_d‖_∞ , ‖P_L v_L‖_∞ , ‖P_U v_U‖_∞ )
/// ```
///
/// `∇L` is the *sum* of exactly these terms, so `dual_inf / D` is the
/// fraction of them that failed to cancel: `1` at a point where nothing
/// cancelled (`min -exp(x) s.t. x >= 0` running away, `∇f = −8.8e47` with
/// no multiplier to meet it), and `~eps` at a point where the cancellation
/// was as complete as the arithmetic allows. That ratio is the
/// scale-invariant statement of stationarity: it is unchanged by
/// multiplying the objective — and hence every multiplier — by a positive
/// constant, which is the map an absolute bound on `dual_inf` is not
/// invariant under.
///
/// The projections are applied rather than assumed away: `P_L`/`P_U` are
/// 0/1 expansion matrices in the main NLP, where the scatter leaves the
/// max-norm alone, but the term's own norm is what this measures and the
/// restoration NLP supplies its own operators.
///
/// No `has_valid_numbers` sweep, unlike [`Self::curr_nlp_error`] (gh #292):
/// `amax` drops NaN, so a NaN gradient reads here as a finite scale. That
/// cannot launder anything, because the only caller pairs this with the
/// aggregate `nlp_err <= tol` test, and `nlp_err` carries that sweep — a
/// NaN anywhere in `∇L` makes it NaN, and `NaN <= tol` is false.
///
/// Repeats the `∇f` and the two transpose products
/// [`Self::curr_grad_lag_x`] already performs on the same iterate, plus
/// four scatters. The evaluations themselves hit `OrigIpoptNLP`'s
/// per-iterate caches, so the marginal cost is the products — but it is
/// still a second pass, and the caller reads this only where a termination
/// certificate is otherwise on the table. See
/// `OptErrorConvCheck::dual_inf_bound`.
pub fn curr_dual_infeasibility_scale_max(&self) -> Number {
let iv = self.curr_iv();
let mut scale = self
.curr_grad_f()
.amax()
.max(self.curr_jac_c_t_times_curr_y_c().amax())
.max(self.curr_jac_d_t_times_curr_y_d().amax())
.max(iv.y_d.amax());
let nlp = self.nlp.borrow();
let mut tmp_x = iv.x.make_new();
nlp.px_l().mult_vector(1.0, &*iv.z_l, 0.0, &mut *tmp_x);
scale = scale.max(tmp_x.amax());
nlp.px_u().mult_vector(1.0, &*iv.z_u, 0.0, &mut *tmp_x);
scale = scale.max(tmp_x.amax());
let mut tmp_s = iv.y_d.make_new();
nlp.pd_l().mult_vector(1.0, &*iv.v_l, 0.0, &mut *tmp_s);
scale = scale.max(tmp_s.amax());
nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp_s);
scale.max(tmp_s.amax())
}
/// [`Self::curr_dual_infeasibility_scale_max`] in the **unscaled**
/// (user-original) space. Every term of the scaled Lagrangian gradient is
/// `df` times its user-space counterpart — `∇f_scaled = df·∇f`,
/// `J_cᵀ_scaled y_c_scaled = Jᵀ(dc ⊙ y_c_scaled) = df·Jᵀ y_c` since
/// `dc ⊙ y_scaled = df·y_user`, and likewise for the bound blocks, POUNCE
/// applying no variable scaling — so the unscaling is the single divide by
/// `|df|` that [`Self::curr_unscaled_dual_infeasibility_max`] performs on
/// the residual, term for term and row scaling included. Magnitude, for
/// the reason documented there: `df` is signed, a max-norm is not.
pub fn curr_unscaled_dual_infeasibility_scale_max(&self) -> Number {
let df = self.nlp.borrow().obj_scaling_factor().abs();
let scaled = self.curr_dual_infeasibility_scale_max();
if df == 0.0 || df == 1.0 {
scaled
} else {
scaled / df
}
}
/// Scaled stationarity of the infeasibility measure `½‖(c, d−s)‖²`
/// — `‖J_cᵀ c + J_dᵀ (d−s)‖_∞ / max(1, ‖(c, d−s)‖_∞)`. The
/// numerator is the x-gradient of the squared constraint
/// violation; a value near zero with the violation itself bounded
/// away from zero marks an iterate converging to a stationary
/// point of the infeasibility — i.e. a locally infeasible problem.
/// No linear solve: two transpose-products. Mirrors the gradient
/// term behind Ipopt's `IpRestoConvCheck.cpp` `LOCALLY_INFEASIBLE`
/// test, applied here in the main loop.
/// Does a short step along `−∇θ` actually reduce the constraint violation?
///
/// `LocalInfeasibility` asserts the iterate has converged to a **stationary
/// point of the constraint violation** — that no local move reduces it. That
/// is a checkable claim, and this checks it directly instead of trusting a
/// threshold on a proxy.
///
/// Why a probe rather than a better proxy: the detector's surrogate is
/// `‖Jᵀc‖ / max(1, ‖c‖)` against an absolute tolerance, and no variant of it
/// separates the cases. Measured over 800 MINLPLib models plus targeted
/// infeasible problems, the scaled form produces a confirmed false verdict
/// (HS13 from `x₀ = (1e4, 1e4)`, where the constraint scaling `dc ≈ 3.3e-7`
/// drives the surrogate to `5e-14` at a point whose violation is 0.51); the
/// unscaled form needs a tolerance ≥ 1e-2 to fire at all, which introduces
/// new false infeasibility on 3+ corpus models while still losing 2 correct
/// detections; and a scale-invariant `‖Jᵀc‖ / ‖c‖²` is not separable even on
/// the targeted set. A single absolute threshold on a surrogate cannot do
/// this job.
///
/// Comparing `θ` at two points is scale-free by construction — the row
/// scaling cancels out of the ratio — so this needs no calibration at all.
///
/// Costs one `eval_c`/`eval_d` pair per probed step, and runs only where the
/// detector was about to fire (both gates already passed for a full streak),
/// which is rare. Steps are clamped to the variable bounds, so descent that
/// only exists outside the box is correctly not counted — that direction
/// would suppress a *correct* infeasibility verdict.
///
/// Returns `true` when descent is available, i.e. the iterate is **not**
/// stationary and `LocalInfeasibility` must not be declared.
pub fn infeasibility_descent_available(&self) -> bool {
use pounce_linalg::DenseVector;
let theta_curr = self.curr_primal_infeasibility_max();
if theta_curr <= 0.0 {
return false;
}
// -grad of 1/2||(c, d-s)||^2 w.r.t. x.
let c = self.curr_c();
let dms = self.curr_d_minus_s();
let jc_t_c = self.curr_jac_c_t_times_vec(&*c);
let jd_t_dms = self.curr_jac_d_t_times_vec(&*dms);
let mut grad = jc_t_c.make_new();
grad.add_two_vectors(1.0, &*jc_t_c, 1.0, &*jd_t_dms, 0.0);
let gnorm = grad.amax();
if !(gnorm > 0.0) || !gnorm.is_finite() {
// A vanishing gradient is the stationary case this exists to
// confirm; a non-finite one gives us nothing to probe with.
return false;
}
let x = self.curr_iv().x.clone();
let nlp = self.nlp.borrow();
// Full-length bound values and finite-bound indicators, lifted through
// the expansion matrices (same pattern as the divergence guard).
let mut ones_l = nlp.x_l().make_new();
ones_l.set(1.0);
let mut has_lb = x.make_new();
nlp.px_l().mult_vector(1.0, &*ones_l, 0.0, &mut *has_lb);
let mut lb = x.make_new();
nlp.px_l().mult_vector(1.0, nlp.x_l(), 0.0, &mut *lb);
let mut ones_u = nlp.x_u().make_new();
ones_u.set(1.0);
let mut has_ub = x.make_new();
nlp.px_u().mult_vector(1.0, &*ones_u, 0.0, &mut *has_ub);
let mut ub = x.make_new();
nlp.px_u().mult_vector(1.0, nlp.x_u(), 0.0, &mut *ub);
drop(nlp);
let dense = |v: &dyn Vector| -> Option<Vec<Number>> {
v.as_any()
.downcast_ref::<DenseVector>()
.map(|d| d.expanded_values())
};
let (Some(xv), Some(gv), Some(lbv), Some(ubv), Some(hl), Some(hu)) = (
dense(&*x),
dense(&*grad),
dense(&*lb),
dense(&*ub),
dense(&*has_lb),
dense(&*has_ub),
) else {
// Non-dense backing: no probe possible. Report "no descent" so the
// caller falls back to the surrogate's verdict rather than silently
// suppressing every infeasibility conclusion.
return false;
};
// Relative step lengths, so the probe is independent of problem scale.
let xnorm = xv.iter().fold(0.0_f64, |a, &v| a.max(v.abs())).max(1.0);
let base = xnorm / gnorm;
let mut trial = x.make_new();
for k in 0..Self::INFEAS_PROBE_STEPS {
let alpha = base * 10f64.powi(-(k as i32));
{
let Some(t) = trial.as_any_mut().downcast_mut::<DenseVector>() else {
return false;
};
for (i, slot) in t.values_mut().iter_mut().enumerate() {
let mut xi = xv[i] - alpha * gv[i];
if hl[i] != 0.0 {
xi = xi.max(lbv[i]);
}
if hu[i] != 0.0 {
xi = xi.min(ubv[i]);
}
*slot = xi;
}
}
if let Some(theta) = self.theta_at(&*trial) {
if theta.is_finite() && theta < theta_curr * (1.0 - Self::INFEAS_PROBE_MARGIN) {
return true;
}
}
}
false
}
/// Number of geometrically decreasing step lengths the descent probe tries.
const INFEAS_PROBE_STEPS: usize = 6;
/// Relative reduction in `θ` a probe step must achieve before it counts as
/// descent and vetoes the verdict.
///
/// Deliberately coarse. The question is not "is this the exact minimiser of
/// the violation" — an interior-point iterate converging toward one always
/// has some infinitesimal descent left, and a tight margin would veto
/// forever and never let a genuine infeasibility be declared. The question
/// is whether a *materially* less-violating point sits nearby, which is what
/// distinguishes "converging to an infeasible stationary point" from
/// "nowhere near stationary".
///
/// The two regimes are far apart, so the exact value is not delicate. On the
/// genuinely infeasible `x³+y³ == 1 ∧ == 2`, iterates near the least-squares
/// point have only ~0.07 % descent available. On HS13's false verdict, one
/// step takes `θ` from 0.51 to **zero** — a 100 % reduction. Anything between
/// a few percent and most of the way separates them; 10 % sits in the middle.
const INFEAS_PROBE_MARGIN: Number = 0.1;
/// Max-norm constraint violation at an arbitrary `x`, evaluated on scratch
/// vectors so the algorithm's `curr`/`trial` state is untouched. `None` if
/// the evaluation is unusable.
fn theta_at(&self, x: &dyn Vector) -> Option<Number> {
let iv = self.curr_iv();
let mut nlp = self.nlp.borrow_mut();
let mut c = iv.y_c.make_new();
nlp.eval_c(x, &mut *c);
let mut d = iv.s.make_new();
nlp.eval_d(x, &mut *d);
// `d - s` against the CURRENT slacks, matching how `curr_d_minus_s`
// measures the violation: the probe moves x only.
let mut dms = iv.s.make_new();
dms.add_two_vectors(1.0, &*d, -1.0, &*iv.s, 0.0);
let t = c.amax().max(dms.amax());
t.is_finite().then_some(t)
}
pub fn curr_infeasibility_stationarity(&self) -> Number {
let c = self.curr_c();
let dms = self.curr_d_minus_s();
let jc_t_c = self.curr_jac_c_t_times_vec(&*c);
let jd_t_dms = self.curr_jac_d_t_times_vec(&*dms);
let mut grad = jc_t_c.make_new();
grad.add_two_vectors(1.0, &*jc_t_c, 1.0, &*jd_t_dms, 0.0);
let viol = c.amax().max(dms.amax());
grad.amax() / viol.max(1.0)
}
// --------------------------------------------------------------
// Average / scalar complementarity
// --------------------------------------------------------------
/// `(z_L · s_L + z_U · s_U + v_L · s_L^d + v_U · s_U^d) / N`
/// where `N` is the total number of bound multipliers
/// (`IpIpoptCalculatedQuantities.cpp:3553-3606`).
pub fn curr_avrg_compl(&self) -> Number {
let iv = self.curr_iv();
let n = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
if n == 0 {
return 0.0;
}
let s_x_l = self.curr_slack_x_l();
let s_x_u = self.curr_slack_x_u();
let s_s_l = self.curr_slack_s_l();
let s_s_u = self.curr_slack_s_u();
let mut acc = iv.z_l.dot(&*s_x_l);
acc += iv.z_u.dot(&*s_x_u);
acc += iv.v_l.dot(&*s_s_l);
acc += iv.v_u.dot(&*s_s_u);
acc / Number::from(n)
}
/// `min_i (s_i · z_i)` over all four bound complementarity blocks.
/// Mirrors `IpIpoptCalculatedQuantities.cpp:CurrComplxMin`
/// (lines 3608-3640) — the smallest pairwise product `s · z`,
/// signalling how close the iterate is to the central path.
/// Empty bound sets contribute `+∞`; returns `0` if no bounds at
/// all.
pub fn curr_complementarity_min(&self) -> Number {
let cxl = self.curr_compl_x_l();
let cxu = self.curr_compl_x_u();
let csl = self.curr_compl_s_l();
let csu = self.curr_compl_s_u();
let m = |v: &Rc<dyn Vector>| {
if v.dim() == 0 {
Number::INFINITY
} else {
v.min()
}
};
let acc = m(&cxl).min(m(&cxu)).min(m(&csl)).min(m(&csu));
if acc.is_infinite() { 0.0 } else { acc }
}
/// Max-norm of the unbarriered complementarity blocks
/// `max_i |s_i · z_i|` across all four `(x_L, x_U, s_L, s_U)`
/// pairs. Mirrors upstream
/// `IpIpoptCalculatedQuantities.cpp:CurrComplementarity(0., NORM_MAX)`
/// — used by `OptimalityErrorConvergenceCheck` to gate the
/// per-component `compl_inf_tol` test independently of the scaled
/// scalar `curr_nlp_error`.
pub fn curr_complementarity_max(&self) -> Number {
self.curr_compl_x_l()
.amax()
.max(self.curr_compl_x_u().amax())
.max(self.curr_compl_s_l().amax())
.max(self.curr_compl_s_u().amax())
}
/// Centrality measure `ξ = min_i(s_i z_i) / avrg(s · z)`. Mirrors
/// `IpIpoptCalculatedQuantities.cpp:CurrCentralityMeasure`. Used
/// by [`crate::mu::oracle::loqo::LoqoMuOracle`] to bias σ toward
/// the central path when the iterate is unbalanced. Returns `1.0`
/// (perfectly central) when there are no bound multipliers.
pub fn curr_centrality_measure(&self) -> Number {
let avrg = self.curr_avrg_compl();
if avrg <= 0.0 {
return 1.0;
}
self.curr_complementarity_min() / avrg
}
/// Barriered KKT error `E_μ(x,y,z)` — port of
/// `IpIpoptCalculatedQuantities.cpp:CurrBarrierError`. Same as
/// [`Self::curr_nlp_error`] but uses the *relaxed* complementarity
/// `s ⊙ z − μ` so the residual is zero when the iterate sits on the
/// μ-perturbed central path. The monotone barrier-update strategy
/// reduces μ only once this error drops below
/// `barrier_tol_factor · μ`.
pub fn curr_barrier_error(&self) -> Number {
let iv = self.curr_iv();
let (s_d, s_c) = self.optimality_error_scaling(&iv);
let glx = self.curr_grad_lag_x();
let gls = self.curr_grad_lag_s();
let dual = glx.amax().max(gls.amax()) / s_d;
let c = self.curr_c();
let dms = self.curr_d_minus_s();
let primal = c.amax().max(dms.amax());
let compl = self
.curr_relaxed_compl_x_l()
.amax()
.max(self.curr_relaxed_compl_x_u().amax())
.max(self.curr_relaxed_compl_s_l().amax())
.max(self.curr_relaxed_compl_s_u().amax())
/ s_c;
dual.max(primal).max(compl)
}
/// Optimality-scaled max-norm KKT error — port of
/// `IpIpoptCalculatedQuantities.cpp:3050-3104`.
///
/// ```text
/// E = max( ||∇_x L, ∇_s L||_∞ / s_d ,
/// ||c, d − s||_∞ ,
/// ||compl||_∞ / s_c )
/// ```
///
/// where `s_d` / `s_c` are the asum-based scalings from
/// `ComputeOptimalityErrorScaling` (see §4 of `MAIN_LOOP.md`).
/// Uses `mu_target = 0` (the unbarriered KKT residual). The
/// barriered variant is `curr_barrier_error` (TODO in Phase 7).
pub fn curr_nlp_error(&self) -> Number {
self.nlp_error(None)
}
/// [`Self::curr_nlp_error`] with the primal-infeasibility term replaced by
/// [`Self::curr_primal_infeasibility_above_noise`] — i.e. counting a
/// constraint row's residual only where it rises above the finest value
/// that row's residual can take in floating point (gh #528).
///
/// Never larger than [`Self::curr_nlp_error`], and equal to it whenever no
/// row is at its own resolution limit — which is every problem whose data
/// is `O(1)`, so the common path is unchanged. It exists because the other
/// two terms of the KKT error are already normalised (`s_d`, `s_c`) while
/// the primal one is a bare absolute residual: `‖c‖_∞` and `‖d − s‖_∞` are
/// quantised in units of `eps ·` the rows' own magnitude, so on a model
/// whose constraint values reach `~1e8` the smallest *nonzero* value the
/// term can take already exceeds the default `tol = 1e-8`. Judging that
/// term absolutely there asks for a residual no iterate can represent.
///
/// Read only by the **strict** convergence gate, which pairs it with the
/// unscaled `constr_viol_tol` test on the full, unfloored residual — so
/// what this admits is bounded by the user's own feasibility tolerance,
/// never by the noise floor alone.
///
/// `kappa` is the safety factor on the per-row floor —
/// [`ROW_NOISE_KAPPA`] by default, from the `primal_noise_floor_kappa`
/// option. **`0` switches the floor off entirely**, making this identical
/// to [`Self::curr_nlp_error`] and the strict gate bit-for-bit upstream's.
pub fn curr_nlp_error_above_primal_noise(&self, kappa: Number) -> Number {
self.nlp_error(Some(kappa))
}
/// `above_primal_noise` carries the floor's `kappa` when the primal term is
/// to be floored, and is `None` for the plain upstream aggregate.
fn nlp_error(&self, above_primal_noise: Option<Number>) -> Number {
let iv = self.curr_iv();
let (s_d, s_c) = self.optimality_error_scaling(&iv);
// dual infeasibility (max-norm of grad_lag_x and grad_lag_s)
let glx = self.curr_grad_lag_x();
let gls = self.curr_grad_lag_s();
// primal: max(||c||, ||d-s||)
let c = self.curr_c();
let dms = self.curr_d_minus_s();
// unbarriered complementarity (mu_target = 0 → just ||compl||)
let cxl = self.curr_compl_x_l();
let cxu = self.curr_compl_x_u();
let csl = self.curr_compl_s_l();
let csu = self.curr_compl_s_u();
// #292: the max-norm (`amax`/BLAS `iamax`) behind every term below
// silently *drops* NaN — `NaN > m` is `false`, so a NaN component
// leaves the running max untouched and is laundered into a finite
// (typically `0.0`) KKT error. A NaN gradient, NaN constraint Jacobian
// (via `∇_x L`'s `Jᵀy` term), or NaN residual would then read as an
// *optimal* solve and return `Solve_Succeeded`. Detect any non-finite
// component here — through the NaN-propagating `asum` behind
// `has_valid_numbers`, not `amax` — and surface it as a non-finite KKT
// error so the caller's existing `!nlp_err.is_finite()` guard fires
// `Invalid_Number_Detected`. This is confined to the convergence/error
// measure; the general `amax` semantics that step-size selection, the
// line search, and the divergence detectors rely on are untouched.
// (Inf is *not* laundered — `Inf > m` is true — so it already
// propagated; this closes only the NaN hole, and Inf for free.)
for v in [&glx, &gls, &c, &dms, &cxl, &cxu, &csl, &csu] {
if !v.has_valid_numbers() {
return Number::NAN;
}
}
let dual = glx.amax().max(gls.amax()) / s_d;
let primal = match above_primal_noise {
Some(kappa) if kappa > 0.0 => self.curr_primal_infeasibility_above_noise(kappa),
_ => c.amax().max(dms.amax()),
};
let compl = cxl.amax().max(cxu.amax()).max(csl.amax()).max(csu.amax()) / s_c;
dual.max(primal).max(compl)
}
/// `(s_d, s_c)` per `ComputeOptimalityErrorScaling`
/// (`IpIpoptCalculatedQuantities.cpp:3663-3700`).
fn optimality_error_scaling(&self, iv: &IteratesVector) -> (Number, Number) {
let s_max = self.s_max;
// s_c: mean asum of all bound multipliers, capped at s_max,
// divided by s_max.
let n_c = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
let s_c = if n_c == 0 {
1.0
} else {
let asum = iv.z_l.asum() + iv.z_u.asum() + iv.v_l.asum() + iv.v_u.asum();
(s_max.max(asum / Number::from(n_c))) / s_max
};
// s_d: mean asum of all dual multipliers, capped, divided.
let n_d =
iv.y_c.dim() + iv.y_d.dim() + iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
let s_d = if n_d == 0 {
1.0
} else {
let asum = iv.y_c.asum()
+ iv.y_d.asum()
+ iv.z_l.asum()
+ iv.z_u.asum()
+ iv.v_l.asum()
+ iv.v_u.asum();
(s_max.max(asum / Number::from(n_d))) / s_max
};
(s_d, s_c)
}
// --------------------------------------------------------------
// Trial-side Lagrangian gradient / complementarity — needed by
// the soft restoration phase's primal-dual error test. Each is a
// line-for-line analog of the `curr_*` method above, reading the
// `trial` iterate instead of `curr`.
// --------------------------------------------------------------
pub fn trial_jac_c(&self) -> Rc<dyn Matrix> {
let iv = self.trial_iv();
self.nlp.borrow_mut().eval_jac_c(&*iv.x)
}
pub fn trial_jac_d(&self) -> Rc<dyn Matrix> {
let iv = self.trial_iv();
self.nlp.borrow_mut().eval_jac_d(&*iv.x)
}
/// `∇_x L` at the trial iterate — analog of [`Self::curr_grad_lag_x`].
pub fn trial_grad_lag_x(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let grad_f = self.trial_grad_f();
let jac_c = self.trial_jac_c();
let jac_d = self.trial_jac_d();
let mut jc_t = iv.x.make_new();
jac_c.trans_mult_vector(1.0, &*iv.y_c, 0.0, &mut *jc_t);
let mut jd_t = iv.x.make_new();
jac_d.trans_mult_vector(1.0, &*iv.y_d, 0.0, &mut *jd_t);
let mut tmp = iv.x.make_new();
tmp.copy(&*grad_f);
tmp.add_two_vectors(1.0, &*jc_t, 1.0, &*jd_t, 1.0);
let nlp = self.nlp.borrow();
nlp.px_l().mult_vector(-1.0, &*iv.z_l, 1.0, &mut *tmp);
nlp.px_u().mult_vector(1.0, &*iv.z_u, 1.0, &mut *tmp);
rc_from(tmp)
}
/// `∇_s L` at the trial iterate — analog of [`Self::curr_grad_lag_s`].
pub fn trial_grad_lag_s(&self) -> Rc<dyn Vector> {
let iv = self.trial_iv();
let mut tmp = iv.y_d.make_new();
let nlp = self.nlp.borrow();
nlp.pd_u().mult_vector(1.0, &*iv.v_u, 0.0, &mut *tmp);
nlp.pd_l().mult_vector(-1.0, &*iv.v_l, 1.0, &mut *tmp);
tmp.axpy(-1.0, &*iv.y_d);
rc_from(tmp)
}
pub fn trial_compl_x_l(&self) -> Rc<dyn Vector> {
Self::calc_compl(&*self.trial_slack_x_l(), &*self.trial_iv().z_l)
}
pub fn trial_compl_x_u(&self) -> Rc<dyn Vector> {
Self::calc_compl(&*self.trial_slack_x_u(), &*self.trial_iv().z_u)
}
pub fn trial_compl_s_l(&self) -> Rc<dyn Vector> {
Self::calc_compl(&*self.trial_slack_s_l(), &*self.trial_iv().v_l)
}
pub fn trial_compl_s_u(&self) -> Rc<dyn Vector> {
Self::calc_compl(&*self.trial_slack_s_u(), &*self.trial_iv().v_u)
}
/// `||s ⊙ z − μ||₁` summed over the four complementarity blocks.
fn relaxed_compl_asum(blocks: &[Rc<dyn Vector>], mu: Number) -> Number {
let mut acc = 0.0;
for compl in blocks {
if compl.dim() == 0 {
continue;
}
let mut r = compl.make_new();
r.copy(&**compl);
r.add_scalar(-mu);
acc += r.asum();
}
acc
}
/// Unscaled primal-dual KKT system error at the current iterate —
/// port of
/// `IpIpoptCalculatedQuantities.cpp:curr_primal_dual_system_error`.
/// Each block uses the 1-norm scaled by its entry count; the result
/// is the sum of the dual-infeasibility, primal-infeasibility, and
/// complementarity terms. Used by the soft restoration phase's
/// sufficient-reduction test.
pub fn curr_primal_dual_system_error(&self, mu: Number) -> Number {
let iv = self.curr_iv();
let n_dual = iv.x.dim() + iv.s.dim();
let dual_inf =
(self.curr_grad_lag_x().asum() + self.curr_grad_lag_s().asum()) / Number::from(n_dual);
let n_primal = iv.y_c.dim() + iv.y_d.dim();
let primal_inf = if n_primal > 0 {
(self.curr_c().asum() + self.curr_d_minus_s().asum()) / Number::from(n_primal)
} else {
0.0
};
let n_cmpl = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
let cmpl = if n_cmpl > 0 {
Self::relaxed_compl_asum(
&[
self.curr_compl_x_l(),
self.curr_compl_x_u(),
self.curr_compl_s_l(),
self.curr_compl_s_u(),
],
mu,
) / Number::from(n_cmpl)
} else {
0.0
};
dual_inf + primal_inf + cmpl
}
/// Unscaled primal-dual KKT system error at the trial iterate —
/// trial-side analog of [`Self::curr_primal_dual_system_error`].
pub fn trial_primal_dual_system_error(&self, mu: Number) -> Number {
let iv = self.trial_iv();
let n_dual = iv.x.dim() + iv.s.dim();
let dual_inf = (self.trial_grad_lag_x().asum() + self.trial_grad_lag_s().asum())
/ Number::from(n_dual);
let n_primal = iv.y_c.dim() + iv.y_d.dim();
let primal_inf = if n_primal > 0 {
(self.trial_c().asum() + self.trial_d_minus_s().asum()) / Number::from(n_primal)
} else {
0.0
};
let n_cmpl = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
let cmpl = if n_cmpl > 0 {
Self::relaxed_compl_asum(
&[
self.trial_compl_x_l(),
self.trial_compl_x_u(),
self.trial_compl_s_l(),
self.trial_compl_s_u(),
],
mu,
) / Number::from(n_cmpl)
} else {
0.0
};
dual_inf + primal_inf + cmpl
}
// --------------------------------------------------------------
// Damping indicators — `IpIpoptCalculatedQuantities.cpp:1044-1092`.
//
// Tmp_x = P_L · 1 − P_U · 1 (per primal: +1 lower-only,
// −1 upper-only, 0 two-sided,
// 0 unbounded)
// dampind_x_L = P_L^T · Tmp_x (1 on lower-only bounds)
// dampind_x_U = −P_U^T · Tmp_x (1 on upper-only bounds)
// --------------------------------------------------------------
fn damping_indicators(&self) -> DampingIndicators {
let nlp = self.nlp.borrow();
let mut tmp_x_l = nlp.x_l().make_new();
tmp_x_l.set(1.0);
let mut tmp_x_u = nlp.x_u().make_new();
tmp_x_u.set(1.0);
let mut tmp_x = self.curr_iv().x.make_new();
nlp.px_l().mult_vector(1.0, &*tmp_x_l, 0.0, &mut *tmp_x);
nlp.px_u().mult_vector(-1.0, &*tmp_x_u, 1.0, &mut *tmp_x);
let mut d_x_l = nlp.x_l().make_new();
nlp.px_l().trans_mult_vector(1.0, &*tmp_x, 0.0, &mut *d_x_l);
let mut d_x_u = nlp.x_u().make_new();
nlp.px_u()
.trans_mult_vector(-1.0, &*tmp_x, 0.0, &mut *d_x_u);
let mut tmp_s_l = nlp.d_l().make_new();
tmp_s_l.set(1.0);
let mut tmp_s_u = nlp.d_u().make_new();
tmp_s_u.set(1.0);
let mut tmp_s = self.curr_iv().s.make_new();
nlp.pd_l().mult_vector(1.0, &*tmp_s_l, 0.0, &mut *tmp_s);
nlp.pd_u().mult_vector(-1.0, &*tmp_s_u, 1.0, &mut *tmp_s);
let mut d_s_l = nlp.d_l().make_new();
nlp.pd_l().trans_mult_vector(1.0, &*tmp_s, 0.0, &mut *d_s_l);
let mut d_s_u = nlp.d_u().make_new();
nlp.pd_u()
.trans_mult_vector(-1.0, &*tmp_s, 0.0, &mut *d_s_u);
DampingIndicators {
x_l: rc_from(d_x_l),
x_u: rc_from(d_x_u),
s_l: rc_from(d_s_l),
s_u: rc_from(d_s_u),
}
}
/// `curr_grad_lag_x` plus the `kappa_d · μ · (Px_L · 1 − Px_U · 1)`
/// damping term on singly-bounded primals — port of
/// `IpIpoptCalculatedQuantities.cpp:2131-2180`. When `kappa_d == 0`
/// returns the un-damped gradient.
pub fn curr_grad_lag_with_damping_x(&self) -> Rc<dyn Vector> {
if self.kappa_d == 0.0 {
return self.curr_grad_lag_x();
}
let mu = self.data.borrow().curr_mu;
let di = self.damping_indicators();
let (d_x_l, d_x_u) = (di.x_l, di.x_u);
let glx = self.curr_grad_lag_x();
let mut tmp = glx.make_new();
tmp.copy(&*glx);
let nlp = self.nlp.borrow();
nlp.px_l()
.mult_vector(self.kappa_d * mu, &*d_x_l, 1.0, &mut *tmp);
nlp.px_u()
.mult_vector(-self.kappa_d * mu, &*d_x_u, 1.0, &mut *tmp);
rc_from(tmp)
}
pub fn curr_grad_lag_with_damping_s(&self) -> Rc<dyn Vector> {
if self.kappa_d == 0.0 {
return self.curr_grad_lag_s();
}
let mu = self.data.borrow().curr_mu;
let di = self.damping_indicators();
let (d_s_l, d_s_u) = (di.s_l, di.s_u);
let gls = self.curr_grad_lag_s();
let mut tmp = gls.make_new();
tmp.copy(&*gls);
let nlp = self.nlp.borrow();
nlp.pd_l()
.mult_vector(self.kappa_d * mu, &*d_s_l, 1.0, &mut *tmp);
nlp.pd_u()
.mult_vector(-self.kappa_d * mu, &*d_s_u, 1.0, &mut *tmp);
rc_from(tmp)
}
/// `kappa_d · (P_L · damping_l − P_U · damping_u)` in the full x
/// space — port of `IpIpoptCalculatedQuantities.cpp::grad_kappa_times_damping_x`
/// (lines 912-949). Unlike `curr_grad_lag_with_damping_x` this does
/// NOT include `grad_lag_x` and is NOT scaled by `mu`; the centering
/// RHS in the quality-function oracle multiplies the returned vector
/// by `-avrg_compl` per upstream `IpQualityFunctionMuOracle.cpp:229`.
pub fn grad_kappa_times_damping_x(&self) -> Rc<dyn Vector> {
let mut tmp = self.curr_iv().x.make_new();
tmp.set(0.0);
if self.kappa_d > 0.0 {
let di = self.damping_indicators();
let nlp = self.nlp.borrow();
nlp.px_l()
.mult_vector(self.kappa_d, &*di.x_l, 0.0, &mut *tmp);
nlp.px_u()
.mult_vector(-self.kappa_d, &*di.x_u, 1.0, &mut *tmp);
}
rc_from(tmp)
}
pub fn grad_kappa_times_damping_s(&self) -> Rc<dyn Vector> {
let mut tmp = self.curr_iv().s.make_new();
tmp.set(0.0);
if self.kappa_d > 0.0 {
let di = self.damping_indicators();
let nlp = self.nlp.borrow();
nlp.pd_l()
.mult_vector(self.kappa_d, &*di.s_l, 0.0, &mut *tmp);
nlp.pd_u()
.mult_vector(-self.kappa_d, &*di.s_u, 1.0, &mut *tmp);
}
rc_from(tmp)
}
// --------------------------------------------------------------
// Affine (predictor) step helpers — port of upstream
// `IpIpoptCalculatedQuantities.cpp:CurrAvrgCompl`/`AffMaxAlpha…`
// used by the Mehrotra probing oracle and the quality-function
// oracle's σ-search.
// --------------------------------------------------------------
/// Max primal step that keeps `s + α · Δs > 0` for the four slack
/// blocks (x_L, x_U, s_L, s_U), bounded by the fraction-to-the-
/// boundary parameter `τ ∈ (0, 1]`. Mirrors
/// `CalcFracToBound` against the projected step `P_L^T Δx`,
/// `−P_U^T Δx`, `P_L^T Δs`, `−P_U^T Δs`.
pub fn aff_step_alpha_primal_max(&self, delta_aff: &IteratesVector, tau: Number) -> Number {
let nlp = self.nlp.borrow();
let s_x_l = self.curr_slack_x_l();
let s_x_u = self.curr_slack_x_u();
let s_s_l = self.curr_slack_s_l();
let s_s_u = self.curr_slack_s_u();
// Project Δx / Δs onto each bound subspace with the right sign.
let mut step_x_l = s_x_l.make_new();
nlp.px_l()
.trans_mult_vector(1.0, &*delta_aff.x, 0.0, &mut *step_x_l);
let mut step_x_u = s_x_u.make_new();
nlp.px_u()
.trans_mult_vector(-1.0, &*delta_aff.x, 0.0, &mut *step_x_u);
let mut step_s_l = s_s_l.make_new();
nlp.pd_l()
.trans_mult_vector(1.0, &*delta_aff.s, 0.0, &mut *step_s_l);
let mut step_s_u = s_s_u.make_new();
nlp.pd_u()
.trans_mult_vector(-1.0, &*delta_aff.s, 0.0, &mut *step_s_u);
s_x_l
.frac_to_bound(&*step_x_l, tau)
.min(s_x_u.frac_to_bound(&*step_x_u, tau))
.min(s_s_l.frac_to_bound(&*step_s_l, tau))
.min(s_s_u.frac_to_bound(&*step_s_u, tau))
}
/// Max dual step that keeps `z + α · Δz > 0` (and same for v).
pub fn aff_step_alpha_dual_max(&self, delta_aff: &IteratesVector, tau: Number) -> Number {
let iv = self.curr_iv();
iv.z_l
.frac_to_bound(&*delta_aff.z_l, tau)
.min(iv.z_u.frac_to_bound(&*delta_aff.z_u, tau))
.min(iv.v_l.frac_to_bound(&*delta_aff.v_l, tau))
.min(iv.v_u.frac_to_bound(&*delta_aff.v_u, tau))
}
/// Predicted average complementarity after the affine step:
/// `(1/N) · Σ (s + α_pri · Δs) · (z + α_du · Δz)` summed over the
/// four bound blocks. Returns `0` when there are no bounds.
pub fn aff_step_compl_avrg(
&self,
delta_aff: &IteratesVector,
alpha_primal: Number,
alpha_dual: Number,
) -> Number {
let iv = self.curr_iv();
let n = iv.z_l.dim() + iv.z_u.dim() + iv.v_l.dim() + iv.v_u.dim();
if n == 0 {
return 0.0;
}
let nlp = self.nlp.borrow();
// s_X_L_aff = s_X_L + α_pri · P_L^T Δx
let s_x_l = self.curr_slack_x_l();
let mut s_x_l_aff = s_x_l.make_new();
s_x_l_aff.copy(&*s_x_l);
let mut tmp = s_x_l.make_new();
nlp.px_l()
.trans_mult_vector(1.0, &*delta_aff.x, 0.0, &mut *tmp);
s_x_l_aff.axpy(alpha_primal, &*tmp);
// z_L_aff = z_L + α_du · Δz_L
let mut z_l_aff = iv.z_l.make_new();
z_l_aff.copy(&*iv.z_l);
z_l_aff.axpy(alpha_dual, &*delta_aff.z_l);
let mut acc = s_x_l_aff.dot(&*z_l_aff);
// s_X_U_aff = s_X_U − α_pri · P_U^T Δx
let s_x_u = self.curr_slack_x_u();
let mut s_x_u_aff = s_x_u.make_new();
s_x_u_aff.copy(&*s_x_u);
let mut tmp = s_x_u.make_new();
nlp.px_u()
.trans_mult_vector(-1.0, &*delta_aff.x, 0.0, &mut *tmp);
s_x_u_aff.axpy(alpha_primal, &*tmp);
let mut z_u_aff = iv.z_u.make_new();
z_u_aff.copy(&*iv.z_u);
z_u_aff.axpy(alpha_dual, &*delta_aff.z_u);
acc += s_x_u_aff.dot(&*z_u_aff);
// s_S_L_aff = s_S_L + α_pri · P_dL^T Δs
let s_s_l = self.curr_slack_s_l();
let mut s_s_l_aff = s_s_l.make_new();
s_s_l_aff.copy(&*s_s_l);
let mut tmp = s_s_l.make_new();
nlp.pd_l()
.trans_mult_vector(1.0, &*delta_aff.s, 0.0, &mut *tmp);
s_s_l_aff.axpy(alpha_primal, &*tmp);
let mut v_l_aff = iv.v_l.make_new();
v_l_aff.copy(&*iv.v_l);
v_l_aff.axpy(alpha_dual, &*delta_aff.v_l);
acc += s_s_l_aff.dot(&*v_l_aff);
// s_S_U_aff = s_S_U − α_pri · P_dU^T Δs
let s_s_u = self.curr_slack_s_u();
let mut s_s_u_aff = s_s_u.make_new();
s_s_u_aff.copy(&*s_s_u);
let mut tmp = s_s_u.make_new();
nlp.pd_u()
.trans_mult_vector(-1.0, &*delta_aff.s, 0.0, &mut *tmp);
s_s_u_aff.axpy(alpha_primal, &*tmp);
let mut v_u_aff = iv.v_u.make_new();
v_u_aff.copy(&*iv.v_u);
v_u_aff.axpy(alpha_dual, &*delta_aff.v_u);
acc += s_s_u_aff.dot(&*v_u_aff);
acc / Number::from(n)
}
}
/// Convenience handle. Mirrors upstream's `SmartPtr<CQ>` flow.
pub type IpoptCqHandle = Rc<RefCell<IpoptCalculatedQuantities>>;
/// Bundle of damping indicators for the four bound spaces — kept
/// internal because `kappa_d == 0` makes them dead in the default
/// configuration.
struct DampingIndicators {
x_l: Rc<dyn Vector>,
x_u: Rc<dyn Vector>,
s_l: Rc<dyn Vector>,
s_u: Rc<dyn Vector>,
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ipopt_data::IpoptData;
use crate::iterates_vector::IteratesVector;
use pounce_common::types::Index;
use pounce_linalg::dense_vector::{DenseVector, DenseVectorSpace};
use pounce_linalg::expansion_matrix::{ExpansionMatrix, ExpansionMatrixSpace};
use pounce_linalg::triplet::{GenTMatrix, GenTMatrixSpace};
use std::rc::Rc as StdRc;
fn dvec(values: &[Number]) -> DenseVector {
let space = DenseVectorSpace::new(values.len() as Index);
let mut v = space.make_new_dense();
v.values_mut().copy_from_slice(values);
v
}
fn rcv(values: &[Number]) -> Rc<dyn Vector> {
StdRc::new(dvec(values))
}
/// Mock IpoptNlp covering: 2 vars, 1 equality, 1 inequality.
/// Bounds: x[0] ≥ 0, x[1] ≤ 5, d ≥ 1.
/// f(x) = x[0]^2 + x[1]^2; ∇f = (2x[0], 2x[1])
/// c(x) = x[0] + x[1] - 1
/// d(x) = x[0]
struct MockNlp {
x_l: DenseVector,
x_u: DenseVector,
d_l: DenseVector,
d_u: DenseVector,
px_l: Rc<dyn Matrix>,
px_u: Rc<dyn Matrix>,
pd_l: Rc<dyn Matrix>,
pd_u: Rc<dyn Matrix>,
// NLP scaling factors. Identity by default; `with_scaling`
// installs non-trivial ones to exercise the unscaled accessors.
// (The mock does not actually apply these in `eval_*`; the tests
// verify the unscaling *arithmetic*, not end-to-end scaling.)
obj_scale: Number,
c_scale: Option<Vec<Number>>,
d_scale: Option<Vec<Number>>,
// #292: inject a non-finite component into the gradient / constraint
// Jacobian to exercise the finiteness guard in `curr_nlp_error`.
nan_grad: bool,
nan_jac_c: bool,
empty_jac_c: bool,
// gh#390: the declared equality RHS the c-block relative measure
// divides by. `None` (the default) is the "not tracked" contract.
c_rhs: Option<Vec<Number>>,
// pounce#476: force `c(x)` to a fixed value so a test can isolate the
// inequality block (the default `x0 + x1 - 1` is 4 at the fixture's
// point, which dominates any d-block difference under a max-norm).
c_override: Option<Number>,
}
impl MockNlp {
fn with_c(mut self, v: Number) -> Self {
self.c_override = Some(v);
self
}
fn with_c_rhs(mut self, rhs: Option<Vec<Number>>) -> Self {
self.c_rhs = rhs;
self
}
fn with_nan_grad(mut self) -> Self {
self.nan_grad = true;
self
}
fn with_nan_jac_c(mut self) -> Self {
self.nan_jac_c = true;
self
}
/// Every variable of the equality row fixed and substituted out, so
/// the row reduces to the constant `0 = b` — what
/// `IpoptCalculatedQuantities::row_noise_floor` calls a row no iterate
/// can move.
fn with_empty_jac_c(mut self) -> Self {
self.empty_jac_c = true;
self
}
/// Re-declare the single `d` row as the box `[−mag, +mag]`, so every
/// bound it has is of the chosen magnitude — the default fixture's
/// lower bound of `1` would otherwise supply the magnitude by itself.
/// `d(x) = x0 = 2` sits outside it, violating by `2 − mag`.
fn with_d_box(mut self, mag: Number) -> Self {
self.d_l = dvec(&[-mag]);
self.d_u = dvec(&[mag]);
self.pd_u = StdRc::new(ExpansionMatrix::new(ExpansionMatrixSpace::new(
1,
1,
&[0],
0,
)));
self
}
fn with_scaling(
mut self,
obj_scale: Number,
c_scale: Option<Vec<Number>>,
d_scale: Option<Vec<Number>>,
) -> Self {
self.obj_scale = obj_scale;
self.c_scale = c_scale;
self.d_scale = d_scale;
self
}
fn new() -> Self {
// x_L holds finite lower bounds; here only x[0] has one (=0).
let x_l = dvec(&[0.0]);
// x_U holds finite upper bounds; here only x[1] has one (=5).
let x_u = dvec(&[5.0]);
// d has one finite lower bound (d ≥ 1) and no finite upper.
let d_l = dvec(&[1.0]);
let d_u = dvec(&[]);
let px_l_space = ExpansionMatrixSpace::new(2, 1, &[0], 0);
let px_u_space = ExpansionMatrixSpace::new(2, 1, &[1], 0);
let pd_l_space = ExpansionMatrixSpace::new(1, 1, &[0], 0);
let pd_u_space = ExpansionMatrixSpace::new(1, 0, &[], 0);
Self {
x_l,
x_u,
d_l,
d_u,
px_l: StdRc::new(ExpansionMatrix::new(px_l_space)),
px_u: StdRc::new(ExpansionMatrix::new(px_u_space)),
pd_l: StdRc::new(ExpansionMatrix::new(pd_l_space)),
pd_u: StdRc::new(ExpansionMatrix::new(pd_u_space)),
obj_scale: 1.0,
c_scale: None,
d_scale: None,
nan_grad: false,
nan_jac_c: false,
empty_jac_c: false,
c_rhs: None,
c_override: None,
}
}
}
impl crate::ipopt_nlp::Nlp for MockNlp {
fn n(&self) -> Index {
2
}
fn m_eq(&self) -> Index {
1
}
fn m_ineq(&self) -> Index {
1
}
fn eval_f(&mut self, x: &dyn Vector) -> Number {
// f(x) = x[0]^2 + x[1]^2
let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
xx.values()[0] * xx.values()[0] + xx.values()[1] * xx.values()[1]
}
fn eval_grad_f(&mut self, x: &dyn Vector, g: &mut dyn Vector) {
// grad f = (2 x[0], 2 x[1])
let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
let gg = g.as_any_mut().downcast_mut::<DenseVector>().unwrap();
gg.values_mut()[0] = 2.0 * xx.values()[0];
gg.values_mut()[1] = 2.0 * xx.values()[1];
if self.nan_grad {
gg.values_mut()[0] = Number::NAN;
}
}
fn eval_c(&mut self, x: &dyn Vector, c: &mut dyn Vector) {
let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
let cc = c.as_any_mut().downcast_mut::<DenseVector>().unwrap();
cc.values_mut()[0] = match self.c_override {
Some(v) => v,
None => xx.values()[0] + xx.values()[1] - 1.0,
};
}
fn eval_d(&mut self, x: &dyn Vector, d: &mut dyn Vector) {
let xx = x.as_any().downcast_ref::<DenseVector>().unwrap();
let dd = d.as_any_mut().downcast_mut::<DenseVector>().unwrap();
dd.values_mut()[0] = xx.values()[0];
}
fn eval_jac_c(&mut self, _x: &dyn Vector) -> Rc<dyn Matrix> {
if self.empty_jac_c {
// No entries at all: the row carries no variable.
let space = GenTMatrixSpace::new(1, 2, vec![], vec![]);
let mut jac = GenTMatrix::new(space);
jac.set_values(&[]);
return StdRc::new(jac);
}
// c(x) = x0 + x1 - 1 → Jc = [1, 1] (1×2), nonzeros (1,1),(1,2).
let space = GenTMatrixSpace::new(1, 2, vec![1, 1], vec![1, 2]);
let mut jac = GenTMatrix::new(space);
if self.nan_jac_c {
jac.set_values(&[Number::NAN, 1.0]);
} else {
jac.set_values(&[1.0, 1.0]);
}
StdRc::new(jac)
}
fn eval_jac_d(&mut self, _x: &dyn Vector) -> Rc<dyn Matrix> {
// d(x) = x0 → Jd = [1, 0] (1×2), single nonzero (1,1).
let space = GenTMatrixSpace::new(1, 2, vec![1], vec![1]);
let mut jac = GenTMatrix::new(space);
jac.set_values(&[1.0]);
StdRc::new(jac)
}
fn eval_h(
&mut self,
_x: &dyn Vector,
_obj_factor: Number,
_y_c: &dyn Vector,
_y_d: &dyn Vector,
) -> Rc<dyn SymMatrix> {
unimplemented!()
}
}
impl IpoptNlp for MockNlp {
fn x_l(&self) -> &dyn Vector {
&self.x_l
}
fn x_u(&self) -> &dyn Vector {
&self.x_u
}
fn d_l(&self) -> &dyn Vector {
&self.d_l
}
fn d_u(&self) -> &dyn Vector {
&self.d_u
}
fn px_l(&self) -> Rc<dyn Matrix> {
self.px_l.clone()
}
fn px_u(&self) -> Rc<dyn Matrix> {
self.px_u.clone()
}
fn pd_l(&self) -> Rc<dyn Matrix> {
self.pd_l.clone()
}
fn pd_u(&self) -> Rc<dyn Matrix> {
self.pd_u.clone()
}
fn obj_scaling_factor(&self) -> Number {
self.obj_scale
}
fn c_scale_vec(&self) -> Option<Vec<Number>> {
self.c_scale.clone()
}
fn d_scale_vec(&self) -> Option<Vec<Number>> {
self.d_scale.clone()
}
fn declared_c_rhs(&self) -> Option<Vec<Number>> {
self.c_rhs.clone()
}
}
fn fixture() -> IpoptCalculatedQuantities {
fixture_with(MockNlp::new())
}
fn fixture_with(nlp: MockNlp) -> IpoptCalculatedQuantities {
fixture_with_x(nlp, &[2.0, 3.0])
}
fn fixture_with_x(nlp: MockNlp, x: &[Number]) -> IpoptCalculatedQuantities {
let mut data = IpoptData::new();
data.curr_mu = 0.1;
// Iterate: x as given (2, 3 by default); s = (4); y_c = (1); y_d = (1);
// z_L = (0.5) [bound on x[0]], z_U = (0.7) [bound on x[1]],
// v_L = (0.3), v_U = ().
let iv = IteratesVector::new(
rcv(x),
rcv(&[4.0]),
rcv(&[1.0]),
rcv(&[1.0]),
rcv(&[0.5]),
rcv(&[0.7]),
rcv(&[0.3]),
rcv(&[]),
);
data.set_curr(iv);
let data_handle = StdRc::new(RefCell::new(data));
let nlp: StdRc<RefCell<dyn IpoptNlp>> = StdRc::new(RefCell::new(nlp));
let mut cq = IpoptCalculatedQuantities::new(data_handle, nlp);
// Disable damping for clean unit-test expectations.
cq.kappa_d = 0.0;
cq
}
fn dense_vals(v: &Rc<dyn Vector>) -> Vec<Number> {
v.as_any()
.downcast_ref::<DenseVector>()
.unwrap()
.values()
.to_vec()
}
#[test]
fn slack_x_lower_is_x0_minus_x_l() {
// P_L^T x = [x[0]] = [2]; x_L = [0]; slack = 2 - 0 = 2.
let cq = fixture();
assert_eq!(dense_vals(&cq.curr_slack_x_l()), vec![2.0]);
}
#[test]
fn slack_x_upper_is_x_u_minus_x1() {
// x_U = [5]; P_U^T x = [3]; slack = 5 - 3 = 2.
let cq = fixture();
assert_eq!(dense_vals(&cq.curr_slack_x_u()), vec![2.0]);
}
#[test]
fn slack_s_lower() {
// d_L = [1]; P_L^T s = [4]; slack = 4 - 1 = 3.
let cq = fixture();
assert_eq!(dense_vals(&cq.curr_slack_s_l()), vec![3.0]);
}
#[test]
fn grad_f_is_twice_x() {
let cq = fixture();
assert_eq!(dense_vals(&cq.curr_grad_f()), vec![4.0, 6.0]);
}
#[test]
fn compl_x_l_is_slack_times_z() {
// slack_x_L = [2]; z_L = [0.5]; compl = [1.0]
let cq = fixture();
assert_eq!(dense_vals(&cq.curr_compl_x_l()), vec![1.0]);
}
#[test]
fn relaxed_compl_x_l_subtracts_mu() {
// compl = 1.0; mu = 0.1; relaxed = 0.9.
let cq = fixture();
assert!((dense_vals(&cq.curr_relaxed_compl_x_l())[0] - 0.9).abs() < 1e-15);
}
#[test]
fn sigma_x_routes_z_over_slack_through_p() {
// P_L lifts (z_L/s_L) = (0.5/2 = 0.25) into x[0] slot.
// P_U lifts (z_U/s_U) = (0.7/2 = 0.35) into x[1] slot.
// sigma = (0.25, 0.35)
let cq = fixture();
let s = dense_vals(&cq.curr_sigma_x());
assert!((s[0] - 0.25).abs() < 1e-15);
assert!((s[1] - 0.35).abs() < 1e-15);
}
#[test]
fn sigma_s_lower_only() {
// P_L lifts (v_L/s_L) = (0.3/3 = 0.1).
let cq = fixture();
let s = dense_vals(&cq.curr_sigma_s());
assert!((s[0] - 0.1).abs() < 1e-15);
}
#[test]
fn avrg_compl_averages_over_active_bounds() {
// z_L·s_L + z_U·s_U + v_L·s_s_L + v_U·s_s_U
// = 0.5*2 + 0.7*2 + 0.3*3 + 0
// = 1 + 1.4 + 0.9 = 3.3
// N = 1 + 1 + 1 + 0 = 3 → 1.1
let cq = fixture();
assert!((cq.curr_avrg_compl() - 1.1).abs() < 1e-15);
}
#[test]
fn complementarity_min_takes_min_over_active_pairs() {
// compl entries: z_L·s_L=1.0, z_U·s_U=1.4, v_L·s_s_L=0.9.
// v_U is empty (skipped). Min = 0.9.
let cq = fixture();
assert!((cq.curr_complementarity_min() - 0.9).abs() < 1e-15);
}
#[test]
fn centrality_measure_is_min_over_avrg() {
// min/avrg = 0.9 / 1.1 ≈ 0.81818…
let cq = fixture();
let xi = cq.curr_centrality_measure();
assert!((xi - 0.9 / 1.1).abs() < 1e-15);
}
#[test]
fn curr_f_evaluates_objective() {
// f(x) = x[0]^2 + x[1]^2 at x = (2, 3) → 4 + 9 = 13.
let cq = fixture();
assert!((cq.curr_f() - 13.0).abs() < 1e-15);
}
#[test]
fn curr_barrier_obj_subtracts_mu_log_slacks() {
// f = 13; slacks = (s_x_L=2, s_x_U=2, s_s_L=3, s_s_U=∅).
// log_sum = ln 2 + ln 2 + ln 3 + 0 = 2 ln 2 + ln 3.
// mu = 0.1 → phi = 13 - 0.1*(2 ln 2 + ln 3).
let cq = fixture();
let expected = 13.0 - 0.1 * (2.0 * 2.0_f64.ln() + 3.0_f64.ln());
assert!((cq.curr_barrier_obj() - expected).abs() < 1e-13);
}
/// pounce#476. `inf_pr_output = original` (upstream's default) must report
/// the violation of the **original** rows, not of the internal slack
/// reformulation. The fixture is exactly the case that made the two
/// diverge on Mittelmann's `robot_a`: `d(x) = 2` against `d >= 1` — the
/// original row is *satisfied*, so the original-NLP violation is 0 — while
/// the slack has drifted to `s = 4`, so `|d − s| = 2` and the internal
/// measure reads 2. Reporting the internal number made feasible iterates
/// look badly infeasible (2.79e4 where Ipopt printed 0.00e+00).
///
/// The equality row is genuinely violated (`c = 4`), and both measures
/// must still see it — the fix must not swallow real infeasibility.
#[test]
fn original_nlp_violation_ignores_slack_drift_but_not_a_violated_row() {
let cq = fixture();
// Internal: max(|c|, |d − s|) = max(4, 2) = 4.
assert_eq!(cq.curr_primal_infeasibility_max(), 4.0);
// Original: max(|c|, dist(d, [d_l, d_u])) = max(4, 0) = 4 — the
// equality violation survives, the slack drift does not contribute.
assert_eq!(cq.curr_unscaled_nlp_constraint_violation_max(), 4.0);
}
/// The other half of pounce#476: with the equality block satisfied, the
/// two measures disagree outright — internal still sees the slack drift,
/// original sees a feasible point.
#[test]
fn original_nlp_violation_is_zero_when_only_the_slack_has_drifted() {
let cq = fixture_with(MockNlp::new().with_c(0.0));
assert_eq!(cq.curr_primal_infeasibility_max(), 2.0);
assert_eq!(cq.curr_unscaled_nlp_constraint_violation_max(), 0.0);
}
/// …and the `inf_pr` column must actually be *wired* to the right one.
/// The two tests above pass whichever accessor `OrigIterationOutput`
/// picks, so without this the exact regression — a one-line match arm
/// reaching for `curr_primal_infeasibility_max` — goes unnoticed.
/// `InfPrTag::Original` is upstream's default, so this is what the column
/// prints unless the user asks for `internal`.
#[test]
fn inf_pr_column_prints_the_original_violation_under_the_default_tag() {
use crate::ipopt_data::IpoptData;
use crate::output::orig::{InfPrTag, OrigIterationOutput};
use crate::output::r#trait::IterationOutput;
// Slack drift only: internal reads 2, original reads 0.
let cq: IpoptCqHandle = Rc::new(RefCell::new(fixture_with(MockNlp::new().with_c(0.0))));
let data: IpoptDataHandle = Rc::new(RefCell::new(IpoptData::default()));
let field = |tag| {
let mut out = OrigIterationOutput::new();
out.inf_pr_output = tag;
// Column 2 of the row is `inf_pr` (iter, objective, inf_pr, …).
out.format_row(&data, &cq)
.split_whitespace()
.nth(2)
.unwrap()
.to_string()
};
assert_eq!(field(InfPrTag::Original), "0.00e+00");
assert_eq!(field(InfPrTag::Internal), "2.00e+00");
}
#[test]
fn curr_constraint_violation_is_one_norm() {
// c(x) = x[0]+x[1]-1 = 4 ⇒ |c| = 4.
// d(x)=x[0]=2; s=4 ⇒ d-s = -2 ⇒ |d-s| = 2.
// theta = 4 + 2 = 6.
let cq = fixture();
assert!((cq.curr_constraint_violation() - 6.0).abs() < 1e-13);
}
/// gh#390. The fixture's equality row is `x0 + x1 == 1` at `x = (2, 3)`,
/// so `c = 4`. Judged against a declared RHS of 2 that is a 200% violation
/// — and it is 200% however the row is written, which is the point.
#[test]
fn relative_c_infeasibility_is_residual_over_declared_rhs() {
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![2.0])));
assert_eq!(cq.relative_c_infeasibility_max(), 2.0);
// The fixture's inequality row (`d = 2` against `d >= 1`) is satisfied,
// so the combined measure is the equality block's verdict.
assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
assert_eq!(cq.curr_relative_primal_infeasibility_max(), 2.0);
}
/// An NLP that does not track the pre-fold RHS (the trait default, e.g.
/// the restoration NLP) must abstain rather than invent a magnitude.
#[test]
fn relative_c_infeasibility_abstains_without_declared_rhs() {
let cq = fixture();
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
assert_eq!(cq.curr_relative_primal_infeasibility_max(), 0.0);
}
/// A homogeneous row (`g(x) == 0`) has no declared magnitude and needs
/// none — `s·g(x) == 0` is the same row at every `s`. Dividing by its zero
/// RHS would report every float-noise residual as an infinite violation.
#[test]
fn relative_c_infeasibility_abstains_on_homogeneous_row() {
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![0.0])));
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
}
/// An unjudgeable row must not fabricate a relative verdict.
#[test]
fn relative_c_infeasibility_abstains_on_non_finite_rhs() {
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::INFINITY])));
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::NAN])));
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
}
/// gh #446. "Homogeneous" has to be judged numerically. The fixture's row
/// is `x0 + x1 == b` at `x = (2, 3)`, so its noise floor is
/// `ROW_NOISE_KAPPA · eps · 1 · 3 ≈ 4.3e-14`: an RHS under that is
/// rounding residue — a converter writing `2^-53` where the model says
/// `0` — and the row must abstain exactly as a declared zero does. Above
/// the floor the RHS is real data and is judged, however small.
#[test]
fn relative_c_infeasibility_abstains_on_rhs_below_the_row_noise_floor() {
let floor = ROW_NOISE_KAPPA * Number::EPSILON * 3.0;
// The QSCSD1 value: an RHS of exactly one machine epsilon.
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![Number::EPSILON])));
assert!(Number::EPSILON < floor);
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
// Just above the floor the row still carries a magnitude, and a
// residual of 4 against it is judged on its merits.
let rhs = 2.0 * floor;
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![rhs])));
assert_eq!(cq.relative_c_infeasibility_max(), 4.0 / rhs);
}
/// gh #446. Every variable of the row fixed and substituted out leaves
/// `0 = b`, which no iterate can move — a statement about the model, for
/// presolve to certify, not a residual to judge an iterate by. QPILOTNO's
/// row 150 reduces to `0 = −2.22e-16` this way and pinned the relative
/// measure at 100% for the entire run.
#[test]
fn relative_c_infeasibility_abstains_on_a_row_no_iterate_can_move() {
let cq = fixture_with(
MockNlp::new()
.with_empty_jac_c()
.with_c_rhs(Some(vec![Number::EPSILON])),
);
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
// Not a licence to ignore a real one: the absolute `constr_viol_tol`
// arm still sees the row, and it is what governs here.
assert_eq!(cq.curr_primal_infeasibility_max(), 4.0);
}
/// gh #446. The inequality block draws its magnitude from the declared
/// bounds, and needs the same numeric reading of "zero" — QPILOTNO carries
/// 43 bounds at `1e-17`–`1e-15`. `d(x) = x0 = 2` against an upper bound
/// under the row's noise floor is 2e14 times its magnitude by the old
/// arithmetic, and unjudgeable by the new.
#[test]
fn relative_d_infeasibility_abstains_on_bound_below_the_row_noise_floor() {
let floor = ROW_NOISE_KAPPA * Number::EPSILON * 3.0;
let cq = fixture_with(MockNlp::new().with_d_box(Number::EPSILON));
assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
// A bound above the floor is real, and `d = 2` violates it hugely.
let bound = 2.0 * floor;
let cq = fixture_with(MockNlp::new().with_d_box(bound));
assert_eq!(cq.relative_d_infeasibility_max(), (2.0 - bound) / bound);
}
/// The floor tracks `‖x‖_∞` **deliberately**, and this pins it. `x` is one
/// vector produced by a linear solve with norm-wise backward error, so a
/// large variable anywhere really does coarsen how finely every other
/// component can be placed — and a declared magnitude finer than that is a
/// target no iterate could hit. The per-row alternative, `Σ_j |a_ij x_j|`
/// via `|J|·|x|`, looks more precise and measures the wrong thing (a row's
/// *evaluation* error, not what limits its residual); it was implemented
/// and it regressed QETAMACR, QSCORPIO and QPILOTNO of gh #446's 15. Re-run
/// those three before changing this.
#[test]
fn row_noise_floor_tracks_the_iterate_norm() {
// `d(x) = x0` against a declared box of ±1e-9.
let bound = 1e-9;
// At ‖x‖_∞ = 3 the floor is ~4.3e-14: the bound is real data, judged.
let cq = fixture_with(MockNlp::new().with_d_box(bound));
assert_eq!(cq.relative_d_infeasibility_max(), (2.0 - bound) / bound);
// At ‖x‖_∞ = 1e8 the floor is ~1.4e-6 and the same bound is finer than
// the iterate can be resolved, so the row abstains.
let cq = fixture_with_x(MockNlp::new().with_d_box(bound), &[2.0, 1e8]);
assert_eq!(cq.relative_d_infeasibility_max(), 0.0);
}
/// A row-count mismatch means the RHS does not describe this `c` block;
/// pairing them up anyway would judge rows against other rows' magnitudes.
#[test]
fn relative_c_infeasibility_abstains_on_length_mismatch() {
let cq = fixture_with(MockNlp::new().with_c_rhs(Some(vec![2.0, 2.0])));
assert_eq!(cq.relative_c_infeasibility_max(), 0.0);
}
#[test]
fn grad_barrier_obj_x_subtracts_mu_inv_slack() {
// grad_f = (4, 6).
// P_L lifts -mu*(1/s_x_L) = -0.1*(1/2)=-0.05 into x[0].
// P_U lifts +mu*(1/s_x_U) = +0.1*(1/2)=+0.05 into x[1].
// result = (4 - 0.05, 6 + 0.05) = (3.95, 6.05).
let cq = fixture();
let g = dense_vals(&cq.curr_grad_barrier_obj_x());
assert!((g[0] - 3.95).abs() < 1e-13);
assert!((g[1] - 6.05).abs() < 1e-13);
}
#[test]
fn grad_lag_s_is_minus_y_d_minus_pl_v_l_plus_pu_v_u() {
// tmp = P_U v_U = (zero-dim contrib) → 0
// tmp -= P_L v_L → tmp = -[0.3]
// tmp -= y_d = -[0.3] - [1.0] = [-1.3]
let cq = fixture();
assert!((dense_vals(&cq.curr_grad_lag_s())[0] + 1.3).abs() < 1e-15);
}
fn zero_iv_like(iv: &IteratesVector) -> IteratesVector {
// Materialize explicit zeros for every component so the
// affine-step tests can compose direct-sum updates.
IteratesVector::new(
rcv(&vec![0.0; iv.x.dim() as usize]),
rcv(&vec![0.0; iv.s.dim() as usize]),
rcv(&vec![0.0; iv.y_c.dim() as usize]),
rcv(&vec![0.0; iv.y_d.dim() as usize]),
rcv(&vec![0.0; iv.z_l.dim() as usize]),
rcv(&vec![0.0; iv.z_u.dim() as usize]),
rcv(&vec![0.0; iv.v_l.dim() as usize]),
rcv(&vec![0.0; iv.v_u.dim() as usize]),
)
}
#[test]
fn aff_step_compl_avrg_with_zero_step_matches_curr_avrg_compl() {
// Δ_aff = 0 ⇒ predicted compl ≡ current compl.
// s_X_L · z_L = 2·0.5=1, s_X_U·z_U=2·0.7=1.4, s_S_L·v_L=3·0.3=0.9.
// Total = 3.3; N = 3 (z_l + z_u + v_l, v_u empty); avrg = 1.1.
let cq = fixture();
let iv = cq.curr_iv();
let zero = zero_iv_like(&iv);
let m = cq.aff_step_compl_avrg(&zero, 1.0, 1.0);
assert!((m - 1.1).abs() < 1e-13);
assert!((cq.curr_avrg_compl() - 1.1).abs() < 1e-13);
}
#[test]
fn aff_step_compl_avrg_responds_to_primal_step() {
// Δ_aff.x = (1, 0), α_pri = 1, others = 0.
// s_X_L_aff = 2 + 1·1 = 3; s_X_U_aff = 2 (P_U^T·dx = 0); s_S_L_aff = 3.
// (3·0.5 + 2·0.7 + 3·0.3) / 3 = (1.5 + 1.4 + 0.9) / 3 = 1.2667.
let cq = fixture();
let iv = cq.curr_iv();
let mut z = zero_iv_like(&iv);
z.x = rcv(&[1.0, 0.0]);
let m = cq.aff_step_compl_avrg(&z, 1.0, 1.0);
assert!((m - 1.2666666666666666).abs() < 1e-13);
}
#[test]
fn aff_step_alpha_primal_truncates_to_x_lower_bound() {
// Δ_aff.x = (-3, 0); s_X_L = 2; tau = 1 ⇒ α_max = 2/3.
let cq = fixture();
let iv = cq.curr_iv();
let mut z = zero_iv_like(&iv);
z.x = rcv(&[-3.0, 0.0]);
let a = cq.aff_step_alpha_primal_max(&z, 1.0);
assert!((a - 2.0 / 3.0).abs() < 1e-13);
}
#[test]
fn aff_step_alpha_dual_truncates_to_z_lower_bound() {
// Δ_aff.z_L = (-1); z_L = 0.5; tau = 1 ⇒ α_max = 0.5.
let cq = fixture();
let iv = cq.curr_iv();
let mut z = zero_iv_like(&iv);
z.z_l = rcv(&[-1.0]);
let a = cq.aff_step_alpha_dual_max(&z, 1.0);
assert!((a - 0.5).abs() < 1e-13);
}
#[test]
fn grad_barr_t_delta_dots_barrier_grads_with_step() {
// ∇_x φ = (3.95, 6.05); ∇_s φ = (-mu/s_s_L) = -0.1/3 ≈ -0.03333…
// δx = (1, 2); δs = (3): result = 3.95·1 + 6.05·2 + (-0.0333…)·3
// = 3.95 + 12.10 − 0.1 = 15.95.
let cq = fixture();
let dx = dvec(&[1.0, 2.0]);
let ds = dvec(&[3.0]);
let r = cq.curr_grad_barr_t_delta(&dx, &ds);
let expected = 3.95 + 12.10 - 0.1;
assert!((r - expected).abs() < 1e-13, "r = {r}");
}
#[test]
fn dwd_with_no_w_collapses_to_sigma_quadratic() {
// W is None in the fixture (no Hessian seeded), perts default to 0.
// σ_x = (0.25, 0.35); σ_s = (0.1).
// δx = (2, -1); δs = (3) ⇒ dWd = 0.25·4 + 0.35·1 + 0.1·9
// = 1.00 + 0.35 + 0.90 = 2.25.
let cq = fixture();
let dx = dvec(&[2.0, -1.0]);
let ds = dvec(&[3.0]);
let r = cq.curr_dwd(&dx, &ds);
assert!((r - 2.25).abs() < 1e-13, "r = {r}");
}
#[test]
fn dwd_includes_pd_perturbations() {
// Without perts: dWd = 0.25·4 + 0.35·1 + 0.1·9 = 2.25.
// δ_pert_x = 0.5, δ_pert_s = 0.25:
// add δ_pert_x · ‖δx‖² + δ_pert_s · ‖δs‖²
// = 0.5·(4+1) + 0.25·9 = 2.5 + 2.25 = 4.75.
// Total = 7.00.
let cq = fixture();
{
let mut d = cq.data.borrow_mut();
d.perturbations.delta_x = 0.5;
d.perturbations.delta_s = 0.25;
}
let dx = dvec(&[2.0, -1.0]);
let ds = dvec(&[3.0]);
let r = cq.curr_dwd(&dx, &ds);
assert!((r - 7.00).abs() < 1e-13, "r = {r}");
}
// ---- #292: NaN gradient / Jacobian must not launder to a finite KKT error
#[test]
fn nlp_error_is_finite_for_a_finite_iterate() {
// Baseline: the well-formed fixture produces a finite, positive KKT
// error (this iterate is not a KKT point). The finiteness guard added
// for #292 must not perturb this normal path.
let cq = fixture();
let err = cq.curr_nlp_error();
assert!(err.is_finite() && err > 0.0, "err = {err}");
}
#[test]
fn nlp_error_is_non_finite_when_gradient_has_nan() {
// A NaN gradient component reaches ∇_x L, whose max-norm (`amax`)
// silently drops NaN and would launder the dual infeasibility to a
// finite value → bogus `Solve_Succeeded` (#292). `curr_nlp_error` must
// instead surface a non-finite error so the caller's
// `!nlp_err.is_finite()` guard fires `Invalid_Number_Detected`.
let cq = fixture_with(MockNlp::new().with_nan_grad());
assert!(
!cq.curr_nlp_error().is_finite(),
"NaN gradient laundered to finite KKT error: {}",
cq.curr_nlp_error()
);
}
#[test]
fn nlp_error_is_non_finite_when_constraint_jacobian_has_nan() {
// A NaN in the constraint Jacobian enters ∇_x L through the Jᵀy term
// and is likewise laundered by `amax` on the fixture's nonzero
// multipliers. Must read as a non-finite KKT error, not `Optimal`.
let cq = fixture_with(MockNlp::new().with_nan_jac_c());
assert!(
!cq.curr_nlp_error().is_finite(),
"NaN constraint Jacobian laundered to finite KKT error: {}",
cq.curr_nlp_error()
);
}
// ---- Unscaled (user-space) KKT residuals — pounce#173 -------------
#[test]
fn unscaled_dual_inf_is_scaled_over_df() {
// df = 2: every Lagrangian-gradient term carries the objective
// factor, so the unscaled dual infeasibility is the scaled one
// divided by df.
let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
let scaled = cq.curr_dual_infeasibility_max();
let unscaled = cq.curr_unscaled_dual_infeasibility_max();
assert!(scaled > 0.0, "fixture should have nonzero dual inf");
assert!(
(unscaled - scaled / 2.0).abs() < 1e-12,
"unscaled {unscaled} != scaled/df {}",
scaled / 2.0
);
}
/// gh #532. The dual *scale* is the largest single term `∇L` is assembled
/// from, so the strict gate can ask what fraction of those terms failed to
/// cancel instead of comparing a residual against an absolute constant.
#[test]
fn dual_inf_scale_is_the_largest_lagrangian_term() {
// Fixture at x = (2, 3): ∇f = (4, 6); J_cᵀ y_c = (1, 1); J_dᵀ y_d =
// (1, 0); y_d = 1; P_L z_L = 0.5; P_U z_U = 0.7; P_L v_L = 0.3; v_U is
// empty. The largest is ‖∇f‖_∞ = 6.
let cq = fixture();
assert_eq!(cq.curr_dual_infeasibility_scale_max(), 6.0);
// No scaling → the unscaled accessor is the identity, as for every
// other residual on the common path.
assert_eq!(
cq.curr_unscaled_dual_infeasibility_scale_max(),
cq.curr_dual_infeasibility_scale_max()
);
}
/// The scale unscales exactly as the residual it is the scale of: every
/// term of the scaled Lagrangian gradient carries `df`, so both are the
/// scaled value over `|df|`. If the two ever divided differently the ratio
/// the strict gate tests would silently pick up a factor of `df`.
#[test]
fn unscaled_dual_inf_scale_is_scaled_over_df() {
let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
assert_eq!(cq.curr_unscaled_dual_infeasibility_scale_max(), 3.0);
// A negative factor is the documented way to pose a maximization; a
// max-norm has no business coming back negative (the sign trap that
// defeated the unscaled dual residual gate).
let neg = fixture_with(MockNlp::new().with_scaling(-2.0, None, None));
assert_eq!(neg.curr_unscaled_dual_infeasibility_scale_max(), 3.0);
}
#[test]
fn unscaled_residuals_are_identity_without_scaling() {
// df = 1, no row scaling → unscaled accessors return exactly the
// scaled values (the common no-scaling path).
let cq = fixture();
assert_eq!(
cq.curr_unscaled_dual_infeasibility_max(),
cq.curr_dual_infeasibility_max()
);
assert_eq!(
cq.curr_unscaled_complementarity_max(),
cq.curr_complementarity_max()
);
assert_eq!(
cq.curr_unscaled_primal_infeasibility_max(),
cq.curr_primal_infeasibility_max()
);
}
#[test]
fn unscaled_compl_is_scaled_over_df() {
let cq = fixture_with(MockNlp::new().with_scaling(2.0, None, None));
let scaled = cq.curr_complementarity_max();
let unscaled = cq.curr_unscaled_complementarity_max();
assert!(scaled > 0.0);
assert!((unscaled - scaled / 2.0).abs() < 1e-12);
}
#[test]
fn unscaled_primal_divides_each_row_by_its_factor() {
// Fixture residuals: c = x0+x1-1 = 4; d-s = x0 - s = 2 - 4 = -2.
// Scaled max-norm primal = max(|4|, |-2|) = 4.
// With dc = [4], dd = [2]: unscaled = max(|4/4|, |-2/2|) = 1.
let cq = fixture_with(MockNlp::new().with_scaling(1.0, Some(vec![4.0]), Some(vec![2.0])));
assert!((cq.curr_primal_infeasibility_max() - 4.0).abs() < 1e-12);
assert!(
(cq.curr_unscaled_primal_infeasibility_max() - 1.0).abs() < 1e-12,
"got {}",
cq.curr_unscaled_primal_infeasibility_max()
);
}
#[test]
fn unscaled_nlp_error_is_max_of_unscaled_components() {
let cq = fixture_with(MockNlp::new().with_scaling(2.0, Some(vec![4.0]), Some(vec![2.0])));
let expected = cq
.curr_unscaled_dual_infeasibility_max()
.max(cq.curr_unscaled_primal_infeasibility_max())
.max(cq.curr_unscaled_complementarity_max());
assert_eq!(cq.curr_unscaled_nlp_error(), expected);
}
/// gh #528. A component at or below its own floor drops out; everything
/// above it is counted in full, not net of the floor — the question the
/// floor answers is whether the row says anything at all.
#[test]
fn amax_above_floor_drops_only_sub_floor_components() {
let v = dvec(&[1e-9, -3e-7, 5e-3]);
assert_eq!(amax_above_floor(&v, &[1e-8, 1e-8, 1e-8]), 5e-3);
// The largest component is the only one under its floor: the max comes
// from what remains, not from the vector's own `amax`.
assert_eq!(amax_above_floor(&v, &[1e-8, 1e-8, 1.0]), 3e-7);
// Everything silenced.
assert_eq!(amax_above_floor(&v, &[1.0, 1.0, 1.0]), 0.0);
// Exactly at the floor is silenced (`>`, not `>=`).
assert_eq!(amax_above_floor(&dvec(&[1e-8]), &[1e-8]), 0.0);
}
/// A floor that cannot be attributed component-wise must not silence
/// anything: over-reporting the residual is the safe direction.
#[test]
fn amax_above_floor_falls_back_on_a_length_mismatch() {
let v = dvec(&[1e-9, -3e-7]);
assert_eq!(amax_above_floor(&v, &[1.0]), 3e-7);
assert_eq!(amax_above_floor(&v, &[]), 3e-7);
}
/// The floored aggregate is never larger than the raw one, and on a
/// fixture whose residuals (`c = 4`, `d − s = −2`) are nowhere near any
/// resolution limit the two are identical — the common path is untouched.
#[test]
fn nlp_error_above_primal_noise_matches_on_ordinary_residuals() {
let cq = fixture_with(MockNlp::new());
assert_eq!(
cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
cq.curr_primal_infeasibility_max()
);
assert_eq!(
cq.curr_nlp_error_above_primal_noise(ROW_NOISE_KAPPA),
cq.curr_nlp_error()
);
}
/// gh #528, **equality block**, through the real accessor rather than a
/// hand-supplied floor. The integration LP is all-inequality (`g_u = 2e19`,
/// so `c.dim() == 0`), so this is the only cover the `declared_c_rhs()`
/// branch has.
///
/// `x = (4, 3)` puts `d = x0 = 4` on top of `s = 4`, so the inequality
/// block's residual is an exact `0` and what the accessor returns is the
/// `c` block alone.
#[test]
fn a_sub_quantum_equality_residual_is_silenced_and_a_coarser_one_is_not() {
let rhs = 1e8;
let floor = ROW_NOISE_KAPPA * Number::EPSILON * rhs;
let cq_for = |c: Number| {
fixture_with_x(
MockNlp::new().with_c_rhs(Some(vec![rhs])).with_c(c),
&[4.0, 3.0],
)
};
// Under the quantum of `g(x) − b` at `|b| = 1e8`: no iterate could
// have placed the residual here, so the row says nothing.
let cq = cq_for(floor * 0.5);
assert_eq!(cq.curr_primal_infeasibility_max(), floor * 0.5);
assert_eq!(
cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
0.0
);
// Above it: counted in full, not net of the floor.
let cq = cq_for(floor * 2.0);
assert_eq!(
cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
floor * 2.0
);
// The placement floor alone would not have silenced anything here —
// at ‖x‖_∞ = 4 through a row of `max_j |∂c/∂x_j| = 1` it is ~5.7e-14,
// eight decades under the formation floor. The `c` branch's own
// magnitude is what does the work.
let cq = fixture_with_x(MockNlp::new().with_c(floor * 0.5), &[4.0, 3.0]);
assert_eq!(
cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
floor * 0.5
);
}
/// The `primal_noise_floor_kappa = 0` escape hatch: every floor collapses
/// to `0`, so every residual is counted and the floored aggregate is the
/// raw one — the strict gate is bit-for-bit upstream Ipopt's again. Pinned
/// on a fixture where the floor otherwise *does* silence the row, so this
/// cannot pass by the two agreeing anyway.
#[test]
fn a_zero_kappa_switches_the_floor_off_completely() {
let rhs = 1e8;
let residual = ROW_NOISE_KAPPA * Number::EPSILON * rhs * 0.5;
let cq = fixture_with_x(
MockNlp::new().with_c_rhs(Some(vec![rhs])).with_c(residual),
&[4.0, 3.0],
);
// The floor is live at the default kappa …
assert_eq!(
cq.curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
0.0
);
// … and gone at zero.
assert_eq!(
cq.curr_primal_infeasibility_above_noise(0.0),
cq.curr_primal_infeasibility_max()
);
assert_eq!(
cq.curr_nlp_error_above_primal_noise(0.0),
cq.curr_nlp_error()
);
}
/// The equality floor rides the row scaling, because both sides of the
/// comparison do: `declared_c_rhs()` reapplies `c_scale` (pinned by
/// `declared_c_rhs_carries_the_row_scaling` in `orig_ipopt_nlp.rs`) and
/// `curr_c()` is the scaled residual `dc · (g(x) − b)`. Scaling a row by
/// `k` scales its residual and its floor together, so the verdict is
/// invariant — which is what makes it legitimate to compare a floor built
/// from the declared RHS against `curr_c()` at all.
#[test]
fn the_equality_floor_rides_the_row_scaling() {
let rhs = 1e8;
let quantum = ROW_NOISE_KAPPA * Number::EPSILON * rhs;
for k in [1.0, 4.0, 0.25] {
let cq_for = |c: Number| {
fixture_with_x(
MockNlp::new()
.with_scaling(1.0, Some(vec![k]), None)
.with_c_rhs(Some(vec![k * rhs]))
.with_c(k * c),
&[4.0, 3.0],
)
};
assert_eq!(
cq_for(quantum * 0.5).curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
0.0,
"sub-quantum residual must stay silenced at row scaling {k}",
);
assert_eq!(
cq_for(quantum * 2.0).curr_primal_infeasibility_above_noise(ROW_NOISE_KAPPA),
k * quantum * 2.0,
"above-quantum residual must survive at row scaling {k}",
);
}
}
}