Measure genotype correlation and prune markers
Nearby variants can carry similar genotype patterns because chromosome segments share a recombination history. Their association statistics can therefore move together. Counting each significant marker as independent biological evidence would ignore that dependence.
This lesson calculates squared correlations between unphased ALT dosage vectors.
PLINK calls the same statistic
--r2-unphased.
The source genotypes retain phase,
but neither calculation below estimates LD from phased haplotype frequencies.
Keep the regional anchor fixed
Section titled “Keep the regional anchor fixed”The generating variant is the first eligible chromosome 22 SNP at or above GRCh38 position 30,000,000, with REF and ALT as lexical tie breakers. The workflow freezes that choice before phenotype generation. The region extends 250 kb on each side and contains only variants from the complete association universe.
Both languages calculate correlation with that anchor for every regional marker and compare PLINK’s report. The heatmap shows the 31 closest eligible markers in coordinate order. Their selection uses distance, not an association result.
The calculations pool the retained people. Their allele frequencies and correlations depend on this cohort’s composition; the displayed LD is not a universal reference for every source population.
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")dosage <- ReadTable("regional_dosages.tsv.gz")region <- MarkerIds("regional_markers.txt")generating <- accepted$panel$generating_variantstopifnot(generating %in% region)genotypes <- as.matrix(dosage[region])stopifnot(all(genotypes %in% 0:2))anchor <- genotypes[, generating]r_squared <- as.numeric(cor(genotypes, anchor)^2)result <- data.frame(ID = region, r_squared = r_squared)primary <- ReadTable("regional_ld.vcor")stopifnot(all(primary$ID_A == generating | primary$ID_B == generating))other <- ifelse(primary$ID_A == generating, primary$ID_B, primary$ID_A)stopifnot(!anyDuplicated(other), setequal(other, setdiff(region, generating)))matched <- result$r_squared[match(other, result$ID)]stopifnot(all(abs(matched - primary$UNPHASED_R2) < 5e-6 * matched + 1e-8))region_variants <- variants[match(region, variants$ID), ]distance <- abs(region_variants$POS - accepted$panel$generating_position)nearest <- order(distance, region_variants$POS, region_variants$REF, region_variants$ALT)[seq_len(31)]nearest <- nearest[order(region_variants$POS[nearest], region_variants$REF[nearest], region_variants$ALT[nearest])]heatmap <- cor(genotypes[, nearest, drop = FALSE])^2dir.create("outputs", showWarnings = FALSE)write.table(result, "outputs/regional_ld_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)write.table(heatmap, "outputs/heatmap_r.tsv", sep = "\t", quote = FALSE, col.names = NA)palette <- hcl.colors(100, "Viridis")png("outputs/linkage_r.png", width = 1050, height = 850, res = 130)layout(matrix(c(1, 2), nrow = 1), widths = c(5, 1))par(mar = c(4, 4, 4, 1))image(seq_len(31), seq_len(31), heatmap, col = palette, zlim = c(0, 1), xlab = "Ordered local marker index", ylab = "Ordered local marker index", main = "The 31 closest eligible chromosome 22 markers")par(mar = c(4, 1, 4, 4))image(1, seq(0, 1, length.out = 100), matrix(seq(0, 1, length.out = 100), nrow = 1), col = palette, axes = FALSE, xlab = "", ylab = "", main = expression(r^2))axis(4, at = seq(0, 1, by = 0.25))invisible(dev.off())candidates <- MarkerIds("pca_candidates.txt")retained <- MarkerIds("ld_pruning.prune.in")excluded <- MarkerIds("ld_pruning.prune.out")stopifnot(!length(intersect(retained, excluded)))stopifnot(setequal(c(retained, excluded), candidates))chromosome <- variants$CHROM[match(candidates, variants$ID)]stopifnot(all(chromosome %in% 1:21))before <- tabulate(chromosome, nbins = 21)after <- tabulate(variants$CHROM[match(retained, variants$ID)], nbins = 21)pruning <- data.frame(CHROM = 1:21, before = before, retained = after)write.table(pruning, "outputs/pruning_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)png("outputs/pruning_r.png", width = 1300, height = 720, res = 130)barplot(rbind(after, before - after), names.arg = 1:21, col = c("#167c80", "#cbd1d5"), border = NA, xlab = "Chromosome", ylab = "Sparse markers", main = "PCA markers before and after the declared LD rule")legend("topright", c("Retained", "Pruned"), fill = c("#167c80", "#cbd1d5"), bty = "n")invisible(dev.off())metrics <- list(regional_markers = length(region), candidate_markers = length(candidates), retained_markers = length(retained), excluded_markers = length(excluded), maximum_ld = max(r_squared), heatmap_markers = 31)WriteMetrics(metrics)cat(sprintf("The ALT dosage comparison checks %d regional markers.\n", length(region)))cat(sprintf("The PCA rule retains %d of %d candidate markers.\n", length(retained), length(candidates)))cat("The PCA candidate set contains chromosomes 1 through 21 only.\n")The ALT dosage comparison checks 965 regional markers.The PCA rule retains 23356 of 27007 candidate markers.The PCA candidate set contains chromosomes 1 through 21 only.
The diagonal equals one because each marker is correlated with itself. The matrix preserves coordinate order, and its colors represent squared correlation.

The primary rule uses a 1,000-kb window, one-marker steps, and an r squared threshold of 0.2. It does not promise that every pair across the genome has correlation below that threshold.
import sys
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
sys.path.insert(0, "/shared")import population_utils as population
accepted = population.read_analysis()variants = population.read_table("variant_universe.tsv.gz").set_index("ID")dosage = population.read_table("regional_dosages.tsv.gz")region = population.marker_ids("regional_markers.txt")generating = accepted["panel"]["generating_variant"]assert generating in regiongenotypes = dosage[region].to_numpy(dtype=float)assert np.isin(genotypes, [0, 1, 2]).all()centered = genotypes - genotypes.mean(0)anchor = centered[:, region.index(generating)]numerator = anchor @ centereddenominator = (anchor @ anchor) * np.sum(centered**2, axis=0)r_squared = numerator**2 / denominatorresult = pd.DataFrame(dict(ID=region, r_squared=r_squared))primary = population.read_table("regional_ld.vcor")assert (primary["ID_A"].eq(generating) | primary["ID_B"].eq(generating)).all()other = np.where(primary["ID_A"].eq(generating), primary["ID_B"], primary["ID_A"])assert len(set(other)) == len(other)assert set(other) == set(region) - {generating}matched = result.set_index("ID").loc[other, "r_squared"]np.testing.assert_allclose(primary["UNPHASED_R2"], matched, rtol=5e-6, atol=1e-8)population.compare_table(result, "outputs/regional_ld_r.tsv", ["ID"], ["r_squared"])region_variants = variants.loc[region].reset_index()region_variants["distance"] = abs(region_variants["POS"] - accepted["panel"]["generating_position"])nearest = region_variants.sort_values(["distance", "POS", "REF", "ALT"])nearest = nearest.iloc[:31].sort_values(["POS", "REF", "ALT"])["ID"].tolist()heatmap = np.corrcoef(dosage[nearest].to_numpy(), rowvar=False)**2reference = pd.read_csv("outputs/heatmap_r.tsv", sep="\t", index_col=0)assert reference.columns.tolist() == nearestassert reference.index.tolist() == nearestnp.testing.assert_allclose(heatmap, reference.to_numpy(), atol=1e-8)fig, ax = plt.subplots(figsize=(8, 7))image = ax.imshow(heatmap, origin="lower", vmin=0, vmax=1, cmap="viridis", extent=[0.5, 31.5, 0.5, 31.5])ax.set(xlabel="Ordered local marker index", ylabel="Ordered local marker index", title="The 31 closest eligible chromosome 22 markers")fig.colorbar(image, ax=ax, label="r squared")fig.savefig("outputs/linkage_python.png", dpi=160, bbox_inches="tight")plt.close(fig)candidates = population.marker_ids("pca_candidates.txt")retained = population.marker_ids("ld_pruning.prune.in")excluded = population.marker_ids("ld_pruning.prune.out")assert not set(retained) & set(excluded)assert set(retained) | set(excluded) == set(candidates)assert variants.loc[candidates, "CHROM"].between(1, 21).all()before = np.bincount(variants.loc[candidates, "CHROM"], minlength=22)[1:]after = np.bincount(variants.loc[retained, "CHROM"], minlength=22)[1:]pruning = pd.DataFrame(dict(CHROM=np.arange(1, 22), before=before, retained=after))population.compare_table(pruning, "outputs/pruning_r.tsv", ["CHROM"], ["before", "retained"], 0)fig, ax = plt.subplots(figsize=(11, 6))ax.bar(pruning["CHROM"], after, color="#167c80", label="Retained")ax.bar(pruning["CHROM"], before - after, bottom=after, color="#cbd1d5", label="Pruned")ax.set_xticks(pruning["CHROM"])ax.set(xlabel="Chromosome", ylabel="Sparse markers", title="PCA markers before and after the declared LD rule")ax.legend()fig.savefig("outputs/pruning_python.png", dpi=160, bbox_inches="tight")plt.close(fig)metrics = dict(regional_markers=len(region), candidate_markers=len(candidates), retained_markers=len(retained), excluded_markers=len(excluded), maximum_ld=float(r_squared.max()), heatmap_markers=31)population.write_metrics(metrics)print(f"The ALT dosage comparison checks {len(region)} regional markers.")print(f"The PCA rule retains {len(retained)} of {len(candidates)} candidates.")print("The PCA candidate set contains chromosomes 1 through 21 only.")The ALT dosage comparison checks 965 regional markers.The PCA rule retains 23356 of 27007 candidates.The PCA candidate set contains chromosomes 1 through 21 only.
Every matrix entry agrees with the R calculation. The separate anchor comparison checks all eligible markers in the declared region against PLINK.

The excluded markers remain in the association universe when they satisfy its selection rule. PCA pruning changes the covariate calculation, not the six association family denominators.
Further reading
Section titled “Further reading”-
The manual distinguishes unphased dosage correlation from phased haplotype estimates. It also explains the window, step, and threshold arguments that produce separate retained and excluded marker lists.
-
The PCA documentation explains why correlated markers can dominate a component. This motivates the separate pruned covariate panel without changing the association universe.