-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-CrossValidation.Rmd
694 lines (617 loc) · 29.1 KB
/
04-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
---
title: "Check prediction accuracy"
author: "wolfemd"
date: "2019-7-27"
output: workflowr::wflow_html
editor_options:
chunk_output_type: inline
---
```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = F, tidy = T)
```
# Previous step
3. [Get BLUPs combining all trial data](03-GetBLUPs.html): Combine data from all trait-trials to get BLUPs for downstream genomic prediction.
# Objective
**Current Step:**
4. [Check prediction accuracy](04-CrossValidation.html): Evaluate prediction accuracy with cross-validation.
5-fold cross-validation. Replicate 5-times.
3 genomic models:
1. Additive-only (**A**)
2. Additive plus dominance (**AD**)
3. Addtitive plus dominance plus epistasis (**ADE**)
# Prep. genomic data
## Get SNP data from FTP
The data for the next step can be found on the cassavabase FTP server [here](ftp://ftp.cassavabase.org/marnin_datasets/NGC_BigData/).
Can be loaded directly to R from FTP.
**NOTICE:** You need enough RAM and a stable network connection. I do the next steps, including cross-validation on a server with plenty of RAM and a good, stable network connection, rather than on my personal computer (a laptop with 16 GB RAM).
The outputs (kinship matrices and filtered snp dosages) of the steps below, which are too large for GitHub, can be found on the cassavabase FTP server [here](ftp://ftp.cassavabase.org/marnin_datasets/NRCRI_2020GS/).
```{bash, eval=F}
# activate multithread OpenBLAS for fast compute of SigmaM (genotypic var-covar matrix)
export OMP_NUM_THREADS=56
```
```{r, eval=F}
library(tidyverse); library(magrittr);
snps<-readRDS(file=url(paste0("ftp://ftp.cassavabase.org/marnin_datasets/NGC_BigData/",
"DosageMatrix_RefPanelAndGSprogeny_ReadyForGP_73019.rds")))
#rm(list=(ls() %>% grep("snps",.,value = T, invert = T)))
```
```{r, eval=F}
blups_nrcri<-readRDS(file=here::here("output","nrcri_blupsForModelTraining_2020April27.rds"))
blups_nrcri<-blups_nrcri %>%
select(Trait,modelOutput) %>%
unnest(modelOutput) %>%
select(Trait,BLUPs) %>%
unnest(BLUPs) %>%
filter(GID %in% rownames(snps))
table(unique(blups_nrcri$GID) %in% rownames(snps)) # 2879!
blups_iita<-readRDS(file=here::here("data","iita_blupsForCrossVal_outliersRemoved_73019.rds"))
blups_iita<-blups_iita %>%
select(Trait,blups) %>%
unnest(blups) %>%
select(-`std error`) %>%
filter(GID %in% rownames(snps),
!grepl("TMS13F|TMS14F|TMS15F|2013_",GID)) # don't want IITA GS progenies
table(unique(blups_iita$GID) %in% rownames(snps)) # 1228
union(blups_nrcri$GID,blups_iita$GID) %>% grep("c2",.,value = T,ignore.case = T)
```
```{r, eval=F}
samples2Keep<-union(blups_nrcri$GID,blups_iita$GID) %>%
union(.,grep("c2",rownames(snps),value = T, ignore.case = T))
table(rownames(snps) %in% union(blups_nrcri$GID,blups_iita$GID)) # 3740
length(samples2Keep) # 7062
snps<-snps[samples2Keep,]
```
## MAF>1% filter
```{r maf_filter, eval=F}
maf_filter<-function(snps,thresh){
freq<-colMeans(snps, na.rm=T)/2; maf<-freq;
maf[which(maf > 0.5)]<-1-maf[which(maf > 0.5)]
snps1<-snps[,which(maf>thresh)];
return(snps1) }
```
```{r, eval=F}
snps %<>% maf_filter(.,0.01)
dim(snps) # [1] 7062 68587
```
## Make Add, Dom and Epi kinships
Going to use my own kinship function b/c I trust it's dominance matrix calculation.
```{r kinship function, eval=F}
#' kinship function
#'
#' Function to create additive and dominance genomic relationship matrices from biallelic dosages.
#'
#' @param M dosage matrix. Assumes SNPs in M coded 0, 1, 2 (requires rounding dosages to integers). M is Nind x Mrow, numeric matrix, with row/columanes to indicate SNP/ind ID.
#' @param type string, "add" or "dom". type="add" gives same as rrBLUP::A.mat(), i.e. Van Raden, Method 1. type="dom" gives classical parameterization according to Vitezica et al. 2013.
#'
#' @return square symmetic genomic relationship matrix
#' @export
#'
#' @examples
#' K<-kinship(M,"add")
kinship<-function(M,type){
M<-round(M)
freq <- colMeans(M,na.rm=T)/2
P <- matrix(rep(freq,nrow(M)),byrow=T,ncol=ncol(M))
if(type=="add"){
Z <- M-2*P
varD<-sum(2*freq*(1-freq))
K <- tcrossprod(Z)/ varD
return(K)
}
if(type=="dom"){
W<-M;
W[which(W==1)]<-2*P[which(W==1)];
W[which(W==2)]<-(4*P[which(W==2)]-2);
W <- W-2*(P^2)
varD<-sum((2*freq*(1-freq))^2)
D <- tcrossprod(W) / varD
return(D)
}
}
```
Make the kinships.
Below e.g. `A*A` makes a matrix that approximates additive-by-additive epistasis relationships.
```{r, eval=F}
A<-kinship(snps,type="add")
D<-kinship(snps,type="dom")
AA<-A*A
AD<-A*D
DD<-D*D
saveRDS(snps,file=here::here("output","DosageMatrix_NRCRI_SamplesForGP_2020April27.rds"))
saveRDS(A,file=here::here("output","Kinship_A_NRCRI_2020April27.rds"))
saveRDS(D,file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
saveRDS(AA,file=here::here("output","Kinship_AA_NRCRI_2020April27.rds"))
saveRDS(AD,file=here::here("output","Kinship_AD_NRCRI_2020April27.rds"))
saveRDS(DD,file=here::here("output","Kinship_DD_NRCRI_2020April27.rds"))
#rm(snps); gc()
```
**NOTICE:** The outputs (kinship matrices and filtered snp dosages) of the steps below, which are too large for GitHub, can be found on the cassavabase FTP server [here](ftp://ftp.cassavabase.org/marnin_datasets/NRCRI_2020GS/).
# Cross-validation
```{bash, eval=F}
# activate multithread OpenBLAS
export OMP_NUM_THREADS=48
#export OMP_NUM_THREADS=88
#export OMP_NUM_THREADS=88
```
## Set-up training-testing data
```{r, eval=F}
rm(list=ls())
library(tidyverse); library(magrittr);
A<-readRDS(file=here::here("output","Kinship_A_NRCRI_2020April27.rds"))
blups_iita<-readRDS(file=here::here("data","iita_blupsForCrossVal_outliersRemoved_73019.rds"))
blups_iita<-blups_iita %>%
dplyr::select(Trait,blups) %>%
unnest(blups) %>%
dplyr::select(-`std error`) %>%
filter(GID %in% rownames(A),
!grepl("TMS13F|TMS14F|TMS15F|2013_",GID)) # don't want IITA GS progenies
blups_nrcri<-readRDS(file=here::here("output","nrcri_blupsForModelTraining_2020April27.rds"))
blups_nrcri<-blups_nrcri %>%
dplyr::select(Trait,modelOutput) %>%
unnest(modelOutput) %>%
dplyr::select(Trait,BLUPs) %>%
unnest(BLUPs) %>%
filter(GID %in% rownames(A))
# Set-up a grouping variable for:
## nrTP, C1a, C1b and C2a.
## Nest by Trait.
c1a<-blups_nrcri$GID %>%
unique %>%
grep("c1a",.,value = T,ignore.case = T) %>%
union(.,blups_nrcri$GID %>% unique %>%
grep("^F",.,value = T,ignore.case = T) %>%
grep("c1b",.,value = T,ignore.case = T,invert = T))
c1b<-blups_nrcri$GID %>% unique %>% grep("c1b",.,value = T,ignore.case = T)
c2a<-blups_nrcri$GID %>% unique %>%
grep("C2a|C2b",.,value = T,ignore.case = T) %>%
grep("NR17",.,value = T,ignore.case = T)
nrTP<-setdiff(unique(blups_nrcri$GID),unique(c(c1a,c1b,c2a)))
cv2do<-blups_nrcri %>%
mutate(Group=ifelse(GID %in% nrTP,"nrTP",
ifelse(GID %in% c1a,"C1a",
ifelse(GID %in% c1b, "C1b",
ifelse(GID %in% c2a,"C2a",NA))))) %>%
nest(TrainTestData=-Trait) %>%
left_join(blups_iita %>%
nest(augmentTP=-Trait))
cv2do$TrainTestData[[6]] %>%
count(Group)
```
```{r, eval=F}
# test arguments to function
# ----------------------
## Test 1 (additive only, no augmentTP)
# TrainTestData<-cv2do_nrAlone$TrainTestData[[1]]
# nrepeats<-1
# nfolds<-2
# ncores<-1
# gid<-"GID"
# byGroup<-TRUE
# modelType<-"A"
# grms<-list(A=A)
# augmentTP<-NULL
#
# ## Test 2 (additive + dominance , no augmentTP)
# TrainTestData<-cv2do_nrAlone$TrainTestData[[10]]
# nrepeats<-1
# nfolds<-2
# ncores<-1
# gid<-"GID"
# byGroup<-TRUE
# modelType<-"AD"
# grms<-list(A=A,D=D)
# augmentTP<-NULL
# splits<-cvsamples$splits[[1]]
# GroupName<-cvsamples$GroupName[[1]]
# ----------------------
```
The function below implements nfold cross-validation. Specifically, for each of **nrepeats** it splits the data into **nfolds** sets according to **gid**. So if `nfolds=5` then the the clones will be divided into 5 groups and 5 predictions will be made. In each prediction, 4/5 of the clones will be used to predict the remaining 1/5. Accuracy of the model is measured as the correlation between the BLUPs (adj. mean for each CLONE) in the _test set_ and the GEBV (the prediction made of each clone when it was in the test set).
## The ultimate runCrossVal func
```{r runCrossVal, eval=F}
#' @param byGroup logical, if TRUE, assumes a column named "Group" is present which unique classifies each GID into some genetic grouping.
#' @param modelType string, A, AD or ADE representing model with Additive-only, Add. plus Dominance, and Add. plus Dom. plus. Epistasis (AA+AD+DD), respectively.
#' @param grms list of GRMs where each element is named either A, D, AA, AD, DD. Matrices supplied must match required by A, AD and ADE models. For ADE grms=list(A=A,D=D,AA=AA,AD=AD,DD=DD)...
#' @param augmentTP option to supply an additional set of training data, which will be added to each training model but never included in the test set.
#' @param TrainTestData data.frame with de-regressed BLUPs, BLUPs and weights (WT) for training and test. If byGroup==TRUE, a column with Group as the header uniquely classifying GIDs into genetic groups, is expected.
runCrossVal<-function(TrainTestData,modelType,grms,nrepeats,nfolds,ncores=1,
byGroup=FALSE,augmentTP=NULL,gid="GID",...){
require(sommer); require(rsample)
# Set-up replicated cross-validation folds
# splitting by clone (if clone in training dataset, it can't be in testing)
if(byGroup){
cvsamples<-tibble(GroupName=unique(TrainTestData$Group))
} else { cvsamples<-tibble(GroupName="None") }
cvsamples<-cvsamples %>%
mutate(Splits=map(GroupName,function(GroupName){
if(GroupName!="None"){
thisgroup<-TrainTestData %>%
filter(Group==GroupName) } else { thisgroup<-TrainTestData }
out<-tibble(repeats=1:nrepeats,
splits=rerun(nrepeats,group_vfold_cv(thisgroup, group = gid, v = nfolds))) %>%
unnest(splits)
return(out)
})) %>%
unnest(Splits)
## Internal function
## fits prediction model and calcs. accuracy for each train-test split
fitModel<-possibly(function(splits,modelType,augmentTP,TrainTestData,GroupName,grms){
starttime<-proc.time()[3]
# Set-up training set
trainingdata<-training(splits)
## Make sure, if there is an augmentTP, no GIDs in test-sets
if(!is.null(augmentTP)){
## remove any test-set members from augment TP before adding to training data
training_augment<-augmentTP %>% filter(!(!!sym(gid) %in% testing(splits)[[gid]]))
trainingdata<-bind_rows(trainingdata,training_augment) }
if(GroupName!="None"){ trainingdata<-bind_rows(trainingdata,
TrainTestData %>%
filter(Group!=GroupName,
!(!!sym(gid) %in% testing(splits)[[gid]]))) }
# Subset kinship matrices
traintestgids<-union(trainingdata[[gid]],testing(splits)[[gid]])
A1<-grms[["A"]][traintestgids,traintestgids]
trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[[gid]],levels=rownames(A1))
if(modelType %in% c("AD","ADE")){
D1<-grms[["D"]][traintestgids,traintestgids]
trainingdata[[paste0(gid,"d")]]<-factor(trainingdata[[gid]],levels=rownames(D1))
if(modelType=="ADE"){
AA1<-grms[["AA"]][traintestgids,traintestgids]
AD1<-grms[["AD"]][traintestgids,traintestgids]
DD1<-grms[["DD"]][traintestgids,traintestgids]
trainingdata[[paste0(gid,"aa")]]<-factor(trainingdata[[gid]],levels=rownames(AA1))
trainingdata[[paste0(gid,"ad")]]<-factor(trainingdata[[gid]],levels=rownames(AD1))
trainingdata[[paste0(gid,"dd")]]<-factor(trainingdata[[gid]],levels=rownames(DD1))
}
}
# Set-up random model statements
randFormula<-paste0("~vs(",gid,"a,Gu=A1)")
if(modelType %in% c("AD","ADE")){
randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D1)")
if(modelType=="ADE"){
randFormula<-paste0(randFormula,
"+vs(",gid,"aa,Gu=AA1)",
"+vs(",gid,"ad,Gu=AD1)",
"+vs(",gid,"dd,Gu=DD1)")
}
}
# Fit genomic prediction model
fit <- mmer(fixed = drgBLUP ~1,
random = as.formula(randFormula),
weights = WT,
data=trainingdata)
# Gather the BLUPs
gblups<-tibble(GID=as.character(names(fit$U[[paste0("u:",gid,"a")]]$drgBLUP)),
GEBV=as.numeric(fit$U[[paste0("u:",gid,"a")]]$drgBLUP))
if(modelType %in% c("AD","ADE")){
gblups %<>% mutate(GEDD=as.numeric(fit$U[[paste0("u:",gid,"d")]]$drgBLUP))
if(modelType=="ADE"){
gblups %<>% mutate(GEEDaa=as.numeric(fit$U[[paste0("u:",gid,"aa")]]$drgBLUP),
GEEDad=as.numeric(fit$U[[paste0("u:",gid,"ad")]]$drgBLUP),
GEEDdd=as.numeric(fit$U[[paste0("u:",gid,"dd")]]$drgBLUP))
}
}
# Calc GETGVs
## Note that for modelType=="A", GEBV==GETGV
gblups %<>%
mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))]))
# Test set validation data
validationData<-TrainTestData %>%
dplyr::select(gid,BLUP) %>%
filter(GID %in% testing(splits)[[gid]])
# Measure accuracy in test set
## cor(GEBV,BLUP)
## cor(GETGV,BLUP)
accuracy<-gblups %>%
mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))])) %>%
filter(GID %in% testing(splits)[[gid]]) %>%
left_join(validationData) %>%
summarize(accGEBV=cor(GEBV,BLUP, use = 'complete.obs'),
accGETGV=cor(GETGV,BLUP, use = 'complete.obs'))
computeTime<-proc.time()[3]-starttime
accuracy %<>% mutate(computeTime=computeTime)
return(accuracy)
},otherwise = NA)
## Run models across all train-test splits
## Parallelize
require(furrr); plan(multiprocess); options(mc.cores=ncores);
cvsamples<-cvsamples %>%
mutate(accuracy=future_map2(splits,GroupName,
~fitModel(splits=.x,GroupName=.y,
modelType=modelType,augmentTP=NULL,TrainTestData=TrainTestData,grms=grms),
.progress = FALSE)) %>%
unnest(accuracy)
return(cvsamples)
}
```
Run some tests of the function...
```{r, eval=F}
# options(future.globals.maxSize= 1500*1024^2)
# test_cv_ad_yield<-runCrossVal(TrainTestData=cv2do$TrainTestData[[8]],
# modelType="AD",
# grms=list(A=A,D=D),
# byGroup=TRUE,augmentTP=NULL,
# nrepeats=1,nfolds=2,ncores=2,gid="GID")
#
# TrainTestData<-cv2do %>% filter(Trait=="logFYLD") %$% TrainTestData[[1]]
# augmentTP<-cv2do %>% filter(Trait=="logFYLD") %$% augmentTP[[1]]
# test_cv_a_augment<-runCrossVal(TrainTestData=TrainTestData,
# modelType="A",
# grms=list(A=A),
# byGroup=TRUE,augmentTP=augmentTP,
# nrepeats=1,nfolds=2,ncores=2,gid="GID")
# test_cv_a_noaug<-runCrossVal(TrainTestData=TrainTestData,
# modelType="A",
# grms=list(A=A),
# byGroup=TRUE,augmentTP=NULL,
# nrepeats=1,nfolds=2,ncores=2,gid="GID")
```
## CV - modelType="A":
### NRCRI alone
cbsulm13 (96 cores; 512GB RAM)
```{r cbsulm13, eval=F}
cv_A_nrOnly<-cv2do %>%
mutate(CVresults=map(TrainTestData,~runCrossVal(TrainTestData=.,
modelType="A",
grms=list(A=A),
byGroup=TRUE,augmentTP=NULL,
nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_A_nrOnly %<>% mutate(Dataset="NRalone",modelType="A") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_A_nrOnly,file=here::here("output","cvresults_A_nrOnly.rds"))
```
### IITA augmented
cbsulm18 (88 cores; 512GB)
For this one, try with `ncores=1` instead of `ncores=10`.
```{r, eval=F}
cv_A_iitaAugmented<-cv2do %>%
mutate(isnullAugment=map_lgl(augmentTP,~is.null(.))) %>%
filter(!isnullAugment) %>%
select(-isnullAugment) %>%
mutate(CVresults=map2(TrainTestData,augmentTP,~runCrossVal(TrainTestData=.x,
modelType="A",
grms=list(A=A),
byGroup=TRUE,augmentTP=.y,
nrepeats=5,nfolds=5,ncores=1,gid="GID")))
cv_A_iitaAugmented %<>% mutate(Dataset="IITAaugmented",modelType="A") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_A_iitaAugmented,file=here::here("output","cvresults_A_iitaAugmented.rds"))
```
## CV - modelType="AD":
### NRCRI alone
cbsulm15 (96 cores; 512GB RAM)
```{r cbsulm15, eval=F}
options(future.globals.maxSize= 1500*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
cv_AD_nrOnly<-cv2do %>%
mutate(CVresults=map(TrainTestData,~runCrossVal(TrainTestData=.,
modelType="AD",
grms=list(A=A,D=D),
byGroup=TRUE,augmentTP=NULL,
nrepeats=5,nfolds=5,ncores=4,gid="GID")))
cv_AD_nrOnly %<>% mutate(Dataset="NRalone",modelType="AD") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_AD_nrOnly,file=here::here("output","cvresults_AD_nrOnly.rds"))
```
### IITA augmented
cbsulm13 (96 cores; 512GB RAM)
```{r, eval=F}
options(future.globals.maxSize= 1500*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
cv_AD_iitaAugmented<-cv2do %>%
mutate(isnullAugment=map_lgl(augmentTP,~is.null(.))) %>%
filter(!isnullAugment) %>%
dplyr::select(-isnullAugment) %>%
mutate(CVresults=map2(TrainTestData,augmentTP,~runCrossVal(TrainTestData=.x,
modelType="AD",
grms=list(A=A,D=D),
byGroup=TRUE,augmentTP=.y,
nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_AD_iitaAugmented %<>% mutate(Dataset="IITAaugmented",modelType="AD") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_AD_iitaAugmented,file=here::here("output","cvresults_AD_iitaAugmented.rds"))
```
## CV - modelType="ADE":
### NRCRI alone
cbsulm15 (96 cores; 512GB RAM)
```{r runCrossVal_dev, eval=F}
runCrossVal_dev<-function(TrainTestData,modelType,grms,nrepeats,nfolds,ncores=1,
byGroup=FALSE,augmentTP=NULL,gid="GID",...){
require(sommer); require(rsample)
# Set-up replicated cross-validation folds
# splitting by clone (if clone in training dataset, it can't be in testing)
if(byGroup){
cvsamples<-tibble(GroupName=unique(TrainTestData$Group))
} else { cvsamples<-tibble(GroupName="None") }
cvsamples<-cvsamples %>%
mutate(Splits=map(GroupName,function(GroupName){
if(GroupName!="None"){
thisgroup<-TrainTestData %>%
filter(Group==GroupName) } else { thisgroup<-TrainTestData }
out<-tibble(repeats=1:nrepeats,
splits=rerun(nrepeats,group_vfold_cv(thisgroup, group = gid, v = nfolds))) %>%
unnest(splits)
return(out)
})) %>%
unnest(Splits)
## Internal function
## fits prediction model and calcs. accuracy for each train-test split
fitModel<-possibly(function(splits,modelType,augmentTP,TrainTestData,GroupName,grms){
starttime<-proc.time()[3]
# Set-up training set
trainingdata<-training(splits)
## Make sure, if there is an augmentTP, no GIDs in test-sets
if(!is.null(augmentTP)){
## remove any test-set members from augment TP before adding to training data
training_augment<-augmentTP %>% filter(!(!!sym(gid) %in% testing(splits)[[gid]]))
trainingdata<-bind_rows(trainingdata,training_augment) }
if(GroupName!="None"){ trainingdata<-bind_rows(trainingdata,
TrainTestData %>%
filter(Group!=GroupName,
!(!!sym(gid) %in% testing(splits)[[gid]]))) }
# Subset kinship matrices
traintestgids<-union(trainingdata[[gid]],testing(splits)[[gid]])
A1<-grms[["A"]][traintestgids,traintestgids]
trainingdata[[paste0(gid,"a")]]<-factor(trainingdata[[gid]],levels=rownames(A1))
if(modelType %in% c("AD","ADE")){
D1<-grms[["D"]][traintestgids,traintestgids]
trainingdata[[paste0(gid,"d")]]<-factor(trainingdata[[gid]],levels=rownames(D1))
if(modelType=="ADE"){
#AA1<-grms[["AA"]][traintestgids,traintestgids]
AD1<-grms[["AD"]][traintestgids,traintestgids]
diag(AD1)<-diag(AD1)+1e-06
#DD1<-grms[["DD"]][traintestgids,traintestgids]
#trainingdata[[paste0(gid,"aa")]]<-factor(trainingdata[[gid]],levels=rownames(AA1))
trainingdata[[paste0(gid,"ad")]]<-factor(trainingdata[[gid]],levels=rownames(AD1))
#trainingdata[[paste0(gid,"dd")]]<-factor(trainingdata[[gid]],levels=rownames(DD1))
}
}
# Set-up random model statements
randFormula<-paste0("~vs(",gid,"a,Gu=A1)")
if(modelType %in% c("AD","ADE")){
randFormula<-paste0(randFormula,"+vs(",gid,"d,Gu=D1)")
if(modelType=="ADE"){
randFormula<-paste0(randFormula,"+vs(",gid,"ad,Gu=AD1)")
#"+vs(",gid,"aa,Gu=AA1)",
#"+vs(",gid,"ad,Gu=AD1)")
#"+vs(",gid,"dd,Gu=DD1)")
}
}
# Fit genomic prediction model
fit <- mmer(fixed = drgBLUP ~1,
random = as.formula(randFormula),
weights = WT,
data=trainingdata)
# Gather the BLUPs
gblups<-tibble(GID=as.character(names(fit$U[[paste0("u:",gid,"a")]]$drgBLUP)),
GEBV=as.numeric(fit$U[[paste0("u:",gid,"a")]]$drgBLUP))
if(modelType %in% c("AD","ADE")){
gblups %<>% mutate(GEDD=as.numeric(fit$U[[paste0("u:",gid,"d")]]$drgBLUP))
if(modelType=="ADE"){
gblups %<>% mutate(#GEEDaa=as.numeric(fit$U[[paste0("u:",gid,"aa")]]$drgBLUP),
GEEDad=as.numeric(fit$U[[paste0("u:",gid,"ad")]]$drgBLUP))
#GEEDdd=as.numeric(fit$U[[paste0("u:",gid,"dd")]]$drgBLUP))
}
}
# Calc GETGVs
## Note that for modelType=="A", GEBV==GETGV
gblups %<>%
mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))]))
# Test set validation data
validationData<-TrainTestData %>%
dplyr::select(gid,BLUP) %>%
filter(GID %in% testing(splits)[[gid]])
# Measure accuracy in test set
## cor(GEBV,BLUP)
## cor(GETGV,BLUP)
accuracy<-gblups %>%
mutate(GETGV=rowSums(.[,grepl("GE",colnames(.))])) %>%
filter(GID %in% testing(splits)[[gid]]) %>%
left_join(validationData) %>%
summarize(accGEBV=cor(GEBV,BLUP, use = 'complete.obs'),
accGETGV=cor(GETGV,BLUP, use = 'complete.obs'))
computeTime<-proc.time()[3]-starttime
accuracy %<>% mutate(computeTime=computeTime)
return(accuracy)
},otherwise = NA)
## Run models across all train-test splits
## Parallelize
require(furrr); plan(multiprocess); options(mc.cores=ncores);
cvsamples<-cvsamples %>%
mutate(accuracy=future_map2(splits,GroupName,
~fitModel(splits=.x,GroupName=.y,
modelType=modelType,augmentTP=NULL,TrainTestData=TrainTestData,grms=grms),
.progress = FALSE)) %>%
unnest(accuracy)
return(cvsamples)
}
```
```{r, eval=F}
options(future.globals.maxSize= 3000*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
#AA<-readRDS(file=here::here("output","Kinship_AA_NRCRI_2020April27.rds"))
AD<-readRDS(file=here::here("output","Kinship_AD_NRCRI_2020April27.rds"))
#DD<-readRDS(file=here::here("output","Kinship_DD_NRCRI_2020April27.rds"))
cv_ADE_nrOnly<-cv2do %>%
mutate(CVresults=map(TrainTestData,~runCrossVal_dev(TrainTestData=.,
modelType="ADE",
grms=list(A=A,D=D,AD=AD),
#grms=list(A=A,D=D,AA=AA,AD=AD,DD=DD), # test with all kernels failed
byGroup=TRUE,augmentTP=NULL,
nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_ADE_nrOnly %<>% mutate(Dataset="NRalone",modelType="ADE") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_ADE_nrOnly,file=here::here("output","cvresults_ADE_nrOnly.rds"))
```
### IITA augmented
```{r cbsulm18, eval=F}
options(future.globals.maxSize= 3000*1024^2)
D<-readRDS(file=here::here("output","Kinship_D_NRCRI_2020April27.rds"))
AD<-readRDS(file=here::here("output","Kinship_AD_NRCRI_2020April27.rds"))
cv_ADE_iitaAugmented<-cv2do %>%
mutate(isnullAugment=map_lgl(augmentTP,~is.null(.))) %>%
filter(!isnullAugment) %>%
dplyr::select(-isnullAugment) %>%
mutate(CVresults=map2(TrainTestData,augmentTP,~runCrossVal_dev(TrainTestData=.x,
modelType="ADE",
grms=list(A=A,D=D,AD=AD),
byGroup=TRUE,augmentTP=.y,
nrepeats=5,nfolds=5,ncores=10,gid="GID")))
cv_ADE_iitaAugmented %<>% mutate(Dataset="IITAaugmented",modelType="ADE") %>% dplyr::select(-TrainTestData,-augmentTP)
saveRDS(cv_ADE_iitaAugmented,file=here::here("output","cvresults_ADE_iitaAugmented.rds"))
```
## PLOT RESULTS
```{r}
rm(list=ls());gc()
library(tidyverse); library(magrittr);
cv<-readRDS(here::here("output","cvresults_A_iitaAugmented.rds")) %>%
bind_rows(readRDS(here::here("output","cvresults_A_nrOnly.rds"))) %>%
bind_rows(readRDS(here::here("output","cvresults_AD_nrOnly.rds"))) %>%
bind_rows(readRDS(here::here("output","cvresults_AD_iitaAugmented.rds"))) %>%
bind_rows(readRDS(here::here("output","cvresults_ADE_nrOnly.rds"))) %>%
bind_rows(readRDS(here::here("output","cvresults_ADE_iitaAugmented.rds"))) %>%
unnest(CVresults) %>%
select(-splits)
```
### Accuracy GEBV
```{r, fig.width=10, fig.height=8}
#library(viridis)
library(tidyverse); library(magrittr);
cv %>%
mutate(GroupName=factor(GroupName,levels=c("nrTP","C1a","C1b","C2a")),
Dataset=factor(Dataset,levels=c("NRalone","IITAaugmented")),
modelType=factor(modelType,levels=c("A","AD","ADE"))) %>%
ggplot(.,aes(x=Dataset,y=accGEBV,fill=modelType,linetype=Dataset)) +
geom_boxplot(position = position_dodge(1),width=0.75,color='gray',size=0.75) +
facet_grid(GroupName~Trait, scales='free') +
theme_bw() +
theme(strip.text.x = element_text(face='bold', size=12),
axis.text.x = element_text(size=10, angle = 90),
axis.title.y = element_text(face='bold', size=12)) +
scale_fill_viridis_d() +
#scale_color_manual(values = c("gray","gold")) +
labs(title="Cross-validated Prediction Accuracy (GEBVs)") +
geom_hline(yintercept = 0, color='darkred')
```
### Accuracy GETGV
```{r, fig.width=10, fig.height=8}
#library(viridis)
library(tidyverse); library(magrittr);
cv %>%
mutate(GroupName=factor(GroupName,levels=c("nrTP","C1a","C1b","C2a")),
Dataset=factor(Dataset,levels=c("NRalone","IITAaugmented")),
modelType=factor(modelType,levels=c("A","AD","ADE"))) %>%
ggplot(.,aes(x=Dataset,y=accGETGV,fill=modelType,linetype=Dataset)) +
geom_boxplot(position = position_dodge(1),width=0.75,color='gray',size=0.75) +
facet_grid(GroupName~Trait, scales='free') +
theme_bw() +
theme(strip.text.x = element_text(face='bold', size=12),
axis.text.x = element_text(size=10, angle = 90),
axis.title.y = element_text(face='bold', size=12)) +
scale_fill_viridis_d() +
#scale_color_manual(values = c("gray","gold")) +
labs(title="Cross-validated Prediction Accuracy (GETGVs)") +
geom_hline(yintercept = 0, color='darkred')
```
# Next step
5. [Genomic prediction of GS C2](05-GetGBLUPs.html): Predict _genomic_ BLUPs (GEBV and GETGV) for all selection candidates using all available data.
```{bash, eval=F, include=F}
rsync --update --archive --verbose /workdir/marnin/NRCRI_2020GS/ mw489@cbsulm13.biohpc.cornell.edu:/workdir/mw489/NRCRI_2020GS;
rsync --update --archive --verbose /workdir/marnin/NRCRI_2020GS/ mw489@cbsulm15.biohpc.cornell.edu:/workdir/mw489/NRCRI_2020GS;
rsync --update --archive --verbose /workdir/marnin/NRCRI_2020GS/ mw489@cbsulm18.biohpc.cornell.edu:/workdir/mw489/NRCRI_2020GS;
rsync --update --archive --verbose /workdir/mw489/NRCRI_2020GS/ mw489@cbsurobbins.biohpc.cornell.edu:/workdir/marnin/NRCRI_2020GS;
```