Coverage for mt_tools/power_rating.py: 99.70%

271 statements  

« prev     ^ index     » next       coverage.py v7.10.6, created at 2026-11-30 17:31 +0000

1"""MT Power Rating engine: Elo over one age group's season, plus a Massey audit (SB-1805). 

2 

3Pure functions over plain dataclasses: no database, no I/O. Gathering the 

4matches, storing a run and serving it are later slices (SB-1784 design, 

5`docs/03-architecture/power-rating-engine.md`). 

6 

7## The model (parameters approved 2026-11-27, `PARAMS_VERSION`) 

8 

9 E = 1 / (1 + 10^(-(R_team - R_opp + H) / 400)) H = +50 home, -50 away, 0 neutral 

10 S = 1 win, 0.5 draw (a shoot-out is a draw), 0 loss 

11 new R = R + K * G * (S - E) 

12 K = 30 for every competition; 60 for a team's first 8 rated matches 

13 G = 1 for a draw or 1-goal margin, 1.5 for 2, 1.75 for 3 or more (cap) 

14 

15The exchange is equal and opposite unless one side is still on provisional K. 

16Ratings start at 1500, or at a carried-over rating (`carry_over`). 

17 

18## What is rated 

19 

20Regulation scores only: a shoot-out is a draw. A match is **not rated**, and is 

21counted in `matches_excluded`, when it was a forfeit (no football was played) or 

22either side is out of pool (no Homegrown conference at this age group). The 

23caller passes only completed matches in which both sides fielded this age group. 

24 

25## Order 

26 

27Chronological by `match_date`, then `kickoff_time` (a match with no kickoff time 

28goes after the timed ones that day), then `match_id`. Every run replays the 

29season from its first match, so a corrected result lands in date order. 

30 

31## Publication 

32 

33An age group gets a national list only when one island (teams connected by 

34rated matches) holds at least 90% of ranked teams **and** every conference in 

35it has at least 5 matches against other conferences. Otherwise it is shown as 

36conference lists only, and no team carries a tier. Teams with fewer than 

37`MIN_MATCHES` rated matches are unranked: listed, never placed. 

38""" 

39 

40from collections import Counter, defaultdict 

41from collections.abc import Iterable, Mapping 

42from dataclasses import dataclass, replace 

43from datetime import date, time 

44from typing import Literal 

45 

46import numpy as np 

47 

48from mt_tools.leaderboards import TeamTally, conference_of 

49 

50PARAMS_VERSION = "elo-v1" 

51 

52START_RATING = 1500.0 

53SCALE = 400.0 

54K = 30.0 

55PROVISIONAL_MATCHES = 8 # K x PROVISIONAL_K_MULT for a team's first 8 rated matches 

56PROVISIONAL_K_MULT = 2.0 

57HOME_ADVANTAGE = 50.0 # in the expected score only; 0 at a neutral venue 

58MARGIN_CAP = 3 

59ROLLOVER_CARRY = 0.3 # new season start = 1500 + 0.3 * (last final - 1500) 

60 

61MIN_MATCHES = 6 # ranked from this many rated matches 

62LOW_CROSS_CONFERENCE = 3 # flagged under this many matches against other conferences 

63 

64NATIONAL_ISLAND_SHARE = 0.9 

65NATIONAL_MIN_CROSS_CONFERENCE = 5 

66 

67MASSEY_CAP = 4 

68MASSEY_RIDGE = 1.0 

69RANK_GAP_FLAG = 30 # Elo vs Massey places, about the worst 5% at the 2026-11-26 freeze 

70 

71Competition = Literal["league", "flex", "tournament", "cup"] 

72NEUTRAL_COMPETITIONS = frozenset({"tournament", "cup"}) 

73 

74# (key, label, minimum rating). Below the last: no label. 

75TIERS: tuple[tuple[str, str, float], ...] = ( 

76 ("elite", "Elite", 1700.0), 

77 ("contender", "Contender", 1600.0), 

78 ("above_average", "Above average", 1500.0), 

79) 

80 

81EXCLUSION_REASONS = ("forfeit", "out_of_pool_opponent") 

82 

83 

84# --- input --------------------------------------------------------------------- 

85 

86 

87@dataclass(frozen=True) 

88class RatedMatch: 

89 """One completed match at the age group, as the gatherer read it. 

90 

91 `conference` is the Homegrown conference (division) of a League match, None 

92 for Flex and tournaments; a team's conference is the one it played most 

93 League matches in. Penalty scores are carried for completeness and never 

94 rated: a level regulation score is a draw. 

95 """ 

96 

97 match_id: int 

98 match_date: date 

99 home_team_id: int 

100 away_team_id: int 

101 home_score: int 

102 away_score: int 

103 competition: Competition = "league" 

104 neutral: bool = False 

105 forfeit: bool = False 

106 home_in_pool: bool = True 

107 away_in_pool: bool = True 

108 kickoff_time: time | None = None 

109 conference: str | None = None 

110 home_penalty_score: int | None = None 

111 away_penalty_score: int | None = None 

112 

113 @property 

114 def is_neutral(self) -> bool: 

115 return self.neutral or self.competition in NEUTRAL_COMPETITIONS 

116 

117 

118def match_order(m: RatedMatch) -> tuple: 

119 """Date, then kickoff (untimed last), then id: deterministic for same-day matches.""" 

120 return (m.match_date, m.kickoff_time is None, m.kickoff_time or time.min, m.match_id) 

121 

122 

123# --- output -------------------------------------------------------------------- 

124 

125 

126@dataclass(frozen=True) 

127class MatchDelta: 

128 """One side of one rated match: what it was expected to take and what it moved.""" 

129 

130 match_id: int 

131 match_date: date 

132 team_id: int 

133 opponent_id: int 

134 rating_before: float 

135 opponent_before: float 

136 expected: float 

137 result: float # 1 / 0.5 / 0 

138 k: float 

139 margin_mult: float 

140 delta: float 

141 

142 

143@dataclass(frozen=True) 

144class TeamRating: 

145 team_id: int 

146 rating: float 

147 start_rating: float 

148 mp: int # rated matches 

149 w: int 

150 d: int 

151 l: int 

152 xconf_mp: int # rated matches against a team of another conference 

153 sos: float # mean opponent rating before each rated match 

154 island: int 

155 conference: str | None 

156 ranked: bool # mp >= MIN_MATCHES 

157 provisional: bool # mp < PROVISIONAL_MATCHES 

158 low_cross_conference: bool # xconf_mp < LOW_CROSS_CONFERENCE 

159 tier: str | None # national lists only, ranked teams in the main island 

160 

161 

162@dataclass(frozen=True) 

163class Publication: 

164 national: bool 

165 reason: str | None # why not national; None when it is 

166 main_island: int | None 

167 main_island_share: float | None # ranked teams in the main island / ranked teams 

168 cross_conference: dict[str, int] # main island's conferences -> matches against others 

169 

170 

171@dataclass(frozen=True) 

172class PowerRatingResult: 

173 teams: tuple[TeamRating, ...] # rating high to low, then team id 

174 deltas: tuple[MatchDelta, ...] # two per rated match, in rating order 

175 matches_counted: int 

176 matches_excluded: dict[str, int] # every reason in EXCLUSION_REASONS, 0 when none 

177 publication: Publication 

178 

179 

180# --- pure pieces ----------------------------------------------------------------- 

181 

182 

183def expected_score(rating: float, opponent: float, home_advantage: float = 0.0) -> float: 

184 return 1.0 / (1.0 + 10.0 ** (-(rating - opponent + home_advantage) / SCALE)) 

185 

186 

187def margin_multiplier(goal_difference: int) -> float: 

188 gd = min(abs(goal_difference), MARGIN_CAP) 

189 return 1.0 if gd <= 1 else 1.5 if gd == 2 else 1.75 

190 

191 

192def tier_for(rating: float) -> str | None: 

193 return next((key for key, _, minimum in TIERS if rating >= minimum), None) 

194 

195 

196def carry_over(final_ratings: Mapping[int, float], carry: float = ROLLOVER_CARRY) -> dict[int, float]: 

197 """Next season's starting ratings. Carried teams keep the provisional K.""" 

198 return {t: START_RATING + carry * (r - START_RATING) for t, r in final_ratings.items()} 

199 

200 

201def select_rated(matches: Iterable[RatedMatch]) -> tuple[list[RatedMatch], dict[str, int]]: 

202 """(the rated matches in rating order, how many were excluded and why).""" 

203 excluded = dict.fromkeys(EXCLUSION_REASONS, 0) 

204 rated = [] 

205 for m in sorted(matches, key=match_order): 

206 if m.forfeit: 

207 excluded["forfeit"] += 1 

208 elif not (m.home_in_pool and m.away_in_pool): 

209 excluded["out_of_pool_opponent"] += 1 

210 else: 

211 rated.append(m) 

212 return rated, excluded 

213 

214 

215def team_conferences(matches: Iterable[RatedMatch]) -> dict[int, str]: 

216 """Each team's conference: the one it played most League matches in (the leaderboards rule).""" 

217 counts: dict[int, Counter] = defaultdict(Counter) 

218 for m in matches: 

219 if m.competition == "league" and m.conference: 

220 counts[m.home_team_id][m.conference] += 1 

221 counts[m.away_team_id][m.conference] += 1 

222 out = {} 

223 for team_id, divisions in counts.items(): 

224 conference = conference_of(TeamTally(team_id=team_id, name="", divisions=divisions)) 

225 if conference: 225 ↛ 223line 225 didn't jump to line 223 because the condition on line 225 was always true

226 out[team_id] = conference 

227 return out 

228 

229 

230def islands(matches: Iterable[RatedMatch]) -> dict[int, int]: 

231 """Team -> island id. Islands are numbered 1.. by size (largest first), then lowest team id.""" 

232 parent: dict[int, int] = {} 

233 

234 def find(x: int) -> int: 

235 parent.setdefault(x, x) 

236 while parent[x] != x: 

237 parent[x] = parent[parent[x]] 

238 x = parent[x] 

239 return x 

240 

241 for m in matches: 

242 a, b = find(m.home_team_id), find(m.away_team_id) 

243 if a != b: 

244 parent[max(a, b)] = min(a, b) 

245 groups: dict[int, list[int]] = defaultdict(list) 

246 for t in list(parent): 

247 groups[find(t)].append(t) 

248 ordered = sorted(groups.values(), key=lambda g: (-len(g), min(g))) 

249 return {t: i for i, group in enumerate(ordered, start=1) for t in group} 

250 

251 

252def is_cross_conference(m: RatedMatch, conferences: Mapping[int, str]) -> bool: 

253 home, away = conferences.get(m.home_team_id), conferences.get(m.away_team_id) 

254 return home is not None and away is not None and home != away 

255 

256 

257def publication( 

258 teams: Iterable[TeamRating], rated: Iterable[RatedMatch], conferences: Mapping[int, str] 

259) -> Publication: 

260 """National list or conference lists only, by the islands rule.""" 

261 ranked = [t for t in teams if t.ranked] 

262 if not ranked: 

263 return Publication(False, "No team has enough rated matches yet.", None, None, {}) 

264 per_island = Counter(t.island for t in ranked) 

265 main, size = sorted(per_island.items(), key=lambda kv: (-kv[1], kv[0]))[0] 

266 share = size / len(ranked) 

267 island_of = {t.team_id: t.island for t in teams} 

268 in_main = {conferences[t] for t, i in island_of.items() if i == main and t in conferences} 

269 cross = dict.fromkeys(sorted(in_main), 0) 

270 for m in rated: 

271 if island_of.get(m.home_team_id) == main and is_cross_conference(m, conferences): 

272 for side in (m.home_team_id, m.away_team_id): 

273 cross[conferences[side]] += 1 

274 if share < NATIONAL_ISLAND_SHARE: 

275 reason = f"The largest connected group holds {share:.0%} of ranked teams; a national list needs 90%." 

276 return Publication(False, reason, main, share, cross) 

277 thin = [c for c, n in cross.items() if n < NATIONAL_MIN_CROSS_CONFERENCE] 

278 if not cross or thin: 

279 reason = ( 

280 f"Conferences with fewer than {NATIONAL_MIN_CROSS_CONFERENCE} matches against other conferences: " 

281 f"{', '.join(thin) or 'no conference data'}." 

282 ) 

283 return Publication(False, reason, main, share, cross) 

284 return Publication(True, None, main, share, cross) 

285 

286 

287# --- Elo ------------------------------------------------------------------------- 

288 

289 

290@dataclass 

291class _Running: 

292 rating: float 

293 start: float 

294 mp: int = 0 

295 w: int = 0 

296 d: int = 0 

297 l: int = 0 

298 xconf: int = 0 

299 opponent_sum: float = 0.0 

300 

301 

302def rate(matches: Iterable[RatedMatch], starting_ratings: Mapping[int, float] | None = None) -> PowerRatingResult: 

303 """Replay one age group's season and rate every team that has a rated match. 

304 

305 A team with no rated match is absent from `teams`, never a 1500 with 0 matches. 

306 """ 

307 matches = list(matches) 

308 starting_ratings = starting_ratings or {} 

309 rated, excluded = select_rated(matches) 

310 conferences = team_conferences(matches) 

311 state: dict[int, _Running] = {} 

312 deltas: list[MatchDelta] = [] 

313 

314 def team(t: int) -> _Running: 

315 if t not in state: 

316 start = float(starting_ratings.get(t, START_RATING)) 

317 state[t] = _Running(rating=start, start=start) 

318 return state[t] 

319 

320 for m in rated: 

321 home, away = team(m.home_team_id), team(m.away_team_id) 

322 hfa = 0.0 if m.is_neutral else HOME_ADVANTAGE 

323 e_home = expected_score(home.rating, away.rating, hfa) 

324 s_home = 1.0 if m.home_score > m.away_score else 0.0 if m.home_score < m.away_score else 0.5 

325 g = 1.0 if s_home == 0.5 else margin_multiplier(m.home_score - m.away_score) 

326 cross = is_cross_conference(m, conferences) 

327 sides = ( 

328 (m.home_team_id, m.away_team_id, home, away, e_home, s_home), 

329 (m.away_team_id, m.home_team_id, away, home, 1.0 - e_home, 1.0 - s_home), 

330 ) 

331 moves = [] 

332 for team_id, opponent_id, me, them, e, s in sides: 

333 k = K * (PROVISIONAL_K_MULT if me.mp < PROVISIONAL_MATCHES else 1.0) 

334 delta = k * g * (s - e) 

335 deltas.append( 

336 MatchDelta(m.match_id, m.match_date, team_id, opponent_id, me.rating, them.rating, e, s, k, g, delta) 

337 ) 

338 moves.append((me, them.rating, s, delta)) 

339 for me, opponent_before, s, delta in moves: 

340 me.rating += delta 

341 me.mp += 1 

342 me.opponent_sum += opponent_before 

343 me.xconf += cross 

344 if s == 1.0: 

345 me.w += 1 

346 elif s == 0.5: 

347 me.d += 1 

348 else: 

349 me.l += 1 

350 

351 island_of = islands(rated) 

352 untiered = [ 

353 TeamRating( 

354 team_id=t, 

355 rating=r.rating, 

356 start_rating=r.start, 

357 mp=r.mp, 

358 w=r.w, 

359 d=r.d, 

360 l=r.l, 

361 xconf_mp=r.xconf, 

362 sos=r.opponent_sum / r.mp, 

363 island=island_of[t], 

364 conference=conferences.get(t), 

365 ranked=r.mp >= MIN_MATCHES, 

366 provisional=r.mp < PROVISIONAL_MATCHES, 

367 low_cross_conference=r.xconf < LOW_CROSS_CONFERENCE, 

368 tier=None, 

369 ) 

370 for t, r in state.items() 

371 ] 

372 pub = publication(untiered, rated, conferences) 

373 # Tiers only once the publication state is known. 

374 teams = sorted((_with_tier(t, pub) for t in untiered), key=lambda t: (-t.rating, t.team_id)) 

375 return PowerRatingResult( 

376 teams=tuple(teams), 

377 deltas=tuple(deltas), 

378 matches_counted=len(rated), 

379 matches_excluded=excluded, 

380 publication=pub, 

381 ) 

382 

383 

384def _with_tier(t: TeamRating, pub: Publication) -> TeamRating: 

385 if not (pub.national and t.ranked and t.island == pub.main_island): 

386 return t 

387 return replace(t, tier=tier_for(t.rating)) 

388 

389 

390# --- Massey audit ---------------------------------------------------------------- 

391 

392 

393@dataclass(frozen=True) 

394class MasseyResult: 

395 ratings: dict[int, float] # goals better than an average team, per match 

396 home_advantage: float 

397 

398 

399def massey(matches: Iterable[RatedMatch], *, cap: int = MASSEY_CAP, ridge: float = MASSEY_RIDGE) -> MasseyResult | None: 

400 """Capped-margin Massey with a home-advantage term and a ridge on team strengths. 

401 

402 Rates the same matches Elo does (forfeits and out-of-pool excluded). Neutral 

403 matches carry no home term. None when there is nothing to rate. 

404 """ 

405 rated, _ = select_rated(matches) 

406 if not rated: 

407 return None 

408 teams = sorted({t for m in rated for t in (m.home_team_id, m.away_team_id)}) 

409 idx = {t: i for i, t in enumerate(teams)} 

410 n = len(teams) 

411 with_home = any(not m.is_neutral for m in rated) 

412 cols = n + 1 if with_home else n 

413 x = np.zeros((len(rated), cols)) 

414 y = np.zeros(len(rated)) 

415 for row, m in enumerate(rated): 

416 x[row, idx[m.home_team_id]] = 1.0 

417 x[row, idx[m.away_team_id]] = -1.0 

418 if with_home and not m.is_neutral: 

419 x[row, n] = 1.0 

420 y[row] = max(-cap, min(cap, m.home_score - m.away_score)) 

421 reg = ridge * np.eye(cols) 

422 if with_home: 

423 reg[n, n] = 0.0 

424 beta = np.linalg.solve(x.T @ x + reg, x.T @ y) 

425 return MasseyResult( 

426 ratings={t: float(beta[idx[t]]) for t in teams}, 

427 home_advantage=float(beta[n]) if with_home else 0.0, 

428 ) 

429 

430 

431@dataclass(frozen=True) 

432class RankGap: 

433 team_id: int 

434 island: int 

435 elo_rank: int 

436 massey_rank: int 

437 

438 @property 

439 def gap(self) -> int: 

440 return abs(self.elo_rank - self.massey_rank) 

441 

442 

443def _ranks(team_ids: list[int], value: Mapping[int, float]) -> dict[int, int]: 

444 return {t: i for i, t in enumerate(sorted(team_ids, key=lambda t: (-value[t], t)), start=1)} 

445 

446 

447def rank_gaps(result: PowerRatingResult, audit: MasseyResult | None, threshold: int = RANK_GAP_FLAG) -> list[RankGap]: 

448 """Ranked teams whose Elo and Massey places, within their island, differ by more than `threshold`.""" 

449 if audit is None: 

450 return [] 

451 by_island: dict[int, list[int]] = defaultdict(list) 

452 for t in result.teams: 

453 if t.ranked and t.team_id in audit.ratings: 

454 by_island[t.island].append(t.team_id) 

455 elo = {t.team_id: t.rating for t in result.teams} 

456 out = [] 

457 for island, team_ids in sorted(by_island.items()): 

458 er, mr = _ranks(team_ids, elo), _ranks(team_ids, audit.ratings) 

459 out.extend(RankGap(t, island, er[t], mr[t]) for t in team_ids if abs(er[t] - mr[t]) > threshold) 

460 return sorted(out, key=lambda g: (-g.gap, g.team_id))