QC and contamination
A low read count and a contaminant are different problems. A sequencing failure can remove useful information from a sample, while reagent DNA can add features that sequence well. A quality filter cannot determine a feature’s origin.
The cohort archive does not provide the extraction blanks and DNA concentration measurements needed for a worked contamination diagnosis. This lesson therefore checks the table and illustrates prevalence filters. It does not claim that the retained table is free of contamination.
Run this example
Section titled “Run this example”The example uses the prepared Kostic colorectal cohort. The workflow and dataset page explains its source, paired design, and selection rule. Counts, taxonomy, and metadata come from the same public archive. The original features are reference OTUs, not ASVs from the separate ampliseq demonstration.
The companion repository
is private and requires access. Its microbiome:0.1.0 container provides the
packages, and the runner mounts the prepared tables at /fixtures.
Run each language’s blocks in order. The container runs without network access.
Read the data and calculate the result
Section titled “Read the data and calculate the result”The example retains an OTU if it has at least five reads in at least ten percent of samples. Both conditions describe this example’s rule. The calculation reports how much count mass that rule retains, so a stricter table does not silently become a different population of features.
The paired counts and metadata come from Kostic and colleagues, distributed in the pinned phyloseq example archive. McMurdie and Holmes distribute that package under AGPL-3. The source notice records the exact archive, the 76-subject selection, and the applicable package terms.
The mouse and mock-community reads come from the Schloss laboratory MiSeq SOP archive, whose source site grants CC BY 4.0. SILVA supplies the 138.2 taxonomy under its own CC BY 4.0 grant. The source notice records these credits and the new analysis outputs.
library(ggplot2)library(jsonlite)
counts <- read.delim( "/fixtures/cohort_counts.tsv", row.names = 1, check.names = FALSE)counts <- t(as.matrix(counts))metadata <- read.delim("/fixtures/cohort_metadata.tsv")metadata <- metadata[match(rownames(counts), metadata$sample_id), ]stopifnot(identical(rownames(counts), metadata$sample_id))stopifnot(all(counts >= 0), all(counts == floor(counts)))dir.create("outputs", showWarnings = FALSE)
prevalence <- colMeans(counts >= 5)keep <- prevalence >= 0.10filtered <- counts[, keep, drop = FALSE]retained_fraction <- rowSums(filtered) / rowSums(counts)cat("OTUs before the filter:", ncol(counts), "\n")cat("OTUs after the filter:", ncol(filtered), "\n")cat(sprintf("Retained count fraction: %.6f\n", sum(filtered) / sum(counts)))plot_data <- data.frame(reads = rowSums(counts), retained = retained_fraction, tissue = metadata$tissue)figure <- ggplot(plot_data, aes(reads, retained, color = tissue)) + geom_point(alpha = 0.65) + scale_x_log10() + theme_minimal(base_size = 12) + labs(x = "Reads before the filter", y = "Fraction retained", color = "Tissue")ggsave("outputs/qc_contamination_r.png", figure, width = 6, height = 4, dpi = 160)write_json(list(retained_features = ncol(filtered), retained_reads = sum(filtered)), "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)OTUs before the filter: 2505OTUs after the filter: 194Retained count fraction: 0.846743
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy import statsfrom scipy.spatial.distance import pdist, squareform
counts = pd.read_csv( "/fixtures/cohort_counts.tsv", sep="\t", index_col=0).Tmetadata = pd.read_csv( "/fixtures/cohort_metadata.tsv", sep="\t", index_col=0).loc[counts.index]assert counts.index.equals(metadata.index)assert (counts.to_numpy() >= 0).all()assert (counts.to_numpy() == np.floor(counts.to_numpy())).all()output = Path("outputs")output.mkdir(exist_ok=True)
prevalence = (counts >= 5).mean(axis=0)filtered = counts.loc[:, prevalence >= 0.10]retained_fraction = filtered.sum(axis=1) / counts.sum(axis=1)print(f"OTUs before the filter: {counts.shape[1]}")print(f"OTUs after the filter: {filtered.shape[1]}")fraction = filtered.to_numpy().sum() / counts.to_numpy().sum()print(f"Retained count fraction: {fraction:.6f}")figure, axis = plt.subplots(figsize=(6, 4))for tissue in ["normal", "tumor"]: selected = metadata["tissue"] == tissue axis.scatter(counts.sum(axis=1)[selected], retained_fraction[selected], alpha=0.65, label=tissue)axis.set(xscale="log", xlabel="Reads before the filter", ylabel="Fraction retained")axis.legend(title="Tissue")figure.tight_layout()figure.savefig(output / "qc_contamination_python.png", dpi=160)plt.close(figure)metrics = {"retained_features": filtered.shape[1], "retained_reads": int(filtered.to_numpy().sum())}(output / "metrics_python.json").write_text(json.dumps(metrics))OTUs before the filter: 2505OTUs after the filter: 194Retained count fraction: 0.846743
Inspect retention from the amplicon workflow
Section titled “Inspect retention from the amplicon workflow”The following table comes from the executed ampliseq demonstration. These are mouse libraries and a mock control, separate from the colorectal cohort above. DADA2 tracks paired observations through filtering, denoising, merging, and chimera removal. Retention uses each library’s original DADA2 input as its denominator.
tracking <- read.delim("/fixtures/ampliseq_read_tracking.tsv")stopifnot(!anyDuplicated(tracking$sample), all(tracking$DADA2_input > 0))stopifnot(all(tracking$nonchim <= tracking$DADA2_input))tracking$retention <- tracking$nonchim / tracking$DADA2_inputwrite.table(tracking, "outputs/amplicon_retention_r.tsv", sep = "\t", row.names = FALSE, quote = FALSE)cat("Amplicon libraries:", nrow(tracking), "\n")cat("Input pairs:", sum(tracking$DADA2_input), "\n")cat("Nonchimeric pairs:", sum(tracking$nonchim), "\n")cat(sprintf("Lowest library retention: %.6f\n", min(tracking$retention)))metrics <- read_json("outputs/metrics_r.json", simplifyVector = TRUE)metrics$amplicon_input <- sum(tracking$DADA2_input)metrics$amplicon_nonchim <- sum(tracking$nonchim)metrics$amplicon_min_retention <- min(tracking$retention)write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)Amplicon libraries: 20Input pairs: 152360Nonchimeric pairs: 121656Lowest library retention: 0.729439tracking = pd.read_csv("/fixtures/ampliseq_read_tracking.tsv", sep="\t")assert tracking["sample"].is_uniqueassert (tracking["DADA2_input"] > 0).all()assert (tracking["nonchim"] <= tracking["DADA2_input"]).all()tracking["retention"] = tracking["nonchim"] / tracking["DADA2_input"]tracking.to_csv(output / "amplicon_retention_python.tsv", sep="\t", index=False)print("Amplicon libraries:", len(tracking))print("Input pairs:", tracking["DADA2_input"].sum())print("Nonchimeric pairs:", tracking["nonchim"].sum())print(f"Lowest library retention: {tracking['retention'].min():.6f}")metrics.update({"amplicon_input": int(tracking["DADA2_input"].sum()), "amplicon_nonchim": int(tracking["nonchim"].sum()), "amplicon_min_retention": float(tracking["retention"].min())})(output / "metrics_python.json").write_text(json.dumps(metrics))Amplicon libraries: 20Input pairs: 152360Nonchimeric pairs: 121656Lowest library retention: 0.729439Low retention identifies a library for inspection; it does not identify the cause. Compare the intermediate columns with read quality, overlap length, and the truncation settings before excluding a sample.
Use controls to investigate contamination
Section titled “Use controls to investigate contamination”Extraction blanks measure material introduced during extraction. PCR negatives measure material introduced during amplification. Positive mock controls test whether the assay recovers organisms with known membership. None replaces the others.
decontam uses prevalence in controls or the relationship between feature frequency and DNA concentration. Its result depends on the control design, the supplied measurements, and the threshold. A taxon reported in a blank is evidence to investigate, not an automatic instruction to remove that taxon from every sample.
Record the original and retained sample lists, the feature rule, and the read retention report. Apply a prespecified rule before testing the tissue contrast. Inspect whether exclusions differ between tissues or batches.
Further reading
Section titled “Further reading”-
Davis and colleagues, decontam
The original method uses DNA concentration or control prevalence to distinguish external contamination. It explains why a rare-feature cutoff alone cannot establish contamination.
-
The tutorial compares input, filtered, denoised, merged, and nonchimeric counts. That sequence helps locate losses in the separate mouse amplicon demonstration.