Skip to content

Nested and crossed grouping factors

Classes sit inside schools, while every rater scores every item. Those two structures need different models, and repeated labels can quietly turn one into the other.

Advanced ~10 min10 steps

What runs in CodeSplash

You will be able to

  • Tell nested factors from crossed ones by how the data were collected
  • Spot labels that repeat across groups
  • Divide variance among sources and say where it mostly lies
  • Decide what to do with a grouping factor that has few levels

Read first

01

Two shapes of data

Read

Factors are nestedNested factorsEach level of one factor belongs to exactly one level of another, as classes do in schools. when each level of one belongs to exactly one level of another: classes in schools, patients in clinics.

Factors are crossedCrossed factorsLevels of two factors combine freely, as when every rater scores every item. when levels combine freely: every rater scores every item, or every plate gets every sample.

The difference is in how the data were collected. You can't read it from the column names.

02

Which is which?

Predict

Predict first

An experiment tests how strongly a paste binds. There are 10 delivery batches, and 30 casks in all, each from one batch. Are casks and batches nested or crossed?

NestedCrossedNeither
Reveal

Nested: a cask comes from one batch. The model estimates variance between batches, between casks within a batch, and among repeat tests of one cask.

03

Read the nested card

In the app
Linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 39 values compared · largest relative difference 2.4e-7
R

Linear mixed model (REML) of strength (n = 60, 10 levels of batch). Adjusted ICC = 0.94; marginal R² = 0.00, conditional R² = 0.94.

ICC (adjusted)
0.9370
R² marginal
0
R² conditional
0.9370
Residual SD
0.8234
AIC
254.99
Random effects LR test p
< .001

Plots

Random effects (conditional modes)How much do groups differ in a mixed model, and which deviate clearly from the average?
View data
Conditional modeLevelhighlowTerm
1.775A:a4.012−0.4630batch:cask: (Intercept)
0.3327A:b2.570−1.905batch:cask: (Intercept)
1.967A:c4.205−0.2708batch:cask: (Intercept)
0.8837B:a3.121−1.354batch:cask: (Intercept)
−2.481B:b−0.2434−4.719batch:cask: (Intercept)
0.2107B:c2.448−2.027batch:cask: (Intercept)
−2.572C:a−0.3345−4.810batch:cask: (Intercept)
2.619C:b4.8570.3814batch:cask: (Intercept)
3.629C:c5.8661.391batch:cask: (Intercept)
−3.053D:a−0.8151−5.291batch:cask: (Intercept)
−2.091D:b0.1463−4.329batch:cask: (Intercept)
4.494D:c6.7322.256batch:cask: (Intercept)
−3.318E:a−1.080−5.555batch:cask: (Intercept)
−3.942E:b−1.705−6.180batch:cask: (Intercept)
−0.3854E:c1.852−2.623batch:cask: (Intercept)
3.598F:a5.8351.360batch:cask: (Intercept)
−1.642F:b0.5959−3.880batch:cask: (Intercept)
−0.1517F:c2.086−2.389batch:cask: (Intercept)
2.454G:a4.6910.2158batch:cask: (Intercept)
−0.1422G:b2.096−2.380batch:cask: (Intercept)
−2.594G:c−0.3559−4.831batch:cask: (Intercept)
−1.790H:a0.4482−4.027batch:cask: (Intercept)
4.267H:b6.5052.029batch:cask: (Intercept)
3.161H:c5.3990.9237batch:cask: (Intercept)
−4.574I:a−2.336−6.812batch:cask: (Intercept)
4.271I:b6.5082.033batch:cask: (Intercept)
−2.219I:c0.0192−4.456batch:cask: (Intercept)
−0.6937J:a1.544−2.931batch:cask: (Intercept)
−0.3092J:b1.929−2.547batch:cask: (Intercept)
−1.703J:c0.5346−3.941batch:cask: (Intercept)
0.8006A2.816−1.215batch: (Intercept)
−0.2725B1.743−2.288batch: (Intercept)
0.7223C2.738−1.294batch: (Intercept)
−0.1278D1.888−2.144batch: (Intercept)
−1.502E0.5134−3.518batch: (Intercept)
0.3545F2.370−1.661batch: (Intercept)
−0.0555G1.960−2.071batch: (Intercept)
1.108H3.124−0.9077batch: (Intercept)
−0.4956I1.520−2.511batch: (Intercept)
−0.5318J1.484−2.548batch: (Intercept)
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
FittedResidual
62.6290.1713
62.629−0.0287
61.187−1.087
61.1871.113
62.821−0.1209
62.8210.2791
60.664−0.6645
60.6640.7355
57.3000.2003
57.300−0.3997
59.9921.108
59.992−1.092
58.2030.4966
58.203−0.7034
63.3950.5053
63.395−0.2947
64.4040.9959
64.404−0.7041
56.8730.2273
56.873−0.4727
57.834−0.9341
57.8340.7659
64.4190.2806
64.4190.0806
55.233−0.1334
55.233−0.1334
54.6080.0915
54.608−0.4085
58.1650.6345
58.165−0.6655
64.005−0.6054
64.0050.8946
58.7660.5340
58.766−0.6660
60.2560.2439
60.256−0.2561
62.4510.0486
62.4510.1486
59.8561.144
59.856−1.156
57.404−0.5043
57.4040.2957
59.372−0.1719
59.3720.0281
65.428−0.2285
65.4280.5715
64.3230.4771
64.323−0.2229
54.984−0.1839
54.984−0.1839
63.8280.1717
63.8280.1717
57.3390.3608
57.339−0.5392
58.828−0.5279
58.8280.4721
59.212−0.0124
59.212−0.0124
57.8181.082
57.818−1.218

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.982, p = .513 on the conditional residuals.
  • Normal random effects (batch:cask: (Intercept)) — Shapiro–Wilk W = 0.948, p = .153 on 30 conditional modes.
  • Normal random effects (batch: (Intercept)) — Shapiro–Wilk W = 0.961, p = .796 on 10 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 10 levels of batch.

Fixed effects

TermBSEdftp95% CI low95% CI high
(Intercept)60.0530.67699.00088.722< .00158.52261.585

t tests with Satterthwaite degrees of freedom (lmerTest).

Random effects

GroupEffectVarianceSDCorrelation
batch:cask(Intercept)8.4342.904—
batch(Intercept)1.6571.287—
Residual0.67800.8234—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
batch:cask(Intercept)A:a1.7751.142
batch:cask(Intercept)A:b0.33271.142
batch:cask(Intercept)A:c1.9671.142
batch:cask(Intercept)B:a0.88371.142
batch:cask(Intercept)B:b−2.4811.142
batch:cask(Intercept)B:c0.21071.142
batch:cask(Intercept)C:a−2.5721.142
batch:cask(Intercept)C:b2.6191.142
batch:cask(Intercept)C:c3.6291.142
batch:cask(Intercept)D:a−3.0531.142
batch:cask(Intercept)D:b−2.0911.142
batch:cask(Intercept)D:c4.4941.142
batch:cask(Intercept)E:a−3.3181.142
batch:cask(Intercept)E:b−3.9421.142
batch:cask(Intercept)E:c−0.38541.142
batch:cask(Intercept)F:a3.5981.142
batch:cask(Intercept)F:b−1.6421.142
batch:cask(Intercept)F:c−0.15171.142
batch:cask(Intercept)G:a2.4541.142
batch:cask(Intercept)G:b−0.14221.142
batch:cask(Intercept)G:c−2.5941.142
batch:cask(Intercept)H:a−1.7901.142
batch:cask(Intercept)H:b4.2671.142
batch:cask(Intercept)H:c3.1611.142
batch:cask(Intercept)I:a−4.5741.142
batch:cask(Intercept)I:b4.2711.142
batch:cask(Intercept)I:c−2.2191.142
batch:cask(Intercept)J:a−0.69371.142
batch:cask(Intercept)J:b−0.30921.142
batch:cask(Intercept)J:c−1.7031.142
batch(Intercept)A0.80061.028
batch(Intercept)B−0.27251.028
batch(Intercept)C0.72231.028
batch(Intercept)D−0.12781.028
batch(Intercept)E−1.5021.028
batch(Intercept)F0.35451.028
batch(Intercept)G−0.05551.028
batch(Intercept)H1.1081.028
batch(Intercept)I−0.49561.028
batch(Intercept)J−0.53181.028
  • REML fit with lme4::lmer; fixed effects tested with Satterthwaite df (lmerTest).
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear mixed model (random intercepts and slopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.lmm 1.0.1 · spec 6984729286f1ff8b
# Dataset: s1_pastes (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)
  library(lmerTest)  # Satterthwaite degrees of freedom
})

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_pastes.parquet", col_select = c("strength", "batch", "cask")))
n_input <- nrow(df)
df[["batch"]] <- factor(df[["batch"]], levels = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J"))  # stored level order
df[["cask"]] <- factor(df[["cask"]], levels = c("a", "b", "c"))  # stored level order
df <- df[stats::complete.cases(df[c("strength", "batch", "cask")]), , 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("strength", "batch", "cask"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome <- "strength"
predictors <- c()
group <- "batch"
slopes <- c()
group2 <- "cask"
nesting <- "nested"  # nested: (1 | group/group2); crossed: (1 | group2)
correlated <- "correlated" == "correlated"  # (1 + x | g) vs (1 + x || g)
interactions <- "none"
reml <- "reml" == "reml"
conf <- 0.95
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
# 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)  # lme4's checks on the grouping factors
if (length(unique(df[[outcome]])) < 2) cs_error("CS_E_CONSTANT", column = outcome)
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)
# Tight optimizer tolerance so the variance parameters are found to ~1e-10 (lme4's default stops near 1e-5).
ctrl <- lmerControl(optimizer = "bobyqa", optCtrl = list(rhoend = 1e-12, maxfun = 1e6))

# %% Fit
fit <- lmerTest::lmer(fml, data = df, REML = reml, 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)
y <- df[[outcome]]
ct <- summary(fit)$coefficients  # Estimate, SE, df (Satterthwaite), t, p
values <- list()
coefs <- list()
for (j in seq_len(k)) {
  est <- ct[j, "Estimate"]; se <- ct[j, "Std. Error"]; ddf <- ct[j, "df"]; tval <- ct[j, "t value"]; pval <- ct[j, "Pr(>|t|)"]
  q <- qt(1 - (1 - conf) / 2, ddf)
  term <- terms_x[j]
  coefs[[j]] <- list(term = term, estimate = est, se = se, df = ddf, t = tval, p = pval, ci_low = est - q * se, ci_high = est + q * se)
  values[[sprintf("coef[%s]", term)]] <- est; values[[sprintf("se[%s]", term)]] <- se; values[[sprintf("df[%s]", term)]] <- ddf
  values[[sprintf("t[%s]", term)]] <- tval; values[[sprintf("p[%s]", term)]] <- pval
  values[[sprintf("ci_low[%s]", term)]] <- est - q * se; values[[sprintf("ci_high[%s]", term)]] <- est + q * se
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
  L <- diag(k)[blocks[[name]], , drop = FALSE]
  tt <- lmerTest::contest(fit, L, joint = TRUE)  # Satterthwaite F test of all the term's coefficients
  e <- list(term = name, f = tt[["F value"]], df1 = tt[["NumDF"]], df2 = tt[["DenDF"]], p = tt[["Pr(>F)"]])
  effects[[length(effects) + 1]] <- e
  values[[sprintf("f[%s]", name)]] <- e$f; values[[sprintf("f_df1[%s]", name)]] <- as.numeric(e$df1)
  values[[sprintf("f_df2[%s]", name)]] <- e$df2; values[[sprintf("f_p[%s]", name)]] <- e$p
}
values$focal_f <- NA; values$focal_df1 <- NA; values$focal_df2 <- NA; values$focal_p <- NA  # no fixed predictor
if (length(effects)) {
  values$focal_f <- effects[[1]]$f; values$focal_df1 <- as.numeric(effects[[1]]$df1)
  values$focal_df2 <- effects[[1]]$df2; values$focal_p <- effects[[1]]$p
}

# %% Variance components, ICC and R² (Nakagawa; random slopes as Johnson 2014)
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]
  }
}
sig <- sigma(fit)
sigma2 <- sig^2
var_fixed <- if (n > 1) var(as.vector(X %*% fixef(fit))) else 0
var_random <- cs_mixed_random_variance(fit, df)
icc <- var_random / (var_random + sigma2)
total <- var_fixed + var_random + sigma2
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta + 1
crit <- if (reml) REMLcrit(fit) else deviance(fit)
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, sigma = sig, log_lik = as.numeric(logLik(fit)), deviance = crit,
                         aic = crit + 2 * n_params, bic = crit + log(n) * n_params, icc = icc, r2_marginal = var_fixed / total,
                         r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random,
                         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, reml = reml))
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, ML)
if (TRUE) {
  ml <- if (reml) update(fit, REML = FALSE) else fit
  fixed_fml <- if (length(predictors)) cs_model_formula(outcome, predictors, interactions) else stats::as.formula(paste0("`", outcome, "` ~ 1"))
  ll_lm <- as.numeric(logLik(lm(fixed_fml, data = df)))
  lrt <- max(2 * (as.numeric(logLik(ml)) - ll_lm), 0)
  lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
  if (n_theta == 1) lrt_p <- lrt_p / 2  # one variance component on its 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
assumptions <- list()
resid <- residuals(fit)
if (n >= 3 && n <= 5000) {
  sw <- shapiro.test(resid)
  values$sw_p_resid <- sw$p.value
  status <- if (sw$p.value >= 0.05) "pass" else if (n < 300) "warn" else "info"
  assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normal residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
    detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s on the conditional residuals", sw$statistic, cs_fmt_p(sw$p.value)),
                    if (n >= 300) " (with many rows small departures are flagged; look at the Q–Q plot)." else "."))
}
re_tab <- cs_mixed_ranef(fit, valid)
for (key in unique(paste(re_tab$group, re_tab$effect, sep = "\r"))) {
  sel <- paste(re_tab$group, re_tab$effect, sep = "\r") == key
  b <- re_tab$estimate[sel]
  if (length(b) >= 8 && diff(range(b)) > 0) {
    swr <- shapiro.test(b)
    assumptions[[length(assumptions) + 1]] <- list(key = "re_normality", label = sprintf("Normal random effects (%s: %s)", re_tab$group[sel][1], re_tab$effect[sel][1]),
      status = if (swr$p.value >= 0.05) "pass" else "warn", statistic = unname(swr$statistic), p = swr$p.value,
      detail = sprintf("Shapiro–Wilk W = %.3f, %s on %d conditional modes.", swr$statistic, cs_fmt_p(swr$p.value), length(b)))
  }
}
singular <- isTRUE(values$singular)
assumptions[[length(assumptions) + 1]] <- 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 (drop a slope or the correlation)." 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[[length(assumptions) + 1]] <- 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))

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
slopes_tab <- if (length(terms_x) && terms_x[1] == "(Intercept)") coefs[-1] else coefs
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])
})
vc_rows[[length(vc_rows) + 1]] <- list(group = "Residual", effect = "", variance = sigma2, sd = sig, cor = NULL)
tests_text <- if (length(effects)) sprintf(" %s: F(%d, %.1f) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df1), effects[[1]]$df2, effects[[1]]$f, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("Linear mixed model (%s) of %s (n = %d, %d levels of %s).%s Adjusted ICC = %.2f; marginal R² = %.2f, conditional R² = %.2f.",
                   if (reml) "REML" else "ML", outcome, n, n_groups, group, tests_text, icc, var_fixed / total, (var_fixed + var_random) / total)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(
  cs_chart("ranef", "caterpillar", "Random effects (conditional modes)", 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"))),
  cs_chart("residuals", "residual-panel", "Residual diagnostics", list(fitted = cs_col("Fitted", unname(fitted(fit))), residual = cs_col("Residual", unname(resid))))
)
if (length(slopes_tab)) {
  charts[[length(charts) + 1]] <- cs_chart("coef", "forest", "Fixed effects", list(
    label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Estimate", vapply(slopes_tab, `[[`, 0, "estimate")),
    low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ci_high"))), controls = list(reference = 0))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
  list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
  list(key = "df", label = "df", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
  list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
  rows = coefs, note = "t tests with Satterthwaite degrees of freedom (lmerTest)."))
if (length(effects)) {
  tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint tests of each predictor", columns = list(
    list(key = "term", label = "Term", type = "string"), list(key = "f", label = "F", type = "number"), list(key = "df1", label = "num df", type = "integer"),
    list(key = "df2", label = "den df", type = "number"), list(key = "p", label = "p", type = "pvalue")),
    rows = effects, note = "All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).")
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects", 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)
statistics <- list(list(key = "icc", label = "ICC (adjusted)", value = icc), list(key = "r2_marginal", label = "R² marginal", value = var_fixed / total),
                   list(key = "r2_conditional", label = "R² conditional", value = (var_fixed + var_random) / total), list(key = "sigma", label = "Residual SD", value = sig),
                   list(key = "aic", label = "AIC", value = crit + 2 * n_params))
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.lmm",
  methodVersion = "1.0.1",
  title = "Linear mixed model",
  engine = cs_engine_info("lme4", "lmerTest", "nanoparquet"),
  n = n,
  summary = summary,
  apa = if (length(effects)) sprintf("F(%d, %.2f) = %.2f, %s", as.integer(effects[[1]]$df1), effects[[1]]$df2, effects[[1]]$f, cs_fmt_p(effects[[1]]$p)) else "",
  statistics = statistics,
  tables = tables,
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%s fit with lme4::lmer; fixed effects tested with Satterthwaite df (lmerTest).", if (reml) "REML" else "Maximum likelihood")),
  charts = charts,
  values = values
))
Python

Linear mixed model (REML) of strength (n = 60, 10 levels of batch). Adjusted ICC = 0.94; marginal R² = 0.00, conditional R² = 0.94.

ICC (adjusted)
0.9370
R² marginal
4.768e-30
R² conditional
0.9370
Residual SD
0.8234
AIC
254.99
Random effects LR test p
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.982, p = .513 on the conditional residuals.
  • Normal random effects (batch: (Intercept)) — Shapiro–Wilk W = 0.961, p = .796 on 10 conditional modes.
  • Normal random effects (batch:cask: (Intercept)) — Shapiro–Wilk W = 0.948, p = .153 on 30 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 10 levels of batch.

Fixed effects

TermBSEdftp95% CI low95% CI high
(Intercept)60.0530.67699.00088.722< .00158.52261.585

t tests with Satterthwaite degrees of freedom (lmerTest).

Random effects

GroupEffectVarianceSDCorrelation
batch(Intercept)1.6571.287—
batch:cask(Intercept)8.4342.904—
Residual0.67800.8234—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
batch(Intercept)A0.80061.028
batch(Intercept)B−0.27251.028
batch(Intercept)C0.72231.028
batch(Intercept)D−0.12781.028
batch(Intercept)E−1.5021.028
batch(Intercept)F0.35451.028
batch(Intercept)G−0.05551.028
batch(Intercept)H1.1081.028
batch(Intercept)I−0.49561.028
batch(Intercept)J−0.53181.028
batch:cask(Intercept)A:a1.7751.142
batch:cask(Intercept)A:b0.33271.142
batch:cask(Intercept)A:c1.9671.142
batch:cask(Intercept)B:a0.88371.142
batch:cask(Intercept)B:b−2.4811.142
batch:cask(Intercept)B:c0.21071.142
batch:cask(Intercept)C:a−2.5721.142
batch:cask(Intercept)C:b2.6191.142
batch:cask(Intercept)C:c3.6291.142
batch:cask(Intercept)D:a−3.0531.142
batch:cask(Intercept)D:b−2.0911.142
batch:cask(Intercept)D:c4.4941.142
batch:cask(Intercept)E:a−3.3181.142
batch:cask(Intercept)E:b−3.9421.142
batch:cask(Intercept)E:c−0.38541.142
batch:cask(Intercept)F:a3.5981.142
batch:cask(Intercept)F:b−1.6421.142
batch:cask(Intercept)F:c−0.15171.142
batch:cask(Intercept)G:a2.4541.142
batch:cask(Intercept)G:b−0.14221.142
batch:cask(Intercept)G:c−2.5941.142
batch:cask(Intercept)H:a−1.7901.142
batch:cask(Intercept)H:b4.2671.142
batch:cask(Intercept)H:c3.1611.142
batch:cask(Intercept)I:a−4.5741.142
batch:cask(Intercept)I:b4.2711.142
batch:cask(Intercept)I:c−2.2191.142
batch:cask(Intercept)J:a−0.69371.142
batch:cask(Intercept)J:b−0.30921.142
batch:cask(Intercept)J:c−1.7031.142
  • REML fit of lme4's model (twin of lme4's profiled deviance); fixed effects tested with Satterthwaite df (lmerTest).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear mixed model (random intercepts and slopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.lmm 1.0.1 · spec 6984729286f1ff8b
# Dataset: s1_pastes (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 + lmerTest (statsmodels' MixedLM has no Satterthwaite df)
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_pastes.parquet", columns=["strength", "batch", "cask"])
n_input = len(df)
df["batch"] = pd.Categorical(df["batch"], categories=["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"])  # stored level order
df["cask"] = pd.Categorical(df["cask"], categories=["a", "b", "c"])  # stored level order
df = df.dropna(subset=["strength", "batch", "cask"])  # listwise deletion over the analysis columns
df["batch"] = df["batch"].cat.remove_unused_categories()
df["cask"] = df["cask"].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, ["strength", "batch", "cask"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome = "strength"
predictors = []
group = "batch"
slopes = []
group2 = "cask"
nesting = "nested"  # nested: (1 | group/group2); crossed: (1 | group2)
correlated = "correlated" == "correlated"  # (1 + x | g) vs (1 + x || g)
interactions = "none"
reml = "reml" == "reml"
conf = 0.95
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))  # lme4's checks on the grouping factors
if df[outcome].nunique() < 2:
    cs.cs_error("CS_E_CONSTANT", column=outcome)
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)  # treatment contrasts, R's column order
terms_x = list(X.columns)
y = df[outcome].to_numpy(dtype=float)
n, k = X.shape

# %% Fit (lme4's profiled deviance; Satterthwaite df as lmerTest)
model = mx.Lmm(y, X.to_numpy(), re)
fit = model.fit(reml)
satt = model.satterthwaite(fit)
values = {}
coefs = []
for j, term in enumerate(terms_x):
    est, se, ddf, tval, pval = satt.test1d(np.eye(k)[j])
    q = stats.t.ppf(1 - (1 - conf) / 2, ddf)
    coefs.append({"term": term, "estimate": est, "se": se, "df": ddf, "t": tval, "p": pval, "ci_low": est - q * se, "ci_high": est + q * se})
    values.update({f"coef[{term}]": est, f"se[{term}]": se, f"df[{term}]": ddf, f"t[{term}]": tval, f"p[{term}]": pval,
                   f"ci_low[{term}]": est - q * se, f"ci_high[{term}]": est + q * se})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
    F, df1, df2, pF = satt.test_md(np.eye(k)[idx])
    effects.append({"term": name, "f": F, "df1": df1, "df2": df2, "p": pF})
    values.update({f"f[{name}]": F, f"f_df1[{name}]": float(df1), f"f_df2[{name}]": df2, f"f_p[{name}]": pF})
values.update({"focal_f": None, "focal_df1": None, "focal_df2": None, "focal_p": None})  # no fixed predictor
if effects:
    values.update({"focal_f": effects[0]["f"], "focal_df1": float(effects[0]["df1"]), "focal_df2": effects[0]["df2"], "focal_p": effects[0]["p"]})

# %% Variance components, ICC and R² (Nakagawa; random slopes as Johnson 2014)
vc = mx.varcorr(re, fit.theta, fit.sigma)
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"]
sigma2 = fit.sigma**2
var_fixed = float(np.var(X.to_numpy() @ fit.beta, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, fit.sigma)
icc = var_random / (var_random + sigma2)
total = var_fixed + var_random + sigma2
n_theta = len(fit.theta)
n_params = k + n_theta + 1
aic = fit.deviance + 2 * n_params
bic = fit.deviance + np.log(n) * n_params
n_groups = re[0].nlev
values.update({"n": n, "k": k, "n_groups": n_groups, "sigma": fit.sigma, "log_lik": fit.log_lik, "deviance": fit.deviance,
               "aic": float(aic), "bic": float(bic), "icc": icc, "r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total,
               "var_fixed": var_fixed, "var_random": var_random, "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, "reml": reml})
if group2:
    values["n_groups2"] = re[-1].nlev  # levels of the second term (group:group2 combinations when nested, as lme4)

# %% Random effects vs none (likelihood ratio, ML)
if True:
    ml = model.fit(False) if reml else fit
    beta_ols, *_ = np.linalg.lstsq(X.to_numpy(), y, rcond=None)
    rss = float(np.sum((y - X.to_numpy() @ beta_ols) ** 2))
    ll_lm = -n / 2 * (np.log(2 * np.pi * rss / n) + 1)
    lrt = max(2 * (ml.log_lik - ll_lm), 0.0)
    lrt_p = float(stats.chi2.sf(lrt, n_theta))
    if n_theta == 1:
        lrt_p /= 2  # one variance component on its 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 = []
resid = fit.resid
if 3 <= n <= 5000:
    sw = stats.shapiro(resid)
    values["sw_p_resid"] = float(sw.pvalue)
    status = "pass" if sw.pvalue >= 0.05 else ("warn" if n < 300 else "info")
    assumptions.append({"key": "normality", "label": "Normal residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
                        "detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)} on the conditional residuals" + (" (with many rows small departures are flagged; look at the Q–Q plot)." if n >= 300 else ".")})
re_rows = []
off = 0
for ti, t in enumerate(re):
    for j, eff in enumerate(t.effects):
        b = np.array([fit.b[off + g * t.k + j] for g in range(t.nlev)])
        sd = np.array([np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)) for g in range(t.nlev)])
        re_rows += [{"group": t.group, "effect": eff, "level": lv, "estimate": float(bv), "sd": float(sv)} for lv, bv, sv in zip(t.levels, b, sd)]
        if t.nlev >= 8 and np.ptp(b) > 0:
            swr = stats.shapiro(b)
            assumptions.append({"key": "re_normality", "label": f"Normal random effects ({t.group}: {eff})", "status": "pass" if swr.pvalue >= 0.05 else "warn",
                                "statistic": float(swr.statistic), "p": float(swr.pvalue), "detail": f"Shapiro–Wilk W = {swr.statistic:.3f}, {cs.fmt_p(swr.pvalue)} on {t.nlev} conditional modes."})
    off += t.nlev * t.k
assumptions.append({"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 (drop a slope or the correlation)." 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"{n_groups} levels of {group}.")})

# %% Result
pct = f"{conf:.0%}"
slopes_tab = coefs[1:] if terms_x and terms_x[0] == "(Intercept)" else coefs
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]
vc_rows.append({"group": "Residual", "effect": "", "variance": sigma2, "sd": fit.sigma, "cor": None})
tests_text = ""
if effects:
    e0 = effects[0]
    tests_text = f" {e0['term']}: F({e0['df1']}, {e0['df2']:.1f}) = {e0['f']:.2f}, {cs.fmt_p(e0['p'])}."
summary = (f"Linear mixed model ({'REML' if reml else 'ML'}) of {outcome} (n = {n}, {n_groups} levels of {group}).{tests_text} "
           f"Adjusted ICC = {icc:.2f}; marginal R² = {var_fixed / total:.2f}, conditional R² = {(var_fixed + var_random) / total:.2f}.")
cat_rows = re_rows[:1000]
charts = [
    cs.chart("ranef", "caterpillar", "Random effects (conditional modes)", {
        "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"] - stats.norm.ppf(1 - (1 - conf) / 2) * r["sd"] for r in cat_rows]),
        "high": cs.col("high", [r["estimate"] + stats.norm.ppf(1 - (1 - conf) / 2) * r["sd"] for r in cat_rows]),
        "term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")}),
    cs.chart("residuals", "residual-panel", "Residual diagnostics", {"fitted": cs.col("Fitted", fit.fitted), "residual": cs.col("Residual", resid)}),
]
if slopes_tab:
    charts.append(cs.chart("coef", "forest", "Fixed effects", {
        "label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col("Estimate", [c["estimate"] for c in slopes_tab]),
        "low": cs.col("low", [c["ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ci_high"] for c in slopes_tab])}, controls={"reference": 0}))
tables = [
    {"key": "fixed", "title": "Fixed effects", "columns": [
        {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
        {"key": "df", "label": "df", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        {"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
     "rows": coefs, "note": "t tests with Satterthwaite degrees of freedom (lmerTest)."},
]
if effects:
    tables.append({"key": "effects", "title": "Joint tests of each predictor", "columns": [
        {"key": "term", "label": "Term", "type": "string"}, {"key": "f", "label": "F", "type": "number"}, {"key": "df1", "label": "num df", "type": "integer"},
        {"key": "df2", "label": "den df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
        "rows": effects, "note": "All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest)."})
tables.append({"key": "random", "title": "Random effects", "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]})
statistics = [{"key": "icc", "label": "ICC (adjusted)", "value": icc}, {"key": "r2_marginal", "label": "R² marginal", "value": var_fixed / total},
              {"key": "r2_conditional", "label": "R² conditional", "value": (var_fixed + var_random) / total}, {"key": "sigma", "label": "Residual SD", "value": fit.sigma},
              {"key": "aic", "label": "AIC", "value": float(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.lmm",
    "methodVersion": "1.0.1",
    "title": "Linear mixed model",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": (f"F({effects[0]['df1']}, {effects[0]['df2']:.2f}) = {effects[0]['f']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
    "statistics": statistics,
    "tables": tables,
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings + ([f"Satterthwaite: the (θ, σ) Hessian has {satt.n_negative} negative eigenvalue(s) — the model may not have converged."] if satt.n_negative else []),
    "notes": [f"{'REML' if reml else 'Maximum likelihood'} fit of lme4's model (twin of lme4's profiled deviance); fixed effects tested with Satterthwaite df (lmerTest)."],
    "charts": charts,
    "values": values,
})

Open the variance table. Which source is largest: batches, casks or repeat tests? Most of the spread lies between casks in the same batch, and the residual SD is only 0.823.

That changes what you'd do next. Testing more casks per batch would teach you much more than testing each cask again.

There are no fixed effects, so the ICC here is 0.937: the share of all variance in the two grouping levels.

04

When labels repeat

Predict

Predict first

Casks are labeled a, b, c inside every batch. Cask a in batch A has nothing to do with cask a in batch B. You leave the second factor set to Crossed with the first. What does the model assume?

It gets it rightIt treats them as one caskIt reports an error
Reveal

It treats all the a casks as one cask, shared across batches. The fit may run with no warning, and the variances will be wrong. Nested in the first reads labels within each group. Unique labels, such as A-a and B-a, make the structure unambiguous.

05

Read the crossed card

In the app
Linear mixed modelRecorded · Python and R agreeRecorded 2026-11-17 · 39 values compared · largest relative difference 2.1e-7
R

Linear mixed model (ML) of diameter (n = 144, 24 levels of plate). Adjusted ICC = 0.93; marginal R² = 0.00, conditional R² = 0.93.

ICC (adjusted)
0.9272
R² marginal
0
R² conditional
0.9272
Residual SD
0.5499
AIC
340.19
Random effects LR test p
< .001

Plots

Random effects (conditional modes)How much do groups differ in a mixed model, and which deviate clearly from the average?
View data
Conditional modeLevelhighlowTerm
0.8044a1.3350.2737plate: (Intercept)
0.8044b1.3350.2737plate: (Intercept)
0.1816c0.7123−0.3490plate: (Intercept)
0.3373d0.8680−0.1934plate: (Intercept)
0.0259e0.5566−0.5047plate: (Intercept)
−0.4411f0.0896−0.9718plate: (Intercept)
−1.375g−0.8446−1.906plate: (Intercept)
0.8044h1.3350.2737plate: (Intercept)
−0.7525i−0.2218−1.283plate: (Intercept)
−0.7525j−0.2218−1.283plate: (Intercept)
0.9601k1.4910.4294plate: (Intercept)
0.4930l1.024−0.0377plate: (Intercept)
1.427m1.9580.8965plate: (Intercept)
0.4930n1.024−0.0377plate: (Intercept)
0.9601o1.4910.4294plate: (Intercept)
0.0259p0.5566−0.5047plate: (Intercept)
−0.2854q0.2453−0.8161plate: (Intercept)
−0.2854r0.2453−0.8161plate: (Intercept)
−1.375s−0.8446−1.906plate: (Intercept)
0.9601t1.4910.4294plate: (Intercept)
−0.9082u−0.3775−1.439plate: (Intercept)
−0.2854v0.2453−0.8161plate: (Intercept)
−0.5968w−0.0661−1.128plate: (Intercept)
−1.220x−0.6889−1.750plate: (Intercept)
2.186A2.5801.791sample: (Intercept)
−1.010B−0.6153−1.404sample: (Intercept)
1.937C2.3311.542sample: (Intercept)
−0.0968D0.2977−0.4913sample: (Intercept)
−0.0138E0.3807−0.4083sample: (Intercept)
−3.002F−2.607−3.396sample: (Intercept)
Residual diagnosticsDo a model's residuals show non-linearity, non-normality, unequal spread or influential points?
View data
FittedResidual
25.9621.038
22.7670.2332
25.7130.2867
23.680−0.6798
23.763−0.7628
20.7750.2252
25.9621.038
22.7670.2332
25.7130.2867
23.680−0.6798
23.763−0.7628
20.7750.2252
25.340−0.3395
22.144−1.144
25.091−0.0905
23.0570.9430
23.1400.8600
20.152−0.1520
25.4950.5048
22.3000.7003
25.246−0.2462
23.213−0.2127
23.296−0.2957
20.308−0.3077
25.184−0.1838
21.9880.0117
24.9351.065
22.901−0.9013
22.9840.0157
19.9960.0037
24.717−0.7168
21.5210.4787
24.4680.5322
22.4340.5657
22.517−0.5173
19.529−0.5293
23.7830.2174
20.587−0.5871
23.534−0.5336
21.500−0.5001
21.5830.4169
18.5950.4049
25.9620.0377
22.767−0.7668
25.7130.2867
23.6800.3202
23.7630.2372
20.7750.2252
24.405−0.4054
21.210−0.2099
24.156−0.1564
22.123−0.1229
22.206−0.2059
19.2180.7821
24.405−0.4054
21.210−0.2099
24.156−0.1564
22.1230.8771
22.206−0.2059
19.218−0.2179

First 60 of 144 rows.

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.989, p = .301 on the conditional residuals.
  • Normal random effects (plate: (Intercept)) — Shapiro–Wilk W = 0.954, p = .334 on 24 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 24 levels of plate.

Fixed effects

TermBSEdftp95% CI low95% CI high
(Intercept)22.9720.74466.68930.852< .00121.19524.750

t tests with Satterthwaite degrees of freedom (lmerTest).

Random effects

GroupEffectVarianceSDCorrelation
plate(Intercept)0.71500.8456—
sample(Intercept)3.1351.771—
Residual0.30240.5499—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
plate(Intercept)a0.80440.2708
plate(Intercept)b0.80440.2708
plate(Intercept)c0.18160.2708
plate(Intercept)d0.33730.2708
plate(Intercept)e0.02590.2708
plate(Intercept)f−0.44110.2708
plate(Intercept)g−1.3750.2708
plate(Intercept)h0.80440.2708
plate(Intercept)i−0.75250.2708
plate(Intercept)j−0.75250.2708
plate(Intercept)k0.96010.2708
plate(Intercept)l0.49300.2708
plate(Intercept)m1.4270.2708
plate(Intercept)n0.49300.2708
plate(Intercept)o0.96010.2708
plate(Intercept)p0.02590.2708
plate(Intercept)q−0.28540.2708
plate(Intercept)r−0.28540.2708
plate(Intercept)s−1.3750.2708
plate(Intercept)t0.96010.2708
plate(Intercept)u−0.90820.2708
plate(Intercept)v−0.28540.2708
plate(Intercept)w−0.59680.2708
plate(Intercept)x−1.2200.2708
sample(Intercept)A2.1860.2013
sample(Intercept)B−1.0100.2013
sample(Intercept)C1.9370.2013
sample(Intercept)D−0.09680.2013
sample(Intercept)E−0.01380.2013
sample(Intercept)F−3.0020.2013
  • Maximum likelihood fit with lme4::lmer; fixed effects tested with Satterthwaite df (lmerTest).
The exact R script · R R version 4.5.1 (2025-06-13)
# Linear mixed model (random intercepts and slopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.lmm 1.0.1 · spec f20f4bf005877b69
# Dataset: s1_penicillin (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)
  library(lmerTest)  # Satterthwaite degrees of freedom
})

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_penicillin.parquet", col_select = c("diameter", "plate", "sample")))
n_input <- nrow(df)
df[["plate"]] <- factor(df[["plate"]], levels = c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x"))  # stored level order
df[["sample"]] <- factor(df[["sample"]], levels = c("A", "B", "C", "D", "E", "F"))  # stored level order
df <- df[stats::complete.cases(df[c("diameter", "plate", "sample")]), , 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("diameter", "plate", "sample"))  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome <- "diameter"
predictors <- c()
group <- "plate"
slopes <- c()
group2 <- "sample"
nesting <- "crossed"  # nested: (1 | group/group2); crossed: (1 | group2)
correlated <- "correlated" == "correlated"  # (1 + x | g) vs (1 + x || g)
interactions <- "none"
reml <- "ml" == "reml"
conf <- 0.95
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
# 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)  # lme4's checks on the grouping factors
if (length(unique(df[[outcome]])) < 2) cs_error("CS_E_CONSTANT", column = outcome)
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)
# Tight optimizer tolerance so the variance parameters are found to ~1e-10 (lme4's default stops near 1e-5).
ctrl <- lmerControl(optimizer = "bobyqa", optCtrl = list(rhoend = 1e-12, maxfun = 1e6))

# %% Fit
fit <- lmerTest::lmer(fml, data = df, REML = reml, 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)
y <- df[[outcome]]
ct <- summary(fit)$coefficients  # Estimate, SE, df (Satterthwaite), t, p
values <- list()
coefs <- list()
for (j in seq_len(k)) {
  est <- ct[j, "Estimate"]; se <- ct[j, "Std. Error"]; ddf <- ct[j, "df"]; tval <- ct[j, "t value"]; pval <- ct[j, "Pr(>|t|)"]
  q <- qt(1 - (1 - conf) / 2, ddf)
  term <- terms_x[j]
  coefs[[j]] <- list(term = term, estimate = est, se = se, df = ddf, t = tval, p = pval, ci_low = est - q * se, ci_high = est + q * se)
  values[[sprintf("coef[%s]", term)]] <- est; values[[sprintf("se[%s]", term)]] <- se; values[[sprintf("df[%s]", term)]] <- ddf
  values[[sprintf("t[%s]", term)]] <- tval; values[[sprintf("p[%s]", term)]] <- pval
  values[[sprintf("ci_low[%s]", term)]] <- est - q * se; values[[sprintf("ci_high[%s]", term)]] <- est + q * se
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
  L <- diag(k)[blocks[[name]], , drop = FALSE]
  tt <- lmerTest::contest(fit, L, joint = TRUE)  # Satterthwaite F test of all the term's coefficients
  e <- list(term = name, f = tt[["F value"]], df1 = tt[["NumDF"]], df2 = tt[["DenDF"]], p = tt[["Pr(>F)"]])
  effects[[length(effects) + 1]] <- e
  values[[sprintf("f[%s]", name)]] <- e$f; values[[sprintf("f_df1[%s]", name)]] <- as.numeric(e$df1)
  values[[sprintf("f_df2[%s]", name)]] <- e$df2; values[[sprintf("f_p[%s]", name)]] <- e$p
}
values$focal_f <- NA; values$focal_df1 <- NA; values$focal_df2 <- NA; values$focal_p <- NA  # no fixed predictor
if (length(effects)) {
  values$focal_f <- effects[[1]]$f; values$focal_df1 <- as.numeric(effects[[1]]$df1)
  values$focal_df2 <- effects[[1]]$df2; values$focal_p <- effects[[1]]$p
}

# %% Variance components, ICC and R² (Nakagawa; random slopes as Johnson 2014)
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]
  }
}
sig <- sigma(fit)
sigma2 <- sig^2
var_fixed <- if (n > 1) var(as.vector(X %*% fixef(fit))) else 0
var_random <- cs_mixed_random_variance(fit, df)
icc <- var_random / (var_random + sigma2)
total <- var_fixed + var_random + sigma2
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta + 1
crit <- if (reml) REMLcrit(fit) else deviance(fit)
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, sigma = sig, log_lik = as.numeric(logLik(fit)), deviance = crit,
                         aic = crit + 2 * n_params, bic = crit + log(n) * n_params, icc = icc, r2_marginal = var_fixed / total,
                         r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random,
                         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, reml = reml))
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, ML)
if (TRUE) {
  ml <- if (reml) update(fit, REML = FALSE) else fit
  fixed_fml <- if (length(predictors)) cs_model_formula(outcome, predictors, interactions) else stats::as.formula(paste0("`", outcome, "` ~ 1"))
  ll_lm <- as.numeric(logLik(lm(fixed_fml, data = df)))
  lrt <- max(2 * (as.numeric(logLik(ml)) - ll_lm), 0)
  lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
  if (n_theta == 1) lrt_p <- lrt_p / 2  # one variance component on its 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
assumptions <- list()
resid <- residuals(fit)
if (n >= 3 && n <= 5000) {
  sw <- shapiro.test(resid)
  values$sw_p_resid <- sw$p.value
  status <- if (sw$p.value >= 0.05) "pass" else if (n < 300) "warn" else "info"
  assumptions[[length(assumptions) + 1]] <- list(key = "normality", label = "Normal residuals", status = status, statistic = unname(sw$statistic), p = sw$p.value,
    detail = paste0(sprintf("Shapiro–Wilk W = %.3f, %s on the conditional residuals", sw$statistic, cs_fmt_p(sw$p.value)),
                    if (n >= 300) " (with many rows small departures are flagged; look at the Q–Q plot)." else "."))
}
re_tab <- cs_mixed_ranef(fit, valid)
for (key in unique(paste(re_tab$group, re_tab$effect, sep = "\r"))) {
  sel <- paste(re_tab$group, re_tab$effect, sep = "\r") == key
  b <- re_tab$estimate[sel]
  if (length(b) >= 8 && diff(range(b)) > 0) {
    swr <- shapiro.test(b)
    assumptions[[length(assumptions) + 1]] <- list(key = "re_normality", label = sprintf("Normal random effects (%s: %s)", re_tab$group[sel][1], re_tab$effect[sel][1]),
      status = if (swr$p.value >= 0.05) "pass" else "warn", statistic = unname(swr$statistic), p = swr$p.value,
      detail = sprintf("Shapiro–Wilk W = %.3f, %s on %d conditional modes.", swr$statistic, cs_fmt_p(swr$p.value), length(b)))
  }
}
singular <- isTRUE(values$singular)
assumptions[[length(assumptions) + 1]] <- 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 (drop a slope or the correlation)." 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[[length(assumptions) + 1]] <- 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))

# %% Result
pct <- sprintf("%.0f%%", conf * 100)
slopes_tab <- if (length(terms_x) && terms_x[1] == "(Intercept)") coefs[-1] else coefs
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])
})
vc_rows[[length(vc_rows) + 1]] <- list(group = "Residual", effect = "", variance = sigma2, sd = sig, cor = NULL)
tests_text <- if (length(effects)) sprintf(" %s: F(%d, %.1f) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df1), effects[[1]]$df2, effects[[1]]$f, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("Linear mixed model (%s) of %s (n = %d, %d levels of %s).%s Adjusted ICC = %.2f; marginal R² = %.2f, conditional R² = %.2f.",
                   if (reml) "REML" else "ML", outcome, n, n_groups, group, tests_text, icc, var_fixed / total, (var_fixed + var_random) / total)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(
  cs_chart("ranef", "caterpillar", "Random effects (conditional modes)", 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"))),
  cs_chart("residuals", "residual-panel", "Residual diagnostics", list(fitted = cs_col("Fitted", unname(fitted(fit))), residual = cs_col("Residual", unname(resid))))
)
if (length(slopes_tab)) {
  charts[[length(charts) + 1]] <- cs_chart("coef", "forest", "Fixed effects", list(
    label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col("Estimate", vapply(slopes_tab, `[[`, 0, "estimate")),
    low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ci_high"))), controls = list(reference = 0))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
  list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B", type = "number"), list(key = "se", label = "SE", type = "number"),
  list(key = "df", label = "df", type = "number"), list(key = "t", label = "t", type = "number"), list(key = "p", label = "p", type = "pvalue"),
  list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number")),
  rows = coefs, note = "t tests with Satterthwaite degrees of freedom (lmerTest)."))
if (length(effects)) {
  tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint tests of each predictor", columns = list(
    list(key = "term", label = "Term", type = "string"), list(key = "f", label = "F", type = "number"), list(key = "df1", label = "num df", type = "integer"),
    list(key = "df2", label = "den df", type = "number"), list(key = "p", label = "p", type = "pvalue")),
    rows = effects, note = "All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest).")
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects", 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)
statistics <- list(list(key = "icc", label = "ICC (adjusted)", value = icc), list(key = "r2_marginal", label = "R² marginal", value = var_fixed / total),
                   list(key = "r2_conditional", label = "R² conditional", value = (var_fixed + var_random) / total), list(key = "sigma", label = "Residual SD", value = sig),
                   list(key = "aic", label = "AIC", value = crit + 2 * n_params))
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.lmm",
  methodVersion = "1.0.1",
  title = "Linear mixed model",
  engine = cs_engine_info("lme4", "lmerTest", "nanoparquet"),
  n = n,
  summary = summary,
  apa = if (length(effects)) sprintf("F(%d, %.2f) = %.2f, %s", as.integer(effects[[1]]$df1), effects[[1]]$df2, effects[[1]]$f, cs_fmt_p(effects[[1]]$p)) else "",
  statistics = statistics,
  tables = tables,
  effectSizes = list(),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("%s fit with lme4::lmer; fixed effects tested with Satterthwaite df (lmerTest).", if (reml) "REML" else "Maximum likelihood")),
  charts = charts,
  values = values
))
Python

Linear mixed model (ML) of diameter (n = 144, 24 levels of plate). Adjusted ICC = 0.93; marginal R² = 0.00, conditional R² = 0.93.

ICC (adjusted)
0.9272
R² marginal
0
R² conditional
0.9272
Residual SD
0.5499
AIC
340.19
Random effects LR test p
< .001

To keep this page light, the plots are shown once, under the R tab.

Assumptions

  • Normal residuals — Shapiro–Wilk W = 0.989, p = .301 on the conditional residuals.
  • Normal random effects (plate: (Intercept)) — Shapiro–Wilk W = 0.954, p = .334 on 24 conditional modes.
  • Non-singular fit — Every variance component is clearly above zero.
  • Enough groups — 24 levels of plate.

Fixed effects

TermBSEdftp95% CI low95% CI high
(Intercept)22.9720.74466.68930.852< .00121.19524.750

t tests with Satterthwaite degrees of freedom (lmerTest).

Random effects

GroupEffectVarianceSDCorrelation
plate(Intercept)0.71500.8456—
sample(Intercept)3.1351.771—
Residual0.30240.5499—

Conditional modes of the random effects

GroupEffectLevelModeConditional SD
plate(Intercept)a0.80440.2708
plate(Intercept)b0.80440.2708
plate(Intercept)c0.18160.2708
plate(Intercept)d0.33730.2708
plate(Intercept)e0.02590.2708
plate(Intercept)f−0.44110.2708
plate(Intercept)g−1.3750.2708
plate(Intercept)h0.80440.2708
plate(Intercept)i−0.75250.2708
plate(Intercept)j−0.75250.2708
plate(Intercept)k0.96010.2708
plate(Intercept)l0.49300.2708
plate(Intercept)m1.4270.2708
plate(Intercept)n0.49300.2708
plate(Intercept)o0.96010.2708
plate(Intercept)p0.02590.2708
plate(Intercept)q−0.28540.2708
plate(Intercept)r−0.28540.2708
plate(Intercept)s−1.3750.2708
plate(Intercept)t0.96010.2708
plate(Intercept)u−0.90820.2708
plate(Intercept)v−0.28540.2708
plate(Intercept)w−0.59680.2708
plate(Intercept)x−1.2200.2708
sample(Intercept)A2.1860.2013
sample(Intercept)B−1.0100.2013
sample(Intercept)C1.9370.2013
sample(Intercept)D−0.09680.2013
sample(Intercept)E−0.01380.2013
sample(Intercept)F−3.0020.2013
  • Maximum likelihood fit of lme4's model (twin of lme4's profiled deviance); fixed effects tested with Satterthwaite df (lmerTest).
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Linear mixed model (random intercepts and slopes)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.lmm 1.0.1 · spec f20f4bf005877b69
# Dataset: s1_penicillin (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 + lmerTest (statsmodels' MixedLM has no Satterthwaite df)
from codesplash.stats import regression as csreg

# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_penicillin.parquet", columns=["diameter", "plate", "sample"])
n_input = len(df)
df["plate"] = pd.Categorical(df["plate"], categories=["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x"])  # stored level order
df["sample"] = pd.Categorical(df["sample"], categories=["A", "B", "C", "D", "E", "F"])  # stored level order
df = df.dropna(subset=["diameter", "plate", "sample"])  # listwise deletion over the analysis columns
df["plate"] = df["plate"].cat.remove_unused_categories()
df["sample"] = df["sample"].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, ["diameter", "plate", "sample"])  # infinite values stop the run (registry/errors.yaml)

# %% Model
outcome = "diameter"
predictors = []
group = "plate"
slopes = []
group2 = "sample"
nesting = "crossed"  # nested: (1 | group/group2); crossed: (1 | group2)
correlated = "correlated" == "correlated"  # (1 + x | g) vs (1 + x || g)
interactions = "none"
reml = "ml" == "reml"
conf = 0.95
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))  # lme4's checks on the grouping factors
if df[outcome].nunique() < 2:
    cs.cs_error("CS_E_CONSTANT", column=outcome)
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)  # treatment contrasts, R's column order
terms_x = list(X.columns)
y = df[outcome].to_numpy(dtype=float)
n, k = X.shape

# %% Fit (lme4's profiled deviance; Satterthwaite df as lmerTest)
model = mx.Lmm(y, X.to_numpy(), re)
fit = model.fit(reml)
satt = model.satterthwaite(fit)
values = {}
coefs = []
for j, term in enumerate(terms_x):
    est, se, ddf, tval, pval = satt.test1d(np.eye(k)[j])
    q = stats.t.ppf(1 - (1 - conf) / 2, ddf)
    coefs.append({"term": term, "estimate": est, "se": se, "df": ddf, "t": tval, "p": pval, "ci_low": est - q * se, "ci_high": est + q * se})
    values.update({f"coef[{term}]": est, f"se[{term}]": se, f"df[{term}]": ddf, f"t[{term}]": tval, f"p[{term}]": pval,
                   f"ci_low[{term}]": est - q * se, f"ci_high[{term}]": est + q * se})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
    F, df1, df2, pF = satt.test_md(np.eye(k)[idx])
    effects.append({"term": name, "f": F, "df1": df1, "df2": df2, "p": pF})
    values.update({f"f[{name}]": F, f"f_df1[{name}]": float(df1), f"f_df2[{name}]": df2, f"f_p[{name}]": pF})
values.update({"focal_f": None, "focal_df1": None, "focal_df2": None, "focal_p": None})  # no fixed predictor
if effects:
    values.update({"focal_f": effects[0]["f"], "focal_df1": float(effects[0]["df1"]), "focal_df2": effects[0]["df2"], "focal_p": effects[0]["p"]})

# %% Variance components, ICC and R² (Nakagawa; random slopes as Johnson 2014)
vc = mx.varcorr(re, fit.theta, fit.sigma)
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"]
sigma2 = fit.sigma**2
var_fixed = float(np.var(X.to_numpy() @ fit.beta, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, fit.sigma)
icc = var_random / (var_random + sigma2)
total = var_fixed + var_random + sigma2
n_theta = len(fit.theta)
n_params = k + n_theta + 1
aic = fit.deviance + 2 * n_params
bic = fit.deviance + np.log(n) * n_params
n_groups = re[0].nlev
values.update({"n": n, "k": k, "n_groups": n_groups, "sigma": fit.sigma, "log_lik": fit.log_lik, "deviance": fit.deviance,
               "aic": float(aic), "bic": float(bic), "icc": icc, "r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total,
               "var_fixed": var_fixed, "var_random": var_random, "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, "reml": reml})
if group2:
    values["n_groups2"] = re[-1].nlev  # levels of the second term (group:group2 combinations when nested, as lme4)

# %% Random effects vs none (likelihood ratio, ML)
if True:
    ml = model.fit(False) if reml else fit
    beta_ols, *_ = np.linalg.lstsq(X.to_numpy(), y, rcond=None)
    rss = float(np.sum((y - X.to_numpy() @ beta_ols) ** 2))
    ll_lm = -n / 2 * (np.log(2 * np.pi * rss / n) + 1)
    lrt = max(2 * (ml.log_lik - ll_lm), 0.0)
    lrt_p = float(stats.chi2.sf(lrt, n_theta))
    if n_theta == 1:
        lrt_p /= 2  # one variance component on its 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 = []
resid = fit.resid
if 3 <= n <= 5000:
    sw = stats.shapiro(resid)
    values["sw_p_resid"] = float(sw.pvalue)
    status = "pass" if sw.pvalue >= 0.05 else ("warn" if n < 300 else "info")
    assumptions.append({"key": "normality", "label": "Normal residuals", "status": status, "statistic": float(sw.statistic), "p": float(sw.pvalue),
                        "detail": f"Shapiro–Wilk W = {sw.statistic:.3f}, {cs.fmt_p(sw.pvalue)} on the conditional residuals" + (" (with many rows small departures are flagged; look at the Q–Q plot)." if n >= 300 else ".")})
re_rows = []
off = 0
for ti, t in enumerate(re):
    for j, eff in enumerate(t.effects):
        b = np.array([fit.b[off + g * t.k + j] for g in range(t.nlev)])
        sd = np.array([np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)) for g in range(t.nlev)])
        re_rows += [{"group": t.group, "effect": eff, "level": lv, "estimate": float(bv), "sd": float(sv)} for lv, bv, sv in zip(t.levels, b, sd)]
        if t.nlev >= 8 and np.ptp(b) > 0:
            swr = stats.shapiro(b)
            assumptions.append({"key": "re_normality", "label": f"Normal random effects ({t.group}: {eff})", "status": "pass" if swr.pvalue >= 0.05 else "warn",
                                "statistic": float(swr.statistic), "p": float(swr.pvalue), "detail": f"Shapiro–Wilk W = {swr.statistic:.3f}, {cs.fmt_p(swr.pvalue)} on {t.nlev} conditional modes."})
    off += t.nlev * t.k
assumptions.append({"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 (drop a slope or the correlation)." 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"{n_groups} levels of {group}.")})

# %% Result
pct = f"{conf:.0%}"
slopes_tab = coefs[1:] if terms_x and terms_x[0] == "(Intercept)" else coefs
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]
vc_rows.append({"group": "Residual", "effect": "", "variance": sigma2, "sd": fit.sigma, "cor": None})
tests_text = ""
if effects:
    e0 = effects[0]
    tests_text = f" {e0['term']}: F({e0['df1']}, {e0['df2']:.1f}) = {e0['f']:.2f}, {cs.fmt_p(e0['p'])}."
summary = (f"Linear mixed model ({'REML' if reml else 'ML'}) of {outcome} (n = {n}, {n_groups} levels of {group}).{tests_text} "
           f"Adjusted ICC = {icc:.2f}; marginal R² = {var_fixed / total:.2f}, conditional R² = {(var_fixed + var_random) / total:.2f}.")
cat_rows = re_rows[:1000]
charts = [
    cs.chart("ranef", "caterpillar", "Random effects (conditional modes)", {
        "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"] - stats.norm.ppf(1 - (1 - conf) / 2) * r["sd"] for r in cat_rows]),
        "high": cs.col("high", [r["estimate"] + stats.norm.ppf(1 - (1 - conf) / 2) * r["sd"] for r in cat_rows]),
        "term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")}),
    cs.chart("residuals", "residual-panel", "Residual diagnostics", {"fitted": cs.col("Fitted", fit.fitted), "residual": cs.col("Residual", resid)}),
]
if slopes_tab:
    charts.append(cs.chart("coef", "forest", "Fixed effects", {
        "label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col("Estimate", [c["estimate"] for c in slopes_tab]),
        "low": cs.col("low", [c["ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ci_high"] for c in slopes_tab])}, controls={"reference": 0}))
tables = [
    {"key": "fixed", "title": "Fixed effects", "columns": [
        {"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
        {"key": "df", "label": "df", "type": "number"}, {"key": "t", "label": "t", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        {"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"}],
     "rows": coefs, "note": "t tests with Satterthwaite degrees of freedom (lmerTest)."},
]
if effects:
    tables.append({"key": "effects", "title": "Joint tests of each predictor", "columns": [
        {"key": "term", "label": "Term", "type": "string"}, {"key": "f", "label": "F", "type": "number"}, {"key": "df1", "label": "num df", "type": "integer"},
        {"key": "df2", "label": "den df", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
        "rows": effects, "note": "All coefficients of the term = 0 (Satterthwaite F test, lmerTest::contest)."})
tables.append({"key": "random", "title": "Random effects", "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]})
statistics = [{"key": "icc", "label": "ICC (adjusted)", "value": icc}, {"key": "r2_marginal", "label": "R² marginal", "value": var_fixed / total},
              {"key": "r2_conditional", "label": "R² conditional", "value": (var_fixed + var_random) / total}, {"key": "sigma", "label": "Residual SD", "value": fit.sigma},
              {"key": "aic", "label": "AIC", "value": float(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.lmm",
    "methodVersion": "1.0.1",
    "title": "Linear mixed model",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n,
    "summary": summary,
    "apa": (f"F({effects[0]['df1']}, {effects[0]['df2']:.2f}) = {effects[0]['f']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
    "statistics": statistics,
    "tables": tables,
    "effectSizes": [],
    "assumptions": assumptions,
    "warnings": warnings + ([f"Satterthwaite: the (θ, σ) Hessian has {satt.n_negative} negative eigenvalue(s) — the model may not have converged."] if satt.n_negative else []),
    "notes": [f"{'REML' if reml else 'Maximum likelihood'} fit of lme4's model (twin of lme4's profiled deviance); fixed effects tested with Satterthwaite df (lmerTest)."],
    "charts": charts,
    "values": values,
})

Here, penicillin samples are tested on plates. Each of the 24 plates gets all 6 samples, so the factors are crossed, for 144 rows.

The variance table has a row for plates and a row for samples, around a residual SD of 0.550. The test of all random effects gives χ2\chi^2(2) = 279.5, p < .001.

06

Few levels

Reflect

With only 6 samples, the variance between samples rests on six values, however many rows you have. Its interval would be wide.

If you care about these six samples and not samples in general, a fixed effect fits better. If they're a random draw from a larger set, a random effect fits, and you should say how few levels it has.

Which grouping factors in your own data are a sample of something larger?

07

Where does the treatment sit?

Read

Clusters decide which variance a treatment is tested against.

If a treatment goes to whole schools, then pupils, and even classes, can't add much to the test of it: schools are what's replicated. If it goes to classes in the same school, comparisons happen within schools, so differences between schools no longer count against it.

Before you fit, write down the level at which each predictor varies. That tells you the effective sample size for its test.

08

Check your understanding

Checkpoint

Check yourself

Each of 12 raters scores the same 40 essays. How are raters and essays related?

Show the answer

Answer: b

Every combination occurs, so they're crossed. If each rater had read different essays, essays would be nested in raters.

Check yourself

Wards are numbered 1, 2, 3 inside each hospital. What must you make sure of before you fit?

Show the answer

Answer: b

Set the factor to nested, or give each ward a unique label. Otherwise the model pools all the ward 1s together.

Check yourself

Variance between hospitals is 1, between wards in a hospital is 6, and residual is 1. What share of the total lies between wards in a hospital?

Show the answer

Answer: 0.75

6 / (1 + 6 + 1) = 0.75. Most of the variation is at the ward level, so that's where to look and where to add units.

09

Fit yours

In the app

Set Grouping factor and Second grouping factor, then pick how they relate under Second grouping factor is.

Python
import pandas as pd
import statsmodels.formula.api as smf

pastes = pd.read_csv("s1_pastes.csv")
nested = smf.mixedlm("strength ~ 1", pastes, groups="batch",
                     vc_formula={"cask": "0 + C(cask)"}).fit()
print(nested.summary())

penicillin = pd.read_csv("s1_penicillin.csv")
penicillin["all"] = 1  # one group, with both factors as variance components
crossed = smf.mixedlm("diameter ~ 1", penicillin, groups="all",
                      vc_formula={"plate": "0 + C(plate)", "sample": "0 + C(sample)"}).fit()
print(crossed.summary())
R
library(lme4)

pastes <- read.csv("s1_pastes.csv")
nested <- lmer(strength ~ 1 + (1 | batch / cask), data = pastes)
VarCorr(nested)

penicillin <- read.csv("s1_penicillin.csv")
crossed <- lmer(diameter ~ 1 + (1 | plate) + (1 | sample), data = penicillin, REML = FALSE)
VarCorr(crossed)
10

Recap

Recap
  • Nested levels belong to one parent, and crossed levels combine freely.
  • Reused labels can turn nesting into crossing without any warning.
  • Variance components show where the variation lies, and so where to add units.
  • A factor with few levels gives an imprecise variance, so consider a fixed effect.