MCPcopy Create free account
hub / github.com/CodeClash-ai/CodeClash / BradleyTerryFitter

Class BradleyTerryFitter

codeclash/analysis/metrics/elo.py:313–485  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

311 boot_matrix["ALL"] = {k: [v[0], v[1]] for k, v in combined.items()}
312 return boot_matrix
313
314 def print_matrix(self) -> None:
315 for game, matchups in sorted(self.win_matrix.items()):
316 print(f"\n{game}:")
317 for (p1, p2), (w1, w2) in sorted(matchups.items()):
318 if game == "ALL":
319 print(f" {p1} vs {p2}: {w1:.3f}-{w2:.3f}")
320 else:
321 print(f" {p1} vs {p2}: {w1:.0f}-{w2:.0f}")
322
323
324class BradleyTerryFitter:
325 def __init__(
326 self,
327 win_matrix: dict[tuple[str, str], list[float]],
328 *,
329 regularization: float = 0.01,
330 compute_uncertainties: bool = True,
331 ):
332 """Fit Bradley-Terry model to a win matrix
333
334 Args:
335 win_matrix: Dictionary mapping player pairs to win counts
336 regularization: L2 regularization strength
337 compute_uncertainties: Whether to compute uncertainties
338 """
339 self.matchups = win_matrix
340 self.regularization = regularization
341 self.compute_uncertainties = compute_uncertainties
342 self.result: dict | None = None
343 """{players: list[str], strengths: np.ndarray, log_likelihood: float}"""
344
345 def _sigmoid(self, x: np.ndarray) -> np.ndarray:
346 return 1 / (1 + np.exp(-x))
347
348 @staticmethod
349 def bt_to_elo(strength: float) -> float:
350 """Convert Bradley-Terry strength to Elo rating.
351
352 Formula: R_i = R_0 + (β/ln(10)) * s_i
353 where β = 400 (ELO_SLOPE), R_0 = 1200 (ELO_BASE)
354 """
355 return ELO_BASE + (ELO_SLOPE / np.log(10)) * strength
356
357 def _negative_log_likelihood(self, strengths: np.ndarray, pairs: list, wins: np.ndarray) -> float:
358 """Negative log-likelihood for Bradley-Terry model with L2 regularization.
359
360 Args:
361 strengths: Array of player strengths (length n_players)
362 pairs: List of (i, j) player index pairs
363 wins: Array of shape (n_pairs, 2) where wins[k] = [w_ij, w_ji]
364
365 Returns:
366 -log(likelihood) + λ * Σ_i s_i^2 (MAP estimate with Gaussian prior)
367 """
368 assert len(wins) == len(pairs)
369 ll = 0.0
370 for k, (i, j) in enumerate(pairs):

Callers 5

_fit_on_matrixMethod · 0.85
runMethod · 0.85
runMethod · 0.85
runMethod · 0.85
elo.pyFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected