/
05-CrossValidation.Rmd
1634 lines (1458 loc) · 62 KB
/
05-CrossValidation.Rmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
title: "Parent-wise cross-validation to check the accuracy of predicting cross (co)-variances"
author: "Marnin Wolfe"
date: "2021-May-14"
output:
workflowr::wflow_html:
toc: true
editor_options:
chunk_output_type: inline
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = F,
eval = FALSE, # <- NOTE THAT EVAL SET TO FALSE!
tidy='styler', tidy.opts=list(strict=FALSE,width.cutoff=100), highlight=TRUE)
```
# Previous step
4. [Preprocess data files](04-PreprocessDataFiles.html): Prepare haplotype and dosage matrices, pedigree and BLUPs, genetic map *and* recombination frequency matrix, for use in predictions.
# Automating cross-validation
In the manuscript, the cross-validation is documented many pages and scripts, [documented here](https://wolfemd.github.io/PredictOutbredCrossVar/).
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.
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.
Revised the functions in **`package:predCrossVar`** to increase the 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. Improvements will benefit users predicting with REML / Bayesian-VPM, but probably worse for Bayesian-PMV.
# Debug the component functions
```{bash, eval=F}
cd /home/jj332_cas/marnin/implementGMSinCassava/;
export PATH=/programs/R-4.0.5clean-p/bin:$PATH;
export OMP_NUM_THREADS=5; # <-- for a 112 core machine. Use ncores=20 below
screen;
R # initiate R session
```
```{r primary debug inputs}
require(tidyverse); require(magrittr);
# SOURCE CORE FUNCTIONS
# source(here::here("code","parentWiseCrossVal.R"))
source(here::here("code","predCrossVar.R"))
# PEDIGREE
ped<-read.table(here::here("output","verified_ped.txt"),
header = T, stringsAsFactors = F) %>%
rename(GID=FullSampleName,
damID=DamID,
sireID=SireID) %>%
dplyr::select(GID,sireID,damID)
# Keep only families with _at least_ 2 offspring
ped %<>%
semi_join(ped %>% count(sireID,damID) %>% filter(n>1) %>% ungroup())
# BLUPs
blups<-readRDS(file=here::here("data","blups_forCrossVal.rds")) %>%
dplyr::select(-varcomp)
# GENOMIC RELATIONSHIP MATRICES (GRMS)
grms<-list(A=readRDS(file=here::here("output","kinship_A_IITA_2021May13.rds")),
D=readRDS(file=here::here("output","kinship_D_IITA_2021May13.rds")))
# DOSAGE MATRIX
dosages<-readRDS(file=here::here("data",
"dosages_IITA_filtered_2021May13.rds"))
# RECOMBINATION FREQUENCY MATRIX
recombFreqMat<-readRDS(file=here::here("data",
"recombFreqMat_1minus2c_2021May13.rds"))
# HAPLOTYPE MATRIX
## keep only haplos for parents-in-the-pedigree
## those which will be used in prediction, saves memory
haploMat<-readRDS(file=here::here("data","haps_IITA_filtered_2021May13.rds"))
parents<-union(ped$sireID,ped$damID)
parenthaps<-sort(c(paste0(parents,"_HapA"),
paste0(parents,"_HapB")))
haploMat<-haploMat[parents,colnames(recombFreqMat)]
# SELECTION INDEX WEIGHTS
## from IYR+IK
## note that not ALL predicted traits are on index
SIwts<-c(logFYLD=20,
HI=10,
DM=15,
MCMDS=-10,
logRTNO=12,
logDYLD=20,
logTOPYLD=15,
PLTHT=10)
```
```{r initial test inputs}
# install.packages("tidyverse",source=T)
# install.packages(c("sommer","furrr","rsample","devtools"));
# devtools::install_github("wolfemd/predCrossVar", ref = 'master', force=T)
# debug --------
nrepeats=1;nfolds=5;seed=53;modelType="AD";
ncores=20;outName="output/cvAD_1rep";
ped=ped;gid="GID";blups=blups;
dosages=dosages;haploMat=haploMat;
grms=grms;recombFreqMat = recombFreqMat;
selInd = TRUE; SIwts = SIwts
blups %<>% slice(1:2)
################
```
```{r source makeParentFolds}
makeParentFolds<-function(ped,gid,nrepeats=5,nfolds=5,seed=NULL){
require(rsample)
set.seed(seed)
parentfolds<-rsample::vfold_cv(tibble(Parents=union(ped$sireID,
ped$damID)),
v = nfolds,repeats = nrepeats) %>%
mutate(folds=map(splits,function(splits){
#splits<-parentfolds$splits[[1]]
testparents<-testing(splits)$Parents
trainparents<-training(splits)$Parents
ped<-ped %>%
rename(gid=!!sym(gid))
offspring<-ped %>%
filter(sireID %in% testparents | damID %in% testparents) %$%
unique(gid)
grandkids<-ped %>%
filter(sireID %in% offspring | damID %in% offspring) %$%
unique(gid)
greatX1grandkids<-ped %>%
filter(sireID %in% grandkids | damID %in% grandkids) %$%
unique(gid)
greatX2grandkids<-ped %>%
filter(sireID %in% greatX1grandkids |
damID %in% greatX1grandkids) %$%
unique(gid)
greatX3grandkids<-ped %>%
filter(sireID %in% greatX2grandkids |
damID %in% greatX2grandkids) %$%
unique(gid)
greatX4grandkids<-ped %>%
filter(sireID %in% greatX3grandkids |
damID %in% greatX3grandkids) %$%
unique(gid)
testset<-unique(c(offspring,
grandkids,
greatX1grandkids,
greatX2grandkids,
greatX3grandkids,
greatX4grandkids)) %>%
.[!. %in% c(testparents,trainparents)]
nontestdescendents<-ped %>%
filter(!gid %in% testset) %$%
unique(gid)
trainset<-union(testparents,trainparents) %>%
union(.,nontestdescendents)
out<-tibble(testparents=list(testparents),
trainset=list(trainset),
testset=list(testset))
return(out) })) %>%
unnest(folds)
if(nrepeats>1){
parentfolds %<>%
rename(Repeat=id,Fold=id2) %>%
select(-splits)
}
if(nrepeats==1){
parentfolds %<>%
mutate(Repeat="Repeat1") %>%
rename(Fold=id) %>%
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),
sireID %in% . | damID %in% .)))
return(parentfolds)
}
```
```{r run makeParentFolds}
parentfolds<-makeParentFolds(ped=ped,gid="GID",
nrepeats=nrepeats,
nfolds=nfolds,
seed=seed)
# debug --------
parentfolds %<>% filter(Fold=="Fold1")
parentfolds$CrossesToPredict[[1]] %<>% slice(1:3)
################
```
```{r debug getMarkEffs}
getMarkEffs<-function(parentfolds,blups,gid,modelType,grms,dosages,ncores){
traintestdata<-parentfolds %>%
dplyr::select(Repeat,Fold,trainset,testset) %>%
pivot_longer(c(trainset,testset),
names_to = "Dataset",
values_to = "sampleIDs") %>%
crossing(Trait=blups$Trait) %>%
left_join(blups) %>%
rename(blupsMat=blups)
## For each training/testing chunk of sampleIDs and each trait
## fit GBLUP model and backsolve SNP-effects
fitModel<-function(sampleIDs,blupsMat,modelType,gid,grms,dosages,...){
# debug
# sampleIDs<-traintestdata$sampleIDs[[2]]; blups<-traintestdata$blups[[2]]
require(predCrossVar)
A<-grms[["A"]]
if(modelType %in% c("AD")){ D<-grms[["D"]] }
trainingdata<-blupsMat %>%
dplyr::rename(gid=!!sym(gid)) %>%
filter(gid %in% sampleIDs)
trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[["gid"]],
levels=rownames(A))
if(modelType %in% c("AD")){
trainingdata[[paste0(gid,"d")]]<-trainingdata[[paste0(gid,"a")]]
}
# Set-up random model statements
randFormula<-paste0("~vs(",gid,"a,Gu=A)")
if(modelType %in% c("AD")){
randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D)")
}
# Fit genomic prediction model
require(sommer)
fit <- sommer::mmer(fixed = drgBLUP ~1,
random = as.formula(randFormula),
weights = WT,
data=trainingdata)
# Gather the GBLUPs
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")){
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
ga<-as.matrix(fit$U[[paste0("u:",gid,"a")]]$drgBLUP,ncol=1)
addsnpeff<-backsolveSNPeff(Z=centerDosage(dosages),g=ga)
if(modelType %in% c("AD")){
gd<-as.matrix(fit$U[[paste0("u:",gid,"d")]]$drgBLUP,ncol=1)
domsnpeff<-backsolveSNPeff(Z=dose2domDev(dosages),g=gd)
}
# Extract variance components
varcomps<-summary(fit)$varcomp
results<-tibble(gblups=list(gblups),
varcomps=list(varcomps),
addsnpeff=list(addsnpeff))
if(modelType %in% c("AD")){
results %<>%
mutate(domsnpeff=list(domsnpeff)) }
# return results
return(results)
}
require(furrr); options(mc.cores=ncores); plan(multicore)
options(future.globals.maxSize=50000*1024^2)
traintestdata<-traintestdata %>%
mutate(modelOut=future_pmap(.,fitModel,
modelType=modelType,
gid=gid,
grms=grms,
dosages=dosages,
seed=T),
modelType=modelType)
traintestdata %<>%
select(-blupsMat,-sampleIDs) %>%
unnest(modelOut) %>%
nest(effects=c(Trait,gblups,varcomps,addsnpeff,domsnpeff))
# this is to remove conflicts with dplyr function select() downstream
detach("package:sommer",unload = T); detach("package:MASS",unload = T)
return(traintestdata)
}
```
```{r test inputs for predictCrossVars}
snpeffs<-traintestdata
```
```{r debug predictCrossVars}
predictCrossVars<-function(modelType,snpeffs,parentfolds,
haploMat,recombFreqMat,ncores){
predvars<-snpeffs %>%
unnest(effects) %>%
filter(Dataset=="trainset") %>%
dplyr::select(Repeat,Fold,Trait,modelType,
any_of(c("addsnpeff","domsnpeff"))) %>%
nest(EffectList=c(Trait,any_of(c("addsnpeff","domsnpeff")))) %>%
mutate(AddEffectList=map(EffectList,
function(EffectList){
addsnpeff<-map(EffectList$addsnpeff,~t(.))
names(addsnpeff)<-EffectList$Trait
return(addsnpeff)}))
if(modelType %in% c("AD")){
predvars<-predvars %>%
mutate(DomEffectList=map(EffectList,
function(EffectList){
domsnpeff<-map(EffectList$domsnpeff,~t(.))
names(domsnpeff)<-EffectList$Trait
return(domsnpeff) })) }
predvars %<>%
left_join(parentfolds %>%
dplyr::select(-testparents,-trainset,-testset)) %>%
dplyr::select(-EffectList)
require(furrr); options(future.globals.maxSize=40000*1024^2)
if(modelType=="A"){
predvars<-predvars %>%
mutate(predVars=map2(CrossesToPredict,AddEffectList,
~predCrossVars(CrossesToPredict=.x,
AddEffectList=.y,
modelType=modelType,
haploMat=haploMat,
recombFreqMat=recombFreqMat,
ncores=ncores))) }
if(modelType=="AD"){
predvars<-predvars %>%
mutate(predVars=pmap(.,function(CrossesToPredict,
AddEffectList,DomEffectList,...){
out<-predCrossVars(CrossesToPredict=CrossesToPredict,
AddEffectList=AddEffectList,
DomEffectList=DomEffectList,
modelType=modelType,
haploMat=haploMat,
recombFreqMat=recombFreqMat,
ncores=ncores)
return(out) })) }
predvars %<>% select(-AddEffectList,-DomEffectList,-CrossesToPredict)
return(predvars)
}
```
```{r inputs for predictCrossMeans}
doseMat=dosages
```
```{r debug predictCrossMeans}
predictCrossMeans<-function(modelType,snpeffs,parentfolds,
doseMat,ncores){
predmeans<-snpeffs %>%
unnest(effects) %>%
filter(Dataset=="trainset") %>%
dplyr::select(Repeat,Fold,Trait,modelType,
any_of(c("addsnpeff","domsnpeff"))) %>%
nest(EffectList=c(Trait,any_of(c("addsnpeff","domsnpeff")))) %>%
mutate(AddEffectList=map(EffectList,
function(EffectList){
addsnpeff<-map(EffectList$addsnpeff,~t(.))
names(addsnpeff)<-EffectList$Trait
return(addsnpeff)}))
if(modelType %in% c("AD")){
predmeans<-predmeans %>%
mutate(DomEffectList=map(EffectList,
function(EffectList){
domsnpeff<-map(EffectList$domsnpeff,~t(.))
names(domsnpeff)<-EffectList$Trait
return(domsnpeff) })) }
predmeans %<>%
left_join(parentfolds %>%
dplyr::select(-testparents,-trainset,-testset)) %>%
dplyr::select(-EffectList)
predmeans %<>%
mutate(predMeans=pmap(.,predCrossMeans,doseMat=doseMat,ncores=ncores)) %>%
select(-contains("EffectList"),-CrossesToPredict)
return(predmeans)
}
```
```{r inputs for varPredAccuracy}
crossValOut<-predvars
SIwts<-c(DM=15,
MCMDS=-10)
```
```{r debug varPredAccuracy}
varPredAccuracy<-function(crossValOut,snpeffs,ped,modelType,
selInd=FALSE,SIwts=NULL){
# Extract and format the GBLUPs from the marker effects object
gblups<-snpeffs %>%
unnest(effects) %>%
filter(Dataset=="testset") %>%
select(Repeat,Fold,modelType,Trait,gblups) %>%
unnest(gblups) %>%
nest(testset_gblups=c(-Repeat,-Fold,-modelType))
# 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
out<-crossValOut %>%
unnest(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,.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)
#famgblups<-out$famgblups[[1]]
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){
#gblupmat<-famgblups$gblupmat[[1]]
covMat<-cov(gblupmat)
# to match predCrossVar output
## keep upper tri + diag of covMat
obsvars<-covMat
obsvars[lower.tri(obsvars)]<-NA
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<-covMat[names(SIwts),names(SIwts)]
selIndVar<-SIwts%*%covmat%*%SIwts
obsvars %<>%
bind_rows(tibble(Trait1="SELIND",
Trait2="SELIND",
obsVar=selIndVar),.) }
return(obsvars) }),
famSize=map_dbl(gblupmat,nrow)) %>%
select(-gblupmat) %>%
unnest(obsvars))})) %>%
select(-famgblups)
cvout<-crossValOut %>%
unnest(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<-cvout %>%
filter(predOf=="VarA") %>%
# Breeding value variance predictions from the predOf=="VarA"
mutate(predOf="VarBV") %>%
# for Total Gen Value variance predictions, need to compute:
## predVarTot = predVarA + predVarD
bind_rows(cvout %>%
group_by(Repeat,Fold,modelType,sireID,damID,Trait1,Trait2) %>%
summarize(predVar=sum(predVar),
Nsegsnps=max(Nsegsnps),.groups = 'drop') %>%
mutate(predOf="VarTGV"))
}
cvout %<>%
nest(predVars=c(sireID,damID,Trait1,Trait2,predVar,Nsegsnps))
if(selInd==TRUE){
# compute predicted selection index variances
cvout %<>%
## loop over each rep-fold-predType
mutate(predVars=map(predVars,function(predVars){
predvars<-predVars %>%
nest(fampredvars=c(-sireID,-damID,-Nsegsnps)) %>%
## internal loop over each family
mutate(predVar=map_dbl(fampredvars,function(fampredvars){
gmat<-fampredvars %>%
pivot_wider(names_from = "Trait2",
values_from = "predVar") %>%
column_to_rownames(var = "Trait1") %>%
as.matrix
gmat[lower.tri(gmat)]<-t(gmat)[lower.tri(gmat)]
gmat %<>% .[names(SIwts),names(SIwts)]
predSelIndVar<-SIwts%*%gmat%*%SIwts
return(predSelIndVar) }),
Trait1="SELIND",
Trait2="SELIND") %>%
select(-fampredvars)
## add sel index predictions to component trait
## var-covar predictions
predvars %<>%
bind_rows(.,predVars) %>%
select(sireID,damID,Trait1,Trait2,predVar,Nsegsnps)
return(predvars) }))
}
out %<>%
mutate(predOf=ifelse(predOf=="GEBV","VarBV","VarTGV")) %>%
left_join(cvout)
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){
out<-psych::cor.wt(predVSobs[,c("predVar","obsVar")],
w = predVSobs$famSize) %$% r[1,2] %>%
round(.,3)
return(out) }))
return(out)
}
```
```{r inputs for meanPredAccuracy}
crossValOut<-predmeans
```
```{r debug meanPredAccuracy}
meanPredAccuracy<-function(crossValOut,snpeffs,ped,modelType,
selInd=FALSE,SIwts=NULL){
# Extract and format the GBLUPs from the marker effects object
# Extract and format the GBLUPs from the marker effects object
gblups<-snpeffs %>%
unnest(effects) %>%
filter(Dataset=="testset") %>%
select(Repeat,Fold,modelType,Trait,gblups) %>%
unnest(gblups) %>%
nest(testset_gblups=c(-Repeat,-Fold,-modelType))
# 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,.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)
}
```
# Debug and test-run primary function
```{bash, eval=F}
cd /home/jj332_cas/marnin/implementGMSinCassava/;
export PATH=/programs/R-4.0.5clean-p/bin:$PATH;
# for a 112 core machine. Use ncores=20 below
export OMP_NUM_THREADS=5;
screen;
R # initiate R session
```
```{r primary test inputs}
require(tidyverse); require(magrittr);
# SOURCE CORE FUNCTIONS
# source(here::here("code","parentWiseCrossVal.R"))
source(here::here("code","predCrossVar.R"))
# PEDIGREE
ped<-read.table(here::here("output","verified_ped.txt"),
header = T, stringsAsFactors = F) %>%
rename(GID=FullSampleName,
damID=DamID,
sireID=SireID) %>%
dplyr::select(GID,sireID,damID)
# Keep only families with _at least_ 2 offspring
ped %<>%
semi_join(ped %>% count(sireID,damID) %>% filter(n>1) %>% ungroup())
# BLUPs
blups<-readRDS(file=here::here("data","blups_forCrossVal.rds")) %>%
dplyr::select(-varcomp)
# GENOMIC RELATIONSHIP MATRICES (GRMS)
grms<-list(A=readRDS(file=here::here("output","kinship_A_IITA_2021May13.rds")),
D=readRDS(file=here::here("output","kinship_D_IITA_2021May13.rds")))
# DOSAGE MATRIX
dosages<-readRDS(file=here::here("data",
"dosages_IITA_filtered_2021May13.rds"))
# RECOMBINATION FREQUENCY MATRIX
recombFreqMat<-readRDS(file=here::here("data",
"recombFreqMat_1minus2c_2021May13.rds"))
# HAPLOTYPE MATRIX
## keep only haplos for parents-in-the-pedigree
## those which will be used in prediction, saves memory
haploMat<-readRDS(file=here::here("data","haps_IITA_filtered_2021May13.rds"))
parents<-union(ped$sireID,ped$damID)
parenthaps<-sort(c(paste0(parents,"_HapA"),
paste0(parents,"_HapB")))
haploMat<-haploMat[parents,colnames(recombFreqMat)]
# SELECTION INDEX WEIGHTS
## from IYR+IK
## note that not ALL predicted traits are on index
SIwts<-c(logFYLD=20,
HI=10,
DM=15,
MCMDS=-10,
logRTNO=12,
logDYLD=20,
logTOPYLD=15,
PLTHT=10)
# SET-UP TEST WEIGHT INPUTS
blups %<>% slice(1:2)
SIwts<-c(DM=15,
MCMDS=-10)
```
```{r functions to source}
makeParentFolds<-function(ped,gid,nrepeats=5,nfolds=5,seed=NULL){
require(rsample)
set.seed(seed)
parentfolds<-rsample::vfold_cv(tibble(Parents=union(ped$sireID,
ped$damID)),
v = nfolds,repeats = nrepeats) %>%
mutate(folds=map(splits,function(splits){
#splits<-parentfolds$splits[[1]]
testparents<-testing(splits)$Parents
trainparents<-training(splits)$Parents
ped<-ped %>%
rename(gid=!!sym(gid))
offspring<-ped %>%
filter(sireID %in% testparents | damID %in% testparents) %$%
unique(gid)
grandkids<-ped %>%
filter(sireID %in% offspring | damID %in% offspring) %$%
unique(gid)
greatX1grandkids<-ped %>%
filter(sireID %in% grandkids | damID %in% grandkids) %$%
unique(gid)
greatX2grandkids<-ped %>%
filter(sireID %in% greatX1grandkids |
damID %in% greatX1grandkids) %$%
unique(gid)
greatX3grandkids<-ped %>%
filter(sireID %in% greatX2grandkids |
damID %in% greatX2grandkids) %$%
unique(gid)
greatX4grandkids<-ped %>%
filter(sireID %in% greatX3grandkids |
damID %in% greatX3grandkids) %$%
unique(gid)
testset<-unique(c(offspring,
grandkids,
greatX1grandkids,
greatX2grandkids,
greatX3grandkids,
greatX4grandkids)) %>%
.[!. %in% c(testparents,trainparents)]
nontestdescendents<-ped %>%
filter(!gid %in% testset) %$%
unique(gid)
trainset<-union(testparents,trainparents) %>%
union(.,nontestdescendents)
out<-tibble(testparents=list(testparents),
trainset=list(trainset),
testset=list(testset))
return(out) })) %>%
unnest(folds)
if(nrepeats>1){
parentfolds %<>%
rename(Repeat=id,Fold=id2) %>%
select(-splits)
}
if(nrepeats==1){
parentfolds %<>%
mutate(Repeat="Repeat1") %>%
rename(Fold=id) %>%
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),
sireID %in% . | damID %in% .)))
return(parentfolds)
}
getMarkEffs<-function(parentfolds,blups,gid,modelType,grms,dosages,ncores){
traintestdata<-parentfolds %>%
dplyr::select(Repeat,Fold,trainset,testset) %>%
pivot_longer(c(trainset,testset),
names_to = "Dataset",
values_to = "sampleIDs") %>%
crossing(Trait=blups$Trait) %>%
left_join(blups) %>%
rename(blupsMat=blups)
## For each training/testing chunk of sampleIDs and each trait
## fit GBLUP model and backsolve SNP-effects
fitModel<-function(sampleIDs,blupsMat,modelType,gid,grms,dosages,...){
# debug
# sampleIDs<-traintestdata$sampleIDs[[2]]; blups<-traintestdata$blups[[2]]
require(predCrossVar)
A<-grms[["A"]]
if(modelType %in% c("AD")){ D<-grms[["D"]] }
trainingdata<-blupsMat %>%
dplyr::rename(gid=!!sym(gid)) %>%
filter(gid %in% sampleIDs)
trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[["gid"]],
levels=rownames(A))
if(modelType %in% c("AD")){
trainingdata[[paste0(gid,"d")]]<-trainingdata[[paste0(gid,"a")]]
}
# Set-up random model statements
randFormula<-paste0("~vs(",gid,"a,Gu=A)")
if(modelType %in% c("AD")){
randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D)")
}
# Fit genomic prediction model
require(sommer)
fit <- sommer::mmer(fixed = drgBLUP ~1,
random = as.formula(randFormula),
weights = WT,
data=trainingdata)
# Gather the GBLUPs
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")){
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
ga<-as.matrix(fit$U[[paste0("u:",gid,"a")]]$drgBLUP,ncol=1)
addsnpeff<-backsolveSNPeff(Z=centerDosage(dosages),g=ga)
if(modelType %in% c("AD")){
gd<-as.matrix(fit$U[[paste0("u:",gid,"d")]]$drgBLUP,ncol=1)
domsnpeff<-backsolveSNPeff(Z=dose2domDev(dosages),g=gd)
}
# Extract variance components
varcomps<-summary(fit)$varcomp
results<-tibble(gblups=list(gblups),
varcomps=list(varcomps),
addsnpeff=list(addsnpeff))
if(modelType %in% c("AD")){
results %<>%
mutate(domsnpeff=list(domsnpeff)) }
# return results
return(results)
}
require(furrr); options(mc.cores=ncores); plan(multicore)
options(future.globals.maxSize=50000*1024^2)
options(future.rng.onMisuse="ignore")
traintestdata<-traintestdata %>%
mutate(modelOut=future_pmap(.,fitModel,
modelType=modelType,
gid=gid,
grms=grms,
dosages=dosages),
modelType=modelType)
traintestdata %<>%
select(-blupsMat,-sampleIDs) %>%
unnest(modelOut) %>%
nest(effects=c(Trait,gblups,varcomps,addsnpeff,domsnpeff))
# this is to remove conflicts with dplyr function select() downstream
# detach("package:sommer",unload = T); detach("package:MASS",unload = T)
return(traintestdata)
}
predictCrossVars<-function(modelType,snpeffs,parentfolds,
haploMat,recombFreqMat,ncores){
predvars<-snpeffs %>%
unnest(effects) %>%
filter(Dataset=="trainset") %>%
dplyr::select(Repeat,Fold,Trait,modelType,
any_of(c("addsnpeff","domsnpeff"))) %>%
nest(EffectList=c(Trait,any_of(c("addsnpeff","domsnpeff")))) %>%
mutate(AddEffectList=map(EffectList,
function(EffectList){
addsnpeff<-map(EffectList$addsnpeff,~t(.))
names(addsnpeff)<-EffectList$Trait
return(addsnpeff)}))
if(modelType %in% c("AD")){
predvars<-predvars %>%
mutate(DomEffectList=map(EffectList,
function(EffectList){
domsnpeff<-map(EffectList$domsnpeff,~t(.))
names(domsnpeff)<-EffectList$Trait
return(domsnpeff) })) }
predvars %<>%
left_join(parentfolds %>%
dplyr::select(-testparents,-trainset,-testset)) %>%
dplyr::select(-EffectList)
require(furrr); options(future.globals.maxSize=40000*1024^2)
if(modelType=="A"){
predvars<-predvars %>%
mutate(predVars=map2(CrossesToPredict,AddEffectList,
~predCrossVars(CrossesToPredict=.x,
AddEffectList=.y,
modelType=modelType,
haploMat=haploMat,
recombFreqMat=recombFreqMat,
ncores=ncores))) }
if(modelType=="AD"){
predvars<-predvars %>%
mutate(predVars=pmap(.,function(CrossesToPredict,
AddEffectList,DomEffectList,...){
out<-predCrossVars(CrossesToPredict=CrossesToPredict,
AddEffectList=AddEffectList,
DomEffectList=DomEffectList,
modelType=modelType,
haploMat=haploMat,
recombFreqMat=recombFreqMat,
ncores=ncores)
return(out) })) }
predvars %<>% select(-AddEffectList,-DomEffectList,-CrossesToPredict)
return(predvars)