# knotkit/hypothesis-test

> Computes t-test, ANOVA, rank-test, goodness-of-fit, and exact-test p-values for counts, samples, and contingency tables

## Use

```ts
import {
  Probability,
  binomialTest,
  chiSquaredGoodnessOfFitTest,
  kruskalWallisTest,
  mannWhitneyUTest,
  oneWayAnova,
  welchTTest,
} from 'knotkit/hypothesis-test'

const fairCoin = binomialTest(63, 100)
const ratio = binomialTest(682, 925, {
  successProbability: Probability.make(0.75),
})
const fit = chiSquaredGoodnessOfFitTest([23, 21, 30, 26], [0.25, 0.25, 0.25, 0.25].map(Probability.make))
const means = welchTTest([2.1, 3.4, 1.9, 5.6], [1.2, 2.9, 3.1, 0.8, 2.2], {
  alternative: 'greater',
})
const groups = oneWayAnova([
  [6, 8, 4, 5],
  [8, 12, 9, 11],
  [13, 9, 11, 8],
])
const ranks = mannWhitneyUTest([19, 22, 16, 29, 24], [20, 11, 17, 12])
const medians = kruskalWallisTest([
  [2.9, 3.0, 2.5, 2.6],
  [3.8, 2.7, 4.0, 2.4],
  [2.8, 3.4, 3.7, 2.2],
])
```

## What it solves

* compute a chi-square p-value for observed counts against category probabilities
* test whether draws fit a continuous distribution with Kolmogorov-Smirnov
* compare the distributions of two samples
* test one sample mean, two sample means, or paired measurements with a t-test, or three or more group means with a one-way ANOVA, or compare samples by rank with Mann-Whitney U, Wilcoxon signed-rank, or Kruskal-Wallis
* test an observed success count using an exact binomial p-value
* calculate a two-sided or directional Fisher exact p-value for a 2-by-2 table

## Try it

ScenarioDefaultReset

* Compare 8 clustered observations against Uniform(0, 1).
* Largest CDF gap D = 0.520. Two-sided p = 0.015 (exact).
* Compare 8 spread observations against Uniform(0, 1).
* Largest CDF gap D = 0.080. Two-sided p = 1.000 (exact).
* Use a one-sample Kolmogorov-Smirnov test for a fully specified continuous null.

Hover or focus a chart for exact values. Each change reruns [`demo.ts`](https://github.com/jkomyno/knotkit/blob/main/packages/hypothesis-test/demo.ts) against `knotkit/hypothesis-test` in your browser; the defaults reproduce the README figure.

## API

| Export                                                                                                           | Returns                                | Does                                                                                                                                                                                                                                                        |
| ---------------------------------------------------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| [`chiSquaredGoodnessOfFitTest`](/reference/knotkit/hypothesis-test/functions/chisquaredgoodnessoffittest/)       | `ChiSquaredGoodnessOfFitTestResult`    | Pearson goodness of fit with optional adjacent pooling. Construct category probabilities with Probability.make. Degrees of freedom above CHI_SQUARED_MAX_DEGREES_OF_FREEDOM surface DistributionInvalidInputError.                                          |
| [`kolmogorovSmirnovTest`](/reference/knotkit/hypothesis-test/functions/kolmogorovsmirnovtest/)                   | `KolmogorovSmirnovTestResult`          | Compare a sample with a continuous distribution, using the exact null distribution at fewer than 100 observations without repeated values.                                                                                                                  |
| [`twoSampleKolmogorovSmirnovTest`](/reference/knotkit/hypothesis-test/functions/twosamplekolmogorovsmirnovtest/) | `TwoSampleKolmogorovSmirnovTestResult` | Compare two samples, using the exact null distribution below 10,000 pairs without repeated pooled values.                                                                                                                                                   |
| [`oneSampleTTest`](/reference/knotkit/hypothesis-test/functions/onesamplettest/)                                 | `OneSampleTTestResult`                 | Student's t-test of a sample mean against an expected mean, as scipy.stats.ttest_1samp. A constant sample throws ZERO_VARIANCE where SciPy returns NaN.                                                                                                     |
| [`twoSampleTTest`](/reference/knotkit/hypothesis-test/functions/twosamplettest/)                                 | `TwoSampleTTestResult`                 | Pooled-variance t-test of two independent samples, as scipy.stats.ttest_ind with equal_var=True. Choose welchTTest when the variances may differ.                                                                                                           |
| [`welchTTest`](/reference/knotkit/hypothesis-test/functions/welchttest/)                                         | `WelchTTestResult`                     | Unequal-variance t-test with Welch-Satterthwaite degrees of freedom, as scipy.stats.ttest_ind with equal_var=False.                                                                                                                                         |
| [`pairedTTest`](/reference/knotkit/hypothesis-test/functions/pairedttest/)                                       | `PairedTTestResult`                    | t-test of paired measurements, as scipy.stats.ttest_rel: oneSampleTTest of the differences against zero.                                                                                                                                                    |
| [`oneWayAnova`](/reference/knotkit/hypothesis-test/functions/onewayanova/)                                       | `OneWayAnovaResult`                    | One-way ANOVA F-test of k >= 2 independent groups, as scipy.stats.f_oneway. The p-value is the upper tail, so it takes no alternative.                                                                                                                      |
| [`mannWhitneyUTest`](/reference/knotkit/hypothesis-test/functions/mannwhitneyutest/)                             | `MannWhitneyUTestResult`               | Mann-Whitney U rank test of two independent samples, as scipy.stats.mannwhitneyu. Exact without ties when the smaller sample has at most 8 values, else a tie-corrected normal approximation. All-equal values throw ZERO_VARIANCE where SciPy returns NaN. |
| [`wilcoxonSignedRankTest`](/reference/knotkit/hypothesis-test/functions/wilcoxonsignedranktest/)                 | `WilcoxonSignedRankTestResult`         | Wilcoxon signed-rank test of paired differences, as scipy.stats.wilcoxon with zero_method wilcox: zeros are dropped and ties take average ranks. All-zero differences throw ZERO_VARIANCE.                                                                  |
| [`kruskalWallisTest`](/reference/knotkit/hypothesis-test/functions/kruskalwallistest/)                           | `KruskalWallisTestResult`              | Tie-corrected Kruskal-Wallis H-test of k >= 2 independent groups, as scipy.stats.kruskal, with a chi-squared upper-tail p-value. It takes no alternative.                                                                                                   |
| [`binomialTest`](/reference/knotkit/hypothesis-test/functions/binomialtest/)                                     | `BinomialTestResult`                   | Test a success count under a binomial null. Construct the null successProbability with Probability.make. Trial counts above BINOMIAL_MAX_TRIALS surface DistributionInvalidInputError.                                                                      |
| [`fisherExactTest`](/reference/knotkit/hypothesis-test/functions/fisherexacttest/)                               | `FisherExactTestResult`                | Test the top-left count of a 2-by-2 table under its fixed margins. Tables above HYPERGEOMETRIC_MAX_POPULATION_SIZE surface DistributionInvalidInputError.                                                                                                   |

## Errors

Every error this module throws is `HypothesisTestInvalidInputError`, with a `code` from a closed, exported list. Branch on the code; the message is for people.

* `EMPTY_SAMPLE` `NON_FINITE_SAMPLE` `INVALID_COUNT` `INVALID_PROBABILITIES` `LENGTH_MISMATCH` `TOO_FEW_CATEGORIES` `INVALID_TABLE` `SUCCESSES_EXCEED_TRIALS` `INVALID_DEGREES_OF_FREEDOM` `ZERO_TOTAL_COUNT` `INVALID_OPTION` `TOO_SMALL_SAMPLE` `TOO_FEW_GROUPS` `ZERO_VARIANCE`

## When not to use it

| If you need to…                                                                                          | Use instead                                      |
| -------------------------------------------------------------------------------------------------------- | ------------------------------------------------ |
| evaluate a probability or draw from a named distribution                                                 | [`knotkit/distribution`](/modules/distribution/) |
| analyze regression, multi-factor or repeated-measures ANOVA, or paired-group rank tests such as Friedman | SciPy or R                                       |
| test chi-squared independence or Fisher exact on a larger contingency table                              | SciPy or R                                       |

## Performance

Measured by the suite in [`packages/hypothesis-test/__tests__/bench`](https://github.com/jkomyno/knotkit/tree/main/packages/hypothesis-test/__tests__/bench). The numbers come from one machine, so run the suite on yours before deciding on speed alone.

## Prompt an agent

Prompt · knotkit/hypothesis-testCopy prompt

```
Use knotkit/hypothesis-test for this task. If Knotkit is missing, follow https://knotkit.jkomyno.dev/getting-started.md#install-from-source. Import from 'knotkit/hypothesis-test'.

Exports:
- `chiSquaredGoodnessOfFitTest` → `ChiSquaredGoodnessOfFitTestResult`: Pearson goodness of fit with optional adjacent pooling. Construct category probabilities with Probability.make. Degrees of freedom above CHI_SQUARED_MAX_DEGREES_OF_FREEDOM surface DistributionInvalidInputError.
- `kolmogorovSmirnovTest` → `KolmogorovSmirnovTestResult`: Compare a sample with a continuous distribution, using the exact null distribution at fewer than 100 observations without repeated values.
- `twoSampleKolmogorovSmirnovTest` → `TwoSampleKolmogorovSmirnovTestResult`: Compare two samples, using the exact null distribution below 10,000 pairs without repeated pooled values.
- `oneSampleTTest` → `OneSampleTTestResult`: Student's t-test of a sample mean against an expected mean, as scipy.stats.ttest_1samp. A constant sample throws ZERO_VARIANCE where SciPy returns NaN.
- `twoSampleTTest` → `TwoSampleTTestResult`: Pooled-variance t-test of two independent samples, as scipy.stats.ttest_ind with equal_var=True. Choose welchTTest when the variances may differ.
- `welchTTest` → `WelchTTestResult`: Unequal-variance t-test with Welch-Satterthwaite degrees of freedom, as scipy.stats.ttest_ind with equal_var=False.
- `pairedTTest` → `PairedTTestResult`: t-test of paired measurements, as scipy.stats.ttest_rel: oneSampleTTest of the differences against zero.
- `oneWayAnova` → `OneWayAnovaResult`: One-way ANOVA F-test of k >= 2 independent groups, as scipy.stats.f_oneway. The p-value is the upper tail, so it takes no alternative.
- `mannWhitneyUTest` → `MannWhitneyUTestResult`: Mann-Whitney U rank test of two independent samples, as scipy.stats.mannwhitneyu. Exact without ties when the smaller sample has at most 8 values, else a tie-corrected normal approximation. All-equal values throw ZERO_VARIANCE where SciPy returns NaN.
- `wilcoxonSignedRankTest` → `WilcoxonSignedRankTestResult`: Wilcoxon signed-rank test of paired differences, as scipy.stats.wilcoxon with zero_method wilcox: zeros are dropped and ties take average ranks. All-zero differences throw ZERO_VARIANCE.
- `kruskalWallisTest` → `KruskalWallisTestResult`: Tie-corrected Kruskal-Wallis H-test of k >= 2 independent groups, as scipy.stats.kruskal, with a chi-squared upper-tail p-value. It takes no alternative.
- `binomialTest` → `BinomialTestResult`: Test a success count under a binomial null. Construct the null successProbability with Probability.make. Trial counts above BINOMIAL_MAX_TRIALS surface DistributionInvalidInputError.
- `fisherExactTest` → `FisherExactTestResult`: Test the top-left count of a 2-by-2 table under its fixed margins. Tables above HYPERGEOMETRIC_MAX_POPULATION_SIZE surface DistributionInvalidInputError.

Use something else when:
- evaluate a probability or draw from a named distribution → knotkit/distribution
- analyze regression, multi-factor or repeated-measures ANOVA, or paired-group rank tests such as Friedman → SciPy or R
- test chi-squared independence or Fisher exact on a larger contingency table → SciPy or R

Errors are HypothesisTestInvalidInputError with a `code` property. Branch on `error.code`, never on the message.

Full page: https://knotkit.jkomyno.dev/modules/hypothesis-test.md
Types: node_modules/knotkit/hypothesis-test/ and https://knotkit.jkomyno.dev/reference/knotkit/hypothesis-test/
```

## See also

* [API reference](/reference/knotkit/hypothesis-test/)every type and signature
* [Capability record](https://github.com/jkomyno/knotkit/blob/main/packages/hypothesis-test/knotkit.capability.json)this page as JSON, also in the installed package
* [Edit this page on GitHub](https://github.com/jkomyno/knotkit/edit/main/packages/hypothesis-test/knotkit.capability.json)suggest a change to the source record
