---
title: "Getting started with the pedsuite"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteIndexEntry{Getting started with the pedsuite}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  echo = TRUE,
  collapse = TRUE,
  comment = "#>",
  dpi = 300,
  fig.align = "center")
```

## Installation

The following command installs the latest official versions of the **pedsuite** packages:

```{r, eval = FALSE}
install.packages("pedsuite")
```

Alternatively, you can install the development versions from GitHub:
```{r, eval = FALSE}
# install.packages("devtools")
devtools::install_github("magnusdv/pedsuite")
```

If you only need a few of the packages, you may choose to install them individually instead of the entire collection.

---


## A quick tour
The aim of this vignette is to illustrate a few of the possibilities of the **pedsuite** packages. It should be noted that we are barely scratching the surface here; in particular several packages are not even mentioned. For a more comprehensive overview, I recommend the [book](https://magnusdv.github.io/pedsuite/articles/web_only/publications.html#book).

To get started we load the **pedsuite** package, which is a convenient shortcut for loading all the [core packages](https://magnusdv.github.io/pedsuite/#core-packages), making their methods available in the current R session.

```{r}
library(pedsuite)
```

### 1. Create a pedigree (**pedtools**)
We begin by creating and plotting a pedigree with a child of first cousins:
```{r fc-ped1, fig.height = 3.5, fig.width = 3.5, out.width = "40%"}
x = cousinPed(1, child = TRUE)
plot(x)
```

For symmetry let us change the sex of individual 3. We also take the opportunity to showcase some of the plot options (many more are available - see the help page by typing `?plotmethods`): 
```{r fc-ped2, fig.height = 3.5, fig.width = 3.5, out.width = "40%"}
x = swapSex(x, ids = 3)

plot(x, 
     hatched = 9, 
     carrier = 7:8,
     fill = list(pink = 1), 
     textAnnot = list(inside = c("1" = "?")))
```

### 2. Calculate the inbreeding coefficient (**ribd**)
The inbreeding coefficient $f$ of a pedigree member is defined as the probability of *autozygosity* at a random autosomal locus. That is, the probability that the two homologous alleles have the same origin within the pedigree.

For a child of first cousins one can work out by pen and paper that $f = 1/16$. Alternatively, we can calculate it with the **ribd** function `inbreeding()`.
```{r}
inbreeding(x, ids = 9)
```
The output agrees with $f = 1/16$.

### 3. Realised inbreeding (**ibdsim2**)
For any particular child of first cousins, the actual autozygous fraction of the genome (except X & Y) is called the coefficient of *realised inbreeding*, denoted $f_R$. This may deviate substantially from the pedigree-based expectation $f = 1/16$.

We can simulate the distribution of $f_R$ with the **ibdsim2** package. Since this is not a core package we must load it separately.
```{r}
library(ibdsim2)
```

First, we use the function `ibdsim()` to simulate the recombination process in the entire pedigree, 200 times:
```{r}
sims = ibdsim(x, N = 200, seed = 123)
```

Now extract the autozygous segments of each simulation.
```{r}
fr = realisedInbreeding(sims, id = 9)
```

Here is a summary of the first 6 simulations, including the number of segments and various length statistics:
```{r}
head(fr$perSimulation)
```

And here is a histogram of the realised inbreeding coefficients (given in the right-most column above):
```{r fr-hist, echo = -1, out.width = "80%", fig.height = 3, fig.width = 7}
op <- par(mar = c(4.1, 4.1, 1, 1))
hist(fr$perSimulation$fReal, xlim = c(0, 0.15), breaks = 16, xlab = "f_R", main = NULL)

# Expected value
abline(v = 1/16, col = 2)
```

```{r, echo = F}
# Just for CRAN
par(op)
```

As we see, the distribution centres around the expectation $f = 1/16 = 0.0625$ (red vertical line) but has substantial spread. The sample standard deviation can be found in `fr$stDev`, which in our case is `r round(fr$stDev, 3)`.

### 4. Marker simulation (**forrel**)
Note that everything we have done so far has been purely theoretical, with no markers involved. In medical and forensic applications we usually work with genetic data in the form of marker genotypes, so let us simulate such a dataset for our family.

The `markerSim()` function of the **forrel** package simulates the genotypes of pedigree members for a specific type of markers. For instance, here we produce 500 SNPs with alleles `A` and `B` (equally frequent, by default):
```{r}
y = markerSim(x, N = 500, alleles = c("A", "B"))
```

We can see the genotypes of the first few markers by printing `y` to the console.
```{r}
y
```

### 5. Inference of pairwise relationships (**forrel**)
If this was a real dataset, a natural quality control step would be to check correctness of the pedigree. One way to do this is to use the data to estimate each pairwise relationship, and compare the result with the pedigree. The function `checkPairwise()` does all of this, and presents the result in a relationship triangle.
```{r check-pairwise, results="hide", fig.height = 5, fig.width = 5, out.width = "60%"}
checkPairwise(y)
```

The plot shows that all pairwise estimates are near their expected location in the triangle.


---


## Where to go from here
If you enjoyed this quick tour and would like more details, you should check out the GitHub README files of the packages that interest you, for instance:

* [pedtools](https://github.com/magnusdv/pedtools): Creating and working with pedigrees and marker data
* [forrel](https://github.com/magnusdv/forrel): Forensic pedigree analysis and relatedness analysis
* [ribd](https://github.com/magnusdv/ribd): Computation of pedigree-based relatedness coefficients
* [verbalisr](https://github.com/magnusdv/verbalisr): Verbal descriptions of pedigree relationships
* [ibdsim2](https://github.com/magnusdv/ibdsim2): Simulation of identity-by-descent sharing by family members
* [dvir](https://github.com/magnusdv/dvir): Disaster victim identification

Try the interactive pedigree builder **QuickPed**: https://magnusdv.shinyapps.io/quickped. 

The [pedtools vignette](https://cran.r-project.org/package=pedtools/vignettes/pedtools.html) contains details on pedigree objects in R and how to plot and manipulate them.
