Skip to content

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.

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.

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_id
metadata$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_overlap
retained <- eligible & rowSums(counts >= 10L) >= 4L
filtered <- counts[retained, , drop = FALSE]
positive <- rowSums(filtered == 0L) == 0L
stopifnot(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: 50599
Retained regions: 48292; positive reference regions: 46424
PCA regions: 500; PC1: 0.9168; PC2: 0.0285
resting_REP1 assigned=6198553 size_factor=1.010085
stimulated_REP1 assigned=8654366 size_factor=1.918401
resting_REP2 assigned=1404936 size_factor=0.336671
stimulated_REP2 assigned=5405031 size_factor=1.256200
resting_REP3 assigned=6409639 size_factor=1.146677
stimulated_REP3 assigned=3711074 size_factor=0.832176
resting_REP4 assigned=5277124 size_factor=1.046049
stimulated_REP4 assigned=5859494 size_factor=1.289874

The PCA connects samples from the same donor.

The distributions summarize normalized counts over retained regions.

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.

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.

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.