---
title: "Basic usage of GBScleanR"
author: 
  -name: "Tomoyuki Furuta"
  affiliation: Institute of Plant Science and Resources, Okayama University, Okayama, Japan
  email: f.tomoyuki@okayama-u.ac.jp
date: "November 17, 2021"
package: GBScleanR
output: 
  BiocStyle::html_document:
    toc: true
    toc_float: true
bibliography: references.bib
vignette: >
  %\VignetteIndexEntry{Basic usage of GBScleanR}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---
```{r global_options, include=FALSE}
knitr::opts_chunk$set(fig.pos = 'H', fig.align = "center", warning = FALSE, message = FALSE)
```

# Introduction
The `r Biocpkg("GBScleanR")` package has been developed to conduct error correction on genotype data obtained via NGS-based genotyping methods such as RAD-seq and GBS [@Miller2007; @Elshire2011]. It is designed to estimate true genotypes along chromosomes from given allele read counts in the VCF file generated by SNP callers like GATK and TASSEL-GBS [@McKenna2010; @Glaubitz2014]. The current implementation supports genotype data of a mapping population derived from two or more diploid founders followed by selfings, sibling crosses, or random crosses. e.g. F$_2$ and 8-way RILs. Our method supposes markers to be biallelic and ordered along chromosomes by mapping reads on a reference genome sequence. To support smooth access to large size genotype data, every input VCF file is first converted to a genomic data structure (GDS) file [@Zheng2012]. The current implementation cannot convert a VCF file containing non-biallelic markers to a GDS file correctly. Thus, any input VCF file should be subjected to filtering for retaining only biallelic SNPs using, for example, bcftools [@Li2011]. `r Biocpkg("GBScleanR")` provides functions for data visualization, filtering, and loading/writing a VCF file. Furthermore, the data structure of the GDS file created via this package is compatible with those used in the `r Biocpkg("SNPRelate")`, `r Biocpkg("GWASTools")` and `r Biocpkg("GENESIS")` packages those are designed to handle large variant data and conduct regression analysis [@Zheng2012; @Gogarten2012; @Gogarten2019]. In this document, we first walk through the utility functions implemented in `r Biocpkg("GBScleanR")` to introduce a basic usage. Then, the core function of `r Biocpkg("GBScleanR")` which estimates true genotypes for error correction will be introduced.


# Prerequisites
This package internally uses the following packages.  
- `r CRANpkg("ggplot2")`  
- `r CRANpkg("dplyr")`  
- `r CRANpkg("tidyr")`  
- `r CRANpkg("expm")`  
- `r Biocpkg("gdsfmt")`  
- `r Biocpkg("Biobase")`  
- `r Biocpkg("GWASTools")`  
- `r Biocpkg("SeqArray")`  
\  

# Installation
You can install `r Biocpkg("GBScleanR")` from the Bioconductor repository with the following code.
```{r eval=FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")

BiocManager::install("GBScleanR")
```
\  

The code below let you install the package from the github repository.
The package released in the github usually get frequent update more than that in Bioconductor due to the release schedule.
```{r eval=FALSE}
if (!requireNamespace("devtools", quietly = TRUE))
    install.packages("devtools")
devtools::install_github("tomoyukif/GBScleanR", build_vignettes = TRUE)
```



# Loading data
The main class of the `r Biocpkg("GBScleanR")` package is `GbsrGenotypData` which inherits the `GenotypeData` class in the `r Biocpkg("GWASTools")` package. The `gbsrGenotypeData` class object has three slots: `data`, `snpAnnot`, and `scanAnnot`. The `data` slot holds genotype data as a `gds.class` object which is defined in the `gdsfmt` package while `snpAnnot` and `scanAnnot` contain objects storing annotation information of SNPs and samples, which are the `SnpAnnotationDataFrame` and `ScanAnnotationDataFrame` objects defined in the `r Biocpkg("GWASTools")` package. See the vignette of `r Biocpkg("GWASTools")` for more detail. `r Biocpkg("GBScleanR")` follows the way of `r Biocpkg("GWASTools")` in which a unique genotyping instance (genotyped sample) is called "scan".  
\ 

Load the package.
```{r warning=FALSE, message=FALSE}
library("GBScleanR")
```
\ 

`r Biocpkg("GBScleanR")` only supports a VCF file as input. As an example data, we use sample genotype data for a biparental F2 population derived from inbred founders.
```{r}
vcf_fn <- system.file("extdata", "sample.vcf", package = "GBScleanR")
gds_fn <- tempfile("sample", fileext = ".gds")
```
\ 

As mentioned above, the `GbsrGenotypeData` class requires genotype data in the `gds.class` object which enable us quick access to the genotype data without loading the whole data on RAM. At the beginning of the processing, we need to convert data format of our genotype data from VCF to GDS. This conversion can be achieved using `gbsrVCF2GDS()` as shown below. A compressed VCF file (.vcf.gz) also can be the input. 
```{r}
# `force = TRUE` allow the function to over write the GDS file,
# even if a GDS file exists at `out_fn`.
gbsrVCF2GDS(vcf_fn = vcf_fn, out_fn = gds_fn, force = TRUE, verbose = FALSE)
```
\ 

Once we converted the VCF to the GDS, we can create a `GbsrGenotypeData` instance for our data.
```{r}
gds <- loadGDS(gds_fn, verbose = FALSE)
```



# Utility methods
## Getters
Getter functions allow you to retrieve basic information of genotype data, e.g. the number of SNPs and samples, chromosome names, physical position of SNPs and alleles.
```{r}
# Number of samples
nscan(gds)
```
\ 
```{r}
# Number of SNPs
nsnp(gds) 
```
\ 
```{r}
# Indices of chromosome ID of all markers
head(getChromosome(gds)) 
```
\ 
```{r}
# Chromosome names of all markers
head(getChromosome(gds, name = TRUE)) 
```
\ 
```{r}
# Unique set of chromosome names
getChromosome(gds, levels = TRUE) 
```
\ 
```{r}
# Position (bp) of all markers
head(getPosition(gds)) 
```
\ 
```{r}
# Reference allele of all markers
head(getAlleleA(gds)) 
```
\ 
```{r}
# Alternative allele of all markers
head(getAlleleB(gds)) 
```
\ 
```{r}
# SNP IDs
head(getSnpID(gds)) 
```
\ 
```{r}
# sample IDs
head(getScanID(gds)) 
```
\ 

The function `getGenotype()` returns genotype call data in which integer numbers 0, 1, and 2 indicate the number of reference allele.
```{r}
geno <- getGenotype(gds)
```
\ 

The function `getRead()` returns read count data as a list with two elements `ref` and `alt` containing reference read counts and alternative read counts, respectively.
```{r}
geno <- getRead(gds)
```



## Data summarization
### Collect basic summary statistics
`countGenotype()` and `countRead()` are class methods of `GbsrGenotypeData` and they summarize genotype counts and read counts per marker and per sample. 
```{r}
gds <- countGenotype(gds)
gds <- countRead(gds)
```
\ 

### Visualize basic summary statistics
These summary statistics can be visualized via plotting functions.
With the values obtained via `countGenotype()`, we can plot histograms of missing rate , heterozygosity, reference allele frequency as shown below.
```{r fig.alt="Missing rate per marker and per sample."}
# Histgrams of missing rate
histGBSR(gds, stats = "missing") 
```
\ 
```{r fig.alt="Heterozygosity per marker and per sample."}
# Histgrams of heterozygosity
histGBSR(gds, stats = "het") 
```
\ 
```{r fig.alt="Reference allele frequency per marker and per sample."}
# Histgrams of reference allele frequency
histGBSR(gds, stats = "raf") 
```
\ 

With the values obtained via `countRead()`, we can plot histograms of total read depth , allele read depth , reference read frequency as shown below.
```{r fig.alt="Total read depth per marker and per sample."}
# Histgrams of total read depth
histGBSR(gds, stats = "dp") 
```
\ 
```{r fig.alt="Reference read depth per marker and per sample."}
# Histgrams of allelic read depth
histGBSR(gds, stats = "ad_ref") 
```
\ 
```{r fig.alt="Alternative read depth per marker and per sample."}
# Histgrams of allelic read depth
histGBSR(gds, stats = "ad_ref") 
```
\ 
```{r fig.alt="Reference read per marker and per sample."}
# Histgrams of reference allele frequency
histGBSR(gds, stats = "rrf") 
```
\ 

### Calculate representative values
In addition to `countGenotype()` and `countRead()`, we can get mean, sd, and quantile of read counts per marker and per sample via `calcReadStats()`. Unlike `countRead()`, this function first normalize read counts by dividing each read count of both alleles at a marker in a sample by the total read count of the sample followed by multiplying it by 10^6 to be read counts per million. This normalization allow us to compare read data distributions obtained for the samples without concern for absolute differences in total read counts between samples.
```{r}
gds <- calcReadStats(gds, q = 0.5)
```
The values specified for the "q" argument are passed to the "quantile" function internally to get quantiles. The "q" argument accepts a numeric vector and has `NULL` as default which let the function return no quantile.  
\ 

### Visualize representative values
To plot those statistics, we can also use `histGBSR()`.
```{r fig.alt="Mean of reference read depth per marker and per sample."}
# Histgrams of mean allelic read depth
histGBSR(gds, stats = "mean_ref") 
```
\ 
```{r fig.alt="Mean of alternative read depth per marker and per sample."}
# Histgrams of mean allelic read depth
histGBSR(gds, stats = "mean_ref") 
```
\ 
```{r fig.alt="SD of reference read depth per marker and per sample."}
# Histgrams of standard deviation of read depth
histGBSR(gds, stats = "sd_ref") 
```
\ 
```{r fig.alt="SD of alternative read depth per marker and per sample."}
# Histgrams of standard deviation of read depth
histGBSR(gds, stats = "sd_ref") 
```
\ 
```{r fig.alt="Quantile of reference read depth per marker and per sample."}
# Histgrams of quantile of read depth
histGBSR(gds, stats = "qtile_ref", q = 0.5) 
```
\ 
```{r fig.alt="Quantile of alternative read depth per marker and per sample."}
# Histgrams of quantile of read depth
histGBSR(gds, stats = "qtile_ref", q = 0.5) 
```
\ 

`plotGBSR()` and `pairsGBSR()` provide other ways to visualize statistics. `plotGBSR()` draws a line plot of a specified statistics per marker along each chromosome. `pairsGBSR()` give us a two-dimensional scatter plot to visualize relationship between statistics.
```{r}
plotGBSR(gds, stats = "missing")
```
\ 

```{r}
plotGBSR(gds, stats = "geno")
```
\ 

```{r}
pairsGBSR(gds, stats1 = "missing", stats2 = "dp")
```
\ 

### Getter methods for summary statistics
The statistics obtained via `countGenotype()`, `countReat()`, and `calcReadStats()` are sotred in the `snpAnnot` and `scanAnnot` slots. They can be retrieved using getter functions as follows.
```{r}
# Reference genotype count per marker
head(getCountGenoRef(gds, target = "snp")) 
# Reference genotype count per sample
head(getCountGenoRef(gds, target = "scan")) 
```
\ 
```{r}
# Heterozygote count per marker
head(getCountGenoHet(gds, target = "snp")) 
# Heterozygote count per sample
head(getCountGenoHet(gds, target = "scan")) 
```
\ 
```{r}
# Alternative genotype count per marker
head(getCountGenoAlt(gds, target = "snp")) 
# Alternative genotype count per sample
head(getCountGenoAlt(gds, target = "scan"))
```
\ 
```{r}
# Missing count per marker
head(getCountGenoMissing(gds, target = "snp")) 
# Missing count per sample
head(getCountGenoMissing(gds, target = "scan")) 
```
\ 
```{r}
# Reference allele count per marker
head(getCountAlleleRef(gds, target = "snp")) 
# Reference allele count per sample
head(getCountAlleleRef(gds, target = "scan")) 
```
\ 
```{r}
# Alternative allele count per marker
head(getCountAlleleAlt(gds, target = "snp")) 
# Alternative allele count per sample
head(getCountAlleleAlt(gds, target = "scan")) 
```
\ 
```{r}
# Missing allele count per marker
head(getCountAlleleMissing(gds, target = "snp")) 
# Missing allele count per sample
head(getCountAlleleMissing(gds, target = "scan")) 
```
\ 
```{r}
# Reference read count per marker
head(getCountReadRef(gds, target = "snp")) 
# Reference read count per sample
head(getCountReadRef(gds, target = "scan")) 
```
\ 
```{r}
# Alternative read count per marker
head(getCountReadAlt(gds, target = "snp")) 
# Alternative read count per sample
head(getCountReadAlt(gds, target = "scan")) 
```
\ 
```{r}
# Sum of reference and alternative read counts per marker
head(getCountRead(gds, target = "snp")) 
# Sum of reference and alternative read counts per sample
head(getCountRead(gds, target = "scan")) 
```
\ 
```{r}
# Mean of reference allele read count per marker
head(getMeanReadRef(gds, target = "snp")) 
# Mean of reference allele read count per sample
head(getMeanReadRef(gds, target = "scan"))
```
\ 
```{r}
# Mean of Alternative allele read count per marker
head(getMeanReadAlt(gds, target = "snp")) 
# Mean of Alternative allele read count per sample
head(getMeanReadAlt(gds, target = "scan")) 
```
\ 
```{r}
# SD of reference allele read count per marker
head(getSDReadRef(gds, target = "snp")) 
# SD of reference allele read count per sample
head(getSDReadRef(gds, target = "scan")) 
```
\ 
```{r}
# SD of Alternative allele read count per marker
head(getSDReadAlt(gds, target = "snp")) 
# SD of Alternative allele read count per sample
head(getSDReadAlt(gds, target = "scan"))
```
\ 
```{r}
# Quantile of reference allele read count per marker
head(getQtileReadRef(gds, target = "snp", q = 0.5)) 
# Quantile of reference allele read count per sample
head(getQtileReadRef(gds, target = "scan", q = 0.5))
```
\ 
```{r}
# Quantile of Alternative allele read count per marker
head(getQtileReadAlt(gds, target = "snp", q = 0.5))
# Quantile of Alternative allele read count per sample
head(getQtileReadAlt(gds, target = "scan", q = 0.5)) 
```
\ 
```{r}
# Minor allele frequency per marker
head(getMAF(gds, target = "snp")) 
# Minor allele frequency per sample
head(getMAF(gds, target = "scan")) 
```
\ 
```{r}
# Minor allele count per marker
head(getMAC(gds, target = "snp")) 
# Minor allele count per sample
head(getMAC(gds, target = "scan")) 
```
\ 

You can get the proportion of each genotype call with `prop = TRUE`.
```{r}
head(getCountGenoRef(gds, target = "snp", prop = TRUE))
head(getCountGenoHet(gds, target = "snp", prop = TRUE))
head(getCountGenoAlt(gds, target = "snp", prop = TRUE))
head(getCountGenoMissing(gds, target = "snp", prop = TRUE))
```
\ 

The proportion of each allele counts.
```{r}
head(getCountAlleleRef(gds, target = "snp", prop = TRUE))
head(getCountAlleleAlt(gds, target = "snp", prop = TRUE))
head(getCountAlleleMissing(gds, target = "snp", prop = TRUE))
```
\ 

The proportion of each allele read counts.
```{r}
head(getCountReadRef(gds, target = "snp", prop = TRUE))
head(getCountReadAlt(gds, target = "snp", prop = TRUE))
```



# Filtering and subsetting
## Filtering data
Based on the statistics we obtained, we can filter out less reliable markers and samples using `setSnpFilter()` and `setScanFilter()`.
```{r eval=FALSE}
gds <- setSnpFilter(missing = 0.2, het = c(0.1, 0.9), maf = 0.05)
gds <- setScanFilter(missing = 0.8, het = c(0.25, 0.75))
```
\ 

`setCallFilter()` is another type of filtering which works on each genotype call. We can replace some genotype calls with missing. If you would like to filter out less reliable genotype calls supported by less than 5 reads, set the arguments as below.
```{r eval=FALSE}
gds <- setCallFilter(gds, dp_count = c(5, Inf))
```
\ 

If need to remove genotype calls supported by too many reads, which might be the results of mismapping from repetitive sequences, set as follows.
```{r eval=FALSE}
# Filtering genotype calls based on total read counts
gds <- setCallFilter(gds, norm_dp_count = c(0, 1000))
# Filtering genotype calls based on reference read counts 
# and alternative read counts separately.
gds <- setCallFilter(gds, norm_ref_count = c(0, 1000), 
                       norm_alt_count = c(0, 800))
```
\ 

Usually reference reads and alternative reads show different data distributions. Thus, we can set the different thresholds for them via `norm_ref_count` and `norm_alt_count`. `setCallFilter()` also has arguments `scan_ref_qtile`, `scan_alt_qtile`, `snp_ref_qtile`, and `snp_alt_qtile` to filter out genotype calls based on quantiles of read counts per marker and per sample.
\ 

Here, the following codes filter out calls supported by less than 5 reads and then filter out markers having more than 20% of missing rate.
```{r}
gds <- setCallFilter(gds, dp_count = c(5, Inf))
gds <- setSnpFilter(gds, missing = 0.2)
```
\ 

In addition to those statistics based filtering functions, `r Biocpkg("GBScleanR")` provides filtering function based on relative marker positions. Markers locating too close each other usually have redundant information, especially if those markers are closer each other than the read length, in which case the markers are supported by completely (or almost) the same set of reads. To select only one marker from those markers, we can sue `thinMarker()`. This function selects one marker having the least missing rate from each stretch with the specified length. If some markers have the least missing rate, select the first marker in the stretch.
```{r}
# Here we select only one marker from each 150 bp stretch.
gds <- thinMarker(gds, range = 150) 
```
\ 

We can obtain the summary statistics using `countGenotype()`, `countRead()`, and `calcReadStats()` for only the SNPs and samples retained after the filtering.
```{r}
gds <- countGenotype(gds)
gds <- countRead(gds)
gds <- calcReadStats(gds)
```
\ 
`calcReadStats()` calculate the normalized read counts based on non filtered data but gets mean, sd, and quantiles from the normalized values of the retained markers of samples.
\ 

We can check which markers and samples are retained after the filtering using `getValidSnp()` and `getValidScan()`.
```{r}
head(getValidSnp(gds))
head(getValidScan(gds))
```
\ 

The class methods of `GbsrGenotypeData` basically work with only the markers and samples having `TRUE` in the returned values of `getValidSnp()` and `getValidScan()`. To use all markers and samples, please specify `valid = FALSE`.
```{r}
nsnp(gds)
nsnp(gds, valid = FALSE)
```
\ 

## Subseting data
The function `subsetGDS()` allows us to create a GDS file with data retained after filtering.
```{r}
subset_fn <- tempfile("sample_subset", fileext = ".gds")
subset_gds <- subsetGDS(gds, out_fn = subset_fn)
```
\ 

Once we made a new GDS file of the subset data, we restart analysis with the subset anytime.
```{r eval = FALSE}
subset_gds <- loadGDS(subset_fn, verbose = FALSE)
```
\ 

If you tried to load a GDS file which has been already loaded in the current R session, `loadGDS()` will return an error like the command above. In that case, please close the connection first and then load again or reload using `loadGDS()`.
```{r}
closeGDS(subset_gds)
subset_gds <- loadGDS(subset_fn, verbose = FALSE)
# If you give a GbsrGenotypeData object to `loadGDS()`,
# the function try to reload the GDS file.
subset_gds <- loadGDS(subset_gds, verbose = FALSE)
```
\ 

The function `subsetGDS()` automatically close the connection to the GDS file of the input `GbsrGenotypeData` object for internal file handling. Please use `openGDS()` to open the connection again. If you use `loadGDS()`, summary statistics and filtering information will be discarded.
```{r}
gds <- openGDS(gds)
```
\ 

## Reset filtering
We can reset filtering as following.
```{r}
# Reset the filter on markers
gds <- resetSnpFilters(gds) 
# Reset the filter on samples
gds <- resetScanFilters(gds) 
# Reset the filter on calls
gds <- setRawGenotype(gds) 
# Reset all filters
gds <- resetFilters(gds) 
```



# Error correction
The error correction algorithm of `r Biocpkg("GBScleanR")` bases on the HMM assuming observed allele read counts for each SNP marker along a chromosome as the outputs from a sequence of latent true genotypes. Our model supposes that a population of $N^o \geq 1$ sampled offspring was originally derived form the crosses between $N^f \geq 2$ founder individuals. The founders can be inbred lines having homozygotes at all markers and outbred lines in which markers show heterozygous genotype.



## Set founders
As the first step for genotype error correcion, we have to specify which samples are the founders of the population via `setParents()`. In the case of genotype data in the biparental population, people usually filter out SNPs which are not monomorphic in each parental sample and not biallelic between parents. `setParents()` automatically do this filtering, if you set `mono = TRUE` and `bi = TRUE`.
```{r}
p1 <- grep("Founder1", getScanID(gds), value = TRUE)
p2 <- grep("Founder2", getScanID(gds), value = TRUE)
gds <- setParents(gds, parents = c(p1, p2), flip = TRUE, mono = TRUE, bi = TRUE)
```
If you set `flip = TRUE`, this function also sorts the genotype data to make the allele of the first parent being the reference allele. Therefore, the order of sample names given to the `parents` argument is important. In this example, all the alleles found in "Founder1" are set as the reference alleles. If you do not need to make alleles of the first founder to be reference alleles, leave `flip = FALSE` as default.



## Data QC and filtering
The next step is to visualize statistical summaries of the data. Get genotype data summaries as mentioned in the previous section.
```{r}
gds <- countGenotype(gds)
```
\ 

Then, get histograms.
```{r}
histGBSR(gds, stats = "missing")
```
\ 
```{r}
histGBSR(gds, stats = "het")
```
\ 
```{r}
histGBSR(gds, stats = "raf")
```
\ 

As the histograms showed, the data contains a lot of missing genotype calls with unreasonable heterozygosity in a F2 population. Reference allele frequency shows a bias to reference allele. If you can say your population has no strong segregation distortion in any positions of the genome, you can filter out the markers having too high or too low reference allele frequency.
```{r eval=FALSE}
# filter out markers with reference allele frequency
# less than 5% or more than 95%.
gds <- setSnpFilter(gds, maf = 0.05) 
```
\ 

However, sometimes filtering based on allele frequency per marker removes all markers from regions truly showing segregation distortion. Although heterozygosity also can be a criterion to filter out markers, this will removes too many markers which even contains useful information for genotyping. 
\ 

If we found poor quality samples in you dataset based on missing rate, heterozygosity, and reference allele frequency, we can omit those samples with `setScanFilter()`.
```{r eval=FALSE}
# Filter out samples with more than 90% missing genotype calls,
# less than 5% heterozygosity, and less than 5% minor allele frequency.
gds <- setScanFilter(gds, missing = 0.9, het = 0.05, maf = 0.05)
```
\ 

Before filtering using `setSnpFilter()` and `setScanFilter()`, we recomend that you conduct filtering on each genotype call based on read depth. The error correction via `r Biocpkg("GBScleanR")` is robust against low coverage calls, while genotype calls messed up by mismapping might lead less reliable error correction. Therefore, filtering for extremely high coverage calls are necessary rather than that for low coverage ones.
```{r}
# Filter out genotype calls supported by reads less than 2 reads.
gds <- setCallFilter(gds, dp_count = c(2, Inf))
# Filter out genotype calls supported by reads more than 100.
gds <- setCallFilter(gds, dp_count = c(0, 100))
# Filter out genotype calls based on quantile values 
# of read counts at markers in each sample.
gds <- setCallFilter(gds, scan_ref_qtile = c(0, 0.9), scan_alt_qtile = c(0, 0.9))
```
\ 

Since missing genotype calls left in the data basically give no negative effect on genotype error correction. Therefore, you can leave any missing genotype calls. We can, however, remove markers based on missing genotype calls, if you need.
```{r}
# Remove markers having more than 75% of missing genotype calls
gds <- setSnpFilter(gds, missing = 0.2) 
nsnp(gds)
```
\ 

To check statistical summaries of the filtered genotype data, we need to set `node = "filt`. Otherwise, `countGenotype()` used the raw genotype data.
```{r}
gds <- countGenotype(gds, node = "filt")
```
\ 
```{r}
histGBSR(gds, stats = "missing")
```
\ 
```{r}
histGBSR(gds, stats = "het")
```
\ 
```{r}
histGBSR(gds, stats = "raf")
```
\ 

We can still see the markers showing distortion in allele frequency, while the expected allele frequency is 0.5 in a F2 population. To investigate that those markers having distorted allele frequency were derived from truly distorted regions or just error prone markers, we must check if there are regions where the markers with distorted allele frequency are clustered.
```{r}
plotGBSR(gds, stats = "raf")
```
\ 

No region seem to have severe distortion. Based on the histogram of reference allele frequency, we can roughly cut off the markers with frequency more than 0.75 or less than 0.25, in other words, less than 0.25 of minor allele frequency.
```{r}
gds <- setSnpFilter(gds, maf = 0.25)
nsnp(gds)
```
\ 

Let's see the statistics again.
```{r}
gds <- countGenotype(gds)
histGBSR(gds, stats = "missing")
```
\ 
```{r}
histGBSR(gds, stats = "het")
```
\ 
```{r}
histGBSR(gds, stats = "raf")
```
\ 

At the end of filtering, check marker density and genotype ratio per marker along chromosomes.
```{r}
# Marker density
plotGBSR(gds, stats = "marker")
```
\ 
```{r}
plotGBSR(gds, stats = "geno")
```
\ 
The `coord` argument controls the number of rows and columns of the facets in the plot.


## Genotype estimation
### Prepare scheme information
Before executing the function for true genotype estimation, we need to build a scheme object. Our sample data is of a biparental F2 population derived from inbred founders. Therefore, we should run `initScheme()` and `addScheme()` as following.
```{r}
gds <- initScheme(gds, crosstype = "pairing", mating = matrix(1:2, 2))
gds <- addScheme(gds, crosstype = "selfing")
```
\ 
The function `initScheme()` initializes the scheme object with information about founders. You need to specify a matrix indicating combinations of `mating`, in which each column shows a pair of parental samples. For example, if you have only two parents, the `mating` matrix should be `mating = matrix(1:2, nrow = 2, ncol = 1)` or equivalents. The indices used in the matrix should match with the IDs labeled to parental samples by `setParents()`. To confirm the IDs for parental samples, run the following code.
```{r}
getParents(gds)
```
The created `GbsrScheme` object is set in the `scheme` slot of the `GbsrGenotypeData` object.
The function `addScheme()` adds the information about the next breeding step of your population. In the case of our example data, the second step was selfing to produce F2 individuals from the F1 obtained via the first founder crossing.
\  
If your population was derived from a 4-way or 8-way cross, you need to add more `paring` steps. In the case of 8-way RILs developed by three pairing crosses followed by five selfing cycles, the scheme object should be built as following. First we need to initialize the scheme object with specifying the first mating scheme. The crosstype argument should be "pairing" and the mating argument should be given as a matrix in which each pairing combination of parents are shown in each column. The following case indicates the pairing of parent 1 and 2 as well as 3 and 4, 5 and 6, and 7 and 8.
```{r eval=FALSE}
gds <- initScheme(gds, crosstype = "pair", mating = cbind(c(1:2), c(3:4), c(5:6), c(7:8)))
```
\  
Now the progenies of the crosses above have member ID 9, 10, 11,
and 12 for each combination of mating. You can check IDs with showScheme().
```{r eval=FALSE}
showScheme(gds)
```
\  
Then, add the step to make 4-way crosses.
```{r eval=FALSE}
gds <- addScheme(gds, crosstype = "pair", mating = cbind(c(9:10), c(11:12)))

# Check IDs.
showScheme(gds)
```
\  
Add the last generation of the paring step .
```{r eval=FALSE}
gds <- addScheme(gds, crosstype = "pair", mating = cbind(c(13:14)))

#' # Check IDs.
showScheme(gds)
```
\  
Now we have the scheme information of a 8-way cross.
The follwoing steps add the selfing cycles.
```{r eval=FALSE}
# Inbreeding by five times selfing.
gds <- addScheme(gds, crosstype = "self")
gds <- addScheme(gds, crosstype = "self")
gds <- addScheme(gds, crosstype = "self")
gds <- addScheme(gds, crosstype = "self")
gds <- addScheme(gds, crosstype = "self")
```
You can set `crosstype = "sibling"` or `crosstype = "random"`, if your population was developed through sibling crosses or random crosses, respectively.｀

### Execute genotype estimation
The following codes suppose that you built the scheme object for the example data that is a biparental F2 population derived from a cross between inbred parents, not for the 8-way RILs explained above.
Now we can execute genotype estimation for error correction. `r Biocpkg("GBScleanR")` estimates error pattern via iterative optimization of parameters for genotype estimation. We could not guess the best number of iterations, but our simulation tests showed `iter = 4` usually saturates the improvement of estimation accuracy.
```{r message=FALSE}
gds <- estGeno(gds, iter = 4)
```
\ 

If your population derived from outbred founders, please set `het_parents = TRUE`.
```{r eval=FALSE}
gds <- estGeno(gds, het_parent = TRUE, iter = 4)
```
The larger number of iterations makes running time longer. If you would like to execute no optimization, set `optim = FALSE` or `iter = 1`.
\ 

```{r eval=FALSE}
# Following codes do the same.
gds <- estGeno(gds, iter = 1)
gds <- estGeno(gds, optim = FALSE)
```
\ 

### Get the results
All of the results of estimation are stored in the gds file linked to the `GbsrGenotypeData` object. You can obtain the estimated genotype data via the `getGenotype()` function with `node = "cor"`.
```{r}
est_geno <- getGenotype(gds, node = "cor")
```
\ 

`r Biocpkg("GBScleanR")` also estimates phased founder genotypes and you can access it.
```{r}
founder_geno <- getGenotype(gds, node = "parents")
```




`r Biocpkg("GBScleanR")` first internally estimate phased haplotype and then convert them to genotype calls. If you need the estimated haplotype data, run `getHaplotype()`.
```{r}
est_hap <- getHaplotype(gds)
```
\ 

The function `gbsrGDS2VCF()` generate a VCF file containing the estimated genotype data and phased haplotype information. The estimated haplotypes are indicated in the FORMAT field with the HAP tag. The founder genotypes correspond to each haplotype are indicated in the INFO field with the PGT tag. HAP shows the pair of haplotype for each marker of each sample, while PGT shows the allele of each haplotype.
```{r}
out_fn <- tempfile("sample_est", fileext = ".vcf.gz")
gbsrGDS2VCF(gds, out_fn)
```
\ 
Same with `subsetGDS()`, `gbsrGDS2VCF` automatically close the connection to the GDS file of the input `GbsrGenotypeData` object for internal file handling. Please use `openGDS()` to open the connection again if you need.
```{r}
gds <- openGDS(gds)
```


# Closing the connection
To safely close the connection to the GDS file, use `closeGDS()`.
```{r}
closeGDS(gds)
closeGDS(subset_gds)
```



# Session info{-}
```{r}
sessionInfo()
```

