Skip to content

Hardy–Weinberg proportions

Check genotype counts against what random mating predicts with the chi-square, likelihood-ratio and exact tests, and see why they part ways for rare alleles.

Advanced ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Compute Hardy–Weinberg expected genotype counts from allele frequency
  • Explain why the exact test is preferred for rare genotypes
  • List reasons other than selection for a departure

Read first

01

What equilibrium predicts

Read

Each person carries two copies of a gene site. If one allele has frequency pp and mating is random with respect to that site, genotypes follow Hardy–WeinbergHardy–Weinberg proportionsThe genotype shares p², 2p(1−p) and (1−p)² that random mating predicts from an allele's frequency. proportions:

AA:p2,Aa:2p(1−p),aa:(1−p)2AA : p^2, \qquad Aa : 2p(1-p), \qquad aa : (1-p)^2

You estimate pp from the genotypes themselves, then ask whether the counts match.

02

Try the guide's counts

Predict

Predict first

The guide's example has 100 people: 36 AAAA, 48 AaAa and 16 aaaa. Work out p^=(2×36+48)/200\hat p = (2 \times 36 + 48)/200, then the expected counts.

How do the observed counts compare?

Far from equilibriumClose to equilibriumExactly at equilibrium
Reveal

Exactly at equilibrium. p^\hat p = 0.6, so the expected counts are 36, 48 and 16. Both X2X^2 and G2G^2 are 0, and the exact p-value is 1. That example shows how to call the tests; it can't show a departure.

03

Now a real departure

Read

Keep p^=0.6\hat p = 0.6 but move people out of the middle: 45 AAAA, 30 AaAa, 25 aaaa. The expected counts are still 36, 48 and 16.

X2=(45−36)236+(30−48)248+(25−16)216=2.25+6.75+5.06=14.06X^2 = \frac{(45-36)^2}{36} + \frac{(30-48)^2}{48} + \frac{(25-16)^2}{16} = 2.25 + 6.75 + 5.06 = 14.06

There is one degree of freedom: three classes, minus one, minus the estimated pp. That gives p < .001. The sample has far too few heterozygotes.

Hardy–Weinberg proportionsRecorded · Python and R agreeRecorded 2026-11-17 · 40 values compared
R

χ²(1, N = 100) = 14.06, p < .001, F = 0.38

Frequency of allele A
0.6000
Minor allele frequency
0.4000
Pearson χ²
14.063
Likelihood ratio G²
14.197
df
1
p (Pearson χ² test)
< .001

Effect size

  • Inbreeding coefficient F 0.3750

Plots

Observed vs expected genotype shares of genotypeHow large are several estimates, how precise, and which exclude the null?

Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares.

View data
ShareserieshighGenotypelow
0.4500observed0.5476AA0.3561
0.3000observed0.3958Aa0.2189
0.2500observed0.3430aa0.1755
0.3600expected0.3600AA0.3600
0.4800expected0.4800Aa0.4800
0.1600expected0.1600aa0.1600

Assumptions

  • Expected counts ≥ 5 — Every expected count is at least 5 (smallest 16.00).
  • Unrelated people from one population — Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see.
  • Reliable genotype calls — Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it.

Observed and expected genotypes

GenotypeObservedExpectedObserved shareExpected sharePearson residual
AA45360.45000.36001.500
Aa30480.30000.4800−2.598
aa25160.25000.16002.250

All the tests of these counts

TestStatisticdfp
Pearson χ²14.06310.0002
Likelihood ratio G²14.19710.0002
Exact: outcomes no more likely than observed——0.0002
Exact: doubled smaller tail——0.0003
Exact: mid-p——0.0001
Exact, one-sided: heterozygote deficit——0.0001
Exact, one-sided: heterozygote excess——1.0000

Exact distribution of the heterozygote count

AaAAaaProbabilityObservedCounted in p
2846262.248e-5yes
3045250.0001yesyes
3244240.0006
3443230.0021
3642220.0066
3841210.0174
4040200.0385
4239190.0715
4438180.1120
4637170.1480
4836160.1650
5035150.1552
5234140.1229
5433130.0818
5632120.0456
5831110.0212
6030100.0082
622990.0026
642880.0007
662770.0001
682662.322e-5yes
  • The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.
  • A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart.
  • The exact distribution has 41 possible heterozygote counts; the table shows the ones nearest the most likely count and the observed one.
The exact R script · R R version 4.5.1 (2025-06-13)
# Hardy–Weinberg proportions (exact, χ², likelihood ratio)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.hwe 1.0.1 · spec 47a5760d8f057f26
# Dataset: hwe_counts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_hwe_* (Hardy–Weinberg tests, Wigginton et al. 2005), cs_prop_ci (twins of codesplash.stats)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hwe_counts.parquet", col_select = c("genotype", "departure")))
n_input <- nrow(df)
df[["genotype"]] <- factor(df[["genotype"]], levels = c("AA", "Aa", "aa"))  # stored level order
df <- df[stats::complete.cases(df[c("genotype", "departure")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("genotype", "departure"))  # infinite values stop the run (registry/errors.yaml)

# %% Genotype counts
g <- "genotype"
counts <- as.numeric(df[["departure"]])  # each row is one genotype with its count
tally <- cs_hwe_genotype_counts(df[[g]], counts, column = g)
n_nocall <- tally$n_nocall
if (n_nocall > 0) warnings <- c(warnings, sprintf("%d genotypes were no-calls and were left out.", as.integer(n_nocall)))
test <- "chisq"
alternative <- "two_sided"
exact_p <- "probability"

# %% Tests
r <- cs_hwe_test(tally$n_aa, tally$n_ab, tally$n_bb, alternative, exact_p)
n <- r$n
if (test == "chisq") {
  p <- r$p_chisq
  label <- "Pearson χ² test"
} else if (test == "lr") {
  p <- r$p_lr
  label <- "likelihood-ratio test"
} else {
  p <- r$p_exact
  label <- cs_hwe_exact_label(alternative, exact_p)
}
f <- r$inbreeding_f
me <- r$min_expected
genotypes <- c(tally$label_aa, tally$label_ab, tally$label_bb)
observed <- c(r$n_aa, r$n_ab, r$n_bb)
expected <- c(r$expected_aa, r$expected_ab, r$expected_bb)

# %% Assumptions
small <- sprintf("The smallest expected count is %.2f, below 5: the χ² and likelihood-ratio p-values lean on an approximation that is unreliable here; the exact test doesn't use it.", me)
if (test == "exact") {
  status <- "info"
  detail <- sprintf("The exact test doesn't use this approximation; the smallest expected count is %.2f.", me)
} else if (me < 1) {
  status <- "fail"
  detail <- sprintf("The smallest expected count is %.2f (below 1): the χ² approximation fails here; use the exact test.", me)
} else if (r$n_below_5 > 0) {
  status <- "warn"
  detail <- sprintf("%d of 3 expected counts are below 5 (smallest %.2f); prefer the exact test.", as.integer(r$n_below_5), me)
} else {
  status <- "pass"
  detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", me)
}
quality <- if (r$direction == "deficit") {
  "Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it."
} else if (r$direction == "excess") {
  "Too many heterozygotes here; paralogous sequence and other calling errors can look like this, so check the assay before reading biology into it."
} else {
  "Calling errors can shift genotype counts; counts alone can't confirm the calls are right."
}
assumptions <- list(
  list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail),
  list(key = "unrelated", label = "Unrelated people from one population", status = "info", detail = "Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see."),
  list(key = "genotype_quality", label = "Reliable genotype calls", status = "info", detail = quality)
)

# %% Result
summary <- sprintf("%s on %d genotypes of %s (%s %d, %s %d, %s %d): %s; minor allele frequency %.3f, F = %.3f.",
                   label, as.integer(n), g, genotypes[1], as.integer(r$n_aa), genotypes[2], as.integer(r$n_ab), genotypes[3], as.integer(r$n_bb),
                   cs_fmt_p(p), r$maf, f)
apa <- if (test == "chisq") {
  sprintf("χ²(1, N = %d) = %s, %s, F = %s", as.integer(n), cs_fmt_num(r$chi2), cs_fmt_p(p), cs_fmt_num(f))
} else if (test == "lr") {
  sprintf("G²(1, N = %d) = %s, %s, F = %s", as.integer(n), cs_fmt_num(r$g2), cs_fmt_p(p), cs_fmt_num(f))
} else {
  sprintf("Hardy–Weinberg %s, N = %d, %s, F = %s", label, as.integer(n), cs_fmt_p(p), cs_fmt_num(f))
}
shares <- observed / n
expected_shares <- expected / n
intervals <- lapply(1:3, function(i) cs_prop_ci(observed[i], n, 0.95, "wilson"))
frequencies <- data.frame(genotype = genotypes, observed = as.integer(observed), expected = expected, share = shares,
                          expected_share = expected_shares, resid = (observed - expected) / sqrt(expected), row.names = NULL)
tests <- data.frame(
  test = c("Pearson χ²", "Likelihood ratio G²", "Exact: outcomes no more likely than observed", "Exact: doubled smaller tail", "Exact: mid-p",
           "Exact, one-sided: heterozygote deficit", "Exact, one-sided: heterozygote excess"),
  statistic = c(r$chi2, r$g2, rep(NA_real_, 5)),
  df = c(1, 1, rep(NA_real_, 5)),
  p = c(r$p_chisq, r$p_lr, r$p_exact_probability, r$p_exact_doubled, r$p_exact_midp, r$p_exact_deficit, r$p_exact_excess),
  row.names = NULL
)
count_a <- 2 * r$n_aa + r$n_ab
count_b <- 2 * r$n_bb + r$n_ab
exact <- cs_hwe_exact_table(r$h, r$probs, r$n_ab, count_a, count_b)
notes <- list(
  "The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.",
  "A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart."
)
if (me < 5) notes <- c(list(small), notes)
if (exact$trimmed) {
  notes <- c(notes, list(sprintf("The exact distribution has %d possible heterozygote counts; the table shows the ones nearest the most likely count and the observed one.", length(r$h))))
}
result_values <- list(
  n = n, n_aa = r$n_aa, n_ab = r$n_ab, n_bb = r$n_bb, n_nocall = n_nocall,
  allele_a = tally$allele_a, allele_b = tally$allele_b, label_aa = genotypes[1], label_ab = genotypes[2], label_bb = genotypes[3],
  p_allele_a = r$p_allele_a, p_allele_b = r$p_allele_b, maf = r$maf,
  expected_aa = r$expected_aa, expected_ab = r$expected_ab, expected_bb = r$expected_bb,
  min_expected = me, n_below_5 = r$n_below_5, het_obs = r$het_obs, het_exp = r$het_exp,
  inbreeding_f = f, d_a = r$d_a, direction = r$direction, chi2 = r$chi2, g2 = r$g2, df = r$df,
  p_chisq = r$p_chisq, p_lr = r$p_lr, p_exact = r$p_exact, p_exact_probability = r$p_exact_probability,
  p_exact_doubled = r$p_exact_doubled, p_exact_midp = r$p_exact_midp, p_exact_deficit = r$p_exact_deficit,
  p_exact_excess = r$p_exact_excess, p_observed = r$p_observed, p = p,
  test = test, test_label = label, alternative = alternative, exact_p = exact_p
)
cs_publish(list(
  method = "genetics.hwe",
  methodVersion = "1.0.1",
  title = "Hardy–Weinberg proportions",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "p_allele_a", label = sprintf("Frequency of allele %s", tally$allele_a), value = r$p_allele_a),
    list(key = "maf", label = "Minor allele frequency", value = r$maf),
    list(key = "chi2", label = "Pearson χ²", value = r$chi2),
    list(key = "g2", label = "Likelihood ratio G²", value = r$g2),
    list(key = "df", label = "df", value = r$df),
    list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")
  ),
  tables = list(
    list(key = "frequencies", title = "Observed and expected genotypes",
         columns = list(list(key = "genotype", label = "Genotype", type = "string"), list(key = "observed", label = "Observed", type = "integer"),
                        list(key = "expected", label = "Expected", type = "number"), list(key = "share", label = "Observed share", type = "number"),
                        list(key = "expected_share", label = "Expected share", type = "number"), list(key = "resid", label = "Pearson residual", type = "number")),
         rows = frequencies),
    list(key = "tests", title = "All the tests of these counts",
         columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
                        list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "p")),
         rows = tests),
    list(key = "exact_distribution", title = "Exact distribution of the heterozygote count",
         columns = list(list(key = "het", label = genotypes[2], type = "integer"), list(key = "n_aa", label = genotypes[1], type = "integer"),
                        list(key = "n_bb", label = genotypes[3], type = "integer"), list(key = "probability", label = "Probability", type = "number"),
                        list(key = "observed", label = "Observed", type = "string"), list(key = "counted", label = "Counted in p", type = "string")),
         rows = exact$rows)
  ),
  effectSizes = list(list(key = "inbreeding_f", label = "Inbreeding coefficient F", value = f, method = "1 − observed heterozygosity / expected heterozygosity")),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(cs_chart(
    "genotype_shares", "forest", sprintf("Observed vs expected genotype shares of %s", g),
    list(label = cs_col("Genotype", rep(genotypes, 2)), estimate = cs_col("Share", c(shares, expected_shares)),
         low = cs_col("low", c(vapply(intervals, `[`, numeric(1), 1), expected_shares)),
         high = cs_col("high", c(vapply(intervals, `[`, numeric(1), 2), expected_shares)),
         group = cs_col("series", rep(c("observed", "expected"), each = 3))),
    note = "Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares."
  )),
  values = result_values
))
Python

χ²(1, N = 100) = 14.06, p < .001, F = 0.38

Frequency of allele A
0.6000
Minor allele frequency
0.4000
Pearson χ²
14.063
Likelihood ratio G²
14.197
df
1
p (Pearson χ² test)
< .001

Effect size

  • Inbreeding coefficient F 0.3750

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Expected counts ≥ 5 — Every expected count is at least 5 (smallest 16.00).
  • Unrelated people from one population — Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see.
  • Reliable genotype calls — Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it.

Observed and expected genotypes

GenotypeObservedExpectedObserved shareExpected sharePearson residual
AA45360.45000.36001.500
Aa30480.30000.4800−2.598
aa25160.25000.16002.250

All the tests of these counts

TestStatisticdfp
Pearson χ²14.06310.0002
Likelihood ratio G²14.19710.0002
Exact: outcomes no more likely than observed——0.0002
Exact: doubled smaller tail——0.0003
Exact: mid-p——0.0001
Exact, one-sided: heterozygote deficit——0.0001
Exact, one-sided: heterozygote excess——1.0000

Exact distribution of the heterozygote count

AaAAaaProbabilityObservedCounted in p
2846262.248e-5yes
3045250.0001yesyes
3244240.0006
3443230.0021
3642220.0066
3841210.0174
4040200.0385
4239190.0715
4438180.1120
4637170.1480
4836160.1650
5035150.1552
5234140.1229
5433130.0818
5632120.0456
5831110.0212
6030100.0082
622990.0026
642880.0007
662770.0001
682662.322e-5yes
  • The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.
  • A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart.
  • The exact distribution has 41 possible heterozygote counts; the table shows the ones nearest the most likely count and the observed one.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hardy–Weinberg proportions (exact, χ², likelihood ratio)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.hwe 1.0.1 · spec 47a5760d8f057f26
# Dataset: hwe_counts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import hwe as csh  # Hardy–Weinberg tests, Wigginton et al. 2005 (twins of cs_hwe_*)
from codesplash.stats import proportions as csp  # Wilson intervals (twin of cs_prop_ci)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/hwe_counts.parquet", columns=["genotype", "departure"])
n_input = len(df)
df["genotype"] = pd.Categorical(df["genotype"], categories=["AA", "Aa", "aa"])  # stored level order
df = df.dropna(subset=["genotype", "departure"])  # listwise deletion over the analysis columns
df["genotype"] = df["genotype"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["genotype", "departure"])  # infinite values stop the run (registry/errors.yaml)

# %% Genotype counts
g = "genotype"
counts = df["departure"].to_numpy(dtype=float)  # each row is one genotype with its count
tally = csh.genotype_counts(df[g], counts, column=g)
n_nocall = int(tally["n_nocall"])
if n_nocall:
    warnings.append(f"{n_nocall} genotypes were no-calls and were left out.")
test = "chisq"
alternative = "two_sided"
exact_p = "probability"

# %% Tests
r = csh.hwe_test(tally["n_aa"], tally["n_ab"], tally["n_bb"], alternative, exact_p)
n = r["n"]
if test == "chisq":
    p, label = r["p_chisq"], "Pearson χ² test"
elif test == "lr":
    p, label = r["p_lr"], "likelihood-ratio test"
else:
    p, label = r["p_exact"], csh.exact_label(alternative, exact_p)
f = r["inbreeding_f"]
me = r["min_expected"]
genotypes = [tally["label_aa"], tally["label_ab"], tally["label_bb"]]
observed = np.array([r["n_aa"], r["n_ab"], r["n_bb"]], dtype=float)
expected = np.array([r["expected_aa"], r["expected_ab"], r["expected_bb"]])

# %% Assumptions
small = f"The smallest expected count is {me:.2f}, below 5: the χ² and likelihood-ratio p-values lean on an approximation that is unreliable here; the exact test doesn't use it."
if test == "exact":
    status, detail = "info", f"The exact test doesn't use this approximation; the smallest expected count is {me:.2f}."
elif me < 1:
    status, detail = "fail", f"The smallest expected count is {me:.2f} (below 1): the χ² approximation fails here; use the exact test."
elif r["n_below_5"] > 0:
    status, detail = "warn", f"{r['n_below_5']} of 3 expected counts are below 5 (smallest {me:.2f}); prefer the exact test."
else:
    status, detail = "pass", f"Every expected count is at least 5 (smallest {me:.2f})."
if r["direction"] == "deficit":
    quality = "Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it."
elif r["direction"] == "excess":
    quality = "Too many heterozygotes here; paralogous sequence and other calling errors can look like this, so check the assay before reading biology into it."
else:
    quality = "Calling errors can shift genotype counts; counts alone can't confirm the calls are right."
assumptions = [
    {"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail},
    {"key": "unrelated", "label": "Unrelated people from one population", "status": "info", "detail": "Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see."},
    {"key": "genotype_quality", "label": "Reliable genotype calls", "status": "info", "detail": quality},
]

# %% Result
summary = (f"{label} on {int(n)} genotypes of {g} ({genotypes[0]} {int(r['n_aa'])}, {genotypes[1]} {int(r['n_ab'])}, {genotypes[2]} {int(r['n_bb'])}): "
           f"{cs.fmt_p(p)}; minor allele frequency {r['maf']:.3f}, F = {f:.3f}.")
if test == "chisq":
    apa = f"χ²(1, N = {int(n)}) = {cs.fmt_num(r['chi2'])}, {cs.fmt_p(p)}, F = {cs.fmt_num(f)}"
elif test == "lr":
    apa = f"G²(1, N = {int(n)}) = {cs.fmt_num(r['g2'])}, {cs.fmt_p(p)}, F = {cs.fmt_num(f)}"
else:
    apa = f"Hardy–Weinberg {label}, N = {int(n)}, {cs.fmt_p(p)}, F = {cs.fmt_num(f)}"
shares = observed / n
expected_shares = expected / n
intervals = [csp.prop_ci(observed[i], n, 0.95, "wilson") for i in range(3)]
frequencies = [{"genotype": genotypes[i], "observed": int(observed[i]), "expected": float(expected[i]), "share": float(shares[i]),
                "expected_share": float(expected_shares[i]), "resid": float((observed[i] - expected[i]) / np.sqrt(expected[i]))} for i in range(3)]
tests = [
    {"test": "Pearson χ²", "statistic": r["chi2"], "df": 1, "p": r["p_chisq"]},
    {"test": "Likelihood ratio G²", "statistic": r["g2"], "df": 1, "p": r["p_lr"]},
    {"test": "Exact: outcomes no more likely than observed", "statistic": None, "df": None, "p": r["p_exact_probability"]},
    {"test": "Exact: doubled smaller tail", "statistic": None, "df": None, "p": r["p_exact_doubled"]},
    {"test": "Exact: mid-p", "statistic": None, "df": None, "p": r["p_exact_midp"]},
    {"test": "Exact, one-sided: heterozygote deficit", "statistic": None, "df": None, "p": r["p_exact_deficit"]},
    {"test": "Exact, one-sided: heterozygote excess", "statistic": None, "df": None, "p": r["p_exact_excess"]},
]
count_a, count_b = 2 * r["n_aa"] + r["n_ab"], 2 * r["n_bb"] + r["n_ab"]
exact_rows, trimmed = csh.exact_table(r["h"], r["probs"], r["n_ab"], count_a, count_b)
notes = [
    "The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.",
    "A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart.",
]
if me < 5:
    notes.insert(0, small)
if trimmed:
    notes.append(f"The exact distribution has {len(r['h'])} possible heterozygote counts; the table shows the ones nearest the most likely count and the observed one.")
values = {
    "n": n, "n_aa": r["n_aa"], "n_ab": r["n_ab"], "n_bb": r["n_bb"], "n_nocall": n_nocall,
    "allele_a": tally["allele_a"], "allele_b": tally["allele_b"], "label_aa": genotypes[0], "label_ab": genotypes[1], "label_bb": genotypes[2],
    "p_allele_a": r["p_allele_a"], "p_allele_b": r["p_allele_b"], "maf": r["maf"],
    "expected_aa": r["expected_aa"], "expected_ab": r["expected_ab"], "expected_bb": r["expected_bb"],
    "min_expected": me, "n_below_5": r["n_below_5"], "het_obs": r["het_obs"], "het_exp": r["het_exp"],
    "inbreeding_f": f, "d_a": r["d_a"], "direction": r["direction"], "chi2": r["chi2"], "g2": r["g2"], "df": r["df"],
    "p_chisq": r["p_chisq"], "p_lr": r["p_lr"], "p_exact": r["p_exact"], "p_exact_probability": r["p_exact_probability"],
    "p_exact_doubled": r["p_exact_doubled"], "p_exact_midp": r["p_exact_midp"], "p_exact_deficit": r["p_exact_deficit"],
    "p_exact_excess": r["p_exact_excess"], "p_observed": r["p_observed"], "p": p,
    "test": test, "test_label": label, "alternative": alternative, "exact_p": exact_p,
}
cs.publish({
    "method": "genetics.hwe",
    "methodVersion": "1.0.1",
    "title": "Hardy–Weinberg proportions",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": int(n),
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "p_allele_a", "label": f"Frequency of allele {tally['allele_a']}", "value": r["p_allele_a"]},
        {"key": "maf", "label": "Minor allele frequency", "value": r["maf"]},
        {"key": "chi2", "label": "Pearson χ²", "value": r["chi2"]},
        {"key": "g2", "label": "Likelihood ratio G²", "value": r["g2"]},
        {"key": "df", "label": "df", "value": r["df"]},
        {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
    ],
    "tables": [
        {"key": "frequencies", "title": "Observed and expected genotypes",
         "columns": [{"key": "genotype", "label": "Genotype", "type": "string"}, {"key": "observed", "label": "Observed", "type": "integer"},
                     {"key": "expected", "label": "Expected", "type": "number"}, {"key": "share", "label": "Observed share", "type": "number"},
                     {"key": "expected_share", "label": "Expected share", "type": "number"}, {"key": "resid", "label": "Pearson residual", "type": "number"}],
         "rows": frequencies},
        {"key": "tests", "title": "All the tests of these counts",
         "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
                     {"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
         "rows": tests},
        {"key": "exact_distribution", "title": "Exact distribution of the heterozygote count",
         "columns": [{"key": "het", "label": genotypes[1], "type": "integer"}, {"key": "n_aa", "label": genotypes[0], "type": "integer"},
                     {"key": "n_bb", "label": genotypes[2], "type": "integer"}, {"key": "probability", "label": "Probability", "type": "number"},
                     {"key": "observed", "label": "Observed", "type": "string"}, {"key": "counted", "label": "Counted in p", "type": "string"}],
         "rows": exact_rows},
    ],
    "effectSizes": [{"key": "inbreeding_f", "label": "Inbreeding coefficient F", "value": f, "method": "1 − observed heterozygosity / expected heterozygosity"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [cs.chart(
        "genotype_shares", "forest", f"Observed vs expected genotype shares of {g}",
        {"label": cs.col("Genotype", genotypes * 2),
         "estimate": cs.col("Share", [float(s) for s in shares] + [float(s) for s in expected_shares]),
         "low": cs.col("low", [c[0] for c in intervals] + [float(s) for s in expected_shares]),
         "high": cs.col("high", [c[1] for c in intervals] + [float(s) for s in expected_shares]),
         "group": cs.col("series", ["observed"] * 3 + ["expected"] * 3)},
        note="Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares.",
    )],
    "values": values,
})

The card also reports the inbreeding coefficientInbreeding coefficient FF = 1 − observed / expected heterozygosity. Positive means too few heterozygotes; negative means too many. FF = 0.375, which is 1−30/481 - 30/48: the share of the expected heterozygotes that are missing. Despite the name, it doesn't prove inbreeding.

04

Move the departure

Explore

Change the allele frequency and the deficit of heterozygotes. Find a setting where the rarest genotype's expected count falls below 5.

BExplorable · Hardy–Weinberg chi square test

Are genotype counts consistent with random mating?

200
0.40
0.15

0 is Hardy–Weinberg equilibrium.

0.050

Your data

Edit the counts
AAAaaa
417683

Dashed lines: the counts H₀ expects (equal shares).

If H₀ were true

χ² = 8.40
  1. The reference: how χ² varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .004).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

χ2=∑g(Og−Eg)2Eg,E=N(p^2, 2p^q^, q^2), ν=1\chi^2 = \sum_{g}\dfrac{(O_g-E_g)^2}{E_g},\quad E = N\left(\hat p^2,\ 2\hat p\hat q,\ \hat q^2\right),\ \nu = 1

With your numbers

χ2=8.40,p^=0.40\chi^2 = 8.40,\quad \hat p = 0.40
p^\hat p
allele frequency estimated from the genotypes
ν=1\nu = 1
3 classes − 1 − 1 estimated frequency

The verdict

χ²(1) = 8.40, p = .004, F = 0.20

p ≤ α = .050: reject H₀

Effect size: inbreeding coefficient F = 0.205

Deviations flag genotyping error, population structure or inbreeding. Use the exact test when a genotype is rare.

Statistic
8.400
p-value
0.0038
Hardy–Weinberg chi square test on 41, 76, 83 across 3 categories: χ²(1) = 8.40, p = .004, F = 0.20. The p-value is below α = .050, so the data are hard to reconcile with H0.

Hardy–Weinberg chi square test on 41, 76, 83 across 3 categories: χ²(1) = 8.40, p = .004, F = 0.20. The p-value is below α = .050, so the data are hard to reconcile with H₀.

This view uses simulated counts. The likelihood-ratio form below is built from the same observed and expected counts, with logs in place of squares.

BExplorable · Hardy–Weinberg likelihood ratio test

Are genotype counts consistent with random mating (likelihood ratio)?

200
0.40
0.15

0 is Hardy–Weinberg equilibrium.

0.050

Your data

Edit the counts
AAAaaa
417683

Dashed lines: the counts H₀ expects (equal shares).

If H₀ were true

G = 8.37
  1. The reference: how G varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the area at least as extreme as yours (p = .004).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

G=2∑gOgln⁡OgEg∼χ12G = 2\sum_g O_g\ln\dfrac{O_g}{E_g}\sim\chi^2_1

With your numbers

G=8.37,p^=0.40G = 8.37,\quad \hat p = 0.40
Og, EgO_g,\ E_g
observed and Hardy–Weinberg expected genotype counts

The verdict

G(1) = 8.37, p = .004, F = 0.20

p ≤ α = .050: reject H₀

Effect size: inbreeding coefficient F = 0.205

Asymptotically the same as the χ² version; both fail with rare genotypes.

Statistic
8.372
p-value
0.0038
Hardy–Weinberg likelihood ratio test on 41, 76, 83 across 3 categories: G(1) = 8.37, p = .004, F = 0.20. The p-value is below α = .050, so the data are hard to reconcile with H0.

Hardy–Weinberg likelihood ratio test on 41, 76, 83 across 3 categories: G(1) = 8.37, p = .004, F = 0.20. The p-value is below α = .050, so the data are hard to reconcile with H₀.

05

The likelihood-ratio test

Read
G2=2∑gOgln⁡OgEgG^2 = 2\sum_{g} O_g \ln\frac{O_g}{E_g}

For the same counts, G2G^2 = 14.20, close to X2X^2 = 14.06. With well-filled cells, the two agree. Neither is trustworthy when an expected count is tiny, because both lean on a chi-square approximation.

06

A rare allele

Predict

Predict first

Now 20 people: 17 AAAA, 2 AaAa, 1 aaaa. So p^=0.9\hat p = 0.9, and the expected aaaa count is only 0.20.2.

What do you expect from the chi-square and exact tests?

All three tests agreeChi-square looks significant, exact doesn'tExact looks significant, chi-square doesn't
Reveal

Chi-square gives X2X^2 = 3.95, p = .047. The likelihood-ratio test gives p = .113. The exact test gives p = .152. One person with aaaa is too little to carry that much weight, and the approximation overstates it.

07

The exact test

Read

Condition on the allele count aa, here 44. Then the only thing that varies is the number of heterozygotes hh:

P(h∣a,N)∝2hh! (a−h2)! (2N−a−h2)!P(h \mid a, N) \propto \frac{2^h}{h!\,\left(\frac{a-h}{2}\right)!\,\left(\frac{2N-a-h}{2}\right)!}
hhGenotypes (AAAA, AaAa, aaaa)Probability
416, 4, 00.8480.848
217, 2, 10.1500.150
018, 0, 20.0020.002

Add every outcome no more likely than yours: 0.150+0.002=0.1520.150 + 0.002 = 0.152.

Hardy–Weinberg proportionsRecorded · Python and R agreeRecorded 2026-11-17 · 40 values compared
R

Hardy–Weinberg exact test, N = 20, p = .152, F = 0.44

Frequency of allele A
0.9000
Minor allele frequency
0.1000
Pearson χ²
3.951
Likelihood ratio G²
2.507
df
1
p (exact test)
.152

Effect size

  • Inbreeding coefficient F 0.4444

Plots

Observed vs expected genotype shares of genotypeHow large are several estimates, how precise, and which exclude the null?

Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares.

View data
ShareserieshighGenotypelow
0.8500observed0.9476AA0.6396
0.1000observed0.3010Aa0.0279
0.0500observed0.2361aa0.0089
0.8100expected0.8100AA0.8100
0.1800expected0.1800Aa0.1800
0.0100expected0.0100aa0.0100

Assumptions

  • Expected counts ≥ 5 — The exact test doesn't use this approximation; the smallest expected count is 0.20.
  • Unrelated people from one population — Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see.
  • Reliable genotype calls — Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it.

Observed and expected genotypes

GenotypeObservedExpectedObserved shareExpected sharePearson residual
AA1716.2000.85000.81000.1988
Aa23.6000.10000.1800−0.8433
aa10.20000.05000.01001.789

All the tests of these counts

TestStatisticdfp
Pearson χ²3.95110.0469
Likelihood ratio G²2.50710.1134
Exact: outcomes no more likely than observed——0.1518
Exact: doubled smaller tail——0.3035
Exact: mid-p——0.0769
Exact, one-sided: heterozygote deficit——0.1518
Exact, one-sided: heterozygote excess——0.9979

Exact distribution of the heterozygote count

AaAAaaProbabilityObservedCounted in p
01820.0021yes
21710.1497yesyes
41600.8482
  • The smallest expected count is 0.20, below 5: the χ² and likelihood-ratio p-values lean on an approximation that is unreliable here; the exact test doesn't use it.
  • The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.
  • A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart.
The exact R script · R R version 4.5.1 (2025-06-13)
# Hardy–Weinberg proportions (exact, χ², likelihood ratio)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.hwe 1.0.1 · spec a6068417f624166e
# Dataset: hwe_counts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr) # cs_hwe_* (Hardy–Weinberg tests, Wigginton et al. 2005), cs_prop_ci (twins of codesplash.stats)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hwe_counts.parquet", col_select = c("genotype", "rare")))
n_input <- nrow(df)
df[["genotype"]] <- factor(df[["genotype"]], levels = c("AA", "Aa", "aa"))  # stored level order
df <- df[stats::complete.cases(df[c("genotype", "rare")]), , drop = FALSE]  # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
  warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("genotype", "rare"))  # infinite values stop the run (registry/errors.yaml)

# %% Genotype counts
g <- "genotype"
counts <- as.numeric(df[["rare"]])  # each row is one genotype with its count
tally <- cs_hwe_genotype_counts(df[[g]], counts, column = g)
n_nocall <- tally$n_nocall
if (n_nocall > 0) warnings <- c(warnings, sprintf("%d genotypes were no-calls and were left out.", as.integer(n_nocall)))
test <- "exact"
alternative <- "two_sided"
exact_p <- "probability"

# %% Tests
r <- cs_hwe_test(tally$n_aa, tally$n_ab, tally$n_bb, alternative, exact_p)
n <- r$n
if (test == "chisq") {
  p <- r$p_chisq
  label <- "Pearson χ² test"
} else if (test == "lr") {
  p <- r$p_lr
  label <- "likelihood-ratio test"
} else {
  p <- r$p_exact
  label <- cs_hwe_exact_label(alternative, exact_p)
}
f <- r$inbreeding_f
me <- r$min_expected
genotypes <- c(tally$label_aa, tally$label_ab, tally$label_bb)
observed <- c(r$n_aa, r$n_ab, r$n_bb)
expected <- c(r$expected_aa, r$expected_ab, r$expected_bb)

# %% Assumptions
small <- sprintf("The smallest expected count is %.2f, below 5: the χ² and likelihood-ratio p-values lean on an approximation that is unreliable here; the exact test doesn't use it.", me)
if (test == "exact") {
  status <- "info"
  detail <- sprintf("The exact test doesn't use this approximation; the smallest expected count is %.2f.", me)
} else if (me < 1) {
  status <- "fail"
  detail <- sprintf("The smallest expected count is %.2f (below 1): the χ² approximation fails here; use the exact test.", me)
} else if (r$n_below_5 > 0) {
  status <- "warn"
  detail <- sprintf("%d of 3 expected counts are below 5 (smallest %.2f); prefer the exact test.", as.integer(r$n_below_5), me)
} else {
  status <- "pass"
  detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", me)
}
quality <- if (r$direction == "deficit") {
  "Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it."
} else if (r$direction == "excess") {
  "Too many heterozygotes here; paralogous sequence and other calling errors can look like this, so check the assay before reading biology into it."
} else {
  "Calling errors can shift genotype counts; counts alone can't confirm the calls are right."
}
assumptions <- list(
  list(key = "expected_counts", label = "Expected counts ≥ 5", status = status, detail = detail),
  list(key = "unrelated", label = "Unrelated people from one population", status = "info", detail = "Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see."),
  list(key = "genotype_quality", label = "Reliable genotype calls", status = "info", detail = quality)
)

# %% Result
summary <- sprintf("%s on %d genotypes of %s (%s %d, %s %d, %s %d): %s; minor allele frequency %.3f, F = %.3f.",
                   label, as.integer(n), g, genotypes[1], as.integer(r$n_aa), genotypes[2], as.integer(r$n_ab), genotypes[3], as.integer(r$n_bb),
                   cs_fmt_p(p), r$maf, f)
apa <- if (test == "chisq") {
  sprintf("χ²(1, N = %d) = %s, %s, F = %s", as.integer(n), cs_fmt_num(r$chi2), cs_fmt_p(p), cs_fmt_num(f))
} else if (test == "lr") {
  sprintf("G²(1, N = %d) = %s, %s, F = %s", as.integer(n), cs_fmt_num(r$g2), cs_fmt_p(p), cs_fmt_num(f))
} else {
  sprintf("Hardy–Weinberg %s, N = %d, %s, F = %s", label, as.integer(n), cs_fmt_p(p), cs_fmt_num(f))
}
shares <- observed / n
expected_shares <- expected / n
intervals <- lapply(1:3, function(i) cs_prop_ci(observed[i], n, 0.95, "wilson"))
frequencies <- data.frame(genotype = genotypes, observed = as.integer(observed), expected = expected, share = shares,
                          expected_share = expected_shares, resid = (observed - expected) / sqrt(expected), row.names = NULL)
tests <- data.frame(
  test = c("Pearson χ²", "Likelihood ratio G²", "Exact: outcomes no more likely than observed", "Exact: doubled smaller tail", "Exact: mid-p",
           "Exact, one-sided: heterozygote deficit", "Exact, one-sided: heterozygote excess"),
  statistic = c(r$chi2, r$g2, rep(NA_real_, 5)),
  df = c(1, 1, rep(NA_real_, 5)),
  p = c(r$p_chisq, r$p_lr, r$p_exact_probability, r$p_exact_doubled, r$p_exact_midp, r$p_exact_deficit, r$p_exact_excess),
  row.names = NULL
)
count_a <- 2 * r$n_aa + r$n_ab
count_b <- 2 * r$n_bb + r$n_ab
exact <- cs_hwe_exact_table(r$h, r$probs, r$n_ab, count_a, count_b)
notes <- list(
  "The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.",
  "A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart."
)
if (me < 5) notes <- c(list(small), notes)
if (exact$trimmed) {
  notes <- c(notes, list(sprintf("The exact distribution has %d possible heterozygote counts; the table shows the ones nearest the most likely count and the observed one.", length(r$h))))
}
result_values <- list(
  n = n, n_aa = r$n_aa, n_ab = r$n_ab, n_bb = r$n_bb, n_nocall = n_nocall,
  allele_a = tally$allele_a, allele_b = tally$allele_b, label_aa = genotypes[1], label_ab = genotypes[2], label_bb = genotypes[3],
  p_allele_a = r$p_allele_a, p_allele_b = r$p_allele_b, maf = r$maf,
  expected_aa = r$expected_aa, expected_ab = r$expected_ab, expected_bb = r$expected_bb,
  min_expected = me, n_below_5 = r$n_below_5, het_obs = r$het_obs, het_exp = r$het_exp,
  inbreeding_f = f, d_a = r$d_a, direction = r$direction, chi2 = r$chi2, g2 = r$g2, df = r$df,
  p_chisq = r$p_chisq, p_lr = r$p_lr, p_exact = r$p_exact, p_exact_probability = r$p_exact_probability,
  p_exact_doubled = r$p_exact_doubled, p_exact_midp = r$p_exact_midp, p_exact_deficit = r$p_exact_deficit,
  p_exact_excess = r$p_exact_excess, p_observed = r$p_observed, p = p,
  test = test, test_label = label, alternative = alternative, exact_p = exact_p
)
cs_publish(list(
  method = "genetics.hwe",
  methodVersion = "1.0.1",
  title = "Hardy–Weinberg proportions",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "p_allele_a", label = sprintf("Frequency of allele %s", tally$allele_a), value = r$p_allele_a),
    list(key = "maf", label = "Minor allele frequency", value = r$maf),
    list(key = "chi2", label = "Pearson χ²", value = r$chi2),
    list(key = "g2", label = "Likelihood ratio G²", value = r$g2),
    list(key = "df", label = "df", value = r$df),
    list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")
  ),
  tables = list(
    list(key = "frequencies", title = "Observed and expected genotypes",
         columns = list(list(key = "genotype", label = "Genotype", type = "string"), list(key = "observed", label = "Observed", type = "integer"),
                        list(key = "expected", label = "Expected", type = "number"), list(key = "share", label = "Observed share", type = "number"),
                        list(key = "expected_share", label = "Expected share", type = "number"), list(key = "resid", label = "Pearson residual", type = "number")),
         rows = frequencies),
    list(key = "tests", title = "All the tests of these counts",
         columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"),
                        list(key = "df", label = "df", type = "number"), list(key = "p", label = "p", type = "p")),
         rows = tests),
    list(key = "exact_distribution", title = "Exact distribution of the heterozygote count",
         columns = list(list(key = "het", label = genotypes[2], type = "integer"), list(key = "n_aa", label = genotypes[1], type = "integer"),
                        list(key = "n_bb", label = genotypes[3], type = "integer"), list(key = "probability", label = "Probability", type = "number"),
                        list(key = "observed", label = "Observed", type = "string"), list(key = "counted", label = "Counted in p", type = "string")),
         rows = exact$rows)
  ),
  effectSizes = list(list(key = "inbreeding_f", label = "Inbreeding coefficient F", value = f, method = "1 − observed heterozygosity / expected heterozygosity")),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(cs_chart(
    "genotype_shares", "forest", sprintf("Observed vs expected genotype shares of %s", g),
    list(label = cs_col("Genotype", rep(genotypes, 2)), estimate = cs_col("Share", c(shares, expected_shares)),
         low = cs_col("low", c(vapply(intervals, `[`, numeric(1), 1), expected_shares)),
         high = cs_col("high", c(vapply(intervals, `[`, numeric(1), 2), expected_shares)),
         group = cs_col("series", rep(c("observed", "expected"), each = 3))),
    note = "Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares."
  )),
  values = result_values
))
Python

Hardy–Weinberg exact test, N = 20, p = .152, F = 0.44

Frequency of allele A
0.9000
Minor allele frequency
0.1000
Pearson χ²
3.951
Likelihood ratio G²
2.507
df
1
p (exact test)
.152

Effect size

  • Inbreeding coefficient F 0.4444

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Expected counts ≥ 5 — The exact test doesn't use this approximation; the smallest expected count is 0.20.
  • Unrelated people from one population — Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see.
  • Reliable genotype calls — Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it.

Observed and expected genotypes

GenotypeObservedExpectedObserved shareExpected sharePearson residual
AA1716.2000.85000.81000.1988
Aa23.6000.10000.1800−0.8433
aa10.20000.05000.01001.789

All the tests of these counts

TestStatisticdfp
Pearson χ²3.95110.0469
Likelihood ratio G²2.50710.1134
Exact: outcomes no more likely than observed——0.1518
Exact: doubled smaller tail——0.3035
Exact: mid-p——0.0769
Exact, one-sided: heterozygote deficit——0.1518
Exact, one-sided: heterozygote excess——0.9979

Exact distribution of the heterozygote count

AaAAaaProbabilityObservedCounted in p
01820.0021yes
21710.1497yesyes
41600.8482
  • The smallest expected count is 0.20, below 5: the χ² and likelihood-ratio p-values lean on an approximation that is unreliable here; the exact test doesn't use it.
  • The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.
  • A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Hardy–Weinberg proportions (exact, χ², likelihood ratio)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.hwe 1.0.1 · spec a6068417f624166e
# Dataset: hwe_counts (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
import numpy as np
import pandas as pd

import codesplash as cs
from codesplash.stats import hwe as csh  # Hardy–Weinberg tests, Wigginton et al. 2005 (twins of cs_hwe_*)
from codesplash.stats import proportions as csp  # Wilson intervals (twin of cs_prop_ci)

# %% Data
df = pd.read_parquet("tests/parity/fixtures/hwe_counts.parquet", columns=["genotype", "rare"])
n_input = len(df)
df["genotype"] = pd.Categorical(df["genotype"], categories=["AA", "Aa", "aa"])  # stored level order
df = df.dropna(subset=["genotype", "rare"])  # listwise deletion over the analysis columns
df["genotype"] = df["genotype"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
    warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["genotype", "rare"])  # infinite values stop the run (registry/errors.yaml)

# %% Genotype counts
g = "genotype"
counts = df["rare"].to_numpy(dtype=float)  # each row is one genotype with its count
tally = csh.genotype_counts(df[g], counts, column=g)
n_nocall = int(tally["n_nocall"])
if n_nocall:
    warnings.append(f"{n_nocall} genotypes were no-calls and were left out.")
test = "exact"
alternative = "two_sided"
exact_p = "probability"

# %% Tests
r = csh.hwe_test(tally["n_aa"], tally["n_ab"], tally["n_bb"], alternative, exact_p)
n = r["n"]
if test == "chisq":
    p, label = r["p_chisq"], "Pearson χ² test"
elif test == "lr":
    p, label = r["p_lr"], "likelihood-ratio test"
else:
    p, label = r["p_exact"], csh.exact_label(alternative, exact_p)
f = r["inbreeding_f"]
me = r["min_expected"]
genotypes = [tally["label_aa"], tally["label_ab"], tally["label_bb"]]
observed = np.array([r["n_aa"], r["n_ab"], r["n_bb"]], dtype=float)
expected = np.array([r["expected_aa"], r["expected_ab"], r["expected_bb"]])

# %% Assumptions
small = f"The smallest expected count is {me:.2f}, below 5: the χ² and likelihood-ratio p-values lean on an approximation that is unreliable here; the exact test doesn't use it."
if test == "exact":
    status, detail = "info", f"The exact test doesn't use this approximation; the smallest expected count is {me:.2f}."
elif me < 1:
    status, detail = "fail", f"The smallest expected count is {me:.2f} (below 1): the χ² approximation fails here; use the exact test."
elif r["n_below_5"] > 0:
    status, detail = "warn", f"{r['n_below_5']} of 3 expected counts are below 5 (smallest {me:.2f}); prefer the exact test."
else:
    status, detail = "pass", f"Every expected count is at least 5 (smallest {me:.2f})."
if r["direction"] == "deficit":
    quality = "Too few heterozygotes here; allelic dropout and other calling errors often look like this, so check the assay before reading biology into it."
elif r["direction"] == "excess":
    quality = "Too many heterozygotes here; paralogous sequence and other calling errors can look like this, so check the assay before reading biology into it."
else:
    quality = "Calling errors can shift genotype counts; counts alone can't confirm the calls are right."
assumptions = [
    {"key": "expected_counts", "label": "Expected counts ≥ 5", "status": status, "detail": detail},
    {"key": "unrelated", "label": "Unrelated people from one population", "status": "info", "detail": "Not checkable from counts: relatives and mixed ancestry both change how many heterozygotes you see."},
    {"key": "genotype_quality", "label": "Reliable genotype calls", "status": "info", "detail": quality},
]

# %% Result
summary = (f"{label} on {int(n)} genotypes of {g} ({genotypes[0]} {int(r['n_aa'])}, {genotypes[1]} {int(r['n_ab'])}, {genotypes[2]} {int(r['n_bb'])}): "
           f"{cs.fmt_p(p)}; minor allele frequency {r['maf']:.3f}, F = {f:.3f}.")
if test == "chisq":
    apa = f"χ²(1, N = {int(n)}) = {cs.fmt_num(r['chi2'])}, {cs.fmt_p(p)}, F = {cs.fmt_num(f)}"
elif test == "lr":
    apa = f"G²(1, N = {int(n)}) = {cs.fmt_num(r['g2'])}, {cs.fmt_p(p)}, F = {cs.fmt_num(f)}"
else:
    apa = f"Hardy–Weinberg {label}, N = {int(n)}, {cs.fmt_p(p)}, F = {cs.fmt_num(f)}"
shares = observed / n
expected_shares = expected / n
intervals = [csp.prop_ci(observed[i], n, 0.95, "wilson") for i in range(3)]
frequencies = [{"genotype": genotypes[i], "observed": int(observed[i]), "expected": float(expected[i]), "share": float(shares[i]),
                "expected_share": float(expected_shares[i]), "resid": float((observed[i] - expected[i]) / np.sqrt(expected[i]))} for i in range(3)]
tests = [
    {"test": "Pearson χ²", "statistic": r["chi2"], "df": 1, "p": r["p_chisq"]},
    {"test": "Likelihood ratio G²", "statistic": r["g2"], "df": 1, "p": r["p_lr"]},
    {"test": "Exact: outcomes no more likely than observed", "statistic": None, "df": None, "p": r["p_exact_probability"]},
    {"test": "Exact: doubled smaller tail", "statistic": None, "df": None, "p": r["p_exact_doubled"]},
    {"test": "Exact: mid-p", "statistic": None, "df": None, "p": r["p_exact_midp"]},
    {"test": "Exact, one-sided: heterozygote deficit", "statistic": None, "df": None, "p": r["p_exact_deficit"]},
    {"test": "Exact, one-sided: heterozygote excess", "statistic": None, "df": None, "p": r["p_exact_excess"]},
]
count_a, count_b = 2 * r["n_aa"] + r["n_ab"], 2 * r["n_bb"] + r["n_ab"]
exact_rows, trimmed = csh.exact_table(r["h"], r["probs"], r["n_ab"], count_a, count_b)
notes = [
    "The allele frequency comes from these same genotypes, which costs one degree of freedom: 3 classes − 1 − 1 estimated frequency.",
    "A departure can come from genotyping error, mixed ancestry, relatives, non-random mating or selection. The test can't tell them apart.",
]
if me < 5:
    notes.insert(0, small)
if trimmed:
    notes.append(f"The exact distribution has {len(r['h'])} possible heterozygote counts; the table shows the ones nearest the most likely count and the observed one.")
values = {
    "n": n, "n_aa": r["n_aa"], "n_ab": r["n_ab"], "n_bb": r["n_bb"], "n_nocall": n_nocall,
    "allele_a": tally["allele_a"], "allele_b": tally["allele_b"], "label_aa": genotypes[0], "label_ab": genotypes[1], "label_bb": genotypes[2],
    "p_allele_a": r["p_allele_a"], "p_allele_b": r["p_allele_b"], "maf": r["maf"],
    "expected_aa": r["expected_aa"], "expected_ab": r["expected_ab"], "expected_bb": r["expected_bb"],
    "min_expected": me, "n_below_5": r["n_below_5"], "het_obs": r["het_obs"], "het_exp": r["het_exp"],
    "inbreeding_f": f, "d_a": r["d_a"], "direction": r["direction"], "chi2": r["chi2"], "g2": r["g2"], "df": r["df"],
    "p_chisq": r["p_chisq"], "p_lr": r["p_lr"], "p_exact": r["p_exact"], "p_exact_probability": r["p_exact_probability"],
    "p_exact_doubled": r["p_exact_doubled"], "p_exact_midp": r["p_exact_midp"], "p_exact_deficit": r["p_exact_deficit"],
    "p_exact_excess": r["p_exact_excess"], "p_observed": r["p_observed"], "p": p,
    "test": test, "test_label": label, "alternative": alternative, "exact_p": exact_p,
}
cs.publish({
    "method": "genetics.hwe",
    "methodVersion": "1.0.1",
    "title": "Hardy–Weinberg proportions",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": int(n),
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "p_allele_a", "label": f"Frequency of allele {tally['allele_a']}", "value": r["p_allele_a"]},
        {"key": "maf", "label": "Minor allele frequency", "value": r["maf"]},
        {"key": "chi2", "label": "Pearson χ²", "value": r["chi2"]},
        {"key": "g2", "label": "Likelihood ratio G²", "value": r["g2"]},
        {"key": "df", "label": "df", "value": r["df"]},
        {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
    ],
    "tables": [
        {"key": "frequencies", "title": "Observed and expected genotypes",
         "columns": [{"key": "genotype", "label": "Genotype", "type": "string"}, {"key": "observed", "label": "Observed", "type": "integer"},
                     {"key": "expected", "label": "Expected", "type": "number"}, {"key": "share", "label": "Observed share", "type": "number"},
                     {"key": "expected_share", "label": "Expected share", "type": "number"}, {"key": "resid", "label": "Pearson residual", "type": "number"}],
         "rows": frequencies},
        {"key": "tests", "title": "All the tests of these counts",
         "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"},
                     {"key": "df", "label": "df", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
         "rows": tests},
        {"key": "exact_distribution", "title": "Exact distribution of the heterozygote count",
         "columns": [{"key": "het", "label": genotypes[1], "type": "integer"}, {"key": "n_aa", "label": genotypes[0], "type": "integer"},
                     {"key": "n_bb", "label": genotypes[2], "type": "integer"}, {"key": "probability", "label": "Probability", "type": "number"},
                     {"key": "observed", "label": "Observed", "type": "string"}, {"key": "counted", "label": "Counted in p", "type": "string"}],
         "rows": exact_rows},
    ],
    "effectSizes": [{"key": "inbreeding_f", "label": "Inbreeding coefficient F", "value": f, "method": "1 − observed heterozygosity / expected heterozygosity"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [cs.chart(
        "genotype_shares", "forest", f"Observed vs expected genotype shares of {g}",
        {"label": cs.col("Genotype", genotypes * 2),
         "estimate": cs.col("Share", [float(s) for s in shares] + [float(s) for s in expected_shares]),
         "low": cs.col("low", [c[0] for c in intervals] + [float(s) for s in expected_shares]),
         "high": cs.col("high", [c[1] for c in intervals] + [float(s) for s in expected_shares]),
         "group": cs.col("series", ["observed"] * 3 + ["expected"] * 3)},
        note="Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares.",
    )],
    "values": values,
})

Other two-sided conventions double the smaller tail (0.304) or use mid-p (0.077). So report which one you used. The card lists all of them, and notes when an expected count is below 5.

08

Why might counts depart?

Reflect

A marker shows a strong heterozygote deficit among your controls. Before you think about biology, list what else could do this.

Think about the lab, who was sampled and how they are related. Which would you check first, and how?

09

Check your understanding

Checkpoint

Check yourself

A sample has 49 AAAA, 42 AaAa and 9 aaaa. What is p^\hat p, the frequency of allele AA?

Show the answer

Answer: 0.7

(2×49+42)/200=140/200=0.7(2 \times 49 + 42)/200 = 140/200 = 0.7. These counts also match p2p^2, 2pq2pq and q2q^2 exactly.

Check yourself

Compute X2X^2 for 45 AAAA, 30 AaAa, 25 aaaa with expected counts 36, 48, 16.

Show the answer

Answer: 14.0625

81/36+324/48+81/16=2.25+6.75+5.0625=14.062581/36 + 324/48 + 81/16 = 2.25 + 6.75 + 5.0625 = 14.0625.

Check yourself

When should you prefer the exact test over chi-square?

Show the answer

Answer: b

The chi-square approximation fails when expected cells are small. Say which exact convention you used, because they can differ.

Check yourself

A strong departure from Hardy–Weinberg proportions shows what?

Show the answer

Answer: c

The test can't tell these apart. Pipelines often treat a strong departure in controls as a genotyping problem first.

10

Run it in Analyze

In the app

Pick the Genotype column. It can hold AA/Aa/aa, A/G, 0|1 or doses of 0, 1 or 2, one row per person. If each row is a genotype with its count, add that column under Counts (optional). Test switches between the exact test, Pearson χ² and the likelihood ratio. With the exact test, choose the Alternative hypothesis and the Exact p-value convention.

The script here needs no extra package. We checked its results against the HardyWeinberg package.

Python
import math
from scipy import stats

def hwe(aa, ab, bb):
    n = aa + ab + bb
    p = (2 * aa + ab) / (2 * n)
    obs = [aa, ab, bb]
    exp = [n * p**2, 2 * n * p * (1 - p), n * (1 - p) ** 2]
    x2 = sum((o - e) ** 2 / e for o, e in zip(obs, exp))
    g2 = 2 * sum(o * math.log(o / e) for o, e in zip(obs, exp) if o > 0)

    a = min(2 * aa + ab, 2 * bb + ab)
    def log_p(h):
        return (h * math.log(2) - math.lgamma(h + 1)
                - math.lgamma((a - h) / 2 + 1)
                - math.lgamma((2 * n - a - h) / 2 + 1))
    probs = {h: math.exp(log_p(h)) for h in range(a % 2, a + 1, 2)}
    total = sum(probs.values())
    observed = probs[ab]
    exact = sum(v for v in probs.values() if v <= observed * (1 + 1e-9)) / total
    return x2, stats.chi2.sf(x2, 1), g2, stats.chi2.sf(g2, 1), exact

print(hwe(45, 30, 25))
print(hwe(17, 2, 1))
R
hwe <- function(aa, ab, bb) {
  n <- aa + ab + bb
  p <- (2 * aa + ab) / (2 * n)
  obs <- c(aa, ab, bb)
  exp <- c(n * p^2, 2 * n * p * (1 - p), n * (1 - p)^2)
  x2 <- sum((obs - exp)^2 / exp)
  g2 <- 2 * sum((obs * log(obs / exp))[obs > 0])

  a <- min(2 * aa + ab, 2 * bb + ab)
  h <- seq(a %% 2, a, by = 2)
  probs <- exp(h * log(2) - lgamma(h + 1) -
                 lgamma((a - h) / 2 + 1) - lgamma((2 * n - a - h) / 2 + 1))
  observed <- probs[h == ab]
  exact <- sum(probs[probs <= observed * (1 + 1e-9)]) / sum(probs)
  c(x2, pchisq(x2, 1, lower.tail = FALSE), g2, pchisq(g2, 1, lower.tail = FALSE), exact)
}

hwe(45, 30, 25)
hwe(17, 2, 1)
11

Recap

Recap
  • Allele frequency predicts genotype counts under Hardy–Weinberg proportions.
  • Chi-square and likelihood-ratio tests agree when cells are well filled; use the exact test when an allele is rare, and say which convention you used.
  • A departure has many possible causes. Check genotyping, ancestry and relatedness first.
  • In Analyze, one card gives all three tests, the allele frequency and FF.

Concepts in this lesson