Paired comparisons: Bradley–Terry and friends
Turn "A or B?" judgments into worths with honest uncertainty. Fit Bradley–Terry, handle ties with Davidson, catch a position bias, and let Crowd-BT down-weight careless judges.
What runs in CodeSplash
- Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT) Verified in Python and R
You will be able to
- Read a worth difference as the odds that one item beats another
- Explain why a win rate leaderboard misleads and when worths don't exist
- Choose between Bradley–Terry, Thurstone, Davidson and Crowd-BT
- Check a position effect and judge reliability before trusting a ranking
Read first
From judgments to worths
ReadSix summarizers, eight judges, 24 prompts: each judgment asks which of two summaries is better. Raw win rates depend on who you happened to face, so a system that met mostly weak rivals looks better than it is.
The Bradley–Terry modelBradley–Terry modelA model of pairwise judgments: the difference in two items' log-worths sets the log odds that one is preferred to the other. gives each item a worthWorthAn item's estimated strength in a preference model; only differences between worths mean anything, so they are centered to sum to 0. and models every judgment the same way:
Only differences matter, so the worths are centered to sum to 0. A difference of 1 multiplies the odds of preferring the first item by .
Bradley–Terry model: LR χ²(5) = 33.32, p < .001
- LR χ²
- 33.325
- p
- < .001
- AIC
- 786.27
- atlas first
- 64.5%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 0.4087 | 0.6396 | atlas | 0.1779 |
| 0.3565 | 0.5969 | birch | 0.1160 |
| 0.0146 | 0.2574 | cedar | −0.2283 |
| −0.0566 | 0.1807 | delta | −0.2940 |
| −0.2480 | 0.0091 | ember | −0.5052 |
| −0.4751 | −0.2326 | fjord | −0.7177 |
View data
| Against | Text | Item | Probability |
|---|---|---|---|
| atlas | atlas | 0.5000 | |
| birch | 0.51 | atlas | 0.5131 |
| cedar | 0.60 | atlas | 0.5973 |
| delta | 0.61 | atlas | 0.6143 |
| ember | 0.66 | atlas | 0.6585 |
| fjord | 0.71 | atlas | 0.7076 |
| atlas | 0.49 | birch | 0.4869 |
| birch | birch | 0.5000 | |
| cedar | 0.58 | birch | 0.5847 |
| delta | 0.60 | birch | 0.6018 |
| ember | 0.65 | birch | 0.6467 |
| fjord | 0.70 | birch | 0.6967 |
| atlas | 0.40 | cedar | 0.4027 |
| birch | 0.42 | cedar | 0.4153 |
| cedar | cedar | 0.5000 | |
| delta | 0.52 | cedar | 0.5178 |
| ember | 0.57 | cedar | 0.5653 |
| fjord | 0.62 | cedar | 0.6200 |
| atlas | 0.39 | delta | 0.3857 |
| birch | 0.40 | delta | 0.3982 |
| cedar | 0.48 | delta | 0.4822 |
| delta | delta | 0.5000 | |
| ember | 0.55 | delta | 0.5477 |
| fjord | 0.60 | delta | 0.6031 |
| atlas | 0.34 | ember | 0.3415 |
| birch | 0.35 | ember | 0.3533 |
| cedar | 0.43 | ember | 0.4347 |
| delta | 0.45 | ember | 0.4523 |
| ember | ember | 0.5000 | |
| fjord | 0.56 | ember | 0.5565 |
| atlas | 0.29 | fjord | 0.2924 |
| birch | 0.30 | fjord | 0.3033 |
| cedar | 0.38 | fjord | 0.3800 |
| delta | 0.40 | fjord | 0.3969 |
| ember | 0.44 | fjord | 0.4435 |
| fjord | fjord | 0.5000 |
View data
| Item | Share of resamples |
|---|---|
| atlas | 0.6450 |
| birch | 0.3500 |
| cedar | 0 |
| delta | 0.0050 |
| ember | 0 |
| fjord | 0 |
Assumptions
- Connected comparisons — Every item wins and loses its way to every other item, so the estimates are finite and unique.
- Worths explain the pairs — G² = 10.65 on 10 df, p = 0.386.
- Judgments per item — Every item has at least 10 judgments (fewest 169).
- Ties — 118 tie(s) left out; the Davidson model would use them.
- Position effect — Likelihood-ratio test for a first-position advantage: χ²(1) = 1.33, p = 0.248.
- Independent judgments — Not checked from data: judgments are treated as independent. The bootstrap resamples single judgments.
Worths (log scale, centered; share = chance of being preferred among all 6)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Wins | Losses | Ties | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | atlas | 0.4087 | 0.1178 | 0.1779 | 0.6396 | 0.2391 | 135 | 83 | 0 | 0.6450 | 1 | 2 |
| 2 | birch | 0.3565 | 0.1227 | 0.1160 | 0.5969 | 0.2269 | 118 | 79 | 0 | 0.3500 | 1 | 2.025 |
| 3 | cedar | 0.0146 | 0.1239 | −0.2283 | 0.2574 | 0.1612 | 92 | 95 | 0 | 0 | 2.975 | 5 |
| 4 | delta | −0.0566 | 0.1211 | −0.2940 | 0.1807 | 0.1501 | 93 | 103 | 0 | 0.0050 | 3 | 5 |
| 5 | ember | −0.2480 | 0.1312 | −0.5052 | 0.0091 | 0.1240 | 74 | 95 | 0 | 0 | 3 | 6 |
| 6 | fjord | −0.4751 | 0.1238 | −0.7177 | −0.2326 | 0.0988 | 72 | 129 | 0 | 0 | 5 | 6 |
Model fit
| Value | |
|---|---|
| Judgments fitted | 584 |
| Log-likelihood | −388.14 |
| AIC | 786.27 |
| BIC | 808.12 |
| LR χ² vs equal worths | 33.325 |
| LR p | 3.244e-6 |
| Goodness of fit G² | 10.648 |
| G² df | 10 |
| G² p | 0.3856 |
- Left out (neither item preferred): inconsistent (12), abstain (6).
- 118 tie(s) were left out; the Davidson model uses them.
- Bradley–Terry model: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (fjord) was the reference in the fit. Outcome read as whether the first item won. Newton iterations: 4.
- Bootstrap: 200 of 200 resamples of single judgments refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.bradley_terry 1.0.0 · spec a550400da8dc7e83
# Dataset: hme_pairs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_pairs.parquet", col_select = c("first", "second", "verdict")))
n_input <- nrow(df)
df[["first"]] <- factor(df[["first"]], levels = c("atlas", "birch", "cedar", "delta", "ember", "fjord")) # stored level order
df[["second"]] <- factor(df[["second"]], levels = c("atlas", "birch", "cedar", "delta", "ember", "fjord")) # stored level order
df[["verdict"]] <- factor(df[["verdict"]], levels = sort(unique(df[["verdict"]]), method = "radix"))
df <- df[stats::complete.cases(df[c("first", "second", "verdict")]), , 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("first", "second", "verdict")) # infinite values stop the run (registry/errors.yaml)
# %% Judgments
col_a <- "first"
col_b <- "second"
col_y <- "verdict"
model <- "bt"
ties <- "drop"
use_order <- FALSE
prior <- 0.5
reps <- 200
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
label <- cs_pc_labels()[[model]]
kinds <- c(
"first" = "categorical",
"second" = "categorical",
"verdict" = "categorical"
)
first <- as.character(df[[col_a]])
second <- as.character(df[[col_b]])
y_raw <- if (kinds[[col_y]] %in% c("categorical", "boolean")) as.character(df[[col_y]]) else df[[col_y]]
dec <- cs_pc_decode_outcomes(kinds[[col_y]], y_raw, first, second, "auto")
codes <- dec$codes
coding <- dec$coding
if (any(codes == -2)) cs_error("CS_E_INVALID_VALUES", column = col_y, requirement = "1 (first item preferred), 0 (second) or 0.5 (tie)", count = sum(codes == -2))
count <- rep(1, nrow(df))
held <- rep(FALSE, nrow(df))
self_pair <- first == second
states <- list()
for (i in which(codes == -1 & !self_pair)) {
key <- dec$other[i]
states[[key]] <- (if (is.null(states[[key]])) 0 else states[[key]]) + count[i]
}
if (any(self_pair)) warnings <- c(warnings, list(sprintf("%d judgment(s) comparing an item with itself were left out.", as.integer(sum(count[self_pair])))))
if (length(states)) {
warnings <- c(warnings, list(paste0("Left out (neither item preferred): ",
paste(sprintf("%s (%d)", names(states), as.integer(unlist(states))), collapse = ", "), ".")))
}
n_left_out <- sum(unlist(states)) + sum(count[self_pair])
oc <- cs_pc_outcome_counts(codes, count, model, ties)
y1 <- oc$y1; y2 <- oc$y2; y3 <- oc$y3
use <- oc$keep & !self_pair
train <- use & !held
items_all <- unique(c(levels(df[[col_a]]), levels(df[[col_b]])))
seen <- unique(c(first[train], second[train]))
items <- items_all[items_all %in% seen]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_a, min = 2, k = k)
ia <- match(first, items)
ib <- match(second, items)
ia[is.na(ia)] <- 0L
ib[is.na(ib)] <- 0L
tr <- which(train)
a <- ia[tr]; b <- ib[tr]
t1 <- y1[tr]; t2 <- y2[tr]; t3 <- y3[tr]; tc <- count[tr]
n_ties <- sum(count[codes == 2 & !self_pair & !held])
if (ties == "drop" && model != "davidson" && n_ties > 0) warnings <- c(warnings, list(sprintf("%d tie(s) were left out; the Davidson model uses them.", as.integer(n_ties))))
if (model == "davidson" && sum(t3) == 0) cs_error("CS_E_UNDEFINED", what = "The Davidson model", reason = "there are no ties; use Bradley–Terry")
col_j <- NULL
judge_names <- character(0)
jcode <- NULL
if (model == "crowd_bt" && is.null(col_j)) cs_error("CS_E_UNDEFINED", what = "Crowd-BT", reason = "it needs a Judge column")
if (model == "crowd_bt" && length(judge_names) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_j, min = 2, k = length(judge_names))
unit_col <- NULL
if (!is.null(unit_col)) {
uv <- as.character(df[[unit_col]])[tr]
unit <- match(uv, unique(uv))
} else {
unit <- NULL
}
n <- sum(t1 + t2 + t3)
adj <- cs_pc_beat_graph(a, b, t1, t2, t3, k)
connected <- cs_pc_strongly_connected(adj)
if (model != "crowd_bt" && !connected) {
cs_error("CS_E_UNDEFINED", what = paste("The", label), reason = "some items never lose (or never win) against the rest, so their worths run off to infinity; add comparisons, or use Crowd-BT, which shrinks the worths toward the middle")
}
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
cell <- cs_pc_cells(a, b, t1, t2, t3, k, if (model == "crowd_bt") jcode else NULL)
fits <- tryCatch(list(
fit = cs_pc_fit_model(model, cell, k, use_order, length(judge_names), prior),
null = if (model == "crowd_bt") NULL else cs_pc_fit_pairs(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, k, use_order, null = TRUE)
), error = function(e) {
if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
cs_error("CS_E_NO_CONVERGENCE", what = paste("The", label))
})
fit <- fits$fit
null <- fits$null
alt <- NULL
alt_note <- NULL
if (model != "crowd_bt" && !use_order) { # the position test refits with a first-position term
alt <- tryCatch(cs_pc_fit_pairs(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, k, TRUE), error = function(e) NULL)
if (is.null(alt)) alt_note <- "A position effect can't be told apart from the worths in this design (for example, one item is always shown first)."
}
s <- fit$scores
z <- cs_pc_z(conf)
se <- if (!is.null(fit$cov)) sqrt(diag(fit$cov)) else rep(NA_real_, k)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
npar <- if (model == "crowd_bt") fit$npar else (k - 1) + as.integer(use_order) + as.integer(model == "davidson")
loglik <- fit$loglik
nz <- function(x) if (is.null(x) || length(x) == 0 || is.na(x)) NULL else x
values <- list(n = n, n_rows = length(tr), items = k, n_ties = n_ties, n_left_out = n_left_out, model_label = label,
loglik = loglik, npar = npar, aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n), iterations = fit$iterations)
if (!is.null(null)) {
lr <- 2 * (loglik - null$loglik)
values$loglik_null <- null$loglik; values$lr <- lr; values$lr_df <- k - 1; values$lr_p <- cs_pc_lr_p(lr, k - 1)
} else {
values["loglik_null"] <- list(NULL); values["lr"] <- list(NULL); values["lr_df"] <- list(NULL); values["lr_p"] <- list(NULL)
}
if (use_order) {
zo <- if (!is.null(fit$alpha_se)) fit$alpha / fit$alpha_se else NULL
values$order_effect <- fit$alpha
values["order_effect_se"] <- list(fit$alpha_se)
values["order_effect_p"] <- list(if (is.null(zo)) NULL else 2 * stats::pnorm(abs(zo), lower.tail = FALSE))
} else {
values["order_effect"] <- list(NULL); values["order_effect_se"] <- list(NULL); values["order_effect_p"] <- list(NULL)
}
if (!is.null(alt)) {
plr <- 2 * (alt$loglik - loglik)
values$position_lr <- plr; values$position_p <- cs_pc_lr_p(plr, 1)
} else {
values["position_lr"] <- list(NULL); values["position_p"] <- list(NULL)
}
if (model == "davidson") {
nu <- fit$nu; lse <- fit$lognu_se
values$nu <- nu; values$nu_low <- exp(log(nu) - z * lse); values$nu_high <- exp(log(nu) + z * lse)
values$tie_rate <- sum(t3) / n
} else {
for (key in c("nu", "nu_low", "nu_high", "tie_rate")) values[key] <- list(NULL)
}
gof <- NULL
if (model != "crowd_bt") {
gof <- cs_pc_gof(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, s, fit$nu, use_order, npar)
if (gof$df > 0) {
values$gof <- gof$g2; values$gof_df <- gof$df; values$gof_p <- cs_pc_lr_p(gof$g2, gof$df)
} else {
values["gof"] <- list(NULL); values["gof_df"] <- list(NULL); values["gof_p"] <- list(NULL)
}
} else {
values["gof"] <- list(NULL); values["gof_df"] <- list(NULL); values["gof_p"] <- list(NULL)
}
st <- cs_pc_item_stats(a, b, codes[tr], tc, k)
wins <- st$wins; losses <- st$losses; tied <- st$ties
ci_low <- s - z * se
ci_high <- s + z * se
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("score[%s]", it)]] <- s[i]
values[sprintf("se[%s]", it)] <- list(nz(se[i]))
values[sprintf("ci_low[%s]", it)] <- list(nz(ci_low[i]))
values[sprintf("ci_high[%s]", it)] <- list(nz(ci_high[i]))
values[[sprintf("worth[%s]", it)]] <- worth[i]
values[[sprintf("rank[%s]", it)]] <- ranks[i]
values[[sprintf("wins[%s]", it)]] <- wins[i]
values[[sprintf("losses[%s]", it)]] <- losses[i]
values[[sprintf("ties[%s]", it)]] <- tied[i]
}
# %% Judges
reversed_judges <- character(0)
if (model == "crowd_bt") {
eta <- fit$eta
n_j <- vapply(seq_along(judge_names), function(g) sum((t1 + t2)[jcode == g]), numeric(1))
for (g in seq_along(judge_names)) {
values[[sprintf("eta[%s]", judge_names[g])]] <- eta[g]
values[[sprintf("n_judge[%s]", judge_names[g])]] <- n_j[g]
}
reversed_judges <- judge_names[eta < 0.5]
} else if (!is.null(col_j)) {
ja <- cs_pc_judge_agreement(a, b, jcode, codes[tr], tc, s, length(judge_names))
for (g in seq_along(judge_names)) {
values[sprintf("agreement[%s]", judge_names[g])] <- list(nz(ja$agreement[g]))
values[[sprintf("n_judge[%s]", judge_names[g])]] <- ja$n[g]
}
}
values["judges"] <- list(if (!is.null(col_j)) length(judge_names) else NULL)
values["reversed_judges"] <- list(if (model == "crowd_bt") length(reversed_judges) else NULL)
# %% Bootstrap of the ranking (shared Wichmann–Hill stream; judgments, or whole clusters/judges)
boot_note <- NULL
boot_scores <- matrix(0, 0, k)
boot_failed <- 0
if (reps > 0) {
draws <- if (is.null(unit)) sum(tc) else max(unit)
if (draws * reps > 5e7) {
boot_note <- "The bootstrap was skipped: resampling this many judgments would take too long; set a Cluster column or fewer resamples."
} else {
bs <- cs_pc_bootstrap(model, a, b, jcode, t1, t2, t3, tc, unit, k, length(judge_names), use_order, prior, reps, seed)
boot_scores <- bs$scores
boot_failed <- bs$failed
}
}
values["boot_ok"] <- list(if (reps > 0) nrow(boot_scores) else NULL)
values["boot_failed"] <- list(if (reps > 0) boot_failed else NULL)
top <- cs_pc_top_index(s)
values$top_item <- items[top]
bsum <- NULL
if (nrow(boot_scores) >= 2) {
bsum <- cs_pc_boot_summary(boot_scores, conf)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("boot_low[%s]", it)]] <- bsum$low[i]
values[[sprintf("boot_high[%s]", it)]] <- bsum$high[i]
values[[sprintf("top_freq[%s]", it)]] <- bsum$top[i]
values[[sprintf("rank_low[%s]", it)]] <- bsum$rank_low[i]
values[[sprintf("rank_high[%s]", it)]] <- bsum$rank_high[i]
}
values$top_item_freq <- bsum$top[top]
} else {
values["top_item_freq"] <- list(NULL)
}
# %% Held-out judgments (rows marked as test)
te <- which(use & held & ia > 0 & ib > 0)
values$n_test <- sum(use & held)
if (length(te)) {
alpha <- if (is.null(fit$alpha)) 0 else fit$alpha
dt <- s[ia[te]] - s[ib[te]] + alpha
if (model == "crowd_bt") {
jt <- as.character(df[[col_j]])[te]
n_jt <- vapply(seq_along(judge_names), function(g) sum((t1 + t2)[jcode == g]), numeric(1))
eta_mean <- sum(fit$eta * n_jt) / sum(n_jt)
et <- ifelse(jt %in% judge_names, fit$eta[match(jt, judge_names)], eta_mean)
q <- cs_pc_crowd_probs(dt, et)
bq <- list(rep(0.5, length(te)), rep(0.5, length(te)), rep(0, length(te)))
} else {
q <- cs_pc_pair_probs(model, dt, fit$nu)
bq <- cs_pc_pair_probs(model, rep(if (is.null(null$alpha)) 0 else null$alpha, length(te)), null$nu)
}
e1 <- y1[te]; e2 <- y2[te]; e3 <- y3[te]
nt <- sum(e1 + e2 + e3)
lg <- function(x) log(ifelse(x > 0, x, 1)) # zero-probability cells carry no weight
values$test_logloss <- -sum(e1 * lg(q[[1]]) + e2 * lg(q[[2]]) + e3 * lg(q[[3]])) / nt
values$test_baseline <- -sum(e1 * lg(bq[[1]]) + e2 * lg(bq[[2]]) + e3 * lg(bq[[3]])) / nt
values["test_brier"] <- list(if (model != "davidson") sum(e1 * (1 - q[[1]])^2 + e2 * q[[1]]^2) / nt else NULL)
values$test_scored <- nt
} else {
for (key in c("test_logloss", "test_baseline", "test_brier", "test_scored")) values[key] <- list(NULL)
}
# %% Assumptions
per_item <- wins + losses + tied
thin <- sprintf("%s (%d)", items, as.integer(per_item))[per_item < 10]
fmt3 <- function(x) formatC(signif(x, 3), digits = 3, format = "fg", flag = "#")
pfmt <- function(x) sub("\\.$", "", formatC(x, digits = 3, format = "g"))
assumptions <- list()
if (model == "crowd_bt") {
wc <- cs_pc_weakly_connected(adj)
assumptions[[length(assumptions) + 1]] <- list(key = "connectivity", label = "Connected comparisons", status = if (wc) "pass" else "warn",
detail = if (wc) "Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite." else
"Some items are never compared, even indirectly, with others; their relative worth comes only from the shrinkage.")
} else {
assumptions[[length(assumptions) + 1]] <- list(key = "connectivity", label = "Connected comparisons", status = "pass",
detail = "Every item wins and loses its way to every other item, so the estimates are finite and unique.")
}
if (!is.null(gof)) {
if (gof$df <= 0) {
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = "info", detail = "Too few distinct pairs for a goodness-of-fit test.")
} else if (gof$small > 0.2) {
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = "info",
detail = sprintf("G² = %.2f on %d df, but %.0f%% of the expected counts are below 5, so the χ² approximation is rough.", gof$g2, as.integer(gof$df), 100 * gof$small))
} else {
gp <- cs_pc_lr_p(gof$g2, gof$df)
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = if (gp < 0.05) "warn" else "pass",
detail = paste0(sprintf("G² = %.2f on %d df, p = %s", gof$g2, as.integer(gof$df), pfmt(gp)),
if (gp < 0.05) ": some pairs win more or less often than their worths say (intransitive or context-dependent preferences)." else "."))
}
}
assumptions[[length(assumptions) + 1]] <- list(key = "sample_size", label = "Judgments per item", status = if (length(thin)) "warn" else "pass",
detail = if (length(thin)) paste0("Fewer than 10 judgments: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
sprintf("Every item has at least 10 judgments (fewest %d).", as.integer(min(per_item))))
if (model == "davidson") {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = "info",
detail = sprintf("Ties are modeled as their own outcome: ν = %.3f (%.1f%% of the fitted judgments are ties); ties are likelier between items of similar worth.", values$nu, 100 * values$tie_rate))
} else if (n_ties > 0) {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = if (ties == "drop") "warn" else "info",
detail = paste0(sprintf("%d tie(s) ", as.integer(n_ties)), if (ties == "drop") "left out; the Davidson model would use them." else "counted as half a win for each item."))
} else {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = "pass", detail = "No ties in the fitted judgments.")
}
if (use_order) {
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = "info",
detail = paste0(sprintf("Fitted first-position effect %.3f", values$order_effect),
if (is.null(values$order_effect_se)) "" else sprintf(" (SE %.3f, p = %s)", values$order_effect_se, pfmt(values$order_effect_p)),
"; worths are net of it."))
} else if (!is.null(alt_note)) {
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = "info", detail = alt_note)
} else if (!is.null(alt)) {
pp <- values$position_p
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = if (pp < 0.05) "warn" else "pass",
detail = paste0(sprintf("Likelihood-ratio test for a first-position advantage: χ²(1) = %.2f, p = %s", values$position_lr, pfmt(pp)),
if (pp < 0.05) " — turn on Position effect." else "."))
}
if (model == "crowd_bt") {
lowest <- which.min(fit$eta)
assumptions[[length(assumptions) + 1]] <- list(key = "reliability", label = "Judge reliability", status = if (length(reversed_judges)) "warn" else "pass",
detail = if (length(reversed_judges)) paste0("Below 0.5 (agreeing with the consensus less than chance): ",
paste(sprintf("%s (%.2f)", reversed_judges, fit$eta[match(reversed_judges, judge_names)]), collapse = ", "), ".") else
sprintf("Every judge agrees with the consensus more often than not (lowest %s: %.2f).", judge_names[lowest], fit$eta[lowest]))
}
unit_label <- if (!is.null(unit_col)) paste("whole values of", unit_col) else "single judgments"
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent judgments", status = "info",
detail = sprintf("Not checked from data: judgments are treated as independent. The bootstrap resamples %s.", unit_label))
# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols <- list(list(key = "rank", label = "Rank", type = "integer"), list(key = "item", label = "Item", type = "string"),
list(key = "score", label = "Worth (log)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "worth", label = "Share", type = "number"), list(key = "wins", label = "Wins", type = "number"),
list(key = "losses", label = "Losses", type = "number"), list(key = "ties", label = "Ties", type = "number"))
if (!is.null(bsum)) {
cols <- c(cols, list(list(key = "top_freq", label = "First in resamples", type = "number"),
list(key = "rank_low", label = "Rank low", type = "number"), list(key = "rank_high", label = "Rank high", type = "number")))
}
rows <- lapply(ord, function(i) {
r <- list(rank = ranks[i], item = items[i], score = s[i], se = nz(se[i]), ci_low = nz(ci_low[i]), ci_high = nz(ci_high[i]),
worth = worth[i], wins = wins[i], losses = losses[i], ties = tied[i])
if (!is.null(bsum)) { r$top_freq <- bsum$top[i]; r$rank_low <- bsum$rank_low[i]; r$rank_high <- bsum$rank_high[i] }
r
})
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being preferred among all %d)", k), columns = cols, rows = rows))
fit_rows <- list(list(stat = "Judgments fitted", value = n), list(stat = "Log-likelihood", value = loglik), list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
if (!is.null(values$lr)) fit_rows <- c(fit_rows, list(list(stat = "LR χ² vs equal worths", value = values$lr), list(stat = "LR p", value = values$lr_p)))
if (!is.null(values$gof)) fit_rows <- c(fit_rows, list(list(stat = "Goodness of fit G²", value = values$gof), list(stat = "G² df", value = values$gof_df), list(stat = "G² p", value = values$gof_p)))
if (!is.null(values$test_logloss)) {
fit_rows <- c(fit_rows, list(list(stat = "Held-out log loss", value = values$test_logloss), list(stat = "Held-out log loss, equal worths", value = values$test_baseline)))
if (!is.null(values$test_brier)) fit_rows <- c(fit_rows, list(list(stat = "Held-out Brier score", value = values$test_brier)))
}
tables[[2]] <- list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows)
if (!is.null(col_j)) {
jcols <- list(list(key = "judge", label = "Judge", type = "string"), list(key = "n", label = "Judgments", type = "number"),
if (model == "crowd_bt") list(key = "eta", label = "Reliability η", type = "number") else list(key = "agreement", label = "Agrees with worth order", type = "number"))
jrows <- lapply(judge_names, function(nm) {
r <- list(judge = nm, n = values[[sprintf("n_judge[%s]", nm)]])
if (model == "crowd_bt") r$eta <- values[[sprintf("eta[%s]", nm)]] else r["agreement"] <- list(values[[sprintf("agreement[%s]", nm)]])
r
})
tables[[3]] <- list(key = "judges", title = "Judges", columns = jcols, rows = jrows)
}
low <- ifelse(is.na(ci_low), if (!is.null(bsum)) bsum$low else s, ci_low)[ord]
high <- ifelse(is.na(ci_high), if (!is.null(bsum)) bsum$high else s, ci_high)[ord]
charts <- list(cs_chart("worths", "forest", sprintf("Worths (log scale) with %s intervals", pct), list(
label = cs_col("Item", items[ord], "categorical", levels = items[ord]),
estimate = cs_col("Worth (log)", s[ord], "numeric"),
low = cs_col("Lower", low, "numeric"),
high = cs_col("Upper", high, "numeric")
), controls = list(reference = 0)))
if (k <= 30) {
shown <- items[ord]
pr <- character(0); pcl <- character(0); pv <- numeric(0); pl <- character(0)
for (i in ord) for (j in ord) {
pr <- c(pr, items[i]); pcl <- c(pcl, items[j])
if (i == j) {
pv <- c(pv, 0.5); pl <- c(pl, "")
} else {
pij <- cs_pc_pair_probs(if (model == "crowd_bt") "bt" else model, s[i] - s[j], fit$nu)[[1]]
pv <- c(pv, pij); pl <- c(pl, sprintf("%.2f", pij))
}
}
charts[[length(charts) + 1]] <- cs_chart("pairs", "matrix-heatmap", "Chance that the row item is preferred to the column item", list(
row = cs_col("Item", pr, "categorical", levels = shown),
col = cs_col("Against", pcl, "categorical", levels = shown),
value = cs_col("Probability", pv, "numeric"),
label = cs_col("Text", pl, "categorical")
), controls = list(scale = "sequential"))
}
if (!is.null(bsum)) {
charts[[length(charts) + 1]] <- cs_chart("top", "bar-ranked", "How often each item comes first in the bootstrap", list(
category = cs_col("Item", items[ord], "categorical", levels = items[ord]),
value = cs_col("Share of resamples", bsum$top[ord], "numeric")
), controls = list(agg = "sum", top = min(30, k)))
}
notes <- list(sprintf("%s: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (%s) was the reference in the fit. Outcome read as %s. Newton iterations: %d.",
label, items[k], if (coding == "winner") "the winner’s name" else "whether the first item won", as.integer(fit$iterations)))
if (model == "thurstone") notes[[length(notes) + 1]] <- "Thurstone worths are on a probit scale (P = Φ(difference)); they're about 0.6 times Bradley–Terry's and can't be compared with them directly."
if (model == "crowd_bt") notes[[length(notes) + 1]] <- sprintf("Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with %s win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.", format(prior))
if (reps > 0) {
notes[[length(notes) + 1]] <- if (!is.null(boot_note)) boot_note else sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.",
nrow(boot_scores), as.integer(reps), unit_label, format(seed), as.integer(boot_failed))
}
summary <- paste0(sprintf("%s for %d items from %d judgments: %s has the highest worth", label, k, as.integer(n), items[top]),
if (!is.null(values$top_item_freq)) sprintf(" and comes first in %.0f%% of the bootstrap resamples.", 100 * values$top_item_freq) else ".")
apa <- paste0(label, if (!is.null(values$lr)) sprintf(": LR χ²(%d) = %s, %s", as.integer(k - 1), cs_fmt_num(values$lr), cs_fmt_p(values$lr_p)) else "")
cs_publish(list(
method = "measurement.bradley_terry",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats", "codesplashr"),
n = as.integer(n),
summary = summary,
apa = apa,
statistics = list(list(key = "lr", label = "LR χ²", value = values$lr), list(key = "lr_p", label = "p", value = values$lr_p, format = "p"),
list(key = "aic", label = "AIC", value = values$aic),
list(key = "top_item_freq", label = paste(items[top], "first"), value = values$top_item_freq, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Bradley–Terry model: LR χ²(5) = 33.32, p < .001
- LR χ²
- 33.325
- p
- < .001
- AIC
- 786.27
- atlas first
- 64.5%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Connected comparisons — Every item wins and loses its way to every other item, so the estimates are finite and unique.
- Worths explain the pairs — G² = 10.65 on 10 df, p = 0.386.
- Judgments per item — Every item has at least 10 judgments (fewest 169).
- Ties — 118 tie(s) left out; the Davidson model would use them.
- Position effect — Likelihood-ratio test for a first-position advantage: χ²(1) = 1.33, p = 0.248.
- Independent judgments — Not checked from data: judgments are treated as independent. The bootstrap resamples single judgments.
Worths (log scale, centered; share = chance of being preferred among all 6)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Wins | Losses | Ties | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | atlas | 0.4087 | 0.1178 | 0.1779 | 0.6396 | 0.2391 | 135 | 83 | 0 | 0.6450 | 1 | 2 |
| 2 | birch | 0.3565 | 0.1227 | 0.1160 | 0.5969 | 0.2269 | 118 | 79 | 0 | 0.3500 | 1 | 2.025 |
| 3 | cedar | 0.0146 | 0.1239 | −0.2283 | 0.2574 | 0.1612 | 92 | 95 | 0 | 0 | 2.975 | 5 |
| 4 | delta | −0.0566 | 0.1211 | −0.2940 | 0.1807 | 0.1501 | 93 | 103 | 0 | 0.0050 | 3 | 5 |
| 5 | ember | −0.2480 | 0.1312 | −0.5052 | 0.0091 | 0.1240 | 74 | 95 | 0 | 0 | 3 | 6 |
| 6 | fjord | −0.4751 | 0.1238 | −0.7177 | −0.2326 | 0.0988 | 72 | 129 | 0 | 0 | 5 | 6 |
Model fit
| Value | |
|---|---|
| Judgments fitted | 584 |
| Log-likelihood | −388.14 |
| AIC | 786.27 |
| BIC | 808.12 |
| LR χ² vs equal worths | 33.325 |
| LR p | 3.244e-6 |
| Goodness of fit G² | 10.648 |
| G² df | 10 |
| G² p | 0.3856 |
- Left out (neither item preferred): inconsistent (12), abstain (6).
- 118 tie(s) were left out; the Davidson model uses them.
- Bradley–Terry model: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (fjord) was the reference in the fit. Outcome read as whether the first item won. Newton iterations: 4.
- Bootstrap: 200 of 200 resamples of single judgments refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.bradley_terry 1.0.0 · spec a550400da8dc7e83
# Dataset: hme_pairs (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
import codesplash as cs
from codesplash.stats import paired_comparison as pc # twin of R's cs_pc_* (R/stats_paired_comparison.R)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/hme_pairs.parquet", columns=["first", "second", "verdict"])
n_input = len(df)
df["first"] = pd.Categorical(df["first"], categories=["atlas", "birch", "cedar", "delta", "ember", "fjord"]) # stored level order
df["second"] = pd.Categorical(df["second"], categories=["atlas", "birch", "cedar", "delta", "ember", "fjord"]) # stored level order
df["verdict"] = pd.Categorical(df["verdict"], categories=sorted(df["verdict"].dropna().unique()))
df = df.dropna(subset=["first", "second", "verdict"]) # listwise deletion over the analysis columns
df["first"] = df["first"].cat.remove_unused_categories()
df["second"] = df["second"].cat.remove_unused_categories()
df["verdict"] = df["verdict"].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, ["first", "second", "verdict"]) # infinite values stop the run (registry/errors.yaml)
# %% Judgments
col_a, col_b, col_y = "first", "second", "verdict"
model = "bt"
ties = "drop"
use_order = False
prior = 0.5
reps = 200
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
label = pc.MODEL_LABELS[model]
kinds = {"first":"categorical","second":"categorical","verdict":"categorical"}
first = df[col_a].astype(str).tolist()
second = df[col_b].astype(str).tolist()
y_raw = df[col_y].astype(str).tolist() if kinds[col_y] in ("categorical", "boolean") else df[col_y].tolist()
codes, coding, other = pc.decode_outcomes(kinds[col_y], y_raw, first, second, "auto")
if (codes == -2).any():
cs.cs_error("CS_E_INVALID_VALUES", column=col_y, requirement="1 (first item preferred), 0 (second) or 0.5 (tie)", count=int((codes == -2).sum()))
count = np.ones(len(df))
held = np.zeros(len(df), dtype=bool)
self_pair = np.array([x == z for x, z in zip(first, second)], dtype=bool)
states = {}
for i in np.flatnonzero((codes == -1) & ~self_pair):
states[other[i]] = states.get(other[i], 0) + int(count[i])
if self_pair.any():
warnings.append(f"{int(count[self_pair].sum())} judgment(s) comparing an item with itself were left out.")
if states:
warnings.append("Left out (neither item preferred): " + ", ".join(f"{k} ({v})" for k, v in states.items()) + ".")
n_left_out = int(sum(states.values()) + count[self_pair].sum())
y1, y2, y3, keep = pc.outcome_counts(codes, count, model, ties)
use = keep & ~self_pair
train = use & ~held
items_all = list(dict.fromkeys([str(x) for x in df[col_a].cat.categories] + [str(x) for x in df[col_b].cat.categories]))
seen = set(np.array(first, dtype=object)[train]) | set(np.array(second, dtype=object)[train])
items = [it for it in items_all if it in seen]
k = len(items)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_a, min=2, k=k)
pos = {it: i for i, it in enumerate(items)}
ia = np.array([pos.get(x, -1) for x in first])
ib = np.array([pos.get(x, -1) for x in second])
tr = np.flatnonzero(train)
a, b = ia[tr], ib[tr]
t1, t2, t3, tc = y1[tr], y2[tr], y3[tr], count[tr]
n_ties = int(count[(codes == 2) & ~self_pair & ~held].sum())
if ties == "drop" and model != "davidson" and n_ties:
warnings.append(f"{n_ties} tie(s) were left out; the Davidson model uses them.")
if model == "davidson" and t3.sum() == 0:
cs.cs_error("CS_E_UNDEFINED", what="The Davidson model", reason="there are no ties; use Bradley–Terry")
col_j, judge_names, jcode = None, [], None
if model == "crowd_bt" and col_j is None:
cs.cs_error("CS_E_UNDEFINED", what="Crowd-BT", reason="it needs a Judge column")
if model == "crowd_bt" and len(judge_names) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_j, min=2, k=len(judge_names))
unit_col = None
if unit_col is not None:
uv = df[unit_col].astype(str).to_numpy()[tr]
unit_names = list(pd.unique(uv))
unit = np.array([unit_names.index(x) for x in uv], dtype=np.int64)
else:
unit = None
n = float((t1 + t2 + t3).sum())
adj = pc.beat_graph(a, b, t1, t2, t3, k)
connected = pc.strongly_connected(adj)
if model != "crowd_bt" and not connected:
cs.cs_error("CS_E_UNDEFINED", what=f"The {label}", reason="some items never lose (or never win) against the rest, so their worths run off to infinity; add comparisons, or use Crowd-BT, which shrinks the worths toward the middle")
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
cell = pc.pair_cells(a, b, t1, t2, t3, k, jcode if model == "crowd_bt" else None)
try:
fit = pc.fit_model(model, cell, k, use_order, len(judge_names), prior)
null = None if model == "crowd_bt" else pc.fit_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], k, use_order, null=True)
except RuntimeError:
cs.cs_error("CS_E_NO_CONVERGENCE", what=f"The {label}")
except np.linalg.LinAlgError:
cs.cs_error("CS_E_COLLINEAR")
alt, alt_note = None, None
if model != "crowd_bt" and not use_order: # the position test refits with a first-position term
try:
alt = pc.fit_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], k, True)
except (RuntimeError, np.linalg.LinAlgError):
alt_note = "A position effect can't be told apart from the worths in this design (for example, one item is always shown first)."
s = fit["scores"]
z = pc.z_value(conf)
se = np.sqrt(np.diag(fit["cov"])) if fit["cov"] is not None else np.full(k, np.nan)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
npar = fit["npar"] if model == "crowd_bt" else (k - 1) + (1 if use_order else 0) + (1 if model == "davidson" else 0)
loglik = fit["loglik"]
values = {"n": n, "n_rows": float(len(tr)), "items": float(k), "n_ties": float(n_ties), "n_left_out": float(n_left_out),
"model_label": label, "loglik": loglik, "npar": float(npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n),
"iterations": float(fit["iterations"])}
if null is not None:
lr = 2 * (loglik - null["loglik"])
values.update({"loglik_null": null["loglik"], "lr": lr, "lr_df": float(k - 1), "lr_p": pc.lr_p(lr, k - 1)})
else:
values.update({"loglik_null": None, "lr": None, "lr_df": None, "lr_p": None})
if use_order:
zo = fit["alpha"] / fit["alpha_se"] if fit["alpha_se"] else None
values.update({"order_effect": fit["alpha"], "order_effect_se": fit["alpha_se"],
"order_effect_p": None if zo is None else float(2 * pc.norm.sf(abs(zo)))})
else:
values.update({"order_effect": None, "order_effect_se": None, "order_effect_p": None})
if alt is not None:
plr = 2 * (alt["loglik"] - loglik)
values.update({"position_lr": plr, "position_p": pc.lr_p(plr, 1)})
else:
values.update({"position_lr": None, "position_p": None})
if model == "davidson":
nu, lse = fit["nu"], fit["lognu_se"]
values.update({"nu": nu, "nu_low": float(np.exp(np.log(nu) - z * lse)), "nu_high": float(np.exp(np.log(nu) + z * lse)),
"tie_rate": float(t3.sum() / n)})
else:
values.update({"nu": None, "nu_low": None, "nu_high": None, "tie_rate": None})
gof = None
if model != "crowd_bt":
g2, gdf, small = pc.gof_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], s, fit["nu"], use_order, npar)
gof = (g2, gdf, small)
values.update({"gof": g2 if gdf > 0 else None, "gof_df": float(gdf) if gdf > 0 else None, "gof_p": pc.lr_p(g2, gdf) if gdf > 0 else None})
else:
values.update({"gof": None, "gof_df": None, "gof_p": None})
wins, losses, tied = pc.item_stats(a, b, codes[tr], tc, k)
for i, it in enumerate(items):
values[f"score[{it}]"] = float(s[i])
values[f"se[{it}]"] = None if np.isnan(se[i]) else float(se[i])
values[f"ci_low[{it}]"] = None if np.isnan(se[i]) else float(s[i] - z * se[i])
values[f"ci_high[{it}]"] = None if np.isnan(se[i]) else float(s[i] + z * se[i])
values[f"worth[{it}]"] = float(worth[i])
values[f"rank[{it}]"] = float(ranks[i])
values[f"wins[{it}]"] = float(wins[i])
values[f"losses[{it}]"] = float(losses[i])
values[f"ties[{it}]"] = float(tied[i])
# %% Judges
reversed_judges = []
if model == "crowd_bt":
eta = fit["eta"]
n_j = np.bincount(jcode, weights=t1 + t2, minlength=len(judge_names))
for g, name in enumerate(judge_names):
values[f"eta[{name}]"] = float(eta[g])
values[f"n_judge[{name}]"] = float(n_j[g])
reversed_judges = [nm for g, nm in enumerate(judge_names) if eta[g] < 0.5]
elif col_j is not None:
agree, n_j = pc.judge_agreement(a, b, jcode, codes[tr], tc, s, len(judge_names))
for g, name in enumerate(judge_names):
values[f"agreement[{name}]"] = None if np.isnan(agree[g]) else float(agree[g])
values[f"n_judge[{name}]"] = float(n_j[g])
values["judges"] = float(len(judge_names)) if col_j is not None else None
values["reversed_judges"] = float(len(reversed_judges)) if model == "crowd_bt" else None
# %% Bootstrap of the ranking (shared Wichmann–Hill stream; judgments, or whole clusters/judges)
boot_note = None
if reps > 0:
draws = float(tc.sum()) if unit is None else float(unit.max() + 1)
if draws * reps > 5e7:
boot_note = "The bootstrap was skipped: resampling this many judgments would take too long; set a Cluster column or fewer resamples."
boot_scores, boot_failed = np.zeros((0, k)), 0
else:
boot_scores, boot_failed = pc.bootstrap_pairs(model, a, b, jcode, t1, t2, t3, tc, unit, k, len(judge_names), use_order, prior, reps, seed)
else:
boot_scores, boot_failed = np.zeros((0, k)), 0
values["boot_ok"] = float(len(boot_scores)) if reps > 0 else None
values["boot_failed"] = float(boot_failed) if reps > 0 else None
top = pc.top_index(s)
values["top_item"] = items[top]
if len(boot_scores) >= 2:
blo, bhi, topf, rlo, rhi = pc.boot_summary(boot_scores, conf)
for i, it in enumerate(items):
values.update({f"boot_low[{it}]": float(blo[i]), f"boot_high[{it}]": float(bhi[i]), f"top_freq[{it}]": float(topf[i]),
f"rank_low[{it}]": float(rlo[i]), f"rank_high[{it}]": float(rhi[i])})
values["top_item_freq"] = float(topf[top])
else:
blo = bhi = topf = rlo = rhi = None
values["top_item_freq"] = None
# %% Held-out judgments (rows marked as test)
te = np.flatnonzero(use & held & (ia >= 0) & (ib >= 0))
values["n_test"] = float((use & held).sum())
if len(te):
alpha = fit["alpha"] or 0.0
dt = s[ia[te]] - s[ib[te]] + alpha
if model == "crowd_bt":
jt = df[col_j].astype(str).to_numpy()[te]
n_jt = np.bincount(jcode, weights=t1 + t2, minlength=len(judge_names))
eta_mean = float(np.sum(fit["eta"] * n_jt) / np.sum(n_jt))
et = np.array([fit["eta"][judge_names.index(x)] if x in judge_names else eta_mean for x in jt])
q1, q2, q3 = pc.crowd_probs(dt, et)
b1 = b2 = np.full(len(te), 0.5)
b3 = np.zeros(len(te))
else:
q1, q2, q3 = pc.pair_probs(model, dt, fit["nu"])
d0 = np.full(len(te), null["alpha"] or 0.0)
b1, b2, b3 = pc.pair_probs(model, d0, null["nu"])
e1, e2, e3 = y1[te], y2[te], y3[te]
nt = float((e1 + e2 + e3).sum())
lg = lambda q: np.log(np.where(q > 0, q, 1.0)) # noqa: E731 (zero-probability cells carry no weight)
values["test_logloss"] = float(-np.sum(e1 * lg(q1) + e2 * lg(q2) + e3 * lg(q3)) / nt)
values["test_baseline"] = float(-np.sum(e1 * lg(b1) + e2 * lg(b2) + e3 * lg(b3)) / nt)
values["test_brier"] = float(np.sum(e1 * (1 - q1) ** 2 + e2 * q1**2) / nt) if model != "davidson" else None
values["test_scored"] = nt
else:
values.update({"test_logloss": None, "test_baseline": None, "test_brier": None, "test_scored": None})
# %% Assumptions
per_item = wins + losses + tied
thin = [f"{it} ({int(per_item[i])})" for i, it in enumerate(items) if per_item[i] < 10]
assumptions = []
if model == "crowd_bt":
assumptions.append({"key": "connectivity", "label": "Connected comparisons", "status": "pass" if pc.weakly_connected(adj) else "warn",
"detail": "Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite."
if pc.weakly_connected(adj) else "Some items are never compared, even indirectly, with others; their relative worth comes only from the shrinkage."})
else:
assumptions.append({"key": "connectivity", "label": "Connected comparisons", "status": "pass",
"detail": "Every item wins and loses its way to every other item, so the estimates are finite and unique."})
if gof is not None:
g2, gdf, small = gof
if gdf <= 0:
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "info", "detail": "Too few distinct pairs for a goodness-of-fit test."})
elif small > 0.2:
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "info",
"detail": f"G² = {g2:.2f} on {gdf} df, but {small:.0%} of the expected counts are below 5, so the χ² approximation is rough."})
else:
gp = pc.lr_p(g2, gdf)
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "warn" if gp < 0.05 else "pass",
"detail": f"G² = {g2:.2f} on {gdf} df, p = {gp:.3g}" + (": some pairs win more or less often than their worths say (intransitive or context-dependent preferences)." if gp < 0.05 else ".")})
assumptions.append({"key": "sample_size", "label": "Judgments per item", "status": "warn" if thin else "pass",
"detail": "Fewer than 10 judgments: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item has at least 10 judgments (fewest {int(per_item.min())})."})
if model == "davidson":
assumptions.append({"key": "ties", "label": "Ties", "status": "info",
"detail": f"Ties are modeled as their own outcome: ν = {values['nu']:.3f} ({values['tie_rate']:.1%} of the fitted judgments are ties); ties are likelier between items of similar worth."})
elif n_ties:
assumptions.append({"key": "ties", "label": "Ties", "status": "warn" if ties == "drop" else "info",
"detail": f"{n_ties} tie(s) " + ("left out; the Davidson model would use them." if ties == "drop" else "counted as half a win for each item.")})
else:
assumptions.append({"key": "ties", "label": "Ties", "status": "pass", "detail": "No ties in the fitted judgments."})
if use_order:
assumptions.append({"key": "position", "label": "Position effect", "status": "info",
"detail": f"Fitted first-position effect {values['order_effect']:.3f}" + ("" if values["order_effect_se"] is None else f" (SE {values['order_effect_se']:.3f}, p = {values['order_effect_p']:.3g})") + "; worths are net of it."})
elif alt_note is not None:
assumptions.append({"key": "position", "label": "Position effect", "status": "info", "detail": alt_note})
elif alt is not None:
pp = values["position_p"]
assumptions.append({"key": "position", "label": "Position effect", "status": "warn" if pp < 0.05 else "pass",
"detail": f"Likelihood-ratio test for a first-position advantage: χ²(1) = {values['position_lr']:.2f}, p = {pp:.3g}" + (" — turn on Position effect." if pp < 0.05 else ".")})
if model == "crowd_bt":
lowest = int(np.argmin(fit["eta"]))
assumptions.append({"key": "reliability", "label": "Judge reliability", "status": "warn" if reversed_judges else "pass",
"detail": (f"Below 0.5 (agreeing with the consensus less than chance): " + ", ".join(f"{nm} ({fit['eta'][judge_names.index(nm)]:.2f})" for nm in reversed_judges) + ".")
if reversed_judges else f"Every judge agrees with the consensus more often than not (lowest {judge_names[lowest]}: {fit['eta'][lowest]:.2f})."})
unit_label = f"whole values of {unit_col}" if unit_col else "single judgments"
assumptions.append({"key": "independence", "label": "Independent judgments", "status": "info",
"detail": f"Not checked from data: judgments are treated as independent. The bootstrap resamples {unit_label}."})
# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols = [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "item", "label": "Item", "type": "string"},
{"key": "score", "label": "Worth (log)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
{"key": "worth", "label": "Share", "type": "number"}, {"key": "wins", "label": "Wins", "type": "number"},
{"key": "losses", "label": "Losses", "type": "number"}, {"key": "ties", "label": "Ties", "type": "number"}]
if blo is not None:
cols += [{"key": "top_freq", "label": "First in resamples", "type": "number"},
{"key": "rank_low", "label": "Rank low", "type": "number"}, {"key": "rank_high", "label": "Rank high", "type": "number"}]
rows = []
for i in order:
r = {"rank": float(ranks[i]), "item": items[i], "score": float(s[i]), "se": values[f"se[{items[i]}]"], "ci_low": values[f"ci_low[{items[i]}]"],
"ci_high": values[f"ci_high[{items[i]}]"], "worth": float(worth[i]), "wins": float(wins[i]), "losses": float(losses[i]), "ties": float(tied[i])}
if blo is not None:
r.update({"top_freq": float(topf[i]), "rank_low": float(rlo[i]), "rank_high": float(rhi[i])})
rows.append(r)
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being preferred among all {k})", "columns": cols, "rows": rows}]
fit_rows = [{"stat": "Judgments fitted", "value": n}, {"stat": "Log-likelihood", "value": loglik}, {"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
if values["lr"] is not None:
fit_rows += [{"stat": "LR χ² vs equal worths", "value": values["lr"]}, {"stat": "LR p", "value": values["lr_p"]}]
if values["gof"] is not None:
fit_rows += [{"stat": "Goodness of fit G²", "value": values["gof"]}, {"stat": "G² df", "value": values["gof_df"]}, {"stat": "G² p", "value": values["gof_p"]}]
if values["test_logloss"] is not None:
fit_rows += [{"stat": "Held-out log loss", "value": values["test_logloss"]}, {"stat": "Held-out log loss, equal worths", "value": values["test_baseline"]}]
if values["test_brier"] is not None:
fit_rows.append({"stat": "Held-out Brier score", "value": values["test_brier"]})
tables.append({"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows})
if col_j is not None:
jcols = [{"key": "judge", "label": "Judge", "type": "string"}, {"key": "n", "label": "Judgments", "type": "number"}]
jcols.append({"key": "eta", "label": "Reliability η", "type": "number"} if model == "crowd_bt" else {"key": "agreement", "label": "Agrees with worth order", "type": "number"})
jrows = [{"judge": nm, "n": values[f"n_judge[{nm}]"], **({"eta": values[f"eta[{nm}]"]} if model == "crowd_bt" else {"agreement": values[f"agreement[{nm}]"]})} for nm in judge_names]
tables.append({"key": "judges", "title": "Judges", "columns": jcols, "rows": jrows})
low = [values[f"ci_low[{items[i]}]"] if values[f"ci_low[{items[i]}]"] is not None else (float(blo[i]) if blo is not None else float(s[i])) for i in order]
high = [values[f"ci_high[{items[i]}]"] if values[f"ci_high[{items[i]}]"] is not None else (float(bhi[i]) if bhi is not None else float(s[i])) for i in order]
charts = [cs.chart("worths", "forest", f"Worths (log scale) with {pct} intervals", {
"label": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"estimate": cs.col("Worth (log)", [float(s[i]) for i in order], "numeric"),
"low": cs.col("Lower", low, "numeric"),
"high": cs.col("Upper", high, "numeric"),
}, controls={"reference": 0})]
if k <= 30:
shown = [items[i] for i in order]
pr, pc_, pv, pl = [], [], [], []
for i in order:
for j in order:
pr.append(items[i])
pc_.append(items[j])
if i == j:
pv.append(0.5)
pl.append("")
else:
pij = float(pc.pair_probs("bt" if model == "crowd_bt" else model, np.array([s[i] - s[j]]), fit["nu"])[0][0])
pv.append(pij)
pl.append(f"{pij:.2f}")
charts.append(cs.chart("pairs", "matrix-heatmap", "Chance that the row item is preferred to the column item", {
"row": cs.col("Item", pr, "categorical", levels=shown),
"col": cs.col("Against", pc_, "categorical", levels=shown),
"value": cs.col("Probability", pv, "numeric"),
"label": cs.col("Text", pl, "categorical"),
}, controls={"scale": "sequential"}))
if topf is not None:
charts.append(cs.chart("top", "bar-ranked", "How often each item comes first in the bootstrap", {
"category": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"value": cs.col("Share of resamples", [float(topf[i]) for i in order], "numeric"),
}, controls={"agg": "sum", "top": min(30, k)}))
notes = [f"{label}: worths are log-worths centered to sum to 0 (only differences mean anything); the last item ({items[-1]}) was the reference in the fit. "
f"Outcome read as {'the winner’s name' if coding == 'winner' else 'whether the first item won'}. Newton iterations: {fit['iterations']}."]
if model == "thurstone":
notes.append("Thurstone worths are on a probit scale (P = Φ(difference)); they're about 0.6 times Bradley–Terry's and can't be compared with them directly.")
if model == "crowd_bt":
notes.append(f"Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with {prior:g} win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.")
if reps > 0:
notes.append(boot_note or f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); {boot_failed} skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.")
summary = f"{label} for {k} items from {int(n)} judgments: {items[top]} has the highest worth" + (f" and comes first in {values['top_item_freq']:.0%} of the bootstrap resamples." if values["top_item_freq"] is not None else ".")
apa = label + (f": LR χ²({k - 1}) = {cs.fmt_num(values['lr'])}, {cs.fmt_p(values['lr_p'])}" if values["lr"] is not None else "")
cs.publish({
"method": "measurement.bradley_terry",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": summary,
"apa": apa,
"statistics": [{"key": "lr", "label": "LR χ²", "value": values["lr"]}, {"key": "lr_p", "label": "p", "value": values["lr_p"], "format": "p"},
{"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "top_item_freq", "label": f"{items[top]} first", "value": values["top_item_freq"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
On these judgments atlas has the highest worth, and it comes first in 65% of the bootstrap resamples. Report that second number: it says how sure the data make the order, not only what the order is.
When worths don't exist
PredictPredict first
One system wins every one of its comparisons. What worth does maximum likelihood give it?
Reveal
No finite worth. The likelihood keeps rising as its worth grows, so the estimate runs off to infinity. The card checks that the win graphWin graphItems as nodes, an arrow from each winner to each loser; worths are finite only if every item can reach every other along arrows. is strongly connected (every item can reach every other along "beat" arrows) and stops with a clear message when it isn't. Add comparisons, or use Crowd-BT, which shrinks worths toward the middle.
Ties and the probit version
In the appThe same judgments can be read in several ways. Pick by what your data contain, not by which ranking you like.
- Thurstone Case V swaps the logistic curve for a normal one (probit). The order rarely changes, but the worths are on a smaller scale, so never compare the numbers across models.
- Davidson makes a tie an outcome of its own, with a tie parameter , instead of dropping ties or splitting them. Here 17% of the judgments are ties and = 0.41; ties come out likelier between items of similar worth. The test rows, kept out of the fit, give a held-out log loss of 1.018 against 1.037 for equal worths.
Position and judges
In the app- Position effect adds one parameter for an advantage of whatever is shown first. LLM judges often have one. With prompts as clusters for the bootstrap, the fitted effect is 0.10 (p = p = .249). When the effect is off, the card still tests for it and tells you to turn it on.
- Crowd-BT gives each judge a reliabilityCrowd-BTBradley–Terry with a reliability per judge: the chance the judge agrees with the consensus order (0.5 random, below 0.5 reversed). : the chance their verdict follows the consensus order. One judge here has = 0.34: below 0.5, so they lean toward picking the weaker item. The card flags 2 judge(s) like that.
Crowd-BT model (judge reliability)
- LR χ²
- —
- p
- —
- AIC
- 760.91
- atlas first
- 60.0%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 1.506 | 1.648 | atlas | 1.081 |
| 1.443 | 1.550 | birch | 0.6026 |
| 0.3180 | 0.7023 | cedar | −0.3255 |
| −0.2989 | −0.0044 | delta | −0.4394 |
| −0.6088 | −0.2289 | ember | −0.9252 |
| −2.359 | −1.205 | fjord | −2.669 |
View data
| Against | Text | Item | Probability |
|---|---|---|---|
| atlas | atlas | 0.5000 | |
| birch | 0.52 | atlas | 0.5155 |
| cedar | 0.77 | atlas | 0.7663 |
| delta | 0.86 | atlas | 0.8587 |
| ember | 0.89 | atlas | 0.8923 |
| fjord | 0.98 | atlas | 0.9795 |
| atlas | 0.48 | birch | 0.4845 |
| birch | birch | 0.5000 | |
| cedar | 0.76 | birch | 0.7550 |
| delta | 0.85 | birch | 0.8510 |
| ember | 0.89 | birch | 0.8862 |
| fjord | 0.98 | birch | 0.9782 |
| atlas | 0.23 | cedar | 0.2337 |
| birch | 0.24 | cedar | 0.2450 |
| cedar | cedar | 0.5000 | |
| delta | 0.65 | cedar | 0.6495 |
| ember | 0.72 | cedar | 0.7164 |
| fjord | 0.94 | cedar | 0.9357 |
| atlas | 0.14 | delta | 0.1413 |
| birch | 0.15 | delta | 0.1490 |
| cedar | 0.35 | delta | 0.3505 |
| delta | delta | 0.5000 | |
| ember | 0.58 | delta | 0.5769 |
| fjord | 0.89 | delta | 0.8870 |
| atlas | 0.11 | ember | 0.1077 |
| birch | 0.11 | ember | 0.1138 |
| cedar | 0.28 | ember | 0.2836 |
| delta | 0.42 | ember | 0.4231 |
| ember | ember | 0.5000 | |
| fjord | 0.85 | ember | 0.8520 |
| atlas | 0.02 | fjord | 0.0205 |
| birch | 0.02 | fjord | 0.0218 |
| cedar | 0.06 | fjord | 0.0643 |
| delta | 0.11 | fjord | 0.1130 |
| ember | 0.15 | fjord | 0.1480 |
| fjord | fjord | 0.5000 |
View data
| Item | Share of resamples |
|---|---|
| atlas | 0.6000 |
| birch | 0.4000 |
| cedar | 0 |
| delta | 0 |
| ember | 0 |
| fjord | 0 |
Assumptions
- Connected comparisons — Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite.
- Judgments per item — Every item has at least 10 judgments (fewest 169).
- Ties — 118 tie(s) left out; the Davidson model would use them.
- Judge reliability — Below 0.5 (agreeing with the consensus less than chance): j8 (0.34), j7 (0.47).
- Independent judgments — Not checked from data: judgments are treated as independent. The bootstrap resamples whole values of judge.
Worths (log scale, centered; share = chance of being preferred among all 6)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Wins | Losses | Ties | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | atlas | 1.506 | — | — | — | 0.3920 | 135 | 83 | 0 | 0.6000 | 1 | 2 |
| 2 | birch | 1.443 | — | — | — | 0.3684 | 118 | 79 | 0 | 0.4000 | 1 | 2 |
| 3 | cedar | 0.3180 | — | — | — | 0.1196 | 92 | 95 | 0 | 0 | 3 | 4.525 |
| 4 | delta | −0.2989 | — | — | — | 0.0645 | 93 | 103 | 0 | 0 | 3 | 5 |
| 5 | ember | −0.6088 | — | — | — | 0.0473 | 74 | 95 | 0 | 0 | 4 | 5 |
| 6 | fjord | −2.359 | — | — | — | 0.0082 | 72 | 129 | 0 | 0 | 6 | 6 |
Model fit
| Value | |
|---|---|
| Judgments fitted | 584 |
| Log-likelihood | −366.45 |
| AIC | 760.91 |
| BIC | 822.09 |
Judges
| Judge | Judgments | Reliability η |
|---|---|---|
| j8 | 76 | 0.3388 |
| j2 | 59 | 0.6602 |
| j7 | 77 | 0.4737 |
| j5 | 66 | 0.9109 |
| j3 | 88 | 0.7753 |
| j6 | 69 | 0.6116 |
| j1 | 72 | 0.7861 |
| j4 | 77 | 0.7817 |
- Left out (neither item preferred): inconsistent (12), abstain (6).
- 118 tie(s) were left out; the Davidson model uses them.
- Crowd-BT model (judge reliability): worths are log-worths centered to sum to 0 (only differences mean anything); the last item (fjord) was the reference in the fit. Outcome read as whether the first item won. Newton iterations: 279.
- Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with 0.5 win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.
- Bootstrap: 20 of 20 resamples of whole values of judge refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.bradley_terry 1.0.0 · spec d86afceb61555d4d
# Dataset: hme_pairs (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_pairs.parquet", col_select = c("first", "second", "verdict", "judge")))
n_input <- nrow(df)
df[["first"]] <- factor(df[["first"]], levels = c("atlas", "birch", "cedar", "delta", "ember", "fjord")) # stored level order
df[["second"]] <- factor(df[["second"]], levels = c("atlas", "birch", "cedar", "delta", "ember", "fjord")) # stored level order
df[["verdict"]] <- factor(df[["verdict"]], levels = sort(unique(df[["verdict"]]), method = "radix"))
df[["judge"]] <- factor(df[["judge"]], levels = c("j1", "j2", "j3", "j4", "j5", "j6", "j7", "j8")) # stored level order
df <- df[stats::complete.cases(df[c("first", "second", "verdict", "judge")]), , 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("first", "second", "verdict", "judge")) # infinite values stop the run (registry/errors.yaml)
# %% Judgments
col_a <- "first"
col_b <- "second"
col_y <- "verdict"
model <- "crowd_bt"
ties <- "drop"
use_order <- FALSE
prior <- 0.5
reps <- 20
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
label <- cs_pc_labels()[[model]]
kinds <- c(
"first" = "categorical",
"second" = "categorical",
"verdict" = "categorical",
"judge" = "categorical"
)
first <- as.character(df[[col_a]])
second <- as.character(df[[col_b]])
y_raw <- if (kinds[[col_y]] %in% c("categorical", "boolean")) as.character(df[[col_y]]) else df[[col_y]]
dec <- cs_pc_decode_outcomes(kinds[[col_y]], y_raw, first, second, "auto")
codes <- dec$codes
coding <- dec$coding
if (any(codes == -2)) cs_error("CS_E_INVALID_VALUES", column = col_y, requirement = "1 (first item preferred), 0 (second) or 0.5 (tie)", count = sum(codes == -2))
count <- rep(1, nrow(df))
held <- rep(FALSE, nrow(df))
self_pair <- first == second
states <- list()
for (i in which(codes == -1 & !self_pair)) {
key <- dec$other[i]
states[[key]] <- (if (is.null(states[[key]])) 0 else states[[key]]) + count[i]
}
if (any(self_pair)) warnings <- c(warnings, list(sprintf("%d judgment(s) comparing an item with itself were left out.", as.integer(sum(count[self_pair])))))
if (length(states)) {
warnings <- c(warnings, list(paste0("Left out (neither item preferred): ",
paste(sprintf("%s (%d)", names(states), as.integer(unlist(states))), collapse = ", "), ".")))
}
n_left_out <- sum(unlist(states)) + sum(count[self_pair])
oc <- cs_pc_outcome_counts(codes, count, model, ties)
y1 <- oc$y1; y2 <- oc$y2; y3 <- oc$y3
use <- oc$keep & !self_pair
train <- use & !held
items_all <- unique(c(levels(df[[col_a]]), levels(df[[col_b]])))
seen <- unique(c(first[train], second[train]))
items <- items_all[items_all %in% seen]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_a, min = 2, k = k)
ia <- match(first, items)
ib <- match(second, items)
ia[is.na(ia)] <- 0L
ib[is.na(ib)] <- 0L
tr <- which(train)
a <- ia[tr]; b <- ib[tr]
t1 <- y1[tr]; t2 <- y2[tr]; t3 <- y3[tr]; tc <- count[tr]
n_ties <- sum(count[codes == 2 & !self_pair & !held])
if (ties == "drop" && model != "davidson" && n_ties > 0) warnings <- c(warnings, list(sprintf("%d tie(s) were left out; the Davidson model uses them.", as.integer(n_ties))))
if (model == "davidson" && sum(t3) == 0) cs_error("CS_E_UNDEFINED", what = "The Davidson model", reason = "there are no ties; use Bradley–Terry")
col_j <- "judge"
jv <- as.character(df[[col_j]])[tr]
judge_names <- unique(jv)
jcode <- match(jv, judge_names)
if (model == "crowd_bt" && is.null(col_j)) cs_error("CS_E_UNDEFINED", what = "Crowd-BT", reason = "it needs a Judge column")
if (model == "crowd_bt" && length(judge_names) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_j, min = 2, k = length(judge_names))
unit_col <- "judge"
if (!is.null(unit_col)) {
uv <- as.character(df[[unit_col]])[tr]
unit <- match(uv, unique(uv))
} else {
unit <- NULL
}
n <- sum(t1 + t2 + t3)
adj <- cs_pc_beat_graph(a, b, t1, t2, t3, k)
connected <- cs_pc_strongly_connected(adj)
if (model != "crowd_bt" && !connected) {
cs_error("CS_E_UNDEFINED", what = paste("The", label), reason = "some items never lose (or never win) against the rest, so their worths run off to infinity; add comparisons, or use Crowd-BT, which shrinks the worths toward the middle")
}
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
cell <- cs_pc_cells(a, b, t1, t2, t3, k, if (model == "crowd_bt") jcode else NULL)
fits <- tryCatch(list(
fit = cs_pc_fit_model(model, cell, k, use_order, length(judge_names), prior),
null = if (model == "crowd_bt") NULL else cs_pc_fit_pairs(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, k, use_order, null = TRUE)
), error = function(e) {
if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
cs_error("CS_E_NO_CONVERGENCE", what = paste("The", label))
})
fit <- fits$fit
null <- fits$null
alt <- NULL
alt_note <- NULL
if (model != "crowd_bt" && !use_order) { # the position test refits with a first-position term
alt <- tryCatch(cs_pc_fit_pairs(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, k, TRUE), error = function(e) NULL)
if (is.null(alt)) alt_note <- "A position effect can't be told apart from the worths in this design (for example, one item is always shown first)."
}
s <- fit$scores
z <- cs_pc_z(conf)
se <- if (!is.null(fit$cov)) sqrt(diag(fit$cov)) else rep(NA_real_, k)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
npar <- if (model == "crowd_bt") fit$npar else (k - 1) + as.integer(use_order) + as.integer(model == "davidson")
loglik <- fit$loglik
nz <- function(x) if (is.null(x) || length(x) == 0 || is.na(x)) NULL else x
values <- list(n = n, n_rows = length(tr), items = k, n_ties = n_ties, n_left_out = n_left_out, model_label = label,
loglik = loglik, npar = npar, aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n), iterations = fit$iterations)
if (!is.null(null)) {
lr <- 2 * (loglik - null$loglik)
values$loglik_null <- null$loglik; values$lr <- lr; values$lr_df <- k - 1; values$lr_p <- cs_pc_lr_p(lr, k - 1)
} else {
values["loglik_null"] <- list(NULL); values["lr"] <- list(NULL); values["lr_df"] <- list(NULL); values["lr_p"] <- list(NULL)
}
if (use_order) {
zo <- if (!is.null(fit$alpha_se)) fit$alpha / fit$alpha_se else NULL
values$order_effect <- fit$alpha
values["order_effect_se"] <- list(fit$alpha_se)
values["order_effect_p"] <- list(if (is.null(zo)) NULL else 2 * stats::pnorm(abs(zo), lower.tail = FALSE))
} else {
values["order_effect"] <- list(NULL); values["order_effect_se"] <- list(NULL); values["order_effect_p"] <- list(NULL)
}
if (!is.null(alt)) {
plr <- 2 * (alt$loglik - loglik)
values$position_lr <- plr; values$position_p <- cs_pc_lr_p(plr, 1)
} else {
values["position_lr"] <- list(NULL); values["position_p"] <- list(NULL)
}
if (model == "davidson") {
nu <- fit$nu; lse <- fit$lognu_se
values$nu <- nu; values$nu_low <- exp(log(nu) - z * lse); values$nu_high <- exp(log(nu) + z * lse)
values$tie_rate <- sum(t3) / n
} else {
for (key in c("nu", "nu_low", "nu_high", "tie_rate")) values[key] <- list(NULL)
}
gof <- NULL
if (model != "crowd_bt") {
gof <- cs_pc_gof(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, s, fit$nu, use_order, npar)
if (gof$df > 0) {
values$gof <- gof$g2; values$gof_df <- gof$df; values$gof_p <- cs_pc_lr_p(gof$g2, gof$df)
} else {
values["gof"] <- list(NULL); values["gof_df"] <- list(NULL); values["gof_p"] <- list(NULL)
}
} else {
values["gof"] <- list(NULL); values["gof_df"] <- list(NULL); values["gof_p"] <- list(NULL)
}
st <- cs_pc_item_stats(a, b, codes[tr], tc, k)
wins <- st$wins; losses <- st$losses; tied <- st$ties
ci_low <- s - z * se
ci_high <- s + z * se
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("score[%s]", it)]] <- s[i]
values[sprintf("se[%s]", it)] <- list(nz(se[i]))
values[sprintf("ci_low[%s]", it)] <- list(nz(ci_low[i]))
values[sprintf("ci_high[%s]", it)] <- list(nz(ci_high[i]))
values[[sprintf("worth[%s]", it)]] <- worth[i]
values[[sprintf("rank[%s]", it)]] <- ranks[i]
values[[sprintf("wins[%s]", it)]] <- wins[i]
values[[sprintf("losses[%s]", it)]] <- losses[i]
values[[sprintf("ties[%s]", it)]] <- tied[i]
}
# %% Judges
reversed_judges <- character(0)
if (model == "crowd_bt") {
eta <- fit$eta
n_j <- vapply(seq_along(judge_names), function(g) sum((t1 + t2)[jcode == g]), numeric(1))
for (g in seq_along(judge_names)) {
values[[sprintf("eta[%s]", judge_names[g])]] <- eta[g]
values[[sprintf("n_judge[%s]", judge_names[g])]] <- n_j[g]
}
reversed_judges <- judge_names[eta < 0.5]
} else if (!is.null(col_j)) {
ja <- cs_pc_judge_agreement(a, b, jcode, codes[tr], tc, s, length(judge_names))
for (g in seq_along(judge_names)) {
values[sprintf("agreement[%s]", judge_names[g])] <- list(nz(ja$agreement[g]))
values[[sprintf("n_judge[%s]", judge_names[g])]] <- ja$n[g]
}
}
values["judges"] <- list(if (!is.null(col_j)) length(judge_names) else NULL)
values["reversed_judges"] <- list(if (model == "crowd_bt") length(reversed_judges) else NULL)
# %% Bootstrap of the ranking (shared Wichmann–Hill stream; judgments, or whole clusters/judges)
boot_note <- NULL
boot_scores <- matrix(0, 0, k)
boot_failed <- 0
if (reps > 0) {
draws <- if (is.null(unit)) sum(tc) else max(unit)
if (draws * reps > 5e7) {
boot_note <- "The bootstrap was skipped: resampling this many judgments would take too long; set a Cluster column or fewer resamples."
} else {
bs <- cs_pc_bootstrap(model, a, b, jcode, t1, t2, t3, tc, unit, k, length(judge_names), use_order, prior, reps, seed)
boot_scores <- bs$scores
boot_failed <- bs$failed
}
}
values["boot_ok"] <- list(if (reps > 0) nrow(boot_scores) else NULL)
values["boot_failed"] <- list(if (reps > 0) boot_failed else NULL)
top <- cs_pc_top_index(s)
values$top_item <- items[top]
bsum <- NULL
if (nrow(boot_scores) >= 2) {
bsum <- cs_pc_boot_summary(boot_scores, conf)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("boot_low[%s]", it)]] <- bsum$low[i]
values[[sprintf("boot_high[%s]", it)]] <- bsum$high[i]
values[[sprintf("top_freq[%s]", it)]] <- bsum$top[i]
values[[sprintf("rank_low[%s]", it)]] <- bsum$rank_low[i]
values[[sprintf("rank_high[%s]", it)]] <- bsum$rank_high[i]
}
values$top_item_freq <- bsum$top[top]
} else {
values["top_item_freq"] <- list(NULL)
}
# %% Held-out judgments (rows marked as test)
te <- which(use & held & ia > 0 & ib > 0)
values$n_test <- sum(use & held)
if (length(te)) {
alpha <- if (is.null(fit$alpha)) 0 else fit$alpha
dt <- s[ia[te]] - s[ib[te]] + alpha
if (model == "crowd_bt") {
jt <- as.character(df[[col_j]])[te]
n_jt <- vapply(seq_along(judge_names), function(g) sum((t1 + t2)[jcode == g]), numeric(1))
eta_mean <- sum(fit$eta * n_jt) / sum(n_jt)
et <- ifelse(jt %in% judge_names, fit$eta[match(jt, judge_names)], eta_mean)
q <- cs_pc_crowd_probs(dt, et)
bq <- list(rep(0.5, length(te)), rep(0.5, length(te)), rep(0, length(te)))
} else {
q <- cs_pc_pair_probs(model, dt, fit$nu)
bq <- cs_pc_pair_probs(model, rep(if (is.null(null$alpha)) 0 else null$alpha, length(te)), null$nu)
}
e1 <- y1[te]; e2 <- y2[te]; e3 <- y3[te]
nt <- sum(e1 + e2 + e3)
lg <- function(x) log(ifelse(x > 0, x, 1)) # zero-probability cells carry no weight
values$test_logloss <- -sum(e1 * lg(q[[1]]) + e2 * lg(q[[2]]) + e3 * lg(q[[3]])) / nt
values$test_baseline <- -sum(e1 * lg(bq[[1]]) + e2 * lg(bq[[2]]) + e3 * lg(bq[[3]])) / nt
values["test_brier"] <- list(if (model != "davidson") sum(e1 * (1 - q[[1]])^2 + e2 * q[[1]]^2) / nt else NULL)
values$test_scored <- nt
} else {
for (key in c("test_logloss", "test_baseline", "test_brier", "test_scored")) values[key] <- list(NULL)
}
# %% Assumptions
per_item <- wins + losses + tied
thin <- sprintf("%s (%d)", items, as.integer(per_item))[per_item < 10]
fmt3 <- function(x) formatC(signif(x, 3), digits = 3, format = "fg", flag = "#")
pfmt <- function(x) sub("\\.$", "", formatC(x, digits = 3, format = "g"))
assumptions <- list()
if (model == "crowd_bt") {
wc <- cs_pc_weakly_connected(adj)
assumptions[[length(assumptions) + 1]] <- list(key = "connectivity", label = "Connected comparisons", status = if (wc) "pass" else "warn",
detail = if (wc) "Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite." else
"Some items are never compared, even indirectly, with others; their relative worth comes only from the shrinkage.")
} else {
assumptions[[length(assumptions) + 1]] <- list(key = "connectivity", label = "Connected comparisons", status = "pass",
detail = "Every item wins and loses its way to every other item, so the estimates are finite and unique.")
}
if (!is.null(gof)) {
if (gof$df <= 0) {
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = "info", detail = "Too few distinct pairs for a goodness-of-fit test.")
} else if (gof$small > 0.2) {
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = "info",
detail = sprintf("G² = %.2f on %d df, but %.0f%% of the expected counts are below 5, so the χ² approximation is rough.", gof$g2, as.integer(gof$df), 100 * gof$small))
} else {
gp <- cs_pc_lr_p(gof$g2, gof$df)
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = if (gp < 0.05) "warn" else "pass",
detail = paste0(sprintf("G² = %.2f on %d df, p = %s", gof$g2, as.integer(gof$df), pfmt(gp)),
if (gp < 0.05) ": some pairs win more or less often than their worths say (intransitive or context-dependent preferences)." else "."))
}
}
assumptions[[length(assumptions) + 1]] <- list(key = "sample_size", label = "Judgments per item", status = if (length(thin)) "warn" else "pass",
detail = if (length(thin)) paste0("Fewer than 10 judgments: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
sprintf("Every item has at least 10 judgments (fewest %d).", as.integer(min(per_item))))
if (model == "davidson") {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = "info",
detail = sprintf("Ties are modeled as their own outcome: ν = %.3f (%.1f%% of the fitted judgments are ties); ties are likelier between items of similar worth.", values$nu, 100 * values$tie_rate))
} else if (n_ties > 0) {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = if (ties == "drop") "warn" else "info",
detail = paste0(sprintf("%d tie(s) ", as.integer(n_ties)), if (ties == "drop") "left out; the Davidson model would use them." else "counted as half a win for each item."))
} else {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = "pass", detail = "No ties in the fitted judgments.")
}
if (use_order) {
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = "info",
detail = paste0(sprintf("Fitted first-position effect %.3f", values$order_effect),
if (is.null(values$order_effect_se)) "" else sprintf(" (SE %.3f, p = %s)", values$order_effect_se, pfmt(values$order_effect_p)),
"; worths are net of it."))
} else if (!is.null(alt_note)) {
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = "info", detail = alt_note)
} else if (!is.null(alt)) {
pp <- values$position_p
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = if (pp < 0.05) "warn" else "pass",
detail = paste0(sprintf("Likelihood-ratio test for a first-position advantage: χ²(1) = %.2f, p = %s", values$position_lr, pfmt(pp)),
if (pp < 0.05) " — turn on Position effect." else "."))
}
if (model == "crowd_bt") {
lowest <- which.min(fit$eta)
assumptions[[length(assumptions) + 1]] <- list(key = "reliability", label = "Judge reliability", status = if (length(reversed_judges)) "warn" else "pass",
detail = if (length(reversed_judges)) paste0("Below 0.5 (agreeing with the consensus less than chance): ",
paste(sprintf("%s (%.2f)", reversed_judges, fit$eta[match(reversed_judges, judge_names)]), collapse = ", "), ".") else
sprintf("Every judge agrees with the consensus more often than not (lowest %s: %.2f).", judge_names[lowest], fit$eta[lowest]))
}
unit_label <- if (!is.null(unit_col)) paste("whole values of", unit_col) else "single judgments"
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent judgments", status = "info",
detail = sprintf("Not checked from data: judgments are treated as independent. The bootstrap resamples %s.", unit_label))
# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols <- list(list(key = "rank", label = "Rank", type = "integer"), list(key = "item", label = "Item", type = "string"),
list(key = "score", label = "Worth (log)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "worth", label = "Share", type = "number"), list(key = "wins", label = "Wins", type = "number"),
list(key = "losses", label = "Losses", type = "number"), list(key = "ties", label = "Ties", type = "number"))
if (!is.null(bsum)) {
cols <- c(cols, list(list(key = "top_freq", label = "First in resamples", type = "number"),
list(key = "rank_low", label = "Rank low", type = "number"), list(key = "rank_high", label = "Rank high", type = "number")))
}
rows <- lapply(ord, function(i) {
r <- list(rank = ranks[i], item = items[i], score = s[i], se = nz(se[i]), ci_low = nz(ci_low[i]), ci_high = nz(ci_high[i]),
worth = worth[i], wins = wins[i], losses = losses[i], ties = tied[i])
if (!is.null(bsum)) { r$top_freq <- bsum$top[i]; r$rank_low <- bsum$rank_low[i]; r$rank_high <- bsum$rank_high[i] }
r
})
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being preferred among all %d)", k), columns = cols, rows = rows))
fit_rows <- list(list(stat = "Judgments fitted", value = n), list(stat = "Log-likelihood", value = loglik), list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
if (!is.null(values$lr)) fit_rows <- c(fit_rows, list(list(stat = "LR χ² vs equal worths", value = values$lr), list(stat = "LR p", value = values$lr_p)))
if (!is.null(values$gof)) fit_rows <- c(fit_rows, list(list(stat = "Goodness of fit G²", value = values$gof), list(stat = "G² df", value = values$gof_df), list(stat = "G² p", value = values$gof_p)))
if (!is.null(values$test_logloss)) {
fit_rows <- c(fit_rows, list(list(stat = "Held-out log loss", value = values$test_logloss), list(stat = "Held-out log loss, equal worths", value = values$test_baseline)))
if (!is.null(values$test_brier)) fit_rows <- c(fit_rows, list(list(stat = "Held-out Brier score", value = values$test_brier)))
}
tables[[2]] <- list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows)
if (!is.null(col_j)) {
jcols <- list(list(key = "judge", label = "Judge", type = "string"), list(key = "n", label = "Judgments", type = "number"),
if (model == "crowd_bt") list(key = "eta", label = "Reliability η", type = "number") else list(key = "agreement", label = "Agrees with worth order", type = "number"))
jrows <- lapply(judge_names, function(nm) {
r <- list(judge = nm, n = values[[sprintf("n_judge[%s]", nm)]])
if (model == "crowd_bt") r$eta <- values[[sprintf("eta[%s]", nm)]] else r["agreement"] <- list(values[[sprintf("agreement[%s]", nm)]])
r
})
tables[[3]] <- list(key = "judges", title = "Judges", columns = jcols, rows = jrows)
}
low <- ifelse(is.na(ci_low), if (!is.null(bsum)) bsum$low else s, ci_low)[ord]
high <- ifelse(is.na(ci_high), if (!is.null(bsum)) bsum$high else s, ci_high)[ord]
charts <- list(cs_chart("worths", "forest", sprintf("Worths (log scale) with %s intervals", pct), list(
label = cs_col("Item", items[ord], "categorical", levels = items[ord]),
estimate = cs_col("Worth (log)", s[ord], "numeric"),
low = cs_col("Lower", low, "numeric"),
high = cs_col("Upper", high, "numeric")
), controls = list(reference = 0)))
if (k <= 30) {
shown <- items[ord]
pr <- character(0); pcl <- character(0); pv <- numeric(0); pl <- character(0)
for (i in ord) for (j in ord) {
pr <- c(pr, items[i]); pcl <- c(pcl, items[j])
if (i == j) {
pv <- c(pv, 0.5); pl <- c(pl, "")
} else {
pij <- cs_pc_pair_probs(if (model == "crowd_bt") "bt" else model, s[i] - s[j], fit$nu)[[1]]
pv <- c(pv, pij); pl <- c(pl, sprintf("%.2f", pij))
}
}
charts[[length(charts) + 1]] <- cs_chart("pairs", "matrix-heatmap", "Chance that the row item is preferred to the column item", list(
row = cs_col("Item", pr, "categorical", levels = shown),
col = cs_col("Against", pcl, "categorical", levels = shown),
value = cs_col("Probability", pv, "numeric"),
label = cs_col("Text", pl, "categorical")
), controls = list(scale = "sequential"))
}
if (!is.null(bsum)) {
charts[[length(charts) + 1]] <- cs_chart("top", "bar-ranked", "How often each item comes first in the bootstrap", list(
category = cs_col("Item", items[ord], "categorical", levels = items[ord]),
value = cs_col("Share of resamples", bsum$top[ord], "numeric")
), controls = list(agg = "sum", top = min(30, k)))
}
notes <- list(sprintf("%s: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (%s) was the reference in the fit. Outcome read as %s. Newton iterations: %d.",
label, items[k], if (coding == "winner") "the winner’s name" else "whether the first item won", as.integer(fit$iterations)))
if (model == "thurstone") notes[[length(notes) + 1]] <- "Thurstone worths are on a probit scale (P = Φ(difference)); they're about 0.6 times Bradley–Terry's and can't be compared with them directly."
if (model == "crowd_bt") notes[[length(notes) + 1]] <- sprintf("Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with %s win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.", format(prior))
if (reps > 0) {
notes[[length(notes) + 1]] <- if (!is.null(boot_note)) boot_note else sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.",
nrow(boot_scores), as.integer(reps), unit_label, format(seed), as.integer(boot_failed))
}
summary <- paste0(sprintf("%s for %d items from %d judgments: %s has the highest worth", label, k, as.integer(n), items[top]),
if (!is.null(values$top_item_freq)) sprintf(" and comes first in %.0f%% of the bootstrap resamples.", 100 * values$top_item_freq) else ".")
apa <- paste0(label, if (!is.null(values$lr)) sprintf(": LR χ²(%d) = %s, %s", as.integer(k - 1), cs_fmt_num(values$lr), cs_fmt_p(values$lr_p)) else "")
cs_publish(list(
method = "measurement.bradley_terry",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats", "codesplashr"),
n = as.integer(n),
summary = summary,
apa = apa,
statistics = list(list(key = "lr", label = "LR χ²", value = values$lr), list(key = "lr_p", label = "p", value = values$lr_p, format = "p"),
list(key = "aic", label = "AIC", value = values$aic),
list(key = "top_item_freq", label = paste(items[top], "first"), value = values$top_item_freq, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Crowd-BT model (judge reliability)
- LR χ²
- —
- p
- —
- AIC
- 760.91
- atlas first
- 60.0%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Connected comparisons — Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite.
- Judgments per item — Every item has at least 10 judgments (fewest 169).
- Ties — 118 tie(s) left out; the Davidson model would use them.
- Judge reliability — Below 0.5 (agreeing with the consensus less than chance): j8 (0.34), j7 (0.47).
- Independent judgments — Not checked from data: judgments are treated as independent. The bootstrap resamples whole values of judge.
Worths (log scale, centered; share = chance of being preferred among all 6)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Wins | Losses | Ties | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | atlas | 1.506 | — | — | — | 0.3920 | 135 | 83 | 0 | 0.6000 | 1 | 2 |
| 2 | birch | 1.443 | — | — | — | 0.3684 | 118 | 79 | 0 | 0.4000 | 1 | 2 |
| 3 | cedar | 0.3180 | — | — | — | 0.1196 | 92 | 95 | 0 | 0 | 3 | 4.525 |
| 4 | delta | −0.2989 | — | — | — | 0.0645 | 93 | 103 | 0 | 0 | 3 | 5 |
| 5 | ember | −0.6088 | — | — | — | 0.0473 | 74 | 95 | 0 | 0 | 4 | 5 |
| 6 | fjord | −2.359 | — | — | — | 0.0082 | 72 | 129 | 0 | 0 | 6 | 6 |
Model fit
| Value | |
|---|---|
| Judgments fitted | 584 |
| Log-likelihood | −366.45 |
| AIC | 760.91 |
| BIC | 822.09 |
Judges
| Judge | Judgments | Reliability η |
|---|---|---|
| j8 | 76 | 0.3388 |
| j2 | 59 | 0.6602 |
| j7 | 77 | 0.4737 |
| j5 | 66 | 0.9109 |
| j3 | 88 | 0.7753 |
| j6 | 69 | 0.6116 |
| j1 | 72 | 0.7861 |
| j4 | 77 | 0.7817 |
- Left out (neither item preferred): inconsistent (12), abstain (6).
- 118 tie(s) were left out; the Davidson model uses them.
- Crowd-BT model (judge reliability): worths are log-worths centered to sum to 0 (only differences mean anything); the last item (fjord) was the reference in the fit. Outcome read as whether the first item won. Newton iterations: 279.
- Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with 0.5 win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.
- Bootstrap: 20 of 20 resamples of whole values of judge refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.bradley_terry 1.0.0 · spec d86afceb61555d4d
# Dataset: hme_pairs (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
import codesplash as cs
from codesplash.stats import paired_comparison as pc # twin of R's cs_pc_* (R/stats_paired_comparison.R)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/hme_pairs.parquet", columns=["first", "second", "verdict", "judge"])
n_input = len(df)
df["first"] = pd.Categorical(df["first"], categories=["atlas", "birch", "cedar", "delta", "ember", "fjord"]) # stored level order
df["second"] = pd.Categorical(df["second"], categories=["atlas", "birch", "cedar", "delta", "ember", "fjord"]) # stored level order
df["verdict"] = pd.Categorical(df["verdict"], categories=sorted(df["verdict"].dropna().unique()))
df["judge"] = pd.Categorical(df["judge"], categories=["j1", "j2", "j3", "j4", "j5", "j6", "j7", "j8"]) # stored level order
df = df.dropna(subset=["first", "second", "verdict", "judge"]) # listwise deletion over the analysis columns
df["first"] = df["first"].cat.remove_unused_categories()
df["second"] = df["second"].cat.remove_unused_categories()
df["verdict"] = df["verdict"].cat.remove_unused_categories()
df["judge"] = df["judge"].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, ["first", "second", "verdict", "judge"]) # infinite values stop the run (registry/errors.yaml)
# %% Judgments
col_a, col_b, col_y = "first", "second", "verdict"
model = "crowd_bt"
ties = "drop"
use_order = False
prior = 0.5
reps = 20
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
label = pc.MODEL_LABELS[model]
kinds = {"first":"categorical","judge":"categorical","second":"categorical","verdict":"categorical"}
first = df[col_a].astype(str).tolist()
second = df[col_b].astype(str).tolist()
y_raw = df[col_y].astype(str).tolist() if kinds[col_y] in ("categorical", "boolean") else df[col_y].tolist()
codes, coding, other = pc.decode_outcomes(kinds[col_y], y_raw, first, second, "auto")
if (codes == -2).any():
cs.cs_error("CS_E_INVALID_VALUES", column=col_y, requirement="1 (first item preferred), 0 (second) or 0.5 (tie)", count=int((codes == -2).sum()))
count = np.ones(len(df))
held = np.zeros(len(df), dtype=bool)
self_pair = np.array([x == z for x, z in zip(first, second)], dtype=bool)
states = {}
for i in np.flatnonzero((codes == -1) & ~self_pair):
states[other[i]] = states.get(other[i], 0) + int(count[i])
if self_pair.any():
warnings.append(f"{int(count[self_pair].sum())} judgment(s) comparing an item with itself were left out.")
if states:
warnings.append("Left out (neither item preferred): " + ", ".join(f"{k} ({v})" for k, v in states.items()) + ".")
n_left_out = int(sum(states.values()) + count[self_pair].sum())
y1, y2, y3, keep = pc.outcome_counts(codes, count, model, ties)
use = keep & ~self_pair
train = use & ~held
items_all = list(dict.fromkeys([str(x) for x in df[col_a].cat.categories] + [str(x) for x in df[col_b].cat.categories]))
seen = set(np.array(first, dtype=object)[train]) | set(np.array(second, dtype=object)[train])
items = [it for it in items_all if it in seen]
k = len(items)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_a, min=2, k=k)
pos = {it: i for i, it in enumerate(items)}
ia = np.array([pos.get(x, -1) for x in first])
ib = np.array([pos.get(x, -1) for x in second])
tr = np.flatnonzero(train)
a, b = ia[tr], ib[tr]
t1, t2, t3, tc = y1[tr], y2[tr], y3[tr], count[tr]
n_ties = int(count[(codes == 2) & ~self_pair & ~held].sum())
if ties == "drop" and model != "davidson" and n_ties:
warnings.append(f"{n_ties} tie(s) were left out; the Davidson model uses them.")
if model == "davidson" and t3.sum() == 0:
cs.cs_error("CS_E_UNDEFINED", what="The Davidson model", reason="there are no ties; use Bradley–Terry")
col_j = "judge"
judge_names = list(pd.unique(df[col_j].astype(str).to_numpy()[tr]))
jcode = np.array([judge_names.index(x) for x in df[col_j].astype(str).to_numpy()[tr]], dtype=np.int64)
if model == "crowd_bt" and col_j is None:
cs.cs_error("CS_E_UNDEFINED", what="Crowd-BT", reason="it needs a Judge column")
if model == "crowd_bt" and len(judge_names) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_j, min=2, k=len(judge_names))
unit_col = "judge"
if unit_col is not None:
uv = df[unit_col].astype(str).to_numpy()[tr]
unit_names = list(pd.unique(uv))
unit = np.array([unit_names.index(x) for x in uv], dtype=np.int64)
else:
unit = None
n = float((t1 + t2 + t3).sum())
adj = pc.beat_graph(a, b, t1, t2, t3, k)
connected = pc.strongly_connected(adj)
if model != "crowd_bt" and not connected:
cs.cs_error("CS_E_UNDEFINED", what=f"The {label}", reason="some items never lose (or never win) against the rest, so their worths run off to infinity; add comparisons, or use Crowd-BT, which shrinks the worths toward the middle")
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
cell = pc.pair_cells(a, b, t1, t2, t3, k, jcode if model == "crowd_bt" else None)
try:
fit = pc.fit_model(model, cell, k, use_order, len(judge_names), prior)
null = None if model == "crowd_bt" else pc.fit_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], k, use_order, null=True)
except RuntimeError:
cs.cs_error("CS_E_NO_CONVERGENCE", what=f"The {label}")
except np.linalg.LinAlgError:
cs.cs_error("CS_E_COLLINEAR")
alt, alt_note = None, None
if model != "crowd_bt" and not use_order: # the position test refits with a first-position term
try:
alt = pc.fit_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], k, True)
except (RuntimeError, np.linalg.LinAlgError):
alt_note = "A position effect can't be told apart from the worths in this design (for example, one item is always shown first)."
s = fit["scores"]
z = pc.z_value(conf)
se = np.sqrt(np.diag(fit["cov"])) if fit["cov"] is not None else np.full(k, np.nan)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
npar = fit["npar"] if model == "crowd_bt" else (k - 1) + (1 if use_order else 0) + (1 if model == "davidson" else 0)
loglik = fit["loglik"]
values = {"n": n, "n_rows": float(len(tr)), "items": float(k), "n_ties": float(n_ties), "n_left_out": float(n_left_out),
"model_label": label, "loglik": loglik, "npar": float(npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n),
"iterations": float(fit["iterations"])}
if null is not None:
lr = 2 * (loglik - null["loglik"])
values.update({"loglik_null": null["loglik"], "lr": lr, "lr_df": float(k - 1), "lr_p": pc.lr_p(lr, k - 1)})
else:
values.update({"loglik_null": None, "lr": None, "lr_df": None, "lr_p": None})
if use_order:
zo = fit["alpha"] / fit["alpha_se"] if fit["alpha_se"] else None
values.update({"order_effect": fit["alpha"], "order_effect_se": fit["alpha_se"],
"order_effect_p": None if zo is None else float(2 * pc.norm.sf(abs(zo)))})
else:
values.update({"order_effect": None, "order_effect_se": None, "order_effect_p": None})
if alt is not None:
plr = 2 * (alt["loglik"] - loglik)
values.update({"position_lr": plr, "position_p": pc.lr_p(plr, 1)})
else:
values.update({"position_lr": None, "position_p": None})
if model == "davidson":
nu, lse = fit["nu"], fit["lognu_se"]
values.update({"nu": nu, "nu_low": float(np.exp(np.log(nu) - z * lse)), "nu_high": float(np.exp(np.log(nu) + z * lse)),
"tie_rate": float(t3.sum() / n)})
else:
values.update({"nu": None, "nu_low": None, "nu_high": None, "tie_rate": None})
gof = None
if model != "crowd_bt":
g2, gdf, small = pc.gof_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], s, fit["nu"], use_order, npar)
gof = (g2, gdf, small)
values.update({"gof": g2 if gdf > 0 else None, "gof_df": float(gdf) if gdf > 0 else None, "gof_p": pc.lr_p(g2, gdf) if gdf > 0 else None})
else:
values.update({"gof": None, "gof_df": None, "gof_p": None})
wins, losses, tied = pc.item_stats(a, b, codes[tr], tc, k)
for i, it in enumerate(items):
values[f"score[{it}]"] = float(s[i])
values[f"se[{it}]"] = None if np.isnan(se[i]) else float(se[i])
values[f"ci_low[{it}]"] = None if np.isnan(se[i]) else float(s[i] - z * se[i])
values[f"ci_high[{it}]"] = None if np.isnan(se[i]) else float(s[i] + z * se[i])
values[f"worth[{it}]"] = float(worth[i])
values[f"rank[{it}]"] = float(ranks[i])
values[f"wins[{it}]"] = float(wins[i])
values[f"losses[{it}]"] = float(losses[i])
values[f"ties[{it}]"] = float(tied[i])
# %% Judges
reversed_judges = []
if model == "crowd_bt":
eta = fit["eta"]
n_j = np.bincount(jcode, weights=t1 + t2, minlength=len(judge_names))
for g, name in enumerate(judge_names):
values[f"eta[{name}]"] = float(eta[g])
values[f"n_judge[{name}]"] = float(n_j[g])
reversed_judges = [nm for g, nm in enumerate(judge_names) if eta[g] < 0.5]
elif col_j is not None:
agree, n_j = pc.judge_agreement(a, b, jcode, codes[tr], tc, s, len(judge_names))
for g, name in enumerate(judge_names):
values[f"agreement[{name}]"] = None if np.isnan(agree[g]) else float(agree[g])
values[f"n_judge[{name}]"] = float(n_j[g])
values["judges"] = float(len(judge_names)) if col_j is not None else None
values["reversed_judges"] = float(len(reversed_judges)) if model == "crowd_bt" else None
# %% Bootstrap of the ranking (shared Wichmann–Hill stream; judgments, or whole clusters/judges)
boot_note = None
if reps > 0:
draws = float(tc.sum()) if unit is None else float(unit.max() + 1)
if draws * reps > 5e7:
boot_note = "The bootstrap was skipped: resampling this many judgments would take too long; set a Cluster column or fewer resamples."
boot_scores, boot_failed = np.zeros((0, k)), 0
else:
boot_scores, boot_failed = pc.bootstrap_pairs(model, a, b, jcode, t1, t2, t3, tc, unit, k, len(judge_names), use_order, prior, reps, seed)
else:
boot_scores, boot_failed = np.zeros((0, k)), 0
values["boot_ok"] = float(len(boot_scores)) if reps > 0 else None
values["boot_failed"] = float(boot_failed) if reps > 0 else None
top = pc.top_index(s)
values["top_item"] = items[top]
if len(boot_scores) >= 2:
blo, bhi, topf, rlo, rhi = pc.boot_summary(boot_scores, conf)
for i, it in enumerate(items):
values.update({f"boot_low[{it}]": float(blo[i]), f"boot_high[{it}]": float(bhi[i]), f"top_freq[{it}]": float(topf[i]),
f"rank_low[{it}]": float(rlo[i]), f"rank_high[{it}]": float(rhi[i])})
values["top_item_freq"] = float(topf[top])
else:
blo = bhi = topf = rlo = rhi = None
values["top_item_freq"] = None
# %% Held-out judgments (rows marked as test)
te = np.flatnonzero(use & held & (ia >= 0) & (ib >= 0))
values["n_test"] = float((use & held).sum())
if len(te):
alpha = fit["alpha"] or 0.0
dt = s[ia[te]] - s[ib[te]] + alpha
if model == "crowd_bt":
jt = df[col_j].astype(str).to_numpy()[te]
n_jt = np.bincount(jcode, weights=t1 + t2, minlength=len(judge_names))
eta_mean = float(np.sum(fit["eta"] * n_jt) / np.sum(n_jt))
et = np.array([fit["eta"][judge_names.index(x)] if x in judge_names else eta_mean for x in jt])
q1, q2, q3 = pc.crowd_probs(dt, et)
b1 = b2 = np.full(len(te), 0.5)
b3 = np.zeros(len(te))
else:
q1, q2, q3 = pc.pair_probs(model, dt, fit["nu"])
d0 = np.full(len(te), null["alpha"] or 0.0)
b1, b2, b3 = pc.pair_probs(model, d0, null["nu"])
e1, e2, e3 = y1[te], y2[te], y3[te]
nt = float((e1 + e2 + e3).sum())
lg = lambda q: np.log(np.where(q > 0, q, 1.0)) # noqa: E731 (zero-probability cells carry no weight)
values["test_logloss"] = float(-np.sum(e1 * lg(q1) + e2 * lg(q2) + e3 * lg(q3)) / nt)
values["test_baseline"] = float(-np.sum(e1 * lg(b1) + e2 * lg(b2) + e3 * lg(b3)) / nt)
values["test_brier"] = float(np.sum(e1 * (1 - q1) ** 2 + e2 * q1**2) / nt) if model != "davidson" else None
values["test_scored"] = nt
else:
values.update({"test_logloss": None, "test_baseline": None, "test_brier": None, "test_scored": None})
# %% Assumptions
per_item = wins + losses + tied
thin = [f"{it} ({int(per_item[i])})" for i, it in enumerate(items) if per_item[i] < 10]
assumptions = []
if model == "crowd_bt":
assumptions.append({"key": "connectivity", "label": "Connected comparisons", "status": "pass" if pc.weakly_connected(adj) else "warn",
"detail": "Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite."
if pc.weakly_connected(adj) else "Some items are never compared, even indirectly, with others; their relative worth comes only from the shrinkage."})
else:
assumptions.append({"key": "connectivity", "label": "Connected comparisons", "status": "pass",
"detail": "Every item wins and loses its way to every other item, so the estimates are finite and unique."})
if gof is not None:
g2, gdf, small = gof
if gdf <= 0:
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "info", "detail": "Too few distinct pairs for a goodness-of-fit test."})
elif small > 0.2:
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "info",
"detail": f"G² = {g2:.2f} on {gdf} df, but {small:.0%} of the expected counts are below 5, so the χ² approximation is rough."})
else:
gp = pc.lr_p(g2, gdf)
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "warn" if gp < 0.05 else "pass",
"detail": f"G² = {g2:.2f} on {gdf} df, p = {gp:.3g}" + (": some pairs win more or less often than their worths say (intransitive or context-dependent preferences)." if gp < 0.05 else ".")})
assumptions.append({"key": "sample_size", "label": "Judgments per item", "status": "warn" if thin else "pass",
"detail": "Fewer than 10 judgments: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item has at least 10 judgments (fewest {int(per_item.min())})."})
if model == "davidson":
assumptions.append({"key": "ties", "label": "Ties", "status": "info",
"detail": f"Ties are modeled as their own outcome: ν = {values['nu']:.3f} ({values['tie_rate']:.1%} of the fitted judgments are ties); ties are likelier between items of similar worth."})
elif n_ties:
assumptions.append({"key": "ties", "label": "Ties", "status": "warn" if ties == "drop" else "info",
"detail": f"{n_ties} tie(s) " + ("left out; the Davidson model would use them." if ties == "drop" else "counted as half a win for each item.")})
else:
assumptions.append({"key": "ties", "label": "Ties", "status": "pass", "detail": "No ties in the fitted judgments."})
if use_order:
assumptions.append({"key": "position", "label": "Position effect", "status": "info",
"detail": f"Fitted first-position effect {values['order_effect']:.3f}" + ("" if values["order_effect_se"] is None else f" (SE {values['order_effect_se']:.3f}, p = {values['order_effect_p']:.3g})") + "; worths are net of it."})
elif alt_note is not None:
assumptions.append({"key": "position", "label": "Position effect", "status": "info", "detail": alt_note})
elif alt is not None:
pp = values["position_p"]
assumptions.append({"key": "position", "label": "Position effect", "status": "warn" if pp < 0.05 else "pass",
"detail": f"Likelihood-ratio test for a first-position advantage: χ²(1) = {values['position_lr']:.2f}, p = {pp:.3g}" + (" — turn on Position effect." if pp < 0.05 else ".")})
if model == "crowd_bt":
lowest = int(np.argmin(fit["eta"]))
assumptions.append({"key": "reliability", "label": "Judge reliability", "status": "warn" if reversed_judges else "pass",
"detail": (f"Below 0.5 (agreeing with the consensus less than chance): " + ", ".join(f"{nm} ({fit['eta'][judge_names.index(nm)]:.2f})" for nm in reversed_judges) + ".")
if reversed_judges else f"Every judge agrees with the consensus more often than not (lowest {judge_names[lowest]}: {fit['eta'][lowest]:.2f})."})
unit_label = f"whole values of {unit_col}" if unit_col else "single judgments"
assumptions.append({"key": "independence", "label": "Independent judgments", "status": "info",
"detail": f"Not checked from data: judgments are treated as independent. The bootstrap resamples {unit_label}."})
# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols = [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "item", "label": "Item", "type": "string"},
{"key": "score", "label": "Worth (log)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
{"key": "worth", "label": "Share", "type": "number"}, {"key": "wins", "label": "Wins", "type": "number"},
{"key": "losses", "label": "Losses", "type": "number"}, {"key": "ties", "label": "Ties", "type": "number"}]
if blo is not None:
cols += [{"key": "top_freq", "label": "First in resamples", "type": "number"},
{"key": "rank_low", "label": "Rank low", "type": "number"}, {"key": "rank_high", "label": "Rank high", "type": "number"}]
rows = []
for i in order:
r = {"rank": float(ranks[i]), "item": items[i], "score": float(s[i]), "se": values[f"se[{items[i]}]"], "ci_low": values[f"ci_low[{items[i]}]"],
"ci_high": values[f"ci_high[{items[i]}]"], "worth": float(worth[i]), "wins": float(wins[i]), "losses": float(losses[i]), "ties": float(tied[i])}
if blo is not None:
r.update({"top_freq": float(topf[i]), "rank_low": float(rlo[i]), "rank_high": float(rhi[i])})
rows.append(r)
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being preferred among all {k})", "columns": cols, "rows": rows}]
fit_rows = [{"stat": "Judgments fitted", "value": n}, {"stat": "Log-likelihood", "value": loglik}, {"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
if values["lr"] is not None:
fit_rows += [{"stat": "LR χ² vs equal worths", "value": values["lr"]}, {"stat": "LR p", "value": values["lr_p"]}]
if values["gof"] is not None:
fit_rows += [{"stat": "Goodness of fit G²", "value": values["gof"]}, {"stat": "G² df", "value": values["gof_df"]}, {"stat": "G² p", "value": values["gof_p"]}]
if values["test_logloss"] is not None:
fit_rows += [{"stat": "Held-out log loss", "value": values["test_logloss"]}, {"stat": "Held-out log loss, equal worths", "value": values["test_baseline"]}]
if values["test_brier"] is not None:
fit_rows.append({"stat": "Held-out Brier score", "value": values["test_brier"]})
tables.append({"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows})
if col_j is not None:
jcols = [{"key": "judge", "label": "Judge", "type": "string"}, {"key": "n", "label": "Judgments", "type": "number"}]
jcols.append({"key": "eta", "label": "Reliability η", "type": "number"} if model == "crowd_bt" else {"key": "agreement", "label": "Agrees with worth order", "type": "number"})
jrows = [{"judge": nm, "n": values[f"n_judge[{nm}]"], **({"eta": values[f"eta[{nm}]"]} if model == "crowd_bt" else {"agreement": values[f"agreement[{nm}]"]})} for nm in judge_names]
tables.append({"key": "judges", "title": "Judges", "columns": jcols, "rows": jrows})
low = [values[f"ci_low[{items[i]}]"] if values[f"ci_low[{items[i]}]"] is not None else (float(blo[i]) if blo is not None else float(s[i])) for i in order]
high = [values[f"ci_high[{items[i]}]"] if values[f"ci_high[{items[i]}]"] is not None else (float(bhi[i]) if bhi is not None else float(s[i])) for i in order]
charts = [cs.chart("worths", "forest", f"Worths (log scale) with {pct} intervals", {
"label": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"estimate": cs.col("Worth (log)", [float(s[i]) for i in order], "numeric"),
"low": cs.col("Lower", low, "numeric"),
"high": cs.col("Upper", high, "numeric"),
}, controls={"reference": 0})]
if k <= 30:
shown = [items[i] for i in order]
pr, pc_, pv, pl = [], [], [], []
for i in order:
for j in order:
pr.append(items[i])
pc_.append(items[j])
if i == j:
pv.append(0.5)
pl.append("")
else:
pij = float(pc.pair_probs("bt" if model == "crowd_bt" else model, np.array([s[i] - s[j]]), fit["nu"])[0][0])
pv.append(pij)
pl.append(f"{pij:.2f}")
charts.append(cs.chart("pairs", "matrix-heatmap", "Chance that the row item is preferred to the column item", {
"row": cs.col("Item", pr, "categorical", levels=shown),
"col": cs.col("Against", pc_, "categorical", levels=shown),
"value": cs.col("Probability", pv, "numeric"),
"label": cs.col("Text", pl, "categorical"),
}, controls={"scale": "sequential"}))
if topf is not None:
charts.append(cs.chart("top", "bar-ranked", "How often each item comes first in the bootstrap", {
"category": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"value": cs.col("Share of resamples", [float(topf[i]) for i in order], "numeric"),
}, controls={"agg": "sum", "top": min(30, k)}))
notes = [f"{label}: worths are log-worths centered to sum to 0 (only differences mean anything); the last item ({items[-1]}) was the reference in the fit. "
f"Outcome read as {'the winner’s name' if coding == 'winner' else 'whether the first item won'}. Newton iterations: {fit['iterations']}."]
if model == "thurstone":
notes.append("Thurstone worths are on a probit scale (P = Φ(difference)); they're about 0.6 times Bradley–Terry's and can't be compared with them directly.")
if model == "crowd_bt":
notes.append(f"Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with {prior:g} win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.")
if reps > 0:
notes.append(boot_note or f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); {boot_failed} skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.")
summary = f"{label} for {k} items from {int(n)} judgments: {items[top]} has the highest worth" + (f" and comes first in {values['top_item_freq']:.0%} of the bootstrap resamples." if values["top_item_freq"] is not None else ".")
apa = label + (f": LR χ²({k - 1}) = {cs.fmt_num(values['lr'])}, {cs.fmt_p(values['lr_p'])}" if values["lr"] is not None else "")
cs.publish({
"method": "measurement.bradley_terry",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": summary,
"apa": apa,
"statistics": [{"key": "lr", "label": "LR χ²", "value": values["lr"]}, {"key": "lr_p", "label": "p", "value": values["lr_p"], "format": "p"},
{"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "top_item_freq", "label": f"{items[top]} first", "value": values["top_item_freq"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
Check the fit before the ranking
In the appThe worths assume one stable dimension: if A beats B and B beats C, A should beat C. The goodness-of-fit row compares each pair's win count with what the worths predict (a G² test). A small p-value points to intransitive or context-dependent preferences, and a single ranking then hides real structure.
The reference study in the expansion guide fits six items to 900 judgments and scores 600 held-out ones. CodeSplash reproduces its estimates and its held-out log loss, 0.5959, against 0.6931 for a coin flip.
Bradley–Terry model: LR χ²(5) = 148.61, p < .001
- LR χ²
- 148.61
- p
- < .001
- AIC
- 1109.05
- i1 first
- 99.0%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 0.9508 | 1.173 | i1 | 0.7284 |
| 0.5448 | 0.7508 | i2 | 0.3388 |
| −0.0320 | 0.1657 | i3 | −0.2298 |
| −0.3095 | −0.1097 | i4 | −0.5094 |
| −0.5197 | −0.3157 | i5 | −0.7238 |
| −0.6343 | −0.4270 | i6 | −0.8416 |
View data
| Against | Text | Item | Probability |
|---|---|---|---|
| i1 | i1 | 0.5000 | |
| i2 | 0.60 | i1 | 0.6001 |
| i3 | 0.73 | i1 | 0.7277 |
| i4 | 0.78 | i1 | 0.7791 |
| i5 | 0.81 | i1 | 0.8131 |
| i6 | 0.83 | i1 | 0.8299 |
| i1 | 0.40 | i2 | 0.3999 |
| i2 | i2 | 0.5000 | |
| i3 | 0.64 | i2 | 0.6403 |
| i4 | 0.70 | i2 | 0.7015 |
| i5 | 0.74 | i2 | 0.7436 |
| i6 | 0.76 | i2 | 0.7648 |
| i1 | 0.27 | i3 | 0.2723 |
| i2 | 0.36 | i3 | 0.3597 |
| i3 | i3 | 0.5000 | |
| i4 | 0.57 | i3 | 0.5689 |
| i5 | 0.62 | i3 | 0.6196 |
| i6 | 0.65 | i3 | 0.6462 |
| i1 | 0.22 | i4 | 0.2209 |
| i2 | 0.30 | i4 | 0.2985 |
| i3 | 0.43 | i4 | 0.4311 |
| i4 | i4 | 0.5000 | |
| i5 | 0.55 | i4 | 0.5524 |
| i6 | 0.58 | i4 | 0.5805 |
| i1 | 0.19 | i5 | 0.1869 |
| i2 | 0.26 | i5 | 0.2564 |
| i3 | 0.38 | i5 | 0.3804 |
| i4 | 0.45 | i5 | 0.4476 |
| i5 | i5 | 0.5000 | |
| i6 | 0.53 | i5 | 0.5286 |
| i1 | 0.17 | i6 | 0.1701 |
| i2 | 0.24 | i6 | 0.2352 |
| i3 | 0.35 | i6 | 0.3538 |
| i4 | 0.42 | i6 | 0.4195 |
| i5 | 0.47 | i6 | 0.4714 |
| i6 | i6 | 0.5000 |
View data
| Item | Share of resamples |
|---|---|
| i1 | 0.9900 |
| i2 | 0.0100 |
| i3 | 0 |
| i4 | 0 |
| i5 | 0 |
| i6 | 0 |
Assumptions
- Connected comparisons — Every item wins and loses its way to every other item, so the estimates are finite and unique.
- Worths explain the pairs — G² = 11.47 on 10 df, p = 0.322.
- Judgments per item — Every item has at least 10 judgments (fewest 300).
- Ties — No ties in the fitted judgments.
- Position effect — Likelihood-ratio test for a first-position advantage: χ²(1) = 0.53, p = 0.468.
- Independent judgments — Not checked from data: judgments are treated as independent. The bootstrap resamples single judgments.
Worths (log scale, centered; share = chance of being preferred among all 6)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Wins | Losses | Ties | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | i1 | 0.9508 | 0.1135 | 0.7284 | 1.173 | 0.3625 | 225 | 75 | 0 | 0.9900 | 1 | 1 |
| 2 | i2 | 0.5448 | 0.1051 | 0.3388 | 0.7508 | 0.2415 | 195 | 105 | 0 | 0.0100 | 2 | 2 |
| 3 | i3 | −0.0320 | 0.1009 | −0.2298 | 0.1657 | 0.1357 | 148 | 152 | 0 | 0 | 3 | 4 |
| 4 | i4 | −0.3095 | 0.1020 | −0.5094 | −0.1097 | 0.1028 | 125 | 175 | 0 | 0 | 3 | 5 |
| 5 | i5 | −0.5197 | 0.1041 | −0.7238 | −0.3157 | 0.0833 | 108 | 192 | 0 | 0 | 4 | 6 |
| 6 | i6 | −0.6343 | 0.1058 | −0.8416 | −0.4270 | 0.0743 | 99 | 201 | 0 | 0 | 5 | 6 |
Model fit
| Value | |
|---|---|
| Judgments fitted | 900 |
| Log-likelihood | −549.53 |
| AIC | 1109.05 |
| BIC | 1133.07 |
| LR χ² vs equal worths | 148.61 |
| LR p | 2.638e-30 |
| Goodness of fit G² | 11.474 |
| G² df | 10 |
| G² p | 0.3218 |
| Held-out log loss | 0.5959 |
| Held-out log loss, equal worths | 0.6931 |
| Held-out Brier score | 0.2045 |
- Bradley–Terry model: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (i6) was the reference in the fit. Outcome read as whether the first item won. Newton iterations: 4.
- Bootstrap: 100 of 100 resamples of single judgments refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.bradley_terry 1.0.0 · spec d1ee5014f1aeb170
# Dataset: hme_pairs_counts (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_pairs_counts.parquet", col_select = c("item_a", "item_b", "a_wins", "n", "split")))
n_input <- nrow(df)
df[["item_a"]] <- factor(df[["item_a"]], levels = c("i1", "i2", "i3", "i4", "i5", "i6")) # stored level order
df[["item_b"]] <- factor(df[["item_b"]], levels = c("i1", "i2", "i3", "i4", "i5", "i6")) # stored level order
df[["split"]] <- factor(df[["split"]], levels = c("test", "train")) # stored level order
df <- df[stats::complete.cases(df[c("item_a", "item_b", "a_wins", "n", "split")]), , 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("item_a", "item_b", "a_wins", "n", "split")) # infinite values stop the run (registry/errors.yaml)
# %% Judgments
col_a <- "item_a"
col_b <- "item_b"
col_y <- "a_wins"
model <- "bt"
ties <- "drop"
use_order <- FALSE
prior <- 0.5
reps <- 100
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
label <- cs_pc_labels()[[model]]
kinds <- c(
"item_a" = "categorical",
"item_b" = "categorical",
"a_wins" = "numeric",
"n" = "numeric",
"split" = "categorical"
)
first <- as.character(df[[col_a]])
second <- as.character(df[[col_b]])
y_raw <- if (kinds[[col_y]] %in% c("categorical", "boolean")) as.character(df[[col_y]]) else df[[col_y]]
dec <- cs_pc_decode_outcomes(kinds[[col_y]], y_raw, first, second, "auto")
codes <- dec$codes
coding <- dec$coding
if (any(codes == -2)) cs_error("CS_E_INVALID_VALUES", column = col_y, requirement = "1 (first item preferred), 0 (second) or 0.5 (tie)", count = sum(codes == -2))
count <- as.numeric(df[["n"]])
bad <- count < 0 | count != floor(count)
if (any(bad)) cs_error("CS_E_INVALID_VALUES", column = "n", requirement = "a whole number of judgments (0 or more)", count = sum(bad))
held <- cs_pc_decode_holdout(kinds[["split"]], df[["split"]])
self_pair <- first == second
states <- list()
for (i in which(codes == -1 & !self_pair)) {
key <- dec$other[i]
states[[key]] <- (if (is.null(states[[key]])) 0 else states[[key]]) + count[i]
}
if (any(self_pair)) warnings <- c(warnings, list(sprintf("%d judgment(s) comparing an item with itself were left out.", as.integer(sum(count[self_pair])))))
if (length(states)) {
warnings <- c(warnings, list(paste0("Left out (neither item preferred): ",
paste(sprintf("%s (%d)", names(states), as.integer(unlist(states))), collapse = ", "), ".")))
}
n_left_out <- sum(unlist(states)) + sum(count[self_pair])
oc <- cs_pc_outcome_counts(codes, count, model, ties)
y1 <- oc$y1; y2 <- oc$y2; y3 <- oc$y3
use <- oc$keep & !self_pair
train <- use & !held
items_all <- unique(c(levels(df[[col_a]]), levels(df[[col_b]])))
seen <- unique(c(first[train], second[train]))
items <- items_all[items_all %in% seen]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_a, min = 2, k = k)
ia <- match(first, items)
ib <- match(second, items)
ia[is.na(ia)] <- 0L
ib[is.na(ib)] <- 0L
tr <- which(train)
a <- ia[tr]; b <- ib[tr]
t1 <- y1[tr]; t2 <- y2[tr]; t3 <- y3[tr]; tc <- count[tr]
n_ties <- sum(count[codes == 2 & !self_pair & !held])
if (ties == "drop" && model != "davidson" && n_ties > 0) warnings <- c(warnings, list(sprintf("%d tie(s) were left out; the Davidson model uses them.", as.integer(n_ties))))
if (model == "davidson" && sum(t3) == 0) cs_error("CS_E_UNDEFINED", what = "The Davidson model", reason = "there are no ties; use Bradley–Terry")
col_j <- NULL
judge_names <- character(0)
jcode <- NULL
if (model == "crowd_bt" && is.null(col_j)) cs_error("CS_E_UNDEFINED", what = "Crowd-BT", reason = "it needs a Judge column")
if (model == "crowd_bt" && length(judge_names) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_j, min = 2, k = length(judge_names))
unit_col <- NULL
if (!is.null(unit_col)) {
uv <- as.character(df[[unit_col]])[tr]
unit <- match(uv, unique(uv))
} else {
unit <- NULL
}
n <- sum(t1 + t2 + t3)
adj <- cs_pc_beat_graph(a, b, t1, t2, t3, k)
connected <- cs_pc_strongly_connected(adj)
if (model != "crowd_bt" && !connected) {
cs_error("CS_E_UNDEFINED", what = paste("The", label), reason = "some items never lose (or never win) against the rest, so their worths run off to infinity; add comparisons, or use Crowd-BT, which shrinks the worths toward the middle")
}
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
cell <- cs_pc_cells(a, b, t1, t2, t3, k, if (model == "crowd_bt") jcode else NULL)
fits <- tryCatch(list(
fit = cs_pc_fit_model(model, cell, k, use_order, length(judge_names), prior),
null = if (model == "crowd_bt") NULL else cs_pc_fit_pairs(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, k, use_order, null = TRUE)
), error = function(e) {
if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
cs_error("CS_E_NO_CONVERGENCE", what = paste("The", label))
})
fit <- fits$fit
null <- fits$null
alt <- NULL
alt_note <- NULL
if (model != "crowd_bt" && !use_order) { # the position test refits with a first-position term
alt <- tryCatch(cs_pc_fit_pairs(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, k, TRUE), error = function(e) NULL)
if (is.null(alt)) alt_note <- "A position effect can't be told apart from the worths in this design (for example, one item is always shown first)."
}
s <- fit$scores
z <- cs_pc_z(conf)
se <- if (!is.null(fit$cov)) sqrt(diag(fit$cov)) else rep(NA_real_, k)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
npar <- if (model == "crowd_bt") fit$npar else (k - 1) + as.integer(use_order) + as.integer(model == "davidson")
loglik <- fit$loglik
nz <- function(x) if (is.null(x) || length(x) == 0 || is.na(x)) NULL else x
values <- list(n = n, n_rows = length(tr), items = k, n_ties = n_ties, n_left_out = n_left_out, model_label = label,
loglik = loglik, npar = npar, aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n), iterations = fit$iterations)
if (!is.null(null)) {
lr <- 2 * (loglik - null$loglik)
values$loglik_null <- null$loglik; values$lr <- lr; values$lr_df <- k - 1; values$lr_p <- cs_pc_lr_p(lr, k - 1)
} else {
values["loglik_null"] <- list(NULL); values["lr"] <- list(NULL); values["lr_df"] <- list(NULL); values["lr_p"] <- list(NULL)
}
if (use_order) {
zo <- if (!is.null(fit$alpha_se)) fit$alpha / fit$alpha_se else NULL
values$order_effect <- fit$alpha
values["order_effect_se"] <- list(fit$alpha_se)
values["order_effect_p"] <- list(if (is.null(zo)) NULL else 2 * stats::pnorm(abs(zo), lower.tail = FALSE))
} else {
values["order_effect"] <- list(NULL); values["order_effect_se"] <- list(NULL); values["order_effect_p"] <- list(NULL)
}
if (!is.null(alt)) {
plr <- 2 * (alt$loglik - loglik)
values$position_lr <- plr; values$position_p <- cs_pc_lr_p(plr, 1)
} else {
values["position_lr"] <- list(NULL); values["position_p"] <- list(NULL)
}
if (model == "davidson") {
nu <- fit$nu; lse <- fit$lognu_se
values$nu <- nu; values$nu_low <- exp(log(nu) - z * lse); values$nu_high <- exp(log(nu) + z * lse)
values$tie_rate <- sum(t3) / n
} else {
for (key in c("nu", "nu_low", "nu_high", "tie_rate")) values[key] <- list(NULL)
}
gof <- NULL
if (model != "crowd_bt") {
gof <- cs_pc_gof(model, cell$a, cell$b, cell$y1, cell$y2, cell$y3, s, fit$nu, use_order, npar)
if (gof$df > 0) {
values$gof <- gof$g2; values$gof_df <- gof$df; values$gof_p <- cs_pc_lr_p(gof$g2, gof$df)
} else {
values["gof"] <- list(NULL); values["gof_df"] <- list(NULL); values["gof_p"] <- list(NULL)
}
} else {
values["gof"] <- list(NULL); values["gof_df"] <- list(NULL); values["gof_p"] <- list(NULL)
}
st <- cs_pc_item_stats(a, b, codes[tr], tc, k)
wins <- st$wins; losses <- st$losses; tied <- st$ties
ci_low <- s - z * se
ci_high <- s + z * se
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("score[%s]", it)]] <- s[i]
values[sprintf("se[%s]", it)] <- list(nz(se[i]))
values[sprintf("ci_low[%s]", it)] <- list(nz(ci_low[i]))
values[sprintf("ci_high[%s]", it)] <- list(nz(ci_high[i]))
values[[sprintf("worth[%s]", it)]] <- worth[i]
values[[sprintf("rank[%s]", it)]] <- ranks[i]
values[[sprintf("wins[%s]", it)]] <- wins[i]
values[[sprintf("losses[%s]", it)]] <- losses[i]
values[[sprintf("ties[%s]", it)]] <- tied[i]
}
# %% Judges
reversed_judges <- character(0)
if (model == "crowd_bt") {
eta <- fit$eta
n_j <- vapply(seq_along(judge_names), function(g) sum((t1 + t2)[jcode == g]), numeric(1))
for (g in seq_along(judge_names)) {
values[[sprintf("eta[%s]", judge_names[g])]] <- eta[g]
values[[sprintf("n_judge[%s]", judge_names[g])]] <- n_j[g]
}
reversed_judges <- judge_names[eta < 0.5]
} else if (!is.null(col_j)) {
ja <- cs_pc_judge_agreement(a, b, jcode, codes[tr], tc, s, length(judge_names))
for (g in seq_along(judge_names)) {
values[sprintf("agreement[%s]", judge_names[g])] <- list(nz(ja$agreement[g]))
values[[sprintf("n_judge[%s]", judge_names[g])]] <- ja$n[g]
}
}
values["judges"] <- list(if (!is.null(col_j)) length(judge_names) else NULL)
values["reversed_judges"] <- list(if (model == "crowd_bt") length(reversed_judges) else NULL)
# %% Bootstrap of the ranking (shared Wichmann–Hill stream; judgments, or whole clusters/judges)
boot_note <- NULL
boot_scores <- matrix(0, 0, k)
boot_failed <- 0
if (reps > 0) {
draws <- if (is.null(unit)) sum(tc) else max(unit)
if (draws * reps > 5e7) {
boot_note <- "The bootstrap was skipped: resampling this many judgments would take too long; set a Cluster column or fewer resamples."
} else {
bs <- cs_pc_bootstrap(model, a, b, jcode, t1, t2, t3, tc, unit, k, length(judge_names), use_order, prior, reps, seed)
boot_scores <- bs$scores
boot_failed <- bs$failed
}
}
values["boot_ok"] <- list(if (reps > 0) nrow(boot_scores) else NULL)
values["boot_failed"] <- list(if (reps > 0) boot_failed else NULL)
top <- cs_pc_top_index(s)
values$top_item <- items[top]
bsum <- NULL
if (nrow(boot_scores) >= 2) {
bsum <- cs_pc_boot_summary(boot_scores, conf)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("boot_low[%s]", it)]] <- bsum$low[i]
values[[sprintf("boot_high[%s]", it)]] <- bsum$high[i]
values[[sprintf("top_freq[%s]", it)]] <- bsum$top[i]
values[[sprintf("rank_low[%s]", it)]] <- bsum$rank_low[i]
values[[sprintf("rank_high[%s]", it)]] <- bsum$rank_high[i]
}
values$top_item_freq <- bsum$top[top]
} else {
values["top_item_freq"] <- list(NULL)
}
# %% Held-out judgments (rows marked as test)
te <- which(use & held & ia > 0 & ib > 0)
values$n_test <- sum(use & held)
if (length(te)) {
alpha <- if (is.null(fit$alpha)) 0 else fit$alpha
dt <- s[ia[te]] - s[ib[te]] + alpha
if (model == "crowd_bt") {
jt <- as.character(df[[col_j]])[te]
n_jt <- vapply(seq_along(judge_names), function(g) sum((t1 + t2)[jcode == g]), numeric(1))
eta_mean <- sum(fit$eta * n_jt) / sum(n_jt)
et <- ifelse(jt %in% judge_names, fit$eta[match(jt, judge_names)], eta_mean)
q <- cs_pc_crowd_probs(dt, et)
bq <- list(rep(0.5, length(te)), rep(0.5, length(te)), rep(0, length(te)))
} else {
q <- cs_pc_pair_probs(model, dt, fit$nu)
bq <- cs_pc_pair_probs(model, rep(if (is.null(null$alpha)) 0 else null$alpha, length(te)), null$nu)
}
e1 <- y1[te]; e2 <- y2[te]; e3 <- y3[te]
nt <- sum(e1 + e2 + e3)
lg <- function(x) log(ifelse(x > 0, x, 1)) # zero-probability cells carry no weight
values$test_logloss <- -sum(e1 * lg(q[[1]]) + e2 * lg(q[[2]]) + e3 * lg(q[[3]])) / nt
values$test_baseline <- -sum(e1 * lg(bq[[1]]) + e2 * lg(bq[[2]]) + e3 * lg(bq[[3]])) / nt
values["test_brier"] <- list(if (model != "davidson") sum(e1 * (1 - q[[1]])^2 + e2 * q[[1]]^2) / nt else NULL)
values$test_scored <- nt
} else {
for (key in c("test_logloss", "test_baseline", "test_brier", "test_scored")) values[key] <- list(NULL)
}
# %% Assumptions
per_item <- wins + losses + tied
thin <- sprintf("%s (%d)", items, as.integer(per_item))[per_item < 10]
fmt3 <- function(x) formatC(signif(x, 3), digits = 3, format = "fg", flag = "#")
pfmt <- function(x) sub("\\.$", "", formatC(x, digits = 3, format = "g"))
assumptions <- list()
if (model == "crowd_bt") {
wc <- cs_pc_weakly_connected(adj)
assumptions[[length(assumptions) + 1]] <- list(key = "connectivity", label = "Connected comparisons", status = if (wc) "pass" else "warn",
detail = if (wc) "Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite." else
"Some items are never compared, even indirectly, with others; their relative worth comes only from the shrinkage.")
} else {
assumptions[[length(assumptions) + 1]] <- list(key = "connectivity", label = "Connected comparisons", status = "pass",
detail = "Every item wins and loses its way to every other item, so the estimates are finite and unique.")
}
if (!is.null(gof)) {
if (gof$df <= 0) {
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = "info", detail = "Too few distinct pairs for a goodness-of-fit test.")
} else if (gof$small > 0.2) {
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = "info",
detail = sprintf("G² = %.2f on %d df, but %.0f%% of the expected counts are below 5, so the χ² approximation is rough.", gof$g2, as.integer(gof$df), 100 * gof$small))
} else {
gp <- cs_pc_lr_p(gof$g2, gof$df)
assumptions[[length(assumptions) + 1]] <- list(key = "fit", label = "Worths explain the pairs", status = if (gp < 0.05) "warn" else "pass",
detail = paste0(sprintf("G² = %.2f on %d df, p = %s", gof$g2, as.integer(gof$df), pfmt(gp)),
if (gp < 0.05) ": some pairs win more or less often than their worths say (intransitive or context-dependent preferences)." else "."))
}
}
assumptions[[length(assumptions) + 1]] <- list(key = "sample_size", label = "Judgments per item", status = if (length(thin)) "warn" else "pass",
detail = if (length(thin)) paste0("Fewer than 10 judgments: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
sprintf("Every item has at least 10 judgments (fewest %d).", as.integer(min(per_item))))
if (model == "davidson") {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = "info",
detail = sprintf("Ties are modeled as their own outcome: ν = %.3f (%.1f%% of the fitted judgments are ties); ties are likelier between items of similar worth.", values$nu, 100 * values$tie_rate))
} else if (n_ties > 0) {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = if (ties == "drop") "warn" else "info",
detail = paste0(sprintf("%d tie(s) ", as.integer(n_ties)), if (ties == "drop") "left out; the Davidson model would use them." else "counted as half a win for each item."))
} else {
assumptions[[length(assumptions) + 1]] <- list(key = "ties", label = "Ties", status = "pass", detail = "No ties in the fitted judgments.")
}
if (use_order) {
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = "info",
detail = paste0(sprintf("Fitted first-position effect %.3f", values$order_effect),
if (is.null(values$order_effect_se)) "" else sprintf(" (SE %.3f, p = %s)", values$order_effect_se, pfmt(values$order_effect_p)),
"; worths are net of it."))
} else if (!is.null(alt_note)) {
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = "info", detail = alt_note)
} else if (!is.null(alt)) {
pp <- values$position_p
assumptions[[length(assumptions) + 1]] <- list(key = "position", label = "Position effect", status = if (pp < 0.05) "warn" else "pass",
detail = paste0(sprintf("Likelihood-ratio test for a first-position advantage: χ²(1) = %.2f, p = %s", values$position_lr, pfmt(pp)),
if (pp < 0.05) " — turn on Position effect." else "."))
}
if (model == "crowd_bt") {
lowest <- which.min(fit$eta)
assumptions[[length(assumptions) + 1]] <- list(key = "reliability", label = "Judge reliability", status = if (length(reversed_judges)) "warn" else "pass",
detail = if (length(reversed_judges)) paste0("Below 0.5 (agreeing with the consensus less than chance): ",
paste(sprintf("%s (%.2f)", reversed_judges, fit$eta[match(reversed_judges, judge_names)]), collapse = ", "), ".") else
sprintf("Every judge agrees with the consensus more often than not (lowest %s: %.2f).", judge_names[lowest], fit$eta[lowest]))
}
unit_label <- if (!is.null(unit_col)) paste("whole values of", unit_col) else "single judgments"
assumptions[[length(assumptions) + 1]] <- list(key = "independence", label = "Independent judgments", status = "info",
detail = sprintf("Not checked from data: judgments are treated as independent. The bootstrap resamples %s.", unit_label))
# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols <- list(list(key = "rank", label = "Rank", type = "integer"), list(key = "item", label = "Item", type = "string"),
list(key = "score", label = "Worth (log)", type = "number"), list(key = "se", label = "SE", type = "number"),
list(key = "ci_low", label = paste(pct, "CI low"), type = "number"), list(key = "ci_high", label = paste(pct, "CI high"), type = "number"),
list(key = "worth", label = "Share", type = "number"), list(key = "wins", label = "Wins", type = "number"),
list(key = "losses", label = "Losses", type = "number"), list(key = "ties", label = "Ties", type = "number"))
if (!is.null(bsum)) {
cols <- c(cols, list(list(key = "top_freq", label = "First in resamples", type = "number"),
list(key = "rank_low", label = "Rank low", type = "number"), list(key = "rank_high", label = "Rank high", type = "number")))
}
rows <- lapply(ord, function(i) {
r <- list(rank = ranks[i], item = items[i], score = s[i], se = nz(se[i]), ci_low = nz(ci_low[i]), ci_high = nz(ci_high[i]),
worth = worth[i], wins = wins[i], losses = losses[i], ties = tied[i])
if (!is.null(bsum)) { r$top_freq <- bsum$top[i]; r$rank_low <- bsum$rank_low[i]; r$rank_high <- bsum$rank_high[i] }
r
})
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being preferred among all %d)", k), columns = cols, rows = rows))
fit_rows <- list(list(stat = "Judgments fitted", value = n), list(stat = "Log-likelihood", value = loglik), list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
if (!is.null(values$lr)) fit_rows <- c(fit_rows, list(list(stat = "LR χ² vs equal worths", value = values$lr), list(stat = "LR p", value = values$lr_p)))
if (!is.null(values$gof)) fit_rows <- c(fit_rows, list(list(stat = "Goodness of fit G²", value = values$gof), list(stat = "G² df", value = values$gof_df), list(stat = "G² p", value = values$gof_p)))
if (!is.null(values$test_logloss)) {
fit_rows <- c(fit_rows, list(list(stat = "Held-out log loss", value = values$test_logloss), list(stat = "Held-out log loss, equal worths", value = values$test_baseline)))
if (!is.null(values$test_brier)) fit_rows <- c(fit_rows, list(list(stat = "Held-out Brier score", value = values$test_brier)))
}
tables[[2]] <- list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows)
if (!is.null(col_j)) {
jcols <- list(list(key = "judge", label = "Judge", type = "string"), list(key = "n", label = "Judgments", type = "number"),
if (model == "crowd_bt") list(key = "eta", label = "Reliability η", type = "number") else list(key = "agreement", label = "Agrees with worth order", type = "number"))
jrows <- lapply(judge_names, function(nm) {
r <- list(judge = nm, n = values[[sprintf("n_judge[%s]", nm)]])
if (model == "crowd_bt") r$eta <- values[[sprintf("eta[%s]", nm)]] else r["agreement"] <- list(values[[sprintf("agreement[%s]", nm)]])
r
})
tables[[3]] <- list(key = "judges", title = "Judges", columns = jcols, rows = jrows)
}
low <- ifelse(is.na(ci_low), if (!is.null(bsum)) bsum$low else s, ci_low)[ord]
high <- ifelse(is.na(ci_high), if (!is.null(bsum)) bsum$high else s, ci_high)[ord]
charts <- list(cs_chart("worths", "forest", sprintf("Worths (log scale) with %s intervals", pct), list(
label = cs_col("Item", items[ord], "categorical", levels = items[ord]),
estimate = cs_col("Worth (log)", s[ord], "numeric"),
low = cs_col("Lower", low, "numeric"),
high = cs_col("Upper", high, "numeric")
), controls = list(reference = 0)))
if (k <= 30) {
shown <- items[ord]
pr <- character(0); pcl <- character(0); pv <- numeric(0); pl <- character(0)
for (i in ord) for (j in ord) {
pr <- c(pr, items[i]); pcl <- c(pcl, items[j])
if (i == j) {
pv <- c(pv, 0.5); pl <- c(pl, "")
} else {
pij <- cs_pc_pair_probs(if (model == "crowd_bt") "bt" else model, s[i] - s[j], fit$nu)[[1]]
pv <- c(pv, pij); pl <- c(pl, sprintf("%.2f", pij))
}
}
charts[[length(charts) + 1]] <- cs_chart("pairs", "matrix-heatmap", "Chance that the row item is preferred to the column item", list(
row = cs_col("Item", pr, "categorical", levels = shown),
col = cs_col("Against", pcl, "categorical", levels = shown),
value = cs_col("Probability", pv, "numeric"),
label = cs_col("Text", pl, "categorical")
), controls = list(scale = "sequential"))
}
if (!is.null(bsum)) {
charts[[length(charts) + 1]] <- cs_chart("top", "bar-ranked", "How often each item comes first in the bootstrap", list(
category = cs_col("Item", items[ord], "categorical", levels = items[ord]),
value = cs_col("Share of resamples", bsum$top[ord], "numeric")
), controls = list(agg = "sum", top = min(30, k)))
}
notes <- list(sprintf("%s: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (%s) was the reference in the fit. Outcome read as %s. Newton iterations: %d.",
label, items[k], if (coding == "winner") "the winner’s name" else "whether the first item won", as.integer(fit$iterations)))
if (model == "thurstone") notes[[length(notes) + 1]] <- "Thurstone worths are on a probit scale (P = Φ(difference)); they're about 0.6 times Bradley–Terry's and can't be compared with them directly."
if (model == "crowd_bt") notes[[length(notes) + 1]] <- sprintf("Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with %s win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.", format(prior))
if (reps > 0) {
notes[[length(notes) + 1]] <- if (!is.null(boot_note)) boot_note else sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.",
nrow(boot_scores), as.integer(reps), unit_label, format(seed), as.integer(boot_failed))
}
summary <- paste0(sprintf("%s for %d items from %d judgments: %s has the highest worth", label, k, as.integer(n), items[top]),
if (!is.null(values$top_item_freq)) sprintf(" and comes first in %.0f%% of the bootstrap resamples.", 100 * values$top_item_freq) else ".")
apa <- paste0(label, if (!is.null(values$lr)) sprintf(": LR χ²(%d) = %s, %s", as.integer(k - 1), cs_fmt_num(values$lr), cs_fmt_p(values$lr_p)) else "")
cs_publish(list(
method = "measurement.bradley_terry",
methodVersion = "1.0.0",
title = label,
engine = cs_engine_info("stats", "codesplashr"),
n = as.integer(n),
summary = summary,
apa = apa,
statistics = list(list(key = "lr", label = "LR χ²", value = values$lr), list(key = "lr_p", label = "p", value = values$lr_p, format = "p"),
list(key = "aic", label = "AIC", value = values$aic),
list(key = "top_item_freq", label = paste(items[top], "first"), value = values$top_item_freq, format = "percent")),
tables = tables,
assumptions = assumptions,
warnings = warnings,
notes = notes,
charts = charts,
values = values
))
Bradley–Terry model: LR χ²(5) = 148.61, p < .001
- LR χ²
- 148.61
- p
- < .001
- AIC
- 1109.05
- i1 first
- 99.0%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Connected comparisons — Every item wins and loses its way to every other item, so the estimates are finite and unique.
- Worths explain the pairs — G² = 11.47 on 10 df, p = 0.322.
- Judgments per item — Every item has at least 10 judgments (fewest 300).
- Ties — No ties in the fitted judgments.
- Position effect — Likelihood-ratio test for a first-position advantage: χ²(1) = 0.53, p = 0.468.
- Independent judgments — Not checked from data: judgments are treated as independent. The bootstrap resamples single judgments.
Worths (log scale, centered; share = chance of being preferred among all 6)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Wins | Losses | Ties | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | i1 | 0.9508 | 0.1135 | 0.7284 | 1.173 | 0.3625 | 225 | 75 | 0 | 0.9900 | 1 | 1 |
| 2 | i2 | 0.5448 | 0.1051 | 0.3388 | 0.7508 | 0.2415 | 195 | 105 | 0 | 0.0100 | 2 | 2 |
| 3 | i3 | −0.0320 | 0.1009 | −0.2298 | 0.1657 | 0.1357 | 148 | 152 | 0 | 0 | 3 | 4 |
| 4 | i4 | −0.3095 | 0.1020 | −0.5094 | −0.1097 | 0.1028 | 125 | 175 | 0 | 0 | 3 | 5 |
| 5 | i5 | −0.5197 | 0.1041 | −0.7238 | −0.3157 | 0.0833 | 108 | 192 | 0 | 0 | 4 | 6 |
| 6 | i6 | −0.6343 | 0.1058 | −0.8416 | −0.4270 | 0.0743 | 99 | 201 | 0 | 0 | 5 | 6 |
Model fit
| Value | |
|---|---|
| Judgments fitted | 900 |
| Log-likelihood | −549.53 |
| AIC | 1109.05 |
| BIC | 1133.07 |
| LR χ² vs equal worths | 148.61 |
| LR p | 2.638e-30 |
| Goodness of fit G² | 11.474 |
| G² df | 10 |
| G² p | 0.3218 |
| Held-out log loss | 0.5959 |
| Held-out log loss, equal worths | 0.6931 |
| Held-out Brier score | 0.2045 |
- Bradley–Terry model: worths are log-worths centered to sum to 0 (only differences mean anything); the last item (i6) was the reference in the fit. Outcome read as whether the first item won. Newton iterations: 4.
- Bootstrap: 100 of 100 resamples of single judgments refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.
The exact Python script · Python Python 3.13.5 · scipy 1.18.1 · pandas 3.1.0
# Paired comparisons (Bradley–Terry, Thurstone, Davidson, Crowd-BT)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.bradley_terry 1.0.0 · spec d1ee5014f1aeb170
# Dataset: hme_pairs_counts (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
import codesplash as cs
from codesplash.stats import paired_comparison as pc # twin of R's cs_pc_* (R/stats_paired_comparison.R)
# %% Data
df = pd.read_parquet("tests/parity/fixtures/hme_pairs_counts.parquet", columns=["item_a", "item_b", "a_wins", "n", "split"])
n_input = len(df)
df["item_a"] = pd.Categorical(df["item_a"], categories=["i1", "i2", "i3", "i4", "i5", "i6"]) # stored level order
df["item_b"] = pd.Categorical(df["item_b"], categories=["i1", "i2", "i3", "i4", "i5", "i6"]) # stored level order
df["split"] = pd.Categorical(df["split"], categories=["test", "train"]) # stored level order
df = df.dropna(subset=["item_a", "item_b", "a_wins", "n", "split"]) # listwise deletion over the analysis columns
df["item_a"] = df["item_a"].cat.remove_unused_categories()
df["item_b"] = df["item_b"].cat.remove_unused_categories()
df["split"] = df["split"].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, ["item_a", "item_b", "a_wins", "n", "split"]) # infinite values stop the run (registry/errors.yaml)
# %% Judgments
col_a, col_b, col_y = "item_a", "item_b", "a_wins"
model = "bt"
ties = "drop"
use_order = False
prior = 0.5
reps = 100
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
label = pc.MODEL_LABELS[model]
kinds = {"a_wins":"numeric","item_a":"categorical","item_b":"categorical","n":"numeric","split":"categorical"}
first = df[col_a].astype(str).tolist()
second = df[col_b].astype(str).tolist()
y_raw = df[col_y].astype(str).tolist() if kinds[col_y] in ("categorical", "boolean") else df[col_y].tolist()
codes, coding, other = pc.decode_outcomes(kinds[col_y], y_raw, first, second, "auto")
if (codes == -2).any():
cs.cs_error("CS_E_INVALID_VALUES", column=col_y, requirement="1 (first item preferred), 0 (second) or 0.5 (tie)", count=int((codes == -2).sum()))
count = df["n"].to_numpy(dtype=float)
bad = (count < 0) | (count != np.floor(count))
if bad.any():
cs.cs_error("CS_E_INVALID_VALUES", column="n", requirement="a whole number of judgments (0 or more)", count=int(bad.sum()))
held = pc.decode_holdout(kinds["split"], df["split"].astype(str).tolist() if kinds["split"] != "numeric" else df["split"].tolist())
self_pair = np.array([x == z for x, z in zip(first, second)], dtype=bool)
states = {}
for i in np.flatnonzero((codes == -1) & ~self_pair):
states[other[i]] = states.get(other[i], 0) + int(count[i])
if self_pair.any():
warnings.append(f"{int(count[self_pair].sum())} judgment(s) comparing an item with itself were left out.")
if states:
warnings.append("Left out (neither item preferred): " + ", ".join(f"{k} ({v})" for k, v in states.items()) + ".")
n_left_out = int(sum(states.values()) + count[self_pair].sum())
y1, y2, y3, keep = pc.outcome_counts(codes, count, model, ties)
use = keep & ~self_pair
train = use & ~held
items_all = list(dict.fromkeys([str(x) for x in df[col_a].cat.categories] + [str(x) for x in df[col_b].cat.categories]))
seen = set(np.array(first, dtype=object)[train]) | set(np.array(second, dtype=object)[train])
items = [it for it in items_all if it in seen]
k = len(items)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_a, min=2, k=k)
pos = {it: i for i, it in enumerate(items)}
ia = np.array([pos.get(x, -1) for x in first])
ib = np.array([pos.get(x, -1) for x in second])
tr = np.flatnonzero(train)
a, b = ia[tr], ib[tr]
t1, t2, t3, tc = y1[tr], y2[tr], y3[tr], count[tr]
n_ties = int(count[(codes == 2) & ~self_pair & ~held].sum())
if ties == "drop" and model != "davidson" and n_ties:
warnings.append(f"{n_ties} tie(s) were left out; the Davidson model uses them.")
if model == "davidson" and t3.sum() == 0:
cs.cs_error("CS_E_UNDEFINED", what="The Davidson model", reason="there are no ties; use Bradley–Terry")
col_j, judge_names, jcode = None, [], None
if model == "crowd_bt" and col_j is None:
cs.cs_error("CS_E_UNDEFINED", what="Crowd-BT", reason="it needs a Judge column")
if model == "crowd_bt" and len(judge_names) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_j, min=2, k=len(judge_names))
unit_col = None
if unit_col is not None:
uv = df[unit_col].astype(str).to_numpy()[tr]
unit_names = list(pd.unique(uv))
unit = np.array([unit_names.index(x) for x in uv], dtype=np.int64)
else:
unit = None
n = float((t1 + t2 + t3).sum())
adj = pc.beat_graph(a, b, t1, t2, t3, k)
connected = pc.strongly_connected(adj)
if model != "crowd_bt" and not connected:
cs.cs_error("CS_E_UNDEFINED", what=f"The {label}", reason="some items never lose (or never win) against the rest, so their worths run off to infinity; add comparisons, or use Crowd-BT, which shrinks the worths toward the middle")
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
cell = pc.pair_cells(a, b, t1, t2, t3, k, jcode if model == "crowd_bt" else None)
try:
fit = pc.fit_model(model, cell, k, use_order, len(judge_names), prior)
null = None if model == "crowd_bt" else pc.fit_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], k, use_order, null=True)
except RuntimeError:
cs.cs_error("CS_E_NO_CONVERGENCE", what=f"The {label}")
except np.linalg.LinAlgError:
cs.cs_error("CS_E_COLLINEAR")
alt, alt_note = None, None
if model != "crowd_bt" and not use_order: # the position test refits with a first-position term
try:
alt = pc.fit_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], k, True)
except (RuntimeError, np.linalg.LinAlgError):
alt_note = "A position effect can't be told apart from the worths in this design (for example, one item is always shown first)."
s = fit["scores"]
z = pc.z_value(conf)
se = np.sqrt(np.diag(fit["cov"])) if fit["cov"] is not None else np.full(k, np.nan)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
npar = fit["npar"] if model == "crowd_bt" else (k - 1) + (1 if use_order else 0) + (1 if model == "davidson" else 0)
loglik = fit["loglik"]
values = {"n": n, "n_rows": float(len(tr)), "items": float(k), "n_ties": float(n_ties), "n_left_out": float(n_left_out),
"model_label": label, "loglik": loglik, "npar": float(npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n),
"iterations": float(fit["iterations"])}
if null is not None:
lr = 2 * (loglik - null["loglik"])
values.update({"loglik_null": null["loglik"], "lr": lr, "lr_df": float(k - 1), "lr_p": pc.lr_p(lr, k - 1)})
else:
values.update({"loglik_null": None, "lr": None, "lr_df": None, "lr_p": None})
if use_order:
zo = fit["alpha"] / fit["alpha_se"] if fit["alpha_se"] else None
values.update({"order_effect": fit["alpha"], "order_effect_se": fit["alpha_se"],
"order_effect_p": None if zo is None else float(2 * pc.norm.sf(abs(zo)))})
else:
values.update({"order_effect": None, "order_effect_se": None, "order_effect_p": None})
if alt is not None:
plr = 2 * (alt["loglik"] - loglik)
values.update({"position_lr": plr, "position_p": pc.lr_p(plr, 1)})
else:
values.update({"position_lr": None, "position_p": None})
if model == "davidson":
nu, lse = fit["nu"], fit["lognu_se"]
values.update({"nu": nu, "nu_low": float(np.exp(np.log(nu) - z * lse)), "nu_high": float(np.exp(np.log(nu) + z * lse)),
"tie_rate": float(t3.sum() / n)})
else:
values.update({"nu": None, "nu_low": None, "nu_high": None, "tie_rate": None})
gof = None
if model != "crowd_bt":
g2, gdf, small = pc.gof_pairs(model, cell["a"], cell["b"], cell["y1"], cell["y2"], cell["y3"], s, fit["nu"], use_order, npar)
gof = (g2, gdf, small)
values.update({"gof": g2 if gdf > 0 else None, "gof_df": float(gdf) if gdf > 0 else None, "gof_p": pc.lr_p(g2, gdf) if gdf > 0 else None})
else:
values.update({"gof": None, "gof_df": None, "gof_p": None})
wins, losses, tied = pc.item_stats(a, b, codes[tr], tc, k)
for i, it in enumerate(items):
values[f"score[{it}]"] = float(s[i])
values[f"se[{it}]"] = None if np.isnan(se[i]) else float(se[i])
values[f"ci_low[{it}]"] = None if np.isnan(se[i]) else float(s[i] - z * se[i])
values[f"ci_high[{it}]"] = None if np.isnan(se[i]) else float(s[i] + z * se[i])
values[f"worth[{it}]"] = float(worth[i])
values[f"rank[{it}]"] = float(ranks[i])
values[f"wins[{it}]"] = float(wins[i])
values[f"losses[{it}]"] = float(losses[i])
values[f"ties[{it}]"] = float(tied[i])
# %% Judges
reversed_judges = []
if model == "crowd_bt":
eta = fit["eta"]
n_j = np.bincount(jcode, weights=t1 + t2, minlength=len(judge_names))
for g, name in enumerate(judge_names):
values[f"eta[{name}]"] = float(eta[g])
values[f"n_judge[{name}]"] = float(n_j[g])
reversed_judges = [nm for g, nm in enumerate(judge_names) if eta[g] < 0.5]
elif col_j is not None:
agree, n_j = pc.judge_agreement(a, b, jcode, codes[tr], tc, s, len(judge_names))
for g, name in enumerate(judge_names):
values[f"agreement[{name}]"] = None if np.isnan(agree[g]) else float(agree[g])
values[f"n_judge[{name}]"] = float(n_j[g])
values["judges"] = float(len(judge_names)) if col_j is not None else None
values["reversed_judges"] = float(len(reversed_judges)) if model == "crowd_bt" else None
# %% Bootstrap of the ranking (shared Wichmann–Hill stream; judgments, or whole clusters/judges)
boot_note = None
if reps > 0:
draws = float(tc.sum()) if unit is None else float(unit.max() + 1)
if draws * reps > 5e7:
boot_note = "The bootstrap was skipped: resampling this many judgments would take too long; set a Cluster column or fewer resamples."
boot_scores, boot_failed = np.zeros((0, k)), 0
else:
boot_scores, boot_failed = pc.bootstrap_pairs(model, a, b, jcode, t1, t2, t3, tc, unit, k, len(judge_names), use_order, prior, reps, seed)
else:
boot_scores, boot_failed = np.zeros((0, k)), 0
values["boot_ok"] = float(len(boot_scores)) if reps > 0 else None
values["boot_failed"] = float(boot_failed) if reps > 0 else None
top = pc.top_index(s)
values["top_item"] = items[top]
if len(boot_scores) >= 2:
blo, bhi, topf, rlo, rhi = pc.boot_summary(boot_scores, conf)
for i, it in enumerate(items):
values.update({f"boot_low[{it}]": float(blo[i]), f"boot_high[{it}]": float(bhi[i]), f"top_freq[{it}]": float(topf[i]),
f"rank_low[{it}]": float(rlo[i]), f"rank_high[{it}]": float(rhi[i])})
values["top_item_freq"] = float(topf[top])
else:
blo = bhi = topf = rlo = rhi = None
values["top_item_freq"] = None
# %% Held-out judgments (rows marked as test)
te = np.flatnonzero(use & held & (ia >= 0) & (ib >= 0))
values["n_test"] = float((use & held).sum())
if len(te):
alpha = fit["alpha"] or 0.0
dt = s[ia[te]] - s[ib[te]] + alpha
if model == "crowd_bt":
jt = df[col_j].astype(str).to_numpy()[te]
n_jt = np.bincount(jcode, weights=t1 + t2, minlength=len(judge_names))
eta_mean = float(np.sum(fit["eta"] * n_jt) / np.sum(n_jt))
et = np.array([fit["eta"][judge_names.index(x)] if x in judge_names else eta_mean for x in jt])
q1, q2, q3 = pc.crowd_probs(dt, et)
b1 = b2 = np.full(len(te), 0.5)
b3 = np.zeros(len(te))
else:
q1, q2, q3 = pc.pair_probs(model, dt, fit["nu"])
d0 = np.full(len(te), null["alpha"] or 0.0)
b1, b2, b3 = pc.pair_probs(model, d0, null["nu"])
e1, e2, e3 = y1[te], y2[te], y3[te]
nt = float((e1 + e2 + e3).sum())
lg = lambda q: np.log(np.where(q > 0, q, 1.0)) # noqa: E731 (zero-probability cells carry no weight)
values["test_logloss"] = float(-np.sum(e1 * lg(q1) + e2 * lg(q2) + e3 * lg(q3)) / nt)
values["test_baseline"] = float(-np.sum(e1 * lg(b1) + e2 * lg(b2) + e3 * lg(b3)) / nt)
values["test_brier"] = float(np.sum(e1 * (1 - q1) ** 2 + e2 * q1**2) / nt) if model != "davidson" else None
values["test_scored"] = nt
else:
values.update({"test_logloss": None, "test_baseline": None, "test_brier": None, "test_scored": None})
# %% Assumptions
per_item = wins + losses + tied
thin = [f"{it} ({int(per_item[i])})" for i, it in enumerate(items) if per_item[i] < 10]
assumptions = []
if model == "crowd_bt":
assumptions.append({"key": "connectivity", "label": "Connected comparisons", "status": "pass" if pc.weakly_connected(adj) else "warn",
"detail": "Every item is linked to the others by comparisons; Crowd-BT's shrinkage keeps the worths finite."
if pc.weakly_connected(adj) else "Some items are never compared, even indirectly, with others; their relative worth comes only from the shrinkage."})
else:
assumptions.append({"key": "connectivity", "label": "Connected comparisons", "status": "pass",
"detail": "Every item wins and loses its way to every other item, so the estimates are finite and unique."})
if gof is not None:
g2, gdf, small = gof
if gdf <= 0:
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "info", "detail": "Too few distinct pairs for a goodness-of-fit test."})
elif small > 0.2:
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "info",
"detail": f"G² = {g2:.2f} on {gdf} df, but {small:.0%} of the expected counts are below 5, so the χ² approximation is rough."})
else:
gp = pc.lr_p(g2, gdf)
assumptions.append({"key": "fit", "label": "Worths explain the pairs", "status": "warn" if gp < 0.05 else "pass",
"detail": f"G² = {g2:.2f} on {gdf} df, p = {gp:.3g}" + (": some pairs win more or less often than their worths say (intransitive or context-dependent preferences)." if gp < 0.05 else ".")})
assumptions.append({"key": "sample_size", "label": "Judgments per item", "status": "warn" if thin else "pass",
"detail": "Fewer than 10 judgments: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item has at least 10 judgments (fewest {int(per_item.min())})."})
if model == "davidson":
assumptions.append({"key": "ties", "label": "Ties", "status": "info",
"detail": f"Ties are modeled as their own outcome: ν = {values['nu']:.3f} ({values['tie_rate']:.1%} of the fitted judgments are ties); ties are likelier between items of similar worth."})
elif n_ties:
assumptions.append({"key": "ties", "label": "Ties", "status": "warn" if ties == "drop" else "info",
"detail": f"{n_ties} tie(s) " + ("left out; the Davidson model would use them." if ties == "drop" else "counted as half a win for each item.")})
else:
assumptions.append({"key": "ties", "label": "Ties", "status": "pass", "detail": "No ties in the fitted judgments."})
if use_order:
assumptions.append({"key": "position", "label": "Position effect", "status": "info",
"detail": f"Fitted first-position effect {values['order_effect']:.3f}" + ("" if values["order_effect_se"] is None else f" (SE {values['order_effect_se']:.3f}, p = {values['order_effect_p']:.3g})") + "; worths are net of it."})
elif alt_note is not None:
assumptions.append({"key": "position", "label": "Position effect", "status": "info", "detail": alt_note})
elif alt is not None:
pp = values["position_p"]
assumptions.append({"key": "position", "label": "Position effect", "status": "warn" if pp < 0.05 else "pass",
"detail": f"Likelihood-ratio test for a first-position advantage: χ²(1) = {values['position_lr']:.2f}, p = {pp:.3g}" + (" — turn on Position effect." if pp < 0.05 else ".")})
if model == "crowd_bt":
lowest = int(np.argmin(fit["eta"]))
assumptions.append({"key": "reliability", "label": "Judge reliability", "status": "warn" if reversed_judges else "pass",
"detail": (f"Below 0.5 (agreeing with the consensus less than chance): " + ", ".join(f"{nm} ({fit['eta'][judge_names.index(nm)]:.2f})" for nm in reversed_judges) + ".")
if reversed_judges else f"Every judge agrees with the consensus more often than not (lowest {judge_names[lowest]}: {fit['eta'][lowest]:.2f})."})
unit_label = f"whole values of {unit_col}" if unit_col else "single judgments"
assumptions.append({"key": "independence", "label": "Independent judgments", "status": "info",
"detail": f"Not checked from data: judgments are treated as independent. The bootstrap resamples {unit_label}."})
# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols = [{"key": "rank", "label": "Rank", "type": "integer"}, {"key": "item", "label": "Item", "type": "string"},
{"key": "score", "label": "Worth (log)", "type": "number"}, {"key": "se", "label": "SE", "type": "number"},
{"key": "ci_low", "label": f"{pct} CI low", "type": "number"}, {"key": "ci_high", "label": f"{pct} CI high", "type": "number"},
{"key": "worth", "label": "Share", "type": "number"}, {"key": "wins", "label": "Wins", "type": "number"},
{"key": "losses", "label": "Losses", "type": "number"}, {"key": "ties", "label": "Ties", "type": "number"}]
if blo is not None:
cols += [{"key": "top_freq", "label": "First in resamples", "type": "number"},
{"key": "rank_low", "label": "Rank low", "type": "number"}, {"key": "rank_high", "label": "Rank high", "type": "number"}]
rows = []
for i in order:
r = {"rank": float(ranks[i]), "item": items[i], "score": float(s[i]), "se": values[f"se[{items[i]}]"], "ci_low": values[f"ci_low[{items[i]}]"],
"ci_high": values[f"ci_high[{items[i]}]"], "worth": float(worth[i]), "wins": float(wins[i]), "losses": float(losses[i]), "ties": float(tied[i])}
if blo is not None:
r.update({"top_freq": float(topf[i]), "rank_low": float(rlo[i]), "rank_high": float(rhi[i])})
rows.append(r)
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being preferred among all {k})", "columns": cols, "rows": rows}]
fit_rows = [{"stat": "Judgments fitted", "value": n}, {"stat": "Log-likelihood", "value": loglik}, {"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
if values["lr"] is not None:
fit_rows += [{"stat": "LR χ² vs equal worths", "value": values["lr"]}, {"stat": "LR p", "value": values["lr_p"]}]
if values["gof"] is not None:
fit_rows += [{"stat": "Goodness of fit G²", "value": values["gof"]}, {"stat": "G² df", "value": values["gof_df"]}, {"stat": "G² p", "value": values["gof_p"]}]
if values["test_logloss"] is not None:
fit_rows += [{"stat": "Held-out log loss", "value": values["test_logloss"]}, {"stat": "Held-out log loss, equal worths", "value": values["test_baseline"]}]
if values["test_brier"] is not None:
fit_rows.append({"stat": "Held-out Brier score", "value": values["test_brier"]})
tables.append({"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows})
if col_j is not None:
jcols = [{"key": "judge", "label": "Judge", "type": "string"}, {"key": "n", "label": "Judgments", "type": "number"}]
jcols.append({"key": "eta", "label": "Reliability η", "type": "number"} if model == "crowd_bt" else {"key": "agreement", "label": "Agrees with worth order", "type": "number"})
jrows = [{"judge": nm, "n": values[f"n_judge[{nm}]"], **({"eta": values[f"eta[{nm}]"]} if model == "crowd_bt" else {"agreement": values[f"agreement[{nm}]"]})} for nm in judge_names]
tables.append({"key": "judges", "title": "Judges", "columns": jcols, "rows": jrows})
low = [values[f"ci_low[{items[i]}]"] if values[f"ci_low[{items[i]}]"] is not None else (float(blo[i]) if blo is not None else float(s[i])) for i in order]
high = [values[f"ci_high[{items[i]}]"] if values[f"ci_high[{items[i]}]"] is not None else (float(bhi[i]) if bhi is not None else float(s[i])) for i in order]
charts = [cs.chart("worths", "forest", f"Worths (log scale) with {pct} intervals", {
"label": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"estimate": cs.col("Worth (log)", [float(s[i]) for i in order], "numeric"),
"low": cs.col("Lower", low, "numeric"),
"high": cs.col("Upper", high, "numeric"),
}, controls={"reference": 0})]
if k <= 30:
shown = [items[i] for i in order]
pr, pc_, pv, pl = [], [], [], []
for i in order:
for j in order:
pr.append(items[i])
pc_.append(items[j])
if i == j:
pv.append(0.5)
pl.append("")
else:
pij = float(pc.pair_probs("bt" if model == "crowd_bt" else model, np.array([s[i] - s[j]]), fit["nu"])[0][0])
pv.append(pij)
pl.append(f"{pij:.2f}")
charts.append(cs.chart("pairs", "matrix-heatmap", "Chance that the row item is preferred to the column item", {
"row": cs.col("Item", pr, "categorical", levels=shown),
"col": cs.col("Against", pc_, "categorical", levels=shown),
"value": cs.col("Probability", pv, "numeric"),
"label": cs.col("Text", pl, "categorical"),
}, controls={"scale": "sequential"}))
if topf is not None:
charts.append(cs.chart("top", "bar-ranked", "How often each item comes first in the bootstrap", {
"category": cs.col("Item", [items[i] for i in order], "categorical", levels=[items[i] for i in order]),
"value": cs.col("Share of resamples", [float(topf[i]) for i in order], "numeric"),
}, controls={"agg": "sum", "top": min(30, k)}))
notes = [f"{label}: worths are log-worths centered to sum to 0 (only differences mean anything); the last item ({items[-1]}) was the reference in the fit. "
f"Outcome read as {'the winner’s name' if coding == 'winner' else 'whether the first item won'}. Newton iterations: {fit['iterations']}."]
if model == "thurstone":
notes.append("Thurstone worths are on a probit scale (P = Φ(difference)); they're about 0.6 times Bradley–Terry's and can't be compared with them directly.")
if model == "crowd_bt":
notes.append(f"Crowd-BT: P(first preferred) = η·σ(d) + (1 − η)·σ(−d) per judge; a virtual item at 0 with {prior:g} win(s) and loss(es) for every item, and a Beta(2, 2) prior on each η, keep the estimates finite. Standard errors come from the bootstrap only.")
if reps > 0:
notes.append(boot_note or f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); {boot_failed} skipped because a resample's win graph wasn't connected or didn't converge. Intervals are percentile intervals.")
summary = f"{label} for {k} items from {int(n)} judgments: {items[top]} has the highest worth" + (f" and comes first in {values['top_item_freq']:.0%} of the bootstrap resamples." if values["top_item_freq"] is not None else ".")
apa = label + (f": LR χ²({k - 1}) = {cs.fmt_num(values['lr'])}, {cs.fmt_p(values['lr_p'])}" if values["lr"] is not None else "")
cs.publish({
"method": "measurement.bradley_terry",
"methodVersion": "1.0.0",
"title": label,
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n),
"summary": summary,
"apa": apa,
"statistics": [{"key": "lr", "label": "LR χ²", "value": values["lr"]}, {"key": "lr_p", "label": "p", "value": values["lr_p"], "format": "p"},
{"key": "aic", "label": "AIC", "value": values["aic"]}, {"key": "top_item_freq", "label": f"{items[top]} first", "value": values["top_item_freq"], "format": "percent"}],
"tables": tables,
"assumptions": assumptions,
"warnings": warnings,
"notes": notes,
"charts": charts,
"values": values,
})
Same model, two dialects
Readimport numpy as np
import pandas as pd
import statsmodels.api as sm
df = pd.read_csv("pairs.csv") # first, second, first_won (1/0)
items = sorted(set(df["first"]) | set(df["second"]))
X = np.zeros((len(df), len(items) - 1)) # the last item is the reference
for r, (a, b) in enumerate(zip(df["first"], df["second"])):
if items.index(a) < len(items) - 1: X[r, items.index(a)] += 1
if items.index(b) < len(items) - 1: X[r, items.index(b)] -= 1
fit = sm.GLM(df["first_won"], X, family=sm.families.Binomial()).fit()
worth = np.r_[fit.params, 0.0]
print(dict(zip(items, worth - worth.mean())))library(BradleyTerry2)
df <- read.csv("pairs.csv")
df$win1 <- df$first_won; df$win2 <- 1 - df$first_won
items <- sort(unique(c(df$first, df$second)))
df$first <- factor(df$first, items); df$second <- factor(df$second, items)
fit <- BTm(cbind(win1, win2), first, second, data = df)
BTabilities(fit) # reference = first item; center to compare with the cardPackages fix a different reference item, so center their worths before comparing digits with the card.
Check your understanding
CheckpointCheck yourself
Item A's worth is 1.0 higher than item B's. Under Bradley–Terry, what is the chance a judge prefers A?
Show the answer
Answer: 0.731
.
Check yourself
System X won 80% of its comparisons and system Y won 60%. Why might Y still have the higher worth?
Show the answer
Answer: b
Worths account for the strength of the opponents; raw win rates don't.
Check yourself
Judges could answer "about the same", and a fifth of the answers are ties. Which choice keeps that information?
Show the answer
Answer: a
Dropping ties throws information away, and recoding them invents preferences. Davidson models them directly.
Check yourself
Crowd-BT estimates a judge's reliability at 0.2. What does that mean?
Show the answer
Answer: c
Reliability is the chance a verdict follows the consensus worth order: 0.5 is a coin flip, and below 0.5 the judge tends to pick the weaker item.
Recap
Recap- Bradley–Terry turns pairwise judgments into worths; only their differences mean anything.
- Report how often the leader stays on top in the bootstrap, not only the order.
- Worths need a strongly connected win graph; Crowd-BT's shrinkage helps when they don't exist.
- Davidson for ties, a position effect for first-shown advantages, Crowd-BT for unreliable judges.
Concepts in this lesson