ATAC-seq quality checks
Quality review precedes the accessibility model. Fragment lengths, TSS enrichment, mitochondrial alignments, duplication, and peak overlap describe different properties of a library. No single number can establish that a sample supports the intended biological comparison.
Keep each metric’s denominator
Section titled “Keep each metric’s denominator”The companion preparation preserves the fresh Bowtie2, ataqv, and Picard reports and independently examines every cleaned BAM. The examples read those checked records rather than estimating quality from a count-matrix column sum.
| Measurement | Definition used here |
|---|---|
| Mapped-mate fraction | Bowtie2’s mapped mates are divided by twice its trimmed input-pair count, before downstream alignment filters. |
| Unmapped mates | These mates remain unaligned after concordant, discordant, and individual-mate searches. |
| Mitochondrial fraction | The numerator is ataqv’s mitochondrial alignments, and the denominator is its properly paired, mapped alignments. |
| Duplicate fraction | Picard counts duplicate unpaired reads plus twice the duplicate pairs, divided by the corresponding examined reads. |
| Fragment lengths | Each primary, proper autosomal pair in the cleaned BAM contributes once through read 1 and its template length. |
| TSS enrichment | Ataqv reports its central fragment-coverage value after normalization to the outer 100 bases of each flank. |
| Unique alignment FRiP | Each mapped alignment contributes at most once when at least 20% of its span overlaps a called peak. |
| Unique fragment FRiP | Each eligible cleaned autosomal pair contributes once when its outer fragment span overlaps the merged sample peak union. |
The two FRiP definitions deliberately use different units and overlap rules. Their values need not agree. ATAC release 2.1.2 sums alignment-to-peak overlaps for its reported FRiP, so one alignment can contribute more than once. The preparation reproduces that reported calculation and also counts unique alignments. The upstream issue describes the repeated-count problem.
The archive read names lack the tile and position fields needed for Picard’s optical duplicate classification. The primary logs report this parsing failure. A zero optical count therefore cannot establish that optical duplicates are absent. The total duplicate fraction remains a measure based on alignment coordinates; it does not establish the cause of repeated fragments. The Picard read-name parser and optical comparison define these requirements.
Picard’s estimated library size uses an optical correction that these names cannot validate. Its metric formulas keep that estimate separate from total duplication. The Preseq curve uses a separate calculation on marked alignments that retain duplicates. Its projection cannot recover the missing optical information.
The TSS profile uses the declared GENCODE v19 gene starts and ataqv 1.3.1. Its implementation measures fragment coverage around those positions, rather than a separate insertion-site profile. The ataqv source defines that calculation. TSS thresholds from another annotation or algorithm cannot transfer unchanged to this profile.
Inspect paired samples together
Section titled “Inspect paired samples together”The mitochondrial and duplicate reports precede the final removal of those alignments. The fragment distribution and independent FRiP checks use the cleaned BAMs after alignment filters. The table retains those distinct stages so a low final mitochondrial count cannot conceal an inefficient original library.
The original FastQC reports count every read in each complete input file. The preparation requires equal mate counts and preserves the observed length ranges. A prefix check establishes read-name structure but cannot establish the full input depth.
The separate alignment table retains all eight samples and names Bowtie2’s trimmed input pairs, input mates, mapped mates, and unmapped mates. The mapped fraction uses all input mates, including mates recovered after a concordant pair search fails. It does not count distinct usable fragments. Its denominator differs from original FASTQ depth and from every cleaned-fragment metric below. The final primary trace selects the eight source reports, and the preparation checks every reported count partition before it copies those reports.
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), ]qc <- read.delim("/fixtures/qc.tsv")qc <- qc[match(metadata$sample_id, qc$sample_id), ]stopifnot(identical(qc$sample_id, metadata$sample_id))read_qc <- read.delim("/fixtures/read_qc.tsv")mate_one <- read_qc[read_qc$mate == 1L, ]mate_two <- read_qc[read_qc$mate == 2L, ]mate_one <- mate_one[match(metadata$sample_id, mate_one$sample_id), ]mate_two <- mate_two[match(metadata$sample_id, mate_two$sample_id), ]stopifnot(identical(mate_one$sample_id, metadata$sample_id))stopifnot(identical(mate_two$sample_id, metadata$sample_id))stopifnot(all(mate_one$reads == mate_two$reads))qc$input_pairs <- mate_one$readsalignment <- read.delim("/fixtures/source/alignment/alignment_qc.tsv")stopifnot(nrow(alignment) == 8L, !anyDuplicated(alignment$sample_id))stopifnot(setequal(alignment$sample_id, metadata$sample_id))alignment <- alignment[match(metadata$sample_id, alignment$sample_id), ]identity_fields <- c("sample_id", "donor", "condition", "geo_accession", "run_accession")for (field in identity_fields) { stopifnot(identical(as.character(alignment[[field]]), metadata[[field]]))}alignment_columns <- c( input_pairs = "alignment_input_pairs", input_mates = "alignment_input_mates", mapped_mates = "alignment_mapped_mates", unaligned_mates = "alignment_unmapped_mates", mapped_mate_fraction = "alignment_mapped_mate_fraction")for (field in names(alignment_columns)) { difference <- qc[[alignment_columns[[field]]]] - alignment[[field]] stopifnot(all(is.finite(difference)), max(abs(difference)) < 1e-12)}alignment_counts <- qc[, unname(alignment_columns)[1:4]]stopifnot(all(is.finite(as.matrix(alignment_counts))))stopifnot(all(alignment_counts >= 0))stopifnot(all(alignment_counts == floor(as.matrix(alignment_counts))))stopifnot(all(qc$alignment_input_pairs > 0))stopifnot(all(qc$alignment_input_mates == 2 * qc$alignment_input_pairs))stopifnot(all(qc$alignment_mapped_mates + qc$alignment_unmapped_mates == qc$alignment_input_mates))mapped_fraction <- qc$alignment_mapped_mates / qc$alignment_input_matesstopifnot(max(abs(mapped_fraction - qc$alignment_mapped_mate_fraction)) < 1e-12)alignment_summary <- qc[, c("sample_id", unname(alignment_columns))]for (i in seq_len(nrow(qc))) { sample_id <- qc$sample_id[i] ataqv_path <- file.path("/fixtures/source/ataqv", paste0(sample_id, ".ataqv.json")) report <- fromJSON(ataqv_path, simplifyVector = FALSE)[[1]] stopifnot(report$ataqv_version == "1.3.1") raw <- report$metrics stopifnot(raw$name == sample_id) stopifnot(raw$total_mitochondrial_reads == qc$mitochondrial_reads[i]) stopifnot(raw$properly_paired_and_mapped_reads == qc$properly_paired_mapped_reads[i]) stopifnot(abs(raw$tss_enrichment - qc$tss_enrichment[i]) < 1e-8) picard_path <- file.path("/fixtures/source/picard", paste0(sample_id, ".mLb.mkD.sorted.MarkDuplicates.metrics.txt")) lines <- readLines(picard_path) header <- which(startsWith(lines, "LIBRARY\t")) stopifnot(length(header) == 1L) picard <- read.delim(text = paste(lines[header + 0:1], collapse = "\n")) fields <- c("UNPAIRED_READS_EXAMINED", "READ_PAIRS_EXAMINED", "UNPAIRED_READ_DUPLICATES", "READ_PAIR_DUPLICATES") for (field in fields) { stopifnot(picard[[field]] == qc[[tolower(field)]][i]) }}stopifnot(all(qc$properly_paired_mapped_reads > 0))qc$mitochondrial_fraction <- qc$mitochondrial_reads / qc$properly_paired_mapped_readsexamined <- qc$unpaired_reads_examined + 2 * qc$read_pairs_examinedduplicate <- qc$unpaired_read_duplicates + 2 * qc$read_pair_duplicatesqc$duplicate_fraction <- duplicate / examinedqc$unique_alignment_frip <- qc$unique_alignments_in_peaks / qc$clean_mapped_alignmentsqc$unique_fragment_frip <- qc$fragments_in_peak_union / qc$clean_autosomal_fragmentsduplicate_difference <- qc$duplicate_fraction - qc$picard_percent_duplicationstopifnot(max(abs(duplicate_difference)) < 1e-6)fractions <- c("mitochondrial_fraction", "duplicate_fraction", "unique_alignment_frip", "unique_fragment_frip")stopifnot(all(as.matrix(qc[, fractions]) >= 0))stopifnot(all(as.matrix(qc[, fractions]) <= 1))fragments <- read.delim("/fixtures/fragment_lengths.tsv")fragments <- fragments[order(fragments$sample_id, fragments$fragment_length), ]fragment_totals <- tapply(fragments$fragments, fragments$sample_id, sum)stopifnot(all(fragment_totals[qc$sample_id] == qc$clean_autosomal_fragments))fragments$fraction <- fragments$fragments / fragment_totals[fragments$sample_id]tss <- read.delim("/fixtures/tss_profiles.tsv")tss <- tss[order(tss$sample_id, tss$position), ]center <- tss[tss$position == 1001L, ]center <- center[match(qc$sample_id, center$sample_id), ]stopifnot(max(abs(center$enrichment - qc$tss_enrichment)) < 1e-8)preseq <- read.delim("/fixtures/preseq.tsv")stopifnot(setequal(preseq$sample_id, qc$sample_id))summary_columns <- c("sample_id", "input_pairs", "mitochondrial_fraction", "duplicate_fraction", "tss_enrichment", "unique_alignment_frip", "unique_fragment_frip")summary <- qc[, summary_columns]for (i in seq_len(nrow(alignment_summary))) { cat(sprintf("%s alignment_pairs=%d input_mates=%d\n", qc$sample_id[i], qc$alignment_input_pairs[i], qc$alignment_input_mates[i])) cat(sprintf(paste0(" mapped_mates=%d unmapped_mates=%d ", "mapped_fraction=%.6f\n"), qc$alignment_mapped_mates[i], qc$alignment_unmapped_mates[i], qc$alignment_mapped_mate_fraction[i]))}for (i in seq_len(nrow(summary))) { cat(sprintf("%s input_pairs=%d mate_lengths=%s/%s\n", summary$sample_id[i], summary$input_pairs[i], mate_one$length_range[i], mate_two$length_range[i])) cat(sprintf("%s mito=%.4f duplicate=%.4f TSS=%.4f\n", summary$sample_id[i], summary$mitochondrial_fraction[i], summary$duplicate_fraction[i], summary$tss_enrichment[i])) cat(sprintf(" alignment_FRiP=%.4f fragment_FRiP=%.4f repeated=%d\n", summary$unique_alignment_frip[i], summary$unique_fragment_frip[i], qc$alignments_overlapping_multiple_peaks[i]))}dir.create("outputs", showWarnings = FALSE)write.table(alignment_summary, "outputs/alignment_summary_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)write.table(summary, "outputs/qc_summary_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)write.table(fragments, "outputs/fragment_profiles_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)metrics <- list(samples = nrow(qc), fragments = sum(fragment_totals), input_pairs = sum(qc$input_pairs), mean_mito = mean(qc$mitochondrial_fraction), mean_duplicate = mean(qc$duplicate_fraction), mean_tss = mean(qc$tss_enrichment), mean_frip = mean(qc$unique_fragment_frip))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)fraction_data <- reshape(qc[, c("sample_id", fractions)], varying = fractions, v.names = "fraction", timevar = "measurement", times = fractions, direction = "long")fraction_data$donor <- metadata$donor[ match(fraction_data$sample_id, metadata$sample_id)]fraction_data$condition <- metadata$condition[ match(fraction_data$sample_id, metadata$sample_id)]fraction_figure <- ggplot(fraction_data, aes(condition, fraction, group = donor, color = donor)) + geom_line(linewidth = 0.5) + geom_point(size = 2) + facet_wrap(~ measurement, ncol = 2) + coord_cartesian(ylim = c(0, 1)) + theme_bw(base_size = 10) + labs(x = "Condition", y = "Fraction", color = "Donor")ggsave("outputs/qc_fractions_r.png", fraction_figure, width = 8, height = 5.4, dpi = 160)fragment_figure <- ggplot(fragments, aes(fragment_length, fraction, color = sample_id)) + geom_line(linewidth = 0.5) + coord_cartesian(xlim = c(0, 1000)) + theme_bw(base_size = 11) + labs(x = "Fragment length in bases", y = "Fraction of cleaned fragments", color = "Sample")ggsave("outputs/qc_fragment_lengths_r.png", fragment_figure, width = 8, height = 4.3, dpi = 160)tss_figure <- ggplot(tss, aes(position - 1001, enrichment, color = sample_id)) + geom_line(linewidth = 0.6) + geom_vline(xintercept = 0, linetype = "dashed") + theme_bw(base_size = 11) + labs(x = "Position relative to the ataqv center", y = "TSS enrichment", color = "Sample")ggsave("outputs/qc_tss_profiles_r.png", tss_figure, width = 8, height = 4.3, dpi = 160)display_limit <- 2 * max(qc$read_pairs_examined)display_preseq <- preseq[preseq$total_pairs <= display_limit, ]complexity_figure <- ggplot(display_preseq, aes(total_pairs / 1e6, expected_distinct / 1e6, color = sample_id)) + geom_line(linewidth = 0.7) + theme_bw(base_size = 11) + labs(x = "Read pairs in the Preseq projection, millions", y = "Expected distinct pairs, millions", color = "Sample")ggsave("outputs/qc_complexity_r.png", complexity_figure, width = 8, height = 4.3, dpi = 160)resting_REP1 alignment_pairs=61526460 input_mates=123052920 mapped_mates=120545613 unmapped_mates=2507307 mapped_fraction=0.979624stimulated_REP1 alignment_pairs=70547808 input_mates=141095616 mapped_mates=138851797 unmapped_mates=2243819 mapped_fraction=0.984097resting_REP2 alignment_pairs=27536167 input_mates=55072334 mapped_mates=54216843 unmapped_mates=855491 mapped_fraction=0.984466stimulated_REP2 alignment_pairs=44852027 input_mates=89704054 mapped_mates=87274431 unmapped_mates=2429623 mapped_fraction=0.972915resting_REP3 alignment_pairs=34831441 input_mates=69662882 mapped_mates=48146769 unmapped_mates=21516113 mapped_fraction=0.691139stimulated_REP3 alignment_pairs=92823668 input_mates=185647336 mapped_mates=112719050 unmapped_mates=72928286 mapped_fraction=0.607168resting_REP4 alignment_pairs=56275096 input_mates=112550192 mapped_mates=109890248 unmapped_mates=2659944 mapped_fraction=0.976367stimulated_REP4 alignment_pairs=51478713 input_mates=102957426 mapped_mates=101068492 unmapped_mates=1888934 mapped_fraction=0.981653resting_REP1 input_pairs=62010110 mate_lengths=20-76/20-76resting_REP1 mito=0.1189 duplicate=0.6723 TSS=6.5532 alignment_FRiP=0.3340 fragment_FRiP=0.3533 repeated=0stimulated_REP1 input_pairs=70999038 mate_lengths=20-76/20-76stimulated_REP1 mito=0.1545 duplicate=0.4864 TSS=5.1571 alignment_FRiP=0.2687 fragment_FRiP=0.2852 repeated=0resting_REP2 input_pairs=27614980 mate_lengths=20-76/20-76resting_REP2 mito=0.0589 duplicate=0.1608 TSS=2.4605 alignment_FRiP=0.0291 fragment_FRiP=0.0300 repeated=0stimulated_REP2 input_pairs=45125416 mate_lengths=20-76/20-76stimulated_REP2 mito=0.0902 duplicate=0.4251 TSS=4.5639 alignment_FRiP=0.2321 fragment_FRiP=0.2475 repeated=0resting_REP3 input_pairs=34962910 mate_lengths=20-76/20-76resting_REP3 mito=0.0637 duplicate=0.1708 TSS=7.2298 alignment_FRiP=0.3391 fragment_FRiP=0.3562 repeated=0stimulated_REP3 input_pairs=93725437 mate_lengths=20-76/20-76stimulated_REP3 mito=0.1452 duplicate=0.7091 TSS=4.4867 alignment_FRiP=0.2421 fragment_FRiP=0.2604 repeated=0resting_REP4 input_pairs=56461627 mate_lengths=20-76/20-76resting_REP4 mito=0.0503 duplicate=0.2552 TSS=4.1104 alignment_FRiP=0.1200 fragment_FRiP=0.1263 repeated=0stimulated_REP4 input_pairs=51718949 mate_lengths=20-76/20-76stimulated_REP4 mito=0.0375 duplicate=0.1868 TSS=4.4708 alignment_FRiP=0.1432 fragment_FRiP=0.1513 repeated=0



import jsonimport iofrom 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)qc = pd.read_csv("/fixtures/qc.tsv", sep="\t").set_index("sample_id")qc = qc.loc[metadata["sample_id"]].reset_index()assert qc["sample_id"].tolist() == metadata["sample_id"].tolist()read_qc = pd.read_csv("/fixtures/read_qc.tsv", sep="\t")mate_one = read_qc.loc[read_qc["mate"].eq(1)].set_index("sample_id")mate_two = read_qc.loc[read_qc["mate"].eq(2)].set_index("sample_id")mate_one = mate_one.loc[metadata["sample_id"]]mate_two = mate_two.loc[metadata["sample_id"]]np.testing.assert_array_equal(mate_one["reads"], mate_two["reads"])qc["input_pairs"] = mate_one["reads"].to_numpy()alignment = pd.read_csv("/fixtures/source/alignment/alignment_qc.tsv", sep="\t", dtype={"donor": str})assert len(alignment) == 8 and alignment["sample_id"].is_uniqueassert set(alignment["sample_id"]) == set(metadata["sample_id"])alignment = alignment.set_index("sample_id").loc[metadata["sample_id"]]alignment = alignment.reset_index()identity_fields = ["sample_id", "donor", "condition", "geo_accession", "run_accession"]pd.testing.assert_frame_equal(alignment[identity_fields], metadata[identity_fields])alignment_columns = { "input_pairs": "alignment_input_pairs", "input_mates": "alignment_input_mates", "mapped_mates": "alignment_mapped_mates", "unaligned_mates": "alignment_unmapped_mates", "mapped_mate_fraction": "alignment_mapped_mate_fraction",}for field, column in alignment_columns.items(): np.testing.assert_allclose(qc[column], alignment[field], atol=1e-12, rtol=0)alignment_counts = qc[list(alignment_columns.values())[:4]].to_numpy()assert np.isfinite(alignment_counts).all() and (alignment_counts >= 0).all()np.testing.assert_array_equal(alignment_counts, np.floor(alignment_counts))assert (qc["alignment_input_pairs"] > 0).all()np.testing.assert_array_equal(qc["alignment_input_mates"], 2 * qc["alignment_input_pairs"])np.testing.assert_array_equal( qc["alignment_mapped_mates"] + qc["alignment_unmapped_mates"], qc["alignment_input_mates"])mapped_fraction = qc["alignment_mapped_mates"] / qc["alignment_input_mates"]np.testing.assert_allclose(mapped_fraction, qc["alignment_mapped_mate_fraction"], atol=1e-12, rtol=0)alignment_summary = qc[["sample_id", *alignment_columns.values()]]for row in qc.itertuples(): source = Path("/fixtures/source") report = json.loads((source / "ataqv" / f"{row.sample_id}.ataqv.json").read_text())[0] assert report["ataqv_version"] == "1.3.1" raw = report["metrics"] assert raw["name"] == row.sample_id assert raw["total_mitochondrial_reads"] == row.mitochondrial_reads assert (raw["properly_paired_and_mapped_reads"] == row.properly_paired_mapped_reads) assert abs(raw["tss_enrichment"] - row.tss_enrichment) < 1e-8 picard_path = source / "picard" / ( f"{row.sample_id}.mLb.mkD.sorted.MarkDuplicates.metrics.txt") lines = picard_path.read_text().splitlines() headers = [i for i, line in enumerate(lines) if line.startswith("LIBRARY\t")] assert len(headers) == 1 header = headers[0] picard = pd.read_csv(io.StringIO("\n".join(lines[header:header + 2])), sep="\t").iloc[0] for field in ["UNPAIRED_READS_EXAMINED", "READ_PAIRS_EXAMINED", "UNPAIRED_READ_DUPLICATES", "READ_PAIR_DUPLICATES"]: assert picard[field] == getattr(row, field.lower())assert (qc["properly_paired_mapped_reads"] > 0).all()qc["mitochondrial_fraction"] = ( qc["mitochondrial_reads"] / qc["properly_paired_mapped_reads"])examined = qc["unpaired_reads_examined"] + 2 * qc["read_pairs_examined"]duplicate = qc["unpaired_read_duplicates"] + 2 * qc["read_pair_duplicates"]qc["duplicate_fraction"] = duplicate / examinedqc["unique_alignment_frip"] = ( qc["unique_alignments_in_peaks"] / qc["clean_mapped_alignments"])qc["unique_fragment_frip"] = ( qc["fragments_in_peak_union"] / qc["clean_autosomal_fragments"])np.testing.assert_allclose(qc["duplicate_fraction"], qc["picard_percent_duplication"], atol=1e-6, rtol=0)fractions = ["mitochondrial_fraction", "duplicate_fraction", "unique_alignment_frip", "unique_fragment_frip"]assert qc[fractions].ge(0).all().all() and qc[fractions].le(1).all().all()fragments = pd.read_csv("/fixtures/fragment_lengths.tsv", sep="\t")fragments = fragments.sort_values(["sample_id", "fragment_length"])fragment_totals = fragments.groupby("sample_id")["fragments"].sum()np.testing.assert_array_equal(fragment_totals.loc[qc["sample_id"]], qc["clean_autosomal_fragments"])fragments["fraction"] = (fragments["fragments"] / fragments["sample_id"].map(fragment_totals))tss = pd.read_csv("/fixtures/tss_profiles.tsv", sep="\t")tss = tss.sort_values(["sample_id", "position"])center = tss.loc[tss["position"].eq(1001)].set_index("sample_id")np.testing.assert_allclose(center.loc[qc["sample_id"], "enrichment"], qc["tss_enrichment"], atol=1e-8, rtol=0)preseq = pd.read_csv("/fixtures/preseq.tsv", sep="\t")assert set(preseq["sample_id"]) == set(qc["sample_id"])summary_columns = ["sample_id", "input_pairs", "mitochondrial_fraction", "duplicate_fraction", "tss_enrichment", "unique_alignment_frip", "unique_fragment_frip"]summary = qc.loc[:, summary_columns]for row in alignment_summary.itertuples(): print(f"{row.sample_id} alignment_pairs={row.alignment_input_pairs} " f"input_mates={row.alignment_input_mates}") print(f" mapped_mates={row.alignment_mapped_mates} " f"unmapped_mates={row.alignment_unmapped_mates} " f"mapped_fraction={row.alignment_mapped_mate_fraction:.6f}")for row in qc.itertuples(): print(f"{row.sample_id} input_pairs={row.input_pairs} " f"mate_lengths={mate_one.at[row.sample_id, 'length_range']}/" f"{mate_two.at[row.sample_id, 'length_range']}") print(f"{row.sample_id} mito={row.mitochondrial_fraction:.4f} " f"duplicate={row.duplicate_fraction:.4f} " f"TSS={row.tss_enrichment:.4f}") print(f" alignment_FRiP={row.unique_alignment_frip:.4f} " f"fragment_FRiP={row.unique_fragment_frip:.4f} " f"repeated={row.alignments_overlapping_multiple_peaks}")output = Path("outputs")output.mkdir(exist_ok=True)alignment_summary.to_csv(output / "alignment_summary_python.tsv", sep="\t", index=False)r_alignment = pd.read_csv(output / "alignment_summary_r.tsv", sep="\t")pd.testing.assert_frame_equal(alignment_summary, r_alignment, check_dtype=False, atol=1e-12, rtol=0)summary.to_csv(output / "qc_summary_python.tsv", sep="\t", index=False)fragments.to_csv(output / "fragment_profiles_python.tsv", sep="\t", index=False)r_summary = pd.read_csv(output / "qc_summary_r.tsv", sep="\t")assert summary["sample_id"].tolist() == r_summary["sample_id"].tolist()np.testing.assert_allclose(summary.iloc[:, 1:], r_summary.iloc[:, 1:], atol=1e-8, rtol=0)r_fragments = pd.read_csv(output / "fragment_profiles_r.tsv", sep="\t")pd.testing.assert_frame_equal(fragments.reset_index(drop=True), r_fragments, check_dtype=False, atol=1e-8, rtol=0)metrics = {"samples": len(qc), "fragments": int(fragment_totals.sum()), "input_pairs": int(qc["input_pairs"].sum()), "mean_mito": float(qc["mitochondrial_fraction"].mean()), "mean_duplicate": float(qc["duplicate_fraction"].mean()), "mean_tss": float(qc["tss_enrichment"].mean()), "mean_frip": float(qc["unique_fragment_frip"].mean())}(output / "metrics_python.json").write_text(json.dumps(metrics))figure, axes = plt.subplots(2, 2, figsize=(8, 5.4), sharey=True)plot_qc = qc.merge(metadata[["sample_id", "donor", "condition"]], on="sample_id", validate="one_to_one")for axis, measurement in zip(axes.flat, fractions, strict=True): for donor, rows in plot_qc.groupby("donor", sort=True): rows = rows.sort_values("condition") axis.plot(rows["condition"], rows[measurement], marker="o", linewidth=0.8, label=donor) axis.set(title=measurement.replace("_", " "), ylabel="Fraction", ylim=(0, 1))axes.flat[-1].legend(title="Donor", fontsize=8)figure.tight_layout()figure.savefig(output / "qc_fractions_python.png", dpi=160)plt.close(figure)plot_definitions = [ (fragments, "fragment_length", "fraction", "qc_fragment_lengths_python.png", "Fragment length in bases", "Fraction of cleaned fragments"), (tss, "position", "enrichment", "qc_tss_profiles_python.png", "Position relative to the ataqv center", "TSS enrichment"), (preseq.loc[preseq["total_pairs"] <= 2 * qc["read_pairs_examined"].max()], "total_pairs", "expected_distinct", "qc_complexity_python.png", "Read pairs in the Preseq projection, millions", "Expected distinct pairs, millions"),]for frame, x_column, y_column, filename, x_label, y_label in plot_definitions: figure, axis = plt.subplots(figsize=(8, 4.3)) for sample_id, rows in frame.groupby("sample_id", sort=True): x = rows[x_column].to_numpy(dtype=float) y = rows[y_column].to_numpy(dtype=float) if x_column == "position": x = x - 1001 elif x_column == "total_pairs": x, y = x / 1e6, y / 1e6 axis.plot(x, y, linewidth=0.8, label=sample_id) if x_column == "fragment_length": axis.set_xlim(0, 1000) elif x_column == "position": axis.axvline(0, color="0.5", linestyle="--", linewidth=0.8) axis.set(xlabel=x_label, ylabel=y_label) axis.legend(title="Sample", fontsize=8, loc="center left", bbox_to_anchor=(1, 0.5)) figure.tight_layout() figure.savefig(output / filename, dpi=160) plt.close(figure)resting_REP1 alignment_pairs=61526460 input_mates=123052920 mapped_mates=120545613 unmapped_mates=2507307 mapped_fraction=0.979624stimulated_REP1 alignment_pairs=70547808 input_mates=141095616 mapped_mates=138851797 unmapped_mates=2243819 mapped_fraction=0.984097resting_REP2 alignment_pairs=27536167 input_mates=55072334 mapped_mates=54216843 unmapped_mates=855491 mapped_fraction=0.984466stimulated_REP2 alignment_pairs=44852027 input_mates=89704054 mapped_mates=87274431 unmapped_mates=2429623 mapped_fraction=0.972915resting_REP3 alignment_pairs=34831441 input_mates=69662882 mapped_mates=48146769 unmapped_mates=21516113 mapped_fraction=0.691139stimulated_REP3 alignment_pairs=92823668 input_mates=185647336 mapped_mates=112719050 unmapped_mates=72928286 mapped_fraction=0.607168resting_REP4 alignment_pairs=56275096 input_mates=112550192 mapped_mates=109890248 unmapped_mates=2659944 mapped_fraction=0.976367stimulated_REP4 alignment_pairs=51478713 input_mates=102957426 mapped_mates=101068492 unmapped_mates=1888934 mapped_fraction=0.981653resting_REP1 input_pairs=62010110 mate_lengths=20-76/20-76resting_REP1 mito=0.1189 duplicate=0.6723 TSS=6.5532 alignment_FRiP=0.3340 fragment_FRiP=0.3533 repeated=0stimulated_REP1 input_pairs=70999038 mate_lengths=20-76/20-76stimulated_REP1 mito=0.1545 duplicate=0.4864 TSS=5.1571 alignment_FRiP=0.2687 fragment_FRiP=0.2852 repeated=0resting_REP2 input_pairs=27614980 mate_lengths=20-76/20-76resting_REP2 mito=0.0589 duplicate=0.1608 TSS=2.4605 alignment_FRiP=0.0291 fragment_FRiP=0.0300 repeated=0stimulated_REP2 input_pairs=45125416 mate_lengths=20-76/20-76stimulated_REP2 mito=0.0902 duplicate=0.4251 TSS=4.5639 alignment_FRiP=0.2321 fragment_FRiP=0.2475 repeated=0resting_REP3 input_pairs=34962910 mate_lengths=20-76/20-76resting_REP3 mito=0.0637 duplicate=0.1708 TSS=7.2298 alignment_FRiP=0.3391 fragment_FRiP=0.3562 repeated=0stimulated_REP3 input_pairs=93725437 mate_lengths=20-76/20-76stimulated_REP3 mito=0.1452 duplicate=0.7091 TSS=4.4867 alignment_FRiP=0.2421 fragment_FRiP=0.2604 repeated=0resting_REP4 input_pairs=56461627 mate_lengths=20-76/20-76resting_REP4 mito=0.0503 duplicate=0.2552 TSS=4.1104 alignment_FRiP=0.1200 fragment_FRiP=0.1263 repeated=0stimulated_REP4 input_pairs=51718949 mate_lengths=20-76/20-76stimulated_REP4 mito=0.0375 duplicate=0.1868 TSS=4.4708 alignment_FRiP=0.1432 fragment_FRiP=0.1513 repeated=0



Make a cohort decision before inference
Section titled “Make a cohort decision before inference”The completed QC review retains all eight profiles for conditional analysis of the four donor pairs. Each pair retains measurable ATAC signal.
Resting REP2 from donor 1002 has the weakest enrichment. Its fragment FRiP is 0.030013 and its TSS enrichment is 2.460463, despite a mapped-mate fraction above 0.98 and relatively low duplication. It retains 20,038,752 clean proper autosomal fragments, structured fragment and TSS profiles, and measurable counts. Those observations support conditional assessment; a size factor cannot restore the lost enrichment.
Donor 1003 has mapped-mate fractions of 0.691139 at rest and 0.607168 after stimulation, while the other six profiles exceed 0.97. Its retained fragments show TSS and peak enrichment in both conditions. Neither normalization nor the donor term repairs that unexplained loss.
A weak TSS profile together with poor peak overlap and an atypical fragment distribution warrants a sample review. A mitochondrial fraction alone does not define failure, and a library with many duplicates can still retain enough distinct fragments for the intended analysis. Preseq extrapolates under its library model; its curve does not guarantee the yield of another sequencing experiment.
Review the two samples from each donor together and preserve every exclusion reason. Removing one profile breaks that donor’s pair and requires another review of the model. Treatment-associated differences in a QC metric also need biological interpretation before that metric becomes a covariate. The differential lesson includes a stated TSS sensitivity fit and separate donor omission fits. Interpretation requires particular attention to donors 1002 and 1003, with effect directions and magnitudes considered alongside discovery membership. Four retained pairs leave only three residual degrees of freedom in the primary model.
Further reading
Section titled “Further reading”The ataqv 1.3.1 metric implementation defines the TSS normalization and central enrichment calculation. It fixes the metric that the displayed profiles summarize.
The Picard 3.0.0 duplication metrics defines the contribution of pairs and unpaired reads to duplication rates. Those definitions explain the denominator used by the lesson.