Last updated: 2021-03-24

Checks: 7 0

Knit directory: PredictOutbredCrossVar/

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(20191123) 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 45e6b20. 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:    output/.DS_Store

Untracked files:
    Untracked:  Icon
    Untracked:  PredictOutbredCrossVarMS_ResponseToReviews_R1.gdoc
    Untracked:  figure/
    Untracked:  manuscript/
    Untracked:  output/crossPredictions/
    Untracked:  output/gblups_DirectionalDom_parentwise_crossVal_folds.rds
    Untracked:  output/gblups_geneticgroups.rds
    Untracked:  output/gblups_parentwise_crossVal_folds.rds
    Untracked:  output/mtMarkerEffects/

Unstaged changes:
    Modified:   analysis/NGCleadersCall.Rmd
    Modified:   code/fitDirectionalDomMtBRR.R
    Modified:   code/fitmtBRR.R
    Modified:   code/getDirectionalDomGenomicBLUPs.R
    Modified:   code/getDirectionalDomMtCrossMeanPreds.R
    Modified:   code/getDirectionalDomMtCrossVarBVpreds.R
    Modified:   code/getDirectionalDomMtCrossVarTGVpreds.R
    Modified:   code/getDirectionalDomVarComps.R
    Modified:   code/getGenomicBLUPs.R
    Modified:   code/getMtCrossMeanPreds.R
    Modified:   code/getMtCrossVarPreds.R
    Modified:   code/getUntestedMtCrossVarPreds.R
    Modified:   code/getVarComps.R
    Modified:   data/blups_forawcdata.rds
    Modified:   data/genmap_awc_May2020.rds
    Modified:   data/parentwise_crossVal_folds.rds
    Modified:   data/ped_awc.rds
    Modified:   data/selection_index_weights_4traits.rds
    Modified:   output/CrossesToPredict_top100stdSI_and_209originalParents.rds
    Modified:   output/accuraciesMeans.rds
    Modified:   output/accuraciesUC.rds
    Modified:   output/accuraciesVars.rds
    Modified:   output/crossRealizations/realizedCrossMeans.rds
    Modified:   output/crossRealizations/realizedCrossMeans_BLUPs.rds
    Modified:   output/crossRealizations/realizedCrossMetrics.rds
    Modified:   output/crossRealizations/realizedCrossVars.rds
    Modified:   output/crossRealizations/realizedCrossVars_BLUPs.rds
    Modified:   output/crossRealizations/realized_cross_means_and_covs_traits.rds
    Modified:   output/crossRealizations/realized_cross_means_and_vars_selindices.rds
    Modified:   output/ddEffects.rds
    Modified:   output/gebvs_ModelA_GroupAll_stdSI.rds
    Modified:   output/obsVSpredMeans.rds
    Modified:   output/obsVSpredUC.rds
    Modified:   output/obsVSpredVars.rds
    Modified:   output/pmv_DirectionalDom_varcomps_geneticgroups.rds
    Modified:   output/pmv_varcomps_geneticgroups.rds
    Modified:   output/pmv_varcomps_geneticgroups_tidy_includingSIvars.rds
    Modified:   output/propHomozygous.rds
    Modified:   output/top100stdSI.rds

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/predictCrossVars.Rmd) and HTML (docs/predictCrossVars.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 be1e9fc wolfemd 2021-03-24 Build site.
Rmd f73b05f wolfemd 2021-03-24 Update to match revised manuscript. Several comparisons moved to Appendix to streamline primary results, figures, etc.
html 4de1330 wolfemd 2021-02-01 Build site.
Rmd 883b1d4 wolfemd 2021-02-01 Update the syntax highlighting and code-block formatting throughout for
Rmd 6a10c30 wolfemd 2021-01-04 Submission and GitHub ready version.
html 6a10c30 wolfemd 2021-01-04 Submission and GitHub ready version.

Predict cross (co)variances

Install package .

# devtools::install_github("wolfemd/predCrossVar", ref = 'master', force=T) 

Models A and AD

Set-up

# activate multithread OpenBLAS
export OMP_NUM_THREADS=88
rm(list=ls()); gc()
library(tidyverse); library(magrittr); library(predCrossVar); library(BGLR);

# BLUPs -----------
blups<-readRDS(here::here("data","blups_forawcdata.rds")) %>% 
  select(Trait,blups) %>% 
  unnest(blups) %>% 
  select(Trait,germplasmName,drgBLUP) %>% 
  spread(Trait,drgBLUP) %>%  
  select(germplasmName,all_of(c("DM","logFYLD","MCMDS","TCHART"))) # precaution to ensure consistent column order

# Training datasets -----------
parentfolds<-readRDS(file = here::here("data","parentwise_crossVal_folds.rds")) %>% 
  rename(Repeat=id,Fold=id2) %>% 
  select(Repeat,Fold,testparents,trainset) %>% 
  pivot_longer(c(trainset), # exclude the testsets
               names_to = "Dataset",
               values_to = "sampleIDs") %>% 
  crossing(Model=c("A","AD")) %>% 
  arrange(desc(Dataset),Repeat,Fold) %>% 
  mutate(blups=map(sampleIDs,~filter(blups,germplasmName %in% .)),
         outName=paste0("mt_",Repeat,"_",Fold,"_",Dataset,"_",Model))

# Pedigree -----------
ped<-readRDS(here::here("data","ped_awc.rds")) %>%
  distinct(sireID,damID)

# Crosses To Predict -------------
parentfolds %<>% 
  mutate(CrossesToPredict=map(testparents,~filter(ped,sireID %in% . | damID %in% .)))

# Recomb frequency matrix ------------
recombFreqMat<-readRDS(here::here("data","recombFreqMat_1minus2c_awcmap_May2020.rds"))

# Haplotype Matrix ------------
haploMat<-readRDS(file=here::here("data","haps_awc.rds"))
parenthaps<-sort(c(paste0(union(ped$sireID,ped$damID),"_HapA"),
                   paste0(union(ped$sireID,ped$damID),"_HapB")))
haploMat<-haploMat[parenthaps,colnames(recombFreqMat)]; rm(parenthaps); dim(haploMat)

# for consistency
parentfolds %<>% 
  rename(outprefix=outName)

# Parallelization specs ---------
require(furrr); options(future.globals.maxSize=50000*1024^2)
ncores<-10; 

# MCMC params ------
nIter<-30000; burnIn<-5000; thin<-5

# Path for output ----------
outpath<-"output/crossPredictions"

# getUntestedMtCrossVarPreds function -------------
## Function to run for each rep-fold-Model (==unique set of marker effects), predict the relevant cross variances.
source(here::here("code","getMtCrossVarPreds.R"))

nchunks<-5
parentfolds %<>% 
  mutate(Chunk=rep(1:nchunks, each=ceiling(nrow(.)/nchunks), length.out=nrow(.))) %>% 
  nest(data=c(-Chunk))

Run variance predictions

# cbsulm17 - done
chunk<-1;
# cbsulm27 - done
chunk<-2;
# cbsulm22 - done
chunk<-3;
# cbsulm09 - (cbsulm15 - done)
chunk<-4;
# cbsulm10 (cbsulm17 - done)
chunk<-5;

# Start run on each server / chunk: Done
predictedCrossVars<-parentfolds %>% 
  slice(chunk) %>% 
  unnest(data) %>% 
  mutate(crossVars=pmap(.,getMtCrossVarPreds,
                        outpath="output/crossPredictions",
                        predType="PMV",nIter=nIter,burnIn=burnIn,thin=thin,
                        recombFreqMat=recombFreqMat,haploMat=haploMat,ncores=ncores))
saveRDS(predictedCrossVars,
        file=here::here("output/crossPredictions",paste0("predictedCrossVars_chunk",chunk,"_2Dec2020.rds")))

Model DirDomAD

Set-up

# activate multithread OpenBLAS
export OMP_NUM_THREADS=112
rm(list=ls()); gc()
library(tidyverse); library(magrittr); library(predCrossVar); library(BGLR);

# BLUPs -----------
blups<-readRDS(here::here("data","blups_forawcdata.rds")) %>% 
  select(Trait,blups) %>% 
  unnest(blups) %>% 
  select(Trait,germplasmName,drgBLUP) %>% 
  spread(Trait,drgBLUP) %>%  
  select(germplasmName,all_of(c("DM","logFYLD","MCMDS","TCHART"))) # precaution to ensure consistent column order

# Training datasets -----------
parentfolds<-readRDS(file = here::here("data","parentwise_crossVal_folds.rds")) %>% 
  rename(Repeat=id,Fold=id2) %>% 
  select(Repeat,Fold,testparents,trainset) %>% 
  pivot_longer(c(trainset), # exclude the testsets
               names_to = "Dataset",
               values_to = "sampleIDs") %>% 
  mutate(Model="DirectionalDom") %>% 
  arrange(desc(Dataset),Repeat,Fold) %>% 
  mutate(blups=map(sampleIDs,~filter(blups,germplasmName %in% .)),
         outName=paste0("mt_",Repeat,"_",Fold,"_",Dataset,"_",Model))

# Pedigree -----------
ped<-readRDS(here::here("data","ped_awc.rds")) %>%
  distinct(sireID,damID)

# Crosses To Predict -------------
parentfolds %<>% 
  mutate(CrossesToPredict=map(testparents,~filter(ped,sireID %in% . | damID %in% .)))

# Recomb frequency matrix ------------
recombFreqMat<-readRDS(here::here("data","recombFreqMat_1minus2c_awcmap_May2020.rds"))

# Haplotype Matrix ------------
haploMat<-readRDS(file=here::here("data","haps_awc.rds"))
parenthaps<-sort(c(paste0(union(ped$sireID,ped$damID),"_HapA"),
                   paste0(union(ped$sireID,ped$damID),"_HapB")))
haploMat<-haploMat[parenthaps,colnames(recombFreqMat)]; rm(parenthaps); dim(haploMat)

# for consistency
parentfolds %<>% 
  rename(outprefix=outName)

# Parallelization specs ---------
require(furrr); options(future.globals.maxSize=50000*1024^2)
ncores<-10; 

# MCMC params ------
nIter<-30000; burnIn<-5000; thin<-5

# Path for output ----------
outpath<-"output/crossPredictions"

# Divide parentfolds into chunks for each server ------------
nchunks<-4
parentfolds %<>% 
  mutate(Chunk=rep(1:nchunks, each=ceiling(nrow(.)/nchunks), length.out=nrow(.))) %>% 
  nest(data=c(-Chunk))

Run Var(TGV) predictions

# Wrapper function for runMtCrossVarPredsAD.
# For each rep-fold (==unique set of marker effects), predict the relevant cross variances.
# This version is for a directional dominance model.
# The only difference from getMtCrossVarPreds is that the inbreeding effect
# For each trait is extract from the BGLR output,
# divided by N snps and added to the vector of SNP effects
# The output predicted variances should be suitable to
# compute predVar(TGV) = predVar(A) + predVar(D)
source(here::here("code","getDirectionalDomMtCrossVarTGVpreds.R"))
# cbsulm13 - Done!
chunk<-1;
# cbsulm15 - Done!
chunk<-2;
# cbsulm17 - Done!
chunk<-3;
# cbsulm26 - Done!
chunk<-4;

# Start run on each server / chunk: Done
predictedCrossVars<-parentfolds %>% 
  slice(chunk) %>% 
  unnest(data) %>% 
  mutate(crossVars=pmap(.,getDirectionalDomMtCrossVarTGVpreds,
                        outpath="output/crossPredictions",
                        predType="PMV",nIter=nIter,burnIn=burnIn,thin=thin,
                        recombFreqMat=recombFreqMat,haploMat=haploMat,ncores=ncores))
saveRDS(predictedCrossVars,
        file=here::here("output/crossPredictions",
                        paste0("predictedDirectionalDomCrossVarTGVs_chunk",chunk,"_15Dec2020.rds")))

Run Var(BV) predictions

# Wrapper function for runMtCrossVarPredsA.
# For each rep-fold (==unique set of marker effects), predict the relevant cross variances.
# This version is for a directional dominance model.
# The only difference from getMtCrossVarPreds are:
# 1. that the inbreeding effect for each trait is extract from the BGLR output,
# divided by N snps and added to the vector of SNP effects
# 2. the allele substitution effects are computed as: a+d(q-p)
# runMtCrossVarPredsA() is run and the 
# output predicted variances should be the predVar(BV) for each family 
source(here::here("code","getDirectionalDomMtCrossVarBVpreds.R"))

# SNP data ------------
snps<-readRDS(here::here("data","dosages_awc.rds")) %>% 
  remove_invariant(.); 
# cbsulm12 - Done!
chunk<-1;
# cbsulm16 - Done! 
chunk<-2;
# cbsulm26 - Done!
chunk<-3;
# cbsulm15 - Done!
chunk<-4;

# Start run on each server / chunk
predictedCrossVars<-parentfolds %>% 
  slice(chunk) %>% 
  unnest(data) %>% 
  mutate(crossVars=pmap(.,getDirectionalDomMtCrossVarBVpreds,
              outpath="output/crossPredictions",
              predType="PMV",nIter=nIter,burnIn=burnIn,thin=thin,
              recombFreqMat=recombFreqMat,haploMat=haploMat,doseMat=snps,ncores=ncores))
saveRDS(predictedCrossVars,
        file=here::here("output/crossPredictions",
                        paste0("predictedDirectionalDomCrossVarBVs_chunk",chunk,"_15Dec2020.rds")))

Predict cross means

Models A and AD

Set-up

# activate multithread OpenBLAS
export OMP_NUM_THREADS=88
rm(list=ls()); gc()
library(tidyverse); library(magrittr); library(predCrossVar); library(BGLR);

# BLUPs -----------
blups<-readRDS(here::here("data","blups_forawcdata.rds")) %>% 
  select(Trait,blups) %>% 
  unnest(blups) %>% 
  select(Trait,germplasmName,drgBLUP) %>% 
  spread(Trait,drgBLUP) %>%  
  select(germplasmName,all_of(c("DM","logFYLD","MCMDS","TCHART"))) # precaution to ensure consistent column order

# Training datasets -----------
parentfolds<-readRDS(file = here::here("data","parentwise_crossVal_folds.rds")) %>% 
  rename(Repeat=id,Fold=id2) %>% 
  select(Repeat,Fold,testparents,trainset) %>% 
  pivot_longer(c(trainset), # exclude the testsets
               names_to = "Dataset",
               values_to = "sampleIDs") %>% 
  crossing(Model=c("A","AD")) %>% 
  arrange(desc(Dataset),Repeat,Fold) %>% 
  mutate(blups=map(sampleIDs,~filter(blups,germplasmName %in% .)),
         outName=paste0("mt_",Repeat,"_",Fold,"_",Dataset,"_",Model))

# Pedigree -----------
ped<-readRDS(here::here("data","ped_awc.rds")) %>%
  distinct(sireID,damID)

# Crosses To Predict -------------
parentfolds %<>% 
  mutate(CrossesToPredict=map(testparents,~filter(ped,sireID %in% . | damID %in% .)))

# SNP data ------------
snps<-readRDS(here::here("data","dosages_awc.rds")) %>% 
  remove_invariant(.); 

# Path for output ----------
outpath<-"output/mtMarkerEffects"

# for consistency
parentfolds %<>% 
  rename(outprefix=outName) 

# Parallelization specs ---------
require(furrr); options(mc.cores=25); plan(multiprocess)
options(future.globals.maxSize=5000*1024^2)

# MCMC params ------
nIter<-30000; burnIn<-5000; thin<-5

# getMtCrossMeanPreds function -------------
## Function to run for each rep-fold-Model (==unique set of marker effects), predict the relevant cross means
source(here::here("code","getMtCrossMeanPreds.R"))

Run mean predictions

# cbsurobbins - Jul 08, 7pm - trivial compute time - COMPLETE
predictedCrossMeans<-parentfolds %>% 
  mutate(crossMeans=future_pmap(.,getMtCrossMeanPreds,doseMat=snps))
saveRDS(predictedCrossMeans,file=here::here("output/crossPredictions","predictedCrossMeans.rds"))

Model DirDomAD

Set-up

# activate multithread OpenBLAS
export OMP_NUM_THREADS=88
rm(list=ls()); gc()
library(tidyverse); library(magrittr); library(predCrossVar); library(BGLR);

# BLUPs -----------
blups<-readRDS(here::here("data","blups_forawcdata.rds")) %>% 
  select(Trait,blups) %>% 
  unnest(blups) %>% 
  select(Trait,germplasmName,drgBLUP) %>% 
  spread(Trait,drgBLUP) %>%  
  select(germplasmName,all_of(c("DM","logFYLD","MCMDS","TCHART"))) # precaution to ensure consistent column order

# Training datasets -----------
parentfolds<-readRDS(file = here::here("data","parentwise_crossVal_folds.rds")) %>% 
  rename(Repeat=id,Fold=id2) %>% 
  select(Repeat,Fold,testparents,trainset) %>% 
  pivot_longer(c(trainset), # exclude the testsets
               names_to = "Dataset",
               values_to = "sampleIDs") %>% 
  mutate(Model="DirectionalDom") %>% 
  arrange(desc(Dataset),Repeat,Fold) %>% 
  mutate(blups=map(sampleIDs,~filter(blups,germplasmName %in% .)),
         outName=paste0("mt_",Repeat,"_",Fold,"_",Dataset,"_",Model))

# Pedigree -----------
ped<-readRDS(here::here("data","ped_awc.rds")) %>%
  distinct(sireID,damID)

# Crosses To Predict -------------
parentfolds %<>% 
  mutate(CrossesToPredict=map(testparents,~filter(ped,sireID %in% . | damID %in% .)))

# SNP data ------------
snps<-readRDS(here::here("data","dosages_awc.rds")) %>% 
  remove_invariant(.); 

# Path for output ----------
outpath<-"output/crossPredictions"

# for consistency
parentfolds %<>% 
  rename(outprefix=outName) 

# Parallelization specs ---------
require(furrr); options(mc.cores=25); plan(multiprocess)
options(future.globals.maxSize=5000*1024^2)

# MCMC params ------
nIter<-30000; burnIn<-5000; thin<-5

# getDirectionalDomMtCrossMeanPreds function
# Wrapper function: for each rep-fold-Model (==unique set of marker effects), predict the relevant cross means.
# This version is for a directional dominance model.
# Differences from getMtCrossMeanPreds:
# 1. inbreeding effect for each trait is extracted from the BGLR output,
### divided by N snps and added to the vector of SNP effects
# 2. Predicted cross mean GEBV: 
### Compute allele sub effects as a+d(q-p) and multiply by allelic dosages of parents. 
### Cross mean GEBV = 0.5*(GEBV_P1 + GEBV+P2)
# 3. Predicted cross mean GETGV: G = sum( 𝑎(𝑝 − 𝑞 − 𝑦) + 𝑑[2𝑝𝑞 + 𝑦(𝑝 − 𝑞)] )
### a and d being the additive and dominance effects
### p and q being the allele frequencies of one parent 
### y is the difference of freq. between the two parents
source(here::here("code","getDirectionalDomMtCrossMeanPreds.R"))

Run mean predictions

# 
predictedCrossMeans<-parentfolds %>% 
  mutate(crossMeans=future_pmap(.,getDirectionalDomMtCrossMeanPreds,doseMat=snps))
saveRDS(predictedCrossMeans,file=here::here("output/crossPredictions","predictedDirectionalDomCrossMeans.rds"))

Process prediction results

Models A and AD

Tidy predicted variances

library(tidyverse); library(magrittr); library(predCrossVar)
# Predicted (co)variances
predictedCrossVars<-list.files(here::here("output/crossPredictions")) %>% 
  grep("predictedCrossVars_chunk",.,value = T) %>% 
  map_df(.,~readRDS(here::here("output/crossPredictions",.))) %>% 
  select(Repeat,Fold,Model,crossVars) %>% 
  mutate(crossVars=map(crossVars,
                       function(crossVars){
                         out<-crossVars$predictedCrossVars$varcovars %>% 
                           mutate(varcomps=map(varcomps,~.$predictedfamvars)) %>% 
                           unnest(varcomps) %>% 
                           unnest(predVars)
                         return(out)})) %>% 
  unnest(crossVars)

Tidy predicted means

# Predicted means
predmeans<-readRDS(here::here("output/crossPredictions","predictedCrossMeans.rds")) %>% 
  select(Repeat,Fold,Model,crossMeans) %>% 
  unnest_wider(crossMeans) %>% 
  select(-runtime) %>% 
  unnest(predictedCrossMeans) %>% 
  select(-sireGEBV,-damGEBV) %>% 
  pivot_longer(cols = contains("predMean"), values_to = "predMean", names_to = "predOf", names_prefix = "pred", values_drop_na=TRUE)

Compute predictions on SI

# Selection weights
indices<-readRDS(file=here::here("data","selection_index_weights_4traits.rds"))
## Predicted Index Variances
predictedCrossVars_SI<-predictedCrossVars %>% 
  pivot_longer(cols=c(VPM,PMV),names_to = "VarMethod",values_to = "Var") %>% 
  select(Repeat,Fold,Model,sireID,damID,VarComp,VarMethod,Trait1,Trait2,Var) %>% 
  nest(varcovars=c(Trait1,Trait2,Var)) %>% 
  mutate(varcovars=map(varcovars,
                       function(varcovars){
                         # pairwise to square symmetric matrix
                         gmat<-varcovars %>% 
                           spread(Trait2,Var) %>% 
                           column_to_rownames(var = "Trait1") %>% 
                           as.matrix %>% 
                           .[indices$Trait,indices$Trait]
                         gmat[lower.tri(gmat)]<-t(gmat)[lower.tri(gmat)]
                         return(gmat) }))
predictedCrossVars_SI %<>% 
  mutate(stdSI=map_dbl(varcovars,~t(indices$stdSI)%*%.%*%indices$stdSI),
         biofortSI=map_dbl(varcovars,~t(indices$biofortSI)%*%.%*%indices$biofortSI)) %>% 
  select(-varcovars) %>% 
  pivot_longer(cols = c(stdSI,biofortSI),
               names_to = "Trait1", 
               values_to = "Var") %>% 
  mutate(Trait2=Trait1) %>% 
  pivot_wider(names_from = "VarMethod", values_from = "Var")
predictedCrossVars %<>% bind_rows(predictedCrossVars_SI,.)
rm(predictedCrossVars_SI)

## Predicted Index Means
predmeans_SI<-predmeans %>% 
  spread(Trait,predMean) %>% 
  nest(predMeans=all_of(indices$Trait)) %>% 
  mutate(stdSI=map_dbl(predMeans,~as.matrix(.)%*%indices$stdSI),
         biofortSI=map_dbl(predMeans,~as.matrix(.)%*%indices$biofortSI)) %>% 
  select(-predMeans) %>% 
  pivot_longer(cols = c(stdSI,biofortSI), names_to = "Trait", values_to = "predMean")
predmeans %<>% bind_rows(predmeans_SI,.)
rm(predmeans_SI,indices)

–> Save

Save the predicted means and variances in the current form. Output contains Nsegsnps and compute times still.

saveRDS(predmeans,here::here("output/crossPredictions","predictedCrossMeans_tidy_withSelIndices.rds"))
saveRDS(predictedCrossVars,here::here("output/crossPredictions","predictedCrossVars_tidy_withSelIndices.rds"))

Model DirDomAD

Tidy predicted variances

library(tidyverse); library(magrittr); library(predCrossVar)
# Predicted (co)variances
predvars<-bind_rows(list.files(here::here("output/crossPredictions")) %>% 
                      grep("predictedDirectionalDomCrossVarBVs_chunk",.,value = T) %>% 
                      grep("_15Dec2020.rds",.,value = T) %>% 
                      map_df(.,~readRDS(here::here("output/crossPredictions",.))) %>% 
                      select(Repeat,Fold,crossVars) %>% 
                      mutate(Model="DirDomBV"),
                    list.files(here::here("output/crossPredictions")) %>% 
                      grep("predictedDirectionalDomCrossVarTGVs_chunk",.,value = T) %>% 
                      grep("_15Dec2020.rds",.,value = T) %>% 
                      map_df(.,~readRDS(here::here("output/crossPredictions",.))) %>% 
                      select(Repeat,Fold,crossVars) %>% 
                      mutate(Model="DirDomAD")) %>% 
  mutate(crossVars=map(crossVars,
                       function(crossVars){
                         out<-crossVars$predictedCrossVars$varcovars %>% 
                           mutate(varcomps=map(varcomps,~.$predictedfamvars)) %>% 
                           unnest(varcomps) %>% 
                           unnest(predVars)
                         return(out)})) %>% 
  unnest(crossVars)
#predvars %>% count(Model,VarComp)

Tidy predicted means

# Predicted means
predmeans<-readRDS(here::here("output/crossPredictions","predictedDirectionalDomCrossMeans.rds")) %>% 
  select(Repeat,Fold,crossMeans) %>% 
  unnest_wider(crossMeans) %>% 
  select(-runtime) %>% 
  unnest(predictedCrossMeans) %>% 
  select(-sireGEBV,-damGEBV) %>% 
  pivot_longer(cols = contains("predMean"), values_to = "predMean", names_to = "predOf", names_prefix = "pred") %>% 
  select(Repeat,Fold,sireID,damID,Trait,predOf,predMean)

Compute predictions on SI

# Selection weights
indices<-readRDS(file=here::here("data","selection_index_weights_4traits.rds"))
## Predicted Index Variances
predvars_SI<-predvars %>% 
  pivot_longer(cols=c(VPM,PMV),names_to = "VarMethod",values_to = "Var") %>% 
  select(Repeat,Fold,sireID,damID,Trait1,Trait2,Model,VarMethod,VarComp,Var) %>% 
  nest(varcovars=c(Trait1,Trait2,Var)) %>% 
  mutate(varcovars=map(varcovars,
                       function(varcovars){
                         # pairwise to square symmetric matrix
                         gmat<-varcovars %>% 
                           spread(Trait2,Var) %>% 
                           column_to_rownames(var = "Trait1") %>% 
                           as.matrix %>% 
                           .[indices$Trait,indices$Trait]
                         gmat[lower.tri(gmat)]<-t(gmat)[lower.tri(gmat)]
                         return(gmat) }))
predvars_SI %<>% 
  mutate(stdSI=map_dbl(varcovars,~t(indices$stdSI)%*%.%*%indices$stdSI),
         biofortSI=map_dbl(varcovars,~t(indices$biofortSI)%*%.%*%indices$biofortSI)) %>% 
  select(-varcovars) %>% 
  pivot_longer(cols = c(stdSI,biofortSI),
               names_to = "Trait1", 
               values_to = "Var") %>% 
  mutate(Trait2=Trait1) %>% 
  pivot_wider(names_from = "VarMethod", values_from = "Var")
predvars %<>% bind_rows(predvars_SI,.)
rm(predvars_SI)

## Predicted Index Means
predmeans_SI<-predmeans %>% 
  spread(Trait,predMean) %>% 
  nest(predMeans=all_of(indices$Trait)) %>% 
  mutate(stdSI=map_dbl(predMeans,~as.matrix(.)%*%indices$stdSI),
         biofortSI=map_dbl(predMeans,~as.matrix(.)%*%indices$biofortSI)) %>% 
  select(-predMeans) %>% 
  pivot_longer(cols = c(stdSI,biofortSI), names_to = "Trait", values_to = "predMean")
predmeans %<>% bind_rows(predmeans_SI,.)
rm(predmeans_SI)

–> Save

Save the predicted means and variances in the current form. Output contains Nsegsnps and compute times still.

saveRDS(predmeans,here::here("output/crossPredictions","predictedCrossMeans_DirectionalDom_tidy_withSelIndices.rds"))
saveRDS(predvars,here::here("output/crossPredictions","predictedCrossVars_DirectionalDom_tidy_withSelIndices.rds"))

sessionInfo()
R version 4.0.3 (2020-10-10)
Platform: x86_64-apple-darwin17.0 (64-bit)
Running under: macOS Big Sur 10.16

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.6        whisker_0.4       knitr_1.31        magrittr_2.0.1   
 [5] R6_2.5.0          rlang_0.4.10      fansi_0.4.2       stringr_1.4.0    
 [9] tools_4.0.3       xfun_0.22         utf8_1.2.1        git2r_0.28.0     
[13] jquerylib_0.1.3   htmltools_0.5.1.1 ellipsis_0.3.1    rprojroot_2.0.2  
[17] yaml_2.2.1        digest_0.6.27     tibble_3.1.0      lifecycle_1.0.0  
[21] crayon_1.4.1      later_1.1.0.1     sass_0.3.1        vctrs_0.3.6      
[25] promises_1.2.0.1  fs_1.5.0          glue_1.4.2        evaluate_0.14    
[29] rmarkdown_2.7     stringi_1.5.3     bslib_0.2.4       compiler_4.0.3   
[33] pillar_1.5.1      jsonlite_1.7.2    httpuv_1.5.5      pkgconfig_2.0.3