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. |
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",...)
require(tidyverse); require(magrittr); require(rsample)
<-read.table(here::here("output","verified_ped.txt"),
pedheader = T, stringsAsFactors = F) %>%
rename(GID=FullSampleName,
damID=DamID,
sireID=SireID) %>%
::select(GID,sireID,damID)
dplyr# only families with _at least_ 2 offspring
%<>%
ped semi_join(ped %>% count(sireID,damID) %>% filter(n>1) %>% ungroup())
<-"GID"
gid<-42
seed<-5
nrepeats<-5 nfolds
# 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".
<-function(ped,gid,nrepeats=5,nfolds=5,seed=NULL){
makeParentFoldsset.seed(seed)
<-rsample::vfold_cv(tibble(Parents=union(ped$sireID,
parentfolds$damID)),
pedv = nfolds,repeats = nrepeats) %>%
mutate(folds=map(splits,function(splits){
#splits<-parentfolds$splits[[1]]
<-testing(splits)$Parents
testparents<-training(splits)$Parents
trainparents<-ped %>%
pedrename(gid=!!sym(gid))
<-ped %>%
offspringfilter(sireID %in% testparents | damID %in% testparents) %$%
unique(gid)
<-ped %>%
grandkidsfilter(sireID %in% offspring | damID %in% offspring) %$%
unique(gid)
<-ped %>%
greatX1grandkidsfilter(sireID %in% grandkids | damID %in% grandkids) %$%
unique(gid)
<-ped %>%
greatX2grandkidsfilter(sireID %in% greatX1grandkids |
%in% greatX1grandkids) %$%
damID unique(gid)
<-ped %>%
greatX3grandkidsfilter(sireID %in% greatX2grandkids |
%in% greatX2grandkids) %$%
damID unique(gid)
<-ped %>%
greatX4grandkidsfilter(sireID %in% greatX3grandkids |
%in% greatX3grandkids) %$%
damID unique(gid)
<-unique(c(offspring,
testset
grandkids,
greatX1grandkids,
greatX2grandkids,
greatX3grandkids,%>%
greatX4grandkids)) !. %in% c(testparents,trainparents)]
.[
<-ped %>%
nontestdescendentsfilter(!gid %in% testset) %$%
unique(gid)
<-union(testparents,trainparents) %>%
trainsetunion(.,nontestdescendents)
<-tibble(testparents=list(testparents),
outtrainset=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),
%in% . | damID %in% .)))
sireID return(parentfolds)
}
<-makeParentFolds(ped=ped,gid="GID",nrepeats=5,nfolds=5,seed=42)
parentfoldssaveRDS(parentfolds,file=here::here("output","parentfolds.rds"))
#parentfolds$CrossesToPredict[[1]]
<-makeParentFolds(ped=ped,gid="GID",nrepeats=5,nfolds=5,seed=42)
parentfolds%>% head parentfolds
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.
<-function(parentfolds,blups,gid,modelType,grms,dosages,ncores){
getMarkEffs<-parentfolds %>%
traintestdata::select(Repeat,Fold,trainset,testset) %>%
dplyrpivot_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
<-function(blups,sampleIDs,modelType,grms){
fitModelrequire(predCrossVar)
<-grms[["A"]]
Aif(modelType %in% c("AD")){ D<-grms[["D"]] }
# debug fitModel()
# sampleIDs<-traintestdata$sampleIDs[[1]]
<-blups %>%
out#slice(1:2) %>% # debug (just 2 traits)
::mutate(trainingdata=map(blups,function(blups){
dplyr<-blups %>%
trainingdatarename(gid=!!sym(gid)) %>%
filter(gid %in% sampleIDs)
paste0(gid,"a")]]<-factor(trainingdata[["gid"]],
trainingdata[[levels=rownames(A))
if(modelType %in% c("AD")){
paste0(gid,"d")]]<-trainingdata[[paste0(gid,"a")]]
trainingdata[[# factor(trainingdata[["gid"]],
# levels=rownames(D))
}return(trainingdata) })) %>%
::select(-blups)
dplyr
# Set-up random model statements
<-paste0("~vs(",gid,"a,Gu=A)")
randFormulaif(modelType %in% c("AD")){
<-paste0(randFormula,"+vs(",gid,"d,Gu=D)")
randFormula
}
# Fit model across each trait
<-out %>%
outmutate(modelOut=map(trainingdata,function(trainingdata){
# Fit genomic prediction model
require(sommer)
<- mmer(fixed = drgBLUP ~1,
fit random = as.formula(randFormula),
weights = WT,
data=trainingdata)
# Gather the GBLUPs
<-tibble(GID=as.character(names(fit$U[[paste0("u:",gid,"a")]]$drgBLUP)),
gblupsGEBV=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
<-as.matrix(fit$U[[paste0("u:",gid,"a")]]$drgBLUP,ncol=1)
ga<-backsolveSNPeff(Z=centerDosage(dosages),g=ga)
addsnpeffif(modelType %in% c("AD")){
<-as.matrix(fit$U[[paste0("u:",gid,"d")]]$drgBLUP,ncol=1)
gd<-backsolveSNPeff(Z=dose2domDev(dosages),g=gd)
domsnpeff
}
# Extract variance components
<-summary(fit)$varcomp
varcomps
<-tibble(gblups=list(gblups),
resultsvarcomps=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)
<-readRDS(file=here::here("output","parentfolds.rds"))
parentfolds
<-readRDS(file=here::here("data","blups_forCrossVal.rds")) %>%
blups::select(-varcomp)
dplyr
<-readRDS(file=here::here("output","kinship_A_IITA_2021May13.rds"))
A<-readRDS(file=here::here("data",
dosages"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
<-getMarkEffs(parentfolds,blups,gid="GID",
markEffsAmodelType="A",grms=list(A=A),dosages,ncores=2)
saveRDS(markEffsA,here::here("output","markerEffectsA.rds"))
# cbsulm31
<-readRDS(file=here::here("output","kinship_D_IITA_2021May13.rds"))
D<-getMarkEffs(parentfolds,blups,gid="GID",
markEffsADmodelType="AD",grms=list(A=A,D=D),dosages,ncores=2)
saveRDS(markEffsAD,here::here("output","markerEffectsAD.rds"))
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);
<-readRDS(file=here::here("output","parentfolds.rds"))
parentfolds<-parentfolds %>%
parentsselect(Repeat,Fold,CrossesToPredict) %>%
unnest(CrossesToPredict) %>%
distinct(sireID,damID) %$%
union(sireID,damID)
# Recomb frequency matrix
<-readRDS(file=here::here("data",
recombFreqMat"recombFreqMat_1minus2c_2021May13.rds"))
# Haplotype Matrix
<-readRDS(file=here::here("data","haps_IITA_filtered_2021May13.rds"))
haploMat## keep only haplos for parents-to-be-predicted, saves memory
<-sort(c(paste0(parents,"_HapA"),
parenthapspaste0(parents,"_HapB")))
<-haploMat[parenthaps,colnames(recombFreqMat)];
haploMat
# Source predictCrossVar predCrossVar function
source(here::here("code","predCrossVar.R"))
source(here::here("code","parentWiseCrossVal.R"))
# cbsulm29
<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsA
<-proc.time()[3]
starttime<-predictCrossVars(modelType="A",ncores=20,
crossValPredsAsnpeffs=markEffsA,parentfolds=parentfolds,
haploMat=haploMat,recombFreqMat=recombFreqMat)
<-crossValPredsA %>% select(-AddEffectList,-CrossesToPredict)
crossValPredsAsaveRDS(crossValPredsA,here::here("output","crossValPredsA.rds"))
<-proc.time()[3] - starttime;
timeelapsedprint(paste0("Elapsed: ",timeelapsed/60/60," hrs"))
# [1] "Elapsed: 6.60880583333333 hrs"
# cbsulm29
<-readRDS(here::here("output","markerEffectsAD.rds"))
markEffsAD
<-proc.time()
starttime<-predictCrossVars(modelType="AD",ncores=20,
crossValPredsADsnpeffs=markEffsAD,parentfolds=parentfolds,
haploMat=haploMat,recombFreqMat=recombFreqMat)
<-crossValPredsAD %>% select(-AddEffectList,-DomEffectList,-CrossesToPredict)
crossValPredsADsaveRDS(crossValPredsAD,here::here("output","crossValPredsAD.rds"))
<-proc.time()[3] - starttime;
timeelapsedprint(paste0("Elapsed: ",timeelapsed/60/60," hrs"))
# didn't record time... 12-14 hours max.
require(tidyverse); require(magrittr);
<-readRDS(file=here::here("output","parentfolds.rds"))
parentfolds<-parentfolds %>%
parentsselect(Repeat,Fold,CrossesToPredict) %>%
unnest(CrossesToPredict) %>%
distinct(sireID,damID) %$%
union(sireID,damID)
# Haplotype Matrix
<-readRDS(file=here::here("data","dosages_IITA_filtered_2021May13.rds"))
doseMat## keep only haplos for parents-to-be-predicted, saves memory
<-doseMat[parents,];
doseMat
# # Source predictCrossVar predCrossVar function
source(here::here("code","predCrossVar.R"))
source(here::here("code","parentWiseCrossVal.R"))
<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsA<-readRDS(here::here("output","markerEffectsAD.rds"))
markEffsAD
<-predictCrossMeans(modelType="A",snpeffs=markEffsA,ncores=11,
cvPredMeansAparentfolds=parentfolds,doseMat=doseMat)
saveRDS(cvPredMeansA,here::here("output","cvPredMeansA.rds"))
<-predictCrossMeans(modelType="AD",snpeffs=markEffsAD,ncores=11,
cvPredMeansADparentfolds=parentfolds,doseMat=doseMat)
saveRDS(cvPredMeansAD,here::here("output","cvPredMeansAD.rds"))
require(tidyverse); require(magrittr);
<-readRDS(here::here("output","crossValPredsA.rds"))
cvPredVarsA<-readRDS(here::here("output","crossValPredsAD.rds"))
cvPredVarsAD
<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsA<-readRDS(here::here("output","markerEffectsAD.rds"))
markEffsAD
<-read.table(here::here("output","verified_ped.txt"),
pedheader = T, stringsAsFactors = F) %>%
rename(GID=FullSampleName,
damID=DamID,
sireID=SireID)
# index weights from IYR+IK
<-c(logFYLD=20,
SIwtsHI=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
<-function(crossValOut,markEffs,ped,modelType,
varPredAccuracyselInd=FALSE,SIwts=NULL){
# Extract and format the GBLUPs from the marker effects object
<-markEffs %>%
gblupsfilter(Dataset=="testset") %>%
mutate(testset_gblups=map(effects,
function(effects){
<-effects %>%
gblupsmutate(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
<-crossValOut %>%
outunnest(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)))
}%<>% unnest(testset_gblups)
out
# 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){
<-cov(gblupmat)
covMat# to match predCrossVar output
## keep upper tri + diag of covMat
<-covMat
obsvarslower.tri(obsvars)]<-NA
obsvars[%<>%
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[names(SIwts),names(SIwts)]
covmat<-SIwts%*%covmat%*%SIwts
selIndVar%<>%
obsvars bind_rows(tibble(Trait1="SELIND",
Trait2="SELIND",
obsVar=selIndVar),.) }
return(obsvars) }),
famSize=map_dbl(gblupmat,nrow)) %>%
select(-gblupmat) %>%
unnest(obsvars))})) %>%
select(-famgblups)
<-crossValOut %>%
cvoutunnest(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 %>%
cvoutfilter(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){
<-fampredvars %>%
gmatpivot_wider(names_from = "Trait1",
values_from = "predVar") %>%
column_to_rownames(var = "Trait2") %>%
as.matrixupper.tri(gmat)]<-t(gmat)[upper.tri(gmat)]
gmat[%<>% .[names(SIwts),names(SIwts)]
gmat <-SIwts%*%gmat%*%SIwts
predSelIndVar<-tibble(Trait1="SELIND",
fampredvarsTrait2="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){
<-psych::cor.wt(predVSobs[,c("predVar","obsVar")],
outw = predVSobs$famSize) %$% r[1,2] %>%
round(.,3)
return(out) }))
return(out)
}
# rm(x,out,gmat,gblups,markEffs,predSelIndV,selInd,modelType)
# rm(cvout,crossValOut)
<-varPredAccuracy(modelType = "A",
cvVarPredAccuracyAcrossValOut = cvPredVarsA,
markEffs = markEffsA,
ped = ped,selInd = TRUE,SIwts = SIwts)
<-varPredAccuracy(modelType = "AD",
cvVarPredAccuracyADcrossValOut = cvPredVarsAD,
markEffs = markEffsAD,
ped = ped,selInd = TRUE,SIwts = SIwts)
saveRDS(cvVarPredAccuracyA,here::here("output","cvVarPredAccuracyA.rds"))
saveRDS(cvVarPredAccuracyAD,here::here("output","cvVarPredAccuracyAD.rds"))
require(tidyverse); require(magrittr);
<-readRDS(here::here("output","cvPredMeansA.rds"))
cvPredMeansA<-readRDS(here::here("output","cvPredMeansAD.rds"))
cvPredMeansAD
<-readRDS(here::here("output","markerEffectsA.rds"))
markEffsA<-readRDS(here::here("output","markerEffectsAD.rds"))
markEffsAD
<-read.table(here::here("output","verified_ped.txt"),
pedheader = T, stringsAsFactors = F) %>%
rename(GID=FullSampleName,
damID=DamID,
sireID=SireID)
# index weights from IYR+IK
<-c(logFYLD=20,
SIwtsHI=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)
# }
<-meanPredAccuracy(modelType = "A",
cvMeanPredAccuracyAcrossValOut = cvPredMeansA,
markEffs = markEffsA,
ped = ped,selInd = TRUE,SIwts = SIwts)
<-meanPredAccuracy(modelType = "AD",
cvMeanPredAccuracyADcrossValOut = cvPredMeansAD,
markEffs = markEffsAD,
ped = ped,selInd = TRUE,SIwts = SIwts)
saveRDS(cvMeanPredAccuracyA,here::here("output","cvMeanPredAccuracyA.rds"))
saveRDS(cvMeanPredAccuracyAD,here::here("output","cvMeanPredAccuracyAD.rds"))