## This README file explains the steps to download and freeze in this
## annotation package the ExAC allele frequencies. If you use these data
## please cite the following publication:

## Exome Aggregation Consortium et al. Analysis of protein-coding genetic
## variation in 60,706 humans. bioRxiv, 2016.
## doi: http://dx.doi.org/10.1101/030338

## The data was downloaded from the FTP server of the Broad Institute as
## follows:
##
## wget ftp://ftp.broadinstitute.org/pub/ExAC_release/release0.3.1/ExAC.r0.3.1.sites.vep.vcf.gz
## wget ftp://ftp.broadinstitute.org/pub/ExAC_release/release0.3.1/ExAC.r0.3.1.sites.vep.vcf.gz.tbi

## The following R script process the downloaded data to
## transform the allele frequencies into minor allele frequencies
## and store them using only one significant digit to reduce the
## memory footprint through RleList objects

library(BSgenome.Hsapiens.1000genomes.hs37d5) ## this is the assembly presumably used by ExAC
library(VariantAnnotation)
library(VariantFiltering)

numDecimals <- function(x) {
  spl <- strsplit(as.character(x+1), "\\.")
  spl <- sapply(spl, "[", 2)
  spl[is.na(spl)] <- ""
  nchar(spl)
}

codeAF2RAW2 <- function(x) {
 maskNAs <- is.na(x)
 z <- x[!maskNAs]
 z[z > 0.1] <- signif(z[z > 0.1], digits=2)
 z[z <= 0.1] <- signif(z[z <= 0.1], digits=1)
 ndec <- numDecimals(z)
 z[ndec < 3] <- z[ndec < 3] * 100
 for (i in 3:max(ndec))
   z[ndec == i] <- z[ndec == i] * 10^i + 100 + (i-3) * 10
 z[z == 0] <- 254  ## code 0 as raw byte value 254 because
                   ## byte value 0 usually implies end of string
                   ## and can lead to problems when serializing it
 x[!maskNAs] <- z
 x[maskNAs] <- 255 ## code NAs as raw byte value 255 because there
                   ## is no NA value for raw vectors
                   ## see "Section 3.3.4 NA handling", R Language Definition
                   ## http://cran.r-project.org/doc/manuals/r-release/R-lang.pdf
 as.raw(x)
}

vcfFilename <- "ExAC.r0.3.1.sites.vep.vcf.gz"
genome <- "hs37d5"
Hsapiens <- hs37d5

vcfHeader <- scanVcfHeader("ExAC.r0.3.1.sites.vep.vcf.gz")
tabHeader <- headerTabix("ExAC.r0.3.1.sites.vep.vcf.gz")

stopifnot(all(seqlengths(vcfHeader)[1:25] == seqlengths(Hsapiens)[1:25])) ## QC

## fill up SeqInfo data
si <- seqinfo(vcfHeader)
isCircular(si) <- isCircular(seqinfo(Hsapiens))[match(seqnames(si), seqnames(seqinfo(Hsapiens)))]
genome(si) <- genome(seqinfo(Hsapiens))[match(seqnames(si), seqnames(seqinfo(Hsapiens)))]

infoCols <- rownames(info(vcfHeader))
ANcols <- c("AN", infoCols[grep("AN_", infoCols)])
exclude <- grep("POPMAX", ANcols)
if (length(exclude) > 0)
    ANcols <- ANcols[-exclude] ## remove colums such as those for maximum allele frequency values among populations
ACcols <- sub("AN", "AC", ANcols)
pops <- substr(ACcols, 4, 20)
AFcols <- gsub("^_", "", paste(pops, "AF", sep="_"))

message("Starting to process variants")

allMAFsnvs <- replicate(n=length(AFcols), RleList(lapply(seqlengths(si), function(x) Rle(raw(x))), compress=FALSE))
names(allMAFsnvs) <- AFcols

## restrict VCF INFO columns to AC and AN values
vcfPar <- ScanVcfParam(geno=NA,
                       fixed="ALT",
                       info=c(ACcols, ANcols))

## read the whole VCF file into main memory (resulting object 'vcf' takes 2.5Gb of RAM)
vcf <- readVcf(vcfFilename, genome=genome, param=vcfPar)

## restrict to SNVs
vcf <- vcf[isSNV(vcf), ]

## fetch variants positions
rr <- rowRanges(vcf)

## fetch allele frequency data
acanValues <- info(vcf)
clsValues <- sapply(acanValues, class)

for (j in seq_along(ACcols)) {
  acCol <- ACcols[j]
  anCol <- ANcols[j]
  afCol <- AFcols[j]
  message(sprintf("Processing %s allele frequencies", afCol))
  acValuesCol <- acanValues[[acCol]]
  anValuesCol <- acanValues[[anCol]]
  if (clsValues[acCol] == "numeric" || clsValues[acCol] == "Numeric" ||
      clsValues[acCol] == "integer" || clsValues[acCol] == "Integer") {
    acValuesCol <- as.numeric(acValuesCol)
  } else if (clsValues[acCol] == "character") {
    acValuesCol <- as.numeric(sub(pattern="\\.", replacement="0", acValuesCol))
  } else if (clsValues[acCol] == "CompressedNumericList" || ## in multiallelic variants take the
           clsValues[acCol] == "CompressedIntegerList") {   ## maximum allele count
    acValuesCol <- as.numeric(sapply(acValuesCol, max))
  } else if (clsValues[acCol] == "CompressedCharacterList") {
    acValuesCol <- sapply(NumericList(lapply(acValuesCol, sub, pattern="\\.", replacement="0")), max)
  }

  if (clsValues[anCol] == "character")
    anValuesCol <- as.numeric(sub(pattern="\\.", replacement="0", anValuesCol))

  mafValuesCol <- acValuesCol / anValuesCol

  ## allele frequencies from ExAC are calculated from allele counts from alternative alleles,
  ## so some of them we need to turn them into minor allele frequencies (MAF)
  mask <- !is.na(mafValuesCol) & mafValuesCol > 0.5
  if (any(mask))
    mafValuesCol[mask] <- 1 - mafValuesCol[mask]

  allMAFsnvs[[afCol]] <- coverage(rr, weight=as.integer(codeAF2RAW2(mafValuesCol)))
  allMAFsnvs[[afCol]] <- RleList(lapply(allMAFsnvs[[afCol]],
                                         function(x) {
                                           runValue(x) <- as.raw(runValue(x))
                                           x
                                         }),
                                   compress=FALSE)
}

## save each raw-Rle object separately
for (i in seq_along(AFcols)) {
  afCol <- AFcols[i]
  dir.create(afCol)
  seqs <- names(allMAFsnvs[[afCol]])
  for (j in seq_along(seqs)) {
    if (any(runValue(allMAFsnvs[[afCol]][[seqs[j]]]) != 0)) {
      fname <- sprintf("%s/snvs.hs37d5.%s.%s.rds", afCol, afCol, seqs[j])
      saveRDS(allMAFsnvs[[afCol]][[seqs[j]]], file=fname)
    }
  }
}

## save the GenomeDescription object
refgenomeGD <- GenomeDescription(organism=organism(Hsapiens),
                                 common_name=commonName(Hsapiens),
                                 provider=provider(Hsapiens),
                                 provider_version=providerVersion(Hsapiens),
                                 release_date=releaseDate(Hsapiens),
                                 release_name=releaseName(Hsapiens),
                                 seqinfo=si)
saveRDS(refgenomeGD, file="refgenomeGD.rds")

## save rs identifier assignment from ExAC
rsIDrrSNVs <- rr[grep("^rs", names(rr))]
mcols(rsIDrrSNVs) <- NULL
rsIDgpSNVs <- as(rsIDrrSNVs, "GPos")
rsIDSNVs <- names(rsIDrrSNVs)
saveRDS(rsIDgpSNVs, file="rsIDgpSNVs.rds")
saveRDS(rsIDSNVs, file="rsIDSNVs.rds")
