1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
// 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/>.
//! Batched **numerical integration** on the hybrid execution backend — `N`
//! independent initial-value problems, or `N` independent definite integrals,
//! advanced at once, serially or across CPU cores.
//!
//! # The two things in here, and why they share a module
//!
//! | Operation | The batch is | Entry point |
//! |---|---|---|
//! | ODE ensemble, one stepper for every lane | `N` independent IVPs | [`integrate_ensemble`] |
//! | ODE ensemble, stepper chosen per lane | `N` independent IVPs | [`integrate_ensemble_mixed`] |
//! | Fixed-rule quadrature | `N` independent definite integrals | [`quadrature_batch`] |
//! | Adaptive quadrature | `N` independent definite integrals | [`adaptive_quadrature_batch`] |
//!
//! Both halves are "numerical integration" in the sense bead `op-yvj.4.5` uses
//! the phrase, and a definite integral genuinely *is* the initial-value problem
//! `dy/dx = f(x)`, `y(a) = 0`, read at `x = b` — so quadrature sitting beside the
//! ODE steppers is not a filing accident. They also share every piece of
//! machinery that is not the arithmetic itself: the lane vocabulary, the
//! per-lane status reporting, the backend-degradation policy, and the
//! determinism argument below. Keeping them together means the crate has **one**
//! batched-integration dialect rather than two.
//!
//! # Reuse, not reimplementation
//!
//! **No new integrator is written here.** The ODE half drives the crate's
//! existing steppers — [`Euler`](crate::ode::Euler),
//! [`Rkf45`](crate::ode::Rkf45), [`Rosenbrock23`](crate::ode::Rosenbrock23),
//! selected through the existing [`OdeSolver`] enum — over the existing
//! adaptive interval loop. This module adds the *ensemble*: the outer loop over
//! lanes, the per-lane outcome reporting, and the backend dispatch.
//!
//! The quadrature half is new code, because the workspace had no general
//! quadrature. The only prior art is
//! `outram-park-fork-dwsim-libs`'s `clean_energies::pem_fuel_cell::simpson_integrate`,
//! which is deliberately **not** reused: it is a verbatim port of OPEM's rule
//! *including its documented flaw* (composite Simpson weights applied without
//! checking that the sample count is odd), and it integrates a slice of
//! pre-sampled values rather than a callable integrand. [`QuadratureRule`]
//! keeps the one convention that does carry over — composite rules over equal
//! subintervals — and makes the sample-count error structurally impossible by
//! counting Simpson *panels* of two subintervals each rather than raw samples.
//! `raffles`'s `distributions::special::integrate_open_unit` is the other
//! in-workspace quadrature: a composite 8-point Gauss-Legendre over
//! geometrically graded panels, hard-wired to the open unit interval and to
//! quantile-function moments. It is not a general routine and is private to that
//! crate's `special` module, so it is cited here as precedent for the
//! Gauss-Legendre choice rather than reused.
//!
//! # Hybrid means dispatch, not two APIs
//!
//! Every entry point takes a [`ComputeBackend`] parameter, and there is no
//! `*_parallel()` sibling anywhere. With the `parallel` feature off,
//! [`ComputeBackend::CpuMulti`] resolves down to [`ComputeBackend::Serial`]
//! through [`ComputeBackend::resolve`] and the answer is unchanged, bit for bit.
//! There is no GPU kernel in this module yet, so a [`ComputeBackend::Gpu`]
//! request degrades to the best available CPU path — see "GPU" below for why
//! that is not merely laziness for the adaptive paths.
//!
//! # Determinism — bitwise identical, and the summation-order question
//!
//! **Every kernel in 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 system or integrand is itself a
//! deterministic pure function of its arguments.
//!
//! For the ODE ensemble this is the same argument as
//! [`crate::math::parallel`]'s: lane `i`'s trajectory is a pure function of lane
//! `i`'s system, initial condition and stepper. No lane reads another lane's
//! state, so there is no cross-lane arithmetic whose association could change,
//! and both backends call the very same per-lane kernel. Each lane also gets its
//! **own** clone of the stepper prototype, so no scratch buffer is ever shared
//! between lanes and the result cannot depend on which lanes a worker happened
//! to run first.
//!
//! Quadrature needs one extra sentence, because a quadrature rule *is* a sum and
//! floating-point addition is not associative. The reason the answer is still
//! bit-identical is the shape of the batch: **one lane is one integral, and one
//! integral is summed sequentially by a single thread.** The parallelism is over
//! lanes, never within a lane, so no partial sum is ever re-associated. This is
//! a deliberate design choice with a real cost — it means a single very
//! expensive integral gets no speed-up from this module at all — and it is taken
//! because a reduction split across threads would give a different answer at
//! every thread count, which for a verification oracle is disqualifying.
//! **Splitting one integral's panels across threads is not offered here**, and
//! if it is ever added it must be a separate, separately-named entry point whose
//! documentation says plainly that it is not bit-reproducible.
//!
//! Verified by the `bitwise_*` tests in `parallel/tests.rs`, which compare
//! serial against `rayon` pools of 1, 2, 4 and 8 workers on batches built to
//! have wildly uneven per-lane cost.
//!
//! For scale, a 4 096-lane deliberately-imbalanced ensemble (half the lanes
//! decaying at `k` near 1, half at `k` near 60, giving 278 318 accepted steps in
//! total — a mean of 67.9 per lane against a maximum of 126) under `Rkf45`, measured
//! 2026-08-13 on 4 logical cores by the `#[ignore]`d
//! `ensemble_thread_scaling_benchmark`, best of 7 samples, with a second
//! independent run alongside:
//!
//! | Worker threads | Time | Speed-up | (repeat) | Bitwise vs serial |
//! |---|---|---|---|---|
//! | *serial reference* | 35808.33 us | 1.00x | 1.00x | — |
//! | 1 | 35839.25 us | 1.00x | 1.00x | identical |
//! | 2 | 18283.82 us | 1.96x | 1.92x | identical |
//! | 4 | 9276.65 us | 3.86x | 3.09x | identical |
//! | 8 | 9128.96 us | 3.92x | 3.05x | identical |
//!
//! The "identical" column is the determinism claim above measured rather than
//! argued, and it is asserted by the benchmark itself, not merely printed. Going
//! through `rayon` with a single worker costs essentially nothing here (1.00x),
//! unlike the batched root finder where it costs about 6% — the per-lane work is
//! large enough that the iterator machinery disappears into it. Eight workers on
//! four cores buy nothing further, the expected signature of a compute-bound
//! kernel that already saturates its cores. **This is one machine, one ensemble
//! and two runs; it is not a scaling study**, and nothing here has been measured
//! on Android hardware or on a many-core server.
//!
//! # Load imbalance — why there is no hand-rolled partition
//!
//! An adaptive stepper takes a different number of sub-steps in every lane, and
//! the spread is not small. On the benchmark ensemble below it is a mean of 67.9
//! accepted steps against a maximum of 126; on the stiff pair in
//! `parallel/tests.rs` a single lane under [`Rkf45`](crate::ode::Rkf45) burns
//! all 10 000 of its allotted steps and still spans only a third of the
//! interval, beside decay lanes finishing in 81. Adaptive quadrature has the
//! same property by construction — 469 to 1 225 integrand evaluations across the
//! three verification integrands. A static equal split across `P` threads
//! therefore ends up waiting on whichever chunk drew the hard lanes.
//!
//! Every parallel path here uses `rayon`'s adaptive splitting with **no**
//! `min_len` floor, so an idle worker can steal down to a single lane. That is
//! the deliberate answer to the imbalance, not an oversight. No granularity
//! floor is imposed even on the fixed-rule quadrature path, where the crate's
//! closed-form polynomial kernels do impose one
//! ([`crate::math::parallel::POLY_BLOCK`]): there, every lane provably costs the
//! same handful of flops, whereas here the per-lane cost is set by the caller
//! through [`QuadratureRule`]'s panel count *and* by the cost of the caller's
//! integrand, so any fixed floor would be wrong for most callers. Work-stealing
//! handles both ends without a number that cannot be justified.
//!
//! Whatever the splitter does, it cannot change a value — every lane is computed
//! independently of every other.
//!
//! # Stiffness — how a mixed ensemble is handled
//!
//! The realistic per-cell chemistry ensemble is *mixed*: most cells are benign
//! and a few are stiff. Three things follow, and all three are deliberate.
//!
//! 1. **The stepper is not switched behind the caller's back.** An ensemble run
//! with [`integrate_ensemble`] uses one stepper for every lane. A stiff lane
//! handed an explicit stepper does not silently return a wrong answer: the
//! adaptive controller shrinks the step until it either meets tolerance —
//! correct but slow — or runs out, at which point the lane reports
//! [`OdeLaneStatus::MaxStepsExceeded`] or
//! [`OdeLaneStatus::StepSizeUnderflow`]. Stiffness therefore shows up as a
//! *named per-lane failure*, not as silent garbage.
//! 2. **Per-lane stepper selection exists** — [`integrate_ensemble_mixed`] takes
//! a closure `Fn(usize) -> OdeSolver`, so a caller that knows which cells are
//! stiff (or that has just been told by a failed
//! [`integrate_ensemble`] pass) can give those lanes
//! [`Rosenbrock23`](crate::ode::Rosenbrock23) and leave the rest on
//! [`Rkf45`](crate::ode::Rkf45). This is the intended recovery path and it
//! costs nothing when unused.
//! 3. **`Rosenbrock23` needs a Jacobian, and this module does not supply one.**
//! [`OdeSystem::jacobian`](crate::ode::OdeSystem::jacobian)'s default
//! implementation panics, and a panic inside a `rayon` worker will propagate
//! out of the batch. Check
//! [`OdeSolver::requires_jacobian`](crate::ode::OdeSolver::requires_jacobian)
//! before selecting it for a system you did not write. Batched *numerical*
//! Jacobians are bead `op-yvj.4.6`, not this one.
//!
//! # Non-convergence is reported, never swallowed
//!
//! An ensemble of 10 000 cells in which 3 fail must say so, and must say which
//! 3. Both halves report failure **per lane**, and make it hard to ignore by
//! construction — the same shape [`crate::math::parallel`] uses:
//!
//! - [`OdeLaneSolution::state`] and [`QuadratureSolution::value`] return
//! `Option`, and hand back `Some` **only** for a lane that succeeded.
//! - The raw number is behind the deliberately-named
//! [`OdeLaneSolution::last_state`] / [`QuadratureSolution::last_value`], so
//! using a failed lane's partial answer is a visible decision in the calling
//! code rather than an accident.
//! - [`OdeEnsemble::states`] and [`QuadratureBatch::values`] are all-or-nothing:
//! they return `Err` naming the failure count and the first failing lane,
//! rather than a plausible-looking `Vec`.
//!
//! **A lane that ran out of steps is never presented as if it had reached
//! `x_end`.** It reports [`OdeLaneStatus::MaxStepsExceeded`], its genuine
//! partial state, and the `x` it actually reached — which is exactly the
//! information needed to decide whether to sub-cycle it or re-run it stiff. A
//! lane whose inputs were unusable reports [`OdeLaneStatus::InvalidLane`] and a
//! `NaN` state, because there is no honest number to return.
//!
//! # GPU
//!
//! There is no `wgpu` kernel here yet; `Gpu` degrades. Two of these four
//! kernels would map to one if written, and two would not, and the distinction
//! is worth recording rather than rediscovering:
//!
//! - **Fixed-rule quadrature is GPU-shaped.** Every lane evaluates the same
//! fixed number of nodes with no data-dependent branching, so a warp never
//! diverges.
//! - **Adaptive quadrature is not, and is CPU-only by design.** Its subdivision
//! pattern is decided by the integrand, so neighbouring lanes take different
//! paths through the code and different numbers of evaluations; on SIMT
//! hardware that serialises the divergent branches and needs a per-lane
//! work stack. It stays on the CPU deliberately.
//! - **Adaptive ODE ensembles have the same problem, sharpened.** A batch run
//! lockstep at the smallest step any lane needs is simple and correct but
//! wastes the whole ensemble's budget on its worst member; per-lane step
//! control is correct but divergent. Neither is attempted here.
//!
//! Note also that WGSL has no `f64`, and the accuracy consequences of an `f32`
//! quadrature or an `f32` error controller are unmeasured in this workspace.
//!
//! # Units
//!
//! Everything here is dimensionless `f64`, for the same reason
//! [`crate::math::parallel`] is: a general integrator has no single physical
//! dimension. One lane's abscissa may be a time in seconds and another's a
//! length in metres, and the state vector's components routinely carry different
//! dimensions from each other.
//!
//! `uom` typing is **not stripped** to get here — it is applied at the boundary,
//! by the caller, exactly as the hybrid-backend epic requires: convert into the
//! batch, convert back out. The doctests on [`integrate_ensemble`] and
//! [`quadrature_batch`] show that boundary explicitly, one recovering a
//! `ThermodynamicTemperature` and the other an `Energy`.
//!
//! # 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 — an ensemble of independent decays
//!
//! ```rust
//! use outram_foam_basic_lib::compute::ComputeBackend;
//! use outram_foam_basic_lib::ode::{OdeSolver, OdeSystem};
//! use outram_foam_basic_lib::ode::parallel::{integrate_ensemble, OdeLane};
//!
//! /// `dy/dx = -k y` — one lane per decay constant.
//! struct Decay { k: f64 }
//! impl OdeSystem for Decay {
//! fn n_eqns(&self) -> usize { 1 }
//! fn derivatives(&self, _x: f64, y: &[f64], dydx: &mut Vec<f64>) {
//! dydx[0] = -self.k * y[0];
//! }
//! }
//!
//! let lanes: Vec<OdeLane<Decay>> = (1..=4)
//! .map(|i| OdeLane::new(Decay { k: i as f64 }, vec![1.0], 0.0, 1.0, 0.1))
//! .collect();
//!
//! let ensemble = integrate_ensemble(
//! &lanes,
//! &OdeSolver::rkf45(1, 1e-10, 1e-8),
//! ComputeBackend::CpuMulti,
//! );
//!
//! let states = ensemble.states().expect("all four lanes complete");
//! for (i, s) in states.iter().enumerate() {
//! let exact = (-(i as f64 + 1.0)).exp();
//! assert!((s[0] - exact).abs() < 1e-8, "lane {i}: {} vs {exact}", s[0]);
//! }
//!
//! // Asking for multi-CPU gives a bit-for-bit identical answer, whether or not
//! // the `parallel` feature is compiled in.
//! let serial = integrate_ensemble(
//! &lanes,
//! &OdeSolver::rkf45(1, 1e-10, 1e-8),
//! ComputeBackend::Serial,
//! );
//! assert_eq!(states, serial.states().unwrap());
//! ```
use RealMath;
use *;
use ;
use crateComputeBackend;
// ── Tuning constants ─────────────────────────────────────────────────────────
/// Lane count below which a [`ComputeBackend::CpuMulti`] request runs
/// [`integrate_ensemble`] 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, machine otherwise idle (see the
/// *Contention* note below, which is not a footnote — it changes the answer).
/// Ensembles of `n` independent one-equation decay problems `dy/dx = -k_i y`,
/// `y(0) = 1`, integrated from `x = 0` to `x = 1` by
/// [`Rkf45`](crate::ode::Rkf45) with `abs_tol = 1e-10`, `rel_tol = 1e-8`,
/// initial step `0.1`. Half the lanes are given `k_i` in `[0.5, 1.5)` and half
/// in `[50, 70)`, so the ensemble is deliberately imbalanced: on the 4 096-lane
/// case the accepted-step count averages **67.9** per lane against a
/// **maximum of 126**. Each lane costs about **8.6 us** of serial work. Best of 7
/// samples per point, wall clock for one whole ensemble. Produced by the
/// `#[ignore]`d `ensemble_crossover_benchmark` test in `parallel/tests.rs` and
/// transcribed from its printed output. Three independent runs are carried
/// side by side rather than averaged, because the parallel column is far
/// noisier than the serial one and the spread is the finding.
///
/// | Lanes | serial (run A) | speed-up A | speed-up B | speed-up C |
/// |---|---|---|---|---|
/// | 8 | 66.85 us | 2.66x | 1.26x | 0.89x |
/// | 16 | 132.56 us | 2.99x | 2.10x | 3.12x |
/// | 32 | 267.99 us | 1.23x | 1.53x | 2.51x |
/// | 64 | 545.25 us | 3.07x | 1.94x | 2.37x |
/// | 128 | 1092.75 us | 3.27x | 1.96x | 3.78x |
/// | 256 | 2212.57 us | 3.67x | 2.41x | 2.99x |
/// | 1 024 | 8814.43 us | 3.55x | 2.94x | 3.72x |
/// | 4 096 | 35205.42 us | 3.67x | 3.87x | 3.60x |
/// | 16 384 | 141229.69 us | 3.86x | 3.89x | 3.74x |
///
/// *Result.* **16** is the smallest size at which the parallel path won in all
/// three runs *and* kept winning at every larger size in all three, and it is
/// the value this constant takes. At 8 lanes it lost run C (0.89x).
///
/// *How firm is that.* Not very, and the table says so honestly. Between 16 and
/// 128 lanes the **sign** of the effect is consistent — the parallel path never
/// loses — but the **magnitude** is not resolved: 32 lanes gave 1.23x and 2.51x
/// in two runs of the same code on the same data. Anywhere in 16–128 would be
/// defensible on this evidence. What the table does establish firmly is the
/// plateau: from 1 024 lanes upward the speed-up sits at 3.5–3.9x on 4 logical
/// cores, run to run, which is close to the ideal and is the expected signature
/// of a compute-bound kernel with no cross-lane traffic.
///
/// *Interpretation.* This is the lowest crossover measured anywhere in the crate
/// — 16x below [`crate::math::parallel::ROOT_BATCH_MIN_PROBLEMS`] (256), 256x
/// below the crate-wide placeholder
/// [`crate::compute::CPU_MULTI_MIN_WORK_ITEMS`] (4 096) and 8 192x below
/// [`crate::fields::parallel::FIELD_PARALLEL_CROSSOVER`] (131 072). The reason
/// is structural: one lane here is 68 adaptive steps, each of them six
/// derivative evaluations, against a state vector of one `f64`. At about 8.6 us
/// per lane it is by a wide margin the most compute-dense per work item of the
/// crate's measured kernels, so `rayon`'s dispatch cost is amortised almost
/// immediately. Five kernel families have now been measured in this crate and
/// they want **16, 256, 4 096, 131 072 and 262 144** — a spread of 16 384x,
/// which is the strongest evidence yet that no single crate-wide threshold can
/// be right.
///
/// The corollary is the one the root finder also found, sharpened here:
/// **the crossover is set by the caller's problem, not by this module.** A lane
/// integrating a short interval, or a two-equation system to a loose tolerance,
/// is an order of magnitude cheaper and crosses over correspondingly later. A
/// caller whose lanes are very cheap should pass [`ComputeBackend::Serial`]
/// explicitly rather than trust this number.
///
/// # Contention — this threshold assumes the cores are actually free
///
/// Three earlier runs of the same benchmark were taken while an unrelated
/// `rustc` was using ~234% CPU on the same 4-core machine (load average 5.08),
/// and they are **not** the table above. Under that load the parallel path lost
/// at 8 lanes in every run and lost once at 64 lanes, and the plateau speed-up
/// fell from 3.5–3.9x to 2.9–3.9x. The lesson generalises beyond this
/// measurement: a threshold measured on an idle machine is optimistic for a
/// process sharing cores with anything else — an MPI rank per core, a coupled
/// solver threading elsewhere, or a CI box running several jobs. In those
/// settings prefer an explicit [`ComputeBackend`].
///
/// # Limitations
///
/// One machine, four logical cores, one system family (scalar linear decay),
/// one stepper (`Rkf45`). Not measured on Android/Termux hardware, not on a
/// many-core server, and not with [`Rosenbrock23`](crate::ode::Rosenbrock23),
/// whose per-lane cost includes an LU factorisation and is therefore higher
/// still — meaning this floor is conservative for stiff ensembles rather than
/// wrong for them.
///
/// # Units
///
/// A count of independent initial-value problems, dimensionless.
pub const ODE_ENSEMBLE_MIN_LANES: usize = 16;
/// Interval count below which a [`ComputeBackend::CpuMulti`] request runs
/// [`quadrature_batch`] and [`adaptive_quadrature_batch`] on the calling thread
/// instead.
///
/// # Measured crossover
///
/// *Methodology.* Same machine, build and conditions as
/// [`ODE_ENSEMBLE_MIN_LANES`] (4 logical cores, release, `--features parallel`,
/// idle, best of 7 samples, three independent runs), measured 2026-08-13.
/// Batches of `n` independent integrals of `exp(-a_i x) sin(b_i x)` with
/// `a_i` in `[0.1, 3)` and `b_i` in `[1, 30)`, over per-lane intervals inside
/// `[0, 4]`, evaluated with [`QuadratureRule::GaussLegendre`] at
/// [`GaussOrder::G5`] over 16 panels — 80 integrand evaluations per lane, about
/// **1.4 us** of serial work, a mid-cost rule. Produced by the `#[ignore]`d
/// `quadrature_crossover_benchmark` test in `parallel/tests.rs` and transcribed
/// from its printed output.
///
/// | Intervals | serial (run A) | speed-up A | speed-up B | speed-up C |
/// |---|---|---|---|---|
/// | 16 | 20.48 us | 1.36x | 1.16x | 0.51x |
/// | 32 | 40.96 us | 2.03x | 2.10x | 1.81x |
/// | 64 | 82.62 us | 1.95x | 2.47x | 2.62x |
/// | 128 | 170.22 us | 1.96x | 1.58x | 2.75x |
/// | 256 | 351.75 us | 3.15x | 3.47x | 3.29x |
/// | 1 024 | 1475.98 us | 3.61x | 3.79x | 3.74x |
/// | 4 096 | 6090.40 us | 3.89x | 3.75x | 3.97x |
/// | 16 384 | 24717.71 us | 3.89x | 3.75x | 3.90x |
///
/// *Result.* **32** is the smallest size at which the parallel path won in all
/// three runs and kept winning at every larger size, and it is the value this
/// constant takes. At 16 intervals it lost run C badly (0.51x).
///
/// *Interpretation.* Twice the ODE floor of 16, on lanes about 6x cheaper
/// (1.4 us against 8.6 us). The two do not scale together, which is the honest
/// reading of a measurement whose 16–128 region is dominated by run-to-run
/// noise in both kernels; what both agree on is that a batch of a few hundred
/// compute-dense lanes is comfortably worth threading and a batch of a handful
/// is not. From 256 intervals upward the speed-up is a stable 3.1–4.0x on 4
/// logical cores.
///
/// **This one floor is shared by both quadrature entry points**, and it was
/// measured on the fixed-rule path only. [`adaptive_quadrature_batch`] costs
/// more per lane than any fixed rule a caller is likely to choose — the
/// verification lanes on that function needed 469 to 1 225 evaluations against
/// this rule's 80 — so it crosses over *earlier* and inherits this floor as a
/// conservative assumption rather than a measurement. A caller whose fixed rule
/// is very cheap — say [`QuadratureRule::Trapezoid`] with one panel, two
/// evaluations — is well below what was measured and should pass a backend
/// explicitly.
///
/// # Contention
///
/// The same caveat as [`ODE_ENSEMBLE_MIN_LANES`], and it bit harder here.
/// Three earlier runs taken while an unrelated `rustc` held ~234% CPU on the
/// same 4-core machine showed the parallel path **losing at every size up to
/// 64** and sitting at 0.98–1.02x — no speed-up at all — at 256 through 4 096,
/// where the idle machine gives 3.1–4.0x. A threshold measured on an idle
/// machine is optimistic for a process that shares its cores.
///
/// # Limitations
///
/// One machine, four logical cores, idle, one integrand family, one rule
/// (`G5` over 16 panels). Not measured on Android/Termux. Not measured for the
/// adaptive path, for the trapezoid or Simpson rules, or for other Gauss orders.
///
/// # Units
///
/// A count of independent definite integrals, dimensionless.
pub const QUADRATURE_MIN_INTERVALS: usize = 32;
/// Hard ceiling on adaptive bisection depth in
/// [`adaptive_quadrature_batch`], regardless of
/// [`AdaptiveSettings::max_subdivisions`].
///
/// A depth of 50 halvings shrinks an interval by a factor of `2^50` (about
/// `10^15`), at which point the sub-interval is at the rounding floor of any
/// abscissa a caller is likely to pass and further subdivision cannot improve
/// the answer. The ceiling exists so that a pathological integrand — one with a
/// genuine singularity inside the interval — terminates with
/// [`QuadratureStatus::ToleranceNotMet`] instead of consuming memory
/// indefinitely.
///
/// # Units
///
/// A count of bisections, dimensionless.
pub const MAX_ADAPTIVE_DEPTH: u32 = 50;
// ── Backend dispatch ─────────────────────────────────────────────────────────
/// Resolve a requested backend to the one this module will actually run, given
/// how much work there is.
///
/// Three reductions, in order: [`ComputeBackend::resolve`] degrades anything
/// whose feature is off; `Gpu` degrades again because this module has no GPU
/// kernel; 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.
/// The [`ComputeBackend`] the ODE ensemble would actually use for `n` lanes if
/// asked for `requested` — without running anything.
///
/// Applies exactly the same reduction the kernels do (feature availability, no
/// GPU kernel here, and the [`ODE_ENSEMBLE_MIN_LANES`] size floor), so what it
/// reports is what would run. Useful for logging and for benchmark harnesses.
///
/// # Arguments
///
/// - `requested` — the backend a caller would pass to [`integrate_ensemble`].
/// - `n` — the number of independent lanes, dimensionless.
///
/// # Returns
///
/// Either [`ComputeBackend::Serial`] or [`ComputeBackend::CpuMulti`]; never
/// [`ComputeBackend::Gpu`], because no GPU kernel exists here.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::ode::parallel::{ensemble_backend_for, ODE_ENSEMBLE_MIN_LANES};
///
/// // Too small to thread, whatever was asked for.
/// assert_eq!(ensemble_backend_for(ComputeBackend::CpuMulti, 4), ComputeBackend::Serial);
///
/// // Big enough; the answer now depends only on whether `parallel` is compiled in.
/// let picked = ensemble_backend_for(ComputeBackend::CpuMulti, ODE_ENSEMBLE_MIN_LANES);
/// assert!(picked.is_available());
/// ```
/// The [`ComputeBackend`] the quadrature kernels would actually use for `n`
/// intervals if asked for `requested` — without running anything.
///
/// The quadrature counterpart of [`ensemble_backend_for`], differing only in
/// using the [`QUADRATURE_MIN_INTERVALS`] size floor. Both
/// [`quadrature_batch`] and [`adaptive_quadrature_batch`] use it.
///
/// # Arguments
///
/// - `requested` — the backend a caller would pass to [`quadrature_batch`].
/// - `n` — the number of independent definite integrals, dimensionless.
///
/// # Returns
///
/// Either [`ComputeBackend::Serial`] or [`ComputeBackend::CpuMulti`].
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::ode::parallel::quadrature_backend_for;
///
/// assert_eq!(quadrature_backend_for(ComputeBackend::CpuMulti, 8), ComputeBackend::Serial);
/// assert_eq!(quadrature_backend_for(ComputeBackend::Serial, 1 << 20), ComputeBackend::Serial);
/// ```
// ═════════════════════════════════════════════════════════════════════════════
// Part A — ODE ensembles
// ═════════════════════════════════════════════════════════════════════════════
/// One member of an ODE ensemble: a system, its initial condition, and the
/// interval to advance it over.
///
/// The system is owned **by value**, so an ensemble is a plain
/// `Vec<OdeLane<S>>` with no lifetime parameter anywhere and no possibility of
/// the system slice and the initial-condition slice disagreeing in length. `S`
/// may be any concrete type implementing [`OdeSystem`], including the caller's
/// own enum over several systems — which is how one ensemble holds genuinely
/// different physics in different lanes.
///
/// # Units
///
/// `x_start`, `x_end` and `dx0` are in the independent variable's units
/// (typically seconds); `y0`'s components are in whatever units that lane's
/// state carries, which need not be the same as each other. All are the
/// caller's own units — see the module-level "Units" section.
///
/// # Validity
///
/// A lane is rejected with [`OdeLaneStatus::InvalidLane`], before any
/// integration, unless all of the following hold:
///
/// - `y0.len() == system.n_eqns()`
/// - `x_start`, `x_end` and every component of `y0` are finite
/// - `dx0` is finite and strictly positive
/// - `x_end >= x_start` — **the underlying interval loop integrates forwards
/// only**, so a reversed interval is a caller error rather than a backwards
/// integration
///
/// `x_end == x_start` is legal and is a no-op: the lane completes in zero steps
/// with its state unchanged.
/// How one lane of an ODE ensemble ended.
///
/// Only [`Completed`](Self::Completed) means the lane reached `x_end`. Every
/// other variant is a failure a caller must handle; see the module-level
/// "Non-convergence is reported, never swallowed" section for the accessors that
/// make it hard to skip.
///
/// | Variant | `last_state` | Meaning |
/// |---|---|---|
/// | [`Completed`](Self::Completed) | the state at `x_end` | reached the end of the interval |
/// | [`MaxStepsExceeded`](Self::MaxStepsExceeded) | genuine partial state at `x_reached` — **not** the answer | ran out of sub-steps |
/// | [`StepSizeUnderflow`](Self::StepSizeUnderflow) | genuine partial state at `x_reached` | the step shrank below `f64::EPSILON` |
/// | [`NotFinite`](Self::NotFinite) | the non-finite state | the state went `NaN`/infinite |
/// | [`InvalidLane`](Self::InvalidLane) | all `NaN` | the lane's inputs were unusable |
///
/// The two middle variants are the *stiffness signature*: an explicit stepper on
/// a stiff lane runs out of budget rather than returning a wrong answer.
///
/// # Units
///
/// Dimensionless — a status tag.
/// The outcome of a single ensemble lane: its status, its final state, how far
/// it got and how much work it took.
///
/// The fields are private on purpose. The only way to get a state that is
/// claimed to be the answer is [`Self::state`], which returns `Option<&[f64]>`
/// and hands back `Some` only for a completed lane. The raw state is available
/// from [`Self::last_state`], whose name is chosen so that using a failed lane's
/// partial trajectory is a visible decision in the calling code.
///
/// # Units
///
/// [`Self::state`] and [`Self::last_state`] carry the lane's own state units;
/// [`Self::x_reached`] and [`Self::dx_final`] are in the independent variable's
/// units; [`Self::steps`] is a dimensionless count.
/// A batch of `N` lane outcomes, in the same order as the lanes handed in.
///
/// Lane `i` of the result corresponds to `lanes[i]`, always — the parallel path
/// preserves order, so no index bookkeeping is needed.
///
/// # Getting states out
///
/// - [`Self::states`] / [`Self::into_states`] — all-or-nothing. `Ok` only when
/// every lane completed; otherwise `Err(`[`OdeEnsembleFailure`]`)`.
/// - [`Self::lanes`] — per-lane, when the caller wants to handle failures
/// individually (re-run stiff, sub-cycle, flag the cell).
///
/// # Units
///
/// See [`OdeLaneSolution`].
/// One or more lanes of an [`OdeEnsemble`] did not complete.
///
/// Returned by [`OdeEnsemble::states`]. 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
/// cells failed" is only actionable once you know *which* cell and *how far* it
/// got.
///
/// # Units
///
/// Counts and indices are dimensionless; `first_x_reached` is in the independent
/// variable's units.
// ── ODE ensemble entry points ────────────────────────────────────────────────
/// Integrate `N` independent initial-value problems with **one stepper for every
/// lane**, on the chosen backend.
///
/// This is the entry point for the common case: one ODE per cell, per particle,
/// or per material point, all of the same character. Each lane gets its own
/// clone of `solver`, so no scratch buffer is shared and no lane can perturb
/// another.
///
/// For an ensemble of mixed stiffness, use [`integrate_ensemble_mixed`] — see
/// the module-level "Stiffness" section.
///
/// # Arguments
///
/// - `lanes` — one [`OdeLane`] per problem. Lane `i` of the result corresponds
/// to `lanes[i]`.
/// - `solver` — the stepper prototype, cloned once per lane. Its
/// [`OdeSolverConfig`](crate::ode::OdeSolverConfig) tolerances and
/// `max_steps` apply to every lane. It must have been built for the same
/// equation count the lanes' systems report, because the steppers size their
/// scratch buffers at construction.
/// - `backend` — requested execution backend. What actually runs is
/// [`ensemble_backend_for`] applied to it: an unavailable backend degrades,
/// `Gpu` degrades (no GPU kernel here), and an ensemble below
/// [`ODE_ENSEMBLE_MIN_LANES`] runs serially. None of those changes the answer.
///
/// # Returns
///
/// An [`OdeEnsemble`] with one [`OdeLaneSolution`] per lane, in input order.
///
/// # Determinism
///
/// Bit-for-bit identical across backends and thread counts, for systems whose
/// `derivatives`/`jacobian` are pure deterministic functions of their arguments.
/// See the module-level "Determinism" section.
///
/// # Cost note
///
/// `solver` is cloned once per lane, which clones its per-equation scratch
/// buffers — a handful of small allocations per lane. This is deliberate: it is
/// what makes each lane a pure function of its own inputs, and therefore what
/// makes the bitwise-identity claim hold without depending on every stepper's
/// buffers being write-before-read. On the measured ensemble it is a small
/// fraction of the per-lane cost — about 8.6 us of integration per lane over 68
/// adaptive steps, see [`ODE_ENSEMBLE_MIN_LANES`] — but a caller integrating a
/// *very* short interval per lane would see it, and it has not been measured
/// separately from the integration it accompanies.
///
/// # Panics
///
/// Panics if `solver` is [`OdeSolver::Rosenbrock23`] and a lane's system does
/// not override
/// [`OdeSystem::jacobian`](crate::ode::OdeSystem::jacobian), whose default
/// implementation panics. On the `CpuMulti` path the panic propagates out of the
/// `rayon` scope. Check
/// [`OdeSolver::requires_jacobian`](crate::ode::OdeSolver::requires_jacobian)
/// first.
///
/// # Verification
///
/// *Methodology.* Checked against the closed-form solution of `dy/dx = -k y`,
/// `y(0) = 1`, namely `y(x) = exp(-k x)`, over 64 lanes with `k` spread evenly
/// across `[0.5, 8]`, integrated to `x = 1` by all three steppers; and against
/// the harmonic oscillator `y1' = -y2`, `y2' = y1` from `y(0) = (1, 0)`, whose
/// solution is `(cos x, sin x)`, over 16 lanes ending at `m * pi/2` for
/// `m = 1..=16`. Tolerances `abs_tol = 1e-10`, `rel_tol = 1e-8` for `Rkf45` and
/// `Rosenbrock23` (`1e-12` / `1e-10` for the oscillator) and `1e-3` / `1e-2`
/// for `Euler`, which cannot reach the high-order tolerances inside the default
/// 10 000-step budget. Pass criteria: `< 1e-8` for the high-order steppers,
/// `< 5e-2` for first-order `Euler`.
///
/// *Results, measured 2026-08-13 by `ensemble_matches_analytic_decay` and
/// `ensemble_matches_harmonic_oscillator` in `parallel/tests.rs`, release
/// build:* worst absolute error over the 64 decay lanes **1.518896e-9**
/// (`Rkf45`, 3 038 total accepted steps, 81 in the worst lane),
/// **1.387431e-9** (`Rosenbrock23`, 46 535 steps, 1 186 in the worst lane) and
/// **1.297370e-3** (`Euler`, 21 817 steps, 421 in the worst lane); worst
/// absolute error on the oscillator **4.905929e-10** (`Rkf45`).
///
/// *Interpretation.* The two high-order steppers agree with the closed form to
/// their requested tolerance and with each other to about 1e-9, while Euler is
/// six orders coarser — the expected signature of three genuinely different
/// steppers being reached through the ensemble, which is what rules out the
/// wrapper silently routing every lane to one of them. The step counts are the
/// other half of the story: `Rosenbrock23` needs 15x the steps of `Rkf45` on a
/// non-stiff problem to reach the same accuracy, which is exactly why
/// [`integrate_ensemble_mixed`] exists rather than "just use the stiff solver
/// everywhere".
///
/// # Example — the `uom` boundary
///
/// The ensemble is dimensionless, and the caller converts at its edge. These
/// lanes are lumped-capacitance bodies cooling towards ambient, `dT/dt =
/// -(T - T_inf) / tau`, one lane per time constant, recovering a
/// `ThermodynamicTemperature`.
///
/// **On the tolerance asserted below.** The stepper's `rel_tol` is `1e-8` and
/// the states are of order 400 K, so the achievable *absolute* accuracy is a
/// few microkelvin — the error floor is set by the controller's tolerance and
/// the magnitude of the state, not by the ensemble. Measured 2026-08-13
/// (release) by `lumped_body_accuracy_is_set_by_the_relative_tolerance` in
/// `parallel/tests.rs`: worst absolute error **1.150937e-6 K** at
/// `abs_tol = 1e-10`, `rel_tol = 1e-8`; **1.222958e-8 K** at `1e-12`/`1e-10`;
/// **1.289209e-10 K** at `1e-14`/`1e-12`. The bound below is `5e-6 K`, set from
/// the first of those measurements — a tighter assertion would be asserting
/// something this stepper at this tolerance does not deliver. A caller wanting
/// sub-nanokelvin must ask for it through the tolerances, and the third row
/// says what that buys.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::ode::{OdeSolver, OdeSystem};
/// use outram_foam_basic_lib::ode::parallel::{integrate_ensemble, OdeLane};
/// use uom::si::f64::{ThermodynamicTemperature, Time};
/// use uom::si::thermodynamic_temperature::kelvin;
/// use uom::si::time::second;
///
/// /// Lumped body: `dT/dt = -(T - T_inf) / tau`, all in SI base units.
/// struct LumpedBody { tau_s: f64, t_inf_k: f64 }
/// impl OdeSystem for LumpedBody {
/// fn n_eqns(&self) -> usize { 1 }
/// fn derivatives(&self, _t: f64, y: &[f64], dydt: &mut Vec<f64>) {
/// dydt[0] = -(y[0] - self.t_inf_k) / self.tau_s;
/// }
/// }
///
/// // Convert in: typed quantities out to plain f64 in named units.
/// let t_inf = ThermodynamicTemperature::new::<kelvin>(300.0);
/// let t0 = ThermodynamicTemperature::new::<kelvin>(500.0);
/// let horizon = Time::new::<second>(10.0);
///
/// let lanes: Vec<OdeLane<LumpedBody>> = [5.0_f64, 20.0]
/// .iter()
/// .map(|&tau| {
/// OdeLane::new(
/// LumpedBody { tau_s: tau, t_inf_k: t_inf.get::<kelvin>() },
/// vec![t0.get::<kelvin>()],
/// 0.0,
/// horizon.get::<second>(),
/// 0.1,
/// )
/// })
/// .collect();
///
/// let ensemble = integrate_ensemble(
/// &lanes,
/// &OdeSolver::rkf45(1, 1e-10, 1e-8),
/// ComputeBackend::CpuMulti,
/// );
///
/// // Convert out: back to typed temperatures.
/// let temperatures: Vec<ThermodynamicTemperature> = ensemble
/// .states()
/// .expect("both lanes complete")
/// .iter()
/// .map(|s| ThermodynamicTemperature::new::<kelvin>(s[0]))
/// .collect();
///
/// // Closed form: T(t) = T_inf + (T0 - T_inf) exp(-t / tau). The 5e-6 K bound
/// // is the measured floor at rel_tol = 1e-8 on a ~400 K state; see above.
/// for (tau, temperature) in [5.0_f64, 20.0].iter().zip(&temperatures) {
/// let exact = 300.0 + 200.0 * (-10.0_f64 / tau).exp();
/// assert!((temperature.get::<kelvin>() - exact).abs() < 5e-6);
/// }
/// ```
/// Integrate `N` independent initial-value problems with the **stepper chosen
/// per lane**, on the chosen backend.
///
/// The mixed-stiffness entry point. `solver_of(i)` is called once for lane `i`
/// and its return value integrates that lane and no other, so a caller can put
/// [`Rosenbrock23`](crate::ode::Rosenbrock23) on the handful of stiff cells and
/// leave the rest on [`Rkf45`](crate::ode::Rkf45) — paying the LU factorisation
/// only where it is needed.
///
/// The natural way to use it is as a second pass: run
/// [`integrate_ensemble`] with an explicit stepper, read
/// [`OdeEnsemble::failures`], and re-run just those lanes stiff.
///
/// # Arguments
///
/// - `lanes` — one [`OdeLane`] per problem.
/// - `solver_of` — `solver_of(i)` returns the stepper for lane `i`. Called
/// exactly once per lane, on whichever thread runs that lane, hence the `Sync`
/// bound; the bound is present in both feature builds so that enabling
/// `parallel` never changes a public signature. It must be a pure
/// deterministic function of `i` — see the module-level "Determinism" section.
/// - `backend` — requested backend; see [`ensemble_backend_for`].
///
/// # Returns
///
/// An [`OdeEnsemble`] with one [`OdeLaneSolution`] per lane, in input order.
///
/// # Panics
///
/// As [`integrate_ensemble`]: a lane given
/// [`OdeSolver::Rosenbrock23`] whose system does not implement
/// [`OdeSystem::jacobian`](crate::ode::OdeSystem::jacobian) panics.
///
/// # Example — a stiff lane and a benign one in one ensemble
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::matrix::SquareMatrix;
/// use outram_foam_basic_lib::ode::{OdeSolver, OdeSystem};
/// use outram_foam_basic_lib::ode::parallel::{integrate_ensemble_mixed, OdeLane};
///
/// /// `dy/dx = -k y`, with an analytic Jacobian so the stiff stepper can run.
/// struct Decay { k: f64 }
/// impl OdeSystem for Decay {
/// fn n_eqns(&self) -> usize { 1 }
/// fn derivatives(&self, _x: f64, y: &[f64], d: &mut Vec<f64>) { d[0] = -self.k * y[0]; }
/// fn jacobian(&self, _x: f64, _y: &[f64], dfdx: &mut Vec<f64>, dfdy: &mut SquareMatrix) {
/// dfdx[0] = 0.0;
/// dfdy.set(0, 0, -self.k);
/// }
/// }
///
/// // Lane 0 is benign (k = 1), lane 1 is stiff (k = 5000).
/// let lanes = vec![
/// OdeLane::new(Decay { k: 1.0 }, vec![1.0], 0.0, 1.0, 0.1),
/// OdeLane::new(Decay { k: 5000.0 }, vec![1.0], 0.0, 1.0, 0.1),
/// ];
///
/// let ensemble = integrate_ensemble_mixed(
/// &lanes,
/// |i| {
/// if i == 1 {
/// OdeSolver::rosenbrock23(1, 1e-10, 1e-8)
/// } else {
/// OdeSolver::rkf45(1, 1e-10, 1e-8)
/// }
/// },
/// ComputeBackend::Serial,
/// );
///
/// assert!(ensemble.all_completed());
/// let states = ensemble.states().unwrap();
/// assert!((states[0][0] - (-1.0_f64).exp()).abs() < 1e-8);
/// assert!(states[1][0].abs() < 1e-8); // exp(-5000) underflows to ~0
/// ```
/// [`integrate_ensemble_mixed`] with the size floor supplied by the caller.
///
/// Exists so the crossover benchmark can measure the multi-CPU path *below*
/// [`ODE_ENSEMBLE_MIN_LANES`] — the only way to find where the crossover
/// actually is — and so the cross-backend bitwise tests are not vacuous on small
/// ensembles. Not public: production callers get the measured floor.
pub
/// Integrate one lane — the single per-lane kernel both backends call.
///
/// Drives the crate's existing [`OdeSolver::solve_step`] through the crate's
/// existing `integrate_interval` loop, wrapping the step closure only to count
/// accepted steps and record how far the trajectory actually got. No integration
/// arithmetic is duplicated here.
// ═════════════════════════════════════════════════════════════════════════════
// Part B — batched quadrature
// ═════════════════════════════════════════════════════════════════════════════
/// One lane of a quadrature batch: the limits of one definite integral.
///
/// # Units
///
/// `a` and `b` are in the integration variable's units. The value the batch
/// returns carries the product of those units and the integrand's.
///
/// # Conventions
///
/// - `a == b` integrates to exactly `0.0`, with no integrand evaluations.
/// - `b < a` is **supported** and returns the negated integral over `[b, a]`,
/// the usual orientation convention. (The ODE half deliberately does *not*
/// accept a reversed interval, because its underlying loop marches forwards
/// only; quadrature has no such constraint.)
/// - A non-finite `a` or `b` yields [`QuadratureStatus::InvalidInterval`]. There
/// is no support for infinite limits; a caller wanting one should substitute
/// the variable itself, which is the only way to choose the transformation
/// knowingly.
/// Node count of a fixed-order Gauss-Legendre rule.
///
/// A closed set rather than an open `usize`, so the choice is exhaustive at
/// every match site and rust-analyzer lists the options on hover — and so the
/// nodes can be validated once per order rather than for whatever number a
/// caller happens to pass.
///
/// An `n`-point Gauss-Legendre rule integrates any polynomial of degree
/// `2n - 1` or less **exactly** (to rounding), which is both the reason to
/// prefer it over Simpson at equal cost and the property the tests use as their
/// oracle.
///
/// | Order | Nodes | Exact to degree |
/// |---|---|---|
/// | [`G2`](Self::G2) | 2 | 3 |
/// | [`G3`](Self::G3) | 3 | 5 |
/// | [`G4`](Self::G4) | 4 | 7 |
/// | [`G5`](Self::G5) | 5 | 9 |
/// | [`G8`](Self::G8) | 8 | 15 |
///
/// # Units
///
/// Dimensionless — a mode selector.
/// Which fixed rule [`quadrature_batch`] applies to every lane.
///
/// All three are **composite** rules over equal subintervals of each lane's own
/// interval, and all three cost a fixed, data-independent number of integrand
/// evaluations per lane — which is what makes them branch-free, and the only
/// part of this module that would map cleanly onto a GPU.
///
/// A `panels` count of `0` is treated as `1`; there is no error path for it,
/// because it is a compile-time-shaped parameter rather than data.
///
/// | Variant | Evaluations per lane | Error order | Exact for |
/// |---|---|---|---|
/// | [`Trapezoid`](Self::Trapezoid) | `panels + 1` | `O(h^2)` | linear integrands |
/// | [`Simpson`](Self::Simpson) | `2 * panels + 1` | `O(h^4)` | cubics |
/// | [`GaussLegendre`](Self::GaussLegendre) | `panels * order` | `O(h^(2n))` | degree `2n - 1` |
///
/// # Relationship to the workspace's other Simpson
///
/// `outram-park-fork-dwsim-libs`'s `simpson_integrate` is a faithful port of
/// OPEM's rule *including* its documented flaw: it applies the `1, 4, 2, ..., 4,
/// 1` weights without requiring an odd sample count, which silently degrades the
/// order to `O(h)` for an even one. [`Simpson`](Self::Simpson) here counts
/// **panels of two subintervals each**, so the sample count is odd by
/// construction and that failure cannot occur. The composite-over-equal-
/// subintervals convention is shared; the sample-slice interface and the bug are
/// not.
///
/// # Units
///
/// Dimensionless — a mode selector plus a count.
/// `panels`, floored at 1 — the one place the "`0` means `1`" convention lives.
const
/// Tolerances and work limit for [`adaptive_quadrature_batch`].
///
/// # Units
///
/// `abs_tol` is in the units of the *integral* (integrand times abscissa);
/// `rel_tol` is a dimensionless ratio; `max_subdivisions` is a count.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::ode::parallel::AdaptiveSettings;
///
/// // Struct-update syntax keeps the defaults you did not mean to change.
/// let s = AdaptiveSettings { abs_tol: 1e-12, ..AdaptiveSettings::default() };
/// assert_eq!(s.rel_tol, 1e-8);
/// ```
/// How one lane of a quadrature batch ended.
///
/// | Variant | `last_value` | Meaning |
/// |---|---|---|
/// | [`Evaluated`](Self::Evaluated) | the integral | the rule ran to completion |
/// | [`ToleranceNotMet`](Self::ToleranceNotMet) | best estimate — **not** to tolerance | adaptive lane ran out of subdivisions |
/// | [`NotFinite`](Self::NotFinite) | `NaN` | the accumulated value was `NaN` or infinite |
/// | [`InvalidInterval`](Self::InvalidInterval) | `NaN` | a limit is not finite |
///
/// # What `Evaluated` does and does not claim
///
/// For [`adaptive_quadrature_batch`] it means the requested tolerance was met.
/// For a fixed [`QuadratureRule`] it means only that every node evaluated to a
/// finite number and the sum is finite — **it makes no accuracy claim at all**,
/// because a fixed rule has no way to know. Choosing enough panels for the
/// integrand is the caller's responsibility, and
/// [`QuadratureSolution::error_estimate`] is `NaN` on that path for exactly this
/// reason.
///
/// # Units
///
/// Dimensionless — a status tag.
/// The outcome of a single quadrature lane.
///
/// The fields are private on purpose, on the same reasoning as
/// [`OdeLaneSolution`]: [`Self::value`] returns `Option<f64>` and hands back
/// `Some` only for a lane that ran to completion, while the raw number is behind
/// the deliberately-named [`Self::last_value`].
///
/// `Copy`, so it can be read out of a [`QuadratureBatch`] without cloning.
///
/// # Units
///
/// [`Self::value`], [`Self::last_value`] and [`Self::error_estimate`] are in the
/// integral's units (integrand times abscissa); [`Self::evaluations`] is a
/// dimensionless count.
/// A batch of `N` quadrature outcomes, in the same order as the intervals handed
/// in.
///
/// Lane `i` of the result corresponds to `intervals[i]`, always — the parallel
/// path preserves order.
///
/// # Getting values out
///
/// - [`Self::values`] — all-or-nothing. `Ok(Vec<f64>)` only when every lane ran
/// to completion; otherwise `Err(`[`QuadratureBatchFailure`]`)`.
/// - [`Self::solutions`] — per-lane, when the caller wants to handle failures
/// individually.
///
/// # Units
///
/// See [`QuadratureSolution`].
/// One or more lanes of a [`QuadratureBatch`] failed.
///
/// Returned by [`QuadratureBatch::values`]. As [`OdeEnsembleFailure`], it names
/// both the scale of the problem and a specific lane to look at.
///
/// # Units
///
/// All counts and indices are dimensionless.
// ── Quadrature entry points ──────────────────────────────────────────────────
/// Evaluate `N` independent definite integrals with a **fixed rule**, on the
/// chosen backend.
///
/// The GPU-shaped half of this module: every lane performs exactly
/// [`QuadratureRule::evaluations`] integrand calls with no data-dependent
/// branching. Use it when the integrand is smooth and the panel count can be
/// chosen once for the whole batch — a band-averaged cross section, a
/// face-integrated flux, a cell-integrated source term.
///
/// # Arguments
///
/// - `intervals` — one [`QuadratureInterval`] per lane.
/// - `rule` — the rule applied to every lane. [`QuadratureRule::GaussLegendre`]
/// is the default worth reaching for on a smooth integrand.
/// - `backend` — requested backend. What actually runs is
/// [`quadrature_backend_for`] applied to it; a batch below
/// [`QUADRATURE_MIN_INTERVALS`] runs serially. None of the degradations
/// changes the answer.
/// - `f` — the integrand. `f(i, x)` must return lane `i`'s integrand at abscissa
/// `x`. It **must be a pure deterministic function of its arguments** — see
/// the module-level "Determinism" section. It is called from multiple threads
/// on the `CpuMulti` path, hence the `Sync` bound; the bound is present in
/// both feature builds so that enabling `parallel` never changes a public
/// signature.
///
/// # Returns
///
/// A [`QuadratureBatch`] with one [`QuadratureSolution`] per interval, in input
/// order.
///
/// # Determinism
///
/// Bit-for-bit identical across backends and thread counts. The sum within a
/// lane is sequential and is never split across threads — see the module-level
/// "Determinism" section for why that restriction is deliberate.
///
/// # Verification
///
/// *Methodology.* Three oracles, all exact rather than another implementation.
/// (1) *Polynomial exactness*: an `n`-point Gauss-Legendre rule must integrate
/// every monomial `x^d` for `d <= 2n - 1` exactly, Simpson must be exact for
/// `d <= 3` and trapezoid for `d <= 1`; checked over `[0, 1]` and `[-2, 3]`
/// against the closed form `(b^(d+1) - a^(d+1)) / (d + 1)`. (2) *Published
/// nodes*: the computed 8-point nodes and weights against the Abramowitz &
/// Stegun 25.4.30 values already carried in this workspace by
/// `crates/raffles/src/distributions.rs`. (3) *Transcendental reference*:
/// `integral of exp(-x) sin(x) from 0 to pi = (1 + exp(-pi)) / 2`. Pass
/// criteria: `< 1e-13` relative for exactness, `< 1e-15` absolute against A&S,
/// `< 1e-12` absolute for the transcendental.
///
/// *Results, measured 2026-08-13 by `gauss_legendre_is_exact_to_its_degree`,
/// `gauss_nodes_match_the_in_workspace_abramowitz_stegun_values`,
/// `simpson_and_trapezoid_are_exact_to_their_degree` and
/// `fixed_rules_match_a_transcendental_reference` in `parallel/tests.rs`,
/// release build:*
///
/// - Exactness sweep (`G2`..`G8`, degrees 0 to 15, both intervals): worst
/// relative error **5.769990e-16**. Simpson over degrees 0 to 3:
/// **3.552714e-16**. Trapezoid over degrees 0 to 1: **0.000000e0**.
/// - Computed `G8` against A&S 25.4.30: worst node difference
/// **1.110223e-16**, worst weight difference **1.249001e-16**, weights
/// summing to **2.00000000000000000**.
/// - Transcendental reference, closed form **0.52160695913188615**: `G8` over 8
/// panels (64 evaluations) gave **0.52160695913188615**, error
/// **0.000000e0**; Simpson over 64 panels (129 evaluations) error
/// **4.206809e-9**; trapezoid over 128 panels (129 evaluations) error
/// **5.236767e-5**.
///
/// *Interpretation.* The Gauss nodes and weights are correct to the last bit
/// `f64` holds — agreeing with a published table to within one unit in the last
/// place while being computed independently of it — the composite mapping onto
/// arbitrary intervals is correct, and the order hierarchy behaves as theory
/// requires: `G8` reaches the rounding floor on a smooth transcendental at half
/// the evaluations where a 64-panel Simpson is still nine orders away and a
/// trapezoid four orders beyond that.
///
/// # Example — the `uom` boundary
///
/// The batch is dimensionless, and the caller converts at its edge. These lanes
/// integrate a linearly-ramping electrical power over time to recover an
/// `Energy`:
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::ode::parallel::{
/// quadrature_batch, GaussOrder, QuadratureInterval, QuadratureRule,
/// };
/// use uom::si::f64::{Energy, Power, Time};
/// use uom::si::energy::joule;
/// use uom::si::power::watt;
/// use uom::si::time::second;
///
/// // P(t) = P0 (1 - t / T), shutting down linearly over the window.
/// let p0 = Power::new::<watt>(2.0e6);
/// let window = Time::new::<second>(30.0);
///
/// // Convert in: limits in seconds, as plain f64.
/// let intervals = [
/// QuadratureInterval::new(0.0, window.get::<second>()),
/// QuadratureInterval::new(0.0, 0.5 * window.get::<second>()),
/// ];
///
/// let batch = quadrature_batch(
/// &intervals,
/// QuadratureRule::GaussLegendre { order: GaussOrder::G4, panels: 4 },
/// ComputeBackend::CpuMulti,
/// |_, t| p0.get::<watt>() * (1.0 - t / window.get::<second>()),
/// );
///
/// // Convert out: back to typed energies.
/// let energies: Vec<Energy> = batch
/// .values()
/// .expect("both lanes evaluate")
/// .into_iter()
/// .map(Energy::new::<joule>)
/// .collect();
///
/// // Closed form over [0, T] is P0 T / 2; over [0, T/2] it is 3 P0 T / 8.
/// assert!((energies[0].get::<joule>() - 0.5 * 2.0e6 * 30.0).abs() < 1e-6);
/// assert!((energies[1].get::<joule>() - 0.375 * 2.0e6 * 30.0).abs() < 1e-6);
/// ```
/// [`quadrature_batch`] with the size floor supplied by the caller; see
/// [`integrate_ensemble_min`] for why the `_min` variants exist.
pub
/// Evaluate `N` independent definite integrals **adaptively**, on the chosen
/// backend.
///
/// Adaptive Simpson with local error control: each lane bisects wherever the
/// integrand resists a Simpson panel, and stops where it does not. Use it when
/// the integrand's difficulty is not known in advance, or differs between lanes,
/// or is concentrated in a small part of the interval — a peak in a resonance
/// integral, a boundary layer, a kink at a phase boundary.
///
/// # Why this path is CPU-only, and stays so
///
/// The subdivision pattern is decided by the integrand at run time, so
/// neighbouring lanes take different branches and perform different numbers of
/// evaluations. That is exactly the control-flow divergence SIMT hardware
/// handles worst — a GPU implementation would serialise the divergent branches
/// and need a per-lane work stack in device memory. Batching it across CPU cores
/// costs nothing and works; putting it on a GPU would be a large amount of code
/// for an unclear win. **It is deliberately CPU-only**, and this is the reason.
///
/// The CPU path is still fully hybrid: it takes a [`ComputeBackend`] and threads
/// across lanes exactly like every other kernel here.
///
/// # Arguments
///
/// - `intervals` — one [`QuadratureInterval`] per lane.
/// - `settings` — tolerances and the subdivision budget; see
/// [`AdaptiveSettings`].
/// - `backend` — requested backend; see [`quadrature_backend_for`]. The
/// [`QUADRATURE_MIN_INTERVALS`] floor is shared with [`quadrature_batch`] and
/// was measured on that path, so it is a conservative assumption here rather
/// than a measurement.
/// - `f` — the integrand, `f(i, x)`. Must be pure and deterministic; called from
/// multiple threads on the `CpuMulti` path.
///
/// # Returns
///
/// A [`QuadratureBatch`]. A lane that met its tolerance reports
/// [`QuadratureStatus::Evaluated`] and a meaningful
/// [`QuadratureSolution::error_estimate`]; a lane that exhausted its budget
/// reports [`QuadratureStatus::ToleranceNotMet`] and its best estimate, and is
/// excluded from [`QuadratureBatch::values`].
///
/// # Determinism
///
/// Bit-for-bit identical across backends and thread counts. The subdivision
/// order within a lane is a deterministic function of the integrand, and no
/// lane's arithmetic is split across threads.
///
/// # Verification
///
/// *Methodology.* Run against three integrands with closed forms, two of them
/// deliberately awkward for a uniform panel layout:
/// `integral of exp(-x) sin(x) from 0 to pi = (1 + exp(-pi)) / 2`;
/// `integral of sqrt(x) from 0 to 1 = 2/3`, which is bounded but has an
/// infinite derivative at the lower limit; and
/// `integral of 1 / (1 + 400 (x - 1/2)^2) from 0 to 1 = atan(10) / 10`, a peak
/// occupying about a twentieth of the interval. Tolerances `abs_tol = 1e-11`,
/// `rel_tol = 1e-10`, `max_subdivisions = 100 000`. Pass criteria: absolute
/// error below `1e-9`; every lane [`QuadratureStatus::Evaluated`]; and the
/// reported [`QuadratureSolution::error_estimate`] no more than 100x smaller
/// than the true error, since an estimate that badly understates the error
/// would be worse than none.
///
/// *Results, measured 2026-08-13 by `adaptive_matches_closed_forms` in
/// `parallel/tests.rs`, release build:*
///
/// | Integrand | Value | Error | Reported estimate | Evaluations |
/// |---|---|---|---|---|
/// | `exp(-x) sin(x)` on `[0, pi]` | 0.52160695913188759 | 1.443290e-15 | 2.034556e-11 | 469 |
/// | `sqrt(x)` on `[0, 1]` | 0.66666666666664931 | 1.731948e-14 | 2.619949e-11 | 1057 |
/// | narrow peak on `[0, 1]` | 0.14711276743037432 | 8.604228e-16 | 2.682116e-11 | 1225 |
///
/// *Interpretation.* All three land at or near the rounding floor, four to five
/// orders better than the requested `1e-11`, and the reported estimate is
/// conservative in every case — it overstates the true error by three to four
/// orders rather than understating it, which is the safe direction for an error
/// bound. The evaluation counts are the point of the adaptive path and the
/// source of the load imbalance work-stealing exists to absorb: 469 against
/// 1 225 for problems posed identically, a 2.6x spread decided entirely by the
/// integrand. `sqrt(x)` is the informative case — its infinite endpoint
/// derivative makes a uniform panel layout converge slowly, and the adaptive
/// path instead concentrates its subdivisions near `x = 0`.
///
/// # Limitations
///
/// **An integrand that is unbounded at an interval endpoint is not supported
/// here.** Adaptive Simpson evaluates `f(a)` and `f(b)` on its very first step,
/// so an integrable singularity sitting exactly on a limit — `ln(x)` or
/// `1/sqrt(x)` at `x = 0` — produces a non-finite first estimate and the lane
/// reports [`QuadratureStatus::NotFinite`]. This inverts the naive expectation
/// that the adaptive path is the more capable one: for an endpoint singularity
/// reach for [`quadrature_batch`] with
/// [`QuadratureRule::GaussLegendre`] instead, whose nodes are strictly interior
/// and never touch the limits. That is exactly the property `raffles` relies on
/// for its quantile-function moments. A singularity in the *interior* of the
/// interval is also not handled: it will exhaust the subdivision budget and
/// report [`QuadratureStatus::ToleranceNotMet`], which is at least honest.
///
/// # Example
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::ode::parallel::{
/// adaptive_quadrature_batch, AdaptiveSettings, QuadratureInterval,
/// };
///
/// // Three lanes of `integral of exp(-a x) from 0 to 1` = (1 - exp(-a)) / a.
/// let a = [1.0_f64, 5.0, 20.0];
/// let intervals: Vec<QuadratureInterval> =
/// (0..3).map(|_| QuadratureInterval::new(0.0, 1.0)).collect();
///
/// let batch = adaptive_quadrature_batch(
/// &intervals,
/// AdaptiveSettings::default(),
/// ComputeBackend::CpuMulti,
/// |i, x| (-a[i] * x).exp(),
/// );
///
/// for (i, v) in batch.values().expect("all lanes meet tolerance").iter().enumerate() {
/// let exact = (1.0 - (-a[i]).exp()) / a[i];
/// assert!((v - exact).abs() < 1e-10, "lane {i}: {v} vs {exact}");
/// }
/// ```
/// [`adaptive_quadrature_batch`] with the size floor supplied by the caller; see
/// [`integrate_ensemble_min`] for why the `_min` variants exist.
pub
// ── Per-lane quadrature kernels — one implementation, both backends ──────────
/// Sort a lane's limits and record the orientation sign.
///
/// Returns `Err(status)` when there is nothing to integrate: a non-finite limit,
/// or a zero-length interval (which is a *success* with value zero, handled by
/// the caller).
/// Evaluate one lane with a fixed rule — the per-lane kernel both backends call.
/// One pending sub-interval of the adaptive lane, held on an explicit stack.
///
/// An explicit stack rather than recursion so the depth is bounded by data the
/// kernel owns rather than by the thread's stack size — a `rayon` worker's stack
/// is not the caller's, and a pathological integrand must not be able to
/// overflow it.
/// Evaluate one lane adaptively — the per-lane kernel both backends call.
///
/// Adaptive Simpson: compare the Simpson estimate over `[a, b]` with the sum of
/// the estimates over its two halves; accept when they agree to the local
/// tolerance, with the Richardson correction `(S_2 - S_1) / 15` applied, and
/// bisect otherwise with the tolerance split between the halves.
// ── Gauss-Legendre nodes ─────────────────────────────────────────────────────
/// Nodes and weights of the `n`-point Gauss-Legendre rule on `[-1, 1]`, in
/// ascending node order.
///
/// **Computed, not transcribed.** The nodes are the roots of the Legendre
/// polynomial `P_n`, found by Newton iteration from the standard Chebyshev-like
/// initial guess `cos(pi (k - 1/4) / (n + 1/2))`, and the weights follow from
/// `w_k = 2 / ((1 - x_k^2) P_n'(x_k)^2)`. `P_n` and `P_n'` come from Bonnet's
/// recurrence. Computing them rather than copying a printed table means the
/// values are correct to the last bit `f64` can hold at any order, with no
/// transcription to get wrong and no literature dependency to record; the
/// exactness property of the rule (degree `2n - 1`) is then a complete
/// self-check, and is what `gauss_legendre_is_exact_to_its_degree` asserts.
///
/// The result is deterministic — the same nodes on every call and every thread —
/// so sharing one table across a batch's lanes cannot change any lane's value.
///
/// # Units
///
/// Dimensionless: nodes on `[-1, 1]`, weights summing to 2.
/// `P_n(x)` and `P_n'(x)` by Bonnet's recurrence.
///
/// `P_0 = 1`, `P_1 = x`, `j P_j = (2j - 1) x P_(j-1) - (j - 1) P_(j-2)`, and
/// `P_n'(x) = n (x P_n - P_(n-1)) / (x^2 - 1)`. Valid for `|x| < 1`, which is
/// where every Gauss node lies.