cs_region_dba.R 7.63 KB
Newer Older
Holger Brandl's avatar
Holger Brandl committed
1 2
#!/usr/bin/env Rscript

3 4 5 6 7
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.4/R/core_commons.R")
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.4/R/ggplot_commons.R")

## todo replace with ngs_tools/dge_workflow/diffex_commons.R
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.40/R/bio/diffex_commons.R")
Holger Brandl's avatar
Holger Brandl committed
8

Holger Brandl's avatar
Holger Brandl committed
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

require(tidyr)
require(knitr)
require.auto(digest)


#' # Region Count Analysis
## spin.R

geneInfo <- quote({
        mart <- biomaRt::useDataset("drerio_gene_ensembl", mart = biomaRt::useMart("ensembl"))
        c("ensembl_gene_id", "external_gene_name", "description", "chromosome_name", "start_position", "end_position") %>%
            biomaRt::getBM(mart=mart)
    }) %>%
    cache_it()

Holger Brandl's avatar
Holger Brandl committed
25 26 27
## todo use docopt here
countData <- read.delim("replicate_counts.tss_2kb.txt")
names(countData) <- names(countData) %>% str_replace("[.]1", "")
Holger Brandl's avatar
Holger Brandl committed
28

Holger Brandl's avatar
Holger Brandl committed
29
countMatrix <- countData %>% column2rownames("ensembl_gene_id") %>% as.matrix()
Holger Brandl's avatar
Holger Brandl committed
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

########################################################################################################################
#' # Differential binding analysis


hasContastsFile=F
if(hasContastsFile){
    contrasts <- read.csv(constrasts_file, header=F) %>% set_names(c("sample_1", "sample_2"))
}else{
    contrasts <- data.frame(sample=colnames(countMatrix)) %>%
        merge(.,., suffixes=c("_1", "_2"), by=NULL) %>%
        filter(ac(sample_1)>ac(sample_2)) %>%
#        filter(ac(sample_1)!=ac(sample_2)) %>%
        fac2char
    write.delim(contrasts.txt, "contrasts.txt")
}

#+ results='asis'
#' Used contrasts model is
contrasts %>% kable()

# See deseq [docs](http://master.bioconductor.org/packages/release/bioc/vignettes/DESeq2/inst/doc/DESeq2.pdf) for details

require.auto(DESeq2)
require.auto(gplots)

## todo make sure that control comes first to get fold-changes right
#Note: In order to benefit from the default settings of the package, you should put the variable of interest
#at the end of the formula and make sure the control level is the first level.

colData <- data.frame(condition=colnames(countMatrix))
dds <- DESeqDataSetFromMatrix(countMatrix, colData, formula(~ condition))
#dds <- DESeq(dds)
dds <- DESeq(dds, fitType='local')
res <- results(dds)

resultsNames(dds)
summary(res)

deResults <- adply(contrasts, 1,  splat(function(sample_1, sample_2){
  #  browser()
   results(dds, contrast=c("condition",sample_1,sample_2)) %>%
        rownames2column("ensembl_gene_id") %>%
        as.data.frame() %>%
        mutate(
            sample_1=sample_1,
            sample_2=sample_2,
            sample_1_overex=log2FoldChange<0
        )
}), .progress="text")

deResults %>% with(as.data.frame(table(sample_1, sample_2)))

#+ fig.width=20, fig.height=18
deResults %>% ggplot(aes(log2FoldChange)) +
    geom_histogram(binwidth=0.1) +
86
    facet_grid(sample_1 ~ sample_2) + geom_vline(xintercept=0, color="blue") +
Holger Brandl's avatar
Holger Brandl committed
87 88
    xlim(-4,4)

Holger Brandl's avatar
Holger Brandl committed
89 90
deResults %>% ggplot(aes(pvalue)) +
    geom_histogram() +
91
    facet_grid(sample_1 ~ sample_2) + geom_vline(xintercept=0.01, slope=1, color="blue")
Holger Brandl's avatar
Holger Brandl committed
92

Holger Brandl's avatar
Holger Brandl committed
93 94 95 96 97 98
### see https://www.biostars.org/p/80448/ for Pairwise Comparison
#res <- results(dds, contrast=c(c("condition","H1M_Dome","H1M_Shield")))
#res <- results(dds, contrast=c(c("condition","H3K4_Shield","H1M_Shield")))
#res <- results(dds, contrast=c(c("condition","H1M_Shield", "H3K4_Shield")))

deResults %<>% mutate(is_hit=pvalue<0.01)
Holger Brandl's avatar
Holger Brandl committed
99 100 101 102 103

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

Holger Brandl's avatar
Holger Brandl committed
104 105 106
degs <- deResults %>% filter(is_hit)

ggplot(degs, aes(paste(sample_1, "vs",  sample_2))) + geom_bar() +xlab(NULL) + ylab("# DBGs") +ggtitle("DBG count summary") + coord_flip()
Holger Brandl's avatar
Holger Brandl committed
107
ggplot(degs, aes(paste(sample_1, "vs",  sample_2), fill=sample_1_overex)) + geom_bar(position="dodge") +xlab(NULL) + ylab("# DBGs") +ggtitle("DBG count summary by direction of expression") + coord_flip()
Holger Brandl's avatar
Holger Brandl committed
108 109 110 111 112 113 114 115 116

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

#res %>% as.df() %>% ggplot(aes(pvalue)) + geom_histogram()
#res %>% as.df() %>% ggplot(aes(padj)) + geom_histogram()


Holger Brandl's avatar
Holger Brandl committed
117 118 119 120 121 122
## todo add gene info
degs %>% inner_join(geneInfo) %>%write.delim(file="degs.txt")
# degs <- read.delim("degs.txt")
#'  [degs](degs.txt)


Holger Brandl's avatar
Holger Brandl committed
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

plotMA(res, main="DESeq2", ylim=c(-2,2))

## note see  ?DESeq section on 'Experiments without replicates'

## hwo to specify which conditions to run the test on
## http://seqanswers.com/forums/showthread.php?t=28350
#For making comparisons of multiple conditions (not only against the base level of a condition), we have recently implemented contrasts in the development branch. This allows one to fit a single model, then generate log2 fold change estimates, standard errors and tests of null hypotheses for other comparisons.

#+ eval=FALSE, echo=FALSE, include=F
## DEBUG start
if(F){
## DEBUG end
## base means (see http://seqanswers.com/forums/showthread.php?t=28350&page=2)
baseMeanPerLvl <- sapply(levels(colData(dds)$condition), function(lvl) rowMeans(counts(dds,normalized=TRUE)[,colData(dds)$condition == lvl]))

counts(dds,normalized=TRUE) %>% as.df() %>% set_names(colData(dds)$condition) %>%
    rownames2column("ensembl_gene_id") %>%
    filter(ensembl_gene_id=="ENSDARG00000098036")

countDataNorm %>% filter(ensembl_gene_id=="ENSDARG00000000324", sample %in% c("H3HA_Oblong", "H3HA_Dome"), feature_type==regionTypeDBA)
#baseMean log2FoldChange     lfcSE       stat     pvalue      padj    ensembl_gene_id    sample_1  sample_2 sample_1_overex
#19  12.529275     0.95396312 0.6345064  1.5034728 0.13271717 0.8131601 ENSDARG00000000324 H3HA_Oblong H3HA_Dome           FALSE
}



########################################################################################################################
#' ## Term enrichment

#+ echo=FALSE

#' This analysis was performed using [David](http://david.abcc.ncifcrf.gov/). The following ontologies were tested: `r paste(ontologies, collapse=', ')`

geneLists <- degs %>%
#    transmute(ensembl_gene_id, list_id=paste(sample_1, "vs", sample_2, "ovex", sample_1_overex, sep="_"))
    transmute(ensembl_gene_id, list_id=paste(sample_1, "vs", sample_2))

split_hit_list <- F
grpdDegs <- if(split_hit_list){
    degs %>% group_by(sample_1, sample_2, sample_1_overex)
}else{
    degs %>% group_by(sample_1, sample_2)
}

enrResults <- grpdDegs %>% do(davidAnnotationChart(.$ensembl_gene_id))


write.delim(enrResults, file="enrResults.txt")
# enrResults <- read.delim("enrResults.txt")
#'  [Enrichment Results](enrResults.txt)

sigEnrResults <- subset(enrResults, Bonferroni <0.01)

write.delim(sigEnrResults, file="sigEnrResults.txt")
# sigEnrResults <- read.delim("sigEnrResults.txt")
#'  [Very Significant Terms](sigEnrResults.txt)


## plot the enrichment results
#sigEnrResults %>% group_by(Category, add=T) %>% do({
#    logPlot <- . %>% ggplot(aes(Term, PValue)) +
#	    geom_bar(stat="identity")+coord_flip() +
#	    xlab("Enriched Terms") +
#	    ggtitle(.$Category[1]) +
#	    scale_y_log10()
#	    print(logPlot)
#})

sigEnrResults %>% do({
    enrResultsGrp <- .
    ## DEBUG enrResultsGrp <- sigEnrResults
    label <-
    dplyr::select(enrResultsGrp, matches(ifelse(split_hit_list, "sample_1|sample_2|sample_1_overex", "sample_1|sample_2"))) %>%
      head(1) %>% apply(1, paste, collapse="_vs_")

    echo("processing", label)

    logPlot <- enrResultsGrp %>%
        ## fix factor order
        mutate(Term=reorder(Term, -PValue) %>% reorder(as.integer(Category))) %>%
        ggplot(aes(Term, PValue, fill=Category)) +
	    geom_bar(stat="identity")+
	    coord_flip() +
	    xlab("Enriched Terms") +
	    ggtitle(label) +
	    scale_y_log10()

	    ggsave(paste0(label, " enrichmed terms.pdf"))
	    print(logPlot)
})
#ggsave2()