Calculate population structure from a declared panel
Principal components summarize variation in the people and markers supplied to the calculation. Relatives, low-frequency variants, and correlated chromosome segments can change that summary. A principal component is therefore a property of this selected matrix, not an intrinsic ancestry label attached to a person.
The teaching covariates use the unrelated subset and the final sparse markers on chromosomes 1 through 21. LD pruning uses a 1,000-kb window, one-marker steps, and an r squared threshold of 0.2. Chromosome 22 remains outside the PCA input, so the dense region and known generating locus cannot dominate these covariates.
Reconstruct the variance-standardized matrix
Section titled “Reconstruct the variance-standardized matrix”For ALT dosage g and retained-sample ALT frequency p, each marker becomes
(g - 2p) / sqrt(2p(1 - p)). The relationship matrix is the cross-product of
that standardized sample-by-marker matrix divided by its marker count.
Both examples extract its leading eigenvectors and compare the complete
ten-dimensional principal subspace with the fresh
PLINK PCA result.
Eigenvector signs are arbitrary. Tied eigenvalues also permit rotations within their shared subspace. The comparison uses orthonormal bases and principal angles, then aligns the displayed coordinates to PLINK. A separate check requires an eigenvalue gap after the tenth component before that ten-dimensional boundary is accepted.
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()dosage <- ReadTable("sparse_dosages.tsv.gz")markers <- MarkerIds("ld_pruning.prune.in")variants <- ReadTable("variant_universe.tsv.gz")stopifnot(all(variants$CHROM[match(markers, variants$ID)] %in% 1:21))genotypes <- as.matrix(dosage[markers])frequency <- colMeans(genotypes) / 2stopifnot(all(frequency >= 0.05 & frequency <= 0.95))standardized <- sweep(genotypes, 2, 2 * frequency, "-")standardized <- sweep(standardized, 2, sqrt(2 * frequency * (1 - frequency)), "/")relationship <- tcrossprod(standardized) / ncol(standardized)set.seed(20261031)decomposition <- RSpectra::eigs_sym(relationship, k = 11, which = "LA", opts = list(tol = 1e-10, maxitr = 10000))order_index <- order(decomposition$values, decreasing = TRUE)eigenvalues <- decomposition$values[order_index]vectors <- decomposition$vectors[, order_index[seq_len(10)], drop = FALSE]stopifnot(eigenvalues[10] - eigenvalues[11] > 1e-8 * eigenvalues[1])primary <- ReadTable("pca.eigenvec")stopifnot(identical(primary$IID, dosage$IID))primary_values <- scan("/fixtures/analysis/pca.eigenval", quiet = TRUE)stopifnot(all(abs(eigenvalues[seq_len(10)] - primary_values) < 5e-6 * primary_values))primary_vectors <- as.matrix(primary[paste0("PC", seq_len(10))])primary_basis <- qr.Q(qr(primary_vectors))singular_values <- svd(crossprod(vectors, primary_basis), nu = 0, nv = 0)$dsubspace_error <- sqrt(max(0, 1 - min(singular_values)^2))stopifnot(subspace_error < 1e-4)alignment <- svd(crossprod(vectors, primary_vectors))aligned <- vectors %*% alignment$u %*% t(alignment$v)colnames(aligned) <- paste0("PC", seq_len(10))scores <- data.frame(IID = dosage$IID, aligned, check.names = FALSE)dir.create("outputs", showWarnings = FALSE)write.table(scores, "outputs/scores_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)write.table(data.frame(component = seq_len(11), eigenvalue = eigenvalues), "outputs/eigenvalues_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)metadata <- ReadSamples()metadata <- metadata[match(scores$IID, metadata$IID), ]colors <- c(AFR = "#9e4f22", AMR = "#7c54a2", EAS = "#167c80", EUR = "#3c6cb0", SAS = "#c48d16")png("outputs/principal_components_r.png", width = 1100, height = 800, res = 130)plot(scores$PC1, scores$PC2, col = colors[metadata$SuperPop], pch = 16, cex = 0.5, xlab = "PC1 eigenvector coordinate", ylab = "PC2 eigenvector coordinate", main = "Retained people and the pruned chromosome 1 to 21 panel")legend("topright", names(colors), col = colors, pch = 16, bty = "n")invisible(dev.off())unpruned <- ReadTable("pca_unpruned.eigenvec")stopifnot(identical(unpruned$IID, scores$IID))unpruned_basis <- qr.Q(qr(as.matrix(unpruned[paste0("PC", seq_len(10))])))sensitivity <- svd(crossprod(primary_basis, unpruned_basis), nu = 0, nv = 0)$dangles <- acos(pmin(1, pmax(0, sensitivity))) * 180 / piwrite.table(data.frame(index = seq_len(10), degrees = angles), "outputs/sensitivity_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)png("outputs/marker_sensitivity_r.png", width = 1050, height = 700, res = 130)barplot(angles, names.arg = seq_len(10), col = "#167c80", border = NA, xlab = "Principal angle index", ylab = "Angle in degrees", main = "Ten-dimensional subspace change after LD pruning")invisible(dev.off())metrics <- list(people = nrow(scores), markers = length(markers), components = 10, leading_eigenvalue = eigenvalues[1], largest_sensitivity_angle = max(angles))WriteMetrics(metrics)cat(sprintf("The independent PCA uses %d people and %d markers.\n", nrow(scores), length(markers)))cat("The complete ten-dimensional subspace agrees with PLINK.\n")cat(sprintf("The tenth-to-eleventh eigenvalue gap is %.9g.\n", eigenvalues[10] - eigenvalues[11]))cat(sprintf("The largest pruning sensitivity angle is %.6f degrees.\n", max(angles)))The independent PCA uses 2574 people and 23356 markers.The complete ten-dimensional subspace agrees with PLINK.The tenth-to-eleventh eigenvalue gap is 0.0444468488.The largest pruning sensitivity angle is 89.297243 degrees.
Colors reproduce source collection labels. The coordinates summarize the selected genotype matrix and do not identify fixed biological categories.

Each bar is a principal angle between the two ten-dimensional subspaces. It is not a separate comparison of equally numbered principal components.
import sys
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy.linalg import eigh
sys.path.insert(0, "/shared")import population_utils as population
accepted = population.read_analysis()dosage = population.read_table("sparse_dosages.tsv.gz")markers = population.marker_ids("ld_pruning.prune.in")variants = population.read_table("variant_universe.tsv.gz").set_index("ID")assert variants.loc[markers, "CHROM"].between(1, 21).all()genotypes = dosage[markers].to_numpy(dtype=float)frequency = genotypes.mean(0) / 2assert ((frequency >= 0.05) & (frequency <= 0.95)).all()standardized = (genotypes - 2 * frequency) / np.sqrt(2 * frequency * (1 - frequency))relationship = standardized @ standardized.T / standardized.shape[1]eigenvalues, all_vectors = eigh(relationship, subset_by_index=[len(dosage) - 11, len(dosage) - 1])eigenvalues = eigenvalues[::-1]vectors = all_vectors[:, ::-1][:, :10]assert eigenvalues[9] - eigenvalues[10] > 1e-8 * eigenvalues[0]primary = population.read_table("pca.eigenvec")assert primary["IID"].tolist() == dosage["IID"].tolist()primary_values = np.loadtxt("/fixtures/analysis/pca.eigenval")np.testing.assert_allclose(eigenvalues[:10], primary_values, rtol=5e-6)pc_names = [f"PC{index}" for index in range(1, 11)]primary_vectors = primary[pc_names].to_numpy()primary_basis = np.linalg.qr(primary_vectors)[0]singular_values = np.linalg.svd(vectors.T @ primary_basis, compute_uv=False)subspace_error = np.sqrt(max(0, 1 - singular_values.min()**2))assert subspace_error < 1e-4left, _, right = np.linalg.svd(vectors.T @ primary_vectors)aligned = vectors @ left @ rightscores = pd.DataFrame(aligned, columns=pc_names)scores.insert(0, "IID", dosage["IID"])population.compare_table(scores, "outputs/scores_r.tsv", ["IID"], pc_names)eigenvalue_table = pd.DataFrame(dict(component=np.arange(1, 12), eigenvalue=eigenvalues))population.compare_table(eigenvalue_table, "outputs/eigenvalues_r.tsv", ["component"], ["eigenvalue"])metadata = population.read_samples().set_index("IID").loc[scores["IID"]]colors = dict(AFR="#9e4f22", AMR="#7c54a2", EAS="#167c80", EUR="#3c6cb0", SAS="#c48d16")fig, ax = plt.subplots(figsize=(9, 6))for group, color in colors.items(): selected = metadata["SuperPop"].eq(group).to_numpy() ax.scatter(scores.loc[selected, "PC1"], scores.loc[selected, "PC2"], s=6, color=color, label=group)ax.set(xlabel="PC1 eigenvector coordinate", ylabel="PC2 eigenvector coordinate", title="Retained people and the pruned chromosome 1 to 21 panel")ax.legend()fig.savefig("outputs/principal_components_python.png", dpi=160, bbox_inches="tight")plt.close(fig)unpruned = population.read_table("pca_unpruned.eigenvec")assert unpruned["IID"].tolist() == scores["IID"].tolist()unpruned_basis = np.linalg.qr(unpruned[pc_names].to_numpy())[0]sensitivity = np.linalg.svd(primary_basis.T @ unpruned_basis, compute_uv=False)angles = np.rad2deg(np.arccos(np.clip(sensitivity, 0, 1)))sensitivity_table = pd.DataFrame(dict(index=np.arange(1, 11), degrees=angles))population.compare_table(sensitivity_table, "outputs/sensitivity_r.tsv", ["index"], ["degrees"], tolerance=1e-6)fig, ax = plt.subplots(figsize=(9, 5))ax.bar(np.arange(1, 11), angles, color="#167c80")ax.set_xticks(np.arange(1, 11))ax.set(xlabel="Principal angle index", ylabel="Angle in degrees", title="Ten-dimensional subspace change after LD pruning")fig.savefig("outputs/marker_sensitivity_python.png", dpi=160, bbox_inches="tight")plt.close(fig)metrics = dict(people=len(scores), markers=len(markers), components=10, leading_eigenvalue=float(eigenvalues[0]), largest_sensitivity_angle=float(angles.max()))population.write_metrics(metrics)print(f"The independent PCA uses {len(scores)} people and " f"{len(markers)} markers.")print("The complete ten-dimensional subspace agrees with PLINK.")print("The tenth-to-eleventh eigenvalue gap is " f"{eigenvalues[9] - eigenvalues[10]:.9g}.")print(f"The largest pruning sensitivity angle is {angles.max():.6f} degrees.")The independent PCA uses 2574 people and 23356 markers.The complete ten-dimensional subspace agrees with PLINK.The tenth-to-eleventh eigenvalue gap is 0.0444468488.The largest pruning sensitivity angle is 89.297243 degrees.
The R and Python calculations agree on every aligned coordinate and leading eigenvalue. Alignment resolves orientation, while the subspace check verifies the shared result.

The unpruned comparison comes from the fresh primary PLINK calculation. The paired examples independently refit the pruned calculation used by the models.
Read the observed sensitivity
Section titled “Read the observed sensitivity”The first eight principal angles are below 6.85 degrees. The ninth is 15.62 degrees and the tenth is 89.30 degrees, so at least one direction changes strongly when the marker set changes. These ordered angles compare two complete ten-dimensional spaces. The tenth angle does not identify PC10.
The pruned calculation has eigenvalues 2.068089581 and 2.023642732 at positions ten and eleven. Their gap of 0.0444468488 separates the selected subspace from the next direction for this matrix. R and Python agree on the fixed pruned calculation, while the pruning comparison shows sensitivity to marker selection.
Carry the covariates into the declared model
Section titled “Carry the covariates into the declared model”The primary workflow centers and scales the ten PLINK coordinates before simulation and association. It preserves every covariate value and verifies the intercept-plus-covariate matrix rank. The association model lesson uses that same saved matrix.
Ten components define this simulation’s adjustment. They do not guarantee that another phenotype model has no residual confounding, nonlinear structure, or unmodeled family dependence.
Further reading
Section titled “Further reading”-
The manual defines the variance-standardized relationship matrix and discusses relatives, batch effects, low-frequency variants, and LD. These limits apply to interpreting the resulting coordinates.
-
The reference defines angles between column spaces and cites the underlying numerical method. A comparison of complete subspaces accommodates sign changes and rotations that separate component comparisons miss.
-
RSpectra symmetric eigenvectors
The manual specifies largest algebraic eigenvalues and solver controls. The example uses these choices to check an eigenvalue gap and the leading ten-dimensional space.