softclip_summary.R 6.65 KB
Newer Older
Melanie Schneider's avatar
Melanie Schneider committed
1 2 3 4 5 6
#!/usr/bin/env Rscript
#' #  Clipping summary of ChipSeq data for `r getwd()`
##+ echo=FALSE, message=FALSE

## Note This script is supposed to be knitr::spin'ed

7 8
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.9/R/core_commons.R")
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.9/R/ggplot_commons.R")
Melanie Schneider's avatar
Melanie Schneider committed
9 10 11 12 13 14 15 16 17 18 19
require(knitr)

## Can we access variables from the parent spin.R process?
#echo("rscript is ", r_script)

argv = commandArgs(TRUE)
#echo("argv is ", argv)

#if(str_detect(argv[1], "softclip_summary")) argv <- argv[-1]

if(length(argv) != 1){
20
  stop("Usage: softclip_summary.R <directory with bam files>")
Melanie Schneider's avatar
Melanie Schneider committed
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
}

baseDir=argv[1]
#baseDir="sftp://bioinformatics-srv1/local/home/mschneid/4_softclipping/small_test"
#baseDir='sftp://bioinformatics-srv1/local/home/brandl/mnt/bioinformatics/projects/Melanie/soft_clipping/small_test'
#baseDir='/home/brandl/mnt/bioinformatics/projects/Melanie/soft_clipping/small_test'

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

##' Analyzed data:
bamDataFiles <- list.files(path=baseDir, pattern="*.bam$", full.names=TRUE, recursive=T)
echo("files are", bamDataFiles)

## Note: Mapping is not done. (For usage remove '#' also in front of 'mapping_command' & 'mapping_output' in 'clippingSummary2')
## building mapping command string for each file 
#fastqDataFiles <- list.files(path=baseDir, pattern="*.fastq*", full.names=TRUE, recursive=T)
#bowtieIndex_mouse="/local2/igenomes/Mus_Musculus/UCSC/mm10/Sequence/Bowtie2Index/genome"
#buildcommand <- function(index, file, bname){ 
#  sprintf("/home/mschneid/bowtie2-2.2.5/bowtie2 --local -p 10 -x %s -U %s | samtools view -bS - |  samtools sort - %s/%s", index, file, baseDir, bname)
#}

## Build counting command strings for each bam file

samtools_flagstat <- function(BAM){
  sprintf("samtools flagstat %s" , BAM)
}
count_all_mapped<- function(BAM){
  sprintf("samtools view -F 4 %s | wc -l ", BAM)
}
count_all_s <- function(BAM){
  sprintf("samtools view %s | awk '($6 ~ /S/ && $6 !~ /*/) || $1 ~ /@/' | wc -l ", BAM)
}
count_end <- function(BAM){
  sprintf("samtools view %s | awk '($6 ~ /S$/ && $6 !~ /*/) || $1 ~ /@/' | wc -l ", BAM)
}
count_front <- function(BAM){
  sprintf("samtools view %s | awk '($6 ~ /S..M/ && $6 !~ /*/) || $1 ~ /@/' | wc -l ", BAM)
}
count_front_and_end <- function(BAM){
  sprintf("samtools view %s | awk '($6 ~ /S$/ && $6 ~ /S..M/ && $6 !~ /*/) || $1 ~ /@/' | wc -l ", BAM)
}


#' ## Clipping summary

clippingSummary <- function(bamFile){
  data.frame(
    condition=basename(bamFile) %>% trim_ext(".bam"),
    #    filename=bname,
    #    bname=sub("^([^.]*).*", "\\1", basename(bamFile)),
    #    bam_stats=system(samtools_flagstat(bamFile), intern=TRUE),
    #    All_mapped_reads=as.numeric(system(paste("cat "bam_stats" | head -n4 | grep 'mapped (' | awk '{print $2}'"), intern=T)),
    All_mapped_reads=as.numeric(system(count_all_mapped(bamFile), intern=TRUE)),
    All_softclipped_reads=as.numeric(system(count_all_s(bamFile), intern=TRUE)),
    softclipped_at_end=as.numeric(system(count_end(bamFile), intern=TRUE)),
    softclipped_at_front=as.numeric(system(count_front(bamFile), intern=TRUE)),
    softclipped_at_frontandend=as.numeric(system(count_front_and_end(bamFile), intern=TRUE))
  )
}


## Including mapping (bowtie2)
#clippingSummary2 <- function(fastqFile){
#  data.frame(
#    bname=sub("^([^.]*).*", "\\1", basename(fastqFile)),
#    mapping_command=buildcommand(bowtieIndex_mouse, fastqFile, bname), # build the mapping command for each fastqFile
#    mapping_output=system(mapping_command, intern=TRUE), # execute mapping command and get terminal output in variable
#  )
#}


## aply clippingSummary to all bamDataFiles
#clippingStats <- bamDataFiles %>% ldply(clippingSummary)
require.auto(foreach); require.auto(doMC); registerDoMC(cores=20)
clippingStats <- bamDataFiles %>% ldply(clippingSummary, .parallel=T)

#+ results = 'asis'
clippingStats %>% head() %>% kable()


## Obtain relative numbers (%) of all kind of softclipped reads and add them to the data frame clippingStats.
clippingStats %<>% mutate(
  All_softclipped_reads_norm=All_softclipped_reads/All_mapped_reads,
  softclipped_at_end_norm=softclipped_at_end/All_softclipped_reads,
  softclipped_at_front_norm=softclipped_at_front/All_softclipped_reads,
  softclipped_at_frontandend_norm=softclipped_at_frontandend/All_softclipped_reads
)

clippingStats[is.na(clippingStats)] <- 0

## Incorporate the .txt file in the html under clickable link
##'  [Softclipping Statistics](chipseq_summary.clippingStats.txt)
write.delim(clippingStats, file="softclip_summary.clippingStats.txt")

## Do dynamic scaling of bar height for all following plots until there is a new heading
#+ fig.height=nrow(clippingStats)/3+2, fig.width=12
require(scales)

ggplot(clippingStats, aes(condition, All_mapped_reads)) +
  geom_bar(stat='identity') +
  coord_flip() +
  scale_y_continuous(labels=comma) +
## other layer with softclipped ones
#  geom_bar(aes(condition, All_softclipped_reads), stat='identity', color='red', alpha=0.4) +
  ggtitle("Number of mapped reads") +
  ylab("Number of mapped reads")

ggplot(clippingStats, aes(condition, All_softclipped_reads_norm)) +
  geom_bar(stat='identity') +
  coord_flip() +
  scale_y_continuous(labels=percent, limits=c(0,1)) +
  ggtitle("Softclipped reads proportion") +
  ylab("Softclipped reads proportion (of all mapped reads)")

ggplot(clippingStats, aes(condition, softclipped_at_end_norm)) +
  geom_bar(stat='identity') +
  coord_flip() +
  scale_y_continuous(labels=percent, limits=c(0,1)) +
  ggtitle("Softclipped-at-end reads proportion") +
  ylab("Softclipped-at-end reads proportion (of softclipped reads)")
  
ggplot(clippingStats, aes(condition, softclipped_at_front_norm)) +
  geom_bar(stat='identity') +
  coord_flip() +
  scale_y_continuous(labels=percent, limits=c(0,1)) +
  ggtitle("Softclipped-at-front reads proportion") +
  ylab("Softclipped-at-front reads proportion (of softclipped reads)")
  
ggplot(clippingStats, aes(condition, softclipped_at_frontandend_norm)) +
  geom_bar(stat='identity') +
  coord_flip() +
  scale_y_continuous(labels=percent, limits=c(0,1)) +
  ggtitle("Softclipped-at-both-ends reads proportion") +
  ylab("Softclipped-at-both-ends reads proportion (of softclipped reads)")



##-----------NOT USED-----------
## For All_softclipped_reads: x/All_mapped_reads
## For the rest: x/All_softclipped_reads

#myfun <- function(x, NOM) x/(NOM)
#clippingStats2 <- mutate_each(clippingStats, funs(myfun(., All_softclipped_reads)), softclipped_at_end, softclipped_at_front, softclipped_at_frontandend)
#clippingStats2 <- mutate_each(clippingStats, funs(myfun(., All_mapped_reads)), All_softclipped_reads)
#-------------------------------