Plot complete simulated association families
A regional display does not change the number of tests already performed. Each phenotype and model in this section has one complete family containing the deduplicated sparse autosomal and dense chromosome 22 union. A marker that belongs to both panels contributes one test.
The six families remain separate. Their Bonferroni threshold is 0.05 / m,
where m is the full union size. Each language also calculates
Benjamini-Hochberg adjustments over the same complete family. Combining calls
across those six summaries would not produce one jointly controlled discovery
list.
Bonferroni does not require independent markers when each null p-value is valid. The usual FDR interpretation of BH also requires its dependence assumptions. The code reports both declared procedures without treating correlated markers as independent biological discoveries.
Preserve the complete p-value vectors
Section titled “Preserve the complete p-value vectors”PLINK writes negative base-10 logarithms of p-values. The examples keep that representation through the plots and BH calculation, so an extremely small simulated p-value does not become a plotted zero after numeric underflow. The calculation checks ordinary BH implementations wherever their output remains representable.
Every Manhattan and Q-Q panel includes every tested variant. Chromosome 22 has denser coverage than the other chromosomes because the universe was chosen for this tutorial. The Q-Q diagonal describes uniform marginal p-values under an appropriate null; correlation among markers does not make these points independent observations.
The genotype data come from Byrska-Bishop and colleagues and NYGC. The collection acknowledgment credits Coriell samples and NHGRI grants 3UM1HG008901-03S1 and 3UM1HG008901-04S2. This lesson calculates its own teaching summaries from the declared source selection.
source("/shared/population_utils.R")accepted <- ReadAnalysis()variants <- ReadTable("variant_universe.tsv.gz")traits <- c("noise", "structure", "genotype_effect")models <- c("unadjusted", "adjusted")family_size <- nrow(variants)threshold <- -log10(0.05 / family_size)results <- list()summary <- data.frame()dir.create("outputs", showWarnings = FALSE)for (trait in traits) { for (model in models) { name <- paste(trait, model, sep = "_") data <- ReadTable(paste0(name, ".tsv.gz")) stopifnot(identical(data$ID, variants$ID), !anyDuplicated(data$ID)) stopifnot(identical(data$A1, variants$ALT)) stopifnot(all(data$ERRCODE == "."), all(data$TEST == "ADD")) adjusted_log <- BhLog10(data$NEG_LOG10_P) ordinary <- p.adjust(10^(-data$NEG_LOG10_P), method = "BH") represented <- ordinary > 1e-300 stopifnot(max(abs(adjusted_log[represented] + log10(ordinary[represented]))) < 1e-8) adjusted <- data.frame(ID = data$ID, negative_log_p = data$NEG_LOG10_P, negative_log_bh = adjusted_log, bonferroni = as.integer( data$NEG_LOG10_P >= threshold), bh = as.integer(adjusted_log >= -log10(0.05))) path <- paste0("outputs/", name, "_adjustments_r.tsv.gz") connection <- gzfile(path, "wt") write.table(adjusted, connection, sep = "\t", row.names = FALSE, quote = FALSE) close(connection) summary <- rbind(summary, data.frame(phenotype = trait, model = model, tests = family_size, bonferroni = sum(adjusted$bonferroni), bh = sum(adjusted$bh))) results[[name]] <- data[c("ID", "CHROM", "POS", "NEG_LOG10_P")] }}write.table(summary, "outputs/family_summary_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)lengths <- c(248956422, 242193529, 198295559, 190214555, 181538259, 170805979, 159345973, 145138636, 138394717, 133797422, 135086622, 133275309, 114364328, 107043718, 101991189, 90338345, 83257441, 80373285, 58617616, 64444167, 46709983, 50818468)offsets <- c(0, cumsum(lengths)[1:21])positions <- variants$POS + offsets[variants$CHROM]centers <- offsets + lengths / 2colors <- c("#167c80", "#425574")[(variants$CHROM %% 2) + 1]png("outputs/manhattan_r.png", width = 1800, height = 1550, res = 130)par(mfrow = c(3, 2), mar = c(4, 4, 3, 1))for (trait in traits) { for (model in models) { data <- results[[paste(trait, model, sep = "_")]] plot(positions, data$NEG_LOG10_P, pch = 16, cex = 0.2, col = colors, xaxt = "n", xlab = "Chromosome", ylab = "Negative log10 p", main = paste("Simulated", trait, model), ylim = c(0, max(threshold, data$NEG_LOG10_P) * 1.05)) axis(1, at = centers, labels = 1:22, cex.axis = 0.7, las = 2) abline(h = threshold, lty = 2, col = "#9e4f22") }}invisible(dev.off())expected <- -log10((seq_len(family_size) - 0.5) / family_size)png("outputs/qq_r.png", width = 1800, height = 1550, res = 130)par(mfrow = c(3, 2), mar = c(4, 4, 3, 1))for (trait in traits) { for (model in models) { data <- results[[paste(trait, model, sep = "_")]] observed <- sort(data$NEG_LOG10_P, decreasing = TRUE) plot(expected, observed, pch = 16, cex = 0.2, col = "#167c80", xlab = "Expected negative log10 p", ylab = "Observed negative log10 p", main = paste("Simulated", trait, model)) abline(0, 1, col = "#9e4f22", lty = 2) }}invisible(dev.off())region <- MarkerIds("regional_markers.txt")generating <- accepted$panel$generating_variantprimary_ld <- ReadTable("regional_ld.vcor")other <- ifelse(primary_ld$ID_A == generating, primary_ld$ID_B, primary_ld$ID_A)ld <- c(setNames(primary_ld$UNPHASED_R2, other), setNames(1, generating))stopifnot(setequal(names(ld), region), !anyDuplicated(names(ld)))palette <- c("#b9bfc7", "#6ea9c4", "#46a59a", "#d59b36", "#b9493f")labels <- c("0.0 to 0.2", "0.2 to 0.4", "0.4 to 0.6", "0.6 to 0.8", "0.8 to 1.0")png("outputs/regional_r.png", width = 1600, height = 760, res = 130)par(mfrow = c(1, 2), mar = c(4, 4, 3, 1))for (model in models) { data <- results[[paste("genotype_effect", model, sep = "_")]] data <- data[match(region, data$ID), ] bin <- pmin(5, floor(pmax(0, ld[data$ID]) * 5) + 1) plot(data$POS / 1e6, data$NEG_LOG10_P, col = palette[bin], pch = 16, cex = 0.55, xlab = "GRCh38 chromosome 22 position, Mb", ylab = "Negative log10 p", main = paste("Simulated genotype effect,", model), ylim = c(0, max(threshold, data$NEG_LOG10_P) * 1.05)) abline(h = threshold, lty = 2, col = "#9e4f22") anchor <- data[data$ID == generating, ] points(anchor$POS / 1e6, anchor$NEG_LOG10_P, pch = 8, cex = 1.5) legend_position <- if (model == "unadjusted") "topleft" else "topright" legend(legend_position, labels, col = palette, pch = 16, bty = "n", cex = 0.7, title = "Dosage r squared")}invisible(dev.off())metrics <- list(families = nrow(summary), tests_per_family = family_size, total_model_tests = sum(summary$tests), bonferroni_calls_across_separate_families = sum(summary$bonferroni), bh_calls_across_separate_families = sum(summary$bh), negative_log_bonferroni = threshold)WriteMetrics(metrics)cat(sprintf("Each of the six families contains %d tests.\n", family_size))cat(sprintf("The complete-family Bonferroni threshold is %.9g.\n", 0.05 / family_size))print(summary, row.names = FALSE)cat("The six summaries do not define one combined discovery list.\n")Each of the six families contains 128859 tests.The complete-family Bonferroni threshold is 3.88021015e-07. phenotype model tests bonferroni bh noise unadjusted 128859 0 0 noise adjusted 128859 0 0 structure unadjusted 128859 95151 115058 structure adjusted 128859 0 0 genotype_effect unadjusted 128859 93287 114460 genotype_effect adjusted 128859 766 1034The six summaries do not define one combined discovery list.
Each panel contains the complete shared universe. The dashed line uses its full-family Bonferroni threshold, and chromosome 22 retains its denser coverage.

The structure and genotype-effect traits have declared non-null mechanisms. Departure from the diagonal cannot be interpreted as technical failure without that model context.

The star marks the frozen generating variant. Colors show dosage LD with that variant, and the horizontal line retains the full family denominator. Correlated points do not establish independent causal effects.
import sys
import matplotlib.pyplot as pltfrom matplotlib.lines import Line2Dimport numpy as npimport pandas as pdfrom statsmodels.stats.multitest import multipletests
sys.path.insert(0, "/shared")import population_utils as population
accepted = population.read_analysis()variants = population.read_table("variant_universe.tsv.gz")traits = ["noise", "structure", "genotype_effect"]models = ["unadjusted", "adjusted"]family_size = len(variants)threshold = -np.log10(0.05 / family_size)results = {}summary = []for trait in traits: for model in models: name = f"{trait}_{model}" data = population.read_table(f"{name}.tsv.gz") assert data["ID"].equals(variants["ID"]) and data["ID"].is_unique assert data["A1"].equals(variants["ALT"]) assert data["ERRCODE"].eq(".").all() and data["TEST"].eq("ADD").all() adjusted_log = population.bh_log10(data["NEG_LOG10_P"]) ordinary = multipletests(np.power(10.0, -data["NEG_LOG10_P"]), method="fdr_bh")[1] represented = ordinary > 1e-300 np.testing.assert_allclose(adjusted_log[represented], -np.log10(ordinary[represented]), atol=1e-8) adjusted = pd.DataFrame(dict( ID=data["ID"], negative_log_p=data["NEG_LOG10_P"], negative_log_bh=adjusted_log, bonferroni=data["NEG_LOG10_P"].ge(threshold).astype(int), bh=(adjusted_log >= -np.log10(0.05)).astype(int), )) population.compare_table(adjusted, f"outputs/{name}_adjustments_r.tsv.gz", ["ID"], ["negative_log_p", "negative_log_bh", "bonferroni", "bh"]) summary.append(dict(phenotype=trait, model=model, tests=family_size, bonferroni=int(adjusted["bonferroni"].sum()), bh=int(adjusted["bh"].sum()))) results[name] = data[["ID", "CHROM", "POS", "NEG_LOG10_P"]]summary = pd.DataFrame(summary)population.compare_table(summary, "outputs/family_summary_r.tsv", ["phenotype", "model"], ["tests", "bonferroni", "bh"], 0)lengths = np.array([ 248956422, 242193529, 198295559, 190214555, 181538259, 170805979, 159345973, 145138636, 138394717, 133797422, 135086622, 133275309, 114364328, 107043718, 101991189, 90338345, 83257441, 80373285, 58617616, 64444167, 46709983, 50818468,])offsets = np.r_[0, np.cumsum(lengths)[:-1]]positions = variants["POS"] + offsets[variants["CHROM"] - 1]centers = offsets + lengths / 2colors = np.array(["#167c80", "#425574"])[variants["CHROM"] % 2]fig, axes = plt.subplots(3, 2, figsize=(14, 12), constrained_layout=True)for row, trait in enumerate(traits): for column, model in enumerate(models): data = results[f"{trait}_{model}"] ax = axes[row, column] ax.scatter(positions, data["NEG_LOG10_P"], s=1, c=colors) ax.axhline(threshold, linestyle="--", color="#9e4f22") ax.set_xticks(centers, np.arange(1, 23), fontsize=7, rotation=90) ax.set(xlabel="Chromosome", ylabel="Negative log10 p", title=f"Simulated {trait} {model}", ylim=(0, max(threshold, data["NEG_LOG10_P"].max()) * 1.05))fig.savefig("outputs/manhattan_python.png", dpi=150)plt.close(fig)expected = -np.log10((np.arange(1, family_size + 1) - 0.5) / family_size)fig, axes = plt.subplots(3, 2, figsize=(14, 12), constrained_layout=True)for row, trait in enumerate(traits): for column, model in enumerate(models): observed = np.sort(results[f"{trait}_{model}"]["NEG_LOG10_P"])[::-1] ax = axes[row, column] ax.scatter(expected, observed, s=1, color="#167c80") ax.plot([0, expected.max()], [0, expected.max()], linestyle="--", color="#9e4f22") ax.set(xlabel="Expected negative log10 p", ylabel="Observed negative log10 p", title=f"Simulated {trait} {model}")fig.savefig("outputs/qq_python.png", dpi=150)plt.close(fig)region = population.marker_ids("regional_markers.txt")generating = accepted["panel"]["generating_variant"]primary_ld = population.read_table("regional_ld.vcor")other = np.where(primary_ld["ID_A"].eq(generating), primary_ld["ID_B"], primary_ld["ID_A"])ld = pd.Series(primary_ld["UNPHASED_R2"].to_numpy(), index=other)ld.loc[generating] = 1.0assert set(ld.index) == set(region) and ld.index.is_uniquepalette = np.array(["#b9bfc7", "#6ea9c4", "#46a59a", "#d59b36", "#b9493f"])labels = ["0.0 to 0.2", "0.2 to 0.4", "0.4 to 0.6", "0.6 to 0.8", "0.8 to 1.0"]handles = [Line2D([0], [0], marker="o", linestyle="", color=color, label=label) for color, label in zip(palette, labels, strict=True)]fig, axes = plt.subplots(1, 2, figsize=(13, 6), constrained_layout=True)for ax, model in zip(axes, models, strict=True): data = results[f"genotype_effect_{model}"].set_index("ID").loc[region] bins = np.minimum(4, np.floor(np.maximum(0, ld.loc[data.index]) * 5)) ax.scatter(data["POS"] / 1e6, data["NEG_LOG10_P"], color=palette[bins.astype(int)], s=7) ax.axhline(threshold, linestyle="--", color="#9e4f22") anchor = data.loc[generating] ax.scatter(anchor["POS"] / 1e6, anchor["NEG_LOG10_P"], marker="*", color="black", s=110) ax.set(xlabel="GRCh38 chromosome 22 position, Mb", ylabel="Negative log10 p", title=f"Simulated genotype effect, {model}", ylim=(0, max(threshold, data["NEG_LOG10_P"].max()) * 1.05)) ax.legend(handles=handles, title="Dosage r squared", fontsize=7)fig.savefig("outputs/regional_python.png", dpi=160)plt.close(fig)metrics = dict(families=len(summary), tests_per_family=family_size, total_model_tests=int(summary["tests"].sum()), bonferroni_calls_across_separate_families=int( summary["bonferroni"].sum()), bh_calls_across_separate_families=int(summary["bh"].sum()), negative_log_bonferroni=float(threshold))population.write_metrics(metrics)print(f"Each of the six families contains {family_size} tests.")print(f"The complete-family Bonferroni threshold is {0.05 / family_size:.9g}.")print(summary.to_string(index=False))print("The six summaries do not define one combined discovery list.")Each of the six families contains 128859 tests.The complete-family Bonferroni threshold is 3.88021015e-07. phenotype model tests bonferroni bh noise unadjusted 128859 0 0 noise adjusted 128859 0 0 structure unadjusted 128859 95151 115058 structure adjusted 128859 0 0genotype_effect unadjusted 128859 93287 114460genotype_effect adjusted 128859 766 1034The six summaries do not define one combined discovery list.
The paired checks compare every raw and adjusted logarithmic p-value, with exact agreement on family membership and threshold calls.

The expected coordinates use all m ordered tests. Neither language selects
only the strongest associations for these panels.

The regional window describes part of the same tested universe. Its LD colors provide correlation context, and its simulated peak is not a biological discovery.
Interpret the specified simulation
Section titled “Interpret the specified simulation”The adjusted structure family has no Bonferroni or BH findings in this run. Its phenotype was generated from the same PC1 that the adjusted model includes. This result verifies the specified simulation.
The adjusted genotype-effect family has many correlated findings around the single generating marker. Those calls do not count independent causal variants. The regional display retains the threshold from all 128,859 tests, and its LD colors describe correlations in the retained people.
The interpretation lesson explains why agreement between these implementations is computational verification rather than independent replication.
Further reading
Section titled “Further reading”-
The reference distinguishes family error control from false discovery control and identifies their dependence assumptions. Its complete-family argument explains why a regional display must retain the original test count.
-
The manual documents logarithmic probability output and genotype model fields. Those fields preserve extremely small simulated probabilities and the identity of each tested allele.