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

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

has_cmdstan <- instantiate::stan_cmdstan_exists()
```

## Introduction

This package implements methods to analyse (multilevel) Vector Autoregression commonly used for the analysis of intensive longitudinal datasets like EMA data.

In the following vignette we will introduce the basic functionality of the package. For more elaborated usecases, we refer to the additional vignettes

- `vignette("Hypothesis-Testing")`
- `vignette("Mixed-Model")`
- `vignette("Missing-Data")`
- `vignette("Random-Effects")`
- `vignette("MCMC-Diagnostics")`


## Setup

First, lets load the package:
```{r setup}
library(bvarnet)
library(qgraph)
```

## Data

Now, we can load the example data:
```{r}
data(studentlife)
```

There is some missing data in the dataset. The models default options handle this by themselves. For a further elaboration on this, you can read `vignette("Missing-Data")`.

Currently, `bvarnet` allowes for the following outcome variables:

- binary (`family = "bernoulli")`
- ordinal (`family = "ordinal")` (adjacent category model)
- continuous (`family = "gaussian")`

For the following tutorial we will investigate the temporal network for the variables `anxious`, `calm`, `conventional`, `critical`, and `dependable`. All these variables are on a ordinal scale. Therefore we will use the adjacent category ordinal model to estimate this model.

## Prior Specification

First we need to specify the prior distributions that we want to use on the parameters.
For this we can use the `set_priors()` function. As we are running a ordinal model, without covariates, we have to specify priors on the temporal structure (denoted by the $\Phi$ matrix) and on the category threshold parameters ($\kappa$) which is specific to the adjacent category ordinal model.

```{r}
priors <- set_priors(phi = prior(family = "normal",
                                 loc = 0,
                                 scale = 0.5),
                     kappa = prior(family = "normal",
                                   loc = 0,
                                   scale = 1))

priors
```

Currently, three prior families are implemented: normal, student-t and chauchy. For standart deviations and random effects all of these priors are automatically scaled to half-priors. 
For each distribution, the location and scale parameters can be specified. For the student-t distribution, the degrees of freedom can also be specified.

## Model Estimation

```{r, eval = has_cmdstan, results='hide', message=FALSE}
fit <- bvar(
  id_col = "id",
  time_col = "day",
  y_cols = c("anxious", "calm", "conventional", "critical", "dependable"),
  x_cols = NULL,
  re_cols = NULL,
  re_temporal = FALSE,
  K = 1,
  data = studentlife,
  family = c("ordinal"),
  priors = priors,
  iter = 4000,
  warmup = 1000,
  chains = 4,
  cores = 4,
  seed = 1337
)
```

If you want to learn how to extend this model to a multilevel model, check out the `Vignette(Random-Effects)`.

## Stan Warnings

Most models will give a warning when initiating sampling, that looks like this:

```text
Chain 1 Informational Message: The current Metropolis proposal is about to be rejected because of the following issue:
Chain 1 Exception: categorical_logit_glm_lpmf: Intercept[3] is -inf, but must be finite! (in '/var/folders/n5/38kfmkv55hq8bnd03344d2b40000gn/T/RtmpkjgDq1/model-a60f79e9a37c.stan', line 153, column 8 to column 94)
Chain 1 If this warning occurs sporadically, such as for highly constrained variable types like covariance matrices, then the sampler is fine,
Chain 1 but if this warning occurs often then your model may be either severely ill-conditioned or misspecified.
Chain 1
```

This warning is printed by Stan when a proposed draw briefly violates internal constraints (here, producing a non-finite intercept), so that proposal is rejected. As long as it occurs only occasionally and the chains run, converge, and pass standard diagnostics, this warning is expected and can be safely ignored.

## Model Output

We can print an overview of the model we just ran using the `print(fit)` functions:
```{r, eval = has_cmdstan}
print(fit)
```

Here we get information about the number of variables and lags, the number of observations and some first indications if the model did converge.

### Summary

To further inspect the model parameters we can use the `summary(fit)` function:

```{r, eval = has_cmdstan}
summary(fit)
```

### Extracting Parameters

Here we can see, that we can not see all category threshold parameters ($\kappa$). To inspect them completely we have to extract them using `extract_param(fit, type = "Threshold")`:

```{r, eval = has_cmdstan}
params <- extract_param(fit, type = "Threshold")
params
```

## Network Visualization

If we are interested in the temporal network structure, we can inspect this using either the `extract_temporal(fit)`, or the `extract_network_matrix(fit)` functions. Here we will use the `extract_network_matrix(fit)` to plot the network:

```{r plot-network, eval = has_cmdstan}
nw_mat <- extract_network_matrix(fit)
qgraph(nw_mat)
```

Lastly, if you want to perform hypothesis tests on your estimated parameters we refer you to the `Vignette(Hypothesis-Testing)`.
