Last updated: 2020-08-26

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 bcd83b4. 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:    .Rproj.user/
    Ignored:    analysis/.DS_Store
    Ignored:    data/.DS_Store

Untracked files:
    Untracked:  data/Report-DCas20-5360/

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/convertDCas20_5360_ToVCF.Rmd) and HTML (docs/convertDCas20_5360_ToVCF.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
Rmd bcd83b4 wolfemd 2020-08-26 Initial publish (prior to running imputation). Debugging will be
Rmd 9d4dfab wolfemd 2020-08-26 Code organized into functions. Ready to run imputation of C2?

Input Parameters

#' @dartvcfInput input name and path of "vcf" file from DArT
#' @dartcountsInput input name and path of counts file from DArT
#' @outName output path and name
#' @nskipvcf number of "VCF" rows to skip on read-in
#' @nskipcounts number of "counts file" rows to skip on read in
#' @ncores number of cores to use, could be VERY memory intensive
#' @dartVars chr vector, column names that _are not_ sample IDs in the read-counts file. I use this internally to assign the sampleIDs in the VCF file

library(tidyverse); library(magrittr)
dartvcfInput<-here::here("data/Report-DCas20-5360","Report_DCas20-5360_SNP_VCF_Version_6.csv")
dartcountsInput<-here::here("data/Report-DCas20-5360","Report_DCas20-5360_SNP_Counts_Version_6_final.csv")
outName<-here::here("data/Report-DCas20-5360","DCas20_5360")

# From report to report, there has been minor (NOT SO MINOR?) variation
# in format among files, requiring user input
# rather frustrating
# can't pipeline their stuff
nskipvcf<-2 
nskipcounts<-3
ncores<-75
dartVars<-read.csv(dartcountsInput, 
                   stringsAsFactors = F,
                   header = T,
                   skip=nskipcounts,
                   nrows = 1) %>% colnames(.) %>% .[1:26] 

Prelim. check format

Start manual. Check that the files read in according to previous code. Adjust code if necessary. Make a function and apply it to the input files.

vcf<-read.table(dartvcfInput,
                stringsAsFactors = F,skip = nskipvcf, header = T, sep = "\t", comment.char = "")
readCounts<-read.csv(dartcountsInput, stringsAsFactors = F,header = T,skip=nskipcounts)

# dim(vcf) 
# [1] 13603  3749
# dim(readCounts) 
# [1] 27206  4105

# colnames(readCounts)[1:100]
 # [1] "AlleleID"                    "CloneID"                    
 #  [3] "AlleleSequence"              "TrimmedSequence"            
 #  [5] "TrimmedSequence_plus_Strand" "Chrom_Cassava_v61"          
 #  [7] "ChromPos_Cassava_v61"        "SNP_ChromPos_Cassava_v61"   
 #  [9] "AlnCnt_Cassava_v61"          "AlnEvalue_Cassava_v61"      
 # [11] "Strand_Cassava_v61"          "SeqDiff_Cassava_v61"        
 # [13] "SNP"                         "SnpPosition.on.Tag"         
 # [15] "CallRate"                    "OneRatioRef"                
 # [17] "OneRatioSnp"                 "FreqHomRef"                 
 # [19] "FreqHomSnp"                  "FreqHets"                   
 # [21] "PICRef"                      "PICSnp"                     
 # [23] "AvgPIC"                      "AvgCountRef"                
 # [25] "AvgCountSnp"                 "RepAvg"                     
 # [27] "X9624.09"                    "BGM.0004" 
 # [29] "BGM.0005"                    "BGM.0006"                   
 # [31] "BGM.0014"                    "BGM.0018"                   
 # [33] "BGM.0019"                    "BGM.0020"                   
 # [35] "BGM.0021"                    "BGM.0022"                   
 # [37] "BGM.0023"                    "BGM.0024" 
# colnames(vcf)[1:30]
#  [1] "X.CHROM"            "POS"                "ID"                
#  [4] "REF"                "ALT"                "QUAL"              
#  [7] "FILTER"             "INFO"               "FORMAT"            
# [10] "X911118200001_A_1"  "X911118200001_A_10" "X911118200001_A_11"
# [13] "X911118200001_A_12" "X911118200001_A_2"  "X911118200001_A_3" 
# [16] "X911118200001_A_4"  "X911118200001_A_5"  "X911118200001_A_6" 
# [19] "X911118200001_A_7"  "X911118200001_A_8"  "X911118200001_A_9" 
# [22] "X911118200001_B_1"  "X911118200001_B_10" "X911118200001_B_11"
# [25] "X911118200001_B_12" "X911118200001_B_2"  "X911118200001_B_3" 
# [28] "X911118200001_B_4"  "X911118200001_B_5"  "X911118200001_B_6" 


colnames(vcf)[10:length(colnames(vcf))]<-colnames(readCounts)[length(dartVars):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))

Conversion function

Printed here, but available and sourced from code/ subdirectory.

convertDart2vcf<-function(dartvcfInput,dartcountsInput,outName,
                          nskipvcf=2,nskipcounts=3,ncores){
  require(tidyverse); require(magrittr)
  # Read and format the counts/vcf files  -------------------

  ## Read in "VCF" (called genotypes from DArT)
  ## and "counts" files (read counts)
  vcf<-read.table(dartvcfInput,
                  stringsAsFactors = F,skip = nskipvcf, header = T, sep = "\t", comment.char = "")
  readCounts<-read.csv(dartcountsInput, stringsAsFactors = F,header = T,skip=nskipcounts)

  ## Liftover the sampleIDs from readCounts onto the VCF

  colnames(vcf)[10:length(colnames(vcf))]<-colnames(readCounts)[length(dartVars):length(colnames(readCounts))]

  ## Formatting chrom and position info
  vcf %<>%
    mutate(X.CHROM=gsub("Chromosome","",X.CHROM)) %>%
    rename(Pos=POS) %>%
    mutate(Chr=as.numeric(gsub("Chromosome","",X.CHROM)),
           Pos=as.numeric(Pos))

  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.
  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)

  # 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))

  # 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))
  vcf %<>% semi_join(sites2keep)
  readCounts %<>% semi_join(sites2keep)

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

  tmp_counts <-readCounts %>%
    .[,c("Chr","Pos","SNPindex","SNP_ID",
         "CloneID","AlleleID","RefAlt","Alleles","QUAL","FILTER","INFO","FORMAT",sampleIDsFromDartVCF)] %>%
    semi_join(sites2keep)

  # readCounts and vcf long by sample ------------------------------
  tmp_counts %<>%
    pivot_longer(cols = all_of(sampleIDsFromDartVCF),
                 names_to = "FullSampleName",
                 values_to = "ReadCount")
  #gather(FullSampleName,ReadCount,sampleIDsFromDartVCF)
  tmp_counts %<>%
    select(-AlleleID) %>%
    spread(RefAlt,ReadCount)
  tmp_counts %<>%
    rename(AltCount=ALT,
           RefCount=REF)
  vcf_long<-vcf %>%
    .[,c("Chr","Pos","SNPindex","SNP_ID",
         "CloneID","Alleles","REF","ALT","QUAL","FILTER","INFO","FORMAT",sampleIDsFromDartVCF)] %>%
    pivot_longer(cols = all_of(sampleIDsFromDartVCF), names_to = "FullSampleName", values_to = "GT")
  #    gather(FullSampleName,GT,sampleIDsFromDartVCF)

  # Add GT from vcf to the counts -----------------------------------
  tmp_counts %<>%
    inner_join(vcf_long)

  # 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)

  # 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)))

  # 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)

  # Header ----------------------------------------
  header<-c("##fileformat=VCFv4.0",
            "##FORMAT=<ID=GT,Number=1,Type=String,Description=\"Genotype\">",
            "##FORMAT=<ID=AD,Number=.,Type=Integer,Description=\"Allelic depths for the reference and alternate alleles in the order listed\">",
            "##FORMAT=<ID=DP,Number=1,Type=Integer,Description=\"Read Depth (only filtered reads used for calling)\">",
            "##FORMAT=<ID=PL,Number=3,Type=Float,Description=\"Normalized, Phred-scaled likelihoods for AA,AB,BB genotypes where A=ref and B=alt; not applicable if site is not biallelic\">")

  # 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"))
}

Run conversion function

source(here::here("code/","convertDart2vcf.R"))
convertDart2vcf(dartvcfInput,dartcountsInput,outName,
                nskipvcf=2,nskipcounts=3,ncores)

Genomewide to per-chrom VCFs

Split the genome-wide VCF into per-chromosome VCFs for imputation.

require(furrr); options(mc.cores=18); plan(multiprocess)
source(here::here("code","imputationFunctions.R"))

vcfIn<-here::here("data/Report-DCas20-5360","DCas20_5360.vcf.gz")
filters<-"--minDP 4 --maxDP 50" # because using GT not PL for impute (Beagle5)
outPath<-here::here("data/Report-DCas20-5360/")
outSuffix<-"DCas20_5360"

future_map(list(Chr=1:18),
           ~splitVCFbyChr(Chr=.),
           vcfIn=vcfIn,filters=filters,
           outPath=outPath,outSuffix=outSuffix)

sessionInfo()
R version 4.0.2 (2020-06-22)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Mojave 10.14.6

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRblas.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] workflowr_1.6.2

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.5      whisker_0.4     knitr_1.29      magrittr_1.5   
 [5] here_0.1        R6_2.4.1        rlang_0.4.7     stringr_1.4.0  
 [9] tools_4.0.2     xfun_0.16       git2r_0.27.1    htmltools_0.5.0
[13] ellipsis_0.3.1  yaml_2.2.1      digest_0.6.25   rprojroot_1.3-2
[17] tibble_3.0.3    lifecycle_0.2.0 crayon_1.3.4    later_1.1.0.1  
[21] vctrs_0.3.2     promises_1.1.1  fs_1.5.0        glue_1.4.1     
[25] evaluate_0.14   rmarkdown_2.3   stringi_1.4.6   compiler_4.0.2 
[29] pillar_1.4.6    backports_1.1.8 httpuv_1.5.4    pkgconfig_2.0.3