EGenetics · genetics.fst
Population differentiation (F_ST)
How different are the allele frequencies of these populations?
Estimates F_ST, the share of genetic variance that lies between populations, with Weir and Cockerham's (1984) θ, which corrects for sample size and uses observed heterozygosity, or Hudson's estimator for two populations (Bhatia et al. 2013). Markers are combined as a ratio of sums, not an average of ratios. A permutation test shuffles people between populations, and pairwise F_ST compares each pair. Research use only.
A real result
Example “Wc perm”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
F_ST (Weir & Cockerham) = 0.039, 3 populations, 16 markers, p = .005
- F_ST (Weir & Cockerham)
- 0.0385
- Informative markers
- 16
- p (permutation)
- .005
Assumptions
- Random mating within populations — Not checkable here: check Hardy–Weinberg proportions within each population.
- Markers not chosen for differences — 16 informative markers; markers chosen because they differ overstate F_ST.
- Enough people per population — Smallest population: 100 people.
Populations
| Population | People | Mean counted-allele frequency |
|---|---|---|
| east | 100 | 0.2770 |
| north | 100 | 0.2597 |
| south | 100 | 0.2193 |
F_ST per marker
| Marker | Counted allele | F_ST |
|---|---|---|
| v09 | B | 0.0189 |
| v10 | B | 0.0730 |
| v11 | B | 2.612e-5 |
| v12 | B | 0.0441 |
| v13 | B | 0.1059 |
| v14 | B | 0.0597 |
| v15 | B | −0.0038 |
| v16 | B | 0.0022 |
| v17 | B | 0.1547 |
| v18 | B | 0.0339 |
| v19 | B | 0.0024 |
| v20 | B | 0.0246 |
| v21 | B | 0.0172 |
| v22 | B | 0.0218 |
| v23 | B | 0.0157 |
| v24 | B | 0.0151 |
Pairwise F_ST (Weir & Cockerham)
| Population A | Population B | F_ST |
|---|---|---|
| east | north | 0.0424 |
| east | south | 0.0331 |
| north | south | 0.0397 |
- Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
- Markers are combined as a ratio of summed variance components, which weights informative markers more than an average of per-marker F_ST would.
- Wright's rough guide: below 0.05 little differentiation, 0.05–0.15 moderate, 0.15–0.25 great, above 0.25 very great.
F_ST (Weir & Cockerham) = 0.039, 3 populations, 16 markers, p = .005
- F_ST (Weir & Cockerham)
- 0.0385
- Informative markers
- 16
- p (permutation)
- .005
Assumptions
- Random mating within populations — Not checkable here: check Hardy–Weinberg proportions within each population.
- Markers not chosen for differences — 16 informative markers; markers chosen because they differ overstate F_ST.
- Enough people per population — Smallest population: 100 people.
Populations
| Population | People | Mean counted-allele frequency |
|---|---|---|
| east | 100 | 0.2770 |
| north | 100 | 0.2597 |
| south | 100 | 0.2193 |
F_ST per marker
| Marker | Counted allele | F_ST |
|---|---|---|
| v09 | B | 0.0189 |
| v10 | B | 0.0730 |
| v11 | B | 2.612e-5 |
| v12 | B | 0.0441 |
| v13 | B | 0.1059 |
| v14 | B | 0.0597 |
| v15 | B | −0.0038 |
| v16 | B | 0.0022 |
| v17 | B | 0.1547 |
| v18 | B | 0.0339 |
| v19 | B | 0.0024 |
| v20 | B | 0.0246 |
| v21 | B | 0.0172 |
| v22 | B | 0.0218 |
| v23 | B | 0.0157 |
| v24 | B | 0.0151 |
Pairwise F_ST (Weir & Cockerham)
| Population A | Population B | F_ST |
|---|---|---|
| east | north | 0.0424 |
| east | south | 0.0331 |
| north | south | 0.0397 |
- Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
- Markers are combined as a ratio of summed variance components, which weights informative markers more than an average of per-marker F_ST would.
- Wright's rough guide: below 0.05 little differentiation, 0.05–0.15 moderate, 0.15–0.25 great, above 0.25 very great.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Wc permge_people · population: population · variants: v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
- Wc all estimatege_people · population: population · variants: v01, v02, v03, v04, v05, v06, v07, v08, v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
- Hudson regionge_people · population: region · variants: v09, v12, v13, v14, v15, v16, v17, v18
- Wc vcf callsge_people · population: population · variants: gt1, gt2, gt3, gt4
- Degenerate all nage_people · population: population · variants: v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
- Degenerate single levelge_people · population: population · variants: v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
- Degenerate one group leftge_people · population: population · variants: v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
- Degenerate infge_people · population: population · variants: v09, v10, v11, v12, v13, v14, v15, v16, v17, v18, v19, v20, v21, v22, v23, v24
In the guides
Where it sits in the decision guides
- More than two groups: χ² independence · Statistics Guide · E — Compare proportions / frequencies
What you need
- Populationcategorical · 1 column · 2–50 levels
- Which population each person belongs to; one row per person.
- Markersnumeric / categorical · 1–10000 columns
- One column per marker: doses 0/1/2, VCF calls (0/1, 1|1, ./.) or two alleles. No-calls are skipped per marker.
Choices you make
statistics
- Estimatordefault weir_cockerham
Both correct for sample size; report which one you used, because their values differ.
- Weir & Cockerham θ(default) — Any number of populations, weighted by sample size, with observed heterozygosity (1984).
- Hudson — Two populations; doesn't depend on their sample sizes' ratio (Bhatia et al. 2013).
- Pairwise F_STdefault on
Also estimate F_ST for every pair of populations (with three or more).
hypothesis
- Testdefault permutation
Whether to test F_ST = 0 by shuffling people between populations.
- Permutation test(default) — Shuffles population labels; p = share of shuffles with F_ST at least as large.
- No test — Estimate only.
- Permutationsdefault 999
Shuffles of the labels; the smallest possible p is 1/(B + 1).
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.
Random mating within populations
θ treats each population as one mating unit; hidden structure inside one inflates F_ST.
Markers not chosen for differences
Markers picked because they differ (ancestry-informative) overstate genome-wide F_ST.
Enough people per population
Small samples make per-marker F_ST noisy; combine many markers.
What it reports
- Tests: The populations share allele frequencies
- n
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- n_pops
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- n_variants
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- n_used
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- fst
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- p
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- n_perm
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- test
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- estimator
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- estimator_label
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- pop_sizes
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- fst_marker
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- pair_fst
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
- pair_labels
- The share of genetic variance that lies between populations; 0 means identical allele frequencies.
Python and R
Python and R agree to 10 decimals (relative tolerance 1e-9). Python uses pandas, numpy, codesplash; R uses stats, nanoparquet, codesplashr.
Default traps between the two languages
- Both engines shuffle labels with the shared Wichmann–Hill stream, so permutation p-values match exactly.
The exact script CodeSplash ran for example “Wc perm” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Population differentiation (F_ST)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.fst 1.0.1 · spec 31353921bc7ab1dd
# Dataset: ge_people (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import math
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.stats import genetics as gen # Weir & Cockerham θ, Hudson F_ST, permutations (twins of cs_gen_*)
# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df = pd.read_parquet("tests/parity/fixtures/ge_people.parquet", columns=["population", "v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."
# %% People and markers
pop_col = "population"
variants = ["v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24"]
keep = df[pop_col].notna().to_numpy()
if (~keep).sum():
warnings.append(f"{int((~keep).sum())} people without a population were left out.")
df = df[keep].reset_index(drop=True)
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
pops = np.array([str(v) for v in df[pop_col]], dtype=object)
levels = sorted(set(pops))
if len(levels) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=pop_col, min=2, k=len(levels)) # F_ST compares populations
g, counted, other = gen.dose_matrix({v: df[v].to_numpy() for v in variants})
# Populations with at least one genotype call: F_ST needs two of them.
k_called = sum(1 for lev in levels if np.any(~np.isnan(g[pops == lev])))
if k_called < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=pop_col, min=2, k=k_called)
estimator = "weir_cockerham"
if estimator == "hudson" and len(levels) != 2:
cs.cs_error("CS_E_GROUP_COUNT", column=pop_col, expected=2, k=len(levels)) # Hudson's estimator compares two populations
pairwise = True
test = "permutation"
n_perm = int(199)
seed = 42 # shared Wichmann–Hill stream: the same shuffles in Python and R
sizes = [int(np.sum(pops == lev)) for lev in levels]
# %% F_ST
if estimator == "weir_cockerham":
fst, per, a, b, c = gen.wc_fst(g, pops, levels)
label = "Weir & Cockerham"
else:
fst, per, num_, den_ = gen.hudson_fst(g, pops, levels)
label = "Hudson"
n_used = int(np.sum(~np.isnan(per)))
if n_used == 0:
cs.cs_error("CS_E_UNDEFINED", what="F_ST", reason="every marker is monomorphic here or lacks calls in a population")
p = gen.fst_permutation(g, pops, levels, fst, estimator, n_perm, seed) if test == "permutation" else None
pair_rows = []
if pairwise and len(levels) > 2:
for i in range(len(levels)):
for j in range(i + 1, len(levels)):
sub = (pops == levels[i]) | (pops == levels[j])
f = gen.wc_fst(g[sub], pops[sub], [levels[i], levels[j]])[0]
pair_rows.append({"a": levels[i], "b": levels[j], "fst": f})
if n_used < len(variants):
warnings.append(f"{len(variants) - n_used} markers are monomorphic here or lack calls in a population, so they add nothing.")
# %% Assumptions
small = min(sizes) < 20
assumptions = [
{"key": "hwe_within", "label": "Random mating within populations", "status": "info", "detail": "Not checkable here: check Hardy–Weinberg proportions within each population."},
{"key": "neutral_markers", "label": "Markers not chosen for differences", "status": "info", "detail": f"{n_used} informative markers; markers chosen because they differ overstate F_ST."},
{"key": "sample_size", "label": "Enough people per population", "status": "warn" if small else "pass",
"detail": f"Smallest population: {min(sizes)} people" + (" (per-marker F_ST will be noisy)." if small else ".")},
]
# %% Result
summary = (f"{label} F_ST = {fst:.4f} across {n_used} markers and {len(levels)} populations ({len(pops)} people)"
+ (f"; permutation test, {cs.fmt_p(p)} ({n_perm} shuffles, seed {seed})." if p is not None else "."))
apa = f"F_ST ({label}) = {cs.fmt_num(fst, 3)}, {len(levels)} populations, {n_used} markers" + (f", {cs.fmt_p(p)}" if p is not None else "")
marker_rows = [{"marker": v, "counted": counted[i], "fst": float(per[i])} for i, v in enumerate(variants)]
pop_rows = [{"population": lev, "n": sizes[i], "freq": float(np.nanmean(g[pops == lev], axis=0).mean() / 2) if np.any(~np.isnan(g[pops == lev])) else math.nan}
for i, lev in enumerate(levels)]
notes = [research_note,
"Markers are combined as a ratio of summed variance components, which weights informative markers more than an average of per-marker F_ST would.",
"Wright's rough guide: below 0.05 little differentiation, 0.05–0.15 moderate, 0.15–0.25 great, above 0.25 very great."]
values = {
"n": len(pops), "n_pops": len(levels), "n_variants": len(variants), "n_used": n_used, "fst": fst, "p": p,
"n_perm": n_perm if p is not None else None, "test": test, "estimator": estimator, "estimator_label": label, "pop_sizes": sizes,
"fst_marker": per.tolist(), "pair_fst": [x["fst"] for x in pair_rows], "pair_labels": [f"{x['a']}|{x['b']}" for x in pair_rows],
}
cs.publish({
"method": "genetics.fst",
"methodVersion": "1.0.1",
"title": "Population differentiation (F_ST)",
"engine": cs.engine_info("pandas", "numpy"),
"n": len(pops),
"summary": summary,
"apa": apa,
"statistics": [
{"key": "fst", "label": f"F_ST ({label})", "value": fst},
{"key": "n_used", "label": "Informative markers", "value": n_used},
] + ([{"key": "p", "label": "p (permutation)", "value": p, "format": "p"}] if p is not None else []),
"tables": [
{"key": "populations", "title": "Populations",
"columns": [{"key": "population", "label": "Population", "type": "string"}, {"key": "n", "label": "People", "type": "integer"},
{"key": "freq", "label": "Mean counted-allele frequency", "type": "number"}],
"rows": pop_rows},
{"key": "markers", "title": "F_ST per marker",
"columns": [{"key": "marker", "label": "Marker", "type": "string"}, {"key": "counted", "label": "Counted allele", "type": "string"},
{"key": "fst", "label": "F_ST", "type": "number"}],
"rows": marker_rows},
] + ([{"key": "pairs", "title": "Pairwise F_ST (Weir & Cockerham)",
"columns": [{"key": "a", "label": "Population A", "type": "string"}, {"key": "b", "label": "Population B", "type": "string"},
{"key": "fst", "label": "F_ST", "type": "number"}],
"rows": pair_rows}] if pair_rows else []),
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": [],
"values": values,
})
The exact script CodeSplash ran for example “Wc perm” · R version 4.5.1 (2025-06-13)
# Population differentiation (F_ST)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.fst 1.0.1 · spec 31353921bc7ab1dd
# Dataset: ge_people (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr) # cs_gen_wc_fst, cs_gen_hudson_fst, cs_gen_fst_permutation (twins of codesplash.stats.genetics)
# %% Data (no rows dropped here: genotype no-calls and missing values are handled by the analysis)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/ge_people.parquet", col_select = c("population", "v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."
# %% People and markers
pop_col <- "population"
variants <- c("v09", "v10", "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23", "v24")
keep <- !is.na(df[[pop_col]])
if (sum(!keep) > 0) warnings <- c(warnings, sprintf("%d people without a population were left out.", sum(!keep)))
df <- df[keep, , drop = FALSE]
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
pops <- as.character(df[[pop_col]])
levels <- sort(unique(pops), method = "radix")
if (length(levels) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pop_col, min = 2, k = length(levels)) # F_ST compares populations
dm <- cs_gen_dose_matrix(df[variants])
g <- dm$g
# Populations with at least one genotype call: F_ST needs two of them.
k_called <- sum(vapply(levels, function(lev) any(!is.na(g[pops == lev, , drop = FALSE])), logical(1)))
if (k_called < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = pop_col, min = 2, k = k_called)
estimator <- "weir_cockerham"
if (estimator == "hudson" && length(levels) != 2) {
cs_error("CS_E_GROUP_COUNT", column = pop_col, expected = 2, k = length(levels)) # Hudson's estimator compares two populations
}
pairwise <- TRUE
test <- "permutation"
n_perm <- as.integer(199)
seed <- 42 # shared Wichmann-Hill stream: the same shuffles in Python and R
sizes <- vapply(levels, function(lev) sum(pops == lev), numeric(1))
# %% F_ST
if (estimator == "weir_cockerham") {
w <- cs_gen_wc_fst(g, pops, levels)
label <- "Weir & Cockerham"
} else {
w <- cs_gen_hudson_fst(g, pops, levels)
label <- "Hudson"
}
fst <- w$fst
per <- w$per
n_used <- sum(!is.na(per))
if (n_used == 0) cs_error("CS_E_UNDEFINED", what = "F_ST", reason = "every marker is monomorphic here or lacks calls in a population")
p <- if (test == "permutation") cs_gen_fst_permutation(g, pops, levels, fst, estimator, n_perm, seed) else NA
pair_rows <- list()
if (pairwise && length(levels) > 2) {
for (i in seq_len(length(levels) - 1)) {
for (j in (i + 1):length(levels)) {
sub <- pops == levels[i] | pops == levels[j]
f <- cs_gen_wc_fst(g[sub, , drop = FALSE], pops[sub], c(levels[i], levels[j]))$fst
pair_rows[[length(pair_rows) + 1]] <- list(a = levels[i], b = levels[j], fst = f)
}
}
}
if (n_used < length(variants)) {
warnings <- c(warnings, sprintf("%d markers are monomorphic here or lack calls in a population, so they add nothing.", length(variants) - n_used))
}
# %% Assumptions
small <- min(sizes) < 20
assumptions <- list(
list(key = "hwe_within", label = "Random mating within populations", status = "info", detail = "Not checkable here: check Hardy–Weinberg proportions within each population."),
list(key = "neutral_markers", label = "Markers not chosen for differences", status = "info", detail = sprintf("%d informative markers; markers chosen because they differ overstate F_ST.", n_used)),
list(key = "sample_size", label = "Enough people per population", status = if (small) "warn" else "pass",
detail = paste0(sprintf("Smallest population: %d people", as.integer(min(sizes))), if (small) " (per-marker F_ST will be noisy)." else "."))
)
# %% Result
has_p <- test == "permutation"
summary <- paste0(sprintf("%s F_ST = %.4f across %d markers and %d populations (%d people)", label, fst, n_used, length(levels), length(pops)),
if (has_p) sprintf("; permutation test, %s (%d shuffles, seed %d).", cs_fmt_p(p), n_perm, as.integer(seed)) else ".")
apa <- paste0(sprintf("F_ST (%s) = %s, %d populations, %d markers", label, cs_fmt_num(fst, 3), length(levels), n_used), if (has_p) sprintf(", %s", cs_fmt_p(p)) else "")
marker_rows <- lapply(seq_along(variants), function(i) list(marker = variants[i], counted = dm$counted[i], fst = per[i]))
pop_rows <- lapply(seq_along(levels), function(i) {
sub <- g[pops == levels[i], , drop = FALSE]
list(population = levels[i], n = sizes[[i]], freq = if (any(!is.na(sub))) mean(colMeans(sub, na.rm = TRUE)) / 2 else NaN)
})
notes <- list(research_note,
"Markers are combined as a ratio of summed variance components, which weights informative markers more than an average of per-marker F_ST would.",
"Wright's rough guide: below 0.05 little differentiation, 0.05–0.15 moderate, 0.15–0.25 great, above 0.25 very great.")
result_values <- list(
n = length(pops), n_pops = length(levels), n_variants = length(variants), n_used = n_used, fst = fst, p = p,
n_perm = if (has_p) n_perm else NA, test = test, estimator = estimator, estimator_label = label, pop_sizes = I(unname(sizes)),
fst_marker = I(unname(per)), pair_fst = I(vapply(pair_rows, function(x) x$fst, numeric(1))),
pair_labels = I(vapply(pair_rows, function(x) paste0(x$a, "|", x$b), character(1)))
)
tables <- list(
list(key = "populations", title = "Populations",
columns = list(list(key = "population", label = "Population", type = "string"), list(key = "n", label = "People", type = "integer"),
list(key = "freq", label = "Mean counted-allele frequency", type = "number")),
rows = pop_rows),
list(key = "markers", title = "F_ST per marker",
columns = list(list(key = "marker", label = "Marker", type = "string"), list(key = "counted", label = "Counted allele", type = "string"),
list(key = "fst", label = "F_ST", type = "number")),
rows = marker_rows)
)
if (length(pair_rows)) {
tables[[3]] <- list(key = "pairs", title = "Pairwise F_ST (Weir & Cockerham)",
columns = list(list(key = "a", label = "Population A", type = "string"), list(key = "b", label = "Population B", type = "string"),
list(key = "fst", label = "F_ST", type = "number")),
rows = pair_rows)
}
stats_rows <- list(list(key = "fst", label = sprintf("F_ST (%s)", label), value = fst), list(key = "n_used", label = "Informative markers", value = n_used))
if (has_p) stats_rows[[3]] <- list(key = "p", label = "p (permutation)", value = p, format = "p")
cs_publish(list(
method = "genetics.fst",
methodVersion = "1.0.1",
title = "Population differentiation (F_ST)",
engine = cs_engine_info("stats", "nanoparquet"),
n = length(pops),
summary = summary,
apa = apa,
statistics = stats_rows,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = list(),
values = result_values
))
Sources
- Weir, B. S., & Cockerham, C. C. (1984). Estimating F-statistics for the analysis of population structure. Evolution, 38, 1358–1370.
- Hudson, R. R., Slatkin, M., & Maddison, W. P. (1992). Estimation of levels of gene flow from DNA sequence data. Genetics, 132, 583–589.
- Bhatia, G., Patterson, N., Sankararaman, S., & Price, A. L. (2013). Estimating and interpreting FST: the impact of rare variants. Genome Research, 23, 1514–1521.
- Wright, S. (1951). The genetical structure of populations. Annals of Eugenics, 15, 323–354.
From the CodeSplash method registry · genetics.fst v1.0.1.