Skip to content
Snippets Groups Projects
cuffdiff_report_NoEnr.R 19.1 KiB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
#!/usr/bin/env Rscript
#+ setup, cache=FALSE

suppressMessages(require(docopt))

doc <- '
Convert a cuffdiff into a dge-report
Usage: cuffdiff_report.R [options] <cuffdb_directory>

Options:
--constrasts=<tab_delim_table> Table with sample pairs for which dge analysis should be performed
--qcutoff <qcutoff>    Use a q-value cutoff of 0.01 instead of a q-value cutoff [default: 0.01]
--pcutoff <pcutoff>    Override q-value filter and filter by p-value instead
--minfpkm <minfpkm>   Minimal expression in any of the sample to be included in the final result list [default: 1]
'
#--directed           Perform directed dge-steps in a directed manner
#-S                     Dont do general statistics and qc analysis

#print("args ars")
#print(commandArgs(TRUE))

opts <- docopt(doc, commandArgs(TRUE)) ## does not work when spining
## florio_11b: setwd("/lustre/projects/bioinfo/holger/projects/florio_11b/cuffdiff/dge_report"); opts <- docopt(doc, "--constrasts contrasts.txt --pcutoff 0.01 /projects/bioinfo/holger/projects/florio_11b/cuffdiff")
# opts <- docopt(doc, "--undirected  ..")
# opts <- docopt(doc, "..")
# opts <- docopt(doc, "--pcutoff 0.05 ..")
# opts <- docopt(doc, paste(Sys.getenv("DGE_PARAMS"), ".."))
## todo use commandArgs here!!
#opts <- docopt(doc, paste(Sys.getenv("DGE_PARAMS"), paste(commandArgs(TRUE), collapse=" ")))
#print(opts)

skipQC <<- opts$S
#split_hit_list <- opts$directed
constrasts_file <- opts$constrasts
pcutoff <- if(is.null(opts$pcutoff)) NULL else as.numeric(opts$pcutoff)
qcutoff <- if(is.numeric(pcutoff)) NULL else as.numeric(opts$qcutoff)
if(is.numeric(pcutoff)) opts$qcutoff <- NULL

minFPKM <- as.numeric(opts$minfpkm)


## do basic validation of configuration
stopifnot(is.numeric(qcutoff) | is.numeric(pcutoff))

cuffdb_directory <- normalizePath(opts$cuffdb_directory)

if(is.na(file.info(cuffdb_directory)$isdir)){
    stop(paste("db directory does not exist", doc))
}


devtools::source_url("https://raw.githubusercontent.com/holgerbrandl/datautils/v1.12/R/core_commons.R")
devtools::source_url("https://raw.githubusercontent.com/holgerbrandl/datautils/v1.12/R/ggplot_commons.R")
devtools::source_url("https://raw.githubusercontent.com/holgerbrandl/datautils/v1.12/R/bio/diffex_commons.R")

#+ results='asis', echo=FALSE
cat('
<link rel="stylesheet" type="text/css" href="http://cdn.datatables.net/1.10.5/css/jquery.dataTables.min.css">
<script type="text/javascript" charset="utf8" src="http://code.jquery.com/jquery-2.1.2.min.js"></script>
<script type="text/javascript" charset="utf8" src="http://cdn.datatables.net/1.10.5/js/jquery.dataTables.min.js"></script>

<script type="text/javascript">
         $(document).ready(function() {
            // alert("test")
             $(".dtable").DataTable();
         } );
</script>
')

require(cummeRbund)
require(knitr)

## reload dplyr to fix namespace issues
unloadNamespace('dplyr'); require(dplyr)
#iris %>% count(Species)

#' Used DGE Analysis Parameters
#vec2df(unlist(opts)) %>% filter(!str_detect(name, "^[<-]")) %>% kable()


########################################################################################################################
#' # Differential Gene Expression Analysis

#' [CuffDiff](http://cufflinks.cbcb.umd.edu/manual.html) and [cummeRbund](http://compbio.mit.edu/cummeRbund/) were used to perform this analysis. For details about how the test for differntial expression works, refer to [Differential analysis of gene regulation at transcript resolution with RNA-seq](http://www.nature.com/nbt/journal/v31/n1/full/nbt.2450.html).


#+ load_db, cache=FALSE, warning=FALSE
isCluster=Sys.getenv("LSF_SERVERDIR")!=""
isBioinfoMountPoint=str_detect(normalizePath(cuffdb_directory), fixed("/mnt/"))
isLocalMountPoint=str_detect(normalizePath(cuffdb_directory), fixed("/Volumes/projects"))

dbTempCopyRequired=isCluster | isBioinfoMountPoint | isLocalMountPoint

if(dbTempCopyRequired){
    ## workaround until sqlite  is fixed on lustre
    tmpdir <- tempfile("cuffdb_dir")
    system(paste("cp -r", cuffdb_directory, tmpdir))
    cuff <- readCufflinks(dir=tmpdir)
}else{
    cuff <- readCufflinks(dir="..")
}

#' The expression tracking reference contained:
cuff

#' Used CuffDiff:
runInfo(cuff) %>% filter(param!="cmd_line") %>% kable()
#' cuffdiff cmd was
#+ results='asis'
cat((runInfo(cuff) %>% filter(param=="cmd_line"))$value %>% gsub('(.{1,80})(,|$|\\s)', '\\1\n', .))

#' ### Samples
replicateInfo <- replicates(cuff) %>%
    mutate(file=basename(file)) %>%
    select(-c(total_mass, norm_mass, internal_scale, external_scale))

replicateInfo %>% kable() # kable("html", table.attr = "class='dtable'", escape=F)

write.delim(replicateInfo, file="replicate_info.txt")
# replicateInfo <- read.delim("replicate_info.txt")
#'  [replicateInfo](replicate_info.txt)

#+ results='asis'
## define or load the contrasts
dbContrasts <- diffData(genes(cuff)) %>% select(sample_1, sample_2) %>% distinct()
if(!is.null(constrasts_file)){
    echo("Using contrasts matrix from: ", basename(constrasts_file))

    contrasts <- read.csv(constrasts_file, header=F) %>% set_names(c("sample_1", "sample_2"))

    ## filter for the direction present in cuffdb
    contrasts <- rbind_list(contrasts, contrasts %>% select(sample_1=sample_2, sample_2=sample_1)) %>%  inner_join(dbContrasts)
}else{
    echo("Comparing all samples against each other")
    contrasts <- diffData(genes(cuff)) %>% select(sample_1, sample_2) %>% distinct()
}

#' The used contrasts model is
contrasts %>% kable()

## download gene info and locations from biomart
geneInfo <- quote({
    martName <- guess_mart(fpkm(genes(cuff))$gene_id)
    mart <- biomaRt::useDataset(martName, mart = biomaRt::useMart("ensembl"))
    biomaRt::getBM(c('ensembl_gene_id', 'external_gene_name', 'description', 'gene_biotype'), mart=mart)
}) %>% cache_it("gene_info")

geneLoci <- quote({
    martName <- guess_mart(fpkm(genes(cuff))$gene_id)
    mart <- biomaRt::useDataset(martName, mart = biomaRt::useMart("ensembl"))
    biomaRt::getBM(c("ensembl_gene_id", "chromosome_name", "start_position", "end_position"), mart=mart)
}) %>% cache_it("gene_loci")
#knitr::opts_knit$set(root.dir = getwd())



#######################################################################################################################
#' ## Count and Expression Score Tables

#' All data has been annotated with ensembl gene information and was exprorted into . Both normalized (FPKM) and raw counts were exported.

fpkmMatrix(genes(cuff)) %>%
    rownames2column("ensembl_gene_id") %>%
    merge(geneInfo, by="ensembl_gene_id", all.x=T) %T>%
    glimpse() %>%
    write.delim(file="gene_fpkms.txt")
# gene_fpkms <- read.delim("gene_fpkms.txt")
#' [Normalized Counts](gene_fpkms.txt)

## export the same but now including replicate information

repFpkmMatrix(genes(cuff)) %>%
    rownames2column("ensembl_gene_id") %>%
    merge(geneInfo, by="ensembl_gene_id", all.x=T) %T>%
    glimpse() %>%
    write.delim(file="gene_fpkms_by_replicate.txt")
# gene_fpkms_by_replicate <- read.delim("gene_fpkms_by_replicate.txt")
#' [Normalized Counts by Replicate](gene_fpkms_by_replicate.txt)

## also export count tables
countMatrix(genes(cuff)) %>%
    rownames2column("ensembl_gene_id") %>%
    merge(geneInfo, by="ensembl_gene_id", all.x=T) %>%
    write.delim(file="gene_counts.txt")
# gene_counts <- read.delim("gene_counts.txt")
#' [Gene Counts](gene_counts.txt)

repCountMatrix(genes(cuff)) %>%
    rownames2column("ensembl_gene_id") %>%
    merge(geneInfo, by="ensembl_gene_id", all.x=T) %>%
    write.delim(file="gene_counts_by_replicate.txt")
# rep_counts_by_replicate <- read.delim("gene_counts_by_replicate.txt")
#' [Gene Counts by Replicate](gene_counts_by_replicate.txt)


#######################################################################################################################
#' ## Quality Control

#' Create some global summary statistic plots in order to get an idea about the general quaniltiy and distribution of the expression data. Descriptions are copied from [Cummerbund Manual](http://compbio.mit.edu/cummeRbund/manual_2_0.html)


#' Several plotting methods are available that allow for quality-control or global analysis of cufflinks data. A good place to begin is to evaluate the quality of the model fitting. Overdispersion is a common problem in RNA-Seq data. As of cufflinks v2.0 mean counts, variance, and dispersion are all emitted, allowing you to visualize the estimated overdispersion for each sample as a quality control measure.
dispersionPlot(genes(cuff)) #+ aes(alpha=0.01)

#' The coefficient of variation (CV) is defined as the ratio of the standard deviation the mean. The squared coefficient of variation is a normalized measure of cross-replicate variability that can be useful for evaluating the quality your RNA-seq data. Differences in CV2 can result in lower numbers of differentially expressed genes due to a higher degree of variability between replicate fpkm estimates.
fpkmSCVPlot(genes(cuff))
#fpkmSCVPlot(genes(cuff), showPool=T)

#' To assess the distributions of FPKM scores across samples, we plot their densities
#csDensity(genes(cuff))
#ggsave2(csBoxplot(genes(cuff))+ ggtitle("fpkm boxplots"))

#csDensity(genes(cuff),features=T)
csBoxplot(genes(cuff),replicates=T)
csBoxplot(genes(cuff))

csScatterMatrix(genes(cuff))

#csVolcano(genes(cuff),"a", "b")
#' For the volcano plot matrix we calculate fold-changes as x/y (ie column/row). For details see [here](http://rpackages.ianhowson.com/bioc/cummeRbund/man/csVolcano.html). Signifcance coloring is based on cuffdiff's internal score an not our hit criterion.
csVolcanoMatrix(genes(cuff))

#' We also plot more detailed scatter plots for just the contrasts for interest. Signifcance coloring is based on cuffdiff's internal score an not our hit criterion.
#csVolcano(genes(cuff),"hESC","Fibroblasts")
csVolcPlots <- alply(contrasts, 1,  splat(function(sample_1, sample_2) {
    csVolcano(genes(cuff), sample_1, sample_2)
 }))

#+ fig.width=16
multiplot(plotlist=csVolcPlots, cols=min(3, length(csVolcPlots)))

#csScatter(genes(cuff),"hESC","Fibroblasts",smooth=T)
#csScatter(genes(cuff), "a", "d", smooth=F) + aes(color=abs(log2(a/b))>2) + scale_colour_manual(values=c("darkgreen", "red"))

#MAplot(genes(cuff), "a", "d")+ aes(color=abs(log2(M))>2)+ ggtitle("MA-plot: a/d")
#MAplot(genes(cuff), "a", "b", useCount=T) #+ aes(color=abs(log2(M))>2)+ ggtitle("MA-plot: Luc/KD")

#csVolcano(genes(cuff),"aRGm", "N") + ggtitle("odd line-shaped fan-out in volcano plot")

## todo consider to add more pretty volcano plots (see stefania's extra plots
#getGenes(cuff,c("ENSMUSG00000097853")) %>%  expressionBarplot()


#######################################################################################################################
#' ## Replicate Correlation and Clustering

#' For most type of experiments we expect replicates to cluster together. Second similar biological conditions should cluster together. As clustering results depend on the method being used, we try a few here to check if we get consistent results.

#' Map replicates into 2-dimensional space to highlight replicate clusters (or the lack of them)
require.auto(edgeR)
plotMDS(repFpkmMatrix(genes(cuff)), top=500, main="top500 MDS")


if(unlen(replicates(cuff)$sample) > 2){  ## >2 only, because MDS will fail with just 2 samples
    MDSplot(genes(cuff)) + ggtitle("mds plot")
}

## todo replace with marta plot
#PCAplot(genes(cuff),"PC1","PC2",replicates=T)

noTextLayer <- function(gg){ gg$layers[[2]] <- NULL;; gg}


## todo use fix scaled here
noTextLayer(csDistHeat(genes(cuff)) +  ggtitle("Sample correlation"))

noTextLayer(csDistHeat(genes(cuff),replicates=T) +  ggtitle("Replicate Correlation")) #+ scale_fill_gradientn(colours=c(low='lightyellow',mid='orange',high='darkred'), limits=c(0,0.15))

csDendro(genes(cuff),replicates=T)

#pdf(paste0(basename(getwd()),"_rep_clustering.pdf"))
#csDendro(genes(cuff),replicates=T)
#dev.off()

#' Also cluster only expressed genes (fpkm >1 for at least one sample)
exprGenes <- repFpkmMatrix(genes(cuff)) %>%
    rownames2column("ensembl_gene_id") %>%
    melt(value.name="fpkm") %>%
    group_by(ensembl_gene_id) %>%
    ## apply log trafo
    mutate(log_fpkm=log10(fpkm+1)) %>%
    ## apply expression filter
    filter(max(log_fpkm)>1) %>%
    dcast( ensembl_gene_id ~ variable, value.var="log_fpkm") %>%
    column2rownames("ensembl_gene_id")

res<-JSdist(makeprobs(exprGenes)) %>% hclust() %>% as.dendrogram()

par(mar=c(10,4,4,4))
plot(res, main="Replicate Clustering of Expressed Genes")


#######################################################################################################################
#' ## Differentially expressed genes

#' Here we are using [cuffdiff](http://cole-trapnell-lab.github.io/cufflinks/cuffdiff) to test for differential expression. Estimate variance-mean dependence in count data from high-throughput sequencing assays and test for differential expression based on a model using the negative binomial distribution.

allDiff <- diffData(genes(cuff)) %>%
    ## just keep pairs of interest
    merge(contrasts) %>%

    ##  discard all genes that are not expressed in any of the cell types (>1)
    filter(gene_id %in% getExpressedGenes(cuff, minFPKM=minFPKM)) %>%
    rename(ensembl_gene_id=gene_id, s2_over_s1_log2fc=log2_fold_change) %>%
    mutate(sample_1_overex=s2_over_s1_log2fc<0)

#+ results='asis'
if(!is.null(qcutoff)){
    echo("Using q-value cutoff of", qcutoff)
    allDiff <- transform(allDiff, is_hit=q_value<=qcutoff)
}else{
    echo("Using p-value cutoff of", pcutoff)
    allDiff <- transform(allDiff, is_hit=p_value<=pcutoff)
}

merge(allDiff, geneInfo, by="ensembl_gene_id", all.x=T) %>% write.delim(file="diff_data.txt")
# allDiff <- read.delim("diff_data.txt")
#'  [Unfiltered CuffDiff Results](diff_data.txt)
#

# Filter for DEGs (differentially expressed genes)
degs <- allDiff %>%
    ## Filter for expressed genes
    filter(is_hit) %>%
    ## filter(significant=="yes") ## original hit-flag provided by cummerbund§
    ## add gene info
    left_join(geneInfo, by="ensembl_gene_id")


#'  DEGs (differentially expressed genes) are contained in the following table
write.delim(degs, file="degs.txt")
# degs <- read.delim("degs.txt")
#' [Differentially Expressed Genes](degs.txt)

#' ### DEG Counts
#with(degs, as.data.frame(table(sample_1, sample_2, sample_1_overex))) %>% filter(Freq >0) %>% kable()
degs %>% count( sample_1, sample_2, sample_1_overex) %>% kable()


#+ fig.height=nrow(contrasts)+2
#ggplot(degs, aes(paste(sample_1, "vs",  sample_2), fill=status)) + geom_bar() +xlab(NULL) + ylab("# DGEs") +ggtitle("DEGs by contrast") + coord_flip()
ggplot(degs, aes(paste(sample_1, "vs",  sample_2), fill=sample_1_overex)) + geom_bar() + xlab(NULL) + ylab("# DGEs") + ggtitle("DEGs by contrast") + coord_flip()


#' DEGs can be browsed in Excel using the exported table or via the embedded table browser. To enable the IGV links, you need to set the port in the IGV preferences to 3334.
kableDegs <- degs
if(nrow(degs>2000)){
    kableDegs <- degs %>% arrange(-q_value) %>% head(1000)
    print("just showing first 1000 most significant hits in interactive hit table!!!! Use Excel to browser to browse the full set")
}

#+ results='asis'
kableDegs %>%
    inner_join(geneLoci) %>%
    mutate(
        ensembl=paste0("<a href='http://www.ensembl.org/Multi/Search/Results?y=0;site=ensembl_all;x=0;page=1;facet_feature_type=Gene;q=",ensembl_gene_id, "'>",ensembl_gene_id, "</a>"),
        igv=paste0("<a href='http://localhost:60151/goto?locus=", chromosome_name,":", start_position, "-", end_position, "'>IGV</a>")
    ) %>%
    select(sample_1, sample_2, value_1, value_2, s2_over_s1_log2fc, p_value, q_value, ensembl, external_gene_name, description, gene_biotype, igv) %>%
    kable("html", table.attr = "class='dtable'", escape=F)

## just needed to restore environment easily
save(degs, file=".degs.RData")
# degs <- local(get(load(".degs.RData")))

#' ### MA Plot
#' Redo MA plots but now including hit overlays

maPlots <- allDiff %>% group_by(sample_1, sample_2) %>% do(gg={ maData <-.
    ## todo why not s2_over_s1_log2fc
    maData %>% ggplot(aes(0.5*log2(value_1*value_2), log2(value_1/value_2), color=is_hit)) +
        geom_point(alpha=0.3) +
        geom_hline(yintercept=0, color="red") +
        ggtitle(with(maData[1,], paste(sample_1, "vs", sample_2)))
}) %$% gg

#+ fig.height=10*ceiling(length(maPlots)/2)
multiplot(plotlist=maPlots, cols=min(2, length(maPlots)))


#' ### Relation of FC and p-values
#' To assess the relation of fold-changes and p-value we plot the data as volcano plots for each contrasts including the number of DEGS according our hit criterion.

hitCounts <- degs %>%
        count(sample_1, sample_2, sample_1_overex) %>%
        rename(hits=n) %>%
        merge(data.frame(sample_1_overex=c(T,F), x_pos=c(-3,3)))

##' For the volcano plot matrix we calculate fold-changes as x/y (ie column/row). For details see [here](http://rpackages.ianhowson.com/bioc/cummeRbund/man/csVolcano.html)
#+ fig.width=16, fig.height=14
#allDiff %>% ggplot(aes(s2_over_s1_log2fc, -log10(p_value), color=is_hit)) +
##    geom_jitter(alpha=0.3, position = position_jitter(height = 0.2)) +
#    geom_point(alpha=0.3) +
##    theme_bw() +
#    xlim(-3.5,3.5) +
#    scale_color_manual(values = c("TRUE"="red", "FALSE"="black")) +
##    ggtitle("Insm1/Ctrl") +
#    ## http://stackoverflow.com/questions/19764968/remove-point-transparency-in-ggplot2-legend
#    guides(colour = guide_legend(override.aes = list(alpha=1))) +
#
#    ## tweak axis labels
#    xlab(expression(log[2]("x/y"))) +
#    ylab(expression(-log[10]("p value"))) +
#
#    ## add hit couts
#    geom_text(aes(label=hits, x=x_pos), y=2, color="red", size=10, data=hitCounts) +
#    facet_grid(sample_1 ~ sample_2)


volcPlots <- allDiff %>% group_by(sample_1, sample_2) %>% do(gg={ maData <-.
    maData %>% ggplot(aes(s2_over_s1_log2fc, -log10(p_value), color=is_hit)) +
    #    geom_jitter(alpha=0.3, position = position_jitter(height = 0.2)) +
        geom_point(alpha=0.3) +
    #    theme_bw() +
        xlim(-3.5,3.5) +
        scale_color_manual(values = c("TRUE"="red", "FALSE"="black")) +
    #    ggtitle("Insm1/Ctrl") +
        ## http://stackoverflow.com/questions/19764968/remove-point-transparency-in-ggplot2-legend
#        guides(colour = guide_legend(override.aes = list(alpha=1))) +
        guides(colour = F) +

        ## tweak axis labels
#        xlab(expression(log[2]("x/y"))) +
        with(maData[1,], xlab(paste0("log2(", sample_2, "/", sample_1, ")"))) +
        ylab(expression(-log[10]("p value"))) +
#        with(maData[1,], ggtitle(paste0(sample_2, " over ", sample_1))) +

        ## add hit couts
        geom_text(aes(label=hits, x=x_pos), y=2.5, color="red", size=10, data=semi_join(hitCounts, maData))
}) %$% gg

#+ fig.height=10*ceiling(length(maPlots)/2)
volcPlots %>% multiplot(plotlist=., cols=min(2, length(.)))


## redefine because changed after v1.8
plotPDF <- function(fileBaseName, expr, ...){ pdf(paste0(fileBaseName, ".pdf"), ...); expr; dev.off(); }
plotPDF("contrasts_volcano", volcPlots %>% multiplot(plotlist=., cols=min(2, length(.))), width=12, height=ceiling(nrow(contrasts)/2)*8 )
#' [volcano PDF](contrasts_volcano.pdf)

##+
#' Created `r format(Sys.Date(), format="%B-%d-%Y")` by `r readLines(pipe('whoami'))`, [Scientific Computing Facility](http://www.mpi-cbg.de/facilities/profiles/bioinformatics-and-scientific-computing.html), MPI-CBG