DRegression models · mixed.glmm
Generalized linear mixed model (logistic / Poisson)
How do predictors change a binary outcome or a count when rows are grouped (repeated measures, clusters)?
lme4-style generalized linear mixed model fitted by the Laplace approximation (glmer, nAGQ = 1): logistic (yes/no, or successes out of trials) or Poisson (counts, optional exposure) with random intercepts (and slopes) for a grouping factor and optionally a second nested or crossed one. Subject-specific odds or rate ratios with Wald tests (covariance from the Hessian, as lme4), joint Wald tests per predictor, variance components, latent-scale ICC and Nakagawa's R², a likelihood-ratio test of the random effects and the conditional modes of the random effects.
A real result
Example “Cbpp trials”, recorded in both engines. In the app, “Try this example” loads it into Analyze.
Wald χ²(3) = 24.95, p < .001
- ICC (latent scale)
- 0.1114
- R² marginal
- 0.0854
- R² conditional
- 0.1873
- AIC
- 194.05
- Random effects LR test p
- < .001
Plots
View data
| Conditional mode | Level | high | low | Term |
|---|---|---|---|---|
| 0.5900 | 1 | 1.273 | −0.0926 | herd: (Intercept) |
| −0.2989 | 2 | 0.4176 | −1.015 | herd: (Intercept) |
| 0.4063 | 3 | 0.9890 | −0.1765 | herd: (Intercept) |
| 0.0393 | 4 | 0.8554 | −0.7768 | herd: (Intercept) |
| −0.1900 | 5 | 0.4968 | −0.8768 | herd: (Intercept) |
| −0.4003 | 6 | 0.3444 | −1.145 | herd: (Intercept) |
| 0.8894 | 7 | 1.529 | 0.2495 | herd: (Intercept) |
| 0.5994 | 8 | 1.229 | −0.0300 | herd: (Intercept) |
| −0.2377 | 9 | 0.6667 | −1.142 | herd: (Intercept) |
| −0.5409 | 10 | 0.1856 | −1.267 | herd: (Intercept) |
| −0.0846 | 11 | 0.5212 | −0.6905 | herd: (Intercept) |
| −0.0648 | 12 | 0.7998 | −0.9294 | herd: (Intercept) |
| −0.6899 | 13 | 0.0643 | −1.444 | herd: (Intercept) |
| 0.9707 | 14 | 1.667 | 0.2741 | herd: (Intercept) |
| −0.5305 | 15 | 0.2490 | −1.310 | herd: (Intercept) |
View data
| Odds ratio | high | Term | low |
|---|---|---|---|
| 0.3707 | 0.6762 | period: 2 | 0.2032 |
| 0.3235 | 0.6136 | period: 3 | 0.1705 |
| 0.2059 | 0.4759 | period: 4 | 0.0891 |
View data
| Scaled residual |
|---|
| 0.4850 |
| 0.9224 |
| 0.9941 |
| 0.2038 |
| 0.3964 |
| 0.5158 |
| 0.2896 |
| 0.8533 |
| 0.6665 |
| 0.1088 |
| 0.7598 |
| 0.6367 |
| 0.0247 |
| 0.9210 |
| 0.6597 |
| 0.6573 |
| 0.0534 |
| 0.1726 |
| 0.8190 |
| 0.4794 |
| 0.2378 |
| 0.1197 |
| 0.6866 |
| 0.9637 |
| 0.4250 |
| 0.9699 |
| 0.4722 |
| 0.8975 |
| 0.5850 |
| 0.1823 |
| 0.0799 |
| 0.4311 |
| 0.0675 |
| 0.3464 |
| 0.2486 |
| 0.7444 |
| 0.0144 |
| 0.8372 |
| 0.7718 |
| 0.6027 |
| 0.6012 |
| 0.6702 |
| 0.5828 |
| 0.2412 |
| 0.0362 |
| 0.4735 |
| 0.2437 |
| 0.2522 |
| 0.9700 |
| 0.0760 |
| 0.0901 |
| 0.0516 |
| 0.1323 |
| 0.3427 |
| 0.6209 |
| 0.1603 |
View data
| Population-level prediction (rank, 0–1) | Scaled residual |
|---|---|
| 0.8036 | 0.4850 |
| 0.3929 | 0.9224 |
| 0.2500 | 0.9941 |
| 0.1071 | 0.2038 |
| 0.9464 | 0.3964 |
| 0.6071 | 0.5158 |
| 0.6250 | 0.2896 |
| 0.9464 | 0.8533 |
| 0.5536 | 0.6665 |
| 0.4821 | 0.1088 |
| 0.3661 | 0.7598 |
| 0.7232 | 0.6367 |
| 0.3304 | 0.0247 |
| 0.2500 | 0.9210 |
| 0.1518 | 0.6597 |
| 0.8571 | 0.6573 |
| 0.7679 | 0.0534 |
| 0.6607 | 0.1726 |
| 0.0536 | 0.8190 |
| 0.8393 | 0.4794 |
| 0.5893 | 0.2378 |
| 0.5268 | 0.1197 |
| 0.3661 | 0.6866 |
| 0.8214 | 0.9637 |
| 0.3304 | 0.4250 |
| 0.2500 | 0.9699 |
| 0.1071 | 0.4722 |
| 1 | 0.8975 |
| 0.6786 | 0.5850 |
| 0.1964 | 0.1823 |
| 0.2143 | 0.0799 |
| 0.1518 | 0.4311 |
| 0.9464 | 0.0675 |
| 0.6964 | 0.3464 |
| 0.5268 | 0.2486 |
| 0.4196 | 0.7444 |
| 0.9821 | 0.0144 |
| 0.7857 | 0.8372 |
| 0.6429 | 0.7718 |
| 0.4196 | 0.6027 |
| 0.7232 | 0.6012 |
| 0.2857 | 0.6702 |
| 0.1786 | 0.5828 |
| 0.1071 | 0.2412 |
| 0.9107 | 0.0362 |
| 0.7500 | 0.4735 |
| 0.5714 | 0.2437 |
| 0.4643 | 0.2522 |
| 0.8839 | 0.9700 |
| 0.0357 | 0.0760 |
| 0.0714 | 0.0901 |
| 0.0179 | 0.0516 |
| 0.8839 | 0.1323 |
| 0.5000 | 0.3427 |
| 0.4464 | 0.6209 |
| 0.3036 | 0.1603 |
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 15 levels of herd.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.123, p = .339 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 1.39, p = .288.
- Number of zeros matches the model (simulation) — Observed / simulated zeros = 1.14, p = .504.
- No more outliers than expected (simulation) — 0 of 56 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = 1.000).
Fixed effects
| Term | B (link scale) | SE | z | p | Odds ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.399 | 0.2325 | −6.016 | < .001 | 0.2470 | 0.1566 | 0.3895 |
| period: 2 | −0.9923 | 0.3066 | −3.236 | .001 | 0.3707 | 0.2032 | 0.6762 |
| period: 3 | −1.129 | 0.3266 | −3.455 | < .001 | 0.3235 | 0.1705 | 0.6136 |
| period: 4 | −1.580 | 0.4274 | −3.697 | < .001 | 0.2059 | 0.0891 | 0.4759 |
Odds ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| period | 24.949 | 3 | < .001 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| herd | (Intercept) | 0.4125 | 0.6423 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| herd | (Intercept) | 1 | 0.5900 | 0.3483 |
| herd | (Intercept) | 2 | −0.2989 | 0.3656 |
| herd | (Intercept) | 3 | 0.4063 | 0.2973 |
| herd | (Intercept) | 4 | 0.0393 | 0.4164 |
| herd | (Intercept) | 5 | −0.1900 | 0.3504 |
| herd | (Intercept) | 6 | −0.4003 | 0.3800 |
| herd | (Intercept) | 7 | 0.8894 | 0.3265 |
| herd | (Intercept) | 8 | 0.5994 | 0.3211 |
| herd | (Intercept) | 9 | −0.2377 | 0.4614 |
| herd | (Intercept) | 10 | −0.5409 | 0.3707 |
| herd | (Intercept) | 11 | −0.0846 | 0.3091 |
| herd | (Intercept) | 12 | −0.0648 | 0.4411 |
| herd | (Intercept) | 13 | −0.6899 | 0.3848 |
| herd | (Intercept) | 14 | 0.9707 | 0.3554 |
| herd | (Intercept) | 15 | −0.5305 | 0.3977 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.1228 | .339 |
| Spread (observed / simulated) | 1.388 | .288 |
| Zeros (observed / simulated) | 1.140 | .504 |
| Outliers (rows at the edge of their simulations) | 0 | 1.000 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Logistic GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); latent residual variance π²/3.
Wald χ²(3) = 24.95, p < .001
- ICC (latent scale)
- 0.1114
- R² marginal
- 0.0854
- R² conditional
- 0.1873
- AIC
- 194.05
- Random effects LR test p
- < .001
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Non-singular fit — Every variance component is clearly above zero.
- Enough groups — 15 levels of herd.
- Simulated residuals look uniform — Kolmogorov–Smirnov D = 0.123, p = .339 over 250 simulations.
- Residual spread matches the model (simulation) — Observed / simulated spread = 1.39, p = .288.
- Number of zeros matches the model (simulation) — Observed / simulated zeros = 1.14, p = .504.
- No more outliers than expected (simulation) — 0 of 56 rows sit at the edge of their 250 simulations (within 1/251 of either end; binomial test, p = 1.000).
Fixed effects
| Term | B (link scale) | SE | z | p | Odds ratio | 95% CI low | 95% CI high |
|---|---|---|---|---|---|---|---|
| (Intercept) | −1.399 | 0.2325 | −6.016 | < .001 | 0.2470 | 0.1566 | 0.3895 |
| period: 2 | −0.9923 | 0.3066 | −3.236 | .001 | 0.3707 | 0.2032 | 0.6762 |
| period: 3 | −1.129 | 0.3266 | −3.455 | < .001 | 0.3235 | 0.1705 | 0.6136 |
| period: 4 | −1.580 | 0.4274 | −3.697 | < .001 | 0.2059 | 0.0891 | 0.4759 |
Odds ratios are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.
Joint Wald tests of each predictor
| Term | Wald χ² | df | p |
|---|---|---|---|
| period | 24.949 | 3 | < .001 |
Random effects (link scale)
| Group | Effect | Variance | SD | Correlation |
|---|---|---|---|---|
| herd | (Intercept) | 0.4125 | 0.6423 | — |
Conditional modes of the random effects
| Group | Effect | Level | Mode | Conditional SD |
|---|---|---|---|---|
| herd | (Intercept) | 1 | 0.5900 | 0.3483 |
| herd | (Intercept) | 2 | −0.2989 | 0.3656 |
| herd | (Intercept) | 3 | 0.4063 | 0.2973 |
| herd | (Intercept) | 4 | 0.0393 | 0.4164 |
| herd | (Intercept) | 5 | −0.1900 | 0.3504 |
| herd | (Intercept) | 6 | −0.4003 | 0.3800 |
| herd | (Intercept) | 7 | 0.8894 | 0.3265 |
| herd | (Intercept) | 8 | 0.5994 | 0.3211 |
| herd | (Intercept) | 9 | −0.2377 | 0.4614 |
| herd | (Intercept) | 10 | −0.5409 | 0.3707 |
| herd | (Intercept) | 11 | −0.0846 | 0.3091 |
| herd | (Intercept) | 12 | −0.0648 | 0.4411 |
| herd | (Intercept) | 13 | −0.6899 | 0.3848 |
| herd | (Intercept) | 14 | 0.9707 | 0.3554 |
| herd | (Intercept) | 15 | −0.5305 | 0.3977 |
Simulated residual checks (DHARMa)
| Check | Statistic | p |
|---|---|---|
| Uniformity (Kolmogorov–Smirnov D) | 0.1228 | .339 |
| Spread (observed / simulated) | 1.388 | .288 |
| Zeros (observed / simulated) | 1.140 | .504 |
| Outliers (rows at the edge of their simulations) | 0 | 1.000 |
250 simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values.
- Logistic GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); latent residual variance π²/3.
Do it in CodeSplash Run it on your own data, in Python or R, with the code to prove it.
Worked examples in the app
- Cbpp trialss1_cbpp · group: herd · outcome: incidence · predictors: period · trials: size
- Visits binarys1_visits · group: patient · outcome: adverse event · predictors: visit, treatment, age
- Ticks poisson nesteds1_ticks · group: location · group2: brood · outcome: ticks · predictors: year, height (z)
- Visits slopes1_visits · group: patient · outcome: adverse event · predictors: visit, treatment · slopes: visit
- Degenerate n3s1_cbpp · group: herd · outcome: incidence · predictors: period · trials: size
- Degenerate single levels1_cbpp · group: herd · outcome: incidence · predictors: period · trials: size
In the guides
Tests from the statistics guide this method runs
Where it sits in the decision guides
- Binary outcome: logistic regression (regularized) · Statistics Guide · D — Predict an outcome
- Count outcome: Poisson / negative binomial / zero-inflated · Statistics Guide · D — Predict an outcome
- Repeated / clustered: mixed models, GEE · Statistics Guide · D — Predict an outcome
- Generalized models · Statistics Guide · Step 3 — If assumptions are violated
What you need
- Outcomeboolean / categorical / numeric · 1 column
- Yes/no (logistic), a count of successes with Trials (logistic), or a count (Poisson).
- Trialsnumeric · 0–1 column
- Logistic with counts: the number of trials per row (the outcome is the number of successes).
- Exposurenumeric · 0–1 column
- Poisson: time at risk or size per row (> 0); its log is an offset, so effects are rate ratios.
- Fixed effectsnumeric / categorical / boolean · 0–20 columns · 2–30 levels
- Predictors with fixed effects (the same for every group).
- Grouping factorcategorical / numeric / boolean · 1 column
- The unit rows belong to (subject, herd, site); each gets its own random intercept.
- Random slopesnumeric · 0–2 columns
- Numeric predictors whose effect may differ between groups.
- Second grouping factorcategorical / numeric / boolean · 0–1 column
- Nested in the first or crossed with it.
Choices you make
statistics
- Outcome modeldefault binomial
Logistic for yes/no outcomes (or successes out of trials); Poisson for counts.
- Logistic (yes/no or successes of trials)(default) — Fits a logistic mixed model; pick it for yes/no outcomes or successes out of trials.
- Poisson (counts) — Fits a log-link count model; pick it for counts whose variance is near their mean.
- Second grouping factor isdefault nested
Whether the second grouping factor is nested in the first (classes in schools) or crossed with it.
- Nested in the first ((1 | g1/g2))(default) — Treats the second group as inside the first, so its labels matter only within it; pick it for pupils in classes in schools.
- Crossed with the first ((1 | g2)) — Treats the second group as separate from the first; pick it for subjects crossed with items.
- Random intercepts and slopesdefault correlated
Whether random intercepts and slopes may correlate (usual), or are kept independent (simpler; can help convergence).
- Correlated ((1 + x | g))(default) — Estimates how random intercepts and slopes move together; the usual choice.
- Independent ((1 + x || g)) — Sets that correlation to zero; pick it when the correlated fit fails to converge or is singular.
- Interactionsdefault none
Add interaction terms so the effect of one predictor can depend on the value of another.
- None (main effects only)(default) — Fits main effects only; the usual starting point and the easiest to read.
- First two predictors (A × B) — Adds the A × B term for the first two predictors; pick it when you expect one effect to depend on the other.
- All pairs of predictors — Adds every two-way term; uses many coefficients, so pick it with plenty of rows and a reason to look.
- Test the random effects (likelihood ratio)default on
Test whether the random effects are needed, with a likelihood-ratio test against the model without them.
hypothesis
- Event (modeled level)default —
Yes/no outcomes: the level whose probability is modeled (default: the second level, true for yes/no).
- Confidence leveldefault 0.95
How sure the intervals should be: 0.95 gives 95% confidence intervals. Higher confidence means wider intervals.
Checks and remedies
CodeSplash checks each testable assumption on every run and shows the result on the card; premises the data can’t test are marked. If a check fails, these are the ways forward.
Non-singular fit
Enough groups
No overdispersion (Poisson)
Pearson χ² / residual df of the conditional fit; values well above 1 suggest an observation-level random effect or a negative binomial model.
Simulated residuals look uniform
DHARMa: each row's residual is where its value falls among 250 simulations from the fitted model (new random effects each time); a Kolmogorov–Smirnov test checks they are uniform.
Residual spread matches the model (simulation)
Counts and successes of trials: the spread of the observed values around the population-level prediction (random effects at zero, as DHARMa) against the same spread in each simulation (two-sided simulation test). Above 1 is overdispersion.
Number of zeros matches the model (simulation)
Counts and successes of trials: the observed number of zeros against the simulations (two-sided simulation test).
No more outliers than expected (simulation)
Rows whose residual is within 1 / (simulations + 1) of 0 or 1 (at or beyond the edge of their simulations), against the expected 2 / (simulations + 1) share (DHARMa's binomial test; approximate for whole-number outcomes, where it can flag too often).
What it reports
- Tests: First fixed effect (Wald test)
- n
- How many independent units the analysis used; it sets precision and power.
- k
- How many groups, studies or clusters the analysis used. Many methods are less reliable when k is small.
- n_groups
- How many independent units the analysis used; it sets precision and power.
- family
- The exact variant that ran (for example Welch vs classic F), shown so the result can be reported and reproduced.
- log_lik
- The logarithm of the likelihood; higher (less negative) means the model fits the data better.
- deviance
- Twice the gap in log-likelihood between a model and a perfect fit; GLMs' analog of the residual sum of squares.
- aic
- A model score balancing fit against complexity; lower is better, and only differences matter.
- bic
- Like AIC but with a stronger penalty for parameters as n grows; favors simpler models.
- icc
- The share of variance due to differences between groups (or raters' agreement on the same subjects).
- r2_marginal
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- r2_conditional
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- var_fixed
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- var_random
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- var_residual
- Marginal R² counts the fixed effects, and conditional R² counts the fixed and random effects together.
- singular
- A mixed model estimated a variance of zero or a perfect correlation; the random-effects structure is too rich for the data.
- n_params
- How many values a model learns from the data: a regression's coefficients (intercept included) or a network's weights and biases.
- n_theta
- How many independent units the analysis used; it sets precision and power.
- max_interaction_order
- The most factors combined in one term of the model: 1 means main effects only, 2 two-way interactions.
- missing_share
- Values that were not recorded; how they went missing decides which fixes are safe.
- focal_chi2
- A sum of squared, scaled differences between observed and expected counts or estimates.
- focal_df
- How much independent information is left to estimate variability after fitting the model.
- focal_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- dharma_n_sim
- How many data sets were simulated from the fitted model to build the scaled (DHARMa-style) residuals.
- dharma_ks
- Kolmogorov–Smirnov distance of the scaled residuals from uniform; a small p-value says the model's distribution is off.
- dharma_ks_p
- How surprising your data would be if the null hypothesis were true, as a probability.
- dharma_outliers
- Rows whose value fell outside every simulated value; more than chance expects suggests misfit or unusual rows.
- dharma_outlier_p
- How surprising your data would be if the null hypothesis were true, as a probability.
Per group, level or term: coef[<term>], se[…], z[…], p[…], ci_low[…], ci_high[…], ratio[…], ratio_ci_low[…], ratio_ci_high[…], chi2[<predictor>], chi2_df[…], chi2_p[…], var[<group>|<effect>], sd[…], cor[<group>|<effect>|<effect>], n_groups2, re_lrt, re_lrt_df, re_lrt_p, dispersion, dharma_disp_ratio, dharma_disp_p, dharma_zero_ratio, dharma_zero_p
Python and R
Python and R agree within simulation error (relative tolerance 1e-4). Python uses pandas, numpy, scipy, codesplash; R uses lme4, nanoparquet, codesplashr.
Default traps between the two languages
- Python has no glmer: the Python engine computes the same Laplace approximation as lme4 (penalized IRLS for the conditional modes to machine precision, objective −2 log f(y|u) + ‖u‖² + log|L|², a clamped logit link, the two-stage θ then (θ, β) optimization). The Laplace objective is flat along correlated fixed effects (e.g. an uncentered covariate and the intercept): with R's bobyqa at rhoend = 1e-12 both engines reach objectives equal to ~1e-10 but parameters only to ~1e-5 (the Python optimum is the lower one in our fixtures).
- Simulated residuals (DHARMa): both engines draw from the same portable random stream (codesplash.stats.dharma ↔ codesplashr cs_dharma_*) in the same order, so given the same fitted model they simulate the same responses; a draw within ~1e-5 of a count's cumulative-probability boundary can still differ through the engines' ~1e-5 difference in estimates, so the simulation p-values (multiples of 1/250) and counts can differ by one step. For successes out of trials the spread is measured around the expected successes (DHARMa 0.5 measures it around the probability).
- Standard errors come from a central finite-difference Hessian of the Laplace deviance (step 1e-4 in Python; lme4's default in R), evaluated at each engine's optimum, so SEs, z and Wald statistics agree to ~5e-5 and tail p-values to ~5e-4 relative.
The exact script CodeSplash ran for example “Cbpp trials” · Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec db67e9043ca420ed
# Dataset: s1_cbpp (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import numpy as np
import pandas as pd
from scipy import stats
import codesplash as cs
from codesplash.stats import mixed as mx # twin of lme4::glmer (Laplace, nAGQ = 1) — no Python library fits it
from codesplash.stats import regression as csreg
from codesplash.stats import dharma # simulated residuals, twin of codesplashr::cs_dharma_*
# %% Data
df = pd.read_parquet("tests/parity/fixtures/s1_cbpp.parquet", columns=["incidence", "size", "period", "herd"])
n_input = len(df)
df["period"] = pd.Categorical(df["period"], categories=["1", "2", "3", "4"]) # stored level order
df["herd"] = pd.Categorical(df["herd"], categories=["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"]) # stored level order
df = df.dropna(subset=["incidence", "size", "period", "herd"]) # listwise deletion over the analysis columns
df["period"] = df["period"].cat.remove_unused_categories()
df["herd"] = df["herd"].cat.remove_unused_categories()
n_dropped = n_input - len(df)
warnings = []
if n_dropped:
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_dropped, total=n_input))
if n_input and not len(df):
cs.cs_error("CS_E_NO_ROWS")
cs.check_finite_columns(df, ["incidence", "size", "period", "herd"]) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome = "incidence"
trials = "size"
exposure = None
predictors = ["period"]
group = "herd"
slopes = []
group2 = None
family = "binomial" # binomial (logit) | poisson (log)
nesting = "nested"
correlated = "correlated" == "correlated"
interactions = "none"
conf = 0.95
event = None
w = np.ones(len(df))
offset = np.zeros(len(df))
if isinstance(df[outcome].dtype, pd.CategoricalDtype):
levels_y = [str(x) for x in df[outcome].cat.categories]
if family != "binomial" or len(levels_y) != 2:
raise ValueError(f"{outcome} is categorical: use the logistic model with exactly two levels (found {len(levels_y)}).")
event = levels_y[1] # default: the second stored level ("true" for yes/no)
y = (df[outcome].astype(str) == event).to_numpy(dtype=float)
else:
y = df[outcome].to_numpy(dtype=float)
if (y < 0).any() or (np.abs(y - np.round(y)) > 1e-9).any():
raise ValueError(f"{outcome} must hold whole non-negative numbers (counts or 0/1).")
if family == "binomial":
if trials:
w = df[trials].to_numpy(dtype=float)
if (w <= 0).any() or (y > w).any():
raise ValueError(f"{trials} must be positive and at least {outcome} on every row.")
y = y / w # proportion of successes with binomial weights = trials (lme4's cbind(succ, fail))
elif not np.all(np.isin(y, (0.0, 1.0))):
raise ValueError(f"{outcome} must be 0/1 for a logistic model (or give the number of Trials).")
if family == "poisson" and exposure:
if (df[exposure] <= 0).any():
raise ValueError(f"{exposure} must be positive (its log is the offset).")
offset = np.log(df[exposure].to_numpy(dtype=float))
re = mx.re_terms(df, group, slopes, group2, nesting, correlated)
# Degenerate input stops with a catalog error before the fit; R runs the same checks in the same order.
mx.check_re_terms(re, len(df), allow_n=True) # glmer's checks on the grouping factors
for pred in predictors:
if df[pred].nunique() < 2: # one value (or one level with data) is no variation
cs.cs_error("CS_E_CONSTANT", column=pred)
X = csreg.design_matrix(df, predictors, interactions)
terms_x = list(X.columns)
n, k = X.shape
# %% Fit (Laplace; covariance of β from the finite-difference Hessian, lme4's default)
model = mx.Glmm(y, X.to_numpy(), re, family, weights=w, offset=offset)
fit = model.fit()
b = fit.beta
se = np.sqrt(np.diag(fit.vcov))
zval = b / se
pval = 2 * stats.norm.sf(np.abs(zval))
crit = stats.norm.ppf(1 - (1 - conf) / 2)
values = {}
coefs = []
for j, t in enumerate(terms_x):
row = {"term": t, "estimate": float(b[j]), "se": float(se[j]), "z": float(zval[j]), "p": float(pval[j]),
"ci_low": float(b[j] - crit * se[j]), "ci_high": float(b[j] + crit * se[j])}
row.update({"ratio": float(np.exp(b[j])), "ratio_ci_low": float(np.exp(row["ci_low"])), "ratio_ci_high": float(np.exp(row["ci_high"]))})
coefs.append(row)
values.update({f"{key}[{t}]": row["estimate" if key == "coef" else key] for key in ("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")})
effects = []
for name, idx in mx.term_blocks(terms_x, predictors, csreg.interaction_pairs(len(predictors), interactions)):
bb = b[idx]
chi2 = float(bb @ np.linalg.solve(fit.vcov[np.ix_(idx, idx)], bb))
pc = float(stats.chi2.sf(chi2, len(idx)))
effects.append({"term": name, "chi2": chi2, "df": len(idx), "p": pc})
values.update({f"chi2[{name}]": chi2, f"chi2_df[{name}]": float(len(idx)), f"chi2_p[{name}]": pc})
values.update({"focal_chi2": None, "focal_df": None, "focal_p": None})
if effects:
values.update({"focal_chi2": effects[0]["chi2"], "focal_df": float(effects[0]["df"]), "focal_p": effects[0]["p"]})
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
vc = mx.varcorr(re, fit.theta, 1.0)
for r in vc:
if r["var2"] is None:
values[f"var[{r['grp']}|{r['var1']}]"] = r["vcov"]
values[f"sd[{r['grp']}|{r['var1']}]"] = r["sdcor"]
else:
values[f"cor[{r['grp']}|{r['var1']}|{r['var2']}]"] = r["sdcor"]
eta_fixed = X.to_numpy() @ b
var_fixed = float(np.var(eta_fixed, ddof=1)) if n > 1 else 0.0
var_random = mx.random_variance(re, fit.theta, 1.0)
if family == "binomial":
var_residual = np.pi**2 / 3 # logistic latent variance
else:
lam = np.exp(np.mean(eta_fixed) + var_random / 2) # lognormal approximation of the observation-level variance
var_residual = float(np.log1p(1 / lam))
total = var_fixed + var_random + var_residual
n_theta = len(fit.theta)
n_params = k + n_theta
values.update({"n": n, "k": k, "n_groups": re[0].nlev, "family": family, "log_lik": fit.log_lik, "deviance": fit.objective,
"aic": fit.objective + 2 * n_params, "bic": fit.objective + np.log(n) * n_params, "icc": var_random / (var_random + var_residual),
"r2_marginal": var_fixed / total, "r2_conditional": (var_fixed + var_random) / total, "var_fixed": var_fixed,
"var_random": var_random, "var_residual": float(var_residual), "singular": fit.singular, "n_params": n_params, "n_theta": n_theta,
"max_interaction_order": 2 if interactions != "none" and len(predictors) >= 2 else 1,
"missing_share": n_dropped / n_input if n_input else 0.0})
if group2:
values["n_groups2"] = re[-1].nlev
# %% Random effects vs none (likelihood ratio against the GLM)
if True:
beta_glm = model._glm_start()
mu_glm = model.linkinv(X.to_numpy() @ beta_glm + offset)
ll_glm = -0.5 * float(np.sum(model.m2ll(y, mu_glm, w)))
lrt = max(2 * (fit.log_lik - ll_glm), 0.0)
lrt_p = float(stats.chi2.sf(lrt, n_theta))
if n_theta == 1:
lrt_p /= 2 # boundary: 50:50 mixture of χ²(0) and χ²(1)
values.update({"re_lrt": lrt, "re_lrt_df": float(n_theta), "re_lrt_p": lrt_p})
# %% Assumptions
assumptions = [{"key": "singular", "label": "Non-singular fit", "status": "warn" if fit.singular else "pass",
"detail": "A variance component is estimated at (or near) zero: simplify the random effects." if fit.singular else "Every variance component is clearly above zero."}]
few = [t.group for t in re if t.nlev < 5]
assumptions.append({"key": "groups", "label": "Enough groups", "status": "warn" if few else "pass",
"detail": (f"Fewer than 5 levels for {', '.join(dict.fromkeys(few))}: its variance is estimated very imprecisely." if few else f"{re[0].nlev} levels of {group}.")})
if family == "poisson":
mu = fit.mu
disp = float(np.sum((y - mu) ** 2 / mu) / (n - k))
values["dispersion"] = disp
assumptions.append({"key": "overdispersion", "label": "No overdispersion", "status": "warn" if disp > 1.5 else "pass", "statistic": disp,
"detail": f"Pearson χ² / residual df = {disp:.2f}" + ("; consider an observation-level random effect or a negative binomial model." if disp > 1.5 else ".")})
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like = family == "poisson" or trials is not None # spread and zeros are checked for counts, not for 0/1 data
m_trials = w if (family == "binomial" and trials) else None
rng = dharma.Rng(dharma.SEED)
eta_pop = X.to_numpy() @ b + offset # fixed part: the simulations draw new random effects around it
sims = dharma.simulate(eta_pop, dharma.sim_terms(re, vc), family, m_trials, dharma.N_SIM, rng)
y_obs = np.round(y * w) if m_trials is not None else y # successes for successes-of-trials outcomes
fitted_resp = dharma.mean_response(eta_pop, family) * (w if m_trials is not None else 1.0) # population-level, as DHARMa
dh = dharma.residuals(y_obs, fitted_resp, sims, family, rng, zeros=counts_like)
values.update({"dharma_n_sim": dh["n_sim"], "dharma_ks": dh["ks"], "dharma_ks_p": dh["ks_p"], "dharma_outliers": dh["outliers"],
"dharma_outlier_p": dh["outlier_p"]})
uni_bad = dh["ks_p"] < 0.05
assumptions.append({"key": "uniformity", "label": "Simulated residuals look uniform", "status": "warn" if uni_bad else "pass",
"statistic": dh["ks"], "p": dh["ks_p"],
"detail": f"Kolmogorov–Smirnov D = {dh['ks']:.3f}, {cs.fmt_p(dh['ks_p'])} over {dh['n_sim']} simulations"
+ ("; the outcome's distribution doesn't match the model (check the residual plots)." if uni_bad else ".")})
if counts_like:
values.update({"dharma_disp_ratio": dh["disp_ratio"], "dharma_disp_p": dh["disp_p"], "dharma_zero_ratio": dh["zero_ratio"], "dharma_zero_p": dh["zero_p"]})
disp_bad = dh["disp_p"] < 0.05
over = dh["disp_ratio"] > 1
assumptions.append({"key": "dispersion", "label": "Residual spread matches the model (simulation)", "status": "warn" if disp_bad else "pass",
"statistic": dh["disp_ratio"], "p": dh["disp_p"],
"detail": f"Observed / simulated spread = {dh['disp_ratio']:.2f}, {cs.fmt_p(dh['disp_p'])}"
+ (("; overdispersion: consider an observation-level random effect or a negative binomial model." if over else "; underdispersion: standard errors are conservative.") if disp_bad else ".")})
zero_bad = dh["zero_p"] < 0.05
assumptions.append({"key": "zero_inflation", "label": "Number of zeros matches the model (simulation)", "status": "warn" if zero_bad else "pass",
"statistic": dh["zero_ratio"], "p": dh["zero_p"],
"detail": f"Observed / simulated zeros = {dh['zero_ratio']:.2f}, {cs.fmt_p(dh['zero_p'])}"
+ (("; more zeros than the model expects: consider a zero-inflated or hurdle model." if dh["zero_ratio"] > 1 else "; fewer zeros than the model expects.") if zero_bad else ".")})
out_bad = dh["outlier_p"] < 0.05
assumptions.append({"key": "outliers", "label": "No more outliers than expected (simulation)", "status": "warn" if out_bad else "pass",
"statistic": float(dh["outliers"]), "p": dh["outlier_p"],
"detail": f"{dh['outliers']} of {n} rows sit at the edge of their {dh['n_sim']} simulations (within 1/{dh['n_sim'] + 1} of either end; binomial test, {cs.fmt_p(dh['outlier_p'])})."})
if not fit.hessian_ok:
warnings.append("The finite-difference Hessian is not positive definite: standard errors use the RX approximation (conditional on the variance parameters), as lme4 falls back to.")
# %% Result
pct = f"{conf:.0%}"
rl = "Odds ratio" if family == "binomial" else "Rate ratio"
re_rows = []
off = 0
for ti, t in enumerate(re):
for j, eff in enumerate(t.effects):
for g, lv in enumerate(t.levels):
re_rows.append({"group": t.group, "effect": eff, "level": lv, "estimate": float(fit.b[off + g * t.k + j]),
"sd": float(np.sqrt(max(fit.cond_var[ti][g][j, j], 0.0)))})
off += t.nlev * t.k
vc_rows = [{"group": r["grp"], "effect": r["var1"] if r["var2"] is None else f"{r['var1']} ~ {r['var2']}",
"variance": r["vcov"] if r["var2"] is None else None, "sd": r["sdcor"] if r["var2"] is None else None,
"cor": r["sdcor"] if r["var2"] is not None else None} for r in vc]
slopes_tab = [c for c in coefs if c["term"] != "(Intercept)"]
tests_text = f" {effects[0]['term']}: Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}." if effects else ""
summary = (f"{'Logistic' if family == 'binomial' else 'Poisson'} mixed model of {outcome}" + (f" (event: {event})" if event else "")
+ f" (n = {n}, {re[0].nlev} levels of {group}).{tests_text} Latent-scale ICC = {values['icc']:.2f}.")
z = stats.norm.ppf(1 - (1 - conf) / 2)
cat_rows = re_rows[:1000]
charts = [cs.chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", {
"group": cs.col("Level", [r["level"] for r in cat_rows], kind="categorical"), "estimate": cs.col("Conditional mode", [r["estimate"] for r in cat_rows]),
"low": cs.col("low", [r["estimate"] - z * r["sd"] for r in cat_rows]), "high": cs.col("high", [r["estimate"] + z * r["sd"] for r in cat_rows]),
"term": cs.col("Term", [f"{r['group']}: {r['effect']}" for r in cat_rows], kind="categorical")})]
if slopes_tab:
charts.append(cs.chart("ratios", "forest", f"{rl}s", {
"label": cs.col("Term", [c["term"] for c in slopes_tab], kind="categorical"), "estimate": cs.col(rl, [c["ratio"] for c in slopes_tab]),
"low": cs.col("low", [c["ratio_ci_low"] for c in slopes_tab]), "high": cs.col("high", [c["ratio_ci_high"] for c in slopes_tab])},
controls={"reference": 1, "log": True}))
tables = [{"key": "fixed", "title": "Fixed effects", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "estimate", "label": "B (link scale)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "z", "label": "z", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}, {"key": "ratio", "label": rl, "type": "number"},
{"key": "ratio_ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ratio_ci_high", "label": f"{pct} CI high", "type": "number"}],
"rows": coefs, "note": f"{rl}s are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance."}]
if effects:
tables.append({"key": "effects", "title": "Joint Wald tests of each predictor", "columns": [
{"key": "term", "label": "Term", "type": "string"}, {"key": "chi2", "label": "Wald χ²", "type": "number"},
{"key": "df", "label": "df", "type": "integer"}, {"key": "p", "label": "p", "type": "pvalue"}], "rows": effects})
tables.append({"key": "random", "title": "Random effects (link scale)", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"},
{"key": "variance", "label": "Variance", "type": "number"}, {"key": "sd", "label": "SD", "type": "number"}, {"key": "cor", "label": "Correlation", "type": "number"}],
"rows": vc_rows})
tables.append({"key": "modes", "title": "Conditional modes of the random effects", "columns": [
{"key": "group", "label": "Group", "type": "string"}, {"key": "effect", "label": "Effect", "type": "string"}, {"key": "level", "label": "Level", "type": "string"},
{"key": "estimate", "label": "Mode", "type": "number"}, {"key": "sd", "label": "Conditional SD", "type": "number"}], "rows": re_rows[:2000]})
dh_rows = [{"check": "Uniformity (Kolmogorov–Smirnov D)", "statistic": dh["ks"], "p": dh["ks_p"]}]
if counts_like:
dh_rows += [{"check": "Spread (observed / simulated)", "statistic": dh["disp_ratio"], "p": dh["disp_p"]},
{"check": "Zeros (observed / simulated)", "statistic": dh["zero_ratio"], "p": dh["zero_p"]}]
dh_rows.append({"check": "Outliers (rows at the edge of their simulations)", "statistic": float(dh["outliers"]), "p": dh["outlier_p"]})
tables.append({"key": "dharma", "title": "Simulated residual checks (DHARMa)", "columns": [
{"key": "check", "label": "Check", "type": "string"}, {"key": "statistic", "label": "Statistic", "type": "number"}, {"key": "p", "label": "p", "type": "pvalue"}],
"rows": dh_rows, "note": f"{dh['n_sim']} simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed {dharma.SEED}. "
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."})
m_show = min(n, 5000) # evenly spaced rows for the residual charts
show = [(i * (n - 1)) // (m_show - 1) if m_show > 1 else 0 for i in range(m_show)]
res_show = [float(dh["residuals"][i]) for i in show]
charts.append(cs.chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", {"x": cs.col("Scaled residual", res_show)},
controls={"reference": "uniform"}))
rank_fit = dharma.rank01(fitted_resp)
charts.append(cs.chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", {
"x": cs.col("Population-level prediction (rank, 0–1)", [float(rank_fit[i]) for i in show]), "y": cs.col("Scaled residual", res_show)}, controls={"fit": "loess"}))
statistics = [{"key": "icc", "label": "ICC (latent scale)", "value": values["icc"]}, {"key": "r2_marginal", "label": "R² marginal", "value": values["r2_marginal"]},
{"key": "r2_conditional", "label": "R² conditional", "value": values["r2_conditional"]}, {"key": "aic", "label": "AIC", "value": values["aic"]}]
if "re_lrt_p" in values:
statistics.append({"key": "re_lrt_p", "label": "Random effects LR test p", "value": values["re_lrt_p"], "format": "p"})
cs.publish({
"method": "mixed.glmm",
"methodVersion": "1.1.0",
"title": "Generalized linear mixed model",
"engine": cs.engine_info("pandas", "numpy", "scipy"),
"n": n,
"summary": summary,
"apa": (f"Wald χ²({effects[0]['df']}) = {effects[0]['chi2']:.2f}, {cs.fmt_p(effects[0]['p'])}" if effects else ""),
"statistics": statistics,
"tables": tables,
"effectSizes": [],
"assumptions": assumptions,
"warnings": warnings,
"notes": [("Logistic" if family == "binomial" else "Poisson") + " GLMM by the Laplace approximation (twin of lme4::glmer, nAGQ = 1); "
+ ("latent residual variance π²/3." if family == "binomial" else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")],
"charts": charts,
"values": values,
})
The exact script CodeSplash ran for example “Cbpp trials” · R version 4.5.1 (2025-06-13)
# Generalized linear mixed model (logistic / Poisson)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method mixed.glmm 1.1.0 · spec db67e9043ca420ed
# Dataset: s1_cbpp (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
suppressPackageStartupMessages(library(lme4))
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s1_cbpp.parquet", col_select = c("incidence", "size", "period", "herd")))
n_input <- nrow(df)
df[["period"]] <- factor(df[["period"]], levels = c("1", "2", "3", "4")) # stored level order
df[["herd"]] <- factor(df[["herd"]], levels = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15")) # stored level order
df <- df[stats::complete.cases(df[c("incidence", "size", "period", "herd")]), , drop = FALSE] # listwise deletion
df[] <- lapply(df, function(x) if (is.factor(x)) droplevels(x) else x)
n_dropped <- n_input - nrow(df)
warnings <- list()
if (n_dropped > 0) {
warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_dropped, total = n_input))
}
if (n_input > 0 && nrow(df) == 0) cs_error("CS_E_NO_ROWS")
cs_check_finite_columns(df, c("incidence", "size", "period", "herd")) # infinite values stop the run (registry/errors.yaml)
# %% Model
outcome <- "incidence"
trials <- "size"
exposure <- NULL
predictors <- c("period")
group <- "herd"
slopes <- c()
group2 <- NULL
family <- "binomial" # binomial (logit) | poisson (log)
nesting <- "nested"
correlated <- "correlated" == "correlated"
interactions <- "none"
conf <- 0.95
df[[group]] <- cs_mixed_group(df[[group]])
if (!is.null(group2)) df[[group2]] <- cs_mixed_group(df[[group2]])
event <- NULL
lhs <- NULL
w <- rep(1, nrow(df))
if (is.factor(df[[outcome]])) {
if (family != "binomial" || nlevels(df[[outcome]]) != 2) stop(sprintf("%s is categorical: use the logistic model with exactly two levels (found %d).", outcome, nlevels(df[[outcome]])))
event <- levels(df[[outcome]])[2] # default: the second stored level ("true" for yes/no)
df$.cs_y <- as.numeric(as.character(df[[outcome]]) == event)
y <- df$.cs_y
lhs <- ".cs_y"
} else {
y <- as.numeric(df[[outcome]])
if (any(y < 0) || any(abs(y - round(y)) > 1e-9)) stop(sprintf("%s must hold whole non-negative numbers (counts or 0/1).", outcome))
if (family == "binomial" && !is.null(trials)) {
w <- df[[trials]]
if (any(w <= 0) || any(y > w)) stop(sprintf("%s must be positive and at least %s on every row.", trials, outcome))
df$.cs_succ <- y
df$.cs_fail <- w - y
lhs <- "cbind(.cs_succ, .cs_fail)" # successes out of trials
y <- y / w
} else if (family == "binomial" && !all(y %in% c(0, 1))) {
stop(sprintf("%s must be 0/1 for a logistic model (or give the number of Trials).", outcome))
}
}
offset <- rep(0, nrow(df))
if (family == "poisson" && !is.null(exposure)) {
if (any(df[[exposure]] <= 0)) stop(sprintf("%s must be positive (its log is the offset).", exposure))
offset <- log(df[[exposure]])
}
df$.cs_offset <- offset
# Degenerate input stops with a catalog error before the fit; Python runs the same checks in the same order.
cs_mixed_check_re(df, group, slopes, group2, nesting, correlated, allow_n = TRUE) # glmer's checks on the grouping factors
for (pred in predictors) {
if (length(unique(df[[pred]])) < 2) cs_error("CS_E_CONSTANT", column = pred) # one value (or one level with data) is no variation
}
fml <- cs_mixed_formula(outcome, predictors, interactions, group, slopes, group2, nesting, correlated, lhs = lhs)
fam <- if (family == "binomial") binomial() else poisson()
# Tight tolerances (default: bobyqa then Nelder–Mead, tolPwrss = 1e-7) so both engines reach the same optimum.
ctrl <- glmerControl(optimizer = c("bobyqa", "bobyqa"), optCtrl = list(rhoend = 1e-12, maxfun = 1e6), tolPwrss = 1e-12)
# %% Fit (Laplace, nAGQ = 1)
fit <- glmer(fml, data = df, family = fam, offset = .cs_offset, nAGQ = 1, control = ctrl)
X <- getME(fit, "X")
terms_x <- cs_design_labels(df, predictors, interactions)
if (ncol(X) < length(terms_x)) cs_error("CS_E_COLLINEAR")
n <- nrow(X)
k <- ncol(X)
b <- unname(fixef(fit))
V <- as.matrix(vcov(fit)) # lme4 default: from the finite-difference Hessian
se <- sqrt(diag(V))
zval <- b / se
pval <- 2 * pnorm(abs(zval), lower.tail = FALSE)
crit <- qnorm(1 - (1 - conf) / 2)
values <- list()
coefs <- list()
for (j in seq_len(k)) {
t <- terms_x[j]
row <- list(term = t, estimate = b[j], se = se[j], z = zval[j], p = pval[j], ci_low = b[j] - crit * se[j], ci_high = b[j] + crit * se[j])
row <- c(row, list(ratio = exp(b[j]), ratio_ci_low = exp(row$ci_low), ratio_ci_high = exp(row$ci_high)))
coefs[[j]] <- row
for (key in c("coef", "se", "z", "p", "ci_low", "ci_high", "ratio", "ratio_ci_low", "ratio_ci_high")) values[[sprintf("%s[%s]", key, t)]] <- if (key == "coef") row$estimate else row[[key]]
}
effects <- list()
blocks <- cs_mixed_term_blocks(terms_x, predictors, interactions)
for (name in names(blocks)) {
idx <- blocks[[name]]
chi2 <- as.numeric(t(b[idx]) %*% solve(V[idx, idx, drop = FALSE], b[idx]))
pc <- pchisq(chi2, length(idx), lower.tail = FALSE)
effects[[length(effects) + 1]] <- list(term = name, chi2 = chi2, df = length(idx), p = pc)
values[[sprintf("chi2[%s]", name)]] <- chi2; values[[sprintf("chi2_df[%s]", name)]] <- as.numeric(length(idx)); values[[sprintf("chi2_p[%s]", name)]] <- pc
}
values$focal_chi2 <- NA; values$focal_df <- NA; values$focal_p <- NA # no fixed predictor
if (length(effects)) {
values$focal_chi2 <- effects[[1]]$chi2; values$focal_df <- as.numeric(effects[[1]]$df); values$focal_p <- effects[[1]]$p
}
# %% Variance components, latent-scale ICC and R² (Nakagawa et al. 2017)
valid <- c(group, group2, if (!is.null(group2)) paste0(group, ":", group2))
vc <- cs_mixed_varcorr(fit, valid)
for (i in seq_len(nrow(vc))) {
if (is.na(vc$effect2[i])) {
values[[sprintf("var[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$vcov[i]
values[[sprintf("sd[%s|%s]", vc$group[i], vc$effect1[i])]] <- vc$sdcor[i]
} else {
values[[sprintf("cor[%s|%s|%s]", vc$group[i], vc$effect1[i], vc$effect2[i])]] <- vc$sdcor[i]
}
}
eta_fixed <- as.vector(X %*% b)
var_fixed <- if (n > 1) var(eta_fixed) else 0
var_random <- cs_mixed_random_variance(fit, df)
var_residual <- if (family == "binomial") pi^2 / 3 else log1p(1 / exp(mean(eta_fixed) + var_random / 2))
total <- var_fixed + var_random + var_residual
n_theta <- length(getME(fit, "theta"))
n_params <- k + n_theta
ll <- as.numeric(logLik(fit))
n_groups <- nlevels(droplevels(df[[group]]))
values <- c(values, list(n = n, k = k, n_groups = n_groups, family = family, log_lik = ll, deviance = -2 * ll, aic = -2 * ll + 2 * n_params,
bic = -2 * ll + log(n) * n_params, icc = var_random / (var_random + var_residual), r2_marginal = var_fixed / total,
r2_conditional = (var_fixed + var_random) / total, var_fixed = var_fixed, var_random = var_random, var_residual = var_residual,
singular = isSingular(fit, tol = 1e-4), n_params = n_params, n_theta = n_theta,
max_interaction_order = if (interactions != "none" && length(predictors) >= 2) 2 else 1,
missing_share = if (n_input > 0) n_dropped / n_input else 0))
if (!is.null(group2)) {
values$n_groups2 <- if (nesting == "nested") nlevels(droplevels(interaction(df[[group]], df[[group2]], drop = TRUE))) else nlevels(droplevels(df[[group2]]))
}
# %% Random effects vs none (likelihood ratio against the GLM)
if (TRUE) {
fixed_rhs <- if (length(predictors)) as.character(cs_model_formula(outcome, predictors, interactions))[3] else "1"
g <- glm(stats::as.formula(paste(if (is.null(lhs)) paste0("`", outcome, "`") else lhs, "~", fixed_rhs)), family = fam, data = df, offset = .cs_offset,
control = glm.control(epsilon = 1e-14, maxit = 100))
lrt <- max(2 * (ll - as.numeric(logLik(g))), 0)
lrt_p <- pchisq(lrt, n_theta, lower.tail = FALSE)
if (n_theta == 1) lrt_p <- lrt_p / 2 # boundary: 50:50 mixture of chi2(0) and chi2(1)
values$re_lrt <- lrt; values$re_lrt_df <- as.numeric(n_theta); values$re_lrt_p <- lrt_p
}
# %% Assumptions
singular <- isTRUE(values$singular)
assumptions <- list(list(key = "singular", label = "Non-singular fit", status = if (singular) "warn" else "pass",
detail = if (singular) "A variance component is estimated at (or near) zero: simplify the random effects." else "Every variance component is clearly above zero."))
nlev <- c(setNames(n_groups, group), if (!is.null(group2)) setNames(values$n_groups2, if (nesting == "nested") paste0(group, ":", group2) else group2))
few <- names(nlev)[nlev < 5]
assumptions[[2]] <- list(key = "groups", label = "Enough groups", status = if (length(few)) "warn" else "pass",
detail = if (length(few)) sprintf("Fewer than 5 levels for %s: its variance is estimated very imprecisely.", paste(few, collapse = ", ")) else sprintf("%d levels of %s.", n_groups, group))
if (family == "poisson") {
mu <- unname(fitted(fit))
disp <- sum((y - mu)^2 / mu) / (n - k)
values$dispersion <- disp
assumptions[[3]] <- list(key = "overdispersion", label = "No overdispersion", status = if (disp > 1.5) "warn" else "pass", statistic = disp,
detail = paste0(sprintf("Pearson χ² / residual df = %.2f", disp), if (disp > 1.5) "; consider an observation-level random effect or a negative binomial model." else "."))
}
# %% Simulated residuals (DHARMa defaults: 250 simulations with new random effects, portable seed 1)
counts_like <- family == "poisson" || !is.null(trials) # spread and zeros are checked for counts, not for 0/1 data
m_trials <- if (family == "binomial" && !is.null(trials)) w else NULL
rng <- cs_rng(1)
dh_terms <- cs_dharma_terms(df, group, slopes, group2, nesting, correlated, vc)
eta_pop <- as.vector(X %*% b) + offset # fixed part: the simulations draw new random effects around it
sims <- cs_dharma_simulate(eta_pop, dh_terms, family, m_trials, 250, rng)
y_obs <- if (!is.null(m_trials)) round(y * w) else y # successes for successes-of-trials outcomes
fitted_resp <- cs_dharma_mean(eta_pop, family) * (if (!is.null(m_trials)) w else 1) # population-level, as DHARMa
dh <- cs_dharma_residuals(y_obs, fitted_resp, sims, family, rng, zeros = counts_like)
values$dharma_n_sim <- dh$n_sim; values$dharma_ks <- dh$ks; values$dharma_ks_p <- dh$ks_p
values$dharma_outliers <- dh$outliers; values$dharma_outlier_p <- dh$outlier_p
uni_bad <- dh$ks_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "uniformity", label = "Simulated residuals look uniform", status = if (uni_bad) "warn" else "pass",
statistic = dh$ks, p = dh$ks_p,
detail = paste0(sprintf("Kolmogorov–Smirnov D = %.3f, %s over %d simulations", dh$ks, cs_fmt_p(dh$ks_p), as.integer(dh$n_sim)),
if (uni_bad) "; the outcome's distribution doesn't match the model (check the residual plots)." else "."))
if (counts_like) {
values$dharma_disp_ratio <- dh$disp_ratio; values$dharma_disp_p <- dh$disp_p
values$dharma_zero_ratio <- dh$zero_ratio; values$dharma_zero_p <- dh$zero_p
disp_bad <- dh$disp_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "dispersion", label = "Residual spread matches the model (simulation)", status = if (disp_bad) "warn" else "pass",
statistic = dh$disp_ratio, p = dh$disp_p,
detail = paste0(sprintf("Observed / simulated spread = %.2f, %s", dh$disp_ratio, cs_fmt_p(dh$disp_p)),
if (!disp_bad) "." else if (dh$disp_ratio > 1) "; overdispersion: consider an observation-level random effect or a negative binomial model." else "; underdispersion: standard errors are conservative."))
zero_bad <- dh$zero_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "zero_inflation", label = "Number of zeros matches the model (simulation)", status = if (zero_bad) "warn" else "pass",
statistic = dh$zero_ratio, p = dh$zero_p,
detail = paste0(sprintf("Observed / simulated zeros = %.2f, %s", dh$zero_ratio, cs_fmt_p(dh$zero_p)),
if (!zero_bad) "." else if (dh$zero_ratio > 1) "; more zeros than the model expects: consider a zero-inflated or hurdle model." else "; fewer zeros than the model expects."))
}
out_bad <- dh$outlier_p < 0.05
assumptions[[length(assumptions) + 1]] <- list(key = "outliers", label = "No more outliers than expected (simulation)", status = if (out_bad) "warn" else "pass",
statistic = as.numeric(dh$outliers), p = dh$outlier_p,
detail = sprintf("%d of %d rows sit at the edge of their %d simulations (within 1/%d of either end; binomial test, %s).", as.integer(dh$outliers), as.integer(n), as.integer(dh$n_sim), as.integer(dh$n_sim) + 1L, cs_fmt_p(dh$outlier_p)))
# %% Result
pct <- sprintf("%.0f%%", conf * 100)
rl <- if (family == "binomial") "Odds ratio" else "Rate ratio"
re_tab <- cs_mixed_ranef(fit, valid)
vc_rows <- lapply(seq_len(nrow(vc)), function(i) {
if (is.na(vc$effect2[i])) list(group = vc$group[i], effect = vc$effect1[i], variance = vc$vcov[i], sd = vc$sdcor[i], cor = NULL)
else list(group = vc$group[i], effect = paste(vc$effect1[i], "~", vc$effect2[i]), variance = NULL, sd = NULL, cor = vc$sdcor[i])
})
slopes_tab <- Filter(function(cf) cf$term != "(Intercept)", coefs)
tests_text <- if (length(effects)) sprintf(" %s: Wald χ²(%d) = %.2f, %s.", effects[[1]]$term, as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else ""
summary <- sprintf("%s mixed model of %s%s (n = %d, %d levels of %s).%s Latent-scale ICC = %.2f.", if (family == "binomial") "Logistic" else "Poisson",
outcome, if (!is.null(event)) sprintf(" (event: %s)", event) else "", n, n_groups, group, tests_text, values$icc)
z <- qnorm(1 - (1 - conf) / 2)
cat_tab <- head(re_tab, 1000)
charts <- list(cs_chart("ranef", "caterpillar", "Random effects (conditional modes, link scale)", list(
group = cs_col("Level", cat_tab$level, kind = "categorical"), estimate = cs_col("Conditional mode", cat_tab$estimate),
low = cs_col("low", cat_tab$estimate - z * cat_tab$sd), high = cs_col("high", cat_tab$estimate + z * cat_tab$sd),
term = cs_col("Term", paste0(cat_tab$group, ": ", cat_tab$effect), kind = "categorical"))))
if (length(slopes_tab)) {
charts[[2]] <- cs_chart("ratios", "forest", paste0(rl, "s"), list(
label = cs_col("Term", vapply(slopes_tab, `[[`, "", "term"), kind = "categorical"), estimate = cs_col(rl, vapply(slopes_tab, `[[`, 0, "ratio")),
low = cs_col("low", vapply(slopes_tab, `[[`, 0, "ratio_ci_low")), high = cs_col("high", vapply(slopes_tab, `[[`, 0, "ratio_ci_high"))),
controls = list(reference = 1, log = TRUE))
}
tables <- list(list(key = "fixed", title = "Fixed effects", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "estimate", label = "B (link scale)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "z", label = "z", type = "number"), list(key = "p", label = "p", type = "pvalue"), list(key = "ratio", label = rl, type = "number"),
list(key = "ratio_ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ratio_ci_high", label = paste(pct, "CI high"), type = "number")),
rows = coefs, note = sprintf("%ss are subject-specific (within a group, random effects held fixed). Wald z tests; covariance from the Hessian of the Laplace deviance.", rl)))
if (length(effects)) {
tables[[length(tables) + 1]] <- list(key = "effects", title = "Joint Wald tests of each predictor", columns = list(
list(key = "term", label = "Term", type = "string"), list(key = "chi2", label = "Wald χ²", type = "number"),
list(key = "df", label = "df", type = "integer"), list(key = "p", label = "p", type = "pvalue")), rows = effects)
}
tables[[length(tables) + 1]] <- list(key = "random", title = "Random effects (link scale)", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"),
list(key = "variance", label = "Variance", type = "number"), list(key = "sd", label = "SD", type = "number"), list(key = "cor", label = "Correlation", type = "number")),
rows = vc_rows)
mode_rows <- lapply(seq_len(min(nrow(re_tab), 2000)), function(i) as.list(re_tab[i, ]))
tables[[length(tables) + 1]] <- list(key = "modes", title = "Conditional modes of the random effects", columns = list(
list(key = "group", label = "Group", type = "string"), list(key = "effect", label = "Effect", type = "string"), list(key = "level", label = "Level", type = "string"),
list(key = "estimate", label = "Mode", type = "number"), list(key = "sd", label = "Conditional SD", type = "number")), rows = mode_rows)
dh_rows <- list(list(check = "Uniformity (Kolmogorov–Smirnov D)", statistic = dh$ks, p = dh$ks_p))
if (counts_like) {
dh_rows <- c(dh_rows, list(list(check = "Spread (observed / simulated)", statistic = dh$disp_ratio, p = dh$disp_p),
list(check = "Zeros (observed / simulated)", statistic = dh$zero_ratio, p = dh$zero_p)))
}
dh_rows[[length(dh_rows) + 1]] <- list(check = "Outliers (rows at the edge of their simulations)", statistic = as.numeric(dh$outliers), p = dh$outlier_p)
tables[[length(tables) + 1]] <- list(key = "dharma", title = "Simulated residual checks (DHARMa)", columns = list(
list(key = "check", label = "Check", type = "string"), list(key = "statistic", label = "Statistic", type = "number"), list(key = "p", label = "p", type = "pvalue")),
rows = dh_rows, note = paste0(sprintf("%d simulations from the fitted model with new random effects (DHARMa's default; spread measured around the population-level prediction), portable seed 1. ", as.integer(dh$n_sim)),
"Each residual is where the observed value falls among its simulations (randomized for whole numbers); uniform residuals mean the model fits. Two-sided simulation p-values."))
m_show <- min(n, 5000) # evenly spaced rows for the residual charts
show <- if (m_show > 1) ((seq_len(m_show) - 1) * (n - 1)) %/% (m_show - 1) + 1 else 1
res_show <- dh$residuals[show]
charts[[length(charts) + 1]] <- cs_chart("dharma_qq", "qq", "Simulated residuals against the uniform distribution", list(x = cs_col("Scaled residual", res_show)),
controls = list(reference = "uniform"))
rank_fit <- cs_dharma_rank01(fitted_resp)
charts[[length(charts) + 1]] <- cs_chart("dharma_resid", "scatter", "Simulated residuals against the population-level prediction (rank)", list(
x = cs_col("Population-level prediction (rank, 0–1)", rank_fit[show]), y = cs_col("Scaled residual", res_show)), controls = list(fit = "loess"))
statistics <- list(list(key = "icc", label = "ICC (latent scale)", value = values$icc), list(key = "r2_marginal", label = "R² marginal", value = values$r2_marginal),
list(key = "r2_conditional", label = "R² conditional", value = values$r2_conditional), list(key = "aic", label = "AIC", value = values$aic))
if (!is.null(values$re_lrt_p)) statistics[[length(statistics) + 1]] <- list(key = "re_lrt_p", label = "Random effects LR test p", value = values$re_lrt_p, format = "p")
cs_publish(list(
method = "mixed.glmm",
methodVersion = "1.1.0",
title = "Generalized linear mixed model",
engine = cs_engine_info("lme4", "nanoparquet"),
n = n,
summary = summary,
apa = if (length(effects)) sprintf("Wald χ²(%d) = %.2f, %s", as.integer(effects[[1]]$df), effects[[1]]$chi2, cs_fmt_p(effects[[1]]$p)) else "",
statistics = statistics,
tables = tables,
effectSizes = list(),
assumptions = assumptions,
warnings = warnings,
notes = list(paste0(if (family == "binomial") "Logistic" else "Poisson", " GLMM by the Laplace approximation (lme4::glmer, nAGQ = 1); ",
if (family == "binomial") "latent residual variance π²/3." else "observation-level variance log(1 + 1/λ), λ = exp(mean fixed predictor + σ²_random / 2).")),
charts = charts,
values = values
))
Sources
- Hartig, F. (2022). DHARMa: Residual diagnostics for hierarchical (multi-level/mixed) regression models. R package version 0.4.6.
- Dunn, P. K., & Smyth, G. K. (1996). Randomized quantile residuals. Journal of Computational and Graphical Statistics, 5(3), 236–244.
- Bates, D., Mächler, M., Bolker, B., & Walker, S. (2015). Fitting linear mixed-effects models using lme4. Journal of Statistical Software, 67(1), 1–48.
- Nakagawa, S., Johnson, P. C. D., & Schielzeth, H. (2017). The coefficient of determination R² and intra-class correlation coefficient from generalized linear mixed-effects models revisited and expanded. Journal of the Royal Society Interface, 14, 20170213.
From the CodeSplash method registry · mixed.glmm v1.1.0.