---
title: "Model specification"
author: "Oliver Jayasinghe and Rex Parsons"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{model-specification}
  %\VignetteEncoding{UTF-8}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  markdown: 
    wrap: 72
---

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

```{r srr, eval = FALSE, echo = FALSE}
#' @srrstats {G2.0a}
#' @srrstats {G2.1a}
#' @srrstats {RE1.1}
```

```{r setup, message=FALSE}
library(GLMMcosinor)
library(dplyr)
```

```{r, echo=F}
withr::with_seed(
  50,
  {
    testdata_simple <- simulate_cosinor(
      1000,
      n_period = 2,
      mesor = 5,
      amp = 2,
      acro = 1,
      beta.mesor = 4,
      beta.amp = 1,
      beta.acro = 0.5,
      family = "poisson",
      period = c(12),
      n_components = 1,
      beta.group = TRUE
    )

    testdata_simple_gaussian <- simulate_cosinor(
      1000,
      n_period = 2,
      mesor = 5,
      amp = 2,
      acro = 1,
      beta.mesor = 4,
      beta.amp = 1,
      beta.acro = 0.5,
      family = "gaussian",
      period = c(12),
      n_components = 1,
      beta.group = TRUE
    )

    testdata_two_components <- simulate_cosinor(
      1000,
      n_period = 10,
      mesor = 7,
      amp = c(0.1, 0.4),
      acro = c(1, 1.5),
      beta.mesor = 4.4,
      beta.amp = c(2, 1),
      beta.acro = c(1, -1.5),
      family = "poisson",
      period = c(12, 6),
      n_components = 2,
      beta.group = TRUE
    )
  }
)
```

## `cglmm()`

`cglmm()` wrangles the data appropriately to fit the cosinor model given
the formula specified by the user. It provides estimates of amplitude,
acrophase, and MESOR (Midline Statistic Of Rhythm).

The formula argument for `cglmm()` is specified using the `{lme4}` style
(for details see `vignette("lmer", package = "lme4")`). The only
difference is that it allows for use of an `amp_acro()` call within the
formula that is used to identify the circadian components and relevant
variables in the `data.frame`. Any other combination of covariates can
also be included in the formula as well as random effects and
zero-inflation (`ziformula`) and dispersion (`dispformula`) formulae.
For detailed examples of how to specify models, see the
[mixed-models](https://docs.ropensci.org/GLMMcosinor/articles/mixed-models.html),
[model-specification](https://docs.ropensci.org/GLMMcosinor/articles/model-specification.html)
and
[multiple-components](https://docs.ropensci.org/GLMMcosinor/articles/multiple-components.html)
vignettes.

## Using cglmm()

The following examples use data simulated by the the `simulate_cosinor`
function.

### Specifying a single-component model with no grouping variable

Here, we fit a simple cosinor model to "testdata_simple" - simulated
data from a Poisson distribution loaded in this vignette. In this
example, there is no grouping variable.

```{r, eval = F}
testdata_simple <- simulate_cosinor(
  1000,
  n_period = 2,
  mesor = 5,
  amp = 2,
  acro = 1,
  beta.mesor = 4,
  beta.amp = 1,
  beta.acro = 0.5,
  family = "poisson",
  period = c(12),
  n_components = 1,
  beta.group = TRUE
)
```

```{r, message=F, warning=F}
object <- cglmm(
  Y ~ amp_acro(times,
    period = 12
  ),
  data = filter(testdata_simple, group == 0),
  family = poisson()
)
object
```

The output shows the estimates for the raw coefficients in addition to
the transformed estimates for amplitude (amp) and acrophase (acr) and
MESOR (`(Intercept)`). The previous section of this vignette: [An
overview of the statistical methods used for parameter
estimation](https://docs.ropensci.org/GLMMcosinor/articles/GLMMcosinor.html#an-overview-of-the-statistical-methods-used-for-parameter-estimation)
outlines the difference between the raw coefficients and the transformed
coefficients.

We would interpret the output as follows:

-   `MESOR estimate = 4.99845`

-   `Amplitude estimate = 1.08228`

-   `Acrophase estimate = 0.99913`

Note that this estimate is in radians to align with conventions. To
interpret this, we can express `0.99913 radians` as a fraction of the
total $2\pi$ and multiply by the period to get the time when the
response is a maximal. Hence, $\frac{0.99913}{2\pi} \times 12 = 1.908$
in the units of the `time_col` column in the original dataframe. This is
saying that the peak response would occur after 1.908 time-units and
every 12 time-units after this. We can confirm this by plotting:

```{r}
autoplot(object, superimpose.data = TRUE)
```

### Specifying a single-component model with a grouping variable and a shared MESOR

Now, we can add a grouping variable by adding the name of the group in
the `amp_acro()` function:

```{r, eval=F}
testdata_simple_gaussian <- simulate_cosinor(
  1000,
  n_period = 2,
  mesor = 5,
  amp = 2,
  acro = 1,
  beta.mesor = 4,
  beta.amp = 1,
  beta.acro = 0.5,
  family = "gaussian",
  period = c(12),
  n_components = 1,
  beta.group = TRUE
)
```

```{r, message=F, warning=F}
object <- cglmm(
  Y ~ amp_acro(times,
    period = 12,
    group = "group"
  ),
  data = testdata_simple_gaussian,
  family = gaussian
)
object
```

In the example above, the amplitude and phase are being estimated
separately for the two groups but the **intercept term is shared**. This
represents a shared estimate of the MESOR for both groups and is useful
if two groups are known to have a common baseline (or equilibrium
point). Hence, we would interpret the transformed coefficients as
follows:

-   The MESOR estimate is 4.47411 for both `group = 0` and `group = 1`.

-   The estimates for amplitude and acrophase are with reference to the
    a MESOR estimate of 4.47411

```{r}
autoplot(object)
```

However, the groups in this dataset were simulated with two different
MESORs, and so it would be more appropriate to specify an intercept term
in the formula, as this will estimate the MESOR for both `group = 0` and
`group = 1`:

### Specifying a single-component model with a grouping variable and an intercept (MESOR)

Similarly to a normal regression model with `{lme4}` or `{glmmTMB}`, we
can add a term for the group in the model so that we can estimate the
**difference in MESOR** between the two groups.

```{r, message=F, warning=F}
object <- cglmm(
  Y ~ group + amp_acro(times,
    period = 12,
    group = "group"
  ),
  data = testdata_simple_gaussian,
  family = gaussian()
)
object
```

This is the same dataset used in the previous example, but note the
following differences:

-   The MESOR estimate for the reference group (`group = 0`) is given by
    `(Intercept) = 4.96476`

-   The estimate for the difference between the MESOR of the reference
    group (`group = 0`) and the treatment group (`group = 1`) is given
    by `[group=1] = -0.98129`. As such, the estimate for the MESOR of
    `group = 1` is `3.98347`.

-   The estimates for amplitude and acrophase are slightly different to
    the previous example because there is no longer a shared MESOR.

Plotting this model and comparing to the previous model which used the
same dataset, one can appreciate the importance of specifying the
formula correctly in order to gain the most accurate model.

```{r}
autoplot(object)
```

We may also be interested in estimating the MESOR for the two groups
separately, rather than the difference between groups. To achieve this,
we can remove the intercept term by using `0 +`.

```{r, message=F, warning=F}
cglmm(
  Y ~ 0 + group + amp_acro(times,
    period = 12,
    group = "group"
  ),
  data = testdata_simple,
  family = poisson()
)
```

### Specifying more complicated models using the `amp_acro()` function

The `amp_acro()` function controls the cosinor components of model
(specifically, this affects just the fixed-effects part). It provides
the user with the ability to specify grouping structures, the period of
the rhythm, and the number of components. There are several arguments
that the user must specify:

-   `group` is the name of the grouping variable in the dataset. This
    can be a string or an object

-   `time_col` is the name of the time column in the dataset. This can
    be a string or an object

-   `n_components` is the number of components.

If the user wishes to fit a multicomponent cosinor model, they can
specify the number of components using the `n_components` variable. The
value of `n_components` will need to match the length of the `group` and
`period` arguments as these will be combined for each component.

For example:

```{r, eval=F}
testdata_two_components <- simulate_cosinor(
  1000,
  n_period = 10,
  mesor = 7,
  amp = c(0.1, 0.4),
  acro = c(1, 1.5),
  beta.mesor = 4.4,
  beta.amp = c(2, 1),
  beta.acro = c(1, -1.5),
  family = "poisson",
  period = c(12, 6),
  n_components = 2,
  beta.group = TRUE
)
```

```{r, message=F, warning=F}
cglmm(
  Y ~ group + amp_acro(
    time_col = times,
    n_components = 2,
    period = c(12, 6),
    group = c("group", "group")
  ),
  data = testdata_two_components,
  family = poisson()
)
```

In the output, the suffix on the estimates for amplitude and acrophase
represents its component:

-   `[group=0]:amp1 = 0.10113` represents the estimate for amplitude of
    `group 0` for the first component

-   `[group=1]:amp1 = 2.00645` represents the estimate for amplitude of
    `group 1` for the first component

-   `[group=0]:amp2 = 0.39776` represents the estimate for amplitude of
    `group 0` for the second component

-   `[group=1]:amp2 = 1.00162` represents the estimate for amplitude of
    `group 1` for the second component

-   *Similarly for acrophase estimates*

If a multicomponent model has one component that is grouped with other
components that aren't, the vector input for `group` must still be the
same length as `n_components` but have the non-grouped components
represented as `group = NA`.

For example, if we wanted only the first component to have a grouped
component, we would specify the `group` argument as
`group = c("group", NA))`.

For a detailed explanation of how to specify multi-component models, see
[multiple-components](https://docs.ropensci.org/GLMMcosinor/articles/multiple-components.html)

### Dispersion and zero-inflation model specification

The `cglmm()` function allows users to specify formulas for dispersion
and zero-inflation models. These formulas are independent of the main
formula specification:

```{r, message=F, warning=F}
testdata_disp_zi <- simulate_cosinor(1000,
  n_period = 6,
  mesor = 7,
  amp = c(0.1, 0.4, 0.5),
  acro = c(1, 1.5, 0.1),
  beta.mesor = 4.4,
  beta.amp = c(2, 1, 0.4),
  beta.acro = c(1, -1.5, -1),
  family = "gaussian",
  period = c(12, 6, 8),
  n_components = 3
)
object_disp_zi <- cglmm(
  Y ~ group + amp_acro(times,
    n_components = 3,
    period = c(12, 6, 8),
    group = "group"
  ),
  data = testdata_disp_zi, family = gaussian(),
  dispformula = ~ group + amp_acro(times,
    n_components = 2,
    group = "group",
    period = c(12, 6)
  ),
  ziformula = ~ group + amp_acro(times,
    n_components = 3,
    group = "group",
    period = c(7, 8, 2)
  )
)

object_disp_zi
```

The output provides estimates for conditional model (default model), the
dispersion model, and also the zero-inflation model. By default,
`dispformula = ~1`, and `ziformula = ~0` which means these additional
models will not be generated in the output.

*Note that in the example above, the value for the periods and the
number of components in the dispersion and zero-inflation formulas were
chosen arbitrarily and purely for demonstration.*

## Using `summary(cglmm)`

The `summary()` method for `cglmm` objects provides a more detailed
summary of the model and its parameter estimates and uncertainty. It
outputs the estimates, standard errors, confidence intervals, and
$p$-values for both the raw model parameters and the transformed
parameters. The summary statistics do not represent a comparison between
any groups for the cosinor components - that is the role of the
`test_cosinor()` function.

Here is an example of how to use `summary()`:

```{r, message=F, warning=F}
object <- cglmm(
  Y ~ group + amp_acro(times,
    period = 12,
    group = "group"
  ),
  data = testdata_simple,
  family = poisson()
)
summary(object)
```

The summary statistics for dispersion and zero-inflation models will
also be provided by the `summary()` function, if the original `cglmm`
object being analyzed contains them. The following demonstration uses
the model specified in the **Dispersion and Zero-inflation model
specification** section of this vignette:

```{r, message=F, warning=F}
summary(object_disp_zi)
```

*Note that this dataset was not simulated with consideration of
dispersion or zero-inflation characteristics, hence the lack of
significant P-values in the model summary for the dispersion and
zero-inflation models.*

## Assessing residual diagnostics of `cglmm` regression models using DHARMa

`{DHARMa}` is an R package used to assess residual diagnostics of
regression models fit using `{glmmTMB}` (which is what is used by
`cglmm()`).

For example, we can apply the functions from `DHARMa` on the `glmmTMB`
model within by accessing it with `$fit`.

```{r}
library(DHARMa)
plotResiduals(simulateResiduals(object$fit))
plotQQunif(simulateResiduals(object$fit))
```