Check archived calls in their population context
A complete archived callset can have no missing genotypes and still retain errors from sequencing, alignment, or variant discovery. The input archive does not contain those original measurements. Its call rate establishes whether a genotype value is present in each inspected record.
The primary workflow validates the complete PGEN and checks every eligible autosomal biallelic SNP before frequency thresholds. Unexpected missing calls stop source acceptance. The declared sample and variant missingness threshold is 0.02, but the examples do not manufacture failed calls to illustrate it.
Recalculate after sample selection
Section titled “Recalculate after sample selection”The main panel requires minor allele frequency of at least 0.05 after the combined relatedness exclusions. Frequencies before and after those exclusions use their actual sample sets. The primary calls explicitly include nonfounders in the allele denominator.
The code below checks every sparse-panel ALT dosage against the final allele counts. It also reproduces each person’s observed heterozygote count and the population-specific expected count used by PLINK. The plotted observed fraction uses the same complete sparse marker denominator for every person.
Use equilibrium as a declared diagnostic
Section titled “Use equilibrium as a declared diagnostic”The equilibrium comparison uses 64 evenly spaced indices from the frozen sparse marker list. It calculates the probability-ordered exact test in each source population and in the pooled retained cohort. This diagnostic panel is not a complete equilibrium screen of every source variant.
Conditional on the observed allele count, a possible heterozygote count has
weight proportional to 2^h / (h! a! b!), where a and b count the two
homozygotes. The shared helper code normalizes these weights and sums outcomes
with probability no greater than the observed outcome. Each language performs
that calculation independently and checks
PLINK’s exact test
without a mid-p correction.
A pooled result can reflect population mixture. The workflow does not exclude markers because the combined cohort departs from an equilibrium assumption that its collection design does not satisfy.
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()samples <- ReadSamples()missing <- ReadTable("complete_sample_missingness.tsv")variants <- ReadTable("variant_universe.tsv.gz")dosage <- ReadTable("sparse_dosages.tsv.gz")markers <- MarkerIds("sparse_markers.txt")sentinels <- MarkerIds("hwe_sentinel_markers.txt")stopifnot(all(missing$MISSING_CT == 0), all(missing$F_MISS == 0))stopifnot(identical(dosage$IID, MarkerIds("unrelated.keep")))genotypes <- as.matrix(dosage[markers])stopifnot(all(genotypes %in% 0:2))metadata <- samples[match(dosage$IID, samples$IID), ]variant_index <- match(markers, variants$ID)stopifnot(all(colSums(genotypes) == variants$ALT_CTS[variant_index]))stopifnot(all(variants$OBS_CT == 2 * nrow(genotypes)))maf <- pmin(variants$ALT_CTS, variants$OBS_CT - variants$ALT_CTS) / variants$OBS_CTstopifnot(all(abs(maf - variants$MAF) < 1e-12), all(maf >= 0.05))heterozygosity <- data.frame(IID = dosage$IID, Population = metadata$Population, heterozygotes = rowSums(genotypes == 1), fraction = rowMeans(genotypes == 1))hwe <- data.frame()groups <- c("POOLED", sort(unique(metadata$Population)))for (group in groups) { selected <- seq_len(nrow(genotypes)) if (group != "POOLED") { selected <- which(metadata$Population == group) } group_genotypes <- genotypes[selected, , drop = FALSE] frequency <- colMeans(group_genotypes) / 2 expected_hets <- sum(2 * frequency * (1 - frequency)) het_report <- ReadTable(paste0("heterozygosity_", group, ".het")) het_report <- het_report[match(dosage$IID[selected], het_report$IID), ] observed <- rowSums(group_genotypes == 1) stopifnot(all(het_report[["O(HET)"]] == observed)) stopifnot(all(het_report$OBS_CT == sum(frequency > 0 & frequency < 1))) stopifnot(all(abs(het_report[["E(HET)"]] - expected_hets) < 5e-6 * expected_hets + 1e-8)) calculated_f <- 1 - observed / expected_hets stopifnot(all(abs(calculated_f - het_report$F) < 1e-5)) selected_genotypes <- group_genotypes[, sentinels, drop = FALSE] counts <- data.frame(Population = group, ID = sentinels, hom_ref = colSums(selected_genotypes == 0), heterozygous = colSums(selected_genotypes == 1), hom_alt = colSums(selected_genotypes == 2)) counts$p_value <- numeric(nrow(counts)) for (index in seq_len(nrow(counts))) { counts$p_value[index] <- HweExact(counts$hom_ref[index], counts$heterozygous[index], counts$hom_alt[index]) } primary_counts <- ReadTable(paste0("hwe_", group, ".gcount")) primary_counts <- primary_counts[match(sentinels, primary_counts$ID), ] stopifnot(all(counts$hom_ref == primary_counts$HOM_REF_CT)) stopifnot(all(counts$heterozygous == primary_counts$HET_REF_ALT1_CT)) stopifnot(all(counts$hom_alt == primary_counts$HOM_ALT1_CT)) stopifnot(all(primary_counts$MISSING_CT == 0)) primary_hwe <- ReadTable(paste0("hwe_", group, ".hardy")) primary_hwe <- primary_hwe[match(sentinels, primary_hwe$ID), ] stopifnot(all(abs(counts$p_value - primary_hwe$P) < 5e-6 * counts$p_value + 1e-14)) hwe <- rbind(hwe, counts)}dir.create("outputs", showWarnings = FALSE)write.table(heterozygosity, "outputs/heterozygosity_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)write.table(hwe, "outputs/hwe_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)png("outputs/frequency_r.png", width = 1050, height = 700, res = 130)hist(maf, breaks = seq(0.05, 0.5, by = 0.025), col = "#167c80", border = "white", main = "The frozen common-variant association universe", xlab = "Minor allele frequency in the retained people", ylab = "Markers")invisible(dev.off())png("outputs/heterozygosity_r.png", width = 1300, height = 720, res = 130)par(mar = c(7, 4, 3, 1))boxplot(fraction ~ Population, data = heterozygosity, las = 2, col = "#78b3b5", ylab = "Observed heterozygous fraction", main = "The same sparse marker denominator for every person", outline = TRUE, outpch = 16, outcex = 0.35)invisible(dev.off())fractions <- numeric(length(groups))for (index in seq_along(groups)) { fractions[index] <- mean(hwe$p_value[hwe$Population == groups[index]] < 0.001)}png("outputs/equilibrium_r.png", width = 1300, height = 720, res = 130)par(mar = c(7, 4, 3, 1))barplot(100 * fractions, names.arg = groups, las = 2, col = c("#9e4f22", rep("#167c80", length(groups) - 1)), ylab = "Diagnostic markers with exact p < 0.001, percent", main = "The fixed 64-marker equilibrium diagnostic")invisible(dev.off())metrics <- list(source_people = nrow(missing), missing_calls = 0, retained_people = nrow(genotypes), sparse_markers = ncol(genotypes), universe_markers = nrow(variants), hwe_tests = nrow(hwe), heterozygous_calls = sum(heterozygosity$heterozygotes))WriteMetrics(metrics)cat(sprintf("The source reports no missing eligible calls in %d people.\n", nrow(missing)))cat(sprintf("All ALT counts agree across %d sparse markers and %d people.\n", ncol(genotypes), nrow(genotypes)))cat(sprintf("The exact test checks %d stratum-marker pairs.\n", nrow(hwe)))cat("No equilibrium diagnostic defines an additional exclusion.\n")The source reports no missing eligible calls in 3202 people.All ALT counts agree across 27390 sparse markers and 2574 people.The exact test checks 1728 stratum-marker pairs.No equilibrium diagnostic defines an additional exclusion.
The histogram starts at the declared common-variant threshold. It describes the selected association universe, which includes dense chromosome 22 coverage. It is not the complete source allele-frequency spectrum.

Every fraction uses the same sparse marker list. The distributions describe that ascertainment and sample selection; they do not rank population quality.

Each column uses the same 64 diagnostic markers. The displayed threshold is a descriptive comparison, not a multiple-testing discovery rule or an exclusion.
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()samples = population.read_samples()missing = population.read_table("complete_sample_missingness.tsv")variants = population.read_table("variant_universe.tsv.gz")dosage = population.read_table("sparse_dosages.tsv.gz")markers = population.marker_ids("sparse_markers.txt")sentinels = population.marker_ids("hwe_sentinel_markers.txt")assert missing["MISSING_CT"].eq(0).all() and missing["F_MISS"].eq(0).all()assert dosage["IID"].tolist() == population.marker_ids("unrelated.keep")genotypes = dosage[markers].to_numpy()assert np.isin(genotypes, [0, 1, 2]).all()metadata = samples.set_index("IID").loc[dosage["IID"]]selected_variants = variants.set_index("ID").loc[markers]np.testing.assert_array_equal(genotypes.sum(0), selected_variants["ALT_CTS"])assert variants["OBS_CT"].eq(2 * len(genotypes)).all()maf = np.minimum(variants["ALT_CTS"], variants["OBS_CT"] - variants["ALT_CTS"]) / variants["OBS_CT"]np.testing.assert_allclose(maf, variants["MAF"], atol=1e-12)assert (maf >= 0.05).all()heterozygosity = pd.DataFrame({ "IID": dosage["IID"], "Population": metadata["Population"].to_numpy(), "heterozygotes": (genotypes == 1).sum(1), "fraction": (genotypes == 1).mean(1),})hwe = []groups = ["POOLED"] + sorted(metadata["Population"].unique())sentinel_indices = pd.Index(markers).get_indexer(sentinels)for group in groups: selected = np.arange(len(genotypes)) if group != "POOLED": selected = np.flatnonzero(metadata["Population"].eq(group)) group_genotypes = genotypes[selected] frequency = group_genotypes.mean(0) / 2 expected_hets = np.sum(2 * frequency * (1 - frequency)) het_report = population.read_table(f"heterozygosity_{group}.het") het_report = het_report.set_index("IID").loc[dosage["IID"].iloc[selected]] observed = (group_genotypes == 1).sum(1) np.testing.assert_array_equal(het_report["O(HET)"], observed) polymorphic = ((frequency > 0) & (frequency < 1)).sum() assert het_report["OBS_CT"].eq(polymorphic).all() np.testing.assert_allclose(het_report["E(HET)"], expected_hets, rtol=5e-6) np.testing.assert_allclose(het_report["F"], 1 - observed / expected_hets, rtol=0, atol=1e-5) selected_genotypes = group_genotypes[:, sentinel_indices] counts = pd.DataFrame({ "Population": group, "ID": sentinels, "hom_ref": (selected_genotypes == 0).sum(0), "heterozygous": (selected_genotypes == 1).sum(0), "hom_alt": (selected_genotypes == 2).sum(0), }) counts["p_value"] = [population.hwe_exact(row.hom_ref, row.heterozygous, row.hom_alt) for row in counts.itertuples(index=False)] primary_counts = population.read_table(f"hwe_{group}.gcount") primary_counts = primary_counts.set_index("ID").loc[sentinels] for own, primary in [("hom_ref", "HOM_REF_CT"), ("heterozygous", "HET_REF_ALT1_CT"), ("hom_alt", "HOM_ALT1_CT")]: np.testing.assert_array_equal(counts[own], primary_counts[primary]) assert primary_counts["MISSING_CT"].eq(0).all() primary_hwe = population.read_table(f"hwe_{group}.hardy") primary_hwe = primary_hwe.set_index("ID").loc[sentinels] np.testing.assert_allclose(primary_hwe["P"], counts["p_value"], rtol=5e-6, atol=1e-14) hwe.append(counts)hwe = pd.concat(hwe, ignore_index=True)population.compare_table(heterozygosity, "outputs/heterozygosity_r.tsv", ["IID", "Population"], ["heterozygotes", "fraction"])population.compare_table(hwe, "outputs/hwe_r.tsv", ["Population", "ID"], ["hom_ref", "heterozygous", "hom_alt", "p_value"])fig, ax = plt.subplots(figsize=(9, 5))ax.hist(maf, bins=np.linspace(0.05, 0.5, 19), color="#167c80", edgecolor="white")ax.set(xlabel="Minor allele frequency in the retained people", ylabel="Markers", title="The frozen common-variant association universe")fig.savefig("outputs/frequency_python.png", dpi=160, bbox_inches="tight")plt.close(fig)population_names = groups[1:]values = [heterozygosity.loc[heterozygosity["Population"].eq(group), "fraction"] for group in population_names]fig, ax = plt.subplots(figsize=(11, 6))ax.boxplot(values, tick_labels=population_names, showfliers=True, flierprops=dict(markersize=2, marker=".", alpha=0.6))ax.tick_params(axis="x", labelrotation=90)ax.set(ylabel="Observed heterozygous fraction", title="The same sparse marker denominator for every person")fig.savefig("outputs/heterozygosity_python.png", dpi=160, bbox_inches="tight")plt.close(fig)fractions = [hwe.loc[hwe["Population"].eq(group), "p_value"].lt(0.001).mean() for group in groups]fig, ax = plt.subplots(figsize=(11, 6))ax.bar(groups, 100 * np.asarray(fractions), color=["#9e4f22"] + ["#167c80"] * (len(groups) - 1))ax.tick_params(axis="x", labelrotation=90)ax.set(ylabel="Diagnostic markers with exact p < 0.001, percent", title="The fixed 64-marker equilibrium diagnostic")fig.savefig("outputs/equilibrium_python.png", dpi=160, bbox_inches="tight")plt.close(fig)metrics = dict(source_people=len(missing), missing_calls=0, retained_people=len(genotypes), sparse_markers=len(markers), universe_markers=len(variants), hwe_tests=len(hwe), heterozygous_calls=int(heterozygosity["heterozygotes"].sum()))population.write_metrics(metrics)print("The source reports no missing eligible calls in " f"{len(missing)} people.")print(f"All ALT counts agree across {len(markers)} sparse markers and " f"{len(genotypes)} people.")print(f"The exact test checks {len(hwe)} stratum-marker pairs.")print("No equilibrium diagnostic defines an additional exclusion.")The source reports no missing eligible calls in 3202 people.All ALT counts agree across 27390 sparse markers and 2574 people.The exact test checks 1728 stratum-marker pairs.No equilibrium diagnostic defines an additional exclusion.
The complete allele counts supply the frequencies. The plotted set follows the declared sample exclusions and common-variant threshold.

The labels retain the source collection categories. Within-population expected heterozygosity is checked separately against PLINK’s report.

The paired comparison checks every genotype count and every exact p-value in this diagnostic panel. The displayed counts do not define a discovery list.
Further reading
Section titled “Further reading”-
The manual documents exact equilibrium tests, optional mid-p adjustment, founder denominators, and genotype counts. These options distinguish the reported diagnostic from a different sample set or test.
-
The resource notes identify the selected callset and corrected pedigree fields. Those source choices determine which people and alleles enter the subsequent count checks.