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
# u-analytics

[![Crates.io](https://img.shields.io/crates/v/u-analytics.svg)](https://crates.io/crates/u-analytics)
[![docs.rs](https://docs.rs/u-analytics/badge.svg)](https://docs.rs/u-analytics)
[![CI](https://github.com/iyulab/u-analytics/actions/workflows/ci.yml/badge.svg)](https://github.com/iyulab/u-analytics/actions/workflows/ci.yml)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

Statistical process control, process capability analysis, Weibull reliability,
change-point detection, correlation, regression, distribution analysis, and
hypothesis testing for industrial quality engineering.

## Modules

| Module | Description |
|--------|-------------|
| `spc` | Control charts (X̄-R, X̄-S, I-MR, P, NP, C, U, Laney P'/U', G, T) with selectable run tests (`RuleSet`; Shewhart/Western Electric/Nelson sets), subgroups n=2..=25 |
| `capability` | Process capability indices (Cp, Cpk, Pp, Ppk, Cpm), sigma level, and Box-Cox non-normal capability |
| `weibull` | Weibull parameter estimation (MLE, MRR) and reliability analysis (R(t), MTBF, B-life) |
| `point_process` | Event-time trend of one unit (a repairable system's failures, a service's incidents): Laplace and MIL-HDBK-189 tests against a constant rate, power-law process (Crow-AMSAA) fit |
| `counter` | Increments of a cumulative counter (a meter's register, an hour meter, a production or byte counter), each classified — normal, declared reset or replacement, wrap through a known modulus, or unexplained — and summed over intervals |
| `detection` | Change-point detection (CUSUM, EWMA, PELT) and one-shot anomaly scoring by spectral residual saliency (Ren et al. 2019) |
| `smoothing` | Time series smoothing (SES, Holt linear trend, Holt-Winters seasonal) |
| `seasonality` | Periodogram (zero-padded FFT) and dominant-period estimation — AutoPeriod: permutation-thresholded peaks refined on the ACF |
| `correlation` | Correlation analysis (Pearson, Spearman, Kendall, partial, correlation matrices) |
| `regression` | Regression analysis (simple OLS, multiple OLS, VIF multicollinearity) |
| `distribution` | Distribution analysis (ECDF, histogram bins — Sturges/Scott/FD/Fixed, QQ-plot, KS test) |
| `testing` | Hypothesis testing (t-tests, ANOVA, chi-squared, normality — SW/AD/JB) |

## Features

### Statistical Process Control (SPC)

Control charts for monitoring process stability:

- **Variables charts**: X̄-R, X̄-S, Individual-MR
- **Attributes charts**: P, NP, C, U
- **Overdispersion-adjusted**: Laney P' and U' (φ coefficient corrects for between-subgroup variation)
- **Rare events**: G chart (geometric distribution) and T chart (exponential) for low-defect processes
- **Run rules**: Nelson (8 rules), Western Electric (4 rules — its run rule is eight points on one side, Nelson's nine); the 3-sigma test alone by default

```rust
use u_analytics::spc::{XBarRChart, ControlChart};

let mut chart = XBarRChart::new(5).expect("5 is a supported subgroup size");
chart.add_sample(&[25.0, 26.0, 24.5, 25.5, 25.0]).unwrap();
chart.add_sample(&[25.2, 24.8, 25.1, 24.9, 25.3]).unwrap();
chart.add_sample(&[25.1, 25.0, 24.7, 25.3, 24.9]).unwrap();

if chart.is_in_control() {
    println!("Process is stable");
}
```

```rust
use u_analytics::spc::{laney_p_chart, g_chart};

// Laney P' chart for overdispersed proportion data
// samples: (defective count, subgroup size)
let samples = vec![(3u64, 100u64), (5, 120), (2, 95)];
let chart = laney_p_chart(&samples, None).unwrap(); // Some(LaneyStandard { .. }) for Phase II
println!("p̄ = {:.4}, φ = {:.4}", chart.p_bar, chart.phi);

// G chart for rare events (e.g., days between nonconformances)
let inter_event_counts = vec![12.0, 8.0, 25.0, 5.0, 18.0];
let gchart = g_chart(&inter_event_counts).unwrap();
```

### Process Capability

Capability indices quantifying process performance against specifications:

- **Short-term**: Cp, Cpk, Cpu, Cpl
- **Long-term**: Pp, Ppk, Ppu, Ppl
- **Taguchi**: Cpm
- **Sigma level**: PPM ↔ sigma conversion (1.5σ shift convention)
- **Non-normal**: Box-Cox transformation + capability on transformed scale

```rust
use u_analytics::capability::{ProcessCapability, sigma_to_ppm};

let spec = ProcessCapability::new(Some(220.0), Some(200.0)).unwrap();
let data = [210.0, 209.5, 210.2, 209.8, 210.1, 210.3, 209.7, 210.0];
let indices = spec.compute(&data, 0.15).unwrap();

println!("Cp = {:.2}, Cpk = {:.2}", indices.cp.unwrap(), indices.cpk.unwrap());
println!("6σ PPM = {:.1}", sigma_to_ppm(6.0)); // 3.4

// No within-subgroup sigma (a flat vector): long-term indices only.
let overall = spec.compute_overall(&data).unwrap();
assert!(overall.pp.is_some() && overall.cp.is_none());
```

`compute` takes the within-subgroup sigma from a control chart (`R-bar/d2`,
`S-bar/c4`, `MR-bar/d2`); `compute_overall` has none and so reports only
Pp/Ppk/Ppu/Ppl and Cpm, leaving `cp`, `cpk`, `cpu`, `cpl` and `std_dev_within`
`None`. Filling the short-term names from the overall sigma would make `cp`
equal `pp` for every input.

```rust
use u_analytics::capability::{boxcox_capability, DEFAULT_LAMBDA_RANGE};

// Non-normal data: estimate λ over [-5, 5], transform spec limits, compute Ppk
let skewed_data = vec![0.5, 1.2, 0.8, 2.1, 0.3, 1.7, 0.9, 1.4];
let result = boxcox_capability(&skewed_data, Some(5.0), Some(0.1), DEFAULT_LAMBDA_RANGE).unwrap();
if result.lambda_at_bound {
    // the likelihood was still rising at an end of the range: λ is that limit
}
let ppk = result.indices.and_then(|i| i.ppk); // `indices` is None without limits
println!("λ = {:.3}, Ppk = {:?}", result.lambda, ppk);
```

### Weibull Reliability

Parameter estimation and reliability engineering metrics:

- **MLE**: Maximum Likelihood Estimation (Newton-Raphson)
- **MRR**: Median Rank Regression (Bernard's approximation)
- **Reliability**: R(t), hazard rate, MTBF, B-life

```rust
use u_analytics::weibull::{weibull_mle, ReliabilityAnalysis};

let failure_times = [150.0, 200.0, 250.0, 300.0, 350.0, 400.0];
let fit = weibull_mle(&failure_times).unwrap();

let ra = ReliabilityAnalysis::from_mle(&fit);
println!("R(200h) = {:.1}%", ra.reliability(200.0) * 100.0);
println!("MTBF = {:.0}h", ra.mtbf());
println!("B10 life = {:.0}h", ra.b_life(0.10).unwrap());
```

### Event-Time Trend — is a unit failing more often?

Weibull fitting assumes independent lifetimes of many units; for the event
times of **one** unit (failures of a repaired machine, incidents of a service)
the first question is whether the rate is constant at all. Observation ends
either at a chosen time (`Truncation::Time(T)`) or at the last event
(`Truncation::Failure`, which then drops that event from the statistics).

- **Laplace test** — approximately normal; `U > 0` means events crowd late
- **MIL-HDBK-189 test** — exactly χ²(2m) under a constant rate
- **Power-law process (Crow-AMSAA)** — `β̂ > 1` rate increasing, `< 1` decreasing,
  with the unbiased `β̄` and the intensity at the end of observation

```rust
use u_analytics::point_process::{mil_hdbk_189_test, power_law_process_fit, Truncation, TrendDirection};

let failures = [12.0, 15.0, 27.0, 34.0, 44.0, 53.0]; // hours, watched until 60
let test = mil_hdbk_189_test(&failures, Truncation::Time(60.0)).unwrap();
assert_eq!(test.direction, TrendDirection::Increasing);
assert!(test.p_value > 0.05); // not significant: 6 events are little evidence
let fit = power_law_process_fit(&failures, Truncation::Time(60.0)).unwrap();
assert!((fit.beta - 1.2509).abs() < 1e-4);
```

Times must be ascending and `> 0`; an unordered, non-positive or late event is
refused with its position.

### Cumulative counters — how much did it advance, and is every step explained?

A meter, an hour meter or a production counter is read as a running total; the
quantity wanted is how much it advanced between readings. A reading below the
one before it has several explanations — the register passed its maximum and
started again from 0, it was reset or replaced, or the reading is wrong — and
none of them is assumed. Each pair of neighbouring readings is classified:
`Normal` (did not fall), `Declared` (a reset or replacement the caller declares,
counted from the new start value), `Wrap` (fell, and the register's `modulus`
explains it — with `max_rate`, only if the counter could advance that much in
the time) or `Unexplained` (fell, nothing given explains it: the increase is
`None`). Monitoring systems usually read every fall as a restart from 0
(Prometheus `increase()`); that is right for process counters and wrong for a
meter whose readings settle a bill.

```rust
use u_analytics::counter::{counter_increments, counter_totals, CounterOptions, IncrementKind};

// A six-digit register read every 6 hours; it passes 999 999 on the second day.
let times = [0.0, 6.0, 12.0, 18.0, 24.0, 30.0, 36.0];
let values = [999_900.0, 999_930.0, 999_950.0, 999_990.0, 20.0, 60.0, 90.0];
let options = CounterOptions { modulus: Some(1_000_000.0), ..Default::default() };
let steps = counter_increments(&times, &values, &options).unwrap();
assert_eq!(steps[3].kind, IncrementKind::Wrap);
assert_eq!(steps[3].increase, Some(30.0));
let days = counter_totals(&steps, &[0.0, 24.0, 48.0]).unwrap();
assert_eq!((days[0].increase, days[1].increase), (90.0, 100.0));
```

A pair belongs to the interval its later reading falls in (its increase is not
split across a boundary it straddles); each interval says how many of its pairs
were left unexplained.

### Change-Point Detection

Algorithms for detecting process mean shifts:

- **CUSUM**: Cumulative Sum chart (Page, 1954)
- **EWMA**: Exponentially Weighted Moving Average (Roberts, 1959)

```rust
use u_analytics::detection::Cusum;

let cusum = Cusum::new(10.0, 1.0).unwrap();
let data = [10.1, 9.9, 10.0, 10.2, 12.0, 12.1, 11.9, 12.3];
let signals = cusum.signal_points(&data);
```

### Spectral residual — where does the series do something its structure does not explain?

`SpectralResidual` scores every point without a trained model and without
assuming a period (Ren et al. 2019, the method behind the Microsoft anomaly
service): the log amplitude spectrum minus its moving average, transformed
back with the original phase, is the *saliency map*, large at spikes, steps
and dropouts. A point's `score` is its saliency relative to the judgement
window before it; it is an anomaly above the threshold (τ = 3) when it also
stands `min_zscore` standard deviations from the level before it. Each point
also carries an `expected` value — the series with anomalies replaced by
their neighbours, reconstructed from its low frequencies — and a
`lower`/`upper` band whose coverage is `sensitivity` percent; the band is for
the chart, the decision is the score.

```rust
use u_analytics::detection::SpectralResidual;

let mut series: Vec<f64> = (0..60).map(|t| (t as f64 * 0.3).sin()).collect();
series[40] += 4.0;
let points = SpectralResidual::new().analyze(&series).unwrap();
assert!(points[40].is_anomaly);
let flagged: Vec<usize> = points.iter().filter(|p| p.is_anomaly).map(|p| p.index).collect();
// `near_edge` marks the kappa = 5 points at either end of a batch, where the
// transform's own boundary handling moves the saliency most. It marks a
// position, not a verdict -- but a flag that appears only there is the one
// worth a second look.
assert_eq!(flagged, vec![40]);
```

Defaults are the paper's (q = 3, z = 40, τ = 3, gate 1.5, 70% band); `with_*`
builders change them, and `with_batch_size` scores a long series in
consecutive batches against their own context. At least 12 points.

### Seasonality — which period does the series repeat on?

Holt-Winters needs the seasonal period as an input; `estimate_period` finds it
from the data. Two stages (Vlachos, Yu & Castelli 2005, *AutoPeriod*): the
linearly detrended, zero-padded periodogram is searched for peaks above what
the same values in random order produce (99th percentile over 100 seeded
permutations — deterministic), then each peak's frequency band is refined on the
autocorrelation function to the integer lag that is a local maximum above the
`1.96/√n` white-noise bound. The answer says explicitly when there is no period.

```rust
use u_analytics::seasonality::estimate_period;

let sawtooth: Vec<f64> = (0..40).map(|i| (i % 7) as f64).collect();
let r = estimate_period(&sawtooth).unwrap();
assert_eq!(r.period, Some(7));            // every validated candidate is in r.candidates

let line: Vec<f64> = (0..40).map(|i| 2.0 * i as f64).collect();
assert_eq!(estimate_period(&line).unwrap().period, None);
```

Only periods from 2 to `n/2` are admissible — a cycle has to be seen twice —
and a series shorter than 8 points is refused (`None` from the function, as
opposed to `period: None` inside a result). Series under ~16 points rarely beat
the permutation threshold: too few orderings differ from the observed one.

## JavaScript / WASM (npm)

```bash
npm install @iyulab/u-analytics
```

The npm package ships two entry points, selected automatically via the
`exports` map:

| Environment | Entry | Notes |
|---|---|---|
| Bundlers (webpack, Vite, …) | ESM + WebAssembly ESM-integration | `default` condition |
| Node.js (`require` **and** `import`) | CJS glue that loads the wasm from the filesystem | `node` condition — works in CJS TS runners (`tsx`, `ts-node`) without loader hooks |

A browser **without** a bundler is not supported: the package loads its `.wasm`
file with an ES module import, which browsers refuse (`application/wasm` is not a
module script type), so `<script type="module">` from a CDN fails, and CDN
re-bundling services fail on the same import. Use a bundler or Node.

```js
// Both work in Node — no bundler, no experimental flags:
const { anderson_darling_test } = require("@iyulab/u-analytics");
// or: import { anderson_darling_test } from "@iyulab/u-analytics";

anderson_darling_test(new Float64Array([4.9, 5.1, 5.0, 5.2, 4.8, 5.05, 4.95, 5.15]));
// → { statistic, statistic_modified, p_value }
```

**Errors.** A refused input throws an `Error` with three extra properties:

```ts
interface AnalyticsError extends Error {
  code: string              // stable reason — branch on this, not on `message`
  index: number | null      // position of the offending element in its input array
  parameter: string | null  // the option the refusal is about, when it is about one
  // parameter_out_of_range also carries the domain and the value given:
  min?: number | null       // inclusive lower bound; null when open or unbounded
  max?: number | null       // inclusive upper bound; null when open or unbounded
  exclusive_min?: number    // exclusive lower bound — present only when that end is open
  exclusive_max?: number    // exclusive upper bound — present only when that end is open
  got?: number
}
// try { c_chart([1, 2, 2.5]) } catch (e) { e.code === "count_not_whole"; e.index === 2 }
// On a [defectives, sample_size] row the code says which member failed:
//   p_chart([[1, 10], [1.5, 10]]) -> count_not_whole,      index 1
//   p_chart([[1, 10], [1, 10.5]]) -> sample_size_not_whole, index 1
// `index` says where in the data; `parameter` says which option:
//   spectral_residual({ data, threshold: 0 }) -> parameter_out_of_range, parameter "threshold",
//                                                min null, exclusive_min 0, max null, got 0
```

`codes()` returns every `code` below, with the fields that can come with it —
`{ refusals: [{ code, fields }], violations: [] }` — built from the table the
refusals come from, so a caller that translates codes can check its list against
the package's. The C library returns the same JSON from `uanalytics_codes()` and
the .NET package from `AnalyticsClient.GetCodes()`.

| `code` | Meaning |
|---|---|
| `count_not_whole` | a defect or defective count is not a whole number ≥ 0 |
| `non_positive_data` | a value that must be `> 0` is not — Box-Cox `data`, Weibull `failure_times`, `percentile_capability` `data` under a `distribution` on (0, ∞) (`index`, `got`) |
| `invalid_option` | a setting refused for a reason a range cannot state — a `lambda_range` with `min >= max` (`parameter`) |
| `sample_size_not_whole` | a sample size is not a whole number ≥ 1 — zero, negative, fractional and not-a-number alike |
| `defectives_exceed_sample` | more defectives than the sample has items |
| `units_not_positive` | units inspected that are not a positive number |
| `insufficient_data` | fewer values than the function needs — `parameter` names the argument, `min` and `got` the counts (`index: null`) |
| `no_specification` | a capability index with neither specification limit — there is nothing to measure the spread against; `expected` is `["usl", "lsl"]` (`index` and `parameter` are `null`) |
| `empty_input` | an argument with nothing in it (`parameter`) |
| `dimension_mismatch` | arrays that must have the same length do not — a subgroup of a different size than the first, a gage study part with another operator count, `x` and `y` of different lengths. `parameter` names the array, `index` is the first element that differs, `expected` and `got` the lengths |
| `parameter_out_of_range` | a value outside its domain — an option, a Phase I `p_bar` (`(0, 1)`) / `u_bar` (`> 0`) / `phi` (`>= 0`), a subgroup size the factor tables do not cover (`parameter: "subgroups"`, `min: 2, max: 25`), an array element. `parameter` names which (`index` its position for an array element) and `got` the value. `min` / `max` are the inclusive bounds, `null` on a side that is open or unbounded; `exclusive_min` / `exclusive_max` are the exclusive bounds, present only on an open side. `> 0` is `{ min: null, exclusive_min: 0, max: null }`, `(0, 1]` is `{ min: null, exclusive_min: 0, max: 1 }`, `usl` not above `lsl` is `exclusive_min: lsl` |
| `value_not_finite` | a NaN or ±Infinity anywhere in an argument — `parameter` is the path to it (`input.data`), `index` its position in that array, or `null` |
| `malformed_input` | not the shape the function takes — a row that is not a pair, an unknown field, a count option with a fraction (`max_lags: 2.5`; a negative count is `parameter_out_of_range`) — `parameter` is the path to the value |
| `unknown_option` | an option given a name the function does not know — `parameter` names it (`rules`, `cost`, `penalty`, `observation.truncation`), `got` the name and `expected` the names it knows |
| `events_unordered` | an event time earlier than the one before it (`index`) |
| `event_after_end` | an event time after the end of observation (`index`) |
| `invalid_input` | any other refusal of the input, without a more specific reason (`index`, `parameter`) |
| `invalid_input` | any other refusal; the message says what |
| `internal` | A result the package could not hand back — a fault in the package, not in the input; please report it |

`message` is written for people and may change between releases; `code` does not.

### TypeScript

Every exported function declares its parameter and return types, and the
declarations are generated from the same structs the binding reads and
serialises, so they cannot drift from what it actually accepts and returns:

```ts
export function spectral_residual(input: SpectralResidualInputDto): SpectralResidualDto;
export function xbar_r_chart(data: number[][], options?: RuleOptions | null): XbarRChartDto;
export function p_chart(samples: [number, number][], options?: PChartOptions | null): PChartDto;
```

An absent optional value is declared `T | null`, which is what the binding
sends. Nothing needs an `as` cast, and a wrong assumption is a compile error
rather than something that fails at run time -- on the way in as well as on
the way out: a misspelt run rule (`RunRule`), a field the input does not have,
a penalty name the detector does not know, or a standard another chart reads
(`u_bar` given to `p_chart`) no longer compiles.

The binding still validates every input at the boundary, for JavaScript
callers and for values that reach it through a cast, and a rejected one says
what was wrong.

### `process_capability(input)`

```ts
process_capability({
  data: number[],
  usl?: number,          // at least one of usl / lsl is required
  lsl?: number,
  sigma_within?: number, // short-term sigma, e.g. R-bar / d2
  target?: number,       // Cpm target; without it `cpm` is null
  sigma_within_df?: number, // degrees of freedom of sigma_within -> cp / cpk intervals
  confidence?: number,   // of `intervals`, in (0, 1); default 0.95
}): {
  mean: number,
  sigma_source: "within" | "overall",
  std_dev_within: number | null,
  std_dev_overall: number,
  cp: number | null, cpk: number | null, cpu: number | null, cpl: number | null,
  pp: number | null, ppk: number | null, ppu: number | null, ppl: number | null,
  cpm: number | null,
  intervals: {
    confidence: number,
    cp: Interval | null, cpk: Interval | null,   // need sigma_within_df
    pp: Interval | null, ppk: Interval | null,   // n - 1 degrees of freedom
  },
}
type Interval = { lower: number, upper: number }  // two-sided at `confidence`
```

**Short-term sigma has to be supplied.** Cp/Cpk are defined against the
within-subgroup standard deviation, which is estimated from a control chart
(R-bar/d2 or S-bar/c4) and is *not* recoverable from a flat measurement vector —
the subgroup structure is gone. Omit `sigma_within` and `sigma_source` comes
back as `"overall"` with `cp`, `cpk`, `cpu`, `cpl` and `std_dev_within` all
`null`: only the long-term indices (Pp/Ppk) are reported. Filling the
short-term names with the long-term sigma instead would make `cp` equal `pp`
for every input.

**Cpm needs a `target`.** It measures how closely the data cluster about the
target -- `min(T - LSL, USL - T) / (3 * sqrt(sum((x - T)^2) / (n - 1)))` -- so it
uses neither sigma and is reported with or without `sigma_within`. Without a
`target` it is `null`; pass the specification midpoint if that is the target.

`xbar_r_chart` returns `sigma_hat` (`R-bar / d2`) for exactly this purpose, and
`sigma_hat_df`, its degrees of freedom, for the Cp/Cpk intervals -- so the two
compose:

```js
const chart = xbar_r_chart(subgroups);
const cap = process_capability({
  data: subgroups.flat(), usl: 11, lsl: 9,
  sigma_within: chart.sigma_hat, sigma_within_df: chart.sigma_hat_df,
});
// cap.sigma_source === "within", cap.cp !== cap.pp, cap.intervals.cpk !== null
```

`sigma_hat_df` is the precision of the chart's sigma expressed as the degrees of
freedom of a sample standard deviation: David's (1951) approximation for
R-bar/d2 and S-bar/c4 (one range of five values is worth 3.8, a little under
the four of a standard deviation), and Wheeler's `0.62 (n - 1)` for the moving
range of an I-MR chart.

One-sided specifications are supported: pass only `usl` or only `lsl`. The
indices that need both limits (`cp`, `pp`, `cpm`) come back `null`.

**Confidence intervals.** An index from a sample is an estimate, and a
capability requirement is usually stated on its lower confidence bound
("Cpk lower bound at 95 % ≥ 1.33"). `intervals` gives two-sided intervals at
`confidence`: Cp/Pp from the chi-square distribution of the variance,
Cpk/Ppk by Bissell's (1990) approximation
`Ĉpk ± z·sqrt(1/(9n) + Ĉpk²/(2ν))`. Pp/Ppk use ν = n − 1. The within sigma's
degrees of freedom depend on how it was estimated -- `n − m` for a pooled
standard deviation of `m` subgroups, about `0.62 (n − 1)` for a moving range
(Wheeler) -- so `cp` / `cpk` intervals are `null` unless you pass
`sigma_within_df`. A one-sided 95 % lower bound is the `lower` of the interval
at `confidence: 0.90`:

```js
const cap = process_capability({ data, usl: 11, lsl: 9, confidence: 0.90 });
cap.intervals.ppk.lower   // Ppk lower bound at 95 %
```

### Choosing which run tests apply

By default a chart applies the 3-sigma test alone (`"shewhart"`). Every added
test raises the false alarm rate of a process that is in control, so the
supplementary tests -- useful while a process is being brought into control --
are asked for rather than assumed (ISO 7870-2:2023, 8.2.7). `xbar_r_chart`
takes an optional second argument: the name of a set, or the tests spelt out.

```js
// Western Electric's four tests
xbar_r_chart(subgroups, { rules: "western_electric" });

// Nelson's eight
xbar_r_chart(subgroups, { rules: "nelson" });

// Exactly these tests
xbar_r_chart(subgroups, { rules: ["BeyondLimits", "SixTrend"] });

// Control limits and nothing else -- no test at all
xbar_r_chart(subgroups, { rules: [] });
```

| set | tests |
|---|---|
| `"shewhart"` (default) | `BeyondLimits` |
| `"western_electric"` | `BeyondLimits`, `TwoOfThreeBeyond2Sigma`, `FourOfFiveBeyond1Sigma`, `EightOneSide` |
| `"nelson"` | `BeyondLimits`, `NineOneSide`, `SixTrend`, `FourteenAlternating`, `TwoOfThreeBeyond2Sigma`, `FourOfFiveBeyond1Sigma`, `FifteenWithin1Sigma`, `EightBeyond1Sigma` |

The two published sets differ in their run on one side of the centre line:
eight points in the Western Electric handbook (`EightOneSide`), nine in Nelson's
list (`NineOneSide`). The test names are the same values each point's
`violations` reports, so a spelt-out set is written in the vocabulary the output
already uses.

Omitting the argument -- or passing `undefined`, `null`, or an object without
`rules` -- means `"shewhart"`. In Rust the same choice is `RuleSet`
(`RuleSet::western_electric()`, `RuleSet::named("nelson")`, ...), passed to a
chart with `with_rules`.

### X-bar-S and Individual-MR charts

```ts
type RuleName = "BeyondLimits" | "NineOneSide" | "SixTrend" | "FourteenAlternating"
              | "TwoOfThreeBeyond2Sigma" | "FourOfFiveBeyond1Sigma"
              | "FifteenWithin1Sigma" | "EightBeyond1Sigma" | "EightOneSide";
type RuleSetName = "shewhart" | "western_electric" | "nelson";
type Point = { index: number, value: number, violations: RuleName[] };

xbar_s_chart(subgroups: number[][], options?: { rules?: RuleSetName | RuleName[] }): {
  xbar_cl: number, xbar_ucl: number, xbar_lcl: number,
  s_cl: number, s_ucl: number, s_lcl: number,
  sigma_hat: number,             // S-bar / c4
  sigma_hat_df: number,          // its degrees of freedom (David's approximation)
  xbar_points: Point[], s_points: Point[], in_control: boolean,
}

imr_chart(values: number[], options?: { rules?: RuleSetName | RuleName[] }): {
  i_cl: number, i_ucl: number, i_lcl: number,
  mr_cl: number, mr_ucl: number, mr_lcl: number,
  sigma_hat: number,             // MR-bar / d2(2)
  sigma_hat_df: number,          // 0.62 (n - 1)
  i_points: Point[],
  mr_points: Point[],            // starts at index 1: the first value has no moving range
  in_control: boolean,
}
```

`xbar_s_chart` takes the same subgroup matrix as `xbar_r_chart`; above about ten
values per subgroup the standard deviation is the better estimate of spread,
because the range uses only the two extremes. Both return `sigma_hat` for
`process_capability`'s `sigma_within`, like `xbar_r_chart`. Subgroups must all
have the same size; a ragged one is reported by its row rather than skipped,
since skipping it would shift the index of every point after it.

### Applying run tests to your own series

```ts
run_rules(
  values: number[],
  limits: { ucl: number, cl: number, lcl: number },   // lcl <= cl <= ucl
  options?: { rules?: RuleSetName | RuleName[] },
): Point[]   // one entry per value, in input order
```

The same engine the charts use, on its own -- for a statistic the crate does not
chart, or for limits fixed from an earlier study:

```js
run_rules([10.1, 10.4, 9.8, 12.9], { ucl: 12, cl: 10, lcl: 8 });
// → [{ index: 0, value: 10.1, violations: [] }, ...,
//    { index: 3, value: 12.9, violations: ["BeyondLimits"] }]
```

Given a chart's own points and limits, it finds exactly the violations the chart
reported.

### Attributes charts

```ts
type AttrPoint = { index: number, value: number, ucl: number, cl: number, lcl: number,
                   out_of_control: boolean,
                   z: number | null };   // (value − cl) / σᵢ — null when σᵢ is 0

p_chart(samples: [defectives: number, size: number][], options?: { p_bar?: number }):
  { p_bar: number, points: AttrPoint[], in_control: boolean }
laney_p_chart(samples: [defectives: number, size: number][],
              options?: { p_bar?: number, phi?: number }):   // both or neither
  { p_bar: number, phi: number, points: AttrPoint[] }
np_chart(defectives: number[], sample_size: number):
  { cl: number, ucl: number, lcl: number, points: AttrPoint[], in_control: boolean }
c_chart(defects: number[]):
  { cl: number, ucl: number, lcl: number, points: AttrPoint[], in_control: boolean }
u_chart(samples: [defects: number, units: number][], options?: { u_bar?: number }):
  { u_bar: number, points: AttrPoint[], in_control: boolean }
laney_u_chart(samples: [defects: number, units: number][],
              options?: { u_bar?: number, phi?: number }):   // both or neither
  { u_bar: number, phi: number, points: AttrPoint[] }
```

**Phase I and Phase II.** Without options the centre (and φ) are estimated from
`samples` — a Phase I study. To judge later samples against it, pass that
study's `p_bar`/`u_bar` (and `phi` for the Laney charts): every limit then uses
the Phase I values with each sample's own size, and a single sample is enough.
Charting Phase I and Phase II together instead would let a Phase II shift pull
the centre toward itself and widen its own limits. A `p_bar` outside (0, 1), a
`u_bar` ≤ 0 or a negative `phi` is refused as `parameter_out_of_range`, naming
it with its domain and `got`; a Laney standard with only one of its two parts,
or a key the chart does not take, is refused rather than completed or ignored.

```js
const phaseOne = laney_p_chart(firstTwelve)              // { p_bar, phi, points }
laney_p_chart(later, { p_bar: phaseOne.p_bar, phi: phaseOne.phi })
```

**Run rules when the sample size varies.** P, U and the Laney charts have a
different pair of limits at every point, so zones on the original scale do not
exist. Each point carries `z`, its distance from the centre line in its own
standard errors; on that scale every limit is ±3 (the standardized control
chart, Montgomery §7.2.2):

```js
const chart = p_chart(samples)
run_rules(chart.points.map(p => p.z), { ucl: 3, cl: 0, lcl: -3 }, { rules: "western_electric" })
```

These charts judge each point against its limits only; for an NP or C chart,
whose limits are constant, pass `value`s and the chart's limits to `run_rules`
directly.

A row the chart cannot use -- a count that is not a whole number, more
defectives than the sample size, a sample size of zero, `units` that are not
positive -- is rejected with its `code` and `index` (see **Errors** above). The
charts would otherwise drop it, and every later point would carry the index of
the wrong row.

### CUSUM and EWMA — sequential shift detection

The Shewhart charts above judge each point on its own, which makes them slow to
notice a **small but persistent** shift. These two accumulate evidence across
points instead, and are the standard answer for that case.

```ts
cusum(input: {
  data: number[],          // observations, in order; must be non-empty
  target: number,          // process target mean (mu_0)
  sigma: number,           // known process sigma; must be > 0
  k?: number,              // reference value / allowance, default 0.5
  h?: number,              // decision interval, default 5.0
}): {
  h: number,               // echoed, so the boundary can be drawn without restating the input
  points: { index: number, s_upper: number, s_lower: number, signal: boolean }[],
  signal_indices: number[],
  in_control: boolean,
}

ewma(input: {
  data: number[],
  target: number,
  sigma: number,
  lambda?: number,         // smoothing constant in (0, 1], default 0.2
  l_factor?: number,       // limit width factor, default 3.0
}): {
  points: { index: number, ewma: number, ucl: number, lcl: number, signal: boolean }[],
  signal_indices: number[],
  in_control: boolean,
}
```

```js
// A 2-sigma shift that begins at observation 10
const data = [...Array(10).fill(10), ...Array(10).fill(12)];
cusum({ data, target: 10, sigma: 1 }).signal_indices;  // → indices inside the shifted half
```

**CUSUM's limit is a single number, EWMA's is per point.** Both cumulative sums
are on the standardized scale (`z = (x - target) / sigma`) and start at zero, so
they compare against `h` directly — hence `h` on the chart rather than on each
point. EWMA's limits are the exact (not asymptotic) ones, so they **widen with
the index** and are returned per point.

The defaults are the values their sources recommend: `k = 0.5` is optimal for a
1-sigma shift and `h = 5` gives ARL_0 ≈ 465 (Page 1954); `lambda = 0.2` with
`L = 3` is sensitive across 0.5–2.0 sigma shifts (Roberts 1959). Both reject an
empty `data` and any parameter outside its domain, naming the offending one.

### Non-normal capability, and sigma level ↔ PPM

```ts
boxcox_capability(input: {
  data: number[],          // >= 4 observations, all strictly positive
  usl?: number,            // optional; each must be positive
  lsl?: number,            // with neither limit, only lambda is estimated (indices null)
  lambda_range?: [number, number],  // search range, default [-5, 5] (Minitab's)
}): {
  lambda: number,          // ML-estimated optimal Box-Cox parameter within lambda_range
  lambda_at_bound: boolean,  // true: likelihood still rising at an end of the range —
                             // lambda is that limit, not an interior optimum
  pp: number | null, ppk: number | null, ppu: number | null, ppl: number | null,
  cp: null, cpk: null, cpu: null, cpl: null,   // always null — see below
  cpm: number | null,
}

sigma_to_ppm(sigma: number): number   // 6 → ~3.4,  3 → ~66807
ppm_to_sigma(ppm: number): number     // inverse; ppm must be inside (0, 1e6)
```

Weibull — fits of failure times (each finite and `> 0`, at least 2) and the
reliability metrics of a fitted or known Weibull:

```ts
weibull_mle(failure_times, suspension_times?, { confidence?, method?, fractions_failed? }?):
  { shape, scale, log_likelihood, iterations, b_life: number[],
    intervals: { confidence, method, shape: { lower, upper }, scale: { lower, upper },
                 b_life: { lower, upper }[] },
    covariance: [[var_shape, cov], [cov, var_scale]] }
  // b_life / intervals.b_life: aligned with fractions_failed (each in (0, 1); 0.1 → B10),
  //   by the same method -- the only place a likelihood-ratio B-life interval is given,
  //   since it needs the data (weibull_reliability composes Wald ones from covariance)
  // suspension_times: right-censored units (still running / removed unfailed at that time)
  // intervals at confidence (default 0.95) by method: "wald" (default) -- log-normal from
  //   the observed Fisher information -- or "likelihood_ratio" -- the profile-likelihood
  //   interval, nearer its level with few failures (8 failures, 90 % B10: 0.86 vs Wald 0.81
  //   by simulation); a likelihood too flat on one side for a limit → invalid_input
  // covariance: inverse observed information -- pass it to weibull_reliability
weibull_mrr(failure_times, suspension_times?): { shape, scale, r_squared }
  // median-rank regression (Bernard); suspensions move the failures' ranks (Johnson)
weibull_reliability({ shape, scale, times?: number[], fractions_failed?: number[],
                      covariance?, confidence? }):
  { mtbf, reliability: number[], hazard_rate: number[], b_life: number[],
    intervals: { confidence, reliability: { lower, upper }[], b_life: { lower, upper }[] } | null }
  // arrays aligned with times (R(t), h(t)) and fractions_failed (0.1 → B10);
  // the time to reliability p is the B-life at 1 − p
  // intervals (with an MLE's covariance; confidence default 0.95): delta method on
  // ln(−ln R) and ln t_p, so the limits stay in (0, 1) and above 0; [1, 1] at t ≤ 0.
  // confidence without covariance → invalid_option; a covariance that is not
  // symmetric positive definite → invalid_option (parameter "covariance")
```

The B10 life of a fleet with units still running, and how sure it is:

```js
const { weibull_mle, weibull_reliability } = require("@iyulab/u-analytics");
const fit = weibull_mle([55, 187, 216, 240, 244, 335, 361, 373], [400, 400]);
const r = weibull_reliability({
  shape: fit.shape, scale: fit.scale, fractions_failed: [0.1],
  covariance: fit.covariance, confidence: 0.9,
});
const [b10, ci] = [r.b_life[0], r.intervals.b_life[0]];
if (!(ci.lower < b10 && b10 < ci.upper)) throw new Error("unexpected");
```

```js
const { weibull_mrr, weibull_reliability } = require("@iyulab/u-analytics");
const fit = weibull_mrr([150, 200, 250, 300, 350, 400]);
const r = weibull_reliability({ shape: fit.shape, scale: fit.scale, times: [200], fractions_failed: [0.1] });
console.log(r.reliability[0] > 0.5, r.b_life[0] < 200); // true true
if (!(r.reliability[0] > 0.5) || !(r.b_life[0] < 200)) throw new Error("unexpected");
```

**Only the long-term indices are reported.** `data` is a flat vector, so there
is no rational subgrouping and no within-subgroup sigma to estimate. Computing
`cp`/`cpk` from the overall sigma instead would make `cp` equal `pp` for every
input — a long-term number wearing a short-term name — so they come back `null`,
the same choice `process_capability` makes when `sigma_within` is omitted.

Every index is on the **transformed** scale, which is where the normal-theory
formulas hold; they are not comparable to indices computed on the raw
non-normal data. The specification limits are transformed with the same lambda.

**`sigma_to_ppm` uses the Motorola convention, including the 1.5-sigma shift**
(`PPM = 10^6 · (1 − Φ(σ − 1.5))`). Six sigma therefore reports ~3.4 PPM rather
than the ~0.002 PPM of an unshifted normal tail — if you are checking against a
table, check which convention it uses. `ppm_to_sigma` is the exact inverse on
the same convention and rejects both ends of `(0, 1e6)`, which the sigma scale
does not reach. The round trip closes to ~3·10⁻⁴ (the inverse normal CDF is a
rational approximation).

### The remaining exports, briefly

Every export takes plain JSON values and returns one; a rejected input throws
an `Error` carrying `code` and `index` (see **Errors**). The shapes below are the ones
the sections above have not already spelled out.

```ts
// Rare-event charts — at least 3 values; gaps >= 0, times > 0
g_chart(gaps: number[] | Float64Array):  { g_bar: number, points: AttrPoint[] }    // events between occurrences
t_chart(times: number[] | Float64Array): { t_bar: number, points: AttrPoint[] }    // time between occurrences

// Normality — at least 8 values, not all equal (below 8 the sample-size
// correction A²* = A²·(1 + 0.75/n + 2.25/n²) is not tabulated)
anderson_darling_test(data: number[] | Float64Array):
  { statistic: number, statistic_modified: number, p_value: number }

// Stationarity — augmented Dickey-Fuller, H₀: unit root. At least 10 values.
// The lag count is chosen by AIC from 0 to max_lags (absent or null: Schwert's
// rule), every candidate fitted on the same observations, then refitted on all
// it leaves — as statsmodels' adfuller(autolag="AIC"); `lags` fixes it instead
// (not both: invalid_option). A deterministic series whose differences the
// lags fit exactly is refused (invalid_input), not tested.
adf_test(input: { data: number[], model?: "none" | "constant" | "constant_trend",
                  max_lags?: number | null, lags?: number | null }):
  { statistic: number, n_lags: number, n_obs: number,
    levels: { level: number, critical_value: number, rejected: boolean }[] }  // 1 %, 5 %, 10 %

// Association and fitting
correlation_matrix(variables: number[][], options?: { method?: "pearson" | "spearman" | "kendall" } | null):
  { matrix: number[][] }        // >= 2 variables of one length >= 3; a constant one -> invalid_input at its index
simple_regression(x: number[] | Float64Array, y: number[] | Float64Array):
  { slope, intercept, r_squared, adjusted_r_squared, slope_se, intercept_se,
    slope_t: number | null, intercept_t: number | null, slope_p, intercept_p, residual_se,
    f_statistic: number | null, f_p_value, residuals: number[], fitted: number[] }  // null t/F: exact fit
fit_best(data: number[] | Float64Array):  // >= 2 values, not all equal; best AIC first
  { distribution: string, parameters: Record<string, number>, log_likelihood, aic, bic }[]
// fit_best ranks continuous families only (Normal; Exponential, Gamma, LogNormal,
// Weibull for positive data; Beta for (0, 1)) -- a probability mass is not ranked
// against densities, so count data get no Poisson entry here.
// A number array is read as sent: `null` or a string at data[i] throws
// malformed_input with index i (it is not averaged as 0).

// Hypothesis tests. Samples are number[] | Float64Array; groups and tables are
// number[][], refused where the value sits (`groups[1][2]` null -> parameter
// "groups[1]", index 2). Too few values -> insufficient_data; a sample with no variation,
// for which the statistic is undefined -> invalid_input.
type TestResult = { statistic: number, df: number, p_value: number }
one_sample_t_test(data, mu0: number): TestResult          // >= 2 values
two_sample_t_test(a, b): TestResult                       // Welch; >= 2 each
paired_t_test(x, y): TestResult                           // same length, >= 2 pairs
mann_whitney_u_test(a, b): TestResult                     // >= 2 each
wilcoxon_signed_rank_test(x, y): TestResult               // pairs with x = y dropped, >= 2 remain
jarque_bera_test(data): TestResult                        // >= 8 values
shapiro_wilk_test(data): { w: number, p_value: number }   // 3 to 5000 values (Royston 1995)
mann_kendall_test(data):                                  // >= 4 values
  { s_statistic, variance, z_statistic, p_value, kendall_tau, sen_slope }
one_way_anova(groups: number[][]):                        // >= 2 groups of >= 2
  { f_statistic, df_between, df_within, p_value, ss_between, ss_within }
kruskal_wallis_test(groups) | levene_test(groups) | bartlett_test(groups): TestResult
chi_squared_goodness_of_fit(observed, expected): TestResult  // observed >= 0, expected > 0
chi_squared_independence(table: number[][]): TestResult      // >= 2 x 2, counts >= 0
fisher_exact_test(table: [[a, b], [c, d]]): TestResult       // whole counts
bonferroni_correction(p_values): Float64Array                // min(p * m, 1), input order
benjamini_hochberg(p_values): Float64Array                   // FDR (1995), input order; p in [0, 1]
```

Event-time trend of one unit — `times` ascending and `> 0`; `observation` is
`{ truncation: "time", end }` (watched until `end`) or `{ truncation: "failure" }`
(stopped at the last event, which is then not used):

```ts
laplace_trend_test(times, observation): TrendTestDto
mil_hdbk_189_test(times, observation): TrendTestDto
  // { statistic, p_value /* two-sided */, direction: "increasing" | "decreasing" | "flat",
  //   events_used, df /* null for Laplace */ }
power_law_process_fit(times, observation):
  { beta, beta_unbiased, lambda, intensity_at_end, end, events }  // Crow-AMSAA
```

```js
const { mil_hdbk_189_test } = require("@iyulab/u-analytics");
const r = mil_hdbk_189_test([12, 15, 27, 34, 44, 53], { truncation: "time", end: 60 });
console.log(r.statistic.toFixed(2), r.df, r.direction); // 9.59 12 increasing
if (r.df !== 12 || r.direction !== "increasing") throw new Error("unexpected");
```

Increments of a cumulative counter — `times` strictly ascending; `options` is
`{ modulus?, max_rate?, discontinuities?: [{ time, start, last? }] }`:

```ts
counter_increments(times, values, options?): CounterIncrementDto[]
  // [{ start, end, increase /* null when unexplained */,
  //    kind: "normal" | "declared" | "wrap" | "unexplained" }]
counter_totals(times, values, edges, options?): CounterTotalDto[]
  // [{ start, end, increase, pairs, unexplained }] over [edges[j], edges[j+1])
```

A declared discontinuity is a reset or replacement between two readings: `start`
is the register's value right after it, `last` (when read) the old register's
final value — without it, what the counter advanced before the change is unknown
and not counted.

```js
const { counter_increments } = require("@iyulab/u-analytics");
const steps = counter_increments([0, 1, 2], [990, 995, 4], { modulus: 1000 });
console.log(steps.map((s) => `${s.kind}:${s.increase}`).join(" ")); // normal:5 wrap:9
if (steps[1].kind !== "wrap" || steps[1].increase !== 9) throw new Error("unexpected");
```

```js
import { two_sample_t_test, one_way_anova } from "@iyulab/u-analytics";

const t = two_sample_t_test([5.1, 4.9, 5.3, 5.0], [5.6, 5.8, 5.5, 5.9, 5.7]);
const f = one_way_anova([[1, 2, 3], [2, 3, 4], [5, 6, 7]]);
console.log(t.p_value < 0.05, f.df_between); // true 2
if (!(t.p_value < 0.05) || f.df_between !== 2) throw new Error("unexpected");
```

```ts

// Changepoints — PELT (Killick et al., 2012)
detect_changepoints(input: {
  data: number[],
  cost?: "l2" | "normal",        // default "l2": mean shift; "normal": mean + variance
  penalty?: "bic" | number,      // default "bic"
  min_segment_len?: number,      // default 2, must be >= 2
}): { changepoints: number[], n_segments: number }
detect_changepoints_multi(input: { signals: number[][], cost?, penalty?, min_segment_len? }):
  { changepoints: number[], n_segments: number }   // channels of equal length

// Seasonality — AutoPeriod (Vlachos et al., 2005); >= 8 finite values
estimate_period(input: { data: number[] }): {
  period: number | null,          // null = no periodicity passed both stages (explicit, not an error)
  candidates: { period: number, acf: number, bin: number, power: number, power_share: number }[],
  n: number, acf_threshold: number, power_threshold: number,
}
// `acf` has the (n - lag)/n bias of the estimator undone -- the value the
// candidate was selected and accepted on, so comparing it against
// `acf_threshold` reaches the same verdict the crate did. The period is exact
// whether or not the series is a whole number of cycles long.

// Spectral residual anomaly scoring — Ren et al. (2019); >= 12 finite values
spectral_residual(input: {
  data: number[],
  averaging_window?: number,      // default 3  (q)
  judgement_window?: number,      // default 40 (z)
  threshold?: number,             // default 3  (τ, on the relative saliency score)
  min_zscore?: number,            // default 1.5; 0 disables the gate
  sensitivity?: number,           // default 70: coverage % of the expected-value band
  batch_size?: number,            // score in consecutive batches (>= 12)
}): {
  points: { index, value, saliency, score, expected, lower, upper: number,
            is_anomaly: boolean, near_edge: boolean }[],
  anomalies: number[],            // indices with is_anomaly
}

// Gage R&R — measurements[part][operator][trial]
gage_rr_xbar_r(input: { measurements: number[][][], tolerance?: number }): {
  // The two charts the method plots, from the same R-bar the components use.
  // Subgroup = one operator x part cell, so n is the trial count (2 or 3).
  range_chart:   { center: number, ucl: number, lcl: number },  // R-bar, D4*R-bar, D3*R-bar
  average_chart: { center: number, ucl: number, lcl: number },  // X-double-bar +/- A2*R-bar
  ev, av, grr, pv, tv, percent_ev, percent_av, percent_grr, percent_pv: number,
  percent_tolerance: number | null, ndc: number, status: "Acceptable" | "Marginal" | "Unacceptable",
}
gage_rr_anova(input: { measurements: number[][][], tolerance?: number }): {
  anova_table: { source, df, ss, ms, f_value: number | null, p_value: number | null }[],
  variance_components: { part, operator, interaction, repeatability, reproducibility, total },
  ev, av, grr, pv, tv, percent_grr: number, percent_tolerance: number | null,
  ndc: number, status: string, interaction_significant: boolean, interaction_pooled: boolean,
}

// Percentile capability (ISO 22514-2) — >= 20 observations, at least one limit.
// The 0.135 % / 50 % / 99.865 % quantiles of a distribution fitted to `data`:
// `distribution` names the family, absent = the one fit_best ranks first.
percentile_capability(input: {
  data: number[], usl?: number, lsl?: number,
  distribution?: "Normal" | "LogNormal" | "Weibull" | "Gamma" | "Exponential" | "Beta",
}): {
  cp_star, cpk_star, cpu_star, cpl_star: number | null,
  median: number, percentile_lower: number, percentile_upper: number,
  distribution: string,                // the family fitted (fit_best's names)
  parameters: Record<string, number>,  // its parameters, as fit_best reports them
}
```

Points on the average chart are *expected* to fall outside its limits -- that is
how the study reads whether the parts vary enough to be told apart. The factors
come from `spc::range_chart_factors(n)` (Rust), which refuses a subgroup size the
tables do not cover rather than approximating it; `gage_rr_xbar_r` itself accepts
only 2 or 3 trials, so that refusal is unreachable through it.

## C FFI (NuGet `UAnalytics`)

The `ffi` feature builds a `cdylib` with a C ABI for hosts that cannot load
WebAssembly — .NET through the `UAnalytics` NuGet package, or anything that can
call a C function.

```bash
cargo build --release --features ffi
```

**Every entry point is JSON-in / JSON-out with one calling convention:**

```c
int32_t uanalytics_<name>(const char *request_json, char **result_ptr);
void    uanalytics_free_string(char *ptr);   // release any string the library returned
char   *uanalytics_version(void);            // crate version; free with uanalytics_free_string
```

| Status | Meaning | `*result_ptr` |
|---|---|---|
| `0` | success | the response JSON |
| `-1` | `request_json` or `result_ptr` was null | null |
| `-2` | the request did not parse into the expected shape | `{"error": "...", "code": "malformed_input", "index": ..., "parameter": ...}` — `parameter` the path to a value of the wrong type (`max_lags`, `signals[1]`), `index` its array position; both `null` for text that is not JSON or a missing field |
| `-3` | the request parsed, and the computation rejected it | `{"error": "...", "code": "...", "index": ..., "parameter": ...}` |
| `-4` | internal panic (caught; never unwinds across the boundary) | `{"error": "...", "code": "invalid_input", "index": null, "parameter": null}` |

`code`, `index` and `parameter` are the same values the JavaScript `Error`
carries (see **Errors** in the JavaScript section).

Unknown request fields are rejected (`-2`, naming the field) rather than
ignored, so a misspelt option cannot silently change which analysis you get.
The string written to `*result_ptr` is owned by the caller and must be released
with `uanalytics_free_string`.

**The FFI and the WASM binding share one contract.** Every entry point that
both transports carry parses the same request type and serialises the same
response type (`src/wire.rs`), and a test pins that the FFI body is the
`serde_json` rendering of the value the WASM binding emits. So the schemas in
the JavaScript section above *are* the FFI schemas: the request is the WASM
function's arguments as one JSON object, the response is the same JSON.

| C entry point | WASM export | Request JSON |
|---|---|---|
| `uanalytics_xbar_r_chart` | `xbar_r_chart(subgroups, { rules? })` | `{ subgroups, rules? }` |
| `uanalytics_xbar_s_chart` | `xbar_s_chart(subgroups, { rules? })` | `{ subgroups, rules? }` |
| `uanalytics_imr_chart` | `imr_chart(values, { rules? })` | `{ values, rules? }` |
| `uanalytics_run_rules` | `run_rules(values, limits, { rules? })` | `{ values, limits: { ucl, cl, lcl }, rules? }` |
| `uanalytics_p_chart` | `p_chart(samples, { p_bar? })` | `{ samples: [[defectives, sample_size], …], p_bar? }` |
| `uanalytics_laney_p_chart` | `laney_p_chart(samples, { p_bar?, phi? })` | `{ samples: [[defectives, sample_size], …], p_bar?, phi? }` |
| `uanalytics_np_chart` | `np_chart(defectives, sample_size)` | `{ defectives: [...], sample_size }` |
| `uanalytics_c_chart` | `c_chart(defects)` | `{ defects: [...] }` |
| `uanalytics_u_chart` | `u_chart(samples, { u_bar? })` | `{ samples: [[defects, units], …], u_bar? }` |
| `uanalytics_laney_u_chart` | `laney_u_chart(samples, { u_bar?, phi? })` | `{ samples: [[defects, units], …], u_bar?, phi? }` |
| `uanalytics_g_chart` | `g_chart(gaps)` | `{ gaps: [...] }` |
| `uanalytics_t_chart` | `t_chart(times)` | `{ times: [...] }` |
| `uanalytics_process_capability` | `process_capability(input)` | `input` as is |
| `uanalytics_percentile_capability` | `percentile_capability(input)` | `input` as is |
| `uanalytics_gage_rr_xbar_r` | `gage_rr_xbar_r(input)` | `input` as is |
| `uanalytics_gage_rr_anova` | `gage_rr_anova(input)` | `input` as is |
| `uanalytics_detect_changepoints` | `detect_changepoints(input)` | `input` as is |
| `uanalytics_detect_changepoints_multi` | `detect_changepoints_multi(input)` | `input` as is |
| `uanalytics_cusum` | `cusum(input)` | `input` as is |
| `uanalytics_ewma` | `ewma(input)` | `input` as is |
| `uanalytics_anderson_darling_test` | `anderson_darling_test(data)` | `{ data: [...] }` |
| `uanalytics_adf_test` | `adf_test(input)` | `input` as is |
| `uanalytics_correlation_matrix` | `correlation_matrix(variables, { method? })` | `{ variables, method? }` |
| `uanalytics_simple_regression` | `simple_regression(x, y)` | `{ x, y }` |
| `uanalytics_fit_best` | `fit_best(data)` | `{ data: [...] }` |
| `uanalytics_estimate_period` | `estimate_period(input)` | `input` as is |
| `uanalytics_spectral_residual` | `spectral_residual(input)` | `input` as is |

The composition documented for JavaScript holds here too: `imr_chart` (or
`xbar_s_chart`) returns `sigma_hat`, which is what `process_capability` needs as
`sigma_within` to report the short-term indices, and `sigma_hat_df` for its
`sigma_within_df` — the FFI does not guess a within sigma from a flat vector any
more than the WASM binding does.

The event-time trend functions take `{ "times": [...], "observation": { "truncation": "time", "end": T } }`
(or `{ "truncation": "failure" }`) and return the same objects as over WASM:
`uanalytics_laplace_trend_test`, `uanalytics_mil_hdbk_189_test`,
`uanalytics_power_law_process_fit`.

The counter functions take the readings and the options flat in one object —
`{ "times": [...], "values": [...], "modulus"?, "max_rate"?, "discontinuities"? }`,
plus `"edges"` for the totals — and return the WASM arrays:
`uanalytics_counter_increments`, `uanalytics_counter_totals`.

The reliability and non-normal capability functions take the WASM argument as the
request (`uanalytics_boxcox_capability`, `uanalytics_weibull_reliability`), wrap a
scalar as `{ "sigma": s }` / `{ "ppm": p }` → `{ "value": … }` (`uanalytics_sigma_to_ppm`,
`uanalytics_ppm_to_sigma`), and take `{ "failure_times": [...] }` for the fits
(`uanalytics_weibull_mle`, `uanalytics_weibull_mrr`); the responses are the WASM ones.

The hypothesis tests take their WASM arguments as one object and return the WASM
results — `uanalytics_one_sample_t_test` `{data, mu0}`, `uanalytics_two_sample_t_test` /
`uanalytics_mann_whitney_u_test` `{a, b}`, `uanalytics_paired_t_test` /
`uanalytics_wilcoxon_signed_rank_test` `{x, y}`, `uanalytics_jarque_bera_test` /
`uanalytics_shapiro_wilk_test` / `uanalytics_mann_kendall_test` `{data}`,
`uanalytics_one_way_anova` / `uanalytics_kruskal_wallis_test` / `uanalytics_levene_test` /
`uanalytics_bartlett_test` `{groups}`, `uanalytics_chi_squared_goodness_of_fit`
`{observed, expected}`, `uanalytics_chi_squared_independence` / `uanalytics_fisher_exact_test`
`{table}`, and `uanalytics_bonferroni_correction` / `uanalytics_benjamini_hochberg`
`{p_values}` → `{values}`.

The .NET client (`bindings/csharp/UAnalytics`, package `UAnalytics`) wraps each
entry point as a method on `AnalyticsClient` — `XbarRChart`, `ImrChart`, `PChart(samples, pBar)`, `LaneyPChart(samples, pBar, phi)`,
`ProcessCapability`, `DetectChangepoints`, … — serialising the arguments to the
request above and returning the response as a typed record. A non-zero status
surfaces as `AnalyticsException` carrying the native status (`Status`), the `error`
message, the body's `code`, `parameter` and `index` as `ErrorCode`, `Parameter`
and `Index`, and the whole body as `Details`. The
package follows its own version line (it is a binding, not the crate), noted
in the CHANGELOG entry that changes it.

## Test Status

```text
560 lib tests (576 with `ffi`, 604 with `wasm`) + 88 doc-tests
0 clippy warnings
```

## Dependencies

- [`u-numflow`](https://crates.io/crates/u-numflow) -- statistics, special functions, probability distributions

## References

- Montgomery, D.C. (2019). *Introduction to Statistical Quality Control*, 8th ed.
- Nelson, L.S. (1984). "The Shewhart Control Chart -- Tests for Special Causes"
- Abernethy, R.B. (2006). *The New Weibull Handbook*, 5th ed.
- Page, E.S. (1954). "Continuous Inspection Schemes", *Biometrika*
- Roberts, S.W. (1959). "Control Chart Tests Based on Geometric Moving Averages"
- Laney, D.B. (2002). "Improved Control Charts for Attributes", *Quality Engineering* 14(4), 531–537
- Stephens, M.A. (1974). "EDF Statistics for Goodness of Fit", *JASA* 69(347), 730–737
- Box, G.E.P. & Cox, D.R. (1964). "An Analysis of Transformations", *JRSS-B* 26(2), 211–252

## Related

- [u-numflow](https://crates.io/crates/u-numflow) -- Mathematical primitives
- [u-insight](https://github.com/iyulab/u-insight) -- Statistical analysis engine with C FFI
- [u-metaheur](https://crates.io/crates/u-metaheur) -- Metaheuristic algorithms
- [u-geometry](https://crates.io/crates/u-geometry) -- Computational geometry
- [u-schedule](https://crates.io/crates/u-schedule) -- Scheduling framework

## License

MIT