Skip to content

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.

Advanced ~12 min10 steps

What runs in CodeSplash

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

Read first

02

Read the card

In the app
Generalized linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 77 values compared · largest relative difference 1.1e-4
R

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

Plots

Random effects (conditional modes, link scale)How much do groups differ in a mixed model, and which deviate clearly from the average?
View data
Conditional modeLevelhighlowTerm
0.8405P011.948−0.2674patient: (Intercept)
0.0062P021.111−1.099patient: (Intercept)
−0.1763P031.290−1.643patient: (Intercept)
−0.4103P040.7568−1.577patient: (Intercept)
−0.0891P051.012−1.190patient: (Intercept)
1.333P062.4740.1910patient: (Intercept)
−0.0742P071.027−1.175patient: (Intercept)
0.3970P081.491−0.6971patient: (Intercept)
−1.041P090.1395−2.222patient: (Intercept)
1.291P102.4370.1449patient: (Intercept)
−0.5103P110.6224−1.643patient: (Intercept)
0.0062P121.111−1.099patient: (Intercept)
−0.0354P131.067−1.138patient: (Intercept)
0.8701P141.976−0.2362patient: (Intercept)
0.4030P151.497−0.6910patient: (Intercept)
−0.4935P160.6409−1.628patient: (Intercept)
−0.9958P170.1927−2.184patient: (Intercept)
−1.018P180.1662−2.203patient: (Intercept)
0.3667P191.461−0.7276patient: (Intercept)
−0.1131P200.9868−1.213patient: (Intercept)
−0.5103P210.6224−1.643patient: (Intercept)
−0.5188P220.6131−1.651patient: (Intercept)
−0.4991P230.6348−1.633patient: (Intercept)
0.4030P241.497−0.6910patient: (Intercept)
−0.9983P250.1898−2.186patient: (Intercept)
0.8111P261.921−0.2985patient: (Intercept)
0.4061P271.500−0.6880patient: (Intercept)
−0.0265P281.077−1.130patient: (Intercept)
0.4151P291.509−0.6789patient: (Intercept)
0.3819P301.476−0.7123patient: (Intercept)
−0.5151P310.7894−1.819patient: (Intercept)
−0.5389P320.7578−1.836patient: (Intercept)
−0.5352P330.7627−1.833patient: (Intercept)
0.5564P341.707−0.5937patient: (Intercept)
1.487P352.5820.3926patient: (Intercept)
0.0420P361.255−1.171patient: (Intercept)
0.0206P371.229−1.188patient: (Intercept)
0.5291P381.676−0.6177patient: (Intercept)
0.0420P391.255−1.171patient: (Intercept)
0.0562P401.272−1.160patient: (Intercept)
−0.5315P410.7676−1.831patient: (Intercept)
0.0278P421.238−1.182patient: (Intercept)
−0.5672P430.7206−1.855patient: (Intercept)
0.0444P441.258−1.169patient: (Intercept)
−0.5711P450.7156−1.858patient: (Intercept)
0.5727P461.725−0.5794patient: (Intercept)
−0.5464P470.7479−1.841patient: (Intercept)
1.466P482.5610.3717patient: (Intercept)
−0.5315P490.7676−1.831patient: (Intercept)
0.5319P501.679−0.6153patient: (Intercept)
0.5564P511.707−0.5937patient: (Intercept)
−0.5464P520.7479−1.841patient: (Intercept)
−0.5278P530.7724−1.828patient: (Intercept)
−0.5242P540.7773−1.826patient: (Intercept)
0.0349P551.246−1.177patient: (Intercept)
0.5099P561.655−0.6347patient: (Intercept)
0.5537P571.704−0.5961patient: (Intercept)
0.0110P581.218−1.196patient: (Intercept)
0.0467P591.261−1.167patient: (Intercept)
0.5264P601.673−0.6201patient: (Intercept)
Odds ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Odds ratiohighTermlow
1.4901.775visit1.251
0.29960.5775treatment: drug0.1555
1.0061.044age0.9690
Simulated residuals against the uniform distributionIs a variable (or a set of residuals) approximately normal, and where does it depart?
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.

Simulated residuals against the population-level prediction (rank)How do two numeric variables move together?
View data
Population-level prediction (rank, 0–1)Scaled residual
0.44070.7746
0.64070.4778
0.76610.9932
0.86440.7464
0.96270.4781
0.31530.0810
0.51360.9071
0.71020.2831
0.80850.4515
0.90680.5123
0.31530.5549
0.58470.6849
0.72710.0451
0.82540.3233
0.92370.3427
0.49830.3539
0.69830.1334
0.79660.9568
0.89490.4240
0.99320.9980
0.35930.9503
0.55590.8422
0.71860.8813
0.81690.7586
0.91530.7756
0.48140.4245
0.68140.6941
0.78640.3560
0.88470.8420
0.98310.1608
0.43390.3787
0.63390.9088
0.75930.6565
0.85760.2840
0.95590.5448
0.50170.0323
0.70170.5848
0.80000.1958
0.89830.1798
0.99660.3354
0.47460.8588
0.67460.7867
0.78310.8550
0.88140.7698
0.97970.9145
0.44070.6230
0.64070.3467
0.76610.4586
0.86440.2623
0.96270.7182
0.31530.7472
0.51360.9036
0.71020.2026
0.80850.6352
0.90680.0112
0.40000.4320
0.60000.4599
0.73560.6455
0.83390.4323
0.93220.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

TermB (link scale)SEzpOdds ratio90% CI low90% CI high
(Intercept)−1.4531.260−1.153.2490.23390.02951.857
visit0.39860.10643.747< .0011.4901.2511.775
treatment: drug−1.2050.3989−3.021.0030.29960.15550.5775
age0.00590.02270.2595.7951.0060.96901.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

TermWald χ²dfp
visit14.0371< .001
treatment9.1281.003
age0.06731.795

Random effects (link scale)

GroupEffectVarianceSDCorrelation
patient(Intercept)0.90760.9527—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
patient(Intercept)P010.84050.6736
patient(Intercept)P020.00620.6717
patient(Intercept)P03−0.17630.8915
patient(Intercept)P04−0.41030.7095
patient(Intercept)P05−0.08910.6692
patient(Intercept)P061.3330.6940
patient(Intercept)P07−0.07420.6695
patient(Intercept)P080.39700.6652
patient(Intercept)P09−1.0410.7179
patient(Intercept)P101.2910.6969
patient(Intercept)P11−0.51030.6887
patient(Intercept)P120.00620.6717
patient(Intercept)P13−0.03540.6705
patient(Intercept)P140.87010.6726
patient(Intercept)P150.40300.6652
patient(Intercept)P16−0.49350.6897
patient(Intercept)P17−0.99580.7226
patient(Intercept)P18−1.0180.7202
patient(Intercept)P190.36670.6653
patient(Intercept)P20−0.11310.6687
patient(Intercept)P21−0.51030.6887
patient(Intercept)P22−0.51880.6882
patient(Intercept)P23−0.49910.6893
patient(Intercept)P240.40300.6652
patient(Intercept)P25−0.99830.7223
patient(Intercept)P260.81110.6746
patient(Intercept)P270.40610.6651
patient(Intercept)P28−0.02650.6707
patient(Intercept)P290.41510.6651
patient(Intercept)P300.38190.6652
patient(Intercept)P31−0.51510.7930
patient(Intercept)P32−0.53890.7883
patient(Intercept)P33−0.53520.7891
patient(Intercept)P340.55640.6992
patient(Intercept)P351.4870.6656
patient(Intercept)P360.04200.7375
patient(Intercept)P370.02060.7348
patient(Intercept)P380.52910.6972
patient(Intercept)P390.04200.7375
patient(Intercept)P400.05620.7392

First 40 of 60 rows.

Simulated residual checks (DHARMa)

CheckStatisticp
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
))
Python

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

TermB (link scale)SEzpOdds ratio90% CI low90% CI high
(Intercept)−1.4531.260−1.153.2490.23390.02941.857
visit0.39860.10643.747< .0011.4901.2511.775
treatment: drug−1.2050.3989−3.021.0030.29960.15550.5775
age0.00590.02270.2595.7951.0060.96901.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

TermWald χ²dfp
visit14.0371< .001
treatment9.1271.003
age0.06731.795

Random effects (link scale)

GroupEffectVarianceSDCorrelation
patient(Intercept)0.90760.9527—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
patient(Intercept)P010.84050.6736
patient(Intercept)P020.00620.6717
patient(Intercept)P03−0.17630.8915
patient(Intercept)P04−0.41030.7095
patient(Intercept)P05−0.08910.6692
patient(Intercept)P061.3330.6940
patient(Intercept)P07−0.07420.6695
patient(Intercept)P080.39700.6652
patient(Intercept)P09−1.0410.7179
patient(Intercept)P101.2910.6969
patient(Intercept)P11−0.51030.6887
patient(Intercept)P120.00620.6717
patient(Intercept)P13−0.03540.6705
patient(Intercept)P140.87010.6726
patient(Intercept)P150.40300.6652
patient(Intercept)P16−0.49350.6897
patient(Intercept)P17−0.99580.7226
patient(Intercept)P18−1.0180.7202
patient(Intercept)P190.36670.6653
patient(Intercept)P20−0.11310.6687
patient(Intercept)P21−0.51030.6887
patient(Intercept)P22−0.51880.6882
patient(Intercept)P23−0.49910.6893
patient(Intercept)P240.40300.6652
patient(Intercept)P25−0.99830.7223
patient(Intercept)P260.81110.6746
patient(Intercept)P270.40610.6651
patient(Intercept)P28−0.02650.6707
patient(Intercept)P290.41510.6651
patient(Intercept)P300.38190.6652
patient(Intercept)P31−0.51510.7930
patient(Intercept)P32−0.53890.7883
patient(Intercept)P33−0.53520.7891
patient(Intercept)P340.55640.6992
patient(Intercept)P351.4870.6656
patient(Intercept)P360.04200.7375
patient(Intercept)P370.02060.7348
patient(Intercept)P380.52910.6972
patient(Intercept)P390.04200.7375
patient(Intercept)P400.05620.7392

First 40 of 60 rows.

Simulated residual checks (DHARMa)

CheckStatisticp
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 χ2\chi^2(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.

03

An ICC with no residual

Predict

A logistic model has no residual variance to divide by. So the ICC uses the variance of the logistic distribution on the latent scale, π2/3\pi^2/3, 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.

04

One patient, or the whole population?

Predict

Predict 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?

Closer to 1The sameFurther from 1
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.

05

Successes out of trials

Read

Sometimes 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.

Generalized linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 75 values compared · largest relative difference 1.9e-5
R

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

Random effects (conditional modes, link scale)How much do groups differ in a mixed model, and which deviate clearly from the average?
View data
Conditional modeLevelhighlowTerm
0.590011.273−0.0926herd: (Intercept)
−0.298920.4176−1.015herd: (Intercept)
0.406330.9890−0.1765herd: (Intercept)
0.039340.8554−0.7768herd: (Intercept)
−0.190050.4968−0.8768herd: (Intercept)
−0.400360.3444−1.145herd: (Intercept)
0.889471.5290.2495herd: (Intercept)
0.599481.229−0.0300herd: (Intercept)
−0.237790.6667−1.142herd: (Intercept)
−0.5409100.1856−1.267herd: (Intercept)
−0.0846110.5212−0.6905herd: (Intercept)
−0.0648120.7998−0.9294herd: (Intercept)
−0.6899130.0643−1.444herd: (Intercept)
0.9707141.6670.2741herd: (Intercept)
−0.5305150.2490−1.310herd: (Intercept)
Odds ratiosHow large are several estimates, how precise, and which exclude the null?
View data
Odds ratiohighTermlow
0.37070.6762period: 20.2032
0.32350.6136period: 30.1705
0.20590.4759period: 40.0891
Simulated residuals against the uniform distributionIs a variable (or a set of residuals) approximately normal, and where does it depart?
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
Simulated residuals against the population-level prediction (rank)How do two numeric variables move together?
View data
Population-level prediction (rank, 0–1)Scaled residual
0.80360.4850
0.39290.9224
0.25000.9941
0.10710.2038
0.94640.3964
0.60710.5158
0.62500.2896
0.94640.8533
0.55360.6665
0.48210.1088
0.36610.7598
0.72320.6367
0.33040.0247
0.25000.9210
0.15180.6597
0.85710.6573
0.76790.0534
0.66070.1726
0.05360.8190
0.83930.4794
0.58930.2378
0.52680.1197
0.36610.6866
0.82140.9637
0.33040.4250
0.25000.9699
0.10710.4722
10.8975
0.67860.5850
0.19640.1823
0.21430.0799
0.15180.4311
0.94640.0675
0.69640.3464
0.52680.2486
0.41960.7444
0.98210.0144
0.78570.8372
0.64290.7718
0.41960.6027
0.72320.6012
0.28570.6702
0.17860.5828
0.10710.2412
0.91070.0362
0.75000.4735
0.57140.2437
0.46430.2522
0.88390.9700
0.03570.0760
0.07140.0901
0.01790.0516
0.88390.1323
0.50000.3427
0.44640.6209
0.30360.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

TermB (link scale)SEzpOdds ratio95% CI low95% CI high
(Intercept)−1.3990.2325−6.016< .0010.24700.15660.3895
period: 2−0.99230.3066−3.236.0010.37070.20320.6762
period: 3−1.1290.3266−3.455< .0010.32350.17050.6136
period: 4−1.5800.4274−3.697< .0010.20590.08910.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

TermWald χ²dfp
period24.9493< .001

Random effects (link scale)

GroupEffectVarianceSDCorrelation
herd(Intercept)0.41250.6423—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
herd(Intercept)10.59000.3483
herd(Intercept)2−0.29890.3656
herd(Intercept)30.40630.2973
herd(Intercept)40.03930.4164
herd(Intercept)5−0.19000.3504
herd(Intercept)6−0.40030.3800
herd(Intercept)70.88940.3265
herd(Intercept)80.59940.3211
herd(Intercept)9−0.23770.4614
herd(Intercept)10−0.54090.3707
herd(Intercept)11−0.08460.3091
herd(Intercept)12−0.06480.4411
herd(Intercept)13−0.68990.3848
herd(Intercept)140.97070.3554
herd(Intercept)15−0.53050.3977

Simulated residual checks (DHARMa)

CheckStatisticp
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)01.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
))
Python

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

TermB (link scale)SEzpOdds ratio95% CI low95% CI high
(Intercept)−1.3990.2325−6.016< .0010.24700.15660.3895
period: 2−0.99230.3066−3.236.0010.37070.20320.6762
period: 3−1.1290.3266−3.455< .0010.32350.17050.6136
period: 4−1.5800.4274−3.697< .0010.20590.08910.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

TermWald χ²dfp
period24.9493< .001

Random effects (link scale)

GroupEffectVarianceSDCorrelation
herd(Intercept)0.41250.6423—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
herd(Intercept)10.59000.3483
herd(Intercept)2−0.29890.3656
herd(Intercept)30.40630.2973
herd(Intercept)40.03930.4164
herd(Intercept)5−0.19000.3504
herd(Intercept)6−0.40030.3800
herd(Intercept)70.88940.3265
herd(Intercept)80.59940.3211
herd(Intercept)9−0.23770.4614
herd(Intercept)10−0.54090.3707
herd(Intercept)11−0.08460.3091
herd(Intercept)12−0.06480.4411
herd(Intercept)13−0.68990.3848
herd(Intercept)140.97070.3554
herd(Intercept)15−0.53050.3977

Simulated residual checks (DHARMa)

CheckStatisticp
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)01.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: χ2\chi^2(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.

06

Counts, with two levels

Predict

Predict 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?

Random effects remove itIt can remainPoisson can't have it here
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.

Generalized linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 79 values compared · largest relative difference 3.2e-4
R

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

TermB (link scale)SEzpRate ratio95% CI low95% CI high
(Intercept)0.46690.19202.431.0151.5951.0952.324
year: 961.1660.22985.072< .0013.2082.0455.033
year: 97−0.97790.2548−3.838< .0010.37610.22820.6197
height (z)−0.84660.1246−6.795< .0010.42890.33590.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

TermWald χ²dfp
year81.4622< .001
height (z)46.1731< .001

Random effects (link scale)

GroupEffectVarianceSDCorrelation
location:brood(Intercept)0.59240.7697—
location(Intercept)0.32960.5741—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
location:brood(Intercept)1:6310.05580.4191
location:brood(Intercept)1:722−0.44440.5149
location:brood(Intercept)2:723−0.23220.5359
location:brood(Intercept)3:601−1.3380.4869
location:brood(Intercept)4:5170.89950.3411
location:brood(Intercept)4:6320.55970.3299
location:brood(Intercept)4:718−0.22180.3880
location:brood(Intercept)4:719−0.32050.3838
location:brood(Intercept)5:6340.06790.4686
location:brood(Intercept)6:602−0.07370.4639
location:brood(Intercept)7:5160.08890.4116
location:brood(Intercept)7:5181.7310.3991
location:brood(Intercept)8:608−0.24630.4827
location:brood(Intercept)9:5210.55540.4712
location:brood(Intercept)10:607−0.30960.4827
location:brood(Intercept)10:720−0.10170.5640
location:brood(Intercept)11:5190.44580.3889
location:brood(Intercept)11:6360.18720.3991
location:brood(Intercept)11:7210.16630.5285
location:brood(Intercept)12:650−0.66410.4908
location:brood(Intercept)13:515−0.56150.4426
location:brood(Intercept)13:5200.85430.3957
location:brood(Intercept)13:635−0.38010.4450
location:brood(Intercept)14:514−0.37190.4180
location:brood(Intercept)14:6030.31640.3590
location:brood(Intercept)14:606−0.04910.3572
location:brood(Intercept)14:742−0.58040.6252
location:brood(Intercept)15:7390.04050.5237
location:brood(Intercept)15:741−0.46320.5832
location:brood(Intercept)16:7240.86900.4899
location:brood(Intercept)17:5130.13910.4966
location:brood(Intercept)18:651−0.34210.4864
location:brood(Intercept)19:5330.89690.3227
location:brood(Intercept)19:535−0.47450.5560
location:brood(Intercept)19:628−0.25250.3605
location:brood(Intercept)19:647−0.38400.3684
location:brood(Intercept)19:7080.67720.3674
location:brood(Intercept)19:7330.41550.4875
location:brood(Intercept)19:740−0.66400.6079
location:brood(Intercept)20:6480.17340.4685

First 40 of 181 rows.

Simulated residual checks (DHARMa)

CheckStatisticp
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
))
Python

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

TermB (link scale)SEzpRate ratio95% CI low95% CI high
(Intercept)0.46690.19202.431.0151.5951.0952.324
year: 961.1660.22985.072< .0013.2082.0455.033
year: 97−0.97790.2548−3.838< .0010.37610.22820.6197
height (z)−0.84660.1246−6.795< .0010.42890.33590.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

TermWald χ²dfp
year81.4602< .001
height (z)46.1721< .001

Random effects (link scale)

GroupEffectVarianceSDCorrelation
location(Intercept)0.32960.5741—
location:brood(Intercept)0.59240.7697—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
location(Intercept)1−0.21630.4133
location(Intercept)2−0.12920.4849
location(Intercept)3−0.74480.4686
location(Intercept)40.51020.3267
location(Intercept)50.03780.4628
location(Intercept)6−0.04100.4614
location(Intercept)71.0130.3974
location(Intercept)8−0.13710.4673
location(Intercept)90.30910.4636
location(Intercept)10−0.22890.4318
location(Intercept)110.44470.3709
location(Intercept)12−0.36960.4699
location(Intercept)13−0.04850.3679
location(Intercept)14−0.38120.3454
location(Intercept)15−0.23520.4436
location(Intercept)160.48360.4696
location(Intercept)170.07740.4718
location(Intercept)18−0.19040.4685
location(Intercept)190.11940.2911
location(Intercept)200.09650.4628
location(Intercept)21−0.26070.4879
location(Intercept)220.33200.4121
location(Intercept)230.44410.3980
location(Intercept)240.80230.4606
location(Intercept)250.42180.4265
location(Intercept)260.29210.4693
location(Intercept)27−0.33280.4771
location(Intercept)280.27070.3058
location(Intercept)29−0.36740.4724
location(Intercept)30−0.05270.4049
location(Intercept)31−0.09460.4387
location(Intercept)32−0.36000.5201
location(Intercept)330.03880.4829
location(Intercept)34−0.41770.4830
location(Intercept)35−0.11830.5480
location(Intercept)360.11000.3419
location(Intercept)37−0.20800.4214
location(Intercept)38−0.20300.4963
location(Intercept)390.21800.4991
location(Intercept)400.22940.4636

First 40 of 181 rows.

Simulated residual checks (DHARMa)

CheckStatisticp
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.

07

How far to trust the approximation

Reflect

The 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?

08

Check your understanding

Checkpoint

Check 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.

09

Fit yours

In the app

Set 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.

Python
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())
R
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 ratios

statsmodels 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.

10

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 π2/3\pi^2/3.
  • Mixed count models can still be overdispersed, so check the dispersion.

Concepts in this lesson