u-analytics 0.27.0

Statistical process control, process capability, Weibull reliability, change-point detection, measurement system analysis (Gage R&R), correlation, regression, distribution analysis, and hypothesis testing.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
//! The JSON wire contract shared by the C FFI and the WASM bindings.
//!
//! Both transports carry the *same* analyses, so they must carry the same
//! shapes. They did not: the X-bar/R chart answered `x_bar_cl` over the FFI and
//! `xbar_cl` over WASM, the P chart took `[inspected, defective]` over one and
//! `[defectives, size]` over the other, and only the WASM side reported point
//! indices, rule violations or an in-control verdict. A consumer moving between
//! the two rewrote its parsing; a consumer reading the P chart pair in the wrong
//! order got a plausible number that was wrong.
//!
//! The types and functions here are the single definition. A transport module is
//! a thin shell over them: it decodes its own input representation, calls one of
//! these, and encodes the result. Nothing in this module names `JsValue` or a raw
//! pointer, which is what lets both sides compile it.
//!
//! **Where the two shapes disagreed, the crate's own model decided.** The pair
//! order follows `PChart::add_sample(defectives, sample_size)`; the field names
//! follow the chart types; the richer per-point payload is kept because dropping
//! it would lose the index a caller needs to line a violation up with its input
//! row.

use serde::{Deserialize, Serialize};

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct XbarRChartDto {
    pub(crate) xbar_cl: f64,
    pub(crate) xbar_ucl: f64,
    pub(crate) xbar_lcl: f64,
    pub(crate) r_cl: f64,
    pub(crate) r_ucl: f64,
    pub(crate) r_lcl: f64,
    /// Short-term sigma implied by this chart (`R-bar / d2`). Feed it to
    /// `process_capability` as `sigma_within` -- it is the quantity a
    /// capability study needs and the one a flat measurement vector cannot
    /// carry.
    pub(crate) sigma_hat: f64,
    /// Degrees of freedom of `sigma_hat` -- `process_capability`'s
    /// `sigma_within_df`, for Cp/Cpk confidence intervals.
    pub(crate) sigma_hat_df: f64,
    pub(crate) xbar_points: Vec<ChartPointDto>,
    pub(crate) r_points: Vec<ChartPointDto>,
    pub(crate) in_control: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct ChartPointDto {
    pub(crate) index: usize,
    pub(crate) value: f64,
    pub(crate) violations: Vec<String>,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct PChartDto {
    pub(crate) p_bar: f64,
    pub(crate) points: Vec<AttributeChartPointDto>,
    pub(crate) in_control: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct AttributeChartPointDto {
    pub(crate) index: usize,
    pub(crate) value: f64,
    pub(crate) ucl: f64,
    pub(crate) cl: f64,
    pub(crate) lcl: f64,
    pub(crate) out_of_control: bool,
    /// Standardized value -- the scale on which every limit is +/-3, so zone
    /// run rules apply to charts whose limits vary with n.
    pub(crate) z: Option<f64>,
}

/// Known (Phase I) parameters an attributes chart can be given.
///
/// One type for all four charts, checked per chart: a key a chart does not
/// take is refused rather than ignored.
#[derive(Deserialize, Default, Debug)]
#[serde(deny_unknown_fields)]
pub(crate) struct AttributeStandardDto {
    #[serde(default)]
    pub(crate) p_bar: Option<f64>,
    #[serde(default)]
    pub(crate) u_bar: Option<f64>,
    #[serde(default)]
    pub(crate) phi: Option<f64>,
}

impl AttributeStandardDto {
    /// Refuses `forbidden` keys: `(name, present)`.
    pub(crate) fn refuse(&self, chart: &str, forbidden: &[(&str, bool)]) -> Result<(), WireError> {
        match forbidden.iter().find(|(_, present)| *present) {
            Some((name, _)) => Err(WireError::new(
                code::MALFORMED_INPUT,
                None,
                format!("options: {chart} does not take `{name}`"),
            )
            .about(name.to_string())),
            None => Ok(()),
        }
    }

    /// The Laney standard: both parts or neither.
    pub(crate) fn laney(
        &self,
        center: Option<f64>,
        center_name: &str,
    ) -> Result<Option<crate::spc::LaneyStandard>, WireError> {
        match (center, self.phi) {
            (Some(center), Some(phi)) => Ok(Some(crate::spc::LaneyStandard { center, phi })),
            (None, None) => Ok(None),
            // Named by the one that is missing.
            (Some(_), None) | (None, Some(_)) => Err(WireError::new(
                code::INVALID_OPTION,
                None,
                format!(
                    "options: `{center_name}` and `phi` are given together -- a Phase I \
                     standard fixes both, since phi scales the error about that centre"
                ),
            )
            .about(if center.is_some() {
                "phi".to_string()
            } else {
                center_name.to_string()
            })),
        }
    }
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct LaneyPChartDto {
    pub(crate) p_bar: f64,
    pub(crate) phi: f64,
    pub(crate) points: Vec<AttributeChartPointDto>,
}

/// Parse an optional `{ rules }` options object into a rule set.
///
/// `rules` is the name of a set (`"shewhart"`, `"western_electric"`,
/// `"nelson"`) or an array of test names -- the values `violations` reports.
/// Absent, `undefined`, `null` or an object without `rules` all mean the
/// default set, [`RuleSet::shewhart`](crate::spc::RuleSet::shewhart). Split out
/// from the binding so it can be exercised without a `JsValue`.
pub(crate) fn rules_from_json(
    options: Option<serde_json::Value>,
) -> Result<crate::spc::RuleSet, WireError> {
    use crate::spc::{RuleSet, ViolationType};

    const EXPECTED: &str = "rules: expected the name of a rule set or an array of rule names";

    let Some(value) = options else {
        return Ok(RuleSet::default());
    };
    if value.is_null() {
        return Ok(RuleSet::default());
    }
    let Some(names) = value.get("rules") else {
        return Ok(RuleSet::default());
    };
    if names.is_null() {
        return Ok(RuleSet::default());
    }
    if let Some(set) = names.as_str() {
        return RuleSet::named(set)
            .ok_or_else(|| WireError::unknown_option("rules", set, &RuleSet::NAMES));
    }
    let names = names
        .as_array()
        .ok_or_else(|| WireError::new(code::MALFORMED_INPUT, None, EXPECTED).about("rules"))?;
    let rule_names: Vec<&str> = ViolationType::ALL.iter().map(|v| v.name()).collect();

    let mut set = RuleSet::none();
    for name in names {
        let name = name
            .as_str()
            .ok_or_else(|| WireError::new(code::MALFORMED_INPUT, None, EXPECTED).about("rules"))?;
        // The names are the values `violations` reports.
        let rule = ViolationType::from_name(name)
            .ok_or_else(|| WireError::unknown_option("rules", name, &rule_names))?;
        set = set.with(rule);
    }
    Ok(set)
}

pub(crate) fn point_dtos(points: &[crate::spc::ChartPoint]) -> Vec<ChartPointDto> {
    points
        .iter()
        .map(|p| ChartPointDto {
            index: p.index,
            value: p.value,
            violations: p.violations.iter().map(|&v| v.name().to_owned()).collect(),
        })
        .collect()
}

/// Checks the matrix a subgroup chart takes and returns its subgroup size.
///
/// A ragged subgroup is refused by its row: the chart would skip it, and every
/// later point would then carry an index one short of the row it came from.
///
/// The supported subgroup range is not restated here. It used to be, as a
/// literal `2..=10` alongside the same literal in the constructor, so widening
/// the crate's factor tables left the binding rejecting sizes the crate had
/// just learned to handle -- a disagreement no test in either crate could see,
/// because each one was right about its own copy.
pub(crate) fn subgroup_size(subgroups: &[Vec<f64>]) -> Result<usize, WireError> {
    subgroups.first().map(Vec::len).ok_or_else(|| {
        WireError::too_few(
            "subgroups",
            1,
            0,
            "subgroups: at least one subgroup required",
        )
    })
}

/// A refused input, in the one shape every transport reports.
///
/// A consumer with a data grid has to tell its user *which* row to fix and
/// *why*, in its own words. Free text carries neither in a form a program can
/// use -- and a count that failed to deserialize carried no row at all -- so
/// every consumer ended up re-validating the rules the crate already enforces.
/// `code` is stable across releases; `message` is for people and may change.
#[derive(Serialize, Debug, Clone, PartialEq)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct WireError {
    /// Stable, machine-readable reason: the name of [`Self::reason`].
    pub(crate) code: &'static str,
    /// The reason as the table names it -- the refusal's declared fields.
    #[serde(skip)]
    #[cfg_attr(feature = "wasm", tsify(skip))]
    pub(crate) reason: Code,
    /// Position of the offending element in its input array, when there is one.
    pub(crate) index: Option<usize>,
    /// Name of the offending *option*, when the refusal is about one.
    ///
    /// `index` says where in the data; this says which knob. Without it the
    /// name lives only in `message`, which is the one field documented as free
    /// to change -- so a consumer wanting to point at the setting has to parse
    /// prose, or re-derive the rule itself.
    pub(crate) parameter: Option<std::borrow::Cow<'static, str>>,
    /// Human-readable description.
    pub(crate) message: String,
    /// The values behind the reason, by name: `min` / `max` (inclusive
    /// bounds, `null` on an unbounded or open side), `exclusive_min` /
    /// `exclusive_max` (only on an open side) and `got` for a value out of
    /// range, `got` and `expected`
    /// for an unknown option name, `min` and `got` for too few values. Set
    /// as properties next to `code` on the WebAssembly `Error`, and as keys
    /// next to `code` in the C error body.
    #[serde(skip)]
    pub(crate) details: Vec<(&'static str, Detail)>,
}

/// A value carried in [`WireError::details`].
#[derive(Debug, Clone, PartialEq)]
pub(crate) enum Detail {
    Num(f64),
    Text(String),
    List(Vec<&'static str>),
    Null,
}

impl Detail {
    /// The value as JSON — the C error body's rendering.
    #[cfg(feature = "ffi")]
    pub(crate) fn to_json(&self) -> serde_json::Value {
        match self {
            Detail::Num(n) => serde_json::json!(n),
            Detail::Text(s) => serde_json::json!(s),
            Detail::List(v) => serde_json::json!(v),
            Detail::Null => serde_json::Value::Null,
        }
    }
}

/// One end of the range a number must fall in.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) enum Bound {
    /// The bound itself is accepted: sent as `min` / `max`.
    Closed(f64),
    /// The bound itself is refused: sent as `exclusive_min` / `exclusive_max`,
    /// with `min` / `max` `null`.
    Open(f64),
    /// No limit on this side: `min` / `max` `null`.
    Unbounded,
}

impl Bound {
    /// The end a public error type states as an inclusive / exclusive pair.
    pub(crate) fn from_pair(inclusive: Option<f64>, exclusive: Option<f64>) -> Self {
        match (inclusive, exclusive) {
            (Some(v), _) => Bound::Closed(v),
            (None, Some(v)) => Bound::Open(v),
            (None, None) => Bound::Unbounded,
        }
    }
}

/// Whether `v` lies in `low`..`high` (a NaN never does).
pub(crate) fn within(v: f64, low: Bound, high: Bound) -> bool {
    let above = match low {
        Bound::Closed(b) => v >= b,
        Bound::Open(b) => v > b,
        Bound::Unbounded => !v.is_nan(),
    };
    let below = match high {
        Bound::Closed(b) => v <= b,
        Bound::Open(b) => v < b,
        Bound::Unbounded => !v.is_nan(),
    };
    above && below
}

/// The range in words, for a message: `> 0`, `>= 0`, `in (0, 1]`.
pub(crate) fn describe(low: Bound, high: Bound) -> String {
    match (low, high) {
        (Bound::Unbounded, Bound::Unbounded) => "a finite number".to_owned(),
        (Bound::Closed(a), Bound::Unbounded) => format!(">= {a}"),
        (Bound::Open(a), Bound::Unbounded) => format!("> {a}"),
        (Bound::Unbounded, Bound::Closed(b)) => format!("<= {b}"),
        (Bound::Unbounded, Bound::Open(b)) => format!("< {b}"),
        (low, high) => {
            let (l, a) = match low {
                Bound::Closed(a) => ('[', a),
                Bound::Open(a) => ('(', a),
                Bound::Unbounded => unreachable!("matched above"),
            };
            let (h, b) = match high {
                Bound::Closed(b) => (']', b),
                Bound::Open(b) => (')', b),
                Bound::Unbounded => unreachable!("matched above"),
            };
            format!("in {l}{a}, {b}{h}")
        }
    }
}

/// A whole number as the caller sent it: any JSON integer, or a float with no
/// fractional part (`3.0`).
///
/// Count options are read as this rather than as `usize`. An unsigned type
/// refuses `-1` while deserializing -- as a shape error, before the range
/// check that refuses `0` or `1` for the same option ever runs -- so two
/// values wrong for the same reason left by different doors. A fraction is
/// still refused while deserializing (`malformed_input` at its path, "expected
/// a whole number"): whether a value is whole is a matter of its type, whether
/// it is in range a matter of its value.
#[derive(Debug, Clone, Copy, PartialEq)]
pub(crate) struct Whole(pub(crate) f64);

impl Whole {
    /// The value as a count, once a range check has accepted it as `>= 0`.
    pub(crate) fn count(self) -> usize {
        debug_assert!(self.0 >= 0.0, "a count is checked non-negative first");
        // Saturates above `usize::MAX`, which no range a count option has
        // reaches.
        self.0 as usize
    }
}

impl From<usize> for Whole {
    fn from(n: usize) -> Self {
        Whole(n as f64)
    }
}

impl<'de> Deserialize<'de> for Whole {
    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
        struct Visitor;
        impl serde::de::Visitor<'_> for Visitor {
            type Value = Whole;
            fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
                f.write_str("a whole number")
            }
            fn visit_i64<E: serde::de::Error>(self, v: i64) -> Result<Whole, E> {
                Ok(Whole(v as f64))
            }
            fn visit_u64<E: serde::de::Error>(self, v: u64) -> Result<Whole, E> {
                Ok(Whole(v as f64))
            }
            fn visit_f64<E: serde::de::Error>(self, v: f64) -> Result<Whole, E> {
                if v.is_finite() && v.fract() == 0.0 {
                    Ok(Whole(v))
                } else {
                    Err(E::invalid_type(serde::de::Unexpected::Float(v), &self))
                }
            }
        }
        deserializer.deserialize_f64(Visitor)
    }
}

/// Where in the argument `param` a request stopped deserializing (both
/// transports read requests through `serde_path_to_error`), as the
/// refusal reports it: the field (`design[1]`, `points[0].y`) and, when the
/// failure sits in an array, its position there -- the same `parameter` /
/// `index` a number array read element by element reports. Without it a
/// `null` three levels down was "invalid type: null, expected f64" with no
/// way to say which row (the gap `read_numbers` closed for bare arrays).
pub(crate) fn failure_site(
    param: &str,
    path: &serde_path_to_error::Path,
) -> (String, Option<usize>) {
    use serde_path_to_error::Segment;
    let segments: Vec<&Segment> = path.iter().collect();
    let index = segments.iter().rev().find_map(|s| match s {
        Segment::Seq { index } => Some(*index),
        _ => None,
    });
    // A trailing `[i]` is the index, not part of the name.
    let named = match segments.last() {
        Some(Segment::Seq { .. }) => &segments[..segments.len() - 1],
        _ => &segments[..],
    };
    let mut name = String::new();
    for segment in named {
        match segment {
            Segment::Seq { index } => name.push_str(&format!("[{index}]")),
            Segment::Map { key } | Segment::Enum { variant: key } => {
                if !name.is_empty() {
                    name.push('.');
                }
                name.push_str(key);
            }
            Segment::Unknown => name.push_str(".?"),
        }
    }
    // A top-level array argument (`data[1][2]`) or a failure at the root
    // (a missing field) is named by the argument itself.
    if name.is_empty() || name.starts_with('[') {
        name.insert_str(0, param);
    }
    (name, index)
}

/// A refusal reason: the `code` a refusal carries (the WebAssembly `Error`'s,
/// the C error body's) and the fields that can
/// stand beside it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[serde(deny_unknown_fields)]
pub(crate) struct RefusalCode {
    pub(crate) code: String,
    pub(crate) fields: Vec<String>,
}

/// A violation a checker reports. This package has no checker; the type is
/// here so every engine's [`Codes`] has one shape.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[serde(deny_unknown_fields)]
pub(crate) struct ViolationCode {
    pub(crate) code: String,
    pub(crate) fields: Vec<String>,
    pub(crate) checkers: Vec<String>,
}

/// What this package can answer with besides a result: every refusal
/// `code`, and no violations -- it has no checker.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, serde::Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[serde(deny_unknown_fields)]
pub(crate) struct Codes {
    pub(crate) refusals: Vec<RefusalCode>,
    pub(crate) violations: Vec<ViolationCode>,
}

pub(crate) fn code_catalog() -> Codes {
    Codes {
        refusals: Code::ALL
            .into_iter()
            .map(|c| RefusalCode {
                code: c.name().to_string(),
                fields: c.fields().iter().map(|f| f.to_string()).collect(),
            })
            .collect(),
        violations: vec![],
    }
}

/// Every reason the crate's transports refuse with: the stable `code` a
/// refusal carries, and the fields that can stand beside it. A [`WireError`]
/// holds one of these (named through [`code`]), so the published list
/// ([`Code::ALL`]) is the list the crate refuses from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Code {
    InvalidInput,
    MalformedInput,
    CountNotWhole,
    SampleSizeNotWhole,
    DefectivesExceedSample,
    UnitsNotPositive,
    ValueNotFinite,
    InsufficientData,
    ParameterOutOfRange,
    EmptyInput,
    NonPositiveData,
    NoSpecification,
    InvalidOption,
    DimensionMismatch,
    UnknownOption,
    EventsUnordered,
    EventAfterEnd,
    /// The package failed, not the input.
    Internal,
}

impl Code {
    pub(crate) const ALL: [Code; 18] = [
        Code::InvalidInput,
        Code::MalformedInput,
        Code::CountNotWhole,
        Code::SampleSizeNotWhole,
        Code::DefectivesExceedSample,
        Code::UnitsNotPositive,
        Code::ValueNotFinite,
        Code::InsufficientData,
        Code::ParameterOutOfRange,
        Code::EmptyInput,
        Code::NonPositiveData,
        Code::NoSpecification,
        Code::InvalidOption,
        Code::DimensionMismatch,
        Code::UnknownOption,
        Code::EventsUnordered,
        Code::EventAfterEnd,
        Code::Internal,
    ];

    pub(crate) fn name(self) -> &'static str {
        match self {
            Code::InvalidInput => "invalid_input",
            Code::MalformedInput => "malformed_input",
            Code::CountNotWhole => "count_not_whole",
            Code::SampleSizeNotWhole => "sample_size_not_whole",
            Code::DefectivesExceedSample => "defectives_exceed_sample",
            Code::UnitsNotPositive => "units_not_positive",
            Code::ValueNotFinite => "value_not_finite",
            Code::InsufficientData => "insufficient_data",
            Code::ParameterOutOfRange => "parameter_out_of_range",
            Code::EmptyInput => "empty_input",
            Code::NonPositiveData => "non_positive_data",
            Code::NoSpecification => "no_specification",
            Code::InvalidOption => "invalid_option",
            Code::DimensionMismatch => "dimension_mismatch",
            Code::UnknownOption => "unknown_option",
            Code::EventsUnordered => "events_unordered",
            Code::EventAfterEnd => "event_after_end",
            Code::Internal => "internal",
        }
    }

    /// The fields a refusal with this code can carry besides `code` and
    /// `message` (`index` and `parameter` are always there, `null` when they
    /// do not apply).
    pub(crate) fn fields(self) -> &'static [&'static str] {
        match self {
            Code::InvalidInput => &["index", "parameter"],
            Code::MalformedInput => &["index", "parameter"],
            Code::CountNotWhole => &["index", "parameter"],
            Code::SampleSizeNotWhole => &["index", "parameter"],
            Code::DefectivesExceedSample => &["index", "parameter"],
            Code::UnitsNotPositive => &["index", "parameter"],
            Code::ValueNotFinite => &["index", "parameter"],
            Code::InsufficientData => &["index", "parameter", "min", "got"],
            Code::ParameterOutOfRange => &[
                "index",
                "parameter",
                "min",
                "max",
                "exclusive_min",
                "exclusive_max",
                "got",
            ],
            Code::EmptyInput => &["index", "parameter"],
            Code::NonPositiveData => &["index", "parameter", "got"],
            Code::NoSpecification => &["index", "parameter", "expected"],
            Code::InvalidOption => &["index", "parameter"],
            Code::DimensionMismatch => &["index", "parameter", "expected", "got"],
            Code::UnknownOption => &["index", "parameter", "got", "expected"],
            Code::EventsUnordered => &["index", "parameter"],
            Code::EventAfterEnd => &["index", "parameter"],
            Code::Internal => &["index", "parameter"],
        }
    }
}

impl PartialEq<&str> for Code {
    fn eq(&self, other: &&str) -> bool {
        self.name() == *other
    }
}

impl PartialEq<Code> for &str {
    fn eq(&self, other: &Code) -> bool {
        *self == other.name()
    }
}

/// The codes by their constant names, as the transports and their tests name
/// them.
pub(crate) mod code {
    /// Any refusal without a more specific code.
    pub(crate) const INVALID_INPUT: super::Code = super::Code::InvalidInput;
    /// The input is not the shape the function takes (not an array, a pair
    /// with the wrong arity, a value of the wrong type).
    pub(crate) const MALFORMED_INPUT: super::Code = super::Code::MalformedInput;
    /// A count that is not a whole number >= 0.
    pub(crate) const COUNT_NOT_WHOLE: super::Code = super::Code::CountNotWhole;
    /// A sample size that is not a whole number >= 1.
    ///
    /// One code for the whole field, not one per way of being wrong: a size of
    /// `0`, `-3`, `10.5` or a NaN are the same mistake to whoever typed the row,
    /// and splitting them made `code` insufficient on its own -- the consumer
    /// had to read `message` to learn whether a `count_not_whole` was about the
    /// defectives or the size beside them.
    pub(crate) const SAMPLE_SIZE_NOT_WHOLE: super::Code = super::Code::SampleSizeNotWhole;
    /// More defectives than the sample has items.
    pub(crate) const DEFECTIVES_EXCEED_SAMPLE: super::Code = super::Code::DefectivesExceedSample;
    /// Units inspected that are not a positive, finite number.
    pub(crate) const UNITS_NOT_POSITIVE: super::Code = super::Code::UnitsNotPositive;
    /// A NaN or an infinity where a measurement belongs.
    pub(crate) const VALUE_NOT_FINITE: super::Code = super::Code::ValueNotFinite;
    /// Fewer samples than the chart needs.
    pub(crate) const INSUFFICIENT_DATA: super::Code = super::Code::InsufficientData;
    /// A value outside its domain -- an option, a Phase I standard, a subgroup
    /// size the factor tables do not cover, an array element. `parameter`
    /// names which, `min` / `max` / `exclusive_*` the domain, `got` the value.
    pub(crate) const PARAMETER_OUT_OF_RANGE: super::Code = super::Code::ParameterOutOfRange;
    /// An argument with nothing in it.
    pub(crate) const EMPTY_INPUT: super::Code = super::Code::EmptyInput;
    /// A value that must be `> 0` is not (Box-Cox data, failure times).
    pub(crate) const NON_POSITIVE_DATA: super::Code = super::Code::NonPositiveData;
    /// A capability index with neither specification limit: there is nothing
    /// to measure the spread against. `expected` lists the two options.
    pub(crate) const NO_SPECIFICATION: super::Code = super::Code::NoSpecification;
    /// A setting refused for a reason a range cannot state (`[lo, hi]` with
    /// `lo >= hi`).
    pub(crate) const INVALID_OPTION: super::Code = super::Code::InvalidOption;
    /// Arrays that must have the same length do not.
    pub(crate) const DIMENSION_MISMATCH: super::Code = super::Code::DimensionMismatch;
    /// An option given a name the function does not know. `parameter` names it.
    pub(crate) const UNKNOWN_OPTION: super::Code = super::Code::UnknownOption;
    /// Event times that go backwards.
    pub(crate) const EVENTS_UNORDERED: super::Code = super::Code::EventsUnordered;
    /// An event time after the end of observation.
    pub(crate) const EVENT_AFTER_END: super::Code = super::Code::EventAfterEnd;
    /// The package failed, not the input: a result it could not hand back.
    pub(crate) const INTERNAL: super::Code = super::Code::Internal;
}

impl WireError {
    pub(crate) fn new(code: Code, index: Option<usize>, message: impl Into<String>) -> Self {
        WireError {
            code: code.name(),
            reason: code,
            index,
            parameter: None,
            message: message.into(),
            details: Vec::new(),
        }
    }

    /// Adds one of the values behind the reason.
    pub(crate) fn with(mut self, key: &'static str, value: Detail) -> Self {
        debug_assert!(
            self.reason.fields().contains(&key),
            "{} refusal with an undeclared field: {key}",
            self.code
        );
        self.details.push((key, value));
        self
    }

    /// An option given a name the function does not know: `parameter`, `got`
    /// and the names it does know as `expected`.
    pub(crate) fn unknown_option(
        parameter: &'static str,
        got: &str,
        expected: &[&'static str],
    ) -> Self {
        Self::new(
            code::UNKNOWN_OPTION,
            None,
            format!(
                "{parameter}: unknown name {got:?}; expected one of {}",
                expected.join(", ")
            ),
        )
        .about(parameter)
        .with("got", Detail::Text(got.to_string()))
        .with("expected", Detail::List(expected.to_vec()))
    }

    /// A number outside the range `low`..`high`. `min` and `max` are always
    /// sent -- the bound when that end is closed, `null` otherwise -- and an
    /// open end adds `exclusive_min` / `exclusive_max`.
    pub(crate) fn out_of_range(
        parameter: impl Into<std::borrow::Cow<'static, str>>,
        low: Bound,
        high: Bound,
        got: f64,
        message: impl Into<String>,
    ) -> Self {
        let mut e = Self::new(code::PARAMETER_OUT_OF_RANGE, None, message).about(parameter);
        for (closed, open, end) in [
            ("min", "exclusive_min", low),
            ("max", "exclusive_max", high),
        ] {
            match end {
                Bound::Closed(v) => e = e.with(closed, Detail::Num(v)),
                Bound::Open(v) => e = e.with(closed, Detail::Null).with(open, Detail::Num(v)),
                Bound::Unbounded => e = e.with(closed, Detail::Null),
            }
        }
        e.with("got", Detail::Num(got))
    }

    /// Fewer values than needed: `parameter`, `min` and `got`.
    pub(crate) fn too_few(
        parameter: impl Into<std::borrow::Cow<'static, str>>,
        min: usize,
        got: usize,
        message: impl Into<String>,
    ) -> Self {
        Self::new(code::INSUFFICIENT_DATA, None, message)
            .about(parameter)
            .with("min", Detail::Num(min as f64))
            .with("got", Detail::Num(got as f64))
    }

    /// An argument with nothing in it.
    pub(crate) fn empty_input(parameter: &'static str) -> Self {
        Self::new(
            code::EMPTY_INPUT,
            None,
            format!("{parameter} must not be empty"),
        )
        .about(parameter)
    }

    /// Names the option a refusal is about, alongside its code.
    pub(crate) fn about(mut self, parameter: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        self.parameter = Some(parameter.into());
        self
    }

    /// A refusal without a more specific code.
    pub(crate) fn invalid_input(message: impl Into<String>) -> Self {
        Self::new(code::INVALID_INPUT, None, message)
    }

    /// Too few samples, with the message naming how many are needed.
    pub(crate) fn insufficient_data(message: impl Into<String>) -> Self {
        Self::new(code::INSUFFICIENT_DATA, None, message)
    }

    /// A chart's refusal of one element, placed at `label[index]`, or of the
    /// input as a whole when `index` is `None`.
    pub(crate) fn chart(
        label: &str,
        index: Option<usize>,
        error: &crate::spc::ControlChartError,
    ) -> Self {
        let message = match index {
            Some(i) => format!("{label}[{i}]: {error}"),
            None => error.to_string(),
        };
        use crate::spc::ControlChartError as E;
        let mut wire = match error {
            // The domain error names the parameter and carries the domain; the
            // wire record should not make a consumer read either back out of
            // the message.
            E::InvalidStandard {
                parameter,
                got,
                min,
                exclusive_min,
                max,
                exclusive_max,
                ..
            } => Self::out_of_range(
                *parameter,
                Bound::from_pair(*min, *exclusive_min),
                Bound::from_pair(*max, *exclusive_max),
                *got,
                message,
            ),
            // The size is the width of the subgroups given.
            E::SubgroupSizeOutOfRange { got, min, max } => Self::out_of_range(
                label.to_string(),
                Bound::Closed(*min as f64),
                Bound::Closed(*max as f64),
                *got as f64,
                message,
            ),
            // Same reason as every other pair of lengths that must agree.
            E::SampleLengthMismatch { expected, got } => {
                Self::new(code::DIMENSION_MISMATCH, index, message)
                    .about(label.to_string())
                    .with("expected", Detail::Num(*expected as f64))
                    .with("got", Detail::Num(*got as f64))
            }
            _ => Self::new(chart_error_code(error), index, message),
        };
        wire.index = index;
        wire
    }

    /// A whole-slice chart's refusal.
    pub(crate) fn chart_input(label: &str, error: &crate::spc::ChartInputError) -> Self {
        use crate::spc::ChartInputError;
        match error {
            ChartInputError::Sample { index, error } => Self::chart(label, Some(*index), error),
            ChartInputError::TooFewSamples { min, got } => {
                Self::new(code::INSUFFICIENT_DATA, None, format!("{label}: {error}"))
                    .about(label.to_string())
                    .with("min", Detail::Num(*min as f64))
                    .with("got", Detail::Num(*got as f64))
            }
            ChartInputError::Standard(error) => Self::chart(label, None, error),
        }
    }
}

impl std::fmt::Display for WireError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl From<String> for WireError {
    fn from(message: String) -> Self {
        Self::invalid_input(message)
    }
}

impl From<&String> for WireError {
    fn from(message: &String) -> Self {
        Self::invalid_input(message.as_str())
    }
}

impl From<&WireError> for WireError {
    fn from(error: &WireError) -> Self {
        error.clone()
    }
}

impl From<&str> for WireError {
    fn from(message: &str) -> Self {
        Self::invalid_input(message)
    }
}

pub(crate) fn chart_error_code(error: &crate::spc::ControlChartError) -> Code {
    use crate::spc::ControlChartError as E;
    match error {
        E::SampleLengthMismatch { .. } => code::DIMENSION_MISMATCH,
        E::NonFiniteValue => code::VALUE_NOT_FINITE,
        E::DefectivesExceedSampleSize { .. } => code::DEFECTIVES_EXCEED_SAMPLE,
        E::NonPositiveUnits => code::UNITS_NOT_POSITIVE,
        // A domain the error states as bounds: `parameter` (with the bounds)
        // tells the two apart.
        E::SubgroupSizeOutOfRange { .. } | E::InvalidStandard { .. } => {
            code::PARAMETER_OUT_OF_RANGE
        }
        E::ZeroSampleSize => code::SAMPLE_SIZE_NOT_WHOLE,
    }
}

/// Feeds rows to a chart, naming the row a rejection came from. The chart
/// knows why a sample is unusable but not where it sat in the caller's input.
pub(crate) fn add_rows<T>(
    rows: impl IntoIterator<Item = T>,
    label: &str,
    mut add: impl FnMut(T) -> Result<(), crate::spc::ControlChartError>,
) -> Result<(), WireError> {
    for (i, row) in rows.into_iter().enumerate() {
        add(row).map_err(|e| WireError::chart(label, Some(i), &e))?;
    }
    Ok(())
}

/// Largest count a JSON number carries exactly (2^53).
const MAX_EXACT_COUNT: f64 = 9_007_199_254_740_992.0;

/// What a whole number means for one input field: its floor, the name it goes
/// by in a message, and the code its refusal carries.
///
/// The two fields of a `[defectives, sample_size]` pair take the same *kind* of
/// value and different *domains*, and reporting both under one code left the
/// difference readable only in the message text.
#[derive(Clone, Copy)]
struct CountDomain {
    min: u64,
    noun: &'static str,
    code: Code,
}

/// A count of things observed: a whole number >= 0.
const COUNT: CountDomain = CountDomain {
    min: 0,
    noun: "a count",
    code: code::COUNT_NOT_WHOLE,
};

/// The size of a sample: a whole number >= 1. Zero is refused here rather than
/// downstream so that every bad size -- zero, negative, fractional, not a
/// number at all -- leaves by the same door.
const SAMPLE_SIZE: CountDomain = CountDomain {
    min: 1,
    noun: "a sample size",
    code: code::SAMPLE_SIZE_NOT_WHOLE,
};

/// A whole number in `domain`. Read from a JSON number of either kind, so a
/// fractional or negative value is refused *here*, with its position, rather
/// than by a deserializer that knows neither.
fn whole_count(
    value: &serde_json::Value,
    at: &str,
    index: Option<usize>,
    domain: CountDomain,
) -> Result<u64, WireError> {
    let CountDomain { min, noun, code } = domain;
    if let Some(n) = value.as_u64() {
        if n >= min {
            return Ok(n);
        }
    }
    let refuse = |shown: String| {
        WireError::new(
            code,
            index,
            format!("{at}: {noun} must be a whole number of at least {min}, got {shown}"),
        )
    };
    match value.as_f64() {
        Some(x) if x >= min as f64 && x.fract() == 0.0 && x <= MAX_EXACT_COUNT => Ok(x as u64),
        Some(x) => Err(refuse(x.to_string())),
        None => Err(refuse(value.to_string())),
    }
}

fn as_array<'a>(
    value: &'a serde_json::Value,
    at: &str,
    expected: &str,
) -> Result<&'a Vec<serde_json::Value>, WireError> {
    value.as_array().ok_or_else(|| {
        WireError::new(
            code::MALFORMED_INPUT,
            None,
            format!("{at}: expected {expected}"),
        )
    })
}

/// The `[a, b]` pair at `label[i]`.
fn pair<'a>(
    row: &'a serde_json::Value,
    label: &str,
    i: usize,
    expected: &str,
) -> Result<(&'a serde_json::Value, &'a serde_json::Value), WireError> {
    match row.as_array().map(Vec::as_slice) {
        Some([a, b]) => Ok((a, b)),
        _ => Err(WireError::new(
            code::MALFORMED_INPUT,
            Some(i),
            format!("{label}[{i}]: expected a pair {expected}, got {row}"),
        )),
    }
}

/// `[c1, c2, ...]` counts.
// Only the WASM binding carries the NP, C and U charts; the FFI has no caller.
#[cfg_attr(not(feature = "wasm"), allow(dead_code))]
pub(crate) fn count_rows(value: &serde_json::Value, label: &str) -> Result<Vec<u64>, WireError> {
    as_array(value, label, "an array of counts")?
        .iter()
        .enumerate()
        .map(|(i, v)| whole_count(v, &format!("{label}[{i}]"), Some(i), COUNT))
        .collect::<Result<Vec<_>, _>>()
        // Every refusal in the rows is about this argument.
        .map_err(|e: WireError| e.about(label.to_owned()))
}

/// The one sample size an NP chart applies to every row. Not an element of an
/// array, so its refusal carries no index.
// Only the WASM binding carries the NP, C and U charts; the FFI has no caller.
#[cfg_attr(not(feature = "wasm"), allow(dead_code))]
pub(crate) fn sample_size_value(value: &serde_json::Value, label: &str) -> Result<u64, WireError> {
    whole_count(value, label, None, SAMPLE_SIZE).map_err(|e| e.about(label.to_owned()))
}

/// `[[defectives, sample_size], ...]` pairs.
pub(crate) fn count_pairs(
    value: &serde_json::Value,
    label: &str,
) -> Result<Vec<(u64, u64)>, WireError> {
    const SHAPE: &str = "[defectives, sample_size]";
    as_array(value, label, &format!("an array of {SHAPE} pairs"))?
        .iter()
        .enumerate()
        .map(|(i, row)| {
            let (d, n) = pair(row, label, i, SHAPE)?;
            Ok((
                whole_count(d, &format!("{label}[{i}][0] (defectives)"), Some(i), COUNT)?,
                whole_count(
                    n,
                    &format!("{label}[{i}][1] (sample size)"),
                    Some(i),
                    SAMPLE_SIZE,
                )?,
            ))
        })
        .collect::<Result<Vec<_>, _>>()
        // Every refusal in the rows is about this argument.
        .map_err(|e: WireError| e.about(label.to_owned()))
}

/// `[[defects, units], ...]` pairs; `units` may be fractional.
// Only the WASM binding carries the NP, C and U charts; the FFI has no caller.
#[cfg_attr(not(feature = "wasm"), allow(dead_code))]
pub(crate) fn rate_pairs(
    value: &serde_json::Value,
    label: &str,
) -> Result<Vec<(u64, f64)>, WireError> {
    const SHAPE: &str = "[defects, units]";
    as_array(value, label, &format!("an array of {SHAPE} pairs"))?
        .iter()
        .enumerate()
        .map(|(i, row)| {
            let (d, u) = pair(row, label, i, SHAPE)?;
            let defects = whole_count(d, &format!("{label}[{i}][0] (defects)"), Some(i), COUNT)?;
            let units = u.as_f64().ok_or_else(|| {
                WireError::new(
                    code::UNITS_NOT_POSITIVE,
                    Some(i),
                    format!("{label}[{i}][1] (units): expected a positive number, got {u}"),
                )
            })?;
            Ok((defects, units))
        })
        .collect::<Result<Vec<_>, _>>()
        // Every refusal in the rows is about this argument.
        .map_err(|e: WireError| e.about(label.to_owned()))
}

pub(crate) fn attribute_point_dtos(
    points: &[crate::spc::AttributeChartPoint],
) -> Vec<AttributeChartPointDto> {
    points
        .iter()
        .map(|p| AttributeChartPointDto {
            index: p.index,
            value: p.value,
            ucl: p.ucl,
            cl: p.cl,
            lcl: p.lcl,
            out_of_control: p.out_of_control,
            z: p.z,
        })
        .collect()
}

pub(crate) fn laney_point_dtos(
    points: &[crate::spc::LaneyAttributePoint],
) -> Vec<AttributeChartPointDto> {
    points
        .iter()
        .map(|p| AttributeChartPointDto {
            index: p.index,
            value: p.value,
            ucl: p.ucl,
            cl: p.cl,
            lcl: p.lcl,
            out_of_control: p.out_of_control,
            z: p.z,
        })
        .collect()
}

pub(crate) fn xbar_r_dto(
    subgroups: Vec<Vec<f64>>,
    rules: crate::spc::RuleSet,
) -> Result<XbarRChartDto, WireError> {
    use crate::spc::{ControlChart, XBarRChart};

    let n = subgroup_size(&subgroups)?;
    let mut chart = XBarRChart::new(n)
        .map_err(|e| WireError::chart("subgroups", None, &e))?
        .with_rules(rules);
    add_rows(&subgroups, "subgroups", |g| chart.add_sample(g))?;
    let too_few = || {
        WireError::too_few(
            "subgroups",
            1,
            0,
            "subgroups: at least one subgroup is needed",
        )
    };
    let x = chart.control_limits().ok_or_else(too_few)?;
    let r = chart.r_limits().ok_or_else(too_few)?;
    Ok(XbarRChartDto {
        xbar_cl: x.cl,
        xbar_ucl: x.ucl,
        xbar_lcl: x.lcl,
        r_cl: r.cl,
        r_ucl: r.ucl,
        r_lcl: r.lcl,
        // Present whenever the limits are: it is their centre line over d2 / c4.
        sigma_hat: chart.sigma_hat().ok_or_else(too_few)?,
        sigma_hat_df: chart.sigma_hat_df().ok_or_else(too_few)?,
        xbar_points: point_dtos(chart.points()),
        r_points: point_dtos(chart.r_points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn p_chart_dto(
    samples: &[(u64, u64)],
    standard: &AttributeStandardDto,
) -> Result<PChartDto, WireError> {
    use crate::spc::PChart;

    standard.refuse(
        "p_chart",
        &[
            ("u_bar", standard.u_bar.is_some()),
            ("phi", standard.phi.is_some()),
        ],
    )?;
    let mut chart = match standard.p_bar {
        Some(p) => PChart::with_center(p).map_err(|e| WireError::chart("options", None, &e))?,
        None => PChart::new(),
    };
    add_rows(samples, "samples", |&(d, n)| chart.add_sample(d, n))?;
    let p_bar = chart.p_bar().ok_or_else(|| {
        WireError::too_few("samples", 1, 0, "samples: at least 1 sample is needed")
    })?;
    Ok(PChartDto {
        p_bar,
        points: attribute_point_dtos(chart.points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn laney_p_dto(
    samples: &[(u64, u64)],
    standard: &AttributeStandardDto,
) -> Result<LaneyPChartDto, WireError> {
    standard.refuse("laney_p_chart", &[("u_bar", standard.u_bar.is_some())])?;
    let laney = standard.laney(standard.p_bar, "p_bar")?;
    let chart = crate::spc::laney_p_chart(samples, laney)
        .map_err(|e| WireError::chart_input("samples", &e))?;
    Ok(LaneyPChartDto {
        p_bar: chart.p_bar,
        phi: chart.phi,
        points: laney_point_dtos(&chart.points),
    })
}

// ---------------------------------------------------------------------------
// Attributes and rare-event charts beyond P / Laney P'
// ---------------------------------------------------------------------------
//
// Shared by the WebAssembly and C transports, so a row refused over one is
// refused over the other with the same code and index.

/// NP and C charts: one set of limits for every point.
#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct FixedLimitChartDto {
    pub(crate) cl: f64,
    pub(crate) ucl: f64,
    pub(crate) lcl: f64,
    pub(crate) points: Vec<AttributeChartPointDto>,
    pub(crate) in_control: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct UChartDto {
    pub(crate) u_bar: f64,
    pub(crate) points: Vec<AttributeChartPointDto>,
    pub(crate) in_control: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct LaneyUChartDto {
    pub(crate) u_bar: f64,
    pub(crate) phi: f64,
    pub(crate) points: Vec<AttributeChartPointDto>,
}
#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct GChartDto {
    pub(crate) g_bar: f64,
    pub(crate) points: Vec<GChartPointDto>,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct GChartPointDto {
    pub(crate) index: usize,
    pub(crate) value: f64,
    pub(crate) ucl: f64,
    pub(crate) cl: f64,
    pub(crate) lcl: f64,
    pub(crate) out_of_control: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct TChartDto {
    pub(crate) t_bar: f64,
    pub(crate) points: Vec<TChartPointDto>,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct TChartPointDto {
    pub(crate) index: usize,
    pub(crate) value: f64,
    pub(crate) ucl: f64,
    pub(crate) cl: f64,
    pub(crate) lcl: f64,
    pub(crate) out_of_control: bool,
}

/// `values` with at least `min` entries, or `insufficient_data` naming both.
pub(crate) fn at_least(
    values: Vec<f64>,
    min: usize,
    param: &'static str,
) -> Result<Vec<f64>, WireError> {
    if values.len() >= min {
        Ok(values)
    } else {
        let got = values.len();
        Err(WireError::too_few(
            param,
            min,
            got,
            format!("{param}: at least {min} values are needed, got {got}"),
        ))
    }
}

/// The first value outside `low`..`high`, as `parameter_out_of_range` at its
/// index with the bounds and the value.
pub(crate) fn each_within(
    values: &[f64],
    param: &'static str,
    low: Bound,
    high: Bound,
) -> Result<(), WireError> {
    match values.iter().position(|&v| !within(v, low, high)) {
        Some(i) => {
            let got = values[i];
            let mut e = WireError::out_of_range(
                param,
                low,
                high,
                got,
                format!("{param}[{i}]: must be {}, got {got}", describe(low, high)),
            );
            e.index = Some(i);
            Err(e)
        }
        None => Ok(()),
    }
}

pub(crate) fn np_chart_dto(
    defectives: &[u64],
    sample_size: u64,
) -> Result<FixedLimitChartDto, WireError> {
    use crate::spc::NPChart;

    let mut chart =
        NPChart::new(sample_size).map_err(|e| WireError::chart("sample_size", None, &e))?;
    add_rows(defectives, "defectives", |&d| chart.add_sample(d))?;
    let (ucl, cl, lcl) = chart
        .control_limits()
        .ok_or_else(|| WireError::too_few("defectives", 1, 0, "defectives must not be empty"))?;
    Ok(FixedLimitChartDto {
        cl,
        ucl,
        lcl,
        points: attribute_point_dtos(chart.points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn c_chart_dto(defects: &[u64]) -> Result<FixedLimitChartDto, WireError> {
    use crate::spc::CChart;

    let mut chart = CChart::new();
    for &c in defects {
        chart.add_sample(c);
    }
    let (ucl, cl, lcl) = chart
        .control_limits()
        .ok_or_else(|| WireError::too_few("defects", 1, 0, "defects must not be empty"))?;
    Ok(FixedLimitChartDto {
        cl,
        ucl,
        lcl,
        points: attribute_point_dtos(chart.points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn u_chart_dto(
    raw: &[(u64, f64)],
    standard: &AttributeStandardDto,
) -> Result<UChartDto, WireError> {
    use crate::spc::UChart;

    standard.refuse(
        "u_chart",
        &[
            ("p_bar", standard.p_bar.is_some()),
            ("phi", standard.phi.is_some()),
        ],
    )?;
    let mut chart = match standard.u_bar {
        Some(u) => UChart::with_center(u).map_err(|e| WireError::chart("options", None, &e))?,
        None => UChart::new(),
    };
    add_rows(raw, "samples", |&(d, u)| chart.add_sample(d, u))?;
    let u_bar = chart
        .u_bar()
        .ok_or_else(|| WireError::too_few("samples", 1, 0, "samples must not be empty"))?;
    Ok(UChartDto {
        u_bar,
        points: attribute_point_dtos(chart.points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn laney_u_dto(
    raw: &[(u64, f64)],
    standard: &AttributeStandardDto,
) -> Result<LaneyUChartDto, WireError> {
    standard.refuse("laney_u_chart", &[("p_bar", standard.p_bar.is_some())])?;
    let laney = standard.laney(standard.u_bar, "u_bar")?;
    let chart =
        crate::spc::laney_u_chart(raw, laney).map_err(|e| WireError::chart_input("samples", &e))?;
    Ok(LaneyUChartDto {
        u_bar: chart.u_bar,
        phi: chart.phi,
        points: laney_point_dtos(&chart.points),
    })
}

/// G chart: inter-event conforming counts, at least 3, each `>= 0`.
pub(crate) fn g_chart_dto(gaps: &[f64]) -> Result<GChartDto, WireError> {
    let gaps = at_least(gaps.to_vec(), 3, "gaps")?;
    each_within(&gaps, "gaps", Bound::Closed(0.0), Bound::Unbounded)?;
    let chart =
        crate::spc::g_chart(&gaps).expect("three or more finite counts >= 0 make a G chart");
    Ok(GChartDto {
        g_bar: chart.g_bar,
        points: chart
            .points
            .iter()
            .map(|p| GChartPointDto {
                index: p.index,
                value: p.value,
                ucl: p.ucl,
                cl: p.cl,
                lcl: p.lcl,
                out_of_control: p.out_of_control,
            })
            .collect(),
    })
}

/// T chart: inter-event times, at least 3, each `> 0`.
pub(crate) fn t_chart_dto(times: &[f64]) -> Result<TChartDto, WireError> {
    let times = at_least(times.to_vec(), 3, "times")?;
    each_within(&times, "times", Bound::Open(0.0), Bound::Unbounded)?;
    let chart = crate::spc::t_chart(&times).expect("three or more finite times > 0 make a T chart");
    Ok(TChartDto {
        t_bar: chart.t_bar,
        points: chart
            .points
            .iter()
            .map(|p| TChartPointDto {
                index: p.index,
                value: p.value,
                ucl: p.ucl,
                cl: p.cl,
                lcl: p.lcl,
                out_of_control: p.out_of_control,
            })
            .collect(),
    })
}

// ---------------------------------------------------------------------------
// Hypothesis tests (WebAssembly; the C transport does not carry them yet)
// ---------------------------------------------------------------------------
//
// Each core checks what it can name -- sizes, shapes, the domain of a count or
// an expected frequency -- and refuses with the argument and the row. What is
// left when the test still returns `None` is data with no variation, refused
// as `invalid_input` naming the argument.
pub(crate) mod hypothesis {
    use super::*;

    /// A test statistic, its degrees of freedom and two-sided p-value.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct TestResultDto {
        pub(crate) statistic: f64,
        pub(crate) df: f64,
        pub(crate) p_value: f64,
    }

    impl From<crate::testing::TestResult> for TestResultDto {
        fn from(r: crate::testing::TestResult) -> Self {
            TestResultDto {
                statistic: r.statistic,
                df: r.df,
                p_value: r.p_value,
            }
        }
    }

    /// One-way ANOVA table.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct AnovaDto {
        pub(crate) f_statistic: f64,
        pub(crate) df_between: usize,
        pub(crate) df_within: usize,
        pub(crate) p_value: f64,
        pub(crate) ss_between: f64,
        pub(crate) ss_within: f64,
    }

    /// Shapiro-Wilk W and its p-value.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct ShapiroWilkDto {
        pub(crate) w: f64,
        pub(crate) p_value: f64,
    }

    /// Mann-Kendall trend test with Sen's slope.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct MannKendallDto {
        pub(crate) s_statistic: i64,
        pub(crate) variance: f64,
        pub(crate) z_statistic: f64,
        pub(crate) p_value: f64,
        pub(crate) kendall_tau: f64,
        pub(crate) sen_slope: f64,
    }

    fn no_variation(test: &str, param: &'static str) -> WireError {
        WireError::invalid_input(format!(
            "{test}: {param} has no variation (every value is the same), so the statistic is undefined"
        ))
        .about(param)
    }

    fn both_constant(test: &str) -> WireError {
        WireError::invalid_input(format!(
            "{test}: a and b together have no variation, so the statistic is undefined"
        ))
    }

    fn same_length(
        x: &[f64],
        y: &[f64],
        xn: &'static str,
        yn: &'static str,
    ) -> Result<(), WireError> {
        if x.len() == y.len() {
            Ok(())
        } else {
            Err(WireError::new(
                code::DIMENSION_MISMATCH,
                None,
                format!(
                    "{yn} has {} values but {xn} has {}; the test pairs them",
                    y.len(),
                    x.len()
                ),
            )
            .about(yn))
        }
    }

    /// At least two groups, each with at least `min` values.
    fn groups_of(groups: &[Vec<f64>], min: usize) -> Result<(), WireError> {
        if groups.len() < 2 {
            return Err(WireError::too_few(
                "groups",
                2,
                groups.len(),
                format!("groups: at least 2 groups are needed, got {}", groups.len()),
            ));
        }
        if let Some(i) = groups.iter().position(|g| g.len() < min) {
            return Err(WireError::new(
                code::INSUFFICIENT_DATA,
                Some(i),
                format!(
                    "groups[{i}]: at least {min} values are needed, got {}",
                    groups[i].len()
                ),
            )
            .about("groups"));
        }
        Ok(())
    }

    fn as_slices(groups: &[Vec<f64>]) -> Vec<&[f64]> {
        groups.iter().map(Vec::as_slice).collect()
    }

    pub(crate) fn one_sample_t_dto(data: &[f64], mu0: f64) -> Result<TestResultDto, WireError> {
        let data = at_least(data.to_vec(), 2, "data")?;
        if !mu0.is_finite() {
            return Err(WireError::new(
                code::VALUE_NOT_FINITE,
                None,
                format!("mu0: expected a finite number, got {mu0}"),
            )
            .about("mu0"));
        }
        crate::testing::one_sample_t_test(&data, mu0)
            .map(Into::into)
            .ok_or_else(|| no_variation("one_sample_t_test", "data"))
    }

    pub(crate) fn two_sample_t_dto(a: &[f64], b: &[f64]) -> Result<TestResultDto, WireError> {
        let a = at_least(a.to_vec(), 2, "a")?;
        let b = at_least(b.to_vec(), 2, "b")?;
        crate::testing::two_sample_t_test(&a, &b)
            .map(Into::into)
            .ok_or_else(|| both_constant("two_sample_t_test"))
    }

    pub(crate) fn paired_t_dto(x: &[f64], y: &[f64]) -> Result<TestResultDto, WireError> {
        same_length(x, y, "x", "y")?;
        let x = at_least(x.to_vec(), 2, "x")?;
        crate::testing::paired_t_test(&x, y)
            .map(Into::into)
            .ok_or_else(|| {
                WireError::invalid_input(
                    "paired_t_test: every difference y - x is the same, so the statistic is undefined",
                )
                .about("y")
            })
    }

    pub(crate) fn mann_whitney_dto(a: &[f64], b: &[f64]) -> Result<TestResultDto, WireError> {
        let a = at_least(a.to_vec(), 2, "a")?;
        let b = at_least(b.to_vec(), 2, "b")?;
        crate::testing::mann_whitney_u_test(&a, &b)
            .map(Into::into)
            .ok_or_else(|| both_constant("mann_whitney_u_test"))
    }

    pub(crate) fn wilcoxon_dto(x: &[f64], y: &[f64]) -> Result<TestResultDto, WireError> {
        same_length(x, y, "x", "y")?;
        let x = at_least(x.to_vec(), 2, "x")?;
        crate::testing::wilcoxon_signed_rank_test(&x, y)
            .map(Into::into)
            .ok_or_else(|| {
                WireError::insufficient_data(
                    "wilcoxon_signed_rank_test: fewer than 2 pairs differ (pairs with x = y are dropped)",
                )
                .about("y")
            })
    }

    pub(crate) fn jarque_bera_dto(data: &[f64]) -> Result<TestResultDto, WireError> {
        let data = at_least(data.to_vec(), 8, "data")?;
        crate::testing::jarque_bera_test(&data)
            .map(Into::into)
            .ok_or_else(|| no_variation("jarque_bera_test", "data"))
    }

    pub(crate) fn shapiro_wilk_dto(data: &[f64]) -> Result<ShapiroWilkDto, WireError> {
        let data = at_least(data.to_vec(), 3, "data")?;
        if data.len() > 5000 {
            return Err(WireError::out_of_range(
                "data",
                Bound::Closed(3.0),
                Bound::Closed(5000.0),
                data.len() as f64,
                format!(
                    "data: Shapiro-Wilk covers 3 to 5000 values (Royston 1995), got {}",
                    data.len()
                ),
            ));
        }
        crate::testing::shapiro_wilk_test(&data)
            .map(|r| ShapiroWilkDto {
                w: r.w,
                p_value: r.p_value,
            })
            .ok_or_else(|| no_variation("shapiro_wilk_test", "data"))
    }

    /// Anderson-Darling normality: A², the sample-size-corrected A²* and its p-value.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct AndersonDarlingDto {
        pub(crate) statistic: f64,
        pub(crate) statistic_modified: f64,
        pub(crate) p_value: f64,
    }

    pub(crate) fn anderson_darling_dto(data: &[f64]) -> Result<AndersonDarlingDto, WireError> {
        let data = at_least(data.to_vec(), 8, "data")?;
        crate::testing::anderson_darling_test(&data)
            .map(|r| AndersonDarlingDto {
                statistic: r.statistic,
                statistic_modified: r.statistic_star,
                p_value: r.p_value,
            })
            .ok_or_else(|| no_variation("anderson_darling_test", "data"))
    }

    /// Augmented Dickey-Fuller unit-root test input.
    #[derive(Deserialize)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    #[serde(deny_unknown_fields)]
    pub(crate) struct AdfInputDto {
        pub(crate) data: Vec<f64>,
        /// Deterministic terms in the test regression.
        #[serde(default = "default_adf_model")]
        #[cfg_attr(feature = "wasm", tsify(optional))]
        #[cfg_attr(
            feature = "wasm",
            tsify(type = "\"none\" | \"constant\" | \"constant_trend\"")
        )]
        pub(crate) model: String,
        /// The largest number of lagged differences the AIC search considers;
        /// absent or `null`: Schwert's rule. Not with `lags`.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) max_lags: Option<Whole>,
        /// Exactly this many lagged differences, no search. Not with `max_lags`.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) lags: Option<Whole>,
    }

    fn default_adf_model() -> String {
        "constant".to_owned()
    }

    /// One significance level of the ADF test.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct AdfLevelDto {
        pub(crate) level: f64,
        pub(crate) critical_value: f64,
        /// `statistic <= critical_value`: the unit root is rejected at this level.
        pub(crate) rejected: bool,
    }

    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct AdfDto {
        pub(crate) statistic: f64,
        pub(crate) n_lags: usize,
        pub(crate) n_obs: usize,
        /// 1 %, 5 % and 10 %, in that order (MacKinnon 2010 response surfaces).
        pub(crate) levels: Vec<AdfLevelDto>,
    }

    /// The fewest rows the test regression is run on.
    const ADF_MIN_REGRESSION_ROWS: usize = 5;

    pub(crate) fn adf_dto(input: AdfInputDto) -> Result<AdfDto, WireError> {
        use crate::testing::AdfModel;
        // Columns besides the lags: the lagged level, plus the deterministic terms.
        let (model, fixed_columns) = match input.model.as_str() {
            "none" => (AdfModel::None, 1),
            "constant" => (AdfModel::Constant, 2),
            "constant_trend" => (AdfModel::ConstantTrend, 3),
            other => {
                return Err(WireError::unknown_option(
                    "model",
                    other,
                    &["none", "constant", "constant_trend"],
                ))
            }
        };
        let data = at_least(input.data, 10, "data")?;
        // With p lags the regression keeps n - 1 - p rows (one value is lost to
        // differencing, p to the lags) and has fixed_columns + p columns. It
        // needs ADF_MIN_REGRESSION_ROWS rows and a residual degree of freedom.
        let n = data.len();
        let max = (n - 1 - ADF_MIN_REGRESSION_ROWS).min((n - 2 - fixed_columns) / 2);
        let count = |parameter: &'static str, value: Option<Whole>| match value {
            Some(Whole(p)) if !(0.0..=max as f64).contains(&p) => Err(WireError::out_of_range(
                parameter,
                Bound::Closed(0.0),
                Bound::Closed(max as f64),
                p,
                format!(
                    "{parameter}: {} values leave room for 0 to {max} lags, got {p}",
                    data.len()
                ),
            )),
            p => Ok(p.map(Whole::count)),
        };
        let lags = match (
            count("max_lags", input.max_lags)?,
            count("lags", input.lags)?,
        ) {
            (Some(_), Some(_)) => {
                return Err(WireError::new(
                    code::INVALID_OPTION,
                    None,
                    "lags fixes the number of lagged differences and max_lags bounds the \
                     AIC search for it -- give one",
                )
                .about("lags"))
            }
            (_, Some(p)) => crate::testing::AdfLags::Fixed(p),
            (max, None) => crate::testing::AdfLags::Aic { max },
        };
        let r = crate::testing::adf_test(&data, model, lags).ok_or_else(|| {
            WireError::invalid_input(
                "adf_test: the test regression is degenerate -- singular, or an exact \
                 fit of the differences (a deterministic series), so the t-ratio is \
                 undefined",
            )
            .about("data")
        })?;
        Ok(AdfDto {
            statistic: r.statistic,
            n_lags: r.n_lags,
            n_obs: r.n_obs,
            levels: [0.01, 0.05, 0.10]
                .iter()
                .zip(r.critical_values.iter().zip(r.rejected.iter()))
                .map(|(&level, (&critical_value, &rejected))| AdfLevelDto {
                    level,
                    critical_value,
                    rejected,
                })
                .collect(),
        })
    }

    pub(crate) fn mann_kendall_dto(data: &[f64]) -> Result<MannKendallDto, WireError> {
        let data = at_least(data.to_vec(), 4, "data")?;
        crate::testing::mann_kendall_test(&data)
            .map(|r| MannKendallDto {
                s_statistic: r.s_statistic,
                variance: r.variance,
                z_statistic: r.z_statistic,
                p_value: r.p_value,
                kendall_tau: r.kendall_tau,
                sen_slope: r.sen_slope,
            })
            .ok_or_else(|| no_variation("mann_kendall_test", "data"))
    }

    pub(crate) fn one_way_anova_dto(groups: &[Vec<f64>]) -> Result<AnovaDto, WireError> {
        groups_of(groups, 2)?;
        crate::testing::one_way_anova(&as_slices(groups))
            .map(|r| AnovaDto {
                f_statistic: r.f_statistic,
                df_between: r.df_between,
                df_within: r.df_within,
                p_value: r.p_value,
                ss_between: r.ss_between,
                ss_within: r.ss_within,
            })
            .ok_or_else(|| no_variation("one_way_anova", "groups"))
    }

    /// Kruskal-Wallis, Levene or Bartlett: `test` names which.
    pub(crate) fn groups_test_dto(
        test: &str,
        groups: &[Vec<f64>],
    ) -> Result<TestResultDto, WireError> {
        groups_of(groups, 2)?;
        let slices = as_slices(groups);
        let result = match test {
            "kruskal_wallis_test" => crate::testing::kruskal_wallis_test(&slices),
            "levene_test" => crate::testing::levene_test(&slices),
            _ => crate::testing::bartlett_test(&slices),
        };
        result
            .map(Into::into)
            .ok_or_else(|| no_variation(test, "groups"))
    }

    pub(crate) fn chi_squared_gof_dto(
        observed: &[f64],
        expected: &[f64],
    ) -> Result<TestResultDto, WireError> {
        same_length(observed, expected, "observed", "expected")?;
        let observed = at_least(observed.to_vec(), 2, "observed")?;
        each_within(&observed, "observed", Bound::Closed(0.0), Bound::Unbounded)?;
        each_within(expected, "expected", Bound::Open(0.0), Bound::Unbounded)?;
        crate::testing::chi_squared_goodness_of_fit(&observed, expected)
            .map(Into::into)
            .ok_or_else(|| {
                WireError::invalid_input(
                    "chi_squared_goodness_of_fit: no statistic -- the observed counts sum to 0",
                )
                .about("observed")
            })
    }

    /// Rows of a contingency table, all the same length.
    fn rectangular(
        table: &[Vec<f64>],
        min_rows: usize,
        min_cols: usize,
    ) -> Result<usize, WireError> {
        if table.len() < min_rows {
            return Err(WireError::too_few(
                "table",
                min_rows,
                table.len(),
                format!(
                    "table: at least {min_rows} rows are needed, got {}",
                    table.len()
                ),
            ));
        }
        let cols = table[0].len();
        if cols < min_cols {
            return Err(WireError::too_few(
                "table",
                min_cols,
                cols,
                format!("table: at least {min_cols} columns are needed, got {cols}"),
            ));
        }
        if let Some(i) = table.iter().position(|r| r.len() != cols) {
            return Err(WireError::new(
                code::DIMENSION_MISMATCH,
                Some(i),
                format!(
                    "table[{i}] has {} cells but table[0] has {cols}; every row needs the same number",
                    table[i].len()
                ),
            )
            .about("table"));
        }
        Ok(cols)
    }

    pub(crate) fn chi_squared_independence_dto(
        table: &[Vec<f64>],
    ) -> Result<TestResultDto, WireError> {
        let cols = rectangular(table, 2, 2)?;
        let flat: Vec<f64> = table.iter().flatten().copied().collect();
        each_within(&flat, "table", Bound::Closed(0.0), Bound::Unbounded)?;
        crate::testing::chi_squared_independence(&flat, table.len(), cols)
            .map(Into::into)
            .ok_or_else(|| {
                WireError::invalid_input(
                    "chi_squared_independence: a row or a column sums to 0, so its expected counts are 0",
                )
                .about("table")
            })
    }

    /// Bonferroni or Benjamini-Hochberg adjusted p-values, in input order.
    pub(crate) fn p_adjust_dto(test: &str, p_values: &[f64]) -> Result<Vec<f64>, WireError> {
        let p = at_least(p_values.to_vec(), 1, "p_values")?;
        each_within(&p, "p_values", Bound::Closed(0.0), Bound::Closed(1.0))?;
        let adjusted = if test == "bonferroni_correction" {
            crate::testing::bonferroni_correction(&p)
        } else {
            crate::testing::benjamini_hochberg(&p)
        };
        Ok(adjusted.expect("probabilities in [0, 1] are adjusted"))
    }

    pub(crate) fn fisher_exact_dto(table: &serde_json::Value) -> Result<TestResultDto, WireError> {
        let rows = as_array(table, "table", "a 2 x 2 array of counts")?;
        if rows.len() != 2 {
            return Err(WireError::new(
                code::DIMENSION_MISMATCH,
                None,
                format!(
                    "table: Fisher's exact test takes 2 rows, got {}",
                    rows.len()
                ),
            )
            .about("table"));
        }
        let mut cells = Vec::with_capacity(4);
        for (i, row) in rows.iter().enumerate() {
            let row = count_rows(row, &format!("table[{i}]"))?;
            if row.len() != 2 {
                return Err(WireError::new(
                    code::DIMENSION_MISMATCH,
                    Some(i),
                    format!(
                        "table[{i}]: Fisher's exact test takes 2 columns, got {}",
                        row.len()
                    ),
                )
                .about("table"));
            }
            cells.extend(row);
        }
        crate::testing::fisher_exact_test(cells[0], cells[1], cells[2], cells[3])
            .map(Into::into)
            .ok_or_else(|| {
                WireError::invalid_input(
                    "fisher_exact_test: a row or a column of the table sums to 0",
                )
                .about("table")
            })
    }
}

/// Input for `process_capability`.
///
/// Every field except `data` is optional, but at least one of `usl`/`lsl` must
/// be present -- a capability index without a specification limit is undefined.
#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct CapabilityInputDto {
    pub(crate) data: Vec<f64>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) usl: Option<f64>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) lsl: Option<f64>,
    /// Short-term (within-subgroup) sigma, normally estimated from a control
    /// chart as R-bar/d2 or S-bar/c4. It cannot be recovered from `data`: the
    /// subgroup structure is not in a flat measurement vector.
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) sigma_within: Option<f64>,
    /// Process target for Cpm. Without it `cpm` is `null`.
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) target: Option<f64>,
    /// Degrees of freedom of `sigma_within` -- they depend on how it was
    /// estimated, so the short-term intervals are given only with them.
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) sigma_within_df: Option<f64>,
    /// Confidence level of `intervals`, in (0, 1). Omitted: 0.95.
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) confidence: Option<f64>,
}

/// A two-sided confidence interval.
#[derive(Serialize, Debug, PartialEq)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
pub(crate) struct IntervalDto {
    pub(crate) lower: f64,
    pub(crate) upper: f64,
}

/// Confidence intervals of the capability indices; `null` where the index is,
/// and for `cp` / `cpk` unless `sigma_within_df` was given.
#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct CapabilityIntervalsDto {
    pub(crate) confidence: f64,
    pub(crate) cp: Option<IntervalDto>,
    pub(crate) cpk: Option<IntervalDto>,
    pub(crate) pp: Option<IntervalDto>,
    pub(crate) ppk: Option<IntervalDto>,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct CapabilityDto {
    pub(crate) mean: f64,
    /// `"within"` when `sigma_within` was supplied, `"overall"` otherwise.
    /// Without it the short-term indices are not computed at all rather than
    /// being filled with the long-term sigma -- a number under the wrong name
    /// is harder to notice than a null.
    pub(crate) sigma_source: &'static str,
    pub(crate) std_dev_within: Option<f64>,
    pub(crate) std_dev_overall: f64,
    pub(crate) cp: Option<f64>,
    pub(crate) cpk: Option<f64>,
    pub(crate) cpu: Option<f64>,
    pub(crate) cpl: Option<f64>,
    pub(crate) pp: Option<f64>,
    pub(crate) ppk: Option<f64>,
    pub(crate) ppu: Option<f64>,
    pub(crate) ppl: Option<f64>,
    pub(crate) cpm: Option<f64>,
    pub(crate) intervals: CapabilityIntervalsDto,
}

/// Pure core of [`process_capability`]: the specification, sigma-source and
/// null-handling contract, with no `JsValue` in sight.
///
/// The binding above is a two-line adapter over this. The split is what makes
/// the contract testable at all on a host without a WebAssembly runner --
/// `JsValue` cannot be constructed off `wasm32`, so a monolithic binding is
/// only reachable from a browser or Node. Everything this function decides
/// (which index family is computed, which fields come back `null`, which
/// specification shapes are legal) is the part a consumer actually observes.
pub(crate) fn capability_dto(input: CapabilityInputDto) -> Result<CapabilityDto, WireError> {
    use crate::capability::ProcessCapability;

    check_specification(input.usl, input.lsl)?;
    let mut spec = ProcessCapability::new(input.usl, input.lsl)
        .map_err(|e| WireError::invalid_input(format!("invalid specification limits: {e}")))?;
    if let Some(target) = input.target {
        if !target.is_finite() {
            return Err(WireError::new(
                code::VALUE_NOT_FINITE,
                None,
                format!("target must be finite, got {target}"),
            )
            .about("target"));
        }
        spec = spec.with_target(target);
    }
    let data = at_least(input.data, 2, "data")?;
    let confidence = input.confidence.unwrap_or(0.95);
    if !(confidence > 0.0 && confidence < 1.0) {
        return Err(WireError::out_of_range(
            "confidence",
            Bound::Open(0.0),
            Bound::Open(1.0),
            confidence,
            format!("confidence must be strictly between 0 and 1, got {confidence}"),
        ));
    }
    if let Some(df) = input.sigma_within_df {
        if !(df.is_finite() && df > 0.0) {
            return Err(WireError::out_of_range(
                "sigma_within_df",
                Bound::Open(0.0),
                Bound::Unbounded,
                df,
                format!("sigma_within_df must be a positive, finite number, got {df}"),
            ));
        }
        if input.sigma_within.is_none() {
            return Err(WireError::new(
                code::INVALID_OPTION,
                None,
                "sigma_within_df is the degrees of freedom of sigma_within; give sigma_within with it",
            )
            .about("sigma_within_df"));
        }
    }

    // The crate decides what a missing within sigma means: `compute_overall`
    // reports the long-term indices only, so the short-term quartet and
    // `std_dev_within` arrive as `None` and are passed through as such.
    let indices = match input.sigma_within {
        Some(sigma_within) => {
            if !sigma_within.is_finite() || sigma_within <= 0.0 {
                return Err(WireError::out_of_range(
                    "sigma_within",
                    Bound::Open(0.0),
                    Bound::Unbounded,
                    sigma_within,
                    format!(
                        "sigma_within must be a positive, finite number (R-bar/d2 or \
                         S-bar/c4 from the control chart), got {sigma_within}"
                    ),
                ));
            }
            spec.compute(&data, sigma_within)
        }
        None => spec.compute_overall(&data),
    }
    .ok_or_else(|| {
        WireError::invalid_input("data: every value is the same, so no spread to measure against")
            .about("data")
    })?;

    let ci = indices
        .intervals(confidence, input.sigma_within_df)
        .expect("confidence and sigma_within_df were checked above");
    let interval = |i: Option<crate::capability::ConfidenceInterval>| {
        i.map(|i| IntervalDto {
            lower: i.lower,
            upper: i.upper,
        })
    };
    let dto = CapabilityDto {
        mean: indices.mean,
        sigma_source: if indices.std_dev_within.is_some() {
            "within"
        } else {
            "overall"
        },
        std_dev_within: indices.std_dev_within,
        std_dev_overall: indices.std_dev_overall,
        cp: indices.cp,
        cpk: indices.cpk,
        cpu: indices.cpu,
        cpl: indices.cpl,
        pp: indices.pp,
        ppk: indices.ppk,
        ppu: indices.ppu,
        ppl: indices.ppl,
        // Not a short-term index: Cpm is the spread about the target, the
        // same whichever sigma the caller could supply.
        cpm: indices.cpm,
        intervals: CapabilityIntervalsDto {
            confidence: ci.confidence,
            cp: interval(ci.cp),
            cpk: interval(ci.cpk),
            pp: interval(ci.pp),
            ppk: interval(ci.ppk),
        },
    };
    Ok(dto)
}

/// Input for `percentile_capability`.
#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct PercentileCapabilityInputDto {
    pub(crate) data: Vec<f64>,
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) lsl: Option<f64>,
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) usl: Option<f64>,
    /// The family to fit, by the names `fit_best` reports; absent = the one it
    /// ranks first.
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(
        feature = "wasm",
        tsify(
            type = "\"Normal\" | \"LogNormal\" | \"Weibull\" | \"Gamma\" | \"Exponential\" | \"Beta\" | null"
        )
    )]
    pub(crate) distribution: Option<String>,
}

/// The families `percentile_capability` fits, by the names `fit_best` uses.
pub(crate) const CAPABILITY_MODELS: &[&str] = &[
    "Normal",
    "LogNormal",
    "Weibull",
    "Gamma",
    "Exponential",
    "Beta",
];

fn capability_model(name: &str) -> Option<crate::capability::CapabilityModel> {
    use crate::capability::CapabilityModel as M;
    Some(match name {
        "Normal" => M::Normal,
        "LogNormal" => M::LogNormal,
        "Weibull" => M::Weibull,
        "Gamma" => M::Gamma,
        "Exponential" => M::Exponential,
        "Beta" => M::Beta,
        _ => return None,
    })
}

fn capability_model_name(model: crate::capability::CapabilityModel) -> &'static str {
    use crate::capability::CapabilityModel as M;
    match model {
        M::Normal => "Normal",
        M::LogNormal => "LogNormal",
        M::Weibull => "Weibull",
        M::Gamma => "Gamma",
        M::Exponential => "Exponential",
        M::Beta => "Beta",
        // `percentile_capability` reports the family it fitted, never `Auto`.
        _ => "Auto",
    }
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct PercentileCapabilityDto {
    pub(crate) cp_star: Option<f64>,
    pub(crate) cpk_star: Option<f64>,
    pub(crate) cpu_star: Option<f64>,
    pub(crate) cpl_star: Option<f64>,
    pub(crate) median: f64,
    pub(crate) percentile_lower: f64,
    pub(crate) percentile_upper: f64,
    /// The family the quantiles come from (`fit_best`'s names).
    #[cfg_attr(
        feature = "wasm",
        tsify(
            type = "\"Normal\" | \"LogNormal\" | \"Weibull\" | \"Gamma\" | \"Exponential\" | \"Beta\""
        )
    )]
    pub(crate) distribution: &'static str,
    /// Its fitted parameters by name, as `fit_best` reports them.
    #[cfg_attr(feature = "wasm", tsify(type = "Record<string, number>"))]
    pub(crate) parameters: std::collections::BTreeMap<String, f64>,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct GageRRInputDto {
    pub(crate) measurements: Vec<Vec<Vec<f64>>>,
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) tolerance: Option<f64>,
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct GageChartLimitsDto {
    pub(crate) center: f64,
    pub(crate) ucl: f64,
    pub(crate) lcl: f64,
}

impl From<crate::msa::GageChartLimits> for GageChartLimitsDto {
    fn from(l: crate::msa::GageChartLimits) -> Self {
        GageChartLimitsDto {
            center: l.center,
            ucl: l.ucl,
            lcl: l.lcl,
        }
    }
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct GageRRResultDto {
    /// The range chart the method plots, from the same RÌ„ the components use.
    pub(crate) range_chart: GageChartLimitsDto,
    /// The average chart the method plots.
    pub(crate) average_chart: GageChartLimitsDto,
    pub(crate) ev: f64,
    pub(crate) av: f64,
    pub(crate) grr: f64,
    pub(crate) pv: f64,
    pub(crate) tv: f64,
    pub(crate) percent_ev: f64,
    pub(crate) percent_av: f64,
    pub(crate) percent_grr: f64,
    pub(crate) percent_pv: f64,
    pub(crate) percent_tolerance: Option<f64>,
    pub(crate) ndc: u32,
    pub(crate) status: String,
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct GageRRAnovaResultDto {
    pub(crate) anova_table: Vec<AnovaRowDto>,
    pub(crate) variance_components: VarianceComponentsDto,
    pub(crate) ev: f64,
    pub(crate) av: f64,
    pub(crate) grr: f64,
    pub(crate) pv: f64,
    pub(crate) tv: f64,
    pub(crate) percent_grr: f64,
    pub(crate) percent_tolerance: Option<f64>,
    pub(crate) ndc: u32,
    pub(crate) status: String,
    pub(crate) interaction_significant: bool,
    pub(crate) interaction_pooled: bool,
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct AnovaRowDto {
    pub(crate) source: String,
    pub(crate) df: f64,
    pub(crate) ss: f64,
    pub(crate) ms: f64,
    pub(crate) f_value: Option<f64>,
    pub(crate) p_value: Option<f64>,
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct VarianceComponentsDto {
    pub(crate) part: f64,
    pub(crate) operator: f64,
    pub(crate) interaction: f64,
    pub(crate) repeatability: f64,
    pub(crate) reproducibility: f64,
    pub(crate) total: f64,
}

pub(crate) fn grr_status_str(status: crate::msa::GrrStatus) -> &'static str {
    match status {
        crate::msa::GrrStatus::Acceptable => "Acceptable",
        crate::msa::GrrStatus::Marginal => "Marginal",
        crate::msa::GrrStatus::Unacceptable => "Unacceptable",
    }
}

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct PeltInputDto {
    pub(crate) data: Vec<f64>,
    #[serde(default = "default_cost")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "\"l2\" | \"normal\""))]
    pub(crate) cost: String,
    #[serde(default = "default_penalty")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "\"bic\" | number"))]
    pub(crate) penalty: PeltPenaltyDto,
    #[serde(default = "default_min_seg")]
    #[cfg_attr(feature = "wasm", tsify(optional, type = "number"))]
    pub(crate) min_segment_len: Whole,
}

#[derive(Deserialize)]
#[serde(untagged)]
pub(crate) enum PeltPenaltyDto {
    Named(String),
    Value(f64),
}

#[derive(Serialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct PeltResultDto {
    pub(crate) changepoints: Vec<usize>,
    pub(crate) n_segments: usize,
}

pub(crate) fn default_cost() -> String {
    "l2".to_owned()
}

pub(crate) fn default_penalty() -> PeltPenaltyDto {
    PeltPenaltyDto::Named("bic".to_owned())
}

pub(crate) fn default_min_seg() -> Whole {
    Whole(2.0)
}

/// The specification limits a capability index is measured against, refused
/// by name: neither given (`no_specification`), or `usl` not above `lsl`
/// (`parameter_out_of_range` on `usl`, with `lsl` as its `exclusive_min`).
pub(crate) fn check_specification(usl: Option<f64>, lsl: Option<f64>) -> Result<(), WireError> {
    match (usl, lsl) {
        (None, None) => Err(WireError::new(
            code::NO_SPECIFICATION,
            None,
            "at least one specification limit (usl or lsl) is required",
        )
        .with("expected", Detail::List(vec!["usl", "lsl"]))),
        (Some(u), Some(l)) if u <= l => Err(WireError::out_of_range(
            "usl",
            Bound::Open(l),
            Bound::Unbounded,
            u,
            format!("usl must be greater than lsl ({l}), got {u}"),
        )),
        _ => Ok(()),
    }
}

/// The measurements of a Gage R&R study, `measurements[part][operator][trial]`,
/// refused where they go wrong: too few parts, operators or trials, or a cell
/// of another size than the first (`dimension_mismatch` naming the part).
fn check_gage_shape(measurements: &[Vec<Vec<f64>>]) -> Result<(usize, usize, usize), WireError> {
    let parts = measurements.len();
    if parts < 2 {
        return Err(WireError::too_few(
            "measurements",
            2,
            parts,
            format!("measurements: at least 2 parts are needed, got {parts}"),
        ));
    }
    let operators = measurements[0].len();
    if operators < 2 {
        return Err(WireError::too_few(
            "measurements[0]",
            2,
            operators,
            format!("measurements[0]: at least 2 operators are needed, got {operators}"),
        ));
    }
    let trials = measurements[0][0].len();
    if trials < 2 {
        return Err(WireError::too_few(
            "measurements[0][0]",
            2,
            trials,
            format!("measurements[0][0]: at least 2 trials are needed, got {trials}"),
        ));
    }
    for (p, part) in measurements.iter().enumerate() {
        if part.len() != operators {
            return Err(WireError::new(
                code::DIMENSION_MISMATCH,
                Some(p),
                format!(
                    "measurements[{p}] has {} operators; measurements[0] has {operators}",
                    part.len()
                ),
            )
            .about("measurements")
            .with("expected", Detail::Num(operators as f64))
            .with("got", Detail::Num(part.len() as f64)));
        }
        if let Some(o) = part.iter().position(|cell| cell.len() != trials) {
            return Err(WireError::new(
                code::DIMENSION_MISMATCH,
                Some(o),
                format!(
                    "measurements[{p}][{o}] has {} trials; measurements[0][0] has {trials}",
                    part[o].len()
                ),
            )
            .about(format!("measurements[{p}]"))
            .with("expected", Detail::Num(trials as f64))
            .with("got", Detail::Num(part[o].len() as f64)));
        }
    }
    Ok((parts, operators, trials))
}

pub(crate) fn percentile_capability_dto(
    input: PercentileCapabilityInputDto,
) -> Result<PercentileCapabilityDto, WireError> {
    use crate::capability::{CapabilityModel as M, PercentileCapabilityError as E};
    check_specification(input.usl, input.lsl)?;
    let model = match input.distribution.as_deref() {
        None => M::Auto,
        Some(name) => capability_model(name)
            .ok_or_else(|| WireError::unknown_option("distribution", name, CAPABILITY_MODELS))?,
    };
    let data = at_least(input.data, crate::capability::MIN_PERCENTILE_DATA, "data")?;
    let result = crate::capability::percentile_capability(&data, input.lsl, input.usl, model)
        .map_err(|e| {
            let message = e.to_string();
            match e {
                E::NonFiniteData { index } => {
                    WireError::new(code::VALUE_NOT_FINITE, Some(index), message).about("data")
                }
                // The families on (0, inf) refuse data that reaches 0 or
                // below; name the first such value.
                E::ModelNotFitted(M::LogNormal | M::Weibull | M::Gamma | M::Exponential)
                    if data.iter().any(|&v| v <= 0.0) =>
                {
                    let index = data.iter().position(|&v| v <= 0.0);
                    let got = index.map_or(Detail::Null, |i| Detail::Num(data[i]));
                    WireError::new(code::NON_POSITIVE_DATA, index, message)
                        .about("data")
                        .with("got", got)
                }
                E::ModelNotFitted(_) => {
                    WireError::new(code::INVALID_OPTION, None, message).about("distribution")
                }
                _ => WireError::invalid_input(message).about("data"),
            }
        })?;
    Ok(PercentileCapabilityDto {
        cp_star: result.cp_star,
        cpk_star: result.cpk_star,
        cpu_star: result.cpu_star,
        cpl_star: result.cpl_star,
        median: result.median,
        percentile_lower: result.percentile_lower,
        percentile_upper: result.percentile_upper,
        distribution: capability_model_name(result.model),
        parameters: result.parameters.into_iter().collect(),
    })
}

pub(crate) fn gage_rr_xbar_r_dto(dto: GageRRInputDto) -> Result<GageRRResultDto, WireError> {
    let (parts, operators, trials) = check_gage_shape(&dto.measurements)?;
    // The method's K-factor tables cover these sizes only.
    for (name, at, got, max) in [
        ("trials", "measurements[0][0]", trials, 3),
        ("operators", "measurements[0]", operators, 3),
        ("parts", "measurements", parts, 10),
    ] {
        if got > max {
            return Err(WireError::out_of_range(
                // `parameter` names the array whose length it is.
                match at {
                    "measurements" => "measurements",
                    "measurements[0]" => "measurements[0]",
                    _ => "measurements[0][0]",
                },
                Bound::Closed(2.0),
                Bound::Closed(max as f64),
                got as f64,
                format!("{at}: the XÌ„-R method supports 2 to {max} {name}, got {got}"),
            ));
        }
    }
    let input = crate::msa::GageRRInput {
        measurements: dto.measurements,
        tolerance: dto.tolerance,
    };
    let result = crate::msa::gage_rr_xbar_r(&input)
        .map_err(|e| WireError::invalid_input(e).about("measurements"))?;
    Ok(GageRRResultDto {
        range_chart: result.range_chart.into(),
        average_chart: result.average_chart.into(),
        ev: result.ev,
        av: result.av,
        grr: result.grr,
        pv: result.pv,
        tv: result.tv,
        percent_ev: result.percent_ev,
        percent_av: result.percent_av,
        percent_grr: result.percent_grr,
        percent_pv: result.percent_pv,
        percent_tolerance: result.percent_tolerance,
        ndc: result.ndc,
        status: grr_status_str(result.status).to_owned(),
    })
}

pub(crate) fn gage_rr_anova_dto(dto: GageRRInputDto) -> Result<GageRRAnovaResultDto, WireError> {
    check_gage_shape(&dto.measurements)?;
    let input = crate::msa::GageRRInput {
        measurements: dto.measurements,
        tolerance: dto.tolerance,
    };
    let result = crate::msa::gage_rr_anova(&input)
        .map_err(|e| WireError::invalid_input(e).about("measurements"))?;
    let anova_table = result
        .anova_table
        .rows
        .iter()
        .map(|r| AnovaRowDto {
            source: r.source.clone(),
            df: r.df,
            ss: r.ss,
            ms: r.ms,
            f_value: r.f_value,
            p_value: r.p_value,
        })
        .collect();
    let vc = &result.variance_components;
    Ok(GageRRAnovaResultDto {
        anova_table,
        variance_components: VarianceComponentsDto {
            part: vc.part,
            operator: vc.operator,
            interaction: vc.interaction,
            repeatability: vc.repeatability,
            reproducibility: vc.reproducibility,
            total: vc.total,
        },
        ev: result.ev,
        av: result.av,
        grr: result.grr,
        pv: result.pv,
        tv: result.tv,
        percent_grr: result.percent_grr,
        percent_tolerance: result.percent_tolerance,
        ndc: result.ndc,
        status: grr_status_str(result.status).to_owned(),
        interaction_significant: result.interaction_significant,
        interaction_pooled: result.interaction_pooled,
    })
}

/// A PELT detector from the wire options, naming the option a refusal is about.
pub(crate) fn pelt_from(
    cost: &str,
    penalty: &PeltPenaltyDto,
    min_segment_len: Whole,
) -> Result<crate::detection::Pelt, WireError> {
    use crate::detection::{CostFunction, Penalty};
    let cost = match cost {
        "l2" => CostFunction::L2,
        "normal" => CostFunction::Normal,
        other => return Err(WireError::unknown_option("cost", other, &["l2", "normal"])),
    };
    let penalty = match *penalty {
        PeltPenaltyDto::Named(ref s) if s == "bic" => Penalty::Bic,
        PeltPenaltyDto::Named(ref s) => {
            return Err(WireError::unknown_option("penalty", s, &["bic"]))
        }
        PeltPenaltyDto::Value(v) if !(v.is_finite() && v > 0.0) => {
            return Err(WireError::out_of_range(
                "penalty",
                Bound::Open(0.0),
                Bound::Unbounded,
                v,
                format!("penalty must be \"bic\" or a finite number > 0, got {v}"),
            ))
        }
        PeltPenaltyDto::Value(v) => Penalty::Custom(v),
    };
    // One check for every value below the floor, `-1` and `1` alike.
    let Whole(len) = min_segment_len;
    if len < 2.0 {
        return Err(WireError::out_of_range(
            "min_segment_len",
            Bound::Closed(2.0),
            Bound::Unbounded,
            len,
            format!("min_segment_len must be at least 2, got {len}"),
        ));
    }
    let min_segment_len = min_segment_len.count();
    Ok(
        crate::detection::Pelt::with_min_segment_len(cost, penalty, min_segment_len)
            .expect("cost, penalty and min_segment_len were checked above"),
    )
}

pub(crate) fn pelt_dto(input: PeltInputDto) -> Result<PeltResultDto, WireError> {
    if input.data.is_empty() {
        return Err(WireError::empty_input("data"));
    }
    let pelt = pelt_from(&input.cost, &input.penalty, input.min_segment_len)?;
    let result = pelt.detect(&input.data);
    Ok(PeltResultDto {
        n_segments: result.changepoints.len() + 1,
        changepoints: result.changepoints,
    })
}

/// PELT over several aligned signals: one set of changepoints for all.
#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct MultiPeltInputDto {
    pub(crate) signals: Vec<Vec<f64>>,
    #[serde(default = "default_cost")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "\"l2\" | \"normal\""))]
    pub(crate) cost: String,
    #[serde(default = "default_penalty")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "\"bic\" | number"))]
    pub(crate) penalty: PeltPenaltyDto,
    #[serde(default = "default_min_seg")]
    #[cfg_attr(feature = "wasm", tsify(optional, type = "number"))]
    pub(crate) min_segment_len: Whole,
}

pub(crate) fn multi_pelt_dto(input: MultiPeltInputDto) -> Result<PeltResultDto, WireError> {
    let Some(first) = input.signals.first() else {
        return Err(WireError::empty_input("signals"));
    };
    let expected = first.len();
    if let Some(i) = input.signals.iter().position(|s| s.len() != expected) {
        let got = input.signals[i].len();
        return Err(WireError::new(
            code::DIMENSION_MISMATCH,
            Some(i),
            format!("signals[{i}] has {got} values; signals[0] has {expected}"),
        )
        .about("signals")
        .with("expected", Detail::Num(expected as f64))
        .with("got", Detail::Num(got as f64)));
    }
    if expected == 0 {
        return Err(WireError::empty_input("signals"));
    }
    let pelt = pelt_from(&input.cost, &input.penalty, input.min_segment_len)?;
    let refs: Vec<&[f64]> = input.signals.iter().map(Vec::as_slice).collect();
    let result = pelt
        .detect_multi(&refs)
        .expect("signals were checked non-empty and of one length above");
    Ok(PeltResultDto {
        n_segments: result.changepoints.len() + 1,
        changepoints: result.changepoints,
    })
}

// ── CUSUM / EWMA: online (sequential) shift detection ──────────────────────

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct CusumInputDto {
    pub(crate) data: Vec<f64>,
    pub(crate) target: f64,
    pub(crate) sigma: f64,
    #[serde(default = "default_cusum_k")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    pub(crate) k: f64,
    #[serde(default = "default_cusum_h")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    pub(crate) h: f64,
}

fn default_cusum_k() -> f64 {
    0.5
}

fn default_cusum_h() -> f64 {
    5.0
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct CusumPointDto {
    pub(crate) index: usize,
    pub(crate) s_upper: f64,
    pub(crate) s_lower: f64,
    pub(crate) signal: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct CusumDto {
    /// Decision interval actually used, echoed so a caller can draw the
    /// boundary without restating its own input. Unlike EWMA's widening
    /// limits this one is constant, so it belongs to the chart, not the point.
    pub(crate) h: f64,
    pub(crate) points: Vec<CusumPointDto>,
    pub(crate) signal_indices: Vec<usize>,
    pub(crate) in_control: bool,
}

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct EwmaInputDto {
    pub(crate) data: Vec<f64>,
    pub(crate) target: f64,
    pub(crate) sigma: f64,
    #[serde(default = "default_ewma_lambda")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    pub(crate) lambda: f64,
    #[serde(default = "default_ewma_l_factor")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    pub(crate) l_factor: f64,
}

fn default_ewma_lambda() -> f64 {
    0.2
}

fn default_ewma_l_factor() -> f64 {
    3.0
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct EwmaPointDto {
    pub(crate) index: usize,
    pub(crate) ewma: f64,
    pub(crate) ucl: f64,
    pub(crate) lcl: f64,
    pub(crate) signal: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct EwmaDto {
    pub(crate) points: Vec<EwmaPointDto>,
    pub(crate) signal_indices: Vec<usize>,
    pub(crate) in_control: bool,
}

/// `value` must be a finite number in `low`..`high`; the refusal names it,
/// with the closed ends as `min` / `max` and the open ends as
/// `exclusive_min` / `exclusive_max`.
fn chart_parameter(
    name: &'static str,
    value: f64,
    low: Bound,
    high: Bound,
) -> Result<(), WireError> {
    if value.is_finite() && within(value, low, high) {
        return Ok(());
    }
    Err(WireError::out_of_range(
        name,
        low,
        high,
        value,
        format!("{name} must be {}, got {value}", describe(low, high)),
    ))
}

pub(crate) fn cusum_dto(input: CusumInputDto) -> Result<CusumDto, WireError> {
    if input.data.is_empty() {
        return Err(WireError::empty_input("data"));
    }
    let CusumInputDto {
        target,
        sigma,
        k,
        h,
        ..
    } = input;
    chart_parameter("target", target, Bound::Unbounded, Bound::Unbounded)?;
    chart_parameter("sigma", sigma, Bound::Open(0.0), Bound::Unbounded)?;
    chart_parameter("k", k, Bound::Closed(0.0), Bound::Unbounded)?;
    chart_parameter("h", h, Bound::Open(0.0), Bound::Unbounded)?;
    let chart = crate::detection::Cusum::with_params(target, sigma, k, h)
        .expect("every parameter was checked against the chart's own conditions above");

    let results = chart.analyze(&input.data);
    let signal_indices: Vec<usize> = results
        .iter()
        .filter(|r| r.signal)
        .map(|r| r.index)
        .collect();
    Ok(CusumDto {
        h,
        in_control: signal_indices.is_empty(),
        signal_indices,
        points: results
            .into_iter()
            .map(|r| CusumPointDto {
                index: r.index,
                s_upper: r.s_upper,
                s_lower: r.s_lower,
                signal: r.signal,
            })
            .collect(),
    })
}

pub(crate) fn ewma_dto(input: EwmaInputDto) -> Result<EwmaDto, WireError> {
    if input.data.is_empty() {
        return Err(WireError::empty_input("data"));
    }
    let EwmaInputDto {
        target,
        sigma,
        lambda,
        l_factor,
        ..
    } = input;
    chart_parameter("target", target, Bound::Unbounded, Bound::Unbounded)?;
    chart_parameter("sigma", sigma, Bound::Open(0.0), Bound::Unbounded)?;
    chart_parameter("lambda", lambda, Bound::Open(0.0), Bound::Closed(1.0))?;
    chart_parameter("l_factor", l_factor, Bound::Open(0.0), Bound::Unbounded)?;
    let chart = crate::detection::Ewma::with_params(target, sigma, lambda, l_factor)
        .expect("every parameter was checked against the chart's own conditions above");

    let results = chart.analyze(&input.data);
    let signal_indices: Vec<usize> = results
        .iter()
        .filter(|r| r.signal)
        .map(|r| r.index)
        .collect();
    Ok(EwmaDto {
        in_control: signal_indices.is_empty(),
        signal_indices,
        points: results
            .into_iter()
            .map(|r| EwmaPointDto {
                index: r.index,
                ewma: r.ewma,
                ucl: r.ucl,
                lcl: r.lcl,
                signal: r.signal,
            })
            .collect(),
    })
}

// ── Correlation, simple regression and distribution fitting ────────────────

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct CorrelationInputDto {
    /// Each inner array is one variable; all the same length.
    pub(crate) variables: Vec<Vec<f64>>,
    #[serde(default = "default_correlation_method")]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(
        feature = "wasm",
        tsify(type = "\"pearson\" | \"spearman\" | \"kendall\"")
    )]
    pub(crate) method: String,
}

pub(crate) fn default_correlation_method() -> String {
    "pearson".to_owned()
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct CorrelationMatrixDto {
    /// `matrix[i][j]` is the correlation of variables `i` and `j`.
    pub(crate) matrix: Vec<Vec<f64>>,
}

/// The index of the first variable whose values are all the same, for which
/// no correlation (and no regression slope) is defined.
fn first_constant(variables: &[Vec<f64>]) -> Option<usize> {
    variables.iter().position(|v| v.iter().all(|&x| x == v[0]))
}

pub(crate) fn correlation_matrix_dto(
    input: CorrelationInputDto,
) -> Result<CorrelationMatrixDto, WireError> {
    type MatrixFn = fn(&[&[f64]]) -> Option<u_numflow::matrix::Matrix>;
    let compute: MatrixFn = match input.method.as_str() {
        "pearson" => crate::correlation::correlation_matrix,
        "spearman" => crate::correlation::spearman_matrix,
        "kendall" => crate::correlation::kendall_matrix,
        other => {
            return Err(WireError::unknown_option(
                "method",
                other,
                &["pearson", "spearman", "kendall"],
            ))
        }
    };
    let variables = input.variables;
    if variables.len() < 2 {
        return Err(WireError::too_few(
            "variables",
            2,
            variables.len(),
            format!(
                "variables: a correlation matrix needs at least 2 variables, got {}",
                variables.len()
            ),
        ));
    }
    let n = variables[0].len();
    if let Some(i) = variables.iter().position(|v| v.len() != n) {
        let got = variables[i].len();
        return Err(WireError::new(
            code::DIMENSION_MISMATCH,
            Some(i),
            format!("variables[{i}] has {got} values; variables[0] has {n}"),
        )
        .about("variables")
        .with("expected", Detail::Num(n as f64))
        .with("got", Detail::Num(got as f64)));
    }
    if n < 3 {
        return Err(WireError::too_few(
            "variables",
            3,
            n,
            format!("variables: each variable needs at least 3 values, got {n}"),
        ));
    }
    if let Some(i) = first_constant(&variables) {
        return Err(WireError::new(
            code::INVALID_INPUT,
            Some(i),
            format!("variables[{i}]: every value is the same, so its correlation is undefined"),
        )
        .about("variables"));
    }
    let refs: Vec<&[f64]> = variables.iter().map(Vec::as_slice).collect();
    let m = compute(&refs).ok_or_else(|| {
        WireError::invalid_input(format!(
            "correlation_matrix: the {} correlation is undefined for these variables",
            input.method
        ))
        .about("variables")
    })?;
    Ok(CorrelationMatrixDto {
        matrix: (0..m.rows())
            .map(|i| (0..m.cols()).map(|j| m.get(i, j)).collect())
            .collect(),
    })
}

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct RegressionInputDto {
    pub(crate) x: Vec<f64>,
    pub(crate) y: Vec<f64>,
}

/// Ordinary least squares `y = intercept + slope · x`.
#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct RegressionDto {
    pub(crate) slope: f64,
    pub(crate) intercept: f64,
    pub(crate) r_squared: f64,
    pub(crate) adjusted_r_squared: f64,
    pub(crate) slope_se: f64,
    pub(crate) intercept_se: f64,
    /// `null` when the fit is exact (a standard error of 0).
    pub(crate) slope_t: Option<f64>,
    /// `null` when the fit is exact (a standard error of 0).
    pub(crate) intercept_t: Option<f64>,
    pub(crate) slope_p: f64,
    pub(crate) intercept_p: f64,
    pub(crate) residual_se: f64,
    /// `null` when the fit is exact.
    pub(crate) f_statistic: Option<f64>,
    pub(crate) f_p_value: f64,
    /// `y[i]` minus its fitted value, in input order.
    pub(crate) residuals: Vec<f64>,
    pub(crate) fitted: Vec<f64>,
}

fn finite(v: f64) -> Option<f64> {
    v.is_finite().then_some(v)
}

pub(crate) fn simple_regression_dto(input: RegressionInputDto) -> Result<RegressionDto, WireError> {
    let RegressionInputDto { x, y } = input;
    if y.len() != x.len() {
        return Err(WireError::new(
            code::DIMENSION_MISMATCH,
            None,
            format!("y has {} values; x has {}", y.len(), x.len()),
        )
        .about("y")
        .with("expected", Detail::Num(x.len() as f64))
        .with("got", Detail::Num(y.len() as f64)));
    }
    let x = at_least(x, 3, "x")?;
    if first_constant(std::slice::from_ref(&x)).is_some() {
        return Err(
            WireError::invalid_input("x: every value is the same, so no slope is defined")
                .about("x"),
        );
    }
    let r = crate::regression::simple_linear_regression(&x, &y)
        .expect("lengths, size and variation of x were checked above; values are finite");
    Ok(RegressionDto {
        slope: r.slope,
        intercept: r.intercept,
        r_squared: r.r_squared,
        adjusted_r_squared: r.adjusted_r_squared,
        slope_se: r.slope_se,
        intercept_se: r.intercept_se,
        slope_t: finite(r.slope_t),
        intercept_t: finite(r.intercept_t),
        slope_p: r.slope_p,
        intercept_p: r.intercept_p,
        residual_se: r.residual_se,
        f_statistic: finite(r.f_statistic),
        f_p_value: r.f_p_value,
        residuals: r.residuals,
        fitted: r.fitted,
    })
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct DistributionFitDto {
    /// `"Normal"`, `"Exponential"`, `"Gamma"`, `"LogNormal"`, `"Weibull"` or `"Beta"`.
    #[cfg_attr(
        feature = "wasm",
        tsify(
            type = "\"Normal\" | \"LogNormal\" | \"Weibull\" | \"Gamma\" | \"Exponential\" | \"Beta\""
        )
    )]
    pub(crate) distribution: String,
    /// Estimated parameters by name (`mu`/`sigma`, `lambda`, `alpha`/`beta`,
    /// `shape`/`scale`).
    #[cfg_attr(feature = "wasm", tsify(type = "Record<string, number>"))]
    pub(crate) parameters: std::collections::BTreeMap<String, f64>,
    pub(crate) log_likelihood: f64,
    pub(crate) aic: f64,
    pub(crate) bic: f64,
}

/// Every continuous family that fits `data`, best AIC first.
pub(crate) fn fit_best_dto(data: &[f64]) -> Result<Vec<DistributionFitDto>, WireError> {
    let data = at_least(data.to_vec(), 2, "data")?;
    if first_constant(std::slice::from_ref(&data)).is_some() {
        return Err(WireError::invalid_input(
            "data: every value is the same, so no distribution can be fitted",
        )
        .about("data"));
    }
    let fits = crate::distribution::fit_best(&data);
    debug_assert!(!fits.is_empty(), "Normal fits any non-constant finite data");
    Ok(fits
        .into_iter()
        .map(|f| DistributionFitDto {
            distribution: f.distribution,
            parameters: f.parameters.into_iter().collect(),
            log_likelihood: f.log_likelihood,
            aic: f.aic,
            bic: f.bic,
        })
        .collect())
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct XbarSChartDto {
    pub(crate) xbar_cl: f64,
    pub(crate) xbar_ucl: f64,
    pub(crate) xbar_lcl: f64,
    pub(crate) s_cl: f64,
    pub(crate) s_ucl: f64,
    pub(crate) s_lcl: f64,
    /// Short-term sigma implied by this chart (`S-bar / c4`), for
    /// `process_capability`'s `sigma_within`.
    pub(crate) sigma_hat: f64,
    /// Degrees of freedom of `sigma_hat`, for `sigma_within_df`.
    pub(crate) sigma_hat_df: f64,
    pub(crate) xbar_points: Vec<ChartPointDto>,
    pub(crate) s_points: Vec<ChartPointDto>,
    pub(crate) in_control: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct ImrChartDto {
    pub(crate) i_cl: f64,
    pub(crate) i_ucl: f64,
    pub(crate) i_lcl: f64,
    pub(crate) mr_cl: f64,
    pub(crate) mr_ucl: f64,
    pub(crate) mr_lcl: f64,
    /// Short-term sigma implied by this chart (`MR-bar / d2(2)`).
    pub(crate) sigma_hat: f64,
    /// Degrees of freedom of `sigma_hat` (`0.62 (n - 1)`), for `sigma_within_df`.
    pub(crate) sigma_hat_df: f64,
    pub(crate) i_points: Vec<ChartPointDto>,
    /// Starts at index 1: the first value has no moving range.
    pub(crate) mr_points: Vec<ChartPointDto>,
    pub(crate) in_control: bool,
}

/// Control limits a caller supplies to `run_rules`.
#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct LimitsInputDto {
    pub(crate) ucl: f64,
    pub(crate) cl: f64,
    pub(crate) lcl: f64,
}

pub(crate) fn xbar_s_dto(
    subgroups: Vec<Vec<f64>>,
    rules: crate::spc::RuleSet,
) -> Result<XbarSChartDto, WireError> {
    use crate::spc::{ControlChart, XBarSChart};

    let n = subgroup_size(&subgroups)?;
    let mut chart = XBarSChart::new(n)
        .map_err(|e| WireError::chart("subgroups", None, &e))?
        .with_rules(rules);
    add_rows(&subgroups, "subgroups", |g| chart.add_sample(g))?;
    let too_few = || {
        WireError::too_few(
            "subgroups",
            1,
            0,
            "subgroups: at least one subgroup is needed",
        )
    };
    let x = chart.control_limits().ok_or_else(too_few)?;
    let s = chart.s_limits().ok_or_else(too_few)?;
    Ok(XbarSChartDto {
        xbar_cl: x.cl,
        xbar_ucl: x.ucl,
        xbar_lcl: x.lcl,
        s_cl: s.cl,
        s_ucl: s.ucl,
        s_lcl: s.lcl,
        // Present whenever the limits are: it is their centre line over d2 / c4.
        sigma_hat: chart.sigma_hat().ok_or_else(too_few)?,
        sigma_hat_df: chart.sigma_hat_df().ok_or_else(too_few)?,
        xbar_points: point_dtos(chart.points()),
        s_points: point_dtos(chart.s_points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn imr_dto(
    values: Vec<f64>,
    rules: crate::spc::RuleSet,
) -> Result<ImrChartDto, WireError> {
    use crate::spc::{ControlChart, IndividualMRChart};

    let mut chart = IndividualMRChart::new().with_rules(rules);
    add_rows(&values, "values", |x| {
        chart.add_sample(std::slice::from_ref(x))
    })?;
    let n = values.len();
    let too_few = || {
        WireError::too_few(
            "values",
            2,
            n,
            format!("values: at least two values are needed for control limits, got {n}"),
        )
    };
    let i = chart.control_limits().ok_or_else(too_few)?;
    let mr = chart.mr_limits().ok_or_else(too_few)?;
    Ok(ImrChartDto {
        i_cl: i.cl,
        i_ucl: i.ucl,
        i_lcl: i.lcl,
        mr_cl: mr.cl,
        mr_ucl: mr.ucl,
        mr_lcl: mr.lcl,
        // Present whenever the limits are: it is their centre line over d2 / c4.
        sigma_hat: chart.sigma_hat().ok_or_else(too_few)?,
        sigma_hat_df: chart.sigma_hat_df().ok_or_else(too_few)?,
        i_points: point_dtos(chart.points()),
        mr_points: point_dtos(chart.mr_points()),
        in_control: chart.is_in_control(),
    })
}

pub(crate) fn run_rules_dto(
    values: Vec<f64>,
    limits: LimitsInputDto,
    rules: crate::spc::RuleSet,
) -> Result<Vec<ChartPointDto>, WireError> {
    use crate::spc::{ChartPoint, ControlLimits, RunRule};

    let LimitsInputDto { ucl, cl, lcl } = limits;
    // Written so that a NaN fails it too. The centre line is the one the
    // other two are ordered about, so the refusal names the limit out of place.
    if !(lcl <= cl && cl <= ucl) {
        let (parameter, min, max, got) = if lcl <= cl {
            ("limits.ucl", Bound::Closed(cl), Bound::Unbounded, ucl)
        } else {
            ("limits.lcl", Bound::Unbounded, Bound::Closed(cl), lcl)
        };
        return Err(WireError::out_of_range(
            parameter,
            min,
            max,
            got,
            format!("limits: need lcl <= cl <= ucl, got lcl={lcl} cl={cl} ucl={ucl}"),
        ));
    }
    if let Some(i) = values.iter().position(|x| !x.is_finite()) {
        return Err(WireError::new(
            code::VALUE_NOT_FINITE,
            Some(i),
            format!("values[{i}] is not a finite number"),
        )
        .about("values"));
    }

    let mut points: Vec<ChartPoint> = values
        .iter()
        .enumerate()
        .map(|(index, &value)| ChartPoint {
            value,
            index,
            violations: Vec::new(),
        })
        .collect();
    for (index, rule) in rules.check(&points, &ControlLimits { ucl, cl, lcl }) {
        if let Some(point) = points.get_mut(index) {
            point.violations.push(rule);
        }
    }
    Ok(point_dtos(&points))
}

// ── Seasonality ──────────────────────────────────────────────────────────────

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct SeasonalityInputDto {
    pub(crate) data: Vec<f64>,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct PeriodCandidateDto {
    pub(crate) period: usize,
    pub(crate) acf: f64,
    pub(crate) bin: usize,
    pub(crate) power: f64,
    pub(crate) power_share: f64,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct SeasonalityDto {
    /// `null` when no periodicity passed both stages.
    pub(crate) period: Option<usize>,
    pub(crate) candidates: Vec<PeriodCandidateDto>,
    pub(crate) n: usize,
    pub(crate) acf_threshold: f64,
    pub(crate) power_threshold: f64,
}

pub(crate) fn seasonality_dto(input: SeasonalityInputDto) -> Result<SeasonalityDto, WireError> {
    if let Some(i) = input.data.iter().position(|x| !x.is_finite()) {
        return Err(WireError::new(
            code::VALUE_NOT_FINITE,
            Some(i),
            format!("data[{i}] is not a finite number"),
        )
        .about("data"));
    }
    let n = input.data.len();
    let r = crate::seasonality::estimate_period(&input.data).ok_or_else(|| {
        let min = crate::seasonality::MIN_OBSERVATIONS;
        WireError::too_few(
            "data",
            min,
            n,
            format!("data must have at least {min} observations, got {n}"),
        )
    })?;
    Ok(SeasonalityDto {
        period: r.period,
        candidates: r
            .candidates
            .into_iter()
            .map(|c| PeriodCandidateDto {
                period: c.period,
                acf: c.acf,
                bin: c.bin,
                power: c.power,
                power_share: c.power_share,
            })
            .collect(),
        n: r.n,
        acf_threshold: r.acf_threshold,
        power_threshold: r.power_threshold,
    })
}

// ── Spectral residual ────────────────────────────────────────────────────────

#[derive(Deserialize)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
#[serde(deny_unknown_fields)]
pub(crate) struct SpectralResidualInputDto {
    pub(crate) data: Vec<f64>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) averaging_window: Option<Whole>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) judgement_window: Option<Whole>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) threshold: Option<f64>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) min_zscore: Option<f64>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) sensitivity: Option<f64>,
    #[serde(default)]
    #[cfg_attr(feature = "wasm", tsify(optional))]
    #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
    pub(crate) batch_size: Option<Whole>,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct SrPointDto {
    pub(crate) index: usize,
    pub(crate) value: f64,
    pub(crate) saliency: f64,
    pub(crate) score: f64,
    pub(crate) expected: f64,
    pub(crate) lower: f64,
    pub(crate) upper: f64,
    pub(crate) is_anomaly: bool,
    /// Within kappa = 5 places of an end of its batch, where the transform's
    /// own boundary handling moves the saliency most.
    pub(crate) near_edge: bool,
}

#[derive(Serialize, Debug)]
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[cfg_attr(feature = "wasm", tsify(missing_as_null))]
pub(crate) struct SpectralResidualDto {
    pub(crate) points: Vec<SrPointDto>,
    pub(crate) anomalies: Vec<usize>,
}

impl From<crate::detection::SpectralResidualError> for WireError {
    fn from(error: crate::detection::SpectralResidualError) -> Self {
        use crate::detection::SpectralResidualError as E;
        let message = error.to_string();
        match error {
            E::OptionOutOfRange {
                option,
                min,
                exclusive_min,
                max,
                exclusive_max,
                got,
                ..
            } => WireError::out_of_range(
                option,
                Bound::from_pair(min, exclusive_min),
                Bound::from_pair(max, exclusive_max),
                got,
                message,
            ),
            E::TooFewObservations { needed, got } => {
                WireError::too_few("data", needed, got, message)
            }
            E::ValueNotFinite { index } => {
                WireError::new(code::VALUE_NOT_FINITE, Some(index), message)
            }
        }
    }
}

pub(crate) fn spectral_residual_dto(
    input: SpectralResidualInputDto,
) -> Result<SpectralResidualDto, WireError> {
    use crate::detection::SrCountOption as Count;
    // A count the builder cannot hold (a negative one) is checked against the
    // floor the builder's own check applies, so it is refused the same way.
    let count = |option: Count, value: Whole| -> Result<usize, WireError> {
        option.check(value.0)?;
        Ok(value.count())
    };
    let mut sr = crate::detection::SpectralResidual::new();
    if let Some(q) = input.averaging_window {
        sr = sr.with_averaging_window(count(Count::AveragingWindow, q)?);
    }
    if let Some(z) = input.judgement_window {
        sr = sr.with_judgement_window(count(Count::JudgementWindow, z)?);
    }
    if let Some(t) = input.threshold {
        sr = sr.with_threshold(t);
    }
    if let Some(z) = input.min_zscore {
        sr = sr.with_min_zscore(z);
    }
    if let Some(s) = input.sensitivity {
        sr = sr.with_sensitivity(s);
    }
    if let Some(b) = input.batch_size {
        sr = sr.with_batch_size(Some(count(Count::BatchSize, b)?));
    }
    // The crate owns these rules, so it is the crate that says which one was
    // broken -- the transports only carry the answer.
    let points = sr.analyze(&input.data)?;
    let anomalies = points
        .iter()
        .filter(|p| p.is_anomaly)
        .map(|p| p.index)
        .collect();
    Ok(SpectralResidualDto {
        points: points
            .into_iter()
            .map(|p| SrPointDto {
                index: p.index,
                value: p.value,
                saliency: p.saliency,
                score: p.score,
                expected: p.expected,
                lower: p.lower,
                upper: p.upper,
                is_anomaly: p.is_anomaly,
                near_edge: p.near_edge,
            })
            .collect(),
        anomalies,
    })
}

/// Weibull fits and reliability metrics, Box-Cox capability, and the sigma
/// level ↔ PPM conversion — the reliability and non-normal capability surface
/// both transports carry.
pub(crate) mod reliability {
    use super::*;

    /// The first problem with values that must be finite and `> 0`, placed.
    fn positive_values(param: &'static str, values: &[f64], min: usize) -> Result<(), WireError> {
        for (i, &v) in values.iter().enumerate() {
            if !v.is_finite() {
                return Err(WireError::new(
                    code::VALUE_NOT_FINITE,
                    Some(i),
                    format!("{param}[{i}]: expected a finite number, got {v}"),
                )
                .about(param));
            }
            if v <= 0.0 {
                return Err(WireError::new(
                    code::NON_POSITIVE_DATA,
                    Some(i),
                    format!("{param}[{i}]: must be > 0, got {v}"),
                )
                .about(param)
                .with("got", Detail::Num(v)));
            }
        }
        if values.len() < min {
            return Err(WireError::too_few(
                param,
                min,
                values.len(),
                format!(
                    "{param}: at least {min} values are needed, got {}",
                    values.len()
                ),
            ));
        }
        Ok(())
    }

    /// A finite number `> 0`, or `parameter_out_of_range`.
    fn positive(param: &'static str, x: f64) -> Result<f64, WireError> {
        if x.is_finite() && x > 0.0 {
            Ok(x)
        } else {
            Err(WireError::out_of_range(
                param,
                Bound::Open(0.0),
                Bound::Unbounded,
                x,
                format!("{param} must be a finite number > 0, got {x}"),
            ))
        }
    }

    // ── Weibull fits ──────────────────────────────────────────────────────

    /// `{ failure_times }` — the C ABI request (WebAssembly takes the array).
    #[cfg(feature = "ffi")]
    /// `{ failure_times, suspension_times? }` — the C ABI request of the
    /// median-rank regression, which also takes right-censored units.
    #[cfg(feature = "ffi")]
    #[derive(Deserialize, Debug)]
    #[serde(deny_unknown_fields)]
    pub(crate) struct WeibullMrrRequestDto {
        pub(crate) failure_times: Vec<f64>,
        #[serde(default)]
        pub(crate) suspension_times: Vec<f64>,
    }

    /// `{ failure_times, suspension_times? }` — the C ABI request of the MLE,
    /// which also takes right-censored units.
    #[cfg(feature = "ffi")]
    #[derive(Deserialize, Debug)]
    #[serde(deny_unknown_fields)]
    pub(crate) struct WeibullMleRequestDto {
        pub(crate) failure_times: Vec<f64>,
        #[serde(default)]
        pub(crate) suspension_times: Vec<f64>,
        #[serde(default)]
        pub(crate) confidence: Option<f64>,
        #[serde(default)]
        pub(crate) method: Option<String>,
        #[serde(default)]
        pub(crate) fractions_failed: Vec<f64>,
    }

    /// The interval methods `weibull_mle` takes, as `method` names them.
    pub(crate) const INTERVAL_METHODS: [&str; 2] = ["wald", "likelihood_ratio"];

    /// Two-sided intervals of the Weibull MLE at `confidence`: `wald` --
    /// normal on the log scale from the observed Fisher information -- or
    /// `likelihood_ratio` -- the profile-likelihood interval.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct WeibullIntervalsDto {
        pub(crate) confidence: f64,
        #[cfg_attr(feature = "wasm", tsify(type = "\"wald\" | \"likelihood_ratio\""))]
        pub(crate) method: &'static str,
        pub(crate) shape: crate::wire::IntervalDto,
        pub(crate) scale: crate::wire::IntervalDto,
        /// The B-life intervals, aligned with `fractions_failed`.
        pub(crate) b_life: Vec<crate::wire::IntervalDto>,
    }

    /// Weibull maximum-likelihood fit.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct WeibullMleDto {
        pub(crate) shape: f64,
        pub(crate) scale: f64,
        pub(crate) log_likelihood: f64,
        pub(crate) iterations: usize,
        /// The B-life at each of the requested `fractions_failed`.
        pub(crate) b_life: Vec<f64>,
        pub(crate) intervals: WeibullIntervalsDto,
        /// Asymptotic covariance of `(shape, scale)` -- the inverse of the
        /// observed Fisher information, rows and columns shape, scale. Pass
        /// it to `weibull_reliability` for B-life and reliability intervals.
        #[cfg_attr(feature = "wasm", tsify(type = "[[number, number], [number, number]]"))]
        pub(crate) covariance: [[f64; 2]; 2],
    }

    /// Weibull median-rank-regression fit.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct WeibullMrrDto {
        pub(crate) shape: f64,
        pub(crate) scale: f64,
        pub(crate) r_squared: f64,
    }

    fn degenerate(method: &str) -> WireError {
        WireError::invalid_input(format!(
            "{method}: failure_times has no spread (every value is the same), so the shape is undefined"
        ))
        .about("failure_times")
    }

    /// `suspensions` are right-censored units -- still running, or removed
    /// unfailed, at that time; empty fits the failures alone.
    pub(crate) fn weibull_mle_dto(
        times: &[f64],
        suspensions: &[f64],
        confidence: Option<f64>,
        method: Option<&str>,
        fractions_failed: &[f64],
    ) -> Result<WeibullMleDto, WireError> {
        let method = match method.unwrap_or("wald") {
            m @ ("wald" | "likelihood_ratio") => INTERVAL_METHODS
                .into_iter()
                .find(|n| *n == m)
                .expect("listed"),
            other => {
                return Err(WireError::unknown_option(
                    "method",
                    other,
                    &INTERVAL_METHODS,
                ))
            }
        };
        positive_values("failure_times", times, 2)?;
        positive_values("suspension_times", suspensions, 0)?;
        fractions("fractions_failed", fractions_failed)?;
        let confidence = confidence.unwrap_or(0.95);
        if !(confidence > 0.0 && confidence < 1.0) {
            return Err(WireError::out_of_range(
                "confidence",
                Bound::Open(0.0),
                Bound::Open(1.0),
                confidence,
                format!("confidence must be strictly between 0 and 1, got {confidence}"),
            ));
        }
        let r = crate::weibull::weibull_mle_censored(times, suspensions)
            .ok_or_else(|| degenerate("weibull_mle"))?;
        let dto = |i: crate::weibull::WeibullInterval| crate::wire::IntervalDto {
            lower: i.lower,
            upper: i.upper,
        };
        let ra = crate::weibull::ReliabilityAnalysis::from_mle(&r);
        let b_life: Vec<f64> = fractions_failed
            .iter()
            .map(|&f| ra.b_life(f).expect("fraction checked inside (0, 1)"))
            .collect();
        let (shape, scale, b_life_intervals) = if method == "wald" {
            let checked = "confidence and fractions were checked above";
            (
                dto(r.shape_interval(confidence).expect(checked)),
                dto(r.scale_interval(confidence).expect(checked)),
                fractions_failed
                    .iter()
                    .map(|&f| dto(ra.b_life_interval(f, confidence).expect(checked).1))
                    .collect(),
            )
        } else {
            use crate::weibull::{weibull_likelihood_interval, WeibullQuantity};
            let profile = |q| {
                weibull_likelihood_interval(times, suspensions, q, confidence)
                    .map(|(_, i)| dto(i))
                    .ok_or_else(|| {
                        WireError::invalid_input(
                            "weibull_mle: the likelihood does not fall far enough on one side for a \
                             likelihood-ratio limit (too few failures for it); use method \"wald\"",
                        )
                        .about("method")
                    })
            };
            (
                profile(WeibullQuantity::Shape)?,
                profile(WeibullQuantity::Scale)?,
                fractions_failed
                    .iter()
                    .map(|&f| profile(WeibullQuantity::BLife(f)))
                    .collect::<Result<_, _>>()?,
            )
        };
        let intervals = WeibullIntervalsDto {
            confidence,
            method,
            shape,
            scale,
            b_life: b_life_intervals,
        };
        Ok(WeibullMleDto {
            shape: r.shape,
            scale: r.scale,
            log_likelihood: r.log_likelihood,
            iterations: r.iterations,
            b_life,
            intervals,
            covariance: r.covariance,
        })
    }

    /// `suspensions` move the failures' ranks (Johnson); empty fits the
    /// failures alone.
    pub(crate) fn weibull_mrr_dto(
        times: &[f64],
        suspensions: &[f64],
    ) -> Result<WeibullMrrDto, WireError> {
        positive_values("failure_times", times, 2)?;
        positive_values("suspension_times", suspensions, 0)?;
        let r = crate::weibull::weibull_mrr_censored(times, suspensions)
            .ok_or_else(|| degenerate("weibull_mrr"))?;
        Ok(WeibullMrrDto {
            shape: r.shape,
            scale: r.scale,
            r_squared: r.r_squared,
        })
    }

    /// Fractions failed, each strictly inside (0, 1) -- the B-lives to report.
    fn fractions(parameter: &'static str, values: &[f64]) -> Result<(), WireError> {
        for (i, &f) in values.iter().enumerate() {
            if !(f > 0.0 && f < 1.0) {
                let mut e = WireError::out_of_range(
                    parameter,
                    Bound::Open(0.0),
                    Bound::Open(1.0),
                    f,
                    format!("{parameter}[{i}]: must be strictly inside (0, 1), got {f}"),
                );
                e.index = Some(i);
                return Err(e);
            }
        }
        Ok(())
    }

    // ── Weibull reliability ───────────────────────────────────────────────

    /// `{ shape, scale, times?, fractions_failed?, covariance?, confidence? }`
    /// — a fitted (or known) Weibull and the points to evaluate it at; with
    /// the fit's `covariance`, intervals at `confidence`.
    #[derive(Deserialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[serde(deny_unknown_fields)]
    pub(crate) struct WeibullReliabilityInputDto {
        pub(crate) shape: f64,
        pub(crate) scale: f64,
        /// Times at which to evaluate `R(t)` and `h(t)`.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional))]
        pub(crate) times: Vec<f64>,
        /// Fractions failed (each in `(0, 1)`) whose B-life to report;
        /// `0.1` is B10. (The time to reliability `p` is the B-life at `1 − p`.)
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional))]
        pub(crate) fractions_failed: Vec<f64>,
        /// Covariance of the estimated `(shape, scale)` (`weibull_mle`'s
        /// `covariance`). With it the answer carries `intervals`.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional))]
        #[cfg_attr(
            feature = "wasm",
            tsify(type = "[[number, number], [number, number]] | null")
        )]
        pub(crate) covariance: Option<[[f64; 2]; 2]>,
        /// Confidence level of `intervals`, in (0, 1). Omitted: 0.95. Given
        /// without `covariance` it is refused -- there is nothing to apply it to.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional))]
        #[cfg_attr(feature = "wasm", tsify(type = "number | null"))]
        pub(crate) confidence: Option<f64>,
    }

    /// Two-sided intervals at `confidence`, aligned with the requested times
    /// and fractions: delta method on `ln(−ln R)` and `ln t_p`.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct WeibullReliabilityIntervalsDto {
        pub(crate) confidence: f64,
        pub(crate) reliability: Vec<crate::wire::IntervalDto>,
        pub(crate) b_life: Vec<crate::wire::IntervalDto>,
    }

    /// Reliability metrics of a Weibull, aligned with the input arrays.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct WeibullReliabilityDto {
        /// Mean time between (to) failure, `η·Γ(1 + 1/β)`.
        pub(crate) mtbf: f64,
        /// `R(t)` for each of `times`.
        pub(crate) reliability: Vec<f64>,
        /// `h(t)` for each of `times`.
        pub(crate) hazard_rate: Vec<f64>,
        /// The B-life for each of `fractions_failed`.
        pub(crate) b_life: Vec<f64>,
        /// Intervals for `reliability` and `b_life`; `null` without a
        /// `covariance`.
        pub(crate) intervals: Option<WeibullReliabilityIntervalsDto>,
    }

    pub(crate) fn weibull_reliability_dto(
        input: WeibullReliabilityInputDto,
    ) -> Result<WeibullReliabilityDto, WireError> {
        let shape = positive("shape", input.shape)?;
        let scale = positive("scale", input.scale)?;
        for (i, &t) in input.times.iter().enumerate() {
            if !t.is_finite() {
                return Err(WireError::new(
                    code::VALUE_NOT_FINITE,
                    Some(i),
                    format!("times[{i}]: expected a finite number, got {t}"),
                )
                .about("times"));
            }
        }
        fractions("fractions_failed", &input.fractions_failed)?;
        let mut ra = crate::weibull::ReliabilityAnalysis::new(shape, scale)
            .expect("shape and scale were checked finite and > 0");
        let confidence = match (input.covariance, input.confidence) {
            (None, None) => None,
            (None, Some(_)) => {
                return Err(WireError::new(
                    code::INVALID_OPTION,
                    None,
                    "confidence sets the level of the intervals, which need the fit's covariance",
                )
                .about("confidence"))
            }
            (Some(covariance), confidence) => {
                for (i, v) in covariance.iter().flatten().enumerate() {
                    if !v.is_finite() {
                        return Err(WireError::new(
                            code::VALUE_NOT_FINITE,
                            Some(i),
                            format!("covariance: expected finite numbers, got {v}"),
                        )
                        .about("covariance"));
                    }
                }
                ra = ra.with_covariance(covariance).ok_or_else(|| {
                    WireError::new(
                        code::INVALID_OPTION,
                        None,
                        "covariance must be symmetric and positive definite",
                    )
                    .about("covariance")
                })?;
                let confidence = confidence.unwrap_or(0.95);
                if !(confidence > 0.0 && confidence < 1.0) {
                    return Err(WireError::out_of_range(
                        "confidence",
                        Bound::Open(0.0),
                        Bound::Open(1.0),
                        confidence,
                        format!("confidence must be strictly between 0 and 1, got {confidence}"),
                    ));
                }
                Some(confidence)
            }
        };
        let interval = |(_, i): (f64, crate::weibull::WeibullInterval)| crate::wire::IntervalDto {
            lower: i.lower,
            upper: i.upper,
        };
        let intervals = confidence.map(|confidence| WeibullReliabilityIntervalsDto {
            confidence,
            reliability: input
                .times
                .iter()
                .map(|&t| {
                    interval(
                        ra.reliability_interval(t, confidence)
                            .expect("covariance, confidence and time were checked"),
                    )
                })
                .collect(),
            b_life: input
                .fractions_failed
                .iter()
                .map(|&f| {
                    interval(
                        ra.b_life_interval(f, confidence)
                            .expect("covariance, confidence and fraction were checked"),
                    )
                })
                .collect(),
        });
        Ok(WeibullReliabilityDto {
            mtbf: ra.mtbf(),
            reliability: input.times.iter().map(|&t| ra.reliability(t)).collect(),
            hazard_rate: input.times.iter().map(|&t| ra.hazard_rate(t)).collect(),
            b_life: input
                .fractions_failed
                .iter()
                .map(|&f| ra.b_life(f).expect("fraction checked inside (0, 1)"))
                .collect(),
            intervals,
        })
    }

    // ── Sigma level ↔ PPM ─────────────────────────────────────────────────

    /// PPM at a sigma level (1.5σ shift convention).
    pub(crate) fn sigma_to_ppm_value(sigma: f64) -> Result<f64, WireError> {
        if !sigma.is_finite() {
            return Err(WireError::new(
                code::VALUE_NOT_FINITE,
                None,
                format!("sigma must be a finite number, got {sigma}"),
            )
            .about("sigma"));
        }
        Ok(crate::capability::sigma_to_ppm(sigma))
    }

    /// Sigma level at a PPM, for `ppm` strictly inside `(0, 1_000_000)`.
    pub(crate) fn ppm_to_sigma_value(ppm: f64) -> Result<f64, WireError> {
        crate::capability::ppm_to_sigma(ppm).ok_or_else(|| {
            WireError::out_of_range(
                "ppm",
                Bound::Open(0.0),
                Bound::Open(1_000_000.0),
                ppm,
                format!("ppm must be finite and strictly inside (0, 1000000), got {ppm}"),
            )
        })
    }

    // ── Box-Cox capability ────────────────────────────────────────────────

    #[derive(Deserialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    #[serde(deny_unknown_fields)]
    pub(crate) struct BoxcoxCapabilityInputDto {
        pub(crate) data: Vec<f64>,
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) usl: Option<f64>,
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) lsl: Option<f64>,
        /// `[min, max]` lambda search range; defaults to `[-5, 5]`.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "[number, number] | null"))]
        pub(crate) lambda_range: Option<[f64; 2]>,
    }

    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct BoxcoxCapabilityDto {
        /// Estimated optimal Box-Cox parameter. `0` is a log transform, `1` the
        /// identity, `0.5` approximately a square root.
        pub(crate) lambda: f64,
        /// `true` when the likelihood maximum is on an end of `lambda_range`, so
        /// `lambda` is that limit rather than an interior estimate.
        pub(crate) lambda_at_bound: bool,
        /// Every index below is on the **transformed** scale, which is where the
        /// normal-theory formulas are valid -- they are not comparable to indices
        /// computed on the raw non-normal data.
        pub(crate) cp: Option<f64>,
        pub(crate) cpk: Option<f64>,
        pub(crate) cpu: Option<f64>,
        pub(crate) cpl: Option<f64>,
        pub(crate) pp: Option<f64>,
        pub(crate) ppk: Option<f64>,
        pub(crate) ppu: Option<f64>,
        pub(crate) ppl: Option<f64>,
        pub(crate) cpm: Option<f64>,
    }

    pub(crate) fn boxcox_capability_dto(
        input: BoxcoxCapabilityInputDto,
    ) -> Result<BoxcoxCapabilityDto, WireError> {
        use crate::capability::NonNormalCapabilityError as E;
        positive_values("data", &input.data, 4)?;
        for (name, limit) in [("usl", input.usl), ("lsl", input.lsl)] {
            if let Some(v) = limit {
                positive(name, v)?;
            }
        }
        let range = input
            .lambda_range
            .map_or(crate::capability::DEFAULT_LAMBDA_RANGE, |[lo, hi]| (lo, hi));
        let result = crate::capability::boxcox_capability(&input.data, input.usl, input.lsl, range)
            .map_err(|e| {
                let message = format!("boxcox_capability: {e}");
                match e {
                    E::InvalidLambdaRange => {
                        WireError::new(code::INVALID_OPTION, None, message).about("lambda_range")
                    }
                    E::CapabilityError => WireError::invalid_input(message).about("data"),
                    // Checked above with their place; kept for completeness.
                    E::NonPositiveData => {
                        WireError::new(code::NON_POSITIVE_DATA, None, message).about("data")
                    }
                    E::NonFiniteData => {
                        WireError::new(code::VALUE_NOT_FINITE, None, message).about("data")
                    }
                    E::InsufficientData => {
                        WireError::new(code::INSUFFICIENT_DATA, None, message).about("data")
                    }
                    E::SpecTransformError => WireError::invalid_input(message),
                }
            })?;
        let i = result.indices.as_ref();
        Ok(BoxcoxCapabilityDto {
            lambda: result.lambda,
            lambda_at_bound: result.lambda_at_bound,
            cp: i.and_then(|i| i.cp),
            cpk: i.and_then(|i| i.cpk),
            cpu: i.and_then(|i| i.cpu),
            cpl: i.and_then(|i| i.cpl),
            pp: i.and_then(|i| i.pp),
            ppk: i.and_then(|i| i.ppk),
            ppu: i.and_then(|i| i.ppu),
            ppl: i.and_then(|i| i.ppl),
            cpm: i.and_then(|i| i.cpm),
        })
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        #[test]
        fn weibull_fits_refuse_with_the_place() {
            let e = weibull_mle_dto(&[10.0, 20.0], &[30.0, -1.0], None, None, &[]).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref(), e.index),
                ("non_positive_data", Some("suspension_times"), Some(1))
            );
            let fit =
                weibull_mle_dto(&[55.0, 187.0, 216.0], &[361.0, 373.0], None, None, &[]).unwrap();
            let alone = weibull_mle_dto(&[55.0, 187.0, 216.0], &[], None, None, &[]).unwrap();
            assert!(fit.scale > alone.scale);
            assert_eq!(fit.intervals.confidence, 0.95);
            assert!(fit.intervals.shape.lower < fit.shape && fit.shape < fit.intervals.shape.upper);
            assert!(fit.intervals.scale.lower < fit.scale && fit.scale < fit.intervals.scale.upper);
            let e = weibull_mle_dto(&[55.0, 187.0, 216.0], &[], Some(1.0), None, &[]).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("parameter_out_of_range", Some("confidence"))
            );
            let e = weibull_mle_dto(&[10.0, -1.0], &[], None, None, &[]).unwrap_err();
            assert_eq!(
                (e.code, e.index, e.parameter.as_deref()),
                ("non_positive_data", Some(1), Some("failure_times"))
            );
            let e = weibull_mrr_dto(&[10.0, f64::NAN], &[]).unwrap_err();
            assert_eq!((e.code, e.index), ("value_not_finite", Some(1)));
            let e = weibull_mrr_dto(&[10.0], &[]).unwrap_err();
            assert_eq!(
                e.details,
                vec![("min", Detail::Num(2.0)), ("got", Detail::Num(1.0))]
            );
            let e = weibull_mle_dto(&[5.0, 5.0, 5.0], &[], None, None, &[]).unwrap_err();
            assert_eq!(e.code, "invalid_input");
            let ok = weibull_mrr_dto(&[150.0, 200.0, 250.0, 300.0, 350.0, 400.0], &[]).unwrap();
            assert!(ok.shape > 0.0 && ok.r_squared > 0.9);
            let censored =
                weibull_mrr_dto(&[150.0, 200.0, 250.0, 300.0, 350.0, 400.0], &[450.0, 450.0])
                    .unwrap();
            assert!(censored.scale > ok.scale);
            let e = weibull_mrr_dto(&[150.0, 200.0], &[0.0]).unwrap_err();
            assert_eq!(e.parameter.as_deref(), Some("suspension_times"));
        }

        #[test]
        fn reliability_is_aligned_with_its_inputs() {
            let r = weibull_reliability_dto(WeibullReliabilityInputDto {
                shape: 2.0,
                scale: 100.0,
                times: vec![0.0, 100.0],
                fractions_failed: vec![0.1, 0.5],
                covariance: None,
                confidence: None,
            })
            .unwrap();
            assert!((r.reliability[1] - (-1.0f64).exp()).abs() < 1e-12);
            assert_eq!(r.reliability[0], 1.0);
            assert_eq!((r.hazard_rate.len(), r.b_life.len()), (2, 2));
            // B10 = η·(−ln 0.9)^(1/β)
            assert!((r.b_life[0] - 100.0 * (-(0.9f64).ln()).sqrt()).abs() < 1e-9);
            assert!((r.mtbf - 100.0 * 0.886_226_925_452_758).abs() < 1e-9);

            let e = weibull_reliability_dto(WeibullReliabilityInputDto {
                shape: 0.0,
                scale: 1.0,
                times: vec![],
                fractions_failed: vec![],
                covariance: None,
                confidence: None,
            })
            .unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("parameter_out_of_range", Some("shape"))
            );
            let e = weibull_reliability_dto(WeibullReliabilityInputDto {
                shape: 1.0,
                scale: 1.0,
                times: vec![],
                fractions_failed: vec![0.5, 1.0],
                covariance: None,
                confidence: None,
            })
            .unwrap_err();
            assert_eq!(
                (e.code, e.index, e.parameter.as_deref()),
                ("parameter_out_of_range", Some(1), Some("fractions_failed"))
            );
        }

        #[test]
        fn the_mle_s_intervals_take_a_method() {
            let (f, s) = (
                &[55.0, 187.0, 216.0, 240.0, 244.0, 335.0][..],
                &[361.0, 373.0][..],
            );
            let wald = weibull_mle_dto(f, s, Some(0.9), None, &[]).unwrap();
            assert_eq!(wald.intervals.method, "wald");
            let lr = weibull_mle_dto(f, s, Some(0.9), Some("likelihood_ratio"), &[]).unwrap();
            assert_eq!(lr.intervals.method, "likelihood_ratio");
            let (_, core) = crate::weibull::weibull_likelihood_interval(
                f,
                s,
                crate::weibull::WeibullQuantity::Scale,
                0.9,
            )
            .unwrap();
            assert_eq!(
                (lr.intervals.scale.lower, lr.intervals.scale.upper),
                (core.lower, core.upper)
            );
            // Same fit, same covariance: only the intervals differ.
            assert_eq!((lr.shape, lr.covariance), (wald.shape, wald.covariance));
            assert_ne!(lr.intervals.shape, wald.intervals.shape);
            let e = weibull_mle_dto(f, s, None, Some("bootstrap"), &[]).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("unknown_option", Some("method"))
            );
            // B-lives at the requested fractions, by the same method.
            let wald = weibull_mle_dto(f, s, Some(0.9), None, &[0.1, 0.5]).unwrap();
            let lr =
                weibull_mle_dto(f, s, Some(0.9), Some("likelihood_ratio"), &[0.1, 0.5]).unwrap();
            assert_eq!(wald.b_life, lr.b_life);
            assert_eq!(
                (wald.intervals.b_life.len(), lr.intervals.b_life.len()),
                (2, 2)
            );
            let core = crate::weibull::weibull_mle_censored(f, s).unwrap();
            let (b10, ci) = core.b_life_interval(0.1, 0.9).unwrap();
            assert_eq!(
                (
                    wald.b_life[0],
                    wald.intervals.b_life[0].lower,
                    wald.intervals.b_life[0].upper
                ),
                (b10, ci.lower, ci.upper)
            );
            let (_, lr10) = crate::weibull::weibull_likelihood_interval(
                f,
                s,
                crate::weibull::WeibullQuantity::BLife(0.1),
                0.9,
            )
            .unwrap();
            assert_eq!(
                (lr.intervals.b_life[0].lower, lr.intervals.b_life[0].upper),
                (lr10.lower, lr10.upper)
            );
            let e = weibull_mle_dto(f, s, None, None, &[0.1, 1.0]).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref(), e.index),
                ("parameter_out_of_range", Some("fractions_failed"), Some(1))
            );
        }

        /// The fit's covariance, passed through, gives the intervals the
        /// core gives the fit -- one definition.
        #[test]
        fn reliability_intervals_come_from_the_fit_s_covariance() {
            let times = [55.0, 187.0, 216.0, 240.0, 244.0, 335.0, 361.0, 373.0];
            let fit = weibull_mle_dto(&times, &[400.0, 400.0], None, None, &[]).unwrap();
            let input = |covariance, confidence| WeibullReliabilityInputDto {
                shape: fit.shape,
                scale: fit.scale,
                times: vec![0.0, 150.0],
                fractions_failed: vec![0.1],
                covariance,
                confidence,
            };
            let r = weibull_reliability_dto(input(Some(fit.covariance), Some(0.9))).unwrap();
            let i = r.intervals.as_ref().expect("covariance given");
            assert_eq!(i.confidence, 0.9);
            assert_eq!((i.reliability.len(), i.b_life.len()), (2, 1));
            assert_eq!((i.reliability[0].lower, i.reliability[0].upper), (1.0, 1.0));
            assert!(
                i.reliability[1].lower < r.reliability[1]
                    && r.reliability[1] < i.reliability[1].upper
            );
            let core = crate::weibull::weibull_mle_censored(&times, &[400.0, 400.0]).unwrap();
            let (b10, ci) = core.b_life_interval(0.1, 0.9).unwrap();
            assert_eq!(
                (r.b_life[0], i.b_life[0].lower, i.b_life[0].upper),
                (b10, ci.lower, ci.upper)
            );
            let r = weibull_reliability_dto(input(Some(fit.covariance), None)).unwrap();
            assert_eq!(r.intervals.expect("default level").confidence, 0.95);
            assert!(weibull_reliability_dto(input(None, None))
                .unwrap()
                .intervals
                .is_none());

            let refused = |covariance, confidence| {
                let e = weibull_reliability_dto(input(covariance, confidence)).unwrap_err();
                (e.code, e.parameter, e.index)
            };
            assert_eq!(
                refused(None, Some(0.9)),
                ("invalid_option", Some("confidence".into()), None)
            );
            assert_eq!(
                refused(Some([[0.04, 2.0], [2.0, 25.0]]), None),
                ("invalid_option", Some("covariance".into()), None)
            );
            assert_eq!(
                refused(Some([[0.04, 0.1], [0.1, f64::INFINITY]]), None),
                ("value_not_finite", Some("covariance".into()), Some(3))
            );
            assert_eq!(
                refused(Some(fit.covariance), Some(1.0)),
                ("parameter_out_of_range", Some("confidence".into()), None)
            );
        }

        #[test]
        fn sigma_and_ppm_refuse_by_code() {
            assert!((ppm_to_sigma_value(3.4).unwrap() - 6.0).abs() < 1e-2);
            let e = ppm_to_sigma_value(0.0).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("parameter_out_of_range", Some("ppm"))
            );
            // (0, 1 000 000): both ends open.
            assert_eq!(
                e.details,
                vec![
                    ("min", Detail::Null),
                    ("exclusive_min", Detail::Num(0.0)),
                    ("max", Detail::Null),
                    ("exclusive_max", Detail::Num(1_000_000.0)),
                    ("got", Detail::Num(0.0)),
                ]
            );
            let e = sigma_to_ppm_value(f64::NAN).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("value_not_finite", Some("sigma"))
            );
        }

        #[test]
        fn boxcox_refusals_name_their_input() {
            let input = |data: Vec<f64>, usl: Option<f64>, range: Option<[f64; 2]>| {
                BoxcoxCapabilityInputDto {
                    data,
                    usl,
                    lsl: None,
                    lambda_range: range,
                }
            };
            let e = boxcox_capability_dto(input(vec![1.0, 2.0, 0.0, 3.0], Some(9.0), None))
                .unwrap_err();
            assert_eq!((e.code, e.index), ("non_positive_data", Some(2)));
            let e = boxcox_capability_dto(input(vec![1.0, 2.0, 3.0], Some(9.0), None)).unwrap_err();
            assert_eq!(
                e.details,
                vec![("min", Detail::Num(4.0)), ("got", Detail::Num(3.0))]
            );
            let e = boxcox_capability_dto(input(vec![1.0, 2.0, 3.0, 4.0], Some(-1.0), None))
                .unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("parameter_out_of_range", Some("usl"))
            );
            let e =
                boxcox_capability_dto(input(vec![1.0, 2.0, 3.0, 4.0], Some(9.0), Some([2.0, 1.0])))
                    .unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("invalid_option", Some("lambda_range"))
            );
        }
    }
}

/// Increments of a cumulative counter (`crate::counter`).
pub(crate) mod counter {
    use super::*;
    use crate::counter::{
        counter_increments, counter_totals, CounterError, CounterIncrement, CounterOptions,
        Discontinuity, IncrementKind,
    };

    /// A reset or replacement the caller declares: when, the register's value
    /// right after it, and (when read) the old register's last value.
    #[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[serde(deny_unknown_fields)]
    pub(crate) struct DiscontinuityDto {
        pub(crate) time: f64,
        pub(crate) start: f64,
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) last: Option<f64>,
    }

    /// The settings of a counter's increments; every one may be left out.
    #[derive(Deserialize, Debug, Clone, Default, PartialEq)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[serde(deny_unknown_fields)]
    pub(crate) struct CounterOptionsDto {
        /// The value at which the register returns to 0.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) modulus: Option<f64>,
        /// The most the counter can advance per unit of time.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional, type = "number | null"))]
        pub(crate) max_rate: Option<f64>,
        /// Resets and replacements, in time order.
        #[serde(default)]
        #[cfg_attr(feature = "wasm", tsify(optional))]
        pub(crate) discontinuities: Vec<DiscontinuityDto>,
    }

    impl From<&CounterOptionsDto> for CounterOptions {
        fn from(o: &CounterOptionsDto) -> Self {
            CounterOptions {
                modulus: o.modulus,
                max_rate: o.max_rate,
                discontinuities: o
                    .discontinuities
                    .iter()
                    .map(|d| Discontinuity {
                        time: d.time,
                        start: d.start,
                        last: d.last,
                    })
                    .collect(),
            }
        }
    }

    /// How much the counter advanced between two neighbouring readings.
    #[derive(Serialize, Debug, PartialEq)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct CounterIncrementDto {
        pub(crate) start: f64,
        pub(crate) end: f64,
        /// `null` when `kind` is `"unexplained"`.
        pub(crate) increase: Option<f64>,
        #[cfg_attr(
            feature = "wasm",
            tsify(type = "\"normal\" | \"declared\" | \"wrap\" | \"unexplained\"")
        )]
        pub(crate) kind: &'static str,
    }

    impl From<CounterIncrement> for CounterIncrementDto {
        fn from(i: CounterIncrement) -> Self {
            CounterIncrementDto {
                start: i.start,
                end: i.end,
                increase: i.increase,
                kind: match i.kind {
                    IncrementKind::Normal => "normal",
                    IncrementKind::Declared => "declared",
                    IncrementKind::Wrap => "wrap",
                    IncrementKind::Unexplained => "unexplained",
                },
            }
        }
    }

    /// The increments that end in one interval `[start, end)`.
    #[derive(Serialize, Debug, PartialEq)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    pub(crate) struct CounterTotalDto {
        pub(crate) start: f64,
        pub(crate) end: f64,
        pub(crate) increase: f64,
        pub(crate) pairs: usize,
        pub(crate) unexplained: usize,
    }

    fn refusal(e: CounterError) -> WireError {
        let message = e.to_string();
        match e {
            CounterError::LengthMismatch { times, values } => {
                WireError::new(code::DIMENSION_MISMATCH, None, message)
                    .about("values")
                    .with("expected", Detail::Num(times as f64))
                    .with("got", Detail::Num(values as f64))
            }
            CounterError::TooFewReadings { got } => {
                // Readings, or interval edges: both need two.
                WireError::too_few("times", 2, got, message)
            }
            CounterError::NotFinite { parameter, index } => {
                WireError::new(code::VALUE_NOT_FINITE, index, message).about(parameter)
            }
            CounterError::Unordered { parameter, index } => {
                WireError::new(code::EVENTS_UNORDERED, Some(index), message).about(parameter)
            }
            CounterError::NotPositive { parameter, got } => {
                WireError::out_of_range(parameter, Bound::Open(0.0), Bound::Unbounded, got, message)
            }
            CounterError::OutsideModulus {
                parameter,
                index,
                got,
                modulus,
            } => {
                let mut e = WireError::out_of_range(
                    parameter,
                    Bound::Closed(0.0),
                    Bound::Open(modulus),
                    got,
                    message,
                );
                e.index = Some(index);
                e
            }
            CounterError::OutsideReadings {
                index,
                got,
                first,
                last,
            } => {
                let mut e = WireError::out_of_range(
                    "discontinuities.time",
                    Bound::Open(first),
                    Bound::Closed(last),
                    got,
                    message,
                );
                e.index = Some(index);
                e
            }
            CounterError::TwoInOnePair { index } => {
                WireError::new(code::INVALID_OPTION, Some(index), message).about("discontinuities")
            }
        }
    }

    /// The C ABI's request for the increments: the readings and, flat beside
    /// them, the settings.
    #[cfg(feature = "ffi")]
    #[derive(Deserialize, Debug)]
    #[serde(deny_unknown_fields)]
    pub(crate) struct CounterRequestDto {
        pub(crate) times: Vec<f64>,
        pub(crate) values: Vec<f64>,
        #[serde(default)]
        pub(crate) modulus: Option<f64>,
        #[serde(default)]
        pub(crate) max_rate: Option<f64>,
        #[serde(default)]
        pub(crate) discontinuities: Vec<DiscontinuityDto>,
    }

    /// The C ABI's request for the totals: the increments' request and the
    /// interval `edges`.
    #[cfg(feature = "ffi")]
    #[derive(Deserialize, Debug)]
    #[serde(deny_unknown_fields)]
    pub(crate) struct CounterTotalsRequestDto {
        pub(crate) times: Vec<f64>,
        pub(crate) values: Vec<f64>,
        pub(crate) edges: Vec<f64>,
        #[serde(default)]
        pub(crate) modulus: Option<f64>,
        #[serde(default)]
        pub(crate) max_rate: Option<f64>,
        #[serde(default)]
        pub(crate) discontinuities: Vec<DiscontinuityDto>,
    }

    #[cfg(feature = "ffi")]
    pub(crate) fn options_of(
        modulus: Option<f64>,
        max_rate: Option<f64>,
        discontinuities: &[DiscontinuityDto],
    ) -> CounterOptionsDto {
        CounterOptionsDto {
            modulus,
            max_rate,
            discontinuities: discontinuities.to_vec(),
        }
    }

    pub(crate) fn increments_dto(
        times: &[f64],
        values: &[f64],
        options: &CounterOptionsDto,
    ) -> Result<Vec<CounterIncrementDto>, WireError> {
        counter_increments(times, values, &options.into())
            .map(|v| v.into_iter().map(Into::into).collect())
            .map_err(refusal)
    }

    pub(crate) fn totals_dto(
        times: &[f64],
        values: &[f64],
        edges: &[f64],
        options: &CounterOptionsDto,
    ) -> Result<Vec<CounterTotalDto>, WireError> {
        let increments = counter_increments(times, values, &options.into()).map_err(refusal)?;
        let totals = counter_totals(&increments, edges).map_err(|e| match e {
            CounterError::TooFewReadings { got } => WireError::too_few(
                "edges",
                2,
                got,
                format!("at least 2 edges are needed for one interval, got {got}"),
            ),
            other => refusal(other),
        })?;
        Ok(totals
            .into_iter()
            .map(|t| CounterTotalDto {
                start: t.start,
                end: t.end,
                increase: t.increase,
                pairs: t.pairs,
                unexplained: t.unexplained,
            })
            .collect())
    }
}

#[cfg(test)]
mod counter_wire_tests {
    use super::counter::*;

    #[test]
    fn increments_carry_their_kind_on_the_wire() {
        let o = CounterOptionsDto {
            modulus: Some(1000.0),
            ..Default::default()
        };
        let out = increments_dto(&[0.0, 1.0, 2.0], &[990.0, 995.0, 4.0], &o).unwrap();
        assert_eq!(out[0].kind, "normal");
        assert_eq!((out[1].kind, out[1].increase), ("wrap", Some(9.0)));
        let out = increments_dto(&[0.0, 1.0], &[5.0, 4.0], &CounterOptionsDto::default()).unwrap();
        assert_eq!((out[0].kind, out[0].increase), ("unexplained", None));
    }

    #[test]
    fn counter_refusals_use_the_shared_reasons() {
        let none = CounterOptionsDto::default();
        let e = increments_dto(&[0.0, 1.0], &[1.0], &none).unwrap_err();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("dimension_mismatch", Some("values"))
        );
        let e = increments_dto(&[1.0, 1.0], &[1.0, 2.0], &none).unwrap_err();
        assert_eq!((e.code, e.index), ("events_unordered", Some(1)));
        let o = CounterOptionsDto {
            modulus: Some(10.0),
            ..Default::default()
        };
        let e = increments_dto(&[0.0, 1.0], &[1.0, 12.0], &o).unwrap_err();
        assert_eq!((e.code, e.index), ("parameter_out_of_range", Some(1)));
        let o = CounterOptionsDto {
            discontinuities: vec![DiscontinuityDto {
                time: 5.0,
                start: 0.0,
                last: None,
            }],
            ..Default::default()
        };
        let e = increments_dto(&[0.0, 1.0], &[1.0, 2.0], &o).unwrap_err();
        assert_eq!(
            (e.code, e.parameter.as_deref(), e.index),
            (
                "parameter_out_of_range",
                Some("discontinuities.time"),
                Some(0)
            )
        );
        let e = totals_dto(&[0.0, 1.0], &[1.0, 2.0], &[0.0], &none).unwrap_err();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("insufficient_data", Some("edges"))
        );
    }

    #[test]
    fn totals_sum_the_pairs_ending_in_each_interval() {
        let t = totals_dto(
            &[0.0, 6.0, 12.0, 24.0, 30.0],
            &[0.0, 1.0, 3.0, 4.0, 2.0],
            &[0.0, 24.0, 48.0],
            &CounterOptionsDto::default(),
        )
        .unwrap();
        assert_eq!((t[0].increase, t[0].pairs, t[0].unexplained), (3.0, 2, 0));
        assert_eq!((t[1].increase, t[1].pairs, t[1].unexplained), (1.0, 2, 1));
    }
}

/// Trend tests and the power-law fit on event times (`crate::point_process`).
pub(crate) mod point_process {
    use super::*;
    use crate::point_process::{PointProcessError, TrendDirection, TrendTestResult, Truncation};

    /// How observation ended: `{ truncation: "time", end }` — watched until
    /// `end` — or `{ truncation: "failure" }` — stopped at the last event.
    #[derive(Deserialize, Debug, Clone, Copy, PartialEq)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[serde(tag = "truncation", rename_all = "snake_case", deny_unknown_fields)]
    pub(crate) enum ObservationDto {
        Time { end: f64 },
        Failure {},
    }

    /// The `truncation` names [`ObservationDto`] accepts.
    pub(crate) const TRUNCATIONS: &[&str] = &["time", "failure"];

    /// `truncation` is a name this function knows, or `unknown_option`.
    pub(crate) fn check_truncation(name: &str) -> Result<(), WireError> {
        if TRUNCATIONS.contains(&name) {
            return Ok(());
        }
        Err(WireError::unknown_option(
            "observation.truncation",
            name,
            TRUNCATIONS,
        ))
    }

    impl From<ObservationDto> for Truncation {
        fn from(o: ObservationDto) -> Self {
            match o {
                ObservationDto::Time { end } => Truncation::Time(end),
                ObservationDto::Failure {} => Truncation::Failure,
            }
        }
    }

    /// A trend test against a constant event rate.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct TrendTestDto {
        pub(crate) statistic: f64,
        /// Two-sided; the one-sided p-value in `direction` is half of it.
        pub(crate) p_value: f64,
        #[cfg_attr(
            feature = "wasm",
            tsify(type = "\"increasing\" | \"decreasing\" | \"flat\"")
        )]
        pub(crate) direction: &'static str,
        pub(crate) events_used: usize,
        /// χ² degrees of freedom (MIL-HDBK-189); `null` for Laplace.
        pub(crate) df: Option<f64>,
    }

    impl From<TrendTestResult> for TrendTestDto {
        fn from(r: TrendTestResult) -> Self {
            TrendTestDto {
                statistic: r.statistic,
                p_value: r.p_value,
                direction: match r.direction {
                    TrendDirection::Increasing => "increasing",
                    TrendDirection::Decreasing => "decreasing",
                    TrendDirection::Flat => "flat",
                },
                events_used: r.events_used,
                df: r.degrees_of_freedom,
            }
        }
    }

    /// A power-law process (Crow-AMSAA) fit.
    #[derive(Serialize, Debug)]
    #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
    #[cfg_attr(feature = "wasm", tsify(missing_as_null))]
    pub(crate) struct PowerLawFitDto {
        pub(crate) beta: f64,
        pub(crate) beta_unbiased: f64,
        pub(crate) lambda: f64,
        pub(crate) intensity_at_end: f64,
        pub(crate) end: f64,
        pub(crate) events: usize,
    }

    fn refusal(e: PointProcessError) -> WireError {
        let message = format!("times: {e}");
        match e {
            PointProcessError::TooFewEvents { min, got } => {
                WireError::too_few("times", min, got, message)
            }
            PointProcessError::NotFinite { index: Some(i) } => {
                WireError::new(code::VALUE_NOT_FINITE, Some(i), message).about("times")
            }
            PointProcessError::NotFinite { index: None } => {
                WireError::new(code::VALUE_NOT_FINITE, None, message).about("observation.end")
            }
            PointProcessError::NotPositive { index, got } => {
                let mut e = WireError::out_of_range(
                    if index.is_some() {
                        "times"
                    } else {
                        "observation.end"
                    },
                    Bound::Open(0.0),
                    Bound::Unbounded,
                    got,
                    message,
                );
                e.index = index;
                e
            }
            PointProcessError::Unordered { index } => {
                WireError::new(code::EVENTS_UNORDERED, Some(index), message).about("times")
            }
            PointProcessError::AfterEnd { index } => {
                WireError::new(code::EVENT_AFTER_END, Some(index), message).about("times")
            }
        }
    }

    pub(crate) fn laplace_dto(times: &[f64], o: ObservationDto) -> Result<TrendTestDto, WireError> {
        crate::point_process::laplace_trend_test(times, o.into())
            .map(Into::into)
            .map_err(refusal)
    }

    pub(crate) fn mil_hdbk_189_dto(
        times: &[f64],
        o: ObservationDto,
    ) -> Result<TrendTestDto, WireError> {
        crate::point_process::mil_hdbk_189_test(times, o.into())
            .map(Into::into)
            .map_err(refusal)
    }

    pub(crate) fn power_law_dto(
        times: &[f64],
        o: ObservationDto,
    ) -> Result<PowerLawFitDto, WireError> {
        crate::point_process::power_law_process_fit(times, o.into())
            .map(|f| PowerLawFitDto {
                beta: f.beta,
                beta_unbiased: f.beta_unbiased,
                lambda: f.lambda,
                intensity_at_end: f.intensity_at_end,
                end: f.end,
                events: f.events,
            })
            .map_err(refusal)
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use serde_json::json;

        #[test]
        fn observation_reads_both_shapes_and_refuses_unknown_keys() {
            let t: ObservationDto =
                serde_json::from_value(json!({ "truncation": "time", "end": 60 })).unwrap();
            assert_eq!(t, ObservationDto::Time { end: 60.0 });
            let f: ObservationDto =
                serde_json::from_value(json!({ "truncation": "failure" })).unwrap();
            assert_eq!(f, ObservationDto::Failure {});
            assert!(serde_json::from_value::<ObservationDto>(
                json!({ "truncation": "failure", "end": 3 })
            )
            .is_err());
            let e = check_truncation("timed").unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("unknown_option", Some("observation.truncation"))
            );
        }

        #[test]
        fn refusals_place_the_event() {
            let o = ObservationDto::Time { end: 10.0 };
            let e = laplace_dto(&[2.0, 1.0], o).unwrap_err();
            assert_eq!(
                (e.code, e.index, e.parameter.as_deref()),
                ("events_unordered", Some(1), Some("times"))
            );
            let e = laplace_dto(&[2.0, 11.0], o).unwrap_err();
            assert_eq!((e.code, e.index), ("event_after_end", Some(1)));
            let e = mil_hdbk_189_dto(&[2.0], ObservationDto::Time { end: 0.0 }).unwrap_err();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("parameter_out_of_range", Some("observation.end"))
            );
            let e = power_law_dto(&[1.0, 2.0], ObservationDto::Failure {}).unwrap_err();
            assert_eq!(e.code, "insufficient_data");
        }

        #[test]
        fn results_carry_the_direction_by_name() {
            let o = ObservationDto::Time { end: 60.0 };
            let r = mil_hdbk_189_dto(&[12.0, 15.0, 27.0, 34.0, 44.0, 53.0], o).unwrap();
            assert_eq!((r.direction, r.df), ("increasing", Some(12.0)));
            assert!(laplace_dto(&[12.0, 15.0], o).unwrap().df.is_none());
        }
    }
}

#[cfg(test)]
mod input_error_tests {
    /// Every refusal names what it is about (C464): these were strings that
    /// left `parameter` empty, several naming two settings in one sentence.
    #[test]
    fn refusals_name_their_parameter() {
        use super::*;
        let cap = |v: serde_json::Value| {
            capability_dto(serde_json::from_value(v).expect("valid shape")).expect_err("refused")
        };
        let e = cap(serde_json::json!({ "data": [1.0, 2.0, 3.0] }));
        assert_eq!((e.code, e.parameter.as_deref()), ("no_specification", None));
        let e = cap(serde_json::json!({ "data": [1.0, 2.0, 3.0], "usl": 1.0, "lsl": 2.0 }));
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("parameter_out_of_range", Some("usl"))
        );
        let e = cap(serde_json::json!({ "data": [1.0], "usl": 2.0 }));
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("insufficient_data", Some("data"))
        );

        let e = percentile_capability_dto(
            serde_json::from_value(
                serde_json::json!({ "data": [1.0, 2.0, 3.0, 4.0, 5.0], "usl": 2.0 }),
            )
            .unwrap(),
        )
        .err()
        .expect("5 < 20");
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("insufficient_data", Some("data"))
        );

        // The family: named, refused by name, or refused at the first value its
        // support excludes -- and the result says which one it fitted.
        let pct = |extra: serde_json::Value| {
            let mut body = serde_json::json!({
                "data": (1..=30).map(|i| 10.0 + (i % 7) as f64 * 0.3).collect::<Vec<_>>(),
                "usl": 14.0, "lsl": 8.0,
            });
            for (k, v) in extra.as_object().unwrap() {
                body[k] = v.clone();
            }
            percentile_capability_dto(serde_json::from_value(body).unwrap())
        };
        let ok = pct(serde_json::json!({ "distribution": "Normal" })).expect("normal fits");
        assert_eq!(ok.distribution, "Normal");
        assert_eq!(
            ok.parameters.keys().map(String::as_str).collect::<Vec<_>>(),
            ["mu", "sigma"]
        );
        assert_ne!(
            pct(serde_json::json!({})).expect("auto").distribution,
            "Auto"
        );
        let e = pct(serde_json::json!({ "distribution": "normal" }))
            .err()
            .expect("unknown");
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("unknown_option", Some("distribution"))
        );
        let mut low: Vec<f64> = (1..=30).map(|i| i as f64).collect();
        low[4] = -2.0;
        let e = pct(serde_json::json!({ "data": low, "lsl": -5.0, "distribution": "Weibull" }))
            .err()
            .expect("weibull needs positive data");
        assert_eq!(
            (e.code, e.parameter.as_deref(), e.index),
            ("non_positive_data", Some("data"), Some(4))
        );

        let grr = |m: serde_json::Value| {
            gage_rr_xbar_r_dto(
                serde_json::from_value(serde_json::json!({ "measurements": m })).unwrap(),
            )
            .err()
            .expect("refused")
        };
        let e = grr(serde_json::json!([
            [[1.0, 2.0], [1.0, 2.0]],
            [[1.0, 2.0], [1.0]]
        ]));
        assert_eq!(
            (e.code, e.parameter.as_deref(), e.index),
            ("dimension_mismatch", Some("measurements[1]"), Some(1))
        );
        let e = grr(serde_json::json!([
            [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0]],
            [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0, 4.0]]
        ]));
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("parameter_out_of_range", Some("measurements[0][0]"))
        );

        let e = imr_dto(vec![1.0], crate::spc::RuleSet::default()).expect_err("one value");
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("insufficient_data", Some("values"))
        );

        let e = run_rules_dto(
            vec![1.0],
            LimitsInputDto {
                ucl: 1.0,
                cl: 2.0,
                lcl: 0.0,
            },
            crate::spc::RuleSet::default(),
        )
        .expect_err("ucl below cl");
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("parameter_out_of_range", Some("limits.ucl"))
        );

        let e = seasonality_dto(SeasonalityInputDto { data: vec![1.0; 3] }).expect_err("too short");
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("insufficient_data", Some("data"))
        );
    }

    /// Row walkers reported the row (`index`) but not whose rows they were.
    #[test]
    fn count_rows_name_their_argument_alongside_the_row() {
        let e = super::count_pairs(&serde_json::json!([[1, 10], [2]]), "samples")
            .expect_err("a row that is not a pair");
        assert_eq!(
            (e.code, e.parameter.as_deref(), e.index),
            ("malformed_input", Some("samples"), Some(1))
        );
        let e = super::rate_pairs(&serde_json::json!([[1, 2.0], [1.5, 2.0]]), "samples")
            .expect_err("1.5 defects");
        assert_eq!(
            (e.parameter.as_deref(), e.index),
            (Some("samples"), Some(1))
        );
        let e = super::count_rows(&serde_json::json!([3, -1]), "defects").expect_err("negative");
        assert_eq!(
            (e.parameter.as_deref(), e.index),
            (Some("defects"), Some(1))
        );
    }

    #[test]
    fn pelt_options_are_refused_by_name_with_their_values() {
        use super::{pelt_dto, Detail, PeltInputDto, PeltPenaltyDto, Whole};
        let input = |cost: &str, penalty: PeltPenaltyDto, min_segment_len: f64| PeltInputDto {
            data: vec![0.0, 0.0, 5.0, 5.0],
            cost: cost.to_string(),
            penalty,
            min_segment_len: Whole(min_segment_len),
        };
        let bic = || PeltPenaltyDto::Named("bic".into());

        let e = pelt_dto(input("l1", bic(), 2.0)).err().unwrap();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("unknown_option", Some("cost"))
        );
        assert_eq!(
            e.details[1],
            ("expected", Detail::List(vec!["l2", "normal"]))
        );

        let e = pelt_dto(input("l2", PeltPenaltyDto::Named("aic".into()), 2.0))
            .err()
            .unwrap();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("unknown_option", Some("penalty"))
        );
        assert_eq!(e.details[0], ("got", Detail::Text("aic".into())));

        let e = pelt_dto(input("l2", PeltPenaltyDto::Value(-1.0), 2.0))
            .err()
            .unwrap();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("parameter_out_of_range", Some("penalty"))
        );
        assert_eq!(
            e.details,
            vec![
                ("min", Detail::Null),
                ("exclusive_min", Detail::Num(0.0)),
                ("max", Detail::Null),
                ("got", Detail::Num(-1.0))
            ]
        );

        // A closed bound keeps its shape: `min`, no `exclusive_min`. A
        // negative length is refused by the same check, in the same shape.
        for got in [1.0, 0.0, -1.0] {
            let e = pelt_dto(input("l2", bic(), got)).err().unwrap();
            assert_eq!(
                (e.code, e.parameter.as_deref()),
                ("parameter_out_of_range", Some("min_segment_len"))
            );
            assert_eq!(
                e.details,
                vec![
                    ("min", Detail::Num(2.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(got))
                ]
            );
        }
        assert!(pelt_dto(input("l2", bic(), 2.0)).is_ok());

        let mut empty = input("l2", bic(), 2.0);
        empty.data.clear();
        let e = pelt_dto(empty).err().unwrap();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("empty_input", Some("data"))
        );
    }

    #[test]
    fn too_few_values_carry_min_and_got() {
        let e = super::at_least(vec![1.0], 3, "data").unwrap_err();
        assert_eq!(
            (e.code, e.parameter.as_deref()),
            ("insufficient_data", Some("data"))
        );
        assert_eq!(
            e.details,
            vec![
                ("min", super::Detail::Num(3.0)),
                ("got", super::Detail::Num(1.0))
            ]
        );
    }

    use super::code;
    use super::*;
    use serde_json::json;

    fn err<T: std::fmt::Debug>(r: Result<T, WireError>) -> (&'static str, Option<usize>, String) {
        let e = r.expect_err("must be refused");
        (e.code, e.index, e.message)
    }

    /// A count that failed to deserialize used to carry no row at all
    /// (`invalid type: floating point 1.5, expected u64`): the count is now
    /// read as a JSON number and refused with its position.
    #[test]
    fn a_count_that_is_not_a_whole_number_is_refused_with_its_row() {
        for bad in [json!(1.5), json!(-1), json!("3"), json!(null), json!(1e300)] {
            let (c, i, m) = err(count_rows(&json!([2, 0, bad]), "defects"));
            assert_eq!((c, i), (code::COUNT_NOT_WHOLE.name(), Some(2)), "{m}");
            assert!(m.starts_with("defects[2]"), "{m}");
        }
        let (c, i, _) = err(count_pairs(&json!([[1, 10], [2.5, 10]]), "samples"));
        assert_eq!((c, i), (code::COUNT_NOT_WHOLE.name(), Some(1)));
        let (c, i, _) = err(rate_pairs(&json!([[1, 1.0], [0.5, 2.0]]), "samples"));
        assert_eq!((c, i), (code::COUNT_NOT_WHOLE.name(), Some(1)));
    }

    /// The other half of a `[defectives, sample_size]` pair has its own domain,
    /// so it has its own code: `count_not_whole` on a pair row used to mean
    /// either member, and which one was readable only in the message.
    #[test]
    fn every_way_a_sample_size_can_be_wrong_carries_one_code() {
        for bad in [
            json!(0),
            json!(-3),
            json!(10.5),
            json!("10"),
            json!(null),
            json!(1e300),
        ] {
            let (c, i, m) = err(count_pairs(&json!([[1, 10], [1, bad]]), "samples"));
            assert_eq!((c, i), (code::SAMPLE_SIZE_NOT_WHOLE.name(), Some(1)), "{m}");
            assert!(m.contains("sample size"), "{m}");
            assert!(m.contains("at least 1"), "{m}");
        }
        // Defectives are checked first, and keep the count code.
        let (c, i, m) = err(count_pairs(&json!([[1, 10], [1.5, 0]]), "samples"));
        assert_eq!((c, i), (code::COUNT_NOT_WHOLE.name(), Some(1)), "{m}");
        assert!(m.contains("defectives"), "{m}");
        // An NP chart's single size is not an element, so it carries no position.
        for bad in [json!(0), json!(-3), json!(10.5)] {
            let (c, i, _) = err(sample_size_value(&bad, "sample_size"));
            assert_eq!((c, i), (code::SAMPLE_SIZE_NOT_WHOLE.name(), None));
        }
    }

    #[test]
    fn whole_counts_written_as_floats_are_accepted() {
        // A JS number is a double; 3 and 3.0 are the same value.
        assert_eq!(
            count_rows(&json!([3.0, 0, 7]), "c").expect("whole"),
            vec![3, 0, 7]
        );
        assert_eq!(sample_size_value(&json!(100.0), "n").expect("whole"), 100);
        assert_eq!(
            count_pairs(&json!([[0, 1], [3.0, 10.0]]), "s").expect("whole"),
            vec![(0, 1), (3, 10)]
        );
    }

    #[test]
    fn a_row_that_is_not_a_pair_is_malformed_at_its_row() {
        let (c, i, _) = err(count_pairs(&json!([[1, 10], [1, 2, 3]]), "samples"));
        assert_eq!((c, i), (code::MALFORMED_INPUT.name(), Some(1)));
        let (c, i, _) = err(rate_pairs(&json!([[1, 1.0], 4]), "samples"));
        assert_eq!((c, i), (code::MALFORMED_INPUT.name(), Some(1)));
        let (c, i, _) = err(count_pairs(&json!({ "samples": [] }), "samples"));
        assert_eq!((c, i), (code::MALFORMED_INPUT.name(), None));
        let (c, i, _) = err(rate_pairs(&json!([[1, 1.0], [2, "x"]]), "samples"));
        assert_eq!((c, i), (code::UNITS_NOT_POSITIVE.name(), Some(1)));
    }

    /// The code and `parameter` together tell every chart refusal apart. The
    /// two that state a domain share `parameter_out_of_range` and differ by
    /// `parameter` (the subgroups, or the standard named) and carry the
    /// domain; every other reason has its own code.
    #[test]
    fn every_chart_error_is_told_apart_by_code_and_parameter() {
        use crate::spc::ControlChartError as E;
        let all = [
            E::SampleLengthMismatch {
                expected: 2,
                got: 3,
            },
            E::NonFiniteValue,
            E::DefectivesExceedSampleSize {
                defectives: 2,
                sample_size: 1,
            },
            E::NonPositiveUnits,
            E::SubgroupSizeOutOfRange {
                got: 1,
                min: 2,
                max: 25,
            },
            E::ZeroSampleSize,
            E::dispersion_standard("phi", -1.0),
            E::proportion_standard("p_bar", 1.5),
        ];
        let refusals: Vec<_> = all
            .iter()
            .map(|e| WireError::chart("subgroups", None, e))
            .collect();
        let reasons: std::collections::HashSet<_> = refusals
            .iter()
            .map(|w| (w.code, w.parameter.clone()))
            .collect();
        assert_eq!(reasons.len(), all.len(), "reasons must be told apart");
        assert!(!reasons.iter().any(|(c, _)| *c == code::INVALID_INPUT));
        // No range reason keeps a code of its own.
        assert!(refusals
            .iter()
            .all(|w| !w.code.ends_with("_out_of_range") || w.code == code::PARAMETER_OUT_OF_RANGE));

        let fields = |w: &WireError| -> std::collections::HashMap<&'static str, Detail> {
            w.details.iter().cloned().collect()
        };
        let num = Detail::Num;
        let size = fields(&refusals[4]);
        assert_eq!(
            (
                refusals[4].code,
                refusals[4].parameter.as_deref(),
                &size["min"],
                &size["max"],
                &size["got"]
            ),
            (
                code::PARAMETER_OUT_OF_RANGE.name(),
                Some("subgroups"),
                &num(2.0),
                &num(25.0),
                &num(1.0)
            )
        );
        let phi = fields(&refusals[6]);
        assert_eq!(refusals[6].parameter.as_deref(), Some("phi"));
        assert_eq!(
            (&phi["min"], &phi["max"], &phi["got"]),
            (&num(0.0), &Detail::Null, &num(-1.0))
        );
        assert!(!phi.contains_key("exclusive_min"));
        let p_bar = fields(&refusals[7]);
        assert_eq!(
            (
                &p_bar["min"],
                &p_bar["exclusive_min"],
                &p_bar["max"],
                &p_bar["exclusive_max"],
                &p_bar["got"]
            ),
            (
                &Detail::Null,
                &num(0.0),
                &Detail::Null,
                &num(1.0),
                &num(1.5)
            )
        );
    }

    #[test]
    fn the_error_serializes_as_code_index_parameter_message() {
        // Both locators are always present: `index` says where in the data,
        // `parameter` says which option, and each is null when it does not
        // apply -- so a consumer reads a field rather than testing for one.
        let e = WireError::new(code::COUNT_NOT_WHOLE, Some(4), "defects[4]: nope");
        assert_eq!(
            serde_json::to_value(&e).expect("serializable"),
            json!({
                "code": "count_not_whole", "index": 4,
                "parameter": null, "message": "defects[4]: nope"
            })
        );

        let e = WireError::new(code::PARAMETER_OUT_OF_RANGE, None, "threshold must be > 0")
            .about("threshold");
        assert_eq!(
            serde_json::to_value(&e).expect("serializable"),
            json!({
                "code": "parameter_out_of_range", "index": null,
                "parameter": "threshold", "message": "threshold must be > 0"
            })
        );
    }

    /// Each refused option arrives naming itself, with the value given and
    /// the bounds of its domain.
    #[test]
    fn a_refused_option_names_itself_on_the_wire() {
        let request = |extra: serde_json::Value| {
            let mut body = json!({ "data": vec![1.0_f64; 20] });
            let (map, extra) = (body.as_object_mut().expect("object"), extra);
            for (k, v) in extra.as_object().expect("object") {
                map.insert(k.clone(), v.clone());
            }
            let input: SpectralResidualInputDto =
                serde_json::from_value(body).expect("valid request");
            spectral_residual_dto(input)
        };

        for (option, body, details) in [
            (
                "threshold",
                json!({ "threshold": 0.0 }),
                vec![
                    ("min", Detail::Null),
                    ("exclusive_min", Detail::Num(0.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(0.0)),
                ],
            ),
            (
                "sensitivity",
                json!({ "sensitivity": 100.0 }),
                vec![
                    ("min", Detail::Null),
                    ("exclusive_min", Detail::Num(0.0)),
                    ("max", Detail::Null),
                    ("exclusive_max", Detail::Num(100.0)),
                    ("got", Detail::Num(100.0)),
                ],
            ),
            (
                "sensitivity",
                json!({ "sensitivity": 0.0 }),
                vec![
                    ("min", Detail::Null),
                    ("exclusive_min", Detail::Num(0.0)),
                    ("max", Detail::Null),
                    ("exclusive_max", Detail::Num(100.0)),
                    ("got", Detail::Num(0.0)),
                ],
            ),
            (
                "batch_size",
                json!({ "batch_size": 5 }),
                vec![
                    ("min", Detail::Num(12.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(5.0)),
                ],
            ),
            // A negative count is refused by the check a too-small one is.
            (
                "batch_size",
                json!({ "batch_size": -1 }),
                vec![
                    ("min", Detail::Num(12.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(-1.0)),
                ],
            ),
            (
                "averaging_window",
                json!({ "averaging_window": 0 }),
                vec![
                    ("min", Detail::Num(1.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(0.0)),
                ],
            ),
            (
                "averaging_window",
                json!({ "averaging_window": -1 }),
                vec![
                    ("min", Detail::Num(1.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(-1.0)),
                ],
            ),
            (
                "judgement_window",
                json!({ "judgement_window": -1 }),
                vec![
                    ("min", Detail::Num(1.0)),
                    ("max", Detail::Null),
                    ("got", Detail::Num(-1.0)),
                ],
            ),
        ] {
            let e = request(body).expect_err("refused");
            assert_eq!(e.code, code::PARAMETER_OUT_OF_RANGE, "{}", e.message);
            assert_eq!(e.parameter.as_deref(), Some(option), "{}", e.message);
            assert!(e.message.starts_with(option), "{}", e.message);
            assert_eq!(e.details, details, "{}", e.message);
        }

        // Data problems keep their own codes and the position. A NaN has no
        // JSON spelling, so this request is built directly.
        let mut data = vec![1.0_f64; 20];
        data[7] = f64::NAN;
        let e = spectral_residual_dto(SpectralResidualInputDto {
            data,
            averaging_window: None,
            judgement_window: None,
            threshold: None,
            min_zscore: None,
            sensitivity: None,
            batch_size: None,
        })
        .expect_err("refused");
        assert_eq!(
            (e.code, e.index, e.parameter),
            (code::VALUE_NOT_FINITE.name(), Some(7), None)
        );

        let input: SpectralResidualInputDto =
            serde_json::from_value(json!({ "data": vec![1.0_f64; 11] })).expect("valid request");
        let e = spectral_residual_dto(input).expect_err("refused");
        assert_eq!(e.code, code::INSUFFICIENT_DATA);

        // And a valid request is still served, whole counts as given.
        assert!(request(json!({})).is_ok());
        assert!(request(json!({ "averaging_window": 3, "batch_size": 12 })).is_ok());
    }

    #[test]
    fn a_count_is_read_as_a_whole_number_of_either_sign() {
        let read = |v: serde_json::Value| serde_json::from_value::<Whole>(v);
        assert_eq!(read(json!(3)).expect("integer"), Whole(3.0));
        assert_eq!(read(json!(-1)).expect("negative"), Whole(-1.0));
        assert_eq!(read(json!(3.0)).expect("whole float"), Whole(3.0));
        assert_eq!(read(json!(u64::MAX)).expect("large").0, u64::MAX as f64);
        // From text too, as the C ABI reads it.
        let text = serde_json::from_str::<Whole>("-1").expect("negative text");
        assert_eq!(text, Whole(-1.0));
        for refused in [json!(2.5), json!(null), json!("3")] {
            let e = read(refused.clone()).expect_err("not a whole number");
            assert!(
                e.to_string().contains("expected a whole number"),
                "{refused}: {e}"
            );
        }
    }

    fn standard(v: serde_json::Value) -> AttributeStandardDto {
        serde_json::from_value(v).expect("valid options")
    }

    #[test]
    fn phase_two_options_reach_the_chart_and_are_checked() {
        let samples = [(11_u64, 170_u64)];
        let d = laney_p_dto(
            &samples,
            &standard(json!({ "p_bar": 0.0514, "phi": 0.236 })),
        )
        .expect("one sample with a standard");
        assert_eq!((d.p_bar, d.phi), (0.0514, 0.236));
        assert!(d.points[0].out_of_control);
        assert!(d.points[0].z.expect("scaled") > 3.0);

        let d = p_chart_dto(&[(2, 100), (20, 100)], &standard(json!({ "p_bar": 0.05 })))
            .expect("valid");
        assert_eq!(d.p_bar, 0.05);

        // Half a Laney standard is refused, not completed by estimation.
        let (c, _, m) = err(laney_p_dto(&samples, &standard(json!({ "p_bar": 0.05 }))));
        assert_eq!(c, code::INVALID_OPTION, "{m}");
        // A key the chart does not take is refused, not ignored.
        let (c, _, m) = err(p_chart_dto(&samples, &standard(json!({ "phi": 1.0 }))));
        assert_eq!(c, code::MALFORMED_INPUT, "{m}");
        assert!(m.contains("phi"), "{m}");
        // Outside its domain.
        let (c, i, _) = err(p_chart_dto(&samples, &standard(json!({ "p_bar": 1.5 }))));
        assert_eq!((c, i), (code::PARAMETER_OUT_OF_RANGE.name(), None));
        let (c, _, _) = err(laney_p_dto(
            &samples,
            &standard(json!({ "p_bar": 0.05, "phi": -2.0 })),
        ));
        assert_eq!(c, code::PARAMETER_OUT_OF_RANGE);
        // Unknown option keys are refused by the schema.
        assert!(serde_json::from_value::<AttributeStandardDto>(json!({ "pbar": 0.1 })).is_err());
    }
}