npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@iyulab/u-analytics

v0.37.0

Published

Statistical process control, process capability, Weibull reliability, change-point detection, measurement system analysis (Gage R&R), correlation, regression, distribution analysis, and hypothesis testing.

Readme

u-analytics

Crates.io docs.rs CI 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) and forecasts, with the prediction intervals of the additive-error state-space models | | seasonality | Periodogram (zero-padded FFT) and dominant-period estimation — AutoPeriod: permutation-thresholded peaks refined on the ACF | | decomposition | Seasonal-trend decomposition by Loess (STL, Cleveland et al. 1990) into trend, seasonal and remainder, with robust outlier weights and the strengths of trend and seasonality | | correlation | Correlation analysis (Pearson, Spearman, Kendall, partial, correlation matrices) | | regression | Regression analysis (simple OLS, multiple OLS, VIF multicollinearity), the coefficients' covariance, and at new points the confidence interval of the mean and the prediction interval of a new observation | | accuracy | Error measures of a model's predictions against observations — mean error, MAE, RMSE, CV(RMSE) and NMBE, with the residual degrees of freedom (ASHRAE Guideline 14's definitions) | | 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) | | equivalence | Equivalence testing — two one-sided tests (TOST) for a mean, paired data and two samples, with the 1 − 2α interval; a margin is on the difference, the p-value is the larger of the two | | tolerance | Normal tolerance intervals — the exact (P, γ) factor k (one- and two-sided, from the confidence integral rather than an approximation) and the interval x̄ ± k·s of a sample |

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
  • Short runs: one chart for a process that runs in groups (a part number, a recipe) — deviation from the group's aim, standardized Z-MR, and standardized P and U against each group's own centre
  • Multivariate: Hotelling T² for correlated variables — individual observations (Phase I and II against exact small-sample limits) and subgroups (covariance pooled within the subgroups)
  • 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
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");
}
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();

A process that makes several kinds of item in short runs has a target and a spread of its own for each kind; on one raw chart the limits widen to cover the distance between the targets and a shift inside one kind hides among the others. The short-run charts put every observation on a scale common to all groups first:

use u_analytics::spc::{standardized_chart, GroupStandard, RuleSet};

// Two kinds of item on one process: aimed at 10 and 20, varying by about 0.2 and 0.1.
let values = [10.2, 20.1, 10.0, 19.9, 10.1, 20.1];
let groups = [0, 1, 0, 1, 0, 1]; // an index into the targets
let chart = standardized_chart(
    &values,
    &groups,
    &[10.0, 20.0],
    GroupStandard::Known(&[0.2, 0.1]), // or GroupStandard::Estimated
    RuleSet::default(),
)
.unwrap();
assert_eq!(chart.limits.ucl, 3.0); // (x − target) / spread: the limits are ±3

Two variables that must keep their correlation can each look fine on their own chart while the pair is out of control. Hotelling's T² charts the distance of every observation from the mean in the metric of the covariance, against an exact limit (a Beta quantile for the history itself, an F quantile for new observations):

use u_analytics::spc::hotelling::{phase_i, phase_ii};

let history = vec![
    vec![1.0, 1.1], vec![2.0, 1.9], vec![3.0, 3.2], vec![4.0, 3.9],
    vec![5.0, 5.1], vec![6.0, 5.8], vec![7.0, 7.2], vec![8.0, 7.9],
    vec![4.5, 1.5], // inside both ranges, off the line the others follow
];
let chart = phase_i(&history, 0.0027).unwrap();
assert_eq!(chart.out_of_control, vec![8]);

// Remove the signal's cause, then watch new observations against the cleaned estimates.
let cleaned = phase_i(&history[..8], 0.0027).unwrap();
let next = phase_ii(&[vec![4.5, 4.4], vec![4.5, 1.5]], &cleaned.estimates, 0.0027).unwrap();
assert_eq!(next.out_of_control, vec![1]);

When the observations come in subgroups, the chart takes their means and measures the spread within the subgroups, so a mean that drifts between subgroups is a signal rather than part of the covariance:

use u_analytics::spc::hotelling::subgroup_phase_i;

// Six subgroups of three observations of two variables; the means move together by 1.5 a step.
let subgroups: Vec<Vec<Vec<f64>>> = (0..6)
    .map(|i| {
        let b = i as f64 * 1.5;
        vec![vec![b + 0.1, b + 0.3], vec![b - 0.2, b + 0.1], vec![b + 0.3, b - 0.1]]
    })
    .collect();
let chart = subgroup_phase_i(&subgroups, 0.0027).unwrap();
assert_eq!((chart.estimates.m, chart.estimates.n), (6, 3));

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
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.

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
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
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.

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)
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.

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.

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.

Decomposition — trend, season and remainder (STL)

With the period known, decomposition::Stl splits the series additively, data = trend + seasonal + residual, by the Loess procedure of Cleveland, Cleveland, McRae & Terpenning (1990), with the defaults of statsmodels' STL (seasonal span 7, trend and low-pass spans from the period, degree 1). robust adds the outer loop: each point gets a bisquare weight from its remainder, so an outlier lands in residual (weight near 0) instead of bending the components. The result also gives the strength of trend and seasonality, max(0, 1 − Var(R)/Var(C + R)) (Wang, Smith & Hyndman 2006).

use u_analytics::decomposition::Stl;

let pattern = [2.0, -1.0, 0.5, -1.5];
let y: Vec<f64> = (0..48).map(|i| 0.3 * i as f64 + pattern[i % 4]).collect();
let r = Stl::new(4).robust(true).decompose(&y).unwrap();
assert!((r.seasonal[20] - 2.0).abs() < 1e-6);
assert!(r.seasonal_strength > 0.99 && r.trend_strength > 0.99);
assert_eq!((r.trend_span, r.low_pass_span), (9, 5)); // statsmodels' defaults

Spans are odd (a Loess span is centred on its point); at least two full cycles of data are needed.

JavaScript / WASM (npm)

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.

// 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:

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, an even stl smoother span (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) | | degenerate_data | data without the variation or information the statistic needs — every value the same (parameter, and index for one of several variables), a test regression that is singular, a table row or column that sums to 0 | | invalid_input | any other refusal of the input, without a more specific reason (index, parameter); 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:

export function spectral_residual(input: SpectralResidualInputDto): SpectralResidualDto;
export function xbar_r_chart(data: number[][], options?: VariablesChartOptions | 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)

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.

Limits use the textbook table constants; sigma_hat uses the precise d2. xbar_r_chart and imr_chart place their limits with the three-digit published factors (A2, E2 -- A2(5) = 0.577, E2 = 2.660, as tabulated in Montgomery), whereas sigma_hat divides by the unrounded d2 (d2(2) = 2/sqrt(pi), d2(5) = 2.3259). The limit half-width is therefore not exactly 3 * sigma_hat -- it differs by about 0.03 % for an X-bar chart of five and 0.05 % for an individuals chart. When you need the half-width to be exactly three sigma (for instance to reproduce a limit from sigma_hat to the last digit), pass the sigma option: the limits are then 3 * sigma / sqrt(n) (3 * sigma for individuals), with no table constant involved.

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:

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

Fixing the within sigma (two-stage Phase I)

ISO 7870-2 (§7.5) homogenises a first study in two steps: the dispersion chart first -- subgroups with an assignable cause are dropped and the limits redone until it is in control, then its sigma is fixed -- and the location chart next, on the subgroups that remain, with that sigma, however many more the location chart drops. The three variables charts take it as sigma, the value the dispersion chart ended on (its sigma_hat):

// Step 1: the dispersion chart, until it is in control
const dispersion = xbar_r_chart(allSubgroups);
// Step 2: the location chart on the remaining subgroups, with step 1's sigma
const location = xbar_r_chart(keptSubgroups, { sigma: dispersion.sigma_hat });

The X-bar chart's centre line is still the grand mean of the subgroups given; its limits are CL ± 3 sigma / sqrt(n), and the R (or S, or MR) chart is that of sigma (d2 sigma, c4 sigma, with the usual D3/D4/B3/B4 factors) rather than of the subgroups' own spread. sigma_hat then returns sigma and sigma_hat_df is null: the degrees of freedom belong to the study that produced the sigma, which the caller knows. A sigma that is not above 0 is refused with parameter_out_of_range (parameter: "sigma", exclusive_min: 0). The same sigma is the "standard given" form of a Phase II limit.

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.

// 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

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[], sigma?: number }): {
  xbar_cl: number, xbar_ucl: number, xbar_lcl: number,
  s_cl: number, s_ucl: number, s_lcl: number,
  sigma_hat: number,             // S-bar / c4 (the `sigma` option, if given)
  sigma_hat_df: number | null,   // its degrees of freedom (David's approximation); null when `sigma` is given
  xbar_points: Point[], s_points: Point[], in_control: boolean,
}

imr_chart(values: number[], options?: { rules?: RuleSetName | RuleName[], sigma?: number }): {
  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) (the `sigma` option, if given)
  sigma_hat_df: number | null,   // 0.62 (n - 1); null when `sigma` is given
  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

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:

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

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.

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):

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 values 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.

Short-run charts — a process that runs in groups

// groups[i]: the group of values[i] — a whole number, an index into targets (and spreads, centers)
short_run_deviation_chart(values: number[], groups: number[], targets: number[],
                          options?: { rules?: RuleSetName | RuleName[], sigma?: number }): ShortRunChart
short_run_standardized_chart(values: number[], groups: number[], targets: number[],
                             options?: { rules?: RuleSetName | RuleName[], spreads?: number[] }): ShortRunChart
short_run_p_chart(samples: [defectives: number, size: number][], groups: number[],
                  options?: { centers?: number[] }): ShortRunAttributeChart
short_run_u_chart(samples: [defects: number, units: number][], groups: number[],
                  options?: { centers?: number[] }): ShortRunAttributeChart

type ShortRunChart = {
  scale: "deviation" | "standardized", groups: number[],
  i_cl: number, i_ucl: number, i_lcl: number,          // the individuals chart is centred at 0
  mr_cl: number, mr_ucl: number, mr_lcl: number,
  sigma_hat: number,                                    // 1 when standardized
  group_spreads: (number | null)[],                     // the spread used per group; [] when "deviation"
  i_points: ChartPoint[], mr_points: ChartPoint[],      // a point's group is groups[point.index]
  in_control: boolean }
type ShortRunAttributeChart = {
  groups: number[], group_centers: (number | null)[],   // null: a group no sample names
  points: AttrPoint[],                                  // each against its own group's cl and limits; z as above
  in_control: boolean }

short_run_deviation_chart plots x − target on one I-MR chart centred at 0 and assumes the groups vary alike; short_run_standardized_chart plots (x − target) / spread on an I-MR chart centred at 0 with sigma 1, so the individuals limits are ±3. A group's spread is given (spreads) or estimated from the moving ranges of that group's own successive values — a range across two groups measures the distance between targets, never a spread — which needs at least 3 observations in the group and values that are not all equal. An estimated spread makes the limits approximate; fix it from an earlier study when there is one. The attributes charts plot each sample against the centre of its own group: a given centers entry (a proportion strictly between 0 and 1, a rate above 0) or the group's total events over its total exposure (at least 2 samples per group). values and targets must be in one unit — the library cannot tell.

A refusal that is about one group rather than one row — insufficient_data for a group too small to estimate, degenerate_data for one that never moves, parameter_out_of_range for a bad spreads or centers entry — carries the group as index; a group beyond targets is parameter_out_of_range on groups with the row as index. A key an options object does not take (sigma on the standardized chart, spreads on the deviation chart) is refused as unknown_option.

const { short_run_standardized_chart } = require("@iyulab/u-analytics");

// Part 0 is aimed at 10 and varies by about 0.2; part 1 is aimed at 20 and varies by about 0.1.
const values = [10.2, 20.1, 10.0, 19.9, 10.1, 20.1];
const groups = [0, 1, 0, 1, 0, 1];
const chart = short_run_standardized_chart(values, groups, [10, 20], { spreads: [0.2, 0.1] });
console.log(chart.i_points.map(p => p.value));  // ≈ [1, 1, 0, -1, 0.5, 1]
console.log(chart.i_ucl, chart.i_lcl);          // 3, -3

Hotelling T² — correlated variables, one chart

// data / observations: one row per observation, one column per variable
hotelling_phase_i(data: number[][], alpha?: number | null): HotellingChart
hotelling_phase_ii(observations: number[][], reference: HotellingReference, alpha?: number | null): HotellingChart

type HotellingReference = { mean: number[], covariance: number[][], m: number }  // m: observations behind them, whole
type HotellingChart = {
  t2: number[],                    // T² of each row, in the order given
  ucl: number,                     // the upper limit (the lower is 0)
  out_of_control: number[],        // positions whose T² exceeds it
  in_control: boolean,
  estimates: HotellingReference }  // the reference Phase II takes

alpha is the false-alarm probability per point (default 0.0027, the 3-sigma rate). Phase I charts the history against its own mean and covariance with the exact limit (m − 1)²/m · B⁻¹(1 − α; p/2, (m − p − 1)/2) (Tracy, Young and Mason 1992), so it holds for small m; it needs m ≥ p + 2 rows. A row that signals is a candidate for removal — take out the ones with a known cause, run it again, and hand the estimates of the cleaned chart to Phase II, whose limit is p(m + 1)(m − 1)/(m(m − p)) · F⁻¹(1 − α; p, m − p) (m ≥ p + 1; observations may be empty: the limit alone). The limits assume independent, multivariate normal observations; subgrouped data and the multivariate EWMA are not computed.

Refusals: insufficient_data (data, or reference.m, with min and got), dimension_mismatch (data or observations with the row as index; reference.mean; reference.covariance with the row), value_not_finite, parameter_out_of_range (alpha, open bounds 0 and 1), malformed_input (reference.m not a whole number), and degenerate_data when the covariance cannot be inverted — a constant variable, or one that is a linear combination of the others.

const { hotelling_phase_i, hotelling_phase_ii } = require("@iyulab/u-analytics");

// Two variables that follow one line; the last row is inside both ranges but off the line.
const history = [[1, 1.1], [2, 1.9], [3, 3.2], [4, 3.9], [5, 5.1], [6, 5.8], [7, 7.2], [8, 7.9], [4.5, 1.5]];
const one = hotelling_phase_i(history);
console.log(one.out_of_control);                    // [8]

const cleaned = hotelling_phase_i(history.slice(0, 8));   // the cause of row 8 is known: drop it
const next = hotelling_phase_ii([[4.5, 4.4], [4.5, 1.5]], cleaned.estimates);
console.log(next.out_of_control, next.ucl > one.ucl);     // [1] true

Subgroups of n ≥ 2 observations use the same two functions with a subgroup in the name:

hotelling_subgroup_phase_i(subgroups: number[][][], alpha?: number | null): HotellingSubgroupChart
hotelling_subgroup_phase_ii(subgroups: number[][][], reference: HotellingSubgroupReference, alpha?: number | null): HotellingSubgroupChart

// subgroups[i]: the rows of subgroup i, every subgroup the same size n
type HotellingSubgroupReference = { mean: number[], covariance: number[][], m: number, n: number }  // m subgroups of n
type HotellingSubgroupChart = { t2: number[], ucl: number, out_of_control: number[], in_control: boolean,
                                estimates: HotellingSubgroupReference }

T² = n (x̄ − x̿)ᵀ S⁻¹ (x̄ − x̿) for each subgroup mean, with S the average of the within-subgroup covariance matrices, against p(m − 1)(n − 1)/(mn − m − p + 1) · F⁻¹(1 − α; p, mn − m − p + 1) (Phase I) or the same with m + 1 (Phase II; Alt 1985). The Phase I limit is Alt's F approximation, not an exact distribution; it needs n ≥ 2 and at least m + p observations in all (insufficient_data). A subgroup of another size or width is dimension_mismatch with the subgroup as index; reference.m and reference.n must be whole numbers.

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.

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,
}
// 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

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:

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:

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");
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.

// 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 (degenerate_data), 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 %
// KPSS — the complement: H0 stationary around a level ("level", default) or a
// trend ("trend"). >= 10 values. The long-run variance's truncation lag is chosen
// by lag_rule ("hobijn", default — Hobijn et al. 1998; "schwert") or fixed by lags
// (0..n-1; not both: invalid_option). ADF not rejecting and KPSS rejecting = a unit
// root: difference once and test again (the usual way to choose d).
kpss_test(input: { data: number[], model?: "level" | "trend",
                   lag_rule?: "hobijn" | "schwert" | null, lags?: number | null }):
  { statistic: number, n_lags: number,
    p_value: number,                                    // interpolated, within [0.01, 0.10]
    p_value_bound: "interpolated" | "at_most" | "at_least",  // beyond the table: a bound
    levels: { level: number, critical_value: number, rejected: boolean }[] }  // 1, 2.5, 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 -> degenerate_data at its index
simple_regression(x: number[] | Float64Array, y: number[] | Float64Array,
                  options?: { predict?: number[] | null, level?: number | null } | null):
  { 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
    intercept_slope_covariance: number, level: number,       // level: default 0.95, in (0, 1)
    predictions: { fit, se_fit, confidence: { lower, upper },  // mean response at that x
                   prediction: { lower, upper } }[] }       // a new observation; one per predict value
multiple_regression(input: {
  predictors: number[][],   // one array per predictor, each as long as y; >= p + 2 observations
  y: number[],
  predict?: number[][] | null,  // new points, laid out as predictors (one array per predictor)
  level?: number | null,        // of the intervals, in (0, 1); default 0.95
}): { coefficients: number[],   // intercept first
      std_errors, t_statistics: (number | null)[], p_values, r_squared, adjusted_r_squared,
      f_statistic: number | null, f_p_value, residual_se, df_residual: number,  // n - p - 1
      residuals, fitted, vif: (number | null)[],
      covariance: number[][],   // of the coefficients, MSE (X'X)^-1 (R's vcov)
      level, predictions: { fit, se_fit, confidence: { lower, upper }, prediction: { lower, upper } }[] }
// A constant predictor (index i) or one the others determine exactly -> degenerate_data.
// Intervals use Student's t on the residual degrees of freedom: the mean's is
// fit ± t·se_fit, a new observation's fit ± t·sqrt(residual_se² + se_fit²).
// Exponential smoothing and its forecasts; constants given or estimated.
exponential_smoothing(input: {
  data: number[],
  method: "simple" | "holt" | "holt_winters",  // level; + trend; + season
  alpha?: number | null,     // each constant in (0, 1); left out: estimated (least squares of
  beta?: number | null,      //   the one-step errors) -- holt, holt_winters (refused elsewhere: invalid_option)
  gamma?: number | null,     // holt_winters
  period?: number | null,    // holt_winters, >= 2; data >= 2 * period (simple >= 2, holt >= 3)
  seasonality?: "additive" | "multiplicative" | null,  // holt_winters; multiplicative needs data > 0
  horizon?: number | null,   // steps to forecast, 0..100000, default 0
  level?: number | null,     // of the prediction intervals, default 0.95
  crossing?: {               // when the forecast total reaches a level; needs horizon >= 1
    threshold: number,       //   non-zero: reached from below when > 0, from above when < 0
    quantiles?: number[] | null,  // each in (0, 1], default [0.1, 0.5, 0.9]
    paths?: number | null,   //   futures simulated, 1..1000000 and paths · horizon <= 1e9, default 10000
    seed?: number | null,    //   0..2^53, default 0
  } | null,
}): { alpha: number, beta: number | null, gamma: number | null,   // used, given or estimated
      estimated: ("alpha" | "beta" | "gamma")[],                    // which were estimated
      components: { level: number[], trend: number[] | null, seasonal: number[] | null },
      fitted: number[],                    // one-step-ahead
      residuals: (number | null)[],        // null where fitted is the initialisation
      sigma: number,                       // RMS one-step error
      level: number,
      forecasts: { step, mean, prediction: { lower, upper } | null,
                   cumulative: { mean, prediction: { lower, upper } | null } }[],  // total of steps 1..step
      first_passage: { threshold, probability,   // share of futures reaching it within the horizon
                       paths, quantiles: { q, time: number | null }[] } | null }  // null without crossing
// The intervals are the additive-error state-space model's (ETS(A,N,N), (A,A,N),
// (A,A,A); Hyndman et al. 2008) -- statsmodels' ETSModel with the same initial
// states. Multiplicative seasonality has no closed form: prediction is null.
// cumulative is the forecast of the total so far (stock consumed, wear, a budget
// spent): its interval comes from the covariances of the step errors,
// σ² Σ_{k<H} (1 + C_k)² with C_k the sum of the first k error weights -- wider than
// the sum of the steps' variances, narrower than adding up the steps' intervals.
// first_passage simulates the same model's innovations: time is in steps after the
// last observation, interpolated within the step the total reaches the level in,
// null when fewer than a share q of the futures reach it within the horizon.
// Cost O(paths · horizon). crossing with multiplicative seasonality: invalid_option.
prediction_errors(input: { observed: number[], predicted: number[],  // one length
                           parameters?: number | null }):           // p, 0..n-1, default 0
  { n, mean_error, mean_absolute_error,    // over n; errors are observed - predicted
    rmse,                                   // sqrt(Σe² / (n - p))
    cv_rmse: number | null,                 // rmse / mean(observed)
    nmbe: number | null,                    // Σe / ((n - p) · mean(observed)); null when that mean is 0
    parameters }
// With p the regression's coefficient count, cv_rmse and nmbe are ASHRAE
// Guideline 14's CV(RMSE) and NMBE -- as fractions (x 100 for percent).
fit_best(data: number[] | Float64Array):  // >= 2 values, not all equal; best AIC first
  { distribution: string, parameters: Record<string, number>, log_likelihood, aic, bic,
    anderson_darling: number }[]   // A² against each fit -- smaller is closer
// 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.
// AIC ranks the families against each other; it does not say the best one fits.
// goodness_of_fit does: A² against the fitted distribution, with a p-value from
// the parametric bootstrap (refit on `replicates` samples drawn from the fit), so
// it accounts for the parameters having been estimated from the same data.
goodness_of_fit(input: {
  data: number[],     // >= 8 values, not all equal
  distribution: "Normal" | "LogNormal" | "Weibull" | "Gamma" | "Exponential" | "Beta",
  replicates?: number, // 1..9999, default 199 (p resolved to 1 / (replicates + 1))
  seed?: number,       // default 0 -- the same request gives the same p-value
}): { distribution, parameters: Record<string, number>, statistic: number,
      p_value: number, replicates: number }   // small p: the family does not fit
// 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 -> degenerate_data.
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
type EquivalenceDto = {
  estimate: number, std_error: number, df: number,   // the difference, its se, the t df
  t_lower: number, t_upper: number,                  // (estimate - low) / se, (estimate - high) / se
  p_lower: number, p_upper: number,                  // P(T >= t_lower), P(T <= t_upper)
  p_value: number,                                   // the procedure's: max(p_lower, p_upper)
  ci_lower: number, ci_upper: number,                // the 1 - 2 * alpha interval of the difference
  equivalent: boolean }                              // p_value < alpha
tost_one_sample(data, target: number, low: number, high: number,
                alpha?: number | null): EquivalenceDto   // mean - target inside (low, high); >= 2 values
tost_paired(x, y, low, high, alpha?): EquivalenceDto     // mean of x - y (paired_t_test is y - x)
tost_two_sample(a, b, low, high, alpha?: number | null,
                equal_variance?: boolean | null): EquivalenceDto  // mean(a) - mean(b); Welch unless true
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]

Equivalence — to show that a difference is inside a margin rather t