Appendix 3.A: Simulation code
This appendix lists the code for the simulation check in Section 3.6.1. Running the following command from the repository root regenerates Table 3.1 and Figure 3.19:
python3 figures/scripts/drift_simulation.py
The code requires Python 3 with NumPy and Matplotlib. The random seed is fixed, so every run produces the same values. The helper module common.py, listed second, sets only the fonts and colours of the figures.
figures/scripts/drift_simulation.py
"""Simulation check of the through-time equations in Chapter 3, Section 3.6.
Scenario A satisfies every assumption of the drift-share derivation; scenario B
adds genetic bias (M-bar = 0.5 G-bar + U) so that the covariance terms matter.
Run from the repository root:
python3 figures/scripts/drift_simulation.py
Writes figures/drift-simulation.pdf and figures/drift-simulation-table.tex.
"""
from itertools import combinations
import matplotlib.pyplot as plt
import numpy as np
from common import COLORS, FIGURES, ROOT, minus, setup
SEED = 20261130
TIMES = 1_000_001 # consecutive pairs of time points -> one million drifts
HALF_WIDTH = 0.025 # drift-size bins are centre +/- this
KEYS = ["G", "$", "M", "eps"]
def simulate(rng, var, bias=0.0):
"""Independent normal component means at each time point; optional M-bar = bias * G-bar + U."""
means = {k: rng.normal(0.0, np.sqrt(var[k]), TIMES) for k in KEYS}
means["M"] = bias * means["G"] + means["M"]
return means
def summary(means):
p = sum(means.values())
var = {k: means[k].var() for k in KEYS}
cov = {(a, b): np.cov(means[a], means[b], bias=True)[0, 1] for a, b in combinations(KEYS, 2)}
full = sum(var.values()) + 2 * sum(cov.values())
dP = np.diff(p)
keep = np.abs(dP) > 1e-6
shares = sum(np.diff(means[k])[keep] / dP[keep] for k in KEYS)
return {
"p": p,
"var_p": p.var(),
"full_error": abs(p.var() - full),
"cov_sum": 2 * sum(cov.values()),
"cov_gm": 2 * cov[("G", "M")],
"ratios": {k: var[k] / p.var() for k in KEYS},
"share_error": np.max(np.abs(shares - 1)),
"dP": np.abs(dP),
"gshare": np.diff(means["G"]) / dP, # unchanged when a pair's order is reversed
"beta": np.cov(means["G"], p, bias=True)[0, 1] / p.var(),
}
def binned(s, centre):
m = np.abs(s["dP"] - centre) <= HALF_WIDTH
return s["gshare"][m].mean(), s["gshare"][m].var(), int(m.sum())
def num(x, digits=3):
return minus(f"{x:.{digits}f}")
def tiny(x):
"""Errors that should be zero up to floating-point rounding."""
if x < 1e-9:
return r"$<10^{-9}$"
mantissa, exponent = f"{x:.1e}".split("e")
return rf"${mantissa} \times 10^{{{int(exponent)}}}$"
def main():
rng = np.random.default_rng(SEED)
a_var = {"G": 0.6, "$": 0.1, "M": 0.2, "eps": 0.1}
b_var = {"G": 0.4, "$": 0.03, "M": 0.04, "eps": 0.03}
a = summary(simulate(rng, a_var))
b = summary(simulate(rng, b_var, bias=0.5))
h2 = a_var["G"]
var_share = lambda d: 2 * h2 * (1 - h2) / d**2
# ---- table
rows = [r"\multicolumn{4}{l}{\textit{Scenario A: independent components}} \\"]
rows.append(rf"$\VAR[\bar P]$ & & 1.000 & {num(a['var_p'])} \\")
rows.append(rf"Full identity, error & \eqref{{eq:time-variance-full}} & 0 & {tiny(a['full_error'])} \\")
rows.append(rf"Sum of covariance shares & \eqref{{eq:time-shares}} & 0 & {num(a['cov_sum'] / a['var_p'])} \\")
for k, label, eq in (("G", r"$h_t^2$", "eq:ht"), ("$", r"$\$_t^2$", "eq:dt"), ("M", r"$m_t^2$", "eq:mt")):
rows.append(rf"{label} & \eqref{{{eq}}} & {num(a_var[k])} & {num(a['ratios'][k])} \\")
rows.append(rf"Drift shares, error in sum & \eqref{{eq:drift-shares}} & 0 & {tiny(a['share_error'])} \\")
for d in (1, 2):
mean, var, n = binned(a, d)
rows.append(rf"Mean genetic share, $\Delta\bar P \approx {d}$ & \eqref{{eq:share-mean}} & {num(h2)} & {num(mean)} \\")
for d in (1, 2):
mean, var, n = binned(a, d)
rows.append(rf"Variance of genetic share, $\Delta\bar P \approx {d}$ & \eqref{{eq:share-var}} & {num(var_share(d))} & {num(var)} \\")
rows.append(r"\hline")
rows.append(r"\multicolumn{4}{l}{\textit{Scenario B: genetic bias, $\bar M = 0.5\,\bar G + U$}} \\")
rows.append(rf"$\VAR[\bar P]$ & & 1.000 & {num(b['var_p'])} \\")
rows.append(rf"Full identity, error & \eqref{{eq:time-variance-full}} & 0 & {tiny(b['full_error'])} \\")
rows.append(rf"$\kappa_{{t,GM}}$ & \eqref{{eq:time-shares}} & 0.400 & {num(b['cov_gm'] / b['var_p'])} \\")
rows.append(rf"Sum of the four variance ratios & \eqref{{eq:time-shares}} & 0.600 & {num(sum(b['ratios'].values()))} \\")
rows.append(rf"$h_t^2$ & \eqref{{eq:ht}} & 0.400 & {num(b['ratios']['G'])} \\")
rows.append(rf"$\beta_t$ & \eqref{{eq:beta}} & 0.600 & {num(b['beta'])} \\")
mean_b, var_b, _ = binned(b, 1)
rows.append(rf"Mean genetic share, $\Delta\bar P \approx 1$ & \eqref{{eq:share-mean}} & 0.600 & {num(mean_b)} \\")
rows.append(rf"Variance of genetic share, $\Delta\bar P \approx 1$ & \eqref{{eq:share-var}} & 0.080 & {num(var_b)} \\")
table = "\n".join([
r"% Generated by figures/scripts/drift_simulation.py; do not edit by hand.",
r"\begin{table}[tbp]",
r" \centering",
r" \small",
r" \begin{tabular}{llrr}",
r" \hline",
r" Quantity & Equation & Predicted & Simulated \\",
r" \hline",
*(" " + row for row in rows),
r" \hline",
r" \end{tabular}",
rf" \caption{{Predicted and simulated values for {f'{TIMES - 1:,}'.replace(',', '{,}')} simulated drifts. Drift-size bins are $\pm {HALF_WIDTH}$ SD wide.}}",
r" \label{tab:drift-simulation}",
r"\end{table}",
"",
])
(FIGURES / "drift-simulation-table.tex").write_text(table)
# ---- figure: scenario A, genetic share against drift size
setup()
centres = np.arange(0.5, 3.01, 0.25)
stats = np.array([binned(a, c)[:2] for c in centres])
grid = np.linspace(0.45, 3.05, 200)
fig, ax = plt.subplots(figsize=(7.2, 4.0))
band = np.sqrt(var_share(grid))
ax.fill_between(grid, h2 - band, h2 + band, color=COLORS["G"], alpha=0.15, lw=0,
label=r"predicted $\pm 1$ SD")
ax.plot(grid, np.full_like(grid, h2), color=COLORS["G"], lw=1.8, label=r"predicted mean $\beta_t = h_t^2 = 0.6$")
ax.errorbar(centres, stats[:, 0], yerr=np.sqrt(stats[:, 1]), fmt="o", color=COLORS["P"], ms=4,
capsize=3, lw=1, label=r"simulated mean $\pm 1$ SD")
ax.set_xlabel(r"Size of drift $|\Delta \bar P|$ (SD of time-point means)")
ax.set_ylabel(r"Genetic share $\Delta \bar G / \Delta \bar P$")
ax.set_xlim(0.4, 3.1)
ax.set_ylim(-0.6, 1.8)
ax.spines[["top", "right"]].set_visible(False)
ax.legend(fontsize=9, frameon=False, loc="upper right")
fig.tight_layout()
fig.savefig(FIGURES / "drift-simulation.pdf")
print("figures/drift-simulation.pdf, figures/drift-simulation-table.tex")
print(f"A: var_p={a['var_p']:.4f} cov_sum={a['cov_sum']:.4f} ratios={ {k: round(v, 4) for k, v in a['ratios'].items()} }")
for c in (1, 2):
print(f"A: dP~{c}: mean, var, n =", binned(a, c), " predicted var", var_share(c))
print(f"B: var_p={b['var_p']:.4f} cov_gm={b['cov_gm']:.4f} ratio_sum={sum(b['ratios'].values()):.4f} beta={b['beta']:.4f} share dP~1 mean={mean_b:.4f} var={var_b:.4f}")
if __name__ == "__main__":
main()
figures/scripts/common.py
"""Shared matplotlib setup for generated manuscript figures."""
from pathlib import Path
import subprocess
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
ROOT = Path(__file__).resolve().parents[2]
FIGURES = ROOT / "figures"
# One colour per model component, shared by every chart in Chapter 3.
COLORS = {"G": "#3b6ea5", "$": "#c0504d", "M": "#d39a2c", "eps": "#8a8a8a", "P": "#2f2f2f"}
def setup():
"""Use the manuscript's New Computer Modern text font when it is available."""
try:
font = subprocess.run(["kpsewhich", "NewCM10-Regular.otf"], capture_output=True, text=True).stdout.strip()
except FileNotFoundError:
font = ""
if font:
font_manager.fontManager.addfont(font)
plt.rcParams["font.family"] = font_manager.FontProperties(fname=font).get_name()
else:
plt.rcParams["font.family"] = "serif"
plt.rcParams.update({"mathtext.fontset": "cm", "font.size": 11, "axes.unicode_minus": True})
def minus(text):
"""Typographic minus signs."""
return text.replace("-", "\u2212")