Counts and normalization
The paired model needs integer counts over the same regions in every sample. Peak scores and bigWig signal cannot supply that matrix. This lesson starts from the fresh consensus featureCounts output and preserves the donor mapping before it filters or normalizes a column.
Define what one count represents
Section titled “Define what one count represents”The execution uses Subread 2.0.1 with -p -F SAF -O --fracOverlap 0.2.
In that version, -p counts paired fragments. Later Subread releases separate
the declaration of paired reads from the --countReadPairs option, so copying
flags between versions can change the count unit. The
Subread release history documents that change.
One fragment contributes at most one count to a given region, even when both
mates overlap it. The -O option permits that fragment to contribute to more
than one region. The overlap fraction refers to aligned read bases; the
unsequenced gap between mates does not itself assign a fragment to a region.
The companion boundary test verifies those rules in the declared container.
The consensus BED uses zero-based starts and exclusive ends. SAF uses
one-based inclusive coordinates. A local correction converts the BED start
to start + 1 before featureCounts runs because ATAC release 2.1.2 writes
the unconverted start. The execution record preserves this correction and
checks every counted interval against the corrected SAF.
These assignments explain why a column sum is not the number of unique fragments in the library. Use the independently counted fragment denominator in the QC lesson for that measurement.
Filter regions before the model
Section titled “Filter regions before the model”The eligible universe contains autosomal consensus regions without any blacklist overlap. Within that universe, retain a region with at least ten assigned fragments in at least four sample profiles. This teaching rule uses count information without selecting an effect direction or a significant p-value. It does not guarantee adequate power at every retained region.
The median-of-ratios estimate uses regions with positive counts in every sample to define its geometric reference. Each sample’s size factor is the exponential of its median log ratio to that reference. Zeros therefore affect which regions estimate the size factors, even when those regions pass the separate count filter.
The completed filter retains 48,292 regions from 50,599 eligible autosomal regions. Of those retained regions, 46,424 have positive counts in every sample and define the median-ratio reference. No count is imputed, and all eight profiles remain in the matrix.
The original experiment comes from Calderon and colleagues, deposited as GSE118189, SRP156496, and PRJNA484801. The companion workflow generates these analysis inputs from eight public read runs covered by the INSDC use policy. The source notice identifies those runs, the GENCODE v19 annotation, the UCSC/NCBI reference, and the Boyle Lab blacklist. It records the source grants and the transformations applied to the inputs.
library(DESeq2)library(ggplot2)library(jsonlite)
metadata <- read.delim("/fixtures/metadata.tsv", colClasses = "character")metadata <- metadata[order(metadata$donor, metadata$condition), ]rownames(metadata) <- metadata$sample_idmetadata$donor <- factor(metadata$donor)metadata$condition <- factor(metadata$condition, levels = c("resting", "stimulated"))regions <- read.delim("/fixtures/regions.tsv", check.names = FALSE)source_counts <- read.delim(gzfile("/fixtures/counts.tsv.gz"), row.names = 1, check.names = FALSE)stopifnot(identical(rownames(source_counts), regions$region_id))stopifnot(setequal(names(source_counts), metadata$sample_id))counts <- as.matrix(source_counts[, metadata$sample_id])stopifnot(all(is.finite(counts)), all(counts >= 0))stopifnot(all(counts == floor(counts)))eligible <- regions$autosomal & !regions$blacklist_overlapretained <- eligible & rowSums(counts >= 10L) >= 4Lfiltered <- counts[retained, , drop = FALSE]positive <- rowSums(filtered == 0L) == 0Lstopifnot(any(positive))log_counts <- log(filtered[positive, , drop = FALSE])log_ratios <- log_counts - rowMeans(log_counts)size_factors <- exp(apply(log_ratios, 2, median))dds <- DESeqDataSetFromMatrix(filtered, metadata, ~donor + condition)dds <- estimateSizeFactors(dds, type = "ratio")stopifnot(max(abs(sizeFactors(dds) - size_factors)) < 1e-8)normalized <- sweep(filtered, 2, size_factors, "/")log_normalized <- log2(normalized + 1)region_variance <- apply(log_normalized, 1, var)selected <- head(order(-region_variance, rownames(filtered)), 500)pca <- prcomp(t(log_normalized[selected, ]), center = TRUE, scale. = FALSE)variance_fraction <- pca$sdev^2 / sum(pca$sdev^2)scores <- data.frame(sample_id = metadata$sample_id, donor = metadata$donor, condition = metadata$condition, pc1 = pca$x[, 1], pc2 = pca$x[, 2])for (component in 1:2) { anchor <- which.max(abs(pca$rotation[, component])) column <- paste0("pc", component) scores[[column]] <- scores[[column]] * sign(pca$rotation[anchor, component])}sample_summary <- data.frame( sample_id = metadata$sample_id, assigned_counts = colSums(filtered), size_factor = as.numeric(size_factors), normalized_total = colSums(normalized))cat(sprintf("Consensus regions: %d; eligible autosomal regions: %d\n", nrow(counts), sum(eligible)))cat(sprintf("Retained regions: %d; positive reference regions: %d\n", nrow(filtered), sum(positive)))cat(sprintf("PCA regions: %d; PC1: %.4f; PC2: %.4f\n", length(selected), variance_fraction[1], variance_fraction[2]))for (i in seq_len(nrow(sample_summary))) { cat(sprintf("%s assigned=%d size_factor=%.6f\n", sample_summary$sample_id[i], sample_summary$assigned_counts[i], sample_summary$size_factor[i]))}dir.create("outputs", showWarnings = FALSE)write.table(sample_summary, "outputs/normalization_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(scores, "outputs/pca_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)writeLines(rownames(filtered), "outputs/retained_regions_r.txt")writeLines(rownames(filtered)[selected], "outputs/pca_regions_r.txt")write_json(list(retained = nrow(filtered), eligible = sum(eligible), positive = sum(positive), total = sum(filtered), pc1 = variance_fraction[1], pc2 = variance_fraction[2]), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)pca_figure <- ggplot(scores, aes(pc1, pc2, color = condition)) + geom_line(aes(group = donor), color = "gray65") + geom_point(size = 3) + geom_text(aes(label = donor), vjust = -0.8, show.legend = FALSE) + scale_color_manual(values = c("#287d8e", "#c95d35")) + scale_y_continuous(expand = expansion(mult = c(0.06, 0.15))) + theme_bw(base_size = 11) + labs(x = sprintf("PC1, %.1f%%", 100 * variance_fraction[1]), y = sprintf("PC2, %.1f%%", 100 * variance_fraction[2]), color = "Condition")ggsave("outputs/counts_pca_r.png", pca_figure, width = 7, height = 4.5, dpi = 160)png("outputs/count_distributions_r.png", width = 1250, height = 750, res = 160)par(mar = c(8, 4, 2, 1))boxplot(log_normalized, outline = FALSE, las = 2, ylab = "log2 normalized assigned counts + 1", col = "#87b9c1")invisible(dev.off())Consensus regions: 52518; eligible autosomal regions: 50599Retained regions: 48292; positive reference regions: 46424PCA regions: 500; PC1: 0.9168; PC2: 0.0285resting_REP1 assigned=6198553 size_factor=1.010085stimulated_REP1 assigned=8654366 size_factor=1.918401resting_REP2 assigned=1404936 size_factor=0.336671stimulated_REP2 assigned=5405031 size_factor=1.256200resting_REP3 assigned=6409639 size_factor=1.146677stimulated_REP3 assigned=3711074 size_factor=0.832176resting_REP4 assigned=5277124 size_factor=1.046049stimulated_REP4 assigned=5859494 size_factor=1.289874

import jsonimport mathfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom pydeseq2.preprocessing import deseq2_norm
metadata = pd.read_csv("/fixtures/metadata.tsv", sep="\t", dtype=str)metadata = metadata.sort_values(["donor", "condition"]).reset_index(drop=True)regions = pd.read_csv("/fixtures/regions.tsv", sep="\t")source_counts = pd.read_csv("/fixtures/counts.tsv.gz", sep="\t", index_col=0)assert source_counts.index.tolist() == regions["region_id"].tolist()assert set(source_counts.columns) == set(metadata["sample_id"])counts = source_counts.loc[:, metadata["sample_id"]].to_numpy()assert np.isfinite(counts).all() and (counts >= 0).all()assert (counts == np.floor(counts)).all()eligible = regions["autosomal"] & ~regions["blacklist_overlap"]retained = eligible.to_numpy() & ((counts >= 10).sum(axis=1) >= 4)filtered = counts[retained]region_ids = source_counts.index[retained].to_numpy()positive = (filtered > 0).all(axis=1)assert positive.any()log_counts = np.log(filtered[positive])log_ratios = log_counts - log_counts.mean(axis=1, keepdims=True)size_factors = np.exp(np.median(log_ratios, axis=0))normalized, package_factors = deseq2_norm(filtered.T)np.testing.assert_allclose(size_factors, package_factors, atol=1e-8, rtol=0)normalized = normalized.Tlog_normalized = np.log2(normalized + 1)region_variance = log_normalized.var(axis=1, ddof=1)selected = np.lexsort((region_ids, -region_variance))[:500]pca_input = log_normalized[selected].Tpca_input = pca_input - pca_input.mean(axis=0)left, singular, right = np.linalg.svd(pca_input, full_matrices=False)variance_fraction = singular**2 / np.sum(singular**2)coordinates = left[:, :2] * singular[:2]for component in range(2): anchor = np.argmax(np.abs(right[component])) coordinates[:, component] *= np.sign(right[component, anchor])scores = metadata.loc[:, ["sample_id", "donor", "condition"]].copy()scores[["pc1", "pc2"]] = coordinatesnormalized_totals = [math.fsum(column) for column in normalized.T]sample_summary = pd.DataFrame({ "sample_id": metadata["sample_id"], "assigned_counts": filtered.sum(axis=0), "size_factor": size_factors, "normalized_total": normalized_totals,})print(f"Consensus regions: {len(counts)}; " f"eligible autosomal regions: {eligible.sum()}")print(f"Retained regions: {len(filtered)}; " f"positive reference regions: {positive.sum()}")print(f"PCA regions: {len(selected)}; PC1: {variance_fraction[0]:.4f}; " f"PC2: {variance_fraction[1]:.4f}")for row in sample_summary.itertuples(): print(f"{row.sample_id} assigned={row.assigned_counts} " f"size_factor={row.size_factor:.6f}")output = Path("outputs")output.mkdir(exist_ok=True)sample_summary.to_csv(output / "normalization_python.tsv", sep="\t", index=False)scores.to_csv(output / "pca_python.tsv", sep="\t", index=False)(output / "retained_regions_python.txt").write_text( "\n".join(region_ids) + "\n")(output / "pca_regions_python.txt").write_text( "\n".join(region_ids[selected]) + "\n")assert region_ids.tolist() == ( output / "retained_regions_r.txt").read_text().splitlines()assert region_ids[selected].tolist() == ( output / "pca_regions_r.txt").read_text().splitlines()r_summary = pd.read_csv(output / "normalization_r.tsv", sep="\t")assert r_summary["sample_id"].tolist() == metadata["sample_id"].tolist()np.testing.assert_array_equal(r_summary["assigned_counts"], sample_summary["assigned_counts"])for column in ["size_factor", "normalized_total"]: np.testing.assert_allclose(r_summary[column], sample_summary[column], atol=1e-6, rtol=0)r_scores = pd.read_csv(output / "pca_r.tsv", sep="\t")np.testing.assert_allclose(r_scores[["pc1", "pc2"]], coordinates, atol=1e-6, rtol=0)metrics = {"retained": len(filtered), "eligible": int(eligible.sum()), "positive": int(positive.sum()), "total": int(filtered.sum()), "pc1": float(variance_fraction[0]), "pc2": float(variance_fraction[1])}(output / "metrics_python.json").write_text(json.dumps(metrics))figure, axis = plt.subplots(figsize=(7, 4.5))for donor, rows in scores.groupby("donor", sort=True): axis.plot(rows["pc1"], rows["pc2"], color="0.65", zorder=1)for condition, color in [("resting", "#287d8e"), ("stimulated", "#c95d35")]: rows = scores.loc[scores["condition"].eq(condition)] axis.scatter(rows["pc1"], rows["pc2"], color=color, label=condition)for row in scores.itertuples(): axis.annotate(row.donor, (row.pc1, row.pc2), xytext=(0, 6), textcoords="offset points", ha="center", fontsize=9)axis.set(xlabel=f"PC1, {100 * variance_fraction[0]:.1f}%", ylabel=f"PC2, {100 * variance_fraction[1]:.1f}%")axis.margins(y=0.12)axis.legend(title="Condition")figure.tight_layout()figure.savefig(output / "counts_pca_python.png", dpi=160)plt.close(figure)figure, axis = plt.subplots(figsize=(7.8, 4.7))axis.boxplot(log_normalized, showfliers=False, tick_labels=metadata["sample_id"])axis.tick_params(axis="x", rotation=90)axis.set_ylabel("log2 normalized assigned counts + 1")figure.tight_layout()figure.savefig(output / "count_distributions_python.png", dpi=160)plt.close(figure)Consensus regions: 52518; eligible autosomal regions: 50599Retained regions: 48292; positive reference regions: 46424PCA regions: 500; PC1: 0.9168; PC2: 0.0285resting_REP1 assigned=6198553 size_factor=1.010085stimulated_REP1 assigned=8654366 size_factor=1.918401resting_REP2 assigned=1404936 size_factor=0.336671stimulated_REP2 assigned=5405031 size_factor=1.256200resting_REP3 assigned=6409639 size_factor=1.146677stimulated_REP3 assigned=3711074 size_factor=0.832176resting_REP4 assigned=5277124 size_factor=1.046049stimulated_REP4 assigned=5859494 size_factor=1.289874

Read the normalization diagnostics
Section titled “Read the normalization diagnostics”PCA uses the 500 most variable retained regions after the displayed log transformation, or every retained region if fewer remain. The calculation centers each region without scaling its variance to one. It does not remove donor effects before display. A connection between two points therefore shows the observed within-donor displacement, rather than an adjusted treatment effect.
PC1 explains 91.68% of variation in the selected 500 regions, and all four pairs move in the same direction along that axis after stimulation. Resting donor 1002 lies apart along PC2 and has the smallest size factor, 0.336671. Its weak TSS and peak enrichment remains a separate limitation. The selected features emphasize variation, so their PCA separation does not independently validate sample quality or the normalization reference.
Normalized distributions can reveal a sample that differs from the other profiles. Similar distributions do not prove that normalization recovered an absolute accessibility scale. Median-of-ratios normalization needs a suitable reference distribution across regions, and widespread directional changes can violate that assumption. The differential lesson compares a TMM normalization sensitivity fit and donor omission fits.
The pseudocount of one belongs only to this exploratory log transformation. The negative binomial model receives the untransformed integer matrix and uses size factors as offsets. It does not receive these plotted log values.
Scientific references
Section titled “Scientific references”Love, Huber, and Anders, 2014 describe the DESeq2 count model and its shrinkage of dispersion and fold change estimates.
Muzellec and colleagues, 2023 describe PyDESeq2, the Python implementation of the DESeq2 method.
Further reading
Section titled “Further reading”The Subread release history records the change to paired-end counting options in version 2.0.2. It explains why the retained 2.0.1 command needs version-specific interpretation.
The DESeq2 normalization guide explains size factors and variance stabilization. These definitions support the manual-versus-package comparison in this lesson.