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.
What runs in CodeSplash
- STAT295Hardy–Weinberg chi square test Runs in CodeSplash
- STAT296Hardy–Weinberg exact test Runs in CodeSplash
- STAT297Hardy–Weinberg likelihood ratio test Runs in CodeSplash
- Hardy–Weinberg proportions (exact, χ², likelihood ratio) Verified in Python and R
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
What equilibrium predicts
ReadEach person carries two copies of a gene site. If one allele has frequency 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:
You estimate from the genotypes themselves, then ask whether the counts match.
Try the guide's counts
PredictPredict first
The guide's example has 100 people: 36 , 48 and 16 . Work out , then the expected counts.
How do the observed counts compare?
Reveal
Exactly at equilibrium. = 0.6, so the expected counts are 36, 48 and 16. Both and are 0, and the exact p-value is 1. That example shows how to call the tests; it can't show a departure.
Now a real departure
ReadKeep but move people out of the middle: 45 , 30 , 25 . The expected counts are still 36, 48 and 16.
There is one degree of freedom: three classes, minus one, minus the estimated . That gives p < .001. The sample has far too few heterozygotes.
χ²(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 shares with 95% Wilson intervals next to the Hardy–Weinberg shares.
View data
| Share | series | high | Genotype | low |
|---|---|---|---|---|
| 0.4500 | observed | 0.5476 | AA | 0.3561 |
| 0.3000 | observed | 0.3958 | Aa | 0.2189 |
| 0.2500 | observed | 0.3430 | aa | 0.1755 |
| 0.3600 | expected | 0.3600 | AA | 0.3600 |
| 0.4800 | expected | 0.4800 | Aa | 0.4800 |
| 0.1600 | expected | 0.1600 | aa | 0.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
| Genotype | Observed | Expected | Observed share | Expected share | Pearson residual |
|---|---|---|---|---|---|
| AA | 45 | 36 | 0.4500 | 0.3600 | 1.500 |
| Aa | 30 | 48 | 0.3000 | 0.4800 | −2.598 |
| aa | 25 | 16 | 0.2500 | 0.1600 | 2.250 |
All the tests of these counts
| Test | Statistic | df | p |
|---|---|---|---|
| Pearson χ² | 14.063 | 1 | 0.0002 |
| Likelihood ratio G² | 14.197 | 1 | 0.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
| Aa | AA | aa | Probability | Observed | Counted in p |
|---|---|---|---|---|---|
| 28 | 46 | 26 | 2.248e-5 | yes | |
| 30 | 45 | 25 | 0.0001 | yes | yes |
| 32 | 44 | 24 | 0.0006 | ||
| 34 | 43 | 23 | 0.0021 | ||
| 36 | 42 | 22 | 0.0066 | ||
| 38 | 41 | 21 | 0.0174 | ||
| 40 | 40 | 20 | 0.0385 | ||
| 42 | 39 | 19 | 0.0715 | ||
| 44 | 38 | 18 | 0.1120 | ||
| 46 | 37 | 17 | 0.1480 | ||
| 48 | 36 | 16 | 0.1650 | ||
| 50 | 35 | 15 | 0.1552 | ||
| 52 | 34 | 14 | 0.1229 | ||
| 54 | 33 | 13 | 0.0818 | ||
| 56 | 32 | 12 | 0.0456 | ||
| 58 | 31 | 11 | 0.0212 | ||
| 60 | 30 | 10 | 0.0082 | ||
| 62 | 29 | 9 | 0.0026 | ||
| 64 | 28 | 8 | 0.0007 | ||
| 66 | 27 | 7 | 0.0001 | ||
| 68 | 26 | 6 | 2.322e-5 | yes |
- 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
))
χ²(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
| Genotype | Observed | Expected | Observed share | Expected share | Pearson residual |
|---|---|---|---|---|---|
| AA | 45 | 36 | 0.4500 | 0.3600 | 1.500 |
| Aa | 30 | 48 | 0.3000 | 0.4800 | −2.598 |
| aa | 25 | 16 | 0.2500 | 0.1600 | 2.250 |
All the tests of these counts
| Test | Statistic | df | p |
|---|---|---|---|
| Pearson χ² | 14.063 | 1 | 0.0002 |
| Likelihood ratio G² | 14.197 | 1 | 0.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
| Aa | AA | aa | Probability | Observed | Counted in p |
|---|---|---|---|---|---|
| 28 | 46 | 26 | 2.248e-5 | yes | |
| 30 | 45 | 25 | 0.0001 | yes | yes |
| 32 | 44 | 24 | 0.0006 | ||
| 34 | 43 | 23 | 0.0021 | ||
| 36 | 42 | 22 | 0.0066 | ||
| 38 | 41 | 21 | 0.0174 | ||
| 40 | 40 | 20 | 0.0385 | ||
| 42 | 39 | 19 | 0.0715 | ||
| 44 | 38 | 18 | 0.1120 | ||
| 46 | 37 | 17 | 0.1480 | ||
| 48 | 36 | 16 | 0.1650 | ||
| 50 | 35 | 15 | 0.1552 | ||
| 52 | 34 | 14 | 0.1229 | ||
| 54 | 33 | 13 | 0.0818 | ||
| 56 | 32 | 12 | 0.0456 | ||
| 58 | 31 | 11 | 0.0212 | ||
| 60 | 30 | 10 | 0.0082 | ||
| 62 | 29 | 9 | 0.0026 | ||
| 64 | 28 | 8 | 0.0007 | ||
| 66 | 27 | 7 | 0.0001 | ||
| 68 | 26 | 6 | 2.322e-5 | yes |
- 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. = 0.375, which is : the share of the expected heterozygotes that are missing. Despite the name, it doesn't prove inbreeding.
Move the departure
ExploreChange 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?
0 is Hardy–Weinberg equilibrium.
Your data
Edit the countsDashed lines: the counts H₀ expects (equal shares).
If H₀ were true
- The reference: how χ² varies across samples when H₀ is true.
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .004).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- allele frequency estimated from the genotypes
- 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 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)?
0 is Hardy–Weinberg equilibrium.
Your data
Edit the countsDashed lines: the counts H₀ expects (equal shares).
If H₀ were true
- The reference: how G varies across samples when H₀ is true.
- Your statistic, from the data above.
- The p-value: the area at least as extreme as yours (p = .004).
- The hatched rejection region at α = .050: statistics landing here reject H₀.
The formula
With your numbers
- 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 H₀.
The likelihood-ratio test
ReadFor the same counts, = 14.20, close to = 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.
A rare allele
PredictPredict first
Now 20 people: 17 , 2 , 1 . So , and the expected count is only .
What do you expect from the chi-square and exact tests?
Reveal
Chi-square gives = 3.95, p = .047. The likelihood-ratio test gives p = .113. The exact test gives p = .152. One person with is too little to carry that much weight, and the approximation overstates it.
The exact test
ReadCondition on the allele count , here . Then the only thing that varies is the number of heterozygotes :
| Genotypes (, , ) | Probability | |
|---|---|---|
| 4 | 16, 4, 0 | |
| 2 | 17, 2, 1 | |
| 0 | 18, 0, 2 |
Add every outcome no more likely than yours: .
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 shares with 95% Wilson intervals next to the Hardy–Weinberg shares.
View data
| Share | series | high | Genotype | low |
|---|---|---|---|---|
| 0.8500 | observed | 0.9476 | AA | 0.6396 |
| 0.1000 | observed | 0.3010 | Aa | 0.0279 |
| 0.0500 | observed | 0.2361 | aa | 0.0089 |
| 0.8100 | expected | 0.8100 | AA | 0.8100 |
| 0.1800 | expected | 0.1800 | Aa | 0.1800 |
| 0.0100 | expected | 0.0100 | aa | 0.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
| Genotype | Observed | Expected | Observed share | Expected share | Pearson residual |
|---|---|---|---|---|---|
| AA | 17 | 16.200 | 0.8500 | 0.8100 | 0.1988 |
| Aa | 2 | 3.600 | 0.1000 | 0.1800 | −0.8433 |
| aa | 1 | 0.2000 | 0.0500 | 0.0100 | 1.789 |
All the tests of these counts
| Test | Statistic | df | p |
|---|---|---|---|
| Pearson χ² | 3.951 | 1 | 0.0469 |
| Likelihood ratio G² | 2.507 | 1 | 0.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
| Aa | AA | aa | Probability | Observed | Counted in p |
|---|---|---|---|---|---|
| 0 | 18 | 2 | 0.0021 | yes | |
| 2 | 17 | 1 | 0.1497 | yes | yes |
| 4 | 16 | 0 | 0.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
))
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
| Genotype | Observed | Expected | Observed share | Expected share | Pearson residual |
|---|---|---|---|---|---|
| AA | 17 | 16.200 | 0.8500 | 0.8100 | 0.1988 |
| Aa | 2 | 3.600 | 0.1000 | 0.1800 | −0.8433 |
| aa | 1 | 0.2000 | 0.0500 | 0.0100 | 1.789 |
All the tests of these counts
| Test | Statistic | df | p |
|---|---|---|---|
| Pearson χ² | 3.951 | 1 | 0.0469 |
| Likelihood ratio G² | 2.507 | 1 | 0.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
| Aa | AA | aa | Probability | Observed | Counted in p |
|---|---|---|---|---|---|
| 0 | 18 | 2 | 0.0021 | yes | |
| 2 | 17 | 1 | 0.1497 | yes | yes |
| 4 | 16 | 0 | 0.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.
Why might counts depart?
ReflectA 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?
Check your understanding
CheckpointCheck yourself
A sample has 49 , 42 and 9 . What is , the frequency of allele ?
Show the answer
Answer: 0.7
. These counts also match , and exactly.
Check yourself
Compute for 45 , 30 , 25 with expected counts 36, 48, 16.
Show the answer
Answer: 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.
Run it in Analyze
In the appPick 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.
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))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)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 .
Concepts in this lesson