Last updated: 2020-09-01

Checks: 7 0

Knit directory: EMBRAPA_2020GS/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200826) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version d97980a. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    analysis/.DS_Store
    Ignored:    data/.DS_Store

Untracked files:
    Untracked:  data/OrderAppendix_1_DCas20-5360/
    Untracked:  data/Report-DCas20-5360/
    Untracked:  workflowr_log.R

Unstaged changes:
    Modified:   analysis/ImputeDCas20_5360.Rmd
    Modified:   analysis/convertDCas20_5360_ToVCF.Rmd

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/convertDCas19_4403_ToVCF_102419.Rmd) and HTML (docs/convertDCas19_4403_ToVCF_102419.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
html d29d605 wolfemd 2020-09-01 Build site.
html 5a2cc5b wolfemd 2020-09-01 Build site.
html ed70a5a wolfemd 2020-08-26 Build site.
Rmd 9d4dfab wolfemd 2020-08-26 Code organized into functions. Ready to run imputation of C2?

Input Parameters

library(tidyverse); library(magrittr)
dartvcfInput<-paste0("/workdir/marnin/DCas19_4403/Report_4403_VCF_Version_6.csv")
dartcountsInput<-paste0("/workdir/marnin/DCas19_4403/Report_4403_Counts_Version_6_updated.csv")
outName<-paste0("/workdir/marnin/DCas19_4403/DCas19_4403_102419")
nskipvcf<-2
nskipcounts<-3
ncores<-75 # using more than a few could be VERY memory intensive

Components of function

Read and format the 4432 counts/vcf files

# convertDart2vcf<-function(dartvcfInput,dartcountsInput,outName,
#                           nskipvcf=2,nskipcounts=3,ncores){
#rm(vcf,readCounts); gc()
vcf<-read.table(dartvcfInput,
                stringsAsFactors = F,skip = nskipvcf, header = T, sep = "\t", comment.char = "")
dim(vcf) # [1] 13603   654
readCounts<-read.csv(dartcountsInput, stringsAsFactors = F,header = T,skip=nskipcounts)
colnames(vcf)[10:length(colnames(vcf))]<-colnames(readCounts)[43:length(colnames(readCounts))]

vcf %<>% 
    mutate(X.CHROM=gsub("Chromosome","",X.CHROM)) %>% 
    rename(Pos=POS) %>% 
    mutate(Chr=as.numeric(gsub("Chromosome","",X.CHROM)),
           Pos=as.numeric(Pos)) 


# dim(readCounts)
# readCounts %>% .[,1:30] %>% str
# readCounts[1:5,1:30]
# readCounts[1:10,] %>% select(SNP,CloneID,AlleleID,Chrom_Cassava_v61,SNP_ChromPos_Cassava_v61)
# vcf[1:10,1:5]
# Note: The ID column in "vcf" is the value for the ALT allele in AlleleID of "readCounts"
readCounts %<>% 
  mutate(RefAlt=ifelse(SNP=="","REF","ALT"),
         Chr=as.numeric(gsub("Chromosome","",Chrom_Cassava_v61)),
         Pos=as.numeric(SNP_ChromPos_Cassava_v61))

Add a SNPindex

Add a unique value “SNPindex” to each SNP in the vcf and readCounts df’s For readCounts, this is going to be the best way to keep track of pairs of rows. Since in many cases, multiple CloneID can point to same Chr-Pos-Alleles and it’s otherwise unclear which pair of rows should go together when subsetting downstream.

dim(vcf) # [1] 13603  655
dim(readCounts) # [1] 27206  690
vcf %<>% 
  mutate(SNPindex=1:nrow(.))
readCounts %<>% 
  mutate(SNPindex=sort(rep(1:(nrow(.)/2),2)))
readCounts %<>% 
  separate(AlleleID,c("tmp","Alleles"),sep=-3,remove = F) %>% 
  select(-tmp) %>% 
  separate(Alleles,c("REF","ALT"),">",remove = F)
vcf %<>%
  separate(ID,c("tmp","Alleles"),sep=-3,remove = F) %>%
  select(-tmp)
vcf %<>% 
    separate(ID,c("CloneID","tmp"),"[|]",remove = F,extra = 'merge') %>% 
    mutate(CloneID=as.numeric(CloneID)) %>% 
    select(-tmp) %>% 
    rename(AlleleID=ID)
readCounts %>% 
  dplyr::select(Chr,Pos,REF,ALT,Alleles,RefAlt,SNPindex,SNP,CloneID,AlleleID) %>% head
vcf %>% 
  dplyr::select(Chr,Pos,ID,REF,ALT,Alleles,SNPindex) %>% head

readCounts and vcf long by sample

# Add required VCF fields
## First have to do some data transformation and 
## create some of the meta-data fields in a VCF, e.g. QUAL, FILTER INFO. 
readCounts %<>%
  arrange(Chr,Pos,SNPindex,CloneID,AlleleID,RefAlt) %>% 
  mutate(QUAL=".",
         FILTER=".",
         INFO=".",
         FORMAT="GT:AD:DP:PL",
         SNP_ID=paste0("S",Chr,"_",Pos))
vcf %<>%
  arrange(Chr,Pos,SNPindex,CloneID,AlleleID) %>% 
  mutate(QUAL=".",
         FILTER=".",
         INFO=".",
         FORMAT="GT:AD:DP:PL",
         SNP_ID=paste0("S",Chr,"_",Pos))
vcf %>% 
  select(Chr,Pos,SNPindex,CloneID,AlleleID,Alleles,REF,ALT,QUAL,FILTER,INFO,FORMAT,SNP_ID) %>% head
readCounts %>% filter(RefAlt=="ALT") %>% 
  select(Chr,Pos,SNPindex,CloneID,AlleleID,Alleles) %>% slice(1:10)

[NEW] Prune duplicate and multi-allelic sites

sites2keep<-vcf %>% 
    count(Chr,Pos) %>% 
    ungroup() %>% 
    filter(n==1) %>% 
    select(-n) %>% 
    semi_join(
        readCounts %>% 
            count(Chr,Pos) %>% 
            arrange(desc(n)) %>% 
            filter(n==2) %>% 
            select(-n)) # 12049 sites

vcf %<>% semi_join(sites2keep)
readCounts %<>% semi_join(sites2keep)
table((readCounts %>% filter(RefAlt=="ALT") %$% SNPindex)==vcf$SNPindex)

sampleIDsFromDartVCF<-colnames(vcf) %>% 
  .[!. %in% c("X.CHROM","Pos","AlleleID","Alleles","REF","ALT","QUAL","FILTER","INFO","FORMAT",
              "Chr","SNPindex","CloneID","SNP_ID","SNP")]
head(sampleIDsFromDartVCF); tail(sampleIDsFromDartVCF)

tmp_counts <-readCounts %>% 
  .[,c("Chr","Pos","SNPindex","SNP_ID",
       "CloneID","AlleleID","RefAlt","Alleles","QUAL","FILTER","INFO","FORMAT",sampleIDsFromDartVCF)] %>% 
    semi_join(sites2keep)
dim(tmp_counts) # [1] 24098   657
tmp_counts %<>%
  gather(FullSampleName,ReadCount,sampleIDsFromDartVCF)
dim(tmp_counts) # [1] 15543210       14
tmp_counts %<>%
  select(-AlleleID) %>% 
  spread(RefAlt,ReadCount) 
dim(tmp_counts) # [1] 7771605      13
head(tmp_counts)
tmp_counts %<>%
  rename(AltCount=ALT,
         RefCount=REF)
dim(tmp_counts) # [1] 7771605      13

vcf_long<-vcf %>% 
    .[,c("Chr","Pos","SNPindex","SNP_ID",
         "CloneID","Alleles","REF","ALT","QUAL","FILTER","INFO","FORMAT",sampleIDsFromDartVCF)] %>% 
    gather(FullSampleName,GT,sampleIDsFromDartVCF)
dim(vcf_long) # [1] 7771605      14
table(vcf_long$CloneID %in% tmp_counts$CloneID) # all true

Add GT from vcf to the counts

I use the DArT genotype call (GT) for the PLINK IBD step.
PLINK requires genotype calls.
Later, I impute in GL mode, so GTs are ignored.

tmp_counts %<>%
  inner_join(vcf_long)
dim(tmp_counts); head(tmp_counts)

Calc PL field

# AD+DP fields
## Now we can calc DP and formate the VCF field "AD" (e.g. "21,0" for 21 reference reads and 0 alt. allele reads)
tmp_counts %<>% 
  mutate(DP=AltCount+RefCount,
         AD=paste0(RefCount,",",AltCount))
tmp1<-tmp_counts %>% 
    filter(!is.na(AltCount),
           !is.na(RefCount))
tmp<-tmp1; rm(tmp1)
tmp %>% head

# Calc. genotype likelihoods

## Genotype likelihoods calculated according to: 
### http://journals.plos.org/plosgenetics/article?id=10.1371/journal.pgen.1000862#s4
## Converted to Normalized Phred Scores according to: 
### https://gatkforums.broadinstitute.org/gatk/discussion/5913/math-notes-how-pl-is-calculated-in-haplotypecaller
## Truncate low Phred probabilities (high Phred scores) to 
### 255 max according to TASSEL's convention (Jeff Glaubitz, pers. communication).

#ref<-171; alt<-171; error<-0.001
calcPL<-function(ref,alt,error=0.001){
    # ref and alt arguments are read counts for ref and alt allele, repsectively
    dp<-ref+alt
    # for values >170, factorial() returns 'inf'
    # Since it means essentially 100% probability of a genotype... 
    # set DP to 169 cieling, ref/alt to equiv. allele proportions
    if(dp>=170){ ref<-169*(ref/dp); alt<-169*(alt/dp); dp<-169 }
    gl_RefRef<-(factorial(dp)/(factorial(ref)*factorial(alt)))*(1-(0.75*error))^ref*(error/4)^(alt)
    gl_RefAlt<-(factorial(dp)/(factorial(ref)*factorial(alt)))*(0.5-(0.25*error))^(ref+alt)*(error/4)^(0)
    gl_AltAlt<-(factorial(dp)/(factorial(ref)*factorial(alt)))*(1-(0.75*error))^alt*(error/4)^(ref)
    phredScale<--10*log10(c(gl_RefRef,gl_RefAlt,gl_AltAlt))
    minPhred<-min(phredScale)    
    normPhred<-round(phredScale-minPhred,0)
    normPhred[which(normPhred>=255)]<-255
    normPhred<-paste0(normPhred,collapse = ",")
    if(dp==0){ normPhred<-"." }
    return(normPhred)
  }
require(furrr); options(mc.cores=ncores); plan(multiprocess)
tmp %<>% 
  mutate(PL=future_map2_chr(RefCount,AltCount,~calcPL(ref=.x,alt=.y)))
tmp %>% head 
dim(tmp) # [1] 7771605      19

Final VCF format

tmp %<>% 
  mutate(FORMATfields=paste(GT,AD,DP,PL,sep=":")) %>% 
  select(Chr,Pos,SNP_ID,REF,ALT,QUAL,FILTER,INFO,FORMAT,FullSampleName,FORMATfields) %>% 
  spread(FullSampleName,FORMATfields) %>% 
  arrange(Chr,Pos) %>% 
  rename(`#CHROM`=Chr,
         POS=Pos,ID=SNP_ID)
dim(tmp) # [1] 12049   654
tmp[1:5,1:20] 

Write to disk

options("scipen"=1000, "digits"=4) 
# for a few SNPs, position kept printing in sci notation e.g. 1e3, screws up Beagle etc., this avoids that (I hope)
write_lines(header,
            path=paste0(outName,".vcf"))
write.table(tmp,
            paste0(outName,".vcf"),
            append = T,sep = "\t",row.names=F, col.names=T, quote=F)
# Save sitesWithAlleles
tmp %>% 
  rename(CHROM=`#CHROM`) %>% 
  select(CHROM:ALT) %>% 
  write.table(.,file=paste0(outName,".sitesWithAlleles"),
              row.names=F)
# Save sample list
write.table(sampleIDsFromDartVCF,file=paste0(outName,".samples"),
            row.names = F, col.names = F, quote = F)

# BGzip
system(paste0("cat ",outName,".vcf ",
              "| bgzip -c > ",outName,".vcf.gz"))
system(paste0("rm ",outName,".vcf"))

sessionInfo()