Last updated: 2021-06-10

Checks: 7 0

Knit directory: implementGMSinCassava/

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(20210504) 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 a8452ba. 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/accuracies.png
    Ignored:    analysis/fig2.png
    Ignored:    analysis/fig3.png
    Ignored:    analysis/fig4.png
    Ignored:    code/.DS_Store
    Ignored:    data/.DS_Store

Untracked files:
    Untracked:  accuracies.png
    Untracked:  analysis/docs/
    Untracked:  analysis/speedUpPredCrossVar.Rmd
    Untracked:  code/AlphaAssign-Python/
    Untracked:  code/calcGameticLD.cpp
    Untracked:  code/col_sums.cpp
    Untracked:  code/convertDart2vcf.R
    Untracked:  code/gsFunctions.R
    Untracked:  code/helloworld.cpp
    Untracked:  code/imputationFunctions.R
    Untracked:  code/matmult.cpp
    Untracked:  code/misc.cpp
    Untracked:  code/test.cpp
    Untracked:  data/CassavaGeneticMap/
    Untracked:  data/DatabaseDownload_2021May04/
    Untracked:  data/GBSdataMasterList_31818.csv
    Untracked:  data/IITA_GBStoPhenoMaster_33018.csv
    Untracked:  data/NRCRI_GBStoPhenoMaster_40318.csv
    Untracked:  data/blups_forCrossVal.rds
    Untracked:  data/chr1_RefPanelAndGSprogeny_ReadyForGP_72719.fam
    Untracked:  data/dosages_IITA_filtered_2021May13.rds
    Untracked:  data/genmap_2021May13.rds
    Untracked:  data/haps_IITA_filtered_2021May13.rds
    Untracked:  data/recombFreqMat_1minus2c_2021May13.rds
    Untracked:  fig2.png
    Untracked:  fig3.png
    Untracked:  figure/
    Untracked:  output/IITA_CleanedTrialData_2021May10.rds
    Untracked:  output/IITA_ExptDesignsDetected_2021May10.rds
    Untracked:  output/IITA_blupsForModelTraining_twostage_asreml_2021May10.rds
    Untracked:  output/IITA_trials_NOT_identifiable.csv
    Untracked:  output/crossValPredsA.rds
    Untracked:  output/crossValPredsAD.rds
    Untracked:  output/cvMeanPredAccuracyA.rds
    Untracked:  output/cvMeanPredAccuracyAD.rds
    Untracked:  output/cvPredMeansA.rds
    Untracked:  output/cvPredMeansAD.rds
    Untracked:  output/cvVarPredAccuracyA.rds
    Untracked:  output/cvVarPredAccuracyAD.rds
    Untracked:  output/kinship_A_IITA_2021May13.rds
    Untracked:  output/kinship_D_IITA_2021May13.rds
    Untracked:  output/markEffsTest.rds
    Untracked:  output/markerEffects.rds
    Untracked:  output/markerEffectsA.rds
    Untracked:  output/markerEffectsAD.rds
    Untracked:  output/maxNOHAV_byStudy.csv
    Untracked:  output/obsCrossMeansAndVars.rds
    Untracked:  output/parentfolds.rds
    Untracked:  output/ped2check_genome.rds
    Untracked:  output/ped2genos.txt
    Untracked:  output/pednames2keep.txt
    Untracked:  output/pednames_Prune100_25_pt25.log
    Untracked:  output/pednames_Prune100_25_pt25.nosex
    Untracked:  output/pednames_Prune100_25_pt25.prune.in
    Untracked:  output/pednames_Prune100_25_pt25.prune.out
    Untracked:  output/potential_dams.txt
    Untracked:  output/potential_sires.txt
    Untracked:  output/predVarTest.rds
    Untracked:  output/samples2keep_IITA_2021May13.txt
    Untracked:  output/samples2keep_IITA_MAFpt01_prune50_25_pt98.log
    Untracked:  output/samples2keep_IITA_MAFpt01_prune50_25_pt98.nosex
    Untracked:  output/samples2keep_IITA_MAFpt01_prune50_25_pt98.prune.in
    Untracked:  output/samples2keep_IITA_MAFpt01_prune50_25_pt98.prune.out
    Untracked:  output/verified_ped.txt

Unstaged changes:
    Modified:   README.md

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/05-CrossValidation.Rmd) and HTML (docs/05-CrossValidation.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 a8452ba wolfemd 2021-06-10 Initial build of the entire page upon completion of all
Rmd 6a5ef32 wolfemd 2021-06-09 meanPredAccuracy() now also included with function moved to “parentWiseCrossVal.R”. NOTE on previous commit: cross-validation functions are NOT in “predCrossVar.R”.
Rmd 63067f7 wolfemd 2021-06-07 Function varPredAccuracy() debugged / tested and moved to predCrossVar.R
Rmd 66c0bde wolfemd 2021-06-07 Remove old and unused code. STILL IN PROGRESS at the computeVarPredAccuracy step.
Rmd 3c085ee wolfemd 2021-06-07 Cross-validation code IN PROGRESS. Currently working on computeVarPredAccuracy.

Previous step

  1. Preprocess data files: Prepare haplotype and dosage matrices, pedigree and BLUPs, genetic map and recombination frequency matrix, for use in predictions.

Automating cross-validation

In the manuscript, the cross-validation is documented many pages and scripts, documented here.

For ongoing GS, I have a function runCrossVal() that manages all inputs and outputs easy to work with pre-computed accuracies.

Goal here is to make a function: runParentWiseCrossVal(), or at least make progress towards developing one.

However, for computational reasons, I imagine it might still be best to separate the task into a few functions.

runParentWiseCrossVal()

cd /home/jj332_cas/marnin/implementGMSinCassava/; 
export OMP_NUM_THREADS=56 # activate multithread OpenBLAS 
##### [considered] 
######/programs/R-4.0.0/bin/R # switched to R V4, having trouble with sommer/Matrix in v3.5
## may have to reinstall packages
# runCrossVal<-function(TrainTestData,modelType,grms,nrepeats,nfolds,ncores=1,
#                           byGroup=FALSE,augmentTP=NULL,gid="GID",...)

Make parent-wise folds

require(tidyverse); require(magrittr); require(rsample)
ped<-read.table(here::here("output","verified_ped.txt"),
                header = T, stringsAsFactors = F) %>% 
  rename(GID=FullSampleName,
         damID=DamID,
         sireID=SireID) %>% 
  dplyr::select(GID,sireID,damID)
# only families with _at least_ 2 offspring
ped %<>%
  semi_join(ped %>% count(sireID,damID) %>% filter(n>1) %>% ungroup())
gid<-"GID"
seed<-42
nrepeats<-5
nfolds<-5
# Prunes out offspring, grandkids, greatgrandkids (up to X4) steps of 
# great ancestors.  It is not automatically recursive across any depth of 
# pedigree. That depth works for current test pedigree (IITA 2021). 
# Must name parent columns in ped "sireID" and "damID".
makeParentFolds<-function(ped,gid,nrepeats=5,nfolds=5,seed=NULL){
  set.seed(seed)
  parentfolds<-rsample::vfold_cv(tibble(Parents=union(ped$sireID,
                                                      ped$damID)),
                                 v = nfolds,repeats = nrepeats) %>% 
    mutate(folds=map(splits,function(splits){
      #splits<-parentfolds$splits[[1]]
      testparents<-testing(splits)$Parents
      trainparents<-training(splits)$Parents
      ped<-ped %>% 
        rename(gid=!!sym(gid))
      offspring<-ped %>% 
        filter(sireID %in% testparents | damID %in% testparents) %$% 
        unique(gid)
      grandkids<-ped %>% 
        filter(sireID %in% offspring | damID %in% offspring) %$% 
        unique(gid)
      greatX1grandkids<-ped %>% 
        filter(sireID %in% grandkids | damID %in% grandkids) %$% 
        unique(gid)
      greatX2grandkids<-ped %>% 
        filter(sireID %in% greatX1grandkids | 
                 damID %in% greatX1grandkids) %$% 
        unique(gid)
      greatX3grandkids<-ped %>% 
        filter(sireID %in% greatX2grandkids | 
                 damID %in% greatX2grandkids) %$% 
        unique(gid)
      greatX4grandkids<-ped %>% 
        filter(sireID %in% greatX3grandkids | 
                 damID %in% greatX3grandkids) %$% 
        unique(gid)
      
      testset<-unique(c(offspring,
                        grandkids,
                        greatX1grandkids,
                        greatX2grandkids,
                        greatX3grandkids,
                        greatX4grandkids)) %>% 
        .[!. %in% c(testparents,trainparents)]
      
      nontestdescendents<-ped %>% 
        filter(!gid %in% testset) %$% 
        unique(gid)
      trainset<-union(testparents,trainparents) %>% 
        union(.,nontestdescendents)
      
      out<-tibble(testparents=list(testparents),
                  trainset=list(trainset),
                  testset=list(testset))
      return(out) })) %>% 
    unnest(folds) %>% 
    rename(Repeat=id,Fold=id2) %>% 
    select(-splits)
  
  # Crosses To Predict
  parentfolds %<>%
    mutate(CrossesToPredict=map(testparents,
                                ~filter(ped %>%
                                          # only need a list of fams-to-predict
                                          # not the progeny info
                                          distinct(damID,sireID),
                                        sireID %in% . | damID %in% .)))
  return(parentfolds) 
}
parentfolds<-makeParentFolds(ped=ped,gid="GID",nrepeats=5,nfolds=5,seed=42)
saveRDS(parentfolds,file=here::here("output","parentfolds.rds"))
#parentfolds$CrossesToPredict[[1]]

parentfolds<-makeParentFolds(ped=ped,gid="GID",nrepeats=5,nfolds=5,seed=42)
parentfolds %>% head

Get univariate REML marker effects

My goal is to simplify and integrate into the pipeline used for NextGen Cassava. In the paper, used multi-trait Bayesian ridge-regression (MtBRR) to obtain marker effects, and also stored posterior matrices on disk to later compute posterior mean variances. This was computationally expensive and different from my standard univariate REML approach. I think MtBRR and PMV are probably the least biased way to go… but…

For the sake of testing a simple integration into the in-use pipeline, I want to try univariate REML to get the marker effects, which I’ll subsequently use for the cross-validation.

getMarkEffs<-function(parentfolds,blups,gid,modelType,grms,dosages,ncores){
  traintestdata<-parentfolds %>% 
    dplyr::select(Repeat,Fold,trainset,testset) %>% 
    pivot_longer(c(trainset,testset),
                 names_to = "Dataset",
                 values_to = "sampleIDs")
  
  # Internal function
  ## For each training or testing chunk of sampleIDs
  ## fit GBLUP model for each trait
  ## Backsolve SNP-effects from GBLUP
  
  fitModel<-function(blups,sampleIDs,modelType,grms){
    require(predCrossVar)
    A<-grms[["A"]]
    if(modelType %in% c("AD")){ D<-grms[["D"]] }
    # debug fitModel()
    # sampleIDs<-traintestdata$sampleIDs[[1]]
    out<-blups %>% 
      #slice(1:2) %>% # debug (just 2 traits)
      dplyr::mutate(trainingdata=map(blups,function(blups){
        trainingdata<-blups %>% 
          rename(gid=!!sym(gid)) %>% 
          filter(gid %in% sampleIDs)
        trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[["gid"]],
                                                levels=rownames(A))
        if(modelType %in% c("AD")){
          trainingdata[[paste0(gid,"d")]]<-trainingdata[[paste0(gid,"a")]]
          # factor(trainingdata[["gid"]],
          #                                         levels=rownames(D))
        }
        return(trainingdata) })) %>% 
      dplyr::select(-blups)
    
    # Set-up random model statements
    randFormula<-paste0("~vs(",gid,"a,Gu=A)")
    if(modelType %in% c("AD")){
      randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D)")
    }

    # Fit model across each trait
    out<-out %>% 
      mutate(modelOut=map(trainingdata,function(trainingdata){
        # Fit genomic prediction model
        require(sommer)
        fit <- mmer(fixed = drgBLUP ~1,
                    random = as.formula(randFormula),
                    weights = WT,
                    data=trainingdata)
        
        # Gather the GBLUPs
        gblups<-tibble(GID=as.character(names(fit$U[[paste0("u:",gid,"a")]]$drgBLUP)),
                       GEBV=as.numeric(fit$U[[paste0("u:",gid,"a")]]$drgBLUP))
        if(modelType %in% c("AD")){
          gblups %<>% 
            mutate(GEDD=as.numeric(fit$U[[paste0("u:",gid,"d")]]$drgBLUP))
        }
        # Calc GETGVs
        ## Note that for modelType=="A", GEBV==GETGV
         gblups %<>%
          mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))]))
        
        # Backsolve SNP effects
        ga<-as.matrix(fit$U[[paste0("u:",gid,"a")]]$drgBLUP,ncol=1)
        addsnpeff<-backsolveSNPeff(Z=centerDosage(dosages),g=ga)
        if(modelType %in% c("AD")){ 
          gd<-as.matrix(fit$U[[paste0("u:",gid,"d")]]$drgBLUP,ncol=1)
          domsnpeff<-backsolveSNPeff(Z=dose2domDev(dosages),g=gd)
        }
     
        # Extract variance components
        varcomps<-summary(fit)$varcomp
        
        results<-tibble(gblups=list(gblups),
                        varcomps=list(varcomps),
                        addsnpeff=list(addsnpeff))
        if(modelType %in% c("AD")){ 
          results %<>% 
            mutate(domsnpeff=list(domsnpeff)) }
        # return results
        return(results)
      }))
    return(out)
  }
  
  require(furrr); options(mc.cores=ncores); plan(multicore)
  options(future.globals.maxSize=10000*1024^2)
  
  traintestdata<-traintestdata %>% 
    #slice(1:2) %>% # debug just 2 chunks
    mutate(effects=future_map(sampleIDs,~fitModel(sampleIDs=.,
                                                  blups=blups,grms=grms,
                                                  modelType=modelType)),
           modelType=modelType)
  return(traintestdata) 
}
require(tidyverse); require(magrittr); require(rsample); library(sommer)
parentfolds<-readRDS(file=here::here("output","parentfolds.rds"))

blups<-readRDS(file=here::here("data","blups_forCrossVal.rds")) %>% 
  dplyr::select(-varcomp)

A<-readRDS(file=here::here("output","kinship_A_IITA_2021May13.rds"))
dosages<-readRDS(file=here::here("data",
                                 "dosages_IITA_filtered_2021May13.rds"))
# D<-readRDS(file=here::here("output","kinship_D_IITA_2021May13.rds"))
# gid="GID"
# grms<-list(A=A,D=D)
# modelType<-"AD"
# # debug fitModel()
# sampleIDs<-traintestdata$sampleIDs[[1]]
# # Fit model across each trait
# trainingdata<-out$trainingdata[[1]]
# # markEffsTest<-getMarkEffs(parentfolds,blups,gid,A,dosages,ncores=2)
# # saveRDS(markEffsTest,here::here("output","markEffsTest.rds"))
# cbsulm15
markEffsA<-getMarkEffs(parentfolds,blups,gid="GID",
                       modelType="A",grms=list(A=A),dosages,ncores=2)
saveRDS(markEffsA,here::here("output","markerEffectsA.rds"))

# cbsulm31
D<-readRDS(file=here::here("output","kinship_D_IITA_2021May13.rds"))
markEffsAD<-getMarkEffs(parentfolds,blups,gid="GID",
                        modelType="AD",grms=list(A=A,D=D),dosages,ncores=2)
saveRDS(markEffsAD,here::here("output","markerEffectsAD.rds"))

Predict cross variances and covariances

cd /home/jj332_cas/marnin/implementGMSinCassava/; 
export OMP_NUM_THREADS=5 # <-- for a 112 core machine. Use ncores=20 below
screen; 
R # initiate R session

Revised the functions in the predCrossVar package to increase their computational efficiency. Not yet included into the actual R package but instead sourced from code/predCrossVar.R. Additional speed increases were achieved by extra testing to optimize balance of OMP_NUM_THREADS setting (multi-core BLAS) and parallel processing of the crosses-being-predicted.

require(tidyverse); require(magrittr); 
parentfolds<-readRDS(file=here::here("output","parentfolds.rds"))
parents<-parentfolds %>% 
  select(Repeat,Fold,CrossesToPredict) %>% 
  unnest(CrossesToPredict) %>% 
  distinct(sireID,damID) %$%
  union(sireID,damID)

# Recomb frequency matrix
recombFreqMat<-readRDS(file=here::here("data",
                                       "recombFreqMat_1minus2c_2021May13.rds"))
# Haplotype Matrix
haploMat<-readRDS(file=here::here("data","haps_IITA_filtered_2021May13.rds"))
## keep only haplos for parents-to-be-predicted, saves memory
parenthaps<-sort(c(paste0(parents,"_HapA"),
                   paste0(parents,"_HapB")))
haploMat<-haploMat[parenthaps,colnames(recombFreqMat)]; 

# Source predictCrossVar  predCrossVar function
source(here::here("code","predCrossVar.R"))

source(here::here("code","parentWiseCrossVal.R"))
# cbsulm29
markEffsA<-readRDS(here::here("output","markerEffectsA.rds"))

starttime<-proc.time()[3]
crossValPredsA<-predictCrossVars(modelType="A",ncores=20,
                                 snpeffs=markEffsA,parentfolds=parentfolds,
                                 haploMat=haploMat,recombFreqMat=recombFreqMat)
crossValPredsA<-crossValPredsA %>% select(-AddEffectList,-CrossesToPredict)
saveRDS(crossValPredsA,here::here("output","crossValPredsA.rds"))
timeelapsed<-proc.time()[3] - starttime; 
print(paste0("Elapsed: ",timeelapsed/60/60," hrs"))
# [1] "Elapsed: 6.60880583333333 hrs"
# cbsulm29
markEffsAD<-readRDS(here::here("output","markerEffectsAD.rds"))

starttime<-proc.time()
crossValPredsAD<-predictCrossVars(modelType="AD",ncores=20,
                                  snpeffs=markEffsAD,parentfolds=parentfolds,
                                  haploMat=haploMat,recombFreqMat=recombFreqMat)
crossValPredsAD<-crossValPredsAD %>% select(-AddEffectList,-DomEffectList,-CrossesToPredict)
saveRDS(crossValPredsAD,here::here("output","crossValPredsAD.rds"))
timeelapsed<-proc.time()[3] - starttime; 
print(paste0("Elapsed: ",timeelapsed/60/60," hrs"))
# didn't record time... 12-14 hours max.

Predict cross means

require(tidyverse); require(magrittr); 
parentfolds<-readRDS(file=here::here("output","parentfolds.rds"))
parents<-parentfolds %>% 
  select(Repeat,Fold,CrossesToPredict) %>% 
  unnest(CrossesToPredict) %>% 
  distinct(sireID,damID) %$%
  union(sireID,damID)

# Haplotype Matrix
doseMat<-readRDS(file=here::here("data","dosages_IITA_filtered_2021May13.rds"))
## keep only haplos for parents-to-be-predicted, saves memory
doseMat<-doseMat[parents,]; 

# # Source predictCrossVar  predCrossVar function
source(here::here("code","predCrossVar.R"))

source(here::here("code","parentWiseCrossVal.R"))
markEffsA<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsAD<-readRDS(here::here("output","markerEffectsAD.rds"))

cvPredMeansA<-predictCrossMeans(modelType="A",snpeffs=markEffsA,ncores=11,
                                parentfolds=parentfolds,doseMat=doseMat)
saveRDS(cvPredMeansA,here::here("output","cvPredMeansA.rds"))

cvPredMeansAD<-predictCrossMeans(modelType="AD",snpeffs=markEffsAD,ncores=11,
                                parentfolds=parentfolds,doseMat=doseMat)
saveRDS(cvPredMeansAD,here::here("output","cvPredMeansAD.rds"))

Variance prediction accuracies

require(tidyverse); require(magrittr); 

cvPredVarsA<-readRDS(here::here("output","crossValPredsA.rds"))
cvPredVarsAD<-readRDS(here::here("output","crossValPredsAD.rds"))

markEffsA<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsAD<-readRDS(here::here("output","markerEffectsAD.rds"))

ped<-read.table(here::here("output","verified_ped.txt"),
                header = T, stringsAsFactors = F) %>% 
  rename(GID=FullSampleName,
         damID=DamID,
         sireID=SireID)

# index weights from IYR+IK
SIwts<-c(logFYLD=20,
         HI=10,
         DM=15,
         MCMDS=-10,
         logRTNO=12,
         logDYLD=20,
         logTOPYLD=15,
         PLTHT=10) # note that not ALL predicted traits are on index

# source(here::here("code","parentWiseCrossVal.R"))
# modelType = "A";
# crossValOut = cvPredVarsA;
# markEffs = markEffsA;
# ped = ped;
# selInd = TRUE;
# SIwts = SIwts
varPredAccuracy<-function(crossValOut,markEffs,ped,modelType,
                          selInd=FALSE,SIwts=NULL){
  
  # Extract and format the GBLUPs from the marker effects object
  gblups<-markEffs %>%
    filter(Dataset=="testset") %>%
    mutate(testset_gblups=map(effects,
                              function(effects){
                                gblups<-effects %>%
                                  mutate(gblups=map(modelOut,
                                                    ~select(.,gblups) %>%
                                                      unnest())) %>%
                                  select(-trainingdata,-modelOut)
                                return(gblups)})) %>%
    select(Repeat,Fold,modelType,testset_gblups)
  # Use the crossValPred object and the pedigree
  # Create a list of the actual members of each family that were predicted
  # in each repeat-fold
  # Join the GBLUPs for each family member for computing
  # cross sample means, variances, covariances
  out<-crossValOut %>%
    unnest(predVars) %>%
    select(Repeat,Fold,modelType,sireID,damID) %>%
    left_join(ped) %>%
    nest(CrossesToPredict=c(sireID,damID,GID)) %>%
    left_join(gblups)
  out %<>%
    # remove any gebv/getgv NOT in the crosses-to-be-predicted to save mem
    mutate(testset_gblups=map2(testset_gblups,CrossesToPredict,
                               ~semi_join(.x %>% unnest(gblups),.y)))
  # for modelType=="A" remove the GETGV as equiv. to GEBV
  if(modelType=="A"){
    out %<>%
      mutate(testset_gblups=map(testset_gblups,
                                ~pivot_longer(.,cols = c(GEBV,GETGV),
                                              names_to = "predOf",
                                              values_to = "GBLUP") %>%
                                  nest(gblups=-predOf) %>%
                                  filter(predOf=="GEBV")))
  }
  # for modelType=="AD" remove the GEDD, pivot to long form GEBV/GETGV
  if(modelType=="AD"){
    out %<>%
      mutate(testset_gblups=map(testset_gblups,
                                ~select(.,-GEDD) %>%
                                  pivot_longer(cols = c(GEBV,GETGV),
                                               names_to = "predOf",
                                               values_to = "GBLUP") %>%
                                  nest(gblups=-predOf)))
  }
  out %<>% unnest(testset_gblups)
  
  # make a matrix of GBLUPs for all traits
  # for each family-to-be-predicted
  # in each rep-fold-predOf combination
  out %<>%
    mutate(famgblups=map2(gblups,CrossesToPredict,
                          ~left_join(.x,.y) %>%
                            pivot_wider(names_from = "Trait",
                                        values_from = "GBLUP") %>%
                            nest(gblupmat=c(-sireID,-damID)) %>%
                            mutate(gblupmat=map(gblupmat,~column_to_rownames(.,var="GID"))))) %>%
    select(-CrossesToPredict,-gblups)
  
  out %<>%
    # outer loop over rep-fold-predtype
    mutate(obsVars=map(famgblups,function(famgblups){
      return(famgblups %>%
               # inner loop over families
               mutate(obsvars=map(gblupmat,
                                  function(gblupmat){
                                    covMat<-cov(gblupmat)
                                    # to match predCrossVar output
                                    ## keep upper tri + diag of covMat
                                    obsvars<-covMat
                                    obsvars[lower.tri(obsvars)]<-NA
                                    obsvars %<>%
                                      as.data.frame(.) %>%
                                      rownames_to_column(var = "Trait1") %>%
                                      pivot_longer(cols = c(-Trait1),
                                                   names_to = "Trait2",
                                                   values_to = "obsVar",
                                                   values_drop_na = T)
                                    if(selInd==TRUE){
                                      covmat<-covMat[names(SIwts),names(SIwts)]
                                      selIndVar<-SIwts%*%covmat%*%SIwts
                                      obsvars %<>%
                                        bind_rows(tibble(Trait1="SELIND",
                                                         Trait2="SELIND",
                                                         obsVar=selIndVar),.) }
                                    return(obsvars) }),
                      famSize=map_dbl(gblupmat,nrow)) %>%
               select(-gblupmat) %>%
               unnest(obsvars))})) %>%
    select(-famgblups)
  
  cvout<-crossValOut %>%
    unnest(predVars) %>%
    unnest(predVars) %>%
    select(Repeat,Fold,modelType,predOf,sireID,damID,Trait1,Trait2,predVar,Nsegsnps)
  
  if(modelType=="A"){ cvout %<>% mutate(predOf="VarBV") }
  
  if(modelType=="AD"){
    cvout<-cvout %>%
      filter(predOf=="VarA") %>%
      # Breeding value variance predictions from the predOf=="VarA"
      mutate(predOf="VarBV") %>% 
      bind_rows(cvout %>% 
                  nest(predVars=c(predOf,predVar,Nsegsnps)) %>% 
                  # for Total Gen Value variance predictions, need to compute:
                  ## predVarTot = predVarA + predVarD
                  mutate(predVar=map_dbl(predVars,~sum(.$predVar)),
                         Nsegsnps=map_dbl(predVars,~max(.$Nsegsnps))) %>% 
                  select(-predVars) %>% 
                  mutate(predOf="VarTGV"))
  }
  cvout %<>% 
    nest(fampredvars=c(-Repeat,-Fold,-modelType,-sireID,-damID,-Nsegsnps,-predOf))
  
  if(selInd==TRUE){
    # compute predicted selection index variances
    cvout %<>% 
      mutate(fampredvars=map(fampredvars,function(fampredvars){
        gmat<-fampredvars %>% 
          pivot_wider(names_from = "Trait1",
                      values_from = "predVar") %>% 
          column_to_rownames(var = "Trait2") %>%
          as.matrix
        gmat[upper.tri(gmat)]<-t(gmat)[upper.tri(gmat)]
        gmat %<>% .[names(SIwts),names(SIwts)]
        predSelIndVar<-SIwts%*%gmat%*%SIwts
        fampredvars<-tibble(Trait1="SELIND",
                            Trait2="SELIND",
                            predVar=predSelIndVar) %>% 
          bind_rows(fampredvars)
        return(fampredvars)}))
  }
  
  out %<>%
    mutate(predOf=ifelse(predOf=="GEBV","VarBV","VarTGV")) %>%
    left_join(cvout %>% 
                unnest(fampredvars) %>% 
                nest(predVars=c(-Repeat,-Fold,-modelType,-predOf)))
  out %<>%
    mutate(predVSobs=map2(predVars,obsVars,
                          ~left_join(.x,.y) %>%
                            nest(predVSobs=c(sireID,damID,predVar,obsVar,famSize,Nsegsnps)))) %>%
    select(-predVars,-obsVars) %>% 
    unnest(predVSobs) %>%
    mutate(AccuracyEst=map_dbl(predVSobs,function(predVSobs){
      out<-psych::cor.wt(predVSobs[,c("predVar","obsVar")],
                         w = predVSobs$famSize) %$% r[1,2] %>%
        round(.,3)
      return(out) }))
  return(out)
}
# rm(x,out,gmat,gblups,markEffs,predSelIndV,selInd,modelType)
# rm(cvout,crossValOut)
cvVarPredAccuracyA<-varPredAccuracy(modelType = "A",
                                    crossValOut = cvPredVarsA,
                                    markEffs = markEffsA,
                                    ped = ped,selInd = TRUE,SIwts = SIwts)

cvVarPredAccuracyAD<-varPredAccuracy(modelType = "AD",
                                     crossValOut = cvPredVarsAD,
                                     markEffs = markEffsAD,
                                     ped = ped,selInd = TRUE,SIwts = SIwts)
saveRDS(cvVarPredAccuracyA,here::here("output","cvVarPredAccuracyA.rds"))
saveRDS(cvVarPredAccuracyAD,here::here("output","cvVarPredAccuracyAD.rds"))

Mean prediction accuracies

require(tidyverse); require(magrittr); 

cvPredMeansA<-readRDS(here::here("output","cvPredMeansA.rds"))
cvPredMeansAD<-readRDS(here::here("output","cvPredMeansAD.rds"))

markEffsA<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsAD<-readRDS(here::here("output","markerEffectsAD.rds"))

ped<-read.table(here::here("output","verified_ped.txt"),
                header = T, stringsAsFactors = F) %>% 
  rename(GID=FullSampleName,
         damID=DamID,
         sireID=SireID)

# index weights from IYR+IK
SIwts<-c(logFYLD=20,
         HI=10,
         DM=15,
         MCMDS=-10,
         logRTNO=12,
         logDYLD=20,
         logTOPYLD=15,
         PLTHT=10) # note that not ALL predicted traits are on index

source(here::here("code","parentWiseCrossVal.R"))
# modelType = "AD"
# crossValOut = cvPredMeansAD
# markEffs = markEffsAD
# meanPredAccuracy<-function(crossValOut,markEffs,ped,modelType,
#                            selInd=FALSE,SIwts=NULL){
#   
#   # Extract and format the GBLUPs from the marker effects object
#   gblups<-markEffs %>%
#     filter(Dataset=="testset") %>%
#     mutate(testset_gblups=map(effects,
#                               function(effects){
#                                 gblups<-effects %>%
#                                   mutate(gblups=map(modelOut,
#                                                     ~select(.,gblups) %>%
#                                                       unnest())) %>%
#                                   select(-trainingdata,-modelOut)
#                                 return(gblups)})) %>%
#     select(Repeat,Fold,modelType,testset_gblups)
#   
#   # Use the crossValPred object and the pedigree
#   # Create a list of the actual members of each family that were predicted
#   # in each repeat-fold
#   # Join the GBLUPs for each family member for computing
#   # cross sample means
#   out<-crossValOut %>%
#     unnest(predMeans) %>% 
#     distinct(Repeat,Fold,modelType,sireID,damID) %>% 
#     left_join(ped) %>% 
#     nest(CrossesToPredict=c(sireID,damID,GID)) %>%
#     left_join(gblups)
#   
#   out %<>%
#     # remove any gebv/getgv NOT in the crosses-to-be-predicted to save mem
#     mutate(testset_gblups=map2(testset_gblups,CrossesToPredict,
#                                ~semi_join(.x %>% unnest(gblups),.y)))
#   # for modelType=="A" remove the GETGV as equiv. to GEBV
#   if(modelType=="A"){
#     out %<>%
#       mutate(testset_gblups=map(testset_gblups,
#                                 ~pivot_longer(.,cols = c(GEBV,GETGV),
#                                               names_to = "predOf",
#                                               values_to = "GBLUP") %>%
#                                   nest(gblups=-predOf) %>%
#                                   filter(predOf=="GEBV")))
#   }
#   # for modelType=="AD" remove the GEDD, pivot to long form GEBV/GETGV
#   if(modelType=="AD"){
#     out %<>%
#       mutate(testset_gblups=map(testset_gblups,
#                                 ~select(.,-GEDD) %>%
#                                   pivot_longer(cols = c(GEBV,GETGV),
#                                                names_to = "predOf",
#                                                values_to = "GBLUP") %>%
#                                   nest(gblups=-predOf)))
#   }
#   out %<>% unnest(testset_gblups)
#   # make a matrix of GBLUPs for all traits
#   # for each family-to-be-predicted
#   # in each rep-fold-predOf combination
#   out %<>%
#     mutate(famgblups=map2(gblups,CrossesToPredict,
#                           ~left_join(.x,.y) %>%
#                             pivot_wider(names_from = "Trait",
#                                         values_from = "GBLUP") %>%
#                             nest(gblupmat=c(-sireID,-damID)) %>% 
#                             mutate(gblupmat=map(gblupmat,~column_to_rownames(.,var="GID"))))) %>%
#     select(-CrossesToPredict,-gblups)
#   
#   out %<>%
#     # outer loop over rep-fold-predtype
#     mutate(obsMeans=map(famgblups,function(famgblups){
#       return(famgblups %>%
#                # inner loop over families
#                mutate(obsmeans=map(gblupmat,
#                                    function(gblupmat){
#                                      gblupmeans<-colMeans(gblupmat) %>% as.list
#                                      if(selInd==TRUE){
#                                        selIndMean<-list(SELIND=as.numeric(gblupmeans[names(SIwts)])%*%SIwts) 
#                                        gblupmeans<-c(selIndMean,gblupmeans)
#                                      }
#                                      obsmeans<-tibble(Trait=names(gblupmeans),
#                                                       obsMean=as.numeric(gblupmeans))
#                                      return(obsmeans) }),
#                       famSize=map_dbl(gblupmat,nrow)) %>%
#                select(-gblupmat) %>%
#                unnest(obsmeans))})) %>%
#     select(-famgblups)
#   
#   cvout<-crossValOut %>%
#     unnest(predMeans) %>% 
#     select(Repeat,Fold,modelType,predOf,sireID,damID,Trait,predMean) %>% 
#     nest(predMeans=c(sireID,damID,Trait,predMean))
#   
#   if(selInd==TRUE){
#     # compute predicted selection index variances
#     cvout %<>%
#       ## loop over each rep-fold-predType
#       mutate(predMeans=map(predMeans,function(predMeans){
#         predmeans<-predMeans %>%
#           pivot_wider(names_from = "Trait",
#                       values_from = "predMean")
#         predmeans %<>% 
#           select(sireID,damID) %>% 
#           mutate(Trait="SELIND",
#                  predMean=(predmeans %>% 
#                              select(any_of(names(SIwts))) %>% 
#                              as.matrix(.)%*%SIwts)) %>% 
#           ## add sel index predictions to component trait
#           ## mean predictions
#           bind_rows(predMeans) 
#         return(predmeans) }))
#   }
#   
#   out %<>%
#     mutate(predOf=ifelse(predOf=="GEBV","MeanBV","MeanTGV")) %>%
#     left_join(cvout)
#   
#   out %<>%
#     mutate(predVSobs=map2(predMeans,obsMeans,
#                           ~left_join(.x,.y) %>%
#                             nest(predVSobs=c(sireID,damID,predMean,obsMean,famSize)))) %>%
#     select(-predMeans,-obsMeans) %>% 
#     unnest(predVSobs) %>% 
#     mutate(AccuracyEst=map_dbl(predVSobs,function(predVSobs){
#       out<-psych::cor.wt(predVSobs[,c("predMean","obsMean")],
#                          w = predVSobs$famSize) %$% r[1,2] %>%
#         round(.,3)
#       return(out) }))
#   return(out)
# }
cvMeanPredAccuracyA<-meanPredAccuracy(modelType = "A",
                                    crossValOut = cvPredMeansA,
                                    markEffs = markEffsA,
                                    ped = ped,selInd = TRUE,SIwts = SIwts)

cvMeanPredAccuracyAD<-meanPredAccuracy(modelType = "AD",
                                     crossValOut = cvPredMeansAD,
                                     markEffs = markEffsAD,
                                     ped = ped,selInd = TRUE,SIwts = SIwts)
saveRDS(cvMeanPredAccuracyA,here::here("output","cvMeanPredAccuracyA.rds"))
saveRDS(cvMeanPredAccuracyAD,here::here("output","cvMeanPredAccuracyAD.rds"))

Next step / Results

See Results: Home for plots and summary tables.


sessionInfo()