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
//! Algorithm builder — port of `Algorithm/IpAlgBuilder.{hpp,cpp}`.
//!
//! Reads `OptionsList`, walks the dependency order documented in
//! `ref/Ipopt/AGENT_REFERENCE/ARCHITECTURE.md` §"BuildBasicAlgorithm",
//! and assembles the strategy objects needed by `IpoptAlgorithm`:
//!
//! * `SymLinearSolver` (MA57 / MUMPS / FERAL) → `AugSystemSolver`
//! (`StdAugSystemSolver`) → `PdSystemSolver` (`PdFullSpaceSolver`)
//! → `SearchDirCalculator` (`PdSearchDirCalc`).
//! * `BacktrackingLsAcceptor` (filter / penalty / cg-penalty) →
//! `BacktrackingLineSearch`.
//! * `MuUpdate` (monotone / adaptive[+oracle]).
//! * `ConvCheck` (`OptErrorConvCheck`).
//! * `IterateInitializer` (default / warm-start) and
//! `EqMultCalculator` (`LeastSquareMults`).
//! * `HessianUpdater` (exact / limited-memory).
//! * `IterationOutput` (`OrigIterationOutput`).
//! * `NLPScalingObject` (none / user / gradient-based / equilibration-based).
//!
//! Phase 7 ships the option-driven dispatch surface; the assembled
//! `IpoptAlgorithm` lands once each strategy's arithmetic does.
use crate::conv_check::opt_error::OptErrorConvCheck;
use crate::eq_mult::least_square::LeastSquareMults;
use crate::hess::exact::ExactHessianUpdater;
use crate::hess::lim_mem_quasi_newton::{InitialApprox, LimMemQuasiNewtonUpdater, UpdateType};
use crate::init::default::DefaultIterateInitializer;
use crate::init::warm_start::WarmStartIterateInitializer;
use crate::kkt::aug_system_solver::AugSystemSolver;
use crate::kkt::low_rank_aug_system_solver::LowRankAugSystemSolver;
use crate::kkt::pd_full_space_solver::PdFullSpaceSolver;
use crate::kkt::pd_search_dir_calc::PdSearchDirCalc;
use crate::kkt::perturbation_handler::PdPerturbationHandler;
use crate::kkt::std_aug_system_solver::StdAugSystemSolver;
use crate::line_search::backtracking::BacktrackingLineSearch;
use crate::line_search::filter_acceptor::FilterLsAcceptor;
use crate::line_search::ls_acceptor::BacktrackingLsAcceptor;
use crate::line_search::penalty_acceptor::PenaltyLsAcceptor;
use crate::mu::adaptive::{AdaptiveMuUpdate, MuOracleKind};
use crate::mu::monotone::MonotoneMuUpdate;
use crate::output::orig::OrigIterationOutput;
use pounce_common::types::{Index, Number};
use pounce_linsol::{SparseSymLinearSolverInterface, TSymLinearSolver};
use std::cell::RefCell;
use std::rc::Rc;
/// Backend factory — the application supplies one before calling
/// [`AlgorithmBuilder::build`]. Mirrors upstream's
/// `SymLinearSolverFactory` knob in `IpAlgBuilder.cpp`. The default
/// factory wires in FERAL; MA57 is selectable when the `ma57` cargo
/// feature is enabled.
pub type LinearBackendFactory =
Box<dyn FnMut(LinearSolverChoice) -> Box<dyn SparseSymLinearSolverInterface>>;
/// Top-level algorithm choice. `InteriorPoint` is pounce's default
/// (the existing `IpoptAlgorithm`); `ActiveSetSqp` is the
/// Phase 5b SQP driver in `crate::sqp::SqpAlgorithm`, which uses
/// `pounce-qp` for QP subproblem solves and reuses
/// `FilterLsAcceptor` for globalization.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum AlgorithmChoice {
#[default]
InteriorPoint,
ActiveSetSqp,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LinearSolverChoice {
Ma57,
Feral,
}
/// Symmetric scaling method applied to the augmented KKT system by
/// [`TSymLinearSolver`]. Mirrors the `linear_system_scaling` option
/// in `IpAlgBuilder.cpp:302-318` and the `RuizTSymScalingMethod` /
/// `Mc19TSymScalingMethod` strategies in upstream Ipopt.
///
/// * `None` (default) — no scaling; `TSymLinearSolver` runs with a
/// null scaling method. Matches upstream's default.
/// * `Ruiz` — iterative symmetric ∞-norm equilibration (Ruiz, 2001).
/// Implemented in `pounce_linsol::RuizTSymScalingMethod`.
/// * `Mc19` — Curtis-Reid (HSL MC19) scaling. Not yet implemented;
/// falls back to `None` with a warning.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LinearSystemScalingChoice {
#[default]
None,
Ruiz,
Mc19,
/// `slack-based` — `IpSlackBasedTSymScalingMethod`. Unlike the
/// others this one is a function of the iterate, not of the matrix,
/// so the algorithm pushes the `s`-block factors down each
/// iteration (see `IpoptAlgorithm::push_slack_scaling`).
SlackBased,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MuStrategyChoice {
Monotone,
Adaptive,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HessianApproxChoice {
Exact,
LimitedMemory,
/// Partitioned quasi-Newton: one small dense block per element
/// function (the objective and each constraint row), assembled into
/// a genuine sparse `SymTMatrix`. See
/// [`crate::hess::partitioned_quasi_newton`].
Partitioned,
/// Sparse finite-difference Lagrangian Hessian, recovered by graph
/// coloring from the analytic Jacobian. See
/// [`crate::hess::fd_hessian`].
FiniteDifference,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LineSearchChoice {
Filter,
CgPenalty,
Penalty,
}
/// Assembled strategy bundle. Phase 7 ships the structural bundle;
/// `IpoptAlgorithm::new` reads from this when it lands.
pub struct AlgorithmBundle {
pub mu_update: Box<dyn crate::mu::r#trait::MuUpdate>,
pub conv_check: Box<dyn crate::conv_check::r#trait::ConvCheck>,
pub init: Box<dyn crate::init::r#trait::IterateInitializer>,
pub eq_mult: Box<dyn crate::eq_mult::r#trait::EqMultCalculator>,
pub hess: Box<dyn crate::hess::r#trait::HessianUpdater>,
pub line_search: BacktrackingLineSearch,
pub iter_output: Box<dyn crate::output::r#trait::IterationOutput>,
/// `Some` when the builder was given a [`LinearBackendFactory`];
/// `None` for the bare structural bundle that pre-Phase-6 unit
/// tests still rely on.
pub search_dir: Option<PdSearchDirCalc>,
}
/// Knobs read off `OptionsList` and baked into the assembled
/// `OptErrorConvCheck`. Defaults mirror
/// `IpOptErrorConvCheck.cpp:RegisterOptions`.
#[derive(Debug, Clone)]
pub struct ConvCheckOptions {
pub tol: Number,
pub dual_inf_tol: Number,
pub constr_viol_tol: Number,
pub compl_inf_tol: Number,
pub acceptable_tol: Number,
pub acceptable_dual_inf_tol: Number,
pub acceptable_constr_viol_tol: Number,
pub acceptable_compl_inf_tol: Number,
pub acceptable_obj_change_tol: Number,
pub acceptable_iter: Index,
pub max_iter: Index,
pub max_cpu_time: Number,
pub max_wall_time: Number,
pub infeas_stationarity_tol: Number,
pub infeas_viol_kappa: Number,
pub infeas_max_streak: Index,
/// Objective-scale floor below which a strict termination certificate is
/// refused while the unscaled KKT error is still above `acceptable_tol`
/// (gh #200). `0` disables the mechanism.
pub obj_scale_certificate_threshold: Number,
/// Safety factor on the per-row floor the **strict** gate uses to decide
/// when a constraint residual is finer than the row can represent
/// (gh #528). `0` disables the floor, restoring upstream Ipopt's
/// bare-absolute primal term.
pub primal_noise_floor_kappa: Number,
/// Fraction of `acceptable_tol` the KKT error and the objective may drift
/// across the acceptable-level streak's window while the streak still
/// counts as settled (gh #533). `0` disables the progress test, leaving
/// acceptable-level termination the bare consecutive-count criterion.
pub acceptable_progress_kappa: Number,
/// Safety factor on the scale-relative floor under `dual_inf_tol` the
/// **strict** gate judges the dual infeasibility against (gh #532). `0`
/// disables the floor, restoring upstream Ipopt's bare-absolute bound.
pub dual_inf_scale_kappa: Number,
}
impl Default for ConvCheckOptions {
fn default() -> Self {
Self {
tol: 1e-8,
dual_inf_tol: 1.0,
constr_viol_tol: 1e-4,
compl_inf_tol: 1e-4,
acceptable_tol: 1e-6,
acceptable_dual_inf_tol: 1e10,
acceptable_constr_viol_tol: 1e-2,
acceptable_compl_inf_tol: 1e-2,
acceptable_obj_change_tol: 1e20,
acceptable_iter: 15,
max_iter: 3000,
max_cpu_time: 1e6,
max_wall_time: 1e6,
infeas_stationarity_tol: 1e-8,
infeas_viol_kappa: 1e2,
infeas_max_streak: 5,
obj_scale_certificate_threshold: 1e-4,
primal_noise_floor_kappa: 64.0,
acceptable_progress_kappa: 1e-1,
dual_inf_scale_kappa: 1.0,
}
}
}
#[derive(Debug, Clone)]
pub struct AlgorithmBuilder {
/// Top-level algorithm dispatch. Default `InteriorPoint` ⇒
/// `build_with_backend` returns the existing `AlgorithmBundle`
/// (consumed by `IpoptAlgorithm`). `ActiveSetSqp` ⇒ caller
/// must use `build_sqp_with_backend` to assemble the Phase 5b
/// `SqpAlgorithm`. The two builder methods sit side by side
/// because the assembled algorithm shape differs (IPM bundle
/// vs SQP struct).
pub algorithm: AlgorithmChoice,
pub linear_solver: LinearSolverChoice,
/// Symmetric scaling method for the augmented KKT system. Wired
/// into [`TSymLinearSolver`] by [`Self::build_with_backend`].
/// Mirrors upstream `linear_system_scaling` (`IpAlgBuilder.cpp:538-560`).
pub linear_system_scaling: LinearSystemScalingChoice,
/// Lazy-vs-eager scaling toggle (`linear_scaling_on_demand`,
/// `IpTSymLinearSolver.cpp:50-58`). Only consulted when
/// `linear_system_scaling != None`. Upstream default is `true`
/// (compute scaling only on the first solve that fails / shows
/// poor conditioning); pounce mirrors that. Set to `false` to
/// scale every factorization.
pub linear_scaling_on_demand: bool,
pub mu_strategy: MuStrategyChoice,
/// Selector forwarded to [`AdaptiveMuUpdate`] when
/// `mu_strategy = Adaptive`. Ignored for `Monotone`. Defaults to
/// `QualityFunction` per upstream's `RegisterOptions` default.
pub mu_oracle: MuOracleKind,
pub hessian_approximation: HessianApproxChoice,
/// Element update formula for
/// [`HessianApproxChoice::Partitioned`] (`partitioned_update_type`).
/// SR1 by default: a single constraint is not convex, so damped
/// BFGS would force every `∇²c_j` model PSD and then scale it by a
/// multiplier of either sign.
pub partitioned_update_type: UpdateType,
/// Whether the caller named `partitioned_update_type` explicitly, so
/// the block mode's BFGS default does not override them.
pub partitioned_update_type_was_set: bool,
/// Widest element that keeps a dense block under
/// [`HessianApproxChoice::Partitioned`]; wider elements degrade to a
/// diagonal approximation (`partitioned_max_element`).
pub partitioned_max_element: usize,
/// Variables the **objective** is nonlinear in, in the compressed
/// `x_var` space — `TNLPAdapter::objective_nonlinear_vars`. Consumed
/// by both the partitioned updater (as its objective element's
/// support) and the finite-difference updater (as the objective's
/// contribution to a Jacobian-derived Hessian pattern, which the
/// constraint Jacobian cannot supply). `None` leaves each to fall
/// back on the first `∇f`'s nonzeros, which is value-derived; see
/// that method for what it costs.
pub objective_nonlinear_vars: Option<Vec<Index>>,
/// `partitioned_curvature_cap` — multiple of an element's implied
/// curvature that one update may reach. See
/// [`crate::hess::partitioned_quasi_newton`].
pub partitioned_curvature_cap: Number,
/// How the Lagrangian is split into elements under
/// [`HessianApproxChoice::Partitioned`] (`partitioned_elements`).
pub partitioned_elements: crate::hess::partitioned_quasi_newton::ElementMode,
/// Target primal-block width when `partitioned_elements` is
/// `blocks` (`partitioned_block_size`).
pub partitioned_block_size: usize,
/// Where [`HessianApproxChoice::FiniteDifference`] takes its
/// sparsity pattern from (`fd_hessian_pattern`).
pub fd_hessian_pattern: crate::hess::fd_hessian::FdPatternSource,
/// How finite-difference probe groups are formed
/// (`fd_hessian_coloring`).
pub fd_hessian_coloring: crate::hess::fd_hessian::FdColoring,
/// Relative movement in `x` AND `y` below which the previous Hessian
/// is reused (`fd_hessian_reuse_tol`). `0` rebuilds every iteration.
pub fd_hessian_reuse_tol: Number,
pub limited_memory_update_type: UpdateType,
/// History length for the limited-memory quasi-Newton approximation
/// (`limited_memory_max_history`). Defaults to upstream's 6.
pub limited_memory_max_history: i32,
/// `limited_memory_init_val_max` / `_min` — the clamp on the initial
/// Hessian scalar σ before the rank-2 updates. Upstream defaults 1e8
/// / 1e-8, which `LimMemQuasiNewtonUpdater` has carried as hard-coded
/// fields and consumed in `initial_hessian_scalar` all along; only
/// the read sites were missing (gh#483, #191 round 2).
pub limited_memory_init_val_max: Number,
pub limited_memory_init_val_min: Number,
/// `limited_memory_initialization` — which formula picks the initial
/// Hessian scalar σ. Matches upstream's `scalar1` (σ = sᵀy/sᵀs).
/// pounce shipped `scalar2` (σ = yᵀy/sᵀy) with no way to change it,
/// because the option was registered and never read (#677).
pub limited_memory_initialization: InitialApprox,
/// `limited_memory_init_val` — σ on the first iteration, before any
/// curvature pair exists, and every iteration under
/// `InitialApprox::Constant`. Upstream default 1.0.
pub limited_memory_init_val: Number,
/// `limited_memory_max_skipping` — consecutive skipped curvature
/// updates before the approximation is discarded (#686). Upstream
/// default 2.
pub limited_memory_max_skipping: Index,
/// Positions in the algorithm's compressed `x_var` space that enter
/// the problem *nonlinearly* (gh#624). `None` — the default —
/// approximates the Hessian over every variable, which is what the
/// limited-memory path has always done. When set, the quasi-Newton
/// update is restricted to this subspace and the Hessian is exactly
/// zero elsewhere. Comes from
/// `TNLPAdapter::quasi_newton_nonlinear_vars` (the TNLP's
/// `get_list_of_nonlinear_variables`, or the `num_linear_variables`
/// prefix fallback) and is ignored on the exact-Hessian path.
///
/// The restoration sub-IPM must clear this: the mask indexes the
/// original NLP's variables, not the restoration compound primal.
pub limited_memory_nonlinear_vars: Option<Vec<Index>>,
pub line_search_method: LineSearchChoice,
pub warm_start_init_point: bool,
/// `mehrotra_algorithm` — when true, [`PdSearchDirCalc`] folds
/// the Mehrotra second-order complementarity term into the
/// search-direction RHS. Mirrors upstream's
/// `IpAlgBuilder.cpp:Mehrotra` flag. Requires `mu_strategy =
/// Adaptive` so that an affine step is computed each iteration;
/// [`Self::build_with_backend`] does not enforce this — the
/// option-parser in `application.rs` is responsible for the
/// cascading defaults (`mu_oracle = probing` etc.).
pub mehrotra_algorithm: bool,
/// `fast_step_computation` — when true, [`PdSearchDirCalc`] accepts
/// the search direction without the residual check and allows an
/// inexact linear solve. Mirrors upstream's flag of the same name,
/// default `no`. The field existed and was consumed from the day the
/// search-direction calculator landed, hard-coded to `false`; only
/// the option's read site was missing, so setting it did nothing
/// (gh#483 follow-up, #191 round 2).
pub fast_step_computation: bool,
/// `kappa_sigma` — factor bounding how far the bound multipliers may
/// deviate from their primal estimates. The clamp
/// (`kappa_sigma_clamp`) runs after every accepted step; `< 1`
/// disables the correction. Mirrors `IpIpoptAlg.cpp` (Eqn. (16)),
/// default `1e10`. Baked onto [`crate::ipopt_alg::IpoptAlgorithm`] by
/// the solve path.
pub kappa_sigma: Number,
/// `recalc_y` / `recalc_y_feas_tol` — least-square re-estimation of
/// the equality multipliers once feasible (#677). Registered
/// upstream, refused by pounce as unimplemented until now. Default
/// `false` matches the registry; the limited-memory path turns it on
/// for itself in `application.rs`, as upstream's own option text
/// says it does.
pub recalc_y: bool,
pub recalc_y_feas_tol: Number,
/// `kappa_d` — weight of the linear damping term added to the barrier
/// objective/gradient (and dual-infeasibility) to handle one-sided
/// bounds. Mirrors `IpIpoptCalculatedQuantities.cpp`, default `1e-5`.
/// Baked onto [`crate::ipopt_cq::IpoptCalculatedQuantities`] by the
/// solve path.
pub kappa_d: Number,
/// `s_max` — cap on the average multiplier magnitude used to build
/// the `(s_d, s_c)` scaling factors of the KKT error test
/// (`IpIpoptCalculatedQuantities.cpp:ComputeOptimalityErrorScaling`,
/// the paragraph after Eqn. (6) of the implementation paper).
/// Registered default `100`, which is what
/// [`crate::ipopt_cq::IpoptCalculatedQuantities`] already carries as
/// its struct default, so forwarding it is behaviour-neutral for a
/// run that does not set it (#551 / #677). Baked onto the cq by the
/// solve path, next to `kappa_d`.
pub s_max: Number,
/// `tiny_step_tol` — relative primal step size below which the full
/// step is accepted without line search; repeated tiny steps
/// terminate the solve. Mirrors `IpBacktrackingLineSearch.cpp`,
/// default `10·EPSILON`. Baked onto
/// [`crate::ipopt_alg::IpoptAlgorithm`] by the solve path.
pub tiny_step_tol: Number,
/// `tiny_step_y_tol` — dual-step threshold; when both primal and dual
/// steps are tiny in consecutive iterations the algorithm stops at the
/// best attainable accuracy. Default `1e-2`.
pub tiny_step_y_tol: Number,
/// `diverging_iterates_tol` — if `max_i |x_i|` exceeds this the solve
/// aborts as diverging. Default `1e20`.
pub diverging_iterates_tol: Number,
/// `dual_diverging_streak` (pounce#246) — consecutive growing-dual-
/// infeasibility iterations before the dual-divergence guard routes to
/// restoration. **Default `0` (off).**
///
/// It defaulted to `15` when introduced, on the strength of a reported
/// emfl050 bad-warm-start grind. That justification did not survive being
/// reproduced: the measurement was caller-side JAX compilation, and the
/// build predating the guard solves both emfl050 instances to the same
/// optimum in the same time (pounce#246 / pounce#250). What remained was a
/// knife-edge, non-monotone effect on four of 1284 MINLPLib models — so it
/// is opt-in rather than imposed. See `upstream_options.rs` for the full
/// account.
pub dual_diverging_streak: Index,
/// `dual_divergence_retry_step_tol` (gh#884) — the scale-relative
/// step `max_i |d_i| / (1 + |x_i|)` at or below which the biactive
/// dual-divergence detector calls the primal iterate *settled*.
/// Default `1e-5`; `0` disables the detector without disabling the
/// `dual_divergence_retry` option. See `upstream_options.rs` for the
/// measured population behind the default.
pub dual_divergence_retry_step_tol: Number,
/// `dual_divergence_retry_du_floor` (gh#884) — the *unscaled* dual
/// infeasibility at or above which the same detector calls the
/// multipliers *diverged*. Default `1e2`. Measured in the model's own
/// units on purpose: the `s_d`-normalised aggregate is what hid the
/// defect. See `upstream_options.rs`.
pub dual_divergence_retry_du_floor: Number,
/// `resto_decline_deferrals` (gh #534) — how many times the
/// acceptable-point restoration decline may be deferred on a solve whose
/// NLP error is still contracting. Default `1`; `0` restores the pre-#534
/// behaviour (decline immediately, always). See `upstream_options.rs`.
pub resto_decline_deferrals: Index,
/// `resto_decline_progress_ratio` (gh #534) — required per-iteration
/// contraction of the NLP error before a decline is deferred. Default
/// `0.5`; at or above `1` the progress requirement is dropped entirely.
pub resto_decline_progress_ratio: Number,
/// `neg_curv_escapes` (gh #797) — how many times a certified stationary
/// point with an indefinite reduced Hessian may be left along a direction
/// of negative curvature instead of reported. Default `1`; `0` restores the
/// pre-#797 behaviour. See `upstream_options.rs`.
pub neg_curv_escapes: Index,
/// `limited_memory_ls_failure_restarts` (gh #818) — how many times a
/// line-search failure at an already-feasible point may re-anchor the
/// quasi-Newton model and retry instead of entering restoration.
/// Default `0`, i.e. the rung is off and a line-search failure always
/// hands off, which is upstream's behaviour; see
/// `DEFAULT_LBFGS_LS_FAILURE_RESTARTS` in `ipopt_alg.rs` for the
/// measurement that put it there. See `upstream_options.rs`.
pub limited_memory_ls_failure_restarts: Index,
/// `kkt_fidelity_tol` (pounce#173). Read by the algorithm as well as by the
/// post-solve gate, because the #200 fallback's tiebreak has to rank the two
/// candidate points by the status each will be *reported* under. Default
/// `0.0` (gate disabled).
pub kkt_fidelity_tol: Number,
pub conv_check: ConvCheckOptions,
pub mu: MuOptions,
pub line_search: LineSearchOptions,
pub refinement: RefinementOptions,
pub perturbation: PerturbationOptions,
pub resto: RestoOptions,
pub output: OutputOptions,
pub warm: WarmStartOptions,
/// SQP-specific options (consulted only when
/// `algorithm = ActiveSetSqp`).
pub sqp: crate::sqp::SqpOptions,
/// QP-subproblem-solver options for the active-set SQP path
/// (`pounce_qp::QpOptions`), threaded into the `SqpAlgorithm` via
/// `with_qp_options`. Consulted only when `algorithm = ActiveSetSqp`.
/// Populated from the `sqp_qp_*` CLI options by
/// `application::apply_qp_subproblem_options`.
pub sqp_qp: pounce_qp::QpOptions,
pub init: InitOptions,
/// Optional block-triangular / Schur KKT partition (pounce#180 item 2):
/// `(schur_indices, feral_cfg)`. When `Some` and the IPM path is selected
/// with the feral linear solver and an exact Hessian, `build_with_backend`
/// wraps the standard aug-system solver in a
/// [`crate::kkt::SchurAugSystemSolver`] over the given KKT-space indices.
/// The Schur solver falls back to the standard solver transparently when
/// the partition is unsuitable. Set via [`Self::set_kkt_schur`].
pub kkt_schur: Option<(Vec<usize>, pounce_feral::FeralConfig)>,
/// Shared tally of successful linear-solver quality escalations, handed
/// to the assembled
/// [`PdFullSpaceSolver`](crate::kkt::pd_full_space_solver::PdFullSpaceSolver)
/// by [`Self::build_with_backend`]. `None` leaves that solver with its
/// own private counter, which is what every test double and every
/// direct builder user gets.
///
/// The point of sharing it is the restoration sub-solve: its inner
/// algorithm is assembled from a *clone* of this builder
/// (`resto_inner_solver::run_inner_resto`), so a `Some` here makes the
/// sub-solve's escalations land in the same total as the main loop's.
/// gh#857's exact leg escalates once in each, and counting only the
/// main loop would report half the trajectory change.
pub quality_escalation_counter: Option<Rc<std::cell::Cell<u64>>>,
}
/// Knobs read off `OptionsList` and baked into
/// [`DefaultIterateInitializer`]. Defaults mirror
/// `IpDefaultIterateInitializer.cpp:RegisterOptions`. The Mehrotra
/// cascade in `application.rs` overrides `bound_push`, `bound_frac`,
/// and `bound_mult_init_val` to upstream's more-aggressive values
/// (`10`, `0.2`, `1.0`).
#[derive(Debug, Clone)]
pub struct InitOptions {
pub bound_push: Number,
pub bound_frac: Number,
pub slack_bound_push: Number,
pub slack_bound_frac: Number,
pub constr_mult_init_max: Number,
pub bound_mult_init_val: Number,
/// `bound_mult_init_method`: `"constant"` (default) or `"mu-based"`
/// (matches upstream's `IpDefaultIterateInitializer.cpp`).
pub bound_mult_init_method: String,
/// `least_square_init_primal` — replace the user's starting `x`
/// with the min-norm primal that satisfies the linearized
/// constraints. Used by the Mehrotra cascade in `application.rs`
/// to drop iter-0 primal infeasibility on LP-shaped problems.
/// Mirrors upstream `IpDefaultIterateInitializer.cpp:200-222`.
pub least_square_init_primal: bool,
}
impl Default for InitOptions {
fn default() -> Self {
Self {
bound_push: 1e-2,
bound_frac: 1e-2,
slack_bound_push: 1e-2,
slack_bound_frac: 1e-2,
constr_mult_init_max: 1e3,
bound_mult_init_val: 1.0,
bound_mult_init_method: "constant".into(),
least_square_init_primal: false,
}
}
}
/// Knobs read off `OptionsList` and baked into
/// [`WarmStartIterateInitializer`]. Defaults mirror
/// `IpWarmStartIterateInitializer.cpp:RegisterOptions`.
///
/// Wired today: every knob above plus the gh#606 recentering pair.
/// `warm_start_entire_iterate` / `warm_start_same_structure` are
/// deliberately *not* here — they name the `GetWarmStartIterate` TNLP
/// surface pounce does not expose, and are refused by
/// [`crate::unimplemented_options`] rather than parsed into a field
/// nothing reads (gh#606).
#[derive(Debug, Clone)]
pub struct WarmStartOptions {
pub bound_push: Number,
pub bound_frac: Number,
pub slack_bound_push: Number,
pub slack_bound_frac: Number,
pub mult_bound_push: Number,
pub mult_init_max: Number,
pub target_mu: Number,
/// The value a NaN-seeded bound multiplier takes: NaN in a
/// user-supplied `z`/`v` seed means "unseeded, use the default".
/// Threaded from `builder.init.bound_mult_init_val` at build time
/// so the Mehrotra override and any user setting stay the single
/// source of truth.
pub bound_mult_init_val: Number,
/// `constr_mult_init_max`, threaded from the init options at build
/// time (gh#606). The warm path's reconstruction of an unseeded
/// equality-multiplier block runs the *cold* path's least-squares
/// solve, so it is capped by the cold path's cap — not by
/// `warm_start_mult_init_max`, which caps multipliers a caller
/// actually supplied and is three orders looser (1e6 vs 1e3).
/// Measured: on `redundant_rows`, whose duplicated equality rows
/// make the least-squares system singular, the looser cap let an
/// arbitrary estimate through and cost 7 -> 25 iterations.
pub constr_mult_init_max: Number,
/// `warm_start_recentering` (gh#606). Whether the initializer
/// measures the supplied point and adapts μ / the multiplier fills
/// to it, or keeps the pre-gh#606 universal constants.
pub recentering: WarmStartRecentering,
}
/// Value of `warm_start_recentering` (gh#606).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WarmStartRecentering {
/// Pre-gh#606 behaviour: constant pushes and floors, `y` left at
/// zero when unseeded, μ untouched unless `warm_start_target_mu`
/// is set. The kill switch.
None,
/// Measure the supplied iterate's residuals and derive μ, the
/// bound-multiplier fills, and the equality-multiplier
/// reconstruction from them.
Residual,
}
impl WarmStartOptions {
/// `mult_init_max` as a usable cap: the registered `0` sentinel
/// means "no cap".
pub(crate) fn mult_init_max_or_inf(&self) -> Number {
if self.mult_init_max > 0.0 {
self.mult_init_max
} else {
Number::INFINITY
}
}
}
impl Default for WarmStartOptions {
fn default() -> Self {
Self {
bound_push: 1e-3,
bound_frac: 1e-3,
slack_bound_push: 1e-3,
slack_bound_frac: 1e-3,
mult_bound_push: 1e-3,
mult_init_max: 1e6,
target_mu: 0.0,
// seeded from the init options so the default has one
// home; build() re-resolves it from the live init options
// anyway (see `resolved_warm_options`)
bound_mult_init_val: InitOptions::default().bound_mult_init_val,
constr_mult_init_max: InitOptions::default().constr_mult_init_max,
recentering: WarmStartRecentering::Residual,
}
}
}
/// The warm-start options as the initializer actually receives them:
/// `bound_mult_init_val` and `constr_mult_init_max` come from the
/// (option-read, Mehrotra-resolved) init options, never from
/// `WarmStartOptions`'s own copy. Split out of `build()` so the threading is testable.
pub(crate) fn resolved_warm_options(
warm: &WarmStartOptions,
init: &InitOptions,
) -> WarmStartOptions {
let mut w = warm.clone();
w.bound_mult_init_val = init.bound_mult_init_val;
w.constr_mult_init_max = init.constr_mult_init_max;
w
}
/// Knobs read off `OptionsList` and baked into the assembled
/// `MonotoneMuUpdate` or `AdaptiveMuUpdate`. Defaults mirror
/// `IpMonotoneMuUpdate.cpp` / `IpAdaptiveMuUpdate.cpp:RegisterOptions`.
/// `mu_max` defaults to the sentinel `-1`; positive values are baked
/// into both updaters at build time (adaptive interprets `-1` as
/// "lazy-init from `mu_max_fact * avrg_compl`").
#[derive(Debug, Clone)]
pub struct MuOptions {
pub mu_init: Number,
pub mu_max: Number,
pub mu_max_fact: Number,
pub mu_min: Number,
pub mu_target: Number,
pub mu_linear_decrease_factor: Number,
pub mu_superlinear_decrease_power: Number,
pub mu_allow_fast_monotone_decrease: bool,
pub barrier_tol_factor: Number,
/// `tau_min` — floor on the fraction-to-the-boundary parameter
/// τ = max(tau_min, 1 − μ). Registered default 0.99, which is what
/// both `MonotoneMuUpdate` and `AdaptiveMuUpdate` already carry as
/// their struct default, so forwarding it is behaviour-neutral for
/// a run that does not set the option (#551 / #677). Consumed by
/// both updaters; the adaptive one also uses it in the monotone
/// mode and for the post-oracle τ = max(tau_min, 1 − NLP error).
pub tau_min: Number,
/// `sigma_max` / `sigma_min` — clamp on the centering parameter σ
/// chosen by `QualityFunctionMuOracle`. Only consumed when
/// `mu_strategy=adaptive` and `mu_oracle=quality-function`.
/// Defaults from `IpQualityFunctionMuOracle.cpp:RegisterOptions`.
pub sigma_max: Number,
pub sigma_min: Number,
/// `adaptive_mu_globalization` — globalization strategy for the
/// adaptive μ-selection mode. Mirrors
/// `IpAdaptiveMuUpdate.cpp:RegisterOptions`. Default is
/// `ObjConstrFilter`; the Mehrotra cascade switches to
/// `NeverMonotoneMode` to disable globalization entirely.
pub adaptive_mu_globalization: crate::mu::adaptive::AdaptiveMuGlobalization,
/// `quality_function_norm_type` — norm used inside the quality
/// function to aggregate the three KKT components. Forwarded to
/// `QualityFunctionMuOracle` when `mu_oracle=quality-function`.
pub quality_function_norm_type: crate::mu::oracle::quality_function::NormType,
/// `quality_function_centrality` — centrality penalty term added
/// to the quality function.
pub quality_function_centrality: crate::mu::oracle::quality_function::CentralityType,
/// `quality_function_balancing_term` — balancing penalty term in
/// the quality function (kicks in when complementarity is far
/// below infeasibilities).
pub quality_function_balancing_term: crate::mu::oracle::quality_function::BalancingTermType,
/// `quality_function_max_section_steps` — cap on golden-section
/// iterations when picking σ. Default 8.
pub quality_function_max_section_steps: i32,
/// `quality_function_section_sigma_tol` — width tolerance in
/// σ-space for golden section. Default 1e-2.
pub quality_function_section_sigma_tol: Number,
/// `quality_function_section_qf_tol` — relative flatness
/// tolerance for golden section. Default 0.0.
pub quality_function_section_qf_tol: Number,
/// `adaptive_mu_safeguard_factor` — guard for the LOQO fallback
/// in adaptive mode. Default 0.0.
pub adaptive_mu_safeguard_factor: Number,
/// `adaptive_mu_monotone_init_factor` — multiplier on the
/// average complementarity when seeding monotone mode after a
/// free-mode bailout. Default 0.8.
pub adaptive_mu_monotone_init_factor: Number,
/// `adaptive_mu_restore_previous_iterate` — restore the most
/// recent free-mode iterate when switching to fixed mode.
/// Default `false`.
pub adaptive_mu_restore_previous_iterate: bool,
/// `adaptive_mu_max_free_returns` (pounce#749, POUNCE
/// extension). Cap on how many times the adaptive strategy may
/// leave fixed-mu mode. `-1` = unlimited (upstream behavior).
pub adaptive_mu_max_free_returns: i32,
/// `adaptive_mu_budget_pin_fraction` (pounce#753, POUNCE
/// extension). Fraction of an explicitly-set `max_cpu_time` /
/// `max_wall_time` after which the adaptive strategy stops
/// returning to free-mu mode and finishes monotone. `1.0`
/// disables. Inert unless the caller set a time budget.
pub adaptive_mu_budget_pin_fraction: Number,
/// `adaptive_mu_kkterror_red_iters` — window length for the
/// `KKT_ERROR` globalization history. Default 4.
pub adaptive_mu_kkterror_red_iters: usize,
/// `adaptive_mu_kkterror_red_fact` — required relative reduction
/// of the KKT error over the window. Default 0.9999.
pub adaptive_mu_kkterror_red_fact: Number,
/// `adaptive_mu_kkt_norm_type` — norm used to score the iterate
/// in adaptive globalization decisions.
pub adaptive_mu_kkt_norm_type: crate::mu::adaptive::AdaptiveMuKktNorm,
/// `filter_margin_fact` — width factor of the margin an entry must
/// clear in the `obj-constr-filter` adaptive globalization test
/// (`margin = filter_margin_fact * min(filter_max_margin, err)`).
/// Only consumed when `mu_strategy=adaptive` and
/// `adaptive_mu_globalization=obj-constr-filter` (the default).
/// Default 1e-5, from `IpAdaptiveMuUpdate.cpp:RegisterOptions`.
pub filter_margin_fact: Number,
/// `filter_max_margin` — cap on the margin above. Default 1.0,
/// from `IpAdaptiveMuUpdate.cpp:RegisterOptions`.
pub filter_max_margin: Number,
/// `probing_iterate_quality_factor` (default 1e4, pounce-specific
/// — see pounce#58). When the probing (Mehrotra) μ-oracle is
/// about to read `curr_avrg_compl()` for its `mu_curr` input, a
/// single imbalanced `(s_i, z_i)` pair can inflate the average
/// 5+ orders above the stored `data.curr_mu`. The oracle then
/// returns `σ · mu_curr` ≫ previous μ, throwing the iterate out
/// of the convergence neighborhood. This guard short-circuits
/// that case by signalling restoration when the ratio
/// `curr_avrg_compl / curr_mu` exceeds the factor. Set to 0 or
/// any non-positive value to disable.
pub probing_iterate_quality_factor: Number,
}
impl Default for MuOptions {
fn default() -> Self {
Self {
mu_init: 0.1,
mu_max: -1.0,
mu_max_fact: 1e3,
mu_min: 1e-11,
mu_target: 0.0,
mu_linear_decrease_factor: 0.2,
mu_superlinear_decrease_power: 1.5,
mu_allow_fast_monotone_decrease: true,
barrier_tol_factor: 10.0,
tau_min: 0.99,
sigma_max: 1e2,
sigma_min: 1e-6,
adaptive_mu_globalization:
crate::mu::adaptive::AdaptiveMuGlobalization::ObjConstrFilter,
quality_function_norm_type:
crate::mu::oracle::quality_function::NormType::TwoNormSquared,
quality_function_centrality: crate::mu::oracle::quality_function::CentralityType::None,
quality_function_balancing_term:
crate::mu::oracle::quality_function::BalancingTermType::None,
quality_function_max_section_steps: 8,
quality_function_section_sigma_tol: 1e-2,
quality_function_section_qf_tol: 0.0,
adaptive_mu_safeguard_factor: 0.0,
adaptive_mu_monotone_init_factor: 0.8,
adaptive_mu_restore_previous_iterate: false,
adaptive_mu_max_free_returns: -1,
adaptive_mu_budget_pin_fraction: 0.75,
adaptive_mu_kkterror_red_iters: 4,
adaptive_mu_kkterror_red_fact: 0.9999,
adaptive_mu_kkt_norm_type: crate::mu::adaptive::AdaptiveMuKktNorm::TwoNormSquared,
filter_margin_fact: 1e-5,
filter_max_margin: 1.0,
probing_iterate_quality_factor: 1e4,
}
}
}
/// Knobs baked into the assembled [`BacktrackingLineSearch`]. Defaults
/// mirror `IpBacktrackingLineSearch.cpp:RegisterOptions`.
#[derive(Debug, Clone)]
pub struct LineSearchOptions {
/// `alpha_red_factor` — fractional reduction applied to the trial
/// step size at every backtracking step
/// (`alpha *= alpha_red_factor`). Mirrors upstream's
/// `IpBacktrackingLineSearch::alpha_red_factor_`.
pub alpha_red_factor: Number,
/// `alpha_red_factor_min` — floor on one backtracking reduction,
/// which turns the fixed geometric trial sequence into a
/// safeguarded quadratic interpolation (gh#818). See
/// `BacktrackingLineSearch::next_alpha`.
///
/// `None` — the default — means "let the Hessian mode decide", and
/// the two modes decide differently:
///
/// * **limited-memory → `0.05`** (interpolation on). The
/// quasi-Newton model's *scale* can be wrong by orders of
/// magnitude in any direction its curvature pairs do not span, so
/// the acceptable `alpha` can be far below 1 and the fixed factor
/// spends `log(1/alpha)` objective evaluations walking to it.
/// * **exact → off** (`alpha_red_factor`, i.e. upstream's fixed
/// sequence). A Newton step's length is meaningful, the
/// acceptable `alpha` is normally within a few halvings of 1, and
/// the trial sequence is not what costs.
///
/// The split is measured, not assumed. Forcing
/// `alpha_red_factor_min 0.05` onto the exact path moves 3 of the
/// 156 fixture-legs in `scripts/sweep-fixtures.sh`, and the one
/// that matters is a **status loss**: `eigena2` goes from
/// `SolveSucceeded`/27 to `SolvedToAcceptableLevel`/32. The other
/// two are `issue_508_infeasible_gap_1em4` 441 → 385 to the same
/// certificate — a gain — and an objective digit on
/// `hs13_bigstart`. One fixture giving up a solve is the whole
/// argument; a faster infeasibility certificate does not buy it
/// back. Before `ALPHA_INTERP_MIN_TRIALS` gated the interpolation
/// the same experiment moved 9 legs and cost
/// `infeasible_square_scaled_1em4` its infeasibility certificate
/// (`InfeasibleProblemDetected`/17 → `ErrorInStepComputation`/12);
/// the gate narrowed the damage, it did not remove the reason for
/// the split.
///
/// An explicit `alpha_red_factor_min` from the user is honoured on
/// both paths — the mode-dependence is only in the default.
pub alpha_red_factor_min: Option<Number>,
pub watchdog_shortened_iter_trigger: Index,
pub watchdog_trial_iter_max: Index,
/// `soft_resto_pderror_reduction_factor` — required relative
/// reduction in the primal-dual error for a soft-resto step.
/// `0` disables the soft restoration phase.
pub soft_resto_pderror_reduction_factor: Number,
/// `max_soft_resto_iters` — cap on consecutive soft-resto
/// iterations before full restoration is forced.
pub max_soft_resto_iters: Index,
/// `accept_every_trial_step` — short-circuits the filter / alpha
/// loop and accepts the full fraction-to-the-boundary step every
/// outer iteration. Mirrors upstream's
/// `IpBacktrackingLineSearch::accept_every_trial_step_`. Drops
/// global convergence guarantees; only safe for problems where the
/// Newton step is already a descent step (LPs, convex QPs). The
/// Mehrotra cascade in `application.rs` flips this on.
pub accept_every_trial_step: bool,
/// `alpha_for_y` — policy for the equality-multiplier (y_c / y_d)
/// step length. Upstream default is `Primal`; the Mehrotra cascade
/// switches to `BoundMult`.
pub alpha_for_y: crate::line_search::backtracking::AlphaForY,
/// `accept_after_max_steps` — accept a trial point once this many
/// backtracking steps have been taken, even if it fails the
/// acceptor's tests. `-1` (the default) disables it, which is why
/// wiring it moves no default trajectory. Mirrors
/// `IpBacktrackingLineSearch.cpp:759-770`.
pub accept_after_max_steps: Index,
// Filter switching / Armijo / margin constants baked onto the
// assembled [`crate::line_search::filter_acceptor::FilterLsAcceptor`]
// (only when `line_search_method = Filter`). All were registered but
// never read (#191); defaults mirror `IpFilterLSAcceptor.cpp`.
/// `eta_phi` — relaxation factor in the Armijo condition (Eqn. (20)).
pub eta_phi: Number,
/// `delta` — multiplier on the constraint violation in the filter's
/// switching rule (Eqn. (19)); maps to
/// [`FilterLsAcceptor::delta_armijo`]. Default 1.0, from
/// `IpFilterLSAcceptor.cpp:RegisterOptions`.
pub delta: Number,
/// `theta_min_fact` — constraint-violation threshold factor in the
/// switching rule.
pub theta_min_fact: Number,
/// `theta_max_fact` — upper-bound factor for constraint violation in
/// the filter (Eqn. (21)).
pub theta_max_fact: Number,
/// `theta_max_row_scale_kappa` — multiplier on the constraint-row
/// count used as the floor of the `theta_max` reference.
/// **Opt-in**: default `0`, which is upstream's bare
/// `max(1, theta_0)` floor bit-for-bit. Set to `1` on a large model
/// that stalls from a feasible start. See
/// [`FilterLsAcceptor::theta_max_row_scale_kappa`].
pub theta_max_row_scale_kappa: Number,
/// `theta_max_adaptive_trigger` — consecutive line searches whose
/// every trial was refused at the `theta_max` gate before the
/// ceiling is raised. `0` disables the rule. See
/// [`FilterLsAcceptor::theta_max_adaptive_trigger`] (pounce#546).
pub theta_max_adaptive_trigger: u32,
/// Geometric factor applied to `theta_max` on each adaptive raise.
/// See [`FilterLsAcceptor::theta_max_adaptive_factor`].
pub theta_max_adaptive_factor: Number,
/// Cap on adaptive raises per solve, which is what keeps `theta_max`
/// finite. See [`FilterLsAcceptor::theta_max_adaptive_max_raises`].
pub theta_max_adaptive_max_raises: u32,
/// `gamma_phi` — filter margin factor for the barrier function
/// (Eqn. (18a)).
pub gamma_phi: Number,
/// `gamma_theta` — filter margin factor for the constraint violation
/// (Eqn. (18b)).
pub gamma_theta: Number,
/// `s_phi` — exponent for the linear barrier model in the switching
/// rule (Eqn. (19)).
pub s_phi: Number,
/// `s_theta` — exponent for the current constraint violation in the
/// switching rule (Eqn. (19)).
pub s_theta: Number,
/// `alpha_min_frac` — safety factor for the minimal step size before
/// switching to restoration (gamma_alpha, Eqn. (23)).
pub alpha_min_frac: Number,
/// `obj_max_inc` — max acceptable increase (orders of magnitude) of
/// the barrier objective for a trial point.
pub obj_max_inc: Number,
/// `max_filter_resets` — maximum number of filter resets allowed
/// (`0` disables the reset heuristic).
pub max_filter_resets: Index,
/// `filter_reset_trigger` — successive filter-rejected iterations that
/// trigger a filter reset.
pub filter_reset_trigger: Index,
/// `filter_theta_roundoff_retry` (gh#945) — whether a line search that
/// runs out of `alpha` at an iterate already feasible to round-off gets
/// one more pass with the filter's `theta` axis measured against
/// `theta`'s own evaluation noise, before the driver hands off to a
/// restoration phase that has nothing to minimize. **On by default**;
/// see `BacktrackingLineSearch::run_filter_line_search` and
/// `IpoptCq::theta_evaluation_noise_floor`.
pub filter_theta_roundoff_retry: bool,
// Penalty-acceptor constants baked onto the assembled
// [`crate::line_search::penalty_acceptor::PenaltyLsAcceptor`] (only
// when `line_search_method = penalty` / `cg-penalty`). Defaults
// mirror `IpPenaltyLSAcceptor.cpp:RegisterOptions`.
/// `nu_init` — initial value of the penalty parameter ν.
pub nu_init: Number,
/// `nu_inc` — increment added when ν is bumped.
pub nu_inc: Number,
/// `rho` — convex-combination weight in the ν update rule.
pub rho: Number,
/// `eta_penalty` — relaxation factor in the Armijo condition on the
/// penalty merit function.
pub eta_penalty: Number,
// Second-order-correction constants baked onto the assembled
// [`BacktrackingLineSearch`]. Registered but never read (#191);
// defaults mirror `IpBacktrackingLineSearch.cpp`.
/// `max_soc` — max second-order-correction trial steps per iteration;
/// `0` disables SOC.
pub max_soc: Index,
/// `kappa_soc` — sufficient-reduction factor for a SOC step to be
/// continued.
pub kappa_soc: Number,
/// `soc_method` — `0` (paper method) or `1` (alpha-on-rhs variant).
pub soc_method: Index,
}
impl Default for LineSearchOptions {
fn default() -> Self {
Self {
alpha_red_factor: 0.5,
alpha_red_factor_min: None,
watchdog_shortened_iter_trigger: 10,
watchdog_trial_iter_max: 3,
soft_resto_pderror_reduction_factor: 1.0 - 1e-4,
max_soft_resto_iters: 10,
accept_every_trial_step: false,
alpha_for_y: crate::line_search::backtracking::AlphaForY::Primal,
accept_after_max_steps: -1,
eta_phi: 1e-8,
delta: 1.0,
theta_min_fact: 1e-4,
theta_max_fact: 1e4,
theta_max_row_scale_kappa: 0.0,
theta_max_adaptive_trigger: 3,
theta_max_adaptive_factor: 100.0,
theta_max_adaptive_max_raises: 4,
gamma_phi: 1e-8,
gamma_theta: 1e-5,
s_phi: 2.3,
s_theta: 1.1,
alpha_min_frac: 0.05,
obj_max_inc: 5.0,
max_filter_resets: 5,
filter_reset_trigger: 5,
filter_theta_roundoff_retry: true,
nu_init: 1e-6,
nu_inc: 1e-4,
rho: 0.1,
eta_penalty: 1e-8,
max_soc: 4,
kappa_soc: 0.99,
soc_method: 0,
}
}
}
/// Inertia-correction / regularization knobs baked onto the assembled
/// [`crate::kkt::perturbation_handler::PdPerturbationHandler`]. Field
/// names use the option names; they map to the handler's `delta_xs_*` /
/// `delta_cd_*` fields. Defaults mirror
/// `IpPDPerturbationHandler.cpp:RegisterOptions`. All were registered but
/// never read (#191).
#[derive(Debug, Clone)]
pub struct PerturbationOptions {
/// `max_hessian_perturbation` → `delta_xs_max`.
pub max_hessian_perturbation: Number,
/// `min_hessian_perturbation` → `delta_xs_min`.
pub min_hessian_perturbation: Number,
/// `perturb_inc_fact_first` → `delta_xs_first_inc_fact`.
pub perturb_inc_fact_first: Number,
/// `perturb_inc_fact` → `delta_xs_inc_fact`.
pub perturb_inc_fact: Number,
/// `perturb_dec_fact` → `delta_xs_dec_fact`.
pub perturb_dec_fact: Number,
/// `first_hessian_perturbation` → `delta_xs_init`.
pub first_hessian_perturbation: Number,
/// `jacobian_regularization_value` → `delta_cd_val`.
pub jacobian_regularization_value: Number,
/// `jacobian_regularization_exponent` → `delta_cd_exp`.
pub jacobian_regularization_exponent: Number,
/// `perturb_always_cd` — always regularize the c/d (Jacobian) block.
pub perturb_always_cd: bool,
/// `perturb_delta_c_max_rungs` → `delta_c_max_rungs` (pounce gh#592).
pub perturb_delta_c_max_rungs: Index,
}
impl Default for PerturbationOptions {
fn default() -> Self {
Self {
max_hessian_perturbation: 1e20,
min_hessian_perturbation: 1e-20,
perturb_inc_fact_first: 100.0,
perturb_inc_fact: 8.0,
perturb_dec_fact: 1.0 / 3.0,
first_hessian_perturbation: 1e-4,
jacobian_regularization_value: 1e-8,
jacobian_regularization_exponent: 0.25,
perturb_always_cd: false,
perturb_delta_c_max_rungs: 3,
}
}
}
/// Restoration-phase knobs carried on the outer builder and copied into
/// the `RestoAlgorithmBuilder` when the restoration factory is minted
/// (`pounce-restoration`). The restoration builder is constructed with
/// defaults by each frontend and never options-configured, so these were
/// registered but never read (#191). Defaults mirror upstream's
/// restoration `RegisterOptions`.
#[derive(Debug, Clone)]
pub struct RestoOptions {
/// `bound_mult_reset_threshold` — reset bound multipliers to 1 after
/// restoration if the largest exceeds this.
pub bound_mult_reset_threshold: Number,
/// `constr_mult_reset_threshold` — ignore the least-square constraint
/// multiplier estimate after restoration if its norm exceeds this
/// (`0` keeps the estimate).
pub constr_mult_reset_threshold: Number,
/// `resto_penalty_parameter` — penalty on the slack 1-norm in the
/// restoration objective (`rho`).
pub resto_penalty_parameter: Number,
/// `resto_proximity_weight` — proximity-term weight (`eta_factor`;
/// `η = eta_factor · sqrt(μ)`).
pub resto_proximity_weight: Number,
/// `required_infeasibility_reduction` — the restoration sub-solve
/// keeps iterating until the *original* NLP's infeasibility has been
/// reduced to at most this fraction of its value at restoration entry
/// (`κ_resto` in `IpRestoConvCheck.cpp:58`). `0` disables the guard,
/// i.e. restoration runs until the sub-NLP itself converges.
pub required_infeasibility_reduction: Number,
/// `evaluate_orig_obj_at_resto_trial` — evaluate the *original*
/// objective at every restoration trial point, so an iterate the
/// restoration problem likes but the original cannot evaluate is
/// rejected there rather than after the phase exits. Upstream default
/// `yes`. `RestoAlgorithmBuilder` has consumed this since it landed;
/// only the read site was missing (gh#483, #191 round 2).
pub evaluate_orig_obj_at_resto_trial: bool,
/// `expect_infeasible_problem` — enter restoration sooner and demand
/// more infeasibility reduction before leaving it. Upstream default
/// `no`. Same story: consumed, never read.
pub expect_infeasible_problem: bool,
/// `start_with_resto` — switch to restoration in the first iteration.
/// Upstream default `no`. Same story.
pub start_with_resto: bool,
/// `max_resto_iter` — cap on *successive* restoration iterations
/// (`IpRestoConvCheck.cpp:144`'s `maximum_resto_iters`). Consumed by
/// `pounce_restoration::conv_check::RestoConvCheckAdapter`, which
/// returns `MaxIterExceeded` once the count is reached; the value
/// used to be the hard-coded `RESTO_MAX_SUCCESSIVE_ITERS` in
/// `resto_inner_solver.rs`, so setting the option did nothing
/// (#551 / #677). The field is named after the option here, but the
/// consumer's field is `maximum_resto_iters` — which is why grepping
/// for the option name found nothing (#551 caution 2).
///
/// **This default deliberately differs from the registered one.**
/// `upstream_options.rs` registers Ipopt's `3000000`; pounce has
/// enforced `3000` since the cap landed. Wiring the option must not
/// change what an unset option does, so the effective cap stays
/// `3000` and only an explicit `max_resto_iter` moves it. Raising
/// the default to upstream's number is a trajectory change (it
/// lets a restoration that pounce currently cuts off at 3000 keep
/// going) and belongs to a change that measures it.
pub max_resto_iter: i32,
}
impl Default for RestoOptions {
fn default() -> Self {
Self {
bound_mult_reset_threshold: 1e3,
constr_mult_reset_threshold: 0.0,
resto_penalty_parameter: 1e3,
resto_proximity_weight: 1.0,
required_infeasibility_reduction: 0.9,
evaluate_orig_obj_at_resto_trial: true,
expect_infeasible_problem: false,
start_with_resto: false,
// NOT the registered default (3000000) — see the field docs.
max_resto_iter: 3000,
}
}
}
/// Iterative-refinement knobs baked onto the assembled
/// [`crate::kkt::pd_full_space_solver::PdFullSpaceSolver`]. Defaults
/// mirror `IpPDFullSpaceSolver.cpp:RegisterOptions`. All were registered
/// but never read (#191).
#[derive(Debug, Clone)]
pub struct RefinementOptions {
/// `min_refinement_steps` — minimum iterative-refinement steps per
/// linear solve.
pub min_refinement_steps: Index,
/// `max_refinement_steps` — maximum iterative-refinement steps.
pub max_refinement_steps: Index,
/// `residual_ratio_max` — refine until the residual test ratio drops
/// below this (or `max_refinement_steps` is reached).
pub residual_ratio_max: Number,
/// `residual_ratio_singular` — above this ratio after failed
/// refinement, the system is declared singular.
pub residual_ratio_singular: Number,
/// `residual_improvement_factor` — minimum per-step reduction of the
/// residual test ratio before refinement is aborted.
pub residual_improvement_factor: Number,
/// `neg_curv_test_tol` — tolerance α_n of the inertia-free curvature
/// test of Zavala & Chiang (2014). Zero (the registered default)
/// disables the heuristic and keeps the inertia check; positive
/// turns the inertia check off and accepts the factorization only
/// when the computed direction passes the curvature test in
/// `PdFullSpaceSolver::solve_once`.
pub neg_curv_test_tol: Number,
/// `neg_curv_test_reg` — whether the curvature test includes the
/// primal regularization δ_x‖dx‖² + δ_s‖ds‖². Registered default
/// `yes`; `no` reproduces the original Ipopt form that ignores it.
/// Only consulted when `neg_curv_test_tol > 0`.
pub neg_curv_test_reg: bool,
}
impl Default for RefinementOptions {
fn default() -> Self {
Self {
min_refinement_steps: 1,
max_refinement_steps: 10,
residual_ratio_max: 1e-10,
residual_ratio_singular: 1e-5,
residual_improvement_factor: 0.999_999_999,
neg_curv_test_tol: 0.0,
neg_curv_test_reg: true,
}
}
}
/// Knobs baked into the assembled [`OrigIterationOutput`]. Defaults
/// mirror `IpOrigIterationOutput.cpp:RegisterOptions` /
/// `IpAlgorithmRegOp.cpp`.
#[derive(Debug, Clone)]
pub struct OutputOptions {
pub print_frequency_iter: Index,
pub print_frequency_time: Number,
/// `print_info_string` (default `false`). When on, the iter row
/// ends with the contents of `IpoptData::info_string` so users
/// can read the per-iteration diagnostic tags.
pub print_info_string: bool,
/// `inf_pr_output` — `"original"` (default) prints the unscaled
/// NLP primal infeasibility; `"internal"` prints the internal
/// reformulated violation. Only meaningful once NLP-side scaling
/// is in play; until then both modes produce the same number.
pub inf_pr_output_internal: bool,
}
impl Default for OutputOptions {
fn default() -> Self {
Self {
print_frequency_iter: 1,
print_frequency_time: 0.0,
print_info_string: false,
inf_pr_output_internal: false,
}
}
}
impl Default for AlgorithmBuilder {
fn default() -> Self {
Self {
algorithm: AlgorithmChoice::default(),
linear_solver: LinearSolverChoice::Feral,
linear_system_scaling: LinearSystemScalingChoice::None,
linear_scaling_on_demand: true,
mu_strategy: MuStrategyChoice::Monotone,
mu_oracle: MuOracleKind::QualityFunction,
hessian_approximation: HessianApproxChoice::Exact,
partitioned_update_type: UpdateType::Sr1,
partitioned_update_type_was_set: false,
partitioned_max_element: 64,
objective_nonlinear_vars: None,
partitioned_curvature_cap: Number::INFINITY,
partitioned_elements: crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
partitioned_block_size: 64,
fd_hessian_pattern: crate::hess::fd_hessian::FdPatternSource::Declared,
fd_hessian_coloring: crate::hess::fd_hessian::FdColoring::Cpr,
fd_hessian_reuse_tol: 0.0,
limited_memory_update_type: UpdateType::Bfgs,
limited_memory_max_history: 6,
limited_memory_init_val_max: 1e8,
limited_memory_init_val_min: 1e-8,
limited_memory_initialization: InitialApprox::Scalar1,
limited_memory_init_val: 1.0,
limited_memory_max_skipping: 2,
limited_memory_nonlinear_vars: None,
line_search_method: LineSearchChoice::Filter,
warm_start_init_point: false,
mehrotra_algorithm: false,
fast_step_computation: false,
kappa_sigma: 1e10,
recalc_y: false,
recalc_y_feas_tol: 1e-6,
kappa_d: 1e-5,
s_max: 100.0,
tiny_step_tol: 10.0 * Number::EPSILON,
tiny_step_y_tol: 1e-2,
diverging_iterates_tol: 1e20,
dual_divergence_retry_step_tol: 1e-5,
dual_divergence_retry_du_floor: 1e2,
dual_diverging_streak: 0,
resto_decline_deferrals: 1,
resto_decline_progress_ratio: 0.5,
neg_curv_escapes: 1,
limited_memory_ls_failure_restarts: 0,
kkt_fidelity_tol: 0.0,
conv_check: ConvCheckOptions::default(),
mu: MuOptions::default(),
line_search: LineSearchOptions::default(),
refinement: RefinementOptions::default(),
perturbation: PerturbationOptions::default(),
resto: RestoOptions::default(),
output: OutputOptions::default(),
warm: WarmStartOptions::default(),
sqp: crate::sqp::SqpOptions::default(),
sqp_qp: pounce_qp::QpOptions::sqp_subproblem(),
init: InitOptions::default(),
kkt_schur: None,
quality_escalation_counter: None,
}
}
}
impl AlgorithmBuilder {
pub fn new() -> Self {
Self::default()
}
/// Install a Schur KKT partition (pounce#180 item 2). `schur_indices` are
/// KKT-space indices (`0..dim`, the `x,s,c,d` block order the aug-system
/// solver assembles); `cfg` configures the per-block feral solvers. Only
/// honored on the IPM + feral + exact-Hessian path by
/// [`Self::build_with_backend`]; ignored otherwise.
pub fn set_kkt_schur(&mut self, schur_indices: Vec<usize>, cfg: pounce_feral::FeralConfig) {
self.kkt_schur = Some((schur_indices, cfg));
}
/// Assemble the strategy bundle without a search-direction
/// calculator. Used by structural unit tests that don't want to
/// pull in a linear-solver backend.
pub fn build(&self) -> AlgorithmBundle {
self.build_inner(None)
}
/// Same as [`Self::build`] but also constructs the
/// `SymLinearSolver → AugSystemSolver → PdFullSpaceSolver →
/// PdSearchDirCalc` chain via the supplied `factory`.
pub fn build_with_backend(&self, mut factory: LinearBackendFactory) -> AlgorithmBundle {
let backend = factory(self.linear_solver);
let make_scaling = || -> Option<Box<dyn pounce_linsol::TSymScalingMethod>> {
match self.linear_system_scaling {
LinearSystemScalingChoice::None => None,
LinearSystemScalingChoice::Ruiz => {
Some(Box::new(pounce_linsol::RuizTSymScalingMethod::new()))
}
LinearSystemScalingChoice::Mc19 => {
tracing::warn!(target: "pounce::algorithm",
"pounce: linear_system_scaling=mc19 not yet implemented; using no scaling"
);
None
}
LinearSystemScalingChoice::SlackBased => {
Some(Box::new(pounce_linsol::SlackBasedTSymScalingMethod::new()))
}
}
};
let linsol = TSymLinearSolver::new(backend, make_scaling(), self.linear_scaling_on_demand);
let inner_aug = StdAugSystemSolver::new(linsol);
// Limited-memory mode publishes the Hessian as a
// `LowRankUpdateSymMatrix`; wrap the standard solver in the
// Sherman-Morrison-Woodbury low-rank solver so the augmented
// system factorizes only the diagonal `B0` and the quasi-Newton
// update is applied as a rank-`m` correction (`O(n·m)` memory).
let is_lbfgs = matches!(
self.hessian_approximation,
HessianApproxChoice::LimitedMemory
);
let aug_solver: Box<dyn AugSystemSolver> = if is_lbfgs {
// A second, independent inner solver for the Hessian-free
// solves. Both see one W shape each for their whole life, so
// neither re-runs the backend's symbolic factorization when
// the other's shape comes round — see
// `LowRankAugSystemSolver::with_bypass_solver` (gh#730).
let bypass_linsol = TSymLinearSolver::new(
factory(self.linear_solver),
make_scaling(),
self.linear_scaling_on_demand,
);
Box::new(LowRankAugSystemSolver::with_bypass_solver(
Box::new(inner_aug),
Box::new(StdAugSystemSolver::new(bypass_linsol)),
))
} else if let Some((indices, cfg)) = self.kkt_schur.clone() {
// Block-triangular / Schur KKT path (pounce#180 item 2). Only on the
// exact-Hessian feral path — the Schur backend is feral-specific,
// and the L-BFGS low-rank Woodbury wrapper owns the (2,2) block.
// The Schur solver falls back to `StdAugSystemSolver` transparently
// when the partition is unsuitable, so a stray hook never breaks a
// solve; we gate on `linear_solver == Feral` here to avoid silently
// ignoring a user's explicit MA57 selection.
if matches!(self.linear_solver, LinearSolverChoice::Feral) {
Box::new(crate::kkt::SchurAugSystemSolver::new(
inner_aug, indices, cfg,
))
} else {
Box::new(inner_aug)
}
} else {
Box::new(inner_aug)
};
// Inertia-correction / Jacobian-regularization constants (#191):
// registered but previously never read. Defaults equal the
// registered defaults. `perturb_always_cd` goes through the setter
// because it also rebuilds the initial jac-degeneracy state.
let mut ph = PdPerturbationHandler::new();
ph.delta_xs_max = self.perturbation.max_hessian_perturbation;
ph.delta_xs_min = self.perturbation.min_hessian_perturbation;
ph.delta_xs_first_inc_fact = self.perturbation.perturb_inc_fact_first;
ph.delta_xs_inc_fact = self.perturbation.perturb_inc_fact;
ph.delta_xs_dec_fact = self.perturbation.perturb_dec_fact;
ph.delta_xs_init = self.perturbation.first_hessian_perturbation;
ph.delta_cd_val = self.perturbation.jacobian_regularization_value;
ph.delta_cd_exp = self.perturbation.jacobian_regularization_exponent;
ph.set_perturb_always_cd(self.perturbation.perturb_always_cd);
ph.delta_c_max_rungs = self.perturbation.perturb_delta_c_max_rungs;
let perturb = Rc::new(RefCell::new(ph));
let mut pd_solver = PdFullSpaceSolver::new(aug_solver, perturb);
// Iterative-refinement constants (#191): registered but previously
// never read, so overrides were silently dropped. Defaults equal
// the registered defaults.
pd_solver.min_refinement_steps = self.refinement.min_refinement_steps;
pd_solver.max_refinement_steps = self.refinement.max_refinement_steps;
pd_solver.residual_ratio_max = self.refinement.residual_ratio_max;
pd_solver.residual_ratio_singular = self.refinement.residual_ratio_singular;
pd_solver.residual_improvement_factor = self.refinement.residual_improvement_factor;
// Inertia-free curvature test (#551 / #677). Both were registered
// and never read; `neg_curv_test_tol` defaults to 0, which leaves
// the heuristic off and the inertia check on, so this changes
// nothing for a run that does not set it.
pd_solver.neg_curv_test_tol = self.refinement.neg_curv_test_tol;
pd_solver.neg_curv_test_reg = self.refinement.neg_curv_test_reg;
// gh#857: share the escalation tally with the caller, so the
// restoration sub-solve built from a clone of this builder counts
// into the same total.
if let Some(counter) = self.quality_escalation_counter.as_ref() {
pd_solver.set_quality_escalation_counter(Rc::clone(counter));
}
let mut search_dir = PdSearchDirCalc::new(pd_solver);
search_dir.mehrotra_algorithm = self.mehrotra_algorithm;
search_dir.fast_step_computation = self.fast_step_computation;
self.build_inner(Some(search_dir))
}
/// Phase 5b assembly path for the SQP algorithm. Consults
/// `self.algorithm`: when `ActiveSetSqp`, constructs an
/// `SqpAlgorithm` using the supplied backend factory for the
/// QP subproblem solver; otherwise returns `None` so the
/// caller can fall back to the IPM `build_with_backend`.
///
/// Sister to `build_with_backend`: the SQP algorithm doesn't
/// share `AlgorithmBundle`'s shape (no mu_update / no IPM
/// line search), so the two paths return different types.
pub fn build_sqp_with_backend(
&self,
mut factory: LinearBackendFactory,
) -> Option<crate::sqp::SqpAlgorithm> {
if !matches!(self.algorithm, AlgorithmChoice::ActiveSetSqp) {
return None;
}
let backend = factory(self.linear_solver);
let qp_solver = pounce_qp::ParametricActiveSetSolver::new(backend);
Some(
crate::sqp::SqpAlgorithm::new(qp_solver, self.sqp.clone())
.with_qp_options(self.sqp_qp.clone()),
)
}
fn build_inner(&self, search_dir: Option<PdSearchDirCalc>) -> AlgorithmBundle {
let mu_update: Box<dyn crate::mu::r#trait::MuUpdate> = match self.mu_strategy {
MuStrategyChoice::Monotone => {
let mut m = MonotoneMuUpdate::new();
m.mu_init = self.mu.mu_init;
// `mu_max` sentinel `-1` keeps the monotone default
// (1e5); only override on a user-supplied positive.
if self.mu.mu_max > 0.0 {
m.mu_max = self.mu.mu_max;
}
m.mu_min = self.mu.mu_min;
m.mu_target = self.mu.mu_target;
m.mu_linear_decrease_factor = self.mu.mu_linear_decrease_factor;
m.mu_superlinear_decrease_power = self.mu.mu_superlinear_decrease_power;
m.mu_allow_fast_monotone_decrease = self.mu.mu_allow_fast_monotone_decrease;
m.barrier_tol_factor = self.mu.barrier_tol_factor;
m.tau_min = self.mu.tau_min;
m.compl_inf_tol = self.conv_check.compl_inf_tol;
Box::new(m)
}
MuStrategyChoice::Adaptive => {
let mut adaptive = AdaptiveMuUpdate::new();
adaptive.mu_oracle = self.mu_oracle;
adaptive.mu_init = self.mu.mu_init;
// Adaptive treats `mu_max == -1` as "lazy init from
// `mu_max_fact * curr_avrg_compl`" — forward the
// sentinel as-is.
adaptive.mu_max = self.mu.mu_max;
adaptive.mu_max_fact = self.mu.mu_max_fact;
adaptive.mu_min = self.mu.mu_min;
adaptive.compl_inf_tol = self.conv_check.compl_inf_tol;
adaptive.mu_linear_decrease_factor = self.mu.mu_linear_decrease_factor;
adaptive.mu_superlinear_decrease_power = self.mu.mu_superlinear_decrease_power;
adaptive.barrier_tol_factor = self.mu.barrier_tol_factor;
adaptive.tau_min = self.mu.tau_min;
adaptive.sigma_min = self.mu.sigma_min;
adaptive.sigma_max = self.mu.sigma_max;
adaptive.adaptive_mu_globalization = self.mu.adaptive_mu_globalization;
adaptive.qf_norm_type = self.mu.quality_function_norm_type;
adaptive.qf_centrality_type = self.mu.quality_function_centrality;
adaptive.qf_balancing_term = self.mu.quality_function_balancing_term;
adaptive.qf_max_section_steps = self.mu.quality_function_max_section_steps;
adaptive.qf_section_sigma_tol = self.mu.quality_function_section_sigma_tol;
adaptive.qf_section_qf_tol = self.mu.quality_function_section_qf_tol;
adaptive.probing_iterate_quality_factor = self.mu.probing_iterate_quality_factor;
adaptive.adaptive_mu_safeguard_factor = self.mu.adaptive_mu_safeguard_factor;
adaptive.adaptive_mu_monotone_init_factor =
self.mu.adaptive_mu_monotone_init_factor;
adaptive.restore_accepted_iterate = self.mu.adaptive_mu_restore_previous_iterate;
adaptive.max_free_returns = self.mu.adaptive_mu_max_free_returns;
adaptive.budget_pin_fraction = self.mu.adaptive_mu_budget_pin_fraction;
// The pin measures against the same budget the
// convergence check enforces (pounce#753); the
// `conv_check` copies are the ones the application
// also hands to `Deadline::new`.
adaptive.max_cpu_time = self.conv_check.max_cpu_time;
adaptive.max_wall_time = self.conv_check.max_wall_time;
adaptive.adaptive_mu_kkterror_red_iters = self.mu.adaptive_mu_kkterror_red_iters;
adaptive.adaptive_mu_kkterror_red_fact = self.mu.adaptive_mu_kkterror_red_fact;
adaptive.adaptive_mu_kkt_norm = self.mu.adaptive_mu_kkt_norm_type;
adaptive.filter_margin_fact = self.mu.filter_margin_fact;
adaptive.filter_max_margin = self.mu.filter_max_margin;
Box::new(adaptive)
}
};
let acceptor: Box<dyn BacktrackingLsAcceptor> = match self.line_search_method {
LineSearchChoice::Filter => {
// Filter switching / Armijo / margin constants (#191):
// registered but previously never read. Set them on the
// concrete acceptor before boxing; defaults equal the
// registered defaults, so a run that doesn't set them is
// unchanged.
let mut f = FilterLsAcceptor::default();
f.eta_phi = self.line_search.eta_phi;
f.delta_armijo = self.line_search.delta;
f.theta_min_fact = self.line_search.theta_min_fact;
f.theta_max_fact = self.line_search.theta_max_fact;
f.theta_max_row_scale_kappa = self.line_search.theta_max_row_scale_kappa;
f.theta_max_adaptive_trigger = self.line_search.theta_max_adaptive_trigger;
f.theta_max_adaptive_factor = self.line_search.theta_max_adaptive_factor;
f.theta_max_adaptive_max_raises = self.line_search.theta_max_adaptive_max_raises;
f.gamma_phi = self.line_search.gamma_phi;
f.gamma_theta = self.line_search.gamma_theta;
f.s_phi = self.line_search.s_phi;
f.s_theta = self.line_search.s_theta;
f.alpha_min_frac = self.line_search.alpha_min_frac;
f.obj_max_inc = self.line_search.obj_max_inc;
f.max_filter_resets = self.line_search.max_filter_resets;
f.filter_reset_trigger = self.line_search.filter_reset_trigger;
Box::new(f)
}
// Penalty-acceptor constants: same direct-field pattern as
// the filter arm above. `reset()` re-seeds ν (and `last_nu`)
// from the freshly-set `nu_init`, which `default()` had
// seeded from the registered default.
LineSearchChoice::Penalty | LineSearchChoice::CgPenalty => {
// CG-penalty acceptor lands with the rest of the
// CG-penalty path; fall back to the penalty acceptor's
// surface for now.
let mut p = PenaltyLsAcceptor::default();
p.nu_init = self.line_search.nu_init;
p.nu_inc = self.line_search.nu_inc;
p.rho = self.line_search.rho;
p.eta_penalty = self.line_search.eta_penalty;
p.reset();
Box::new(p)
}
};
let mut line_search = BacktrackingLineSearch::new(acceptor);
line_search.alpha_red_factor = self.line_search.alpha_red_factor;
line_search.filter_theta_roundoff_retry = self.line_search.filter_theta_roundoff_retry;
// Resolve `None` against the Hessian mode; see the field's doc
// for the measurement behind the split (gh#818).
line_search.alpha_red_factor_min =
self.line_search
.alpha_red_factor_min
.unwrap_or(match self.hessian_approximation {
// The criterion in the field's doc is whether the
// model's *scale* is trustworthy, not whether it is
// the exact Hessian. A quasi-Newton `B` can be wrong
// by orders of magnitude in any direction its
// curvature pairs do not span, which is as true of
// the partitioned elements as of the limited-memory
// ones — they are the same update on a finer
// decomposition.
HessianApproxChoice::LimitedMemory | HessianApproxChoice::Partitioned => 0.05,
// Equal to `alpha_red_factor`, so the clamp in
// `next_alpha` collapses and the sequence is upstream's.
//
// `FiniteDifference` belongs here rather than above:
// it recovers the Lagrangian Hessian itself by
// probing the analytic Jacobian, so it carries no
// curvature history and its step is a Newton step
// whose length is meaningful. It is the same
// distinction `hessian_at_current` draws — a pure
// function of `(x, y)` on one side, a history-carrying
// `B` on the other. And the measurement behind the
// split cuts this way too: forcing `0.05` onto a path
// with a meaningful step length cost `eigena2` a
// solve.
HessianApproxChoice::Exact | HessianApproxChoice::FiniteDifference => {
self.line_search.alpha_red_factor
}
});
line_search.watchdog_shortened_iter_trigger =
self.line_search.watchdog_shortened_iter_trigger;
line_search.watchdog_trial_iter_max = self.line_search.watchdog_trial_iter_max;
line_search.soft_resto_pderror_reduction_factor =
self.line_search.soft_resto_pderror_reduction_factor;
line_search.max_soft_resto_iters = self.line_search.max_soft_resto_iters;
line_search.accept_every_trial_step = self.line_search.accept_every_trial_step;
line_search.alpha_for_y = self.line_search.alpha_for_y;
line_search.accept_after_max_steps = self.line_search.accept_after_max_steps;
// Second-order-correction constants (#191): registered but
// previously never read. Same direct-field pattern as the
// watchdog knobs above.
line_search.max_soc = self.line_search.max_soc;
line_search.kappa_soc = self.line_search.kappa_soc;
line_search.soc_method = self.line_search.soc_method;
let conv_check: Box<dyn crate::conv_check::r#trait::ConvCheck> =
Box::new(OptErrorConvCheck {
tol: self.conv_check.tol,
dual_inf_tol: self.conv_check.dual_inf_tol,
constr_viol_tol: self.conv_check.constr_viol_tol,
compl_inf_tol: self.conv_check.compl_inf_tol,
acceptable_tol: self.conv_check.acceptable_tol,
acceptable_dual_inf_tol: self.conv_check.acceptable_dual_inf_tol,
acceptable_constr_viol_tol: self.conv_check.acceptable_constr_viol_tol,
acceptable_compl_inf_tol: self.conv_check.acceptable_compl_inf_tol,
acceptable_obj_change_tol: self.conv_check.acceptable_obj_change_tol,
acceptable_iter: self.conv_check.acceptable_iter,
max_iter: self.conv_check.max_iter,
max_cpu_time: self.conv_check.max_cpu_time,
max_wall_time: self.conv_check.max_wall_time,
acceptable_count: 0,
last_acceptable_obj: None,
infeas_stationarity_tol: self.conv_check.infeas_stationarity_tol,
infeas_viol_kappa: self.conv_check.infeas_viol_kappa,
infeas_max_streak: self.conv_check.infeas_max_streak,
infeas_streak: 0,
obj_scale_certificate_threshold: self.conv_check.obj_scale_certificate_threshold,
primal_noise_floor_kappa: self.conv_check.primal_noise_floor_kappa,
acceptable_progress_kappa: self.conv_check.acceptable_progress_kappa,
acceptable_window: std::collections::VecDeque::new(),
acceptable_progress_refusals: 0,
dual_inf_scale_kappa: self.conv_check.dual_inf_scale_kappa,
dual_floor_reported: false,
veto_fired: false,
acceptable_veto_fired: false,
masked_acceptable_veto_fired: false,
veto_extra_iters: 0,
rel_infeas_extra_iters: 0,
prev_rel_viol: f64::NAN,
});
let init: Box<dyn crate::init::r#trait::IterateInitializer> = if self.warm_start_init_point
{
Box::new(WarmStartIterateInitializer::with_options(
resolved_warm_options(&self.warm, &self.init),
))
} else {
let mut d = DefaultIterateInitializer::with_eq_mult_calculator(Box::new(
LeastSquareMults::new(),
));
d.bound_push = self.init.bound_push;
d.bound_frac = self.init.bound_frac;
d.slack_bound_push = self.init.slack_bound_push;
d.slack_bound_frac = self.init.slack_bound_frac;
d.constr_mult_init_max = self.init.constr_mult_init_max;
d.bound_mult_init_val = self.init.bound_mult_init_val;
d.bound_mult_init_method = self.init.bound_mult_init_method.clone();
d.least_square_init_primal = self.init.least_square_init_primal;
Box::new(d)
};
let eq_mult: Box<dyn crate::eq_mult::r#trait::EqMultCalculator> =
Box::new(LeastSquareMults::new());
let hess: Box<dyn crate::hess::r#trait::HessianUpdater> = match self.hessian_approximation {
HessianApproxChoice::Exact => Box::new(ExactHessianUpdater::new()),
HessianApproxChoice::LimitedMemory => Box::new(LimMemQuasiNewtonUpdater {
update_type: self.limited_memory_update_type,
max_history: self.limited_memory_max_history,
init_val_max: self.limited_memory_init_val_max,
init_val_min: self.limited_memory_init_val_min,
initial_approx: self.limited_memory_initialization,
init_val: self.limited_memory_init_val,
max_skipping: self.limited_memory_max_skipping,
nonlinear_vars: self.limited_memory_nonlinear_vars.clone(),
..LimMemQuasiNewtonUpdater::default()
}),
HessianApproxChoice::Partitioned => {
let mut u =
crate::hess::partitioned_quasi_newton::PartitionedQuasiNewtonUpdater::new(
self.partitioned_update_type,
);
u.max_element = self.partitioned_max_element;
u.objective_vars = self.objective_nonlinear_vars.clone();
u.curvature_cap = self.partitioned_curvature_cap;
u.mode = self.partitioned_elements;
u.block_size = self.partitioned_block_size;
// Damped BFGS is the right pairing for a Lagrangian
// block: unlike a single constraint's Hessian, the
// Lagrangian's is the object the IPM wants a positive
// definite model of, and the sign problem that makes
// damping wrong per constraint does not arise. Only when
// the caller has not named a formula.
if self.partitioned_elements
== crate::hess::partitioned_quasi_newton::ElementMode::PrimalBlock
&& !self.partitioned_update_type_was_set
{
u.update_type = UpdateType::Bfgs;
}
u.init_val_min = self.limited_memory_init_val_min;
u.init_val_max = self.limited_memory_init_val_max;
Box::new(u)
}
HessianApproxChoice::FiniteDifference => {
let mut u = crate::hess::fd_hessian::FdHessianUpdater::new(self.fd_hessian_pattern);
u.coloring = self.fd_hessian_coloring;
u.reuse_tol = self.fd_hessian_reuse_tol;
u.objective_vars = self.objective_nonlinear_vars.clone();
u.nonlinear_vars = self.limited_memory_nonlinear_vars.clone();
Box::new(u)
}
};
let iter_output: Box<dyn crate::output::r#trait::IterationOutput> = {
use crate::output::orig::{InfPrTag, PrintInfoString};
let mut o = OrigIterationOutput::new();
o.print_frequency_iter = self.output.print_frequency_iter;
o.print_frequency_time = self.output.print_frequency_time;
o.print_info_string = if self.output.print_info_string {
PrintInfoString::Yes
} else {
PrintInfoString::No
};
o.inf_pr_output = if self.output.inf_pr_output_internal {
InfPrTag::Internal
} else {
InfPrTag::Original
};
Box::new(o)
};
AlgorithmBundle {
mu_update,
conv_check,
init,
eq_mult,
hess,
line_search,
iter_output,
search_dir,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn warm_options_take_the_init_default_not_their_own() {
let mut init = InitOptions::default();
init.bound_mult_init_val = 10.0; // the Mehrotra override value
let mut warm = WarmStartOptions::default();
warm.bound_mult_init_val = 123.0; // stale copy must lose
let resolved = resolved_warm_options(&warm, &init);
assert_eq!(resolved.bound_mult_init_val, 10.0);
// everything else passes through untouched
assert_eq!(resolved.mult_bound_push, warm.mult_bound_push);
assert_eq!(resolved.target_mu, warm.target_mu);
}
#[test]
fn default_builder_assembles() {
let bundle = AlgorithmBuilder::new().build();
// Sanity: the placeholder traits compile and the boxed
// strategies don't panic on construction.
let _ = bundle.line_search.acceptor();
assert!(bundle.search_dir.is_none());
}
#[test]
fn build_with_backend_assembles_search_dir_chain() {
// Drive the builder with the FERAL backend factory; the
// resulting bundle should expose a populated `PdSearchDirCalc`.
let factory: LinearBackendFactory = Box::new(|_| {
Box::new(pounce_feral::FeralSolverInterface::new())
as Box<dyn SparseSymLinearSolverInterface>
});
let bundle = AlgorithmBuilder::new().build_with_backend(factory);
assert!(bundle.search_dir.is_some());
}
#[test]
fn limited_memory_sr1_propagates() {
let b = AlgorithmBuilder {
hessian_approximation: HessianApproxChoice::LimitedMemory,
limited_memory_update_type: UpdateType::Sr1,
..AlgorithmBuilder::default()
};
let _bundle = b.build();
}
#[test]
fn every_strategy_combination_assembles_without_panic() {
let solvers = [LinearSolverChoice::Ma57, LinearSolverChoice::Feral];
let mu = [MuStrategyChoice::Monotone, MuStrategyChoice::Adaptive];
let hess = [
HessianApproxChoice::Exact,
HessianApproxChoice::LimitedMemory,
];
let ls = [
LineSearchChoice::Filter,
LineSearchChoice::CgPenalty,
LineSearchChoice::Penalty,
];
for &linear_solver in &solvers {
for &mu_strategy in &mu {
for &hessian_approximation in &hess {
for &line_search_method in &ls {
let _ = AlgorithmBuilder {
algorithm: AlgorithmChoice::default(),
linear_solver,
linear_system_scaling: LinearSystemScalingChoice::None,
linear_scaling_on_demand: true,
mu_strategy,
mu_oracle: MuOracleKind::QualityFunction,
hessian_approximation,
partitioned_update_type: UpdateType::Sr1,
partitioned_update_type_was_set: false,
partitioned_max_element: 64,
objective_nonlinear_vars: None,
partitioned_curvature_cap: Number::INFINITY,
partitioned_elements:
crate::hess::partitioned_quasi_newton::ElementMode::PerConstraint,
partitioned_block_size: 64,
fd_hessian_pattern: crate::hess::fd_hessian::FdPatternSource::Declared,
fd_hessian_coloring: crate::hess::fd_hessian::FdColoring::Cpr,
fd_hessian_reuse_tol: 0.0,
limited_memory_update_type: UpdateType::Bfgs,
limited_memory_max_history: 6,
limited_memory_init_val_max: 1e8,
limited_memory_init_val_min: 1e-8,
limited_memory_initialization: InitialApprox::Scalar1,
limited_memory_init_val: 1.0,
limited_memory_max_skipping: 2,
limited_memory_nonlinear_vars: None,
line_search_method,
warm_start_init_point: false,
mehrotra_algorithm: false,
fast_step_computation: false,
kappa_sigma: 1e10,
recalc_y: false,
recalc_y_feas_tol: 1e-6,
kappa_d: 1e-5,
s_max: 100.0,
tiny_step_tol: 10.0 * Number::EPSILON,
tiny_step_y_tol: 1e-2,
diverging_iterates_tol: 1e20,
dual_diverging_streak: 0,
dual_divergence_retry_step_tol: 1e-5,
dual_divergence_retry_du_floor: 1e2,
resto_decline_deferrals: 1,
resto_decline_progress_ratio: 0.5,
neg_curv_escapes: 1,
limited_memory_ls_failure_restarts: 0,
kkt_fidelity_tol: 0.0,
conv_check: ConvCheckOptions::default(),
mu: MuOptions::default(),
line_search: LineSearchOptions::default(),
refinement: RefinementOptions::default(),
perturbation: PerturbationOptions::default(),
resto: RestoOptions::default(),
output: OutputOptions::default(),
warm: WarmStartOptions::default(),
sqp: crate::sqp::SqpOptions::default(),
sqp_qp: pounce_qp::QpOptions::sqp_subproblem(),
init: InitOptions::default(),
kkt_schur: None,
quality_escalation_counter: None,
}
.build();
}
}
}
}
}
}