#!/usr/bin/env Rscript
# Refit the selected nine-trait, intercept-only Arctic charr model.
# Run from the repository root after tutorial/data/prepare-charr.R.
# Usage: Rscript --vanilla tutorial/downloads/charr/fit-charr.R glmmTMB
# Rscript --vanilla tutorial/downloads/charr/fit-charr.R gllvmTMB
args <- commandArgs(trailingOnly = TRUE)
if (length(args) != 1L || !args[[1L]] %in% c("glmmTMB", "gllvmTMB")) {
stop("Choose one engine: glmmTMB or gllvmTMB.", call. = FALSE)
}
engine <- args[[1L]]
prepared_path <- file.path("analysis", "cache", "tutorial-data", "charr-nine-intercept.rds")
if (!file.exists(prepared_path)) {
stop("Run tutorial/data/prepare-charr.R from the repository root first.", call. = FALSE)
}
prepared <- readRDS(prepared_path)
d <- prepared$long
traits <- prepared$traits
stopifnot(nrow(d) == 21278L, length(traits) == 9L,
nlevels(d$individual) == 1185L, nlevels(d$occasion) == 2370L)
set.seed(20261109L)
if (engine == "glmmTMB") {
suppressPackageStartupMessages(library(glmmTMB))
form <- value ~ 0 + trait +
rr(0 + trait | individual, d = 2) + diag(0 + trait | individual) +
rr(0 + trait | occasion, d = 2)
initial <- glmmTMB(form, data = d, family = gaussian(),
dispformula = ~ 0 + trait, REML = FALSE)
starts <- initial$obj$env$parList(initial$fit$par)[c("beta", "betadisp", "theta")]
fit <- glmmTMB(form, data = d, family = gaussian(),
dispformula = ~ 0 + trait, REML = FALSE, start = starts,
control = glmmTMBControl(optimizer = optim,
optArgs = list(method = "BFGS"),
optCtrl = list(maxit = 3000L, reltol = 1e-11)))
convergence <- fit$fit$convergence
positive_hessian <- isTRUE(fit$sdr$pdHess)
max_gradient <- max(abs(fit$sdr$gradient.fixed))
logLik_value <- as.numeric(logLik(fit))
parameter_count <- attr(logLik(fit), "df")
parameter_values <- fit$fit$par
} else {
suppressPackageStartupMessages(library(gllvmTMB))
form <- value ~ 0 + trait +
latent(0 + trait | individual, d = 2, unique = TRUE) +
latent(0 + trait | occasion, d = 2, unique = TRUE)
initial <- gllvmTMB(form, data = d, trait = "trait", unit = "individual",
unit_obs = "occasion", family = gaussian(), REML = FALSE)
fit <- gllvmTMB(form, data = d, trait = "trait", unit = "individual",
unit_obs = "occasion", family = gaussian(), REML = FALSE,
control = gllvmTMBcontrol(optimizer = "optim", n_init = 1L,
init_jitter = 0, start_from = initial,
optArgs = list(method = "BFGS",
control = list(maxit = 3000L, reltol = 1e-11))))
convergence <- fit$fit_health$convergence
positive_hessian <- isTRUE(fit$fit_health$pd_hessian)
max_gradient <- max(abs(fit$tmb_obj$gr(fit$opt$par)))
logLik_value <- -fit$opt$objective
parameter_count <- length(fit$opt$par)
parameter_values <- fit$opt$par
}
aic <- -2 * logLik_value + 2 * parameter_count
diagnostics <- data.frame(
engine = engine,
package_version = as.character(packageVersion(engine)),
convergence = convergence,
positive_hessian = positive_hessian,
maximum_absolute_gradient = max_gradient,
log_likelihood = logLik_value,
parameters = parameter_count,
AIC = aic,
numerical_checks_pass = isTRUE(convergence == 0) && positive_hessian &&
is.finite(max_gradient) && max_gradient <= 0.01 &&
is.finite(logLik_value) && is.finite(parameter_count) &&
all(is.finite(parameter_values))
)
print(diagnostics, row.names = FALSE)
normal_matrix <- function(x, traits) {
x <- as.matrix(x)
if (!identical(dim(x), c(length(traits), length(traits))))
stop("Covariance dimension does not match the trait list.")
strip <- function(z) sub("^trait", "", z)
rn <- rownames(x); cn <- colnames(x)
if (!is.null(rn) && !is.null(cn)) {
if (!setequal(strip(rn), traits) || !setequal(strip(cn), traits))
stop("Covariance labels do not match the prepared trait order.")
x <- x[match(traits, strip(rn)), match(traits, strip(cn)), drop = FALSE]
}
dimnames(x) <- list(traits, traits)
x
}
extract_glmm_matrices <- function(fit, traits) {
vc <- glmmTMB::VarCorr(fit)$cond
out <- list()
for (tier in c("B", "W")) {
group <- if (tier == "B") "individual" else "occasion"
keys <- names(vc)[sub("\\.[0-9]+$", "", names(vc)) == group]
codes <- vapply(vc[keys], function(x) names(attr(x, "blockCode"))[1L],
character(1))
rr <- keys[codes == "rr"]
diagonal <- keys[codes == "diag"]
if (length(rr) != 1L) stop("Expected one shared covariance block at ", tier)
shared <- normal_matrix(vc[[rr]], traits)
if (tier == "B") {
if (length(diagonal) != 1L) stop("Expected one between-fish unique block.")
unique <- normal_matrix(vc[[diagonal]], traits)
} else {
if (length(diagonal)) stop("Unexpected within-fish diagonal block.")
beta <- glmmTMB::fixef(fit)$disp
wanted <- paste0("trait", traits)
if (length(beta) != length(traits) || !setequal(names(beta), wanted))
stop("Expected one Gaussian dispersion parameter per trait.")
unique <- diag(exp(2 * beta[match(wanted, names(beta))]), length(traits))
dimnames(unique) <- list(traits, traits)
}
out[[paste0(tier, "_shared")]] <- shared
out[[paste0(tier, "_unique")]] <- unique
out[[paste0(tier, "_total")]] <- shared + unique
}
out
}
extract_gllvm_matrices <- function(fit, traits) {
out <- list()
for (tier in c("B", "W")) {
level <- if (tier == "B") "unit" else "unit_obs"
total <- normal_matrix(gllvmTMB::extract_Sigma(
fit, level = level, part = "total", link_residual = "none")$Sigma,
traits)
shared <- normal_matrix(gllvmTMB::extract_Sigma(
fit, level = level, part = "shared", link_residual = "none")$Sigma,
traits)
unique_result <- gllvmTMB::extract_Sigma(
fit, level = level, part = "unique", link_residual = "none")
unique <- if (is.null(unique_result$Sigma)) {
diag(as.numeric(unique_result$s), length(traits))
} else normal_matrix(unique_result$Sigma, traits)
if (is.null(dimnames(unique))) dimnames(unique) <- list(traits, traits)
if (tier == "W") {
observation_variance <- as.numeric(fit$report$sigma_eps)^2
unique <- unique + diag(observation_variance, length(traits))
total <- total + diag(observation_variance, length(traits))
}
out[[paste0(tier, "_shared")]] <- shared
out[[paste0(tier, "_unique")]] <- unique
out[[paste0(tier, "_total")]] <- total
}
out
}
matrices <- if (engine == "glmmTMB") extract_glmm_matrices(fit, traits) else
extract_gllvm_matrices(fit, traits)
for (tier in c("B", "W")) {
shared <- matrices[[paste0(tier, "_shared")]]
unique <- matrices[[paste0(tier, "_unique")]]
total <- matrices[[paste0(tier, "_total")]]
stopifnot(max(abs(total - shared - unique)) < 1e-8,
max(abs(unique - diag(diag(unique)))) < 1e-8,
min(eigen((total + t(total))/2, symmetric = TRUE,
only.values = TRUE)$values) >= -1e-8)
}
distance <- match("Dtot", traits)
exit_time <- match("Exit.time", traits)
point_results <- do.call(rbind, lapply(c("B", "W"), function(tier) {
total <- matrices[[paste0(tier, "_total")]]
shared <- matrices[[paste0(tier, "_shared")]]
data.frame(
engine = engine,
level = if (tier == "B") "Between fish" else "Within fish",
distance_exit_correlation = stats::cov2cor(total)[distance, exit_time],
distance_communality = diag(shared)[distance] / diag(total)[distance],
exit_time_communality = diag(shared)[exit_time] / diag(total)[exit_time],
distance_repeatability = if (tier == "B") {
diag(matrices$B_total)[distance] /
(diag(matrices$B_total)[distance] + diag(matrices$W_total)[distance])
} else NA_real_,
exit_time_repeatability = if (tier == "B") {
diag(matrices$B_total)[exit_time] /
(diag(matrices$B_total)[exit_time] + diag(matrices$W_total)[exit_time])
} else NA_real_
)
}))
point_results$fit_passes_numerical_screen <- diagnostics$numerical_checks_pass
print(point_results, row.names = FALSE)
if (!diagnostics$numerical_checks_pass) {
warning("The fresh point estimates are diagnostic only because the fit did not pass the numerical screen.",
call. = FALSE)
}
out_dir <- file.path("analysis", "cache", "tutorial-data")
dir.create(out_dir, recursive = TRUE, showWarnings = FALSE)
utils::write.csv(diagnostics, file.path(out_dir, paste0("charr-", engine, "-diagnostics.csv")),
row.names = FALSE)
utils::write.csv(point_results,
file.path(out_dir, paste0("charr-", engine, "-point-results.csv")),
row.names = FALSE)
saveRDS(list(initial = initial, fit = fit, diagnostics = diagnostics,
matrices = matrices, point_results = point_results),
file.path(out_dir, paste0("charr-", engine, "-fit.rds")))