Skip to content

Differential accessibility within donors

The condition coefficient compares stimulated with resting cells within the same donors. A positive log2 fold change means higher relative accessibility in stimulated cells after the donor term. It does not estimate an absolute change in accessible molecules per cell.

The design is ~ donor + condition, with resting as the condition reference. Four donor pairs provide eight observations and five coefficients, leaving three residual degrees of freedom. An instrument term for the donor 1003 technical merge would duplicate that donor’s indicator and cannot enter this design as a separate estimable effect.

The input universe and count filter match the normalization lesson. Both models use median-of-ratios size factors, a parametric dispersion trend, and unshrunk Wald coefficients. The comparison disables count replacement, Cook’s filtering, and independent filtering so both languages address the declared region family. That choice makes the implementation comparison explicit; it does not remove the need to examine influential samples and count outliers.

Benjamini-Hochberg correction applies across retained regions for this one contrast, with a discovery threshold of 0.05. The foreground for later motif analysis also requires a positive log2 fold change of at least one. That effect threshold selects a subset of discoveries; it does not turn the Wald test into a test against a log2 fold change of one.

R supplies the primary DESeq2 result and the sensitivity fits. The TMM fit replaces the size factors with scaled effective library sizes from edgeR while retaining the DESeq2 model. Each donor omission fit removes both profiles from one donor and preserves the original tested region universe. Those fits assess influence; they do not add independent replication.

The TSS sensitivity adds a standardized log2 TSS enrichment term only when that design has full rank. TSS enrichment can change with treatment as well as technical quality. Its adjustment can therefore change the biological question, and the additional term leaves only two residual degrees of freedom.

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(edgeR)
library(ggplot2)
library(jsonlite)
#' Fit a declared accessibility model without count replacement.
#'
#' @param count_matrix Integer region-by-sample counts.
#' @param sample_metadata Sample rows aligned to count columns.
#' @param design_formula The paired design and any sensitivity term.
#' @param factors Optional externally calculated size factors.
#' @return A list containing the fitted dataset and unshrunk result table.
FitAccessibility <- function(count_matrix, sample_metadata,
design_formula = ~donor + condition,
factors = NULL) {
sample_metadata <- droplevels(sample_metadata)
design <- model.matrix(design_formula, sample_metadata)
stopifnot(qr(design)$rank == ncol(design))
dds <- DESeqDataSetFromMatrix(count_matrix, sample_metadata, design_formula)
if (!is.null(factors)) {
sizeFactors(dds) <- factors
}
dds <- DESeq(dds, fitType = "parametric", sfType = "ratio",
betaPrior = FALSE, minReplicatesForReplace = Inf,
minmu = 0.5, quiet = TRUE)
result <- as.data.frame(results(
dds, contrast = c("condition", "stimulated", "resting"), alpha = 0.05,
cooksCutoff = FALSE, independentFiltering = FALSE
))
stopifnot(all(mcols(dds)$betaConv))
stopifnot(all(is.finite(result$log2FoldChange)))
stopifnot(all(is.finite(result$pvalue)))
result$region_id <- rownames(result)
result <- result[, c("region_id", "baseMean", "log2FoldChange", "lfcSE",
"stat", "pvalue", "padj")]
list(dds = dds, result = result)
}
#' Compare one sensitivity fit with the primary fit.
#'
#' @param primary The primary result table.
#' @param alternative A sensitivity result table in the same region order.
#' @param label The declared sensitivity name.
#' @return A one-row data frame with effect and discovery comparisons.
CompareSensitivity <- function(primary, alternative, label) {
stopifnot(identical(primary$region_id, alternative$region_id))
primary_hits <- primary$padj < 0.05
alternative_hits <- alternative$padj < 0.05
union_count <- sum(primary_hits | alternative_hits)
jaccard <- if (union_count > 0L) {
sum(primary_hits & alternative_hits) / union_count
} else {
1
}
data.frame(
sensitivity = label, discoveries = sum(alternative_hits),
effect_correlation = cor(primary$log2FoldChange,
alternative$log2FoldChange),
median_effect_change = median(abs(primary$log2FoldChange -
alternative$log2FoldChange)),
discovery_jaccard = jaccard
)
}
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")
source_counts <- read.delim(gzfile("/fixtures/counts.tsv.gz"), row.names = 1,
check.names = FALSE)
stopifnot(identical(rownames(source_counts), regions$region_id))
counts <- as.matrix(source_counts[, metadata$sample_id])
retained <- regions$autosomal & !regions$blacklist_overlap &
rowSums(counts >= 10L) >= 4L
filtered <- counts[retained, , drop = FALSE]
primary <- FitAccessibility(filtered, metadata)
result <- primary$result
fit_type <- attr(dispersionFunction(primary$dds), "fitType")
stopifnot(fit_type == "parametric")
dir.create("outputs", showWarnings = FALSE)
write.table(result, "outputs/differential_r.tsv", sep = "\t",
quote = FALSE, row.names = FALSE)
sample_factors <- data.frame(sample_id = metadata$sample_id,
size_factor = sizeFactors(primary$dds))
write.table(sample_factors, "outputs/size_factors_r.tsv", sep = "\t",
quote = FALSE, row.names = FALSE)
cat(sprintf("Tested regions: %d; discoveries: %d; increased: %d\n",
nrow(result), sum(result$padj < 0.05),
sum(result$padj < 0.05 & result$log2FoldChange > 0)))
cat(sprintf("Motif foreground regions: %d\n",
sum(result$padj < 0.05 & result$log2FoldChange >= 1)))
tmm <- calcNormFactors(DGEList(filtered), method = "TMM")
effective_library <- tmm$samples$lib.size * tmm$samples$norm.factors
tmm_factors <- effective_library / exp(mean(log(effective_library)))
tmm_fit <- FitAccessibility(filtered, metadata, factors = tmm_factors)
sensitivity <- list(CompareSensitivity(result, tmm_fit$result, "TMM"))
write.table(tmm_fit$result, "outputs/differential_tmm_r.tsv", sep = "\t",
quote = FALSE, row.names = FALSE)
for (donor in levels(metadata$donor)) {
selected <- metadata$donor != donor
fit <- FitAccessibility(filtered[, selected], metadata[selected, ])
label <- paste0("omit_", donor)
sensitivity[[label]] <- CompareSensitivity(result, fit$result, label)
write.table(fit$result, paste0("outputs/differential_", label, "_r.tsv"),
sep = "\t", quote = FALSE, row.names = FALSE)
}
qc <- read.delim("/fixtures/qc.tsv")
tss <- qc$tss_enrichment[match(metadata$sample_id, qc$sample_id)]
stopifnot(all(is.finite(tss)), all(tss > 0))
tss_estimable <- FALSE
if (sd(log2(tss)) > 0) {
metadata$tss_scaled <- as.numeric(scale(log2(tss)))
tss_design <- model.matrix(~donor + condition + tss_scaled, metadata)
tss_estimable <- qr(tss_design)$rank == ncol(tss_design)
}
if (tss_estimable) {
tss_fit <- FitAccessibility(filtered, metadata,
~donor + condition + tss_scaled)
sensitivity[["TSS"]] <- CompareSensitivity(result, tss_fit$result, "TSS")
write.table(tss_fit$result, "outputs/differential_tss_r.tsv", sep = "\t",
quote = FALSE, row.names = FALSE)
}
sensitivity <- do.call(rbind, sensitivity)
write.table(sensitivity, "outputs/sensitivity_r.tsv", sep = "\t",
quote = FALSE, row.names = FALSE)
cat(sprintf("TSS sensitivity estimable: %s\n", tss_estimable))
for (i in seq_len(nrow(sensitivity))) {
cat(sprintf("%s discoveries=%d effect_r=%.4f median_change=%.4f\n",
sensitivity$sensitivity[i], sensitivity$discoveries[i],
sensitivity$effect_correlation[i],
sensitivity$median_effect_change[i]))
}
result$discovery <- result$padj < 0.05
ma_figure <- ggplot(result, aes(baseMean, log2FoldChange, color = discovery)) +
geom_point(size = 0.45, alpha = 0.35) + scale_x_log10() +
geom_hline(yintercept = 0, color = "gray60") +
scale_color_manual(values = c("#9a9a9a", "#c95d35")) +
theme_bw(base_size = 11) +
labs(x = "Mean normalized assigned count",
y = "Stimulated versus resting, log2 fold change", color = "FDR < 0.05")
ggsave("outputs/accessibility_ma_r.png", ma_figure,
width = 7, height = 4.6, dpi = 160)
sensitivity_figure <- ggplot(sensitivity,
aes(sensitivity, median_effect_change)) +
geom_col(fill = "#287d8e") + theme_bw(base_size = 11) +
labs(x = "Sensitivity fit", y = "Median absolute change in log2 effect")
ggsave("outputs/accessibility_sensitivity_r.png", sensitivity_figure,
width = 7, height = 4.2, dpi = 160)
write_json(list(regions = nrow(filtered), samples = ncol(filtered),
count_total = sum(filtered),
design_rank = qr(model.matrix(~donor + condition,
metadata))$rank),
"outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)
Tested regions: 48292; discoveries: 24573; increased: 14116
Motif foreground regions: 13447
TSS sensitivity estimable: TRUE
TMM discoveries=23873 effect_r=1.0000 median_change=0.0633
omit_1001 discoveries=15874 effect_r=0.9914 median_change=0.1189
omit_1002 discoveries=23272 effect_r=0.9910 median_change=0.1324
omit_1003 discoveries=18849 effect_r=0.9891 median_change=0.1351
omit_1004 discoveries=21461 effect_r=0.9890 median_change=0.1370
TSS discoveries=25317 effect_r=0.9994 median_change=0.0120

The MA plot shows unshrunk donor-adjusted effects.

The sensitivity plot measures effect changes after each declared alteration.

The deterministic checks require identical region identifiers, count totals, sample order, and design rank. Size factors must agree within the declared absolute tolerance. Dispersion estimation and coefficient optimization are separate implementations, so the report measures their differences instead of requiring identical p-values. A result near the discovery threshold can change its label even when its estimated effect changes little.

The completed primary R fit reports 24,573 discoveries among 48,292 regions; Python reports 24,637. Their 66 discordant discovery labels comprise one R-only result and 65 Python-only results, all near the adjusted p-value threshold of 0.05. None changes effect direction. Close implementation agreement does not establish stability to the choice of donors.

Both primary fits pass their coefficient convergence checks and retain the declared parametric dispersion trend. The exported tables omit separate dispersion convergence fields, so they cannot establish complete dispersion convergence. PyDESeq2 warns about dispersion-prior estimation with three residual degrees of freedom. Its pinned implementation warns at three or fewer; this warning does not indicate a design-rank error.

The omission fits can lose discoveries because they remove information as well as donor influence. Compare effect sizes alongside discovery counts; loss of significance alone does not establish a reversed biological effect. Each omitted pair leaves only two residual degrees of freedom.

All 24,573 primary discoveries retain their estimated direction in every declared sensitivity fit and in Python. That statement applies to the primary discovery set; some other tested regions change estimated sign. The two donors with the clearest QC limits retain the following memberships from the primary result when omitted.

Omitted donor Primary discoveries retained Primary foreground regions retained
1002 22,222 12,696
1003 18,494 10,581

At Interval_42062, omission of donor 1003 changes the estimated log2 fold change from 4.616 to 2.840 and the adjusted p-value from 0.0167 to 0.1668. The direction persists while the magnitude and discovery label change. Omitting donor 1001 loses 8,714 primary discoveries, the largest loss among the four omissions. These comparisons do not identify the cause of donor 1003’s alignment loss or show that the QC deficits are harmless.

The TMM fit tests one alternative normalization reference, not an absolute accessibility calibration. The TSS fit addresses a conditional association that can differ from the main treatment comparison.

Preserve the primary foreground definition

Section titled “Preserve the primary foreground definition”

Only 9,215 of the 13,447 primary foreground regions satisfy the same foreground rule in every R sensitivity fit. That intersection describes dependence on donors and model choices; it does not replace the declared foreground. The motif analysis remains conditional on the primary set.

The primary DESeq2 table supplies subsequent motif and visualization inputs. The original study used limma-voom with donor and TSS terms, so these models demonstrate a new analysis of the selected cohort rather than a reproduction of every published result. The method references are DESeq2, PyDESeq2, and TMM normalization.

Love, Huber, and Anders, 2014 describe the DESeq2 count model and its shrinkage of dispersion and fold change estimates.

Chen and colleagues, 2025 describe edgeR version 4 and its differential analysis of sequencing count data.

Muzellec and colleagues, 2023 describe PyDESeq2, the Python implementation of the DESeq2 method.

The DESeq2 model guide explains design formulas, contrasts, and dispersion estimation. The donor term accounts for the four paired comparisons used here.

The PyDESeq2 0.5.3 example documents the model and Wald-test interfaces. It provides the API context for the Python implementation.