Fit the declared simulated association models
The genotype calls describe real people, but the outcomes in this lesson are simulated. The workflow fixes the sample list, test universe, chromosome 22 generating variant, ALT dosage, and PCA covariates before it creates an outcome. An association result cannot change those choices.
The simulation uses NumPy’s PCG64 generator with seed 20261031. Its three independent standard-normal residual columns remain saved with the complete phenotype vectors. R reads the same realized values.
| Simulated trait | Generating equation |
|---|---|
| Noise | The outcome equals its independent residual. |
| Structure | The outcome equals 1.5 times standardized PC1 plus its independent residual. |
| Genotype effect | The outcome equals 1.5 times standardized PC1 plus 0.8 times centered ALT dosage plus its independent residual. |
The intercept absorbs the centering of the generating dosage. Its declared genotype coefficient is 0.8 outcome units per ALT allele after the structure term is included.
Preserve the fitted model
Section titled “Preserve the fitted model”Each trait has an unadjusted model with an intercept and ALT dosage, and an
adjusted model that also contains the ten saved standardized PCs. PLINK uses
--glm omit-ref, so A1
must equal ALT for every tested biallelic marker.
No sex covariate is added to these autosomal quantitative models.
The scan contains six separate test families with the same complete variant universe. The code below verifies those identities, then independently refits four markers selected before association: the generating marker, the neighboring eligible markers on either side, and the first sparse chromosome 1 marker.
R and Python compare the complete sample list, effect allele, coefficient,
standard error, t statistic, and p-value. PLINK prints rounded results, so its
numeric comparison allows relative error of 5e-6 and absolute error of 5e-8.
The independent R and Python fits agree within 1e-8. Logarithmic p-values
preserve signals smaller than ordinary floating-point p-values can represent.
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()phenotypes <- ReadTable("simulated_phenotypes.tsv")covariates <- ReadTable("covariates.tsv")noise <- ReadTable("simulation_noise.tsv")dosage <- ReadTable("regional_dosages.tsv.gz")variants <- ReadTable("variant_universe.tsv.gz")markers <- MarkerIds("refit_markers.txt")generating <- accepted$panel$generating_variantstopifnot(identical(phenotypes$IID, dosage$IID))stopifnot(identical(phenotypes$IID, covariates$IID))stopifnot(identical(phenotypes$IID, noise$IID))centered_dosage <- dosage[[generating]] - mean(dosage[[generating]])stopifnot(max(abs(phenotypes$noise - noise$epsilon_noise)) < 1e-12)stopifnot(max(abs(phenotypes$structure - 1.5 * covariates$PC1 - noise$epsilon_structure)) < 1e-12)stopifnot(max(abs(phenotypes$genotype_effect - 1.5 * covariates$PC1 - 0.8 * centered_dosage - noise$epsilon_effect)) < 1e-12)traits <- c("noise", "structure", "genotype_effect")pc_names <- paste0("PC", seq_len(10))refits <- data.frame()for (trait in traits) { for (model in c("unadjusted", "adjusted")) { primary <- ReadTable(paste0(trait, "_", model, ".tsv.gz")) stopifnot(identical(primary$ID, variants$ID)) stopifnot(identical(primary$A1, variants$ALT)) stopifnot(all(primary$OBS_CT == nrow(phenotypes))) stopifnot(all(primary$TEST == "ADD"), all(primary$ERRCODE == ".")) for (marker in markers) { data <- data.frame(phenotype = phenotypes[[trait]], ALT_DOSAGE = dosage[[marker]]) terms <- "ALT_DOSAGE" if (model == "adjusted") { data <- cbind(data, covariates[pc_names]) terms <- c(terms, pc_names) } formula <- reformulate(terms, response = "phenotype") fit <- lm(formula, data = data, na.action = na.fail) stopifnot(fit$rank == length(terms) + 1) coefficients <- summary(fit)$coefficients["ALT_DOSAGE", ] negative_log_p <- -(log(2) + pt(abs(coefficients[3]), fit$df.residual, lower.tail = FALSE, log.p = TRUE)) / log(10) source <- primary[match(marker, primary$ID), ] calculated <- c(coefficients[1:3], negative_log_p) reference <- unlist(source[c("BETA", "SE", "T_STAT", "NEG_LOG10_P")]) stopifnot(all(abs(calculated - reference) < 5e-6 * abs(calculated) + 5e-8)) critical <- qt(0.975, fit$df.residual) refits <- rbind(refits, data.frame( phenotype = trait, model = model, ID = marker, effect_allele = source$A1, samples = nobs(fit), beta = unname(coefficients[1]), se = unname(coefficients[2]), t_statistic = unname(coefficients[3]), negative_log_p = negative_log_p, lower = coefficients[1] - critical * coefficients[2], upper = coefficients[1] + critical * coefficients[2] )) } }}dir.create("outputs", showWarnings = FALSE)write.table(refits, "outputs/refits_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)selected <- refits[refits$ID == generating, ]row_position <- match(selected$phenotype, traits)offset <- ifelse(selected$model == "adjusted", 0.12, -0.12)colors <- ifelse(selected$model == "adjusted", "#167c80", "#9e4f22")png("outputs/coefficients_r.png", width = 1200, height = 760, res = 130)par(mar = c(5, 8, 4, 1))plot(selected$beta, row_position + offset, xlim = range(c(selected$lower, selected$upper, 0, 0.8)), ylim = c(0.5, 3.5), axes = FALSE, pch = 16, col = colors, xlab = "Effect per ALT allele, simulated outcome units", ylab = "", main = "The frozen generating variant", sub = generating)segments(selected$lower, row_position + offset, selected$upper, row_position + offset, col = colors)axis(1)axis(2, at = 1:3, labels = c("Noise", "Structure", "Genotype effect"), las = 1)abline(v = 0, lty = 2, col = "#969ca3")points(c(0, 0, 0.8), 1:3, pch = 18, cex = 1.2)legend("right", c("Unadjusted", "Adjusted", "Generating coefficient"), col = c("#9e4f22", "#167c80", "black"), pch = c(16, 16, 18), bty = "n")invisible(dev.off())metrics <- list(people = nrow(phenotypes), families = 6, refitted_markers = length(markers), refits = nrow(refits), total_tests = 6 * nrow(variants))WriteMetrics(metrics)cat(sprintf("The independent comparison checks %d complete model fits.\n", nrow(refits)))cat(sprintf("All six scan families contain the same %d variants.\n", nrow(variants)))print(selected[c("phenotype", "model", "beta", "se")], row.names = FALSE, digits = 6)The independent comparison checks 24 complete model fits.All six scan families contain the same 128859 variants. phenotype model beta se noise unadjusted -0.0118243 0.0322667 noise adjusted -0.0147871 0.0334408 structure unadjusted -0.3607456 0.0568992 structure adjusted -0.0154383 0.0326684 genotype_effect unadjusted 0.4539248 0.0575133 genotype_effect adjusted 0.7839295 0.0337413
The points show estimates, and the lines show individual 95 percent t intervals. Diamonds mark the declared conditional genotype coefficients. These intervals do not control errors across the complete scan.
import sys
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy.stats import timport statsmodels.api as sm
sys.path.insert(0, "/shared")import population_utils as population
accepted = population.read_analysis()phenotypes = population.read_table("simulated_phenotypes.tsv")covariates = population.read_table("covariates.tsv")noise = population.read_table("simulation_noise.tsv")dosage = population.read_table("regional_dosages.tsv.gz")variants = population.read_table("variant_universe.tsv.gz")markers = population.marker_ids("refit_markers.txt")generating = accepted["panel"]["generating_variant"]for data in [covariates, noise, dosage]: assert data["IID"].tolist() == phenotypes["IID"].tolist()centered_dosage = dosage[generating] - dosage[generating].mean()generator = np.random.Generator(np.random.PCG64(20261031))generated_noise = generator.normal(size=(len(phenotypes), 3))np.testing.assert_allclose(generated_noise, noise.iloc[:, 1:], atol=1e-14)np.testing.assert_allclose(phenotypes["noise"], noise["epsilon_noise"])np.testing.assert_allclose(phenotypes["structure"], 1.5 * covariates["PC1"] + noise["epsilon_structure"])np.testing.assert_allclose(phenotypes["genotype_effect"], 1.5 * covariates["PC1"] + 0.8 * centered_dosage + noise["epsilon_effect"])traits = ["noise", "structure", "genotype_effect"]pc_names = [f"PC{index}" for index in range(1, 11)]refits = []for trait in traits: for model in ["unadjusted", "adjusted"]: primary = population.read_table(f"{trait}_{model}.tsv.gz") assert primary["ID"].equals(variants["ID"]) assert primary["A1"].equals(variants["ALT"]) assert primary["OBS_CT"].eq(len(phenotypes)).all() assert primary["TEST"].eq("ADD").all() assert primary["ERRCODE"].eq(".").all() for marker in markers: matrix = pd.DataFrame(dict(intercept=1.0, ALT_DOSAGE=dosage[marker])) if model == "adjusted": matrix = pd.concat([matrix, covariates[pc_names]], axis=1) assert np.linalg.matrix_rank(matrix) == matrix.shape[1] fit = sm.OLS(phenotypes[trait], matrix, missing="raise").fit() beta = float(fit.params["ALT_DOSAGE"]) standard_error = float(fit.bse["ALT_DOSAGE"]) statistic = float(fit.tvalues["ALT_DOSAGE"]) negative_log_p = population.student_t_log_p(statistic, fit.df_resid) source = primary.loc[primary["ID"].eq(marker)].iloc[0] calculated = [beta, standard_error, statistic, negative_log_p] reference = source[["BETA", "SE", "T_STAT", "NEG_LOG10_P"]] np.testing.assert_allclose(reference.to_numpy(dtype=float), calculated, rtol=5e-6, atol=5e-8) critical = t.ppf(0.975, fit.df_resid) refits.append(dict( phenotype=trait, model=model, ID=marker, effect_allele=source["A1"], samples=int(fit.nobs), beta=beta, se=standard_error, t_statistic=statistic, negative_log_p=negative_log_p, lower=beta - critical * standard_error, upper=beta + critical * standard_error, ))refits = pd.DataFrame(refits)population.compare_table(refits, "outputs/refits_r.tsv", ["phenotype", "model", "ID", "effect_allele"], ["samples", "beta", "se", "t_statistic", "negative_log_p", "lower", "upper"])selected = refits.loc[refits["ID"].eq(generating)]fig, ax = plt.subplots(figsize=(10, 6))for model, color, offset in [("unadjusted", "#9e4f22", -0.12), ("adjusted", "#167c80", 0.12)]: subset = selected.loc[selected["model"].eq(model)] positions = [traits.index(trait) + offset for trait in subset["phenotype"]] error = np.vstack([subset["beta"] - subset["lower"], subset["upper"] - subset["beta"]]) ax.errorbar(subset["beta"], positions, xerr=error, fmt="o", color=color, label=model.capitalize())ax.scatter([0, 0, 0.8], [0, 1, 2], marker="D", color="black", label="Generating coefficient")ax.axvline(0, linestyle="--", color="#969ca3")ax.set_yticks([0, 1, 2], ["Noise", "Structure", "Genotype effect"])ax.set(xlabel="Effect per ALT allele, simulated outcome units", title=f"The frozen generating variant\n{generating}")ax.legend(loc="center right")fig.savefig("outputs/coefficients_python.png", dpi=160, bbox_inches="tight")plt.close(fig)metrics = dict(people=len(phenotypes), families=6, refitted_markers=len(markers), refits=len(refits), total_tests=6 * len(variants))population.write_metrics(metrics)print(f"The independent comparison checks {len(refits)} complete model fits.")print(f"All six scan families contain the same {len(variants)} variants.")print(selected[["phenotype", "model", "beta", "se"]].to_string(index=False))The independent comparison checks 24 complete model fits.All six scan families contain the same 128859 variants. phenotype model beta se noise unadjusted -0.011824 0.032267 noise adjusted -0.014787 0.033441 structure unadjusted -0.360746 0.056899 structure adjusted -0.015438 0.032668genotype_effect unadjusted 0.453925 0.057513genotype_effect adjusted 0.783929 0.033741
Both languages fit the same sample rows and ALT allele. The figure describes the declared simulation; none of its coefficients estimates a clinical effect.
The association figures apply error control over each complete family and preserve that denominator in regional displays.
Further reading
Section titled “Further reading”-
PLINK quantitative association models
The manual specifies the genotype term, intercept, covariates, and omit-ref convention. These definitions identify the exact ALT dosage model that both languages refit.
-
The equation expresses the incomplete beta function through a hypergeometric function. The Python helper cites it for the logarithmic Student t tail when ordinary probabilities underflow.