EProportions & counts · genetics.hwe
Hardy–Weinberg proportions (exact, χ², likelihood ratio)
Do the genotype counts at one marker match what random mating predicts?
Compares genotype counts at one biallelic marker with the shares p², 2p(1−p) and (1−p)² expected from the allele frequency, using the exact test (Wigginton et al. 2005; no simulation), Pearson's χ² or the likelihood-ratio test. Reports the allele frequencies, expected counts, the inbreeding coefficient F and every exact convention, and notes when expected counts are too small for the approximations.
A real result
Example “Guide exact”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Hardy–Weinberg exact test, N = 100, p = 1.000, F = 0.00
- Frequency of allele A
- 0.6000
- Minor allele frequency
- 0.4000
- Pearson χ²
- 0
- Likelihood ratio G²
- 0
- df
- 1
- p (exact test)
- 1.000
Effect size
- Inbreeding coefficient F 0
Plots
Observed shares with 95% Wilson intervals next to the Hardy–Weinberg shares.
View data
| Share | series | high | Genotype | low |
|---|---|---|---|---|
| 0.3600 | observed | 0.4576 | AA | 0.2727 |
| 0.4800 | observed | 0.5768 | Aa | 0.3846 |
| 0.1600 | observed | 0.2442 | aa | 0.1010 |
| 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 — The exact test doesn't use this approximation; the smallest expected count is 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 — Calling errors can shift genotype counts; counts alone can't confirm the calls are right.
Observed and expected genotypes
| Genotype | Observed | Expected | Observed share | Expected share | Pearson residual |
|---|---|---|---|---|---|
| AA | 36 | 36 | 0.3600 | 0.3600 | 0 |
| Aa | 48 | 48 | 0.4800 | 0.4800 | 0 |
| aa | 16 | 16 | 0.1600 | 0.1600 | 0 |
All the tests of these counts
| Test | Statistic | df | p |
|---|---|---|---|
| Pearson χ² | 0 | 1 | 1 |
| Likelihood ratio G² | 0 | 1 | 1 |
| Exact: outcomes no more likely than observed | — | — | 1 |
| Exact: doubled smaller tail | — | — | 1 |
| Exact: mid-p | — | — | 0.9175 |
| Exact, one-sided: heterozygote deficit | — | — | 0.5618 |
| Exact, one-sided: heterozygote excess | — | — | 0.6032 |
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 | |
| 32 | 44 | 24 | 0.0006 | yes | |
| 34 | 43 | 23 | 0.0021 | yes | |
| 36 | 42 | 22 | 0.0066 | yes | |
| 38 | 41 | 21 | 0.0174 | yes | |
| 40 | 40 | 20 | 0.0385 | yes | |
| 42 | 39 | 19 | 0.0715 | yes | |
| 44 | 38 | 18 | 0.1120 | yes | |
| 46 | 37 | 17 | 0.1480 | yes | |
| 48 | 36 | 16 | 0.1650 | yes | yes |
| 50 | 35 | 15 | 0.1552 | yes | |
| 52 | 34 | 14 | 0.1229 | yes | |
| 54 | 33 | 13 | 0.0818 | yes | |
| 56 | 32 | 12 | 0.0456 | yes | |
| 58 | 31 | 11 | 0.0212 | yes | |
| 60 | 30 | 10 | 0.0082 | yes | |
| 62 | 29 | 9 | 0.0026 | yes | |
| 64 | 28 | 8 | 0.0007 | yes | |
| 66 | 27 | 7 | 0.0001 | yes | |
| 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.
Hardy–Weinberg exact test, N = 100, p = 1.000, F = 0.00
- Frequency of allele A
- 0.6000
- Minor allele frequency
- 0.4000
- Pearson χ²
- 0
- Likelihood ratio G²
- 0
- df
- 1
- p (exact test)
- 1.000
Effect size
- Inbreeding coefficient F 0
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 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 — Calling errors can shift genotype counts; counts alone can't confirm the calls are right.
Observed and expected genotypes
| Genotype | Observed | Expected | Observed share | Expected share | Pearson residual |
|---|---|---|---|---|---|
| AA | 36 | 36 | 0.3600 | 0.3600 | 0 |
| Aa | 48 | 48 | 0.4800 | 0.4800 | 0 |
| aa | 16 | 16 | 0.1600 | 0.1600 | 0 |
All the tests of these counts
| Test | Statistic | df | p |
|---|---|---|---|
| Pearson χ² | 0 | 1 | 1 |
| Likelihood ratio G² | 0 | 1 | 1 |
| Exact: outcomes no more likely than observed | — | — | 1 |
| Exact: doubled smaller tail | — | — | 1 |
| Exact: mid-p | — | — | 0.9175 |
| Exact, one-sided: heterozygote deficit | — | — | 0.5618 |
| Exact, one-sided: heterozygote excess | — | — | 0.6032 |
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 | |
| 32 | 44 | 24 | 0.0006 | yes | |
| 34 | 43 | 23 | 0.0021 | yes | |
| 36 | 42 | 22 | 0.0066 | yes | |
| 38 | 41 | 21 | 0.0174 | yes | |
| 40 | 40 | 20 | 0.0385 | yes | |
| 42 | 39 | 19 | 0.0715 | yes | |
| 44 | 38 | 18 | 0.1120 | yes | |
| 46 | 37 | 17 | 0.1480 | yes | |
| 48 | 36 | 16 | 0.1650 | yes | yes |
| 50 | 35 | 15 | 0.1552 | yes | |
| 52 | 34 | 14 | 0.1229 | yes | |
| 54 | 33 | 13 | 0.0818 | yes | |
| 56 | 32 | 12 | 0.0456 | yes | |
| 58 | 31 | 11 | 0.0212 | yes | |
| 60 | 30 | 10 | 0.0082 | yes | |
| 62 | 29 | 9 | 0.0026 | yes | |
| 64 | 28 | 8 | 0.0007 | yes | |
| 66 | 27 | 7 | 0.0001 | yes | |
| 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.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Guide chisqhwe_counts · count: guide · genotype: genotype
- Guide exacthwe_counts · count: guide · genotype: genotype
- Guide lrhwe_counts · count: guide · genotype: genotype
- Departure chisqhwe_counts · count: departure · genotype: genotype
- Departure lrhwe_counts · count: departure · genotype: genotype
- Departure exacthwe_counts · count: departure · genotype: genotype
- Rare chisqhwe_counts · count: rare · genotype: genotype
- Rare lrhwe_counts · count: rare · genotype: genotype
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Expected counts ≥ 5? otherwise exact tests · Statistics Guide · E — Compare proportions / frequencies
- Goodness of fit · Statistics Guide · E — Compare proportions / frequencies
What you need
- Genotypecategorical / numeric · 1 column · 1–24 levels
- One marker, two alleles: AA/Aa/aa, A/G, 0|1, or a dose of 0, 1 or 2. Order doesn't matter (A/G = G/A); ./. is a no-call.
- Counts (optional)numeric · 0–1 column
- Use when each row is a genotype with its count. Without it, each row is one person.
Choices you make
hypothesis
- Testdefault exact
The exact test is valid at any sample size. χ² and the likelihood ratio rely on large expected counts.
- Exact test(default) — Sums the exact probabilities of the possible heterozygote counts; no simulation, safe for rare alleles.
- Pearson χ² — Observed against expected counts on 1 df; fine when every expected count is at least 5.
- Likelihood ratio (G²) — Twice the log-likelihood ratio on 1 df; agrees with χ² when cells are well filled.
- Alternative hypothesisdefault two_sided
Decide the direction before looking at the data. A deficit is what mixed ancestry and dropout usually produce.
- Any departure(default) — Too few or too many heterozygotes.
- Heterozygote deficit — One-sided: too few heterozygotes, as with inbreeding, mixed ancestry or allelic dropout.
- Heterozygote excess — One-sided: too many heterozygotes, as with paralogous sequence or some selection.
- Exact p-valuedefault probability
Exact conventions can disagree, so report the one you used.
- Outcomes no more likely(default) — Adds every outcome as likely as or less likely than the observed one (Wigginton et al. 2005).
- Doubled smaller tail — Twice the smaller one-sided p, capped at 1.
- Mid-p — Counts only half the observed outcome: less conservative, but no longer guaranteed to hold its level.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Expected counts ≥ 5
χ² and the likelihood ratio lean on a large-sample approximation. The exact test doesn't.
- If violated → Exact test — The exact test uses the conditional distribution of the heterozygote count, so small expected counts don't matter.
Unrelated people from one population
Relatives and mixed ancestry change the heterozygote count, and neither shows up in the counts alone.
Reliable genotype calls
Calling errors such as allelic dropout can create a departure, so check the assay first.
What it reports
- Tests: Fit to Hardy–Weinberg proportions
- n
- How many independent units the analysis used; it sets precision and power.
- n_aa
- The pair of alleles a person carries at one site. Two copies of one allele make a homozygote; two different alleles, a heterozygote.
- n_ab
- The pair of alleles a person carries at one site. Two copies of one allele make a homozygote; two different alleles, a heterozygote.
- n_bb
- The pair of alleles a person carries at one site. Two copies of one allele make a homozygote; two different alleles, a heterozygote.
- n_nocall
- A genotype the assay couldn't read, often written ./. or NN. The test leaves it out and reports how many there were.
- allele_a
- The share of all gene copies at a site that carry a given allele.
- allele_b
- The share of all gene copies at a site that carry a given allele.
- label_aa
- The pair of alleles a person carries at one site. Two copies of one allele make a homozygote; two different alleles, a heterozygote.
- label_ab
- The pair of alleles a person carries at one site. Two copies of one allele make a homozygote; two different alleles, a heterozygote.
- label_bb
- The pair of alleles a person carries at one site. Two copies of one allele make a homozygote; two different alleles, a heterozygote.
- p_allele_a
- The share of all gene copies at a site that carry a given allele.
- p_allele_b
- The share of all gene copies at a site that carry a given allele.
- maf
- The share of all gene copies at a site that carry a given allele.
- expected_aa
- The counts Hardy–Weinberg proportions predict from the estimated allele frequency, np², 2np(1−p) and n(1−p)².
- expected_ab
- The counts Hardy–Weinberg proportions predict from the estimated allele frequency, np², 2np(1−p) and n(1−p)².
- expected_bb
- The counts Hardy–Weinberg proportions predict from the estimated allele frequency, np², 2np(1−p) and n(1−p)².
- min_expected
- The counts a contingency table would have if the variables were independent; χ² needs them not too small.
- n_below_5
- The counts Hardy–Weinberg proportions predict from the estimated allele frequency, np², 2np(1−p) and n(1−p)².
- het_obs
- The share of people carrying two different alleles at a site, as observed or as Hardy–Weinberg proportions predict.
- het_exp
- The share of people carrying two different alleles at a site, as observed or as Hardy–Weinberg proportions predict.
- inbreeding_f
- F = 1 − observed / expected heterozygosity. Positive means too few heterozygotes; negative means too many.
- d_a
- How far the AA share sits from p², D = P(AA) − p². It is 0 at Hardy–Weinberg proportions.
- direction
- Fewer heterozygotes than Hardy–Weinberg proportions predict. An excess is the opposite.
- chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- g2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- df
- How much independent information is left to estimate variability after fitting the model.
- p_chisq
- Compare observed with expected genotype counts on χ² with 1 df. Both rely on large expected counts.
- p_lr
- Compare observed with expected genotype counts on χ² with 1 df. Both rely on large expected counts.
- p_exact
- Gets its p-value from the exact distribution of the heterozygote count given the allele counts, with no simulation or approximation.
- p_exact_probability
- Gets its p-value from the exact distribution of the heterozygote count given the allele counts, with no simulation or approximation.
- p_exact_doubled
- A two-sided p-value made by doubling the smaller one-sided p, capped at 1.
- p_exact_midp
- An exact p-value that counts only half the observed outcome's probability. Less conservative, but its level is no longer guaranteed.
- p_exact_deficit
- Fewer heterozygotes than Hardy–Weinberg proportions predict. An excess is the opposite.
- p_exact_excess
- Fewer heterozygotes than Hardy–Weinberg proportions predict. An excess is the opposite.
- p_observed
- Gets its p-value from the exact distribution of the heterozygote count given the allele counts, with no simulation or approximation.
- p
- How surprising your data would be if the null hypothesis were true, as a probability.
- test
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- test_label
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- alternative
- Fewer heterozygotes than Hardy–Weinberg proportions predict. An excess is the opposite.
- exact_p
- Gets its p-value from the exact distribution of the heterozygote count given the allele counts, with no simulation or approximation.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-10). Python uses pandas, numpy, scipy, codesplash; R uses stats, nanoparquet, codesplashr.
The exact script CodeSplash ran for example “Guide exact” · 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 7b8c9ed5243ae3ed
# 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", "guide"])
n_input = len(df)
df["genotype"] = pd.Categorical(df["genotype"], categories=["AA", "Aa", "aa"]) # stored level order
df = df.dropna(subset=["genotype", "guide"]) # 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", "guide"]) # infinite values stop the run (registry/errors.yaml)
# %% Genotype counts
g = "genotype"
counts = df["guide"].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,
})
The exact script CodeSplash ran for example “Guide exact” · 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 7b8c9ed5243ae3ed
# 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", "guide")))
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", "guide")]), , 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", "guide")) # infinite values stop the run (registry/errors.yaml)
# %% Genotype counts
g <- "genotype"
counts <- as.numeric(df[["guide"]]) # 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
))
Sources
- Wigginton, J. E., Cutler, D. J., & Abecasis, G. R. (2005). A note on exact tests of Hardy–Weinberg equilibrium. American Journal of Human Genetics, 76, 887–893.
- Haldane, J. B. S. (1954). An exact test for randomness of mating. Journal of Genetics, 52, 631–635.
- Emigh, T. H. (1980). A comparison of tests for Hardy–Weinberg equilibrium. Biometrics, 36, 627–642.
- Weir, B. S. (1996). Genetic Data Analysis II. Sinauer.
- Engels, W. R. (2009). Exact tests for Hardy–Weinberg proportions. Genetics, 183, 1431–1441.
- Graffelman, J., & Moreno, V. (2013). The mid p-value in exact tests for Hardy–Weinberg equilibrium. Statistical Applications in Genetics and Molecular Biology, 12, 433–448.
From the CodeSplash method registry · genetics.hwe v1.0.1.