Counterfactual Prediction and Simulation with SEMs in RTMB
R, RTMB
The past few posts, I’ve been talking a lot about just how to fit an SEM with RTMB and how to assess its fit. It’s been a bit messy, but fun! I hope. Assuming we have a model that we feel has the correct structure, though, how do you use it? Already I’ve looked at evaluating direct, indirect, and total effects of a driver in the model - something that is pretty darned common in the SEM world.
But, what if we want to look at a few different scenarios and do full counterfactual inference. Or we wanted to evaluate a piece of the whole model - nonlinearities and all! At the moment, while we can predict from single relationships, we cannot propagate predicted values through the whole.
Our Model
Let’s say we started with our simple model from before using the Keeley data -
We had a nice model for this
keeley_firesev_mod <- function(data, params){
# let's goooooooo!
getAll(data, params)
# What are we observing for later sims and predictions
rich <- OBS(rich)
cover_obs <- cover
cover <- OBS(cover)
# cover predictors
cover_sigma <- exp(log_cover_sigma)
cover_hat <- firesev_cover * firesev + cover_int
cover %~% dnorm(cover_hat, cover_sigma)
ADREPORT(cover_hat); ADREPORT(cover_sigma);
REPORT(cover_hat);
# predictors of richness
# GLM with a log link
log_rich_hat <- cover_rich * cover_obs + firesev_rich * firesev + rich_int
rich_hat <- exp(log_rich_hat)
theta = exp(log_theta)
rich %~% dnbinom2(mu = rich_hat, size = theta)
ADREPORT(rich_hat); REPORT(rich_hat)
}Which we can load and fit
library(RTMB)
library(RTMBdist)
library(dplyr) # for playing with coefficient tables
library(ggplot2) # for viz
data("keeley", package = "piecewiseSEM")
keeley_firesev_params <- list(
cover_rich = 1,
firesev_rich = 1,
rich_int = 1,
firesev_cover = 1,
cover_int = 1,
log_cover_sigma = log(sd(keeley$cover)),
log_theta = 1
)
# combine data in
cmb <- function(f, d) function(p) f(p, d)
# RTMB object
keeley_firesev_fit <- cmb(keeley_firesev_mod, keeley) |>
MakeADFun(keeley_firesev_params,
silent = TRUE)
#optimize
keeley_firesev_opt <- with(keeley_firesev_fit,
nlminb(par, fn, gr))Onwards to Prediction!
But, let’s say we want to make a prediction. Using our logic from predictions for regression we need to put in NAs for values we are predicting to. But, then we’re left with the usual conundrum - only now it’s compounded. What is our source of variability that we wish to propagate through the network? Do we want to look at our fit predictions, propagating only coefficient uncertainty? Or do we want to pull in residual variation? While in a single response variable framework, this question is fairly straightforward - fit or prediction error - in SEM it has real consequences. Let’s think about them for a moment.
Propagate coefficient uncertainty - OK, if this is all you want to do, again, makes sense going from a predictor variable to a response. But, in an SEM, we are faced with a real issue. Let’s say you have a -> b -> c. If you predict b from a, do you 1) predict c from the mean value of the prediction in b and use coefficient uncertainty? Or, do you 2) predict c using the prediction of b, its uncertainty, and then the uncertainty in the coefficient for b? I think most of us would answer 2 (right?) This raises a third issue, however. 3) What then does the prediction of c mean? The predicted value would be the estimate of c conditioned on the residual value of b being set to 0. Thus c is only influenced by variables in the system, and there are no other outside influences. In a system of linear equations, or one where error is very small, this is fine, as the average will at least still be the same. However, as soon as we introduce nonlinearities, this becomes problematic due to Jensen’s inequality. ${f(x)} f({x})$.
So, ok, should we propagate residual uncertainty as well? For correct intervals for prediction of actual values instead of just trying to understand how the influence of a change in a variable wends its way through a network of effects - as we did when decomposing total, direct, and indirect effects previously - then we have to consider the unmeasured residual influences in the model. Further, we might even want to consider proper propagate both coefficient and residual uncertainty to get the correct intervals here. Three layers of tasks!
Fortunately, it’s not a horrible task. We can build a model that outputs a few different responses - first, our values based on just propagating parameter uncertainty. This is just calculating effects through using fitted - *_hat - values. So, we might think we should build a model like so:
keeley_firesev_predict <- function(data, params){
# let's goooooooo!
getAll(data, params)
cover <- OBS(cover);
rich <- OBS(rich);
# cover predictors
cover_sigma <- exp(log_cover_sigma)
cover_hat <- firesev_cover * firesev + cover_int
cover %~% dnorm(cover_hat, cover_sigma)
# predictors of richness
# GLM with a log link
log_rich_hat <- cover_rich * cover_hat + firesev_rich * firesev + rich_int
rich_hat <- exp(log_rich_hat)
theta = exp(log_theta)
rich %~% dnbinom2(mu = rich_hat, size = theta)
# Collect and report
ADREPORT(cover_hat); REPORT(cover_hat);
ADREPORT(rich_hat); REPORT(rich_hat)
}Now, notice the line
log_rich_hat <- cover_rich * cover_use + firesev_rich * firesev + rich_int
This is using fit values instead of predicted values. So, no propagation of residual error. If we want to truly allow residual error through, for everything save those variables only predicted by exogenous variables, we’re going to need to setup a parallel equation. Indeed, let’s rewrite the above function a hair so that we can clearly see the separation of propagation of fit versus residual error.
keeley_firesev_predict <- function(data, params){
# let's goooooooo!
getAll(data, params)
# define some obs variables so we can use probability distributions
# and get reports of output - these are our predicted variables
cover <- OBS(cover);
rich <- OBS(rich);
####
## Let's just propagate coefficient error
####
cover_hat <- firesev_cover * firesev + cover_int
log_rich_hat <- cover_rich * cover_hat +
firesev_rich * firesev + rich_int
rich_hat <- exp(log_rich_hat)
####
## Now, let's look at residual error and propagation
####
cover_sigma <- exp(log_cover_sigma)
cover %~% dnorm(cover_hat, cover_sigma)
# we add this cover_use as we cannot use cover in equations
# and it is our predicted value of cover with residual
# variation
cover_pred <- cover
# now a *predicted* value of richness
# affected by a predicted value of cover
# but adding a hat as it's the fitted value
# based on propagating prediction error
log_rich_pred_hat <- cover_rich * cover_pred +
firesev_rich * firesev + rich_int
rich_pred_hat <- exp(log_rich_pred_hat)
theta = exp(log_theta)
rich %~% dnbinom2(mu = rich_pred_hat, size = theta)
# Collect and report - we want the hats
# but we don't need the preds - those are observed
# variables so we get them already
ADREPORT(cover_hat); REPORT(cover_hat);
ADREPORT(rich_hat); REPORT(rich_hat)
}What I like about the above is it shows how we can use one function to do many different things. Heck, we could have folded the block above into our initial function and used some is.na() logic. But, I’m a simple man, and I like to keep things separated sometimes so it’s easier to work with. And easier to tool around with, diagnose, and fix problems rather than having to refit every time - particularly for more complex models. I’m a piecewise man for piecewise SEM.
OK, enough of that. What do we do now? Well, we need to create a data frame, first, with NAs.
kpred <- data.frame(
firesev = 3,
cover = NA,
rich = NA
)Great, now we need to get our parameters and our Hessian from the original model. Then, we want to put it all together into a new prediction RTMB object.
# extract parameters and Hessian
keeley_fit_params <- keeley_firesev_opt$par
keeley_fit_hessian <- keeley_firesev_fit$he()
pred_adfun <- MakeADFun(cmb(keeley_firesev_predict,
kpred),
as.list(keeley_fit_params),
silent = TRUE)So - are we good? Can we just run sdreport()? NO!
Huh? Why? Well, two problems. First, sdreport() - or rather, the summary of the sdreport - will only give us information about the fit values and error. And - BIGGER PROBLEM - the values of richness and its error will be wrong.
gasp
Why?
${f(x)} f({x})$ - DAMN YOU JENSEN!
summary.sdreport() is using the delta method, an approximation. It is using mean fit values and not propagating the parameter uncertainty’s effects on cover for its calculations of its effects on richness.
pred_values <-
sdreport(pred_adfun,
hessian.fixed = keeley_fit_hessian) |>
summary() |>
as_tibble(rownames = "parameter") |>
janitor::clean_names() |>
filter(grepl("_hat", parameter))
pred_values# A tibble: 2 × 3
parameter estimate std_error
<chr> <dbl> <dbl>
1 cover_hat 0.823 0.0413
2 rich_hat 54.9 2.36
What’s worse, that looks sensible! And if we went on and used simulate() to get prediction intervals, while things would change a bit, coefficient uncertainty still wouldn’t be propagated properly, meaning that the estimates of mean richness could be off. In this example, as you will see, the consequences aren’t enormous, but, if we had a lot of uncertainty in coefficients and/or a wide range of predictor values, it could be fairly drastic.
Simulation to the Rescue
Fortunately, the solution addresses two problems at once. We have to use simulate(). But, we have to do it many times over with different parameter values - draws from our distribution of parameters. As long as our Hessian is well behaved, we can make a paramter variance-covariance matrix by inverting it.
param_vcov <- solve(keeley_fit_hessian)
rownames(param_vcov) <-
colnames(param_vcov) <-
names(keeley_firesev_fit$par)
param_vcov |> round(4) cover_rich firesev_rich rich_int firesev_cover cover_int
cover_rich 0.0118 0.0009 -0.0125 0.0000 0.0000
firesev_rich 0.0009 0.0004 -0.0026 0.0000 0.0000
rich_int -0.0125 -0.0026 0.0216 0.0000 0.0000
firesev_cover 0.0000 0.0000 0.0000 0.0003 -0.0015
cover_int 0.0000 0.0000 0.0000 -0.0015 0.0078
log_cover_sigma 0.0000 0.0000 0.0000 0.0000 0.0000
log_theta -0.0002 0.0000 0.0000 0.0000 0.0000
log_cover_sigma log_theta
cover_rich 0.0000 -2e-04
firesev_rich 0.0000 0e+00
rich_int 0.0000 0e+00
firesev_cover 0.0000 0e+00
cover_int 0.0000 0e+00
log_cover_sigma 0.0056 0e+00
log_theta 0.0000 4e-02
Then, we need to decide how many draws of parameters we want, and draw from the multivariate normal distribution of parameters.
n <- 1000
param_draws <- MASS::mvrnorm(n, mu = keeley_fit_params, Sigma = param_vcov)
dim(param_draws)[1] 1000 7
So, we have a matrix of 1000 draws of our 7 parameters. Each row is a draw and each column a parameter. We can use this with an apply() or other appropriate way of looping to iterate over these, and we’ll whip up a quickie function to run simulate just to make the apply statement look nicer. Note, each parameter draw then gets one draw from the residual distribution. If you wanted to explore how each component of variation contributes to variability, you could do that, but, whew.
make_a_prediction_sim <- function(p, pred_obj){
pred_obj$simulate(par = p)
}
sim_draws <- apply(param_draws, 1,
make_a_prediction_sim, pred_adfun)
sim_draws[[1]]$cover
[1] 0.8335565
$rich
[1] 36
$cover_hat
[1] 0.8356141
$rich_hat
[1] 53.26819
We are left with a list which we can merge into a data frame, iterate over, and calculate the means and SD (or CIs) of.
lapply(sim_draws, as.data.frame) |>
do.call(rbind, args = _) |>
mutate(sim = 1:n()) |>
tidyr::pivot_longer(-sim, names_to = "parameter", values_to = "est") |>
group_by(parameter) |>
summarize(estimate = mean(est),
std_error = sd(est),
lower_ci = quantile(est, probs = 0.025),
upper_ci = quantile(est, probs = 0.755),
) # A tibble: 4 × 5
parameter estimate std_error lower_ci upper_ci
<chr> <dbl> <dbl> <dbl> <dbl>
1 cover 0.826 0.293 0.236 1.04
2 cover_hat 0.821 0.0412 0.739 0.849
3 rich 55.5 16.9 28 65.2
4 rich_hat 54.9 2.39 50.2 56.6
What is interesting about this is twofold. One, you can see the impact of the additional variation on the SE and CIs. But even moreso, note the change in the mean estimate of the predicted richness. It’s non-trivial! And that’s for this well fit relationship. So, important to do going forward!
Where do we go from here

Well that was a lot, and SUPER interesting. We see how using RTMB, we have a level of precision and control to really generate meaningful simulation results from our fit models. This was a relatively simple model, but the principles of proper progation, simulation, and more can easily be telescoped out to far more complex models. And you can be super transparent about what you’re doing!
I’ll admit, we’re a bit in a land where RTMB and packages like rethinking and stan itself are converging - and, indeed, you could use all of the above and tmbstan to hop over into full luxury Bayesian SEM. But, it’s useful to see how to build these in a nice R-native and friendly(-ish) format for initial model development and seeing where things fail before taking the jump to the next level.
I think I’ll write one or two more of these - maybe one on a full Latent Variable SEM and…. maybe I will go Bayes! For funsies. But, I’m hoping from what I’ve written so far, that SEM in RTMB seems fairly straightforward as these things go, and you can see the possibility of implementing some fun and hella complex models here that maybe you could either not implement or not know how to work with using piecewiseSEM previously. As, if you could just use piecewiseSEM, why go for this added level of complexity?