---
title: "Introduction to sltree"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Introduction to sltree}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
```

`sltree` learns latent tree structures from data with continuous, binary and
ordinal variables. Latent correlations are estimated under a Gaussian copula,
converted to information distances, and the SLS algorithm recovers the latent
nodes and the tree topology from the bottom up.

```{r}
library(sltree)
```

## 1. A true tree

`latent_tree_models()` contains six preset trees.

```{r}
model <- latent_tree_models(1)
head(model)
```

`view_ltree()` also accepts a preset number. By default it draws an
interactive plot with visNetwork, or a static plot if visNetwork is not
installed.

```{r, eval = FALSE}
view_ltree(1)                        # direction = "LR" suits trees with many leaves
```

In the static plot latent nodes are circles and observed nodes are coloured
by type. The plot returns the `ltree` object.

```{r, fig.width = 7, fig.height = 5}
preset_tree <- view_ltree(1, "plot")
```

## 2. Simulating data

`simulate_ltree_data()` can generate data from the preset models; it needs
the pcalg and graph packages.

```{r, eval = FALSE}
set.seed(1234)
dat <- simulate_ltree_data(n = 1e5, model = model)
```

For a small reproducible example using only the package's required
dependencies, consider four observed variables with one common latent
Gaussian parent. We generate 400 observations and transform two columns to
binary and ordinal variables. The continuous transformations are monotone,
so all four columns follow the semi-parametric model.

```{r}
set.seed(1234)
n <- 400
h <- rnorm(n)
gaussian_x <- as.data.frame(replicate(4, 0.8 * h + 0.6 * rnorm(n)))
names(gaussian_x) <- paste0("V", 1:4)
x <- data.frame(
  V1 = exp(gaussian_x$V1),
  V2 = gaussian_x$V2^3,
  V3 = as.integer(gaussian_x$V3 > 0),
  V4 = findInterval(gaussian_x$V4, c(-0.5, 0.5))
)
head(x)

true_edges <- data.frame(
  node = c(paste0("V", 1:4), "H1"),
  parent = c(rep("H1", 4), "")
)
true_types <- c("continuous", "continuous", "binary", "ordinal", "latent")
true_tree <- ltree_from_edge(true_edges, true_types)
```

## 3. Learning the tree

`learn_sltree()` computes the information distance and passes it to `sls()`.
With the default `model = "stm"` it infers the variable types, estimates the
latent correlations, projects them with `nearPD` when Matrix is available,
and uses `-log|rho|` as the distance. Here we set `use_near_pd = FALSE` so
the example also runs without Matrix. The intermediate results show the
inferred variable types and estimated information distances.

```{r}
fit <- learn_sltree(x, tau1 = 3, tau2 = 5, use_near_pd = FALSE,
                   return_intermediate = TRUE)
est_tree <- fit$tree
fit$variable_types
round(fit$distance, 3)
edges_from_ltree(est_tree)
```

```{r, fig.width = 7, fig.height = 5}
view_ltree(est_tree, "plot")
```

Interactive viewing and file export are also available:

```{r, eval = FALSE}
view_ltree(est_tree)
save_ltree(est_tree, file.path(tempdir(), "est_tree"))  # PNG, EPS and HTML
```

The Gaussian, discrete and parametric mixed models use the same learning
interface. Discrete variables must all have the same number of observed
states; the parametric mixed model accepts binary and conditionally Gaussian
variables.

```{r}
tree_gaussian <- learn_sltree(gaussian_x, model = "gaussian")
h_binary <- rbinom(n, 1, 0.5)
discrete_x <- as.data.frame(replicate(4, rbinom(n, 1, 0.1 + 0.8 * h_binary)))
names(discrete_x) <- paste0("V", 1:4)
tree_discrete <- learn_sltree(discrete_x, model = "discrete")
mixed_x <- data.frame(
  V1 = rnorm(n, mean = 2 * h_binary - 1, sd = 0.6),
  V2 = rnorm(n, mean = 2 * h_binary - 1, sd = 0.6),
  V3 = discrete_x$V3,
  V4 = discrete_x$V4
)
tree_mixed <- learn_sltree(mixed_x, model = "mixed")
c(stm = is_ltree(est_tree), gaussian = is_ltree(tree_gaussian),
  discrete = is_ltree(tree_discrete), mixed = is_ltree(tree_mixed))
```

The `stm`, `gaussian` and `discrete` models allow observed variables to be
internal nodes; the parametric `mixed` model restricts them to leaves. Only
`stm` uses `nearPD` by default; set `use_near_pd` to change this.

The same steps can be run one at a time:

```{r}
variable_types <- infer_variable_types(x)
correlation <- latent_correlation(x, variable_types)
distance <- -log(abs(correlation)); diag(distance) <- 0
tree_from_steps <- sls(distance, tau1 = 3, tau2 = 5,
                       node_types = variable_types, node_names = colnames(x))
```

## 4. Comparing with the true tree

The RF distance compares the observed-node splits and ignores latent-node
names and the root position. Finite samples need not recover the exact true
tree; a value of zero indicates complete recovery in this example.

```{r}
robinson_foulds_distance(true_tree, est_tree)   # 0 if fully recovered
```

## 5. Observed internal nodes

`allow_observed_internal` controls whether observed variables may be internal
nodes. In `sls()` it defaults to `TRUE`; in `learn_sltree()` the default
depends on the model.
