Item response theory
Model each item's difficulty and discrimination. Compare Rasch and 2PL, read item curves, and see why a scale's precision depends on the person being measured.
What runs in CodeSplash
- Item response theory (Rasch, 2PL, graded response) Verified in Python and R
You will be able to
- Interpret item difficulty and discrimination
- Compare Rasch and 2PL using a likelihood-ratio test and AIC
- Explain why measurement precision varies with ability
Read first
Model the item, not the total
ReadClassical scoring adds up the items. Item response theoryItem response theoryModels the chance of each response to each item from a person's latent trait and the item's own parameters. models the chance of answering each item correctly as a function of an underlying trait :
- , the difficultyItem difficultyThe trait level at which a person has a 50% chance of endorsing or passing an item.: the trait level where the chance is 50%.
- , the discriminationItem discriminationHow sharply an item separates people slightly below and slightly above its difficulty.: how sharply the item separates people near that level.
View data
| ability θ | P(correct) | item |
|---|---|---|
| −4 | 0.0336 | Q1 (easy) |
| −3.900 | 0.0384 | Q1 (easy) |
| −3.800 | 0.0439 | Q1 (easy) |
| −3.700 | 0.0502 | Q1 (easy) |
| −3.600 | 0.0573 | Q1 (easy) |
| −3.500 | 0.0654 | Q1 (easy) |
| −3.400 | 0.0745 | Q1 (easy) |
| −3.300 | 0.0847 | Q1 (easy) |
| −3.200 | 0.0962 | Q1 (easy) |
| −3.100 | 0.1091 | Q1 (easy) |
| −3 | 0.1235 | Q1 (easy) |
| −2.900 | 0.1394 | Q1 (easy) |
| −2.800 | 0.1571 | Q1 (easy) |
| −2.700 | 0.1765 | Q1 (easy) |
| −2.600 | 0.1978 | Q1 (easy) |
| −2.500 | 0.2210 | Q1 (easy) |
| −2.400 | 0.2460 | Q1 (easy) |
| −2.300 | 0.2729 | Q1 (easy) |
| −2.200 | 0.3015 | Q1 (easy) |
| −2.100 | 0.3318 | Q1 (easy) |
| −2 | 0.3635 | Q1 (easy) |
| −1.900 | 0.3965 | Q1 (easy) |
| −1.800 | 0.4304 | Q1 (easy) |
| −1.700 | 0.4651 | Q1 (easy) |
| −1.600 | 0.5000 | Q1 (easy) |
| −1.500 | 0.5349 | Q1 (easy) |
| −1.400 | 0.5696 | Q1 (easy) |
| −1.300 | 0.6035 | Q1 (easy) |
| −1.200 | 0.6364 | Q1 (easy) |
| −1.100 | 0.6682 | Q1 (easy) |
| −1 | 0.6985 | Q1 (easy) |
| −0.9000 | 0.7271 | Q1 (easy) |
| −0.8000 | 0.7540 | Q1 (easy) |
| −0.7000 | 0.7790 | Q1 (easy) |
| −0.6000 | 0.8022 | Q1 (easy) |
| −0.5000 | 0.8235 | Q1 (easy) |
| −0.4000 | 0.8429 | Q1 (easy) |
| −0.3000 | 0.8606 | Q1 (easy) |
| −0.2000 | 0.8765 | Q1 (easy) |
| −0.1000 | 0.8909 | Q1 (easy) |
| 0 | 0.9038 | Q1 (easy) |
| 0.1000 | 0.9153 | Q1 (easy) |
| 0.2000 | 0.9255 | Q1 (easy) |
| 0.3000 | 0.9346 | Q1 (easy) |
| 0.4000 | 0.9427 | Q1 (easy) |
| 0.5000 | 0.9498 | Q1 (easy) |
| 0.6000 | 0.9561 | Q1 (easy) |
| 0.7000 | 0.9616 | Q1 (easy) |
| 0.8000 | 0.9664 | Q1 (easy) |
| 0.9000 | 0.9707 | Q1 (easy) |
| 1 | 0.9744 | Q1 (easy) |
| 1.100 | 0.9777 | Q1 (easy) |
| 1.200 | 0.9805 | Q1 (easy) |
| 1.300 | 0.9830 | Q1 (easy) |
| 1.400 | 0.9852 | Q1 (easy) |
| 1.500 | 0.9871 | Q1 (easy) |
| 1.600 | 0.9888 | Q1 (easy) |
| 1.700 | 0.9902 | Q1 (easy) |
| 1.800 | 0.9915 | Q1 (easy) |
| 1.900 | 0.9926 | Q1 (easy) |
First 60 of 405 rows.
Rasch or 2PL?
PredictPredict first
The Rasch model gives every item the same discrimination. The 2PL lets each item have its own, at the cost of extra parameters.
On five LSAT items answered by 1,000 people, which fits better?
Reveal
2PL. Log-likelihoods are −2658.8 and −2664.9, so the likelihood-ratio statistic is about 12 on 4 degrees of freedom. AIC agrees: 5337.6 against 5341.8. Item 3 discriminates noticeably more than the others. Some users prefer Rasch anyway, for its simple scoring, and that's a choice about measurement, not about fit.
Read the items
In the appFind each item's and on the card. A negative difficulty means an easy item: most people have at least a 50% chance. Very low means an item that barely separates people.
Two-parameter logistic (2PL) model: log-likelihood = −2658.81, AIC = 5337.6, BIC = 5386.7
- Log-likelihood
- −2658.81
- AIC
- 5337.61
- BIC
- 5386.69
- Empirical reliability
- 0.4521
Plots
View data
| Item | Probability | Trait (θ) |
|---|---|---|
| item_1 | 0.1096 | −4 |
| item_1 | 0.1197 | −3.900 |
| item_1 | 0.1305 | −3.800 |
| item_1 | 0.1421 | −3.700 |
| item_1 | 0.1546 | −3.600 |
| item_1 | 0.1679 | −3.500 |
| item_1 | 0.1822 | −3.400 |
| item_1 | 0.1973 | −3.300 |
| item_1 | 0.2134 | −3.200 |
| item_1 | 0.2305 | −3.100 |
| item_1 | 0.2485 | −3 |
| item_1 | 0.2674 | −2.900 |
| item_1 | 0.2871 | −2.800 |
| item_1 | 0.3078 | −2.700 |
| item_1 | 0.3292 | −2.600 |
| item_1 | 0.3514 | −2.500 |
| item_1 | 0.3742 | −2.400 |
| item_1 | 0.3976 | −2.300 |
| item_1 | 0.4215 | −2.200 |
| item_1 | 0.4457 | −2.100 |
| item_1 | 0.4702 | −2 |
| item_1 | 0.4949 | −1.900 |
| item_1 | 0.5196 | −1.800 |
| item_1 | 0.5441 | −1.700 |
| item_1 | 0.5685 | −1.600 |
| item_1 | 0.5926 | −1.500 |
| item_1 | 0.6162 | −1.400 |
| item_1 | 0.6392 | −1.300 |
| item_1 | 0.6617 | −1.200 |
| item_1 | 0.6834 | −1.100 |
| item_1 | 0.7044 | −1 |
| item_1 | 0.7245 | −0.9000 |
| item_1 | 0.7438 | −0.8000 |
| item_1 | 0.7622 | −0.7000 |
| item_1 | 0.7796 | −0.6000 |
| item_1 | 0.7961 | −0.5000 |
| item_1 | 0.8117 | −0.4000 |
| item_1 | 0.8263 | −0.3000 |
| item_1 | 0.8400 | −0.2000 |
| item_1 | 0.8528 | −0.1000 |
| item_1 | 0.8648 | 0 |
| item_1 | 0.8759 | 0.1000 |
| item_1 | 0.8863 | 0.2000 |
| item_1 | 0.8959 | 0.3000 |
| item_1 | 0.9047 | 0.4000 |
| item_1 | 0.9129 | 0.5000 |
| item_1 | 0.9204 | 0.6000 |
| item_1 | 0.9274 | 0.7000 |
| item_1 | 0.9338 | 0.8000 |
| item_1 | 0.9396 | 0.9000 |
| item_1 | 0.9450 | 1 |
| item_1 | 0.9499 | 1.100 |
| item_1 | 0.9544 | 1.200 |
| item_1 | 0.9585 | 1.300 |
| item_1 | 0.9623 | 1.400 |
| item_1 | 0.9657 | 1.500 |
| item_1 | 0.9688 | 1.600 |
| item_1 | 0.9717 | 1.700 |
| item_1 | 0.9743 | 1.800 |
| item_1 | 0.9766 | 1.900 |
First 60 of 405 rows.
View data
| Information | Standard error | Trait (θ) |
|---|---|---|
| 0.2874 | 1.865 | −4 |
| 0.3082 | 1.801 | −3.900 |
| 0.3303 | 1.740 | −3.800 |
| 0.3540 | 1.681 | −3.700 |
| 0.3791 | 1.624 | −3.600 |
| 0.4060 | 1.569 | −3.500 |
| 0.4346 | 1.517 | −3.400 |
| 0.4650 | 1.466 | −3.300 |
| 0.4975 | 1.418 | −3.200 |
| 0.5321 | 1.371 | −3.100 |
| 0.5691 | 1.326 | −3 |
| 0.6084 | 1.282 | −2.900 |
| 0.6503 | 1.240 | −2.800 |
| 0.6949 | 1.200 | −2.700 |
| 0.7423 | 1.161 | −2.600 |
| 0.7925 | 1.123 | −2.500 |
| 0.8456 | 1.087 | −2.400 |
| 0.9014 | 1.053 | −2.300 |
| 0.9597 | 1.021 | −2.200 |
| 1.020 | 0.9902 | −2.100 |
| 1.082 | 0.9616 | −2 |
| 1.144 | 0.9351 | −1.900 |
| 1.205 | 0.9111 | −1.800 |
| 1.264 | 0.8896 | −1.700 |
| 1.318 | 0.8709 | −1.600 |
| 1.367 | 0.8552 | −1.500 |
| 1.408 | 0.8427 | −1.400 |
| 1.439 | 0.8335 | −1.300 |
| 1.459 | 0.8278 | −1.200 |
| 1.467 | 0.8258 | −1.100 |
| 1.461 | 0.8274 | −1 |
| 1.442 | 0.8327 | −0.9000 |
| 1.411 | 0.8418 | −0.8000 |
| 1.369 | 0.8547 | −0.7000 |
| 1.317 | 0.8712 | −0.6000 |
| 1.258 | 0.8914 | −0.5000 |
| 1.194 | 0.9152 | −0.4000 |
| 1.126 | 0.9423 | −0.3000 |
| 1.056 | 0.9729 | −0.2000 |
| 0.9867 | 1.007 | −0.1000 |
| 0.9181 | 1.044 | 0 |
| 0.8515 | 1.084 | 0.1000 |
| 0.7876 | 1.127 | 0.2000 |
| 0.7271 | 1.173 | 0.3000 |
| 0.6700 | 1.222 | 0.4000 |
| 0.6166 | 1.273 | 0.5000 |
| 0.5669 | 1.328 | 0.6000 |
| 0.5207 | 1.386 | 0.7000 |
| 0.4780 | 1.446 | 0.8000 |
| 0.4386 | 1.510 | 0.9000 |
| 0.4024 | 1.576 | 1 |
| 0.3690 | 1.646 | 1.100 |
| 0.3384 | 1.719 | 1.200 |
| 0.3102 | 1.795 | 1.300 |
| 0.2844 | 1.875 | 1.400 |
| 0.2607 | 1.958 | 1.500 |
| 0.2390 | 2.045 | 1.600 |
| 0.2191 | 2.136 | 1.700 |
| 0.2009 | 2.231 | 1.800 |
| 0.1842 | 2.330 | 1.900 |
First 60 of 81 rows.
View data
| With | Text | Item | Q3 |
|---|---|---|---|
| item_1 | item_1 | 0 | |
| item_2 | -0.13 | item_1 | −0.1345 |
| item_3 | -0.21 | item_1 | −0.2137 |
| item_4 | -0.01 | item_1 | −0.0121 |
| item_5 | 0.01 | item_1 | 0.0087 |
| item_1 | -0.13 | item_2 | −0.1345 |
| item_2 | item_2 | 0 | |
| item_3 | -0.16 | item_2 | −0.1628 |
| item_4 | -0.13 | item_2 | −0.1339 |
| item_5 | -0.12 | item_2 | −0.1245 |
| item_1 | -0.21 | item_3 | −0.2137 |
| item_2 | -0.16 | item_3 | −0.1628 |
| item_3 | item_3 | 0 | |
| item_4 | -0.17 | item_3 | −0.1698 |
| item_5 | -0.11 | item_3 | −0.1147 |
| item_1 | -0.01 | item_4 | −0.0121 |
| item_2 | -0.13 | item_4 | −0.1339 |
| item_3 | -0.17 | item_4 | −0.1698 |
| item_4 | item_4 | 0 | |
| item_5 | -0.05 | item_4 | −0.0545 |
| item_1 | 0.01 | item_5 | 0.0087 |
| item_2 | -0.12 | item_5 | −0.1245 |
| item_3 | -0.11 | item_5 | −0.1147 |
| item_4 | -0.05 | item_5 | −0.0545 |
| item_5 | item_5 | 0 |
Assumptions
- One underlying trait — Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items.
- Sample size — 1000 respondents for 10 parameters.
- Category use — Every category has at least 10 responses.
- Convergence — EM converged in 107 cycles.
- Item fit — S-X² flags item_2 (Holm-adjusted p < .05): the model describes this item poorly.
- Local independence — Largest Q3 0.009 against an average of -0.111; no pair is more than 0.2 above the average.
Item parameters (IRT form: logit = a(θ − b))
| Item | Discrimination a | SE | Difficulty b | SE |
|---|---|---|---|---|
| item_1 | 0.9875 | 0.1772 | −1.879 | 0.2640 |
| item_2 | 1.081 | 0.1688 | −0.7475 | 0.1093 |
| item_3 | 1.707 | 0.3211 | −1.057 | 0.1154 |
| item_4 | 0.7650 | 0.1341 | −0.6353 | 0.1301 |
| item_5 | 0.7357 | 0.1511 | −2.521 | 0.4463 |
Person scores (EAP)
| Value | |
|---|---|
| Mean | 4.939e-10 |
| SD | 0.6724 |
| Mean posterior SD | 0.7402 |
| Empirical reliability | 0.4521 |
Item fit (S-X²)
| Item | S-X² | df | p | p (Holm) | RMSEA |
|---|---|---|---|---|---|
| item_1 | 4.751 | 2 | .093 | .292 | 0.0371 |
| item_2 | 14.453 | 2 | < .001 | .004 | 0.0789 |
| item_3 | 1.273 | 2 | .529 | 1.000 | 0 |
| item_4 | 5.236 | 2 | .073 | .292 | 0.0402 |
| item_5 | 0.9409 | 2 | .625 | 1.000 | 0 |
Limited-information fit
| Measure | Value |
|---|---|
| M2 | 11.938 |
| df | 5 |
| p | 0.0356 |
| RMSEA2 | 0.0373 |
| RMSEA2 90% CI low | 0.0090 |
| RMSEA2 90% CI high | 0.0650 |
| SRMSR | 0.0320 |
- Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; 107 EM cycles. Categories: item_1: 0, 1; item_2: 0, 1; item_3: 0, 1; item_4: 0, 1; item_5: 0, 1
The exact R script · R R version 4.5.1 (2025-06-13)
# Item response theory (Rasch, 2PL, graded response)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.irt 1.1.0 · spec f45cc74bb0458728
# Dataset: s3_lsat7 (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# mirt::mirt(data, 1, itemtype = "2PL" | "graded" | "Rasch") fits the same models on the same grid;
# cs_meas_irt_fit adds observed-information standard errors and keeps R and Python identical.
# %% Data (missing responses are kept; respondents with no response are left out)
items <- c("item_1", "item_2", "item_3", "item_4", "item_5")
kinds <- c(
"item_1" = "numeric",
"item_2" = "numeric",
"item_3" = "numeric",
"item_4" = "numeric",
"item_5" = "numeric"
)
stored <- list(
"item_1" = NULL,
"item_2" = NULL,
"item_3" = NULL,
"item_4" = NULL,
"item_5" = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s3_lsat7.parquet", col_select = items))
warnings <- list()
codes <- matrix(NA_real_, nrow(df), length(items))
categories <- list()
for (j in seq_along(items)) {
it <- items[j]
if (kinds[[it]] == "numeric") {
x <- as.double(df[[it]])
cs_check_finite(x, it) # infinite values stop the run (registry/errors.yaml)
vals <- sort(unique(x[!is.na(x)]))
codes[, j] <- match(x, vals) - 1
labels <- vapply(vals, function(v) if (v == round(v)) sprintf("%.0f", v) else formatC(v, digits = 15, format = "g"), character(1))
} else {
v <- df[[it]]
t <- ifelse(is.na(v), NA_character_, if (is.logical(v)) tolower(as.character(v)) else as.character(v))
ord <- if (!is.null(stored[[it]])) stored[[it]] else sort(unique(stats::na.omit(t)), method = "radix")
used <- ord[ord %in% t]
if (length(used) < length(ord)) warnings <- c(warnings, sprintf("%s: categories nobody chose were dropped (%s).", it, paste(setdiff(ord, used), collapse = ", ")))
codes[, j] <- match(t, used) - 1
labels <- used
}
if (length(labels) == 0) cs_error("CS_E_ALL_MISSING", column = it)
if (length(labels) < 2) cs_error("CS_E_CONSTANT", column = it) # one response category: nothing to scale
categories[[j]] <- labels
}
answered <- rowSums(!is.na(codes)) > 0
if (any(!answered)) warnings <- c(warnings, sprintf("%d respondents without any response were left out.", sum(!answered)))
codes <- codes[answered, , drop = FALSE]
n <- nrow(codes)
binary <- all(vapply(categories, length, integer(1)) == 2)
model <- "auto"
if (model == "auto") model <- if (binary) "2pl" else "grm"
if (model %in% c("rasch", "2pl") && !binary) stop("The Rasch and 2PL models need right/wrong items; use the graded response model for more categories")
model_label <- c(rasch = "Rasch (1PL) model", "2pl" = "Two-parameter logistic (2PL) model", grm = "Graded response model")[[model]]
lcfirst <- function(s) paste0(tolower(substr(s, 1, 1)), substr(s, 2, nchar(s)))
# %% Fit (marginal maximum likelihood, EM on 61 quadrature points)
fit <- tryCatch(cs_meas_irt_fit(codes, model), error = function(e) {
# a singular information matrix: estimates run off, e.g. an item that separates respondents perfectly
if (grepl("singular", conditionMessage(e), fixed = TRUE)) cs_error("CS_E_NO_CONVERGENCE", what = c(rasch = "The Rasch model", "2pl" = "The 2PL model", grm = "The graded response model")[[model]])
stop(e)
})
tab <- cs_meas_irt_items(fit)
npar <- fit$npar
loglik <- fit$loglik
eap <- fit$eap
psd <- fit$psd
var_eap <- mean((eap - mean(eap))^2)
reliability <- var_eap / (var_eap + mean(psd^2))
values <- list(n = n, items = length(items), npar = npar, loglik = loglik, aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n),
reliability = reliability, eap_mean = mean(eap), eap_sd = sqrt(var_eap), model_label = model_label)
rows <- list()
kmax <- max(vapply(categories, length, integer(1)))
for (j in seq_along(items)) {
it <- items[j]
r <- tab[[j]]
values[[sprintf("a[%s]", it)]] <- r$a
values[[sprintf("se_a[%s]", it)]] <- r$se_a
row <- list(item = it, a = r$a, se_a = r$se_a)
if (length(categories[[j]]) == 2) {
values[[sprintf("b[%s]", it)]] <- r$b[1]
values[[sprintf("se_b[%s]", it)]] <- r$se_b[1]
row$b1 <- r$b[1]
row$se_b1 <- r$se_b[1]
} else {
for (m in seq_along(r$b)) {
values[[sprintf("b[%s|%d]", it, m)]] <- r$b[m]
values[[sprintf("se_b[%s|%d]", it, m)]] <- r$se_b[m]
row[[sprintf("b%d", m)]] <- r$b[m]
row[[sprintf("se_b%d", m)]] <- r$se_b[m]
}
}
rows[[j]] <- row
}
# %% Item and model fit: S-X² per item (Orlando & Thissen; mirt's cell collapsing), M2 / M2* with RMSEA2
# and SRMSR (Maydeu-Olivares & Joe), Yen's Q3 at the EAP scores — mirt::itemfit, M2 and residuals compute the same
diag <- cs_meas_irt_diagnostics(fit, codes, items)
for (k in names(diag$values)) values[k] <- list(diag$values[[k]])
# %% Assumptions
sparse <- character(0)
for (j in seq_along(items)) {
cats <- categories[[j]]
counts <- vapply(seq_along(cats) - 1, function(c0) sum(codes[, j] == c0, na.rm = TRUE), numeric(1))
sparse <- c(sparse, sprintf("%s = %s (%d)", items[j], cats, counts)[counts < 10])
}
need <- if (model != "grm") 200 else 500
assumptions <- list(
list(key = "unidimensionality", label = "One underlying trait", status = "info",
detail = "Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items."),
list(key = "sample_size", label = "Sample size", status = if (n < need) "warn" else "pass",
detail = paste0(sprintf("%d respondents for %d parameters", n, npar), if (n < need) sprintf(" — %d or more are usually recommended for the %s.", need, lcfirst(model_label)) else ".")),
list(key = "categories", label = "Category use", status = if (length(sparse)) "warn" else "pass",
detail = if (length(sparse)) paste0("Fewer than 10 responses: ", paste(utils::head(sparse, 8), collapse = "; "), if (length(sparse) > 8) " …" else "", ".")
else "Every category has at least 10 responses."),
list(key = "convergence", label = "Convergence", status = if (fit$converged) "pass" else "warn",
detail = if (fit$converged) sprintf("EM converged in %d cycles.", fit$iterations) else sprintf("EM stopped after %d cycles without converging.", fit$iterations))
)
assumptions <- c(assumptions, diag$assumptions) # item fit (S-X², Holm-adjusted) and local independence (Q3 more than 0.2 above its average)
# %% Result
cols <- list(list(key = "item", label = "Item", type = "string"), list(key = "a", label = "Discrimination a", type = "number"),
list(key = "se_a", label = "SE", type = "number"))
for (m in seq_len(kmax - 1)) {
cols <- c(cols, list(list(key = sprintf("b%d", m), label = if (kmax == 2) "Difficulty b" else sprintf("Threshold b%d", m), type = "number"),
list(key = sprintf("se_b%d", m), label = "SE", type = "number")))
}
theta <- round((-40:40) / 10, 10)
info <- cs_meas_irt_information(fit, theta)
curve_t <- numeric(0)
curve_p <- numeric(0)
curve_i <- character(0)
curve_c <- character(0)
for (j in seq_along(items)) {
P <- cs_meas_cat_probs(fit$params[[j]]$a, fit$params[[j]]$d, theta)
cats <- categories[[j]]
shown <- if (length(cats) == 2) length(cats) else seq_along(cats)
for (c0 in shown) {
curve_t <- c(curve_t, theta)
curve_p <- c(curve_p, P[, c0])
curve_i <- c(curve_i, rep(items[j], length(theta)))
curve_c <- c(curve_c, rep(cats[c0], length(theta)))
}
}
total <- colSums(info)
curve_roles <- list(
theta = cs_col("Trait (θ)", curve_t, "numeric"),
probability = cs_col("Probability", curve_p, "numeric"),
item = cs_col("Item", curve_i, "categorical", levels = items)
)
if (!binary) curve_roles$category <- cs_col("Category", curve_c, "categorical")
charts <- list(
cs_chart("curves", "item-curves", if (binary) "Item characteristic curves" else "Category response curves", curve_roles, controls = list(kind = "icc")),
cs_chart("information", "test-information", "Test information", list(
theta = cs_col("Trait (θ)", theta, "numeric"),
information = cs_col("Information", total, "numeric"),
se = cs_col("Standard error", 1 / sqrt(total), "numeric")
))
)
q3 <- diag$q3
qc <- expand.grid(j = seq_along(items), i = seq_along(items))
show <- qc$i != qc$j & is.finite(q3[cbind(qc$i, qc$j)])
charts <- c(charts, list(cs_chart("q3", "matrix-heatmap", "Residual correlations (Q3)", list(
row = cs_col("Item", items[qc$i], "categorical", levels = items),
col = cs_col("With", items[qc$j], "categorical", levels = items),
value = cs_col("Q3", ifelse(show, q3[cbind(qc$i, qc$j)], 0), "numeric"),
label = cs_col("Text", ifelse(show, sprintf("%.2f", q3[cbind(qc$i, qc$j)]), ""), "categorical")
), controls = list(scale = "diverging"))))
cat_note <- substr(paste(vapply(seq_along(items), function(j) sprintf("%s: %s", items[j], paste(categories[[j]], collapse = ", ")), character(1)), collapse = "; "), 1, 600)
cs_publish(list(
method = "measurement.irt",
methodVersion = "1.1.0",
title = model_label,
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%s for %d items and %d respondents: log-likelihood %.2f, empirical reliability %.2f.", model_label, length(items), n, loglik, reliability),
apa = sprintf("%s: log-likelihood = %s, AIC = %s, BIC = %s", model_label, cs_fmt_num(loglik), cs_fmt_num(values$aic, 1), cs_fmt_num(values$bic, 1)),
statistics = list(list(key = "loglik", label = "Log-likelihood", value = loglik), list(key = "aic", label = "AIC", value = values$aic),
list(key = "bic", label = "BIC", value = values$bic), list(key = "reliability", label = "Empirical reliability", value = reliability)),
tables = c(list(
list(key = "items", title = "Item parameters (IRT form: logit = a(θ − b))", columns = cols, rows = rows),
list(key = "persons", title = "Person scores (EAP)", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(stat = "Mean", value = mean(eap)), list(stat = "SD", value = sqrt(var_eap)),
list(stat = "Mean posterior SD", value = sqrt(mean(psd^2))), list(stat = "Empirical reliability", value = reliability)))
), diag$tables),
assumptions = assumptions,
warnings = warnings,
notes = c(list(paste0(sprintf("Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; %d EM cycles. Categories: ", fit$iterations), cat_note)),
diag$notes),
charts = charts,
values = values
))
Two-parameter logistic (2PL) model: log-likelihood = −2658.81, AIC = 5337.6, BIC = 5386.7
- Log-likelihood
- −2658.81
- AIC
- 5337.61
- BIC
- 5386.69
- Empirical reliability
- 0.4521
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- One underlying trait — Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items.
- Sample size — 1000 respondents for 10 parameters.
- Category use — Every category has at least 10 responses.
- Convergence — EM converged in 107 cycles.
- Item fit — S-X² flags item_2 (Holm-adjusted p < .05): the model describes this item poorly.
- Local independence — Largest Q3 0.009 against an average of -0.111; no pair is more than 0.2 above the average.
Item parameters (IRT form: logit = a(θ − b))
| Item | Discrimination a | SE | Difficulty b | SE |
|---|---|---|---|---|
| item_1 | 0.9875 | 0.1772 | −1.879 | 0.2640 |
| item_2 | 1.081 | 0.1688 | −0.7475 | 0.1093 |
| item_3 | 1.707 | 0.3211 | −1.057 | 0.1154 |
| item_4 | 0.7650 | 0.1341 | −0.6353 | 0.1301 |
| item_5 | 0.7357 | 0.1511 | −2.521 | 0.4463 |
Person scores (EAP)
| Value | |
|---|---|
| Mean | 4.939e-10 |
| SD | 0.6724 |
| Mean posterior SD | 0.7402 |
| Empirical reliability | 0.4521 |
Item fit (S-X²)
| Item | S-X² | df | p | p (Holm) | RMSEA |
|---|---|---|---|---|---|
| item_1 | 4.751 | 2 | .093 | .292 | 0.0371 |
| item_2 | 14.453 | 2 | < .001 | .004 | 0.0789 |
| item_3 | 1.273 | 2 | .529 | 1.000 | 0 |
| item_4 | 5.236 | 2 | .073 | .292 | 0.0402 |
| item_5 | 0.9409 | 2 | .625 | 1.000 | 0 |
Limited-information fit
| Measure | Value |
|---|---|
| M2 | 11.938 |
| df | 5 |
| p | 0.0356 |
| RMSEA2 | 0.0373 |
| RMSEA2 90% CI low | 0.0090 |
| RMSEA2 90% CI high | 0.0650 |
| SRMSR | 0.0320 |
- Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; 107 EM cycles. Categories: item_1: 0, 1; item_2: 0, 1; item_3: 0, 1; item_4: 0, 1; item_5: 0, 1
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Item response theory (Rasch, 2PL, graded response)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.irt 1.1.0 · spec f45cc74bb0458728
# Dataset: s3_lsat7 (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_finite
from codesplash.stats import measurement as ms # MML-EM IRT twin of R's cs_meas_irt_fit
from codesplash.stats import measurement_fit as mf # S-X², M2 and Q3 twins of R's cs_meas_irt_diagnostics
# mirt::mirt(data, 1, itemtype = "2PL" | "graded" | "Rasch") fits the same models on the same grid;
# the twin adds observed-information standard errors and keeps Python and R identical.
# %% Data (missing responses are kept; respondents with no response are left out)
items = ["item_1", "item_2", "item_3", "item_4", "item_5"]
kinds = {"item_1":"numeric","item_2":"numeric","item_3":"numeric","item_4":"numeric","item_5":"numeric"}
stored = json.loads("{\"item_1\":null,\"item_2\":null,\"item_3\":null,\"item_4\":null,\"item_5\":null}")
df = pd.read_parquet("tests/parity/fixtures/s3_lsat7.parquet", columns=items)
warnings = []
n0 = len(df)
codes = np.full((n0, len(items)), np.nan)
categories = []
for j, it in enumerate(items):
if kinds[it] == "numeric":
x = df[it].to_numpy(dtype=float)
check_finite(x, it) # infinite values stop the run (registry/errors.yaml)
vals = np.unique(x[~np.isnan(x)])
codes[:, j] = np.where(np.isnan(x), np.nan, np.searchsorted(vals, np.nan_to_num(x)))
labels = [f"{v:.0f}" if float(v).is_integer() else f"{v:.15g}" for v in vals]
else:
t = [None if pd.isna(v) else (str(v).lower() if isinstance(v, (bool, np.bool_)) else str(v)) for v in df[it]]
order = stored[it] or sorted({v for v in t if v is not None})
used = [c for c in order if c in set(t)]
if len(used) < len(order):
warnings.append(f"{it}: categories nobody chose were dropped ({', '.join(c for c in order if c not in used)}).")
pos = {c: i for i, c in enumerate(used)}
codes[:, j] = [pos[v] if v is not None else np.nan for v in t]
labels = used
if len(labels) == 0:
cs.cs_error("CS_E_ALL_MISSING", column=it)
if len(labels) < 2:
cs.cs_error("CS_E_CONSTANT", column=it) # one response category: nothing to scale
categories.append(labels)
answered = np.sum(~np.isnan(codes), axis=1) > 0
if (~answered).any():
warnings.append(f"{int((~answered).sum())} respondents without any response were left out.")
codes = codes[answered]
n = codes.shape[0]
binary = all(len(c) == 2 for c in categories)
model = "auto"
if model == "auto":
model = "2pl" if binary else "grm"
if model in ("rasch", "2pl") and not binary:
raise ValueError("The Rasch and 2PL models need right/wrong items; use the graded response model for more categories")
model_label = {"rasch": "Rasch (1PL) model", "2pl": "Two-parameter logistic (2PL) model", "grm": "Graded response model"}[model]
# %% Fit (marginal maximum likelihood, EM on 61 quadrature points)
try:
fit = ms.irt_fit(codes, model)
except np.linalg.LinAlgError: # a singular information matrix: estimates run off, e.g. an item that separates respondents perfectly
cs.cs_error("CS_E_NO_CONVERGENCE", what={"rasch": "The Rasch model", "2pl": "The 2PL model", "grm": "The graded response model"}[model])
table = ms.irt_item_table(fit)
npar = fit["npar"]
loglik = fit["loglik"]
eap, psd = fit["eap"], fit["psd"]
var_eap = float(np.mean((eap - eap.mean()) ** 2))
reliability = var_eap / (var_eap + float(np.mean(psd**2)))
values = {"n": float(n), "items": float(len(items)), "npar": float(npar), "loglik": loglik, "aic": -2 * loglik + 2 * npar,
"bic": -2 * loglik + npar * np.log(n), "reliability": reliability, "eap_mean": float(eap.mean()), "eap_sd": float(np.sqrt(var_eap)),
"model_label": model_label}
rows = []
kmax = max(len(c) for c in categories)
for it, r, cats in zip(items, table, categories):
values[f"a[{it}]"] = r["a"]
values[f"se_a[{it}]"] = r["se_a"]
row = {"item": it, "a": r["a"], "se_a": r["se_a"]}
if len(cats) == 2:
values[f"b[{it}]"] = r["b"][0]
values[f"se_b[{it}]"] = r["se_b"][0]
row.update({"b1": r["b"][0], "se_b1": r["se_b"][0]})
else:
for m, (b, se) in enumerate(zip(r["b"], r["se_b"]), start=1):
values[f"b[{it}|{m}]"] = b
values[f"se_b[{it}|{m}]"] = se
row.update({f"b{m}": b, f"se_b{m}": se})
rows.append(row)
# %% Item and model fit: S-X² per item (Orlando & Thissen; mirt's cell collapsing), M2 / M2* with RMSEA2
# and SRMSR (Maydeu-Olivares & Joe), Yen's Q3 at the EAP scores — mirt::itemfit, M2 and residuals compute the same
diag = mf.irt_diagnostics(fit, codes, items)
values.update(diag["values"])
# %% Assumptions
sparse = []
for j, (it, cats) in enumerate(zip(items, categories)):
counts = [int(np.sum(codes[:, j] == c)) for c in range(len(cats))]
sparse += [f"{it} = {cats[c]} ({counts[c]})" for c in range(len(cats)) if counts[c] < 10]
need = 200 if model != "grm" else 500
assumptions = [
{"key": "unidimensionality", "label": "One underlying trait", "status": "info",
"detail": "Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items."},
{"key": "sample_size", "label": "Sample size", "status": "warn" if n < need else "pass",
"detail": f"{n} respondents for {npar} parameters" + (f" — {need} or more are usually recommended for the {model_label[0].lower() + model_label[1:]}." if n < need else ".")},
{"key": "categories", "label": "Category use", "status": "warn" if sparse else "pass",
"detail": "Fewer than 10 responses: " + "; ".join(sparse[:8]) + (" …" if len(sparse) > 8 else "") + "." if sparse else "Every category has at least 10 responses."},
{"key": "convergence", "label": "Convergence", "status": "pass" if fit["converged"] else "warn",
"detail": f"EM converged in {fit['iterations']} cycles." if fit["converged"] else f"EM stopped after {fit['iterations']} cycles without converging."},
*diag["assumptions"], # item fit (S-X², Holm-adjusted) and local independence (Q3 more than 0.2 above its average)
]
# %% Result
cols = [{"key": "item", "label": "Item", "type": "string"}, {"key": "a", "label": "Discrimination a", "type": "number"},
{"key": "se_a", "label": "SE", "type": "number"}]
for m in range(1, kmax):
cols += [{"key": f"b{m}", "label": "Difficulty b" if kmax == 2 else f"Threshold b{m}", "type": "number"},
{"key": f"se_b{m}", "label": "SE", "type": "number"}]
theta = np.round(np.arange(-40, 41) / 10, 10)
info = ms.irt_information(fit, theta)
curve_t, curve_p, curve_i, curve_c = [], [], [], []
for (a, d), it, cats in zip(fit["params"], items, categories):
P = ms.category_probs(a, d, theta)
shown = [len(cats) - 1] if len(cats) == 2 else range(len(cats))
for c in shown:
curve_t += theta.tolist()
curve_p += P[:, c].tolist()
curve_i += [it] * len(theta)
curve_c += [cats[c]] * len(theta)
total = info.sum(axis=0)
charts = [
cs.chart("curves", "item-curves", "Item characteristic curves" if binary else "Category response curves", {
"theta": cs.col("Trait (θ)", curve_t, "numeric"),
"probability": cs.col("Probability", curve_p, "numeric"),
"item": cs.col("Item", curve_i, "categorical", levels=items),
**({} if binary else {"category": cs.col("Category", curve_c, "categorical")}),
}, controls={"kind": "icc"}),
cs.chart("information", "test-information", "Test information", {
"theta": cs.col("Trait (θ)", theta.tolist(), "numeric"),
"information": cs.col("Information", total.tolist(), "numeric"),
"se": cs.col("Standard error", (1 / np.sqrt(total)).tolist(), "numeric"),
}),
]
q3 = diag["q3"]
cells = [(i, j) for i in range(len(items)) for j in range(len(items))]
show = lambda i, j: i != j and np.isfinite(q3[i, j]) # noqa: E731
charts.append(cs.chart("q3", "matrix-heatmap", "Residual correlations (Q3)", {
"row": cs.col("Item", [items[i] for i, _ in cells], "categorical", levels=items),
"col": cs.col("With", [items[j] for _, j in cells], "categorical", levels=items),
"value": cs.col("Q3", [float(q3[i, j]) if show(i, j) else 0.0 for i, j in cells], "numeric"),
"label": cs.col("Text", [f"{q3[i, j]:.2f}" if show(i, j) else "" for i, j in cells], "categorical"),
}, controls={"scale": "diverging"}))
cs.publish({
"method": "measurement.irt",
"methodVersion": "1.1.0",
"title": model_label,
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": f"{model_label} for {len(items)} items and {n} respondents: log-likelihood {loglik:.2f}, empirical reliability {reliability:.2f}.",
"apa": f"{model_label}: log-likelihood = {cs.fmt_num(loglik)}, AIC = {cs.fmt_num(values['aic'], 1)}, BIC = {cs.fmt_num(values['bic'], 1)}",
"statistics": [{"key": "loglik", "label": "Log-likelihood", "value": loglik}, {"key": "aic", "label": "AIC", "value": values["aic"]},
{"key": "bic", "label": "BIC", "value": values["bic"]}, {"key": "reliability", "label": "Empirical reliability", "value": reliability}],
"tables": [{"key": "items", "title": "Item parameters (IRT form: logit = a(θ − b))", "columns": cols, "rows": rows},
{"key": "persons", "title": "Person scores (EAP)", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"stat": "Mean", "value": float(eap.mean())}, {"stat": "SD", "value": float(np.sqrt(var_eap))},
{"stat": "Mean posterior SD", "value": float(np.sqrt(np.mean(psd**2)))}, {"stat": "Empirical reliability", "value": reliability}]},
*diag["tables"]],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; "
f"{fit['iterations']} EM cycles. Categories: " + "; ".join(f"{it}: {', '.join(c)}" for it, c in zip(items, categories))[:600],
*diag["notes"]],
"charts": charts,
"values": values,
})
Precision depends on the person
In the appAn item is most informative near its difficulty. All these LSAT items are easy, so the test measures low-ability people better than high-ability ones.
That's the big idea: there's no single "reliability". The card's single summary, 0.45, is an average over the people in this sample. The test information curve shows where the scale is sharp.
Ordered responses get thresholds instead of one difficulty, using the graded response model. For the four-item science attitude scale, reliability is 0.67.
Graded response model: log-likelihood = −1608.87, AIC = 3249.7, BIC = 3313.3
- Log-likelihood
- −1608.87
- AIC
- 3249.74
- BIC
- 3313.28
- Empirical reliability
- 0.6665
Assumptions
- One underlying trait — Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items.
- Sample size — 392 respondents for 16 parameters — 500 or more are usually recommended for the graded response model.
- Category use — Fewer than 10 responses: comfort = 1 (5).
- Convergence — EM converged in 134 cycles.
- Item fit — No item's S-X² is significant after Holm's adjustment (smallest adjusted p = 1.000).
- Local independence — Q3 more than 0.2 above its average (-0.190): comfort with benefit (0.085). These items may share something beyond the trait.
Item parameters (IRT form: logit = a(θ − b))
| Item | Discrimination a | SE | Threshold b1 | SE | Threshold b2 | SE | Threshold b3 | SE |
|---|---|---|---|---|---|---|---|---|
| comfort | 1.041 | 0.1882 | −4.673 | 0.8142 | −2.536 | 0.3920 | 1.408 | 0.2310 |
| work | 1.226 | 0.1817 | −2.385 | 0.3045 | −0.7351 | 0.1311 | 1.849 | 0.2343 |
| future | 2.301 | 0.4882 | −2.280 | 0.2591 | −0.9644 | 0.1160 | 0.8552 | 0.1118 |
| benefit | 1.094 | 0.1832 | −3.060 | 0.4481 | −0.9064 | 0.1615 | 1.543 | 0.2313 |
Person scores (EAP)
| Value | |
|---|---|
| Mean | 3.557e-8 |
| SD | 0.8164 |
| Mean posterior SD | 0.5775 |
| Empirical reliability | 0.6665 |
Item fit (S-X²)
| Item | S-X² | df | p | p (Holm) | RMSEA |
|---|---|---|---|---|---|
| comfort | 4.787 | 6 | .571 | 1.000 | 0 |
| work | 8.757 | 9 | .460 | 1.000 | 0 |
| future | 7.554 | 8 | .478 | 1.000 | 0 |
| benefit | 9.925 | 11 | .537 | 1.000 | 0 |
Limited-information fit
| Measure | Value |
|---|---|
| M2* | — |
| df | — |
| p | — |
| RMSEA2 | — |
| RMSEA2 90% CI low | — |
| RMSEA2 90% CI high | — |
| SRMSR | 0.0726 |
- Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; 134 EM cycles. Categories: comfort: 1, 2, 3, 4; work: 1, 2, 3, 4; future: 1, 2, 3, 4; benefit: 1, 2, 3, 4
- M2 needs more item means and cross-products than parameters (10 vs 16); only the SRMSR is shown.
The exact R script · R R version 4.5.1 (2025-06-13)
# Item response theory (Rasch, 2PL, graded response)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.irt 1.1.0 · spec 0175706c384a4424
# Dataset: s3_science (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# mirt::mirt(data, 1, itemtype = "2PL" | "graded" | "Rasch") fits the same models on the same grid;
# cs_meas_irt_fit adds observed-information standard errors and keeps R and Python identical.
# %% Data (missing responses are kept; respondents with no response are left out)
items <- c("comfort", "work", "future", "benefit")
kinds <- c(
"comfort" = "numeric",
"work" = "numeric",
"future" = "numeric",
"benefit" = "numeric"
)
stored <- list(
"comfort" = NULL,
"work" = NULL,
"future" = NULL,
"benefit" = NULL
)
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/s3_science.parquet", col_select = items))
warnings <- list()
codes <- matrix(NA_real_, nrow(df), length(items))
categories <- list()
for (j in seq_along(items)) {
it <- items[j]
if (kinds[[it]] == "numeric") {
x <- as.double(df[[it]])
cs_check_finite(x, it) # infinite values stop the run (registry/errors.yaml)
vals <- sort(unique(x[!is.na(x)]))
codes[, j] <- match(x, vals) - 1
labels <- vapply(vals, function(v) if (v == round(v)) sprintf("%.0f", v) else formatC(v, digits = 15, format = "g"), character(1))
} else {
v <- df[[it]]
t <- ifelse(is.na(v), NA_character_, if (is.logical(v)) tolower(as.character(v)) else as.character(v))
ord <- if (!is.null(stored[[it]])) stored[[it]] else sort(unique(stats::na.omit(t)), method = "radix")
used <- ord[ord %in% t]
if (length(used) < length(ord)) warnings <- c(warnings, sprintf("%s: categories nobody chose were dropped (%s).", it, paste(setdiff(ord, used), collapse = ", ")))
codes[, j] <- match(t, used) - 1
labels <- used
}
if (length(labels) == 0) cs_error("CS_E_ALL_MISSING", column = it)
if (length(labels) < 2) cs_error("CS_E_CONSTANT", column = it) # one response category: nothing to scale
categories[[j]] <- labels
}
answered <- rowSums(!is.na(codes)) > 0
if (any(!answered)) warnings <- c(warnings, sprintf("%d respondents without any response were left out.", sum(!answered)))
codes <- codes[answered, , drop = FALSE]
n <- nrow(codes)
binary <- all(vapply(categories, length, integer(1)) == 2)
model <- "auto"
if (model == "auto") model <- if (binary) "2pl" else "grm"
if (model %in% c("rasch", "2pl") && !binary) stop("The Rasch and 2PL models need right/wrong items; use the graded response model for more categories")
model_label <- c(rasch = "Rasch (1PL) model", "2pl" = "Two-parameter logistic (2PL) model", grm = "Graded response model")[[model]]
lcfirst <- function(s) paste0(tolower(substr(s, 1, 1)), substr(s, 2, nchar(s)))
# %% Fit (marginal maximum likelihood, EM on 61 quadrature points)
fit <- tryCatch(cs_meas_irt_fit(codes, model), error = function(e) {
# a singular information matrix: estimates run off, e.g. an item that separates respondents perfectly
if (grepl("singular", conditionMessage(e), fixed = TRUE)) cs_error("CS_E_NO_CONVERGENCE", what = c(rasch = "The Rasch model", "2pl" = "The 2PL model", grm = "The graded response model")[[model]])
stop(e)
})
tab <- cs_meas_irt_items(fit)
npar <- fit$npar
loglik <- fit$loglik
eap <- fit$eap
psd <- fit$psd
var_eap <- mean((eap - mean(eap))^2)
reliability <- var_eap / (var_eap + mean(psd^2))
values <- list(n = n, items = length(items), npar = npar, loglik = loglik, aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n),
reliability = reliability, eap_mean = mean(eap), eap_sd = sqrt(var_eap), model_label = model_label)
rows <- list()
kmax <- max(vapply(categories, length, integer(1)))
for (j in seq_along(items)) {
it <- items[j]
r <- tab[[j]]
values[[sprintf("a[%s]", it)]] <- r$a
values[[sprintf("se_a[%s]", it)]] <- r$se_a
row <- list(item = it, a = r$a, se_a = r$se_a)
if (length(categories[[j]]) == 2) {
values[[sprintf("b[%s]", it)]] <- r$b[1]
values[[sprintf("se_b[%s]", it)]] <- r$se_b[1]
row$b1 <- r$b[1]
row$se_b1 <- r$se_b[1]
} else {
for (m in seq_along(r$b)) {
values[[sprintf("b[%s|%d]", it, m)]] <- r$b[m]
values[[sprintf("se_b[%s|%d]", it, m)]] <- r$se_b[m]
row[[sprintf("b%d", m)]] <- r$b[m]
row[[sprintf("se_b%d", m)]] <- r$se_b[m]
}
}
rows[[j]] <- row
}
# %% Item and model fit: S-X² per item (Orlando & Thissen; mirt's cell collapsing), M2 / M2* with RMSEA2
# and SRMSR (Maydeu-Olivares & Joe), Yen's Q3 at the EAP scores — mirt::itemfit, M2 and residuals compute the same
diag <- cs_meas_irt_diagnostics(fit, codes, items)
for (k in names(diag$values)) values[k] <- list(diag$values[[k]])
# %% Assumptions
sparse <- character(0)
for (j in seq_along(items)) {
cats <- categories[[j]]
counts <- vapply(seq_along(cats) - 1, function(c0) sum(codes[, j] == c0, na.rm = TRUE), numeric(1))
sparse <- c(sparse, sprintf("%s = %s (%d)", items[j], cats, counts)[counts < 10])
}
need <- if (model != "grm") 200 else 500
assumptions <- list(
list(key = "unidimensionality", label = "One underlying trait", status = "info",
detail = "Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items."),
list(key = "sample_size", label = "Sample size", status = if (n < need) "warn" else "pass",
detail = paste0(sprintf("%d respondents for %d parameters", n, npar), if (n < need) sprintf(" — %d or more are usually recommended for the %s.", need, lcfirst(model_label)) else ".")),
list(key = "categories", label = "Category use", status = if (length(sparse)) "warn" else "pass",
detail = if (length(sparse)) paste0("Fewer than 10 responses: ", paste(utils::head(sparse, 8), collapse = "; "), if (length(sparse) > 8) " …" else "", ".")
else "Every category has at least 10 responses."),
list(key = "convergence", label = "Convergence", status = if (fit$converged) "pass" else "warn",
detail = if (fit$converged) sprintf("EM converged in %d cycles.", fit$iterations) else sprintf("EM stopped after %d cycles without converging.", fit$iterations))
)
assumptions <- c(assumptions, diag$assumptions) # item fit (S-X², Holm-adjusted) and local independence (Q3 more than 0.2 above its average)
# %% Result
cols <- list(list(key = "item", label = "Item", type = "string"), list(key = "a", label = "Discrimination a", type = "number"),
list(key = "se_a", label = "SE", type = "number"))
for (m in seq_len(kmax - 1)) {
cols <- c(cols, list(list(key = sprintf("b%d", m), label = if (kmax == 2) "Difficulty b" else sprintf("Threshold b%d", m), type = "number"),
list(key = sprintf("se_b%d", m), label = "SE", type = "number")))
}
theta <- round((-40:40) / 10, 10)
info <- cs_meas_irt_information(fit, theta)
curve_t <- numeric(0)
curve_p <- numeric(0)
curve_i <- character(0)
curve_c <- character(0)
for (j in seq_along(items)) {
P <- cs_meas_cat_probs(fit$params[[j]]$a, fit$params[[j]]$d, theta)
cats <- categories[[j]]
shown <- if (length(cats) == 2) length(cats) else seq_along(cats)
for (c0 in shown) {
curve_t <- c(curve_t, theta)
curve_p <- c(curve_p, P[, c0])
curve_i <- c(curve_i, rep(items[j], length(theta)))
curve_c <- c(curve_c, rep(cats[c0], length(theta)))
}
}
total <- colSums(info)
curve_roles <- list(
theta = cs_col("Trait (θ)", curve_t, "numeric"),
probability = cs_col("Probability", curve_p, "numeric"),
item = cs_col("Item", curve_i, "categorical", levels = items)
)
if (!binary) curve_roles$category <- cs_col("Category", curve_c, "categorical")
charts <- list(
cs_chart("curves", "item-curves", if (binary) "Item characteristic curves" else "Category response curves", curve_roles, controls = list(kind = "icc")),
cs_chart("information", "test-information", "Test information", list(
theta = cs_col("Trait (θ)", theta, "numeric"),
information = cs_col("Information", total, "numeric"),
se = cs_col("Standard error", 1 / sqrt(total), "numeric")
))
)
q3 <- diag$q3
qc <- expand.grid(j = seq_along(items), i = seq_along(items))
show <- qc$i != qc$j & is.finite(q3[cbind(qc$i, qc$j)])
charts <- c(charts, list(cs_chart("q3", "matrix-heatmap", "Residual correlations (Q3)", list(
row = cs_col("Item", items[qc$i], "categorical", levels = items),
col = cs_col("With", items[qc$j], "categorical", levels = items),
value = cs_col("Q3", ifelse(show, q3[cbind(qc$i, qc$j)], 0), "numeric"),
label = cs_col("Text", ifelse(show, sprintf("%.2f", q3[cbind(qc$i, qc$j)]), ""), "categorical")
), controls = list(scale = "diverging"))))
cat_note <- substr(paste(vapply(seq_along(items), function(j) sprintf("%s: %s", items[j], paste(categories[[j]], collapse = ", ")), character(1)), collapse = "; "), 1, 600)
cs_publish(list(
method = "measurement.irt",
methodVersion = "1.1.0",
title = model_label,
engine = cs_engine_info("stats", "codesplashr"),
n = n,
summary = sprintf("%s for %d items and %d respondents: log-likelihood %.2f, empirical reliability %.2f.", model_label, length(items), n, loglik, reliability),
apa = sprintf("%s: log-likelihood = %s, AIC = %s, BIC = %s", model_label, cs_fmt_num(loglik), cs_fmt_num(values$aic, 1), cs_fmt_num(values$bic, 1)),
statistics = list(list(key = "loglik", label = "Log-likelihood", value = loglik), list(key = "aic", label = "AIC", value = values$aic),
list(key = "bic", label = "BIC", value = values$bic), list(key = "reliability", label = "Empirical reliability", value = reliability)),
tables = c(list(
list(key = "items", title = "Item parameters (IRT form: logit = a(θ − b))", columns = cols, rows = rows),
list(key = "persons", title = "Person scores (EAP)", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")),
rows = list(list(stat = "Mean", value = mean(eap)), list(stat = "SD", value = sqrt(var_eap)),
list(stat = "Mean posterior SD", value = sqrt(mean(psd^2))), list(stat = "Empirical reliability", value = reliability)))
), diag$tables),
assumptions = assumptions,
warnings = warnings,
notes = c(list(paste0(sprintf("Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; %d EM cycles. Categories: ", fit$iterations), cat_note)),
diag$notes),
charts = charts,
values = values
))
Graded response model: log-likelihood = −1608.87, AIC = 3249.7, BIC = 3313.3
- Log-likelihood
- −1608.87
- AIC
- 3249.74
- BIC
- 3313.28
- Empirical reliability
- 0.6665
Assumptions
- One underlying trait — Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items.
- Sample size — 392 respondents for 16 parameters — 500 or more are usually recommended for the graded response model.
- Category use — Fewer than 10 responses: comfort = 1 (5).
- Convergence — EM converged in 134 cycles.
- Item fit — No item's S-X² is significant after Holm's adjustment (smallest adjusted p = 1.000).
- Local independence — Q3 more than 0.2 above its average (-0.190): comfort with benefit (0.085). These items may share something beyond the trait.
Item parameters (IRT form: logit = a(θ − b))
| Item | Discrimination a | SE | Threshold b1 | SE | Threshold b2 | SE | Threshold b3 | SE |
|---|---|---|---|---|---|---|---|---|
| comfort | 1.041 | 0.1882 | −4.673 | 0.8142 | −2.536 | 0.3920 | 1.408 | 0.2310 |
| work | 1.226 | 0.1817 | −2.385 | 0.3045 | −0.7351 | 0.1311 | 1.849 | 0.2343 |
| future | 2.301 | 0.4882 | −2.280 | 0.2591 | −0.9644 | 0.1160 | 0.8552 | 0.1118 |
| benefit | 1.094 | 0.1832 | −3.060 | 0.4481 | −0.9064 | 0.1615 | 1.543 | 0.2313 |
Person scores (EAP)
| Value | |
|---|---|
| Mean | 3.557e-8 |
| SD | 0.8164 |
| Mean posterior SD | 0.5775 |
| Empirical reliability | 0.6665 |
Item fit (S-X²)
| Item | S-X² | df | p | p (Holm) | RMSEA |
|---|---|---|---|---|---|
| comfort | 4.787 | 6 | .571 | 1.000 | 0 |
| work | 8.757 | 9 | .460 | 1.000 | 0 |
| future | 7.554 | 8 | .478 | 1.000 | 0 |
| benefit | 9.925 | 11 | .537 | 1.000 | 0 |
Limited-information fit
| Measure | Value |
|---|---|
| M2* | — |
| df | — |
| p | — |
| RMSEA2 | — |
| RMSEA2 90% CI low | — |
| RMSEA2 90% CI high | — |
| SRMSR | 0.0726 |
- Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; 134 EM cycles. Categories: comfort: 1, 2, 3, 4; work: 1, 2, 3, 4; future: 1, 2, 3, 4; benefit: 1, 2, 3, 4
- M2 needs more item means and cross-products than parameters (10 vs 16); only the SRMSR is shown.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Item response theory (Rasch, 2PL, graded response)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.irt 1.1.0 · spec 0175706c384a4424
# Dataset: s3_science (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_finite
from codesplash.stats import measurement as ms # MML-EM IRT twin of R's cs_meas_irt_fit
from codesplash.stats import measurement_fit as mf # S-X², M2 and Q3 twins of R's cs_meas_irt_diagnostics
# mirt::mirt(data, 1, itemtype = "2PL" | "graded" | "Rasch") fits the same models on the same grid;
# the twin adds observed-information standard errors and keeps Python and R identical.
# %% Data (missing responses are kept; respondents with no response are left out)
items = ["comfort", "work", "future", "benefit"]
kinds = {"benefit":"numeric","comfort":"numeric","future":"numeric","work":"numeric"}
stored = json.loads("{\"benefit\":null,\"comfort\":null,\"future\":null,\"work\":null}")
df = pd.read_parquet("tests/parity/fixtures/s3_science.parquet", columns=items)
warnings = []
n0 = len(df)
codes = np.full((n0, len(items)), np.nan)
categories = []
for j, it in enumerate(items):
if kinds[it] == "numeric":
x = df[it].to_numpy(dtype=float)
check_finite(x, it) # infinite values stop the run (registry/errors.yaml)
vals = np.unique(x[~np.isnan(x)])
codes[:, j] = np.where(np.isnan(x), np.nan, np.searchsorted(vals, np.nan_to_num(x)))
labels = [f"{v:.0f}" if float(v).is_integer() else f"{v:.15g}" for v in vals]
else:
t = [None if pd.isna(v) else (str(v).lower() if isinstance(v, (bool, np.bool_)) else str(v)) for v in df[it]]
order = stored[it] or sorted({v for v in t if v is not None})
used = [c for c in order if c in set(t)]
if len(used) < len(order):
warnings.append(f"{it}: categories nobody chose were dropped ({', '.join(c for c in order if c not in used)}).")
pos = {c: i for i, c in enumerate(used)}
codes[:, j] = [pos[v] if v is not None else np.nan for v in t]
labels = used
if len(labels) == 0:
cs.cs_error("CS_E_ALL_MISSING", column=it)
if len(labels) < 2:
cs.cs_error("CS_E_CONSTANT", column=it) # one response category: nothing to scale
categories.append(labels)
answered = np.sum(~np.isnan(codes), axis=1) > 0
if (~answered).any():
warnings.append(f"{int((~answered).sum())} respondents without any response were left out.")
codes = codes[answered]
n = codes.shape[0]
binary = all(len(c) == 2 for c in categories)
model = "auto"
if model == "auto":
model = "2pl" if binary else "grm"
if model in ("rasch", "2pl") and not binary:
raise ValueError("The Rasch and 2PL models need right/wrong items; use the graded response model for more categories")
model_label = {"rasch": "Rasch (1PL) model", "2pl": "Two-parameter logistic (2PL) model", "grm": "Graded response model"}[model]
# %% Fit (marginal maximum likelihood, EM on 61 quadrature points)
try:
fit = ms.irt_fit(codes, model)
except np.linalg.LinAlgError: # a singular information matrix: estimates run off, e.g. an item that separates respondents perfectly
cs.cs_error("CS_E_NO_CONVERGENCE", what={"rasch": "The Rasch model", "2pl": "The 2PL model", "grm": "The graded response model"}[model])
table = ms.irt_item_table(fit)
npar = fit["npar"]
loglik = fit["loglik"]
eap, psd = fit["eap"], fit["psd"]
var_eap = float(np.mean((eap - eap.mean()) ** 2))
reliability = var_eap / (var_eap + float(np.mean(psd**2)))
values = {"n": float(n), "items": float(len(items)), "npar": float(npar), "loglik": loglik, "aic": -2 * loglik + 2 * npar,
"bic": -2 * loglik + npar * np.log(n), "reliability": reliability, "eap_mean": float(eap.mean()), "eap_sd": float(np.sqrt(var_eap)),
"model_label": model_label}
rows = []
kmax = max(len(c) for c in categories)
for it, r, cats in zip(items, table, categories):
values[f"a[{it}]"] = r["a"]
values[f"se_a[{it}]"] = r["se_a"]
row = {"item": it, "a": r["a"], "se_a": r["se_a"]}
if len(cats) == 2:
values[f"b[{it}]"] = r["b"][0]
values[f"se_b[{it}]"] = r["se_b"][0]
row.update({"b1": r["b"][0], "se_b1": r["se_b"][0]})
else:
for m, (b, se) in enumerate(zip(r["b"], r["se_b"]), start=1):
values[f"b[{it}|{m}]"] = b
values[f"se_b[{it}|{m}]"] = se
row.update({f"b{m}": b, f"se_b{m}": se})
rows.append(row)
# %% Item and model fit: S-X² per item (Orlando & Thissen; mirt's cell collapsing), M2 / M2* with RMSEA2
# and SRMSR (Maydeu-Olivares & Joe), Yen's Q3 at the EAP scores — mirt::itemfit, M2 and residuals compute the same
diag = mf.irt_diagnostics(fit, codes, items)
values.update(diag["values"])
# %% Assumptions
sparse = []
for j, (it, cats) in enumerate(zip(items, categories)):
counts = [int(np.sum(codes[:, j] == c)) for c in range(len(cats))]
sparse += [f"{it} = {cats[c]} ({counts[c]})" for c in range(len(cats)) if counts[c] < 10]
need = 200 if model != "grm" else 500
assumptions = [
{"key": "unidimensionality", "label": "One underlying trait", "status": "info",
"detail": "Assumed by the model; check it with a one-factor analysis (exploratory factor analysis or CFA) of the items."},
{"key": "sample_size", "label": "Sample size", "status": "warn" if n < need else "pass",
"detail": f"{n} respondents for {npar} parameters" + (f" — {need} or more are usually recommended for the {model_label[0].lower() + model_label[1:]}." if n < need else ".")},
{"key": "categories", "label": "Category use", "status": "warn" if sparse else "pass",
"detail": "Fewer than 10 responses: " + "; ".join(sparse[:8]) + (" …" if len(sparse) > 8 else "") + "." if sparse else "Every category has at least 10 responses."},
{"key": "convergence", "label": "Convergence", "status": "pass" if fit["converged"] else "warn",
"detail": f"EM converged in {fit['iterations']} cycles." if fit["converged"] else f"EM stopped after {fit['iterations']} cycles without converging."},
*diag["assumptions"], # item fit (S-X², Holm-adjusted) and local independence (Q3 more than 0.2 above its average)
]
# %% Result
cols = [{"key": "item", "label": "Item", "type": "string"}, {"key": "a", "label": "Discrimination a", "type": "number"},
{"key": "se_a", "label": "SE", "type": "number"}]
for m in range(1, kmax):
cols += [{"key": f"b{m}", "label": "Difficulty b" if kmax == 2 else f"Threshold b{m}", "type": "number"},
{"key": f"se_b{m}", "label": "SE", "type": "number"}]
theta = np.round(np.arange(-40, 41) / 10, 10)
info = ms.irt_information(fit, theta)
curve_t, curve_p, curve_i, curve_c = [], [], [], []
for (a, d), it, cats in zip(fit["params"], items, categories):
P = ms.category_probs(a, d, theta)
shown = [len(cats) - 1] if len(cats) == 2 else range(len(cats))
for c in shown:
curve_t += theta.tolist()
curve_p += P[:, c].tolist()
curve_i += [it] * len(theta)
curve_c += [cats[c]] * len(theta)
total = info.sum(axis=0)
charts = [
cs.chart("curves", "item-curves", "Item characteristic curves" if binary else "Category response curves", {
"theta": cs.col("Trait (θ)", curve_t, "numeric"),
"probability": cs.col("Probability", curve_p, "numeric"),
"item": cs.col("Item", curve_i, "categorical", levels=items),
**({} if binary else {"category": cs.col("Category", curve_c, "categorical")}),
}, controls={"kind": "icc"}),
cs.chart("information", "test-information", "Test information", {
"theta": cs.col("Trait (θ)", theta.tolist(), "numeric"),
"information": cs.col("Information", total.tolist(), "numeric"),
"se": cs.col("Standard error", (1 / np.sqrt(total)).tolist(), "numeric"),
}),
]
q3 = diag["q3"]
cells = [(i, j) for i in range(len(items)) for j in range(len(items))]
show = lambda i, j: i != j and np.isfinite(q3[i, j]) # noqa: E731
charts.append(cs.chart("q3", "matrix-heatmap", "Residual correlations (Q3)", {
"row": cs.col("Item", [items[i] for i, _ in cells], "categorical", levels=items),
"col": cs.col("With", [items[j] for _, j in cells], "categorical", levels=items),
"value": cs.col("Q3", [float(q3[i, j]) if show(i, j) else 0.0 for i, j in cells], "numeric"),
"label": cs.col("Text", [f"{q3[i, j]:.2f}" if show(i, j) else "" for i, j in cells], "categorical"),
}, controls={"scale": "diverging"}))
cs.publish({
"method": "measurement.irt",
"methodVersion": "1.1.0",
"title": model_label,
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": f"{model_label} for {len(items)} items and {n} respondents: log-likelihood {loglik:.2f}, empirical reliability {reliability:.2f}.",
"apa": f"{model_label}: log-likelihood = {cs.fmt_num(loglik)}, AIC = {cs.fmt_num(values['aic'], 1)}, BIC = {cs.fmt_num(values['bic'], 1)}",
"statistics": [{"key": "loglik", "label": "Log-likelihood", "value": loglik}, {"key": "aic", "label": "AIC", "value": values["aic"]},
{"key": "bic", "label": "BIC", "value": values["bic"]}, {"key": "reliability", "label": "Empirical reliability", "value": reliability}],
"tables": [{"key": "items", "title": "Item parameters (IRT form: logit = a(θ − b))", "columns": cols, "rows": rows},
{"key": "persons", "title": "Person scores (EAP)", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}],
"rows": [{"stat": "Mean", "value": float(eap.mean())}, {"stat": "SD", "value": float(np.sqrt(var_eap))},
{"stat": "Mean posterior SD", "value": float(np.sqrt(np.mean(psd**2)))}, {"stat": "Empirical reliability", "value": reliability}]},
*diag["tables"]],
"assumptions": assumptions,
"warnings": warnings,
"notes": [f"Marginal maximum likelihood (EM over 61 points on [−6, 6], θ ~ N(0, 1)); standard errors from the observed information; "
f"{fit['iterations']} EM cycles. Categories: " + "; ".join(f"{it}: {', '.join(c)}" for it, c in zip(items, categories))[:600],
*diag["notes"]],
"charts": charts,
"values": values,
})
Shortened for the Academy: 3 chart(s) dropped to stay under 100 KB; 3 chart(s) dropped to stay under 100 KB.
Same model, two dialects
Readimport pandas as pd
from girth import twopl_mml
df = pd.read_csv("s3_lsat7.csv")
# girth expects items in rows and people in columns
est = twopl_mml(df.to_numpy().T)
print(est["Discrimination"], est["Difficulty"])library(mirt)
df <- read.csv("s3_lsat7.csv")
fit2 <- mirt(df, 1, itemtype = "2PL", verbose = FALSE)
fit1 <- mirt(df, 1, itemtype = "Rasch", verbose = FALSE)
anova(fit1, fit2)
coef(fit2, IRTpars = TRUE, simplify = TRUE)$itemsScoring methods and estimation settings differ among packages, so compare estimates with the card rather than expecting identical digits.
Check your understanding
CheckpointCheck yourself
A person's trait level equals an item's difficulty, . What is their chance of answering correctly under the 2PL?
Show the answer
Answer: 0.5
At the exponent is 0, so the probability is .
Check yourself
Item A has = 2, and item B has = 0.4, at the same difficulty. Which is true?
Show the answer
Answer: a
Discrimination sets the steepness of the curve at the difficulty.
Check yourself
You need a test to identify the very top performers. Which items should you add?
Show the answer
Answer: b
Information peaks near an item's difficulty, and it's greater with higher discrimination.
Recap
Recap- IRT models each item through its difficulty and discrimination.
- Rasch fixes discrimination; 2PL estimates it, and a likelihood-ratio test compares them.
- Precision varies across the trait, so read the information curve.
Concepts in this lesson