Skip to content

Designing a human evaluation: from protocol to crossed random effects

A human or AI-judge evaluation is an experiment. Plan the sampling, blind and randomize the presentation, add checks like MUSHRA's hidden reference, and analyze ratings with listeners and items as crossed random effects.

Advanced ~15 min10 steps

What runs in CodeSplash

You will be able to

  • Draw the sampling stages of a judgment study and say which ones a model can't repair
  • Compare MOS and MUSHRA designs and the checks each builds in
  • Analyze listener × clip × system ratings with crossed random effects instead of one big mean
  • Validate an AI judge against human judgments before substituting it

Read first

01

An evaluation is an experiment

Read

Every model in this track turns judgments into numbers. None of them can fix a badly collected sample. Before anyone judges anything, draw the sampling diagram:

  1. Which items (prompts, clips, documents) are sampled, and from what population?
  2. Which judges, and how are they assigned to items?
  3. Which pairs or systems does each judge see, in what order?
  4. What gets excluded, abstained or skipped, and why?
  5. Which model aggregates the judgments, and on which held-out data is it checked?

If hard audio is skipped more often, a fitted model describes the clips that were kept. Record skipped, unavailable, abstained and missing as different states.

02

Blinding, order and style

Read

Countermeasures that cost little and prevent a lot:

  • Hide system identity where you can, and randomize or counterbalance order (lesson 3).
  • Separate style from substance. Build controlled pairs with the same content but different length, formatting or citation style, plus true-quality contrasts, so a fix that suppresses length bias isn't mistaken for a good judge that rates everything as a tie.
  • Pre-register the rules for ties, abstentions, exclusions and the final composite score.
  • Pilot. Check that judges understand the task and that differences are perceptible at all.
03

MOS and MUSHRA

Read

Two standard listening-test designs for speech and audio quality, and they are different scales:

  • MOSMean opinion score (MOS)The average of listeners' ratings, usually on a 1–5 scale; report its interval and the rater panel, not just the mean.. Listeners rate one clip at a time on a 1–5 scale; the mean opinion score is the average. Easy to run, but MOS from different panels, devices and rooms isn't comparable.
  • MUSHRAMUSHRA listening testListeners rate several versions of a clip side by side on a 0–100 scale, with a hidden reference and a low anchor to check attention.. Listeners rate several versions of one clip side by side on 0–100, including a hidden reference (the original, unlabeled) and a low anchor (a deliberately degraded version). Listeners who don't rate the hidden reference near the top are screened out.

Both need a defined protocol: equipment, environment, recruitment, randomization, repeated items to measure consistency.

Reference · EVA044 · Partly runs in CodeSplashMOS and MUSHRA listening studiesCollect human judgments of speech or audio quality under defined listening protocols.
04

Predict: the standard error of a MOS

Predict

Predict first

Twenty listeners each rate the same 30 clips from a system, 600 ratings in all. You compute the MOS's standard error as SD over the square root of 600. Is that right?

About right: there are many ratingsToo small: ratings share listeners and clips
Reveal

Too small. Ratings by one listener share their harshness, and ratings of one clip share its content. Neither the listeners nor the clips are 600 independent units. A model with listener and clip effects gives an honest interval, and it generalizes to new listeners and new clips.

05

Crossed random effects

Read

Write each rating as a system effect plus a listener effect plus a clip effect plus noise:

ylcs=μ+βs+ul+vc+εlcs,ul∼N(0,σu2), vc∼N(0,σv2).y_{lcs}=\mu+\beta_s+u_l+v_c+\varepsilon_{lcs},\qquad u_l\sim N(0,\sigma_u^2),\ v_c\sim N(0,\sigma_v^2).

Listeners and clips are crossedCrossed factorsLevels of two factors combine freely, as when every rater scores every item.: every listener hears many clips and every clip is heard by many listeners. Treating both as random effectsRandom effectGroup-level variation modeled as draws from a distribution rather than one parameter per group. makes the system comparison account for both sources of variation. Linear mixed model (random intercepts and slopes) fits crossed effects; the penicillin example below has plates crossed with samples, the same structure as listeners crossed with clips.

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,
})

With 24 levels of one factor crossed with 6 of the other, the two random effects explain a share 0.93 of the variance: ignoring them would make every comparison look far more precise than it is.

06

When a simpler analysis works

Read

If every listener rates every system on the same clips, you can average each listener's ratings per system and run Repeated-measures ANOVA (one within factor) with listeners as subjects. It respects that ratings come in sets per listener, though it ignores clip-to-clip variation.

Repeated-measures ANOVARecorded · Python and R agreeRecorded 2026-11-25 · 32 values compared
R

F(1.00, 9.00) = 16.50, p = .003, η²p = .65

F
16.501
df (effect)
1
df (error)
9
p
.003
ε applied
1

Effect size

  • Partial η² 0.6471
  • Generalized η² 0.1613

Plots

extra by drug per patientHow did each subject change across conditions or time points?
View data
drugpatientextra
drug 110.7000
drug 211.900
drug 12−1.600
drug 220.8000
drug 13−0.2000
drug 231.100
drug 14−1.200
drug 240.1000
drug 15−0.1000
drug 25−0.1000
drug 163.400
drug 264.400
drug 173.700
drug 275.500
drug 180.8000
drug 281.600
drug 190
drug 294.600
drug 1102
drug 2103.400

Assumptions

  • Normality of residuals — Shapiro–Wilk on the residuals: p = .168.
  • Sphericity — Always satisfied with two conditions.
  • Complete subjects — 10 subjects have a value for every condition.

Within-subjects effects

SourceSSdfMSFpp (GG)p (HF)
drug12.482112.48216.501.003.003.003
Residual6.80890.7564————
Subjects58.0789—————

Descriptives

drugnMeanSDSECI lowCI high
drug 1100.75001.7890.5657−0.52982.030
drug 2102.3302.0020.63320.89773.762

Pairwise paired t-tests (Holm adjustment)

ContrastMean differenceSEtdfpp adj.CI lowCI high
drug 1 - drug 2−1.5800.3890−4.0629.003.003−2.460−0.7001
  • Within factor drug with 2 levels on 10 subjects; sphericity correction: none.
The exact R script · R R version 4.5.1 (2025-06-13)
# Repeated-measures ANOVA (one within factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.repeated 1.1.1 · spec d6263488ddefb631
# Dataset: sleep_long (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.

# %% Setup
library(codesplashr)

# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/sleep_long.parquet", col_select = c("patient", "drug", "extra")))
n_input <- nrow(df)
df[["patient"]] <- factor(df[["patient"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))  # stored level order
df[["drug"]] <- factor(df[["drug"]], levels = c("drug 1", "drug 2"))  # stored level order
df <- df[stats::complete.cases(df[c("patient", "drug", "extra")]), , 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("patient", "drug", "extra"))  # infinite values stop the run (registry/errors.yaml)

# %% Wide format: one row per subject, one column per condition
subj <- "patient"
cond <- "drug"
y <- "extra"
cells <- table(df[[subj]], df[[cond]])
n_dup <- sum(cells > 1)
agg <- stats::aggregate(df[[y]], by = list(s = df[[subj]], c = df[[cond]]), FUN = mean)
wide <- matrix(NA_real_, nlevels(df[[subj]]), nlevels(df[[cond]]), dimnames = list(levels(df[[subj]]), levels(df[[cond]])))
wide[cbind(as.character(agg$s), as.character(agg$c))] <- agg$x
complete <- wide[stats::complete.cases(wide), , drop = FALSE]
n_dropped_subjects <- sum(rowSums(!is.na(wide)) > 0) - nrow(complete)
if (n_dup > 0) warnings <- c(warnings, sprintf("%d subject × condition cell(s) had more than one value; their mean was used.", n_dup))
if (n_dropped_subjects > 0) warnings <- c(warnings, sprintf("%d subject(s) without a value for every condition were left out.", n_dropped_subjects))
conditions <- colnames(complete)
subjects <- rownames(complete)
Y <- unname(complete)
n_subj <- nrow(Y)
k <- ncol(Y)
if (n_subj < 2) {
  cs_error("CS_E_UNDEFINED", what = "This repeated-measures analysis", reason = "fewer than two subjects have a value for every condition")
}
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = cond, min = 2, k = k)
if (length(unique(as.vector(Y))) < 2) cs_error("CS_E_CONSTANT", column = y)  # a constant outcome leaves nothing to test (the F ratios would be 0/0)

# %% Test
correction <- "auto"  # auto: Huynh-Feldt if eps_GG >= .75, else Greenhouse-Geisser
conf <- 0.95
# No error variation (every subject changes by the same amount between conditions): the F ratio is undefined.
resid0 <- sweep(sweep(Y, 1, rowMeans(Y)), 2, colMeans(Y)) + mean(Y)
if (sum(resid0^2) <= 1e-12 * sum((Y - mean(Y))^2)) {
  cs_error("CS_E_UNDEFINED", what = "Repeated-measures ANOVA",
           reason = "every subject changes by the same amount between conditions, so there is no error variation to test against")
}
r <- cs_rm_oneway(Y)  # sums of squares, Mauchly, epsilon (twin of codesplash.stats.anova.rm_oneway)
applied <- if (k < 3 || correction == "none") "none" else if (correction == "auto") (if (r$gg >= 0.75) "hf" else "gg") else correction
epsilon <- switch(applied, none = 1, gg = r$gg, hf = r$hf, lb = r$lb)
df1c <- r$df1 * epsilon
df2c <- r$df2 * epsilon
p_corrected <- pf(r$f, df1c, df2c, lower.tail = FALSE)
p_gg <- pf(r$f, r$df1 * r$gg, r$df2 * r$gg, lower.tail = FALSE)
p_hf <- pf(r$f, r$df1 * r$hf, r$df2 * r$hf, lower.tail = FALSE)
labels <- c(none = "none", gg = "Greenhouse–Geisser", hf = "Huynh–Feldt", lb = "lower-bound")

# %% Pairwise comparisons: paired t on each pair of conditions
pairs <- data.frame()
if (TRUE && k >= 2) {
  for (i in seq_len(k - 1)) {
    for (j in (i + 1):k) {
      d <- Y[, i] - Y[, j]
      se <- sd(d) / sqrt(n_subj)
      t <- mean(d) / se
      q <- qt(0.5 + conf / 2, n_subj - 1)
      pairs <- rbind(pairs, data.frame(contrast = paste(conditions[i], "-", conditions[j]), estimate = mean(d), se = se, t = t,
                                       df = n_subj - 1, p = 2 * pt(abs(t), n_subj - 1, lower.tail = FALSE),
                                       ci_low = mean(d) - q * se, ci_high = mean(d) + q * se, stringsAsFactors = FALSE))
    }
  }
  pairs$p_adj <- cs_p_adjust(pairs$p, "holm")
}

# %% Assumptions
assumptions <- list()
resid <- Y - outer(rowMeans(Y), rep(1, k)) - outer(rep(1, n_subj), colMeans(Y)) + mean(Y)
sw_p <- if (length(resid) >= 3 && length(resid) <= 5000) shapiro.test(as.vector(t(resid)))$p.value else NULL
if (is.null(sw_p)) {
  assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "info", detail = "Too few (or too many) residuals for Shapiro–Wilk.")
} else if (sw_p < 0.05 && n_subj < 30) {
  assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = "warn", p = sw_p,
                           detail = sprintf("Shapiro–Wilk on the residuals: %s with fewer than 30 subjects; consider the Friedman test.", cs_fmt_p(sw_p)))
} else {
  assumptions[[1]] <- list(key = "normality", label = "Normality of residuals", status = if (sw_p >= 0.05) "pass" else "info", p = sw_p,
                           detail = paste0(sprintf("Shapiro–Wilk on the residuals: %s", cs_fmt_p(sw_p)),
                                           if (sw_p >= 0.05) "." else "; with 30 or more subjects the F test is robust."))
}
if (k < 3) {
  assumptions[[2]] <- list(key = "sphericity", label = "Sphericity", status = "pass", detail = "Always satisfied with two conditions.")
} else if (is.nan(r$mauchly_p)) {
  assumptions[[2]] <- list(key = "sphericity", label = "Sphericity", status = "info",
                           detail = sprintf("Mauchly's test needs more subjects than conditions; ε_GG = %.3f.", r$gg))
} else {
  bad <- r$mauchly_p < 0.05
  assumptions[[2]] <- list(key = "sphericity", label = "Sphericity", status = if (bad) "warn" else "pass",
                           statistic = r$mauchly_w, p = r$mauchly_p,
                           detail = paste0(sprintf("Mauchly's W = %.3f, %s; ε_GG = %.3f, ε_HF = %.3f.", r$mauchly_w, cs_fmt_p(r$mauchly_p), r$gg, r$hf),
                                           if (applied != "none") sprintf(" The %s correction is applied.", labels[[applied]])
                                           else if (bad) " No correction is applied." else ""))
}
assumptions[[3]] <- list(key = "complete", label = "Complete subjects", status = if (n_dropped_subjects > 0) "warn" else "pass",
                         detail = paste0(sprintf("%d subjects have a value for every condition", n_subj),
                                         if (n_dropped_subjects > 0) sprintf("; %d were left out.", n_dropped_subjects) else "."))

# %% Result
q <- qt(0.5 + conf / 2, n_subj - 1)
descriptives <- data.frame(condition = conditions, n = n_subj, mean = colMeans(Y), sd = apply(Y, 2, sd),
                           se = apply(Y, 2, sd) / sqrt(n_subj), stringsAsFactors = FALSE)
descriptives$ci_low <- descriptives$mean - q * descriptives$se
descriptives$ci_high <- descriptives$mean + q * descriptives$se
values <- list(
  f = r$f, df1 = r$df1, df2 = r$df2, p = r$p, epsilon = epsilon, df1_corrected = df1c, df2_corrected = df2c,
  p_corrected = p_corrected, gg_epsilon = r$gg, hf_epsilon = r$hf, lb_epsilon = r$lb, p_gg = p_gg, p_hf = p_hf,
  mauchly_w = r$mauchly_w, mauchly_p = r$mauchly_p, eta_p = r$eta_p, eta_g = r$eta_g,
  ss_condition = r$ss_cond, ss_subjects = r$ss_subj, ss_error = r$ss_err, n_subjects = n_subj, k = k,
  sw_p_resid = sw_p, correction = applied, correction_label = labels[[applied]], n_dropped_subjects = n_dropped_subjects
)
for (j in seq_len(k)) values[[sprintf("mean[%s]", conditions[j])]] <- descriptives$mean[j]
for (r_ in seq_len(nrow(pairs))) {
  values[[sprintf("diff[%s]", pairs$contrast[r_])]] <- pairs$estimate[r_]
  values[[sprintf("p_adj[%s]", pairs$contrast[r_])]] <- pairs$p_adj[r_]
}
tables <- list(
  list(key = "anova", title = "Within-subjects effects",
       columns = list(list(key = "source", label = "Source", type = "string"), list(key = "ss", label = "SS", type = "number"),
                      list(key = "df", label = "df", type = "number"), list(key = "ms", label = "MS", type = "number"),
                      list(key = "f", label = "F", type = "number"), list(key = "p", label = "p", type = "pvalue"),
                      list(key = "p_gg", label = "p (GG)", type = "pvalue"), list(key = "p_hf", label = "p (HF)", type = "pvalue")),
       rows = list(list(source = cond, ss = r$ss_cond, df = r$df1, ms = r$ss_cond / r$df1, f = r$f, p = r$p, p_gg = p_gg, p_hf = p_hf),
                   list(source = "Residual", ss = r$ss_err, df = r$df2, ms = r$ss_err / r$df2),
                   list(source = "Subjects", ss = r$ss_subj, df = n_subj - 1))),
  list(key = "descriptives", title = "Descriptives",
       columns = list(list(key = "condition", label = cond, type = "string"), list(key = "n", label = "n", type = "integer"),
                      list(key = "mean", label = "Mean", type = "number"), list(key = "sd", label = "SD", type = "number"),
                      list(key = "se", label = "SE", type = "number"), list(key = "ci_low", label = "CI low", type = "number"),
                      list(key = "ci_high", label = "CI high", type = "number")),
       rows = descriptives)
)
if (nrow(pairs) > 0) {
  adjust_label <- c(holm = "Holm", bonferroni = "Bonferroni", BH = "Benjamini–Hochberg", none = "no")[["holm"]]
  tables[[3]] <- list(key = "posthoc", title = sprintf("Pairwise paired t-tests (%s adjustment)", adjust_label),
                      columns = list(list(key = "contrast", label = "Contrast", type = "string"), list(key = "estimate", label = "Mean difference", type = "number"),
                                     list(key = "se", label = "SE", type = "number"), list(key = "t", label = "t", type = "number"),
                                     list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue"),
                                     list(key = "p_adj", label = "p adj.", type = "pvalue"), list(key = "ci_low", label = "CI low", type = "number"),
                                     list(key = "ci_high", label = "CI high", type = "number")),
                      rows = pairs)
}
long_s <- rep(subjects, each = k)
long_c <- rep(conditions, times = n_subj)
long_v <- as.vector(t(Y))
keep <- seq_len(min(length(long_v), 5000))
values$missing_share <- if (n_input > 0) n_dropped / n_input else 0  # consult-a-statistician input
values$max_interaction_order <- 1
eps_text <- if (applied != "none") sprintf(", %s ε = %.3f", labels[[applied]], epsilon) else ""
cs_publish(list(
  method = "anova.repeated",
  methodVersion = "1.1.1",
  title = "Repeated-measures ANOVA",
  engine = cs_engine_info("stats", "nanoparquet"),
  n = n_subj,
  summary = sprintf("F(%s, %s) = %s, %s%s; partial η² = %.3f.", cs_fmt_num(df1c), cs_fmt_num(df2c), cs_fmt_num(r$f), cs_fmt_p(p_corrected), eps_text, r$eta_p),
  apa = sprintf("F(%s, %s) = %s, %s, η²p = %s", cs_fmt_num(df1c), cs_fmt_num(df2c), cs_fmt_num(r$f), cs_fmt_p(p_corrected), cs_fmt_num(r$eta_p, 2, leading_zero = FALSE)),
  statistics = list(
    list(key = "f", label = "F", value = r$f), list(key = "df1_corrected", label = "df (effect)", value = df1c),
    list(key = "df2_corrected", label = "df (error)", value = df2c), list(key = "p_corrected", label = "p", value = p_corrected, format = "p"),
    list(key = "epsilon", label = "ε applied", value = epsilon)
  ),
  tables = tables,
  effectSizes = list(
    list(key = "eta_p", label = "Partial η²", value = r$eta_p, method = "SS_condition / (SS_condition + SS_error)"),
    list(key = "eta_g", label = "Generalized η²", value = r$eta_g, method = "Olejnik & Algina (2003)")
  ),
  assumptions = assumptions,
  warnings = warnings,
  notes = list(sprintf("Within factor %s with %d levels on %d subjects; sphericity correction: %s.", cond, k, n_subj, labels[[applied]])),
  values = values,
  charts = list(cs_chart("profiles", "paired-lines", sprintf("%s by %s per %s", y, cond, subj), list(
    subject = cs_col(subj, long_s[keep], "categorical"),
    condition = cs_col(cond, long_c[keep], "categorical", levels = conditions),
    value = cs_col(y, long_v[keep], "numeric"))))
))
Python

F(1.00, 9.00) = 16.50, p = .003, η²p = .65

F
16.501
df (effect)
1
df (error)
9
p
.003
ε applied
1

Effect size

  • Partial η² 0.6471
  • Generalized η² 0.1613

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

Assumptions

  • Normality of residuals — Shapiro–Wilk on the residuals: p = .168.
  • Sphericity — Always satisfied with two conditions.
  • Complete subjects — 10 subjects have a value for every condition.

Within-subjects effects

SourceSSdfMSFpp (GG)p (HF)
drug12.482112.48216.501.003.003.003
Residual6.80890.7564————
Subjects58.0789—————

Descriptives

drugnMeanSDSECI lowCI high
drug 1100.75001.7890.5657−0.52982.030
drug 2102.3302.0020.63320.89773.762

Pairwise paired t-tests (Holm adjustment)

ContrastMean differenceSEtdfpp adj.CI lowCI high
drug 1 - drug 2−1.5800.3890−4.0629.003.003−2.460−0.7001
  • Within factor drug with 2 levels on 10 subjects; sphericity correction: none.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Repeated-measures ANOVA (one within factor)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method anova.repeated 1.1.1 · spec d6263488ddefb631
# Dataset: sleep_long (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 anova as csa
from codesplash.stats.padjust import p_adjust

# %% Data
df = pd.read_parquet("tests/parity/fixtures/sleep_long.parquet", columns=["patient", "drug", "extra"])
n_input = len(df)
df["patient"] = pd.Categorical(df["patient"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"])  # stored level order
df["drug"] = pd.Categorical(df["drug"], categories=["drug 1", "drug 2"])  # stored level order
df = df.dropna(subset=["patient", "drug", "extra"])  # listwise deletion over the analysis columns
df["patient"] = df["patient"].cat.remove_unused_categories()
df["drug"] = df["drug"].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, ["patient", "drug", "extra"])  # infinite values stop the run (registry/errors.yaml)

# %% Wide format: one row per subject, one column per condition
subj, cond, y = "patient", "drug", "extra"
cells = df.groupby([subj, cond], observed=True)[y].size()
n_dup = int((cells > 1).sum())
wide = df.pivot_table(index=subj, columns=cond, values=y, aggfunc="mean", observed=False)
wide = wide.reindex(index=df[subj].cat.categories, columns=df[cond].cat.categories)
complete = wide.dropna()
n_dropped_subjects = int(wide.notna().any(axis=1).sum() - len(complete))
if n_dup:
    warnings.append(f"{n_dup} subject × condition cell(s) had more than one value; their mean was used.")
if n_dropped_subjects:
    warnings.append(f"{n_dropped_subjects} subject(s) without a value for every condition were left out.")
conditions = [str(c) for c in complete.columns]
subjects = [str(s) for s in complete.index]
Y = complete.to_numpy(dtype=float)
n_subj, k = Y.shape
if n_subj < 2:
    cs.cs_error("CS_E_UNDEFINED", what="This repeated-measures analysis", reason="fewer than two subjects have a value for every condition")
if k < 2:
    cs.cs_error("CS_E_TOO_FEW_GROUPS", column=cond, min=2, k=k)
if len(np.unique(Y)) < 2:  # a constant outcome leaves nothing to test (the F ratios would be 0/0)
    cs.cs_error("CS_E_CONSTANT", column=y)

# %% Test
correction = "auto"  # auto: Huynh–Feldt if ε_GG ≥ .75, else Greenhouse–Geisser
conf = 0.95
# No error variation (every subject changes by the same amount between conditions): the F ratio is undefined.
resid0 = Y - Y.mean(axis=1, keepdims=True) - Y.mean(axis=0, keepdims=True) + Y.mean()
if float((resid0**2).sum()) <= 1e-12 * float(((Y - Y.mean()) ** 2).sum()):
    cs.cs_error("CS_E_UNDEFINED", what="Repeated-measures ANOVA",
                reason="every subject changes by the same amount between conditions, so there is no error variation to test against")
r = csa.rm_oneway(Y)  # sums of squares, Mauchly, ε (twin of R's cs_rm_oneway)
if k < 3 or correction == "none":
    applied = "none"
elif correction == "auto":
    applied = "hf" if r["gg"] >= 0.75 else "gg"
else:
    applied = correction
epsilon = {"none": 1.0, "gg": r["gg"], "hf": r["hf"], "lb": r["lb"]}[applied]
df1c, df2c = r["df1"] * epsilon, r["df2"] * epsilon
p_corrected = float(stats.f.sf(r["f"], df1c, df2c))
p_gg = float(stats.f.sf(r["f"], r["df1"] * r["gg"], r["df2"] * r["gg"]))
p_hf = float(stats.f.sf(r["f"], r["df1"] * r["hf"], r["df2"] * r["hf"]))
labels = {"none": "none", "gg": "Greenhouse–Geisser", "hf": "Huynh–Feldt", "lb": "lower-bound"}

# %% Pairwise comparisons: paired t on each pair of conditions
pairs = []
if True and k >= 2:
    for i in range(k):
        for j in range(i + 1, k):
            d = Y[:, i] - Y[:, j]
            se = d.std(ddof=1) / np.sqrt(n_subj)
            t = d.mean() / se
            q = stats.t.ppf(0.5 + conf / 2, n_subj - 1)
            pairs.append({"contrast": f"{conditions[i]} - {conditions[j]}", "estimate": float(d.mean()), "se": float(se),
                          "t": float(t), "df": n_subj - 1, "p": float(2 * stats.t.sf(abs(t), n_subj - 1)),
                          "ci_low": float(d.mean() - q * se), "ci_high": float(d.mean() + q * se)})
    for row, pa in zip(pairs, p_adjust([x["p"] for x in pairs], "holm")):
        row["p_adj"] = float(pa)

# %% Assumptions
assumptions = []
resid = Y - Y.mean(axis=1, keepdims=True) - Y.mean(axis=0, keepdims=True) + Y.mean()
sw_p = float(stats.shapiro(resid.ravel()).pvalue) if 3 <= resid.size <= 5000 else None
if sw_p is None:
    assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "info", "detail": "Too few (or too many) residuals for Shapiro–Wilk."})
elif sw_p < 0.05 and n_subj < 30:
    assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "warn", "p": sw_p,
                        "detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)} with fewer than 30 subjects; consider the Friedman test."})
else:
    assumptions.append({"key": "normality", "label": "Normality of residuals", "status": "pass" if sw_p >= 0.05 else "info", "p": sw_p,
                        "detail": f"Shapiro–Wilk on the residuals: {cs.fmt_p(sw_p)}" + ("." if sw_p >= 0.05 else "; with 30 or more subjects the F test is robust.")})
if k < 3:
    assumptions.append({"key": "sphericity", "label": "Sphericity", "status": "pass", "detail": "Always satisfied with two conditions."})
elif np.isnan(r["mauchly_p"]):
    assumptions.append({"key": "sphericity", "label": "Sphericity", "status": "info",
                        "detail": f"Mauchly's test needs more subjects than conditions; ε_GG = {r['gg']:.3f}."})
else:
    bad = r["mauchly_p"] < 0.05
    assumptions.append({"key": "sphericity", "label": "Sphericity", "status": "warn" if bad else "pass",
                        "statistic": r["mauchly_w"], "p": r["mauchly_p"],
                        "detail": f"Mauchly's W = {r['mauchly_w']:.3f}, {cs.fmt_p(r['mauchly_p'])}; ε_GG = {r['gg']:.3f}, ε_HF = {r['hf']:.3f}."
                        + (f" The {labels[applied]} correction is applied." if applied != "none" else (" No correction is applied." if bad else ""))})
assumptions.append({"key": "complete", "label": "Complete subjects", "status": "warn" if n_dropped_subjects else "pass",
                    "detail": f"{n_subj} subjects have a value for every condition" + (f"; {n_dropped_subjects} were left out." if n_dropped_subjects else ".")})

# %% Result
descriptives = []
for j, c in enumerate(conditions):
    x = Y[:, j]
    se = x.std(ddof=1) / np.sqrt(n_subj)
    q = stats.t.ppf(0.5 + conf / 2, n_subj - 1)
    descriptives.append({"condition": c, "n": n_subj, "mean": float(x.mean()), "sd": float(x.std(ddof=1)), "se": float(se),
                         "ci_low": float(x.mean() - q * se), "ci_high": float(x.mean() + q * se)})
values = {
    "f": r["f"], "df1": r["df1"], "df2": r["df2"], "p": r["p"], "epsilon": epsilon, "df1_corrected": df1c, "df2_corrected": df2c,
    "p_corrected": p_corrected, "gg_epsilon": r["gg"], "hf_epsilon": r["hf"], "lb_epsilon": r["lb"], "p_gg": p_gg, "p_hf": p_hf,
    "mauchly_w": r["mauchly_w"], "mauchly_p": r["mauchly_p"], "eta_p": r["eta_p"], "eta_g": r["eta_g"],
    "ss_condition": r["ss_cond"], "ss_subjects": r["ss_subj"], "ss_error": r["ss_err"], "n_subjects": n_subj, "k": k,
    "sw_p_resid": sw_p, "correction": applied, "correction_label": labels[applied], "n_dropped_subjects": n_dropped_subjects,
}
for row in descriptives:
    values[f"mean[{row['condition']}]"] = row["mean"]
for row in pairs:
    values[f"diff[{row['contrast']}]"] = row["estimate"]
    values[f"p_adj[{row['contrast']}]"] = row["p_adj"]
long_rows = [(s, c, Y[i, j]) for i, s in enumerate(subjects) for j, c in enumerate(conditions)][:5000]
tables = [
    {"key": "anova", "title": "Within-subjects effects", "columns": [
        {"key": "source", "label": "Source", "type": "string"}, {"key": "ss", "label": "SS", "type": "number"},
        {"key": "df", "label": "df", "type": "number"}, {"key": "ms", "label": "MS", "type": "number"},
        {"key": "f", "label": "F", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"},
        {"key": "p_gg", "label": "p (GG)", "type": "pvalue"}, {"key": "p_hf", "label": "p (HF)", "type": "pvalue"}],
     "rows": [
        {"source": cond, "ss": r["ss_cond"], "df": r["df1"], "ms": r["ss_cond"] / r["df1"], "f": r["f"], "p": r["p"], "p_gg": p_gg, "p_hf": p_hf},
        {"source": "Residual", "ss": r["ss_err"], "df": r["df2"], "ms": r["ss_err"] / r["df2"]},
        {"source": "Subjects", "ss": r["ss_subj"], "df": n_subj - 1}]},
    {"key": "descriptives", "title": "Descriptives", "columns": [
        {"key": "condition", "label": cond, "type": "string"}, {"key": "n", "label": "n", "type": "integer"},
        {"key": "mean", "label": "Mean", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"},
        {"key": "se", "label": "SE", "type": "number"}, {"key": "ci_low", "label": "CI low", "type": "number"},
        {"key": "ci_high", "label": "CI high", "type": "number"}], "rows": descriptives},
]
if pairs:
    adjust_label = {"holm": "Holm", "bonferroni": "Bonferroni", "BH": "Benjamini–Hochberg", "none": "no"}["holm"]
    tables.append({"key": "posthoc", "title": f"Pairwise paired t-tests ({adjust_label} adjustment)",
                   "columns": [{"key": "contrast", "label": "Contrast", "type": "string"}, {"key": "estimate", "label": "Mean difference", "type": "number"},
                               {"key": "se", "label": "SE", "type": "number"}, {"key": "t", "label": "t", "type": "number"},
                               {"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"},
                               {"key": "p_adj", "label": "p adj.", "type": "pvalue"}, {"key": "ci_low", "label": "CI low", "type": "number"},
                               {"key": "ci_high", "label": "CI high", "type": "number"}], "rows": pairs})
eps_text = f", {labels[applied]} ε = {epsilon:.3f}" if applied != "none" else ""
values["missing_share"] = n_dropped / n_input if n_input else 0.0  # consult-a-statistician input
values["max_interaction_order"] = 1
cs.publish({
    "method": "anova.repeated",
    "methodVersion": "1.1.1",
    "title": "Repeated-measures ANOVA",
    "engine": cs.engine_info("pandas", "numpy", "scipy"),
    "n": n_subj,
    "summary": f"F({cs.fmt_num(df1c)}, {cs.fmt_num(df2c)}) = {cs.fmt_num(r['f'])}, {cs.fmt_p(p_corrected)}{eps_text}; partial η² = {r['eta_p']:.3f}.",
    "apa": f"F({cs.fmt_num(df1c)}, {cs.fmt_num(df2c)}) = {cs.fmt_num(r['f'])}, {cs.fmt_p(p_corrected)}, η²p = {cs.fmt_num(r['eta_p'], 2, leading_zero=False)}",
    "statistics": [
        {"key": "f", "label": "F", "value": r["f"]}, {"key": "df1_corrected", "label": "df (effect)", "value": df1c},
        {"key": "df2_corrected", "label": "df (error)", "value": df2c}, {"key": "p_corrected", "label": "p", "value": p_corrected, "format": "p"},
        {"key": "epsilon", "label": "ε applied", "value": epsilon},
    ],
    "tables": tables,
    "effectSizes": [
        {"key": "eta_p", "label": "Partial η²", "value": r["eta_p"], "method": "SS_condition / (SS_condition + SS_error)"},
        {"key": "eta_g", "label": "Generalized η²", "value": r["eta_g"], "method": "Olejnik & Algina (2003)"},
    ],
    "assumptions": assumptions,
    "warnings": warnings,
    "notes": [f"Within factor {cond} with {k} levels on {n_subj} subjects; sphericity correction: {labels[applied]}."],
    "values": values,
    "charts": [cs.chart("profiles", "paired-lines", f"{y} by {cond} per {subj}", {
        "subject": cs.col(subj, [x[0] for x in long_rows], "categorical"),
        "condition": cs.col(cond, [x[1] for x in long_rows], "categorical", levels=conditions),
        "value": cs.col(y, [float(x[2]) for x in long_rows], "numeric")})],
})

Report the full score distributions per system, not only means; a 1–5 scale is ordinal, and a many-facet Rasch model (lesson 7) can put raters' different uses of the scale on one footing.

07

Validating an AI judge

Read

An AI judgeLLM-as-judgeA language model scores generated text against a rubric (1–5 per criterion or pass/fail), or picks the better of two responses. is one more rater, with its own biases (position, length, its own model family's style). Before substituting it for people:

  • Collect human judgments on a sample and compare: agreement, and whether both rank systems the same way.
  • Test reversed order and length-controlled pairs.
  • Freeze and record the model id, prompt, decoding settings and parser; count parser failures instead of silently turning them into losses.
  • Keep separate dimensions separate; one "overall" verdict hides tradeoffs.
08

Where it stands in CodeSplash

Read
EntryIn CodeSplash
MOS and MUSHRA listening studies (EVA044)Partly runs in CodeSplash: analyze the ratings (listener, clip, system, score) with Linear mixed model (crossed listener and clip effects) or Repeated-measures ANOVA; running the listening test itself happens outside the app

The audio track's lesson Evaluating audio compares these tests with automatic quality scores.

09

Check your understanding

Checkpoint

Check yourself

What is MUSHRA's hidden reference for?

Show the answer

Answer: b

The hidden reference and the low anchor are built-in attention and sensitivity checks; MOS designs have no equivalent.

Check yourself

In a listening test, every listener rates many clips and every clip is rated by many listeners. How should listeners and clips enter the analysis?

Show the answer

Answer: c

Crossed random effects generalize the comparison to new listeners and new clips, and give honest intervals.

Check yourself

A paper reports MOS 4.1 for its TTS system and quotes another paper's MOS 3.9 for a competitor. What's wrong with comparing them?

Show the answer

Answer: b

MOS depends on the protocol and panel. Compare systems within one randomized study, with listener and clip effects.

Check yourself

Annotators may skip clips they find hard, and hard clips are skipped far more often. What does a model fitted to the remaining ratings describe?

Show the answer

Answer: b

A model can't repair a biased sample of items. Record skips as their own state and consider how they relate to difficulty.

10

Recap

Recap
  • Plan the sampling stages first; models can't fix a biased sample.
  • Blind, randomize, control style, pre-register rules and pilot.
  • MOS and MUSHRA are different designs; MUSHRA builds in a hidden reference and an anchor.
  • Analyze listener × clip × system ratings with crossed random effects; validate any AI judge against people.

Concepts in this lesson