## https://github.com/stan-dev/example-models/tree/master/knitr/bradley-terry
library(rstan)
options(mc.cores = 4)
rstan_options(auto_write = TRUE)\[\begin{align} \text{Pr}(i \succ j) &= \frac{\nu_i}{\nu_i + \nu_j} = \frac{\exp \alpha_i}{\exp \alpha_i + \exp \alpha_j} = \frac{\dfrac{\exp \alpha_i}{\exp \alpha_j}} {\dfrac{\exp \alpha_i}{\exp \alpha_j} + \dfrac{\exp \alpha_j}{\exp \alpha_j}} = \frac{\exp(\alpha_i - \alpha_j)}{1 + \exp(\alpha_i - \alpha_j)}\\ \text{logit Pr}(i \succ j) &= \log \frac{\dfrac{\exp \alpha_i}{\exp \alpha_i + \exp \alpha_j}} {\dfrac{\exp \alpha_j}{\exp \alpha_i + \exp \alpha_j}} = \log \frac{\exp \alpha_i}{\exp \alpha_j} = \alpha_i - \alpha_j \end{align}\]
K <- 50 # number of potential players
alpha <- rnorm(K) |> # mean centered player abilities
scale(scale = FALSE) |>
sort()
N <- K^2 # number of possible matches
dat <- replicate(N, sample(1:K, 2)) |> # but who plays whom is random
t() |>
as.data.frame() |>
setNames(c("player0", "player1"))
## Draw match outcome given two players and their abilities
rbtl <- function(plr0, plr1, alpha) {
pwin1 <- plogis(alpha[plr1] - alpha[plr0]) # winning prob for player 1
rbinom(length(pwin1), 1, pwin1)
}
dat$y <- rbtl(dat$player0, dat$player1, alpha)datlist <- c(dat,
K = c(dat$player0, dat$player1) |> unique() |> length(), # actual players
N = nrow(dat)
)
s <- "
data {
int<lower=1> K; // number of players
int<lower=1> N; // number of matches
array[N] int<lower=1, upper=K> player0; // player 0 indicator
array[N] int<lower=1, upper=K> player1; // player 1 indicator
array[N] int<lower=0, upper=1> y; // match outcome
}
parameters {
//vector[K] alpha;
sum_to_zero_vector[K] alpha; // player ability
}
model {
alpha ~ normal(0, 1);
y ~ bernoulli_logit(alpha[player1] - alpha[player0]);
}
"
m <- stan(model_code = s, data = datlist)
print(m, pars = c("alpha[1]", "alpha[50]"), probs = c(.025, .975))## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## alpha[1] -1.44 0 0.23 -1.91 -1.00 6751 1
## alpha[50] 2.48 0 0.30 1.91 3.11 5790 1
##
## Samples were drawn using NUTS(diag_e) at Wed Nov 25 18:09:18 2026.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
## Parameter recovery
extract(m)$alpha |>
colMeans() |>
plot(alpha, y = _, col = "darkblue")
abline(0, 1)s <- "
data {
int<lower=1> K;
int<lower=1> N;
array[N] int<lower=1, upper=K> player0;
array[N] int<lower=1, upper=K> player1;
array[N] int<lower=0, upper=1> y;
}
parameters {
real<lower=0> sigma; // player variation
//vector[K] alpha;
sum_to_zero_vector[K] alpha;
}
model {
sigma ~ lognormal(0, .5);
alpha ~ normal(0, sigma);
y ~ bernoulli_logit(alpha[player1] - alpha[player0]);
}
"
m <- stan(model_code = s, data = datlist)## recompiling to avoid crashing R session
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## sigma 0.99 0 0.11 0.80 1.23 4220 1
## alpha[1] -1.43 0 0.23 -1.89 -0.98 5700 1
## alpha[50] 2.47 0 0.30 1.89 3.10 5835 1
##
## Samples were drawn using NUTS(diag_e) at Wed Nov 25 18:10:24 2026.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).
K <- 50 # players
J <- 3 # players per team
N <- K^2 * J # matches
alpha <- rnorm(K) |> # mean centered player abilities
scale(scale = FALSE) |>
sort()
players <- replicate(N,
sample(1:K, 2 * J)) # draw w/o replacement
team0 <- players[ 1:J, ] |> t() # for distinct teams
team1 <- players[-(1:J), ] |> t()
## Draw match outcome given two teams of 3 players each and their abilities
rbtlteam <- function(tm0, tm1, alpha) {
N <- nrow(tm0)
pwin1 <- rep(0, N)
for(i in 1:N) {
pwin1[i] <- plogis(sum(alpha[tm1[i, ]]) - sum(alpha[tm0[i, ]]))
}
rbinom(N, 1, pwin1)
}
datlist <- list(team0 = team0, team1 = team1,
y = rbtlteam(team0, team1, alpha),
K = c(players) |> unique() |> length(), # actual players
J = ncol(team0),
N = nrow(team0)
)s <- "
data {
int<lower=1> K; // players
int<lower=1> J; // players per team
int<lower=1> N; // matches
array[N, J] int<lower=1, upper=K> team0; // team 0 players
array[N, J] int<lower=1, upper=K> team1; // team 1 players
array[N] int<lower=0, upper=1> y; // winner team
}
parameters {
real<lower=0> sigma;
//vector[K] alpha;
sum_to_zero_vector[K] z;
}
transformed parameters {
vector[K] alpha = sigma * z; // alpha = 0 + sigma * alpha_z;
}
model {
sigma ~ lognormal(0, 0.5);
z ~ std_normal();
for (i in 1:N) {
// additive Bradley-Terry model
y[i] ~ bernoulli_logit(sum(alpha[team1[i]]) - sum(alpha[team0[i]]));
}
}
"
m <- stan(model_code = s, data = datlist)## recompiling to avoid crashing R session
## Warning: Bulk Effective Samples Size (ESS) is too low, indicating posterior means and medians may be unreliable.
## Running the chains for more iterations may help. See
## https://mc-stan.org/misc/warnings.html#bulk-ess
## Warning: Tail Effective Samples Size (ESS) is too low, indicating posterior variances and tail quantiles may be unreliable.
## Running the chains for more iterations may help. See
## https://mc-stan.org/misc/warnings.html#tail-ess
## Inference for Stan model: anon_model.
## 4 chains, each with iter=2000; warmup=1000; thin=1;
## post-warmup draws per chain=1000, total post-warmup draws=4000.
##
## mean se_mean sd 2.5% 97.5% n_eff Rhat
## sigma 0.98 0.01 0.10 0.80 1.19 174 1.03
## alpha[1] -1.63 0.00 0.10 -1.82 -1.45 5156 1.00
## alpha[50] 2.40 0.00 0.11 2.20 2.62 4256 1.00
##
## Samples were drawn using NUTS(diag_e) at Wed Nov 25 18:14:43 2026.
## For each parameter, n_eff is a crude measure of effective sample size,
## and Rhat is the potential scale reduction factor on split chains (at
## convergence, Rhat=1).