#!/usr/bin/env Rscript # Compare two gene count matrices on the average expression per group. # Genome counts come from featureCounts. # Transcript counts are Salmon NumReads summed to genes. # For each gene, the error is the absolute difference of those group means. # Relative error divides that difference by the average of the two means. # Both means at 0 count as zero error. # Input sample design. DESIGN_FILE = "design.csv" # Gene counts from genome alignment. GENOME_FILE = "csv/gene_counts.csv" # Gene counts from transcripts summed to genes. TRANSCRIPT_FILE = "csv/transcripts_as_genes.csv" # One row per gene and group, largest differences first. ERROR_FILE = "csv/gene_count_errors.csv" # How many of the largest differences to print. TOP_N = 15 # 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("-g", "--genome_file"), action="store", default=GENOME_FILE, dest="genome_file", type="character", help="gene counts from genome alignment [%default]"), make_option(c("-t", "--transcript_file"), action="store", default=TRANSCRIPT_FILE, dest="transcript_file", type="character", help="gene counts from transcripts summed to genes [%default]"), make_option(c("-o", "--output"), action="store", default=ERROR_FILE, dest="error_file", type="character", help="per-gene errors, largest differences first [%default]"), make_option(c("-n", "--top"), action="store", default=TOP_N, dest="top_n", type="integer", help="how many of the largest differences to print [%default]") ) # Parse the options. opt = parse_args(OptionParser(option_list=option_list)) # Set the values from the options. design_file = opt$design_file genome_file = opt$genome_file transcript_file = opt$transcript_file error_file = opt$error_file top_n = opt$top_n cat("#\n") cat("# Compare two gene count matrices\n") cat("#\n") cat("# Error is the absolute difference of group means\n") cat("# Pass the -h flag to get help on parameters\n") # Average counts of each gene within each group. group_means <- function(counts, design) { groups <- unique(design$group) means <- vapply(groups, function(g) { samples <- design$sample[design$group == g] rowMeans(counts[, samples, drop = FALSE]) }, numeric(nrow(counts))) colnames(means) <- groups means } # Group means for one count matrix, with id and name. read_means <- function(path, design) { cat("# Loading counts from:", path, "\n") tab <- read.csv(path, check.names = FALSE, stringsAsFactors = FALSE) if (!"id" %in% names(tab)) stop("Count file must have an id column: ", path) missing <- setdiff(design$sample, colnames(tab)) if (length(missing)) { stop("Missing samples in ", path, ": ", paste(missing, collapse = ", ")) } means <- group_means(tab, design) data.frame( id = tab$id, name = tab$name, means, check.names = FALSE, stringsAsFactors = FALSE ) } # |a - b| / mean(a, b). Both zero is agreement, not division by zero. rel_error <- function(a, b) { err <- abs(a - b) denom <- (a + b) / 2 ifelse(denom == 0, 0, err / denom) } # Absolute and relative error for each gene and group, largest first. compare_means <- function(genome, transcript) { both <- intersect(genome$id, transcript$id) if (!length(both)) stop("No genes in common") g <- genome[match(both, genome$id), ] t <- transcript[match(both, transcript$id), ] groups <- setdiff(colnames(genome), c("id", "name")) name <- ifelse(is.na(g$name) | g$name == "", t$name, g$name) rows <- lapply(groups, function(group) { a <- g[[group]] b <- t[[group]] data.frame( id = g$id, name = name, group = group, genome = a, transcript = b, abs_error = abs(a - b), rel_error = rel_error(a, b), stringsAsFactors = FALSE ) }) err <- do.call(rbind, rows) err[order(-err$abs_error, err$id, err$group), ] } # Print mean and median error for each group. print_average <- function(err, groups) { num <- function(x) sprintf("%.2f", x) line <- function(label, vals) { cat(sprintf("%-20s", label), paste(sprintf("%12s", vals), collapse = ""), "\n", sep = "") } take <- function(group, col) err[[col]][err$group == group] line("", groups) line("genes", sapply(groups, function(g) sum(err$group == g))) line("mean abs error", sapply(groups, function(g) num(mean(take(g, "abs_error"))))) line("median abs error", sapply(groups, function(g) num(median(take(g, "abs_error"))))) line("mean rel error", sapply(groups, function(g) num(mean(take(g, "rel_error"))))) line("median rel error", sapply(groups, function(g) num(median(take(g, "rel_error"))))) } # Print the largest absolute differences. print_top <- function(err, n) { top <- head(err, n) cat(sprintf( "%-22s %-16s %-8s %12s %12s %12s %12s\n", "id", "name", "group", "genome", "transcript", "abs_error", "rel_error" )) for (i in seq_len(nrow(top))) { row <- top[i, ] cat(sprintf( "%-22s %-16s %-8s %12.2f %12.2f %12.2f %12.2f\n", row$id, row$name, row$group, row$genome, row$transcript, row$abs_error, row$rel_error )) } } cat("# Loading design from:", design_file, "\n") design <- read.csv(design_file, stringsAsFactors = FALSE) genome <- read_means(genome_file, design) transcript <- read_means(transcript_file, design) shared <- intersect(genome$id, transcript$id) cat("# Genes in both:", length(shared), "\n") cat("# Genes only in genome counts:", length(setdiff(genome$id, transcript$id)), "\n") cat("# Genes only in transcript counts:", length(setdiff(transcript$id, genome$id)), "\n") cat("# Comparing average expression per group\n") err <- compare_means(genome, transcript) dir.create(dirname(error_file), showWarnings = FALSE, recursive = TRUE) cat("# Saving per-gene errors to:", error_file, "\n") write.csv(err, error_file, row.names = FALSE, quote = FALSE) cat("\n") cat("# abs error = |genome - transcript|\n") cat("# rel error = abs error / mean(genome, transcript); 0 when both are 0\n") print_average(err, unique(design$group)) cat("\n") cat("# Most dissimilar expression levels\n") print_top(err, top_n)