IntergenicBinding.R 6 KB
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
#!/usr/bin/env Rscript
#+ setup, cache=FALSE

suppressMessages(require(docopt))

doc <- '
Calculate amount of intergenic binding for a set of bam files
Usage: IntergenicBinding.R [options] <species> <ens_archive> <bamfiles>...

Options:
--sloping <sloping>    The target organism (ensembl biomart name) [default: 1000]
'

opts <- docopt(doc, commandArgs(TRUE)) ## does not work when spining
# opts <- docopt(doc, "--species hsapiens /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/arhgap11b_2/arhgap11b_2.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/control_1/control_1.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/arhgap11b_7/arhgap11b_7.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/arhgap11b_1/arhgap11b_1.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/arhgap11b_4/arhgap11b_4.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/control_6/control_6.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/arhgap11b_6/arhgap11b_6.bam /projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/control_4/control_4.bam")
# opts <- docopt(doc, "--species mmusculus ../mapped/arhgap11b_2/arhgap11b_2.bam ../mapped/arhgap11b_3/arhgap11b_3.bam ../mapped/control_1/control_1.bam ../mapped/arhgap11b_1/arhgap11b_1.bam ../mapped/control_3/control_3.bam ../mapped/control_2/control_2.bam ../mapped/arhgap11b_4/arhgap11b_4.bam ../mapped/control_4/control_4.bam")
require(biomaRt)

#' Used configuration
print(opts)

bamFiles <- opts$bamfiles
ensVersion <- opts$ens_archive
#ensVersion <- "mar2016"
species <- opts$species
sloping <- opts$sloping

28 29
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.22/R//core_commons.R")
devtools::source_url("https://git.mpi-cbg.de/bioinfo/datautils/raw/v1.22/R//bio/bioinfo_commons.R")
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

require_auto(whisker) # http://stackoverflow.com/questions/10341114/alternative-function-to-paste
#?whisker.render

########################################################################################################################
##> Build integenic model {eval=FALSE}


geneInfo <- quote({
    # mart <- paste0(species, "_gene_ensembl") %>% biomaRt::useDataset(mart = biomaRt::useMart("ensembl"))
    mart <- paste0(species, "_gene_ensembl") %>% useDataset(mart = biomaRt::useMart("ENSEMBL_MART_ENSEMBL", host=paste0(ensVersion, ".archive.ensembl.org")))

    getBM(c('ensembl_gene_id', 'chromosome_name', 'strand', 'start_position', 'end_position'), mart=mart)
}) %>% cache_it()

## write gene bed file
#genes <- getBM(attributes=c('ensembl_gene_id', 'chromosome_name', 'strand', 'start_position', 'end_position'), mart=mart)
bedFile=paste(species, ensVersion, "genes.bed", sep="_")
geneInfo %>% mutate(
        strand=ifelse(strand>0, "+", "-"),
        chromosome_name=paste0("chr", chromosome_name)
    ) %>%
    #just keep regular chromsomes
    filter(str_detect(chromosome_name, "chr[0-9XY]{1,2}$")) %>%
    with(data.frame(chromosome_name, start_position, end_position, ensembl_gene_id, score='.', strand)) %>%
    filter(start_position<end_position) %>%
    write.bed(file=bedFile)


## slop-complement the genes
## https://www.biostars.org/p/113100/

#mouse:GRCm38==mm10
species2ucsc <- c(hsapiens="hg38", mmusculus="mm10")
stopifnot(!is.na(species2ucsc[species]))

ucscGeneome=species2ucsc[species]

whisker.render('
genomeBuild={{ucscGeneome}}
geneExt={{sloping}}
#genomeBuild=hg38

mysql --user=genome --host=genome-mysql.cse.ucsc.edu -A -e "select chrom, size from $genomeBuild.chromInfo" | sort -k 1,1 > $genomeBuild.genome

# genesBed=hsapiens_genes.bed
genesBed={{bedFile}}

#slopBed -b ${geneExt} -i $genesBed  -g $genomeBuild.genome | sortBed -i stdin | complementBed -i stdin -g $genomeBuild.genome  | grep "^chr" | grep -v "alt"| grep -v "Un"| grep -v "random" > $(basename $genesBed .bed).intergenic_1k.bed
genesBedExt=$(basename $genesBed .bed).1k.bed
slopBed -b ${geneExt} -i $genesBed  -g $genomeBuild.genome | sortBed -i stdin | sed s/chr//g  > ${genesBedExt}

') %T>% cat %>% system()


########################################################################################################################
##> Overlap tags with integenic model

bamsCsv=bamFiles %>% paste(collapse=" ")

#if(!file.exists("ig_overlaps"))
whisker.render('
#mkdir ig_overlaps

genesBed={{bedFile}}
genesBedExt=$(basename $genesBed .bed).1k.bed
bamFiles="{{bamsCsv}}"
#bamFiles=$(find $baseDir/mapped -name "*.bam" | grep -v unmapped)

#head $genesBedExt
#cut -f1 $isBed | sort | uniq -c

jl reset

for bamFile in $bamFiles; do
    ## DEBUG bamFile="../ctrl_high_1.bam"
    echo "processing $bamFile"

#    jl submit -n "ib__$(basename $bamFile)"  "sortBed -i $bamFile | intersectBed -sorted -wb -a ${genesBedExt} -b stdin  | wc -l > $(basename $bamFile .bam).genic_tags.txt"
    jl submit -n "ib__$(basename $bamFile)"  "intersectBed -u -bed -a ${bamFile} -b ${genesBedExt} | wc -l > $(basename $bamFile .bam).genic_tags.txt"
done

jl wait
') %T>% cat %>% system()



genicTags <- list.files(".", ".genic_tags.txt", full.names=TRUE) %>% ldply(function(tagCountFile){
    data.frame(
        sample=basename(tagCountFile) %>% str_split_fixed(fixed("."), 2) %>% subset(sel=1),
        num_genic_tags=readLines(tagCountFile) %>% as.numeric()
    )
})


## eneable threading support
library(foreach); library(doMC); registerDoMC(cores=10)

totalAlgns <- quote(ldply(bamFiles, function(bamFile){
    ## DEBUG bamFile="/projects/bioinfo/holger/projects/rnaseq_florio_11b_hsap6h/mapped/control_1/control_1.bam"

    data_frame(
        sample=basename(bamFile) %>% trim_ext(".bam"),
        total_algn=paste("samtools flagstat ", bamFile, " | cut -f1 -d' ' | head -n1") %>% system(intern=T) %>% as.numeric()
    )
}, .parallel=T)) %>%  cache_it()


inner_join(genicTags, totalAlgns) %>%
    mutate(genic_tag_proportion=num_genic_tags/total_algn) %T>% write.delim(file="ig_proportions.txt") %>%
    ggplot(aes(sample, genic_tag_proportion)) +
    geom_bar(stat="identity") +
    ggtitle("genic tag proportions") +
    coord_flip() +
    ylim(0,1)