Last updated: 2020-12-04

Checks: 7 0

Knit directory: IITA_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(20200915) 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 79b6430. 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
    Ignored:    output/.DS_Store

Untracked files:
    Untracked:  data/GEBV_IITA_OutliersRemovedTRUE_73119.csv
    Untracked:  data/PedigreeGeneticGainCycleTime_aafolabi_01122020.csv
    Untracked:  data/iita_blupsForCrossVal_outliersRemoved_73019.rds
    Untracked:  output/DosageMatrix_IITA_2020Sep16.rds
    Untracked:  output/IITA_CleanedTrialData_2020Dec03.rds
    Untracked:  output/IITA_ExptDesignsDetected_2020Dec03.rds
    Untracked:  output/Kinship_AA_IITA_2020Sep16.rds
    Untracked:  output/Kinship_AD_IITA_2020Sep16.rds
    Untracked:  output/Kinship_A_IITA_2020Sep16.rds
    Untracked:  output/Kinship_DD_IITA2020Sep16.rds
    Untracked:  output/Kinship_D_IITA_2020Sep16.rds
    Untracked:  output/cvresults_ModelADE_chunk1.rds
    Untracked:  output/cvresults_ModelADE_chunk2.rds
    Untracked:  output/cvresults_ModelADE_chunk3.rds
    Untracked:  output/genomicPredictions_ModelADE_threestage_IITA_2020Sep21.rds
    Untracked:  output/genomicPredictions_ModelADE_twostage_IITA_2020Dec03.rds
    Untracked:  output/genomicPredictions_ModelA_threestage_IITA_2020Sep21.rds
    Untracked:  output/iita_blupsForModelTraining_twostage_asreml_2020Dec03.rds
    Untracked:  output/model_meangetgvs_vs_year.csv
    Untracked:  output/model_rawgetgvs_vs_year.csv
    Untracked:  output/training_data_summary.csv
    Untracked:  workflowr_log.R

Unstaged changes:
    Modified:   output/IITA_ExptDesignsDetected.rds
    Modified:   output/iita_blupsForModelTraining.rds
    Modified:   output/meanGETGVbyYear_IITA_2020Dec03.csv

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/04-CrossValidation.Rmd) and HTML (docs/04-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
html 7bae38d wolfemd 2020-12-03 Build site.
html b9bb6f8 wolfemd 2020-12-03 Build site.
html d72a9ed wolfemd 2020-09-21 Build site.
html 9194239 wolfemd 2020-09-21 Build site.
Rmd 97778e7 wolfemd 2020-09-21 Big update. Two types of pipeline to get BLUPs, GEBVs and GETGVs:
Rmd d2bfe1c wolfemd 2020-09-17 tiny tweak
html d2bfe1c wolfemd 2020-09-17 tiny tweak
html d6d72f8 wolfemd 2020-09-17 Build site.
html 7e156dd wolfemd 2020-09-17 Build site.
Rmd 7ea8b80 wolfemd 2020-09-17 All steps including genomic predicting (excluding cross-validation),

Previous step

  1. Get BLUPs combining all trial data: Combine data from all trait-trials to get BLUPs for downstream genomic prediction.

Objective

Current Step:

  1. Check prediction accuracy: 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.

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.

# activate multithread OpenBLAS for fast compute of SigmaM (genotypic var-covar matrix)
export OMP_NUM_THREADS=56
library(tidyverse)
library(magrittr)
source(here::here("code", "gsFunctions.R"))
snps <- readRDS(file = url(paste0("ftp://ftp.cassavabase.org/marnin_datasets/NGC_BigData/", 
    "DosageMatrix_RefPanelAndGSprogeny_ReadyForGP_73019.rds")))
blups <- readRDS(file = here::here("output", "iita_blupsForModelTraining.rds"))

blups %<>% select(Trait, modelOutput) %>% unnest(modelOutput) %>% select(Trait, BLUPs) %>% 
    unnest(BLUPs)

table(unique(blups$GID) %in% rownames(snps))
# FALSE TRUE 36837 7638

# keep only samples that are either geno+pheno or genotyped with TMS18 in the
# name.
iitaSamples2keep <- union(unique(blups$GID) %>% .[. %in% rownames(snps)], rownames(snps) %>% 
    grep("TMS18", ., value = T))
length(iitaSamples2keep)  # [1] 9061

# subset BLUPs and snps
blups %<>% filter(GID %in% iitaSamples2keep) %>% nest(TrainingData = -Trait)
snps <- snps[iitaSamples2keep, ]

## MAF>1% filter
snps %<>% maf_filter(., 0.01)
dim(snps)  # [1]  9061 68029

Make Add, Dom and Epi kinships

Going to use my own kinship function.

Make the kinships.

Below e.g. A*A makes a matrix that approximates additive-by-additive epistasis relationships.

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_IITA_2020Sep16.rds"))
saveRDS(A, file = here::here("output", "Kinship_A_IITA_2020Sep16.rds"))
saveRDS(D, file = here::here("output", "Kinship_D_IITA_2020Sep16.rds"))
saveRDS(AA, file = here::here("output", "Kinship_AA_IITA_2020Sep16.rds"))
saveRDS(AD, file = here::here("output", "Kinship_AD_IITA_2020Sep16.rds"))
saveRDS(DD, file = here::here("output", "Kinship_DD_IITA2020Sep16.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.

Cross-validation

# activate multithread OpenBLAS for fast matrix algebra
export OMP_NUM_THREADS=56

Set-up CV folds

library(tidyverse)
library(magrittr)
# BLUPs from the 3 stage procedure (representing stage 2 of 3) using the 2020
# standard procedure
blups_3stage_lmer <- readRDS(here::here("output", "iita_blupsForModelTraining.rds"))

# BLUPs from the 2 stage procedure (stage 1 of 2) using the 2019 procedure
blups_2stage_asreml <- readRDS(file = here::here("output", "iita_blupsForModelTraining_twostage_asreml.rds"))

# merge two sets of BLUPs
blups <- blups_2stage_asreml %>% dplyr::select(Trait, blups) %>% rename(blups2stage = blups) %>% 
    left_join(blups_3stage_lmer %>% dplyr::select(Trait, modelOutput) %>% unnest(modelOutput) %>% 
        dplyr::select(Trait, BLUPs) %>% rename(blups3stage = BLUPs))
rm(blups_2stage_asreml, blups_3stage_lmer)

# read additive kinship matrix
A <- readRDS(file = here::here("output", "Kinship_A_IITA_2020Sep16.rds"))

Next, set-up a common set of train-test cross-validation folds to compare the two sets of BLUPs with.

require(sommer); require(rsample)
nrepeats<-5; nfolds<-5
blups %<>% 
  # operate on GID common to both sets of BLUPs
  mutate(cvfolds=map2(blups2stage,blups3stage,
                      # GIDs in both sets of BLUPs
                      ~tibble(GID=unique(intersect(.x$GID,.y$GID)) %>% 
                                # and genotyped (in kinship)
                                .[. %in% rownames(A)])))
# for each trait, set-up nrepeats of nfold CVs
blups %<>% 
  mutate(cvfolds=map(cvfolds,~tibble(repeats=1:nrepeats,
                                     splits=rerun(nrepeats,vfold_cv(., v = nfolds))) %>% 
                       unnest(splits))) %>% 
  unnest(cvfolds)
blups %<>% 
  mutate(blups2stage=map(blups2stage,as.tibble)) %>% 
  pivot_longer(cols = c(blups2stage,blups3stage), 
               names_to = "VersionOfBLUPs", 
               values_to = "TrainTestData")

# decided to only do CV for 3 traits ("quick" test)
blups %<>%
  filter(Trait %in% c("MCMDS","DM","logFYLD")) 
gc()

blups %>% head

Function to do CV

# function to predict train and test sets, calc accuracy
fitModel <- possibly(function(splits, modelType, TrainTestData, grms, gid = "GID") {
    # test arguments for function ---------------------- splits<-blups$splits[[1]]
    # TrainTestData<-blups$TrainTestData[[1]] modelType<-'A' grms=list(A=A) gid='GID'
    # ----------------------
    
    starttime <- proc.time()[3]
    # Set-up training set
    trainingdata <- TrainTestData %>% filter(GID %in% training(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") {
            AD1 <- grms[["AD"]][traintestgids, traintestgids]
            diag(AD1) <- diag(AD1) + 1e-06
            trainingdata[[paste0(gid, "ad")]] <- factor(trainingdata[[gid]], levels = rownames(AD1))
        }
    }
    # 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)")
        }
    }
    # 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(GEEDad = as.numeric(fit$U[[paste0("u:", gid, "ad")]]$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 CV - Model A

## Run models across all train-test splits Parallelize
ncores <- 5
require(furrr)
plan(multiprocess)
options(mc.cores = ncores)
options(future.globals.maxSize = 1500 * 1024^2)

## three chunks, three servers for speed

### cbsulm15
cv_1 <- blups %>% slice(1:50) %>% mutate(accuracy = future_map2(splits, TrainTestData, 
    ~fitModel(splits = .x, TrainTestData = .y, modelType = "A", grms = list(A = A)), 
    .progress = FALSE)) %>% unnest(accuracy)
saveRDS(cv_1 %>% dplyr::select(-TrainTestData), here::here("output", "cvresults_ModelA_chunk1.rds"))

### cbsulm16
cv_2 <- blups %>% slice(51:100) %>% mutate(accuracy = future_map2(splits, TrainTestData, 
    ~fitModel(splits = .x, TrainTestData = .y, modelType = "A", grms = list(A = A)), 
    .progress = FALSE)) %>% unnest(accuracy)
saveRDS(cv_2 %>% dplyr::select(-TrainTestData), here::here("output", "cvresults_ModelA_chunk2.rds"))

### cbsulm17
cv_3 <- blups %>% slice(101:150) %>% mutate(accuracy = future_map2(splits, TrainTestData, 
    ~fitModel(splits = .x, TrainTestData = .y, modelType = "A", grms = list(A = A)), 
    .progress = FALSE)) %>% unnest(accuracy)
saveRDS(cv_3 %>% dplyr::select(-TrainTestData), here::here("output", "cvresults_ModelA_chunk3.rds"))

# ~3 hrs

Run CV - Model ADE

Same R session as Model A… exact train-test folds not otherwise stored.

# read dominance and add-by-dom epistasis kinship matrices
D <- readRDS(file = here::here("output", "Kinship_D_IITA_2020Sep16.rds"))
AD <- readRDS(file = here::here("output", "Kinship_AD_IITA_2020Sep16.rds"))

## Run models across all train-test splits Parallelize
ncores <- 5
require(furrr)
plan(multiprocess)
options(mc.cores = ncores)
options(future.globals.maxSize = 3000 * 1024^2)

## three chunks, three servers for speed

### cbsulm15
cv_1 <- blups %>% slice(1:50) %>% mutate(accuracy = future_map2(splits, TrainTestData, 
    ~fitModel(splits = .x, TrainTestData = .y, modelType = "ADE", grms = list(A = A, 
        D = D, AD = AD)), .progress = FALSE)) %>% unnest(accuracy)
saveRDS(cv_1 %>% dplyr::select(-TrainTestData), here::here("output", "cvresults_ModelADE_chunk1.rds"))

### cbsulm16
cv_2 <- blups %>% slice(51:100) %>% mutate(accuracy = future_map2(splits, TrainTestData, 
    ~fitModel(splits = .x, TrainTestData = .y, modelType = "ADE", grms = list(A = A, 
        D = D, AD = AD)), .progress = FALSE)) %>% unnest(accuracy)
saveRDS(cv_2 %>% dplyr::select(-TrainTestData), here::here("output", "cvresults_ModelADE_chunk2.rds"))

### cbsulm17
cv_3 <- blups %>% slice(101:150) %>% mutate(accuracy = future_map2(splits, TrainTestData, 
    ~fitModel(splits = .x, TrainTestData = .y, modelType = "ADE", grms = list(A = A, 
        D = D, AD = AD)), .progress = FALSE)) %>% unnest(accuracy)
saveRDS(cv_3 %>% dplyr::select(-TrainTestData), here::here("output", "cvresults_ModelADE_chunk3.rds"))

# 12:35pm

Next step

  1. Genomic prediction: Predict genomic BLUPs (GEBV and GETGV) for all selection candidates using all available data.

sessionInfo()