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
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 OUTRAM PARK contributors
//
// This file is part of OUTRAM PARK.
//
// OUTRAM PARK is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// OUTRAM PARK is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with OUTRAM PARK. If not, see <https://www.gnu.org/licenses/>.
//! **Numerical differentiation of a supplied function** — finite differences,
//! batched derivatives, and batched Jacobians, dispatched across
//! [`ComputeBackend`].
//!
//! # This is NOT the FV gradient operator
//!
//! [`crate::fv_operators`] implements the *spatial* finite-volume `grad`, `div`
//! and `laplacian` over a mesh: they differentiate a **field** with respect to
//! **position**, using face fluxes and cell volumes, and they are the right tool
//! for a PDE discretisation. This module differentiates an arbitrary
//! **caller-supplied function** with respect to its own arguments, by sampling
//! it. If you are discretising a transport equation you want `fv_operators`; if
//! you need `df/dx` of a closure, a property correlation or an ODE right-hand
//! side, you are in the right place.
//!
//! # The problem this exists to solve
//!
//! [`crate::ode::OdeSystem::jacobian`] has a default body that is
//! `unimplemented!()`. Any system that does not hand-code its Jacobian
//! **panics** the moment [`crate::ode::Rosenbrock23`] — the crate's only stiff
//! solver — asks for one, and inside
//! [`crate::ode::parallel::integrate_ensemble`] that panic propagates out
//! through the `rayon` scope. [`NumericalJacobian`] closes that hole: wrap a
//! system, and `Rosenbrock23` integrates it with no hand-coded Jacobian at all.
//! Measured cost of doing so, on Van der Pol (`mu = 5`, `x` in `[0, 10]`,
//! tolerances `1e-8`) — see "Measured cost against a hand-coded Jacobian" below
//! — is **1.9x** wall clock for a forward difference and 2.0x for a central
//! one, for the same answer to all eight printed decimals.
//!
//! # Provenance — a generalisation of two settled workspace conventions
//!
//! Nothing here is a new algorithm. Both halves of the formulation are taken
//! from implementations already working in this workspace, and the divergences
//! are stated rather than left to be discovered.
//!
//! **The Jacobian assembly** generalises:
//!
//! ```text
//! crates/outram-park-fork-dwsim-libs/src/columns/linalg.rs:183
//! pub fn finite_difference_jacobian<F>(f: &mut F, x: &[f64], epsilon: f64)
//! -> Option<Array2<f64>>
//! ```
//!
//! itself a port of DWSIM's `NewtonRaphson.vb:669-705` (`FunctionGradient`),
//! used there for the Naphtali-Sandholm column solver's initial Broyden
//! Jacobian. Kept from it: the **central** stencil, the **relative**
//! perturbation, and the **failure-is-`Option`** convention — a caller never
//! receives a matrix it cannot tell apart from a good one. `dwsim-libs` cannot
//! be depended on from here (this crate has no internal workspace dependencies,
//! by policy), so this is a reuse of *formulation*, not of code.
//!
//! Three deliberate divergences from it, each because the alternative is a known
//! defect:
//!
//! | This module | `finite_difference_jacobian` | Why |
//! |---|---|---|
//! | `h = rel * max(\|x\|, min_scale)` | `x*(1±eps)`, or `eps` and `2*eps` when `x == 0` | The `x == 0` branch silently switches to a *one-sided* stencil at a *different* step, so the scheme changes with the data. The `max` floor keeps one scheme everywhere. |
//! | A failed entry is `NaN` and the status says so | a non-finite entry is written as `0.0` | A zero is a *plausible* Jacobian entry. It cannot be detected downstream, and a Newton or Rosenbrock step built on it returns a wrong answer instead of an error. |
//! | Divides by the realised step `xp - xm` | divides by the requested `2*eps*x` | `x + h` is not representable, so the requested step is not the step taken. See [`derivative`]. |
//!
//! **The step-size rule** is the one already in:
//!
//! ```text
//! crates/outram-park-fork-offbeat/src/rheology/aster/integration.rs:298
//! pub fn newton_perturbed(...) // h = perturbation * x.abs().max(1.0)
//! pub fn perturbed_default() -> f64 // f64::EPSILON.cbrt()
//! ```
//!
//! which is upstream Code_Aster's `NEWTON_PERT`. This module adopts both the
//! `max(|x|, 1)` floor and `eps^(1/3)` for the central scheme verbatim — see
//! [`CBRT_EPSILON`] and [`DiffSettings::step_for`] — and extends the same
//! reasoning to the other three orders.
//!
//! A third, narrower precedent —
//! `tampines-steam-tables`' `w_ps_eqm_region4_finite_diff_vol`
//! (`region_4_vap_liq_equilibrium/speed_of_sound_eqm.rs:83`) — takes
//! `dv/dp|_s` by central differences with a hard-coded `dp = 1e-4 * p`, clamped
//! at the minimum table pressure. That is a *relative* step of `1e-4`, sixteen
//! times coarser than [`CBRT_EPSILON`], which is the right call there because
//! the IF97 flash it differentiates is far noisier than machine epsilon. It is
//! recorded here as the standing reminder that **the optimal step assumes the
//! function is evaluated to rounding accuracy**, and a caller whose function is
//! noisier should raise [`DiffSettings::relative_step`] accordingly.
//!
//! # Achievable accuracy is `sqrt(eps)` to `eps^(4/5)`, NEVER `eps`
//!
//! This is the single most common misunderstanding about finite differences, so
//! it is measured rather than asserted. Truncation error falls as `h^p` while
//! round-off grows as `eps/h`; their sum is minimised at `h ~ eps^(1/(p+1))`,
//! where the achievable accuracy is `~ eps^(p/(p+1))`:
//!
//! | Scheme | Order `p` | Optimal `h` | Predicted accuracy |
//! |---|---|---|---|
//! | [`DiffScheme::Forward`] / [`DiffScheme::Backward`] | 1 | `sqrt(eps) = 1.49e-8` | `sqrt(eps) = 1.49e-8` |
//! | [`DiffScheme::Central`] | 2 | `eps^(1/3) = 6.06e-6` | `eps^(2/3) = 3.67e-11` |
//! | [`DiffScheme::Central4th`] | 4 | `eps^(1/5) = 7.40e-4` | `eps^(4/5) = 3.00e-13` |
//!
//! **A caller expecting `1e-15` from a finite difference will be wrong by seven
//! orders of magnitude for a forward difference.** If you need machine
//! precision, hand-code the derivative.
//!
//! *Measured.* `accuracy_floor_at_the_default_step` in `differentiate/tests.rs`,
//! release, 2026-08-13. Worst relative error over six points in `[0.25, 3.3]`,
//! each scheme at its own default step:
//!
//! | Function | forward | backward | central | central-4th |
//! |---|---|---|---|---|
//! | `sin` | 1.281191e-8 | 1.401018e-8 | 6.528067e-11 | 1.785239e-13 |
//! | `exp` | 2.413003e-8 | 2.383524e-8 | 6.640831e-11 | 1.800352e-13 |
//! | `x^3 - 2x` | 4.470348e-8 | 4.470348e-8 | 4.583556e-11 | 9.992007e-14 |
//! | `1/(1 + x^2)` | 8.046627e-9 | 8.430242e-9 | 2.949979e-11 | 9.620083e-14 |
//! | `tanh` | 6.775837e-9 | 8.125324e-9 | 1.244682e-11 | 1.963985e-13 |
//! | **worst** | **4.470348e-8** | **4.470348e-8** | **6.640831e-11** | **1.963985e-13** |
//! | *predicted* | *1.490116e-8* | *1.490116e-8* | *3.666853e-11* | *3.000214e-13* |
//!
//! Every scheme lands within a factor of three of its prediction, and the
//! **ordering is exactly as predicted: central-4th beats central by 338x, and
//! central beats forward by 673x.** The theory is a usable bound, not a story.
//!
//! *Observed convergence order.* `observed_convergence_order_matches_theory`,
//! same run. Absolute error of `d/dx sin(x)` at `x = 1` (exact
//! `5.40302305868139765e-1`) against the relative step:
//!
//! | Relative step | forward | backward | central | central-4th |
//! |---|---|---|---|---|
//! | `1e-1` | 4.293855e-2 | 4.113845e-2 | 9.000537e-4 | 1.125295e-7 |
//! | `1e-2` | 4.216325e-3 | 4.198315e-3 | 9.004993e-6 | 1.126843e-11 |
//! | `1e-3` | 4.208255e-4 | 4.206454e-4 | 9.005042e-8 | 1.049161e-13 |
//! | `1e-4` | 4.207445e-5 | 4.207265e-5 | 9.003700e-10 | 3.312906e-13 |
//! | **observed order** | **1.0079** | **0.9912** | **1.9998** | **3.9994** |
//!
//! The fourth-order column turning back upward at `1e-4` (1.05e-13 to 3.31e-13)
//! is the round-off wall arriving, exactly where `eps^(1/5) = 7.4e-4` says it
//! should.
//!
//! *The round-off wall.* `a_step_far_below_the_optimum_is_worse_not_better`,
//! same run. Central difference, `d/dx sin(x)` at `x = 1`, relative error:
//!
//! | Relative step | Relative error |
//! |---|---|
//! | `1.0000e-2` | 1.666658e-5 |
//! | `6.0555e-6` ([`CBRT_EPSILON`]) | **5.373555e-12** |
//! | `1.0000e-8` | 5.303737e-9 |
//! | `1.0000e-10` | 1.909780e-7 |
//! | `1.0000e-12` | 5.609880e-5 |
//! | `1.0000e-14` | 7.666335e-3 |
//!
//! **A step six million times smaller than the optimum is ten million times
//! worse:** `1e-12` against `6.06e-6` moves the error from 5.373555e-12 to
//! 5.609880e-5, a factor of 1.04e7. "Make `h` tiny for accuracy" is the intuition this table exists to
//! destroy.
//!
//! # Forward against central: the cost/accuracy trade, measured
//!
//! For an `n`-dimensional Jacobian the evaluation counts are `n + 1`, `2n` and
//! `4n` (see [`DiffScheme::evaluations_per_jacobian`]). The measured accuracy
//! ratio from the table above is **673x** for one extra evaluation per column
//! going forward to central, and a further **338x** for two more going to
//! `Central4th`. Central is very nearly always the right default, which is why
//! it is what [`DiffSettings::central`] exists for and what
//! [`NumericalJacobian`]'s documentation recommends; [`DiffScheme::Forward`] is
//! for the case where the function is genuinely expensive and `1e-8` is enough.
//!
//! # Verification against analytic Jacobians
//!
//! *Methodology.* Three systems whose Jacobians can be written down exactly are
//! differenced and compared entry by entry: a **quadratic** system
//! `[x0^2 + x1, x0*x1^2]`, a **trigonometric** system
//! `[sin(x0)cos(x1), exp(x0)*x1]` in which no derivative of any order vanishes,
//! and a **stiff linear pair** `[-1000*y0 + y1, y0 - y1]` with a 1000:1 entry
//! spread. Pass criterion: worst relative error below `1e-7` for the first-order
//! schemes and `1e-10`/`1e-11` for the higher-order ones. All four schemes pass
//! on all three systems (release, 2026-08-13).
//!
//! *The stiff pair is the informative one*, because a **linear** system has
//! exactly zero truncation error — so every digit lost is cancellation, and the
//! measurement isolates it. Absolute error per entry at `y = [0.4, -0.9]`:
//!
//! | Scheme | `J[0][0]` (-1000) | `J[0][1]` (1) | `J[1][0]` (1) | `J[1][1]` (-1) |
//! |---|---|---|---|---|
//! | forward | 0 | 0 | 0 | 0 |
//! | backward | 0 | 0 | 0 | 0 |
//! | central | 6.600658e-10 | **1.778424e-9** | 9.167112e-12 | 1.833422e-11 |
//! | central-4th | 5.456968e-12 | 6.380474e-11 | 2.498002e-14 | 0 |
//!
//! **`J[0][1]` is the worst entry by two orders of magnitude, and it is the
//! small entry in the row that also holds `-1000`.** Row 0 evaluates to about
//! `-400.9`; perturbing `x1` changes it by `1.2e-5`, so forming that difference
//! discards eleven significant digits before the division. This is a **general
//! property of finite-difference Jacobians, not of this implementation**: an
//! entry is only as accurate as its own magnitude relative to the largest term
//! in its row. A badly-scaled system loses precision in exactly the entries a
//! stiff solver most needs. If that matters, hand-code the Jacobian or rescale
//! the equations.
//!
//! The one-sided schemes returning **exactly zero** error here is a property of
//! this particular linear case (`f(x+h) - f(x)` is exact when `f` is affine and
//! the operands round identically) and must not be read as one-sided differences
//! being more accurate in general — the accuracy table above shows them 673x
//! *worse* on smooth non-linear functions.
//!
//! # Measured cost against a hand-coded Jacobian
//!
//! *Methodology.* Van der Pol `mu = 5`, `y(0) = [2, 0]`, integrated over
//! `x` in `[0, 10]` by [`crate::ode::Rosenbrock23`] with `abs_tol = rel_tol =
//! 1e-8`; best of 5, release, default features, the loaded 4-core machine
//! described on [`DERIVATIVE_BATCH_MIN_POINTS`]. Van der Pol *has* an analytic
//! Jacobian, which is the baseline. Produced by the `#[ignore]`d
//! `numerical_jacobian_overhead_benchmark`, two runs.
//!
//! | Jacobian | Time (A) | Time (B) | vs analytic (A) | (B) | `y0(10)` |
//! |---|---|---|---|---|---|
//! | analytic (hand-coded) | 849.99 us | 855.47 us | 1.00x | 1.00x | -1.15870127 |
//! | [`DiffScheme::Forward`] | 1619.03 us | 1603.88 us | 1.90x | 1.87x | -1.15870127 |
//! | [`DiffScheme::Backward`] | 1607.45 us | 1614.33 us | 1.89x | 1.89x | -1.15870127 |
//! | [`DiffScheme::Central`] | 1673.66 us | 1677.88 us | 1.97x | 1.96x | -1.15870127 |
//! | [`DiffScheme::Central4th`] | 2487.96 us | 2455.24 us | 2.93x | 2.87x | -1.15870127 |
//!
//! **All four schemes reproduce the analytic result to all eight printed
//! decimals**, at roughly twice the cost. That is the honest headline: a
//! numerical Jacobian is not free, it is not exact, and for a `n = 2` stiff
//! system it costs about a factor of two and changes nothing you can see.
//!
//! # A NaN Jacobian is NOT reported by the solver — check the counter
//!
//! When a Jacobian cannot be differenced, this module writes `NaN` into the
//! entries and says so through [`DiffStatus`]. The natural expectation is that
//! `Rosenbrock23` then fails loudly. **It does not, and this was measured
//! rather than assumed** (`a_jacobian_that_cannot_be_differenced_is_counted_and_reaches_the_solver_as_nan`):
//!
//! - [`crate::ode::Rosenbrock23::integrate`] returns **`Ok(())`**;
//! - the state vector comes back **`NaN`**.
//!
//! The cause is in the ODE layer, not here: `ode::normalize_error` folds the
//! per-equation errors with `f64::max`, and `f64::max(0.0, NaN)` is `0.0` — so a
//! `NaN` error estimate looks like a *perfectly converged* step and every
//! sub-step is accepted. Nothing in this module can change that.
//!
//! **Consequence for callers:** [`NumericalJacobian::non_finite_jacobians`] is
//! the only in-band signal that anything went wrong. Check it after any
//! integration whose result you intend to trust. It is not decoration.
//!
//! # Hybrid means dispatch, not two APIs
//!
//! Every entry point takes a [`ComputeBackend`] parameter; there is no
//! `_parallel()` sibling. With the `parallel` feature off,
//! [`ComputeBackend::CpuMulti`] resolves down to [`ComputeBackend::Serial`] and
//! the answer is unchanged — bit for bit, not merely close. There is no `Gpu`
//! kernel here yet, so a `Gpu` request degrades to the best available CPU path.
//!
//! **Two independent parallel axes** live here, with separately measured
//! crossovers 2048x apart:
//!
//! | Entry point | Parallel over | Crossover |
//! |---|---|---|
//! | [`derivative_batch`] | independent points | [`DERIVATIVE_BATCH_MIN_POINTS`] = 65 536 |
//! | [`jacobian_batch`] | independent lanes | [`JACOBIAN_BATCH_MIN_PROBLEMS`] = 256 |
//! | [`jacobian`] | the columns of **one** Jacobian | [`JACOBIAN_COLUMN_MIN_DIMENSION`] = 32 |
//!
//! They are not nested: [`jacobian_batch`] runs each lane's columns serially,
//! because the lane axis is already saturating the pool.
//!
//! # Determinism — bitwise identical across backends and thread counts
//!
//! **This module returns bit-for-bit identical output on
//! [`ComputeBackend::Serial`] and [`ComputeBackend::CpuMulti`], at any thread
//! count, on every run**, provided the caller's function is a deterministic pure
//! function of its arguments.
//!
//! The argument is the same one [`crate::math::minimise`] makes: lane `i`'s (or
//! column `j`'s) answer is a pure function of its own samples, and **no
//! arithmetic crosses lanes or columns**. A parallel *sum* would have to
//! re-associate, and floating-point addition is not associative; a set of
//! independent difference quotients has nothing to re-associate. Both backends
//! call the same `#[inline]` per-lane and per-column kernels, and only the
//! identity of the calling thread differs.
//!
//! Verified by the `bitwise_*` tests in `differentiate/tests.rs` on 2 048
//! derivative lanes, 512 four-dimensional Jacobian lanes and one 96-dimensional
//! Jacobian, all built with points spread over seven decades so the per-lane
//! step differs. **Measured 2026-08-13 (release, `--features parallel`, 4
//! logical cores): bit-identical on every observable field of every lane, for
//! all four [`DiffScheme`] variants, at 1, 2, 4 and 8 workers.** The
//! single-point [`derivative`] and single-lane [`jacobian`] forms are separately
//! asserted bit-identical to their one-element batches.
//!
//! The `#[ignore]`d `differentiate_thread_scaling_benchmark` re-asserts the same
//! identity while timing it, on 65 536 lanes with
//! [`DiffScheme::Central4th`] (4 evaluations per lane), best of 7, two runs:
//!
//! | Worker threads | Time (A) | Speed-up (A) | (B) | Bitwise vs serial |
//! |---|---|---|---|---|
//! | *serial reference* | 5902.59 us | 1.00x | 1.00x | — |
//! | 1 | 6008.47 us | 0.98x | 0.98x | identical |
//! | 2 | 3181.82 us | 1.86x | 1.85x | identical |
//! | 4 | 1582.50 us | 3.73x | 3.70x | identical |
//! | 8 | 1577.90 us | 3.74x | 3.83x | identical |
//!
//! The "identical" column is asserted by the benchmark, not merely printed.
//! Scaling is close to linear to 4 workers and flat beyond, which is what four
//! logical cores should do. **The machine was not idle** (see
//! [`DERIVATIVE_BATCH_MIN_POINTS`] for the load); one machine, one batch, two
//! runs, nothing measured on Android hardware or a many-core server.
//!
//! The one way a caller can break this is to supply a function that is not pure
//! — one that reads a random number generator, accumulates into shared
//! interior-mutable state, or depends on the calling thread. The `Sync` bound
//! permits it; this contract forbids it.
//!
//! # Failure is reported, never swallowed
//!
//! - Every lane and every Jacobian carries a [`DiffStatus`].
//! - [`DerivativeSolution::derivative`] and [`JacobianSolution::matrix`] return
//! `Option`, `Some` **only** on success. The diagnostic values are behind the
//! deliberately-named [`DerivativeSolution::raw_value`] and
//! [`JacobianSolution::raw_matrix`].
//! - [`DerivativeBatch::values`] and [`JacobianBatch::matrices`] are
//! all-or-nothing: they return [`DiffBatchFailure`] naming the failure count
//! and the first failing lane, rather than a `Vec` with a `NaN` in it.
//! - A failed Jacobian column is `NaN`, never `0.0`, and
//! [`JacobianSolution::first_bad_column`] names the offending **variable**.
//!
//! **But read the limits of that guarantee** — the "What is detected, and what
//! cannot be" section on [`derivative`] lists three classes of bad input that no
//! finite-difference kernel can detect, chief among them a singularity that a
//! symmetric stencil steps over.
//!
//! # What is deliberately NOT here: dual-number autodiff
//!
//! Bead `op-yvj.4.6` offers forward-mode dual numbers as an optional exact
//! alternative, *"only if it stays simple"*. It is not implemented, on purpose.
//! Making it useful means every function a caller wants differentiated must be
//! generic over the scalar type, which would push a type parameter through
//! `OdeSystem`, through the thermophysics kernels, and into every caller's own
//! code. That is precisely the rise in reader context load the crate-level
//! "Human interface layer" rule forbids, and the bead itself ranks that rule
//! above the convenience. A caller who wants exact derivatives should hand-code
//! them; that is what [`crate::ode::OdeSystem::jacobian`] is for.
//!
//! # Units
//!
//! Everything here is dimensionless `f64`, and that is a deliberate decision
//! rather than `uom` being stripped.
//!
//! **A derivative changes dimension.** `d(enthalpy)/d(temperature)` is a heat
//! capacity; `d(pressure)/d(volume)` is none of the three. A generic
//! differentiator therefore has no single `uom` type it could return — the
//! output type is a *function* of two input types, which Rust can only express
//! through a trait with an associated output type, i.e. exactly the generic
//! machinery the "Human interface layer" rule forbids adding for its own sake.
//! The bead anticipates this and directs that, where the generic form cannot be
//! typed cleanly, a small number of **concrete typed wrappers** is preferred
//! over one generic nobody can read.
//!
//! So: `uom` typing is applied **at the boundary, by the caller** — convert in,
//! convert out — exactly as [`crate::math::minimise`] and
//! [`crate::math::parallel`] do. The one place a dimension does appear in this
//! module's own API is [`DiffSettings::min_scale`], which carries the units of
//! the variable being perturbed; its documentation says so, because a caller
//! differentiating with respect to a pressure in pascals near zero must not
//! leave it at `1.0`.
//!
//! # Cargo features and portability
//!
//! The `rayon` paths sit behind the crate's `parallel` feature, which is **off
//! by default**; with it off this module still compiles and every entry point
//! still works. `rayon` is pure Rust with no system component, so everything
//! here compiles and runs on `aarch64-linux-android` / Termux exactly as on
//! desktop. Nothing in this module is target-gated.
//!
//! # Example
//!
//! ```rust
//! use outram_foam_basic_lib::math::differentiate::{DiffSettings, NumericalJacobian};
//! use outram_foam_basic_lib::ode::{OdeSystem, Rosenbrock23};
//!
//! // A stiff system with NO hand-coded Jacobian. Without the wrapper the
//! // default `OdeSystem::jacobian` would panic inside Rosenbrock23.
//! struct StiffPair;
//! impl OdeSystem for StiffPair {
//! fn n_eqns(&self) -> usize { 2 }
//! fn derivatives(&self, _x: f64, y: &[f64], dydx: &mut Vec<f64>) {
//! dydx.clear();
//! dydx.push(-1000.0 * y[0] + y[1]);
//! dydx.push(y[0] - y[1]);
//! }
//! }
//!
//! let system = NumericalJacobian::new(StiffPair, DiffSettings::central());
//! let mut solver = Rosenbrock23::new(2, 1e-10, 1e-10);
//! let mut y = vec![1.0_f64, 1.0];
//! let mut dx = 1e-6;
//! solver.integrate(&system, 0.0, 1.0, &mut y, &mut dx).expect("integrates");
//!
//! // The fast mode has decayed; the slow mode (eigenvalue about -0.999) remains.
//! assert!(y[1].abs() < 1.0 && y[1] > 0.0, "y1 = {}", y[1]);
//! // ALWAYS check this -- the solver does not report a NaN Jacobian itself.
//! assert_eq!(system.non_finite_jacobians(), 0);
//! ```
use *;
use ;
use crateComputeBackend;
use crateSquareMatrix;
use crateOdeSystem;
// ── Constants ────────────────────────────────────────────────────────────────
/// `f64::EPSILON.cbrt()` = `6.0554544523933395e-6` — the relative step that
/// balances truncation against round-off for a **central** difference.
///
/// A central difference has truncation error proportional to `h^2` (the
/// coefficient is the third derivative over six) and round-off error
/// proportional to `eps/h`; minimising their sum over `h` gives
/// `h ~ eps^(1/3)`. The resulting accuracy is `~ eps^(2/3) = 3.67e-11`, **not**
/// `eps` — see the module-level "Achievable accuracy" table for the measured
/// value.
///
/// This is the same constant `outram-park-fork-offbeat`'s
/// `rheology::aster::integration::perturbed_default()` returns, for exactly the
/// same reason; see the module-level "Provenance" section.
///
/// # Units
///
/// Dimensionless — it multiplies a length scale in `x`.
pub const CBRT_EPSILON: f64 = 6.055_454_452_393_339_5e-6;
/// `f64::EPSILON.powf(0.2)` = `7.40095979741405e-4` — the relative step that
/// balances truncation against round-off for the **fourth-order** Richardson
/// scheme [`DiffScheme::Central4th`].
///
/// Truncation error proportional to `h^4`, round-off proportional to `eps/h`,
/// so the balance is at `h ~ eps^(1/5)` and the accuracy is
/// `~ eps^(4/5) = 3.00e-13`.
///
/// # Units
///
/// Dimensionless.
pub const FIFTH_ROOT_EPSILON: f64 = 7.400_959_797_414_05e-4;
/// Point count below which a [`ComputeBackend::CpuMulti`] request runs
/// [`derivative_batch`] on the calling thread instead.
///
/// # Measured crossover
///
/// *Methodology.* Measured 2026-08-13 on this workspace's development machine,
/// `std::thread::available_parallelism()` = **4**, release build,
/// `--features parallel`, `rayon`'s global pool. **The machine was NOT idle:**
/// 1-minute load average was 2.3-3.6 on 4 cores throughout, with a
/// `bn daemon run` process holding a steady ~37% of one core. Batches of `n`
/// points spread over seven decades of magnitude, [`DiffSettings::central`],
/// best of 7 samples per point, wall clock for one whole batch. Produced by the
/// `#[ignore]`d `differentiate_crossover_benchmark` test and transcribed from
/// its printed output. `cheap` is a two-flop parabola; `costly` adds an
/// `ln`/`exp`/`sqrt`/`tanh` chain, standing in for a property evaluation. Two
/// independent runs are carried side by side rather than averaged, because the
/// parallel column is far noisier than the serial one.
///
/// | Points | cheap serial | cheap speed-up (A) | (B) | costly serial | costly speed-up (A) | (B) |
/// |---|---|---|---|---|---|---|
/// | 16 | 0.18 us | 0.03x | 0.01x | 1.15 us | 0.14x | 0.04x |
/// | 32 | 0.29 us | 0.03x | 0.01x | 2.11 us | 0.20x | 0.07x |
/// | 64 | 0.51 us | 0.06x | 0.02x | 4.09 us | 0.39x | 0.13x |
/// | 128 | 0.97 us | 0.10x | 0.04x | 8.07 us | 0.47x | 0.23x |
/// | 256 | 1.87 us | 0.17x | 0.06x | 16.05 us | 0.71x | 0.40x |
/// | 512 | 3.70 us | 0.27x | 0.11x | 31.85 us | 0.74x | 0.67x |
/// | 1 024 | 7.33 us | 0.38x | 0.19x | 63.41 us | 0.85x | 1.12x |
/// | 4 096 | 28.86 us | 0.56x | 0.52x | 253.71 us | 1.52x | 2.35x |
/// | 16 384 | 115.53 us | 0.99x | 1.34x | 1025.92 us | 1.82x | 2.50x |
/// | 65 536 | 484.26 us | **1.34x** | **1.35x** | 4224.20 us | 1.90x | 2.74x |
///
/// *Result.* **65 536** is the smallest size at which the cheap objective won in
/// *both* runs, and it is the value this constant takes. That is 16x above the
/// crate-wide [`crate::compute::CPU_MULTI_MIN_WORK_ITEMS`] placeholder and 256x
/// above [`crate::math::minimise::MINIMISE_BATCH_MIN_PROBLEMS`], and the reason
/// is structural rather than accidental: a scalar finite difference is **two to
/// four evaluations of the caller's function and one division**, so with a cheap
/// function the kernel is memory-bandwidth bound in exactly the way
/// [`crate::fields::parallel`] is — and it lands within a factor of two of that
/// module's independently measured 131 072. A batched root find, by contrast,
/// runs *tens* of iterations per lane and crosses over at 256.
///
/// **The caller's function cost moves this by more than an order of magnitude.**
/// The costly objective first wins at 1 024-4 096, sixteen to sixty-four times
/// lower. A caller who knows its function is expensive should name
/// [`ComputeBackend::CpuMulti`] explicitly rather than trust this number.
///
/// # Limitations
///
/// One machine, four logical cores, under load, one objective family. Not
/// measured on Android/Termux hardware and not on a many-core server. The
/// absolute timings should be read as ratios only.
///
/// # Units
///
/// A count of independent points, dimensionless.
pub const DERIVATIVE_BATCH_MIN_POINTS: usize = 65_536;
/// Lane count below which a [`ComputeBackend::CpuMulti`] request runs
/// [`jacobian_batch`] on the calling thread instead.
///
/// # Measured crossover
///
/// *Methodology.* Same machine, date, build and load as
/// [`DERIVATIVE_BATCH_MIN_POINTS`] — 4 logical cores, load average 2.3-3.6,
/// **not idle**. `n = 4` Jacobians, [`DiffSettings::central`] so each lane costs
/// 8 evaluations of a 4-component function, best of 7, two independent runs.
/// Produced by the same `#[ignore]`d `differentiate_crossover_benchmark` test.
///
/// | Lanes | cheap serial | cheap speed-up (A) | (B) | costly speed-up (A) | (B) |
/// |---|---|---|---|---|---|
/// | 4 | 1.56 us | 0.19x | 0.16x | 0.21x | 0.21x |
/// | 8 | 3.05 us | 0.10x | 0.12x | 0.63x | 0.35x |
/// | 16 | 6.05 us | 0.19x | 0.21x | 0.60x | 0.65x |
/// | 32 | 12.06 us | 0.83x | 0.33x | 1.52x | 1.03x |
/// | 64 | 23.64 us | 0.57x | 0.70x | 1.18x | 2.18x |
/// | 128 | 48.36 us | 0.84x | 1.34x | 1.86x | 2.46x |
/// | 256 | 95.16 us | **1.09x** | **1.11x** | 1.88x | 2.61x |
/// | 1 024 | 373.05 us | 1.63x | 2.18x | 1.86x | 1.50x |
/// | 4 096 | 1590.74 us | 1.75x | 1.90x | 1.85x | 3.10x |
/// | 16 384 | 6702.36 us | 1.83x | 2.98x | 2.06x | 2.88x |
///
/// *Result.* **256** — the smallest lane count that won in both runs. It lands
/// on exactly the same value as
/// [`crate::math::minimise::MINIMISE_BATCH_MIN_PROBLEMS`] and
/// [`crate::math::parallel::ROOT_BATCH_MIN_PROBLEMS`], and 256x *below* this
/// module's own [`DERIVATIVE_BATCH_MIN_POINTS`]. The two numbers in one module
/// disagreeing by 256x is the clearest evidence yet for the point
/// [`crate::compute::CPU_MULTI_MIN_WORK_ITEMS`] makes: the crossover tracks
/// **work per lane**, not the algorithm. A Jacobian lane here does 8 function
/// evaluations, four vector allocations and a matrix assembly; a scalar
/// derivative lane does 2 evaluations and a division.
///
/// # A performance trap found by this measurement, recorded so it is not reintroduced
///
/// The first version of the central-difference column copied the point **twice**
/// per column (`x.to_vec()` for the `+h` probe and again for the `-h` probe).
/// With that version the parallel path **never won at any size measured**,
/// topping out at 0.96x on 16 384 lanes — allocation traffic, not arithmetic,
/// was the whole cost. Reusing a single probe buffer made the serial path ~1.4x
/// faster *and* restored parallel scaling to 1.8-3.0x. If a future change
/// reintroduces a per-column allocation, this crossover is the measurement that
/// will notice.
///
/// # Limitations
///
/// As for [`DERIVATIVE_BATCH_MIN_POINTS`], plus: measured at `n = 4` only. A
/// larger `n` raises the per-lane cost and should lower this crossover, but that
/// has not been measured.
///
/// # Units
///
/// A count of independent Jacobian problems, dimensionless.
pub const JACOBIAN_BATCH_MIN_PROBLEMS: usize = 256;
/// Dimension below which [`jacobian`] computes one Jacobian's columns on the
/// calling thread rather than spreading them across `rayon`.
///
/// This is the **other** parallel axis, and it is the one bead `op-yvj.4.6`
/// names: an `n`-dimensional Jacobian's `n + 1` (or `2n`, or `4n`) evaluations
/// are all independent.
///
/// # Measured crossover
///
/// *Methodology.* Same machine, date, build and load as
/// [`DERIVATIVE_BATCH_MIN_POINTS`] — 4 logical cores, load average 2.3-2.9,
/// **not idle**. One Jacobian of dimension `n`, [`DiffSettings::central`] so
/// `2n` evaluations, of a residual whose every component sums over all `n`
/// inputs — so one evaluation is `O(n^2)` and the whole Jacobian is `O(n^3)`,
/// the shape a genuinely coupled residual has. Best of 7, two independent runs.
/// Produced by the `#[ignore]`d `jacobian_column_crossover_benchmark` test.
///
/// | Dimension | `f` evals | serial | speed-up (A) | (B) |
/// |---|---|---|---|---|
/// | 4 | 8 | 0.72 us | 0.09x | 0.09x |
/// | 8 | 16 | 3.03 us | 0.35x | 0.16x |
/// | 16 | 32 | 15.93 us | 0.41x | 0.46x |
/// | 32 | 64 | 103.63 us | **1.49x** | **1.53x** |
/// | 64 | 128 | 767.15 us | 2.67x | 2.58x |
/// | 128 | 256 | 6117.53 us | 1.98x | 2.55x |
/// | 256 | 512 | 48189.43 us | 4.04x | 2.84x |
/// | 512 | 1024 | 389479.48 us | 3.97x | 3.55x |
///
/// *Result.* **32** — the lowest dimension that won in both runs, and the
/// smallest crossover anywhere in this crate. That is not surprising once the
/// cost is written down: at `n = 32` a single Jacobian is already 64 evaluations
/// of an `O(n^2)` residual, which is far more work per dispatch than 32 lanes of
/// anything else in the crate.
///
/// **This crossover is even more caller-dependent than the others**, because it
/// scales with the residual's own cost in `n`. A residual that is `O(1)` per
/// component rather than `O(n)` will cross over much later. 32 is set for the
/// coupled case; a caller with a cheap decoupled residual should pass
/// [`ComputeBackend::Serial`] explicitly.
///
/// # Why an ODE Jacobian does not use this
///
/// [`ode_system_jacobian`] and [`NumericalJacobian`] always run their columns
/// serially, whatever the dimension. An ODE system's `n` is its equation count —
/// typically single or double digits, well under this threshold — and the
/// parallel axis that matters for ODE work is the *ensemble lane*, which
/// [`crate::ode::parallel::integrate_ensemble`] already provides. Nesting a
/// `rayon` map inside that one would only contend for the same pool.
///
/// # Limitations
///
/// As for [`DERIVATIVE_BATCH_MIN_POINTS`], plus: one residual shape (`O(n)` per
/// component). The 128 row losing ground to both its neighbours in run A
/// (1.98x against 2.67x and 4.04x) is measurement noise on a loaded machine, not
/// a real effect — do not read this table as a scaling study.
///
/// # Units
///
/// A count of Jacobian columns, i.e. the length of the point. Dimensionless.
pub const JACOBIAN_COLUMN_MIN_DIMENSION: usize = 32;
// ── Backend dispatch ─────────────────────────────────────────────────────────
/// Resolve a requested backend to the one this module will actually run.
///
/// Three reductions, in order: [`ComputeBackend::resolve`] degrades anything
/// whose feature is off; `Gpu` degrades again because this module has no GPU
/// kernel yet; and `CpuMulti` degrades to `Serial` below `min_work_items`. The
/// result is only ever `Serial` or `CpuMulti`, and none of the degradations can
/// change a returned value.
///
/// Identical in shape to `minimise::effective_backend` and
/// `parallel::effective_backend`; kept private and duplicated rather than
/// hoisted because all three are four lines and hoisting would put a
/// dispatch-policy helper in a module whose docs say it holds no kernels.
/// The [`ComputeBackend`] [`derivative_batch`] would actually use for `n`
/// points if asked for `requested` — without running anything.
///
/// Applies exactly the same reduction the kernel does (feature availability, no
/// GPU kernel here, and the [`DERIVATIVE_BATCH_MIN_POINTS`] size floor), so what
/// it reports is what would run.
///
/// # Arguments
///
/// - `requested` — the backend a caller would pass to [`derivative_batch`].
/// - `n` — number of independent points in the batch, dimensionless.
///
/// # Returns
///
/// Either [`ComputeBackend::Serial`] or [`ComputeBackend::CpuMulti`]; never
/// [`ComputeBackend::Gpu`], because no GPU kernel exists here yet.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::math::differentiate::{
/// derivative_backend_for, DERIVATIVE_BATCH_MIN_POINTS,
/// };
///
/// assert_eq!(
/// derivative_backend_for(ComputeBackend::CpuMulti, 8),
/// ComputeBackend::Serial
/// );
/// assert!(derivative_backend_for(ComputeBackend::CpuMulti, DERIVATIVE_BATCH_MIN_POINTS)
/// .is_available());
/// ```
/// The [`ComputeBackend`] [`jacobian_batch`] would actually use for `n`
/// independent Jacobian problems — without running anything.
///
/// # Arguments
///
/// - `requested` — the backend a caller would pass to [`jacobian_batch`].
/// - `n` — number of independent Jacobian problems (lanes), dimensionless.
///
/// # Returns
///
/// Either [`ComputeBackend::Serial`] or [`ComputeBackend::CpuMulti`].
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::math::differentiate::jacobian_batch_backend_for;
///
/// assert_eq!(
/// jacobian_batch_backend_for(ComputeBackend::CpuMulti, 2),
/// ComputeBackend::Serial
/// );
/// ```
/// The [`ComputeBackend`] [`jacobian`] would actually use to spread the columns
/// of **one** `dimension`-dimensional Jacobian — without running anything.
///
/// This is the *other* axis of parallelism in this module: [`jacobian_batch`]
/// spreads independent problems across threads, while [`jacobian`] spreads the
/// `n` independent column evaluations of a single problem.
///
/// # Arguments
///
/// - `requested` — the backend a caller would pass to [`jacobian`].
/// - `dimension` — the length of the point `x`, i.e. the number of Jacobian
/// columns. Dimensionless.
///
/// # Returns
///
/// Either [`ComputeBackend::Serial`] or [`ComputeBackend::CpuMulti`].
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::math::differentiate::jacobian_column_backend_for;
///
/// // A 3-equation ODE Jacobian is never worth threading.
/// assert_eq!(
/// jacobian_column_backend_for(ComputeBackend::CpuMulti, 3),
/// ComputeBackend::Serial
/// );
/// ```
// ── Scheme, settings ─────────────────────────────────────────────────────────
/// Which finite-difference stencil to use.
///
/// The choice is a **cost against accuracy** trade, and both halves are
/// measured — see the module-level "Achievable accuracy" table for the observed
/// error floors and "Cost" for the evaluation counts.
///
/// # Units
///
/// Dimensionless — a mode selector, not a quantity.
/// Step-size policy for every entry point in this module.
///
/// # The step-size rule
///
/// ```text
/// h = relative_step * max(|x|, min_scale)
/// ```
///
/// The step is **relative to the magnitude of the variable being perturbed**,
/// because a step that is right for `x ~ 1` is far too small for a pressure in
/// pascals and far too large for a mole fraction. `min_scale` is the floor that
/// keeps the rule usable at `x = 0` — see [`Self::step_for`].
///
/// # Units
///
/// `relative_step` is dimensionless. `min_scale` carries the **same units as
/// the variable being differentiated with respect to**, because it is a
/// fallback magnitude for `x`, and its default of `1.0` therefore means "one of
/// whatever unit `x` is in". A caller differentiating with respect to a
/// pressure in pascals near zero wants `min_scale` set to a pascal-scale
/// number, not `1.0`.
// ── Status ───────────────────────────────────────────────────────────────────
/// Why a derivative or Jacobian entry is, or is not, trustworthy.
///
/// # Units
///
/// Dimensionless — a status code.
// ── Scalar derivative ────────────────────────────────────────────────────────
/// One lane's scalar derivative, with the diagnostics needed to judge it.
///
/// # Units
///
/// [`Self::raw_value`] carries the units of `f` divided by the units of `x`
/// — a derivative changes dimension, which is exactly why this module does not
/// try to `uom`-type the generic form. See the module-level "Units" section.
/// [`realised_step`](Self::realised_step) carries the units of `x`.
/// One or more lanes of a [`DerivativeBatch`] or [`JacobianBatch`] failed.
///
/// Returned by the all-or-nothing accessors [`DerivativeBatch::values`] and
/// [`JacobianBatch::matrices`]. It names both the scale of the problem (how
/// many of how many) and a specific lane to look at, because "3 of 10 000 lanes
/// failed" is only actionable once you know *which* lane.
///
/// # Units
///
/// All counts and indices are dimensionless.
/// The result of [`derivative_batch`] — one [`DerivativeSolution`] per point,
/// in point order.
/// Differentiate one scalar function at one point.
///
/// The single-lane form of [`derivative_batch`], for callers with one
/// derivative to take. It runs on the calling thread — there is nothing to
/// spread — and calls the *same* per-lane kernel, so it agrees with a
/// one-element batch bit for bit.
///
/// # The realised-step correction
///
/// `x + h` is generally not representable, so the value the machine actually
/// evaluates at differs from `x + h` in the last bits and the true step is not
/// `h`. This kernel therefore evaluates at `xp = x + h` and divides by
/// `xp - x`, which **is** exact, rather than by `h`. The device is from
/// *Numerical Recipes* (Press et al., 3rd ed., section 5.7) and it removes an
/// error source that would otherwise be comparable to the round-off term the
/// step rule is trying to balance. [`DerivativeSolution::realised_step`]
/// reports the corrected denominator.
///
/// # Arguments
///
/// - `x` — the point, in the caller's own units.
/// - `settings` — scheme and step-size policy; see [`DiffSettings`].
/// - `f` — the function. Units of the return value are the caller's.
///
/// # Returns
///
/// A [`DerivativeSolution`] whose [`derivative`](DerivativeSolution::derivative)
/// is `Some` only if every evaluation was finite and the realised step was
/// non-zero. **That is the whole of the guarantee** — read the next section
/// before relying on it.
///
/// # What is detected, and what cannot be
///
/// The status is computed from exactly one predicate — every sampled value and
/// the resulting quotient are finite, and the realised step is non-zero — and
/// [`DerivativeSolution::derivative`] returns `Some` on exactly that same
/// predicate. They cannot disagree.
///
/// **Detected:** a non-finite sample ([`DiffStatus::NotFinite`]), a non-finite
/// point ([`DiffStatus::InvalidPoint`]), and a step that rounds away so
/// `x + h == x` ([`DiffStatus::DegenerateStep`]).
///
/// **Not detected, and not detectable by any finite-difference kernel:**
///
/// - **A singularity the stencil steps over.** `1/x` at `x = 0` is sampled by
/// the central stencil at `+h` and `-h`, both perfectly finite, so it returns
/// `1/h^2` with [`DiffStatus::Ok`]. The kernel never evaluates at the pole and
/// has no way to learn it is there. A one-sided scheme *does* see this
/// particular case, because it evaluates at `x` itself — but it has the
/// mirror-image blind spot on the other side.
/// - **Cancellation that leaves a finite number with no correct digits.** The
/// quotient is a perfectly ordinary `f64`; nothing about it says how many of
/// its bits survived. This is what the step-size rule exists to bound, and why
/// the module documents an *accuracy floor* rather than a guarantee.
/// - **A function that is not differentiable at `x`.** `|x|` at `0` returns `0`
/// from the central stencil, confidently.
///
/// If the function may be singular or kinked, bracket it away from the trouble
/// or check the result against a second scheme; the status field will not do it
/// for you.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::math::differentiate::{
/// derivative, DiffSettings, DiffStatus,
/// };
///
/// // d/dx sin(x) at x = 1 is cos(1).
/// let s = derivative(1.0, DiffSettings::central(), |x: f64| x.sin());
/// let d = s.derivative().expect("finite everywhere");
/// assert!((d - 1.0_f64.cos()).abs() < 1e-10, "got {d}");
///
/// // A sample that comes back non-finite IS reported: the central stencil for
/// // sqrt at x = 0 evaluates at -h, which is NaN.
/// let bad = derivative(0.0, DiffSettings::central(), |x: f64| x.sqrt());
/// assert_eq!(bad.status(), DiffStatus::NotFinite);
/// assert!(bad.derivative().is_none());
///
/// // But a pole the stencil STEPS OVER is not, and cannot be -- see
/// // "What is detected, and what cannot be" above.
/// let undetected = derivative(0.0, DiffSettings::central(), |x: f64| 1.0 / x);
/// assert_eq!(undetected.status(), DiffStatus::Ok);
/// assert!(undetected.derivative().is_some());
/// ```
/// Differentiate `N` independent scalar functions at `N` points, on the chosen
/// backend.
///
/// This is the batched, GPU-shaped form: lane `i` differentiates `f(i, .)` at
/// `points[i]`, and no arithmetic crosses lanes.
///
/// # Arguments
///
/// - `points` — one abscissa per lane, in the caller's own units.
/// - `settings` — scheme and step-size policy, shared by every lane.
/// - `backend` — requested execution backend. What actually runs is
/// [`derivative_backend_for`] applied to it. **None of the degradations
/// changes the answer.**
/// - `f` — `f(i, x)` is lane `i`'s function evaluated at `x`. It **must be a
/// pure deterministic function of its arguments** — see the module-level
/// "Determinism" section. The `Sync` bound is present in both feature builds
/// so enabling `parallel` never changes a public signature.
///
/// # Returns
///
/// A [`DerivativeBatch`] with one solution per point, in point order. An empty
/// `points` slice returns an empty batch and calls `f` zero times.
///
/// # Cost
///
/// [`DiffScheme::evaluations_per_derivative`] calls to `f` per lane — 2 for the
/// three second-order-or-lower schemes, 4 for [`DiffScheme::Central4th`].
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::math::differentiate::{
/// derivative_batch, DiffSettings,
/// };
///
/// // Lane i differentiates x^(i+1) at x = 2; the answer is (i+1) * 2^i.
/// let points = vec![2.0_f64; 4];
/// let batch = derivative_batch(
/// &points,
/// DiffSettings::central(),
/// ComputeBackend::CpuMulti,
/// |i, x: f64| x.powi(i as i32 + 1),
/// );
///
/// let d = batch.values().expect("all lanes finite");
/// for (i, got) in d.iter().enumerate() {
/// let want = (i as f64 + 1.0) * 2.0_f64.powi(i as i32);
/// assert!((got - want).abs() < 1e-6 * want.abs().max(1.0), "lane {i}: {got} vs {want}");
/// }
/// ```
/// [`derivative_batch`] with the size floor supplied by the caller.
///
/// Exists so the crossover benchmark can measure the multi-CPU path *below*
/// [`DERIVATIVE_BATCH_MIN_POINTS`] — the only way to find where the crossover
/// actually is — and so the cross-backend bitwise tests are not vacuous on
/// small batches. Not public: production callers get the measured floor.
pub
// ── Per-lane scalar kernel — one implementation, both backends ───────────────
/// The single-lane finite difference that **both** backends run.
///
/// `#[inline]` so the serial loop and the `rayon` map compile to the same inner
/// code — part of why the two backends agree bit for bit.
/// Forward (`h > 0`) or backward (`h < 0`) difference at `x`.
/// Central difference at `x` with half-width `h`.
// ── Jacobians ────────────────────────────────────────────────────────────────
/// One lane's Jacobian, with the status needed to judge it.
///
/// # Units
///
/// Entry `(i, j)` of the matrix carries the units of `f_i` divided by the units
/// of `x_j`. See the module-level "Units" section for why the generic form is
/// not `uom`-typed.
/// The result of [`jacobian_batch`] — one [`JacobianSolution`] per lane.
/// Assemble the Jacobian `J[i][j] = d f_i / d x_j` of one `n`-dimensional
/// vector function at one point, by finite differences.
///
/// The direct feeder for multi-dimensional Newton and — through
/// [`NumericalJacobian`] — for [`crate::ode::Rosenbrock23`].
///
/// # Square only
///
/// `f` must return exactly `x.len()` components. A rectangular Jacobian is
/// rejected with [`DiffStatus::DimensionMismatch`] rather than silently padded.
/// This restriction is deliberate and matches the prior art: the consumer
/// (`n` ODE equations in `n` states) is square, the crate's [`SquareMatrix`] is
/// square, and `outram-park-fork-dwsim-libs`' `finite_difference_jacobian`
/// rejects the non-square case too.
///
/// # Arguments
///
/// - `x` — the point, one component per variable, in the caller's own units.
/// - `settings` — scheme and step-size policy; see [`DiffSettings`]. The step
/// is computed per-column from that column's own `x[j]`, so variables of
/// wildly different magnitude each get an appropriate step.
/// - `backend` — requested backend for spreading the **columns** of this one
/// Jacobian. What actually runs is [`jacobian_column_backend_for`] applied to
/// it; a small `n` runs serially. **None of the degradations changes the
/// answer.**
/// - `f` — `f(0, x, out)` must fill `out` with the `n` function components at
/// `x`. The lane index is always `0` here; it is in the signature so the same
/// closure works with [`jacobian_batch`]. It **must be a pure deterministic
/// function of its arguments**.
///
/// # Returns
///
/// A [`JacobianSolution`] whose [`matrix`](JacobianSolution::matrix) is `Some`
/// only if every column succeeded.
///
/// # Cost
///
/// [`DiffScheme::evaluations_per_jacobian`] calls to `f`: `n + 1` for
/// [`DiffScheme::Forward`]/[`DiffScheme::Backward`], `2n` for
/// [`DiffScheme::Central`], `4n` for [`DiffScheme::Central4th`].
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::math::differentiate::{jacobian, DiffSettings};
///
/// // f(x, y) = [x^2 * y, sin(x) + y^3]
/// // J = [[2xy, x^2], [cos(x), 3y^2]]
/// let point = [1.5_f64, 2.0];
/// let s = jacobian(
/// &point,
/// DiffSettings::central(),
/// ComputeBackend::Serial,
/// |_, v: &[f64], out: &mut Vec<f64>| {
/// out.push(v[0] * v[0] * v[1]);
/// out.push(v[0].sin() + v[1] * v[1] * v[1]);
/// },
/// );
///
/// let j = s.matrix().expect("smooth everywhere");
/// let (x, y) = (point[0], point[1]);
/// for (got, want) in [
/// (j.get(0, 0), 2.0 * x * y),
/// (j.get(0, 1), x * x),
/// (j.get(1, 0), x.cos()),
/// (j.get(1, 1), 3.0 * y * y),
/// ] {
/// assert!((got - want).abs() < 1e-8 * want.abs().max(1.0), "{got} vs {want}");
/// }
/// ```
/// Assemble `N` independent Jacobians, one per lane, on the chosen backend.
///
/// This is the batched form: the parallel axis is the **lane**, not the column,
/// so it is the right entry point when there are many small Jacobians (a
/// per-cell chemistry Jacobian over a mesh, an ensemble of ODE systems). Use
/// [`jacobian`] when there is one large Jacobian instead.
///
/// # The flat point layout
///
/// `points` is a **flat, row-major** buffer of `lanes * n` values: lane `i`'s
/// point is `points[i * n .. (i + 1) * n]`. A `&[Vec<f64>]` would be the
/// obvious alternative and is rejected on purpose — it costs one allocation and
/// one pointer chase per lane, and it is not the layout a GPU buffer would ever
/// take. `points.len()` must be an exact multiple of `n`.
///
/// # Arguments
///
/// - `points` — flat `lanes * n` buffer as above, in the caller's own units.
/// - `n` — the dimension of each point, dimensionless. Must be non-zero.
/// - `settings` — scheme and step-size policy, shared by every lane.
/// - `backend` — requested backend; see [`jacobian_batch_backend_for`]. Each
/// lane's columns are computed serially, since the lane axis is already the
/// parallel one.
/// - `f` — `f(i, x, out)` must fill `out` with lane `i`'s `n` function
/// components at `x`. It **must be a pure deterministic function of its
/// arguments**.
///
/// # Returns
///
/// A [`JacobianBatch`] with one solution per lane, in lane order. An empty
/// `points` slice, or `n == 0`, returns an empty batch and calls `f` zero
/// times. A `points.len()` that is not a multiple of `n` returns an empty batch
/// as well — it is a caller bug, not a numerical failure, and there is no
/// sensible lane count to report per-lane statuses against.
///
/// # Cost
///
/// `lanes * `[`DiffScheme::evaluations_per_jacobian`]`(n)` calls to `f`.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::math::differentiate::{jacobian_batch, DiffSettings};
///
/// // 3 lanes of the 2-D rotation-like system f = [-k_i * y, k_i * x],
/// // whose Jacobian is [[0, -k_i], [k_i, 0]].
/// let k = [1.0_f64, 2.5, 7.0];
/// let points: Vec<f64> = vec![0.3, -0.7, 0.3, -0.7, 0.3, -0.7];
///
/// let batch = jacobian_batch(
/// &points,
/// 2,
/// DiffSettings::central(),
/// ComputeBackend::CpuMulti,
/// |i, v: &[f64], out: &mut Vec<f64>| {
/// out.push(-k[i] * v[1]);
/// out.push(k[i] * v[0]);
/// },
/// );
///
/// let mats = batch.matrices().expect("linear system, exact everywhere");
/// for (i, m) in mats.iter().enumerate() {
/// assert!((m.get(0, 1) + k[i]).abs() < 1e-9);
/// assert!((m.get(1, 0) - k[i]).abs() < 1e-9);
/// }
/// ```
/// [`jacobian_batch`] with the size floor supplied by the caller.
///
/// Exists so the crossover benchmark can measure the multi-CPU path *below*
/// [`JACOBIAN_BATCH_MIN_PROBLEMS`], and so the cross-backend bitwise tests are
/// not vacuous on small batches. Not public.
pub
/// Assemble one lane's Jacobian, spreading the columns across `backend` when
/// the dimension justifies it.
///
/// Delegates to [`jacobian_columns_serial`] for everything except the `rayon`
/// arm, and both arms call the same [`jacobian_column`] kernel — which is why
/// every public Jacobian entry point agrees bit for bit.
/// One lane's Jacobian, columns computed on the calling thread.
///
/// Carries **no** `Sync` bound, which is what lets [`ode_system_jacobian`]
/// difference an `OdeSystem` that is not itself `Sync`.
/// The unperturbed evaluation `f(x)`, shared by every column of a one-sided
/// scheme — which is what makes [`DiffScheme::Forward`] cost `n + 1`
/// evaluations rather than `2n`. `None` for the symmetric schemes, whose
/// stencils never touch `x` itself.
/// Pack per-column results into a [`SquareMatrix`], filling failed columns with
/// `NaN` and recording the first failure.
/// An all-`NaN` Jacobian carrying the reason it could not be formed.
/// Column `j` of the Jacobian: `d f / d x_j`, all `n` components at once.
///
/// `base` carries the shared unperturbed evaluation for the one-sided schemes
/// and is `None` for the symmetric ones.
/// Forward (`h > 0`) or backward (`h < 0`) column, reusing the shared base.
/// Central column with half-width `h`.
// ── The ODE consumer ─────────────────────────────────────────────────────────
/// Fill an [`OdeSystem`]'s Jacobian slots by finite differences.
///
/// This is the free-function form of what [`NumericalJacobian`] does, for
/// callers who already have an `OdeSystem` and want the numbers rather than a
/// wrapper. It fills exactly the two buffers
/// [`OdeSystem::jacobian`] is contracted to fill:
///
/// - `dfdy[i][j] = d f_i / d y_j`, an `n x n` [`SquareMatrix`];
/// - `dfdx[i] = d f_i / d x`, the derivative with respect to the **independent
/// variable** (time, for a transient), length `n`.
///
/// Both are resized to `n = system.n_eqns()` if the caller's buffers are the
/// wrong size, so it is safe to pass freshly-defaulted ones.
///
/// # Failure is written into the buffers, not swallowed
///
/// On failure the offending entries are filled with `NaN` **and** the reason is
/// returned. Nothing is quietly zeroed. This matters: filling a failed entry
/// with `0.0` — which
/// `outram-park-fork-dwsim-libs`' `finite_difference_jacobian` does — turns an
/// undetectable-at-the-call-site failure into a plausible-looking Jacobian, and
/// a Rosenbrock step built on it produces a wrong trajectory rather than an
/// error. With `NaN` the failure propagates into the step, the normalised error
/// estimate becomes `NaN`, the step controller shrinks `dx` and
/// [`crate::ode::OdeError::StepSizeUnderflow`] is reported. Loud is better.
///
/// # Arguments
///
/// - `system` — the ODE system whose [`OdeSystem::derivatives`] is sampled.
/// - `x` — the independent variable, caller's units.
/// - `y` — the state, length `system.n_eqns()`.
/// - `settings` — scheme and step-size policy; see [`DiffSettings`].
/// - `dfdx`, `dfdy` — output buffers, filled in place.
///
/// # Returns
///
/// [`DiffStatus::Ok`] if every entry of both outputs was formed from finite
/// evaluations; the first failing status otherwise.
///
/// # Cost
///
/// `1 + `[`DiffScheme::evaluations_per_jacobian`]`(n)` calls to
/// [`OdeSystem::derivatives`] for the one-sided schemes — the base evaluation
/// is shared between `dfdy`'s columns and `dfdx` — and
/// [`DiffScheme::evaluations_per_jacobian`]`(n) + 2` or `+ 4` for the symmetric
/// ones.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::math::differentiate::{
/// ode_system_jacobian, DiffSettings, DiffStatus,
/// };
/// use outram_foam_basic_lib::matrix::SquareMatrix;
/// use outram_foam_basic_lib::ode::OdeSystem;
///
/// // dy/dx = [-2*y0 + y1, x * y0] -- Jacobian [[-2, 1], [x, 0]], dfdx = [0, y0].
/// struct Linear;
/// impl OdeSystem for Linear {
/// fn n_eqns(&self) -> usize { 2 }
/// fn derivatives(&self, x: f64, y: &[f64], dydx: &mut Vec<f64>) {
/// dydx.clear();
/// dydx.push(-2.0 * y[0] + y[1]);
/// dydx.push(x * y[0]);
/// }
/// }
///
/// let mut dfdx = Vec::new();
/// let mut dfdy = SquareMatrix::new(2);
/// let status = ode_system_jacobian(
/// &Linear, 0.5, &[1.0, 2.0], DiffSettings::central(), &mut dfdx, &mut dfdy,
/// );
///
/// assert_eq!(status, DiffStatus::Ok);
/// assert!((dfdy.get(0, 0) + 2.0).abs() < 1e-8);
/// assert!((dfdy.get(0, 1) - 1.0).abs() < 1e-8);
/// assert!((dfdy.get(1, 0) - 0.5).abs() < 1e-8);
/// assert!(dfdy.get(1, 1).abs() < 1e-8);
/// assert!(dfdx[0].abs() < 1e-8);
/// assert!((dfdx[1] - 1.0).abs() < 1e-8); // d/dx (x * y0) = y0 = 1
/// ```
/// Fill `dfdx` — the derivative of each equation with respect to the
/// independent variable, holding the state fixed.
/// The `dfdx` stencil: one scalar direction, `n` outputs.
///
/// Structurally identical to [`jacobian_column`] with `j = 0`; kept separate
/// only because its function takes a bare `f64` rather than a slice, which is
/// what [`OdeSystem::derivatives`] wants for its independent variable.
/// Wrap any [`OdeSystem`] so that [`crate::ode::Rosenbrock23`] can integrate it
/// **without a hand-coded Jacobian**.
///
/// # The problem this solves
///
/// [`OdeSystem::jacobian`] has a default body that is `unimplemented!()`, so a
/// system that does not override it panics the moment a stiff solver asks for a
/// Jacobian — inside `Rosenbrock23::inner_step`, and, if the integration is
/// running in an ensemble, out through the `rayon` scope. Every system that
/// only knows its own `derivatives` is locked out of the crate's only stiff
/// solver.
///
/// Wrapping it in `NumericalJacobian` supplies the missing method by finite
/// differences and changes nothing else: `n_eqns` and `derivatives` are
/// forwarded verbatim.
///
/// # Owning, not borrowing
///
/// The wrapper **owns** the system by value, so it needs no lifetime parameter
/// and no `Box` — both forbidden by the workspace design rules. Construct it
/// with [`Self::new`], get the system back with [`Self::into_inner`].
///
/// # An analytic Jacobian is still better
///
/// Finite differences cost `n + 1` to `4n` extra `derivatives` calls per
/// Rosenbrock stage and are accurate to roughly `sqrt(eps)` to `eps^(4/5)`
/// rather than to machine precision — see the module-level "Achievable
/// accuracy" table. If the analytic Jacobian is available, write it. This
/// wrapper is for the systems where it is not, and as a **verification oracle**
/// for the ones where it is: differencing a system that also implements
/// `jacobian` analytically and comparing is the cheapest real check that the
/// hand-derived version has no sign or transposition error.
///
/// # Units
///
/// Inherited from the wrapped system; nothing here is dimensioned.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::math::differentiate::{DiffSettings, NumericalJacobian};
/// use outram_foam_basic_lib::ode::{OdeSystem, Rosenbrock23};
///
/// // A stiff scalar system with NO hand-coded Jacobian: dy/dx = -1000 y.
/// struct StiffDecay;
/// impl OdeSystem for StiffDecay {
/// fn n_eqns(&self) -> usize { 1 }
/// fn derivatives(&self, _x: f64, y: &[f64], dydx: &mut Vec<f64>) {
/// dydx.clear();
/// dydx.push(-1000.0 * y[0]);
/// }
/// // no `jacobian` override -- the default would panic
/// }
///
/// let system = NumericalJacobian::new(StiffDecay, DiffSettings::central());
/// let mut solver = Rosenbrock23::new(1, 1e-10, 1e-10);
/// let mut y = vec![1.0_f64];
/// let mut dx = 1e-5;
/// solver.integrate(&system, 0.0, 0.01, &mut y, &mut dx).expect("integrates");
///
/// // exp(-1000 * 0.01) = exp(-10) = 4.5399929762484854e-5
/// let exact = (-10.0_f64).exp();
/// assert!((y[0] - exact).abs() < 1e-8, "got {}, want {exact}", y[0]);
/// assert_eq!(system.non_finite_jacobians(), 0);
/// ```