## Installing Required Packages

Before proceeding, ensure that the necessary package are installed and loaded.
We use `cTMed` for calculating total, direct, and indirect effects in continuous-time mediation model.

```{r, include = FALSE, message = FALSE, warning = FALSE, results = 'hide'}
pkg <- c("dynr", "expm", "simStateSpace", "cTMed")
for (i in seq_along(pkg)) {
  if (!require(pkg[i], character.only = TRUE, quietly = TRUE)) {
    install.packages(pkg[i], dependencies = TRUE)
  }
}
```

```{r}
library(cTMed)
```

## Extracting Matrices for Use in `cTMed`

We begin by defining the drift matrix `phi` ($\boldsymbol{\Phi}$).

```{r}
phi <- matrix(
  data = c(
    -0.357, 0.771, -0.450,
    0.000, -0.511, 0.729,
    0.000, 0.000, -0.693
  ),
  nrow = 3,
  ncol = 3
)
phi
```

Next, we assign row and column names to `phi` ($\boldsymbol{\Phi}$), which will be used to index the matrix.

```{r}
colnames(phi) <- rownames(phi) <- c("x", "m", "y")
phi
```

We need the process noise covariance matrix `sigma` ($\boldsymbol{\Sigma}$) to calculate the standardized total, direct, and indirect effects.

```{r}
sigma <- matrix(
  data = c(
    0.24455556, 0.02201587, -0.05004762,
    0.02201587, 0.07067800, 0.01539456,
    -0.05004762, 0.01539456, 0.07553061
  ),
  nrow = 3,
  ncol = 3
)
sigma
```

We then create a sequence of time intervals `delta_t` ($\Delta t$) ranging from 0.01 to 10, with a total of 1,000 equally spaced values.

```{r}
delta_t <- seq(from = 0.01, to = 10, length.out = 1000)
```

## Total, Direct, and Indirect Effects in CT-Med

Now, we compute the total, direct, and indirect effects across the sequence of `delta_t` ($\Delta t$), and visualize their dynamic behavior.

```{r}
med <- Med(
  phi = phi,
  delta_t = delta_t,
  from = "x",
  to = "y",
  med = "m"
)
plot(med)
```

## Standardized Total, Direct, and Indirect Effects in CT-Med

Let's calculate the standardized total, direct, and indirect effects for the sequence of `delta_t` ($\Delta t$). We plot to visualize the dynamics.

```{r}
med_std <- MedStd(
  phi = phi,
  sigma = sigma,
  delta_t = delta_t,
  from = "x",
  to = "y",
  med = "m"
)
plot(med_std)
```
