#!/usr/bin/env Rscript # Heatmap of samples in a count matrix. # The count columns are used as stored. Pass the normalized counts from # an edgeR table. When that table has an FDR column, genes above # FDR_CUTOFF are dropped first. --invert keeps those genes instead. # Every gene that passes is drawn. Each row is a z-score: how far that # sample sits from the gene's own mean, in standard deviations. # Values beyond Z_LIMIT are capped so one outlier does not stretch the # color scale. Column annotation is a column from the design file. # Gene names that fit are shown. When they do not, an evenly spaced # subset is marked beside the heatmap. # Input sample design. DESIGN_FILE = "design.csv" # Input gene counts. COUNT_FILE = "csv/gene_counts.csv" # Output heatmap. HEATMAP_PLOT = "pdf/heatmap.pdf" # Keep genes at or 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 annotate columns. COLOR_BY = "group" # Cap the color scale at this many standard deviations. Z_LIMIT = 2 # Gene name size, in points. Used to decide how many names fit. FONT_ROW = 8 # Plot size in inches. 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=HEATMAP_PLOT, dest="heatmap_plot", type="character", help="output heatmap [%default]"), make_option(c("-f", "--fdr"), action="store", default=FDR_CUTOFF, dest="fdr", type="double", help="keep genes with FDR at or 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 annotate columns [%default]"), make_option(c("-z", "--zlimit"), action="store", default=Z_LIMIT, dest="z_limit", type="double", help="cap the color scale at this many standard deviations [%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 heatmap_plot = opt$heatmap_plot fdr = opt$fdr invert = opt$invert color_by = opt$color_by z_limit = opt$z_limit plot_width = opt$plot_width plot_height = opt$plot_height cat("#\n") cat("# Heatmap of samples in the gene count matrix\n") cat("#\n") cat("# https://bioconductor.org/packages/ComplexHeatmap\n") cat("# Pass the -h flag to get help on parameters\n") if (!suppressPackageStartupMessages(require(ComplexHeatmap, quietly=T))) { cat("\n") cat("pixi add bioconductor-complexheatmap\n") cat("\n") cat("or visit\n") cat("\n") cat("https://bioconductor.org/packages/ComplexHeatmap\n") quit(status = 1) } suppressPackageStartupMessages(library(grid)) # Keep genes with FDR at or 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] } # Count matrix for the samples in the design. # Row names are the name column. A blank name falls back to the id. read_matrix <- function(path, design, fdr, invert) { counts <- read.csv(path, strip.white = TRUE, check.names = FALSE, stringsAsFactors = FALSE) if (!"id" %in% names(counts)) stop("Count file must have an id column") if (!"name" %in% names(counts)) stop("Count file must have a name 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(counts[, design$sample, drop = FALSE]) storage.mode(mat) <- "double" if (anyNA(mat)) stop("Count matrix contains missing values") rows <- counts$name blank <- is.na(rows) | rows == "" rows[blank] <- counts$id[blank] rownames(mat) <- make.unique(rows) attr(mat, "has_fdr") <- has_fdr mat } # Row z-scores of the count values. Constant rows have no z-score. # Values are capped so the color scale stays fixed. zscore <- function(mat, limit) { s <- apply(mat, 1, sd) keep <- !is.na(s) & s > 0 cat("# Genes drawn:", sum(keep), "of", nrow(mat), "\n") if (sum(keep) < 2) stop("Not enough variable genes to draw a heatmap") mat <- mat[keep, , drop = FALSE] z <- t(scale(t(mat))) z[z > limit] <- limit z[z < -limit] <- -limit dimnames(z) <- dimnames(mat) z } # How many gene names fit beside a heatmap of this height. label_slots <- function(height, fontsize) { body <- max(height - 1.8, 2) gap <- fontsize / 72 + 0.04 max(8, floor(body / gap)) } # Original row indices evenly spaced along the clustered order. spaced_rows <- function(order, n) { at <- unique(as.integer(round(seq(1, length(order), length.out = n)))) order[at] } # Label boxes taller than the gap between marked rows. anno_mark then # pushes the names apart and bends the link, instead of a straight tick. mark_padding <- function(n_genes, n_labels, height) { body <- max(height - 1.2, 2) gap_mm <- body / n_labels * 25.4 font_mm <- FONT_ROW / 72 * 25.4 row_mm <- body / n_genes * 25.4 unit(max(1, gap_mm - font_mm + row_mm), "mm") } # Blue is below the row mean, red is above it. plot_heatmap <- function(mat, design, color_by, z_limit, height) { dend <- as.dendrogram(hclust(dist(mat))) order <- order.dendrogram(dend) n <- min(nrow(mat), label_slots(height, FONT_ROW)) show_all <- n >= nrow(mat) mark <- if (show_all) integer(0) else spaced_rows(order, n) vals <- design[[color_by]][match(colnames(mat), design$sample)] vals <- factor(vals, levels = unique(design[[color_by]])) pal <- c("#1B9E77", "#D95F02", "#7570B3", "#E7298A", "#66A61E", "#E6AB02", "#A6761D", "#666666") ann_col <- setNames(pal[seq_along(levels(vals))], levels(vals)) ann_args <- list( col = setNames(list(ann_col), color_by), show_annotation_name = FALSE ) ann_args[[color_by]] <- vals top <- do.call(HeatmapAnnotation, ann_args) right <- NULL if (!show_all) { right <- rowAnnotation( link = anno_mark( at = mark, labels = rownames(mat)[mark], labels_gp = gpar(fontsize = FONT_ROW), link_width = unit(8, "mm"), padding = mark_padding(nrow(mat), length(mark), height) ), show_annotation_name = FALSE ) } cat("# Row labels shown:", if (show_all) nrow(mat) else length(mark), "of", nrow(mat), "\n") Heatmap( mat, name = "z-score", col = circlize::colorRamp2(c(-z_limit, 0, z_limit), c("#2166AC", "#F7F7F7", "#B2182B")), cluster_rows = dend, cluster_columns = TRUE, show_row_names = show_all, row_names_side = "right", row_names_gp = gpar(fontsize = FONT_ROW), column_names_rot = 45, column_names_gp = gpar(fontsize = 9), top_annotation = top, right_annotation = right, column_title = paste0("Heatmap: ", color_by), row_dend_width = unit(12, "mm"), use_raster = nrow(mat) > 200, raster_quality = 2, border = FALSE ) } # Write the heatmap to PDF, PNG, or JPEG based on the file extension. save_heatmap <- function(ht, path, width, height) { ext <- tolower(tools::file_ext(path)) if (ext == "png") { png(path, width = width, height = height, units = "in", res = 150) } else if (ext %in% c("jpg", "jpeg")) { jpeg(path, width = width, height = height, units = "in", res = 150, quality = 95) } else { pdf(path, width = width, height = height) } draw( ht, heatmap_legend_side = "left", annotation_legend_side = "left", padding = unit(c(16, 2, 2, 6), "mm") ) invisible(dev.off()) } 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("# Annotating columns 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("# Scaling each gene to a z-score, capped at", z_limit, "\n") z <- zscore(mat, z_limit) dir.create(dirname(heatmap_plot), showWarnings = FALSE, recursive = TRUE) cat("# Saving heatmap to:", heatmap_plot, "\n") ht <- plot_heatmap(z, design, color_by, z_limit, plot_height) save_heatmap(ht, heatmap_plot, plot_width, plot_height) if (has_fdr) cat("# FDR column found:", nrow(z), "rows included\n")