Show donor pairs and genomic tracks
A group summary can hide a response driven by one donor. Paired count plots show each donor before and after stimulation, while a genomic track shows where fragments cover the selected interval. These displays answer different questions and use different normalizations.
State how the displayed regions enter the figure
Section titled “State how the displayed regions enter the figure”The count panels show up to six regions with adjusted p-values below 0.05, log2 fold changes of at least one, and mean normalized counts of at least 50. They rank by adjusted p-value, raw p-value, and region identifier. The heatmap uses the same regions and preserves donor order. These regions illustrate selected model results; they are not independent validation data.
The track window covers the first selected region plus 5,000 reference bases on each side, clipped to the chromosome bounds. The preparation extracts that same window from each fresh bigWig and preserves local bigWig and BEDGraph files. Both languages read the BEDGraph intervals and calculate length-weighted means in 50-base display bins, including uncovered bases as zero. The final bin can contain fewer than 50 bases.
The completed export uses chr12:24987051-24998140 on GRCh37/hg19 around
Interval_10778. These coordinates give the manifest’s zero-based start
and exclusive end. Each of the eight sample tracks contains 222 bins;
the first 221 span 50 bases each, and the last spans 39 bases. The primary
model selected this window, so its track pattern cannot independently
validate the reported condition effect.
Keep the two normalization scales distinct
Section titled “Keep the two normalization scales distinct”The count plots divide integer region assignments by the primary DESeq2 size
factors. Their heatmap centers and scales log2(normalized count + 1) within
each region, so its colors describe relative sample patterns and cannot
compare abundance between regions.
The nf-core track process uses paired fragment coverage from
bedtools genomecov -pc. Its scale factor is one million divided by mapped
alignments, with the decimal precision written by the pipeline. The track
unit is therefore fragment coverage per million mapped alignments.
It is not the DESeq2 normalized count, and it does not measure absolute
accessibility. Every sample track shares one vertical scale.
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)
metadata <- read.delim("/fixtures/metadata.tsv", colClasses = "character")metadata <- metadata[order(metadata$donor, metadata$condition), ]selected <- read.delim("/fixtures/display_regions.tsv")factors <- read.delim("/fixtures/size_factors_r.tsv")factors <- factors[match(metadata$sample_id, factors$sample_id), ]stopifnot(identical(factors$sample_id, metadata$sample_id))counts <- read.delim(gzfile("/fixtures/counts.tsv.gz"), row.names = 1, check.names = FALSE)counts <- as.matrix(counts[selected$region_id, metadata$sample_id])normalized <- sweep(counts, 2, factors$size_factor, "/")log_counts <- log2(normalized + 1)row_z <- t(scale(t(log_counts)))stopifnot(all(is.finite(row_z)))count_data <- data.frame( region_id = rep(selected$region_id, each = nrow(metadata)), sample_id = rep(metadata$sample_id, nrow(selected)), normalized_count = as.vector(t(normalized)), row_z = as.vector(t(row_z)))count_data$donor <- metadata$donor[ match(count_data$sample_id, metadata$sample_id)]count_data$condition <- metadata$condition[ match(count_data$sample_id, metadata$sample_id)]manifest <- fromJSON("/fixtures/track_export/manifest.json")starts <- seq(manifest$start, manifest$end - 1L, by = 50L)ends <- pmin(starts + 50L, manifest$end)tracks <- list()for (sample_id in metadata$sample_id) { path <- file.path("/fixtures/track_export", paste0(sample_id, ".bedgraph")) coverage <- numeric(manifest$end - manifest$start) if (file.info(path)$size > 0) { intervals <- read.delim(path, header = FALSE, col.names = c("chrom", "start", "end", "value")) stopifnot(all(intervals$chrom == manifest$chrom)) stopifnot(all(intervals$start >= manifest$start)) stopifnot(all(intervals$end <= manifest$end)) stopifnot(all(intervals$start[-1] >= head(intervals$end, -1))) for (i in seq_len(nrow(intervals))) { first <- intervals$start[i] - manifest$start + 1L last <- intervals$end[i] - manifest$start coverage[first:last] <- intervals$value[i] } } bin_means <- numeric(length(starts)) for (i in seq_along(starts)) { first <- starts[i] - manifest$start + 1L last <- ends[i] - manifest$start bin_means[i] <- mean(coverage[first:last]) } tracks[[sample_id]] <- data.frame(sample_id = sample_id, start = starts, end = ends, coverage = bin_means)}track_data <- do.call(rbind, tracks)dir.create("outputs", showWarnings = FALSE)write.table(count_data, "outputs/display_counts_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(track_data, "outputs/display_tracks_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)metrics <- list(regions = nrow(selected), samples = nrow(metadata), bins = length(starts), track_sum = sum(track_data$coverage), normalized_sum = sum(normalized))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)cat(sprintf("Displayed regions: %d; sample tracks: %d; bins per track: %d\n", metrics$regions, metrics$samples, metrics$bins))cat(sprintf("GRCh37 window: %s:%d-%d; selected region: %s\n", manifest$chrom, manifest$start, manifest$end, manifest$selected_region))cat(sprintf("Track unit: %s\n", manifest$units))pair_figure <- ggplot(count_data, aes(condition, normalized_count, group = donor, color = donor)) + geom_line(linewidth = 0.6) + geom_point(size = 2) + facet_wrap(~ region_id, scales = "free_y", ncol = 3) + scale_y_continuous(trans = "log1p") + theme_bw(base_size = 10) + labs(x = "Condition", y = "Normalized count, log1p scale", color = "Donor")ggsave("outputs/region_pairs_r.png", pair_figure, width = 9, height = 5.5, dpi = 160)count_data$sample_id <- factor(count_data$sample_id, levels = metadata$sample_id)count_data$region_id <- factor(count_data$region_id, levels = rev(selected$region_id))heatmap_figure <- ggplot(count_data, aes(sample_id, region_id, fill = row_z)) + geom_tile() + scale_fill_gradient2(low = "#2166ac", high = "#b2182b") + theme_bw(base_size = 10) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + labs(x = "Sample in donor order", y = "Region", fill = "Within-region z")ggsave("outputs/region_heatmap_r.png", heatmap_figure, width = 8, height = 4.5, dpi = 160)track_data$sample_id <- factor(track_data$sample_id, levels = metadata$sample_id)track_figure <- ggplot(track_data, aes((start + end) / 2, coverage)) + annotate("rect", xmin = selected$start[1], xmax = selected$end[1], ymin = -Inf, ymax = Inf, fill = "#d5b86d", alpha = 0.25) + geom_area(fill = "#347c8b") + facet_wrap(~ sample_id, ncol = 1) + theme_bw(base_size = 9) + labs(x = paste(manifest$chrom, "GRCh37 reference position"), y = "Fragment coverage per million mapped alignments")ggsave("outputs/genomic_tracks_r.png", track_figure, width = 8, height = 9, dpi = 160)dir.create("outputs/track_export", showWarnings = FALSE)exports <- list.files("/fixtures/track_export", full.names = TRUE)stopifnot(all(file.copy(exports, "outputs/track_export", overwrite = TRUE)))Displayed regions: 6; sample tracks: 8; bins per track: 222GRCh37 window: chr12:24987051-24998140; selected region: Interval_10778Track unit: Fragment coverage per million mapped alignments


import jsonimport shutilfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
metadata = pd.read_csv("/fixtures/metadata.tsv", sep="\t", dtype=str)metadata = metadata.sort_values(["donor", "condition"]).reset_index(drop=True)selected = pd.read_csv("/fixtures/display_regions.tsv", sep="\t")factors = pd.read_csv("/fixtures/size_factors_r.tsv", sep="\t")factors = factors.set_index("sample_id").loc[metadata["sample_id"]]counts = pd.read_csv("/fixtures/counts.tsv.gz", sep="\t", index_col=0)counts = counts.loc[selected["region_id"], metadata["sample_id"]]normalized = counts.to_numpy() / factors["size_factor"].to_numpy()log_counts = np.log2(normalized + 1)row_z = ((log_counts - log_counts.mean(axis=1, keepdims=True)) / log_counts.std(axis=1, ddof=1, keepdims=True))assert np.isfinite(row_z).all()count_data = pd.DataFrame({ "region_id": np.repeat(selected["region_id"], len(metadata)), "sample_id": np.tile(metadata["sample_id"], len(selected)), "normalized_count": normalized.ravel(), "row_z": row_z.ravel()})count_data = count_data.merge(metadata[["sample_id", "donor", "condition"]], on="sample_id", validate="many_to_one")manifest = json.loads(Path("/fixtures/track_export/manifest.json").read_text())starts = np.arange(manifest["start"], manifest["end"], 50)ends = np.minimum(starts + 50, manifest["end"])tracks = []for sample_id in metadata["sample_id"]: path = Path("/fixtures/track_export") / f"{sample_id}.bedgraph" coverage = np.zeros(manifest["end"] - manifest["start"]) if path.stat().st_size: intervals = pd.read_csv(path, sep="\t", header=None, names=["chrom", "start", "end", "value"]) assert intervals["chrom"].eq(manifest["chrom"]).all() assert intervals["start"].ge(manifest["start"]).all() assert intervals["end"].le(manifest["end"]).all() assert np.all(intervals["start"].to_numpy()[1:] >= intervals["end"].to_numpy()[:-1]) for row in intervals.itertuples(): left = row.start - manifest["start"] right = row.end - manifest["start"] coverage[left:right] = row.value bin_means = [] for left, right in zip(starts, ends, strict=True): bin_means.append(coverage[left - manifest["start"]: right - manifest["start"]].mean()) tracks.append(pd.DataFrame({"sample_id": sample_id, "start": starts, "end": ends, "coverage": bin_means}))track_data = pd.concat(tracks, ignore_index=True)output = Path("outputs")output.mkdir(exist_ok=True)count_data.to_csv(output / "display_counts_python.tsv", sep="\t", index=False)track_data.to_csv(output / "display_tracks_python.tsv", sep="\t", index=False)r_counts = pd.read_csv(output / "display_counts_r.tsv", sep="\t", dtype={"donor": str})pd.testing.assert_frame_equal(count_data, r_counts, check_dtype=False, atol=1e-8, rtol=0)r_tracks = pd.read_csv(output / "display_tracks_r.tsv", sep="\t")pd.testing.assert_frame_equal(track_data, r_tracks, check_dtype=False, atol=1e-8, rtol=0)metrics = {"regions": len(selected), "samples": len(metadata), "bins": len(starts), "track_sum": float(track_data["coverage"].sum()), "normalized_sum": float(normalized.sum())}(output / "metrics_python.json").write_text(json.dumps(metrics))print(f"Displayed regions: {metrics['regions']}; " f"sample tracks: {metrics['samples']}; bins per track: {metrics['bins']}")print(f"GRCh37 window: {manifest['chrom']}:{manifest['start']}-" f"{manifest['end']}; selected region: {manifest['selected_region']}")print(f"Track unit: {manifest['units']}")figure, axes = plt.subplots(2, 3, figsize=(9, 5.5))for axis, region_id in zip(axes.flat, selected["region_id"]): frame = count_data.loc[count_data["region_id"].eq(region_id)] for donor, rows in frame.groupby("donor", sort=True): axis.plot(rows["condition"], np.log1p(rows["normalized_count"]), marker="o", linewidth=0.8, label=donor) axis.set(title=region_id, ylabel="log1p normalized count")for axis in list(axes.flat)[len(selected):]: axis.set_visible(False)axes.flat[0].legend(title="Donor", fontsize=8)figure.tight_layout()figure.savefig(output / "region_pairs_python.png", dpi=160)plt.close(figure)figure, axis = plt.subplots(figsize=(8, 4.5))limit = np.abs(row_z).max()heatmap = axis.imshow(row_z, aspect="auto", cmap="RdBu_r", vmin=-limit, vmax=limit)axis.set_xticks(np.arange(len(metadata)), metadata["sample_id"], rotation=45, ha="right")axis.set_yticks(np.arange(len(selected)), selected["region_id"])axis.set(xlabel="Sample in donor order", ylabel="Region")figure.colorbar(heatmap, ax=axis, label="Within-region z")figure.tight_layout()figure.savefig(output / "region_heatmap_python.png", dpi=160)plt.close(figure)figure, axes = plt.subplots(8, 1, figsize=(8, 9), sharex=True, sharey=True)maximum = track_data["coverage"].max() * 1.05for axis, sample_id in zip(axes, metadata["sample_id"], strict=True): frame = track_data.loc[track_data["sample_id"].eq(sample_id)] axis.axvspan(selected["start"].iloc[0], selected["end"].iloc[0], color="#d5b86d", alpha=0.25) axis.fill_between((frame["start"] + frame["end"]) / 2, frame["coverage"], color="#347c8b") axis.set_ylim(0, maximum) axis.set_ylabel(sample_id, rotation=0, ha="right", va="center", labelpad=12, fontsize=8)axes[-1].set_xlabel(f"{manifest['chrom']} GRCh37 reference position")figure.suptitle("Fragment coverage per million mapped alignments")figure.tight_layout()figure.savefig(output / "genomic_tracks_python.png", dpi=160)plt.close(figure)(output / "track_export").mkdir(exist_ok=True)for path in Path("/fixtures/track_export").iterdir(): shutil.copyfile(path, output / "track_export" / path.name)Displayed regions: 6; sample tracks: 8; bins per track: 222GRCh37 window: chr12:24987051-24998140; selected region: Interval_10778Track unit: Fragment coverage per million mapped alignments


Use the local track export with its manifest
Section titled “Use the local track export with its manifest”The run writes outputs/track_export/ with eight windowed bigWigs, eight
BEDGraph files, the local consensus BED, and manifest.json. Load those files
with the hg19 assembly in a local genome browser. The exported bigWigs contain
this window only; absent coverage elsewhere in those files says nothing
about the rest of the genome. The complete primary bigWigs remain in the
primary execution outputs.
Keep the shared vertical scale when comparing donors. A visually tall peak does not establish a nearby gene as its target, and a heatmap pattern does not replace the paired model or its donor omission checks.
Further reading
Section titled “Further reading”The nf-core/atacseq 2.1.2 usage guide describes the processing choices behind the count and coverage files. A track and a normalized count summarize different parts of those outputs.
The DESeq2 transformation guide explains transformed counts and sample exploration. It provides context for the heatmap and paired donor displays.