Generalized mixed models: binary and count outcomes
Random effects also work with logistic and Poisson models. Learn to read within-group odds ratios, an ICC on the latent scale, successes out of trials, and overdispersion in a mixed count model.
What runs in CodeSplash
- Generalized linear mixed model (logistic / Poisson) Verified in Python and R
You will be able to
- Write a logistic mixed model and say what its odds ratios describe
- Compute a latent-scale ICC from a random-effect variance
- Fit successes out of trials and mixed count models
- Check overdispersion, and know the limits of the Laplace approximation
Add a link
ReadA generalized mixed modelGeneralized linear mixed modelA logistic or Poisson model with random effects inside the link. Its ratios are for one group member. puts a random effect inside a link function. For a yes-or-no outcome:
The shift each patient up or down on the log-odds scale. You can't integrate them out exactly, so CodeSplash uses the Laplace approximation, as lme4's glmer does by default.
Read the card
In the appWald χ²(1) = 14.04, p < .001
- ICC (latent scale)
- 0.2162
- R² marginal
- 0.1430
- R² conditional
- 0.3283
- AIC
- 343.78
- Random effects LR test p
- .001
Plots
View data
| Conditional mode | Level | high | low | Term |
|---|---|---|---|---|
| 0.8405 | P01 | 1.948 | −0.2674 | patient: (Intercept) |
| 0.0062 | P02 | 1.111 | −1.099 | patient: (Intercept) |
| −0.1763 | P03 | 1.290 | −1.643 | patient: (Intercept) |
| −0.4103 | P04 | 0.7568 | −1.577 | patient: (Intercept) |
| −0.0891 | P05 | 1.012 | −1.190 | patient: (Intercept) |
| 1.333 | P06 | 2.474 | 0.1910 | patient: (Intercept) |
| −0.0742 | P07 | 1.027 | −1.175 | patient: (Intercept) |
| 0.3970 | P08 | 1.491 | −0.6971 | patient: (Intercept) |
| −1.041 | P09 | 0.1395 | −2.222 | patient: (Intercept) |
| 1.291 | P10 | 2.437 | 0.1449 | patient: (Intercept) |
| −0.5103 | P11 | 0.6224 | −1.643 | patient: (Intercept) |
| 0.0062 | P12 | 1.111 | −1.099 | patient: (Intercept) |
| −0.0354 | P13 | 1.067 | −1.138 | patient: (Intercept) |
| 0.8701 | P14 | 1.976 | −0.2362 | patient: (Intercept) |
| 0.4030 | P15 | 1.497 | −0.6910 | patient: (Intercept) |
| −0.4935 | P16 | 0.6409 | −1.628 | patient: (Intercept) |
| −0.9958 | P17 | 0.1927 | −2.184 | patient: (Intercept) |
| −1.018 | P18 | 0.1662 | −2.203 | patient: (Intercept) |
| 0.3667 | P19 | 1.461 | −0.7276 | patient: (Intercept) |
| −0.1131 | P20 | 0.9868 | −1.213 | patient: (Intercept) |
| −0.5103 | P21 | 0.6224 | −1.643 | patient: (Intercept) |
| −0.5188 | P22 | 0.6131 | −1.651 | patient: (Intercept) |
| −0.4991 | P23 | 0.6348 | −1.633 | patient: (Intercept) |
| 0.4030 | P24 | 1.497 | −0.6910 | patient: (Intercept) |
| −0.9983 | P25 | 0.1898 | −2.186 | patient: (Intercept) |
| 0.8111 | P26 | 1.921 | −0.2985 | patient: (Intercept) |
| 0.4061 | P27 | 1.500 | −0.6880 | patient: (Intercept) |
| −0.0265 | P28 | 1.077 | −1.130 | patient: (Intercept) |
| 0.4151 | P29 | 1.509 | −0.6789 | patient: (Intercept) |
| 0.3819 | P30 | 1.476 | −0.7123 | patient: (Intercept) |
| −0.5151 | P31 | 0.7894 | −1.819 | patient: (Intercept) |
| −0.5389 | P32 | 0.7578 | −1.836 | patient: (Intercept) |
| −0.5352 | P33 | 0.7627 | −1.833 | patient: (Intercept) |
| 0.5564 | P34 | 1.707 | −0.5937 | patient: (Intercept) |
| 1.487 | P35 | 2.582 | 0.3926 | patient: (Intercept) |
| 0.0420 | P36 | 1.255 | −1.171 | patient: (Intercept) |
| 0.0206 | P37 | 1.229 | −1.188 | patient: (Intercept) |
| 0.5291 | P38 | 1.676 | −0.6177 | patient: (Intercept) |
| 0.0420 | P39 | 1.255 | −1.171 | patient: (Intercept) |
| 0.0562 | P40 | 1.272 | −1.160 | patient: (Intercept) |
| −0.5315 | P41 | 0.7676 | −1.831 | patient: (Intercept) |
| 0.0278 | P42 | 1.238 | −1.182 | patient: (Intercept) |
| −0.5672 | P43 | 0.7206 | −1.855 | patient: (Intercept) |
| 0.0444 | P44 | 1.258 | −1.169 | patient: (Intercept) |
| −0.5711 | P45 | 0.7156 | −1.858 | patient: (Intercept) |
| 0.5727 | P46 | 1.725 | −0.5794 | patient: (Intercept) |
| −0.5464 | P47 | 0.7479 | −1.841 | patient: (Intercept) |
| 1.466 | P48 | 2.561 | 0.3717 | patient: (Intercept) |
| −0.5315 | P49 | 0.7676 | −1.831 | patient: (Intercept) |
| 0.5319 | P50 | 1.679 | −0.6153 | patient: (Intercept) |
| 0.5564 | P51 | 1.707 | −0.5937 | patient: (Intercept) |
| −0.5464 | P52 | 0.7479 | −1.841 | patient: (Intercept) |
| −0.5278 | P53 | 0.7724 | −1.828 | patient: (Intercept) |
| −0.5242 | P54 | 0.7773 | −1.826 | patient: (Intercept) |
| 0.0349 | P55 | 1.246 | −1.177 | patient: (Intercept) |
| 0.5099 | P56 | 1.655 | −0.6347 | patient: (Intercept) |
| 0.5537 | P57 | 1.704 | −0.5961 | patient: (Intercept) |
| 0.0110 | P58 | 1.218 | −1.196 | patient: (Intercept) |
| 0.0467 | P59 | 1.261 | −1.167 | patient: (Intercept) |
| 0.5264 | P60 | 1.673 | −0.6201 | patient: (Intercept) |
View data
| Odds ratio | high | Term | low |
|---|---|---|---|
| 1.490 | 1.775 | visit | 1.251 |
| 0.2996 | 0.5775 | treatment: drug | 0.1555 |
| 1.006 | 1.044 | age | 0.9690 |
View data
| Scaled residual |
|---|
| 0.7746 |
| 0.4778 |
| 0.9932 |
| 0.7464 |
| 0.4781 |
| 0.0810 |
| 0.9071 |
| 0.2831 |
| 0.4515 |
| 0.5123 |
| 0.5549 |
| 0.6849 |
| 0.0451 |
| 0.3233 |
| 0.3427 |
| 0.3539 |
| 0.1334 |
| 0.9568 |
| 0.4240 |
| 0.9980 |
| 0.9503 |
| 0.8422 |
| 0.8813 |
| 0.7586 |
| 0.7756 |
| 0.4245 |
| 0.6941 |
| 0.3560 |
| 0.8420 |
| 0.1608 |
| 0.3787 |
| 0.9088 |
| 0.6565 |
| 0.2840 |
| 0.5448 |
| 0.0323 |
| 0.5848 |
| 0.1958 |
| 0.1798 |
| 0.3354 |
| 0.8588 |
| 0.7867 |
| 0.8550 |
| 0.7698 |
| 0.9145 |
| 0.6230 |
| 0.3467 |
| 0.4586 |
| 0.2623 |
| 0.7182 |
| 0.7472 |
| 0.9036 |
| 0.2026 |
| 0.6352 |
| 0.0112 |
| 0.4320 |
| 0.4599 |
| 0.6455 |
| 0.4323 |
| 0.1864 |
First 60 of 295 rows.
View data
| Population-level prediction (rank, 0–1) | Scaled residual |
|---|---|
| 0.4407 | 0.7746 |
| 0.6407 | 0.4778 |
| 0.7661 | 0.9932 |
| 0.8644 | 0.7464 |
| 0.9627 | 0.4781 |
| 0.3153 | 0.0810 |
| 0.5136 | 0.9071 |
| 0.7102 | 0.2831 |
| 0.8085 | 0.4515 |
| 0.9068 | 0.5123 |
| 0.3153 | 0.5549 |
| 0.5847 | 0.6849 |
| 0.7271 | 0.0451 |
| 0.8254 | 0.3233 |
| 0.9237 | 0.3427 |
| 0.4983 | 0.3539 |
| 0.6983 | 0.1334 |
| 0.7966 | 0.9568 |
| 0.8949 | 0.4240 |
| 0.9932 | 0.9980 |
| 0.3593 | 0.9503 |
| 0.5559 | 0.8422 |
| 0.7186 | 0.8813 |
| 0.8169 | 0.7586 |
| 0.9153 | 0.7756 |
| 0.4814 | 0.4245 |
| 0.6814 | 0.6941 |
| 0.7864 | 0.3560 |
| 0.8847 | 0.8420 |
| 0.9831 | 0.1608 |
| 0.4339 | 0.3787 |
| 0.6339 | 0.9088 |
| 0.7593 | 0.6565 |
| 0.8576 | 0.2840 |
| 0.9559 | 0.5448 |
| 0.5017 | 0.0323 |
| 0.7017 | 0.5848 |
| 0.8000 | 0.1958 |
| 0.8983 | 0.1798 |
| 0.9966 | 0.3354 |
| 0.4746 | 0.8588 |
| 0.6746 | 0.7867 |
| 0.7831 | 0.8550 |
| 0.8814 | 0.7698 |
| 0.9797 | 0.9145 |
| 0.4407 | 0.6230 |
| 0.6407 | 0.3467 |
| 0.7661 | 0.4586 |
| 0.8644 | 0.2623 |
| 0.9627 | 0.7182 |
| 0.3153 | 0.7472 |
| 0.5136 | 0.9036 |
| 0.7102 | 0.2026 |
| 0.8085 | 0.6352 |
| 0.9068 | 0.0112 |
| 0.4000 | 0.4320 |
| 0.6000 | 0.4599 |
| 0.7356 | 0.6455 |
| 0.8339 | 0.4323 |
| 0.9322 | 0.1864 |
First 60 of 295 rows.
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 60 levels of patient.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.067, p = .145 over 250 simulations.
- No more outliers than expected (simulation) — 4 of 295 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = .305).
Fixed effects
| Term | B (link scale) | SE | z | p | Odds ratio | 90% CI low | 90% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.453 | 1.260 | −1.153 | .249 | 0.2339 | 0.0295 | 1.857 |
| visit | 0.3986 | 0.1064 | 3.747 | < .001 | 1.490 | 1.251 | 1.775 |
| treatment: drug | −1.205 | 0.3989 | −3.021 | .003 | 0.2996 | 0.1555 | 0.5775 |
| age | 0.0059 | 0.0227 | 0.2595 | .795 | 1.006 | 0.9690 | 1.044 |
Odds ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| visit | 14.037 | 1 | < .001 |
| treatment | 9.128 | 1 | .003 |
| age | 0.0673 | 1 | .795 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| patient | (Intercept) | 0.9076 | 0.9527 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| patient | (Intercept) | P01 | 0.8405 | 0.6736 |
| patient | (Intercept) | P02 | 0.0062 | 0.6717 |
| patient | (Intercept) | P03 | −0.1763 | 0.8915 |
| patient | (Intercept) | P04 | −0.4103 | 0.7095 |
| patient | (Intercept) | P05 | −0.0891 | 0.6692 |
| patient | (Intercept) | P06 | 1.333 | 0.6940 |
| patient | (Intercept) | P07 | −0.0742 | 0.6695 |
| patient | (Intercept) | P08 | 0.3970 | 0.6652 |
| patient | (Intercept) | P09 | −1.041 | 0.7179 |
| patient | (Intercept) | P10 | 1.291 | 0.6969 |
| patient | (Intercept) | P11 | −0.5103 | 0.6887 |
| patient | (Intercept) | P12 | 0.0062 | 0.6717 |
| patient | (Intercept) | P13 | −0.0354 | 0.6705 |
| patient | (Intercept) | P14 | 0.8701 | 0.6726 |
| patient | (Intercept) | P15 | 0.4030 | 0.6652 |
| patient | (Intercept) | P16 | −0.4935 | 0.6897 |
| patient | (Intercept) | P17 | −0.9958 | 0.7226 |
| patient | (Intercept) | P18 | −1.018 | 0.7202 |
| patient | (Intercept) | P19 | 0.3667 | 0.6653 |
| patient | (Intercept) | P20 | −0.1131 | 0.6687 |
| patient | (Intercept) | P21 | −0.5103 | 0.6887 |
| patient | (Intercept) | P22 | −0.5188 | 0.6882 |
| patient | (Intercept) | P23 | −0.4991 | 0.6893 |
| patient | (Intercept) | P24 | 0.4030 | 0.6652 |
| patient | (Intercept) | P25 | −0.9983 | 0.7223 |
| patient | (Intercept) | P26 | 0.8111 | 0.6746 |
| patient | (Intercept) | P27 | 0.4061 | 0.6651 |
| patient | (Intercept) | P28 | −0.0265 | 0.6707 |
| patient | (Intercept) | P29 | 0.4151 | 0.6651 |
| patient | (Intercept) | P30 | 0.3819 | 0.6652 |
| patient | (Intercept) | P31 | −0.5151 | 0.7930 |
| patient | (Intercept) | P32 | −0.5389 | 0.7883 |
| patient | (Intercept) | P33 | −0.5352 | 0.7891 |
| patient | (Intercept) | P34 | 0.5564 | 0.6992 |
| patient | (Intercept) | P35 | 1.487 | 0.6656 |
| patient | (Intercept) | P36 | 0.0420 | 0.7375 |
| patient | (Intercept) | P37 | 0.0206 | 0.7348 |
| patient | (Intercept) | P38 | 0.5291 | 0.6972 |
| patient | (Intercept) | P39 | 0.0420 | 0.7375 |
| patient | (Intercept) | P40 | 0.0562 | 0.7392 |
First 40 of 60 rows.
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0667 | .145 |
| Outliers (rows at the edge of their simulations) | 4 | .305 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- 5 of 300 rows were left out because a value was missing.
- Logistic GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); latent residual variance π²/3.
The exact R script · R R version 4.5.1 (2025-06-13)
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec 8d8bb8afc6ce0a43
# Dataset: s1_visits (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(lme4))
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_visits.parquet", col_select = c("adverse event", "visit", "treatment", "age", "patient")))
n_input <- nrow(df)
df[["adverse event"]] <- factor(df[["adverse event"]], levels = c("false", "true")) # stored level order
df[["treatment"]] <- factor(df[["treatment"]], levels = c("control", "drug")) # stored level order
df[["patient"]] <- factor(df[["patient"]], levels = c("P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16", "P17", "P18", "P19", "P20", "P21", "P22", "P23", "P24", "P25", "P26", "P27", "P28", "P29", "P30", "P31", "P32", "P33", "P34", "P35", "P36", "P37", "P38", "P39", "P40", "P41", "P42", "P43", "P44", "P45", "P46", "P47", "P48", "P49", "P50", "P51", "P52", "P53", "P54", "P55", "P56", "P57", "P58", "P59", "P60")) # stored level order
df <- df[stats::complete.cases(df[c("adverse event", "visit", "treatment", "age", "patient")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("adverse event", "visit", "treatment", "age", "patient")) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome <- "adverse event"
trials <- NULL
exposure <- NULL
predictors <- c("visit", "treatment", "age")
group <- "patient"
slopes <- c()
group2 <- NULL
family <- "binomial" # binomial (logit) | poisson (log)
nesting <- "nested"
correlated <- "correlated" == "correlated"
interactions <- "none"
conf <- 0.9
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
event <- NULL
lhs <- NULL
w <- rep(1, nrow(df))
if (is.factor(df[[outcome]])) {
if (family != "binomial" || nlevels(df[[outcome]]) != 2) stop(sprintf("%s is categorical: use the logistic model with exactly two levels (found %d).", outcome, nlevels(df[[outcome]])))
event <- levels(df[[outcome]])[2] # default: the second stored level ("true" for yes/no)
df$.cs_y <- as.numeric(as.character(df[[outcome]]) == event)
y <- df$.cs_y
lhs <- ".cs_y"
} else {
y <- as.numeric(df[[outcome]])
if (any(y < 0) || any(abs(y - round(y)) > 1e-9)) stop(sprintf("%s must hold whole non-negative numbers (counts or 0/1).", outcome))
if (family == "binomial" && !is.null(trials)) {
w <- df[[trials]]
if (any(w <= 0) || any(y > w)) stop(sprintf("%s must be positive and at least %s on every row.", trials, outcome))
df$.cs_succ <- y
df$.cs_fail <- w - y
lhs <- "cbind(.cs_succ, .cs_fail)" # successes out of trials
y <- y / w
} else if (family == "binomial" && !all(y %in% c(0, 1))) {
stop(sprintf("%s must be 0/1 for a logistic model (or give the number of Trials).", outcome))
}
}
offset <- rep(0, nrow(df))
if (family == "poisson" && !is.null(exposure)) {
if (any(df[[exposure]] <= 0)) stop(sprintf("%s must be positive (its log is the offset).", exposure))
offset <- log(df[[exposure]])
}
df$.cs_offset <- offset
# Degenerate input stops with a catalog error before the fit; Python runs the same checks in the same order.
cs_mixed_check_re(df, group, slopes, group2, nesting, correlated, allow_n = TRUE) # glmer's checks on the grouping factors
for (pred in predictors) {
if (length(unique(df[[pred]])) < 2) cs_error("CS_E_CONSTANT", column = pred) # one value (or one level with data) is no variation
}
fml <- cs_mixed_formula(outcome, predictors, interactions, group, slopes, group2, nesting, correlated, lhs = lhs)
fam <- if (family == "binomial") binomial() else poisson()
# Tight tolerances (default: bobyqa then Nelder–Mead, tolPwrss = 1e-7) so both engines reach the same optimum.
ctrl <- glmerControl(optimizer = c("bobyqa", "bobyqa"), optCtrl = list(rhoend = 1e-12, maxfun = 1e6), tolPwrss = 1e-12)
# %% Fit (Laplace, nAGQ = 1)
fit <- glmer(fml, data = df, family = fam, offset = .cs_offset, nAGQ = 1, control = ctrl)
X <- getME(fit, "X")
terms_x <- cs_design_labels(df, predictors, interactions)
if (ncol(X) < length(terms_x)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
b <- unname(fixef(fit))
V <- as.matrix(vcov(fit)) # lme4 default: from the finite-difference Hessian
se <- sqrt(diag(V))
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
values <- list()
coefs <- list()
for (j in seq_len(k)) {
t <- terms_x[j]
row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j])
row <- c(row, list(ratio = exp(b[j]), ratio_ci_low = exp(row$ci_low), ratio_ci_high = exp(row$ci_high)))
coefs[[j]] <- row
for (key in c("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")) values[[sprintf("%s[%s]", key, t)]] <- if (key == "coef") row$estimate else row[[key]]
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
idx <- blocks[[name]]
chi2 <- as.numeric(t(b[idx]) %*% solve(V[idx, idx, drop = FALSE], b[idx]))
pc <- pchisq(chi2, length(idx), lower.tail = FALSE)
effects[[length(effects) + 1]] <- list(term = name, chi2 = chi2, df = length(idx), p = pc)
values[[sprintf("chi2[%s]", name)]] <- chi2; values[[sprintf("chi2_df[%s]", name)]] <- as.numeric(length(idx)); values[[sprintf("chi2_p[%s]", name)]] <- pc
}
values$focal_chi2 <- NA; values$focal_df <- NA; values$focal_p <- NA # no fixed predictor
if (length(effects)) {
values$focal_chi2 <- effects[[1]]$chi2; values$focal_df <- as.numeric(effects[[1]]$df); values$focal_p <- effects[[1]]$p
}
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
valid <- c(group, group2, if (!is.null(group2)) paste0(group, ":", group2))
vc <- cs_mixed_varcorr(fit, valid)
for (i in seq_len(nrow(vc))) {
if (is.na(vc$effect2[i])) {
values[[sprintf("var[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$vcov[i]
values[[sprintf("sd[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$sdcor[i]
} else {
values[[sprintf("cor[%s|%s|%s]", vc$group[i], vc$effect1[i], vc$effect2[i])]] <- vc$sdcor[i]
}
}
eta_fixed <- as.vector(X %*% b)
var_fixed <- if (n > 1) var(eta_fixed) else 0
var_random <- cs_mixed_random_variance(fit, df)
var_residual <- if (family == "binomial") pi^2 / 3 else log1p(1 / exp(mean(eta_fixed) + var_random / 2))
total <- var_fixed + var_random + var_residual
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta
ll <- as.numeric(logLik(fit))
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, family = family, log_lik = ll, deviance = -2 * ll, aic = -2 * ll + 2 * n_params,
bic = -2 * ll + log(n) * n_params, icc = var_random / (var_random + var_residual), r2_marginal = var_fixed / total,
r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random, var_residual = var_residual,
singular = isSingular(fit, tol = 1e-4), n_params = n_params, n_theta = n_theta,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (!is.null(group2)) {
values$n_groups2 <- if (nesting == "nested") nlevels(droplevels(interaction(df[[group]], df[[group2]], drop = TRUE))) else nlevels(droplevels(df[[group2]]))
}
# %% Random effects vs none (likelihood ratio against the GLM)
if (TRUE) {
fixed_rhs <- if (length(predictors)) as.character(cs_model_formula(outcome, predictors, interactions))[3] else "1"
g <- glm(stats::as.formula(paste(if (is.null(lhs)) paste0("`", outcome, "`") else lhs, "~", fixed_rhs)), family = fam, data = df, offset = .cs_offset,
control = glm.control(epsilon = 1e-14, maxit = 100))
lrt <- max(2 * (ll - as.numeric(logLik(g))), 0)
lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
if (n_theta == 1) lrt_p <- lrt_p / 2 # boundary: 50:50 mixture of chi2(0) and chi2(1)
values$re_lrt <- lrt; values$re_lrt_df <- as.numeric(n_theta); values$re_lrt_p <- lrt_p
}
# %% Assumptions
singular <- isTRUE(values$singular)
assumptions <- list(list(key = "singular", label = "Non-singular fit", status = if (singular) "warn" else "pass",
detail = if (singular) "A variance component is estimated at (or near) zero: simplify the random effects." else "Every variance component is clearly above zero."))
nlev <- c(setNames(n_groups, group), if (!is.null(group2)) setNames(values$n_groups2, if (nesting == "nested") paste0(group, ":", group2) else group2))
few <- names(nlev)[nlev < 5]
assumptions[[2]] <- list(key = "groups", label = "Enough groups", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 5 levels for %s: its variance is estimated very imprecisely.", paste(few, collapse = ", ")) else sprintf("%d levels of %s.", n_groups, group))
if (family == "poisson") {
mu <- unname(fitted(fit))
disp <- sum((y - mu)^2 / mu) / (n - k)
values$dispersion <- disp
assumptions[[3]] <- list(key = "overdispersion", label = "No overdispersion", status = if (disp > 1.5) "warn" else "pass", statistic = disp,
detail = paste0(sprintf("Pearson χ² / residual df = %.2f", disp), if (disp > 1.5) "; consider an observation-level random effect or a negative binomial model." else "."))
}
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like <- family == "poisson" || !is.null(trials) # spread and zeros are checked for counts, not for 0/1 data
m_trials <- if (family == "binomial" && !is.null(trials)) w else NULL
rng <- cs_rng(1)
dh_terms <- cs_dharma_terms(df, group, slopes, group2, nesting, correlated, vc)
eta_pop <- as.vector(X %*% b) + offset # fixed part: the simulations draw new random effects around it
sims <- cs_dharma_simulate(eta_pop, dh_terms, family, m_trials, 250, rng)
y_obs <- if (!is.null(m_trials)) round(y * w) else y # successes for successes-of-trials outcomes
fitted_resp <- cs_dharma_mean(eta_pop, family) * (if (!is.null(m_trials)) w else 1) # population-level, as DHARMa
dh <- cs_dharma_residuals(y_obs, fitted_resp, sims, family, rng, zeros = counts_like)
values$dharma_n_sim <- dh$n_sim; values$dharma_ks <- dh$ks; values$dharma_ks_p <- dh$ks_p
values$dharma_outliers <- dh$outliers; values$dharma_outlier_p <- dh$outlier_p
uni_bad <- dh$ks_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "uniformity", label = "Simulated residuals look uniform", status = if (uni_bad) "warn" else "pass",
statistic = dh$ks, p = dh$ks_p,
detail = paste0(sprintf("Kolmogorov–Smirnov D = %.3f, %s over %d simulations", dh$ks, cs_fmt_p(dh$ks_p), as.integer(dh$n_sim)),
if (uni_bad) "; the outcome's distribution doesn't match the model (check the residual plots)." else "."))
if (counts_like) {
values$dharma_disp_ratio <- dh$disp_ratio; values$dharma_disp_p <- dh$disp_p
values$dharma_zero_ratio <- dh$zero_ratio; values$dharma_zero_p <- dh$zero_p
disp_bad <- dh$disp_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "dispersion", label = "Residual spread matches the model (simulation)", status = if (disp_bad) "warn" else "pass",
statistic = dh$disp_ratio, p = dh$disp_p,
detail = paste0(sprintf("Observed / simulated spread = %.2f, %s", dh$disp_ratio, cs_fmt_p(dh$disp_p)),
if (!disp_bad) "." else if (dh$disp_ratio > 1) "; overdispersion: consider an observation-level random effect or a negative binomial model." else "; underdispersion: standard errors are conservative."))
zero_bad <- dh$zero_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "zero_inflation", label = "Number of zeros matches the model (simulation)", status = if (zero_bad) "warn" else "pass",
statistic = dh$zero_ratio, p = dh$zero_p,
detail = paste0(sprintf("Observed / simulated zeros = %.2f, %s", dh$zero_ratio, cs_fmt_p(dh$zero_p)),
if (!zero_bad) "." else if (dh$zero_ratio > 1) "; more zeros than the model expects: consider a zero-inflated or hurdle model." else "; fewer zeros than the model expects."))
}
out_bad <- dh$outlier_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "outliers", label = "No more outliers than expected (simulation)", status = if (out_bad) "warn" else "pass",
statistic = as.numeric(dh$outliers), p = dh$outlier_p,
detail = sprintf("%d of %d rows sit at the edge of their %d simulations (within 1/%d of either end; binomial test, %s).", as.integer(dh$outliers), as.integer(n), as.integer(dh$n_sim), as.integer(dh$n_sim) + 1L, cs_fmt_p(dh$outlier_p)))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
rl <- if (family == "binomial") "Odds ratio" else "Rate ratio"
re_tab <- cs_mixed_ranef(fit, valid)
vc_rows <- lapply(seq_len(nrow(vc)), function(i) {
if (is.na(vc$effect2[i])) list(group = vc$group[i], effect = vc$effect1[i], variance = vc$vcov[i], sd = vc$sdcor[i], cor = NULL)
else list(group = vc$group[i], effect = paste(vc$effect1[i], "~", vc$effect2[i]), variance = NULL, sd = NULL, cor = vc$sdcor[i])
})
slopes_tab <- Filter(function(cf) cf$term != "(Intercept)", coefs)
tests_text <- if (length(effects)) sprintf(" %s: Wald χ²(%d) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("%s mixed model of %s%s (n = %d, %d levels of %s).%s Latent-scale ICC = %.2f.", if (family == "binomial") "Logistic" else "Poisson",
outcome, if (!is.null(event)) sprintf(" (event: %s)", event) else "", n, n_groups, group, tests_text, values$icc)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(cs_chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", list(
group = cs_col("Level", cat_tab$level, kind = "categorical"), estimate = cs_col("Conditional mode", cat_tab$estimate),
low = cs_col("low", cat_tab$estimate - z * cat_tab$sd), high = cs_col("high", cat_tab$estimate + z * cat_tab$sd),
term = cs_col("Term", paste0(cat_tab$group, ": ", cat_tab$effect), kind = "categorical"))))
if (length(slopes_tab)) {
charts[[2]] <- cs_chart("ratios", "forest", paste0(rl, "s"), list(
label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col(rl, vapply(slopes_tab, `[[`, 0, "ratio")),
low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ratio_ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ratio_ci_high"))),
controls = list(reference = 1, log = TRUE))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B (link scale)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "ratio", label = rl, type = "number"),
list(key = "ratio_ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ratio_ci_high", label = paste(pct, "CI high"), type = "number")),
rows = coefs, note = sprintf("%ss are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.", rl)))
if (length(effects)) {
tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint Wald tests of each predictor", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "chi2", label = "Wald χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = effects)
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects (link scale)", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"),
list(key = "variance", label = "Variance", type = "number"), list(key = "sd", label = "SD", type = "number"), list(key = "cor", label = "Correlation", type = "number")),
rows = vc_rows)
mode_rows <- lapply(seq_len(min(nrow(re_tab), 2000)), function(i) as.list(re_tab[i, ]))
tables[[length(tables) + 1]] <- list(key = "modes", title = "Conditional modes of the random effects", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "estimate", label = "Mode", type = "number"), list(key = "sd", label = "Conditional SD", type = "number")), rows = mode_rows)
dh_rows <- list(list(check = "Uniformity (Kolmogorov–Smirnov D)", statistic = dh$ks, p = dh$ks_p))
if (counts_like) {
dh_rows <- c(dh_rows, list(list(check = "Spread (observed / simulated)", statistic = dh$disp_ratio, p = dh$disp_p),
list(check = "Zeros (observed / simulated)", statistic = dh$zero_ratio, p = dh$zero_p)))
}
dh_rows[[length(dh_rows) + 1]] <- list(check = "Outliers (rows at the edge of their simulations)", statistic = as.numeric(dh$outliers), p = dh$outlier_p)
tables[[length(tables) + 1]] <- list(key = "dharma", title = "Simulated residual checks (DHARMa)", columns = list(
list(key = "check", label = "Check", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = dh_rows, note = paste0(sprintf("%d simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. ", as.integer(dh$n_sim)),
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."))
m_show <- min(n, 5000) # evenly spaced rows for the residual charts
show <- if (m_show > 1) ((seq_len(m_show) - 1) * (n - 1)) %/% (m_show - 1) + 1 else 1
res_show <- dh$residuals[show]
charts[[length(charts) + 1]] <- cs_chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", list(x = cs_col("Scaled residual", res_show)),
controls = list(reference = "uniform"))
rank_fit <- cs_dharma_rank01(fitted_resp)
charts[[length(charts) + 1]] <- cs_chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", list(
x = cs_col("Population-level prediction (rank, 0–1)", rank_fit[show]), y = cs_col("Scaled residual", res_show)), controls = list(fit = "loess"))
statistics <- list(list(key = "icc", label = "ICC (latent scale)", value = values$icc), list(key = "r2_marginal", label = "R² marginal", value = values$r2_marginal),
list(key = "r2_conditional", label = "R² conditional", value = values$r2_conditional), list(key = "aic", label = "AIC", value = values$aic))
if (!is.null(values$re_lrt_p)) statistics[[length(statistics) + 1]] <- list(key = "re_lrt_p", label = "Random effects LR test p", value = values$re_lrt_p, format = "p")
cs_publish(list(
method = "mixed.glmm",
methodVersion = "1.1.0",
title = "Generalized linear mixed model",
engine = cs_engine_info("lme4", "nanoparquet"),
n = n,
summary = summary,
apa = if (length(effects)) sprintf("Wald χ²(%d) = %.2f, %s", as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else "",
statistics = statistics,
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (family == "binomial") "Logistic" else "Poisson", " GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); ",
if (family == "binomial") "latent residual variance π²/3." else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")),
charts = charts,
values = values
))
Wald χ²(1) = 14.04, p < .001
- ICC (latent scale)
- 0.2162
- R² marginal
- 0.1430
- R² conditional
- 0.3283
- AIC
- 343.78
- Random effects LR test p
- .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 60 levels of patient.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.067, p = .145 over 250 simulations.
- No more outliers than expected (simulation) — 4 of 295 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = .305).
Fixed effects
| Term | B (link scale) | SE | z | p | Odds ratio | 90% CI low | 90% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.453 | 1.260 | −1.153 | .249 | 0.2339 | 0.0294 | 1.857 |
| visit | 0.3986 | 0.1064 | 3.747 | < .001 | 1.490 | 1.251 | 1.775 |
| treatment: drug | −1.205 | 0.3989 | −3.021 | .003 | 0.2996 | 0.1555 | 0.5775 |
| age | 0.0059 | 0.0227 | 0.2595 | .795 | 1.006 | 0.9690 | 1.044 |
Odds ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| visit | 14.037 | 1 | < .001 |
| treatment | 9.127 | 1 | .003 |
| age | 0.0673 | 1 | .795 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| patient | (Intercept) | 0.9076 | 0.9527 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| patient | (Intercept) | P01 | 0.8405 | 0.6736 |
| patient | (Intercept) | P02 | 0.0062 | 0.6717 |
| patient | (Intercept) | P03 | −0.1763 | 0.8915 |
| patient | (Intercept) | P04 | −0.4103 | 0.7095 |
| patient | (Intercept) | P05 | −0.0891 | 0.6692 |
| patient | (Intercept) | P06 | 1.333 | 0.6940 |
| patient | (Intercept) | P07 | −0.0742 | 0.6695 |
| patient | (Intercept) | P08 | 0.3970 | 0.6652 |
| patient | (Intercept) | P09 | −1.041 | 0.7179 |
| patient | (Intercept) | P10 | 1.291 | 0.6969 |
| patient | (Intercept) | P11 | −0.5103 | 0.6887 |
| patient | (Intercept) | P12 | 0.0062 | 0.6717 |
| patient | (Intercept) | P13 | −0.0354 | 0.6705 |
| patient | (Intercept) | P14 | 0.8701 | 0.6726 |
| patient | (Intercept) | P15 | 0.4030 | 0.6652 |
| patient | (Intercept) | P16 | −0.4935 | 0.6897 |
| patient | (Intercept) | P17 | −0.9958 | 0.7226 |
| patient | (Intercept) | P18 | −1.018 | 0.7202 |
| patient | (Intercept) | P19 | 0.3667 | 0.6653 |
| patient | (Intercept) | P20 | −0.1131 | 0.6687 |
| patient | (Intercept) | P21 | −0.5103 | 0.6887 |
| patient | (Intercept) | P22 | −0.5188 | 0.6882 |
| patient | (Intercept) | P23 | −0.4991 | 0.6893 |
| patient | (Intercept) | P24 | 0.4030 | 0.6652 |
| patient | (Intercept) | P25 | −0.9983 | 0.7223 |
| patient | (Intercept) | P26 | 0.8111 | 0.6746 |
| patient | (Intercept) | P27 | 0.4061 | 0.6651 |
| patient | (Intercept) | P28 | −0.0265 | 0.6707 |
| patient | (Intercept) | P29 | 0.4151 | 0.6651 |
| patient | (Intercept) | P30 | 0.3819 | 0.6652 |
| patient | (Intercept) | P31 | −0.5151 | 0.7930 |
| patient | (Intercept) | P32 | −0.5389 | 0.7883 |
| patient | (Intercept) | P33 | −0.5352 | 0.7891 |
| patient | (Intercept) | P34 | 0.5564 | 0.6992 |
| patient | (Intercept) | P35 | 1.487 | 0.6656 |
| patient | (Intercept) | P36 | 0.0420 | 0.7375 |
| patient | (Intercept) | P37 | 0.0206 | 0.7348 |
| patient | (Intercept) | P38 | 0.5291 | 0.6972 |
| patient | (Intercept) | P39 | 0.0420 | 0.7375 |
| patient | (Intercept) | P40 | 0.0562 | 0.7392 |
First 40 of 60 rows.
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0667 | .145 |
| Outliers (rows at the edge of their simulations) | 4 | .305 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- 5 of 300 rows were left out because a value was missing.
- Logistic GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); latent residual variance π²/3.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec 8d8bb8afc6ce0a43
# Dataset: s1_visits (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import mixed as mx # twin of lme4::glmer (Laplace, nAGQ = 1) — no Python library fits it
from codesplash.stats import regression as csreg
from codesplash.stats import dharma # simulated residuals, twin of codesplashr::cs_dharma_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_visits.parquet", columns=["adverse event", "visit", "treatment", "age", "patient"])
n_input = len(df)
df["adverse event"] = pd.Categorical(df["adverse event"], categories=["false", "true"]) # stored level order
df["treatment"] = pd.Categorical(df["treatment"], categories=["control", "drug"]) # stored level order
df["patient"] = pd.Categorical(df["patient"], categories=["P01", "P02", "P03", "P04", "P05", "P06", "P07", "P08", "P09", "P10", "P11", "P12", "P13", "P14", "P15", "P16", "P17", "P18", "P19", "P20", "P21", "P22", "P23", "P24", "P25", "P26", "P27", "P28", "P29", "P30", "P31", "P32", "P33", "P34", "P35", "P36", "P37", "P38", "P39", "P40", "P41", "P42", "P43", "P44", "P45", "P46", "P47", "P48", "P49", "P50", "P51", "P52", "P53", "P54", "P55", "P56", "P57", "P58", "P59", "P60"]) # stored level order
df = df.dropna(subset=["adverse event", "visit", "treatment", "age", "patient"]) # listwise deletion over the analysis columns
df["adverse event"] = df["adverse event"].cat.remove_unused_categories()
df["treatment"] = df["treatment"].cat.remove_unused_categories()
df["patient"] = df["patient"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["adverse event", "visit", "treatment", "age", "patient"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome = "adverse event"
trials = None
exposure = None
predictors = ["visit", "treatment", "age"]
group = "patient"
slopes = []
group2 = None
family = "binomial" # binomial (logit) | poisson (log)
nesting = "nested"
correlated = "correlated" == "correlated"
interactions = "none"
conf = 0.9
event = None
w = np.ones(len(df))
offset = np.zeros(len(df))
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
levels_y = [str(x) for x in df[outcome].cat.categories]
if family != "binomial" or len(levels_y) != 2:
raise ValueError(f"{outcome} is categorical: use the logistic model with exactly two levels (found {len(levels_y)}).")
event = levels_y[1] # default: the second stored level ("true" for yes/no)
y = (df[outcome].astype(str) == event).to_numpy(dtype=float)
else:
y = df[outcome].to_numpy(dtype=float)
if (y < 0).any() or (np.abs(y - np.round(y)) > 1e-9).any():
raise ValueError(f"{outcome} must hold whole non-negative numbers (counts or 0/1).")
if family == "binomial":
if trials:
w = df[trials].to_numpy(dtype=float)
if (w <= 0).any() or (y > w).any():
raise ValueError(f"{trials} must be positive and at least {outcome} on every row.")
y = y / w # proportion of successes with binomial weights = trials (lme4's cbind(succ, fail))
elif not np.all(np.isin(y, (0.0, 1.0))):
raise ValueError(f"{outcome} must be 0/1 for a logistic model (or give the number of Trials).")
if family == "poisson" and exposure:
if (df[exposure] <= 0).any():
raise ValueError(f"{exposure} must be positive (its log is the offset).")
offset = np.log(df[exposure].to_numpy(dtype=float))
re = mx.re_terms(df, group, slopes, group2, nesting, correlated)
# Degenerate input stops with a catalog error before the fit; R runs the same checks in the same order.
mx.check_re_terms(re, len(df), allow_n=True) # glmer's checks on the grouping factors
for pred in predictors:
if df[pred].nunique() < 2: # one value (or one level with data) is no variation
cs.cs_error("CS_E_CONSTANT", column=pred)
X = csreg.design_matrix(df, predictors, interactions)
terms_x = list(X.columns)
n, k = X.shape
# %% Fit (Laplace; covariance of β from the finite-difference Hessian, lme4's default)
model = mx.Glmm(y, X.to_numpy(), re, family, weights=w, offset=offset)
fit = model.fit()
b = fit.beta
se = np.sqrt(np.diag(fit.vcov))
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
values = {}
coefs = []
for j, t in enumerate(terms_x):
row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j])}
row.update({"ratio": float(np.exp(b[j])), "ratio_ci_low": float(np.exp(row["ci_low"])), "ratio_ci_high": float(np.exp(row["ci_high"]))})
coefs.append(row)
values.update({f"{key}[{t}]": row["estimate" if key == "coef" else key] for key in ("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
bb = b[idx]
chi2 = float(bb @ np.linalg.solve(fit.vcov[np.ix_(idx, idx)], bb))
pc = float(stats.chi2.sf(chi2, len(idx)))
effects.append({"term": name, "chi2": chi2, "df": len(idx), "p": pc})
values.update({f"chi2[{name}]": chi2, f"chi2_df[{name}]": float(len(idx)), f"chi2_p[{name}]": pc})
values.update({"focal_chi2": None, "focal_df": None, "focal_p": None})
if effects:
values.update({"focal_chi2": effects[0]["chi2"], "focal_df": float(effects[0]["df"]), "focal_p": effects[0]["p"]})
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
vc = mx.varcorr(re, fit.theta, 1.0)
for r in vc:
if r["var2"] is None:
values[f"var[{r['grp']}|{r['var1']}]"] = r["vcov"]
values[f"sd[{r['grp']}|{r['var1']}]"] = r["sdcor"]
else:
values[f"cor[{r['grp']}|{r['var1']}|{r['var2']}]"] = r["sdcor"]
eta_fixed = X.to_numpy() @ b
var_fixed = float(np.var(eta_fixed, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, 1.0)
if family == "binomial":
var_residual = np.pi**2 / 3 # logistic latent variance
else:
lam = np.exp(np.mean(eta_fixed) + var_random / 2) # lognormal approximation of the observation-level variance
var_residual = float(np.log1p(1 / lam))
total = var_fixed + var_random + var_residual
n_theta = len(fit.theta)
n_params = k + n_theta
values.update({"n": n, "k": k, "n_groups": re[0].nlev, "family": family, "log_lik": fit.log_lik, "deviance": fit.objective,
"aic": fit.objective + 2 * n_params, "bic": fit.objective + np.log(n) * n_params, "icc": var_random / (var_random + var_residual),
"r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total, "var_fixed": var_fixed,
"var_random": var_random, "var_residual": float(var_residual), "singular": fit.singular, "n_params": n_params, "n_theta": n_theta,
"max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
if group2:
values["n_groups2"] = re[-1].nlev
# %% Random effects vs none (likelihood ratio against the GLM)
if True:
beta_glm = model._glm_start()
mu_glm = model.linkinv(X.to_numpy() @ beta_glm + offset)
ll_glm = -0.5 * float(np.sum(model.m2ll(y, mu_glm, w)))
lrt = max(2 * (fit.log_lik - ll_glm), 0.0)
lrt_p = float(stats.chi2.sf(lrt, n_theta))
if n_theta == 1:
lrt_p /= 2 # boundary: 50:50 mixture of χ²(0) and χ²(1)
values.update({"re_lrt": lrt, "re_lrt_df": float(n_theta), "re_lrt_p": lrt_p})
# %% Assumptions
assumptions = [{"key": "singular", "label": "Non-singular fit", "status": "warn" if fit.singular else "pass",
"detail": "A variance component is estimated at (or near) zero: simplify the random effects." if fit.singular else "Every variance component is clearly above zero."}]
few = [t.group for t in re if t.nlev < 5]
assumptions.append({"key": "groups", "label": "Enough groups", "status": "warn" if few else "pass",
"detail": (f"Fewer than 5 levels for {', '.join(dict.fromkeys(few))}: its variance is estimated very imprecisely." if few else f"{re[0].nlev} levels of {group}.")})
if family == "poisson":
mu = fit.mu
disp = float(np.sum((y - mu) ** 2 / mu) / (n - k))
values["dispersion"] = disp
assumptions.append({"key": "overdispersion", "label": "No overdispersion", "status": "warn" if disp > 1.5 else "pass", "statistic": disp,
"detail": f"Pearson χ² / residual df = {disp:.2f}" + ("; consider an observation-level random effect or a negative binomial model." if disp > 1.5 else ".")})
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like = family == "poisson" or trials is not None # spread and zeros are checked for counts, not for 0/1 data
m_trials = w if (family == "binomial" and trials) else None
rng = dharma.Rng(dharma.SEED)
eta_pop = X.to_numpy() @ b + offset # fixed part: the simulations draw new random effects around it
sims = dharma.simulate(eta_pop, dharma.sim_terms(re, vc), family, m_trials, dharma.N_SIM, rng)
y_obs = np.round(y * w) if m_trials is not None else y # successes for successes-of-trials outcomes
fitted_resp = dharma.mean_response(eta_pop, family) * (w if m_trials is not None else 1.0) # population-level, as DHARMa
dh = dharma.residuals(y_obs, fitted_resp, sims, family, rng, zeros=counts_like)
values.update({"dharma_n_sim": dh["n_sim"], "dharma_ks": dh["ks"], "dharma_ks_p": dh["ks_p"], "dharma_outliers": dh["outliers"],
"dharma_outlier_p": dh["outlier_p"]})
uni_bad = dh["ks_p"] < 0.05
assumptions.append({"key": "uniformity", "label": "Simulated residuals look uniform", "status": "warn" if uni_bad else "pass",
"statistic": dh["ks"], "p": dh["ks_p"],
"detail": f"Kolmogorov–Smirnov D = {dh['ks']:.3f}, {cs.fmt_p(dh['ks_p'])} over {dh['n_sim']} simulations"
+ ("; the outcome's distribution doesn't match the model (check the residual plots)." if uni_bad else ".")})
if counts_like:
values.update({"dharma_disp_ratio": dh["disp_ratio"], "dharma_disp_p": dh["disp_p"], "dharma_zero_ratio": dh["zero_ratio"], "dharma_zero_p": dh["zero_p"]})
disp_bad = dh["disp_p"] < 0.05
over = dh["disp_ratio"] > 1
assumptions.append({"key": "dispersion", "label": "Residual spread matches the model (simulation)", "status": "warn" if disp_bad else "pass",
"statistic": dh["disp_ratio"], "p": dh["disp_p"],
"detail": f"Observed / simulated spread = {dh['disp_ratio']:.2f}, {cs.fmt_p(dh['disp_p'])}"
+ (("; overdispersion: consider an observation-level random effect or a negative binomial model." if over else "; underdispersion: standard errors are conservative.") if disp_bad else ".")})
zero_bad = dh["zero_p"] < 0.05
assumptions.append({"key": "zero_inflation", "label": "Number of zeros matches the model (simulation)", "status": "warn" if zero_bad else "pass",
"statistic": dh["zero_ratio"], "p": dh["zero_p"],
"detail": f"Observed / simulated zeros = {dh['zero_ratio']:.2f}, {cs.fmt_p(dh['zero_p'])}"
+ (("; more zeros than the model expects: consider a zero-inflated or hurdle model." if dh["zero_ratio"] > 1 else "; fewer zeros than the model expects.") if zero_bad else ".")})
out_bad = dh["outlier_p"] < 0.05
assumptions.append({"key": "outliers", "label": "No more outliers than expected (simulation)", "status": "warn" if out_bad else "pass",
"statistic": float(dh["outliers"]), "p": dh["outlier_p"],
"detail": f"{dh['outliers']} of {n} rows sit at the edge of their {dh['n_sim']} simulations (within 1/{dh['n_sim'] + 1} of either end; binomial test, {cs.fmt_p(dh['outlier_p'])})."})
if not fit.hessian_ok:
warnings.append("The finite-difference Hessian is not positive definite: standard errors use the RX approximation (conditional on the variance parameters), as lme4 falls back to.")
# %% Result
pct = f"{conf:.0%}"
rl = "Odds ratio" if family == "binomial" else "Rate ratio"
re_rows = []
off = 0
for ti, t in enumerate(re):
for j, eff in enumerate(t.effects):
for g, lv in enumerate(t.levels):
re_rows.append({"group": t.group, "effect": eff, "level": lv, "estimate": float(fit.b[off + g * t.k + j]),
"sd": float(np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)))})
off += t.nlev * t.k
vc_rows = [{"group": r["grp"], "effect": r["var1"] if r["var2"] is None else f"{r['var1']} ~ {r['var2']}",
"variance": r["vcov"] if r["var2"] is None else None, "sd": r["sdcor"] if r["var2"] is None else None,
"cor": r["sdcor"] if r["var2"] is not None else None} for r in vc]
slopes_tab = [c for c in coefs if c["term"] != "(Intercept)"]
tests_text = f" {effects[0]['term']}: Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}." if effects else ""
summary = (f"{'Logistic' if family == 'binomial' else 'Poisson'} mixed model of {outcome}" + (f" (event: {event})" if event else "")
+ f" (n = {n}, {re[0].nlev} levels of {group}).{tests_text} Latent-scale ICC = {values['icc']:.2f}.")
z = stats.norm.ppf(1 - (1 - conf) / 2)
cat_rows = re_rows[:1000]
charts = [cs.chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", {
"group": cs.col("Level", [r["level"] for r in cat_rows], kind="categorical"), "estimate": cs.col("Conditional mode", [r["estimate"] for r in cat_rows]),
"low": cs.col("low", [r["estimate"] - z * r["sd"] for r in cat_rows]), "high": cs.col("high", [r["estimate"] + z * r["sd"] for r in cat_rows]),
"term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")})]
if slopes_tab:
charts.append(cs.chart("ratios", "forest", f"{rl}s", {
"label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col(rl, [c["ratio"] for c in slopes_tab]),
"low": cs.col("low", [c["ratio_ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ratio_ci_high"] for c in slopes_tab])},
controls={"reference": 1, "log": True}))
tables = [{"key": "fixed", "title": "Fixed effects", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B (link scale)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "ratio", "label": rl, "type": "number"},
{"key": "ratio_ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ratio_ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": coefs, "note": f"{rl}s are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance."}]
if effects:
tables.append({"key": "effects", "title": "Joint Wald tests of each predictor", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "chi2", "label": "Wald χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": effects})
tables.append({"key": "random", "title": "Random effects (link scale)", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"},
{"key": "variance", "label": "Variance", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}, {"key": "cor", "label": "Correlation", "type": "number"}],
"rows": vc_rows})
tables.append({"key": "modes", "title": "Conditional modes of the random effects", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "estimate", "label": "Mode", "type": "number"}, {"key": "sd", "label": "Conditional SD", "type": "number"}], "rows": re_rows[:2000]})
dh_rows = [{"check": "Uniformity (Kolmogorov–Smirnov D)", "statistic": dh["ks"], "p": dh["ks_p"]}]
if counts_like:
dh_rows += [{"check": "Spread (observed / simulated)", "statistic": dh["disp_ratio"], "p": dh["disp_p"]},
{"check": "Zeros (observed / simulated)", "statistic": dh["zero_ratio"], "p": dh["zero_p"]}]
dh_rows.append({"check": "Outliers (rows at the edge of their simulations)", "statistic": float(dh["outliers"]), "p": dh["outlier_p"]})
tables.append({"key": "dharma", "title": "Simulated residual checks (DHARMa)", "columns": [
{"key": "check", "label": "Check", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": dh_rows, "note": f"{dh['n_sim']} simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed {dharma.SEED}. "
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."})
m_show = min(n, 5000) # evenly spaced rows for the residual charts
show = [(i * (n - 1)) // (m_show - 1) if m_show > 1 else 0 for i in range(m_show)]
res_show = [float(dh["residuals"][i]) for i in show]
charts.append(cs.chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", {"x": cs.col("Scaled residual", res_show)},
controls={"reference": "uniform"}))
rank_fit = dharma.rank01(fitted_resp)
charts.append(cs.chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", {
"x": cs.col("Population-level prediction (rank, 0–1)", [float(rank_fit[i]) for i in show]), "y": cs.col("Scaled residual", res_show)}, controls={"fit": "loess"}))
statistics = [{"key": "icc", "label": "ICC (latent scale)", "value": values["icc"]}, {"key": "r2_marginal", "label": "R² marginal", "value": values["r2_marginal"]},
{"key": "r2_conditional", "label": "R² conditional", "value": values["r2_conditional"]}, {"key": "aic", "label": "AIC", "value": values["aic"]}]
if "re_lrt_p" in values:
statistics.append({"key": "re_lrt_p", "label": "Random effects LR test p", "value": values["re_lrt_p"], "format": "p"})
cs.publish({
"method": "mixed.glmm",
"methodVersion": "1.1.0",
"title": "Generalized linear mixed model",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": (f"Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
"statistics": statistics,
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [("Logistic" if family == "binomial" else "Poisson") + " GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); "
+ ("latent residual variance π²/3." if family == "binomial" else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")],
"charts": charts,
"values": values,
})
These simulated data follow 60 patients over 295 visits, recording whether an adverse event occurred.
The test of visit gives (1) = 14.0, p < .001.
The odds ratios are subject-specific: they say how the odds change for one patient, as that patient's visit number or age changes. The random effects are tested too: p = .001.
An ICC with no residual
PredictA logistic model has no residual variance to divide by. So the ICC uses the variance of the logistic distribution on the latent scale, , which is 3.29.
Predict first
Patients have a random-effect variance of 0.908. What's the ICC on this latent scale?
Make your guess between 0 and 1 ICC, then reveal.
Reveal
Divide it by the total: the card gives 0.216. Be careful with it: this is a correlation on a hidden scale, not between the yes-or-no outcomes themselves.
One patient, or the whole population?
PredictPredict first
A mixed model says a drug multiplies a patient's odds by a certain ratio. Average over patients with high and low baseline risks, and compare the groups' overall event rates. How does this population-level odds ratio compare with the patient-level one?
Reveal
Closer to 1. Averaging S-shaped curves gives a flatter curve, so the population-level effect is smaller. Neither one is wrong: they answer different questions. The next lesson's GEE targets the population-level one.
Successes out of trials
ReadSometimes a row is already a count of events out of a number of chances: sick cattle out of a herd, at each of several periods. Use Outcome for the events and Trials for the size.
Wald χ²(3) = 24.95, p < .001
- ICC (latent scale)
- 0.1114
- R² marginal
- 0.0854
- R² conditional
- 0.1873
- AIC
- 194.05
- Random effects LR test p
- < .001
Plots
View data
| Conditional mode | Level | high | low | Term |
|---|---|---|---|---|
| 0.5900 | 1 | 1.273 | −0.0926 | herd: (Intercept) |
| −0.2989 | 2 | 0.4176 | −1.015 | herd: (Intercept) |
| 0.4063 | 3 | 0.9890 | −0.1765 | herd: (Intercept) |
| 0.0393 | 4 | 0.8554 | −0.7768 | herd: (Intercept) |
| −0.1900 | 5 | 0.4968 | −0.8768 | herd: (Intercept) |
| −0.4003 | 6 | 0.3444 | −1.145 | herd: (Intercept) |
| 0.8894 | 7 | 1.529 | 0.2495 | herd: (Intercept) |
| 0.5994 | 8 | 1.229 | −0.0300 | herd: (Intercept) |
| −0.2377 | 9 | 0.6667 | −1.142 | herd: (Intercept) |
| −0.5409 | 10 | 0.1856 | −1.267 | herd: (Intercept) |
| −0.0846 | 11 | 0.5212 | −0.6905 | herd: (Intercept) |
| −0.0648 | 12 | 0.7998 | −0.9294 | herd: (Intercept) |
| −0.6899 | 13 | 0.0643 | −1.444 | herd: (Intercept) |
| 0.9707 | 14 | 1.667 | 0.2741 | herd: (Intercept) |
| −0.5305 | 15 | 0.2490 | −1.310 | herd: (Intercept) |
View data
| Odds ratio | high | Term | low |
|---|---|---|---|
| 0.3707 | 0.6762 | period: 2 | 0.2032 |
| 0.3235 | 0.6136 | period: 3 | 0.1705 |
| 0.2059 | 0.4759 | period: 4 | 0.0891 |
View data
| Scaled residual |
|---|
| 0.4850 |
| 0.9224 |
| 0.9941 |
| 0.2038 |
| 0.3964 |
| 0.5158 |
| 0.2896 |
| 0.8533 |
| 0.6665 |
| 0.1088 |
| 0.7598 |
| 0.6367 |
| 0.0247 |
| 0.9210 |
| 0.6597 |
| 0.6573 |
| 0.0534 |
| 0.1726 |
| 0.8190 |
| 0.4794 |
| 0.2378 |
| 0.1197 |
| 0.6866 |
| 0.9637 |
| 0.4250 |
| 0.9699 |
| 0.4722 |
| 0.8975 |
| 0.5850 |
| 0.1823 |
| 0.0799 |
| 0.4311 |
| 0.0675 |
| 0.3464 |
| 0.2486 |
| 0.7444 |
| 0.0144 |
| 0.8372 |
| 0.7718 |
| 0.6027 |
| 0.6012 |
| 0.6702 |
| 0.5828 |
| 0.2412 |
| 0.0362 |
| 0.4735 |
| 0.2437 |
| 0.2522 |
| 0.9700 |
| 0.0760 |
| 0.0901 |
| 0.0516 |
| 0.1323 |
| 0.3427 |
| 0.6209 |
| 0.1603 |
View data
| Population-level prediction (rank, 0–1) | Scaled residual |
|---|---|
| 0.8036 | 0.4850 |
| 0.3929 | 0.9224 |
| 0.2500 | 0.9941 |
| 0.1071 | 0.2038 |
| 0.9464 | 0.3964 |
| 0.6071 | 0.5158 |
| 0.6250 | 0.2896 |
| 0.9464 | 0.8533 |
| 0.5536 | 0.6665 |
| 0.4821 | 0.1088 |
| 0.3661 | 0.7598 |
| 0.7232 | 0.6367 |
| 0.3304 | 0.0247 |
| 0.2500 | 0.9210 |
| 0.1518 | 0.6597 |
| 0.8571 | 0.6573 |
| 0.7679 | 0.0534 |
| 0.6607 | 0.1726 |
| 0.0536 | 0.8190 |
| 0.8393 | 0.4794 |
| 0.5893 | 0.2378 |
| 0.5268 | 0.1197 |
| 0.3661 | 0.6866 |
| 0.8214 | 0.9637 |
| 0.3304 | 0.4250 |
| 0.2500 | 0.9699 |
| 0.1071 | 0.4722 |
| 1 | 0.8975 |
| 0.6786 | 0.5850 |
| 0.1964 | 0.1823 |
| 0.2143 | 0.0799 |
| 0.1518 | 0.4311 |
| 0.9464 | 0.0675 |
| 0.6964 | 0.3464 |
| 0.5268 | 0.2486 |
| 0.4196 | 0.7444 |
| 0.9821 | 0.0144 |
| 0.7857 | 0.8372 |
| 0.6429 | 0.7718 |
| 0.4196 | 0.6027 |
| 0.7232 | 0.6012 |
| 0.2857 | 0.6702 |
| 0.1786 | 0.5828 |
| 0.1071 | 0.2412 |
| 0.9107 | 0.0362 |
| 0.7500 | 0.4735 |
| 0.5714 | 0.2437 |
| 0.4643 | 0.2522 |
| 0.8839 | 0.9700 |
| 0.0357 | 0.0760 |
| 0.0714 | 0.0901 |
| 0.0179 | 0.0516 |
| 0.8839 | 0.1323 |
| 0.5000 | 0.3427 |
| 0.4464 | 0.6209 |
| 0.3036 | 0.1603 |
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 15 levels of herd.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.123, p = .339 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 1.39, p = .288.
- Number of zeros matches the model (simulation) — Observed / simulated zeros = 1.14, p = .504.
- No more outliers than expected (simulation) — 0 of 56 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = 1.000).
Fixed effects
| Term | B (link scale) | SE | z | p | Odds ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.399 | 0.2325 | −6.016 | < .001 | 0.2470 | 0.1566 | 0.3895 |
| period: 2 | −0.9923 | 0.3066 | −3.236 | .001 | 0.3707 | 0.2032 | 0.6762 |
| period: 3 | −1.129 | 0.3266 | −3.455 | < .001 | 0.3235 | 0.1705 | 0.6136 |
| period: 4 | −1.580 | 0.4274 | −3.697 | < .001 | 0.2059 | 0.0891 | 0.4759 |
Odds ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| period | 24.949 | 3 | < .001 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| herd | (Intercept) | 0.4125 | 0.6423 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| herd | (Intercept) | 1 | 0.5900 | 0.3483 |
| herd | (Intercept) | 2 | −0.2989 | 0.3656 |
| herd | (Intercept) | 3 | 0.4063 | 0.2973 |
| herd | (Intercept) | 4 | 0.0393 | 0.4164 |
| herd | (Intercept) | 5 | −0.1900 | 0.3504 |
| herd | (Intercept) | 6 | −0.4003 | 0.3800 |
| herd | (Intercept) | 7 | 0.8894 | 0.3265 |
| herd | (Intercept) | 8 | 0.5994 | 0.3211 |
| herd | (Intercept) | 9 | −0.2377 | 0.4614 |
| herd | (Intercept) | 10 | −0.5409 | 0.3707 |
| herd | (Intercept) | 11 | −0.0846 | 0.3091 |
| herd | (Intercept) | 12 | −0.0648 | 0.4411 |
| herd | (Intercept) | 13 | −0.6899 | 0.3848 |
| herd | (Intercept) | 14 | 0.9707 | 0.3554 |
| herd | (Intercept) | 15 | −0.5305 | 0.3977 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.1228 | .339 |
| Spread (observed / simulated) | 1.388 | .288 |
| Zeros (observed / simulated) | 1.140 | .504 |
| Outliers (rows at the edge of their simulations) | 0 | 1.000 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Logistic GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); latent residual variance π²/3.
The exact R script · R R version 4.5.1 (2025-06-13)
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec db67e9043ca420ed
# Dataset: s1_cbpp (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(lme4))
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_cbpp.parquet", col_select = c("incidence", "size", "period", "herd")))
n_input <- nrow(df)
df[["period"]] <- factor(df[["period"]], levels = c("1", "2", "3", "4")) # stored level order
df[["herd"]] <- factor(df[["herd"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15")) # stored level order
df <- df[stats::complete.cases(df[c("incidence", "size", "period", "herd")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("incidence", "size", "period", "herd")) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome <- "incidence"
trials <- "size"
exposure <- NULL
predictors <- c("period")
group <- "herd"
slopes <- c()
group2 <- NULL
family <- "binomial" # binomial (logit) | poisson (log)
nesting <- "nested"
correlated <- "correlated" == "correlated"
interactions <- "none"
conf <- 0.95
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
event <- NULL
lhs <- NULL
w <- rep(1, nrow(df))
if (is.factor(df[[outcome]])) {
if (family != "binomial" || nlevels(df[[outcome]]) != 2) stop(sprintf("%s is categorical: use the logistic model with exactly two levels (found %d).", outcome, nlevels(df[[outcome]])))
event <- levels(df[[outcome]])[2] # default: the second stored level ("true" for yes/no)
df$.cs_y <- as.numeric(as.character(df[[outcome]]) == event)
y <- df$.cs_y
lhs <- ".cs_y"
} else {
y <- as.numeric(df[[outcome]])
if (any(y < 0) || any(abs(y - round(y)) > 1e-9)) stop(sprintf("%s must hold whole non-negative numbers (counts or 0/1).", outcome))
if (family == "binomial" && !is.null(trials)) {
w <- df[[trials]]
if (any(w <= 0) || any(y > w)) stop(sprintf("%s must be positive and at least %s on every row.", trials, outcome))
df$.cs_succ <- y
df$.cs_fail <- w - y
lhs <- "cbind(.cs_succ, .cs_fail)" # successes out of trials
y <- y / w
} else if (family == "binomial" && !all(y %in% c(0, 1))) {
stop(sprintf("%s must be 0/1 for a logistic model (or give the number of Trials).", outcome))
}
}
offset <- rep(0, nrow(df))
if (family == "poisson" && !is.null(exposure)) {
if (any(df[[exposure]] <= 0)) stop(sprintf("%s must be positive (its log is the offset).", exposure))
offset <- log(df[[exposure]])
}
df$.cs_offset <- offset
# Degenerate input stops with a catalog error before the fit; Python runs the same checks in the same order.
cs_mixed_check_re(df, group, slopes, group2, nesting, correlated, allow_n = TRUE) # glmer's checks on the grouping factors
for (pred in predictors) {
if (length(unique(df[[pred]])) < 2) cs_error("CS_E_CONSTANT", column = pred) # one value (or one level with data) is no variation
}
fml <- cs_mixed_formula(outcome, predictors, interactions, group, slopes, group2, nesting, correlated, lhs = lhs)
fam <- if (family == "binomial") binomial() else poisson()
# Tight tolerances (default: bobyqa then Nelder–Mead, tolPwrss = 1e-7) so both engines reach the same optimum.
ctrl <- glmerControl(optimizer = c("bobyqa", "bobyqa"), optCtrl = list(rhoend = 1e-12, maxfun = 1e6), tolPwrss = 1e-12)
# %% Fit (Laplace, nAGQ = 1)
fit <- glmer(fml, data = df, family = fam, offset = .cs_offset, nAGQ = 1, control = ctrl)
X <- getME(fit, "X")
terms_x <- cs_design_labels(df, predictors, interactions)
if (ncol(X) < length(terms_x)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
b <- unname(fixef(fit))
V <- as.matrix(vcov(fit)) # lme4 default: from the finite-difference Hessian
se <- sqrt(diag(V))
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
values <- list()
coefs <- list()
for (j in seq_len(k)) {
t <- terms_x[j]
row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j])
row <- c(row, list(ratio = exp(b[j]), ratio_ci_low = exp(row$ci_low), ratio_ci_high = exp(row$ci_high)))
coefs[[j]] <- row
for (key in c("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")) values[[sprintf("%s[%s]", key, t)]] <- if (key == "coef") row$estimate else row[[key]]
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
idx <- blocks[[name]]
chi2 <- as.numeric(t(b[idx]) %*% solve(V[idx, idx, drop = FALSE], b[idx]))
pc <- pchisq(chi2, length(idx), lower.tail = FALSE)
effects[[length(effects) + 1]] <- list(term = name, chi2 = chi2, df = length(idx), p = pc)
values[[sprintf("chi2[%s]", name)]] <- chi2; values[[sprintf("chi2_df[%s]", name)]] <- as.numeric(length(idx)); values[[sprintf("chi2_p[%s]", name)]] <- pc
}
values$focal_chi2 <- NA; values$focal_df <- NA; values$focal_p <- NA # no fixed predictor
if (length(effects)) {
values$focal_chi2 <- effects[[1]]$chi2; values$focal_df <- as.numeric(effects[[1]]$df); values$focal_p <- effects[[1]]$p
}
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
valid <- c(group, group2, if (!is.null(group2)) paste0(group, ":", group2))
vc <- cs_mixed_varcorr(fit, valid)
for (i in seq_len(nrow(vc))) {
if (is.na(vc$effect2[i])) {
values[[sprintf("var[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$vcov[i]
values[[sprintf("sd[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$sdcor[i]
} else {
values[[sprintf("cor[%s|%s|%s]", vc$group[i], vc$effect1[i], vc$effect2[i])]] <- vc$sdcor[i]
}
}
eta_fixed <- as.vector(X %*% b)
var_fixed <- if (n > 1) var(eta_fixed) else 0
var_random <- cs_mixed_random_variance(fit, df)
var_residual <- if (family == "binomial") pi^2 / 3 else log1p(1 / exp(mean(eta_fixed) + var_random / 2))
total <- var_fixed + var_random + var_residual
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta
ll <- as.numeric(logLik(fit))
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, family = family, log_lik = ll, deviance = -2 * ll, aic = -2 * ll + 2 * n_params,
bic = -2 * ll + log(n) * n_params, icc = var_random / (var_random + var_residual), r2_marginal = var_fixed / total,
r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random, var_residual = var_residual,
singular = isSingular(fit, tol = 1e-4), n_params = n_params, n_theta = n_theta,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (!is.null(group2)) {
values$n_groups2 <- if (nesting == "nested") nlevels(droplevels(interaction(df[[group]], df[[group2]], drop = TRUE))) else nlevels(droplevels(df[[group2]]))
}
# %% Random effects vs none (likelihood ratio against the GLM)
if (TRUE) {
fixed_rhs <- if (length(predictors)) as.character(cs_model_formula(outcome, predictors, interactions))[3] else "1"
g <- glm(stats::as.formula(paste(if (is.null(lhs)) paste0("`", outcome, "`") else lhs, "~", fixed_rhs)), family = fam, data = df, offset = .cs_offset,
control = glm.control(epsilon = 1e-14, maxit = 100))
lrt <- max(2 * (ll - as.numeric(logLik(g))), 0)
lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
if (n_theta == 1) lrt_p <- lrt_p / 2 # boundary: 50:50 mixture of chi2(0) and chi2(1)
values$re_lrt <- lrt; values$re_lrt_df <- as.numeric(n_theta); values$re_lrt_p <- lrt_p
}
# %% Assumptions
singular <- isTRUE(values$singular)
assumptions <- list(list(key = "singular", label = "Non-singular fit", status = if (singular) "warn" else "pass",
detail = if (singular) "A variance component is estimated at (or near) zero: simplify the random effects." else "Every variance component is clearly above zero."))
nlev <- c(setNames(n_groups, group), if (!is.null(group2)) setNames(values$n_groups2, if (nesting == "nested") paste0(group, ":", group2) else group2))
few <- names(nlev)[nlev < 5]
assumptions[[2]] <- list(key = "groups", label = "Enough groups", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 5 levels for %s: its variance is estimated very imprecisely.", paste(few, collapse = ", ")) else sprintf("%d levels of %s.", n_groups, group))
if (family == "poisson") {
mu <- unname(fitted(fit))
disp <- sum((y - mu)^2 / mu) / (n - k)
values$dispersion <- disp
assumptions[[3]] <- list(key = "overdispersion", label = "No overdispersion", status = if (disp > 1.5) "warn" else "pass", statistic = disp,
detail = paste0(sprintf("Pearson χ² / residual df = %.2f", disp), if (disp > 1.5) "; consider an observation-level random effect or a negative binomial model." else "."))
}
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like <- family == "poisson" || !is.null(trials) # spread and zeros are checked for counts, not for 0/1 data
m_trials <- if (family == "binomial" && !is.null(trials)) w else NULL
rng <- cs_rng(1)
dh_terms <- cs_dharma_terms(df, group, slopes, group2, nesting, correlated, vc)
eta_pop <- as.vector(X %*% b) + offset # fixed part: the simulations draw new random effects around it
sims <- cs_dharma_simulate(eta_pop, dh_terms, family, m_trials, 250, rng)
y_obs <- if (!is.null(m_trials)) round(y * w) else y # successes for successes-of-trials outcomes
fitted_resp <- cs_dharma_mean(eta_pop, family) * (if (!is.null(m_trials)) w else 1) # population-level, as DHARMa
dh <- cs_dharma_residuals(y_obs, fitted_resp, sims, family, rng, zeros = counts_like)
values$dharma_n_sim <- dh$n_sim; values$dharma_ks <- dh$ks; values$dharma_ks_p <- dh$ks_p
values$dharma_outliers <- dh$outliers; values$dharma_outlier_p <- dh$outlier_p
uni_bad <- dh$ks_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "uniformity", label = "Simulated residuals look uniform", status = if (uni_bad) "warn" else "pass",
statistic = dh$ks, p = dh$ks_p,
detail = paste0(sprintf("Kolmogorov–Smirnov D = %.3f, %s over %d simulations", dh$ks, cs_fmt_p(dh$ks_p), as.integer(dh$n_sim)),
if (uni_bad) "; the outcome's distribution doesn't match the model (check the residual plots)." else "."))
if (counts_like) {
values$dharma_disp_ratio <- dh$disp_ratio; values$dharma_disp_p <- dh$disp_p
values$dharma_zero_ratio <- dh$zero_ratio; values$dharma_zero_p <- dh$zero_p
disp_bad <- dh$disp_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "dispersion", label = "Residual spread matches the model (simulation)", status = if (disp_bad) "warn" else "pass",
statistic = dh$disp_ratio, p = dh$disp_p,
detail = paste0(sprintf("Observed / simulated spread = %.2f, %s", dh$disp_ratio, cs_fmt_p(dh$disp_p)),
if (!disp_bad) "." else if (dh$disp_ratio > 1) "; overdispersion: consider an observation-level random effect or a negative binomial model." else "; underdispersion: standard errors are conservative."))
zero_bad <- dh$zero_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "zero_inflation", label = "Number of zeros matches the model (simulation)", status = if (zero_bad) "warn" else "pass",
statistic = dh$zero_ratio, p = dh$zero_p,
detail = paste0(sprintf("Observed / simulated zeros = %.2f, %s", dh$zero_ratio, cs_fmt_p(dh$zero_p)),
if (!zero_bad) "." else if (dh$zero_ratio > 1) "; more zeros than the model expects: consider a zero-inflated or hurdle model." else "; fewer zeros than the model expects."))
}
out_bad <- dh$outlier_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "outliers", label = "No more outliers than expected (simulation)", status = if (out_bad) "warn" else "pass",
statistic = as.numeric(dh$outliers), p = dh$outlier_p,
detail = sprintf("%d of %d rows sit at the edge of their %d simulations (within 1/%d of either end; binomial test, %s).", as.integer(dh$outliers), as.integer(n), as.integer(dh$n_sim), as.integer(dh$n_sim) + 1L, cs_fmt_p(dh$outlier_p)))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
rl <- if (family == "binomial") "Odds ratio" else "Rate ratio"
re_tab <- cs_mixed_ranef(fit, valid)
vc_rows <- lapply(seq_len(nrow(vc)), function(i) {
if (is.na(vc$effect2[i])) list(group = vc$group[i], effect = vc$effect1[i], variance = vc$vcov[i], sd = vc$sdcor[i], cor = NULL)
else list(group = vc$group[i], effect = paste(vc$effect1[i], "~", vc$effect2[i]), variance = NULL, sd = NULL, cor = vc$sdcor[i])
})
slopes_tab <- Filter(function(cf) cf$term != "(Intercept)", coefs)
tests_text <- if (length(effects)) sprintf(" %s: Wald χ²(%d) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("%s mixed model of %s%s (n = %d, %d levels of %s).%s Latent-scale ICC = %.2f.", if (family == "binomial") "Logistic" else "Poisson",
outcome, if (!is.null(event)) sprintf(" (event: %s)", event) else "", n, n_groups, group, tests_text, values$icc)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(cs_chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", list(
group = cs_col("Level", cat_tab$level, kind = "categorical"), estimate = cs_col("Conditional mode", cat_tab$estimate),
low = cs_col("low", cat_tab$estimate - z * cat_tab$sd), high = cs_col("high", cat_tab$estimate + z * cat_tab$sd),
term = cs_col("Term", paste0(cat_tab$group, ": ", cat_tab$effect), kind = "categorical"))))
if (length(slopes_tab)) {
charts[[2]] <- cs_chart("ratios", "forest", paste0(rl, "s"), list(
label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col(rl, vapply(slopes_tab, `[[`, 0, "ratio")),
low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ratio_ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ratio_ci_high"))),
controls = list(reference = 1, log = TRUE))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B (link scale)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "ratio", label = rl, type = "number"),
list(key = "ratio_ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ratio_ci_high", label = paste(pct, "CI high"), type = "number")),
rows = coefs, note = sprintf("%ss are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.", rl)))
if (length(effects)) {
tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint Wald tests of each predictor", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "chi2", label = "Wald χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = effects)
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects (link scale)", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"),
list(key = "variance", label = "Variance", type = "number"), list(key = "sd", label = "SD", type = "number"), list(key = "cor", label = "Correlation", type = "number")),
rows = vc_rows)
mode_rows <- lapply(seq_len(min(nrow(re_tab), 2000)), function(i) as.list(re_tab[i, ]))
tables[[length(tables) + 1]] <- list(key = "modes", title = "Conditional modes of the random effects", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "estimate", label = "Mode", type = "number"), list(key = "sd", label = "Conditional SD", type = "number")), rows = mode_rows)
dh_rows <- list(list(check = "Uniformity (Kolmogorov–Smirnov D)", statistic = dh$ks, p = dh$ks_p))
if (counts_like) {
dh_rows <- c(dh_rows, list(list(check = "Spread (observed / simulated)", statistic = dh$disp_ratio, p = dh$disp_p),
list(check = "Zeros (observed / simulated)", statistic = dh$zero_ratio, p = dh$zero_p)))
}
dh_rows[[length(dh_rows) + 1]] <- list(check = "Outliers (rows at the edge of their simulations)", statistic = as.numeric(dh$outliers), p = dh$outlier_p)
tables[[length(tables) + 1]] <- list(key = "dharma", title = "Simulated residual checks (DHARMa)", columns = list(
list(key = "check", label = "Check", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = dh_rows, note = paste0(sprintf("%d simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. ", as.integer(dh$n_sim)),
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."))
m_show <- min(n, 5000) # evenly spaced rows for the residual charts
show <- if (m_show > 1) ((seq_len(m_show) - 1) * (n - 1)) %/% (m_show - 1) + 1 else 1
res_show <- dh$residuals[show]
charts[[length(charts) + 1]] <- cs_chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", list(x = cs_col("Scaled residual", res_show)),
controls = list(reference = "uniform"))
rank_fit <- cs_dharma_rank01(fitted_resp)
charts[[length(charts) + 1]] <- cs_chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", list(
x = cs_col("Population-level prediction (rank, 0–1)", rank_fit[show]), y = cs_col("Scaled residual", res_show)), controls = list(fit = "loess"))
statistics <- list(list(key = "icc", label = "ICC (latent scale)", value = values$icc), list(key = "r2_marginal", label = "R² marginal", value = values$r2_marginal),
list(key = "r2_conditional", label = "R² conditional", value = values$r2_conditional), list(key = "aic", label = "AIC", value = values$aic))
if (!is.null(values$re_lrt_p)) statistics[[length(statistics) + 1]] <- list(key = "re_lrt_p", label = "Random effects LR test p", value = values$re_lrt_p, format = "p")
cs_publish(list(
method = "mixed.glmm",
methodVersion = "1.1.0",
title = "Generalized linear mixed model",
engine = cs_engine_info("lme4", "nanoparquet"),
n = n,
summary = summary,
apa = if (length(effects)) sprintf("Wald χ²(%d) = %.2f, %s", as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else "",
statistics = statistics,
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (family == "binomial") "Logistic" else "Poisson", " GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); ",
if (family == "binomial") "latent residual variance π²/3." else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")),
charts = charts,
values = values
))
Wald χ²(3) = 24.95, p < .001
- ICC (latent scale)
- 0.1114
- R² marginal
- 0.0854
- R² conditional
- 0.1873
- AIC
- 194.05
- Random effects LR test p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 15 levels of herd.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.123, p = .339 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 1.39, p = .288.
- Number of zeros matches the model (simulation) — Observed / simulated zeros = 1.14, p = .504.
- No more outliers than expected (simulation) — 0 of 56 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = 1.000).
Fixed effects
| Term | B (link scale) | SE | z | p | Odds ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.399 | 0.2325 | −6.016 | < .001 | 0.2470 | 0.1566 | 0.3895 |
| period: 2 | −0.9923 | 0.3066 | −3.236 | .001 | 0.3707 | 0.2032 | 0.6762 |
| period: 3 | −1.129 | 0.3266 | −3.455 | < .001 | 0.3235 | 0.1705 | 0.6136 |
| period: 4 | −1.580 | 0.4274 | −3.697 | < .001 | 0.2059 | 0.0891 | 0.4759 |
Odds ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| period | 24.949 | 3 | < .001 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| herd | (Intercept) | 0.4125 | 0.6423 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| herd | (Intercept) | 1 | 0.5900 | 0.3483 |
| herd | (Intercept) | 2 | −0.2989 | 0.3656 |
| herd | (Intercept) | 3 | 0.4063 | 0.2973 |
| herd | (Intercept) | 4 | 0.0393 | 0.4164 |
| herd | (Intercept) | 5 | −0.1900 | 0.3504 |
| herd | (Intercept) | 6 | −0.4003 | 0.3800 |
| herd | (Intercept) | 7 | 0.8894 | 0.3265 |
| herd | (Intercept) | 8 | 0.5994 | 0.3211 |
| herd | (Intercept) | 9 | −0.2377 | 0.4614 |
| herd | (Intercept) | 10 | −0.5409 | 0.3707 |
| herd | (Intercept) | 11 | −0.0846 | 0.3091 |
| herd | (Intercept) | 12 | −0.0648 | 0.4411 |
| herd | (Intercept) | 13 | −0.6899 | 0.3848 |
| herd | (Intercept) | 14 | 0.9707 | 0.3554 |
| herd | (Intercept) | 15 | −0.5305 | 0.3977 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.1228 | .339 |
| Spread (observed / simulated) | 1.388 | .288 |
| Zeros (observed / simulated) | 1.140 | .504 |
| Outliers (rows at the edge of their simulations) | 0 | 1.000 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Logistic GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); latent residual variance π²/3.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec db67e9043ca420ed
# Dataset: s1_cbpp (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import mixed as mx # twin of lme4::glmer (Laplace, nAGQ = 1) — no Python library fits it
from codesplash.stats import regression as csreg
from codesplash.stats import dharma # simulated residuals, twin of codesplashr::cs_dharma_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_cbpp.parquet", columns=["incidence", "size", "period", "herd"])
n_input = len(df)
df["period"] = pd.Categorical(df["period"], categories=["1", "2", "3", "4"]) # stored level order
df["herd"] = pd.Categorical(df["herd"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]) # stored level order
df = df.dropna(subset=["incidence", "size", "period", "herd"]) # listwise deletion over the analysis columns
df["period"] = df["period"].cat.remove_unused_categories()
df["herd"] = df["herd"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["incidence", "size", "period", "herd"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome = "incidence"
trials = "size"
exposure = None
predictors = ["period"]
group = "herd"
slopes = []
group2 = None
family = "binomial" # binomial (logit) | poisson (log)
nesting = "nested"
correlated = "correlated" == "correlated"
interactions = "none"
conf = 0.95
event = None
w = np.ones(len(df))
offset = np.zeros(len(df))
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
levels_y = [str(x) for x in df[outcome].cat.categories]
if family != "binomial" or len(levels_y) != 2:
raise ValueError(f"{outcome} is categorical: use the logistic model with exactly two levels (found {len(levels_y)}).")
event = levels_y[1] # default: the second stored level ("true" for yes/no)
y = (df[outcome].astype(str) == event).to_numpy(dtype=float)
else:
y = df[outcome].to_numpy(dtype=float)
if (y < 0).any() or (np.abs(y - np.round(y)) > 1e-9).any():
raise ValueError(f"{outcome} must hold whole non-negative numbers (counts or 0/1).")
if family == "binomial":
if trials:
w = df[trials].to_numpy(dtype=float)
if (w <= 0).any() or (y > w).any():
raise ValueError(f"{trials} must be positive and at least {outcome} on every row.")
y = y / w # proportion of successes with binomial weights = trials (lme4's cbind(succ, fail))
elif not np.all(np.isin(y, (0.0, 1.0))):
raise ValueError(f"{outcome} must be 0/1 for a logistic model (or give the number of Trials).")
if family == "poisson" and exposure:
if (df[exposure] <= 0).any():
raise ValueError(f"{exposure} must be positive (its log is the offset).")
offset = np.log(df[exposure].to_numpy(dtype=float))
re = mx.re_terms(df, group, slopes, group2, nesting, correlated)
# Degenerate input stops with a catalog error before the fit; R runs the same checks in the same order.
mx.check_re_terms(re, len(df), allow_n=True) # glmer's checks on the grouping factors
for pred in predictors:
if df[pred].nunique() < 2: # one value (or one level with data) is no variation
cs.cs_error("CS_E_CONSTANT", column=pred)
X = csreg.design_matrix(df, predictors, interactions)
terms_x = list(X.columns)
n, k = X.shape
# %% Fit (Laplace; covariance of β from the finite-difference Hessian, lme4's default)
model = mx.Glmm(y, X.to_numpy(), re, family, weights=w, offset=offset)
fit = model.fit()
b = fit.beta
se = np.sqrt(np.diag(fit.vcov))
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
values = {}
coefs = []
for j, t in enumerate(terms_x):
row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j])}
row.update({"ratio": float(np.exp(b[j])), "ratio_ci_low": float(np.exp(row["ci_low"])), "ratio_ci_high": float(np.exp(row["ci_high"]))})
coefs.append(row)
values.update({f"{key}[{t}]": row["estimate" if key == "coef" else key] for key in ("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
bb = b[idx]
chi2 = float(bb @ np.linalg.solve(fit.vcov[np.ix_(idx, idx)], bb))
pc = float(stats.chi2.sf(chi2, len(idx)))
effects.append({"term": name, "chi2": chi2, "df": len(idx), "p": pc})
values.update({f"chi2[{name}]": chi2, f"chi2_df[{name}]": float(len(idx)), f"chi2_p[{name}]": pc})
values.update({"focal_chi2": None, "focal_df": None, "focal_p": None})
if effects:
values.update({"focal_chi2": effects[0]["chi2"], "focal_df": float(effects[0]["df"]), "focal_p": effects[0]["p"]})
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
vc = mx.varcorr(re, fit.theta, 1.0)
for r in vc:
if r["var2"] is None:
values[f"var[{r['grp']}|{r['var1']}]"] = r["vcov"]
values[f"sd[{r['grp']}|{r['var1']}]"] = r["sdcor"]
else:
values[f"cor[{r['grp']}|{r['var1']}|{r['var2']}]"] = r["sdcor"]
eta_fixed = X.to_numpy() @ b
var_fixed = float(np.var(eta_fixed, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, 1.0)
if family == "binomial":
var_residual = np.pi**2 / 3 # logistic latent variance
else:
lam = np.exp(np.mean(eta_fixed) + var_random / 2) # lognormal approximation of the observation-level variance
var_residual = float(np.log1p(1 / lam))
total = var_fixed + var_random + var_residual
n_theta = len(fit.theta)
n_params = k + n_theta
values.update({"n": n, "k": k, "n_groups": re[0].nlev, "family": family, "log_lik": fit.log_lik, "deviance": fit.objective,
"aic": fit.objective + 2 * n_params, "bic": fit.objective + np.log(n) * n_params, "icc": var_random / (var_random + var_residual),
"r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total, "var_fixed": var_fixed,
"var_random": var_random, "var_residual": float(var_residual), "singular": fit.singular, "n_params": n_params, "n_theta": n_theta,
"max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
if group2:
values["n_groups2"] = re[-1].nlev
# %% Random effects vs none (likelihood ratio against the GLM)
if True:
beta_glm = model._glm_start()
mu_glm = model.linkinv(X.to_numpy() @ beta_glm + offset)
ll_glm = -0.5 * float(np.sum(model.m2ll(y, mu_glm, w)))
lrt = max(2 * (fit.log_lik - ll_glm), 0.0)
lrt_p = float(stats.chi2.sf(lrt, n_theta))
if n_theta == 1:
lrt_p /= 2 # boundary: 50:50 mixture of χ²(0) and χ²(1)
values.update({"re_lrt": lrt, "re_lrt_df": float(n_theta), "re_lrt_p": lrt_p})
# %% Assumptions
assumptions = [{"key": "singular", "label": "Non-singular fit", "status": "warn" if fit.singular else "pass",
"detail": "A variance component is estimated at (or near) zero: simplify the random effects." if fit.singular else "Every variance component is clearly above zero."}]
few = [t.group for t in re if t.nlev < 5]
assumptions.append({"key": "groups", "label": "Enough groups", "status": "warn" if few else "pass",
"detail": (f"Fewer than 5 levels for {', '.join(dict.fromkeys(few))}: its variance is estimated very imprecisely." if few else f"{re[0].nlev} levels of {group}.")})
if family == "poisson":
mu = fit.mu
disp = float(np.sum((y - mu) ** 2 / mu) / (n - k))
values["dispersion"] = disp
assumptions.append({"key": "overdispersion", "label": "No overdispersion", "status": "warn" if disp > 1.5 else "pass", "statistic": disp,
"detail": f"Pearson χ² / residual df = {disp:.2f}" + ("; consider an observation-level random effect or a negative binomial model." if disp > 1.5 else ".")})
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like = family == "poisson" or trials is not None # spread and zeros are checked for counts, not for 0/1 data
m_trials = w if (family == "binomial" and trials) else None
rng = dharma.Rng(dharma.SEED)
eta_pop = X.to_numpy() @ b + offset # fixed part: the simulations draw new random effects around it
sims = dharma.simulate(eta_pop, dharma.sim_terms(re, vc), family, m_trials, dharma.N_SIM, rng)
y_obs = np.round(y * w) if m_trials is not None else y # successes for successes-of-trials outcomes
fitted_resp = dharma.mean_response(eta_pop, family) * (w if m_trials is not None else 1.0) # population-level, as DHARMa
dh = dharma.residuals(y_obs, fitted_resp, sims, family, rng, zeros=counts_like)
values.update({"dharma_n_sim": dh["n_sim"], "dharma_ks": dh["ks"], "dharma_ks_p": dh["ks_p"], "dharma_outliers": dh["outliers"],
"dharma_outlier_p": dh["outlier_p"]})
uni_bad = dh["ks_p"] < 0.05
assumptions.append({"key": "uniformity", "label": "Simulated residuals look uniform", "status": "warn" if uni_bad else "pass",
"statistic": dh["ks"], "p": dh["ks_p"],
"detail": f"Kolmogorov–Smirnov D = {dh['ks']:.3f}, {cs.fmt_p(dh['ks_p'])} over {dh['n_sim']} simulations"
+ ("; the outcome's distribution doesn't match the model (check the residual plots)." if uni_bad else ".")})
if counts_like:
values.update({"dharma_disp_ratio": dh["disp_ratio"], "dharma_disp_p": dh["disp_p"], "dharma_zero_ratio": dh["zero_ratio"], "dharma_zero_p": dh["zero_p"]})
disp_bad = dh["disp_p"] < 0.05
over = dh["disp_ratio"] > 1
assumptions.append({"key": "dispersion", "label": "Residual spread matches the model (simulation)", "status": "warn" if disp_bad else "pass",
"statistic": dh["disp_ratio"], "p": dh["disp_p"],
"detail": f"Observed / simulated spread = {dh['disp_ratio']:.2f}, {cs.fmt_p(dh['disp_p'])}"
+ (("; overdispersion: consider an observation-level random effect or a negative binomial model." if over else "; underdispersion: standard errors are conservative.") if disp_bad else ".")})
zero_bad = dh["zero_p"] < 0.05
assumptions.append({"key": "zero_inflation", "label": "Number of zeros matches the model (simulation)", "status": "warn" if zero_bad else "pass",
"statistic": dh["zero_ratio"], "p": dh["zero_p"],
"detail": f"Observed / simulated zeros = {dh['zero_ratio']:.2f}, {cs.fmt_p(dh['zero_p'])}"
+ (("; more zeros than the model expects: consider a zero-inflated or hurdle model." if dh["zero_ratio"] > 1 else "; fewer zeros than the model expects.") if zero_bad else ".")})
out_bad = dh["outlier_p"] < 0.05
assumptions.append({"key": "outliers", "label": "No more outliers than expected (simulation)", "status": "warn" if out_bad else "pass",
"statistic": float(dh["outliers"]), "p": dh["outlier_p"],
"detail": f"{dh['outliers']} of {n} rows sit at the edge of their {dh['n_sim']} simulations (within 1/{dh['n_sim'] + 1} of either end; binomial test, {cs.fmt_p(dh['outlier_p'])})."})
if not fit.hessian_ok:
warnings.append("The finite-difference Hessian is not positive definite: standard errors use the RX approximation (conditional on the variance parameters), as lme4 falls back to.")
# %% Result
pct = f"{conf:.0%}"
rl = "Odds ratio" if family == "binomial" else "Rate ratio"
re_rows = []
off = 0
for ti, t in enumerate(re):
for j, eff in enumerate(t.effects):
for g, lv in enumerate(t.levels):
re_rows.append({"group": t.group, "effect": eff, "level": lv, "estimate": float(fit.b[off + g * t.k + j]),
"sd": float(np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)))})
off += t.nlev * t.k
vc_rows = [{"group": r["grp"], "effect": r["var1"] if r["var2"] is None else f"{r['var1']} ~ {r['var2']}",
"variance": r["vcov"] if r["var2"] is None else None, "sd": r["sdcor"] if r["var2"] is None else None,
"cor": r["sdcor"] if r["var2"] is not None else None} for r in vc]
slopes_tab = [c for c in coefs if c["term"] != "(Intercept)"]
tests_text = f" {effects[0]['term']}: Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}." if effects else ""
summary = (f"{'Logistic' if family == 'binomial' else 'Poisson'} mixed model of {outcome}" + (f" (event: {event})" if event else "")
+ f" (n = {n}, {re[0].nlev} levels of {group}).{tests_text} Latent-scale ICC = {values['icc']:.2f}.")
z = stats.norm.ppf(1 - (1 - conf) / 2)
cat_rows = re_rows[:1000]
charts = [cs.chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", {
"group": cs.col("Level", [r["level"] for r in cat_rows], kind="categorical"), "estimate": cs.col("Conditional mode", [r["estimate"] for r in cat_rows]),
"low": cs.col("low", [r["estimate"] - z * r["sd"] for r in cat_rows]), "high": cs.col("high", [r["estimate"] + z * r["sd"] for r in cat_rows]),
"term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")})]
if slopes_tab:
charts.append(cs.chart("ratios", "forest", f"{rl}s", {
"label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col(rl, [c["ratio"] for c in slopes_tab]),
"low": cs.col("low", [c["ratio_ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ratio_ci_high"] for c in slopes_tab])},
controls={"reference": 1, "log": True}))
tables = [{"key": "fixed", "title": "Fixed effects", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B (link scale)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "ratio", "label": rl, "type": "number"},
{"key": "ratio_ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ratio_ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": coefs, "note": f"{rl}s are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance."}]
if effects:
tables.append({"key": "effects", "title": "Joint Wald tests of each predictor", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "chi2", "label": "Wald χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": effects})
tables.append({"key": "random", "title": "Random effects (link scale)", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"},
{"key": "variance", "label": "Variance", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}, {"key": "cor", "label": "Correlation", "type": "number"}],
"rows": vc_rows})
tables.append({"key": "modes", "title": "Conditional modes of the random effects", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "estimate", "label": "Mode", "type": "number"}, {"key": "sd", "label": "Conditional SD", "type": "number"}], "rows": re_rows[:2000]})
dh_rows = [{"check": "Uniformity (Kolmogorov–Smirnov D)", "statistic": dh["ks"], "p": dh["ks_p"]}]
if counts_like:
dh_rows += [{"check": "Spread (observed / simulated)", "statistic": dh["disp_ratio"], "p": dh["disp_p"]},
{"check": "Zeros (observed / simulated)", "statistic": dh["zero_ratio"], "p": dh["zero_p"]}]
dh_rows.append({"check": "Outliers (rows at the edge of their simulations)", "statistic": float(dh["outliers"]), "p": dh["outlier_p"]})
tables.append({"key": "dharma", "title": "Simulated residual checks (DHARMa)", "columns": [
{"key": "check", "label": "Check", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": dh_rows, "note": f"{dh['n_sim']} simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed {dharma.SEED}. "
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."})
m_show = min(n, 5000) # evenly spaced rows for the residual charts
show = [(i * (n - 1)) // (m_show - 1) if m_show > 1 else 0 for i in range(m_show)]
res_show = [float(dh["residuals"][i]) for i in show]
charts.append(cs.chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", {"x": cs.col("Scaled residual", res_show)},
controls={"reference": "uniform"}))
rank_fit = dharma.rank01(fitted_resp)
charts.append(cs.chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", {
"x": cs.col("Population-level prediction (rank, 0–1)", [float(rank_fit[i]) for i in show]), "y": cs.col("Scaled residual", res_show)}, controls={"fit": "loess"}))
statistics = [{"key": "icc", "label": "ICC (latent scale)", "value": values["icc"]}, {"key": "r2_marginal", "label": "R² marginal", "value": values["r2_marginal"]},
{"key": "r2_conditional", "label": "R² conditional", "value": values["r2_conditional"]}, {"key": "aic", "label": "AIC", "value": values["aic"]}]
if "re_lrt_p" in values:
statistics.append({"key": "re_lrt_p", "label": "Random effects LR test p", "value": values["re_lrt_p"], "format": "p"})
cs.publish({
"method": "mixed.glmm",
"methodVersion": "1.1.0",
"title": "Generalized linear mixed model",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": (f"Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
"statistics": statistics,
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [("Logistic" if family == "binomial" else "Poisson") + " GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); "
+ ("latent residual variance π²/3." if family == "binomial" else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")],
"charts": charts,
"values": values,
})
Across 15 herds, disease incidence changes across periods: (3) = 24.9, p < .001.
Herds differ too: the latent-scale ICC is 0.111, and the test of the random effect gives p < .001.
Counts, with two levels
PredictPredict first
Ticks are counted on grouse chicks, by brood within location, with a Poisson mixed model. The model already allows for differences between broods and locations. Can overdispersion remain?
Reveal
It can. Random effects absorb group differences, and rows can still vary more than a Poisson allows. Here the Pearson dispersion is 1.73, well above 1. You could add an observation-level random effect, or use a negative binomial model.
Wald χ²(2) = 81.46, p < .001
- ICC (latent scale)
- 0.7558
- R² marginal
- 0.5865
- R² conditional
- 0.8990
- AIC
- 1987.88
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 63 levels of location.
- No overdispersion — Pearson χ² / residual df = 1.73; consider an observation-level random effect or a negative binomial model.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.038, p = .596 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 1.16, p = .464.
- Number of zeros matches the model (simulation) — Observed / simulated zeros = 1.07, p = .488.
- No more outliers than expected (simulation) — 2 of 403 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = .777).
Fixed effects
| Term | B (link scale) | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.4669 | 0.1920 | 2.431 | .015 | 1.595 | 1.095 | 2.324 |
| year: 96 | 1.166 | 0.2298 | 5.072 | < .001 | 3.208 | 2.045 | 5.033 |
| year: 97 | −0.9779 | 0.2548 | −3.838 | < .001 | 0.3761 | 0.2282 | 0.6197 |
| height (z) | −0.8466 | 0.1246 | −6.795 | < .001 | 0.4289 | 0.3359 | 0.5475 |
Rate ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| year | 81.462 | 2 | < .001 |
| height (z) | 46.173 | 1 | < .001 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| location:brood | (Intercept) | 0.5924 | 0.7697 | — |
| location | (Intercept) | 0.3296 | 0.5741 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| location:brood | (Intercept) | 1:631 | 0.0558 | 0.4191 |
| location:brood | (Intercept) | 1:722 | −0.4444 | 0.5149 |
| location:brood | (Intercept) | 2:723 | −0.2322 | 0.5359 |
| location:brood | (Intercept) | 3:601 | −1.338 | 0.4869 |
| location:brood | (Intercept) | 4:517 | 0.8995 | 0.3411 |
| location:brood | (Intercept) | 4:632 | 0.5597 | 0.3299 |
| location:brood | (Intercept) | 4:718 | −0.2218 | 0.3880 |
| location:brood | (Intercept) | 4:719 | −0.3205 | 0.3838 |
| location:brood | (Intercept) | 5:634 | 0.0679 | 0.4686 |
| location:brood | (Intercept) | 6:602 | −0.0737 | 0.4639 |
| location:brood | (Intercept) | 7:516 | 0.0889 | 0.4116 |
| location:brood | (Intercept) | 7:518 | 1.731 | 0.3991 |
| location:brood | (Intercept) | 8:608 | −0.2463 | 0.4827 |
| location:brood | (Intercept) | 9:521 | 0.5554 | 0.4712 |
| location:brood | (Intercept) | 10:607 | −0.3096 | 0.4827 |
| location:brood | (Intercept) | 10:720 | −0.1017 | 0.5640 |
| location:brood | (Intercept) | 11:519 | 0.4458 | 0.3889 |
| location:brood | (Intercept) | 11:636 | 0.1872 | 0.3991 |
| location:brood | (Intercept) | 11:721 | 0.1663 | 0.5285 |
| location:brood | (Intercept) | 12:650 | −0.6641 | 0.4908 |
| location:brood | (Intercept) | 13:515 | −0.5615 | 0.4426 |
| location:brood | (Intercept) | 13:520 | 0.8543 | 0.3957 |
| location:brood | (Intercept) | 13:635 | −0.3801 | 0.4450 |
| location:brood | (Intercept) | 14:514 | −0.3719 | 0.4180 |
| location:brood | (Intercept) | 14:603 | 0.3164 | 0.3590 |
| location:brood | (Intercept) | 14:606 | −0.0491 | 0.3572 |
| location:brood | (Intercept) | 14:742 | −0.5804 | 0.6252 |
| location:brood | (Intercept) | 15:739 | 0.0405 | 0.5237 |
| location:brood | (Intercept) | 15:741 | −0.4632 | 0.5832 |
| location:brood | (Intercept) | 16:724 | 0.8690 | 0.4899 |
| location:brood | (Intercept) | 17:513 | 0.1391 | 0.4966 |
| location:brood | (Intercept) | 18:651 | −0.3421 | 0.4864 |
| location:brood | (Intercept) | 19:533 | 0.8969 | 0.3227 |
| location:brood | (Intercept) | 19:535 | −0.4745 | 0.5560 |
| location:brood | (Intercept) | 19:628 | −0.2525 | 0.3605 |
| location:brood | (Intercept) | 19:647 | −0.3840 | 0.3684 |
| location:brood | (Intercept) | 19:708 | 0.6772 | 0.3674 |
| location:brood | (Intercept) | 19:733 | 0.4155 | 0.4875 |
| location:brood | (Intercept) | 19:740 | −0.6640 | 0.6079 |
| location:brood | (Intercept) | 20:648 | 0.1734 | 0.4685 |
First 40 of 181 rows.
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0383 | .596 |
| Spread (observed / simulated) | 1.161 | .464 |
| Zeros (observed / simulated) | 1.067 | .488 |
| Outliers (rows at the edge of their simulations) | 2 | .777 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Poisson GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).
The exact R script · R R version 4.5.1 (2025-06-13)
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec 3e47d54d6697f84c
# Dataset: s1_ticks (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(lme4))
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_ticks.parquet", col_select = c("ticks", "year", "height (z)", "location", "brood")))
n_input <- nrow(df)
df[["year"]] <- factor(df[["year"]], levels = c("95", "96", "97")) # stored level order
df[["location"]] <- factor(df[["location"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63")) # stored level order
df[["brood"]] <- factor(df[["brood"]], levels = c("501", "502", "503", "504", "505", "506", "507", "509", "510", "511", "512", "513", "514", "515", "516", "517", "518", "519", "520", "521", "522", "523", "525", "526", "528", "531", "533", "535", "537", "538", "539", "540", "542", "548", "549", "550", "553", "559", "601", "602", "603", "604", "605", "606", "607", "608", "609", "610", "611", "612", "614", "615", "616", "617", "618", "621", "623", "624", "625", "626", "628", "629", "630", "631", "632", "634", "635", "636", "638", "640", "641", "642", "643", "645", "647", "648", "650", "651", "652", "701", "702", "704", "705", "706", "708", "709", "710", "711", "712", "713", "714", "715", "716", "717", "718", "719", "720", "721", "722", "723", "724", "725", "727", "728", "729", "730", "731", "732", "733", "734", "736", "737", "738", "739", "740", "741", "742", "743")) # stored level order
df <- df[stats::complete.cases(df[c("ticks", "year", "height (z)", "location", "brood")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("ticks", "year", "height (z)", "location", "brood")) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome <- "ticks"
trials <- NULL
exposure <- NULL
predictors <- c("year", "height (z)")
group <- "location"
slopes <- c()
group2 <- "brood"
family <- "poisson" # binomial (logit) | poisson (log)
nesting <- "nested"
correlated <- "correlated" == "correlated"
interactions <- "none"
conf <- 0.95
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
event <- NULL
lhs <- NULL
w <- rep(1, nrow(df))
if (is.factor(df[[outcome]])) {
if (family != "binomial" || nlevels(df[[outcome]]) != 2) stop(sprintf("%s is categorical: use the logistic model with exactly two levels (found %d).", outcome, nlevels(df[[outcome]])))
event <- levels(df[[outcome]])[2] # default: the second stored level ("true" for yes/no)
df$.cs_y <- as.numeric(as.character(df[[outcome]]) == event)
y <- df$.cs_y
lhs <- ".cs_y"
} else {
y <- as.numeric(df[[outcome]])
if (any(y < 0) || any(abs(y - round(y)) > 1e-9)) stop(sprintf("%s must hold whole non-negative numbers (counts or 0/1).", outcome))
if (family == "binomial" && !is.null(trials)) {
w <- df[[trials]]
if (any(w <= 0) || any(y > w)) stop(sprintf("%s must be positive and at least %s on every row.", trials, outcome))
df$.cs_succ <- y
df$.cs_fail <- w - y
lhs <- "cbind(.cs_succ, .cs_fail)" # successes out of trials
y <- y / w
} else if (family == "binomial" && !all(y %in% c(0, 1))) {
stop(sprintf("%s must be 0/1 for a logistic model (or give the number of Trials).", outcome))
}
}
offset <- rep(0, nrow(df))
if (family == "poisson" && !is.null(exposure)) {
if (any(df[[exposure]] <= 0)) stop(sprintf("%s must be positive (its log is the offset).", exposure))
offset <- log(df[[exposure]])
}
df$.cs_offset <- offset
# Degenerate input stops with a catalog error before the fit; Python runs the same checks in the same order.
cs_mixed_check_re(df, group, slopes, group2, nesting, correlated, allow_n = TRUE) # glmer's checks on the grouping factors
for (pred in predictors) {
if (length(unique(df[[pred]])) < 2) cs_error("CS_E_CONSTANT", column = pred) # one value (or one level with data) is no variation
}
fml <- cs_mixed_formula(outcome, predictors, interactions, group, slopes, group2, nesting, correlated, lhs = lhs)
fam <- if (family == "binomial") binomial() else poisson()
# Tight tolerances (default: bobyqa then Nelder–Mead, tolPwrss = 1e-7) so both engines reach the same optimum.
ctrl <- glmerControl(optimizer = c("bobyqa", "bobyqa"), optCtrl = list(rhoend = 1e-12, maxfun = 1e6), tolPwrss = 1e-12)
# %% Fit (Laplace, nAGQ = 1)
fit <- glmer(fml, data = df, family = fam, offset = .cs_offset, nAGQ = 1, control = ctrl)
X <- getME(fit, "X")
terms_x <- cs_design_labels(df, predictors, interactions)
if (ncol(X) < length(terms_x)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
b <- unname(fixef(fit))
V <- as.matrix(vcov(fit)) # lme4 default: from the finite-difference Hessian
se <- sqrt(diag(V))
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
values <- list()
coefs <- list()
for (j in seq_len(k)) {
t <- terms_x[j]
row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j])
row <- c(row, list(ratio = exp(b[j]), ratio_ci_low = exp(row$ci_low), ratio_ci_high = exp(row$ci_high)))
coefs[[j]] <- row
for (key in c("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")) values[[sprintf("%s[%s]", key, t)]] <- if (key == "coef") row$estimate else row[[key]]
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
idx <- blocks[[name]]
chi2 <- as.numeric(t(b[idx]) %*% solve(V[idx, idx, drop = FALSE], b[idx]))
pc <- pchisq(chi2, length(idx), lower.tail = FALSE)
effects[[length(effects) + 1]] <- list(term = name, chi2 = chi2, df = length(idx), p = pc)
values[[sprintf("chi2[%s]", name)]] <- chi2; values[[sprintf("chi2_df[%s]", name)]] <- as.numeric(length(idx)); values[[sprintf("chi2_p[%s]", name)]] <- pc
}
values$focal_chi2 <- NA; values$focal_df <- NA; values$focal_p <- NA # no fixed predictor
if (length(effects)) {
values$focal_chi2 <- effects[[1]]$chi2; values$focal_df <- as.numeric(effects[[1]]$df); values$focal_p <- effects[[1]]$p
}
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
valid <- c(group, group2, if (!is.null(group2)) paste0(group, ":", group2))
vc <- cs_mixed_varcorr(fit, valid)
for (i in seq_len(nrow(vc))) {
if (is.na(vc$effect2[i])) {
values[[sprintf("var[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$vcov[i]
values[[sprintf("sd[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$sdcor[i]
} else {
values[[sprintf("cor[%s|%s|%s]", vc$group[i], vc$effect1[i], vc$effect2[i])]] <- vc$sdcor[i]
}
}
eta_fixed <- as.vector(X %*% b)
var_fixed <- if (n > 1) var(eta_fixed) else 0
var_random <- cs_mixed_random_variance(fit, df)
var_residual <- if (family == "binomial") pi^2 / 3 else log1p(1 / exp(mean(eta_fixed) + var_random / 2))
total <- var_fixed + var_random + var_residual
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta
ll <- as.numeric(logLik(fit))
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, family = family, log_lik = ll, deviance = -2 * ll, aic = -2 * ll + 2 * n_params,
bic = -2 * ll + log(n) * n_params, icc = var_random / (var_random + var_residual), r2_marginal = var_fixed / total,
r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random, var_residual = var_residual,
singular = isSingular(fit, tol = 1e-4), n_params = n_params, n_theta = n_theta,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (!is.null(group2)) {
values$n_groups2 <- if (nesting == "nested") nlevels(droplevels(interaction(df[[group]], df[[group2]], drop = TRUE))) else nlevels(droplevels(df[[group2]]))
}
# %% Random effects vs none (likelihood ratio against the GLM)
if (FALSE) {
fixed_rhs <- if (length(predictors)) as.character(cs_model_formula(outcome, predictors, interactions))[3] else "1"
g <- glm(stats::as.formula(paste(if (is.null(lhs)) paste0("`", outcome, "`") else lhs, "~", fixed_rhs)), family = fam, data = df, offset = .cs_offset,
control = glm.control(epsilon = 1e-14, maxit = 100))
lrt <- max(2 * (ll - as.numeric(logLik(g))), 0)
lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
if (n_theta == 1) lrt_p <- lrt_p / 2 # boundary: 50:50 mixture of chi2(0) and chi2(1)
values$re_lrt <- lrt; values$re_lrt_df <- as.numeric(n_theta); values$re_lrt_p <- lrt_p
}
# %% Assumptions
singular <- isTRUE(values$singular)
assumptions <- list(list(key = "singular", label = "Non-singular fit", status = if (singular) "warn" else "pass",
detail = if (singular) "A variance component is estimated at (or near) zero: simplify the random effects." else "Every variance component is clearly above zero."))
nlev <- c(setNames(n_groups, group), if (!is.null(group2)) setNames(values$n_groups2, if (nesting == "nested") paste0(group, ":", group2) else group2))
few <- names(nlev)[nlev < 5]
assumptions[[2]] <- list(key = "groups", label = "Enough groups", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 5 levels for %s: its variance is estimated very imprecisely.", paste(few, collapse = ", ")) else sprintf("%d levels of %s.", n_groups, group))
if (family == "poisson") {
mu <- unname(fitted(fit))
disp <- sum((y - mu)^2 / mu) / (n - k)
values$dispersion <- disp
assumptions[[3]] <- list(key = "overdispersion", label = "No overdispersion", status = if (disp > 1.5) "warn" else "pass", statistic = disp,
detail = paste0(sprintf("Pearson χ² / residual df = %.2f", disp), if (disp > 1.5) "; consider an observation-level random effect or a negative binomial model." else "."))
}
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like <- family == "poisson" || !is.null(trials) # spread and zeros are checked for counts, not for 0/1 data
m_trials <- if (family == "binomial" && !is.null(trials)) w else NULL
rng <- cs_rng(1)
dh_terms <- cs_dharma_terms(df, group, slopes, group2, nesting, correlated, vc)
eta_pop <- as.vector(X %*% b) + offset # fixed part: the simulations draw new random effects around it
sims <- cs_dharma_simulate(eta_pop, dh_terms, family, m_trials, 250, rng)
y_obs <- if (!is.null(m_trials)) round(y * w) else y # successes for successes-of-trials outcomes
fitted_resp <- cs_dharma_mean(eta_pop, family) * (if (!is.null(m_trials)) w else 1) # population-level, as DHARMa
dh <- cs_dharma_residuals(y_obs, fitted_resp, sims, family, rng, zeros = counts_like)
values$dharma_n_sim <- dh$n_sim; values$dharma_ks <- dh$ks; values$dharma_ks_p <- dh$ks_p
values$dharma_outliers <- dh$outliers; values$dharma_outlier_p <- dh$outlier_p
uni_bad <- dh$ks_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "uniformity", label = "Simulated residuals look uniform", status = if (uni_bad) "warn" else "pass",
statistic = dh$ks, p = dh$ks_p,
detail = paste0(sprintf("Kolmogorov–Smirnov D = %.3f, %s over %d simulations", dh$ks, cs_fmt_p(dh$ks_p), as.integer(dh$n_sim)),
if (uni_bad) "; the outcome's distribution doesn't match the model (check the residual plots)." else "."))
if (counts_like) {
values$dharma_disp_ratio <- dh$disp_ratio; values$dharma_disp_p <- dh$disp_p
values$dharma_zero_ratio <- dh$zero_ratio; values$dharma_zero_p <- dh$zero_p
disp_bad <- dh$disp_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "dispersion", label = "Residual spread matches the model (simulation)", status = if (disp_bad) "warn" else "pass",
statistic = dh$disp_ratio, p = dh$disp_p,
detail = paste0(sprintf("Observed / simulated spread = %.2f, %s", dh$disp_ratio, cs_fmt_p(dh$disp_p)),
if (!disp_bad) "." else if (dh$disp_ratio > 1) "; overdispersion: consider an observation-level random effect or a negative binomial model." else "; underdispersion: standard errors are conservative."))
zero_bad <- dh$zero_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "zero_inflation", label = "Number of zeros matches the model (simulation)", status = if (zero_bad) "warn" else "pass",
statistic = dh$zero_ratio, p = dh$zero_p,
detail = paste0(sprintf("Observed / simulated zeros = %.2f, %s", dh$zero_ratio, cs_fmt_p(dh$zero_p)),
if (!zero_bad) "." else if (dh$zero_ratio > 1) "; more zeros than the model expects: consider a zero-inflated or hurdle model." else "; fewer zeros than the model expects."))
}
out_bad <- dh$outlier_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "outliers", label = "No more outliers than expected (simulation)", status = if (out_bad) "warn" else "pass",
statistic = as.numeric(dh$outliers), p = dh$outlier_p,
detail = sprintf("%d of %d rows sit at the edge of their %d simulations (within 1/%d of either end; binomial test, %s).", as.integer(dh$outliers), as.integer(n), as.integer(dh$n_sim), as.integer(dh$n_sim) + 1L, cs_fmt_p(dh$outlier_p)))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
rl <- if (family == "binomial") "Odds ratio" else "Rate ratio"
re_tab <- cs_mixed_ranef(fit, valid)
vc_rows <- lapply(seq_len(nrow(vc)), function(i) {
if (is.na(vc$effect2[i])) list(group = vc$group[i], effect = vc$effect1[i], variance = vc$vcov[i], sd = vc$sdcor[i], cor = NULL)
else list(group = vc$group[i], effect = paste(vc$effect1[i], "~", vc$effect2[i]), variance = NULL, sd = NULL, cor = vc$sdcor[i])
})
slopes_tab <- Filter(function(cf) cf$term != "(Intercept)", coefs)
tests_text <- if (length(effects)) sprintf(" %s: Wald χ²(%d) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("%s mixed model of %s%s (n = %d, %d levels of %s).%s Latent-scale ICC = %.2f.", if (family == "binomial") "Logistic" else "Poisson",
outcome, if (!is.null(event)) sprintf(" (event: %s)", event) else "", n, n_groups, group, tests_text, values$icc)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(cs_chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", list(
group = cs_col("Level", cat_tab$level, kind = "categorical"), estimate = cs_col("Conditional mode", cat_tab$estimate),
low = cs_col("low", cat_tab$estimate - z * cat_tab$sd), high = cs_col("high", cat_tab$estimate + z * cat_tab$sd),
term = cs_col("Term", paste0(cat_tab$group, ": ", cat_tab$effect), kind = "categorical"))))
if (length(slopes_tab)) {
charts[[2]] <- cs_chart("ratios", "forest", paste0(rl, "s"), list(
label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col(rl, vapply(slopes_tab, `[[`, 0, "ratio")),
low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ratio_ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ratio_ci_high"))),
controls = list(reference = 1, log = TRUE))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B (link scale)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "ratio", label = rl, type = "number"),
list(key = "ratio_ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ratio_ci_high", label = paste(pct, "CI high"), type = "number")),
rows = coefs, note = sprintf("%ss are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.", rl)))
if (length(effects)) {
tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint Wald tests of each predictor", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "chi2", label = "Wald χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = effects)
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects (link scale)", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"),
list(key = "variance", label = "Variance", type = "number"), list(key = "sd", label = "SD", type = "number"), list(key = "cor", label = "Correlation", type = "number")),
rows = vc_rows)
mode_rows <- lapply(seq_len(min(nrow(re_tab), 2000)), function(i) as.list(re_tab[i, ]))
tables[[length(tables) + 1]] <- list(key = "modes", title = "Conditional modes of the random effects", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "estimate", label = "Mode", type = "number"), list(key = "sd", label = "Conditional SD", type = "number")), rows = mode_rows)
dh_rows <- list(list(check = "Uniformity (Kolmogorov–Smirnov D)", statistic = dh$ks, p = dh$ks_p))
if (counts_like) {
dh_rows <- c(dh_rows, list(list(check = "Spread (observed / simulated)", statistic = dh$disp_ratio, p = dh$disp_p),
list(check = "Zeros (observed / simulated)", statistic = dh$zero_ratio, p = dh$zero_p)))
}
dh_rows[[length(dh_rows) + 1]] <- list(check = "Outliers (rows at the edge of their simulations)", statistic = as.numeric(dh$outliers), p = dh$outlier_p)
tables[[length(tables) + 1]] <- list(key = "dharma", title = "Simulated residual checks (DHARMa)", columns = list(
list(key = "check", label = "Check", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = dh_rows, note = paste0(sprintf("%d simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. ", as.integer(dh$n_sim)),
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."))
m_show <- min(n, 5000) # evenly spaced rows for the residual charts
show <- if (m_show > 1) ((seq_len(m_show) - 1) * (n - 1)) %/% (m_show - 1) + 1 else 1
res_show <- dh$residuals[show]
charts[[length(charts) + 1]] <- cs_chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", list(x = cs_col("Scaled residual", res_show)),
controls = list(reference = "uniform"))
rank_fit <- cs_dharma_rank01(fitted_resp)
charts[[length(charts) + 1]] <- cs_chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", list(
x = cs_col("Population-level prediction (rank, 0–1)", rank_fit[show]), y = cs_col("Scaled residual", res_show)), controls = list(fit = "loess"))
statistics <- list(list(key = "icc", label = "ICC (latent scale)", value = values$icc), list(key = "r2_marginal", label = "R² marginal", value = values$r2_marginal),
list(key = "r2_conditional", label = "R² conditional", value = values$r2_conditional), list(key = "aic", label = "AIC", value = values$aic))
if (!is.null(values$re_lrt_p)) statistics[[length(statistics) + 1]] <- list(key = "re_lrt_p", label = "Random effects LR test p", value = values$re_lrt_p, format = "p")
cs_publish(list(
method = "mixed.glmm",
methodVersion = "1.1.0",
title = "Generalized linear mixed model",
engine = cs_engine_info("lme4", "nanoparquet"),
n = n,
summary = summary,
apa = if (length(effects)) sprintf("Wald χ²(%d) = %.2f, %s", as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else "",
statistics = statistics,
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (family == "binomial") "Logistic" else "Poisson", " GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); ",
if (family == "binomial") "latent residual variance π²/3." else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")),
charts = charts,
values = values
))
Wald χ²(2) = 81.46, p < .001
- ICC (latent scale)
- 0.7558
- R² marginal
- 0.5865
- R² conditional
- 0.8990
- AIC
- 1987.88
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 63 levels of location.
- No overdispersion — Pearson χ² / residual df = 1.73; consider an observation-level random effect or a negative binomial model.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.038, p = .596 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 1.16, p = .464.
- Number of zeros matches the model (simulation) — Observed / simulated zeros = 1.07, p = .488.
- No more outliers than expected (simulation) — 2 of 403 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = .777).
Fixed effects
| Term | B (link scale) | SE | z | p | Rate ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | 0.4669 | 0.1920 | 2.431 | .015 | 1.595 | 1.095 | 2.324 |
| year: 96 | 1.166 | 0.2298 | 5.072 | < .001 | 3.208 | 2.045 | 5.033 |
| year: 97 | −0.9779 | 0.2548 | −3.838 | < .001 | 0.3761 | 0.2282 | 0.6197 |
| height (z) | −0.8466 | 0.1246 | −6.795 | < .001 | 0.4289 | 0.3359 | 0.5475 |
Rate ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| year | 81.460 | 2 | < .001 |
| height (z) | 46.172 | 1 | < .001 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| location | (Intercept) | 0.3296 | 0.5741 | — |
| location:brood | (Intercept) | 0.5924 | 0.7697 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| location | (Intercept) | 1 | −0.2163 | 0.4133 |
| location | (Intercept) | 2 | −0.1292 | 0.4849 |
| location | (Intercept) | 3 | −0.7448 | 0.4686 |
| location | (Intercept) | 4 | 0.5102 | 0.3267 |
| location | (Intercept) | 5 | 0.0378 | 0.4628 |
| location | (Intercept) | 6 | −0.0410 | 0.4614 |
| location | (Intercept) | 7 | 1.013 | 0.3974 |
| location | (Intercept) | 8 | −0.1371 | 0.4673 |
| location | (Intercept) | 9 | 0.3091 | 0.4636 |
| location | (Intercept) | 10 | −0.2289 | 0.4318 |
| location | (Intercept) | 11 | 0.4447 | 0.3709 |
| location | (Intercept) | 12 | −0.3696 | 0.4699 |
| location | (Intercept) | 13 | −0.0485 | 0.3679 |
| location | (Intercept) | 14 | −0.3812 | 0.3454 |
| location | (Intercept) | 15 | −0.2352 | 0.4436 |
| location | (Intercept) | 16 | 0.4836 | 0.4696 |
| location | (Intercept) | 17 | 0.0774 | 0.4718 |
| location | (Intercept) | 18 | −0.1904 | 0.4685 |
| location | (Intercept) | 19 | 0.1194 | 0.2911 |
| location | (Intercept) | 20 | 0.0965 | 0.4628 |
| location | (Intercept) | 21 | −0.2607 | 0.4879 |
| location | (Intercept) | 22 | 0.3320 | 0.4121 |
| location | (Intercept) | 23 | 0.4441 | 0.3980 |
| location | (Intercept) | 24 | 0.8023 | 0.4606 |
| location | (Intercept) | 25 | 0.4218 | 0.4265 |
| location | (Intercept) | 26 | 0.2921 | 0.4693 |
| location | (Intercept) | 27 | −0.3328 | 0.4771 |
| location | (Intercept) | 28 | 0.2707 | 0.3058 |
| location | (Intercept) | 29 | −0.3674 | 0.4724 |
| location | (Intercept) | 30 | −0.0527 | 0.4049 |
| location | (Intercept) | 31 | −0.0946 | 0.4387 |
| location | (Intercept) | 32 | −0.3600 | 0.5201 |
| location | (Intercept) | 33 | 0.0388 | 0.4829 |
| location | (Intercept) | 34 | −0.4177 | 0.4830 |
| location | (Intercept) | 35 | −0.1183 | 0.5480 |
| location | (Intercept) | 36 | 0.1100 | 0.3419 |
| location | (Intercept) | 37 | −0.2080 | 0.4214 |
| location | (Intercept) | 38 | −0.2030 | 0.4963 |
| location | (Intercept) | 39 | 0.2180 | 0.4991 |
| location | (Intercept) | 40 | 0.2294 | 0.4636 |
First 40 of 181 rows.
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.0383 | .596 |
| Spread (observed / simulated) | 1.161 | .464 |
| Zeros (observed / simulated) | 1.066 | .488 |
| Outliers (rows at the edge of their simulations) | 2 | .777 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Poisson GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec 3e47d54d6697f84c
# Dataset: s1_ticks (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import mixed as mx # twin of lme4::glmer (Laplace, nAGQ = 1) — no Python library fits it
from codesplash.stats import regression as csreg
from codesplash.stats import dharma # simulated residuals, twin of codesplashr::cs_dharma_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_ticks.parquet", columns=["ticks", "year", "height (z)", "location", "brood"])
n_input = len(df)
df["year"] = pd.Categorical(df["year"], categories=["95", "96", "97"]) # stored level order
df["location"] = pd.Categorical(df["location"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "60", "61", "62", "63"]) # stored level order
df["brood"] = pd.Categorical(df["brood"], categories=["501", "502", "503", "504", "505", "506", "507", "509", "510", "511", "512", "513", "514", "515", "516", "517", "518", "519", "520", "521", "522", "523", "525", "526", "528", "531", "533", "535", "537", "538", "539", "540", "542", "548", "549", "550", "553", "559", "601", "602", "603", "604", "605", "606", "607", "608", "609", "610", "611", "612", "614", "615", "616", "617", "618", "621", "623", "624", "625", "626", "628", "629", "630", "631", "632", "634", "635", "636", "638", "640", "641", "642", "643", "645", "647", "648", "650", "651", "652", "701", "702", "704", "705", "706", "708", "709", "710", "711", "712", "713", "714", "715", "716", "717", "718", "719", "720", "721", "722", "723", "724", "725", "727", "728", "729", "730", "731", "732", "733", "734", "736", "737", "738", "739", "740", "741", "742", "743"]) # stored level order
df = df.dropna(subset=["ticks", "year", "height (z)", "location", "brood"]) # listwise deletion over the analysis columns
df["year"] = df["year"].cat.remove_unused_categories()
df["location"] = df["location"].cat.remove_unused_categories()
df["brood"] = df["brood"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["ticks", "year", "height (z)", "location", "brood"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome = "ticks"
trials = None
exposure = None
predictors = ["year", "height (z)"]
group = "location"
slopes = []
group2 = "brood"
family = "poisson" # binomial (logit) | poisson (log)
nesting = "nested"
correlated = "correlated" == "correlated"
interactions = "none"
conf = 0.95
event = None
w = np.ones(len(df))
offset = np.zeros(len(df))
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
levels_y = [str(x) for x in df[outcome].cat.categories]
if family != "binomial" or len(levels_y) != 2:
raise ValueError(f"{outcome} is categorical: use the logistic model with exactly two levels (found {len(levels_y)}).")
event = levels_y[1] # default: the second stored level ("true" for yes/no)
y = (df[outcome].astype(str) == event).to_numpy(dtype=float)
else:
y = df[outcome].to_numpy(dtype=float)
if (y < 0).any() or (np.abs(y - np.round(y)) > 1e-9).any():
raise ValueError(f"{outcome} must hold whole non-negative numbers (counts or 0/1).")
if family == "binomial":
if trials:
w = df[trials].to_numpy(dtype=float)
if (w <= 0).any() or (y > w).any():
raise ValueError(f"{trials} must be positive and at least {outcome} on every row.")
y = y / w # proportion of successes with binomial weights = trials (lme4's cbind(succ, fail))
elif not np.all(np.isin(y, (0.0, 1.0))):
raise ValueError(f"{outcome} must be 0/1 for a logistic model (or give the number of Trials).")
if family == "poisson" and exposure:
if (df[exposure] <= 0).any():
raise ValueError(f"{exposure} must be positive (its log is the offset).")
offset = np.log(df[exposure].to_numpy(dtype=float))
re = mx.re_terms(df, group, slopes, group2, nesting, correlated)
# Degenerate input stops with a catalog error before the fit; R runs the same checks in the same order.
mx.check_re_terms(re, len(df), allow_n=True) # glmer's checks on the grouping factors
for pred in predictors:
if df[pred].nunique() < 2: # one value (or one level with data) is no variation
cs.cs_error("CS_E_CONSTANT", column=pred)
X = csreg.design_matrix(df, predictors, interactions)
terms_x = list(X.columns)
n, k = X.shape
# %% Fit (Laplace; covariance of β from the finite-difference Hessian, lme4's default)
model = mx.Glmm(y, X.to_numpy(), re, family, weights=w, offset=offset)
fit = model.fit()
b = fit.beta
se = np.sqrt(np.diag(fit.vcov))
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
values = {}
coefs = []
for j, t in enumerate(terms_x):
row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j])}
row.update({"ratio": float(np.exp(b[j])), "ratio_ci_low": float(np.exp(row["ci_low"])), "ratio_ci_high": float(np.exp(row["ci_high"]))})
coefs.append(row)
values.update({f"{key}[{t}]": row["estimate" if key == "coef" else key] for key in ("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
bb = b[idx]
chi2 = float(bb @ np.linalg.solve(fit.vcov[np.ix_(idx, idx)], bb))
pc = float(stats.chi2.sf(chi2, len(idx)))
effects.append({"term": name, "chi2": chi2, "df": len(idx), "p": pc})
values.update({f"chi2[{name}]": chi2, f"chi2_df[{name}]": float(len(idx)), f"chi2_p[{name}]": pc})
values.update({"focal_chi2": None, "focal_df": None, "focal_p": None})
if effects:
values.update({"focal_chi2": effects[0]["chi2"], "focal_df": float(effects[0]["df"]), "focal_p": effects[0]["p"]})
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
vc = mx.varcorr(re, fit.theta, 1.0)
for r in vc:
if r["var2"] is None:
values[f"var[{r['grp']}|{r['var1']}]"] = r["vcov"]
values[f"sd[{r['grp']}|{r['var1']}]"] = r["sdcor"]
else:
values[f"cor[{r['grp']}|{r['var1']}|{r['var2']}]"] = r["sdcor"]
eta_fixed = X.to_numpy() @ b
var_fixed = float(np.var(eta_fixed, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, 1.0)
if family == "binomial":
var_residual = np.pi**2 / 3 # logistic latent variance
else:
lam = np.exp(np.mean(eta_fixed) + var_random / 2) # lognormal approximation of the observation-level variance
var_residual = float(np.log1p(1 / lam))
total = var_fixed + var_random + var_residual
n_theta = len(fit.theta)
n_params = k + n_theta
values.update({"n": n, "k": k, "n_groups": re[0].nlev, "family": family, "log_lik": fit.log_lik, "deviance": fit.objective,
"aic": fit.objective + 2 * n_params, "bic": fit.objective + np.log(n) * n_params, "icc": var_random / (var_random + var_residual),
"r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total, "var_fixed": var_fixed,
"var_random": var_random, "var_residual": float(var_residual), "singular": fit.singular, "n_params": n_params, "n_theta": n_theta,
"max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
if group2:
values["n_groups2"] = re[-1].nlev
# %% Random effects vs none (likelihood ratio against the GLM)
if False:
beta_glm = model._glm_start()
mu_glm = model.linkinv(X.to_numpy() @ beta_glm + offset)
ll_glm = -0.5 * float(np.sum(model.m2ll(y, mu_glm, w)))
lrt = max(2 * (fit.log_lik - ll_glm), 0.0)
lrt_p = float(stats.chi2.sf(lrt, n_theta))
if n_theta == 1:
lrt_p /= 2 # boundary: 50:50 mixture of χ²(0) and χ²(1)
values.update({"re_lrt": lrt, "re_lrt_df": float(n_theta), "re_lrt_p": lrt_p})
# %% Assumptions
assumptions = [{"key": "singular", "label": "Non-singular fit", "status": "warn" if fit.singular else "pass",
"detail": "A variance component is estimated at (or near) zero: simplify the random effects." if fit.singular else "Every variance component is clearly above zero."}]
few = [t.group for t in re if t.nlev < 5]
assumptions.append({"key": "groups", "label": "Enough groups", "status": "warn" if few else "pass",
"detail": (f"Fewer than 5 levels for {', '.join(dict.fromkeys(few))}: its variance is estimated very imprecisely." if few else f"{re[0].nlev} levels of {group}.")})
if family == "poisson":
mu = fit.mu
disp = float(np.sum((y - mu) ** 2 / mu) / (n - k))
values["dispersion"] = disp
assumptions.append({"key": "overdispersion", "label": "No overdispersion", "status": "warn" if disp > 1.5 else "pass", "statistic": disp,
"detail": f"Pearson χ² / residual df = {disp:.2f}" + ("; consider an observation-level random effect or a negative binomial model." if disp > 1.5 else ".")})
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like = family == "poisson" or trials is not None # spread and zeros are checked for counts, not for 0/1 data
m_trials = w if (family == "binomial" and trials) else None
rng = dharma.Rng(dharma.SEED)
eta_pop = X.to_numpy() @ b + offset # fixed part: the simulations draw new random effects around it
sims = dharma.simulate(eta_pop, dharma.sim_terms(re, vc), family, m_trials, dharma.N_SIM, rng)
y_obs = np.round(y * w) if m_trials is not None else y # successes for successes-of-trials outcomes
fitted_resp = dharma.mean_response(eta_pop, family) * (w if m_trials is not None else 1.0) # population-level, as DHARMa
dh = dharma.residuals(y_obs, fitted_resp, sims, family, rng, zeros=counts_like)
values.update({"dharma_n_sim": dh["n_sim"], "dharma_ks": dh["ks"], "dharma_ks_p": dh["ks_p"], "dharma_outliers": dh["outliers"],
"dharma_outlier_p": dh["outlier_p"]})
uni_bad = dh["ks_p"] < 0.05
assumptions.append({"key": "uniformity", "label": "Simulated residuals look uniform", "status": "warn" if uni_bad else "pass",
"statistic": dh["ks"], "p": dh["ks_p"],
"detail": f"Kolmogorov–Smirnov D = {dh['ks']:.3f}, {cs.fmt_p(dh['ks_p'])} over {dh['n_sim']} simulations"
+ ("; the outcome's distribution doesn't match the model (check the residual plots)." if uni_bad else ".")})
if counts_like:
values.update({"dharma_disp_ratio": dh["disp_ratio"], "dharma_disp_p": dh["disp_p"], "dharma_zero_ratio": dh["zero_ratio"], "dharma_zero_p": dh["zero_p"]})
disp_bad = dh["disp_p"] < 0.05
over = dh["disp_ratio"] > 1
assumptions.append({"key": "dispersion", "label": "Residual spread matches the model (simulation)", "status": "warn" if disp_bad else "pass",
"statistic": dh["disp_ratio"], "p": dh["disp_p"],
"detail": f"Observed / simulated spread = {dh['disp_ratio']:.2f}, {cs.fmt_p(dh['disp_p'])}"
+ (("; overdispersion: consider an observation-level random effect or a negative binomial model." if over else "; underdispersion: standard errors are conservative.") if disp_bad else ".")})
zero_bad = dh["zero_p"] < 0.05
assumptions.append({"key": "zero_inflation", "label": "Number of zeros matches the model (simulation)", "status": "warn" if zero_bad else "pass",
"statistic": dh["zero_ratio"], "p": dh["zero_p"],
"detail": f"Observed / simulated zeros = {dh['zero_ratio']:.2f}, {cs.fmt_p(dh['zero_p'])}"
+ (("; more zeros than the model expects: consider a zero-inflated or hurdle model." if dh["zero_ratio"] > 1 else "; fewer zeros than the model expects.") if zero_bad else ".")})
out_bad = dh["outlier_p"] < 0.05
assumptions.append({"key": "outliers", "label": "No more outliers than expected (simulation)", "status": "warn" if out_bad else "pass",
"statistic": float(dh["outliers"]), "p": dh["outlier_p"],
"detail": f"{dh['outliers']} of {n} rows sit at the edge of their {dh['n_sim']} simulations (within 1/{dh['n_sim'] + 1} of either end; binomial test, {cs.fmt_p(dh['outlier_p'])})."})
if not fit.hessian_ok:
warnings.append("The finite-difference Hessian is not positive definite: standard errors use the RX approximation (conditional on the variance parameters), as lme4 falls back to.")
# %% Result
pct = f"{conf:.0%}"
rl = "Odds ratio" if family == "binomial" else "Rate ratio"
re_rows = []
off = 0
for ti, t in enumerate(re):
for j, eff in enumerate(t.effects):
for g, lv in enumerate(t.levels):
re_rows.append({"group": t.group, "effect": eff, "level": lv, "estimate": float(fit.b[off + g * t.k + j]),
"sd": float(np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)))})
off += t.nlev * t.k
vc_rows = [{"group": r["grp"], "effect": r["var1"] if r["var2"] is None else f"{r['var1']} ~ {r['var2']}",
"variance": r["vcov"] if r["var2"] is None else None, "sd": r["sdcor"] if r["var2"] is None else None,
"cor": r["sdcor"] if r["var2"] is not None else None} for r in vc]
slopes_tab = [c for c in coefs if c["term"] != "(Intercept)"]
tests_text = f" {effects[0]['term']}: Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}." if effects else ""
summary = (f"{'Logistic' if family == 'binomial' else 'Poisson'} mixed model of {outcome}" + (f" (event: {event})" if event else "")
+ f" (n = {n}, {re[0].nlev} levels of {group}).{tests_text} Latent-scale ICC = {values['icc']:.2f}.")
z = stats.norm.ppf(1 - (1 - conf) / 2)
cat_rows = re_rows[:1000]
charts = [cs.chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", {
"group": cs.col("Level", [r["level"] for r in cat_rows], kind="categorical"), "estimate": cs.col("Conditional mode", [r["estimate"] for r in cat_rows]),
"low": cs.col("low", [r["estimate"] - z * r["sd"] for r in cat_rows]), "high": cs.col("high", [r["estimate"] + z * r["sd"] for r in cat_rows]),
"term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")})]
if slopes_tab:
charts.append(cs.chart("ratios", "forest", f"{rl}s", {
"label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col(rl, [c["ratio"] for c in slopes_tab]),
"low": cs.col("low", [c["ratio_ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ratio_ci_high"] for c in slopes_tab])},
controls={"reference": 1, "log": True}))
tables = [{"key": "fixed", "title": "Fixed effects", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B (link scale)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "ratio", "label": rl, "type": "number"},
{"key": "ratio_ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ratio_ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": coefs, "note": f"{rl}s are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance."}]
if effects:
tables.append({"key": "effects", "title": "Joint Wald tests of each predictor", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "chi2", "label": "Wald χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": effects})
tables.append({"key": "random", "title": "Random effects (link scale)", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"},
{"key": "variance", "label": "Variance", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}, {"key": "cor", "label": "Correlation", "type": "number"}],
"rows": vc_rows})
tables.append({"key": "modes", "title": "Conditional modes of the random effects", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "estimate", "label": "Mode", "type": "number"}, {"key": "sd", "label": "Conditional SD", "type": "number"}], "rows": re_rows[:2000]})
dh_rows = [{"check": "Uniformity (Kolmogorov–Smirnov D)", "statistic": dh["ks"], "p": dh["ks_p"]}]
if counts_like:
dh_rows += [{"check": "Spread (observed / simulated)", "statistic": dh["disp_ratio"], "p": dh["disp_p"]},
{"check": "Zeros (observed / simulated)", "statistic": dh["zero_ratio"], "p": dh["zero_p"]}]
dh_rows.append({"check": "Outliers (rows at the edge of their simulations)", "statistic": float(dh["outliers"]), "p": dh["outlier_p"]})
tables.append({"key": "dharma", "title": "Simulated residual checks (DHARMa)", "columns": [
{"key": "check", "label": "Check", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": dh_rows, "note": f"{dh['n_sim']} simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed {dharma.SEED}. "
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."})
m_show = min(n, 5000) # evenly spaced rows for the residual charts
show = [(i * (n - 1)) // (m_show - 1) if m_show > 1 else 0 for i in range(m_show)]
res_show = [float(dh["residuals"][i]) for i in show]
charts.append(cs.chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", {"x": cs.col("Scaled residual", res_show)},
controls={"reference": "uniform"}))
rank_fit = dharma.rank01(fitted_resp)
charts.append(cs.chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", {
"x": cs.col("Population-level prediction (rank, 0–1)", [float(rank_fit[i]) for i in show]), "y": cs.col("Scaled residual", res_show)}, controls={"fit": "loess"}))
statistics = [{"key": "icc", "label": "ICC (latent scale)", "value": values["icc"]}, {"key": "r2_marginal", "label": "R² marginal", "value": values["r2_marginal"]},
{"key": "r2_conditional", "label": "R² conditional", "value": values["r2_conditional"]}, {"key": "aic", "label": "AIC", "value": values["aic"]}]
if "re_lrt_p" in values:
statistics.append({"key": "re_lrt_p", "label": "Random effects LR test p", "value": values["re_lrt_p"], "format": "p"})
cs.publish({
"method": "mixed.glmm",
"methodVersion": "1.1.0",
"title": "Generalized linear mixed model",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": (f"Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
"statistics": statistics,
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [("Logistic" if family == "binomial" else "Poisson") + " GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); "
+ ("latent residual variance π²/3." if family == "binomial" else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")],
"charts": charts,
"values": values,
})
Shortened for the Academy: 4 chart(s) dropped to stay under 100 KB; 4 chart(s) dropped to stay under 100 KB.
How far to trust the approximation
ReflectThe Laplace approximation is good when groups have many rows. With a yes-or-no outcome and few rows per group, it can underestimate the variance. Random slopes ask more still: with a slope for visit, 300 yes-or-no rows from 60 patients must support two random effects.
How many rows per group do you have? If it's only a few, how would you check that the answer holds up?
Check your understanding
CheckpointCheck yourself
In a logistic mixed model, a treatment has an odds ratio of 0.3. Which reading is right?
Show the answer
Answer: a
A mixed model's ratios are conditional on the random effect. The population-level ratio is closer to 1, and a change in odds isn't a change in probability.
Check yourself
A logistic mixed model has a random-effect variance of 0.91. Using 3.29 for the latent residual variance, what's the ICC? Give two decimals.
Show the answer
Answer: 0.216222804615503
0.91 / (0.91 + 3.29) ≈ 0.22. On the latent scale, about a fifth of the unexplained variance is between patients.
Check yourself
A row records 7 defects in 200 items, for each machine in each week. How do you set up the mixed model?
Show the answer
Answer: b
Trials tell the model how much information each row holds. A rate of 7/200 and a rate of 1/29 aren't equally informative.
Check yourself
A Poisson mixed model reports a dispersion of 3. What should you do?
Show the answer
Answer: b
A dispersion well above 1 means rows vary more than the conditional Poisson model allows, so its standard errors are too small.
Fit yours
In the appSet Outcome model to binomial or Poisson. Add Trials for successes out of a total, or Exposure for rates. Set Event (modeled level) for a yes-or-no outcome, so you know what the odds are odds of.
import pandas as pd
from statsmodels.genmod.bayes_mixed_glm import BinomialBayesMixedGLM
df = pd.read_csv("s1_visits.csv").rename(columns={"adverse event": "event"}).dropna()
df["event"] = df["event"].astype(int)
model = BinomialBayesMixedGLM.from_formula(
"event ~ visit + treatment + age", {"patient": "0 + C(patient)"}, df)
fit = model.fit_vb()
print(fit.summary())library(lme4)
df <- read.csv("s1_visits.csv", check.names = FALSE)
names(df)[names(df) == "adverse event"] <- "event"
df$event <- as.integer(df$event == "true")
fit <- glmer(event ~ visit + treatment + age + (1 | patient), data = df, family = binomial)
summary(fit)
exp(fixef(fit)) # subject-specific odds ratiosstatsmodels has no Laplace fit for this model, so that script uses a variational Bayes approximation. Its numbers are close to glmer's but not the same. The CodeSplash Python engine runs its own twin of glmer, which is why the card agrees in both engines.
Recap
Recap- A GLMM puts random effects inside a link, and it's fitted by an approximation.
- Its ratios are for one group member, not for the population as a whole.
- A logistic ICC is on a latent scale, with residual variance .
- Mixed count models can still be overdispersed, so check the dispersion.
Concepts in this lesson