Skip to content

Testing neutrality: Tajima's D and McDonald–Kreitman

Two classic tests of neutral evolution, read from the guide's validated outputs. Both are sensitive to population history, so a rejection doesn't name a cause.

Advanced ~14 min11 steps

What runs in CodeSplash

You will be able to

  • Explain Tajima's D as a difference between two estimates of variation
  • Build and read a McDonald–Kreitman table
  • Say why neither test identifies selection on its own

Read first

01

Two estimates of one thing

Read

Under a standard neutral modelNeutral modelA model of genetic variation where drift and mutation alone shape allele frequencies, with no selection., a sample of sequences gives two estimates of the same variation:

  • π^\hat\pi, the average number of differences between pairs of sequences.
  • S/a1S/a_1, the number of variable sites, scaled by sample size.

Tajima's DTajima's DA standardized difference between two estimates of genetic variation, from pairwise differences and from variable sites. is their standardized difference:

D=π^−S/a1e1S+e2S(S−1)D = \frac{\hat\pi - S/a_1}{\sqrt{e_1 S + e_2 S(S-1)}}

The numbers below are the guide's validated outputs, not recorded engine runs. The last step runs both tests in CodeSplash.

02

Rare or common?

Predict

Predict first

Rare variants add to SS but barely change π^\hat\pi, because few pairs of sequences differ at them.

A sample has a great excess of rare variants. What sign does DD take?

NegativeClose to zeroPositive
Reveal

Negative. S/a1S/a_1 grows faster than π^\hat\pi. An excess of intermediate-frequency variants pushes DD the other way.

03

The guide's example

Read

The guide uses 12 sequences and 8 variable sites, with allele counts of 1, 2, 3, 4, 2, 1, 5 and 6.

Tajima D               0.3918923
Segregating sites      8
Pairwise differences   2.9090909

Here π^=2.909\hat\pi = 2.909 and S/a1=8/3.020=2.649S/a_1 = 8/3.020 = 2.649, so their difference is positive but small.

The guide stops there, and for good reason: it reports no p-value. DD isn't standard normal. A p-value needs simulation under a neutral model with a stated demography and recombination rate.

04

Same D, different stories

Reflect

Suppose you find a strongly negative DD. A recent selective sweep could do that. So could a population that has recently grown fast.

What other information would help you tell these apart? Consider comparing many regions of the genome: which explanation should act on all of them, and which on one?

05

McDonald–Kreitman

Read

The McDonald–Kreitman testMcDonald–Kreitman testCompares protein-changing and silent changes, within a species and between species, in a 2 × 2 table. compares changes that alter a protein (nonsynonymous) with those that don't (synonymous), both within a species and between species.

NonsynonymousSynonymous
PolymorphicPNP_N = 12PSP_S = 30
FixedDND_N = 8DSD_S = 40

Under neutrality, the ratio of nonsynonymous to synonymous should be the same in both rows. Fixations carrying extra protein changes suggest adaptive evolution.

06

Read the ratios

Predict

Predict first

DN/DS=8/40D_N/D_S = 8/40 and PN/PS=12/30P_N/P_S = 12/30. An estimate of the adaptive fraction is:

α=1−DSPNDNPS\alpha = 1 - \frac{D_S P_N}{D_N P_S}

What sign does α\alpha take for this table?

Positive, some fixations look adaptiveZero, exactly neutralNegative, an excess of protein polymorphism
Reveal

Negative: 1−(40×12)/(8×30)=1−2=−11 - (40 \times 12)/(8 \times 30) = 1 - 2 = -1. That isn't a meaningful "fraction". It reflects more protein polymorphism than the fixed differences would suggest, which weakly harmful variants can produce.

07

The guide's test

Read

Fisher's exact test on the table gives the guide's validated output:

Fisher's Exact Test for Count Data
p-value = 0.2094
95 percent confidence interval: 0.6510192 6.3634915
odds ratio 1.984466

So p=.209p = .209: compatible with neutrality.

08

See the table test

Explore

Change the two proportions and watch Fisher's exact test respond. Then shrink the counts: with few changes in each cell, even a large gap between the rows can stay compatible with neutrality.

BExplorable · McDonald–Kreitman test

Is the ratio of nonsynonymous to synonymous changes the same for fixed differences and polymorphisms?

30
40
0.55
0.30
0.050

Alternative

Your data

Edit the counts
SuccessFailureTotal
Row 1
14E = 11.6
16E = 18.4
30
Row 2
13E = 15.4
27E = 24.6
40
Total274370

E is the count expected if rows and columns were unrelated.

If H₀ were true

a = 14
  1. The reference: how a varies across samples when H₀ is true.
  2. Your statistic, from the data above.
  3. The p-value: the total probability of outcomes no more likely than yours (p = .321).
  4. The hatched rejection region at α = .050: statistics landing here reject H₀.

The formula

P(a)=(a+ba)(c+dc)(na+c) (Fisher’s exact test on the 2 × 2 table)P(a) = \dfrac{\binom{a+b}{a}\binom{c+d}{c}}{\binom{n}{a+c}}\ \text{(Fisher's exact test on the 2 × 2 table)}

With your numbers

a=14, b=16, c=13, d=27a = 14,\ b = 16,\ c = 13,\ d = 27
a, ba,\ b
nonsynonymous: fixed, polymorphic
c, dc,\ d
synonymous: fixed, polymorphic

The verdict

a = 14, p = .321, OR = 1.80

p > α = .050: compatible with H₀

Effect size: conditional MLE odds ratio OR = 1.802

An excess of nonsynonymous fixed differences points to adaptive evolution. Rows: nonsynonymous, synonymous; columns: fixed, polymorphic, so this bench's odds ratio is (D_N·P_S)/(P_N·D_S), the reference's orientation. CodeSplash's headline odds ratio is the reciprocal, (P_N·D_S)/(P_S·D_N), oriented like the neutrality index (or_cmle); the reference-oriented ratio is reported as or_reference. Which tail a one-sided Fisher p-value tests depends on this orientation, and the result card says which.

Statistic
14.000
p-value
0.3213
McDonald–Kreitman test on a 2 × 2 table of 70 counts: a = 14, p = .321, OR = 1.80. The p-value is above α = .050, so the data are compatible with H0.

McDonald–Kreitman test on a 2 × 2 table of 70 counts: a = 14, p = .321, OR = 1.80. The p-value is above α = .050, so the data are compatible with H₀.

09

Check your understanding

Checkpoint

Check yourself

A region gives a strongly negative Tajima's D. What can you conclude?

Show the answer

Answer: c

Demography and selection can give the same signal, and DD has no standard normal reference. Calibrate it by simulation under a stated model.

Check yourself

A table has DN=20D_N = 20, DS=20D_S = 20, PN=10P_N = 10, PS=20P_S = 20. Compute α=1−(DSPN)/(DNPS)\alpha = 1 - (D_S P_N)/(D_N P_S).

Show the answer

Answer: 0.5

1−(20×10)/(20×20)=1−0.5=0.51 - (20 \times 10)/(20 \times 20) = 1 - 0.5 = 0.5. This suggests that about half of the fixed protein changes could be adaptive, if the model's assumptions hold.

Check yourself

Why can weakly harmful variants bias the McDonald–Kreitman test?

Show the answer

Answer: b

Extra nonsynonymous polymorphism raises PNP_N relative to DND_N. That can hide real adaptation, or give a negative α\alpha as in this example.

10

Run it in CodeSplash

In the app

Tajima's D and McDonald–Kreitman are CodeSplash methods: Neutrality test (Tajima's D) and McDonald–Kreitman test. Run the guide's examples here, or open one as a notebook or in the Genetics studio to change the data. Genetics methods aren't in Analyze's list.

Tajima's DRecorded · Python and R agreeRecorded 2026-11-17 · 29 values compared
R

Tajima's D = 0.39, S = 8, n = 12, p = .702

Tajima's D
0.3919
π (mean pairwise differences)
2.909
θ_W = S / a₁
2.649
Segregating sites S
8
p (beta)
.702

Plots

Folded site frequency spectrumHow many sites carry the derived allele once, twice, …, and does that match what a constant-size neutral population predicts?
View data
Minor-allele countSites
12
22
31
41
51
61

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 — Tajima's beta distribution doesn't model recombination either; it is an approximation for any region.
  • Random sample of homologous sequences — 12 sequences, 8 sites (0 monomorphic, not counted in S).

Calibrations of D

Referencepp (D lower)p (D higher)
Tajima's beta distribution0.70180.64910.3509

Folded site frequency spectrum

Minor-allele countSites
12
22
31
41
51
61
  • 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.
The exact R script · R 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 dab5344119f05c07
# 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 <- "beta"
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
))
Python

Tajima's D = 0.39, S = 8, n = 12, p = .702

Tajima's D
0.3919
π (mean pairwise differences)
2.909
θ_W = S / a₁
2.649
Segregating sites S
8
p (beta)
.702

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 — Tajima's beta distribution doesn't model recombination either; it is an approximation for any region.
  • Random sample of homologous sequences — 12 sequences, 8 sites (0 monomorphic, not counted in S).

Calibrations of D

Referencepp (D lower)p (D higher)
Tajima's beta distribution0.70180.64910.3509

Folded site frequency spectrum

Minor-allele countSites
12
22
31
41
51
61
  • 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.
The exact Python script · Python 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 dab5344119f05c07
# 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 = "beta"
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,
})
McDonald–Kreitman testRecorded · Python and R agreeRecorded 2026-11-17 · 27 values compared
R

McDonald–Kreitman test, P_N = 12, P_S = 30, D_N = 8, D_S = 40, p = .209, NI = 2.00

Neutrality index NI
2
α (adaptive substitutions)
−1
Direction of selection DoS
−0.1190
p (Fisher's exact test)
.209

Effect size

  • Neutrality index (conditional odds ratio) 1.984 95% CI [0.6510, 6.363]

Assumptions

  • Expected counts ≥ 5 (G and χ²) — Fisher's test conditions on the margins; the smallest expected count is 9.33.
  • Synonymous sites are neutral — Not checkable from counts: strong codon bias would break the yardstick.
  • Few slightly deleterious polymorphisms — NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards.
  • Correct orthology and site classes — Assumed: one outgroup, polymorphic and fixed sites called correctly.

McDonald–Kreitman table

NonsynonymousSynonymous
Polymorphic1230
Fixed840

Tests of the summed table

TestStatisticp
Fisher's exact (two-sided)—0.2094
G-test1.8390.1751
Pearson χ²1.8370.1753
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.
  • Conditional odds ratio 1.984 (95% exact CI 0.651 to 6.363) estimates NI from the table.
  • Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1.
The exact R script · R R version 4.5.1 (2025-06-13)
# McDonald–Kreitman test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.mk 1.1.1 · spec 83168d3002026461
# Dataset: ge_mk_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_mk_test, cs_gen_fisher_2x2 (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_mk_guide.parquet", col_select = c("pn", "ps", "dn", "ds")))
n_input <- nrow(df)
warnings <- list()
research_note <- "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% Counts
cols <- c("pn", "ps", "dn", "ds")
gene_col <- NULL
ok <- stats::complete.cases(df[cols])
if (sum(!ok) > 0) warnings <- c(warnings, sprintf("%d rows had a missing count and were left out.", sum(!ok)))
df <- df[ok, , drop = FALSE]
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, cols)  # infinite values stop the run (registry/errors.yaml)
genes <- if (!is.null(gene_col)) as.character(df[[gene_col]]) else sprintf("row %d", seq_len(nrow(df)))
test <- "fisher"
conf <- 0.95
r <- cs_gen_mk_test(df[[cols[1]]], df[[cols[2]]], df[[cols[3]]], df[[cols[4]]], conf)
p <- switch(test, fisher = r$p_fisher, g = r$p_g, chisq = r$p_chisq)
label <- switch(test, fisher = "Fisher's exact test", g = "G-test", chisq = "Pearson χ² test")
if (nrow(df) > 1) {
  warnings <- c(warnings, sprintf("%d genes: the summed table pools them, which can bias α when genes differ; α across genes (α_TG) weights each gene by its own counts.", nrow(df)))
}

# %% Assumptions
me <- r$min_expected
if (test == "fisher") {
  e_status <- "info"
  e_detail <- sprintf("Fisher's test conditions on the margins; the smallest expected count is %.2f.", me)
} else if (me < 5) {
  e_status <- "warn"
  e_detail <- sprintf("The smallest expected count is %.2f, below 5: prefer Fisher's exact test.", me)
} else {
  e_status <- "pass"
  e_detail <- sprintf("Every expected count is at least 5 (smallest %.2f).", me)
}
ni_high <- !is.na(r$ni) && r$ni > 1
assumptions <- list(
  list(key = "expected_counts", label = "Expected counts ≥ 5 (G and χ²)", status = e_status, detail = e_detail),
  list(key = "neutral_synonymous", label = "Synonymous sites are neutral", status = "info", detail = "Not checkable from counts: strong codon bias would break the yardstick."),
  list(key = "deleterious", label = "Few slightly deleterious polymorphisms", status = if (ni_high) "warn" else "info",
       detail = if (ni_high) "NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards." else
         "Excluding rare polymorphisms (for example below 5–15% frequency) reduces their bias."),
  list(key = "classification", label = "Correct orthology and site classes", status = "info", detail = "Assumed: one outgroup, polymorphic and fixed sites called correctly.")
)

# %% Result
summary <- sprintf("P_N = %s, P_S = %s, D_N = %s, D_S = %s: NI = %.3f, α = %.3f, DoS = %.3f; %s, %s.",
                   format(r$pn), format(r$ps), format(r$dn), format(r$ds), r$ni, r$alpha, r$dos, label, cs_fmt_p(p))
apa <- sprintf("McDonald–Kreitman test, P_N = %s, P_S = %s, D_N = %s, D_S = %s, %s, NI = %s",
               format(r$pn), format(r$ps), format(r$dn), format(r$ds), cs_fmt_p(p), cs_fmt_num(r$ni))
table <- list(list(class = "Polymorphic", nonsynonymous = r$pn, synonymous = r$ps), list(class = "Fixed", nonsynonymous = r$dn, synonymous = r$ds))
gene_rows <- lapply(r$genes, function(x) c(list(gene = genes[x$i + 1]), x[c("pn", "ps", "dn", "ds", "p_fisher", "p_g", "ni", "alpha", "dos")]))
tests <- list(list(test = "Fisher's exact (two-sided)", statistic = NA, p = r$p_fisher),
              list(test = "G-test", statistic = r$g2, p = r$p_g),
              list(test = "Pearson χ²", statistic = r$chi2, p = r$p_chisq))
notes <- list(research_note,
              "NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.",
              sprintf("Conditional odds ratio %.3f (%.0f%% exact CI %.3f to %.3f) estimates NI from the table.", r$or_cmle, 100 * conf, r$or_low, r$or_high),
              "Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1.")
result_values <- c(r[c("pn", "ps", "dn", "ds", "n_genes", "p_fisher", "p_fisher_less", "p_fisher_greater", "or_cmle", "or_low", "or_high",
                       "chi2", "p_chisq", "g2", "p_g", "min_expected", "ni", "alpha", "alpha_tg", "dos")],
                   list(or_reference = 1 / r$ni, or_reference_cmle = 1 / r$or_cmle),  # the reference's fixed-over-polymorphic orientation
                   list(p = p, test = test, gene_p = I(vapply(r$genes, function(x) x$p_fisher, numeric(1))),
                        gene_ni = I(vapply(r$genes, function(x) x$ni, numeric(1))), gene_dos = I(vapply(r$genes, function(x) x$dos, numeric(1)))))
tables <- list(
  list(key = "table", title = "McDonald–Kreitman table",
       columns = list(list(key = "class", label = "", type = "string"), list(key = "nonsynonymous", label = "Nonsynonymous", type = "integer"),
                      list(key = "synonymous", label = "Synonymous", type = "integer")),
       rows = table),
  list(key = "tests", title = "Tests of the summed table",
       columns = list(list(key = "test", label = "Test", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "p")),
       rows = tests)
)
if (length(gene_rows) > 1) {
  tables[[3]] <- list(key = "genes", title = "Each gene",
                      columns = list(list(key = "gene", label = "Gene", type = "string"), list(key = "pn", label = "P_N", type = "integer"), list(key = "ps", label = "P_S", type = "integer"),
                                     list(key = "dn", label = "D_N", type = "integer"), list(key = "ds", label = "D_S", type = "integer"), list(key = "p_fisher", label = "p (Fisher)", type = "p"),
                                     list(key = "p_g", label = "p (G)", type = "p"), list(key = "ni", label = "NI", type = "number"), list(key = "alpha", label = "α", type = "number"),
                                     list(key = "dos", label = "DoS", type = "number")),
                      rows = gene_rows)
}
cs_publish(list(
  method = "genetics.mk",
  methodVersion = "1.1.1",
  title = "McDonald–Kreitman test",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = r$pn + r$ps + r$dn + r$ds,
  summary = summary,
  apa = apa,
  statistics = list(
    list(key = "ni", label = "Neutrality index NI", value = r$ni),
    list(key = "alpha", label = "α (adaptive substitutions)", value = r$alpha),
    list(key = "dos", label = "Direction of selection DoS", value = r$dos),
    list(key = "p", label = sprintf("p (%s)", label), value = p, format = "p")
  ),
  tables = tables,
  effectSizes = list(list(key = "or_cmle", label = "Neutrality index (conditional odds ratio)", value = r$or_cmle, ciLow = r$or_low,
                          ciHigh = r$or_high, ciLevel = conf, method = "Conditional MLE with exact interval")),
  assumptions = assumptions,
  warnings = warnings,
  notes = notes,
  charts = list(),
  values = result_values
))
Python

McDonald–Kreitman test, P_N = 12, P_S = 30, D_N = 8, D_S = 40, p = .209, NI = 2.00

Neutrality index NI
2
α (adaptive substitutions)
−1
Direction of selection DoS
−0.1190
p (Fisher's exact test)
.209

Effect size

  • Neutrality index (conditional odds ratio) 1.984 95% CI [0.6510, 6.363]

Assumptions

  • Expected counts ≥ 5 (G and χ²) — Fisher's test conditions on the margins; the smallest expected count is 9.33.
  • Synonymous sites are neutral — Not checkable from counts: strong codon bias would break the yardstick.
  • Few slightly deleterious polymorphisms — NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards.
  • Correct orthology and site classes — Assumed: one outgroup, polymorphic and fixed sites called correctly.

McDonald–Kreitman table

NonsynonymousSynonymous
Polymorphic1230
Fixed840

Tests of the summed table

TestStatisticp
Fisher's exact (two-sided)—0.2094
G-test1.8390.1751
Pearson χ²1.8370.1753
  • Research use only: not for clinical or diagnostic decisions. Genotypes are personal data.
  • NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.
  • Conditional odds ratio 1.984 (95% exact CI 0.651 to 6.363) estimates NI from the table.
  • Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# McDonald–Kreitman test
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method genetics.mk 1.1.1 · spec 83168d3002026461
# Dataset: ge_mk_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  # McDonald–Kreitman tables, Fisher with conditional OR (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_mk_guide.parquet", columns=["pn", "ps", "dn", "ds"])
n_input = len(df)
warnings = []
research_note = "Research use only: not for clinical or diagnostic decisions. Genotypes are personal data."

# %% Counts
cols = ["pn", "ps", "dn", "ds"]
gene_col = None
ok = df[cols].notna().all(axis=1).to_numpy()
if (~ok).sum():
    warnings.append(f"{int((~ok).sum())} rows had a missing count and were left out.")
df = df[ok].reset_index(drop=True)
if not len(df):
    cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, cols)  # infinite values stop the run (registry/errors.yaml)
genes = [str(v) for v in df[gene_col]] if gene_col else [f"row {i + 1}" for i in range(len(df))]
test = "fisher"
conf = float(0.95)
r = gen.mk_test(*(df[c].to_numpy(dtype=float) for c in cols), conf)
p = {"fisher": r["p_fisher"], "g": r["p_g"], "chisq": r["p_chisq"]}[test]
label = {"fisher": "Fisher's exact test", "g": "G-test", "chisq": "Pearson χ² test"}[test]
if len(df) > 1:
    warnings.append(f"{len(df)} genes: the summed table pools them, which can bias α when genes differ; α across genes (α_TG) weights each gene by its own counts.")

# %% Assumptions
me = r["min_expected"]
if test == "fisher":
    e_status, e_detail = "info", f"Fisher's test conditions on the margins; the smallest expected count is {me:.2f}."
elif me < 5:
    e_status, e_detail = "warn", f"The smallest expected count is {me:.2f}, below 5: prefer Fisher's exact test."
else:
    e_status, e_detail = "pass", f"Every expected count is at least 5 (smallest {me:.2f})."
assumptions = [
    {"key": "expected_counts", "label": "Expected counts ≥ 5 (G and χ²)", "status": e_status, "detail": e_detail},
    {"key": "neutral_synonymous", "label": "Synonymous sites are neutral", "status": "info", "detail": "Not checkable from counts: strong codon bias would break the yardstick."},
    {"key": "deleterious", "label": "Few slightly deleterious polymorphisms", "status": "warn" if r["ni"] > 1 else "info",
     "detail": "NI above 1: an excess of protein-changing polymorphism, the signature of slightly deleterious variants that bias α downwards." if r["ni"] > 1
     else "Excluding rare polymorphisms (for example below 5–15% frequency) reduces their bias."},
    {"key": "classification", "label": "Correct orthology and site classes", "status": "info", "detail": "Assumed: one outgroup, polymorphic and fixed sites called correctly."},
]

# %% Result
summary = (f"P_N = {r['pn']:g}, P_S = {r['ps']:g}, D_N = {r['dn']:g}, D_S = {r['ds']:g}: NI = {r['ni']:.3f}, α = {r['alpha']:.3f}, "
           f"DoS = {r['dos']:.3f}; {label}, {cs.fmt_p(p)}.")
apa = f"McDonald–Kreitman test, P_N = {r['pn']:g}, P_S = {r['ps']:g}, D_N = {r['dn']:g}, D_S = {r['ds']:g}, {cs.fmt_p(p)}, NI = {cs.fmt_num(r['ni'])}"
table = [{"class": "Polymorphic", "nonsynonymous": r["pn"], "synonymous": r["ps"]}, {"class": "Fixed", "nonsynonymous": r["dn"], "synonymous": r["ds"]}]
gene_rows = [{"gene": genes[x["i"]], **{k: x[k] for k in ("pn", "ps", "dn", "ds", "p_fisher", "p_g", "ni", "alpha", "dos")}} for x in r["genes"]]
tests = [{"test": "Fisher's exact (two-sided)", "statistic": None, "p": r["p_fisher"]},
         {"test": "G-test", "statistic": r["g2"], "p": r["p_g"]},
         {"test": "Pearson χ²", "statistic": r["chi2"], "p": r["p_chisq"]}]
notes = [research_note,
         "NI = (P_N/P_S)/(D_N/D_S): above 1 points to slightly deleterious polymorphism, below 1 to adaptive substitution; α = 1 − NI.",
         f"Conditional odds ratio {r['or_cmle']:.3f} ({conf:.0%} exact CI {r['or_low']:.3f} to {r['or_high']:.3f}) estimates NI from the table.",
         "Odds-ratio direction: the headline odds ratio is polymorphic over fixed (NI orientation, (P_N/P_S)/(D_N/D_S)). The reference's MK odds ratio is fixed over polymorphic, its reciprocal: reported as or_reference (sample) and or_reference_cmle (conditional). One-sided Fisher p: 'less' tests NI < 1 (adaptive substitution), 'greater' tests NI > 1."]
values = {k: r[k] for k in ("pn", "ps", "dn", "ds", "n_genes", "p_fisher", "p_fisher_less", "p_fisher_greater", "or_cmle", "or_low", "or_high",
                            "chi2", "p_chisq", "g2", "p_g", "min_expected", "ni", "alpha", "alpha_tg", "dos")}
def _inv(v):
    """Reciprocal with 0 ↔ ∞ (the reference's fixed-over-polymorphic orientation)."""
    return math.inf if v == 0 else (0.0 if math.isinf(v) else 1.0 / v)


values.update({"or_reference": _inv(r["ni"]), "or_reference_cmle": _inv(r["or_cmle"])})
values.update({"p": p, "test": test, "gene_p": [x["p_fisher"] for x in r["genes"]], "gene_ni": [x["ni"] for x in r["genes"]],
               "gene_dos": [x["dos"] for x in r["genes"]]})
cs.publish({
    "method": "genetics.mk",
    "methodVersion": "1.1.1",
    "title": "McDonald–Kreitman test",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": int(r["pn"] + r["ps"] + r["dn"] + r["ds"]),
    "summary": summary,
    "apa": apa,
    "statistics": [
        {"key": "ni", "label": "Neutrality index NI", "value": r["ni"]},
        {"key": "alpha", "label": "α (adaptive substitutions)", "value": r["alpha"]},
        {"key": "dos", "label": "Direction of selection DoS", "value": r["dos"]},
        {"key": "p", "label": f"p ({label})", "value": p, "format": "p"},
    ],
    "tables": [
        {"key": "table", "title": "McDonald–Kreitman table",
         "columns": [{"key": "class", "label": "", "type": "string"}, {"key": "nonsynonymous", "label": "Nonsynonymous", "type": "integer"},
                     {"key": "synonymous", "label": "Synonymous", "type": "integer"}],
         "rows": table},
        {"key": "tests", "title": "Tests of the summed table",
         "columns": [{"key": "test", "label": "Test", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "p"}],
         "rows": tests},
    ] + ([{"key": "genes", "title": "Each gene",
           "columns": [{"key": "gene", "label": "Gene", "type": "string"}, {"key": "pn", "label": "P_N", "type": "integer"}, {"key": "ps", "label": "P_S", "type": "integer"},
                       {"key": "dn", "label": "D_N", "type": "integer"}, {"key": "ds", "label": "D_S", "type": "integer"}, {"key": "p_fisher", "label": "p (Fisher)", "type": "p"},
                       {"key": "p_g", "label": "p (G)", "type": "p"}, {"key": "ni", "label": "NI", "type": "number"}, {"key": "alpha", "label": "α", "type": "number"},
                       {"key": "dos", "label": "DoS", "type": "number"}],
           "rows": gene_rows}] if len(gene_rows) > 1 else []),
    "effectSizes": [{"key": "or_cmle", "label": "Neutrality index (conditional odds ratio)", "value": r["or_cmle"], "ciLow": r["or_low"],
                     "ciHigh": r["or_high"], "ciLevel": conf, "method": "Conditional MLE with exact interval"}],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": notes,
    "charts": [],
    "values": values,
})

This script reproduces both outputs. Replace the counts with your own.

Python
import numpy as np
from scipy import stats

n = 12
counts = np.array([1, 2, 3, 4, 2, 1, 5, 6])
S = len(counts)
pi = np.sum(2 * counts * (n - counts) / (n * (n - 1)))

j = np.arange(1, n)
a1, a2 = np.sum(1 / j), np.sum(1 / j**2)
b1 = (n + 1) / (3 * (n - 1))
b2 = 2 * (n * n + n + 3) / (9 * n * (n - 1))
c1 = b1 - 1 / a1
c2 = b2 - (n + 2) / (a1 * n) + a2 / a1**2
e1, e2 = c1 / a1, c2 / (a1**2 + a2)
print((pi - S / a1) / np.sqrt(e1 * S + e2 * S * (S - 1)), pi)

table = np.array([[12, 30], [8, 40]])    # polymorphic, then fixed
print(stats.fisher_exact(table))
R
n <- 12
counts <- c(1, 2, 3, 4, 2, 1, 5, 6)
S <- length(counts)
pi <- sum(2 * counts * (n - counts) / (n * (n - 1)))

a1 <- sum(1 / (1:(n - 1))); a2 <- sum(1 / (1:(n - 1))^2)
b1 <- (n + 1) / (3 * (n - 1))
b2 <- 2 * (n^2 + n + 3) / (9 * n * (n - 1))
c1 <- b1 - 1 / a1
c2 <- b2 - (n + 2) / (a1 * n) + a2 / a1^2
e1 <- c1 / a1; e2 <- c2 / (a1^2 + a2)
c((pi - S / a1) / sqrt(e1 * S + e2 * S * (S - 1)), pi)

tab <- matrix(c(12, 30, 8, 40), 2, byrow = TRUE,
              dimnames = list(c("polymorphic", "fixed"), c("nonsynonymous", "synonymous")))
fisher.test(tab)
11

Recap

Recap
  • Tajima's D compares two estimates of variation; negative means extra rare variants.
  • DD needs simulation under a stated demography for a p-value.
  • McDonald–Kreitman compares protein and silent changes within and between species.
  • Demography can mimic selection in both, so neither test names a cause.

Concepts in this lesson