HazelJS Stats Package
@hazeljs/stats provides descriptive statistics, inference, regression, resampling, and streaming statistics for TypeScript.
Quick Reference
- Purpose — Summarize observations, compare samples, estimate uncertainty, and fit statistical models.
- When to use — Analyze a batch, a stream, or the results of a Frame query inside a TypeScript app.
- Key concepts — Sample variance, missing-value policies, regression design, and mergeable accumulators.
- Dependencies —
@hazeljs/numeric. Frame adapters use the optional@hazeljs/framepeer. - Common patterns — Summarize a sample, choose a test or model, then read the result and its uncertainty.
- Common mistakes — Using unaligned rows for paired tests or assuming
describeuses population variance.
Purpose
Stats provides a common API for exploratory summaries and inference. Test and regression results expose estimates, test statistics, and uncertainty where the selected method provides them.
Architecture
graph TD A["Arrays and Numeric NDArrays"] --> B["Batch summaries, tests, and models"] C["Frame queries"] --> D["DuckDB descriptive summary"] C --> E["Aligned arrays"] E --> B F["Streaming observations"] --> G["Mergeable accumulators"] G --> H["Snapshots"]
Advantages
- Batch routines accept both regular JavaScript arrays and TypedArrays.
- Frame summaries can aggregate in DuckDB and transfer a single result row.
- Streaming accumulators can combine partition results in fixed memory.
Installation
The examples target HazelJS 2.2.0 and require Node.js 20 or later. Stats depends on Numeric for array and numerical operations.
npm install @hazeljs/stats@2.2.0
Quick Start
Summarize and compare samples
import { describe, meanAndVariance, tests } from '@hazeljs/stats';
const a = new Float64Array([12, 15, 10, 14, 13]);
const b = new Float64Array([10, 12, 9, 11, 12]);
const summary = describe(a);
const moments = meanAndVariance(a);
const welch = tests.ttestIndependent(a, b);
console.log(summary.median, moments.variance, welch.pValue);
describe accepts number arrays, Float32Array, Float64Array, and Numeric arrays. Its default is sample variance (ddof: 1). Use ddof: 0 for population variance. For a finite Float64Array that only needs mean and variance, meanAndVariance shares the mean calculation and skips quantiles and other descriptive statistics.
For operations that expose nanPolicy, omit excludes nonfinite observations, raise throws, and propagate reports missing results. Descriptive statistics default to omit.
API Overview
| API | Use |
|---|---|
tests.ttestIndependent | Welch's test by default. Set equalVariance: true for the pooled test. |
tests.ttestOneSample and tests.ttestPaired | Compare against a reference mean or analyze paired differences. |
tests.anovaOneWay | Compare multiple group means under the equal-variance assumption. |
tests.mannWhitneyU and tests.shapiroWilk | Run a tie-corrected rank test or test for normality. |
correlation.pearson and correlation.spearman | Measure linear or rank association. |
confidence.mean and effectSize.cohensD | Estimate a confidence interval for a mean or a standardized mean difference. |
distributions | Evaluate densities, probabilities, quantiles, or seeded samples for supported continuous and discrete distributions. |
Recipes
Port SciPy statistics
import { stats } from '@hazeljs/stats';
const a = [2, 4, 6, 8];
const b = [4, 7, 9, 12];
const pooled = stats.ttest_ind(a, b);
const welch = stats.ttest_ind(a, b, { equalVariance: false });
const sample = [1, 2, NaN, 3];
const ranks = stats.rankdata(sample, { nanPolicy: 'omit' }); // [1, 2, NaN, 3]
const standardized = stats.zscore(sample, { nanPolicy: 'omit', ddof: 1 }); // [-1, 0, NaN, 1]
console.log(pooled.pValue, welch.pValue);
Use the stats namespace or named imports from @hazeljs/stats. These functions work on one sample per input. Numeric arrays are flattened in row-major order. Hypothesis tests return HazelJS result objects with fields such as statistic and pValue.
| SciPy-style call | HazelJS behavior |
|---|---|
ttest_ind(a, b, options?) | Pooled variance by default. Use { equalVariance: false } for Welch. tests.ttestIndependent defaults to Welch. |
ttest_1samp(a, populationMean, options?), ttest_rel(a, b, options?) | Test a sample against a reference mean or test paired differences. |
f_oneway(...groups) | Equal-variance one-way ANOVA. Use tests.anovaOneWay(groups, options) to pass inference options. |
chi2_contingency(table, options?) | Chi-square independence test. Applies Yates’ correction to 2 × 2 tables by default. |
mannwhitneyu(a, b, options?), shapiro(a, options?) | Asymptotic Mann–Whitney U with tie correction, or Shapiro–Wilk normality testing. |
rankdata(a, options?) | Returns one-based ranks in a Float64Array. Tie methods are average (default), min, max, dense, and ordinal. |
zscore(a, options?), sem(a, options?) | Z-scores return a Float64Array and default to ddof: 0. Standard error returns a number and defaults to ddof: 1. |
iqr(a, { range: [25, 75] }), median_abs_deviation(a, { scale: 'normal' }) | Compute percentile spread or median absolute deviation. The percentile range defaults to 25–75. MAD defaults to scale 1, and the camelCase medianAbsDeviation has the same signature. |
norm, t, pearsonr, spearmanr | Evaluate distributions or compute correlations and their p-values. |
The SciPy-style t-test, ANOVA, Mann–Whitney, and Shapiro–Wilk wrappers and the descriptive helpers propagate nonfinite values by default. Where supported, pass { nanPolicy: 'omit' } to exclude them or { nanPolicy: 'raise' } to reject the input. Under omit, rankdata and zscore keep excluded positions as NaN.
Fit models and bootstrap intervals
import { bootstrap, mean, regression } from '@hazeljs/stats';
const x = [[0], [1], [2], [3], [4], [5]];
const linear = regression.ols(x, [1, 2, 2, 4, 5, 7]);
const logistic = regression.glm(x, [0, 0, 1, 0, 1, 1], {
family: 'binomial',
});
const estimate = bootstrap([1, 2, 4, 7, 9], mean, {
method: 'percentile',
level: 0.95,
nResamples: 2_000,
seed: 42,
});
console.log(estimate.confidenceInterval);
Pass one feature row per response. Models include an intercept by default and require a full-rank design with positive residual degrees of freedom. Regression rejects nonfinite inputs by default. Setting nanPolicy: 'omit' drops entire affected rows. GLM supports Gaussian identity, binomial logit for binary outcomes, and Poisson log for counts.
Bootstrap runs a scalar statistic on resamples drawn with replacement. Choose percentile or basic for the interval and set a seed for reproducibility.
Analyze Frame queries
Install Frame for the optional @hazeljs/stats/frame entry point.
npm install @hazeljs/frame@2.2.0
import { frame } from '@hazeljs/frame';
import { tests } from '@hazeljs/stats';
import { collectFrameColumns, describeFrame } from '@hazeljs/stats/frame';
const readings = frame([
{ id: 1, enabled: true, before: 12, after: 10 },
{ id: 2, enabled: true, before: 15, after: 12 },
{ id: 3, enabled: true, before: 14, after: 13 },
{ id: 4, enabled: false, before: 10, after: 10 },
])
.filter('enabled', 'eq', true)
.sortBy('id');
const summary = await describeFrame(readings, 'after');
const { before, after } = await collectFrameColumns(readings, ['before', 'after']);
const paired = tests.ttestPaired(before, after);
Both adapters accept columns declared as number. describeFrame runs the descriptive aggregates inside DuckDB after applying the query and transfers one aggregate row. collectFrameColumns transfers aligned Float64Array values and represents SQL NULL as NaN. Use .sortBy() when row order matters.
Process streams and merge partitions
import { OnlineCovariance, OnlineStats } from '@hazeljs/stats';
const totals = new OnlineStats().addAll([12, 15, 10]);
totals.merge(new OnlineStats().addAll([11, 17]));
const { count, mean, variance } = totals.snapshot();
const pairs = new OnlineCovariance();
pairs.add(12, 10).add(15, 12).add(10, 9);
const { covariance, correlation } = pairs.snapshot();
These accumulators use fixed memory. For an async stream, call .add() inside a for await...of loop. Merge accumulators that share the same nanPolicy. Snapshots report finite and missing counts separately. Pass snapshot(0) for population variance and covariance.
Benchmarks
Stats recorded the lowest medians among Stats, simple-statistics, and jStat for mean plus sample variance and the Welch t statistic on the 100,000-observation benchmark. Stats benchmark results
Run the Stats suite from the HazelJS source checkout.
npm ci
npm run build -w @hazeljs/frame -w @hazeljs/numeric -w @hazeljs/stats
cd benchmarks/stats
npm ci
npm start -- 100000
Each row reports the median of nine warm runs. mean_var and ttest_welch_stat compare equivalent calculations with simple-statistics and jStat. frame_describe compares in-DuckDB aggregation with collecting the same Frame data for JavaScript statistics. A dash means the suite has no timing for that library on that workload. Compare timings across the same row and check its reported sample size. The suite records measured medians and runtime metadata in results/latest.json.
Related Resources
- Numeric Package for multidimensional arrays and linear algebra
- Frame Package for typed tabular queries