---
title: "Causal Inference for QTL Networks with R/qtlnet"
author: "Elias Chaibub Neto and Brian S. Yandell"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{QTLNET Overview}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  fig.width = 6,
  fig.height = 4.5
)
```

This vignette briefly describes the `qtlnet` R package. It incorporates the legacy `qdg` package and includes code corresponding to Chaibub Neto et al. (2008) and Chaibub Neto et al. (2010). Not all routines are described here, and parallel processing routines using Condor are documented separately in `inst/parallel/`.

## Installation

`qtlnet` depends on Bioconductor packages `graph` and `RBGL` (via `pcalg`) as well as CRAN packages `qtl`, `igraph`, `pcalg`, and `lavaan`. You can install the Bioconductor dependencies and CRAN dependencies from within R as follows:

```{r install, eval = FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE)) {
  install.packages("BiocManager")
}
BiocManager::install(c("graph", "RBGL"))
install.packages(c("qtl", "igraph", "pcalg", "lavaan"))
```

## QTLNET routines

Load `qtlnet` and inspect the bundled `Pscdbp.qtlnet` MCMC network example (from Ghazalpour et al. 2006 / Chaibub Neto et al. 2010):

```{r load-qtlnet, message = FALSE}
library(qtlnet)
data(Pscdbp.qtlnet)
summary(Pscdbp.qtlnet)
```

```{r plot-pscdbp}
pscdbp_graph <- igraph.qtlnet(Pscdbp.qtlnet)
plot(pscdbp_graph)
```

Additional bundled simulation and data examples can be explored interactively via `example()` (note that full network simulations and MCMC runs are wrapped in `\dontrun{}` in their help pages):

```{r qtlnet-examples, eval = FALSE}
## Acyclic and cyclic graph simulations (Chaibub Neto et al. 2008)
example(acyclic)
example(cyclica)
example(cyclicb)
example(cyclicc)

## GLX network example (Chaibub Neto et al. 2008; Ferrara et al. 2008)
example(glxnet)
```

## QDG routines

The QDG (QTL-driven Directed Graph) routines are incorporated into `qtlnet`. Below we generate synthetic data, infer a QDG model, and plot the inferred graph. We focus on a simple acyclic graph (`y1 -> y3`, `y2 -> y3`, and `y3 -> y4`) with QTLs affecting each of the four phenotypes.

Simulate a genetic map (20 autosomes, 10 unevenly spaced markers per chromosome) and an F2 cross with 200 individuals:

```{r simulate-cross}
set.seed(1234)
mymap <- qtl::sim.map(len = rep(100, 20), n.mar = 10, eq.spacing = FALSE, include.x = FALSE)
n.ind <- 200
mycross <- qtl::sim.cross(map = mymap, n.ind = n.ind, type = "f2")
```

Produce genotype imputations using `qtl::sim.geno()`. The `qtl::makeqtl()` function requires it, though a single imputation suffices here because there is no missing data and we use marker genotypes directly:

```{r sim-geno}
mycross <- qtl::sim.geno(mycross, n.draws = 1)
```

Sample 2 markers per phenotype from the cross and simulate the four phenotypes:

```{r simulate-phenos}
genotypes <- qtl::pull.geno(mycross)
geno.names <- dimnames(genotypes)[[2]]
m1 <- sample(geno.names, 2, replace = FALSE)
m2 <- sample(geno.names, 2, replace = FALSE)
m3 <- sample(geno.names, 2, replace = FALSE)
m4 <- sample(geno.names, 2, replace = FALSE)

## Get marker genotypes
g11 <- genotypes[, m1[1]]; g12 <- genotypes[, m1[2]]
g21 <- genotypes[, m2[1]]; g22 <- genotypes[, m2[2]]
g31 <- genotypes[, m3[1]]; g32 <- genotypes[, m3[2]]
g41 <- genotypes[, m4[1]]; g42 <- genotypes[, m4[2]]

## Generate phenotypes
y1 <- runif(3, 0.5, 1)[g11] + runif(3, 0.5, 1)[g12] + rnorm(n.ind)
y2 <- runif(3, 0.5, 1)[g21] + runif(3, 0.5, 1)[g22] + rnorm(n.ind)
y3 <- runif(1, 0.5, 1) * y1 + runif(1, 0.5, 1) * y2 +
  runif(3, 0.5, 1)[g31] + runif(3, 0.5, 1)[g32] + rnorm(n.ind)
y4 <- runif(1, 0.5, 1) * y3 +
  runif(3, 0.5, 1)[g41] + runif(3, 0.5, 1)[g42] + rnorm(n.ind)

mycross$pheno <- data.frame(y1, y2, y3, y4)
```

Create the markers list and `qtl` objects for each phenotype:

```{r make-qtl}
markers <- list(y1 = m1, y2 = m2, y3 = m3, y4 = m4)

allqtls <- lapply(markers, function(m) {
  m.pos <- qtl::find.markerpos(mycross, m)
  qtl::makeqtl(mycross, chr = m.pos[, "chr"], pos = m.pos[, "pos"])
})
```

Infer the QDG object:

```{r run-qdg}
out <- qdg(
  cross = mycross,
  phenotype.names = c("y1", "y2", "y3", "y4"),
  marker.names = markers,
  QTL = allqtls,
  alpha = 0.005,
  n.qdg.random.starts = 10,
  skel.method = "pcskel"
)
out
```

Plot the inferred graph. `graph.qdg()` returns an `igraph` object that can be plotted with `plot()` (or interactively with `igraph::tkplot()`):

```{r plot-qdg}
gr <- graph.qdg(out)
plot(gr)
```

## Scoring Directed Graphs with SEM (`lavaan`)

For directed graphs—and especially when candidate solutions include cyclic graphs where QDG's unnormalized log-likelihood cannot compare cyclic and acyclic structures—`qdg.sem()` fits structural equation models to the phenotype network using `lavaan`:

```{r run-qdg-sem}
out_sem <- qdg.sem(out, cross = mycross)
out_sem
out_sem$BIC.SEM
out_sem$path.coeffs
```

The scored `qdg.sem` object can also be converted to an `igraph` object and plotted:

```{r plot-qdg-sem}
gr_sem <- graph.qdg(out_sem)
plot(gr_sem)
```

For cyclic networks, `qdg.sem()` scores the candidate cyclic solutions returned by `qdg()`. Here we illustrate this on the bundled `cyclica` dataset:

```{r cyclic-sem}
data(cyclica)
cyclic_qdg <- qdg(
  cross = cyclica.data,
  phenotype.names = paste0("y", 1:6),
  marker.names = cyclica.qtl$markers,
  QTL = cyclica.qtl$allqtl,
  alpha = 0.005,
  n.qdg.random.starts = 10,
  skel.method = "pcskel"
)
cyclic_sem <- qdg.sem(cyclic_qdg, cross = cyclica.data)
cyclic_sem
```

## References

- Chaibub Neto E, Ferrara CT, Attie AD, Yandell BS (2008). Inferring causal phenotype networks from segregating populations. *Genetics* 179: 1089–1100.
- Chaibub Neto E, Keller MP, Attie AD, Yandell BS (2010). Causal Graphical Models in Systems Genetics: a unified framework for joint inference of causal network and genetic architecture for correlated phenotypes. *Annals of Applied Statistics* 4: 320–339.
