Last updated: 2020-10-16

Checks: 7 0

Knit directory: NRCRI_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(20200421) 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 c5c0337. 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:  CrossValidationFunction_PlusNRCRI_2020GSnotes.gslides
    Untracked:  data/DatabaseDownload_2020Oct13/
    Untracked:  data/chr1_RefPanelAndGSprogeny_ReadyForGP_72719.fam
    Untracked:  output/Kinship_AA_NRCRI_2020April27.rds
    Untracked:  output/Kinship_AD_NRCRI_2020April27.rds
    Untracked:  output/Kinship_AD_NRCRI_2020Oct15.rds
    Untracked:  output/Kinship_A_NRCRI_2020April27.rds
    Untracked:  output/Kinship_A_NRCRI_2020Oct15.rds
    Untracked:  output/Kinship_DD_NRCRI_2020April27.rds
    Untracked:  output/Kinship_D_NRCRI_2020April27.rds
    Untracked:  output/Kinship_D_NRCRI_2020Oct15.rds
    Untracked:  workflowr_log.R

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/07-GetBLUPs.Rmd) and HTML (docs/07-GetBLUPs.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 12bd17b wolfemd 2020-10-16 Build site.
Rmd 977f389 wolfemd 2020-10-16 Publish NRCRI imputations for 2020 (DCas20_5510 and DCas20_5440) plus a

Previous step

  1. Prepare training dataset: Download data from DB, “Clean” and format DB data.

Objective

Two-stage genomic prediction refers to the following procedure:

Stage 1: Fit a linear mixed model to the data without genomic data. Individuals (e.g. clones / accessions) are modeled as independent and identically distributed (i.i.d.) random effects. The BLUPs for this random effect represent the measurable total genetic values of each individual. All the experimental design variation, e.g. replication and blocking effects have been controlled for in the creation of our new response variable, the BLUPs from the gneotype random effect.

Stage 2: Using a modified version of the BLUPs from step 1 as the response variable, fit a genomic prediction model, which now has reduced size because the number of observations is now the same as the number of individuals.

NOTE: In the animal breeding literature single-step often refers to predictions that combine pedigree and marker information simultaneously. That is not our meaning here.

The code below represents Stage I.

Set-up training datasets

This next step fits models to each trait, combining curated data (BLUPs) from each trial, which we computed in the previous step.

rm(list=ls())
library(tidyverse); library(magrittr);
source(here::here("code","gsFunctions.R"))
dbdata<-readRDS(file=here::here("output","NRCRI_ExptDesignsDetected_2020Oct13.rds"))
traits<-c("CGM","CGMS1","CGMS2","MCMDS","DM","PLTHT","BRNHT1","HI","logFYLD","logTOPYLD","logRTNO")

# **Nest by trait.** Need to restructure the data from per-trial by regrouping by trait. 
dbdata<-nestDesignsDetectedByTraits(dbdata,traits)
dbdata %>% mutate(N_blups=map_dbl(MultiTrialTraitData,nrow)) %>% rmarkdown::paged_table()

Function to fit mixed-models

To fit the mixed-model that I want, I am again resorting to asreml-R. I fit random effects for rep and block only where complete and incomplete blocks, respectively are indicated in the trial design variables. sommer should be able to fit the same model via the at() function, but I am having trouble with it and sommer is much slower even without a dense covariance (i.e. a kinship), compared to lme4::lmer() or asreml(). Note: For genomic predictions I do use sommer.

dbdata %<>% 
  mutate(fixedFormula=ifelse(Trait %in% c("logFYLD","logRTNO","logTOPYLD"),"Value ~ yearInLoc","Value ~ yearInLoc + PropNOHAV"),
         randFormula=paste0("~idv(GID) + idv(trialInLocYr) + at(CompleteBlocks,'Yes'):repInTrial ",
                            "+ at(IncompleteBlocks,'Yes'):blockInRep"))
dbdata %>% 
  mutate(Nobs=map_dbl(MultiTrialTraitData,nrow)) %>% 
  select(Trait,Nobs,fixedFormula,randFormula) %>% 
  rmarkdown::paged_table()
# randFormula<-paste0("~vs(GID) + vs(trialInLocYr) + vs(at(CompleteBlocks,'Yes'),repInTrial) + vs(at(IncompleteBlocks,'Yes'),blockInRep)")
# library(sommer)
# fit <- mmer(fixed = Value ~ 1 + yearInLoc,
#             random = as.formula(randFormula),
#             data=trainingdata,
#             getPEV=TRUE)

Includes rounds of outlier removal and re-fitting.

fitASfunc<-function(fixedFormula,randFormula,MultiTrialTraitData,...){
  # test arguments for function
  # ----------------------
  # MultiTrialTraitData<-dbdata$MultiTrialTraitData[[7]]
  # #Trait<-dbdata$Trait[[3]]
  # fixedFormula<-dbdata$fixedFormula[[7]]
  # randFormula<-dbdata$randFormula[[7]]
  # test<-fitASfunc(fixedFormula,randFormula,MultiTrialTraitData)
  # ----------------------
  require(asreml); 
  fixedFormula<-as.formula(fixedFormula)
  randFormula<-as.formula(randFormula)
  # fit asreml 
  out<-asreml(fixed = fixedFormula,
              random = randFormula,
              data = MultiTrialTraitData, 
              maxiter = 40, workspace=800e6, na.method.X = "omit")
  #### extract residuals - Round 1
  
  outliers1<-which(abs(scale(out$residuals))>3.3)
  
  if(length(outliers1)>0){
    
    x<-MultiTrialTraitData[-outliers1,]
    # re-fit
    out<-asreml(fixed = fixedFormula,
                random = randFormula,
                data = x, 
                maxiter = 40, workspace=800e6, na.method.X = "omit")
    #### extract residuals - Round 2
    outliers2<-which(abs(scale(out$residuals))>3.3)
    if(length(outliers2)>0){
      #### remove outliers
      x<-x[-outliers2,]
      # final re-fit
      out<-asreml(fixed = fixedFormula,
                  random = randFormula,
                  data = x, maxiter = 40,workspace=800e6, na.method.X = "omit")
    }
  }
  if(length(outliers1)==0){ outliers1<-NULL }
  if(length(outliers2)==0){ outliers2<-NULL }
  
  ll<-summary(out,all=T)$loglik
  varcomp<-summary(out,all=T)$varcomp
  Vg<-varcomp["GID!GID.var","component"]
  Ve<-varcomp["R!variance","component"]
  H2=Vg/(Vg+Ve)
  blups<-summary(out,all=T)$coef.random %>%
    as.data.frame %>%
    rownames_to_column(var = "GID") %>%
    dplyr::select(GID,solution,`std error`) %>%
    filter(grepl("GID",GID)) %>%
    rename(BLUP=solution) %>%
    mutate(GID=gsub("GID_","",GID),
           PEV=`std error`^2, # asreml specific
           REL=1-(PEV/Vg), # Reliability
           drgBLUP=BLUP/REL, # deregressed BLUP
           WT=(1-H2)/((0.1 + (1-REL)/REL)*H2)) # weight for use in Stage 2
  out<-tibble(loglik=ll,Vg,Ve,H2,
              blups=list(blups),
              varcomp=list(varcomp),
              outliers1=list(outliers1),
              outliers2=list(outliers2))
  return(out) }

Run asreml

library(furrr); options(mc.cores=11); plan(multiprocess)
library(asreml)
dbdata %<>% 
  mutate(fitAS=future_pmap(.,fitASfunc))
dbdata %<>%
  select(-fixedFormula,-randFormula,-MultiTrialTraitData) %>%
  unnest(fitAS)

Output file

saveRDS(dbdata,file=here::here("output","nrcri_blupsForModelTraining_twostage_asreml_2020Oct13.rds"))

Results

See Results

Next step

  1. Check prediction accuracy: Evaluate prediction accuracy with cross-validation.

sessionInfo()