EGenetics · genetics.neutrality
Neutrality test (Tajima's D)
Does the allele-frequency spectrum of these sequences fit a neutral, constant-size population?
Compares two estimates of variation from the same sequences: the average number of pairwise differences (π) and the number of segregating sites scaled by sample size (S/a₁). Tajima's D standardizes their difference. Negative D means too many rare variants, positive D too many at intermediate frequency. The p-value comes from neutral coalescent simulations or Tajima's beta distribution, never the normal curve. Growth, structure and selection all move D, so a rejection doesn't name a cause. Research use only.
A real result
Example “Guide coalescent”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Tajima's D = 0.39, S = 8, n = 12, p = .639
- Tajima's D
- 0.3919
- π (mean pairwise differences)
- 2.909
- θ_W = S / a₁
- 2.649
- Segregating sites S
- 8
- p (simulation)
- .639
Plots
View data
| Minor-allele count | Sites |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
Observed D = 0.392.
View data
| Simulated D |
|---|
| 0.5289 |
| −1.778 |
| 0.2092 |
| −0.4075 |
| 0.6431 |
| −0.1334 |
| 0.9400 |
| −1.983 |
| −0.7958 |
| −0.4760 |
| −0.7272 |
| 0.2092 |
| −0.0877 |
| 0.2092 |
| −0.3847 |
| 0.5289 |
| −0.4532 |
| −1.230 |
| −0.1563 |
| 0.4833 |
| 1.374 |
| 0.0493 |
| 0.3462 |
| −0.2705 |
| 0.2092 |
| 0.4147 |
| 0.0493 |
| 0.5061 |
| −0.3161 |
| 0.2092 |
| −0.6816 |
| 0.9857 |
| −1.161 |
| 1.100 |
| −0.4303 |
| 0.5518 |
| −1.367 |
| −1.207 |
| −0.4075 |
| −1.983 |
| −0.4760 |
| −0.8871 |
| −0.2705 |
| −0.1106 |
| −0.0192 |
| −0.2705 |
| 0.4833 |
| −0.3618 |
| −1.572 |
| −0.4075 |
| 0.7802 |
| −1.412 |
| 0.0265 |
| 0.6203 |
| −0.2019 |
| −1.504 |
| 0.0950 |
| 1.374 |
| 0.0265 |
| −1.412 |
First 60 of 1000 rows.
Assumptions
- Standard neutral model — Not checkable from these counts: growth, bottlenecks and structure move D as selection does.
- One mutation per site — Assumed: each segregating site arose once. Multi-allelic or recurrent sites should be left out first.
- Recombination — The simulated genealogies don't recombine; for long regions this widens the null and makes p conservative.
- Random sample of homologous sequences — 12 sequences, 8 sites (0 monomorphic, not counted in S).
Calibrations of D
| Reference | p | p (D lower) | p (D higher) |
|---|---|---|---|
| Tajima's beta distribution | 0.7018 | 0.6491 | 0.3509 |
| Coalescent simulation (1,000) | 0.6394 | 0.6883 | 0.3197 |
Folded site frequency spectrum
| Minor-allele count | Sites |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
- Only 8 segregating sites: D has little power and its null distribution is lumpy.
- Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
- D lies between -2.353 (every site a singleton) and 3.065 (every site split evenly) as S grows (Tajima 1989).
- A rejection says the spectrum doesn't fit a constant-size neutral population; it doesn't say which assumption failed.
Tajima's D = 0.39, S = 8, n = 12, p = .639
- Tajima's D
- 0.3919
- π (mean pairwise differences)
- 2.909
- θ_W = S / a₁
- 2.649
- Segregating sites S
- 8
- p (simulation)
- .639
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Standard neutral model — Not checkable from these counts: growth, bottlenecks and structure move D as selection does.
- One mutation per site — Assumed: each segregating site arose once. Multi-allelic or recurrent sites should be left out first.
- Recombination — The simulated genealogies don't recombine; for long regions this widens the null and makes p conservative.
- Random sample of homologous sequences — 12 sequences, 8 sites (0 monomorphic, not counted in S).
Calibrations of D
| Reference | p | p (D lower) | p (D higher) |
|---|---|---|---|
| Tajima's beta distribution | 0.7018 | 0.6491 | 0.3509 |
| Coalescent simulation (1,000) | 0.6394 | 0.6883 | 0.3197 |
Folded site frequency spectrum
| Minor-allele count | Sites |
|---|---|
| 1 | 2 |
| 2 | 2 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
| 6 | 1 |
- Only 8 segregating sites: D has little power and its null distribution is lumpy.
- Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
- D lies between -2.353 (every site a singleton) and 3.065 (every site split evenly) as S grows (Tajima 1989).
- A rejection says the spectrum doesn't fit a constant-size neutral population; it doesn't say which assumption failed.
Do it in CodeSplash Run it on your own data. It's in the Experimental lane in the app.
Worked examples in the app
- Guide coalescentge_tajima_guide · derived: derived · sample_size: sequences
- Guide betage_tajima_guide · derived: derived · sample_size: sequences
- Guide typed nge_tajima_guide · derived: derived
- Sites windowsge_sites · derived: derived · position: position · sample_size: sequences
- Sites greater simge_sites · derived: derived_complete · sample_size: complete
- Sites less betage_sites · derived: derived_complete · position: position · sample_size: complete
- Degenerate empty after filterge_tajima_guide · derived: derived · sample_size: sequences
- Degenerate infge_tajima_guide · derived: derived · sample_size: sequences
In the guides
Tests from the statistics guide this method runs
What you need
- Derived-allele countnumeric · 1 column
- One row per site: how many of the sampled sequences carry the derived (or alternative) allele.
- Sequences at the site (optional)numeric · 0–1 column
- How many sequences were called at each site. Without it, set the number of sequences below.
- Position (optional)numeric · 0–1 column
- Base-pair position of each site; needed for D in sliding windows.
Choices you make
hypothesis
- Number of sequencesdefault —
Sequences sampled at every site, when there is no sample-size column.
- Reference distributiondefault coalescent
D isn't standard normal, so its p-value needs a neutral model. Both choices assume a constant-size, random-mating population.
- Coalescent simulation(default) — Neutral genealogies with the observed number of segregating sites (Hudson's fixed-S method); no recombination.
- Tajima's beta distribution — Tajima's (1989) beta approximation between D's lowest and highest possible values; no simulation.
- Alternative hypothesisdefault two_sided
Decide the direction before looking at the data.
- Any departure(default) — D far from 0 in either direction.
- Excess of rare variants (D < 0) — As after population growth, a sweep or purifying selection.
- Excess of intermediate variants (D > 0) — As with balancing selection, a bottleneck or population structure.
- Simulationsdefault 1000
Neutral samples to simulate; the smallest possible p is 1/(B + 1).
statistics
- Window size (bp)default 0
Also compute D in windows of this many base pairs along the positions; 0 turns windows off.
- Window step (bp)default 0
Distance between window starts; 0 means windows don't overlap (step = size).
- Fewest sites per windowdefault 3
Windows with fewer segregating sites get no D.
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.
Standard neutral model
Constant size, random mating and no structure: departures from any of them move D as selection does.
One mutation per site
Each segregating site arose by a single mutation (infinite-sites model); recurrent mutation biases π and S.
Recombination
Simulated genealogies don't recombine, which widens the null for long regions and makes the test conservative.
Random sample of homologous sequences
Sequences drawn at random from one population, aligned at the same sites.
What it reports
- Tests: Neutral evolution in a constant-size population
- n
- A site where the sampled sequences carry more than one allele. Sites where every sequence agrees (monomorphic) don't count in S.
- n_sites
- A site where the sampled sequences carry more than one allele. Sites where every sequence agrees (monomorphic) don't count in S.
- s
- A site where the sampled sequences carry more than one allele. Sites where every sequence agrees (monomorphic) don't count in S.
- n_monomorphic
- A site where the sampled sequences carry more than one allele. Sites where every sequence agrees (monomorphic) don't count in S.
- n_short
- A site where the sampled sequences carry more than one allele. Sites where every sequence agrees (monomorphic) don't count in S.
- pi
- The average number of differences between two sequences drawn from the sample; each site adds 2k(n − k)/[n(n − 1)].
- theta_w
- The number of segregating sites divided by a₁ = 1 + 1/2 + … + 1/(n − 1); under neutrality it estimates 4Nμ.
- tajima_d
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- d_min
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- d_max
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- a1
- The number of segregating sites divided by a₁ = 1 + 1/2 + … + 1/(n − 1); under neutrality it estimates 4Nμ.
- a2
- The number of segregating sites divided by a₁ = 1 + 1/2 + … + 1/(n − 1); under neutrality it estimates 4Nμ.
- e1
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- e2
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- p
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- p_beta
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- p_beta_less
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- p_beta_greater
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- p_sim
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- sim_mean
- Draws random family trees of the sampled sequences under neutrality, drops the observed mutations on them, and sees what D chance gives.
- sim_sd
- Draws random family trees of the sampled sequences under neutrality, drops the observed mutations on them, and sees what D chance gives.
- sim_q025
- Draws random family trees of the sampled sequences under neutrality, drops the observed mutations on them, and sees what D chance gives.
- sim_q975
- Draws random family trees of the sampled sequences under neutrality, drops the observed mutations on them, and sees what D chance gives.
- n_sim
- Draws random family trees of the sampled sequences under neutrality, drops the observed mutations on them, and sees what D chance gives.
- calibration
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- alternative
- D isn't standard normal. Its p-value comes from simulated neutral genealogies, or from Tajima's beta distribution over D's possible range.
- n_windows
- The statistic computed in windows of a fixed number of base pairs along the positions, to find regions that stand out.
- window_d
- The statistic computed in windows of a fixed number of base pairs along the positions, to find regions that stand out.
- sfs_counts
- How many sites carry the minor allele in 1, 2, 3 … of the sampled sequences. Tajima's D summarizes its shape.
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.
Default traps between the two languages
- Both engines simulate the same genealogies from the shared Wichmann–Hill stream, so simulated p-values match exactly; packages that simulate with their own generators (ms, PopGenome) differ by Monte Carlo error.
- Sites with missing calls use their own sample size in π, while S/a₁ and the variance use the largest sample size (scikit-allel's convention).
The exact script CodeSplash ran for example “Guide coalescent” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Neutrality test (Tajima's D)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.neutrality 1.0.1 · spec f3cfb9ecfd430545
# Dataset: ge_tajima_guide (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 # Tajima's D, coalescent and beta calibration (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_tajima_guide.parquet", columns=["derived", "sequences"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."
# %% Sites
derived_col = "derived"
size_col = "sequences"
pos_col = None
n_typed = None
keep = df[derived_col].notna()
if size_col is not None:
keep &= df[size_col].notna()
if pos_col is not None:
keep &= df[pos_col].notna()
n_dropped = int((~keep).sum())
if n_dropped:
warnings.append(f"{n_dropped} of {n_input} sites were left out because a value was missing.")
df = df[keep]
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, [c for c in (derived_col, size_col, pos_col) if c is not None]) # infinite values stop the run
derived = df[derived_col].to_numpy(dtype=float)
if size_col is not None:
sizes = df[size_col].to_numpy(dtype=float)
elif n_typed is not None:
sizes = np.full(len(derived), float(n_typed))
else:
raise ValueError("Bind a column with the number of sequences at each site, or type the number of sequences.")
positions = df[pos_col].to_numpy(dtype=float) if pos_col is not None else None
calibration = "coalescent"
alternative = "two_sided"
n_sim = int(1000)
seed = 42 # shared Wichmann–Hill stream: the same genealogies in Python and R
window = float(0)
step = float(0)
min_sites = int(3)
# %% Tajima's D
r = gen.neutrality(derived, sizes, positions, window, step, calibration, alternative, n_sim, seed, min_sites)
n, s, d, p = r["n"], r["s"], r["tajima_d"], r["p"]
sim = calibration == "coalescent"
cal_label = f"{n_sim:,} neutral coalescent simulations with S = {s} (seed {seed})" if sim else "Tajima's beta distribution"
alt_label = {"two_sided": "two-sided", "less": "one-sided, excess of rare variants", "greater": "one-sided, excess of intermediate variants"}[alternative]
if r["n_short"]:
warnings.append(f"{r['n_short']} sites have fewer than {int(n)} sequences called; their π uses their own sample size.")
if s < 10:
warnings.append(f"Only {s} segregating sites: D has little power and its null distribution is lumpy.")
# %% Assumptions
assumptions = [
{"key": "neutral_model", "label": "Standard neutral model", "status": "info",
"detail": "Not checkable from these counts: growth, bottlenecks and structure move D as selection does."},
{"key": "infinite_sites", "label": "One mutation per site", "status": "info",
"detail": "Assumed: each segregating site arose once. Multi-allelic or recurrent sites should be left out first."},
{"key": "recombination", "label": "Recombination", "status": "info" if sim else "pass",
"detail": "The simulated genealogies don't recombine; for long regions this widens the null and makes p conservative." if sim
else "Tajima's beta distribution doesn't model recombination either; it is an approximation for any region."},
{"key": "sample", "label": "Random sample of homologous sequences", "status": "info",
"detail": f"{int(n)} sequences, {r['n_sites']} sites ({r['n_monomorphic']} monomorphic, not counted in S)."},
]
# %% Result
summary = (f"Tajima's D = {d:.3f} over {s} segregating sites in {int(n)} sequences (π = {r['pi']:.3f}, S/a₁ = {r['theta_w']:.3f}): "
f"{cs.fmt_p(p)} ({alt_label}, {cal_label}).")
apa = f"Tajima's D = {cs.fmt_num(d)}, S = {s}, n = {int(n)}, {cs.fmt_p(p)}"
stats_rows = [
{"key": "tajima_d", "label": "Tajima's D", "value": d},
{"key": "pi", "label": "π (mean pairwise differences)", "value": r["pi"]},
{"key": "theta_w", "label": "θ_W = S / a₁", "value": r["theta_w"]},
{"key": "s", "label": "Segregating sites S", "value": s},
{"key": "p", "label": f"p ({'simulation' if sim else 'beta'})", "value": p, "format": "p"},
]
tests = [{"test": "Tajima's beta distribution", "p": r["p_beta"], "less": r["p_beta_less"], "greater": r["p_beta_greater"]}]
if sim:
tests.append({"test": f"Coalescent simulation ({n_sim:,})", "p": r["p_sim"], "less": r["p_sim_less"], "greater": r["p_sim_greater"]})
spectrum = [{"minor_count": i + 1, "sites": c} for i, c in enumerate(r["sfs_counts"])]
win = r["windows"]
notes = [research_note,
f"D lies between {r['d_min']:.3f} (every site a singleton) and {r['d_max']:.3f} (every site split evenly) as S grows (Tajima 1989).",
"A rejection says the spectrum doesn't fit a constant-size neutral population; it doesn't say which assumption failed."]
if win:
notes.append(f"{len(win)} windows of {int(window):,} bp; windows with fewer than {min_sites} segregating sites have no D.")
charts = [cs.chart("sfs", "sfs-bar", "Folded site frequency spectrum", {
"count": cs.col("Minor-allele count", list(range(1, len(r["sfs_counts"]) + 1)), "numeric"),
"sites": cs.col("Sites", r["sfs_counts"], "numeric")}, controls={"n": int(n), "folded": True})]
if sim:
charts.append(cs.chart("null_d", "histogram", "Tajima's D in neutral simulations",
{"x": cs.col("Simulated D", r["sim_d"])}, note=f"Observed D = {d:.3f}."))
if win:
charts.append(cs.chart("windows", "line", "Tajima's D along the region",
{"x": cs.col("Window start", [w["start"] for w in win]), "y": cs.col("Tajima's D", [w["tajima_d"] for w in win])}))
values = {
"n": n, "n_sites": r["n_sites"], "s": s, "n_monomorphic": r["n_monomorphic"], "n_short": r["n_short"],
"pi": r["pi"], "theta_w": r["theta_w"], "tajima_d": d, "d_min": r["d_min"], "d_max": r["d_max"],
"a1": r["a1"], "a2": r["a2"], "e1": r["e1"], "e2": r["e2"], "p": p, "p_beta": r["p_beta"],
"p_beta_less": r["p_beta_less"], "p_beta_greater": r["p_beta_greater"],
"p_sim": r["p_sim"] if sim else None, "sim_mean": r["sim_mean"] if sim else None, "sim_sd": r["sim_sd"] if sim else None,
"sim_q025": r["sim_q025"] if sim else None, "sim_q975": r["sim_q975"] if sim else None,
"n_sim": n_sim if sim else None, "calibration": calibration, "alternative": alternative,
"n_windows": len(win), "window_d": [w["tajima_d"] for w in win], "sfs_counts": r["sfs_counts"],
}
cs.publish({
"method": "genetics.neutrality",
"methodVersion": "1.0.1",
"title": "Tajima's D",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": int(n),
"summary": summary,
"apa": apa,
"statistics": stats_rows,
"tables": [
{"key": "tests", "title": "Calibrations of D",
"columns": [{"key": "test", "label": "Reference", "type": "string"}, {"key": "p", "label": "p", "type": "p"},
{"key": "less", "label": "p (D lower)", "type": "p"}, {"key": "greater", "label": "p (D higher)", "type": "p"}],
"rows": tests},
{"key": "spectrum", "title": "Folded site frequency spectrum",
"columns": [{"key": "minor_count", "label": "Minor-allele count", "type": "integer"}, {"key": "sites", "label": "Sites", "type": "integer"}],
"rows": spectrum},
] + ([{"key": "windows", "title": "Tajima's D in windows",
"columns": [{"key": "start", "label": "Start", "type": "integer"}, {"key": "stop", "label": "Stop", "type": "integer"},
{"key": "sites", "label": "Sites", "type": "integer"}, {"key": "s", "label": "S", "type": "integer"},
{"key": "pi", "label": "π", "type": "number"}, {"key": "theta_w", "label": "θ_W", "type": "number"},
{"key": "tajima_d", "label": "D", "type": "number"}],
"rows": win}] if win else []),
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Guide coalescent” · R version 4.5.1 (2025-06-13)
# Neutrality test (Tajima's D)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.neutrality 1.0.1 · spec f3cfb9ecfd430545
# Dataset: ge_tajima_guide (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_neutrality (Tajima's D with coalescent / beta calibration; twin 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_tajima_guide.parquet", col_select = c("derived", "sequences")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."
# %% Sites
derived_col <- "derived"
size_col <- "sequences"
pos_col <- NULL
n_typed <- NULL
keep <- !is.na(df[[derived_col]])
if (!is.null(size_col)) keep <- keep & !is.na(df[[size_col]])
if (!is.null(pos_col)) keep <- keep & !is.na(df[[pos_col]])
n_dropped <- sum(!keep)
if (n_dropped > 0) warnings <- c(warnings, sprintf("%d of %d sites were left out because a value was missing.", n_dropped, n_input))
df <- df[keep, , drop = FALSE]
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c(derived_col, size_col, pos_col)) # infinite values stop the run
derived <- as.numeric(df[[derived_col]])
sizes <- if (!is.null(size_col)) {
as.numeric(df[[size_col]])
} else if (!is.null(n_typed)) {
rep(as.numeric(n_typed), length(derived))
} else {
stop("Bind a column with the number of sequences at each site, or type the number of sequences.", call. = FALSE)
}
positions <- if (!is.null(pos_col)) as.numeric(df[[pos_col]]) else NULL
calibration <- "coalescent"
alternative <- "two_sided"
n_sim <- as.integer(1000)
seed <- 42 # shared Wichmann-Hill stream: the same genealogies in Python and R
window <- 0
step <- 0
min_sites <- as.integer(3)
# %% Tajima's D
r <- cs_gen_neutrality(derived, sizes, positions, window, step, calibration, alternative, n_sim, seed, min_sites)
n <- r$n
s <- r$s
d <- r$tajima_d
p <- r$p
sim <- calibration == "coalescent"
cal_label <- if (sim) sprintf("%s neutral coalescent simulations with S = %d (seed %d)", format(n_sim, big.mark = ","), as.integer(s), as.integer(seed)) else "Tajima's beta distribution"
alt_label <- switch(alternative, two_sided = "two-sided", less = "one-sided, excess of rare variants", greater = "one-sided, excess of intermediate variants")
if (r$n_short > 0) warnings <- c(warnings, sprintf("%d sites have fewer than %d sequences called; their π uses their own sample size.", as.integer(r$n_short), as.integer(n)))
if (s < 10) warnings <- c(warnings, sprintf("Only %d segregating sites: D has little power and its null distribution is lumpy.", as.integer(s)))
# %% Assumptions
assumptions <- list(
list(key = "neutral_model", label = "Standard neutral model", status = "info",
detail = "Not checkable from these counts: growth, bottlenecks and structure move D as selection does."),
list(key = "infinite_sites", label = "One mutation per site", status = "info",
detail = "Assumed: each segregating site arose once. Multi-allelic or recurrent sites should be left out first."),
list(key = "recombination", label = "Recombination", status = if (sim) "info" else "pass",
detail = if (sim) "The simulated genealogies don't recombine; for long regions this widens the null and makes p conservative." else
"Tajima's beta distribution doesn't model recombination either; it is an approximation for any region."),
list(key = "sample", label = "Random sample of homologous sequences", status = "info",
detail = sprintf("%d sequences, %d sites (%d monomorphic, not counted in S).", as.integer(n), as.integer(r$n_sites), as.integer(r$n_monomorphic)))
)
# %% Result
summary <- sprintf("Tajima's D = %.3f over %d segregating sites in %d sequences (π = %.3f, S/a₁ = %.3f): %s (%s, %s).",
d, as.integer(s), as.integer(n), r$pi, r$theta_w, cs_fmt_p(p), alt_label, cal_label)
apa <- sprintf("Tajima's D = %s, S = %d, n = %d, %s", cs_fmt_num(d), as.integer(s), as.integer(n), cs_fmt_p(p))
stats_rows <- list(
list(key = "tajima_d", label = "Tajima's D", value = d),
list(key = "pi", label = "π (mean pairwise differences)", value = r$pi),
list(key = "theta_w", label = "θ_W = S / a₁", value = r$theta_w),
list(key = "s", label = "Segregating sites S", value = s),
list(key = "p", label = sprintf("p (%s)", if (sim) "simulation" else "beta"), value = p, format = "p")
)
tests <- list(list(test = "Tajima's beta distribution", p = r$p_beta, less = r$p_beta_less, greater = r$p_beta_greater))
if (sim) tests[[2]] <- list(test = sprintf("Coalescent simulation (%s)", format(n_sim, big.mark = ",")), p = r$p_sim, less = r$p_sim_less, greater = r$p_sim_greater)
spectrum <- lapply(seq_along(r$sfs_counts), function(i) list(minor_count = i, sites = r$sfs_counts[i]))
win <- r$windows
win_d <- vapply(win, function(w) w$tajima_d, numeric(1))
notes <- list(research_note,
sprintf("D lies between %.3f (every site a singleton) and %.3f (every site split evenly) as S grows (Tajima 1989).", r$d_min, r$d_max),
"A rejection says the spectrum doesn't fit a constant-size neutral population; it doesn't say which assumption failed.")
if (length(win)) notes <- c(notes, sprintf("%d windows of %s bp; windows with fewer than %d segregating sites have no D.", length(win), format(window, big.mark = ","), min_sites))
charts <- list(cs_chart("sfs", "sfs-bar", "Folded site frequency spectrum",
list(count = cs_col("Minor-allele count", seq_along(r$sfs_counts), "numeric"),
sites = cs_col("Sites", as.numeric(r$sfs_counts), "numeric")),
controls = list(n = as.integer(n), folded = TRUE)))
if (sim) {
charts[[length(charts) + 1]] <- cs_chart("null_d", "histogram", "Tajima's D in neutral simulations",
list(x = cs_col("Simulated D", r$sim_d)), note = sprintf("Observed D = %.3f.", d))
}
if (length(win)) {
charts[[length(charts) + 1]] <- cs_chart("windows", "line", "Tajima's D along the region",
list(x = cs_col("Window start", vapply(win, function(w) w$start, numeric(1))), y = cs_col("Tajima's D", win_d)))
}
tables <- list(
list(key = "tests", title = "Calibrations of D",
columns = list(list(key = "test", label = "Reference", type = "string"), list(key = "p", label = "p", type = "p"),
list(key = "less", label = "p (D lower)", type = "p"), list(key = "greater", label = "p (D higher)", type = "p")),
rows = tests),
list(key = "spectrum", title = "Folded site frequency spectrum",
columns = list(list(key = "minor_count", label = "Minor-allele count", type = "integer"), list(key = "sites", label = "Sites", type = "integer")),
rows = spectrum)
)
if (length(win)) {
tables[[3]] <- list(key = "windows", title = "Tajima's D in windows",
columns = list(list(key = "start", label = "Start", type = "integer"), list(key = "stop", label = "Stop", type = "integer"),
list(key = "sites", label = "Sites", type = "integer"), list(key = "s", label = "S", type = "integer"),
list(key = "pi", label = "π", type = "number"), list(key = "theta_w", label = "θ_W", type = "number"),
list(key = "tajima_d", label = "D", type = "number")),
rows = win)
}
result_values <- list(
n = n, n_sites = r$n_sites, s = s, n_monomorphic = r$n_monomorphic, n_short = r$n_short,
pi = r$pi, theta_w = r$theta_w, tajima_d = d, d_min = r$d_min, d_max = r$d_max,
a1 = r$a1, a2 = r$a2, e1 = r$e1, e2 = r$e2, p = p, p_beta = r$p_beta,
p_beta_less = r$p_beta_less, p_beta_greater = r$p_beta_greater,
p_sim = if (sim) r$p_sim else NA, sim_mean = if (sim) r$sim_mean else NA, sim_sd = if (sim) r$sim_sd else NA,
sim_q025 = if (sim) r$sim_q025 else NA, sim_q975 = if (sim) r$sim_q975 else NA,
n_sim = if (sim) n_sim else NA, calibration = calibration, alternative = alternative,
n_windows = length(win), window_d = I(win_d), sfs_counts = I(r$sfs_counts)
)
cs_publish(list(
method = "genetics.neutrality",
methodVersion = "1.0.1",
title = "Tajima's D",
engine = cs_engine_info("stats", "nanoparquet"),
n = n,
summary = summary,
apa = apa,
statistics = stats_rows,
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = result_values
))
Sources
- Tajima, F. (1989). Statistical method for testing the neutral mutation hypothesis by DNA polymorphism. Genetics, 123, 585–595.
- Watterson, G. A. (1975). On the number of segregating sites in genetical models without recombination. Theoretical Population Biology, 7, 256–276.
- Kingman, J. F. C. (1982). The coalescent. Stochastic Processes and their Applications, 13, 235–248.
- Hudson, R. R. (1990). Gene genealogies and the coalescent process. Oxford Surveys in Evolutionary Biology, 7, 1–44.
From the CodeSplash method registry · genetics.neutrality v1.0.1.