/
01-cleanTPdata.Rmd
439 lines (377 loc) · 19 KB
/
01-cleanTPdata.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
---
title: "Review and QC of TARI training data"
site: workflowr::wflow_site
date: "2020-December-18"
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)
```
Follow outlined GenomicPredictionChecklist and previous pipeline to process cassavabase data for ultimate genomic prediction.
Below we will clean and format training data.
* Inputs: "Raw" field trial data
* Expected outputs: "Cleaned" field trial data
# [User input] Cassavabase download
Downloaded **all** TARI field trials.
1. [Cassavabase search wizard](https://www.cassavabase.org/breeders/search):
2. Selected *all* TARI trials currently available. Make a list. Named it **ALL_TARI_TRIALS_2020Dec18**.
3. Go to **Manage** --> **Download** [here](https://www.cassavabase.org/breeders/download). Download phenotypes (plot-basis only) and meta-data as CSV using the corresponding boxes / drop-downs.
4. Store flatfiles, unaltered in directory `data/DatabaseDownload_2020Dec18/`.
* **TRIED TO DOWNLOAD META-DATA, BUT DB IS GIVING "SERVER ERROR"**
```{r}
rm(list=ls())
library(tidyverse); library(magrittr);
source(here::here("code","gsFunctions.R"))
```
Read DB data directly from the Cassavabase FTP server.
```{r}
dbdata<-readDBdata(phenotypeFile = here::here("data/DatabaseDownload_2020Dec18","2020-12-18T183047phenotype_download.csv"),
metadataFile = here::here("data/DatabaseDownload_2020Dec18","2020-12-18T174951metadata_download.csv"))
#meta<-read.csv(here::here("data/DatabaseDownload_2020Dec18","2020-12-18T174951metadata_download.csv"),stringsAsFactors = F)
dbdata %<>%
mutate(locationName=ifelse(locationName=="bwanga","Bwanga",locationName),
locationName=ifelse(locationName=="kasulu","Kasulu",locationName))
```
# Group and select trials to analyze
Make TrialType Variable
```{r}
dbdata<-makeTrialTypeVar(dbdata)
dbdata %>%
count(TrialType) %>% rmarkdown::paged_table()
```
## Trials NOT included
Looking at the **studyName**'s of trials getting NA for TrialType, which can't be classified at present.
Here is the list of trials I am _not_ including.
```{r}
dbdata %>% filter(is.na(TrialType)) %$% unique(studyName) %>%
write.csv(.,file = here::here("output","TARI_trials_NOT_identifiable.csv"), row.names = F)
```
Wrote to disk a CSV in the `output/` sub-directory.
Should any of these trials have been included?
```{r}
dbdata %>%
filter(is.na(TrialType)) %$% unique(studyName)
```
## Remove unclassified trials
```{r}
dbdata %<>%
filter(!is.na(TrialType))
dbdata %>%
group_by(programName) %>%
summarize(N=n()) %>% rmarkdown::paged_table()
# 12718 plots
```
Making a table of abbreviations for renaming
```{r}
traitabbrevs<-tribble(~TraitAbbrev,~TraitName,
"CMD1S","cassava.mosaic.disease.severity.1.month.evaluation.CO_334.0000191",
"CMD3S","cassava.mosaic.disease.severity.3.month.evaluation.CO_334.0000192",
"CMD6S","cassava.mosaic.disease.severity.6.month.evaluation.CO_334.0000194",
"CMD9S","cassava.mosaic.disease.severity.9.month.evaluation.CO_334.0000193",
"CBSD3S","cassava.brown.streak.disease.leaf.severity.3.month.evaluation.CO_334.0000204",
"CBSD6S","cassava.brown.streak.disease.leaf.severity.6.month.evaluation.CO_334.0000205",
"CBSD9S","cassava.brown.streak.disease.leaf.severity.9.month.evaluation.CO_334.0000206",
"CBSDRS","cassava.brown.streak.disease.root.severity.12.month.evaluation.CO_334.0000201",
#"CGM","Cassava.green.mite.severity.CO_334.0000033",
"CGMS1","cassava.green.mite.severity.first.evaluation.CO_334.0000189",
"CGMS2","cassava.green.mite.severity.second.evaluation.CO_334.0000190",
"DM","dry.matter.content.by.specific.gravity.method.CO_334.0000160",
# "DM","dry.matter.content.percentage.CO_334.0000092",
"PLTHT","plant.height.measurement.in.cm.CO_334.0000018",
"BRNHT1","first.apical.branch.height.measurement.in.cm.CO_334.0000106",
"SHTWT","fresh.shoot.weight.measurement.in.kg.per.plot.CO_334.0000016",
"RTWT","fresh.storage.root.weight.per.plot.CO_334.0000012",
"RTNO","root.number.counting.CO_334.0000011",
"TCHART","total.carotenoid.by.chart.1.8.CO_334.0000161",
"NOHAV","plant.stands.harvested.counting.CO_334.0000010")
traitabbrevs %>% rmarkdown::paged_table()
# dbdata %>% colnames(.) %>% grep("fresh.root",.,value=T)
# dbdata$cassava.green.mite.severity.first.evaluation.CO_334.0000189 %>% summary
```
Run function `renameAndSelectCols()` to rename columns and remove everything unecessary
```{r}
dbdata<-renameAndSelectCols(traitabbrevs,indata=dbdata,customColsToKeep = "TrialType")
```
# QC Trait values
```{r}
dbdata<-dbdata %>%
mutate(#CMD1S=ifelse(CMD1S<1 | CMD1S>5,NA,CMD1S),
CMD3S=ifelse(CMD3S<1 | CMD3S>5,NA,CMD3S),
CMD6S=ifelse(CMD6S<1 | CMD6S>5,NA,CMD6S),
CMD9S=ifelse(CMD9S<1 | CMD9S>5,NA,CMD9S),
CBSD3S=ifelse(CBSD3S<1 | CBSD3S>5,NA,CBSD3S),
CBSD6S=ifelse(CBSD6S<1 | CBSD6S>5,NA,CBSD6S),
CBSD9S=ifelse(CBSD9S<1 | CBSD9S>5,NA,CMD9S),
CBSDRS=ifelse(CBSDRS<1 | CBSDRS>5,NA,CBSDRS),
#CGM=ifelse(CGM<1 | CGM>5,NA,CGM),
CGMS1=ifelse(CGMS1<1 | CGMS1>5,NA,CGMS1),
CGMS2=ifelse(CGMS2<1 | CGMS2>5,NA,CGMS2),
DM=ifelse(DM>100 | DM<=0,NA,DM),
RTWT=ifelse(RTWT==0 | NOHAV==0 | is.na(NOHAV),NA,RTWT),
SHTWT=ifelse(SHTWT==0 | NOHAV==0 | is.na(NOHAV),NA,SHTWT),
RTNO=ifelse(RTNO==0 | NOHAV==0 | is.na(NOHAV),NA,RTNO),
NOHAV=ifelse(NOHAV==0,NA,NOHAV),
NOHAV=ifelse(NOHAV>42,NA,NOHAV),
RTNO=ifelse(!RTNO %in% 1:10000,NA,RTNO))
```
# Post-QC traits
## Harvest index
```{r}
dbdata<-dbdata %>%
mutate(HI=RTWT/(RTWT+SHTWT))
```
## Unit area traits
I anticipate this will not be necessary as it will be computed before or during data upload.
For calculating fresh root yield:
1. **PlotSpacing:** Area in $m^2$ per plant. plotWidth and plotLength metadata would hypothetically provide this info, but is missing for vast majority of trials. Therefore, use info from Fola.
2. **maxNOHAV:** Instead of ExpectedNOHAV. Need to know the max number of plants in the area harvested. For some trials, only the inner (or "net") plot is harvested, therefore the PlantsPerPlot meta-variable will not suffice. Besides, the PlantsPerPlot information is missing for the vast majority of trials. Instead, use observed max(NOHAV) for each trial. We use this plus the PlotSpacing to calc. the area over which the RTWT was measured. During analysis, variation in the actual number of plants harvested will be accounted for.
```{r, message=F, warning=F}
dbdata<-dbdata %>%
mutate(PlotSpacing=ifelse(programName!="IITA",1,
ifelse(studyYear<2013,1,
ifelse(TrialType %in% c("CET","GeneticGain","ExpCET"),1,0.8))))
maxNOHAV_byStudy<-dbdata %>%
group_by(programName,locationName,studyYear,studyName,studyDesign) %>%
summarize(MaxNOHAV=max(NOHAV, na.rm=T)) %>%
ungroup() %>%
mutate(MaxNOHAV=ifelse(MaxNOHAV=="-Inf",NA,MaxNOHAV))
write.csv(maxNOHAV_byStudy %>% arrange(studyYear),file=here::here("output","maxNOHAV_byStudy.csv"), row.names = F)
```
```{r}
# I log transform yield traits
# to satisfy homoskedastic residuals assumption
# of linear mixed models
dbdata<-left_join(dbdata,maxNOHAV_byStudy) %>%
mutate(RTWT=ifelse(NOHAV>MaxNOHAV,NA,RTWT),
SHTWT=ifelse(NOHAV>MaxNOHAV,NA,SHTWT),
RTNO=ifelse(NOHAV>MaxNOHAV,NA,RTNO),
HI=ifelse(NOHAV>MaxNOHAV,NA,HI),
FYLD=RTWT/(MaxNOHAV*PlotSpacing)*10,
DYLD=FYLD*(DM/100),
logFYLD=log(FYLD),
logDYLD=log(DYLD),
logTOPYLD=log(SHTWT/(MaxNOHAV*PlotSpacing)*10),
logRTNO=log(RTNO),
PropNOHAV=NOHAV/MaxNOHAV)
# remove non transformed / per-plot (instead of per area) traits
dbdata %<>% select(-RTWT,-SHTWT,-RTNO,-FYLD,-DYLD)
```
## Season-wide mean disease severity
```{r}
dbdata<-dbdata %>%
mutate(MCMDS=rowMeans(.[,c("CMD3S","CMD6S","CMD9S")], na.rm = T),
MCBSDS=rowMeans(.[,c("CBSD3S","CBSD6S","CBSD9S")], na.rm = T)) %>%
select(-CMD3S,-CMD6S,-CMD9S,-CBSD3S,-CBSD6S,-CBSD9S)
```
# [User input] Assign genos to phenos
This step is mostly copy-pasted from previous processing of IITA- and NRCRI-specific data.
Uses 3 flat files, which are available e.g. [here](ftp://ftp.cassavabase.org/marnin_datasets/NRCRI_2020GS/data/). Specifically, `IITA_GBStoPhenoMaster_33018.csv`, `GBSdataMasterList_31818.csv` and `NRCRI_GBStoPhenoMaster_40318.csv`. I copy them to the `data/` sub-directory for the current analysis.
In addition, DArT-only samples are now expected to also have phenotypes. Therefore, checking for matches in new flatfiles, deposited in the `data/` (see code below).
```{r}
library(tidyverse); library(magrittr)
gbs2phenoMaster<-dbdata %>%
select(germplasmName) %>%
distinct %>%
left_join(read.csv(here::here("data","NRCRI_GBStoPhenoMaster_40318.csv"),
stringsAsFactors = F)) %>%
mutate(FullSampleName=ifelse(grepl("C2a",germplasmName,ignore.case = T) &
is.na(FullSampleName),germplasmName,FullSampleName)) %>%
filter(!is.na(FullSampleName)) %>%
select(germplasmName,FullSampleName) %>%
bind_rows(dbdata %>%
select(germplasmName) %>%
distinct %>%
left_join(read.csv(here::here("data","IITA_GBStoPhenoMaster_33018.csv"),
stringsAsFactors = F)) %>%
filter(!is.na(FullSampleName)) %>%
select(germplasmName,FullSampleName)) %>%
bind_rows(dbdata %>%
select(germplasmName) %>%
distinct %>%
left_join(read.csv(here::here("data","GBSdataMasterList_31818.csv"),
stringsAsFactors = F) %>%
select(DNASample,FullSampleName) %>%
rename(germplasmName=DNASample)) %>%
filter(!is.na(FullSampleName)) %>%
select(germplasmName,FullSampleName)) %>%
bind_rows(dbdata %>%
select(germplasmName) %>%
distinct %>%
mutate(germplasmSynonyms=ifelse(grepl("^UG",germplasmName,ignore.case = T),
gsub("UG","Ug",germplasmName),germplasmName)) %>%
left_join(read.csv(here::here("data","GBSdataMasterList_31818.csv"),
stringsAsFactors = F) %>%
select(DNASample,FullSampleName) %>%
rename(germplasmSynonyms=DNASample)) %>%
filter(!is.na(FullSampleName)) %>%
select(germplasmName,FullSampleName)) %>%
bind_rows(dbdata %>%
select(germplasmName) %>%
distinct %>%
mutate(germplasmSynonyms=ifelse(grepl("^TZ",germplasmName,
ignore.case = T),
gsub("TZ","",germplasmName),germplasmName)) %>%
left_join(read.csv(here::here("data","GBSdataMasterList_31818.csv"),
stringsAsFactors = F) %>%
select(DNASample,FullSampleName) %>%
rename(germplasmSynonyms=DNASample)) %>%
filter(!is.na(FullSampleName)) %>%
select(germplasmName,FullSampleName)) %>%
distinct %>%
left_join(read.csv(here::here("data","GBSdataMasterList_31818.csv"),
stringsAsFactors = F) %>%
select(FullSampleName,OrigKeyFile,Institute) %>%
rename(OriginOfSample=Institute)) %>%
mutate(OrigKeyFile=ifelse(grepl("C2a",germplasmName,ignore.case = T),
ifelse(is.na(OrigKeyFile),"LavalGBS",OrigKeyFile),
OrigKeyFile),
OriginOfSample=ifelse(grepl("C2a",germplasmName,ignore.case = T),
ifelse(is.na(OriginOfSample),"NRCRI",OriginOfSample),
OriginOfSample))
## NEW: check for germName-DArT name matches
germNamesWithoutGBSgenos<-dbdata %>%
select(programName,germplasmName) %>%
distinct %>%
left_join(gbs2phenoMaster) %>%
filter(is.na(FullSampleName)) %>%
select(-FullSampleName)
## NEW: check for germName-DArT name matches
germNamesWithoutGBSgenos<-dbdata %>%
select(programName,germplasmName) %>%
distinct %>%
left_join(gbs2phenoMaster) %>%
filter(is.na(FullSampleName)) %>%
select(-FullSampleName)
germNamesWithDArT<-germNamesWithoutGBSgenos %>%
inner_join(read.table(here::here("data","chr1_RefPanelAndGSprogeny_ReadyForGP_72719.fam"),
header = F, stringsAsFactors = F)$V2 %>%
grep("TMS16|TMS17|TMS18|TMS19|TMS20",.,value = T, ignore.case = T) %>%
tibble(dartName=.) %>%
separate(dartName,c("germplasmName","dartID"),"_",extra = 'merge',remove = F)) %>%
group_by(germplasmName) %>%
slice(1) %>%
ungroup() %>%
rename(FullSampleName=dartName) %>%
mutate(OrigKeyFile="DArTseqLD", OriginOfSample="IITA") %>%
select(-dartID)
print(paste0(nrow(germNamesWithDArT)," germNames with DArT-only genos"))
# first, filter to just program-DNAorigin matches
germNamesWithGenos<-dbdata %>%
select(programName,germplasmName) %>%
distinct %>%
left_join(gbs2phenoMaster) %>%
filter(!is.na(FullSampleName))
print(paste0(nrow(germNamesWithGenos)," germNames with GBS genos"))
# program-germNames with locally sourced GBS samples
germNamesWithGenos_HasLocalSourcedGBS<-germNamesWithGenos %>%
filter(programName==OriginOfSample) %>%
select(programName,germplasmName) %>%
semi_join(germNamesWithGenos,.) %>%
group_by(programName,germplasmName) %>% # select one DNA per germplasmName per program
slice(1) %>% ungroup()
print(paste0(nrow(germNamesWithGenos_HasLocalSourcedGBS)," germNames with local GBS genos"))
# the rest (program-germNames) with GBS but coming from a different breeding program
germNamesWithGenos_NoLocalSourcedGBS<-germNamesWithGenos %>%
filter(programName==OriginOfSample) %>%
select(programName,germplasmName) %>%
anti_join(germNamesWithGenos,.) %>%
# select one DNA per germplasmName per program
group_by(programName,germplasmName) %>%
slice(1) %>% ungroup()
print(paste0(nrow(germNamesWithGenos_NoLocalSourcedGBS)," germNames without local GBS genos"))
genosForPhenos<-bind_rows(germNamesWithGenos_HasLocalSourcedGBS,
germNamesWithGenos_NoLocalSourcedGBS) %>%
bind_rows(germNamesWithDArT)
print(paste0(nrow(genosForPhenos)," total germNames with genos either GBS or DArT"))
dbdata %<>%
left_join(genosForPhenos)
# Create a new identifier, GID
## Equals the value SNP data name (FullSampleName)
## else germplasmName if no SNP data
dbdata %<>%
mutate(GID=ifelse(is.na(FullSampleName),germplasmName,FullSampleName))
```
### Write lists for matching genos-to-phenos
```{r, eval=F}
snps_refpanel<-readRDS(here::here("output","DosageMatrix_ImputationReferencePanel_StageVI_91119.rds"))
snps5629<-readRDS(here::here("output","DosageMatrix_DCas20_5629_EA_REFimputedAndFiltered.rds"))
dbdata %>%
distinct(germplasmName,FullSampleName) %>%
write.csv(.,file = here::here("output","germplasmName_to_DNAname_matches_TARI_2020Dec22.csv"), row.names = F)
rownames(snps_refpanel) %>%
write.csv(.,file = here::here("output","rownames_DosageMatrix_ImputationReferencePanel_StageVI_91119.csv"), row.names = F)
rownames(snps5629) %>%
write.csv(.,file = here::here("output","rownames_DosageMatrix_DCas20_5629_EA_REFimputedAndFiltered.csv"), row.names = F)
rm(snps_refpanel,snps5629); gc()
```
```{r}
# dbdata %>%
# count(germplasmName,FullSampleName) %>% filter(is.na(FullSampleName)) %$% unique(germplasmName)
```
```{r}
# going to check against SNP data
# DosageMatrix_ImputationReferencePanel_StageVI_91119.rds
# DosageMatrix_DCas20_5629_EA_REFimputedAndFiltered.rds
#
# snps<-readRDS(file=url(paste0("ftp://ftp.cassavabase.org/marnin_datasets/NGC_BigData/",
# "DosageMatrix_RefPanelAndGSprogeny_ReadyForGP_73019.rds")))
# rownames_snps<-rownames(snps); rm(snps); gc()
# # current matches to SNP data
# dbdata %>%
# distinct(GID,germplasmName,FullSampleName) %>%
# semi_join(tibble(GID=rownames_snps)) %>% nrow() #1340
# dbdata %>%
# distinct(GID,germplasmName,FullSampleName) %>%
# semi_join(tibble(GID=rownames_snps)) %>%
# filter(grepl("c1",GID,ignore.case = F)) # no C1 clones currently match
# dbdata %>%
# distinct(GID,germplasmName,FullSampleName) %>%
# semi_join(tibble(GID=rownames_snps)) %>%
# filter(grepl("c2",GID,ignore.case = F)) # no C2 clones either
# dbdata %>%
# distinct(GID,germplasmName,FullSampleName) %>%
# anti_join(tibble(GID=rownames_snps)) %>%
# filter(grepl("c1|c2",GID,ignore.case = T)) # definitely there are both C1 and C2 phenotypes
# # and there are C1 and C2 genotypes
# rownames_snps %>% grep("c1",.,value = T,ignore.case = T) %>% length # [1] 1762
# rownames_snps %>% grep("c2",.,value = T,ignore.case = T) %>% length # [1] 4291
```
## Output "cleaned" file
```{r}
saveRDS(dbdata,file=here::here("output","TARI_CleanedTrialData_2020Dec18.rds"))
```
# Detect experimental designs
The next step is to check the experimental design of each trial. If you are absolutely certain of the usage of the design variables in your dataset, you might not need this step.
Examples of reasons to do the step below:
- Some trials appear to be complete blocked designs and the blockNumber is used instead of replicate, which is what most use.
- Some complete block designs have nested, incomplete sub-blocks, others simply copy the "replicate" variable into the "blockNumber variable"
- Some trials have only incomplete blocks _but_ the incomplete block info might be in the replicate _and/or_ the blockNumber column
One reason it might be important to get this right is that the variance among complete blocks might not be the same among incomplete blocks. If we treat a mixture of complete and incomplete blocks as part of the same random-effect (replicated-within-trial), we assume they have the same variance.
Also error variances might be heterogeneous among different trial-types (blocking scheme available) _and/or_ plot sizes (maxNOHAV).
Start with cleaned data from previous step.
```{r, warning=F, message=F}
rm(list=ls()); gc()
library(tidyverse); library(magrittr);
source(here::here("code","gsFunctions.R"))
dbdata<-readRDS(here::here("output","TARI_CleanedTrialData_2020Dec18.rds"))
```
```{r}
dbdata %>% head %>% rmarkdown::paged_table()
```
Detect designs
```{r}
dbdata<-detectExptDesigns(dbdata)
```
```{r}
dbdata %>%
count(programName,CompleteBlocks,IncompleteBlocks) %>% rmarkdown::paged_table()
```
## Output file
```{r}
saveRDS(dbdata,file=here::here("output","TARI_ExptDesignsDetected_2020Dec18.rds"))
```
# Next step
2. [Get BLUPs combining all trial data](02-GetBLUPs.html): Combine data from all trait-trials to get BLUPs for downstream genomic prediction.
* Fit mixed-model to multi-trial dataset and extract BLUPs, de-regressed BLUPs and weights. Include two rounds of outlier removal.