---
title: "Check prediction accuracy"
author: "wolfemd"
date: "2019-7-27"
output: workflowr::wflow_html
editor_options:
  chunk_output_type: inline
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = F, tidy = T)
```

# Previous step 

3. [Get BLUPs combining all trial data](03-GetBLUPs.html): Combine data from all trait-trials to get BLUPs for downstream genomic prediction.

# Objective

**Current Step:**  

4. [Check prediction accuracy](04-CrossValidation.html): Evaluate prediction accuracy with cross-validation.

5-fold cross-validation. Replicate 5-times. 

3 genomic models:  

1. Additive-only (**A**)
2. Additive plus dominance (**AD**)
3. Addtitive plus dominance plus epistasis (**ADE**)

# Prep. genomic data 


## Get SNP data from FTP

The data for the next step can be found on the cassavabase FTP server [here](ftp://ftp.cassavabase.org/marnin_datasets/NGC_BigData/).

Can be loaded directly to R from FTP. 

**NOTICE:** You need enough RAM and a stable network connection. I do the next steps, including cross-validation on a server with plenty of RAM and a good, stable network connection, rather than on my personal computer (a laptop with 16 GB RAM). 

The outputs (kinship matrices and filtered snp dosages) of the steps below, which are too large for GitHub, can be found on the cassavabase FTP server [here](ftp://ftp.cassavabase.org/marnin_datasets/NRCRI_2020GS/).

```{bash, eval=F}
# activate multithread OpenBLAS for fast compute of SigmaM (genotypic var-covar matrix)
export OMP_NUM_THREADS=56
```

```{r, eval=F}
library(tidyverse); library(magrittr); 
snps<-readRDS(file=url(paste0("ftp://ftp.cassavabase.org/marnin_datasets/NGC_BigData/",
                              "DosageMatrix_RefPanelAndGSprogeny_ReadyForGP_73019.rds")))
#rm(list=(ls() %>% grep("snps",.,value = T, invert = T)))
```


```{r, eval=F}
blups_nrcri<-readRDS(file=here::here("output","nrcri_blupsForModelTraining_2020April27.rds"))
blups_nrcri<-blups_nrcri %>% 
  select(Trait,modelOutput) %>% 
  unnest(modelOutput) %>% 
  select(Trait,BLUPs) %>% 
  unnest(BLUPs) %>%  
  filter(GID %in% rownames(snps))
table(unique(blups_nrcri$GID) %in% rownames(snps)) # 2879!

blups_iita<-readRDS(file=here::here("data","iita_blupsForCrossVal_outliersRemoved_73019.rds"))
blups_iita<-blups_iita %>% 
  select(Trait,blups) %>% 
  unnest(blups) %>% 
  select(-`std error`) %>% 
  filter(GID %in% rownames(snps),
         !grepl("TMS13F|TMS14F|TMS15F|2013_",GID)) # don't want IITA GS progenies
table(unique(blups_iita$GID) %in% rownames(snps)) # 1228
union(blups_nrcri$GID,blups_iita$GID) %>% grep("c2",.,value = T,ignore.case = T)
```

```{r, eval=F}
samples2Keep<-union(blups_nrcri$GID,blups_iita$GID) %>% 
  union(.,grep("c2",rownames(snps),value = T, ignore.case = T))
table(rownames(snps) %in% union(blups_nrcri$GID,blups_iita$GID)) # 3740
length(samples2Keep) # 7062
snps<-snps[samples2Keep,]
```

## MAF>1% filter
```{r maf_filter, eval=F}
maf_filter<-function(snps,thresh){
    freq<-colMeans(snps, na.rm=T)/2; maf<-freq;
    maf[which(maf > 0.5)]<-1-maf[which(maf > 0.5)]
    snps1<-snps[,which(maf>thresh)];
    return(snps1) }
```

```{r, eval=F}
snps %<>% maf_filter(.,0.01)
dim(snps) # [1]  7062 68587
```

## Make Add, Dom and Epi kinships

Going to use my own kinship function b/c I trust it's dominance matrix calculation.
```{r kinship function, eval=F}
#' kinship function
#'
#' Function to create additive and dominance genomic relationship matrices from biallelic dosages.
#'
#' @param M dosage matrix. Assumes SNPs in M coded 0, 1, 2 (requires rounding dosages to integers). M is Nind x Mrow, numeric matrix, with row/columanes to indicate SNP/ind ID.
#' @param type string, "add" or "dom". type="add" gives same as rrBLUP::A.mat(), i.e. Van Raden, Method 1. type="dom" gives classical parameterization according to Vitezica et al. 2013.
#'
#' @return square symmetic genomic relationship matrix
#' @export
#'
#' @examples
#' K<-kinship(M,"add")
kinship<-function(M,type){
      M<-round(M)
      freq <- colMeans(M,na.rm=T)/2
      P <- matrix(rep(freq,nrow(M)),byrow=T,ncol=ncol(M))
      if(type=="add"){
            Z <- M-2*P
            varD<-sum(2*freq*(1-freq))
            K <- tcrossprod(Z)/ varD
            return(K)
      }
      if(type=="dom"){
            W<-M;
            W[which(W==1)]<-2*P[which(W==1)];
            W[which(W==2)]<-(4*P[which(W==2)]-2);
            W <- W-2*(P^2)
            varD<-sum((2*freq*(1-freq))^2)
            D <- tcrossprod(W) / varD
            return(D)
      }
}
```

Make the kinships. 

Below e.g. `A*A` makes a matrix that approximates additive-by-additive epistasis relationships.
```{r, eval=F}
A<-kinship(snps,type="add")
D<-kinship(snps,type="dom")
AA<-A*A
AD<-A*D
DD<-D*D

saveRDS(snps,file=here::here("output","DosageMatrix_NRCRI_SamplesForGP_2020April27.rds"))
saveRDS(A,file=here::here("output","Kinship_A_NRCRI_2020April27.rds"))
saveRDS(D,file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
saveRDS(AA,file=here::here("output","Kinship_AA_NRCRI_2020April27.rds"))
saveRDS(AD,file=here::here("output","Kinship_AD_NRCRI_2020April27.rds"))
saveRDS(DD,file=here::here("output","Kinship_DD_NRCRI_2020April27.rds"))
#rm(snps); gc()
```

**NOTICE:** The outputs (kinship matrices and filtered snp dosages) of the steps below, which are too large for GitHub, can be found on the cassavabase FTP server [here](ftp://ftp.cassavabase.org/marnin_datasets/NRCRI_2020GS/).


# Cross-validation
```{bash, eval=F}
# activate multithread OpenBLAS 
export OMP_NUM_THREADS=48
#export OMP_NUM_THREADS=88
#export OMP_NUM_THREADS=88
```
## Set-up training-testing data

```{r, eval=F}
rm(list=ls())
library(tidyverse); library(magrittr); 
A<-readRDS(file=here::here("output","Kinship_A_NRCRI_2020April27.rds"))

blups_iita<-readRDS(file=here::here("data","iita_blupsForCrossVal_outliersRemoved_73019.rds"))
blups_iita<-blups_iita %>% 
  dplyr::select(Trait,blups) %>% 
  unnest(blups) %>% 
  dplyr::select(-`std error`) %>% 
  filter(GID %in% rownames(A),
         !grepl("TMS13F|TMS14F|TMS15F|2013_",GID)) # don't want IITA GS progenies
blups_nrcri<-readRDS(file=here::here("output","nrcri_blupsForModelTraining_2020April27.rds"))
blups_nrcri<-blups_nrcri %>% 
  dplyr::select(Trait,modelOutput) %>% 
  unnest(modelOutput) %>% 
  dplyr::select(Trait,BLUPs) %>% 
  unnest(BLUPs) %>%  
  filter(GID %in% rownames(A))
# Set-up a grouping variable for:
## nrTP, C1a, C1b and C2a.
## Nest by Trait.
c1a<-blups_nrcri$GID %>% 
  unique %>% 
  grep("c1a",.,value = T,ignore.case = T) %>% 
  union(.,blups_nrcri$GID %>% unique %>% 
          grep("^F",.,value = T,ignore.case = T) %>% 
          grep("c1b",.,value = T,ignore.case = T,invert = T))
c1b<-blups_nrcri$GID %>% unique %>% grep("c1b",.,value = T,ignore.case = T)
c2a<-blups_nrcri$GID %>% unique %>% 
  grep("C2a|C2b",.,value = T,ignore.case = T) %>% 
  grep("NR17",.,value = T,ignore.case = T)
nrTP<-setdiff(unique(blups_nrcri$GID),unique(c(c1a,c1b,c2a)))

cv2do<-blups_nrcri %>%
  mutate(Group=ifelse(GID %in% nrTP,"nrTP",
                      ifelse(GID %in% c1a,"C1a",
                             ifelse(GID %in% c1b, "C1b",
                                    ifelse(GID %in% c2a,"C2a",NA))))) %>%
  nest(TrainTestData=-Trait) %>% 
  left_join(blups_iita %>% 
               nest(augmentTP=-Trait))
cv2do$TrainTestData[[6]] %>%
  count(Group)
```
```{r, eval=F}
cv2do$TrainTestData[[6]] %>% head
```

```{r, eval=F}
# test arguments to function
# ----------------------
## Test 1 (additive only, no augmentTP)
# TrainTestData<-cv2do_nrAlone$TrainTestData[[1]]
# nrepeats<-1
# nfolds<-2
# ncores<-1
# gid<-"GID"
# byGroup<-TRUE
# modelType<-"A"
# grms<-list(A=A)
# augmentTP<-NULL
# 
# ## Test 2 (additive + dominance , no augmentTP)
# TrainTestData<-cv2do_nrAlone$TrainTestData[[10]]
# nrepeats<-1
# nfolds<-2
# ncores<-1
# gid<-"GID"
# byGroup<-TRUE
# modelType<-"AD"
# grms<-list(A=A,D=D)
# augmentTP<-NULL
# splits<-cvsamples$splits[[1]]
# GroupName<-cvsamples$GroupName[[1]]
# ----------------------
```


The function below implements nfold cross-validation. Specifically, for each of **nrepeats** it splits the data into **nfolds** sets according to **gid**. So if `nfolds=5` then the the clones will be divided into 5 groups and 5 predictions will be made. In each prediction, 4/5 of the clones will be used to predict the remaining 1/5. Accuracy of the model is measured as the correlation between the BLUPs (adj. mean for each CLONE) in the _test set_ and the GEBV (the prediction made of each clone when it was in the test set).

## The ultimate runCrossVal func
```{r runCrossVal, eval=F}
#' @param byGroup logical, if TRUE, assumes a column named "Group" is present which unique classifies each GID into some genetic grouping. 
#' @param modelType string, A, AD or ADE representing model with Additive-only, Add. plus Dominance, and Add. plus Dom. plus. Epistasis (AA+AD+DD), respectively.
#' @param grms list of GRMs where each element is named either A, D, AA, AD, DD. Matrices supplied must match required by A, AD and ADE models. For ADE grms=list(A=A,D=D,AA=AA,AD=AD,DD=DD)...
#' @param augmentTP option to supply an additional set of training data, which will be added to each training model but never included in the test set.
#' @param TrainTestData data.frame with de-regressed BLUPs, BLUPs and weights (WT) for training and test. If byGroup==TRUE, a column with Group as the header uniquely classifying GIDs into genetic groups, is expected.
runCrossVal<-function(TrainTestData,modelType,grms,nrepeats,nfolds,ncores=1,
                      byGroup=FALSE,augmentTP=NULL,gid="GID",...){
  require(sommer); require(rsample)
  # Set-up replicated cross-validation folds 
  # splitting by clone (if clone in training dataset, it can't be in testing)
  if(byGroup){ 
    cvsamples<-tibble(GroupName=unique(TrainTestData$Group))
  } else { cvsamples<-tibble(GroupName="None") }
  cvsamples<-cvsamples %>% 
    mutate(Splits=map(GroupName,function(GroupName){
      if(GroupName!="None"){ 
        thisgroup<-TrainTestData %>% 
          filter(Group==GroupName) } else { thisgroup<-TrainTestData }
      out<-tibble(repeats=1:nrepeats,
                  splits=rerun(nrepeats,group_vfold_cv(thisgroup, group = gid, v = nfolds))) %>% 
        unnest(splits)
      return(out)
    })) %>% 
    unnest(Splits)
  
  ## Internal function
  ## fits prediction model and calcs. accuracy for each train-test split
  
  fitModel<-possibly(function(splits,modelType,augmentTP,TrainTestData,GroupName,grms){
    starttime<-proc.time()[3]
    # Set-up training set
    trainingdata<-training(splits)
    ## Make sure, if there is an augmentTP, no GIDs in test-sets
    if(!is.null(augmentTP)){
      ## remove any test-set members from augment TP before adding to training data
      training_augment<-augmentTP %>% filter(!(!!sym(gid) %in% testing(splits)[[gid]]))
      trainingdata<-bind_rows(trainingdata,training_augment) }
    if(GroupName!="None"){ trainingdata<-bind_rows(trainingdata,
                                                   TrainTestData %>% 
                                                     filter(Group!=GroupName,
                                                            !(!!sym(gid) %in% testing(splits)[[gid]]))) }
    # Subset kinship matrices
    traintestgids<-union(trainingdata[[gid]],testing(splits)[[gid]])
    A1<-grms[["A"]][traintestgids,traintestgids]
    trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[[gid]],levels=rownames(A1))
    if(modelType %in% c("AD","ADE")){
      D1<-grms[["D"]][traintestgids,traintestgids]
      trainingdata[[paste0(gid,"d")]]<-factor(trainingdata[[gid]],levels=rownames(D1))
      if(modelType=="ADE"){
        AA1<-grms[["AA"]][traintestgids,traintestgids]
        AD1<-grms[["AD"]][traintestgids,traintestgids]
        DD1<-grms[["DD"]][traintestgids,traintestgids]
        trainingdata[[paste0(gid,"aa")]]<-factor(trainingdata[[gid]],levels=rownames(AA1))
        trainingdata[[paste0(gid,"ad")]]<-factor(trainingdata[[gid]],levels=rownames(AD1))
        trainingdata[[paste0(gid,"dd")]]<-factor(trainingdata[[gid]],levels=rownames(DD1))
      }
    }
    # Set-up random model statements
    randFormula<-paste0("~vs(",gid,"a,Gu=A1)")
    if(modelType %in% c("AD","ADE")){
      randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D1)")
      if(modelType=="ADE"){
        randFormula<-paste0(randFormula,
                            "+vs(",gid,"aa,Gu=AA1)",
                            "+vs(",gid,"ad,Gu=AD1)",
                            "+vs(",gid,"dd,Gu=DD1)")
      }
    }
    # Fit genomic prediction model  
    fit <- mmer(fixed = drgBLUP ~1,
                random = as.formula(randFormula),
                weights = WT,
                data=trainingdata) 
    # Gather the BLUPs
    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","ADE")){
      gblups %<>% mutate(GEDD=as.numeric(fit$U[[paste0("u:",gid,"d")]]$drgBLUP))
      if(modelType=="ADE"){
        gblups %<>% mutate(GEEDaa=as.numeric(fit$U[[paste0("u:",gid,"aa")]]$drgBLUP),
                           GEEDad=as.numeric(fit$U[[paste0("u:",gid,"ad")]]$drgBLUP),
                           GEEDdd=as.numeric(fit$U[[paste0("u:",gid,"dd")]]$drgBLUP)) 
      }
    }
    # Calc GETGVs 
    ## Note that for modelType=="A", GEBV==GETGV
    gblups %<>% 
      mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))])) 
    # Test set validation data
    validationData<-TrainTestData %>% 
      dplyr::select(gid,BLUP) %>% 
      filter(GID %in% testing(splits)[[gid]])
    # Measure accuracy in test set
    ## cor(GEBV,BLUP)
    ## cor(GETGV,BLUP)
    accuracy<-gblups %>% 
      mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))])) %>% 
      filter(GID %in% testing(splits)[[gid]]) %>% 
      left_join(validationData) %>% 
      summarize(accGEBV=cor(GEBV,BLUP, use = 'complete.obs'),
                accGETGV=cor(GETGV,BLUP, use = 'complete.obs'))
    computeTime<-proc.time()[3]-starttime
    accuracy %<>% mutate(computeTime=computeTime)
    return(accuracy)
  },otherwise = NA)
  ## Run models across all train-test splits
  ## Parallelize 
  require(furrr); plan(multiprocess); options(mc.cores=ncores);
  cvsamples<-cvsamples %>% 
    mutate(accuracy=future_map2(splits,GroupName,
                                ~fitModel(splits=.x,GroupName=.y,
                                          modelType=modelType,augmentTP=NULL,TrainTestData=TrainTestData,grms=grms),
                                .progress = FALSE)) %>% 
    unnest(accuracy)
  return(cvsamples) 
}
```
Run some tests of the function...
```{r, eval=F}
# options(future.globals.maxSize= 1500*1024^2)
# test_cv_ad_yield<-runCrossVal(TrainTestData=cv2do$TrainTestData[[8]],
#                               modelType="AD",
#                               grms=list(A=A,D=D),
#                               byGroup=TRUE,augmentTP=NULL,
#                               nrepeats=1,nfolds=2,ncores=2,gid="GID")
# 
# TrainTestData<-cv2do %>% filter(Trait=="logFYLD") %$% TrainTestData[[1]]
# augmentTP<-cv2do %>% filter(Trait=="logFYLD") %$% augmentTP[[1]]
# test_cv_a_augment<-runCrossVal(TrainTestData=TrainTestData,
#                                modelType="A",
#                                grms=list(A=A),
#                                byGroup=TRUE,augmentTP=augmentTP,
#                                nrepeats=1,nfolds=2,ncores=2,gid="GID")
# test_cv_a_noaug<-runCrossVal(TrainTestData=TrainTestData,
#                              modelType="A",
#                              grms=list(A=A),
#                              byGroup=TRUE,augmentTP=NULL,
#                              nrepeats=1,nfolds=2,ncores=2,gid="GID")
```

## CV - modelType="A":

### NRCRI alone

cbsulm13 (96 cores; 512GB RAM)

```{r cbsulm13, eval=F}
cv_A_nrOnly<-cv2do %>% 
  mutate(CVresults=map(TrainTestData,~runCrossVal(TrainTestData=.,
                                                  modelType="A",
                                                  grms=list(A=A),
                                                  byGroup=TRUE,augmentTP=NULL,
                                                  nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_A_nrOnly %<>% mutate(Dataset="NRalone",modelType="A") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_A_nrOnly,file=here::here("output","cvresults_A_nrOnly.rds"))
```

### IITA augmented

cbsulm18 (88 cores; 512GB) 

For this one, try with `ncores=1` instead of `ncores=10`.
```{r, eval=F}
cv_A_iitaAugmented<-cv2do %>% 
  mutate(isnullAugment=map_lgl(augmentTP,~is.null(.))) %>% 
  filter(!isnullAugment) %>% 
  select(-isnullAugment) %>% 
  mutate(CVresults=map2(TrainTestData,augmentTP,~runCrossVal(TrainTestData=.x,
                                                  modelType="A",
                                                  grms=list(A=A),
                                                  byGroup=TRUE,augmentTP=.y,
                                                  nrepeats=5,nfolds=5,ncores=1,gid="GID")))
cv_A_iitaAugmented %<>% mutate(Dataset="IITAaugmented",modelType="A") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_A_iitaAugmented,file=here::here("output","cvresults_A_iitaAugmented.rds"))
```

## CV - modelType="AD":

### NRCRI alone

cbsulm15 (96 cores; 512GB RAM)

```{r cbsulm15, eval=F}
options(future.globals.maxSize= 1500*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
cv_AD_nrOnly<-cv2do %>% 
  mutate(CVresults=map(TrainTestData,~runCrossVal(TrainTestData=.,
                                                  modelType="AD",
                                                  grms=list(A=A,D=D),
                                                  byGroup=TRUE,augmentTP=NULL,
                                                  nrepeats=5,nfolds=5,ncores=4,gid="GID")))
cv_AD_nrOnly %<>% mutate(Dataset="NRalone",modelType="AD") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_AD_nrOnly,file=here::here("output","cvresults_AD_nrOnly.rds"))
```

### IITA augmented

cbsulm13 (96 cores; 512GB RAM)

```{r, eval=F}
options(future.globals.maxSize= 1500*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
cv_AD_iitaAugmented<-cv2do %>% 
  mutate(isnullAugment=map_lgl(augmentTP,~is.null(.))) %>% 
  filter(!isnullAugment) %>% 
  dplyr::select(-isnullAugment) %>% 
  mutate(CVresults=map2(TrainTestData,augmentTP,~runCrossVal(TrainTestData=.x,
                                                             modelType="AD",
                                                             grms=list(A=A,D=D),
                                                             byGroup=TRUE,augmentTP=.y,
                                                             nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_AD_iitaAugmented %<>% mutate(Dataset="IITAaugmented",modelType="AD") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_AD_iitaAugmented,file=here::here("output","cvresults_AD_iitaAugmented.rds"))

```

## CV - modelType="ADE":

### NRCRI alone

cbsulm15 (96 cores; 512GB RAM)

Had to modify initial version of `runCrossVal` function. Original version uses a A+D+AA+AD+DD model, but 5 kernel models kept failing (and they are slow). For now, reduce to a 3 kernel model, which although it expected the list of kernels to be like `grms=list(A=A,D=D,AD=AD)`, a user could just supply a different set of 3 kernels (but named A, D and AD)... or easily modify the `runCrossVal` function.

```{r runCrossVal_dev, eval=F}
runCrossVal_dev<-function(TrainTestData,modelType,grms,nrepeats,nfolds,ncores=1,
                      byGroup=FALSE,augmentTP=NULL,gid="GID",...){
  require(sommer); require(rsample)
  # Set-up replicated cross-validation folds 
  # splitting by clone (if clone in training dataset, it can't be in testing)
  if(byGroup){ 
    cvsamples<-tibble(GroupName=unique(TrainTestData$Group))
  } else { cvsamples<-tibble(GroupName="None") }
  cvsamples<-cvsamples %>% 
    mutate(Splits=map(GroupName,function(GroupName){
      if(GroupName!="None"){ 
        thisgroup<-TrainTestData %>% 
          filter(Group==GroupName) } else { thisgroup<-TrainTestData }
      out<-tibble(repeats=1:nrepeats,
                  splits=rerun(nrepeats,group_vfold_cv(thisgroup, group = gid, v = nfolds))) %>% 
        unnest(splits)
      return(out)
    })) %>% 
    unnest(Splits)
  
  ## Internal function
  ## fits prediction model and calcs. accuracy for each train-test split
  
  fitModel<-possibly(function(splits,modelType,augmentTP,TrainTestData,GroupName,grms){
    starttime<-proc.time()[3]
    # Set-up training set
    trainingdata<-training(splits)
    ## Make sure, if there is an augmentTP, no GIDs in test-sets
    if(!is.null(augmentTP)){
      ## remove any test-set members from augment TP before adding to training data
      training_augment<-augmentTP %>% filter(!(!!sym(gid) %in% testing(splits)[[gid]]))
      trainingdata<-bind_rows(trainingdata,training_augment) }
    if(GroupName!="None"){ trainingdata<-bind_rows(trainingdata,
                                                   TrainTestData %>% 
                                                     filter(Group!=GroupName,
                                                            !(!!sym(gid) %in% testing(splits)[[gid]]))) }
    # Subset kinship matrices
    traintestgids<-union(trainingdata[[gid]],testing(splits)[[gid]])
    A1<-grms[["A"]][traintestgids,traintestgids]
    trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[[gid]],levels=rownames(A1))
    if(modelType %in% c("AD","ADE")){
      D1<-grms[["D"]][traintestgids,traintestgids]
      trainingdata[[paste0(gid,"d")]]<-factor(trainingdata[[gid]],levels=rownames(D1))
      if(modelType=="ADE"){
        #AA1<-grms[["AA"]][traintestgids,traintestgids]
        AD1<-grms[["AD"]][traintestgids,traintestgids]
        diag(AD1)<-diag(AD1)+1e-06
        #DD1<-grms[["DD"]][traintestgids,traintestgids]
        #trainingdata[[paste0(gid,"aa")]]<-factor(trainingdata[[gid]],levels=rownames(AA1))
        trainingdata[[paste0(gid,"ad")]]<-factor(trainingdata[[gid]],levels=rownames(AD1))
        #trainingdata[[paste0(gid,"dd")]]<-factor(trainingdata[[gid]],levels=rownames(DD1))
      }
    }
    # Set-up random model statements
    randFormula<-paste0("~vs(",gid,"a,Gu=A1)")
    if(modelType %in% c("AD","ADE")){
      randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D1)")
      if(modelType=="ADE"){
        randFormula<-paste0(randFormula,"+vs(",gid,"ad,Gu=AD1)")
                            #"+vs(",gid,"aa,Gu=AA1)",
                            #"+vs(",gid,"ad,Gu=AD1)")
                            #"+vs(",gid,"dd,Gu=DD1)")
      }
    }
    # Fit genomic prediction model  
    fit <- mmer(fixed = drgBLUP ~1,
                random = as.formula(randFormula),
                weights = WT,
                data=trainingdata) 
    # Gather the BLUPs
    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","ADE")){
      gblups %<>% mutate(GEDD=as.numeric(fit$U[[paste0("u:",gid,"d")]]$drgBLUP))
      if(modelType=="ADE"){
        gblups %<>% mutate(#GEEDaa=as.numeric(fit$U[[paste0("u:",gid,"aa")]]$drgBLUP),
                           GEEDad=as.numeric(fit$U[[paste0("u:",gid,"ad")]]$drgBLUP))
                           #GEEDdd=as.numeric(fit$U[[paste0("u:",gid,"dd")]]$drgBLUP)) 
      }
    }
    # Calc GETGVs 
    ## Note that for modelType=="A", GEBV==GETGV
    gblups %<>% 
      mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))])) 
    # Test set validation data
    validationData<-TrainTestData %>% 
      dplyr::select(gid,BLUP) %>% 
      filter(GID %in% testing(splits)[[gid]])
    # Measure accuracy in test set
    ## cor(GEBV,BLUP)
    ## cor(GETGV,BLUP)
    accuracy<-gblups %>% 
      mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))])) %>% 
      filter(GID %in% testing(splits)[[gid]]) %>% 
      left_join(validationData) %>% 
      summarize(accGEBV=cor(GEBV,BLUP, use = 'complete.obs'),
                accGETGV=cor(GETGV,BLUP, use = 'complete.obs'))
    computeTime<-proc.time()[3]-starttime
    accuracy %<>% mutate(computeTime=computeTime)
    return(accuracy)
  },otherwise = NA)
  ## Run models across all train-test splits
  ## Parallelize 
  require(furrr); plan(multiprocess); options(mc.cores=ncores);
  cvsamples<-cvsamples %>% 
    mutate(accuracy=future_map2(splits,GroupName,
                                ~fitModel(splits=.x,GroupName=.y,
                                          modelType=modelType,augmentTP=NULL,TrainTestData=TrainTestData,grms=grms),
                                .progress = FALSE)) %>% 
    unnest(accuracy)
  return(cvsamples) 
}
```

```{r, eval=F}
options(future.globals.maxSize= 3000*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
#AA<-readRDS(file=here::here("output","Kinship_AA_NRCRI_2020April27.rds"))
AD<-readRDS(file=here::here("output","Kinship_AD_NRCRI_2020April27.rds"))
#DD<-readRDS(file=here::here("output","Kinship_DD_NRCRI_2020April27.rds"))

cv_ADE_nrOnly<-cv2do %>% 
  mutate(CVresults=map(TrainTestData,~runCrossVal_dev(TrainTestData=.,
                                                  modelType="ADE",
                                                  grms=list(A=A,D=D,AD=AD),
                                                  #grms=list(A=A,D=D,AA=AA,AD=AD,DD=DD), # test with all kernels failed
                                                  byGroup=TRUE,augmentTP=NULL,
                                                  nrepeats=5,nfolds=5,ncores=10,gid="GID")))

cv_ADE_nrOnly %<>% mutate(Dataset="NRalone",modelType="ADE") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_ADE_nrOnly,file=here::here("output","cvresults_ADE_nrOnly.rds"))

```

### IITA augmented
```{r cbsulm18, eval=F}
options(future.globals.maxSize= 3000*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
AD<-readRDS(file=here::here("output","Kinship_AD_NRCRI_2020April27.rds"))

cv_ADE_iitaAugmented<-cv2do %>% 
  mutate(isnullAugment=map_lgl(augmentTP,~is.null(.))) %>% 
  filter(!isnullAugment) %>% 
  dplyr::select(-isnullAugment) %>% 
  mutate(CVresults=map2(TrainTestData,augmentTP,~runCrossVal_dev(TrainTestData=.x,
                                                             modelType="ADE",
                                                             grms=list(A=A,D=D,AD=AD),
                                                             byGroup=TRUE,augmentTP=.y,
                                                             nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_ADE_iitaAugmented %<>% mutate(Dataset="IITAaugmented",modelType="ADE") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_ADE_iitaAugmented,file=here::here("output","cvresults_ADE_iitaAugmented.rds"))


```
```{r, eval=F}
cv<-readRDS(here::here("output","cvresults_A_iitaAugmented.rds"))
cv$CVresults[[1]]
```

## PLOT RESULTS

```{r}
rm(list=ls());gc()
library(tidyverse); library(magrittr); 
cv<-readRDS(here::here("output","cvresults_A_iitaAugmented.rds")) %>% 
  bind_rows(readRDS(here::here("output","cvresults_A_nrOnly.rds"))) %>% 
  bind_rows(readRDS(here::here("output","cvresults_AD_nrOnly.rds"))) %>% 
  bind_rows(readRDS(here::here("output","cvresults_AD_iitaAugmented.rds"))) %>% 
  bind_rows(readRDS(here::here("output","cvresults_ADE_nrOnly.rds"))) %>% 
  bind_rows(readRDS(here::here("output","cvresults_ADE_iitaAugmented.rds"))) %>% 
  unnest(CVresults) %>% 
  select(-splits)
```
### Accuracy GEBV
```{r, fig.width=10, fig.height=8}
#library(viridis)
library(tidyverse); library(magrittr); 
cv %>% 
  mutate(GroupName=factor(GroupName,levels=c("nrTP","C1a","C1b","C2a")),
         Dataset=factor(Dataset,levels=c("NRalone","IITAaugmented")),
         modelType=factor(modelType,levels=c("A","AD","ADE"))) %>% 
  ggplot(.,aes(x=Dataset,y=accGEBV,fill=modelType,linetype=Dataset)) + 
  geom_boxplot(position = position_dodge(1),width=0.75,color='gray',size=0.75) + 
  facet_grid(GroupName~Trait, scales='free') + 
  theme_bw() + 
  theme(strip.text.x = element_text(face='bold', size=12),
        axis.text.x = element_text(size=10, angle = 90),
        axis.title.y = element_text(face='bold', size=12)) + 
  scale_fill_viridis_d() + 
  #scale_color_manual(values = c("gray","gold")) + 
  labs(title="Cross-validated Prediction Accuracy (GEBVs)") +
  geom_hline(yintercept = 0, color='darkred')
```
### Accuracy GETGV
```{r, fig.width=10, fig.height=8}
#library(viridis)
library(tidyverse); library(magrittr); 
cv %>% 
  mutate(GroupName=factor(GroupName,levels=c("nrTP","C1a","C1b","C2a")),
         Dataset=factor(Dataset,levels=c("NRalone","IITAaugmented")),
         modelType=factor(modelType,levels=c("A","AD","ADE"))) %>% 
  ggplot(.,aes(x=Dataset,y=accGETGV,fill=modelType,linetype=Dataset)) + 
  geom_boxplot(position = position_dodge(1),width=0.75,color='gray',size=0.75) + 
  facet_grid(GroupName~Trait, scales='free') + 
  theme_bw() + 
  theme(strip.text.x = element_text(face='bold', size=12),
        axis.text.x = element_text(size=10, angle = 90),
        axis.title.y = element_text(face='bold', size=12)) + 
  scale_fill_viridis_d() + 
  #scale_color_manual(values = c("gray","gold")) + 
  labs(title="Cross-validated Prediction Accuracy (GETGVs)") +
  geom_hline(yintercept = 0, color='darkred')
```

# Next step

5. [Genomic prediction of GS C2](05-GetGBLUPs.html): Predict _genomic_ BLUPs (GEBV and GETGV) for all selection candidates using all available data.


```{bash, eval=F, include=F}
rsync --update --archive --verbose /workdir/marnin/NRCRI_2020GS/ mw489@cbsulm13.biohpc.cornell.edu:/workdir/mw489/NRCRI_2020GS;
rsync --update --archive --verbose /workdir/marnin/NRCRI_2020GS/ mw489@cbsulm15.biohpc.cornell.edu:/workdir/mw489/NRCRI_2020GS;
rsync --update --archive --verbose /workdir/marnin/NRCRI_2020GS/ mw489@cbsulm18.biohpc.cornell.edu:/workdir/mw489/NRCRI_2020GS;

rsync --update --archive --verbose /workdir/mw489/NRCRI_2020GS/ mw489@cbsurobbins.biohpc.cornell.edu:/workdir/marnin/NRCRI_2020GS;
```
