Spaces:
Running
Running
File size: 8,909 Bytes
1790bde | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | """Monte-Carlo simulation of the 2026 World Cup under the real 48-team format.
Group stage scorelines are sampled from the Dixon-Coles joint grid; group
standings use FIFA tiebreakers (points, GD, GF). The 8 best third-placed teams
are selected and allocated to bracket slots via Annex-C cluster matching; the
fixed single-elimination bracket is then played out, with draws in knockout
matches resolved in proportion to regulation win strength (ET/penalties)."""
from __future__ import annotations
import json
import time
import networkx as nx
import numpy as np
import config
from db import connect
import bracket as B
from wcmodel import WorldCupModel, load_training_frame
# ---------------------------------------------------------------- caches
def build_caches(model: WorldCupModel, groups: dict[str, list[str]]):
"""Precompute group-stage scoreline samplers and a knockout win matrix."""
teams = sorted({t for ts in groups.values() for t in ts})
idx = {t: i for i, t in enumerate(teams)}
n = len(teams)
with connect() as conn:
fixtures = conn.execute(
"SELECT home_team,away_team,neutral FROM matches "
"WHERE stage='group' ORDER BY date,id"
).fetchall()
# group-stage fixtures -> flattened cumulative distribution over scorelines
gs = []
for f in fixtures:
g = model.predict_grid(f["home_team"], f["away_team"], neutral=bool(f["neutral"]))
grid = np.asarray(g.grid)
flat = grid.ravel()
flat = flat / flat.sum()
gs.append((f["home_team"], f["away_team"], np.cumsum(flat), grid.shape[1]))
# knockout: advance-probability matrix (neutral venue), team i beats team j
adv = np.zeros((n, n))
for a in teams:
for b in teams:
if a == b:
continue
g = model.predict_grid(a, b, neutral=True)
ph, pdr, pa = (float(x) for x in g.home_draw_away)
denom = ph + pa
adv[idx[a], idx[b]] = ph + (pdr * ph / denom if denom > 0 else 0.5 * pdr)
return teams, idx, gs, adv
# ---------------------------------------------------------------- one sim
def _rank(table: dict) -> list[str]:
"""Sort teams by points, goal difference, goals for, then random jitter."""
return sorted(
table,
key=lambda t: (table[t]["pts"], table[t]["gd"], table[t]["gf"], table[t]["r"]),
reverse=True,
)
def _assign_thirds(third_groups: list[str], rng) -> dict[int, str]:
"""Match the 8 qualified third-place groups to the 8 bracket slots so each
lands in an Annex-C-permitted cluster (bipartite maximum matching)."""
G = nx.Graph()
slots = list(B.THIRD_SLOTS)
for mid in slots:
G.add_node(("slot", mid))
for grp in third_groups:
G.add_node(("grp", grp))
for mid in slots:
if grp in B.THIRD_SLOTS[mid]:
G.add_edge(("grp", grp), ("slot", mid))
m = nx.bipartite.maximum_matching(G, top_nodes={("grp", g) for g in third_groups})
return {mid: m[("slot", mid)][1] for mid in slots if ("slot", mid) in m}
def simulate_once(groups, idx, gs, adv, rng) -> tuple[dict, str]:
# ---- group stage ----
tables = {g: {t: {"pts": 0, "gf": 0, "ga": 0, "gd": 0, "r": rng.random()}
for t in ts} for g, ts in groups.items()}
team_group = {t: g for g, ts in groups.items() for t in ts}
ncol = gs[0][3]
for home, away, cum, _nc in gs:
k = int(np.searchsorted(cum, rng.random()))
hs, as_ = divmod(k, ncol)
g = team_group[home]
th, ta = tables[g][home], tables[g][away]
th["gf"] += hs; th["ga"] += as_; ta["gf"] += as_; ta["ga"] += hs
if hs > as_:
th["pts"] += 3
elif hs < as_:
ta["pts"] += 3
else:
th["pts"] += 1; ta["pts"] += 1
for g in tables:
for t in tables[g]:
tables[g][t]["gd"] = tables[g][t]["gf"] - tables[g][t]["ga"]
winners, runners, thirds = {}, {}, []
reached = {} # team -> furthest stage code
for g, tbl in tables.items():
order = _rank(tbl)
winners[g], runners[g] = order[0], order[1]
thirds.append((g, order[2], tbl[order[2]]))
for t in order:
reached[t] = "group"
# best 8 third-placed teams
thirds.sort(key=lambda x: (x[2]["pts"], x[2]["gd"], x[2]["gf"], x[2]["r"]), reverse=True)
best8 = thirds[:8]
third_team_of_group = {g: t for g, t, _ in best8}
slot_group = _assign_thirds([g for g, _, _ in best8], rng)
third_for_slot = {mid: third_team_of_group[slot_group[mid]] for mid in slot_group}
# ---- resolve R32 entrants ----
def resolve(slot):
kind, val = slot
if kind == "W":
return winners[val]
if kind == "RU":
return runners[val]
return None # third slots filled below
qualified = set()
match_team = {}
for mid, (sa, sb) in B.R32.items():
ta = resolve(sa)
tb = resolve(sb) if sb[0] != "3" else third_for_slot[mid]
match_team[mid] = [ta, tb]
qualified.update([ta, tb])
for t in qualified:
reached[t] = "R32"
# ---- play knockout bracket ----
def play(mid):
ta, tb = match_team[mid]
pa = adv[idx[ta], idx[tb]]
winner = ta if rng.random() < pa else tb
return winner
# R32
r32_winners = {mid: play(mid) for mid in B.R32}
for w in r32_winners.values():
reached[w] = "R16"
# subsequent rounds use FEED
winners_by_match = dict(r32_winners)
next_stage_code = {"R16": "QF", "QF": "SF", "SF": "F", "F": "champion"}
for mid in (89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 104):
a, b = B.FEED[mid]
match_team[mid] = [winners_by_match[a], winners_by_match[b]]
w = play(mid)
winners_by_match[mid] = w
reached[w] = next_stage_code[B.STAGE_OF[mid]]
champion = winners_by_match[104]
return reached, champion, winners
# ---------------------------------------------------------------- aggregate
STAGES = ["group", "R32", "R16", "QF", "SF", "F", "champion"]
# cumulative "reached at least" mapping
REACH_AT_LEAST = {
"p_advance": ["R32", "R16", "QF", "SF", "F", "champion"],
"p_r16": ["R16", "QF", "SF", "F", "champion"],
"p_qf": ["QF", "SF", "F", "champion"],
"p_sf": ["SF", "F", "champion"],
"p_final": ["F", "champion"],
"p_win": ["champion"],
}
def run(n_sims: int = 20000, seed: int = 12345) -> dict:
groups = json.loads((config.PROCESSED / "groups.json").read_text(encoding="utf-8"))
model = WorldCupModel.load()
teams, idx, gs, adv = build_caches(model, groups)
rng = np.random.default_rng(seed)
counts = {t: {k: 0 for k in REACH_AT_LEAST} for t in teams}
group_win = {t: 0 for t in teams}
t0 = time.time()
for _ in range(n_sims):
reached, champ, winners = simulate_once(groups, idx, gs, adv, rng)
for w in winners.values():
group_win[w] += 1
for t, st in reached.items():
for key, ok in REACH_AT_LEAST.items():
if st in ok:
counts[t][key] += 1
dt = time.time() - t0
team_group = {t: g for g, ts in groups.items() for t in ts}
results = []
for t in teams:
c = counts[t]
results.append({
"team": t, "group": team_group[t],
"p_group_win": round(group_win[t] / n_sims, 4),
"p_advance": round(c["p_advance"] / n_sims, 4),
"p_r16": round(c["p_r16"] / n_sims, 4),
"p_qf": round(c["p_qf"] / n_sims, 4),
"p_sf": round(c["p_sf"] / n_sims, 4),
"p_final": round(c["p_final"] / n_sims, 4),
"p_win": round(c["p_win"] / n_sims, 4),
})
results.sort(key=lambda r: r["p_win"], reverse=True)
print(f"{n_sims} sims in {dt:.1f}s ({n_sims/dt:.0f}/s)")
return {"n_sims": n_sims, "results": results}
def store(sim: dict, run_id: int) -> None:
with connect() as conn:
conn.execute("DELETE FROM simulations WHERE run_id=?", (run_id,))
conn.executemany(
"""INSERT INTO simulations(run_id,team,group_label,p_group_win,
p_advance,p_r16,p_qf,p_sf,p_final,p_win,exp_points)
VALUES(?,?,?,?,?,?,?,?,?,?,?)""",
[(run_id, r["team"], r["group"], r["p_group_win"], r["p_advance"],
r["p_r16"], r["p_qf"], r["p_sf"], r["p_final"], r["p_win"], 0.0)
for r in sim["results"]],
)
if __name__ == "__main__":
import sys
n = int(sys.argv[1]) if len(sys.argv) > 1 else 20000
out = run(n)
print("\nTitle odds (top 12):")
for r in out["results"][:12]:
print(f" {r['team']:<16} {r['group']} win={r['p_win']*100:5.2f}% "
f"final={r['p_final']*100:5.1f}% adv={r['p_advance']*100:5.1f}%")
|