hardy-weinberg-genetics
v0.3.1
Published
Hardy-Weinberg equilibrium: allele/genotype frequencies, expected counts, and a chi-square goodness-of-fit test.
Maintainers
Readme
hardy-weinberg-genetics
Hardy-Weinberg equilibrium math for a single biallelic locus, plus a chi-square goodness-of-fit test to check whether an observed population departs from equilibrium. Pure ESM, zero dependencies.
Model
For alleles A and a with frequencies p and q (p + q = 1), the equilibrium genotype frequencies are:
AA = p^2 Aa = 2pq aa = q^2Genotype counts are passed as { AA, Aa, aa }.
Usage
import { alleleFrequencies, hweTest } from 'hardy-weinberg-genetics';
alleleFrequencies({ AA: 298, Aa: 489, aa: 213 });
// { p: 0.5425, q: 0.4575 }
const r = hweTest({ AA: 0, Aa: 100, aa: 0 });
// r.chi2, r.df (=1), r.pValue, r.expected, r.inEquilibriumAPI
alleleFrequencies({AA,Aa,aa})→{ p, q }expectedFrequencies(p)→{ AA, Aa, aa }expectedCounts(p, n)→ expected genotype countschiSquare(observed)→{ chi2, df, expected }chiSquarePValue(chi2, df)→ upper-tail p-valuehweTest(observed, alpha=0.05)→ full report incl.inEquilibrium
The p-value uses a series expansion of the regularized lower incomplete gamma function with a Lanczos ln-gamma; it's accurate to a few parts in 10^-4 across the usual chi-square range, which is well past what a genotype table needs.
Note on df
A biallelic HWE test has 1 degree of freedom: three genotype categories, minus one for the fixed total, minus one for the estimated allele frequency.
License
BSD-3-Clause
