---
title: "Review and QC of TARI training data"
site: workflowr::wflow_site
date: "2020-December-18"
output: 
  workflowr::wflow_html:
    highlight: breezedark
editor_options:
  chunk_output_type: inline
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, message = FALSE, warning = F, 
                      tidy='styler', tidy.opts=list(strict=FALSE,width.cutoff=100), highlight=TRUE)
```

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_2021Jan20**.
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_2021Jan20/`. 


```{r}
rm(list=ls())
library(tidyverse); library(magrittr);
source(here::here("code","gsFunctions.R"))
```

But first.... TARI seems to have a'lot of plant-basis data which I am not usually including.
```{r}
indata<-read.csv(here::here("data/DatabaseDownload_2021Jan20","2021-01-20T203949phenotype_download.csv"),
                   na.strings = c("#VALUE!",NA,".",""," ","-","\""),
                   stringsAsFactors = F)
indata %>% count(observationLevel)
```
Over 191K "plants" between 2018-2020.

The following printed studyNames have plant-basis data. They **WILL NOT** be included in subsequent analyses.
```{r}
indata %>% filter(observationLevel=="plant") %$% unique(studyName)
```

Read DB data directly from the Cassavabase FTP server.

```{r}
rm(indata);
dbdata<-readDBdata(phenotypeFile = here::here("data/DatabaseDownload_2021Jan20","2021-01-20T203949phenotype_download.csv"),
                   metadataFile = here::here("data/DatabaseDownload_2021Jan20","2021-01-20T174234metadata_download.csv"))
```

Before proceeding, the 2019 seedling nursery....

```{r}
dbdata %>% 
  filter(studyName=="19_C1_GS_Seedling_Nursery_Chambezi",
         germplasmName=="TZMRK180069") %>% 
  distinct(germplasmName,observationUnitName,plantNumber,plotNumber,observationUnitName) %>% 
  rmarkdown::paged_table()
```
```{r}
snps5629<-readRDS(here::here("output","DosageMatrix_DCas20_5629_EA_REFimputedAndFiltered.rds"))
rownames(snps5629) %>% grep("TZMRK180069",., value = T, ignore.case = T)
```

Unfortunately, these don't currently match. As of Jan 21, wrote to TARI team about this. Will proceed with prediction, but CBSD phenos for the GS C1 seedlings _won't_ be included at this time. 
```{r}
rm(snps5629); gc()
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)
```

Include (by request) the "19_C1_GS_Seedling_Nursery_Chambezi".

```{r}
dbdata %<>% 
  mutate(TrialType=ifelse(studyName=="19_C1_GS_Seedling_Nursery_Chambezi","SeedlingNursery",TrialType))
```

## Remove unclassified trials

```{r}
dbdata %<>% 
    filter(!is.na(TrialType)) 
dbdata %>% 
    group_by(programName) %>% 
    summarize(N=n()) %>% rmarkdown::paged_table()
#	18591	(now including a ~5K plot seedling nursery) 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 = c("TrialType","observationUnitName"))
```

# 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


I customized this step for TARI. 

Match "germplasmName" from TARI phenotyping trials to "FullSampleName" from TARI GBS and DArT genotyping data.

Uses 2 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`. 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)

# Distinct "germplasmName" identifying clones in TARI phenotyping plots
tzgermnames<-dbdata %>% 
  distinct(germplasmName)

  # 1) Match TARI samples where germplasmName is prefixed with TZ, but FullSampleName
phenos2genos<-tzgermnames %>% 
  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)) %>%  
  # 2) Match additional samples based on genotyping done by IITA and NaCRRI:
  ## IITA
  bind_rows(tzgermnames %>%
              left_join(read.csv(here::here("data","IITA_GBStoPhenoMaster_33018.csv"),
                                 stringsAsFactors = F))) %>% 
  ## NaCRRI
  bind_rows(tzgermnames %>%
              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)))
phenos2genos %>% filter(!is.na(FullSampleName)) %>% distinct(germplasmName) %>% nrow(.) # [1] 435
# Only about half the germplasmName we expect
```
Only about half the ~834 germplasmName we expect to correspond to the clones from Ukiriguru _and_ Kibaha. 

At this point, I realized the Kibaha samples are missing.

The solution is in the code below. It required some staring at names. Heneriko supplied a list from the 2016 predictions (see: `data/TARI 2016_TP_CLONES.csv`), which was helpful. 

```{r}
phenos2genos %<>% 
  bind_rows(tzgermnames %>% 
              mutate(germplasmSynonyms=gsub("^TZ","",germplasmName),
                     germplasmSynonyms=gsub("HS","_",germplasmSynonyms),
                     germplasmSynonyms=gsub("FS","_",germplasmSynonyms)) %>% 
              left_join(read.csv(here::here("data","GBSdataMasterList_31818.csv"), 
                                 stringsAsFactors = F) %>% 
                          select(DNASample,FullSampleName) %>% 
                          rename(germplasmSynonyms=DNASample) %>% 
                          filter(grepl("^KBH",germplasmSynonyms)) %>% 
                          mutate(germplasmSynonyms=gsub("KBH2012","KBH12",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2013","KBH13",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2014","KBH14",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2015","KBH15",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2016","KBH16",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2017","KBH17",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2018","KBH18",germplasmSynonyms),
                                 germplasmSynonyms=gsub("KBH2019","KBH19",germplasmSynonyms))))
phenos2genos %<>% 
  filter(!is.na(FullSampleName)) %>% 
  distinct(germplasmName,FullSampleName)

phenos2genos %>% distinct(germplasmName) %>% nrow(.) # [1] 914
```

Now there are 914 germplasmName-FullSampleName matches.

For both the "germplasmName" and the "FullSampleName" lists, try matching by making everything upper case on both sides. There are many capitolization related issues I see. Examples:

* germplasmName == "LIONGOKWIMBA", FullSampleName == "Liongokwimba"
* germplasmName == "kiroba", FullSampleName == "KIROBA"
* germplasmName == "Mkumba", FullSampleName == "MKUMBA"

But also, e.g.:

* germplasmName == "TZ-130", FullSampleName == "TZ_130"
```{r}
phenos2genos %<>% 
  bind_rows(tzgermnames %>% 
  anti_join(phenos2genos) %>%
  mutate(germplasmSynonyms=toupper(germplasmName),
         germplasmSynonyms=gsub("-","_",germplasmSynonyms)) %>% 
  left_join(read.csv(here::here("data","GBSdataMasterList_31818.csv"), 
                                 stringsAsFactors = F) %>% 
                          select(DNASample,FullSampleName) %>% 
                          rename(germplasmSynonyms=DNASample) %>% 
                          mutate(germplasmSynonyms=toupper(germplasmSynonyms),
                                 germplasmSynonyms=gsub("-","_",germplasmSynonyms)))) %>% 
  filter(!is.na(FullSampleName)) %>% 
  distinct(germplasmName,FullSampleName)

phenos2genos %>% distinct(germplasmName) %>% nrow(.) # [1] 921 .... not an awesome improvement

```

Next, and last but not least, need to check for matches with the new germplasm genotyped only by DArTseqLD (DCas20_5629). Based on the check I did above, this is not currently possible, so skip.

```{r}
germNamesWithoutGBSgenos<-tzgermnames %>%
  anti_join(phenos2genos)
germNamesWithoutGBSgenos %>% nrow() # [1] 2938
```

Select one genotype record (FullSampleName) per unique clone (germplasmName)
```{r}
genosChosenForPhenos<-phenos2genos %>% 
  group_by(germplasmName) %>% 
  slice(1) %>% ungroup()
print(paste0(nrow(genosChosenForPhenos)," germNames with GBS geno. records"))
```

```{r}
dbdata %<>% 
    left_join(genosChosenForPhenos) 

# Create a new identifier, GID
## Equals the value SNP data name (FullSampleName) 
## else germplasmName if no SNP data
## [FOR TARI] if studyName=="19_C1_GS_Seedling_Nursery_Chambezi", GID should be the "observationUnitName"
dbdata %<>% 
  mutate(GID=ifelse(is.na(FullSampleName),
                    ifelse(studyName=="19_C1_GS_Seedling_Nursery_Chambezi",
                           observationUnitName,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"))
# 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()

write.csv(genosChosenForPhenos,
          file = here::here("output","OnlyChosen_germplasmName_to_FullSampleName_matches_TARI_2021Jan21.csv"), 
          row.names = F)

write.csv(phenos2genos,
          file = here::here("output","AllIdentified_germplasmName_to_FullSampleName_matches_TARI_2021Jan21.csv"), 
          row.names = F)

```

## Output "cleaned" file
```{r}
saveRDS(dbdata,file=here::here("output","TARI_CleanedTrialData_2021Jan21.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_2021Jan21.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_2021Jan21.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.
