#!/usr/bin/env Rscript
# Differential expression between tissues taken from the same patients, with DESeq2.
#
# Usage: Rscript analyses/deseq2_paired.R
#
# Reads counts.tsv and samples.tsv (see analyses//get_inputs.py) and writes, per comparison,
# a results table for every tested gene, plus quality-check plots, summary.json
# and session-info.txt. The plain-words explanation of each step is on the site at
# /guides/how-we-run-differential-expression/. The volcano plot and pathway results on the
# example pages are made by the DE Results tool itself (scripts/example_tool_outputs.py).
suppressPackageStartupMessages({
library(DESeq2)
library(ggplot2)
library(pheatmap)
library(jsonlite)
})
args <- commandArgs(trailingOnly = TRUE)
stopifnot(length(args) == 3)
in_dir <- args[1]
out_dir <- args[2]
comparisons <- strsplit(strsplit(args[3], ",")[[1]], ":")
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
set.seed(1)
ALPHA <- 0.05 # adjusted p-value cutoff
MIN_LFC <- 1 # |log2 fold change| cutoff used when counting "changed" genes
MIN_COUNT <- 10 # a gene needs at least this many reads ...
COLOURS <- c(normal = "#2B67B1", tumor = "#C4443A", metastasis = "#B7791F")
OUTLIER_IQR <- 3 # flag a sample whose typical distance to its own tissue group is this many IQRs above the upper quartile
# ---- 1. Read the inputs ---------------------------------------------------
counts <- read.delim(file.path(in_dir, "counts.tsv"), check.names = FALSE, quote = "", stringsAsFactors = FALSE)
samples <- read.delim(file.path(in_dir, "samples.tsv"), stringsAsFactors = FALSE)
stopifnot(all(samples$sample %in% colnames(counts)), !anyDuplicated(counts$gene_id))
symbols <- setNames(counts$symbol, counts$gene_id)
m <- as.matrix(counts[, samples$sample])
storage.mode(m) <- "integer"
rownames(m) <- counts$gene_id
rownames(samples) <- samples$sample
samples$donor <- factor(samples$donor)
samples$tissue <- factor(samples$tissue)
# ---- 2. Drop genes with almost no reads -----------------------------------
# ... in at least as many samples as the smallest tissue group has.
smallest <- min(table(samples$tissue))
keep <- rowSums(m >= MIN_COUNT) >= smallest
m_kept <- m[keep, ]
# ---- 3. Quality checks on all samples -------------------------------------
dds_qc <- DESeqDataSetFromMatrix(m_kept, samples, design = ~ donor + tissue)
vsd <- vst(dds_qc, blind = TRUE)
lib <- data.frame(label = paste(samples$donor, samples$tissue), tissue = samples$tissue,
reads = colSums(m) / 1e6)
p <- ggplot(lib, aes(x = reorder(label, reads), y = reads, fill = tissue)) +
geom_col() + coord_flip() + scale_fill_manual(values = COLOURS) +
labs(x = NULL, y = "Reads assigned to genes (millions)", fill = NULL) +
theme_minimal(base_size = 11) + theme(legend.position = "top", panel.grid.major.y = element_blank())
ggsave(file.path(out_dir, "library-sizes.png"), p, width = 6.5, height = 9, dpi = 160, bg = "white")
pca <- plotPCA(vsd, intgroup = "tissue", ntop = 500, returnData = TRUE)
pct <- round(100 * attr(pca, "percentVar"))
p <- ggplot(pca, aes(PC1, PC2, colour = tissue)) + geom_point(size = 2.6, alpha = 0.9) +
scale_colour_manual(values = COLOURS) +
labs(x = paste0("PC1 (", pct[1], "% of variance)"), y = paste0("PC2 (", pct[2], "% of variance)"), colour = NULL) +
theme_minimal(base_size = 12) + theme(legend.position = "top")
ggsave(file.path(out_dir, "pca.png"), p, width = 6.5, height = 5, dpi = 160, bg = "white")
write.table(data.frame(sample = rownames(pca), donor = samples[rownames(pca), "donor"], tissue = pca$tissue,
PC1 = signif(pca$PC1, 4), PC2 = signif(pca$PC2, 4)),
file.path(out_dir, "pca.txt"), sep = "\t", quote = FALSE, row.names = FALSE)
d <- dist(t(assay(vsd)))
dm <- as.matrix(d)
rownames(dm) <- colnames(dm) <- paste(samples$donor, samples$tissue)
ann <- data.frame(tissue = samples$tissue, row.names = rownames(dm))
# Label check: does each sample look more like the average of its own tissue or of another?
# Distances are measured on the 500 most variable genes, the same genes the PCA uses.
top_var <- head(order(apply(assay(vsd), 1, var), decreasing = TRUE), 500)
x <- assay(vsd)[top_var, ]
centres <- sapply(levels(samples$tissue), function(t) rowMeans(x[, samples$tissue == t, drop = FALSE]))
nearest <- apply(x, 2, function(v) colnames(centres)[which.min(colSums((centres - v)^2))])
label_check <- data.frame(sample = samples$sample, title = samples$title, donor = samples$donor,
labelled = samples$tissue, resembles = nearest)
mismatched <- label_check[as.character(label_check$labelled) != label_check$resembles, ]
write.table(label_check, file.path(out_dir, "label-check.txt"), sep = "\t", quote = FALSE, row.names = FALSE)
# Flag (do not remove) samples that sit unusually far from the rest of their own tissue group.
typical <- sapply(seq_len(ncol(dm)), function(i) {
same <- samples$tissue == samples$tissue[i]
same[i] <- FALSE
median(dm[i, same])
})
q <- quantile(typical, c(0.25, 0.75))
flagged <- samples$sample[typical > q[2] + OUTLIER_IQR * diff(q)]
pheatmap(dm, clustering_distance_rows = d, clustering_distance_cols = d,
annotation_col = ann, annotation_colors = list(tissue = COLOURS[levels(samples$tissue)]),
color = colorRampPalette(c("#14202B", "#0B7A75", "#F4F6F8"))(60), border_color = NA,
fontsize = 6, show_colnames = FALSE,
filename = file.path(out_dir, "sample-distances.png"), width = 8, height = 7)
# ---- 4. Test each comparison ----------------------------------------------
# The model is ~ donor + tissue: every tissue is compared within the same patient.
# The model is fitted once per comparison with that comparison's reference tissue first,
# which is what apeglm shrinkage needs. The fit itself is the same either way.
summary <- list()
for (cmp in comparisons) {
grp <- cmp[1]
ref <- cmp[2]
s <- samples
s$tissue <- relevel(s$tissue, ref = ref)
dds <- DESeqDataSetFromMatrix(m_kept, s, design = ~ donor + tissue)
dds <- DESeq(dds, quiet = TRUE)
coef <- paste0("tissue_", grp, "_vs_", ref)
stopifnot(coef %in% resultsNames(dds))
res <- results(dds, name = coef, alpha = ALPHA)
shr <- lfcShrink(dds, coef = coef, type = "apeglm", res = res, quiet = TRUE)
out <- data.frame(gene = unname(symbols[rownames(res)]), gene_id = rownames(res),
baseMean = signif(res$baseMean, 4),
log2FoldChange = signif(shr$log2FoldChange, 4),
lfcSE = signif(shr$lfcSE, 4),
log2FC_unshrunken = signif(res$log2FoldChange, 4),
pvalue = signif(res$pvalue, 4), padj = signif(res$padj, 4))
out <- out[order(out$pvalue, -abs(out$log2FoldChange)), ]
name <- paste0(grp, "-vs-", ref)
write.table(out, file.path(out_dir, paste0(name, ".txt")), sep = "\t", quote = FALSE, row.names = FALSE, na = "NA")
tested <- !is.na(out$padj)
sig <- tested & out$padj < ALPHA
# "At least 2-fold", on the rounded values in the published table, so the counts here
# match what the DE Results tool shows for the same table.
up <- sig & out$log2FoldChange >= MIN_LFC
down <- sig & out$log2FoldChange <= -MIN_LFC
donors <- intersect(samples$donor[samples$tissue == grp], samples$donor[samples$tissue == ref])
top <- function(rows) lapply(head(which(rows), 10), function(i)
list(gene = out$gene[i], log2FoldChange = out$log2FoldChange[i], padj = out$padj[i]))
summary[[name]] <- list(
group = grp, reference = ref,
samples_group = sum(samples$tissue == grp), samples_reference = sum(samples$tissue == ref),
patients_with_both = length(donors),
genes_tested = sum(tested), genes_padj_below_cutoff = sum(sig),
up = sum(up), down = sum(down),
outlier_genes_set_to_NA = sum(is.na(out$pvalue)),
top_up = top(up), top_down = top(down))
}
# ---- 5. Record what was run -----------------------------------------------
info <- list(
genes_in_file = nrow(m), genes_kept = nrow(m_kept), min_count = MIN_COUNT, min_samples = unname(smallest),
samples = as.list(table(samples$tissue)), patients = nlevels(samples$donor),
padj_cutoff = ALPHA, lfc_cutoff = MIN_LFC, design = "~ donor + tissue",
pca_percent_variance = pct[1:2],
outlier_rule = paste0("median distance to own tissue group > upper quartile + ", OUTLIER_IQR, " x IQR"),
flagged_samples = as.list(flagged),
label_mismatches = lapply(seq_len(nrow(mismatched)), function(i) as.list(mismatched[i, ])),
reads_millions = list(min = round(min(lib$reads), 1), median = round(median(lib$reads), 1), max = round(max(lib$reads), 1)),
versions = list(R = paste(R.version$major, R.version$minor, sep = "."),
Bioconductor = as.character(BiocManager::version()),
DESeq2 = as.character(packageVersion("DESeq2")),
apeglm = as.character(packageVersion("apeglm"))),
container = Sys.getenv("ANALYSIS_IMAGE", unset = NA),
comparisons = summary)
write_json(info, file.path(out_dir, "summary.json"), auto_unbox = TRUE, pretty = TRUE, digits = NA)
writeLines(capture.output(sessionInfo()), file.path(out_dir, "session-info.txt"))
cat(toJSON(info, auto_unbox = TRUE, pretty = TRUE, digits = NA), "\n")