---
title: "hsemx: extended hierarchical structural equation models"
author: "Rezzy Eko Caraka"
date: "`r Sys.Date()`"
output:
  rmarkdown::html_vignette:
    fig_width: 8
    fig_height: 5.2
vignette: >
  %\VignetteIndexEntry{hsemx: extended hierarchical structural equation models}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", dpi = 96, out.width = "100%",
                      message = FALSE, warning = FALSE)
set.seed(2026)
```

```{r}
library(hsemx)
```

**About.** `hsemx` (*hsem extended*) is an extended, re-engineered successor of
the CRAN package `hsem` 1.0 (Caraka, Noh & Lee, 2021), building on the
hierarchical-likelihood SEM of Caraka et al. (2021, 2022) and their
h-likelihood work in machine learning and software (Caraka et al., 2020, 2022;
see References).  It keeps the
h-likelihood framework and the function name `hsem()`, but replaces the
estimation engine and adds estimated cross-equation random-effect
covariances, indirect effects with random slopes, neural-network components,
path diagrams with random effects, assumption diagnostics, and simulation
tools.  Because it is a separate package, `hsem` and `hsemx` can be installed
side by side; load only one of them in a session, since both export `hsem()`.

## 1. The model

A hierarchical structural equation model (HSEM) is a recursive system of
(generalized) linear mixed models.  For equation $k$, observation $i$ and
cluster $j$

$$g_k(\mu_{kij}) = x_{kij}^\top\beta_k + z_{kij}^\top b_{kj},\qquad
y_{kij}\mid b \sim \text{EF}(\mu_{kij},\phi_{kij}),\qquad
\log\phi_{kij} = w_{kij}^\top\gamma_k ,$$

and the random coefficients of **all** equations that share a grouping factor
are stacked, $b_j = (b_{1j}^\top,\dots,b_{Kj}^\top)^\top \sim N(0,\Sigma)$.
The covariance matrix $\Sigma$ links the equations: for instance, the
covariance between the random $a$-path ($x\to m$) and the random $b$-path
($m\to y$) of a multilevel mediation model.  Given $b$, the responses of
different equations are independent, so endogenous variables can be used as
predictors of later equations.

Estimation uses the h-likelihood $h = \log f(y\mid u) + \log f(u)$ with
$b = \Lambda(\theta)u$, $u\sim N(0,I)$:

* the joint mode of $h$ in $(\beta,u)$ is found by penalised IRLS;
* variance components and dispersion parameters maximise the adjusted
  profile likelihood $p_u(h)$ (ML) or $p_{\beta,u}(h)$ (REML).

For Gaussian identity-link equations these are the **exact** ML/REML
likelihoods; otherwise they are Laplace approximations computed with the
observed information (identical to `glmmTMB`'s Laplace approximation when
`laplace = TRUE`).  The package test suite checks the estimates against
`lme4`, `nlme` and `glmmTMB`.

## 2. Multilevel mediation with random paths

`mlmed` holds 50 clusters × 20 observations generated with $a=0.5$, $b=0.4$,
$c'=0.2$ and correlated random $a$- and $b$-paths (true average indirect effect
0.2525).

```{r fit}
fit <- hsem(list(m ~ x + (1 + x | cluster),
                 y ~ m + x + (1 + m + x | cluster)),
            data = mlmed)
summary(fit)
```

The average indirect effect over clusters is
$E[a_jb_j] = ab + \sigma_{a_j b_j}$ (Kenny, Korchmaros & Bolger, 2003):

```{r effects}
eff <- hsem_effects(fit, from = "x", to = "y", seed = 1)
eff
```

```{r effects-plot, fig.height = 6.5}
plot(eff)
```

## 3. Seeing the random effects: alternative path diagrams

**Classic.** Arrows carry the fixed paths; a black dot on an arrow marks a
random slope (with its SD across clusters); circles mark random intercepts;
dashed violet curves are significant random-effect correlations.

```{r path-classic, fig.height = 4.6}
hsem_plot_path(fit)
```

**Two-level.** The multilevel-SEM depiction: each random coefficient is a latent
between-cluster variable pointing at the intercept or slope it modifies.

```{r path-twolevel, fig.height = 6}
hsem_plot_path(fit, style = "twolevel")
```

**Cluster-specific path models**, chosen to span the distribution of the
cluster-specific indirect effect:

```{r path-clusters, fig.height = 5}
hsem_plot_path(fit, style = "clusters")
```

**Distributions of the random paths**, including the share of clusters whose
path is positive, $\Phi(\hat\beta/\hat\sigma)$:

```{r ridge, fig.height = 7}
hsem_plot_ridge(fit)
```

**Caterpillar plot** with prediction intervals, and the **random-effect
correlation matrix**:

```{r forest, fig.height = 6}
hsem_plot_forest(fit)
```

```{r recor, fig.width = 7, fig.height = 6}
hsem_plot_recor(fit)
```

## 4. Checking the assumptions

`hsem_check()` computes randomized quantile residuals, simulation-based scaled
residuals, standardized BLUPs, and a battery of tests; `plot()` draws the
dashboard for one equation.

```{r check}
chk <- hsem_check(fit, nsim = 200, seed = 1)
chk
```

```{r check-plot, fig.height = 13}
plot(chk, equation = "y")
```

**Visual inference.** In a lineup (Buja et al., 2009) the real residual plot is
hidden among plots of data simulated from the fitted model and refitted.  If
you can spot it, the model is rejected at level 1/20.

```{r lineup, eval = FALSE}
lu <- hsem_lineup(fit, equation = "y", type = "resid", seed = 7)
lu
lineup_answer(lu)
```

Cluster influence by leave-one-cluster-out refits:

```{r influence, eval = FALSE}
infl <- hsem_influence(fit)
plot(infl)
```

## 5. Dynamic SEM: cross-lagged panel with random effects

`smoke_ema` contains 80 persons × 40 occasions of urge to smoke and depression.
A two-level cross-lagged model with person-specific means, autoregressive and
cross-lagged effects:

```{r dsem}
ema <- hsem_center(subset(smoke_ema, time > 1), c("urge_lag1", "dep_lag1"), "id")
dsem <- hsem(list(urge ~ urge_lag1_cw + dep_lag1_cw + (1 + urge_lag1_cw | id),
                  dep  ~ urge_lag1_cw + dep_lag1_cw + (1 + dep_lag1_cw  | id)),
             data = ema)
summary(dsem)
```

Lagged predictors are centred within persons so that the lag effects are
within-person effects.  With observed person means the autoregressive effect
has the usual Nickell bias of order $1/T$.

```{r dsem-plot, fig.height = 4.8}
hsem_plot_path(dsem, show_cor = "all")
```

## 6. Non-Gaussian outcomes

```{r binary}
db <- hsem_sim_mediation(J = 60, nj = 25, family_y = "binomial", seed = 11)
fb <- hsem(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 | cluster)),
           data = db, family = list(m = "gaussian", y = binomial()), laplace = TRUE)
summary(fb)$coefficients
```

Effects through a non-identity link are reported on the linear-predictor scale
(with a warning), because a product of coefficients is not a causal indirect
effect on the probability scale.

## 7. Neural-network components

`hsem_nn()` adds a neural network $f(s)$ to selected equations while keeping the
linear paths and the random effects.  Architectures: `"mlp"`, `"resnet"`
(residual blocks), `"glu"` (gated linear units) and `"ensemble"` (deep ensemble).

```{r nn}
nnfit <- hsem_nn(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)),
                 data = mlmed, nn = list(y = ~ z1 + z2), architecture = "resnet",
                 hidden = c(32, 32, 32), epochs = 80, seed = 1)
round(fixef(nnfit$fit), 3)
cor(nn_component(nnfit), nnfit$data$g_true)
```

```{r nn-pdp, fig.height = 4}
hsem_nn_pdp(nnfit)
```

Cross-validated comparison of the architectures (held-out clusters):

```{r cv, eval = FALSE}
cv <- hsem_cv(list(m ~ x + (1 + x | cluster), y ~ m + x + (1 + m | cluster)),
              data = mlmed, nn = list(y = ~ z1 + z2), cluster = "cluster",
              architectures = c("linear", "mlp", "resnet", "glu", "ensemble"),
              folds = 5, seed = 1)
cv
plot(cv)
```

## 8. Simulation studies and power

```{r sim}
ss <- hsem_simstudy(
  nrep = 30,
  generate = function(r) hsem_sim_mediation(J = 30, nj = 10),
  fit = function(d) hsem(list(m ~ x + (1 + x | cluster),
                              y ~ m + x + (1 + m | cluster)), d),
  truth = c("m~x" = 0.5, "y~m" = 0.4, "y~x" = 0.2), seed = 1)
ss
```

```{r sim-plot, fig.height = 5.5}
plot(ss)
```

```{r zip, fig.height = 4.5}
plot(ss, type = "zip", parameter = "y~m")
```

Simulation-based power over the number of clusters:

```{r power, eval = FALSE}
pw <- hsem_power(J = c(10, 20, 40, 80), nrep = 200,
                 generate = function(J) hsem_sim_mediation(J = J, nj = 10, b = 0.2),
                 fit = function(d) hsem(list(m ~ x + (1 + x | cluster),
                                             y ~ m + x + (1 + m | cluster)), d),
                 parameter = "y~m", truth = c("y~m" = 0.2), seed = 1)
plot(pw)
```

## 9. Migrating from hsem 1.0 (CRAN)

`hsemfit()` and `hsemmodeling()` still work as wrappers around `hsem()`.  Note
that in hsem 1.0 a term `(x | id)` denoted a *single* random slope; the wrapper
translates it to `(0 + x | id)`.  Random effects in dispersion models and
non-normal random effects are not available in 2.x.

## References

*h-likelihood and HSEM work of the author*

* Caraka, R. E., Noh, M. & Lee, Y. (2021). *hsem: Hierarchical Structural Equation Model*. R package version 1.0, CRAN.
* Caraka, R. E., Lee, Y., Chen, R. C. & Toharudin, T. (2020). Using hierarchical likelihood towards support vector machine: theory and its application. *IEEE Access*, 8, 194795–194807. doi:10.1109/ACCESS.2020.3033796
* Caraka, R. E., Noh, M., Chen, R. C., Lee, Y., Gio, P. U. & Pardamean, B. (2021). Connecting climate and communicable disease to penta helix using hierarchical likelihood structural equation modelling. *Symmetry*, 13(4), 657. doi:10.3390/sym13040657
* Caraka, R. E., Noh, M., Lee, Y., Toharudin, T., Yusra, Tyasti, A. E., Royanow, A. F., Dewata, D. P., Gio, P. U., Basyuni, M. & Pardamean, B. (2022). The impact of social media influencers Raffi Ahmad and Nagita Slavina on tourism visit intentions across millennials and zoomers using a hierarchical likelihood structural equation model. *Sustainability*, 14(1), 524. doi:10.3390/su14010524
* Caraka, R. E., Lee, Y., Han, J., Lee, H., Noh, M., Ha, I. D., Gio, P. U. et al. (2022). Albatross analytics a hands-on into practice: statistical and data science application. *Journal of Big Data*, 9, 70. doi:10.1186/s40537-022-00626-y

*Methodology*

* Bauer, D. J., Preacher, K. J. & Gil, K. M. (2006). *Psychological Methods*, 11, 142–163.
* Buja, A. et al. (2009). *Phil. Trans. R. Soc. A*, 367, 4361–4383.
* Dunn, P. K. & Smyth, G. K. (1996). *J. Comput. Graph. Stat.*, 5, 236–244.
* Kenny, D. A., Korchmaros, J. D. & Bolger, N. (2003). *Psychological Methods*, 8, 115–128.
* Lee, Y. & Nelder, J. A. (1996). *JRSS B*, 58, 619–678.
* Lee, Y., Nelder, J. A. & Pawitan, Y. (2006). *Generalized Linear Models with Random Effects*. Chapman & Hall.
* Morris, T. P., White, I. R. & Crowther, M. J. (2019). *Statistics in Medicine*, 38, 2074–2102.
* Nakagawa, S., Johnson, P. C. D. & Schielzeth, H. (2017). *J. R. Soc. Interface*, 14, 20170213.
