KiThe 0.3.22

A numerical suite for chemical kinetics and thermodynamics, combustion, heat and mass transfer,chemical equilibrium, chemical engeneering
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
//! Numerical solvers, error types, and SVD reaction basis for chemical equilibrium.
//!
//! # Purpose
//!
//! This module provides the **numerical core** of the equilibrium calculation pipeline.
//! It contains three nonlinear solvers (Levenberg-Marquardt, Newton-Raphson, Trust Region),
//! the SVD-based reaction basis computation, error types for the entire equilibrium
//! subsystem, and the feasibility constraint for mole non-negativity.
//!
//! # Physical and Mathematical Background
//!
//! ## Levenberg-Marquardt (LMSolver)
//!
//! Solves the nonlinear least-squares problem `min ||F(x)||²` using the damped
//! Gauss-Newton method:
//!
//! ```text
//! (J^T·J + λ·I)·s = -J^T·F
//! x_{k+1} = x_k + s
//! ```
//!
//! where `λ` is the damping parameter. The algorithm adapts `λ`:
//! - If the step reduces the residual, `λ` is decreased (closer to Gauss-Newton).
//! - If the step increases the residual, `λ` is increased (closer to gradient descent).
//!
//! The solvers enforce feasibility through their trial-state predicates and
//! the canonical positive log-mole representation.
//!
//! ## Newton-Raphson (NRSolver)
//!
//! Solves `F(x) = 0` using:
//!
//! ```text
//! J(x_k)·s = -F(x_k)
//! x_{k+1} = x_k + α_k · s
//! ```
//!
//! where `α_k ∈ (0, 1]` is determined by **line search with Armijo condition**:
//!
//! ```text
//! ||F(x_k + α·s)||² ≤ (1 - 2·α·c) · ||F(x_k)||²
//! ```
//!
//! Trial states are checked by the solver's feasibility predicate.
//!
//! ## Trust Region (TrustRegionSolver)
//!
//! Solves the constrained subproblem:
//!
//! ```text
//! min_{||s|| ≤ Δ} ||F(x_k) + J(x_k)·s||²
//! ```
//!
//! where `Δ` is the trust-region radius. The ratio of actual to predicted reduction:
//!
//! ```text
//! ρ = (||F(x_k)||² - ||F(x_k + s)||²) / (||F(x_k)||² - ||F(x_k) + J·s||²)
//! ```
//!
//! determines radius adaptation: if `ρ` is large, the radius grows; if small, it shrinks.
//!
//! ## SVD Reaction Basis
//!
//! The reaction basis is computed from the element composition matrix `A (species × elements)`:
//!
//! ```text
//! A = U · Σ · V^T
//! ```
//!
//! The stoichiometric matrix `ν (species × reactions)` is formed from columns of `V`
//! corresponding to zero (or near-zero) singular values. This guarantees that:
//!
//! ```text
//! A^T · ν = 0    (element conservation by construction)
//! ```
//!
//! If SVD does not return a complete nullspace, Gram-Schmidt orthogonalization
//! completes the basis.
//!
//! # Key Structures
//!
//! | Structure | Role |
//! |-----------|------|
//! | [`LMSolver`] | Levenberg-Marquardt solver with adaptive damping |
//! | [`NRSolver`] | Newton-Raphson solver with line search |
//! | [`TrustRegionSolver`] | Trust Region solver with adaptive radius |
//! | [`ReactionBasis`] | Container for SVD-derived reaction stoichiometry |
//! | [`SolveError`] | Solver-level errors (max iterations, singular matrix, eval error) |
//! | [`ReactionExtentError`] | Comprehensive equilibrium error hierarchy |
//! | [`BackendFailureKind`] | Classification of backend failures for retry logic |
//!
//! # Dataflow
//!
//! ```text
//!   Element composition matrix A (species × elements)
//!     │
//!     v
//!   compute_reaction_basis(A)
//!     ├── SVD: A = U·Σ·V^T
//!     ├── Extract nullspace columns from V
//!     ├── Gram-Schmidt completion if needed
//!     └── Return ReactionBasis { stoich_matrix, n_reactions }
//!     │
//!     v
//!   EquilibriumLogMoles builds residual/Jacobian closures
//!     │
//!     v
//!   LMSolver / NRSolver / TrustRegionSolver
//!     ├── Iterate until ||F(x)|| < tol or max_iter
//!     ├── Check trial-state feasibility
//!     └── Return solution or SolveError
//! ```
//!
//! # Error Hierarchy
//!
//! ```text
//! ReactionExtentError
//!   ├── InvalidProblem { field, message }     ── configuration errors
//!   ├── InvalidConditions { parameter, value } ── T, P, p0 validation
//!   ├── InvalidCandidate { message }           ── non-finite log-moles
//!   ├── DimensionMismatch(String)              ── matrix/vector shape errors
//!   ├── BackendFailure { kind, attempts }      ── solver cascade failures
//!   ├── SolveError                             ── wrapped solver errors
//!   ├── SpeciesNotAssigned(usize)              ── species without phase
//!   ├── SubsDataError                          ── database errors
//!   └── Aborted { reason }                     ── cascade aborted
//! ```
//!
//! # Examples
//!
//! ```rust
//! use KiThe::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::*;
//! use nalgebra::DMatrix;
//!
//! // Compute reaction basis for O2 dissociation
//! let elem_comp = DMatrix::from_row_slice(2, 1, &[2.0, 1.0]); // O2, O
//! let basis = compute_reaction_basis(&elem_comp, 1e-12).unwrap();
//! assert_eq!(basis.n_reactions, 1);
//! ```
//!
//! # Non-obvious Details
//!
//! - The LM solver's damping parameter `λ` is **adaptive**: it increases by 10× on
//!   rejected steps and decreases by 10× on accepted steps, clamped to `[1e-10, 1e10]`.
//! - The NR solver uses a **safeguarded line search** that backtracks from α=1 with
//!   a reduction factor of 0.5, ensuring sufficient decrease.
//! - The Trust Region solver solves the subproblem via the **dogleg method** when the
//!   Gauss-Newton step lies outside the trust region.
//! - Gram-Schmidt completion in `compute_reaction_basis` handles the case where SVD
//!   returns fewer nullspace vectors than the dimension of the nullspace.
//!
//! # Related Modules
//!
//! - [`equilibrium_log_moles`](super::equilibrium_log_moles) — orchestrator that uses these solvers
//! - [`equilibrium_native_backend`](super::equilibrium_native_backend) — adapter wrapping these solvers
//! - [`equilibrium_reaction_basis`](super::equilibrium_reaction_basis) — typed reaction basis wrapper
//!
use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventoryError;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::NativeSolverStage;
#[cfg(any(test, feature = "equilibrium-instrumentation"))]
use crate::Thermodynamics::ChemEquilibrium::equilibrium_instrumentation::{
    NativeCallbackKind, native_solver_timing_enabled, record_native_callback,
    record_native_jacobian, record_native_linear_system, record_native_residual,
    record_native_stage,
};
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::SolverAttemptOutcome;
use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::SolverAttemptReport;
use crate::Thermodynamics::User_substances_error::SubsDataError;
// These are fallback nonlinear implementations. Keep detailed iteration
// diagnostics available at debug level without making normal solves noisy.
use log::{debug as info, error};
use nalgebra::{DMatrix, DVector};
use std::error::Error;
use std::fmt;

/// Errors that can occur during nonlinear solving
#[derive(Debug, Clone)]
pub enum SolveError {
    /// Solver did not converge within max_iter
    MaxIterations,
    /// Linear system (LM normal equations) could not be solved
    SingularMatrix,
    /// Residual or Jacobian evaluation failed during solve
    EvalError(String),
}

impl fmt::Display for SolveError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MaxIterations => write!(f, "nonlinear solver reached its iteration limit"),
            Self::SingularMatrix => write!(f, "nonlinear solver encountered a singular matrix"),
            Self::EvalError(message) => write!(f, "nonlinear solver evaluation failed: {message}"),
        }
    }
}

impl Error for SolveError {}

/// Machine-readable class of a numerical backend failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendFailureKind {
    /// The backend could not solve one of its linearized subproblems.
    LinearSolve,
    /// The backend detected a singular or ill-conditioned Jacobian.
    SingularJacobian,
    /// The backend encountered NaN, Inf, or another numerical breakdown.
    NumericalBreakdown,
}

/// One rejected physical-temperature start in bounded monolithic P,H
/// recovery. The original typed cause remains available for backend-level
/// diagnostics.
#[derive(Debug)]
pub struct PhMonolithicSeedFailure {
    temperature_seed_k: f64,
    cause: Box<ReactionExtentError>,
}

impl PhMonolithicSeedFailure {
    pub(crate) fn new(temperature_seed_k: f64, cause: ReactionExtentError) -> Self {
        Self {
            temperature_seed_k,
            cause: Box::new(cause),
        }
    }

    /// Physical temperature used to construct this fresh nonlinear start.
    pub fn temperature_seed_k(&self) -> f64 {
        self.temperature_seed_k
    }

    /// Typed backend/formulation cause for this rejected start.
    pub fn cause(&self) -> &ReactionExtentError {
        &self.cause
    }

    pub(crate) fn into_cause(self) -> ReactionExtentError {
        *self.cause
    }
}

/// One rejected initial log-mole seed in explicit multi-start recovery.
/// The original typed cause remains available for backend-level diagnostics.
#[derive(Debug)]
pub struct MultiStartSeedFailure {
    start_index: usize,
    cause: Box<ReactionExtentError>,
}

impl MultiStartSeedFailure {
    pub(crate) fn new(start_index: usize, cause: ReactionExtentError) -> Self {
        Self {
            start_index,
            cause: Box::new(cause),
        }
    }

    /// Position of the seed in the caller-provided ordered seed list.
    pub fn start_index(&self) -> usize {
        self.start_index
    }

    /// Typed backend or formulation cause for this rejected seed.
    pub fn cause(&self) -> &ReactionExtentError {
        &self.cause
    }
}

/// Comprehensive error types for chemical equilibrium calculations
#[derive(Debug)]
pub enum ReactionExtentError {
    /// The caller cancelled a typed solve before its current transaction boundary.
    Cancelled,
    /// A typed equilibrium-problem field violates its documented contract.
    InvalidProblem {
        /// Name of the invalid field or invariant.
        field: &'static str,
        /// Human-readable explanation suitable for diagnostics.
        message: String,
    },
    /// A typed input-preparation boundary rejected the requested formulation.
    Preparation(EquilibriumPreparationError),
    /// Temperature, pressure, or reference pressure is invalid.
    InvalidConditions {
        /// Name of the invalid condition.
        parameter: &'static str,
        /// Invalid value supplied by the caller.
        value: f64,
    },
    /// A numerical backend returned a candidate that violates equilibrium
    /// acceptance invariants.
    InvalidCandidate {
        /// Name of the violated candidate invariant.
        field: &'static str,
        /// Explanation of the failed invariant.
        message: String,
    },
    /// Every backend in an explicit fallback policy terminated without an
    /// accepted candidate. The reports preserve the deterministic attempt trace.
    AllBackendsFailed { attempts: Vec<SolverAttemptReport> },
    /// A cascade already performed one or more numerical attempts, then met a
    /// non-retryable domain or configuration error. The trace is retained so
    /// callers can distinguish an aborted cascade from ordinary exhaustion.
    CascadeAborted {
        /// Ordered outcomes recorded before the aborting error.
        attempts: Vec<SolverAttemptReport>,
        /// The non-retryable error that stopped further fallback attempts.
        cause: Box<ReactionExtentError>,
    },
    /// A physical solve failed numerically and the explicit extensive-
    /// normalization recovery could not complete normalized discovery or the
    /// audited physical publication stage. Both causes remain available for
    /// release diagnostics.
    ExtensiveNormalizationRecoveryFailed {
        /// Recovery stage that failed after the original physical rejection.
        stage: &'static str,
        /// Original failure in physical extensive coordinates.
        physical: Box<ReactionExtentError>,
        /// Failure produced by normalized discovery or physical publication.
        recovery: Box<ReactionExtentError>,
    },
    /// Error from substance database operations
    SubsDataError(SubsDataError),
    /// Error originating from the underlying nonlinear solver
    SolveError(SolveError),
    /// A named numerical backend failed in a way that is distinct from a
    /// domain/residual contract failure and may be retried by a cascade.
    BackendFailure {
        /// Stable backend identifier from the solve policy.
        backend: String,
        /// Typed numerical failure class.
        kind: BackendFailureKind,
        /// Backend-provided diagnostic detail.
        message: String,
    },
    /// SVD failed when computing reaction basis
    SVDError(String),
    /// A requested validation/solver path is intentionally not applicable to
    /// the supplied system size or model class.
    ValidationNotApplicable {
        /// Name of the requested validation or solver path.
        path: &'static str,
        /// Human-readable reason for the refusal.
        message: String,
    },
    /// A selected backend cannot represent the requested nonlinear
    /// formulation. This is a capability mismatch, not a numerical failure,
    /// so backend fallback must not hide it.
    UnsupportedBackendCapability {
        /// Stable backend name from the solve policy.
        backend: String,
        /// Requested formulation/capability identifier.
        capability: &'static str,
        /// Alternatives that the caller may select explicitly.
        alternatives: String,
    },
    /// Phase-control outer loop exhausted its allowed restart budget.
    PhaseControlDidNotConverge {
        /// Number of outer iterations completed before the budget was hit.
        iterations: usize,
    },
    /// The active-set controller revisited an earlier phase assemblage.
    PhaseControlCycleDetected {
        /// Outer iteration at which the repeated set was proposed.
        iteration: usize,
        /// Ordered indices of phases that would be active after the transition.
        active_phases: Vec<usize>,
    },
    /// One outer P,H temperature trial failed while evaluating its inner
    /// fixed-`P,T` equilibrium. The location is retained instead of reducing
    /// the failure to an unqualified scalar-solver error.
    TemperatureTrialFailed {
        /// Zero-based position in the outer temperature trial sequence.
        trial_index: usize,
        /// Temperature passed to the inner equilibrium request.
        temperature: f64,
        /// Original typed failure from the inner solve or thermochemistry.
        cause: Box<ReactionExtentError>,
    },
    /// One point in a fixed-pressure temperature range failed. Unlike a
    /// display-only range annotation, this preserves the original backend
    /// trace and timing/termination metrics for release diagnosis.
    TemperatureRangePointFailed {
        /// Zero-based position in the requested temperature grid.
        point_index: usize,
        /// Temperature passed to the fixed-`P,T` equilibrium request.
        temperature: f64,
        /// Original typed failure from the prepared solve.
        cause: Box<ReactionExtentError>,
    },
    /// An automatic P,H solve exhausted both its monolithic primary route and
    /// its nested numerical recovery. Keeping both typed causes is essential:
    /// the final nested error alone cannot explain whether the primary route
    /// failed because of a phase boundary, a Jacobian problem, or a backend.
    PhAutoFallbackFailed {
        /// Rejected coupled log-mole/temperature attempt.
        monolithic: Box<ReactionExtentError>,
        /// Rejected safeguarded nested recovery attempt.
        nested: Box<ReactionExtentError>,
    },
    /// Every deterministic physical-temperature start for the monolithic P,H
    /// formulation was rejected. Each start owns its original backend trace.
    PhMonolithicSeedRecoveryFailed {
        /// Ordered fresh temperature starts and their typed causes.
        attempts: Vec<PhMonolithicSeedFailure>,
    },
    /// Every explicit multi-start log-mole seed was rejected. Each seed owns
    /// its original typed cascade error instead of reducing the batch to one
    /// summary string.
    MultiStartSeedRecoveryFailed {
        /// Ordered seed failures and their complete typed causes.
        attempts: Vec<MultiStartSeedFailure>,
    },
    /// A bounded monolithic P,H all-active probe solved numerically, but its
    /// TPD evidence did not authorize publishing the probed phase set.
    ///
    /// This is not malformed input and not an accepted physical candidate.
    /// The independently formulated nested-temperature route may therefore
    /// recover when `P,H Auto` is selected.
    PhMonolithicPhaseProbeRejected {
        /// Auditable reason why the probe could not become a lifecycle state.
        message: String,
    },
    /// Dimension mismatch between vectors/matrices
    DimensionMismatch(String),
    /// Duplicate species assigned to multiple phases
    DuplicateSpecies(usize),
    /// A species is not assigned to any phase.
    SpeciesNotAssigned { index: usize },
    /// Initial residual evaluation produced NaN/Inf
    InvalidInitialResiduals(Vec<f64>),
    /// Residual evaluation failed (generic)
    ResidualEvaluation(String),
    /// Jacobian evaluation failed (generic)
    JacobianEvaluation(String),
    /// Invalid species mole numbers (negative or zero)
    InvalidSpeciesAmount { index: usize, value: f64 },
    /// Invalid per-phase totals
    InvalidNPhase { index: usize, value: f64 },
    /// Invalid phi value
    InvalidPhi { index: usize, value: f64 },
    /// A species Gibbs-energy closure returned a non-finite value at the
    /// requested temperature.
    InvalidDG0 {
        /// Species position in the deterministic prepared ordering.
        species_index: usize,
        /// Value returned by the Gibbs-energy closure.
        dg0: f64,
        /// Temperature passed to the closure.
        temperature: f64,
    },
}

/// Typed failures that occur while preparing an equilibrium problem before a
/// nonlinear backend is allowed to run.
#[derive(Debug, Clone, PartialEq)]
pub enum EquilibriumPreparationError {
    /// No real phase/component universe was available for the requested input.
    EmptySpeciesUniverse,
    /// The supplied elemental inventory is not representable by the selected
    /// real-component matrix.
    NonRepresentableInventory { message: String },
    /// Numerical linear algebra could not construct the element-feasible seed.
    FeasibleSeedConstruction { message: String },
    /// The inventory failed typed validation or could not align to the matrix.
    ElementInventory(ElementInventoryError),
}

impl fmt::Display for EquilibriumPreparationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptySpeciesUniverse => {
                write!(
                    f,
                    "equilibrium preparation requires at least one real species"
                )
            }
            Self::NonRepresentableInventory { message } => {
                write!(f, "elemental inventory is not representable: {message}")
            }
            Self::FeasibleSeedConstruction { message } => {
                write!(f, "element-feasible seed construction failed: {message}")
            }
            Self::ElementInventory(error) => write!(f, "element inventory is invalid: {error}"),
        }
    }
}

impl Error for EquilibriumPreparationError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::ElementInventory(error) => Some(error),
            _ => None,
        }
    }
}

impl From<ElementInventoryError> for ReactionExtentError {
    fn from(value: ElementInventoryError) -> Self {
        Self::Preparation(EquilibriumPreparationError::ElementInventory(value))
    }
}

/// Machine-readable high-level classification for equilibrium failures.
///
/// This gives callers a stable, typed way to branch on failure families while
/// the detailed preparation cause remains available through the error value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ReactionExtentErrorKind {
    Cancelled,
    InvalidInput,
    ThermochemicalLookup,
    Formulation,
    ResidualEvaluation,
    JacobianEvaluation,
    BackendFailure,
    NonConvergence,
    InvalidCandidate,
    UnsupportedModel,
    ValidationMismatch,
    AllBackendsFailed,
    CascadeAborted,
}

impl From<SubsDataError> for ReactionExtentError {
    fn from(value: SubsDataError) -> Self {
        ReactionExtentError::SubsDataError(value)
    }
}

impl fmt::Display for ReactionExtentError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Cancelled => write!(f, "equilibrium solve was cancelled"),
            Self::InvalidProblem { field, message } => {
                write!(f, "invalid equilibrium problem field '{field}': {message}")
            }
            Self::Preparation(error) => write!(f, "equilibrium preparation failed: {error}"),
            Self::InvalidConditions { parameter, value } => {
                write!(f, "invalid equilibrium condition '{parameter}': {value}")
            }
            Self::InvalidCandidate { field, message } => {
                write!(
                    f,
                    "equilibrium candidate field '{field}' was rejected: {message}"
                )
            }
            Self::AllBackendsFailed { attempts } => {
                write!(
                    f,
                    "all equilibrium solver backends failed after {} attempt(s)",
                    attempts.len()
                )
            }
            Self::CascadeAborted { attempts, cause } => write!(
                f,
                "equilibrium solver cascade aborted after {} attempt(s): {cause}",
                attempts.len()
            ),
            Self::ExtensiveNormalizationRecoveryFailed {
                stage,
                physical,
                recovery,
            } => write!(
                f,
                "extensive-normalization recovery failed during {stage}; physical attempt: {physical}; recovery attempt: {recovery}"
            ),
            Self::SubsDataError(error) => write!(f, "equilibrium data preparation failed: {error}"),
            Self::SolveError(error) => write!(f, "equilibrium solver failed: {error}"),
            Self::BackendFailure {
                backend,
                kind,
                message,
            } => write!(
                f,
                "equilibrium backend '{backend}' failed ({kind:?}): {message}"
            ),
            Self::SVDError(message) => write!(f, "reaction-basis construction failed: {message}"),
            Self::ValidationNotApplicable { path, message } => {
                write!(f, "validation path '{path}' is not applicable: {message}")
            }
            Self::UnsupportedBackendCapability {
                backend,
                capability,
                alternatives,
            } => write!(
                f,
                "backend '{backend}' does not support capability '{capability}'; supported alternatives: {alternatives}"
            ),
            Self::PhaseControlDidNotConverge { iterations } => {
                write!(
                    f,
                    "phase-control outer loop did not converge after {iterations} iteration(s)"
                )
            }
            Self::PhaseControlCycleDetected {
                iteration,
                active_phases,
            } => write!(
                f,
                "phase-control cycle detected at iteration {iteration} for active phases {active_phases:?}"
            ),
            Self::TemperatureTrialFailed {
                trial_index,
                temperature,
                cause,
            } => write!(
                f,
                "P,H temperature trial {trial_index} at {temperature} K failed: {cause}"
            ),
            Self::TemperatureRangePointFailed {
                point_index,
                temperature,
                cause,
            } => write!(
                f,
                "equilibrium temperature-range point {point_index} at {temperature} K failed: {cause}"
            ),
            Self::PhAutoFallbackFailed { monolithic, nested } => write!(
                f,
                "automatic P,H recovery failed; monolithic attempt: {monolithic}; nested recovery: {nested}"
            ),
            Self::PhMonolithicSeedRecoveryFailed { attempts } => write!(
                f,
                "monolithic P,H temperature-seed recovery failed after {} attempt(s)",
                attempts.len()
            ),
            Self::MultiStartSeedRecoveryFailed { attempts } => write!(
                f,
                "explicit multi-start recovery failed after {} seed attempt(s)",
                attempts.len()
            ),
            Self::PhMonolithicPhaseProbeRejected { message } => {
                write!(f, "monolithic P,H phase probe was rejected: {message}")
            }
            Self::DimensionMismatch(message) => {
                write!(f, "equilibrium dimension mismatch: {message}")
            }
            Self::DuplicateSpecies(index) => {
                write!(f, "species index {index} belongs to multiple phases")
            }
            Self::SpeciesNotAssigned { index } => {
                write!(f, "species index {index} is not assigned to any phase")
            }
            Self::InvalidInitialResiduals(values) => {
                write!(
                    f,
                    "initial equilibrium residual contains non-finite values: {values:?}"
                )
            }
            Self::ResidualEvaluation(message) => {
                write!(f, "equilibrium residual evaluation failed: {message}")
            }
            Self::JacobianEvaluation(message) => {
                write!(f, "equilibrium Jacobian evaluation failed: {message}")
            }
            Self::InvalidSpeciesAmount { index, value } => {
                write!(f, "invalid mole amount at species index {index}: {value}")
            }
            Self::InvalidNPhase { index, value } => {
                write!(f, "invalid total mole amount for phase {index}: {value}")
            }
            Self::InvalidPhi { index, value } => {
                write!(f, "invalid phase correction at phase {index}: {value}")
            }
            Self::InvalidDG0 {
                species_index,
                dg0,
                temperature,
            } => {
                write!(
                    f,
                    "invalid standard Gibbs energy {dg0} for species index {species_index} at temperature {temperature}"
                )
            }
        }
    }
}

impl Error for ReactionExtentError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Cancelled => None,
            Self::Preparation(error) => Some(error),
            Self::SubsDataError(error) => Some(error),
            Self::SolveError(error) => Some(error),
            Self::CascadeAborted { cause, .. } => Some(cause.as_ref()),
            Self::ExtensiveNormalizationRecoveryFailed { recovery, .. } => Some(recovery.as_ref()),
            Self::TemperatureTrialFailed { cause, .. } => Some(cause.as_ref()),
            Self::TemperatureRangePointFailed { cause, .. } => Some(cause.as_ref()),
            Self::PhAutoFallbackFailed { nested, .. } => Some(nested.as_ref()),
            Self::PhMonolithicSeedRecoveryFailed { attempts } => {
                attempts.last().map(|attempt| attempt.cause() as _)
            }
            Self::MultiStartSeedRecoveryFailed { attempts } => {
                attempts.last().map(|attempt| attempt.cause() as _)
            }
            _ => None,
        }
    }
}

impl ReactionExtentError {
    /// Returns the machine-readable high-level kind for this error.
    pub fn kind(&self) -> ReactionExtentErrorKind {
        match self {
            Self::Cancelled => ReactionExtentErrorKind::Cancelled,
            Self::Preparation(_) => ReactionExtentErrorKind::InvalidInput,
            Self::InvalidProblem { .. }
            | Self::InvalidConditions { .. }
            | Self::DimensionMismatch(_)
            | Self::DuplicateSpecies(_)
            | Self::SpeciesNotAssigned { .. }
            | Self::InvalidInitialResiduals(_)
            | Self::InvalidSpeciesAmount { .. }
            | Self::InvalidNPhase { .. }
            | Self::InvalidPhi { .. } => ReactionExtentErrorKind::Formulation,
            Self::SubsDataError(_) => ReactionExtentErrorKind::ThermochemicalLookup,
            Self::InvalidCandidate { .. } => ReactionExtentErrorKind::InvalidCandidate,
            Self::InvalidDG0 { .. } => ReactionExtentErrorKind::ThermochemicalLookup,
            Self::SolveError(SolveError::MaxIterations) => ReactionExtentErrorKind::NonConvergence,
            Self::SolveError(_) => ReactionExtentErrorKind::BackendFailure,
            Self::BackendFailure { .. } => ReactionExtentErrorKind::BackendFailure,
            Self::SVDError(_) => ReactionExtentErrorKind::UnsupportedModel,
            Self::ValidationNotApplicable { .. } => ReactionExtentErrorKind::ValidationMismatch,
            Self::UnsupportedBackendCapability { .. } => ReactionExtentErrorKind::UnsupportedModel,
            Self::PhaseControlDidNotConverge { .. } | Self::PhaseControlCycleDetected { .. } => {
                ReactionExtentErrorKind::NonConvergence
            }
            Self::ResidualEvaluation(_) => ReactionExtentErrorKind::ResidualEvaluation,
            Self::JacobianEvaluation(_) => ReactionExtentErrorKind::JacobianEvaluation,
            Self::AllBackendsFailed { .. } => ReactionExtentErrorKind::AllBackendsFailed,
            Self::CascadeAborted { .. } => ReactionExtentErrorKind::CascadeAborted,
            Self::ExtensiveNormalizationRecoveryFailed { recovery, .. } => recovery.kind(),
            Self::TemperatureTrialFailed { cause, .. } => cause.kind(),
            Self::TemperatureRangePointFailed { cause, .. } => cause.kind(),
            Self::PhAutoFallbackFailed { nested, .. } => nested.kind(),
            Self::PhMonolithicSeedRecoveryFailed { .. } => {
                ReactionExtentErrorKind::AllBackendsFailed
            }
            Self::MultiStartSeedRecoveryFailed { .. } => ReactionExtentErrorKind::AllBackendsFailed,
            Self::PhMonolithicPhaseProbeRejected { .. } => {
                ReactionExtentErrorKind::InvalidCandidate
            }
        }
    }

    /// Number of concrete nonlinear backend attempts retained by this error.
    ///
    /// Wrapper errors are traversed recursively so P,H seed recovery, `Auto`
    /// fallback, and range failures can enforce one global work budget.
    pub fn started_backend_attempts(&self) -> usize {
        match self {
            Self::AllBackendsFailed { attempts } | Self::CascadeAborted { attempts, .. } => {
                attempts
                    .iter()
                    .filter(|attempt| {
                        !matches!(attempt.outcome, SolverAttemptOutcome::Skipped { .. })
                    })
                    .count()
            }
            Self::TemperatureTrialFailed { cause, .. }
            | Self::TemperatureRangePointFailed { cause, .. } => cause.started_backend_attempts(),
            Self::ExtensiveNormalizationRecoveryFailed {
                physical, recovery, ..
            } => physical
                .started_backend_attempts()
                .saturating_add(recovery.started_backend_attempts()),
            Self::PhAutoFallbackFailed { monolithic, nested } => monolithic
                .started_backend_attempts()
                .saturating_add(nested.started_backend_attempts()),
            Self::PhMonolithicSeedRecoveryFailed { attempts } => attempts
                .iter()
                .map(|attempt| attempt.cause().started_backend_attempts())
                .sum(),
            Self::MultiStartSeedRecoveryFailed { attempts } => attempts
                .iter()
                .map(|attempt| attempt.cause().started_backend_attempts())
                .sum(),
            _ => 0,
        }
    }

    /// Returns every retained concrete backend attempt in execution order.
    ///
    /// Wrapper failures are flattened so diagnostics can account for the
    /// original physical solve, normalization discovery, seed recovery, and
    /// nested P,H fallback without reconstructing the error tree themselves.
    pub fn backend_attempt_reports(&self) -> Vec<SolverAttemptReport> {
        let mut reports = Vec::new();
        self.collect_backend_attempt_reports(&mut reports);
        reports
    }

    fn collect_backend_attempt_reports(&self, output: &mut Vec<SolverAttemptReport>) {
        match self {
            Self::AllBackendsFailed { attempts } | Self::CascadeAborted { attempts, .. } => {
                output.extend(attempts.iter().cloned());
            }
            Self::TemperatureTrialFailed { cause, .. }
            | Self::TemperatureRangePointFailed { cause, .. } => {
                cause.collect_backend_attempt_reports(output);
            }
            Self::ExtensiveNormalizationRecoveryFailed {
                physical, recovery, ..
            } => {
                physical.collect_backend_attempt_reports(output);
                recovery.collect_backend_attempt_reports(output);
            }
            Self::PhAutoFallbackFailed { monolithic, nested } => {
                monolithic.collect_backend_attempt_reports(output);
                nested.collect_backend_attempt_reports(output);
            }
            Self::PhMonolithicSeedRecoveryFailed { attempts } => {
                for attempt in attempts {
                    attempt.cause().collect_backend_attempt_reports(output);
                }
            }
            Self::MultiStartSeedRecoveryFailed { attempts } => {
                for attempt in attempts {
                    attempt.cause().collect_backend_attempt_reports(output);
                }
            }
            _ => {}
        }
    }

    /// Aggregate nonlinear iterations retained by this error's backend trace.
    pub fn nonlinear_iterations(&self) -> usize {
        match self {
            Self::AllBackendsFailed { attempts } | Self::CascadeAborted { attempts, .. } => {
                attempts
                    .iter()
                    .filter_map(|attempt| attempt.metrics.as_ref())
                    .map(|metrics| metrics.iterations)
                    .sum()
            }
            Self::TemperatureTrialFailed { cause, .. }
            | Self::TemperatureRangePointFailed { cause, .. } => cause.nonlinear_iterations(),
            Self::ExtensiveNormalizationRecoveryFailed {
                physical, recovery, ..
            } => physical
                .nonlinear_iterations()
                .saturating_add(recovery.nonlinear_iterations()),
            Self::PhAutoFallbackFailed { monolithic, nested } => monolithic
                .nonlinear_iterations()
                .saturating_add(nested.nonlinear_iterations()),
            Self::PhMonolithicSeedRecoveryFailed { attempts } => attempts
                .iter()
                .map(|attempt| attempt.cause().nonlinear_iterations())
                .sum(),
            Self::MultiStartSeedRecoveryFailed { attempts } => attempts
                .iter()
                .map(|attempt| attempt.cause().nonlinear_iterations())
                .sum(),
            _ => 0,
        }
    }

    /// Returns `true` when another numerical backend may legitimately retry.
    ///
    /// Invalid input, malformed configuration, and unsupported model errors
    /// deliberately return `false` so fallback cannot hide a bad problem
    /// definition behind later attempts.
    pub fn is_retryable_backend_failure(&self) -> bool {
        matches!(
            self.kind(),
            ReactionExtentErrorKind::NonConvergence
                | ReactionExtentErrorKind::BackendFailure
                | ReactionExtentErrorKind::ResidualEvaluation
                | ReactionExtentErrorKind::JacobianEvaluation
        )
    }

    /// Returns `true` when a distinct numerical *formulation* may recover the
    /// request after this error.
    ///
    /// An exhausted backend cascade is not retryable by one more backend, but
    /// it is a valid reason for P,H `Auto` to try the independently formulated
    /// nested temperature workflow. Non-retryable input and thermochemistry
    /// errors deliberately remain outside this boundary.
    pub fn is_retryable_formulation_failure(&self) -> bool {
        match self {
            Self::AllBackendsFailed { attempts } => {
                !attempts.is_empty()
                    && attempts.iter().all(|attempt| {
                        matches!(attempt.outcome, SolverAttemptOutcome::Failed { .. })
                    })
            }
            Self::CascadeAborted { cause, .. } => cause.is_retryable_formulation_failure(),
            Self::PhMonolithicSeedRecoveryFailed { attempts } => {
                !attempts.is_empty()
                    && attempts
                        .iter()
                        .all(|attempt| attempt.cause().is_retryable_formulation_failure())
            }
            Self::MultiStartSeedRecoveryFailed { attempts } => {
                !attempts.is_empty()
                    && attempts
                        .iter()
                        .all(|attempt| attempt.cause().is_retryable_formulation_failure())
            }
            Self::PhMonolithicPhaseProbeRejected { .. } => true,
            _ => self.is_retryable_backend_failure(),
        }
    }

    /// Returns `true` for errors that should fail fast before fallback.
    pub fn is_non_retryable_input_error(&self) -> bool {
        if matches!(self, Self::PhMonolithicPhaseProbeRejected { .. }) {
            return false;
        }
        matches!(
            self.kind(),
            ReactionExtentErrorKind::InvalidInput
                | ReactionExtentErrorKind::ThermochemicalLookup
                | ReactionExtentErrorKind::Formulation
                | ReactionExtentErrorKind::InvalidCandidate
                | ReactionExtentErrorKind::UnsupportedModel
                | ReactionExtentErrorKind::ValidationMismatch
        )
    }
}

#[cfg(test)]
mod error_contract_tests {
    use super::{
        EquilibriumPreparationError, MultiStartSeedFailure, PhMonolithicSeedFailure,
        ReactionExtentError, ReactionExtentErrorKind, SolveError,
    };
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_element_inventory::ElementInventoryError;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_log_moles::Solvers;
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_solver_policy::{
        SolverAttemptFailureKind, SolverAttemptMetrics, SolverAttemptOutcome, SolverAttemptReport,
        SolverBackend, SolverTermination,
    };
    use crate::Thermodynamics::User_substances_error::SubsDataError;
    use std::error::Error;

    #[test]
    fn equilibrium_errors_are_displayable_and_preserve_nested_sources() {
        let solve_error = ReactionExtentError::SolveError(SolveError::MaxIterations);
        assert_eq!(
            solve_error.to_string(),
            "equilibrium solver failed: nonlinear solver reached its iteration limit"
        );
        assert!(solve_error.source().is_some());

        let data_error =
            ReactionExtentError::from(SubsDataError::SubstanceNotFound("O2".to_string()));
        assert!(data_error.to_string().contains("O2"));
        assert!(data_error.source().is_some());
    }

    #[test]
    fn preparation_errors_keep_typed_inventory_causes_and_fail_fast_classification() {
        let error = ReactionExtentError::from(ElementInventoryError::EmptyInventory);
        assert!(matches!(
            &error,
            ReactionExtentError::Preparation(EquilibriumPreparationError::ElementInventory(
                ElementInventoryError::EmptyInventory
            ))
        ));
        assert_eq!(error.kind(), ReactionExtentErrorKind::InvalidInput);
        assert!(error.is_non_retryable_input_error());
        assert!(error.source().is_some());
        assert!(error.to_string().contains("at least one positive amount"));
    }

    #[test]
    fn multi_start_failure_preserves_each_typed_cascade_and_aggregates_work() {
        let cascade_failure = |solver| ReactionExtentError::AllBackendsFailed {
            attempts: vec![SolverAttemptReport {
                backend: SolverBackend::Native(solver),
                outcome: SolverAttemptOutcome::Failed {
                    kind: SolverAttemptFailureKind::Solver,
                    reason: "iteration limit".to_string(),
                    elapsed_micros: 0,
                },
                metrics: Some(SolverAttemptMetrics {
                    termination: SolverTermination::MaxIterations,
                    backend_converged: false,
                    iterations: 3,
                    backend_progress_available: true,
                    residual_evaluations: 4,
                    jacobian_evaluations: 3,
                    linear_solves: 3,
                    counters_collected: true,
                    timings_collected: false,
                    elapsed_millis: 1,
                    elapsed_micros: 1_000,
                    evaluation_timing: None,
                }),
            }],
        };
        let error = ReactionExtentError::MultiStartSeedRecoveryFailed {
            attempts: vec![
                MultiStartSeedFailure::new(0, cascade_failure(Solvers::LM)),
                MultiStartSeedFailure::new(1, cascade_failure(Solvers::NR)),
            ],
        };

        assert_eq!(error.kind(), ReactionExtentErrorKind::AllBackendsFailed);
        assert_eq!(error.started_backend_attempts(), 2);
        assert_eq!(error.nonlinear_iterations(), 6);
        assert!(error.is_retryable_formulation_failure());
        assert!(error.source().is_some());
        assert!(error.to_string().contains("2 seed attempt(s)"));
        let ReactionExtentError::MultiStartSeedRecoveryFailed { attempts } = error else {
            panic!("expected typed multi-start recovery failure");
        };
        assert_eq!(attempts[0].start_index(), 0);
        assert!(matches!(
            attempts[0].cause(),
            ReactionExtentError::AllBackendsFailed { attempts } if attempts.len() == 1
        ));
    }

    #[test]
    fn all_backend_failure_display_reports_the_attempt_count() {
        let error = ReactionExtentError::AllBackendsFailed {
            attempts: Vec::new(),
        };
        assert_eq!(
            error.to_string(),
            "all equilibrium solver backends failed after 0 attempt(s)"
        );
        assert!(error.source().is_none());
        assert_eq!(error.kind(), ReactionExtentErrorKind::AllBackendsFailed);
        assert!(!error.is_retryable_backend_failure());
        assert!(!error.is_retryable_formulation_failure());
    }

    #[test]
    fn auto_formulation_retry_requires_only_started_numerical_failures() {
        let backend = SolverBackend::Native(Solvers::NR);
        let failed = || SolverAttemptReport {
            backend,
            outcome: SolverAttemptOutcome::Failed {
                kind: SolverAttemptFailureKind::Solver,
                reason: "iteration limit".to_string(),
                elapsed_micros: 0,
            },
            metrics: None,
        };
        let rejected = SolverAttemptReport {
            backend,
            outcome: SolverAttemptOutcome::RejectedCandidate {
                reason: "candidate residual is too large".to_string(),
            },
            metrics: None,
        };
        let skipped = SolverAttemptReport {
            backend,
            outcome: SolverAttemptOutcome::Skipped {
                reason: "cascade budget exhausted".to_string(),
            },
            metrics: None,
        };

        let retryable = ReactionExtentError::AllBackendsFailed {
            attempts: vec![failed(), failed()],
        };
        assert!(retryable.is_retryable_formulation_failure());

        for attempts in [
            vec![rejected.clone()],
            vec![skipped.clone()],
            vec![failed(), rejected],
            Vec::new(),
        ] {
            let error = ReactionExtentError::AllBackendsFailed { attempts };
            assert!(!error.is_retryable_formulation_failure());
        }
    }

    #[test]
    fn rejected_monolithic_phase_probe_allows_only_formulation_fallback() {
        let error = ReactionExtentError::PhMonolithicPhaseProbeRejected {
            message: "TPD did not authorize the probed phase".to_string(),
        };

        assert_eq!(error.kind(), ReactionExtentErrorKind::InvalidCandidate);
        assert!(!error.is_retryable_backend_failure());
        assert!(error.is_retryable_formulation_failure());
        assert!(!error.is_non_retryable_input_error());
        assert!(error.to_string().contains("phase probe was rejected"));
    }

    #[test]
    fn aggregate_ph_errors_report_started_backend_work_recursively() {
        let backend = SolverBackend::Native(Solvers::NR);
        let failed_seed = |temperature| {
            PhMonolithicSeedFailure::new(
                temperature,
                ReactionExtentError::AllBackendsFailed {
                    attempts: vec![SolverAttemptReport {
                        backend,
                        outcome: SolverAttemptOutcome::Failed {
                            kind: SolverAttemptFailureKind::Solver,
                            reason: "iteration limit".to_string(),
                            elapsed_micros: 0,
                        },
                        metrics: None,
                    }],
                },
            )
        };
        let monolithic = ReactionExtentError::PhMonolithicSeedRecoveryFailed {
            attempts: vec![failed_seed(600.0), failed_seed(1_000.0)],
        };
        assert_eq!(monolithic.started_backend_attempts(), 2);
        assert_eq!(monolithic.nonlinear_iterations(), 0);

        let auto = ReactionExtentError::PhAutoFallbackFailed {
            monolithic: Box::new(monolithic),
            nested: Box::new(ReactionExtentError::AllBackendsFailed {
                attempts: vec![SolverAttemptReport {
                    backend,
                    outcome: SolverAttemptOutcome::Failed {
                        kind: SolverAttemptFailureKind::Solver,
                        reason: "nested iteration limit".to_string(),
                        elapsed_micros: 0,
                    },
                    metrics: None,
                }],
            }),
        };
        assert_eq!(auto.started_backend_attempts(), 3);
    }

    #[test]
    fn aborted_cascade_preserves_the_non_retryable_cause() {
        let error = ReactionExtentError::CascadeAborted {
            attempts: Vec::new(),
            cause: Box::new(ReactionExtentError::InvalidProblem {
                field: "solver_policy",
                message: "missing backend".to_string(),
            }),
        };
        assert!(
            error
                .to_string()
                .contains("cascade aborted after 0 attempt(s)")
        );
        assert!(error.source().is_some());
        assert_eq!(error.kind(), ReactionExtentErrorKind::CascadeAborted);
    }

    #[test]
    fn auto_ph_failure_retains_primary_and_recovery_causes() {
        let error = ReactionExtentError::PhAutoFallbackFailed {
            monolithic: Box::new(ReactionExtentError::AllBackendsFailed {
                attempts: Vec::new(),
            }),
            nested: Box::new(ReactionExtentError::SolveError(SolveError::MaxIterations)),
        };

        assert!(error.to_string().contains("monolithic attempt"));
        assert!(error.to_string().contains("nested recovery"));
        assert!(error.source().is_some());
        assert_eq!(error.kind(), ReactionExtentErrorKind::NonConvergence);
        assert!(error.is_retryable_backend_failure());
    }

    #[test]
    fn species_not_assigned_display_reports_the_missing_index() {
        let error = ReactionExtentError::SpeciesNotAssigned { index: 3 };
        assert_eq!(
            error.to_string(),
            "species index 3 is not assigned to any phase"
        );
    }

    #[test]
    fn error_kind_classifies_core_families() {
        assert_eq!(
            ReactionExtentError::InvalidProblem {
                field: "solver_policy",
                message: "missing backend".to_string(),
            }
            .kind(),
            ReactionExtentErrorKind::Formulation
        );
        assert_eq!(
            ReactionExtentError::from(SubsDataError::SubstanceNotFound("O2".to_string())).kind(),
            ReactionExtentErrorKind::ThermochemicalLookup
        );
        assert_eq!(
            ReactionExtentError::ResidualEvaluation("bad residual".to_string()).kind(),
            ReactionExtentErrorKind::ResidualEvaluation
        );
        assert_eq!(
            ReactionExtentError::SolveError(SolveError::MaxIterations).kind(),
            ReactionExtentErrorKind::NonConvergence
        );
        assert_eq!(
            ReactionExtentError::ValidationNotApplicable {
                path: "keq_solver",
                message: "too many reactions".to_string(),
            }
            .kind(),
            ReactionExtentErrorKind::ValidationMismatch
        );
        let phase_error = ReactionExtentError::PhaseControlDidNotConverge { iterations: 3 };
        assert_eq!(phase_error.kind(), ReactionExtentErrorKind::NonConvergence);
        assert!(phase_error.to_string().contains("phase-control outer loop"));
    }

    #[test]
    fn unsupported_backend_capability_is_typed_and_non_retryable() {
        let error = ReactionExtentError::UnsupportedBackendCapability {
            backend: "RustedSciThe".to_string(),
            capability: "monolithic_p_h",
            alternatives: "native LM, NR, or trust-region backends".to_string(),
        };

        assert_eq!(error.kind(), ReactionExtentErrorKind::UnsupportedModel);
        assert!(!error.is_retryable_backend_failure());
        let message = error.to_string();
        assert!(message.contains("RustedSciThe"));
        assert!(message.contains("monolithic_p_h"));
        assert!(message.contains("native LM"));
    }

    #[test]
    fn cancellation_is_a_non_retryable_typed_error() {
        let error = ReactionExtentError::Cancelled;
        assert_eq!(error.to_string(), "equilibrium solve was cancelled");
        assert_eq!(error.kind(), ReactionExtentErrorKind::Cancelled);
        assert!(!error.is_retryable_backend_failure());
        assert!(!error.is_non_retryable_input_error());
        assert!(error.source().is_none());
    }

    #[test]
    fn temperature_trial_error_preserves_location_source_and_kind() {
        let cause = ReactionExtentError::InvalidProblem {
            field: "inner",
            message: "synthetic endpoint failure".to_string(),
        };
        let error = ReactionExtentError::TemperatureTrialFailed {
            trial_index: 3,
            temperature: 812.5,
            cause: Box::new(cause),
        };

        assert!(error.to_string().contains("trial 3"));
        assert!(error.to_string().contains("812.5 K"));
        assert!(error.source().is_some());
        assert_eq!(error.kind(), ReactionExtentErrorKind::Formulation);
        assert!(error.is_non_retryable_input_error());
    }
}

/// Levenberg-Marquardt solver for nonlinear equation systems
///
/// Robust solver that combines Gauss-Newton with gradient descent using adaptive damping.
/// Particularly effective for chemical equilibrium problems with poor initial guesses.
pub struct LMSolver<F, J, C>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
    J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
    C: Fn(&[f64]) -> bool,
{
    /// Residual function f(x) = 0
    pub f: F,
    /// Jacobian function J(x) = df/dx
    pub jacobian: J,
    /// Feasibility constraint checker
    pub feasible: C,
    /// Damping parameter (increased when steps rejected)
    pub lambda: f64,
    /// Convergence tolerance for ||f(x)||
    pub tol: f64,
    /// Maximum number of iterations
    pub max_iter: usize,
    /// Minimum step size before giving up
    pub alpha_min: f64,
}

impl<F, J, C> LMSolver<F, J, C>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
    J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
    C: Fn(&[f64]) -> bool,
{
    /// Solves nonlinear system f(x) = 0 using Levenberg-Marquardt algorithm
    ///
    /// Uses adaptive damping and line search to ensure robust convergence.
    /// Respects feasibility constraints throughout the solution process.
    pub fn solve(&mut self, mut x: Vec<f64>) -> Result<Vec<f64>, SolveError> {
        let n = x.len();

        let mut lambda = self.lambda;

        for _iter in 0..self.max_iter {
            let f_val = timed_native_residual(&self.f, &x).map_err(|error| {
                SolveError::EvalError(format!("residual evaluation failed: {error}"))
            })?;
            info!("Iteration {}, x = {:?}, f = {:?}", _iter, x, f_val);
            let f_norm = l2_norm(&f_val);
            info!("  ||f|| = {}", f_norm);
            if f_norm < self.tol {
                return Ok(x);
            }
            if f_norm.is_nan() || f_norm.is_infinite() {
                return Err(SolveError::SingularMatrix);
            }

            let j = timed_native_jacobian(&self.jacobian, &x).map_err(|error| {
                SolveError::EvalError(format!("Jacobian evaluation failed: {error}"))
            })?;
            info!("  Jacobian:\n{}", j);
            if j.nrows() != n || j.ncols() != n {
                error!(
                    "Jacobian nrows = {} ncols = {}, state length = {}",
                    j.nrows(),
                    j.ncols(),
                    n
                );
                return Err(SolveError::EvalError(
                    "Jacobian dimension mismatch".to_string(),
                ));
            }
            if j.iter().any(|value| !value.is_finite()) {
                return Err(SolveError::SingularMatrix);
            }
            let jt = timed_native_stage(NativeSolverStage::MatrixOperations, || j.transpose());

            let mut lhs = timed_native_stage(NativeSolverStage::MatrixOperations, || &jt * &j);
            let jtj = &lhs;
            info!("  Jᵀ·J:\n{}", jtj);
            timed_native_stage(NativeSolverStage::MatrixOperations, || {
                for i in 0..n {
                    lhs[(i, i)] += lambda;
                }
            });

            let rhs = timed_native_stage(NativeSolverStage::MatrixOperations, || {
                -(&jt * DVector::from_vec(f_val))
            });

            let delta_result = timed_native_linear_system(|| lhs.lu().solve(&rhs));
            let delta = delta_result.ok_or(SolveError::SingularMatrix)?;
            info!("  Step delta: {:?}", delta);

            let mut alpha = 1.0;
            let mut accepted = false;

            while alpha >= self.alpha_min {
                let x_trial: Vec<f64> = timed_native_stage(NativeSolverStage::TrialVector, || {
                    x.iter()
                        .zip(delta.iter())
                        .map(|(xi, dxi)| xi + alpha * dxi)
                        .collect()
                });
                info!("    Trial x (alpha={}): {:?}", alpha, x_trial);
                let feasible = timed_native_stage(NativeSolverStage::Feasibility, || {
                    (self.feasible)(&x_trial)
                });
                if !feasible {
                    alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
                    continue;
                }

                let f_trial = timed_native_residual(&self.f, &x_trial).map_err(|error| {
                    SolveError::EvalError(format!("residual evaluation failed: {error}"))
                })?;
                info!("    Trial f: {:?}", f_trial);
                let f_trial_norm = l2_norm(&f_trial);
                info!("    ||f_trial|| = {}", f_trial_norm);
                if f_trial_norm < f_norm {
                    x = x_trial;
                    lambda = timed_native_stage(NativeSolverStage::Globalization, || lambda * 0.3);
                    accepted = true;
                    break;
                } else {
                    alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
                }
            }

            if !accepted {
                lambda = timed_native_stage(NativeSolverStage::Globalization, || lambda * 10.0);
                info!(
                    "  No acceptable step found; increasing lambda to {}",
                    lambda
                );
            }
        }

        Err(SolveError::MaxIterations)
    }
}
//////////////////////////////////////NR SOLVER//////////////////////////////////////////////////////////////

/// Newton-Raphson solver with line search and feasibility constraints
///
/// Fast quadratic convergence near solution, with backtracking line search
/// and bound constraints to handle chemical equilibrium problems.
pub struct NRSolver<F, J, C>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
    J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
    C: Fn(&[f64]) -> bool,
{
    /// Residual function f(x) = 0
    pub f: F,
    /// Jacobian function J(x) = df/dx
    pub jacobian: J,
    /// Feasibility constraint checker
    pub feasible: C,
    /// Convergence tolerance for ||f(x)||
    pub tol: f64,
    /// Maximum number of iterations
    pub max_iter: usize,
    /// Minimum step size before giving up
    pub alpha_min: f64,
}

impl<F, J, C> NRSolver<F, J, C>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
    J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
    C: Fn(&[f64]) -> bool,
{
    /// Solves nonlinear system using Newton-Raphson with line search
    ///
    /// Performs backtracking line search with feasibility checking.
    /// Checks trial-state feasibility before accepting a step.
    pub fn solve(&mut self, mut x: Vec<f64>) -> Result<Vec<f64>, SolveError> {
        let n = x.len();

        for iter in 0..self.max_iter {
            let f_val = timed_native_residual(&self.f, &x)
                .map_err(|error| SolveError::EvalError(error.to_string()))?;
            info!("NR Iteration {}, x = {:?}, f = {:?}", iter, x, f_val);
            let f_norm = l2_norm(&f_val);
            info!(" ||f|| = {}", f_norm);
            if f_norm < self.tol {
                return Ok(x);
            }
            if f_norm.is_nan() || f_norm.is_infinite() {
                return Err(SolveError::SingularMatrix);
            }
            let j = timed_native_jacobian(&self.jacobian, &x)
                .map_err(|error| SolveError::EvalError(error.to_string()))?;

            info!(" Jacobian:\n{}", j);
            if j.nrows() != n || j.ncols() != n {
                error!(
                    "Jacobian nrows = {} ncols ={}, initial guess length {}",
                    j.nrows(),
                    j.ncols(),
                    n
                );
                return Err(SolveError::EvalError(
                    "Jacobian dimension mismatch".to_string(),
                ));
            }
            // Solve J * delta = -f
            let rhs = timed_native_stage(NativeSolverStage::MatrixOperations, || {
                -DVector::from_vec(f_val)
            });
            let delta_result = timed_native_linear_system(|| j.lu().solve(&rhs));
            let delta_vec = delta_result.ok_or(SolveError::SingularMatrix)?;
            let delta = delta_vec.data.as_vec();
            info!(" Step delta: {:?}", delta_vec);
            let mut alpha = 1.0;
            info!("bounded step {}", alpha);

            let mut accepted = false;
            while alpha >= self.alpha_min {
                let x_trial: Vec<f64> = timed_native_stage(NativeSolverStage::TrialVector, || {
                    x.iter()
                        .zip(delta.iter())
                        .map(|(xi, dxi)| xi + alpha * dxi)
                        .collect()
                });
                info!(" Trial x (alpha={}): {:?}", alpha, x_trial);
                let feasible = timed_native_stage(NativeSolverStage::Feasibility, || {
                    (self.feasible)(&x_trial)
                });
                if !feasible {
                    alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
                    continue;
                }

                let f_trial = timed_native_residual(&self.f, &x_trial)
                    .map_err(|error| SolveError::EvalError(error.to_string()))?;

                info!(" Trial f: {:?}", f_trial);

                let f_trial_norm = l2_norm(&f_trial);
                info!(" ||f_trial|| = {}", f_trial_norm);
                if f_trial_norm < f_norm {
                    x = x_trial;
                    accepted = true;
                    break;
                }

                alpha = timed_native_stage(NativeSolverStage::Globalization, || alpha * 0.5);
                if !accepted {
                    info!(" No acceptable step found; continuing to next iteration");
                }
            }

            if !accepted {
                error!(
                    "NR solver exhausted iteration {} without an acceptable step",
                    iter
                );
                return Err(SolveError::MaxIterations);
            }
        }

        error!("NR solver reached the iteration limit without convergence");
        Err(SolveError::MaxIterations)
    }
}

#[inline]
fn timed_native_residual<F>(f: &F, values: &[f64]) -> Result<Vec<f64>, ReactionExtentError>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
{
    #[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
    {
        return f(values);
    }

    #[cfg(any(test, feature = "equilibrium-instrumentation"))]
    {
        if native_solver_timing_enabled() {
            record_native_callback(NativeCallbackKind::Residual, values);
        }
        let started = native_solver_timing_enabled().then(std::time::Instant::now);
        let result = f(values);
        if let Some(started) = started {
            record_native_residual(started.elapsed());
        }
        result
    }
}

#[inline]
fn timed_native_jacobian<F>(
    jacobian: &F,
    values: &[f64],
) -> Result<DMatrix<f64>, ReactionExtentError>
where
    F: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
{
    #[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
    {
        return jacobian(values);
    }

    #[cfg(any(test, feature = "equilibrium-instrumentation"))]
    {
        if native_solver_timing_enabled() {
            record_native_callback(NativeCallbackKind::Jacobian, values);
        }
        let started = native_solver_timing_enabled().then(std::time::Instant::now);
        let result = jacobian(values);
        if let Some(started) = started {
            record_native_jacobian(started.elapsed());
        }
        result
    }
}

#[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
#[inline]
fn timed_native_linear_system<F, T>(solve: F) -> T
where
    F: FnOnce() -> T,
{
    solve()
}

#[cfg(any(test, feature = "equilibrium-instrumentation"))]
fn timed_native_linear_system<F, T>(solve: F) -> T
where
    F: FnOnce() -> T,
{
    let started = std::time::Instant::now();
    let result = solve();
    record_native_linear_system(started.elapsed());
    result
}

#[cfg(not(any(test, feature = "equilibrium-instrumentation")))]
#[inline]
fn timed_native_stage<T, F>(_: NativeSolverStage, operation: F) -> T
where
    F: FnOnce() -> T,
{
    operation()
}

#[cfg(any(test, feature = "equilibrium-instrumentation"))]
#[inline]
fn timed_native_stage<T, F>(stage: NativeSolverStage, operation: F) -> T
where
    F: FnOnce() -> T,
{
    let started = native_solver_timing_enabled().then(std::time::Instant::now);
    let result = operation();
    if let Some(started) = started {
        record_native_stage(stage, started.elapsed());
    }
    result
}

/// Computes L2 norm of a vector
///
/// Helper function for convergence checking in solvers.
fn l2_norm(v: &[f64]) -> f64 {
    timed_native_stage(NativeSolverStage::Norm, || {
        v.iter().map(|x| x * x).sum::<f64>().sqrt()
    })
}
///////////////////////TRUST REGION///////////////////////////////////////////////////

pub struct TrustRegionSolver<F, J, C>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
    J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
    C: Fn(&[f64]) -> bool,
{
    pub f: F,
    pub jacobian: J,
    pub feasible: C,

    pub tol: f64,
    pub max_iter: usize,

    // Trust region parameters
    pub delta_init: f64,
    pub delta_max: f64,
    pub eta: f64, // acceptance threshold (e.g. 0.1)
}

impl<F, J, C> TrustRegionSolver<F, J, C>
where
    F: Fn(&[f64]) -> Result<Vec<f64>, ReactionExtentError>,
    J: Fn(&[f64]) -> Result<DMatrix<f64>, ReactionExtentError>,
    C: Fn(&[f64]) -> bool,
{
    pub fn solve(&self, mut x: Vec<f64>) -> Result<Vec<f64>, SolveError> {
        let n = x.len();
        let mut delta = self.delta_init;

        for _iter in 0..self.max_iter {
            let f_val = timed_native_residual(&self.f, &x)
                .map_err(|error| SolveError::EvalError(error.to_string()))?;
            if f_val.len() != n {
                return Err(SolveError::EvalError("residual dimension mismatch".into()));
            }
            if f_val.iter().any(|value| !value.is_finite()) {
                return Err(SolveError::SingularMatrix);
            }

            let f_norm = l2_norm(&f_val);
            if f_norm < self.tol {
                return Ok(x);
            }

            let J = timed_native_jacobian(&self.jacobian, &x)
                .map_err(|error| SolveError::EvalError(error.to_string()))?;

            if J.nrows() != n || J.ncols() != n {
                error!(
                    "Trust region Jacobian nrows = {} ncols = {}, state length = {}",
                    J.nrows(),
                    J.ncols(),
                    n
                );
                return Err(SolveError::EvalError("Jacobian not square".into()));
            }
            if J.iter().any(|value| !value.is_finite()) {
                return Err(SolveError::SingularMatrix);
            }

            let fvec = timed_native_stage(NativeSolverStage::MatrixOperations, || {
                DVector::from_vec(f_val)
            });

            // --- Cauchy step ---
            let g = timed_native_stage(NativeSolverStage::MatrixOperations, || {
                &J.transpose() * &fvec
            });
            let g_norm_sq = timed_native_stage(NativeSolverStage::Norm, || g.dot(&g));
            let jg = timed_native_stage(NativeSolverStage::MatrixOperations, || &J * &g);
            let jg_norm_sq = timed_native_stage(NativeSolverStage::Norm, || jg.dot(&jg));
            let alpha = g_norm_sq / jg_norm_sq.max(1e-16);
            let cauchy_step =
                timed_native_stage(NativeSolverStage::MatrixOperations, || -alpha * g.clone());

            // --- Dogleg step ---
            let cauchy_norm = timed_native_stage(NativeSolverStage::Norm, || cauchy_step.norm());
            // A boundary Cauchy step does not use the Newton step. Delay the
            // LU solve until the dogleg path actually needs Newton data.
            let p = if cauchy_norm >= delta {
                timed_native_stage(NativeSolverStage::MatrixOperations, || {
                    delta / cauchy_norm * cauchy_step
                })
            } else {
                let newton_step_result =
                    timed_native_linear_system(|| J.clone().lu().solve(&(-&fvec)));
                let newton_step = newton_step_result.ok_or(SolveError::SingularMatrix)?;
                let newton_norm =
                    timed_native_stage(NativeSolverStage::Norm, || newton_step.norm());
                timed_native_stage(NativeSolverStage::MatrixOperations, || {
                    if newton_norm <= delta {
                        newton_step
                    } else {
                        let p_u = cauchy_step;
                        let p_b = newton_step;
                        let d = &p_b - &p_u;

                        let a = d.dot(&d);
                        let b = 2.0 * p_u.dot(&d);
                        let c = p_u.dot(&p_u) - delta * delta;

                        let tau = (-b + (b * b - 4.0 * a * c).sqrt()) / (2.0 * a);
                        p_u + tau * d
                    }
                })
            };
            let p_norm = timed_native_stage(NativeSolverStage::Norm, || p.norm());

            let x_trial: Vec<f64> = timed_native_stage(NativeSolverStage::TrialVector, || {
                x.iter().zip(p.iter()).map(|(xi, pi)| xi + pi).collect()
            });

            let feasible =
                timed_native_stage(NativeSolverStage::Feasibility, || (self.feasible)(&x_trial));
            if !feasible {
                timed_native_stage(NativeSolverStage::Globalization, || delta *= 0.25);
                continue;
            }

            let f_trial = timed_native_residual(&self.f, &x_trial)
                .map_err(|error| SolveError::EvalError(error.to_string()))?;

            // A numerically exact trial root must be accepted directly.  At
            // that point the quadratic-model reduction can be zero or lose
            // its sign through round-off, which is not a reason to reject a
            // valid solution and shrink the region into a false singularity.
            if l2_norm(&f_trial) < self.tol {
                return Ok(x_trial);
            }

            let actual_reduction = f_norm.powi(2) - l2_norm(&f_trial).powi(2);
            if !actual_reduction.is_finite() {
                return Err(SolveError::SingularMatrix);
            }

            // The quadratic model is for ||f + Jp||^2, so its linear term is
            // g^T p where g = J^T f. Using f^T p here is dimensionally wrong
            // and can make a well-improving step look harmful when J is
            // ill-conditioned, collapsing the trust region to machine noise.
            // The quadratic model only needs p^T J^T J p = ||Jp||^2.
            // Forming the dense J^T J matrix here repeats expensive work and
            // allocates a matrix that is immediately reduced to one scalar.
            let jacobian_trial =
                timed_native_stage(NativeSolverStage::MatrixOperations, || &J * &p);
            let linear_model_term = timed_native_stage(NativeSolverStage::Norm, || g.dot(&p));
            let quadratic_model_term = timed_native_stage(NativeSolverStage::Norm, || {
                jacobian_trial.dot(&jacobian_trial)
            });
            let model_reduction = -2.0 * linear_model_term - quadratic_model_term;

            if !model_reduction.is_finite() || model_reduction <= 0.0 {
                timed_native_stage(NativeSolverStage::Globalization, || delta *= 0.25);
                continue;
            }

            let rho = actual_reduction / model_reduction;

            // --- Trust region update ---
            timed_native_stage(NativeSolverStage::Globalization, || {
                if rho < 0.25 {
                    delta *= 0.25;
                } else if rho > 0.75 && (p_norm - delta).abs() < 1e-12 {
                    delta = (2.0 * delta).min(self.delta_max);
                }
            });

            // --- Accept / reject ---
            if rho > self.eta {
                x = x_trial;
            }

            if delta < 1e-14 {
                error!("Trust region solver exhausted the trust radius before convergence");
                return Err(SolveError::SingularMatrix);
            }
        }

        error!("Trust region solver reached the iteration limit without convergence");
        Err(SolveError::MaxIterations)
    }
}

/////////////////////////////////////////////////////////////////////////////////////////////////
/// Container for independent chemical reaction basis
///
/// Holds the results of SVD-based reaction discovery from elemental composition.
#[derive(Debug, Clone)]
pub struct ReactionBasis {
    /// Rank of element composition matrix A
    pub rank: usize,
    /// Number of independent reactions (nullspace dimension)
    pub num_reactions: usize,
    /// Reaction stoichiometry matrix N (m x r)
    /// Each column is one independent reaction
    pub reactions: DMatrix<f64>,
}

/// Computes a basis of independent chemical reactions from an element
/// composition matrix.
///
/// # Mathematical meaning
///
/// Let `A` be the element composition matrix with:
/// - rows corresponding to chemical species
/// - columns corresponding to chemical elements
/// - `A[i, e]` equal to the number of atoms of element `e` in species `i`
///
/// Any physically admissible chemical reaction must conserve each element:
///
/// ```text
/// Aᵀ · ν = 0
/// ```
///
/// where `ν` is the vector of stoichiometric coefficients of a reaction.
/// Therefore, all independent reactions lie in the nullspace of `Aᵀ`.
///
/// This function computes a basis of that nullspace using singular value
/// decomposition (SVD).
///
/// # Physical meaning
///
/// - Each column of the returned matrix represents one independent chemical
///   reaction.
/// - The sign and scaling of each reaction vector are arbitrary and have no
///   physical significance.
/// - Together, these reactions span all possible composition changes that
///   conserve elements.
///
/// The number of independent reactions is:
///
/// ```text
/// r = number_of_species − rank(A)
/// ```
///
/// This construction guarantees that:
/// - Element conservation is satisfied automatically
/// - No redundant or dependent reactions are introduced
/// - Equilibrium systems formulated in reaction extents are well-conditioned
///
/// # Arguments
///
/// * `a`   – Element composition matrix `(m × E)`
/// * `tol` – Singular value threshold used to determine numerical rank
///
/// # Returns
///
/// A [`ReactionBasis`] containing:
/// - the rank of the element matrix
/// - the number of independent reactions
/// - a reaction stoichiometry matrix `(m × r)`
///
/// # Notes
///
/// This function does **not** classify species as reactants or products.
/// That distinction emerges naturally from the solution of the equilibrium
/// equations.
///
/// # Panics
///
/// Panics if SVD decomposition fails (which should not happen for finite
/// matrices).
pub fn compute_reaction_basis(
    a: &DMatrix<f64>,
    tol: f64,
) -> Result<ReactionBasis, ReactionExtentError> {
    use nalgebra::linalg::SVD;

    if !tol.is_finite() || tol <= 0.0 {
        return Err(ReactionExtentError::InvalidProblem {
            field: "reaction_basis_tolerance",
            message: "reaction-basis tolerance must be finite and strictly positive".to_string(),
        });
    }
    if a.nrows() == 0 || a.ncols() == 0 {
        return Err(ReactionExtentError::InvalidProblem {
            field: "reaction_basis_matrix",
            message: "element composition matrix must have positive dimensions".to_string(),
        });
    }
    if a.iter().any(|value| !value.is_finite()) {
        return Err(ReactionExtentError::InvalidProblem {
            field: "reaction_basis_matrix",
            message: "element composition matrix must contain only finite values".to_string(),
        });
    }

    let m = a.nrows(); // species

    // SVD of Aᵀ (elements × species)
    let at = a.transpose();
    let svd = SVD::new(at, true, true);

    let v_t = match svd.v_t {
        Some(v) => v,
        None => {
            let msg = "SVD failed: Vᵀ".to_string();
            error!("{}", msg);
            return Err(ReactionExtentError::SVDError(msg));
        }
    };
    let singular_values = svd.singular_values;

    // Numerical rank
    let rank = singular_values.iter().filter(|&&s| s > tol).count();

    let num_reactions = if rank <= m { m - rank } else { 0 };

    let mut reactions = DMatrix::<f64>::zeros(m, num_reactions);

    // Collect available rows of Vᵀ (nalgebra returns a "thin" Vᵀ of size min(E, m) × m)
    let p = v_t.nrows(); // number of available singular vectors (<= m)

    // Convert rows of v_t into column vectors of length m
    let mut v_rows: Vec<DVector<f64>> = Vec::new();
    for i in 0..p {
        v_rows.push(v_t.row(i).transpose());
    }

    // Fill reaction columns using available nullspace vectors from Vᵀ (those with zero singular values
    // that are present in the returned Vᵀ). If there are fewer available than needed, we'll complete the
    // nullspace by constructing orthonormal vectors orthogonal to the span of the nonzero-singular-value rows.
    let mut col = 0;

    // Rows corresponding to small/zero singular values are at indices rank..p-1
    for i in rank..p {
        if col >= num_reactions {
            break;
        }
        reactions.set_column(col, &v_rows[i]);
        col += 1;
    }

    // If we still need more nullspace vectors (happens when p < m), construct them via Gram-Schmidt
    if col < num_reactions {
        // The span we must be orthogonal to is the space spanned by the first `rank` rows (if rank>0)
        let orth_span: Vec<&DVector<f64>> = v_rows.iter().take(rank).collect();

        // The thin SVD may already have supplied part of the nullspace.
        // Seed Gram-Schmidt with those vectors so completion cannot duplicate
        // or linearly combine an already selected reaction direction.
        let mut null_basis: Vec<DVector<f64>> = v_rows[rank..p].to_vec();

        for j in 0..m {
            if col >= num_reactions {
                break;
            }

            // start from standard basis vector e_j
            let mut cand = DVector::<f64>::from_element(m, 0.0);
            cand[j] = 1.0;

            // subtract projection onto orth_span (non-null singular vectors)
            for rvec in &orth_span {
                let dot = rvec.dot(&cand);
                cand -= *rvec * dot;
            }

            // subtract projection onto previously found null basis vectors to maintain orthogonality
            for u in &null_basis {
                let dot = u.dot(&cand);
                cand -= u * dot;
            }

            let norm = cand.norm();
            if norm > tol {
                let u = cand / norm;
                reactions.set_column(col, &u);
                null_basis.push(u);
                col += 1;
            }
        }
    }
    if col != num_reactions {
        return Err(ReactionExtentError::InvalidProblem {
            field: "reaction_basis_nullspace",
            message: format!(
                "constructed {col} independent nullspace vectors, expected {num_reactions}"
            ),
        });
    }

    let reactions = -1.0 * reactions; // flip sign convention

    Ok(ReactionBasis {
        rank,
        num_reactions,
        reactions,
    })
}
///////////////////////////////TESTS////////////////////////////////////
#[cfg(test)]
mod tests {
    fn approx_eq(a: f64, b: f64, tol: f64) -> bool {
        (a - b).abs() < tol
    }
    use super::*;
    #[test]
    fn lm_solves_scalar_quadratic() {
        let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 2.0]) as Result<Vec<f64>, ReactionExtentError>;

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
                as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_x: &[f64]| true;

        let mut solver = LMSolver {
            f,
            jacobian: j,
            feasible,
            lambda: 1e-3,
            tol: 1e-12,
            max_iter: 50,
            alpha_min: 1e-6,
        };

        let x0 = vec![1.0];
        let sol = solver.solve(x0).unwrap();

        assert!(approx_eq(sol[0], 2.0_f64.sqrt(), 1e-8));
    }
    #[test]
    fn lm_solves_2d_nonlinear_system() {
        let f = |x: &[f64]| {
            Ok(vec![x[0] * x[0] + x[1] * x[1] - 1.0, x[0] - x[1]])
                as Result<Vec<f64>, ReactionExtentError>
        };

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(
                2,
                2,
                &[2.0 * x[0], 2.0 * x[1], 1.0, -1.0],
            )) as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_x: &[f64]| true;

        let mut solver = LMSolver {
            f,
            jacobian: j,
            feasible,
            lambda: 1e-3,
            tol: 1e-12,
            max_iter: 50,
            alpha_min: 1e-6,
        };

        let x0 = vec![0.8, 0.3];
        let sol = solver.solve(x0).unwrap();

        let expected = 1.0 / 2.0_f64.sqrt();
        assert!(approx_eq(sol[0], expected, 1e-8));
        assert!(approx_eq(sol[1], expected, 1e-8));
    }

    #[test]
    fn lm_respects_feasibility_constraint() {
        let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 1.0]) as Result<Vec<f64>, ReactionExtentError>;

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
                as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |x: &[f64]| x[0] >= 0.0;

        let mut solver = LMSolver {
            f,
            jacobian: j,
            feasible,
            lambda: 1e-3,
            tol: 1e-12,
            max_iter: 50,
            alpha_min: 1e-6,
        };

        let x0 = vec![0.1];
        let sol = solver.solve(x0).unwrap();

        assert!(approx_eq(sol[0], 1.0, 1e-8));
    }

    #[test]
    fn lm_handles_flat_jacobian() {
        let f = |x: &[f64]| Ok(vec![x[0].powi(3)]) as Result<Vec<f64>, ReactionExtentError>;

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(
                1,
                1,
                &[3.0 * x[0] * x[0]],
            )) as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_x: &[f64]| true;

        let mut solver = LMSolver {
            f,
            jacobian: j,
            feasible,
            lambda: 1e-4,
            tol: 1e-15,
            max_iter: 1000,
            alpha_min: 1e-8,
        };

        let x0 = vec![0.5];
        let sol = solver.solve(x0).unwrap();
        info!("{:?}", &sol);
        assert!(sol[0].abs() < 1e-5);
    }
    #[test]
    fn lm_reports_max_iterations() {
        let f = |_x: &[f64]| Ok(vec![1.0]); // no root
        let j = |_x: &[f64]| Ok(nalgebra::DMatrix::identity(1, 1));
        let feasible = |_x: &[f64]| true;

        let mut solver = LMSolver {
            f,
            jacobian: j,
            feasible,
            lambda: 1e-3,
            tol: 1e-12,
            max_iter: 5,
            alpha_min: 1e-6,
        };

        let res = solver.solve(vec![0.0]);
        assert!(matches!(res, Err(SolveError::MaxIterations)));
    }
}

#[cfg(test)]
mod tests_reaction_basis {
    use crate::Thermodynamics::ChemEquilibrium::equilibrium_nonlinear::{
        ReactionExtentError, compute_reaction_basis,
    };
    use log::info;
    use nalgebra::DMatrix;

    const TOL: f64 = 1e-10;

    #[test]
    fn diatomic_dissociation_o2_o() {
        // Species: O2, O
        // Elements: O
        //
        // Reaction: O2 ⇌ 2 O

        let a = DMatrix::from_row_slice(
            2,
            1,
            &[
                2.0, // O2
                1.0, // O
            ],
        );

        let basis = compute_reaction_basis(&a, TOL).unwrap();
        info!("basis: {:?}", basis);
        assert_eq!(basis.rank, 1);
        assert_eq!(basis.num_reactions, 1);

        // Check element conservation: Aᵀ * ν = 0
        let residual = a.transpose() * &basis.reactions;
        assert!(residual.norm() < 1e-12);
    }

    #[test]
    fn nitrogen_oxygen_system() {
        // Species: N2, O2, NO, NO2
        // Elements: N, O

        let a = DMatrix::from_row_slice(
            4,
            2,
            &[
                2.0, 0.0, // N2
                0.0, 2.0, // O2
                1.0, 1.0, // NO
                1.0, 2.0, // NO2
            ],
        );

        let basis = compute_reaction_basis(&a, TOL).unwrap();

        assert_eq!(basis.rank, 2);
        assert_eq!(basis.num_reactions, 2);

        // Check nullspace condition
        let residual = a.transpose() * &basis.reactions;
        assert!(residual.norm() < 1e-12);
    }

    #[test]
    fn methane_combustion_species() {
        // Species: CH4, O2, CO2, H2O
        // Elements: C, H, O

        let a = DMatrix::from_row_slice(
            4,
            3,
            &[
                1.0, 4.0, 0.0, // CH4
                0.0, 0.0, 2.0, // O2
                1.0, 0.0, 2.0, // CO2
                0.0, 2.0, 1.0, // H2O
            ],
        );

        let basis = compute_reaction_basis(&a, TOL).unwrap();
        assert_eq!(basis.rank, 3);
        assert_eq!(basis.num_reactions, 1);

        let residual = a.transpose() * &basis.reactions;
        assert!(residual.norm() < 1e-12);
    }

    #[test]
    fn reaction_basis_o2_not_zero() {
        use nalgebra::DMatrix;

        let a = DMatrix::from_row_slice(2, 1, &[2.0, 1.0]);

        let rb = compute_reaction_basis(&a, 1e-12).unwrap();

        assert_eq!(rb.num_reactions, 1);

        let nu = rb.reactions.column(0);

        assert!(
            nu.iter().any(|&x| x.abs() > 1e-6),
            "Reaction vector is zero!"
        );

        // Element conservation check
        assert!((2.0 * nu[0] + 1.0 * nu[1]).abs() < 1e-10);
    }

    #[test]
    fn rectangular_rank_deficient_basis_has_complete_independent_nullspace() {
        // Four species and two declared element columns, with the second
        // element column dependent on the first by being identically zero.
        let a = DMatrix::from_row_slice(4, 2, &[1.0, 0.0, 2.0, 0.0, 3.0, 0.0, 4.0, 0.0]);

        let basis = compute_reaction_basis(&a, 1e-12).unwrap();
        assert_eq!(basis.rank, 1);
        assert_eq!(basis.num_reactions, 3);
        assert!(
            (basis.reactions.transpose() * &basis.reactions)
                .svd(false, false)
                .singular_values
                .iter()
                .all(|value| *value > 1e-8),
            "reaction columns must be independent: {:?}",
            basis.reactions
        );
        assert!((a.transpose() * &basis.reactions).norm() < 1e-10);
    }

    #[test]
    fn reaction_basis_rejects_invalid_matrix_and_rank_tolerances() {
        let a = DMatrix::from_row_slice(2, 1, &[2.0, 1.0]);
        assert!(matches!(
            compute_reaction_basis(&a, 0.0),
            Err(ReactionExtentError::InvalidProblem {
                field: "reaction_basis_tolerance",
                ..
            })
        ));
        assert!(matches!(
            compute_reaction_basis(&DMatrix::from_row_slice(1, 1, &[f64::NAN]), 1e-12),
            Err(ReactionExtentError::InvalidProblem {
                field: "reaction_basis_matrix",
                ..
            })
        ));

        let nearly_dependent = DMatrix::from_row_slice(2, 2, &[1.0, 0.0, 0.0, 1e-14]);
        assert_eq!(
            compute_reaction_basis(&nearly_dependent, 1e-12)
                .unwrap()
                .rank,
            1
        );
        assert_eq!(
            compute_reaction_basis(&nearly_dependent, 1e-16)
                .unwrap()
                .rank,
            2
        );
    }
}

#[cfg(test)]
mod nr_tests {
    use super::*;
    use nalgebra::DMatrix;

    #[test]
    fn nr_solver_respects_bounds_and_converges() {
        // Solve simple scalar problem f(x) = x (root at 0). Start at small positive x0.
        let f = |x: &[f64]| Ok(vec![x[0]]) as Result<Vec<f64>, ReactionExtentError>;
        let j = |_: &[f64]| {
            Ok(DMatrix::from_row_slice(1, 1, &[1.0])) as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |x: &[f64]| x[0] >= 0.0;

        let mut solver = NRSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 100,
            alpha_min: 1e-12,
        };

        let sol = solver.solve(vec![0.01]).unwrap();

        // Solution should remain non-negative and be close to zero
        assert!(sol[0] >= 0.0);
        assert!(sol[0].abs() < 1e-8);
    }
}

#[cfg(test)]
mod trust_region_tests {
    use super::*;
    use approx::assert_relative_eq;
    #[allow(dead_code)]
    fn vec_norm(v: &[f64]) -> f64 {
        v.iter().map(|x| x * x).sum::<f64>().sqrt()
    }

    fn approx_eq(a: &[f64], b: &[f64], tol: f64) -> bool {
        a.iter().zip(b.iter()).all(|(x, y)| (*x - *y).abs() < tol)
    }

    #[test]
    fn trust_region_linear_system() {
        let f = |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> {
            Ok(vec![3.0 * x[0] + 1.0 * x[1] - 1.0, 1.0 * x[0] + 2.0 * x[1]])
        };

        let j = |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
            Ok(DMatrix::from_row_slice(2, 2, &[3.0, 1.0, 1.0, 2.0]))
        };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 10,
            delta_init: 1.0,
            delta_max: 10.0,
            eta: 0.1,
        };

        let x0 = vec![0.0, 0.0];
        let sol = solver.solve(x0).unwrap();

        assert!(approx_eq(&sol, &[0.4, -0.2], 1e-10));
    }

    #[test]
    fn trust_region_scalar_nonlinear() {
        let f =
            |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> { Ok(vec![x[0] * x[0] - 2.0]) };

        let j = |x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
            Ok(DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
        };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 50,
            delta_init: 0.1, // intentionally small
            delta_max: 10.0,
            eta: 0.1,
        };

        let sol = solver.solve(vec![0.1]).unwrap();
        assert!((sol[0] - 2.0_f64.sqrt()).abs() < 1e-10);
    }

    #[test]
    fn trust_region_ill_conditioned() {
        let f = |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> {
            Ok(vec![1e6 * x[0] - 1.0, x[1] - 1.0])
        };

        let j = |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
            Ok(DMatrix::from_row_slice(2, 2, &[1e6, 0.0, 0.0, 1.0]))
        };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 50,
            delta_init: 0.01,
            delta_max: 1.0,
            eta: 0.1,
        };

        let sol = solver.solve(vec![0.0, 0.0]).unwrap();

        assert!((sol[0] - 1e-6).abs() < 1e-10);
        assert!((sol[1] - 1.0).abs() < 1e-10);
    }

    #[test]
    fn trust_region_feasibility_constraint() {
        let f = |x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> { Ok(vec![x[0] - 1.0]) };

        let j = |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> {
            Ok(DMatrix::from_row_slice(1, 1, &[1.0]))
        };

        let feasible = |x: &[f64]| x[0] >= 0.0;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 50,
            delta_init: 10.0,
            delta_max: 10.0,
            eta: 0.1,
        };

        let sol = solver.solve(vec![-10.0]).unwrap();
        assert!((sol[0] - 1.0).abs() < 1e-10);
    }

    #[test]
    fn trust_region_singular_jacobian() {
        let f = |_x: &[f64]| -> Result<Vec<f64>, ReactionExtentError> { Ok(vec![1.0]) };

        let j =
            |_x: &[f64]| -> Result<DMatrix<f64>, ReactionExtentError> { Ok(DMatrix::zeros(1, 1)) };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 5,
            delta_init: 1.0,
            delta_max: 1.0,
            eta: 0.1,
        };

        let res = solver.solve(vec![0.0]);
        assert!(matches!(res, Err(SolveError::SingularMatrix)));
    }
    ///////////////////////
    #[test]
    fn tr_solves_scalar_quadratic() {
        let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 2.0]) as Result<Vec<f64>, ReactionExtentError>;

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
                as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 50,
            delta_init: 0.1,
            delta_max: 10.0,
            eta: 0.0,
        };

        let x0 = vec![0.1];
        let sol = solver.solve(x0).unwrap();

        assert_relative_eq!(sol[0], 2.0_f64.sqrt(), epsilon = 1e-8);
    }

    #[test]
    fn tr_solves_2d_nonlinear_system() {
        let f = |x: &[f64]| {
            Ok(vec![x[0] * x[0] + x[1] * x[1] - 1.0, x[0] - x[1]])
                as Result<Vec<f64>, ReactionExtentError>
        };

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(
                2,
                2,
                &[2.0 * x[0], 2.0 * x[1], 1.0, -1.0],
            )) as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 1000,
            delta_init: 0.1,
            delta_max: 10.0,
            eta: 0.0,
        };

        let x0 = vec![0.5, 0.5];
        let sol = solver.solve(x0).unwrap();

        let expected = 1.0 / 2.0_f64.sqrt();
        assert_relative_eq!(sol[0], expected, epsilon = 1e-8);
        assert_relative_eq!(sol[1], expected, epsilon = 1e-8);
    }

    #[test]
    fn tr_respects_feasibility_constraint() {
        let f = |x: &[f64]| Ok(vec![x[0] * x[0] - 1.0]) as Result<Vec<f64>, ReactionExtentError>;

        let j = |x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(1, 1, &[2.0 * x[0]]))
                as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 50,
            delta_init: 1.0,
            delta_max: 10.0,
            eta: 0.1,
        };

        let x0 = vec![0.1];
        let sol = solver.solve(x0).unwrap();

        // The unconstrained problem has two equally valid roots. The
        // feasibility predicate above accepts both, so the contract is root
        // convergence rather than a particular sign selected by the solver.
        assert_relative_eq!(sol[0].abs(), 1.0, epsilon = 1e-8);
    }

    #[test]
    fn tr_reports_max_iterations() {
        let f = |_x: &[f64]| Ok(vec![1.0]); // no root
        let j = |_x: &[f64]| Ok(nalgebra::DMatrix::identity(1, 1));
        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 5,
            delta_init: 1.0,
            delta_max: 10.0,
            eta: 0.1,
        };

        let res = solver.solve(vec![0.0]);
        assert!(matches!(res, Err(SolveError::MaxIterations)));
    }

    #[test]
    fn tr_reports_jacobian_dimension_mismatch() {
        let f = |_x: &[f64]| Ok(vec![1.0]) as Result<Vec<f64>, ReactionExtentError>;

        let j = |_x: &[f64]| {
            Ok(nalgebra::DMatrix::from_row_slice(1, 2, &[1.0, 0.0]))
                as Result<DMatrix<f64>, ReactionExtentError>
        };

        let feasible = |_x: &[f64]| true;

        let solver = TrustRegionSolver {
            f,
            jacobian: j,
            feasible,
            tol: 1e-12,
            max_iter: 5,
            delta_init: 1.0,
            delta_max: 10.0,
            eta: 0.1,
        };

        let res = solver.solve(vec![0.0]);
        assert!(matches!(res, Err(SolveError::EvalError(_))));
    }
}