Rankings: the Plackett–Luce model
Model a ranking as a sequence of choices. Use partial and top-k rankings correctly, read worth shares, and see how many rankings it takes before an order is settled.
What runs in CodeSplash
- Rankings (Plackett–Luce) Verified in Python and R
You will be able to
- Write the probability of a ranking under Plackett–Luce
- Explain why an unranked but shown item still matters in a top-k ranking
- Read worths, shares and bootstrap rank intervals
A ranking is a sequence of choices
ReadA taster ranks the fruits they were given. The Plackett–Luce modelPlackett–Luce modelA model of rankings as successive choices: each next item is picked from those left with chance proportional to its worth. reads that ranking as successive choices: first the favorite from everything on offer, then the favorite from what's left, and so on. Each item has a worth , and each choice picks item with probability divided by the total worth still available:
With only two items, that's exactly Bradley–Terry. Writing 900 pairwise judgments as two-item rankings gives the same worths and log-likelihood (−549.53).
Top-k rankings and shown items
PredictPredict first
A taster was given six fruits but ranked only their top three. What should the model do with the other three?
Reveal
Keep them as alternatives at every step. Each of the three choices was made with those fruits still on the table, so they belong in every denominator. Dropping them would pretend the taster chose from three fruits, and calling them tied invents a judgment nobody made. Leave their rank missing and the card treats them correctly. Here 56 of the 150 rankings are top-3 only.
Read the card
In the appPlackett–Luce model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 89.0%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 0.7604 | 0.9882 | mango | 0.5326 |
| 0.5478 | 0.7845 | peach | 0.3111 |
| 0.3851 | 0.6220 | melon | 0.1482 |
| −0.0653 | 0.1708 | pear | −0.3013 |
| −0.1676 | 0.0660 | plum | −0.4011 |
| −0.5964 | −0.3467 | lemon | −0.8460 |
| −0.8642 | −0.5987 | lime | −1.130 |
View data
| Item | Share of resamples |
|---|---|
| mango | 0.8900 |
| peach | 0.1000 |
| melon | 0.0100 |
| pear | 0 |
| plum | 0 |
| lemon | 0 |
| lime | 0 |
Assumptions
- Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
- First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
- Rankings per item — Every item is in at least 10 rankings (fewest 101).
- Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples single rankings.
Worths (log scale, centered; share = chance of being ranked first among all 7)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.8900 | 1 | 2 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.1000 | 1 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0.0100 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.44 |
- Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Lower values of rank are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
- Bootstrap: 200 of 200 resamples of single rankings refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 8227e60eb1412e03
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r <- "taster"
col_i <- "fruit"
col_v <- "rank"
col_c <- NULL
cols <- unique(c(col_r, col_i, col_v, col_c))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_rankings.parquet", col_select = cols))
stored_levels <- c("lemon", "lime", "mango", "melon", "peach", "pear", "plum")
n_input <- nrow(df)
need <- c(col_r, col_i, col_c)
df <- df[stats::complete.cases(df[need]), , drop = FALSE] # rows without a ranking, item or cluster can't be placed
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
value <- as.numeric(df[[col_v]])
cs_check_finite(value, col_v) # infinite values stop the run (registry/errors.yaml)
item_text <- as.character(df[[col_i]])
levels_i <- if (!is.null(stored_levels)) stored_levels else sort(unique(item_text), method = "radix")
rid <- as.character(df[[col_r]])
names_r <- unique(rid)
code <- match(rid, names_r)
dup <- duplicated(paste(code, item_text, sep = "\r"))
if (any(dup)) cs_error("CS_E_INVALID_VALUES", column = col_i, requirement = "listed at most once in each ranking", count = sum(dup))
if (all(is.na(value))) cs_error("CS_E_ALL_MISSING", column = col_v)
better <- "lower"
reps <- 200
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
item_all <- match(item_text, levels_i)
stg <- cs_pc_pl_stages(code, item_all, value, better)
if (stg$tied > 0) cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = sprintf("ranking %s has tied ranks; break the ties or leave that ranking out", names_r[stg$tied]))
if (length(unique(item_text)) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = length(unique(item_text)))
if (length(stg$st_choice) == 0) cs_error("CS_E_TOO_FEW_ROWS", what = "The Plackett–Luce model", min = 2, n = 0) # no ranking shows two or more items
n_rank <- stg$n_rank
used <- sort(unique(stg$mem_item))
items <- levels_i[used]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = k)
remap <- rep(0L, length(levels_i))
remap[used] <- seq_len(k)
st_rank <- stg$st_rank
st_choice <- remap[stg$st_choice]
mem_stage <- stg$mem_stage
mem_item <- remap[stg$mem_item]
w_rank <- rep(1, n_rank)
w_stage <- w_rank[st_rank]
adj <- cs_pc_pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if (!cs_pc_strongly_connected(adj)) {
cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = "some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
}
if (!is.null(col_c)) {
cv <- as.character(df[[col_c]])
first_row <- match(seq_len(n_rank), code)
cl <- cv[first_row]
unit <- match(cl, unique(cl))
unit_label <- paste("whole values of", col_c)
} else {
unit <- NULL
unit_label <- "single rankings"
}
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
fit <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, w_stage, k), error = function(e) {
if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
cs_error("CS_E_NO_CONVERGENCE", what = "The Plackett–Luce model")
})
s <- fit$scores
se <- sqrt(diag(fit$cov))
z <- cs_pc_z(conf)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
loglik <- fit$loglik
loglik0 <- fit$loglik_null
npar <- k - 1
lr <- 2 * (loglik - loglik0)
ff <- cs_pc_pl_first_fit(st_rank, st_choice, mem_stage, mem_item, fit$raw, w_rank, k)
worst <- which.max(abs(ff$z))
pairs <- unique((st_rank[mem_stage] - 1) * k + mem_item) # rankings in which each item takes part
shown <- tabulate((pairs - 1) %% k + 1, nbins = k)
values <- list(n_rankings = n_rank, n_choices = length(st_choice), items = k, partial = stg$partial, n_left_out = n_input - nrow(df),
loglik = loglik, loglik_null = loglik0, npar = npar, lr = lr, lr_df = npar, lr_p = cs_pc_lr_p(lr, npar),
aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n_rank), fit_max_z = abs(ff$z[worst]),
fit_item = items[worst], iterations = fit$iterations)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("score[%s]", it)]] <- s[i]
values[[sprintf("se[%s]", it)]] <- se[i]
values[[sprintf("ci_low[%s]", it)]] <- s[i] - z * se[i]
values[[sprintf("ci_high[%s]", it)]] <- s[i] + z * se[i]
values[[sprintf("worth[%s]", it)]] <- worth[i]
values[[sprintf("rank[%s]", it)]] <- ranks[i]
values[[sprintf("shown[%s]", it)]] <- shown[i]
values[[sprintf("first_choices[%s]", it)]] <- ff$O[i]
values[[sprintf("first_expected[%s]", it)]] <- ff$E[i]
}
# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot <- list()
boot_failed <- 0
if (reps > 0) {
counts <- cs_pc_boot_counts(w_rank, unit, reps, seed)
for (r in seq_len(reps)) {
wb <- counts[r, ][st_rank]
if (!cs_pc_strongly_connected(cs_pc_pl_graph(st_choice, mem_stage, mem_item, wb, k))) {
boot_failed <- boot_failed + 1
next
}
res <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, wb, k)$scores, error = function(e) NULL)
if (is.null(res)) boot_failed <- boot_failed + 1 else boot[[length(boot) + 1]] <- res
}
}
boot_scores <- if (length(boot)) do.call(rbind, boot) else matrix(0, 0, k)
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)
}
# %% Assumptions
thin <- sprintf("%s (%d)", items, as.integer(shown))[shown < 10]
assumptions <- list(
list(key = "connectivity", label = "Connected rankings", status = "pass",
detail = "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."),
list(key = "fit", label = "First choices match the model", status = if (abs(ff$z[worst]) > 3) "warn" else "pass",
detail = paste0(sprintf("Largest standardized gap: %s, first in %.0f rankings against %.1f expected (z = %.2f)", items[worst], ff$O[worst], ff$E[worst], ff$z[worst]),
if (abs(ff$z[worst]) > 3) " — the model misses this item's first choices." else ".")),
list(key = "sample_size", label = "Rankings per item", status = if (length(thin)) "warn" else "pass",
detail = if (length(thin)) paste0("In fewer than 10 rankings: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
sprintf("Every item is in at least 10 rankings (fewest %d).", as.integer(min(shown)))),
list(key = "independence", label = "Independent rankings", status = "info",
detail = sprintf("Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples %s.", unit_label))
)
# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols_t <- 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 = "shown", label = "Rankings", type = "number"),
list(key = "first", label = "Ranked first", type = "number"), list(key = "expected", label = "Expected first", type = "number"))
if (!is.null(bsum)) {
cols_t <- c(cols_t, 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 = se[i], ci_low = s[i] - z * se[i], ci_high = s[i] + z * se[i],
worth = worth[i], shown = shown[i], first = ff$O[i], expected = ff$E[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
})
fit_rows <- list(list(stat = "Rankings", value = n_rank), list(stat = "Choices", value = length(st_choice)),
list(stat = "Log-likelihood", value = loglik), list(stat = "Log-likelihood, equal worths", value = loglik0),
list(stat = "LR χ² vs equal worths", value = lr), list(stat = "LR p", value = values$lr_p),
list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being ranked first among all %d)", k), columns = cols_t, rows = rows),
list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows))
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", (s - z * se)[ord], "numeric"),
high = cs_col("Upper", (s + z * se)[ord], "numeric")
), controls = list(reference = 0)))
if (!is.null(bsum)) {
charts[[2]] <- 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("Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (%s) was the reference in the fit. %s values of %s are better. %d of %d rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: %d.",
items[k], if (better == "lower") "Lower" else "Higher", col_v, as.integer(stg$partial), as.integer(n_rank), as.integer(fit$iterations)))
if (reps > 0) {
notes[[2]] <- sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's rankings weren'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("Plackett–Luce model for %d items from %d rankings: %s has the highest worth", k, as.integer(n_rank), 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 ".")
cs_publish(list(
method = "measurement.plackett_luce",
methodVersion = "1.0.0",
title = "Plackett–Luce model",
engine = cs_engine_info("stats", "codesplashr"),
n = as.integer(n_rank),
summary = summary,
apa = sprintf("Plackett–Luce model: LR χ²(%d) = %s, %s", as.integer(npar), cs_fmt_num(lr), cs_fmt_p(values$lr_p)),
statistics = list(list(key = "lr", label = "LR χ²", value = 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
))
Plackett–Luce model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 89.0%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
- First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
- Rankings per item — Every item is in at least 10 rankings (fewest 101).
- Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples single rankings.
Worths (log scale, centered; share = chance of being ranked first among all 7)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.8900 | 1 | 2 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.1000 | 1 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0.0100 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.44 |
- Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Lower values of rank are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
- Bootstrap: 200 of 200 resamples of single rankings refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren'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
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 8227e60eb1412e03
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_finite
from codesplash.stats import paired_comparison as pc # twin of R's cs_pc_* (R/stats_paired_comparison.R)
# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r, col_i, col_v = "taster", "fruit", "rank"
col_c = None
cols = [c for c in (col_r, col_i, col_v, col_c) if c is not None]
df = pd.read_parquet("tests/parity/fixtures/hme_rankings.parquet", columns=list(dict.fromkeys(cols)))
stored = json.loads("{\"fruit\":[\"lemon\",\"lime\",\"mango\",\"melon\",\"peach\",\"pear\",\"plum\"],\"rank\":null,\"taster\":null}")
n_input = len(df)
need = [c for c in (col_r, col_i, col_c) if c is not None]
df = df.dropna(subset=need).reset_index(drop=True) # rows without a ranking, item or cluster can't be placed
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
value = df[col_v].to_numpy(dtype=float)
check_finite(value, col_v) # infinite values stop the run (registry/errors.yaml)
item_text = df[col_i].astype(str).to_numpy()
levels = stored.get(col_i) or sorted(set(item_text))
rid = df[col_r].astype(str).to_numpy()
names = list(pd.unique(rid))
code = np.array([names.index(x) for x in rid], dtype=np.int64)
dup = pd.Series(list(zip(code, item_text))).duplicated().to_numpy()
if dup.any():
cs.cs_error("CS_E_INVALID_VALUES", column=col_i, requirement="listed at most once in each ranking", count=int(dup.sum()))
if np.isnan(value).all():
cs.cs_error("CS_E_ALL_MISSING", column=col_v)
better = "lower"
reps = 200
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
pos_all = {it: i for i, it in enumerate(levels)}
item_all = np.array([pos_all[x] for x in item_text], dtype=np.int64)
st_rank, st_choice, mem_stage, mem_item, n_rank, partial, tied = pc.pl_stages(code, item_all, value, better)
if tied >= 0:
cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason=f"ranking {names[tied]} has tied ranks; break the ties or leave that ranking out")
if len(set(item_text)) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=len(set(item_text)))
if len(st_choice) == 0: # no ranking shows two or more items
cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Plackett–Luce model", min=2, n=0)
used = sorted(set(mem_item.tolist()))
items = [levels[i] for i in used]
k = len(items)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=k)
remap = np.full(len(levels), -1, dtype=np.int64)
remap[used] = np.arange(k)
st_choice, mem_item = remap[st_choice], remap[mem_item]
w_rank = np.ones(n_rank)
w_stage = w_rank[st_rank]
adj = pc.pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if not pc.strongly_connected(adj):
cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason="some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
if col_c is not None:
cv = df[col_c].astype(str).to_numpy()
first_row = np.array([np.flatnonzero(code == g)[0] for g in range(n_rank)])
cl_names = list(pd.unique(cv[first_row]))
unit = np.array([cl_names.index(x) for x in cv[first_row]], dtype=np.int64)
unit_label = f"whole values of {col_c}"
else:
unit = None
unit_label = "single rankings"
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
try:
fit = pc.fit_pl(st_choice, mem_stage, mem_item, w_stage, k)
except RuntimeError:
cs.cs_error("CS_E_NO_CONVERGENCE", what="The Plackett–Luce model")
except np.linalg.LinAlgError:
cs.cs_error("CS_E_COLLINEAR")
s = fit["scores"]
se = np.sqrt(np.diag(fit["cov"]))
z = pc.z_value(conf)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
loglik, loglik0 = fit["loglik"], fit["loglik_null"]
npar = k - 1
lr = 2 * (loglik - loglik0)
O, E, zr = pc.pl_first_choice_fit(st_rank, st_choice, mem_stage, mem_item, fit["raw"], w_rank, k)
worst = int(np.argmax(np.abs(zr)))
pairs = np.unique(st_rank[mem_stage] * k + mem_item) # rankings in which each item takes part
shown = np.bincount(pairs % k, minlength=k).astype(float)
values = {"n_rankings": float(n_rank), "n_choices": float(len(st_choice)), "items": float(k), "partial": float(partial),
"n_left_out": float(n_input - len(df)), "loglik": loglik, "loglik_null": loglik0, "npar": float(npar), "lr": lr,
"lr_df": float(npar), "lr_p": pc.lr_p(lr, npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n_rank),
"fit_max_z": float(np.abs(zr[worst])), "fit_item": items[worst], "iterations": float(fit["iterations"])}
for i, it in enumerate(items):
values.update({f"score[{it}]": float(s[i]), f"se[{it}]": float(se[i]), f"ci_low[{it}]": float(s[i] - z * se[i]),
f"ci_high[{it}]": float(s[i] + z * se[i]), f"worth[{it}]": float(worth[i]), f"rank[{it}]": float(ranks[i]),
f"shown[{it}]": float(shown[i]), f"first_choices[{it}]": float(O[i]), f"first_expected[{it}]": float(E[i])})
# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot_scores, boot_failed = [], 0
if reps > 0:
counts = pc.boot_counts(w_rank, unit, reps, seed)
for r in range(reps):
wb = counts[r][st_rank]
if not pc.strongly_connected(pc.pl_graph(st_choice, mem_stage, mem_item, wb, k)):
boot_failed += 1
continue
try:
boot_scores.append(pc.fit_pl(st_choice, mem_stage, mem_item, wb, k)["scores"])
except (RuntimeError, np.linalg.LinAlgError):
boot_failed += 1
boot_scores = np.array(boot_scores) if boot_scores else np.zeros((0, k))
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
# %% Assumptions
thin = [f"{it} ({int(shown[i])})" for i, it in enumerate(items) if shown[i] < 10]
assumptions = [
{"key": "connectivity", "label": "Connected rankings", "status": "pass",
"detail": "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."},
{"key": "fit", "label": "First choices match the model", "status": "warn" if abs(zr[worst]) > 3 else "pass",
"detail": f"Largest standardized gap: {items[worst]}, first in {O[worst]:.0f} rankings against {E[worst]:.1f} expected (z = {zr[worst]:.2f})"
+ (" — the model misses this item's first choices." if abs(zr[worst]) > 3 else ".")},
{"key": "sample_size", "label": "Rankings per item", "status": "warn" if thin else "pass",
"detail": "In fewer than 10 rankings: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item is in at least 10 rankings (fewest {int(shown.min())})."},
{"key": "independence", "label": "Independent rankings", "status": "info",
"detail": f"Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples {unit_label}."},
]
# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols_t = [{"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": "shown", "label": "Rankings", "type": "number"},
{"key": "first", "label": "Ranked first", "type": "number"}, {"key": "expected", "label": "Expected first", "type": "number"}]
if blo is not None:
cols_t += [{"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": float(se[i]), "ci_low": float(s[i] - z * se[i]),
"ci_high": float(s[i] + z * se[i]), "worth": float(worth[i]), "shown": float(shown[i]), "first": float(O[i]), "expected": float(E[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)
fit_rows = [{"stat": "Rankings", "value": float(n_rank)}, {"stat": "Choices", "value": float(len(st_choice))},
{"stat": "Log-likelihood", "value": loglik}, {"stat": "Log-likelihood, equal worths", "value": loglik0},
{"stat": "LR χ² vs equal worths", "value": lr}, {"stat": "LR p", "value": values["lr_p"]},
{"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being ranked first among all {k})", "columns": cols_t, "rows": rows},
{"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows}]
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", [float(s[i] - z * se[i]) for i in order], "numeric"),
"high": cs.col("Upper", [float(s[i] + z * se[i]) for i in order], "numeric"),
}, controls={"reference": 0})]
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"Plackett–Luce model: worths are log-worths centered to sum to 0; the last item ({items[-1]}) was the reference in the fit. "
f"{'Lower' if better == 'lower' else 'Higher'} values of {col_v} are better. {partial} of {n_rank} rankings leave some shown items unranked; "
f"those items stay among the alternatives at every step. Newton iterations: {fit['iterations']}."]
if reps > 0:
notes.append(f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); "
f"{boot_failed} skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.")
summary = f"Plackett–Luce model for {k} items from {n_rank} rankings: {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 ".")
cs.publish({
"method": "measurement.plackett_luce",
"methodVersion": "1.0.0",
"title": "Plackett–Luce model",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_rank),
"summary": summary,
"apa": f"Plackett–Luce model: LR χ²({npar}) = {cs.fmt_num(lr)}, {cs.fmt_p(values['lr_p'])}",
"statistics": [{"key": "lr", "label": "LR χ²", "value": 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,
})
mango has the highest worth. Its share, 26%, is its chance of being picked first if every fruit were on the table. The bootstrap resamples whole rankings: the leader stays on top in 89% of them, and the rank intervals show which places are still open.
The fit check compares each fruit's first places with what the worths predict, given which fruits each taster saw. The largest gap is 1.13 standard deviations; beyond 3 the model misses that item.
Scores work too: set Which values are better to Higher. When the same panel produced several rankings, set it as the cluster so the bootstrap resamples whole panels.
Plackett–Luce model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 98.0%
Plots
View data
| Worth (log) | Upper | Item | Lower |
|---|---|---|---|
| 0.7604 | 0.9882 | mango | 0.5326 |
| 0.5478 | 0.7845 | peach | 0.3111 |
| 0.3851 | 0.6220 | melon | 0.1482 |
| −0.0653 | 0.1708 | pear | −0.3013 |
| −0.1676 | 0.0660 | plum | −0.4011 |
| −0.5964 | −0.3467 | lemon | −0.8460 |
| −0.8642 | −0.5987 | lime | −1.130 |
View data
| Item | Share of resamples |
|---|---|
| mango | 0.9800 |
| peach | 0.0200 |
| melon | 0 |
| pear | 0 |
| plum | 0 |
| lemon | 0 |
| lime | 0 |
Assumptions
- Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
- First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
- Rankings per item — Every item is in at least 10 rankings (fewest 101).
- Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples whole values of panel.
Worths (log scale, centered; share = chance of being ranked first among all 7)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.9800 | 1 | 1 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.0200 | 2 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.44 |
- Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Higher values of score are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
- Bootstrap: 100 of 100 resamples of whole values of panel refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.
The exact R script · R R version 4.5.1 (2025-06-13)
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 2aa873d158f2e4e5
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs_publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
library(codesplashr)
# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r <- "taster"
col_i <- "fruit"
col_v <- "score"
col_c <- "panel"
cols <- unique(c(col_r, col_i, col_v, col_c))
df <- as.data.frame(nanoparquet::read_parquet("tests/parity/fixtures/hme_rankings.parquet", col_select = cols))
stored_levels <- c("lemon", "lime", "mango", "melon", "peach", "pear", "plum")
n_input <- nrow(df)
need <- c(col_r, col_i, col_c)
df <- df[stats::complete.cases(df[need]), , drop = FALSE] # rows without a ranking, item or cluster can't be placed
warnings <- list()
if (n_input - nrow(df) > 0) warnings <- c(warnings, cs_warning("CS_W_ROWS_DROPPED", dropped = n_input - nrow(df), total = n_input))
if (nrow(df) == 0) cs_error("CS_E_NO_ROWS")
value <- as.numeric(df[[col_v]])
cs_check_finite(value, col_v) # infinite values stop the run (registry/errors.yaml)
item_text <- as.character(df[[col_i]])
levels_i <- if (!is.null(stored_levels)) stored_levels else sort(unique(item_text), method = "radix")
rid <- as.character(df[[col_r]])
names_r <- unique(rid)
code <- match(rid, names_r)
dup <- duplicated(paste(code, item_text, sep = "\r"))
if (any(dup)) cs_error("CS_E_INVALID_VALUES", column = col_i, requirement = "listed at most once in each ranking", count = sum(dup))
if (all(is.na(value))) cs_error("CS_E_ALL_MISSING", column = col_v)
better <- "higher"
reps <- 100
conf <- 0.95
seed <- 42 # portable Wichmann–Hill stream: Python draws the same resamples for this seed
# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
item_all <- match(item_text, levels_i)
stg <- cs_pc_pl_stages(code, item_all, value, better)
if (stg$tied > 0) cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = sprintf("ranking %s has tied ranks; break the ties or leave that ranking out", names_r[stg$tied]))
if (length(unique(item_text)) < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = length(unique(item_text)))
if (length(stg$st_choice) == 0) cs_error("CS_E_TOO_FEW_ROWS", what = "The Plackett–Luce model", min = 2, n = 0) # no ranking shows two or more items
n_rank <- stg$n_rank
used <- sort(unique(stg$mem_item))
items <- levels_i[used]
k <- length(items)
if (k < 2) cs_error("CS_E_TOO_FEW_GROUPS", column = col_i, min = 2, k = k)
remap <- rep(0L, length(levels_i))
remap[used] <- seq_len(k)
st_rank <- stg$st_rank
st_choice <- remap[stg$st_choice]
mem_stage <- stg$mem_stage
mem_item <- remap[stg$mem_item]
w_rank <- rep(1, n_rank)
w_stage <- w_rank[st_rank]
adj <- cs_pc_pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if (!cs_pc_strongly_connected(adj)) {
cs_error("CS_E_UNDEFINED", what = "The Plackett–Luce model", reason = "some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
}
if (!is.null(col_c)) {
cv <- as.character(df[[col_c]])
first_row <- match(seq_len(n_rank), code)
cl <- cv[first_row]
unit <- match(cl, unique(cl))
unit_label <- paste("whole values of", col_c)
} else {
unit <- NULL
unit_label <- "single rankings"
}
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
fit <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, w_stage, k), error = function(e) {
if (grepl("singular", conditionMessage(e))) cs_error("CS_E_COLLINEAR")
cs_error("CS_E_NO_CONVERGENCE", what = "The Plackett–Luce model")
})
s <- fit$scores
se <- sqrt(diag(fit$cov))
z <- cs_pc_z(conf)
worth <- exp(s) / sum(exp(s))
ranks <- cs_pc_point_ranks(s)
loglik <- fit$loglik
loglik0 <- fit$loglik_null
npar <- k - 1
lr <- 2 * (loglik - loglik0)
ff <- cs_pc_pl_first_fit(st_rank, st_choice, mem_stage, mem_item, fit$raw, w_rank, k)
worst <- which.max(abs(ff$z))
pairs <- unique((st_rank[mem_stage] - 1) * k + mem_item) # rankings in which each item takes part
shown <- tabulate((pairs - 1) %% k + 1, nbins = k)
values <- list(n_rankings = n_rank, n_choices = length(st_choice), items = k, partial = stg$partial, n_left_out = n_input - nrow(df),
loglik = loglik, loglik_null = loglik0, npar = npar, lr = lr, lr_df = npar, lr_p = cs_pc_lr_p(lr, npar),
aic = -2 * loglik + 2 * npar, bic = -2 * loglik + npar * log(n_rank), fit_max_z = abs(ff$z[worst]),
fit_item = items[worst], iterations = fit$iterations)
for (i in seq_len(k)) {
it <- items[i]
values[[sprintf("score[%s]", it)]] <- s[i]
values[[sprintf("se[%s]", it)]] <- se[i]
values[[sprintf("ci_low[%s]", it)]] <- s[i] - z * se[i]
values[[sprintf("ci_high[%s]", it)]] <- s[i] + z * se[i]
values[[sprintf("worth[%s]", it)]] <- worth[i]
values[[sprintf("rank[%s]", it)]] <- ranks[i]
values[[sprintf("shown[%s]", it)]] <- shown[i]
values[[sprintf("first_choices[%s]", it)]] <- ff$O[i]
values[[sprintf("first_expected[%s]", it)]] <- ff$E[i]
}
# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot <- list()
boot_failed <- 0
if (reps > 0) {
counts <- cs_pc_boot_counts(w_rank, unit, reps, seed)
for (r in seq_len(reps)) {
wb <- counts[r, ][st_rank]
if (!cs_pc_strongly_connected(cs_pc_pl_graph(st_choice, mem_stage, mem_item, wb, k))) {
boot_failed <- boot_failed + 1
next
}
res <- tryCatch(cs_pc_fit_pl(st_choice, mem_stage, mem_item, wb, k)$scores, error = function(e) NULL)
if (is.null(res)) boot_failed <- boot_failed + 1 else boot[[length(boot) + 1]] <- res
}
}
boot_scores <- if (length(boot)) do.call(rbind, boot) else matrix(0, 0, k)
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)
}
# %% Assumptions
thin <- sprintf("%s (%d)", items, as.integer(shown))[shown < 10]
assumptions <- list(
list(key = "connectivity", label = "Connected rankings", status = "pass",
detail = "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."),
list(key = "fit", label = "First choices match the model", status = if (abs(ff$z[worst]) > 3) "warn" else "pass",
detail = paste0(sprintf("Largest standardized gap: %s, first in %.0f rankings against %.1f expected (z = %.2f)", items[worst], ff$O[worst], ff$E[worst], ff$z[worst]),
if (abs(ff$z[worst]) > 3) " — the model misses this item's first choices." else ".")),
list(key = "sample_size", label = "Rankings per item", status = if (length(thin)) "warn" else "pass",
detail = if (length(thin)) paste0("In fewer than 10 rankings: ", paste(utils::head(thin, 8), collapse = ", "), if (length(thin) > 8) " …" else "", ".") else
sprintf("Every item is in at least 10 rankings (fewest %d).", as.integer(min(shown)))),
list(key = "independence", label = "Independent rankings", status = "info",
detail = sprintf("Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples %s.", unit_label))
)
# %% Result
ord <- order(-round(s, 10), method = "radix")
pct <- sprintf("%.0f%%", conf * 100)
cols_t <- 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 = "shown", label = "Rankings", type = "number"),
list(key = "first", label = "Ranked first", type = "number"), list(key = "expected", label = "Expected first", type = "number"))
if (!is.null(bsum)) {
cols_t <- c(cols_t, 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 = se[i], ci_low = s[i] - z * se[i], ci_high = s[i] + z * se[i],
worth = worth[i], shown = shown[i], first = ff$O[i], expected = ff$E[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
})
fit_rows <- list(list(stat = "Rankings", value = n_rank), list(stat = "Choices", value = length(st_choice)),
list(stat = "Log-likelihood", value = loglik), list(stat = "Log-likelihood, equal worths", value = loglik0),
list(stat = "LR χ² vs equal worths", value = lr), list(stat = "LR p", value = values$lr_p),
list(stat = "AIC", value = values$aic), list(stat = "BIC", value = values$bic))
tables <- list(list(key = "items", title = sprintf("Worths (log scale, centered; share = chance of being ranked first among all %d)", k), columns = cols_t, rows = rows),
list(key = "fit", title = "Model fit", columns = list(list(key = "stat", label = "", type = "string"), list(key = "value", label = "Value", type = "number")), rows = fit_rows))
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", (s - z * se)[ord], "numeric"),
high = cs_col("Upper", (s + z * se)[ord], "numeric")
), controls = list(reference = 0)))
if (!is.null(bsum)) {
charts[[2]] <- 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("Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (%s) was the reference in the fit. %s values of %s are better. %d of %d rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: %d.",
items[k], if (better == "lower") "Lower" else "Higher", col_v, as.integer(stg$partial), as.integer(n_rank), as.integer(fit$iterations)))
if (reps > 0) {
notes[[2]] <- sprintf("Bootstrap: %d of %d resamples of %s refitted (seed %s; the same resamples in Python and R); %d skipped because a resample's rankings weren'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("Plackett–Luce model for %d items from %d rankings: %s has the highest worth", k, as.integer(n_rank), 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 ".")
cs_publish(list(
method = "measurement.plackett_luce",
methodVersion = "1.0.0",
title = "Plackett–Luce model",
engine = cs_engine_info("stats", "codesplashr"),
n = as.integer(n_rank),
summary = summary,
apa = sprintf("Plackett–Luce model: LR χ²(%d) = %s, %s", as.integer(npar), cs_fmt_num(lr), cs_fmt_p(values$lr_p)),
statistics = list(list(key = "lr", label = "LR χ²", value = 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
))
Plackett–Luce model: LR χ²(6) = 115.08, p < .001
- LR χ²
- 115.08
- p
- < .001
- AIC
- 1259.38
- mango first
- 98.0%
To keep this page light, the plots are shown once, under the R tab.
Assumptions
- Connected rankings — Every item is ranked above and below its way to every other item, so the estimates are finite and unique.
- First choices match the model — Largest standardized gap: lemon, first in 15 rankings against 11.4 expected (z = 1.13).
- Rankings per item — Every item is in at least 10 rankings (fewest 101).
- Independent rankings — Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples whole values of panel.
Worths (log scale, centered; share = chance of being ranked first among all 7)
| Rank | Item | Worth (log) | SE | 95% CI low | 95% CI high | Share | Rankings | Ranked first | Expected first | First in resamples | Rank low | Rank high |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 1 | mango | 0.7604 | 0.1162 | 0.5326 | 0.9882 | 0.2643 | 112 | 41 | 39.595 | 0.9800 | 1 | 1 |
| 2 | peach | 0.5478 | 0.1208 | 0.3111 | 0.7845 | 0.2137 | 101 | 27 | 29.383 | 0.0200 | 2 | 3 |
| 3 | melon | 0.3851 | 0.1209 | 0.1482 | 0.6220 | 0.1816 | 102 | 27 | 25.873 | 0 | 2 | 3 |
| 4 | pear | −0.0653 | 0.1204 | −0.3013 | 0.1708 | 0.1158 | 104 | 14 | 18.017 | 0 | 4 | 5 |
| 5 | plum | −0.1676 | 0.1192 | −0.4011 | 0.0660 | 0.1045 | 115 | 19 | 17.293 | 0 | 4 | 5 |
| 6 | lemon | −0.5964 | 0.1274 | −0.8460 | −0.3467 | 0.0681 | 112 | 15 | 11.410 | 0 | 6 | 7 |
| 7 | lime | −0.8642 | 0.1354 | −1.130 | −0.5987 | 0.0521 | 108 | 7 | 8.429 | 0 | 6 | 7 |
Model fit
| Value | |
|---|---|
| Rankings | 150 |
| Choices | 541 |
| Log-likelihood | −623.69 |
| Log-likelihood, equal worths | −681.23 |
| LR χ² vs equal worths | 115.08 |
| LR p | 1.754e-22 |
| AIC | 1259.38 |
| BIC | 1277.44 |
- Plackett–Luce model: worths are log-worths centered to sum to 0; the last item (plum) was the reference in the fit. Higher values of score are better. 56 of 150 rankings leave some shown items unranked; those items stay among the alternatives at every step. Newton iterations: 4.
- Bootstrap: 100 of 100 resamples of whole values of panel refitted (seed 42; the same resamples in Python and R); 0 skipped because a resample's rankings weren'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
# Rankings (Plackett–Luce)
# Generated by CodeSplash Analytics 1.0.0 on 2026-11-09 · method measurement.plackett_luce 1.0.0 · spec 2aa873d158f2e4e5
# Dataset: hme_rankings (version 1)
# Runs on its own: outside the app, cs.publish() writes $CS_RESULT_PATH or prints the result JSON.
# %% Setup
import json
import numpy as np
import pandas as pd
import codesplash as cs
from codesplash.errors import check_finite
from codesplash.stats import paired_comparison as pc # twin of R's cs_pc_* (R/stats_paired_comparison.R)
# %% Data (long rankings: one row per item shown; a missing rank = shown but not ranked)
col_r, col_i, col_v = "taster", "fruit", "score"
col_c = "panel"
cols = [c for c in (col_r, col_i, col_v, col_c) if c is not None]
df = pd.read_parquet("tests/parity/fixtures/hme_rankings.parquet", columns=list(dict.fromkeys(cols)))
stored = json.loads("{\"fruit\":[\"lemon\",\"lime\",\"mango\",\"melon\",\"peach\",\"pear\",\"plum\"],\"panel\":[\"panel 1\",\"panel 2\",\"panel 3\",\"panel 4\",\"panel 5\",\"panel 6\",\"panel 7\",\"panel 8\",\"panel 9\",\"panel 10\"],\"score\":null,\"taster\":null}")
n_input = len(df)
need = [c for c in (col_r, col_i, col_c) if c is not None]
df = df.dropna(subset=need).reset_index(drop=True) # rows without a ranking, item or cluster can't be placed
warnings = []
if n_input - len(df):
warnings.append(cs.cs_warning("CS_W_ROWS_DROPPED", dropped=n_input - len(df), total=n_input))
if not len(df):
cs.cs_error("CS_E_NO_ROWS")
value = df[col_v].to_numpy(dtype=float)
check_finite(value, col_v) # infinite values stop the run (registry/errors.yaml)
item_text = df[col_i].astype(str).to_numpy()
levels = stored.get(col_i) or sorted(set(item_text))
rid = df[col_r].astype(str).to_numpy()
names = list(pd.unique(rid))
code = np.array([names.index(x) for x in rid], dtype=np.int64)
dup = pd.Series(list(zip(code, item_text))).duplicated().to_numpy()
if dup.any():
cs.cs_error("CS_E_INVALID_VALUES", column=col_i, requirement="listed at most once in each ranking", count=int(dup.sum()))
if np.isnan(value).all():
cs.cs_error("CS_E_ALL_MISSING", column=col_v)
better = "higher"
reps = 100
conf = 0.95
seed = 42 # portable Wichmann–Hill stream: R draws the same resamples for this seed
# %% Choice stages (each ranking = a sequence of choices from the items not yet chosen)
pos_all = {it: i for i, it in enumerate(levels)}
item_all = np.array([pos_all[x] for x in item_text], dtype=np.int64)
st_rank, st_choice, mem_stage, mem_item, n_rank, partial, tied = pc.pl_stages(code, item_all, value, better)
if tied >= 0:
cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason=f"ranking {names[tied]} has tied ranks; break the ties or leave that ranking out")
if len(set(item_text)) < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=len(set(item_text)))
if len(st_choice) == 0: # no ranking shows two or more items
cs.cs_error("CS_E_TOO_FEW_ROWS", what="The Plackett–Luce model", min=2, n=0)
used = sorted(set(mem_item.tolist()))
items = [levels[i] for i in used]
k = len(items)
if k < 2:
cs.cs_error("CS_E_TOO_FEW_GROUPS", column=col_i, min=2, k=k)
remap = np.full(len(levels), -1, dtype=np.int64)
remap[used] = np.arange(k)
st_choice, mem_item = remap[st_choice], remap[mem_item]
w_rank = np.ones(n_rank)
w_stage = w_rank[st_rank]
adj = pc.pl_graph(st_choice, mem_stage, mem_item, w_stage, k)
if not pc.strongly_connected(adj):
cs.cs_error("CS_E_UNDEFINED", what="The Plackett–Luce model", reason="some items are never ranked below (or never above) the rest, so their worths run off to infinity; add rankings that link them")
if col_c is not None:
cv = df[col_c].astype(str).to_numpy()
first_row = np.array([np.flatnonzero(code == g)[0] for g in range(n_rank)])
cl_names = list(pd.unique(cv[first_row]))
unit = np.array([cl_names.index(x) for x in cv[first_row]], dtype=np.int64)
unit_label = f"whole values of {col_c}"
else:
unit = None
unit_label = "single rankings"
# %% Fit (maximum likelihood: Newton steps on log-worths, the last item as reference, then centered)
try:
fit = pc.fit_pl(st_choice, mem_stage, mem_item, w_stage, k)
except RuntimeError:
cs.cs_error("CS_E_NO_CONVERGENCE", what="The Plackett–Luce model")
except np.linalg.LinAlgError:
cs.cs_error("CS_E_COLLINEAR")
s = fit["scores"]
se = np.sqrt(np.diag(fit["cov"]))
z = pc.z_value(conf)
worth = np.exp(s) / np.exp(s).sum()
ranks = pc.point_ranks(s)
loglik, loglik0 = fit["loglik"], fit["loglik_null"]
npar = k - 1
lr = 2 * (loglik - loglik0)
O, E, zr = pc.pl_first_choice_fit(st_rank, st_choice, mem_stage, mem_item, fit["raw"], w_rank, k)
worst = int(np.argmax(np.abs(zr)))
pairs = np.unique(st_rank[mem_stage] * k + mem_item) # rankings in which each item takes part
shown = np.bincount(pairs % k, minlength=k).astype(float)
values = {"n_rankings": float(n_rank), "n_choices": float(len(st_choice)), "items": float(k), "partial": float(partial),
"n_left_out": float(n_input - len(df)), "loglik": loglik, "loglik_null": loglik0, "npar": float(npar), "lr": lr,
"lr_df": float(npar), "lr_p": pc.lr_p(lr, npar), "aic": -2 * loglik + 2 * npar, "bic": -2 * loglik + npar * np.log(n_rank),
"fit_max_z": float(np.abs(zr[worst])), "fit_item": items[worst], "iterations": float(fit["iterations"])}
for i, it in enumerate(items):
values.update({f"score[{it}]": float(s[i]), f"se[{it}]": float(se[i]), f"ci_low[{it}]": float(s[i] - z * se[i]),
f"ci_high[{it}]": float(s[i] + z * se[i]), f"worth[{it}]": float(worth[i]), f"rank[{it}]": float(ranks[i]),
f"shown[{it}]": float(shown[i]), f"first_choices[{it}]": float(O[i]), f"first_expected[{it}]": float(E[i])})
# %% Bootstrap of the order (shared Wichmann–Hill stream; rankings, or whole clusters)
boot_scores, boot_failed = [], 0
if reps > 0:
counts = pc.boot_counts(w_rank, unit, reps, seed)
for r in range(reps):
wb = counts[r][st_rank]
if not pc.strongly_connected(pc.pl_graph(st_choice, mem_stage, mem_item, wb, k)):
boot_failed += 1
continue
try:
boot_scores.append(pc.fit_pl(st_choice, mem_stage, mem_item, wb, k)["scores"])
except (RuntimeError, np.linalg.LinAlgError):
boot_failed += 1
boot_scores = np.array(boot_scores) if boot_scores else np.zeros((0, k))
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
# %% Assumptions
thin = [f"{it} ({int(shown[i])})" for i, it in enumerate(items) if shown[i] < 10]
assumptions = [
{"key": "connectivity", "label": "Connected rankings", "status": "pass",
"detail": "Every item is ranked above and below its way to every other item, so the estimates are finite and unique."},
{"key": "fit", "label": "First choices match the model", "status": "warn" if abs(zr[worst]) > 3 else "pass",
"detail": f"Largest standardized gap: {items[worst]}, first in {O[worst]:.0f} rankings against {E[worst]:.1f} expected (z = {zr[worst]:.2f})"
+ (" — the model misses this item's first choices." if abs(zr[worst]) > 3 else ".")},
{"key": "sample_size", "label": "Rankings per item", "status": "warn" if thin else "pass",
"detail": "In fewer than 10 rankings: " + ", ".join(thin[:8]) + (" …" if len(thin) > 8 else "") + "." if thin else f"Every item is in at least 10 rankings (fewest {int(shown.min())})."},
{"key": "independence", "label": "Independent rankings", "status": "info",
"detail": f"Not checked from data: rankings are treated as independent, and each choice ignores the items already chosen (independence of irrelevant alternatives). The bootstrap resamples {unit_label}."},
]
# %% Result
order = np.argsort(-np.round(s, 10), kind="stable")
pct = f"{conf:.0%}"
cols_t = [{"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": "shown", "label": "Rankings", "type": "number"},
{"key": "first", "label": "Ranked first", "type": "number"}, {"key": "expected", "label": "Expected first", "type": "number"}]
if blo is not None:
cols_t += [{"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": float(se[i]), "ci_low": float(s[i] - z * se[i]),
"ci_high": float(s[i] + z * se[i]), "worth": float(worth[i]), "shown": float(shown[i]), "first": float(O[i]), "expected": float(E[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)
fit_rows = [{"stat": "Rankings", "value": float(n_rank)}, {"stat": "Choices", "value": float(len(st_choice))},
{"stat": "Log-likelihood", "value": loglik}, {"stat": "Log-likelihood, equal worths", "value": loglik0},
{"stat": "LR χ² vs equal worths", "value": lr}, {"stat": "LR p", "value": values["lr_p"]},
{"stat": "AIC", "value": values["aic"]}, {"stat": "BIC", "value": values["bic"]}]
tables = [{"key": "items", "title": f"Worths (log scale, centered; share = chance of being ranked first among all {k})", "columns": cols_t, "rows": rows},
{"key": "fit", "title": "Model fit", "columns": [{"key": "stat", "label": "", "type": "string"}, {"key": "value", "label": "Value", "type": "number"}], "rows": fit_rows}]
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", [float(s[i] - z * se[i]) for i in order], "numeric"),
"high": cs.col("Upper", [float(s[i] + z * se[i]) for i in order], "numeric"),
}, controls={"reference": 0})]
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"Plackett–Luce model: worths are log-worths centered to sum to 0; the last item ({items[-1]}) was the reference in the fit. "
f"{'Lower' if better == 'lower' else 'Higher'} values of {col_v} are better. {partial} of {n_rank} rankings leave some shown items unranked; "
f"those items stay among the alternatives at every step. Newton iterations: {fit['iterations']}."]
if reps > 0:
notes.append(f"Bootstrap: {len(boot_scores)} of {reps} resamples of {unit_label} refitted (seed {seed}; the same resamples in Python and R); "
f"{boot_failed} skipped because a resample's rankings weren't connected or didn't converge. Intervals are percentile intervals.")
summary = f"Plackett–Luce model for {k} items from {n_rank} rankings: {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 ".")
cs.publish({
"method": "measurement.plackett_luce",
"methodVersion": "1.0.0",
"title": "Plackett–Luce model",
"engine": cs.engine_info("numpy", "scipy", "codesplash"),
"n": int(n_rank),
"summary": summary,
"apa": f"Plackett–Luce model: LR χ²({npar}) = {cs.fmt_num(lr)}, {cs.fmt_p(values['lr_p'])}",
"statistics": [{"key": "lr", "label": "LR χ²", "value": 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 choix
import pandas as pd
df = pd.read_csv("rankings.csv") # taster, fruit, rank (complete rankings only)
items = sorted(df["fruit"].unique())
rankings = [[items.index(f) for f in g.sort_values("rank")["fruit"]] for _, g in df.groupby("taster")]
print(dict(zip(items, choix.opt_rankings(len(items), rankings))))library(PlackettLuce)
df <- read.csv("rankings.csv") # taster, fruit, rank (0 = shown but not ranked)
R <- as.rankings(df, id = "taster", item = "fruit", rank = "rank")
fit <- PlackettLuce(R, npseudo = 0)
coef(fit, log = TRUE) # reference = first item; center to comparechoix's opt_rankings reads each list as a ranking of exactly those items. A top-k ranking needs the shown-but-unranked items too, which the card and PlackettLuce handle.
Check your understanding
CheckpointCheck yourself
Three items have worths 3, 2 and 1. What is the probability of the ranking (first, third, second) under Plackett–Luce?
Show the answer
Answer: 0.1667
.
Check yourself
An item's share is 0.35. What does that mean?
Show the answer
Answer: a
The share is the worth divided by the sum of all worths: the model's chance of a first place among all items. The observed share of first places depends on which items each ranking showed.
Check yourself
Two items in one ranking share rank 2. What does the card do?
Show the answer
Answer: c
The basic Plackett–Luce model has no tie outcome, so a tied ranking can't be scored as it stands.
Recap
Recap- Plackett–Luce reads a ranking as successive choices, each from the items still available.
- Keep shown-but-unranked items, with a missing rank, so top-k rankings are scored correctly.
- Report shares and bootstrap rank intervals, and resample whole judges or panels when they made several rankings.
Concepts in this lesson