Skip to main content

Random slopes: reaction norms and group-specific covariance

Question. If fish respond differently to warming, how does the variation among fish change with temperature?

Choose a route. Start by predicting how two fish will respond to warming. Then fit and check one model with the included simulated data, or read the saved reaction norms and repeatability curve. Both routes end at Finish the example. Multivariate and group-specific models are under Go further.

Home · Previous: Red knots

Picture the reaction norm

Imagine two fish whose expected activity is measured at a reference temperature. One fish may start above the population average but respond less to warming. Another may start lower and respond more strongly. Their lines can therefore cross. A random slope lets each fish have its own response to temperature, rather than assuming that all fish change at the same rate.

Predict. If animals with higher activity at the reference temperature tend to have lower temperature slopes, would intercept and slope deviations have positive or negative covariance?

Check your prediction

Negative. Higher-than-average intercepts go with lower-than-average slopes.

The univariate simulation uses 36 animals measured at seven temperatures. Its fitted intercept variance was 0.285, slope variance 0.121, intercept–slope covariance -0.063, and residual variance 0.312. These values belong to one simulated dataset. Use them to calculate repeatability at the reference temperature and one unit above it:

temperature <- c(0, 1)
between_variance <- 0.285 + 2 * temperature * (-0.063) +
  temperature^2 * 0.121
repeatability <- between_variance / (between_variance + 0.312)
data.frame(temperature, between_variance, repeatability)
  temperature between_variance repeatability
1           0            0.285     0.4773869
2           1            0.280     0.4729730

At the reference temperature, among-animal variance is 0.285 and repeatability is about 0.477. One unit above the reference, the negative intercept–slope covariance makes the variance slightly smaller, about 0.280, and repeatability about 0.473. The plotted curve shows this balance across the temperature range.

A complete univariate fit in glmmTMB

The simulation has 36 individuals and seven measurements spanning the same temperature range for each individual. The planted intercept–slope correlation is -0.45. glmmTMB 1.1.14 fit the first model in less than one second on the local computer. The retained point estimate is -0.338; one realised sample does not need to equal its generating value.

To run the first fit, extract the reproduction download and open R in the folder containing tutorial/ and analysis/. Install glmmTMB if you have not already done so. Open the existing simulated input and inspect one individual’s measurements at the seven temperatures.

reaction_path <- "tutorial/downloads/extensions/univariate-input.csv"
if (!file.exists(reaction_path)) {
  reaction_path <- "downloads/extensions/univariate-input.csv"
}
reaction_data <- read.csv(reaction_path)
reaction_data$individual <- factor(reaction_data$individual)
subset(reaction_data, individual == individual[1])
    individual replicate temp_c     value
1            1         1   -1.5 0.8390457
37           1         2   -1.0 2.1488732
73           1         3   -0.5 3.3592575
109          1         4    0.0 3.0777615
145          1         5    0.5 4.1887372
181          1         6    1.0 4.2435146
217          1         7    1.5 4.0343996

temp_c is centred at the reference temperature. The model gives each individual its own intercept and temperature slope.

fit_univariate <- glmmTMB::glmmTMB(
  value ~ temp_c + (1 + temp_c | individual),
  data = reaction_data,
  family = gaussian()
)

Check convergence, curvature and the gradient before comparing temperatures. The saved fit returned convergence code 0, a positive-definite Hessian and a maximum absolute gradient of about 0.00056.

slope_checks <- c(
  convergence = fit_univariate$fit$convergence,
  positive_hessian = isTRUE(fit_univariate$sdr$pdHess),
  max_gradient = max(abs(fit_univariate$sdr$gradient.fixed))
)
slope_checks
if (!all(is.finite(slope_checks)) || slope_checks["convergence"] != 0 ||
    slope_checks["positive_hessian"] != 1 || slope_checks["max_gradient"] > 0.01) {
  stop("The fit did not pass. Check the diagnostics before reporting a result.")
}

Use the checked covariance matrix to calculate repeatability at the same two temperatures as the hand calculation.

temperature <- c(0, 1)
slope_covariance <- as.matrix(glmmTMB::VarCorr(fit_univariate)$cond$individual)
between_variance <- slope_covariance["(Intercept)", "(Intercept)"] +
  2 * temperature * slope_covariance["(Intercept)", "temp_c"] +
  temperature^2 * slope_covariance["temp_c", "temp_c"]
residual_variance <- sigma(fit_univariate)^2
data.frame(
  temperature,
  repeatability = between_variance / (between_variance + residual_variance)
)

The curves below show the saved simulation fit. Your fresh estimates may differ slightly with software version.

Twelve labelled panels each show one simulated individual: blue observation points and an orange fitted reaction-norm line. The fitted slopes differ between animals; a dashed vertical line marks the reference temperature in every panel.

Twelve individuals’ observed points and fitted reaction norms, one individual per panel. The dashed vertical lines mark the reference temperature.

Because the fitted intercept–slope covariance is negative, estimated among-individual variance and repeatability are lower at some temperatures than others.

Line chart of pointwise repeatability against temperature relative to the reference, from -1.5 to 1.5. A blue curve declines from about 0.70 at the cold end to a minimum near 0.45 slightly above the reference, then rises to about 0.54. A grey dashed vertical line marks the reference temperature at zero.

Fitted pointwise repeatability across the simulated temperature interval.

Finish the example

Report the saved result. Repeatability was about 0.48 at the reference temperature and 0.47 one unit above it. Individual differences in temperature response can change the fraction of variation that lies among animals. These are point estimates from one simulated dataset.

You’ve finished the main lesson when you can explain why a random slope makes repeatability depend on temperature. If you refitted the model, report the values from your checked fit. To use your own data, first check that temperature varies within individuals.

Go further

The next sections show the covariance calculation, the multivariate extension and the optional group comparison. Reproduce the simulations to regenerate the files used by the lesson.

How temperature changes the covariance

Let \(\mathrm{temp}_{ij}\) be a temperature relative to a declared reference, for individual \(i\) at occasion \(j\). A reaction norm is an individual’s expected behaviour as the environment changes. The notation below is the manuscript’s random-slope extension:

Symbol Meaning in this temperature example
\(y_{ijt}\) Trait \(t\) recorded for animal \(i\) on occasion \(j\).
\(\mu_t\), \(\beta_{t,\mathrm{temp}}\) Population mean at the reference temperature and its average change per temperature unit.
\(u_{it}\), \(b_{it}\) Animal \(i\)’s deviations in the intercept and slope for trait \(t\). Its full slope is \(\beta_{t,\mathrm{temp}}+b_{it}\).
\(e_{ijt}\) Complete within-individual, occasion-level deviation for trait \(t\).
\(\mathbf{b}_{B,i}\), \(\boldsymbol{\Sigma}^{(\mathrm{aug})}_B\) Stacked intercept-and-slope deviations and their augmented between-individual covariance matrix.
\(\mathbf{G}_t\) The \(2\times2\) intercept–slope covariance matrix for one trait.

A random-slope reaction norm for one trait is

\[ y_{ijt}=\mu_t+\beta_{t,\mathrm{temp}}\,\mathrm{temp}_{ij} +u_{it}+b_{it}\,\mathrm{temp}_{ij}+e_{ijt}. \]

Here \(u_{it}\) is the individual’s deviation at the declared reference temperature, rather than a temperature-free personality score, and \(b_{it}\) is its temperature response. For one trait, their covariance matrix is

\[ \mathbf{G}_t = \begin{pmatrix} \mathrm{Var}(u_{it}) & \mathrm{Cov}(u_{it},b_{it})\\ \mathrm{Cov}(b_{it},u_{it}) & \mathrm{Var}(b_{it}) \end{pmatrix}. \]

We estimate the intercept–slope covariance rather than assume it is zero.

At a particular temperature \(x\), \(V_{B,t}(x)\) is the variance among animals’ expected values for trait \(t\) and \(R_t(x)\) is repeatability at that temperature:

\[ V_{B,t}(x)=\mathrm{Var}(u_{it})+2x\,\mathrm{Cov}(u_{it},b_{it}) +x^2\,\mathrm{Var}(b_{it}),\qquad R_t(x)=\frac{V_{B,t}(x)}{V_{B,t}(x)+\mathrm{Var}(e_{ijt})}. \]

Changing the reference by \(c\) replaces \(u_{it}\) by \(u_{it}+c b_{it}\). Thus the intercept variance and intercept–slope covariance change when the reference changes; the slope variance does not. A diagonal unique-variance restriction is therefore a constraint at a particular reference, not an invariant biological claim. Centre temperature where the intercept is scientifically meaningful and report that value.

To summarise repeatability over the observed temperatures rather than at one value, average \(V_{B,t}(x)\) over the temperature distribution. With \(X=\mathrm{temp}\), \(\mu_X=\mathbb{E}[X]\) and \(\sigma_X^2=\mathrm{Var}(X)\),

On a narrow screen, press Tab until the equation has a visible outline, then use the arrow keys to scroll across it.

\[ V^{\mathrm{marg}}_{B,t}=\mathrm{Var}(u_{it})+2\mu_X\,\mathrm{Cov}(u_{it},b_{it}) +(\sigma_X^2+\mu_X^2)\,\mathrm{Var}(b_{it}),\qquad R_t^{\mathrm{marg}}=\frac{V^{\mathrm{marg}}_{B,t}}{V^{\mathrm{marg}}_{B,t}+\mathrm{Var}(e_{ijt})}. \]

When temperature is centred at its mean (\(\mu_X=0\)), the first expression reduces to \(\mathrm{Var}(u_{it})+\sigma_X^2\,\mathrm{Var}(b_{it})\).

A multivariate random-regression extension in gllvmTMB

For three traits, the manuscript keeps the intercept and slope vectors distinct: \(\mathbf{u}_i\) contains the three intercept deviations and \(\mathbf{b}_i\) contains the three temperature-slope deviations. The augmented coefficient vector is

\[ \mathbf{b}_{B,i}= \begin{pmatrix} \mathbf{u}_i\\ \mathbf{b}_i \end{pmatrix}, \qquad \boldsymbol{\Sigma}^{(\mathrm{aug})}_B =\mathrm{Var}(\mathbf{b}_{B,i}). \]

The occasion-level vector remains \(\mathbf{e}_{ij}\sim\mathcal{MVN}(\mathbf{0},\boldsymbol{\Sigma}_W)\). For any temperature \(x\), let \(\mathbf{A}(x)\) select each trait’s intercept plus \(x\) times its slope. The resulting among-individual covariance among traits is

\[ \boldsymbol{\Sigma}_B(x)= \mathbf{A}(x)\boldsymbol{\Sigma}^{(\mathrm{aug})}_B \mathbf{A}(x)^\mathsf{T}. \]

For one trait, the row \([1,x]\) combines \(u_{it}\) and \(b_{it}\) as \(u_{it}+x b_{it}\); the matrix repeats that operation for all three traits. The superscript \(\mathsf{T}\) transposes the selection matrix. This is why both variance and covariance between traits can vary over temperature.

This three-trait simulation has 30 animals, six sessions per animal and 540 long-format response rows. The installed public gllvmTMB 0.7.1 interface supports this Gaussian, long-format individual random-regression model. The extension fits a rank-one-plus-diagonal individual block and the same form for session-level covariance; rank one is planted in this demonstration, not selected from the data. The diagonal unique-variance block assumes zero trait-specific intercept–slope covariance at the declared reference. Recentring generally creates such covariance; fitting the same diagonal restriction at a different reference therefore changes the model. Choose and report the reference before fitting. The stored fit passed its optimizer, gradient (0.0001525), Hessian, and boundary checks. Its two-second runtime is a local teaching fit, not a benchmark.

The matching multivariate model stays in long format. The first latent() term gives each individual trait-specific intercept and temperature-slope coefficients with a rank-one shared component and unique variances. The second term represents covariance among measurements in the same recorded session.

#| eval: false
latent <- gllvmTMB::latent
fit_multivariate <- gllvmTMB::gllvmTMB(
  value ~ 0 + trait + (0 + trait):temp_c +
    latent(0 + trait + (0 + trait):temp_c | individual,
           d = 1, unique = TRUE) +
    latent(0 + trait | session_id, d = 1, unique = TRUE),
  data = reaction_long, trait = "trait",
  unit = "individual", unit_obs = "session_id", family = gaussian()
)

The complete script below generates reaction_long, records the fit-health checks, and reconstructs the temperature-specific covariance targets. It is a one-realisation teaching example, not a model-selection or sample-size study.

Line chart of model-based repeatability against temperature relative to the reference. From -1.25 to 1.25, activity rises from 0.48 to 0.88 and boldness from 0.59 to 0.88; exploration falls from 0.89 to 0.63. The curves are near 0.8 at the reference temperature, marked by a vertical dashed line at zero. These values describe this simulated fit.

Fitted pointwise repeatability for simulated boldness, exploration, and activity.

gllvmTMB::slope() is deliberately not used here: it models covariance among response-column coefficients, whereas this example needs individual-specific intercepts and slopes. The documented latent(... | individual) random-regression form below is the relevant interface. The package reports the Gaussian row-level residual scale as mapped off because the session-level trait-specific component already represents that variation.

Line chart of fitted among-individual covariance between boldness and exploration across temperature relative to the reference. Covariance stays positive, rises from about 0.37 at the cold end to about 0.42 near the reference, then falls to about 0.34 at the warm end. Dashed horizontal and vertical lines mark zero covariance and the reference temperature.

Estimated among-individual covariance between simulated boldness and exploration across temperature.

This curve is one off-diagonal element of \(\mathbf{A}(x)\boldsymbol{\Sigma}^{(\mathrm{aug})}_B\mathbf{A}(x)^\mathsf{T}\). It answers a different question from the trait-specific repeatability curves: how do two traits vary together among individuals at the same temperature?

Communality with random slopes

With a reduced-rank individual block, the intercept and slope deviations each have a shared part and a trait-specific part. Write the intercept and slope blocks of \(\boldsymbol{\Sigma}^{(\mathrm{aug})}_B\) as

\[ \boldsymbol{\Sigma}^{(u)}_B=\boldsymbol{\Lambda}_u\boldsymbol{\Lambda}_u^{\mathsf T}+\boldsymbol{\Psi}_u, \qquad \boldsymbol{\Sigma}^{(b)}_B=\boldsymbol{\Lambda}_b\boldsymbol{\Lambda}_b^{\mathsf T}+\boldsymbol{\Psi}_b, \qquad \boldsymbol{\Sigma}^{(u,b)}_B=\boldsymbol{\Lambda}_u\boldsymbol{\Lambda}_b^{\mathsf T}, \]

where \(\boldsymbol{\Lambda}_u\) and \(\boldsymbol{\Lambda}_b\) are the intercept and slope rows of the loading matrix. The manuscript’s Appendix B defines three communalities. Choose the one that matches the question.

  • Intercept (personality) communality, at the reference temperature: \(c_{B,t}^2=(\boldsymbol{\Lambda}_u\boldsymbol{\Lambda}_u^{\mathsf T})_{tt}/(\boldsymbol{\Sigma}^{(u)}_B)_{tt}\). This is the main-text \(c_B^2\) applied to the intercept block.
  • Communality at a focal temperature \(x\): the shared part of \(\boldsymbol{\Sigma}_B(x)\) is \((\boldsymbol{\Lambda}_u+x\boldsymbol{\Lambda}_b)(\boldsymbol{\Lambda}_u+x\boldsymbol{\Lambda}_b)^{\mathsf T}\), so \(c^2_{t\mid x}\) is its \(t\)th diagonal entry divided by \([\boldsymbol{\Sigma}_B(x)]_{tt}\).
  • Marginalised communality: average both the shared and the total matrices over the temperature distribution, then take the ratio of their \(t\)th diagonal entries (below).

For the marginalised communality, the averaged shared matrix is

\[ \boldsymbol{\Sigma}^{\mathrm{common,marg}}_B=\boldsymbol{\Lambda}_u\boldsymbol{\Lambda}_u^{\mathsf T} +\mu_X\big(\boldsymbol{\Lambda}_u\boldsymbol{\Lambda}_b^{\mathsf T}+\boldsymbol{\Lambda}_b\boldsymbol{\Lambda}_u^{\mathsf T}\big) +(\sigma_X^2+\mu_X^2)\,\boldsymbol{\Lambda}_b\boldsymbol{\Lambda}_b^{\mathsf T}, \]

and \(\boldsymbol{\Sigma}^{\mathrm{marg}}_B\) has the same form with the full blocks \(\boldsymbol{\Sigma}^{(u)}_B\), \(\boldsymbol{\Sigma}^{(u,b)}_B\), \(\boldsymbol{\Sigma}^{(b,u)}_B\) and \(\boldsymbol{\Sigma}^{(b)}_B\) in place of the loading products. Then \(c^{2,\mathrm{marg}}_t=[\boldsymbol{\Sigma}^{\mathrm{common,marg}}_B]_{tt}/[\boldsymbol{\Sigma}^{\mathrm{marg}}_B]_{tt}\).

The first is a property of the reference temperature. The second and third describe how strongly the shared axes structure the realised among-individual variance. The downloadable script reports covariance and repeatability curves; it does not compute these communalities. Each is a ratio of entries from the same fitted matrices, so it can be added in a few lines after extraction.

All figures in this lesson use ggplot2, with the complete plotting code below. Individual reaction norms use labelled panels, and trait curves use both colour and line type so the message does not depend on colour alone. Each plotting function writes a PNG for the page and a vector PDF for reuse.

Group-specific covariance: female and male animals

Optional Appendix B example: compare groups

Sex is a 0/1 grouping attribute, rather than a reaction-norm covariate: an animal does not change sex from one recorded occasion to the next. It can therefore enter the mean model, but a sex coefficient must not be called plasticity. The relevant question is whether the among-individual covariance matrix differs between females and males.

For a trait \(t\), code female as \(\mathrm{sex}_i=0\) and male as \(\mathrm{sex}_i=1\):

\[ y_{ijt} = \mu_t + \beta_{t,\mathrm{sex}}\mathrm{sex}_i + \nu_{it} + \omega_{it}\mathrm{sex}_i+e_{ijt}. \]

This provides a compact way to write the target. The group-specific between-individual deviations are \(\nu_{it}\) for females and \(\nu_{it}+\omega_{it}\) for males, so

\[ \boldsymbol{\Sigma}^{(F)}_B=\mathrm{Var}(\boldsymbol{\nu}_i), \qquad \boldsymbol{\Sigma}^{(M)}_B=\mathrm{Var}(\boldsymbol{\nu}_i+\boldsymbol{\omega}_i). \]

The corresponding trait-specific repeatabilities are

\[ R_t^{(g)}=\frac{(\boldsymbol{\Sigma}^{(g)}_B)_{tt}} {(\boldsymbol{\Sigma}^{(g)}_B)_{tt}+(\boldsymbol{\Sigma}^{(g)}_W)_{tt}}, \qquad g\in\{F,M\}. \]

A person sees only one sex for each animal. Thus the data directly identify female and male covariance matrices, but do not by themselves uniquely identify every separate intercept–sex-coefficient covariance in the equation above. For this reason the runnable example fits one covariance model per sex; it reports the direct group-specific targets.

When each sex has a reduced-rank B matrix, communality can also differ by sex. With the joint parameterisation, female deviations have shared part \(\boldsymbol{\Lambda}_\nu\boldsymbol{\Lambda}_\nu^{\mathsf T}\) and male deviations have shared part \((\boldsymbol{\Lambda}_\nu+\boldsymbol{\Lambda}_\omega)(\boldsymbol{\Lambda}_\nu+\boldsymbol{\Lambda}_\omega)^{\mathsf T}\), so

\[ c_t^{2(F)}=\frac{(\boldsymbol{\Lambda}_\nu\boldsymbol{\Lambda}_\nu^{\mathsf T})_{tt}}{(\boldsymbol{\Sigma}^{(F)}_B)_{tt}}, \qquad c_t^{2(M)}=\frac{\big((\boldsymbol{\Lambda}_\nu+\boldsymbol{\Lambda}_\omega)(\boldsymbol{\Lambda}_\nu+\boldsymbol{\Lambda}_\omega)^{\mathsf T}\big)_{tt}}{(\boldsymbol{\Sigma}^{(M)}_B)_{tt}}. \]

With separate rank-one-plus-\(\boldsymbol{\Psi}\) fits per sex, use each fit’s own loadings in the numerator. A difference between \(c_t^{2(F)}\) and \(c_t^{2(M)}\) says the sexes differ in how strongly trait \(t\) takes part in the shared pattern, not only in repeatability. The runnable example uses unstructured matrices, so it has no communality to report. A joint 0/1 random-slope model can be a parsimonious constrained parameterisation, but it should be used only when its constraints and identifiability are made explicit.

The simulated example has 60 females and 60 males, each measured on seven occasions for boldness, exploration, and activity. It uses unstructured three-trait B and W covariance matrices so that the group comparison is transparent. With more traits, each group can instead use the manuscript’s rank-one-plus-\(\boldsymbol{\Psi}\) representation, provided the data support that reduction.

#| eval: false
fit_female <- glmmTMB::glmmTMB(
  value ~ 0 + trait + (0 + trait | individual) + (0 + trait | occasion_id),
  family = gaussian(), dispformula = ~ 0,
  data = subset(sex_data, sex == "female")
)
fit_male <- update(fit_female, data = subset(sex_data, sex == "male"))

The script uses a BFGS polish from each first fit and retains the convergence, curvature, and gradient record. It then reconstructs \(\boldsymbol{\Sigma}^{(F)}_B\), \(\boldsymbol{\Sigma}^{(M)}_B\), the two within-individual matrices, and their repeatabilities. The points below are point estimates from one simulated data set; they are not confidence intervals.

Point plot of repeatability for boldness, exploration, and activity, with separate female and male estimates for each trait. Female and male estimates are similar for boldness (about 0.60) and exploration (about 0.54 and 0.58). Activity repeatability is higher for males (about 0.64) than females (about 0.51). Circles mark females and triangles mark males.

Female and male simulated trait-specific repeatabilities. Each trait has a pink female point and blue male point between zero and one.

Point plot comparing female and male among-individual correlations for boldness-exploration, boldness-activity, and exploration-activity. Female estimates are positive for all three pairs (about 0.45, 0.25, and 0.27). The boldness-exploration estimate is negative for males (about -0.28), while exploration-activity is positive (about 0.47); the boldness-activity estimate is near zero. A dashed horizontal line marks zero. Circles mark females and triangles mark males.

Female and male simulated among-individual correlations for the three trait pairs.

The comparison concerns sex-specific behavioural syndrome patterns: it does not describe personality–plasticity covariance, and it does not show that sex caused the difference. The same distinction applies to morph, population, or any other individual-level grouping attribute.

Reproduce without fitting during site render

To run the simulation script, install MASS in addition to ggplot2, glmmTMB and gllvmTMB from Install the software.

Follow Run the extensions to simulate the data, fit the models, and write the tables and plots. The page displays saved results from those simulations.

Download the complete script, simulated univariate input, univariate estimates, first-fit diagnostics, multivariate input, multivariate fit health, temperature-specific summaries, and the sex-group files: input data, fit diagnostics, repeatability estimates, and correlation estimates.

Complete code

Show the complete simulation and fitting script

The following is the exact downloadable script, including simulation, glmmTMB and gllvmTMB fits, public covariance extraction, all result tables, and every plotted figure. It is shown rather than evaluated here so rendering the site never refits a model.

#!/usr/bin/env Rscript
# Simulated reaction norms for tutorial/random-slopes.qmd.  Run this script;
# website rendering only reads the files it writes.

root <- getwd()
if (!dir.exists(file.path(root, "tutorial"))) stop("Run from the repository root.")
out_analysis <- file.path(root, "analysis", "extensions", "outputs")
out_fig <- file.path(root, "tutorial", "figures", "extensions")
out_download <- file.path(root, "tutorial", "downloads", "extensions")
for (d in c(out_analysis, out_fig, out_download)) dir.create(d, recursive = TRUE, showWarnings = FALSE)

`%||%` <- function(x, y) if (is.null(x)) y else x
require_namespace <- function(x) if (!requireNamespace(x, quietly = TRUE)) stop("Need package: ", x)
require_namespace("glmmTMB"); require_namespace("gllvmTMB"); require_namespace("MASS"); require_namespace("ggplot2")
suppressPackageStartupMessages(library(ggplot2))

Sigma_uni <- matrix(c(0.70^2, -0.45 * 0.70 * 0.30,
                      -0.45 * 0.70 * 0.30, 0.30^2), 2, 2,
                    dimnames = list(c("intercept", "slope"), c("intercept", "slope")))

make_univariate <- function(n_ind = 36L, n_rep = 7L, seed = 20260906L) {
  set.seed(seed)
  x <- seq(-1.5, 1.5, length.out = n_rep)
  b <- MASS::mvrnorm(n_ind, mu = c(0, 0), Sigma = Sigma_uni)
  d <- expand.grid(individual = factor(seq_len(n_ind)), replicate = seq_len(n_rep), KEEP.OUT.ATTRS = FALSE)
  d$temp_c <- rep(x, each = n_ind)
  d$value <- 3 + 0.40 * d$temp_c + b[as.integer(d$individual), 1] +
    b[as.integer(d$individual), 2] * d$temp_c + rnorm(nrow(d), 0, 0.55)
  d
}

fit_univariate <- function(d) {
  glmmTMB::glmmTMB(value ~ temp_c + (1 + temp_c | individual), data = d, family = gaussian())
}

extract_univariate <- function(fit, x = seq(-1.5, 1.5, length.out = 100L)) {
  S <- as.matrix(glmmTMB::VarCorr(fit)$cond$individual)
  resid <- sigma(fit)^2
  cov01 <- S["(Intercept)", "temp_c"]
  vb <- S["(Intercept)", "(Intercept)"] + 2 * x * cov01 + x^2 * S["temp_c", "temp_c"]
  data.frame(temp_c = x, between_variance = vb, residual_variance = resid,
             repeatability = vb / (vb + resid))
}

reaction_norm_rows <- function(fit, d) {
  re <- glmmTMB::ranef(fit)$cond$individual
  fe <- glmmTMB::fixef(fit)$cond
  g <- expand.grid(individual = rownames(re), temp_c = seq(min(d$temp_c), max(d$temp_c), length.out = 80L), KEEP.OUT.ATTRS = FALSE)
  g$prediction <- fe["(Intercept)"] + fe["temp_c"] * g$temp_c +
    re[g$individual, "(Intercept)"] + re[g$individual, "temp_c"] * g$temp_c
  g
}

# The same ggplot2 objects can be restyled and saved at publication resolution.
save_teaching_plot <- function(p, path, width = 8, height = 5.5) {
  p <- p + theme_minimal(base_size = 12) +
    theme(panel.grid.minor = element_blank(), legend.position = "bottom",
          plot.title = element_text(face = "bold"))
  ggsave(path, p, width = width, height = height, dpi = 180)
  ggsave(sub("\\.png$", ".pdf", path), p, width = width, height = height)
}

plot_univariate <- function(d, lines, path) {
  ids <- levels(d$individual); keep <- ids[seq_len(min(12L, length(ids)))]
  # Small multiples let readers follow one animal without relying on 12 colours.
  p <- ggplot(d[d$individual %in% keep, ], aes(temp_c, value)) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey55") +
    geom_point(colour = "#0072B2", alpha = .7, size = 1.5) +
    geom_line(data = lines[lines$individual %in% keep, ],
              aes(y = prediction, group = individual), colour = "#D55E00", linewidth = .8) +
    facet_wrap(~individual, ncol = 4, labeller = label_both) +
    labs(x = "Temperature relative to reference", y = "Behaviour",
         title = "Each animal has its own reaction norm",
         subtitle = "Points: simulated observations; lines: fitted individual responses")
  save_teaching_plot(p, path, width = 9, height = 6.5)
}

plot_repeatability <- function(tab, path) {
  p <- ggplot(tab, aes(temp_c, repeatability)) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey55") +
    geom_line(colour = "#0072B2", linewidth = 1.2) +
    scale_y_continuous(limits = c(0, 1)) +
    labs(x = "Temperature relative to reference", y = "Pointwise repeatability",
         title = "Repeatability changes with temperature")
  save_teaching_plot(p, path)
}

require_healthy_fit <- function(convergence, pd_hessian, max_gradient, label) {
  if (!isTRUE(convergence == 0L) || !isTRUE(pd_hessian) ||
      !isTRUE(is.finite(max_gradient) && max_gradient <= .01)) {
    stop(label, " fit failed its numerical checks. Read the saved fit-health table.")
  }
}

run_univariate <- function() {
  d <- make_univariate(); started <- proc.time()[["elapsed"]]; fit <- fit_univariate(d)
  elapsed <- proc.time()[["elapsed"]] - started
  if (elapsed > 120) stop("First glmmTMB fit exceeded the 2-minute tutorial budget.")
  health <- data.frame(convergence = fit$fit$convergence,
    pd_hessian = isTRUE(fit$sdr$pdHess),
    max_gradient = max(abs(fit$obj$gr(fit$fit$par))))
  utils::write.csv(health, file.path(out_analysis, "univariate-fit-health.csv"), row.names = FALSE)
  require_healthy_fit(health$convergence, health$pd_hessian, health$max_gradient, "Univariate")
  tab <- extract_univariate(fit); lines <- reaction_norm_rows(fit, d)
  S <- as.matrix(glmmTMB::VarCorr(fit)$cond$individual)
  result <- data.frame(term = c("intercept_variance", "slope_variance", "intercept_slope_covariance", "intercept_slope_correlation", "residual_variance", "fit_seconds"),
                       estimate = c(S[1,1], S[2,2], S[1,2], attr(S, "correlation")[1,2], sigma(fit)^2, elapsed))
  utils::write.csv(d, file.path(out_analysis, "univariate-input.csv"), row.names = FALSE)
  utils::write.csv(tab, file.path(out_analysis, "univariate-repeatability.csv"), row.names = FALSE)
  utils::write.csv(result, file.path(out_analysis, "univariate-results.csv"), row.names = FALSE)
  plot_univariate(d, lines, file.path(out_fig, "univariate-reaction-norms.png"))
  plot_repeatability(tab, file.path(out_fig, "univariate-repeatability.png"))
  list(data = d, fit = fit, table = tab, elapsed = elapsed)
}

make_multivariate <- function(n_ind = 30L, n_rep = 6L, seed = 20260907L) {
  set.seed(seed); traits <- c("boldness", "exploration", "activity")
  # Rank-one-plus-diagonal truth, ordered intercept.trait then slope.temperature.trait.
  Lb <- c(0.65, 0.48, 0.36, 0.24, -0.18, 0.15); Sb <- tcrossprod(Lb) + diag(c(.14, .12, .11, .08, .08, .08)^2)
  Lw <- c(0.30, 0.20, 0.15); Sw <- tcrossprod(Lw) + diag(c(.24, .22, .20)^2)
  u <- MASS::mvrnorm(n_ind, rep(0, 6), Sb); w <- MASS::mvrnorm(n_ind * n_rep, rep(0, 3), Sw)
  z <- expand.grid(individual = factor(seq_len(n_ind)), session = seq_len(n_rep), trait = traits, KEEP.OUT.ATTRS = FALSE)
  z$trait <- factor(z$trait, levels = traits); z$session_id <- interaction(z$individual, z$session, drop = TRUE)
  z$temp_c <- rep(rep(seq(-1.25, 1.25, length.out = n_rep), each = n_ind), times = length(traits))
  ti <- as.integer(z$trait); ii <- as.integer(z$individual); si <- as.integer(z$session_id)
  beta0 <- c(3.2, 2.8, 3.5); beta1 <- c(.35, .20, -.15)
  z$value <- beta0[ti] + beta1[ti] * z$temp_c + u[cbind(ii, ti)] +
    u[cbind(ii, ti + 3L)] * z$temp_c + w[cbind(si, ti)]
  list(data = z, Sigma_B = Sb, Sigma_W = Sw, traits = traits)
}

fit_multivariate <- function(d) {
  # `latent()` is parsed from the formula; package qualification belongs on the fitter.
  latent <- gllvmTMB::latent
  gllvmTMB::gllvmTMB(
  value ~ 0 + trait + (0 + trait):temp_c +
    latent(0 + trait + (0 + trait):temp_c | individual, d = 1, unique = TRUE) +
    latent(0 + trait | session_id, d = 1, unique = TRUE),
  data = d, trait = "trait", unit = "individual", unit_obs = "session_id", family = gaussian(),
  control = gllvmTMB::gllvmTMBcontrol(se = TRUE), silent = TRUE)
}

multivariate_curves <- function(Sb, Sw, traits, x = seq(-1.25, 1.25, length.out = 100L)) {
  intercept <- paste0("intercept.", traits); slope <- paste0("slope.temp_c.", traits)
  # Current public extractor labels the predictor with its formula name; fail loudly if that changes.
  if (!all(intercept %in% rownames(Sb)) || !all(slope %in% rownames(Sb))) stop("Unexpected public gllvmTMB covariance labels.")
  out <- lapply(x, function(xx) {
    A <- cbind(diag(length(traits)), xx * diag(length(traits)))
    B <- Sb[c(intercept, slope), c(intercept, slope), drop = FALSE]
    V <- A %*% B %*% t(A)
    data.frame(temp_c = xx, trait = traits, between_variance = diag(V),
      repeatability = diag(V) / (diag(V) + diag(Sw[traits, traits, drop = FALSE])),
      cov_boldness_exploration = V[1, 2])
  })
  do.call(rbind, out)
}

plot_multivariate <- function(tab, path) {
  p <- ggplot(tab, aes(temp_c, repeatability, colour = trait, linetype = trait)) +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey70") +
    geom_line(linewidth = 1.2) + scale_y_continuous(limits = c(0, 1)) +
    scale_colour_manual(values = c(activity = "#009E73", boldness = "#0072B2", exploration = "#D55E00")) +
    labs(x = "Temperature relative to reference", y = "Pointwise repeatability",
         colour = "Trait", linetype = "Trait",
         title = "Three traits, three temperature-dependent patterns")
  save_teaching_plot(p, path)
}

plot_covariance <- function(tab, path) {
  p <- ggplot(tab[tab$trait == "boldness", ], aes(temp_c, cov_boldness_exploration)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_vline(xintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_line(colour = "#009E73", linewidth = 1.2) +
    labs(x = "Temperature relative to reference", y = "Among-individual covariance",
         title = "Boldness and exploration can covary differently",
         subtitle = "The fitted association depends on the temperature at which it is evaluated")
  save_teaching_plot(p, path)
}

run_multivariate <- function() {
  x <- make_multivariate(); started <- proc.time()[["elapsed"]]; fit <- fit_multivariate(x$data); elapsed <- proc.time()[["elapsed"]] - started
  health <- gllvmTMB::check_gllvmTMB(fit)
  utils::write.csv(health, file.path(out_analysis, "multivariate-fit-health.csv"), row.names = FALSE)
  h <- fit$fit_health
  require_healthy_fit(h$convergence, h$pd_hessian, h$max_gradient, "Multivariate")
  Sb <- gllvmTMB::extract_Sigma(fit, level = "unit_slope", part = "total")$Sigma
  Sw <- gllvmTMB::extract_Sigma(fit, level = "unit_obs", part = "total")$Sigma
  tab <- multivariate_curves(Sb, Sw, x$traits)
  utils::write.csv(x$data, file.path(out_analysis, "multivariate-input.csv"), row.names = FALSE)
  utils::write.csv(tab, file.path(out_analysis, "multivariate-curves.csv"), row.names = FALSE)
  utils::write.csv(Sb, file.path(out_analysis, "multivariate-unit-slope-covariance.csv"))
  utils::write.csv(Sw, file.path(out_analysis, "multivariate-session-covariance.csv"))
  plot_multivariate(tab, file.path(out_fig, "multivariate-repeatability.png"))
  plot_covariance(tab, file.path(out_fig, "multivariate-covariance.png"))
  elapsed
}

# Sex is constant within an individual.  This is a group-specific covariance
# example, not a reaction norm: fit each sex directly so the estimands are
# unambiguous female and male B/W covariance matrices.
make_sex_groups <- function(n_per_sex = 60L, n_rep = 7L, seed = 1L) {
  set.seed(seed)
  traits <- c("boldness", "exploration", "activity")
  B_female <- matrix(c(.55,.22,.12, .22,.45,.15, .12,.15,.36), 3, byrow = TRUE)
  B_male <- matrix(c(.35,-.10,.08, -.10,.65,.18, .08,.18,.48), 3, byrow = TRUE)
  W <- matrix(c(.25,.08,.04, .08,.30,.07, .04,.07,.28), 3, byrow = TRUE)
  make_one <- function(sex, B) {
    u <- MASS::mvrnorm(n_per_sex, rep(0, 3), B)
    w <- MASS::mvrnorm(n_per_sex * n_rep, rep(0, 3), W)
    z <- expand.grid(individual = factor(seq_len(n_per_sex)), occasion = seq_len(n_rep),
                     trait = traits, KEEP.OUT.ATTRS = FALSE)
    z$sex <- sex
    z$trait <- factor(z$trait, levels = traits)
    z$occasion_id <- interaction(z$individual, z$occasion, drop = TRUE)
    ii <- as.integer(z$individual); jj <- as.integer(z$occasion_id); tt <- as.integer(z$trait)
    z$value <- c(1.0, 1.2, .8)[tt] + u[cbind(ii, tt)] + w[cbind(jj, tt)]
    z
  }
  list(data = rbind(make_one("female", B_female), make_one("male", B_male)), traits = traits)
}

fit_sex_group <- function(d) {
  first <- glmmTMB::glmmTMB(
    value ~ 0 + trait +
      (0 + trait | individual) + (0 + trait | occasion_id),
    family = gaussian(), dispformula = ~ 0, data = d
  )
  # A BFGS polish begins from the first fit, rather than a new default start.
  update(first,
    start = list(beta = unname(glmmTMB::fixef(first)$cond),
                 theta = unname(glmmTMB::getME(first, "theta"))),
    control = glmmTMB::glmmTMBControl(
      optimizer = optim, optArgs = list(method = "BFGS"),
      optCtrl = list(maxit = 5000, reltol = 1e-12)
    )
  )
}

sum_group_blocks <- function(fit, prefix) {
  vc <- glmmTMB::VarCorr(fit)$cond
  blocks <- vc[startsWith(names(vc), prefix)]
  if (length(blocks) != 1L) stop("Expected one unstructured covariance block for ", prefix)
  as.matrix(blocks[[1]])
}

sex_group_summary <- function(fits, traits) {
  do.call(rbind, lapply(names(fits), function(sex) {
    B <- sum_group_blocks(fits[[sex]], "individual")
    W <- sum_group_blocks(fits[[sex]], "occasion_id")
    data.frame(sex = sex, trait = traits, between_variance = diag(B),
               within_variance = diag(W), repeatability = diag(B) / diag(B + W))
  }))
}

sex_correlation_summary <- function(fits) {
  do.call(rbind, lapply(names(fits), function(sex) {
    B <- sum_group_blocks(fits[[sex]], "individual")
    C <- cov2cor(B)
    data.frame(sex = sex,
               trait_1 = sub("^trait", "", rownames(C)[c(1, 1, 2)]),
               trait_2 = sub("^trait", "", colnames(C)[c(2, 3, 3)]),
               correlation = C[cbind(c(1, 1, 2), c(2, 3, 3))])
  }))
}

plot_sex_repeatability <- function(tab, path) {
  p <- ggplot(tab, aes(trait, repeatability, colour = sex, shape = sex, group = sex)) +
    geom_point(size = 3, position = position_dodge(width = .35)) +
    scale_colour_manual(values = c(female = "#CC79A7", male = "#0072B2")) +
    scale_y_continuous(limits = c(0, 1)) +
    labs(x = "Trait", y = "Group-specific repeatability", colour = "Sex", shape = "Sex",
         title = "Repeatability can differ between groups")
  save_teaching_plot(p, path)
}

plot_sex_correlations <- function(tab, path) {
  tab$pair <- factor(paste(tab$trait_1, tab$trait_2, sep = "--"),
                     levels = c("boldness--exploration", "boldness--activity", "exploration--activity"),
                     labels = c("Boldness-exploration", "Boldness-activity", "Exploration-activity"))
  p <- ggplot(tab, aes(pair, correlation, colour = sex, shape = sex, group = sex)) +
    geom_hline(yintercept = 0, linetype = "dashed", colour = "grey60") +
    geom_point(size = 3, position = position_dodge(width = .35)) +
    scale_colour_manual(values = c(female = "#CC79A7", male = "#0072B2")) +
    coord_cartesian(ylim = c(-1, 1)) +
    labs(x = "Among-individual trait pair", y = "Correlation", colour = "Sex", shape = "Sex",
         title = "Behavioural-syndrome correlations can differ between groups")
  save_teaching_plot(p, path)
}

run_sex_groups <- function() {
  x <- make_sex_groups(); started <- proc.time()[["elapsed"]]
  fits <- lapply(split(x$data, x$data$sex), fit_sex_group)
  elapsed <- proc.time()[["elapsed"]] - started
  if (!all(vapply(fits, function(f) isTRUE(f$sdr$pdHess) && f$fit$convergence == 0 && max(abs(f$obj$gr(f$fit$par))) <= .01, logical(1)))) {
    stop("A sex-group fit did not pass the declared convergence, curvature, and gradient checks.")
  }
  summary <- sex_group_summary(fits, x$traits)
  correlations <- sex_correlation_summary(fits)
  health <- data.frame(sex = names(fits), convergence = vapply(fits, function(f) f$fit$convergence, numeric(1)),
                       pd_hessian = vapply(fits, function(f) isTRUE(f$sdr$pdHess), logical(1)),
                       max_gradient = vapply(fits, function(f) max(abs(f$obj$gr(f$fit$par))), numeric(1)))
  utils::write.csv(x$data, file.path(out_analysis, "sex-group-input.csv"), row.names = FALSE)
  utils::write.csv(summary, file.path(out_analysis, "sex-group-repeatability.csv"), row.names = FALSE)
  utils::write.csv(correlations, file.path(out_analysis, "sex-group-correlations.csv"), row.names = FALSE)
  utils::write.csv(health, file.path(out_analysis, "sex-group-fit-health.csv"), row.names = FALSE)
  plot_sex_repeatability(summary, file.path(out_fig, "sex-group-repeatability.png"))
  plot_sex_correlations(correlations, file.path(out_fig, "sex-group-correlations.png"))
  elapsed
}

u <- run_univariate()
mv_seconds <- run_multivariate()
sex_seconds <- run_sex_groups()
meta <- data.frame(component = c("univariate_first_fit", "multivariate_fit", "sex_group_fits"),
                   seconds = c(u$elapsed, mv_seconds, sex_seconds))
utils::write.csv(meta, file.path(out_analysis, "runtime.csv"), row.names = FALSE)
file.copy(list.files(out_analysis, full.names = TRUE), out_download, overwrite = TRUE)
file.copy(list.files(out_fig, full.names = TRUE), out_download, overwrite = TRUE)
file.copy(file.path(root, "analysis", "extensions", "random-slopes.R"), out_download, overwrite = TRUE)
WarningLimits of this lesson

The examples are Gaussian and simulated. The temperature example needs repeated within-individual temperature coverage; lines inferred from different animals observed at different narrow temperature ranges do not identify the same reaction norm. The sex example identifies group-specific covariance targets, not within-animal plasticity. Neither example supports causal claims, performance, interval calibration, a sample size, or a design rule.