---
title: "Visibility graphs and partial visibility curves with tsvisibility"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Visibility graphs and partial visibility curves with tsvisibility}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 6,
                      fig.height = 4)
has_lp <- requireNamespace("lpSolve", quietly = TRUE)
```

```{r setup}
library(tsvisibility)
```

## 1. From a time series to a graph

The *natural visibility* algorithm links two observations when the straight
line joining them passes above all the observations in between; the
*horizontal visibility* algorithm links them when every observation in
between is lower than both.

```{r}
x <- c(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5)
g_nat <- vgraph(x, type = "natural")
g_hor <- vgraph(x, type = "horizontal")
g_nat
g_hor
head(g_hor$edges)
```

```{r, fig.height = 3.5}
op <- par(mfrow = c(1, 2))
plot(g_nat)
plot(g_hor)
par(op)
```

The adjacency matrix can be dense or sparse, and the graph can be converted
to `igraph` to use any network measure:

```{r}
visibility_matrix(c(1, 2, 1, 2, 1))
if (requireNamespace("igraph", quietly = TRUE)) {
  ig <- vgraph_to_igraph(runif(200))
  c(clustering = igraph::transitivity(ig, type = "global"),
    mean_distance = igraph::mean_distance(ig))
}
```

## 2. Classical exact results

For an uncorrelated series the degree distribution of the horizontal
visibility graph is $P(k) = \frac13 (2/3)^{k-2}$ and its mean degree is 4.

```{r}
set.seed(1)
u <- runif(10000)
d <- degree_distribution(u)
head(cbind(d, theory = hvg_degree_iid(d$k)))
hvg_lambda(u, kmax = 12)$lambda   # log(3/2) = 0.405
```

Chaotic series have $\lambda < \log(3/2)$ and are time irreversible:

```{r}
z <- logistic_series(r = 4, n = 10000, x0 = 0.2)
hvg_lambda(z, kmax = 12)$lambda
visibility_irreversibility(u)
visibility_irreversibility(z)
```

Periodic orbits of the period-doubling cascade give *Feigenbaum graphs*,
whose degree distribution is known exactly:

```{r}
p8 <- logistic_series(logistic_superstable(3), 800, x0 = 0.3)
merge(degree_distribution(p8), feigenbaum_degree_distribution(3),
      by = "k", suffixes = c("_empirical", "_theory"))
```

## 3. Basins of visibility

The basin of visibility of a point is the set of points that it sees
(itself included); the basin of a set of points is the union of their
basins.

```{r}
y <- logistic_series(logistic_superstable(1), 24, x0 = 0.3)
visibility_distribution(y)     # half of the points see 3, half see 5
basin_set(y, c(2, 8))
visibility_set(y, c(2, 8))
```

## 4. Total visibility and partial visibility curve

The *total visibility number* is the smallest fraction of points whose
basins cover the whole series. The *partial visibility curve* gives, for
each fraction $\mu = m/n$ of chosen points, the largest fraction
$\nu$ of the series that they can see (Nuño and Muñoz, 2020).

Three solvers are available: a genetic algorithm (`"ga"`, used in the
original paper), a fast greedy heuristic (`"greedy"`) and an exact integer
linear programming formulation (`"exact"`, requires **lpSolve**).

```{r}
y4 <- logistic_series(logistic_superstable(2), 48, x0 = 0.3)
cg <- partial_visibility_curve(y4, method = "greedy")
total_visibility(y4, method = "greedy")$fraction
```

```{r, eval = has_lp}
ce <- partial_visibility_curve(y4, method = "exact")
total_visibility(y4, method = "exact")$fraction   # 1/4
```

The exact curves of the periodic series coincide with the analytical
$k$-polygonals of the paper:

```{r, eval = has_lp}
plot(ce, main = "Period 4 (k = 2)")
lines(pvc_theoretical(2), col = "red", lwd = 2)
lines(cg, col = "blue", lty = 2)
legend("bottomright", c("exact", "theory", "greedy"),
       col = c("black", "red", "blue"), lty = c(1, 1, 2), bty = "n")
c(exact = pvc_length(ce), theory = pvc_theoretical_length(2))
```

The lengths of the $k$-polygonals converge to the length of the partial
visibility curve at the onset of chaos:

```{r}
pvc_theoretical_length(c(1:6, Inf))
pvc_theoretical_length(c(1:6, Inf), cascade = "period3")
```

```{r}
plot(pvc_theoretical(1), type = "l", main = "Feigenbaum cascade")
for (k in 2:8) lines(pvc_theoretical(k), col = k)
```

## References

* Lacasa, L. et al. (2008). From time series to complex networks: the
  visibility graph. *PNAS* 105, 4972--4975.
* Luque, B. et al. (2009). Horizontal visibility graphs: exact results for
  random time series. *Phys. Rev. E* 80, 046103.
* Luque, B. et al. (2011). Feigenbaum graphs: a complex network perspective
  of chaos. *PLoS ONE* 6, e22411.
* Nuño, J. C. and Muñoz, F. J. (2020). The partial visibility curve of the
  Feigenbaum cascade to chaos. *Chaos, Solitons & Fractals* 131, 109537.
