---
title: "4. Graphical VAR"
output:
  rmarkdown::html_vignette:
    toc: true
bibliography: references.bib
link-citations: true
vignette: >
  %\VignetteIndexEntry{4. Graphical VAR}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE, comment = "#>", message = FALSE, warning = FALSE,
  fig.width = 7, fig.height = 5.5
)
library(idiographic)
data(esm_srl)
vars <- c("efficacy", "value", "planning", "monitoring", "effort",
          "regulation", "motivated", "enjoyment", "anxiety")
has_cograph <- requireNamespace("cograph", quietly = TRUE)
```

The graphical vector autoregression models one person's multivariate series as a
first-order Gaussian process, in which each occasion's measurements are
determined jointly by the values of all variables one occasion earlier and by
the associations that remain among the variables within the same occasion. It is
an idiographic model, estimated for a single individual, on the premise that
within-person dynamics need not match the between-person structure of the group.
It presumes weak stationarity, meaning that the mean, variance,
and autocovariance of every series are constant across the observation window;
linear, lag-one dynamics; approximately Gaussian fluctuations; and equally
spaced measurement occasions. To these it adds a structural assumption of its
own — sparsity — namely that many of the possible associations are genuinely
absent, and that estimation should recover which ones.

The model yields two networks over the same variables [@epskamp2018mlvar]. The
temporal network is directed: an edge `from -> to` states that the value of
`from` at occasion $t-1$ predicts the value of `to` at occasion $t$, holding the
other lagged variables constant, so that each arrow is a claim about lag-one
prediction rather than co-occurrence. The contemporaneous network is undirected:
after the previous occasion has explained what it can, the part of each variable
left unexplained — its innovation — may still be associated with the innovations
of the others, and the contemporaneous edges are the partial correlations among
these remainders, the within-occasion associations that lagged prediction does
not account for.

`fit_graphical_var()` estimates both networks jointly by a penalized two-step
procedure: a lasso-penalized regression estimates the lagged effects, a graphical
lasso estimates the within-occasion associations from the residuals of that
regression, and the two steps alternate until the solution stabilizes. The
strength of the penalty is selected by the extended Bayesian information
criterion, whose conservatism is governed by a parameter that charges for every
retained edge. This is what
distinguishes the graphical estimator from the ordinary VAR fitted by
`fit_var()`, which returns a coefficient in every cell of both networks and
leaves the analyst to judge which small values are noise. Under the penalty,
weak edges are shrunk to exactly zero, so an absent edge is a model-selected
absence rather than a small estimate the reader rounds away; the cost is a
downward bias on the weights of the edges that survive.

# Data and preprocessing

The `esm_srl` data are the supplied anonymized momentary
self-regulated-learning, motivation, and anxiety ratings for 41 students, each
assessed repeatedly during a study. This vignette keeps the established worked
example: Quinn on all nine indicators. Quinn was chosen for this deliberately
edge-rich demonstration; the choice is not a population-sampling rule and must
not be used as evidence that every participant has a non-empty temporal
network. Because the penalty does not protect
against a violated stationarity assumption — a trend inflates the lagged
coefficients whether or not they are penalized — the stationarity screen
precedes the fit.

```{r audit}
preprocess(esm_srl, vars = vars, id = "name", subject = "Quinn")
```

Quinn contributes 79 occasions, of which 78 form complete current/lagged pairs.
Six of the nine series carry a linear-trend flag. The model below is therefore a
worked API and interpretation example, not a confirmatory analysis of Quinn's
dynamics. A substantive analysis should resolve the flagged non-stationarity
and report a detrending sensitivity analysis before interpreting the temporal
edges.

# Fitting the model

Two non-default arguments make this an intentionally sensitive demonstration.
`penalize_diagonal = FALSE` exempts the
autoregressions from the lasso penalty; the default penalizes them along with
the cross-lags, which shrinks the carry-over of each variable — often the most
robust temporal effect — to zero. `gamma = 0.1` is a less conservative selection
threshold than the default of 0.5. These settings preserve the established
non-empty worked network, but they are stated explicitly so that it cannot be
mistaken for an outcome-neutral default fit. The selected edges belong to the
more sensitive, less specific end of the selection scale.

```{r fit}
fit <- fit_graphical_var(esm_srl, vars = vars, id = "name", subject = "Quinn",
                         penalize_diagonal = FALSE, gamma = 0.1,
                         n_lambda = 8)
fit
```

The model is estimated on 78 lagged pairs. It retains four directed cross-lagged
temporal edges and the nine autoregressions, together with seven contemporaneous
partial correlations.

# Reading the output

The `summary()` method reports one row per network layer, with the edge count,
density, mean absolute weight, and the split of positive and negative edges.

```{r summary}
summary(fit)
```

The temporal layer holds four cross-lagged edges (density 0.056, mean absolute
weight 0.178) and the contemporaneous layer seven (density 0.194, mean absolute
weight 0.070); every retained edge in both layers is positive.

```{r edges-temporal}
edges(fit, network = "temporal", n = 5)
```

The directed temporal edges describe a motivation-to-regulation sequence.
Enjoyment at one occasion predicts higher effort regulation at the next (0.30),
feeling motivated predicts later enjoyment (0.16), and monitoring predicts later
motivation (0.08); anxiety predicts higher subsequent monitoring (0.17), a
within-person coupling of momentary anxiety to the regulation that follows it.

```{r edges-contemp}
edges(fit, network = "contemporaneous", n = 8)
```

The within-occasion structure is anchored by a positive enjoyment–anxiety
partial correlation (0.26) and a planning–regulation coupling (0.12), with
enjoyment and regulation connecting the motivation and self-regulation clusters
in the same moment.

```{r nodes}
nodes(fit)
```

`nodes()` separates each variable's outgoing and incoming cross-lagged strength
from its autoregression, and gives its total strength in the undirected
contemporaneous layer. Enjoyment is the busiest node across both layers,
receiving and sending temporal edges and anchoring the contemporaneous cluster.

# Visualizing the network

The `plot()` method draws every network in the result, and passing `layer=`
isolates one. Arrows in the temporal panel encode lag-one prediction; edge width
scales with absolute weight and colour encodes sign.

```{r plot-all, eval=has_cograph}
plot(fit)
```

```{r plot-temporal, eval=has_cograph}
plot(fit, layer = "temporal")
```

The temporal graph is directed and sparse, tracing the motivation-to-regulation
sequence the edge table quantified.

```{r plot-contemp, eval=has_cograph}
plot(fit, layer = "contemporaneous")
```

The contemporaneous graph is undirected, with enjoyment and regulation at the
junction of the momentary motivation and self-regulation associations.

Because the result combines a directed temporal layer and an undirected
contemporaneous layer, it is itself a mixed network, and `plot(fit, mixed =
TRUE)` draws both in one graph: the lag-one effects as curved arrows and the
contemporaneous partial correlations as straight edges.

```{r plot-mixed, eval=has_cograph}
plot(fit, mixed = TRUE)
```

# References
