Motif enrichment in accessible regions
A motif enrichment result depends on the sequences used as its background. Longer regions offer more possible match positions, GC content changes the sequence alphabet available to a motif, and mean accessibility changes which regions enter a differential foreground. A comparison against arbitrary genomic sequence mixes these effects with the biological contrast.
Define the foreground before the scan
Section titled “Define the foreground before the scan”The foreground contains tested regions with a DESeq2 adjusted p-value below 0.05 and a stimulated-versus-resting log2 fold change of at least one. This uses the primary R model from the differential lesson. Regions containing ambiguous reference bases leave the motif analysis only; their exclusion does not change the accessibility model.
The background pool contains the other sequence-eligible tested regions.
The preparation matches one background region to each foreground region
without replacement, using GC fraction, natural log sequence length, and
log1p mean normalized count. It standardizes those features over the eligible
tested regions and uses greedy Euclidean nearest neighbors in a fixed random
foreground order. The seed is 20261031.
A second background draws the same number of regions at random from the same pool with one fixed seed. It provides a sensitivity comparison for the matching decision, without independent biological replication or a repeated randomization null distribution. Neither background includes a foreground region. The two backgrounds can overlap each other because they answer separate comparisons.
Keep the scan separate from the enrichment test
Section titled “Keep the scan separate from the enrichment test”The shared scan uses FIMO 5.5.9 and the JASPAR 2026 CORE vertebrate collection. It scans the union of the three selected sets on both strands. Its zero-order base frequencies come from all sequence-eligible tested regions and average each base with its complement. Every comparison therefore uses the same motif scores and sequence background model.
FIMO retains sites with a p-value below 1e-4. Text mode avoids the stored-score
limit and omits site q-values, as the
FIMO documentation specifies.
The companion preserves the full scan and records its container digest,
command, sequence hashes, and motif hash. The lessons use a compact presence
table with one row per region and motif, regardless of the number of sites.
The enrichment test asks whether a motif occurs in a larger fraction of the foreground than the background. Its one-sided Fisher exact test uses the hypergeometric upper tail. Benjamini-Hochberg correction covers every motif in the declared collection, including motifs with no retained sites. The matched and random comparisons each have a separate 1,019-motif correction family. These adjusted enrichment p-values are separate from FIMO’s site threshold.
Compare backgrounds and inspect balance
Section titled “Compare backgrounds and inspect balance”The reported odds ratio adds 0.5 to each cell so empty cells yield a finite effect estimate. This correction affects the displayed effect only; the exact test uses the original integer counts. Balance uses the foreground minus background mean divided by their pooled standard deviation. A large remaining difference limits the interpretation of the matched comparison.
The prepared matched background improves balance for all three features,
but its mean GC fraction remains 0.455927 against 0.422455 in the foreground.
The standardized GC difference is -0.549413, compared with -1.582897 for
the random background. Matched differences are 0.014763 for log length and
-0.124799 for log1p mean count. Residual GC imbalance confounds the motif
comparisons, so their results cannot isolate transcription-factor effects.
Both enrichment plots display 15 matched-comparison motifs from a set of 28 whose tail probabilities underflow to zero in both implementations. Their adjusted p-values are also zero at the stored precision. Motif identifiers break those ties, so the displayed order does not resolve their relative tail probabilities. The color scale caps negative log10 adjusted p-values at 300 and cannot distinguish these tied values.
The motif definitions come from the JASPAR 2026 collection, maintained by the JASPAR consortium under CC BY 4.0. The companion scan converts these motifs into region-level presence records. This lesson compares those records between foreground regions and the two declared backgrounds.
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(ggplot2)library(jsonlite)
regions <- read.delim("/fixtures/motif_regions.tsv")catalog <- read.delim("/fixtures/motif_catalog.tsv")catalog <- catalog[order(catalog$motif_id), ]presence <- read.delim(gzfile("/fixtures/motif_presence.tsv.gz"))stopifnot(!anyDuplicated(presence[, c("region_id", "motif_id")]))stopifnot(all(presence$motif_id %in% catalog$motif_id))foreground <- regions$sequence_eligible & regions$foregroundforeground_ids <- regions$region_id[foreground]foreground_hits <- tabulate(match(presence$motif_id[ presence$region_id %in% foreground_ids], catalog$motif_id), nbins = nrow(catalog))results <- list()balance_rows <- list()for (background_name in c("matched", "random")) { background <- regions[[paste0(background_name, "_background")]] stopifnot(!any(foreground & background)) stopifnot(sum(background) == sum(foreground)) background_ids <- regions$region_id[background] background_hits <- tabulate(match(presence$motif_id[ presence$region_id %in% background_ids], catalog$motif_id), nbins = nrow(catalog)) a <- foreground_hits b <- sum(foreground) - a c <- background_hits d <- sum(background) - c pvalue <- phyper(a - 1L, a + c, b + d, sum(foreground), lower.tail = FALSE) results[[background_name]] <- data.frame( motif_id = catalog$motif_id, background = background_name, foreground_hit = a, foreground_absent = b, background_hit = c, background_absent = d, odds_ratio = ((a + 0.5) * (d + 0.5)) / ((b + 0.5) * (c + 0.5)), pvalue = pvalue, padj = p.adjust(pvalue, method = "BH") ) for (feature in c("gc", "log_length", "log_mean")) { x <- regions[[feature]][foreground] y <- regions[[feature]][background] pooled_sd <- sqrt((var(x) + var(y)) / 2) stopifnot(pooled_sd > 0) balance_rows[[length(balance_rows) + 1L]] <- data.frame( background = background_name, feature = feature, foreground_mean = mean(x), background_mean = mean(y), standardized_difference = (mean(x) - mean(y)) / pooled_sd ) }}result <- do.call(rbind, results)balance <- do.call(rbind, balance_rows)dir.create("outputs", showWarnings = FALSE)write.table(result, "outputs/motif_enrichment_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(balance, "outputs/motif_balance_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)matched <- results$matchedrandom <- results$randommetrics <- list(motifs = nrow(catalog), foreground = sum(foreground), matched_discoveries = sum(matched$padj < 0.05), random_discoveries = sum(random$padj < 0.05), discordant = sum((matched$padj < 0.05) != (random$padj < 0.05)))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)cat(sprintf("Foreground regions: %d; motifs: %d\n", metrics$foreground, metrics$motifs))cat(sprintf("Enriched motifs: matched=%d; random=%d; discordant=%d\n", metrics$matched_discoveries, metrics$random_discoveries, metrics$discordant))for (i in seq_len(nrow(balance))) { cat(sprintf("%s %s standardized difference: %.6f\n", balance$background[i], balance$feature[i], balance$standardized_difference[i]))}selected <- order(matched$padj, matched$pvalue, matched$motif_id)[1:15]display <- matched[selected, ]display$label <- paste(catalog$motif_name[selected], display$motif_id)display$label <- factor(display$label, levels = rev(display$label))enrichment_figure <- ggplot(display, aes(log2(odds_ratio), label, color = -log10(pmax(padj, 1e-300)))) + geom_point(size = 3) + theme_bw(base_size = 10) + labs(x = "log2 corrected odds ratio", y = NULL, color = "Negative log10\nadjusted p-value")ggsave("outputs/motif_enrichment_r.png", enrichment_figure, width = 8, height = 5.7, dpi = 160)balance_figure <- ggplot(balance, aes(standardized_difference, feature, color = background)) + geom_vline(xintercept = c(-0.1, 0.1), linetype = "dotted") + geom_point(size = 3) + theme_bw(base_size = 11) + labs(x = "Standardized foreground minus background difference", y = NULL, color = "Background")ggsave("outputs/motif_balance_r.png", balance_figure, width = 8, height = 3.5, dpi = 160)Foreground regions: 13447; motifs: 1019Enriched motifs: matched=395; random=442; discordant=107matched gc standardized difference: -0.549413matched log_length standardized difference: 0.014763matched log_mean standardized difference: -0.124799random gc standardized difference: -1.582897random log_length standardized difference: -0.627423random log_mean standardized difference: -0.837897

The motif definitions come from the JASPAR 2026 collection, maintained by the JASPAR consortium under CC BY 4.0. The companion scan converts these motifs into region-level presence records. This lesson compares those records between foreground regions and the two declared backgrounds.
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy.stats import hypergeomfrom statsmodels.stats.multitest import multipletests
regions = pd.read_csv("/fixtures/motif_regions.tsv", sep="\t")catalog = pd.read_csv("/fixtures/motif_catalog.tsv", sep="\t")catalog = catalog.sort_values("motif_id").reset_index(drop=True)presence = pd.read_csv("/fixtures/motif_presence.tsv.gz", sep="\t")assert not presence.duplicated(["region_id", "motif_id"]).any()assert presence["motif_id"].isin(catalog["motif_id"]).all()foreground = regions["sequence_eligible"] & regions["foreground"]foreground_ids = regions.loc[foreground, "region_id"]foreground_hits = presence.loc[ presence["region_id"].isin(foreground_ids), "motif_id"].value_counts()foreground_hits = foreground_hits.reindex(catalog["motif_id"], fill_value=0)results = []balance_rows = []for background_name in ["matched", "random"]: background = regions[f"{background_name}_background"] assert not (foreground & background).any() assert background.sum() == foreground.sum() background_ids = regions.loc[background, "region_id"] background_hits = presence.loc[ presence["region_id"].isin(background_ids), "motif_id"].value_counts() background_hits = background_hits.reindex(catalog["motif_id"], fill_value=0) a = foreground_hits.to_numpy() b = int(foreground.sum()) - a c = background_hits.to_numpy() d = int(background.sum()) - c pvalue = hypergeom.sf(a - 1, a + b + c + d, a + c, a + b) results.append(pd.DataFrame({ "motif_id": catalog["motif_id"], "background": background_name, "foreground_hit": a, "foreground_absent": b, "background_hit": c, "background_absent": d, "odds_ratio": ((a + 0.5) * (d + 0.5)) / ((b + 0.5) * (c + 0.5)), "pvalue": pvalue, "padj": multipletests(pvalue, method="fdr_bh")[1]})) for feature in ["gc", "log_length", "log_mean"]: x = regions.loc[foreground, feature] y = regions.loc[background, feature] pooled_sd = np.sqrt((x.var(ddof=1) + y.var(ddof=1)) / 2) assert pooled_sd > 0 balance_rows.append({ "background": background_name, "feature": feature, "foreground_mean": x.mean(), "background_mean": y.mean(), "standardized_difference": (x.mean() - y.mean()) / pooled_sd})result = pd.concat(results, ignore_index=True)balance = pd.DataFrame(balance_rows)output = Path("outputs")output.mkdir(exist_ok=True)result.to_csv(output / "motif_enrichment_python.tsv", sep="\t", index=False)balance.to_csv(output / "motif_balance_python.tsv", sep="\t", index=False)r_result = pd.read_csv(output / "motif_enrichment_r.tsv", sep="\t")pd.testing.assert_frame_equal(result.iloc[:, :6], r_result.iloc[:, :6], check_dtype=False)np.testing.assert_allclose(result["odds_ratio"], r_result["odds_ratio"], atol=1e-8, rtol=1e-12)np.testing.assert_allclose(result[["pvalue", "padj"]], r_result[["pvalue", "padj"]], atol=1e-10, rtol=0)r_balance = pd.read_csv(output / "motif_balance_r.tsv", sep="\t")pd.testing.assert_frame_equal(balance, r_balance, check_dtype=False, atol=1e-8, rtol=0)matched, random = resultsmetrics = {"motifs": len(catalog), "foreground": int(foreground.sum()), "matched_discoveries": int(matched["padj"].lt(0.05).sum()), "random_discoveries": int(random["padj"].lt(0.05).sum()), "discordant": int((matched["padj"].lt(0.05) != random["padj"].lt(0.05)).sum())}(output / "metrics_python.json").write_text(json.dumps(metrics))print(f"Foreground regions: {metrics['foreground']}; " f"motifs: {metrics['motifs']}")print(f"Enriched motifs: matched={metrics['matched_discoveries']}; " f"random={metrics['random_discoveries']}; " f"discordant={metrics['discordant']}")for row in balance.itertuples(): print(f"{row.background} {row.feature} standardized difference: " f"{row.standardized_difference:.6f}")display = matched.sort_values(["padj", "pvalue", "motif_id"]).head(15)display = display.merge(catalog, on="motif_id", validate="one_to_one")labels = display["motif_name"] + " " + display["motif_id"]figure, axis = plt.subplots(figsize=(8, 5.7))points = axis.scatter(np.log2(display["odds_ratio"]), labels, c=-np.log10(display["padj"].clip(lower=1e-300)), vmin=0, vmax=300)axis.invert_yaxis()axis.set_xlabel("log2 corrected odds ratio")figure.colorbar(points, ax=axis, label="Negative log10 adjusted p-value")figure.tight_layout()figure.savefig(output / "motif_enrichment_python.png", dpi=160)plt.close(figure)figure, axis = plt.subplots(figsize=(8, 3.5))for name, frame in balance.groupby("background", sort=True): axis.scatter(frame["standardized_difference"], frame["feature"], label=name)for threshold in [-0.1, 0.1]: axis.axvline(threshold, linestyle=":", color="0.6")axis.set_xlabel("Standardized foreground minus background difference")axis.legend(title="Background")figure.tight_layout()figure.savefig(output / "motif_balance_python.png", dpi=160)plt.close(figure)Foreground regions: 13447; motifs: 1019Enriched motifs: matched=395; random=442; discordant=107matched gc standardized difference: -0.549413matched log_length standardized difference: 0.014763matched log_mean standardized difference: -0.124799random gc standardized difference: -1.582897random log_length standardized difference: -0.627423random log_mean standardized difference: -0.837897

Interpret sequence preferences within the tested universe
Section titled “Interpret sequence preferences within the tested universe”The matched comparison reports 395 enriched motifs at adjusted p-value below 0.05, while the random comparison reports 442. They share 365 calls; 30 occur only with the matched background and 77 only with the random background. The 107 different calls show that background choice changes the reported associations within this foreground. Each comparison retains its separate correction family, and the residual GC difference remains a limit on both biological interpretation and comparisons between backgrounds.
Foreground regions come from the same experiment that defines mean accessibility, so this analysis describes sequence associations within the observed response. It does not independently validate the accessibility discoveries. Background sensitivity and residual imbalance belong beside the enrichment results because either can change their biological meaning.
Related transcription factors often recognize similar motifs. A match cannot identify which family member binds, whether that factor is expressed, or whether its binding caused the accessibility change. Those claims require additional evidence from expression, occupancy assays, or perturbation. The annotation lesson applies the same separation between a measured association and a regulatory claim.
Scientific references
Section titled “Scientific references”The motif collection comes from JASPAR, which states CC BY 4.0. The companion manifest identifies the 2026 collection used here. Motif data attribution is separate from the origin of the enrichment code.
Further reading
Section titled “Further reading”The FIMO manual defines motif scanning, score thresholds, and output modes. These settings determine the presence table used by the enrichment test.
The JASPAR terms and FAQ describe the motif collection and its CC BY 4.0 terms. The companion manifest fixes the 2026 collection used here.