#!/usr/bin/env Rscript # PCA of samples in the gene count matrix. # A gene is kept when it has at least MIN_COUNT reads in as many samples # as the smallest group. When the count file has an FDR column, genes at # or above FDR_CUTOFF are dropped first. --invert keeps those genes # instead. vst() estimates library-size factors from the raw counts and # applies the variance-stabilizing transform. Do not pre-normalize. # blind = TRUE (the default) keeps the transform independent of the # design. plotPCA uses the 500 most variable genes. # After VST, gene variances are comparable, so PCA is unscaled. # Point color is a column from the design file. # Input sample design. DESIGN_FILE = "design.csv" # Input gene counts. COUNT_FILE = "csv/gene_counts.csv" # Output PCA plot. PCA_PLOT = "pdf/pca.pdf" # Keep genes with at least this many counts in the smallest group. MIN_COUNT = 10 # Keep genes below this FDR when the count file has an FDR column. FDR_CUTOFF = 0.05 # Keep genes that fail the FDR cutoff instead of those that pass. INVERT = FALSE # Design column used to color points. COLOR_BY = "group" # How far to move the sample label, in PC units. NUDGE_Y = 1 # Plot size in inches. Matches the default pdf() device. PLOT_WIDTH = 9 PLOT_HEIGHT = 6 # Install the optparse package automatically. if(!require(optparse, quietly=T)){ install.packages("optparse", repos="http://cran.us.r-project.org") library(optparse) } # Command line options. option_list = list( make_option(c("-d", "--design_file"), action="store", default=DESIGN_FILE, dest="design_file", type="character", help="input sample design [%default]"), make_option(c("-c", "--count_file"), action="store", default=COUNT_FILE, dest="count_file", type="character", help="input gene counts [%default]"), make_option(c("-o", "--output"), action="store", default=PCA_PLOT, dest="pca_plot", type="character", help="output PCA plot [%default]"), make_option(c("-m", "--mincount"), action="store", default=MIN_COUNT, dest="min_count", type="integer", help="keep genes with at least this many counts in the smallest group [%default]"), make_option(c("-f", "--fdr"), action="store", default=FDR_CUTOFF, dest="fdr", type="double", help="keep genes with FDR below this cutoff when the count file has an FDR column [%default]"), make_option(c("-i", "--invert"), action="store_true", default=INVERT, dest="invert", help="keep genes that do not pass the FDR cutoff"), make_option(c("--color_by"), action="store", default=COLOR_BY, dest="color_by", type="character", help="design column used to color points [%default]"), make_option(c("-n", "--nudge"), action="store", default=NUDGE_Y, dest="nudge_y", type="double", help="how far to move the sample label, in PC units [%default]"), make_option(c("-w", "--width"), action="store", default=PLOT_WIDTH, dest="plot_width", type="double", help="plot width in inches [%default]"), make_option(c("--height"), action="store", default=PLOT_HEIGHT, dest="plot_height", type="double", help="plot height in inches [%default]") ) # Parse the options. opt = parse_args(OptionParser(option_list=option_list)) # Set the values from the options. design_file = opt$design_file count_file = opt$count_file pca_plot = opt$pca_plot min_count = opt$min_count fdr = opt$fdr invert = opt$invert color_by = opt$color_by nudge_y = opt$nudge_y plot_width = opt$plot_width plot_height = opt$plot_height cat("#\n") cat("# PCA of samples in the gene count matrix\n") cat("#\n") cat("# https://bioconductor.org/packages/release/bioc/html/DESeq2.html\n") cat("# Pass the -h flag to get help on parameters\n") suppressPackageStartupMessages({ library(DESeq2) library(ggplot2) }) # Keep genes with FDR below the cutoff. --invert keeps the rest. # Leave the table unchanged when the column is absent. filter_fdr <- function(counts, fdr, invert) { if (!"FDR" %in% names(counts)) return(counts) values <- suppressWarnings(as.numeric(counts$FDR)) pass <- !is.na(values) & values < fdr keep <- if (invert) !pass else pass if (invert) { cat("# Genes not passing FDR <", fdr, ":", sum(keep), "of", nrow(counts), "\n") } else { cat("# Genes with FDR <", fdr, ":", sum(keep), "of", nrow(counts), "\n") } if (!any(keep)) stop("No genes left after the FDR filter") counts[keep, , drop = FALSE] } # Integer count matrix for the samples in the design. read_matrix <- function(path, design, fdr, invert) { counts <- read.csv(path, strip.white = TRUE, check.names = FALSE) if (!"id" %in% names(counts)) stop("Count file must have an id column") has_fdr <- "FDR" %in% names(counts) counts <- filter_fdr(counts, fdr, invert) missing <- setdiff(design$sample, names(counts)) if (length(missing)) stop("Count file is missing samples: ", paste(missing, collapse = ", ")) mat <- as.matrix(round(counts[, design$sample, drop = FALSE])) storage.mode(mat) <- "integer" rownames(mat) <- counts$id attr(mat, "has_fdr") <- has_fdr mat } # Drop genes that do not reach min_count in the smallest group. filter_counts <- function(mat, design, min_count) { n <- min(table(design$group)) keep <- rowSums(mat >= min_count) >= n cat("# Smallest group has", n, "samples\n") cat("# Genes retained:", sum(keep), "of", nrow(mat), "\n") mat[keep, , drop = FALSE] } # Variance-stabilized counts. The transform ignores sample groups. vst_matrix <- function(mat, design, color_by) { coldata <- data.frame(row.names = design$sample) coldata$group <- factor(design$group, levels = unique(design$group)) if (color_by != "group") { coldata[[color_by]] <- factor(design[[color_by]], levels = unique(design[[color_by]])) } dds <- DESeqDataSetFromMatrix(mat, coldata, design = ~group) vst(dds) } # plotPCA figure with sample labels. Axes share a fixed scale. plot_pca <- function(vsd, color_by, nudge_y) { vals <- colData(vsd)[[color_by]] groups <- if (is.factor(vals)) levels(vals) else unique(as.character(vals)) plotPCA(vsd, intgroup = color_by) + geom_text(aes(label = colnames(vsd)), position = position_nudge(y = nudge_y), size = 2.5) + labs(color = color_by) + ggtitle(paste0("PCA: ", color_by)) } cat("# Loading design from:", design_file, "\n") design <- read.csv(design_file, strip.white = TRUE, stringsAsFactors = FALSE) if (!all(c("sample", "group") %in% names(design))) { stop("Design file must have sample and group columns") } if (!color_by %in% names(design)) stop("Design file has no column: ", color_by) cat("# Coloring points by:", color_by, "\n") cat("# Loading gene counts from:", count_file, "\n") mat <- read_matrix(count_file, design, fdr, invert) has_fdr <- isTRUE(attr(mat, "has_fdr")) if (nrow(mat) == 0) stop("The count data has no rows") cat("# Filtering genes below", min_count, "counts in the smallest group\n") mat <- filter_counts(mat, design, min_count) if (nrow(mat) == 0) stop("No genes passed the count filter") cat("# Applying variance stabilizing transformation\n") vsd <- vst_matrix(mat, design, color_by) dir.create(dirname(pca_plot), showWarnings = FALSE, recursive = TRUE) cat("# Saving PCA plot to:", pca_plot, "\n") ggsave(pca_plot, plot_pca(vsd, color_by, nudge_y), width = plot_width, height = plot_height) if (has_fdr) cat("# FDR column found:", nrow(mat), "rows included\n")