Refactor snooker simulator to use DB world rankings, add snooker-elo admin page

- Remove hardcoded SEEDINGS_2026 name→seed map from snooker-simulator.ts
- Load worldRanking from participantExpectedValues (same column darts uses)
- Top 16 by worldRanking get seeded; fallback to Elo order if none stored
- Add /admin/sports-seasons/:id/snooker-elo route with bulk import (name, Elo,
  world ranking format) and per-player Elo + Rank # form, matching darts-elo UX
- Update snooker simulator tests: remove name-based ranking fixtures, add tests
  for DB-driven rankings and Elo fallback

https://claude.ai/code/session_01Fz54vdsLjDVintFguH32To
This commit is contained in:
Claude 2026-04-01 21:27:15 +00:00
parent c5ccee2225
commit c58cfb2d2f
No known key found for this signature in database
4 changed files with 576 additions and 114 deletions

View file

@ -99,6 +99,10 @@ export default [
"sports-seasons/:id/darts-elo",
"routes/admin.sports-seasons.$id.darts-elo.tsx"
),
route(
"sports-seasons/:id/snooker-elo",
"routes/admin.sports-seasons.$id.snooker-elo.tsx"
),
route(
"sports-seasons/:id/golf-skills",
"routes/admin.sports-seasons.$id.golf-skills.tsx"

View file

@ -0,0 +1,472 @@
import { Form, redirect, useLoaderData, useActionData, useNavigation } from 'react-router';
import type { Route } from './+types/admin.sports-seasons.$id.snooker-elo';
import { logger } from '~/lib/logger';
import { findSportsSeasonById, updateSportsSeason } from '~/models/sports-season';
import { findParticipantsBySportsSeasonId } from '~/models/participant';
import {
getAllParticipantEVsForSeason,
batchSaveSourceElos,
batchUpsertParticipantEVs,
} from '~/models/participant-expected-value';
import { batchUpsertParticipantEvSnapshots } from '~/models/ev-snapshot';
import { getSimulator, type SimulatorType } from '~/services/simulations/registry';
import { calculateEV } from '~/services/ev-calculator';
import { DEFAULT_SCORING_RULES } from '~/lib/scoring-types';
import { recalculateStandings } from '~/models/scoring-calculator';
import { database } from '~/database/context';
import * as schema from '~/database/schema';
import { eq } from 'drizzle-orm';
import { Button } from '~/components/ui/button';
import { Input } from '~/components/ui/input';
import { Label } from '~/components/ui/label';
import { Textarea } from '~/components/ui/textarea';
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from '~/components/ui/card';
import { useState } from 'react';
import { Loader2, CheckCircle2, AlertCircle } from 'lucide-react';
import { normalizeName } from '~/lib/fuzzy-match';
export function meta({ data }: Route.MetaArgs): Route.MetaDescriptors {
return [{ title: `Snooker Elo & Rankings — ${data?.sportsSeason?.name ?? "Sports Season"} - Brackt Admin` }];
}
export async function loader({ params }: Route.LoaderArgs) {
const sportsSeasonId = params.id;
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
if (!sportsSeason) {
throw new Response('Sports season not found', { status: 404 });
}
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
const existingEVs = await getAllParticipantEVsForSeason(sportsSeasonId);
const existingData: Record<string, { elo: number | null; ranking: number | null }> = {};
for (const ev of existingEVs) {
existingData[ev.participantId] = {
elo: ev.sourceElo ?? null,
ranking: ev.worldRanking ?? null,
};
}
return { sportsSeason, participants, existingData };
}
interface ActionData {
success?: boolean;
message?: string;
}
export async function action({ request, params }: Route.ActionArgs) {
const sportsSeasonId = params.id;
const formData = await request.formData();
const sportsSeason = await findSportsSeasonById(sportsSeasonId);
if (!sportsSeason) {
return { success: false, message: 'Sports season not found' };
}
const participants = await findParticipantsBySportsSeasonId(sportsSeasonId);
// Parse Elo ratings and world rankings from form
const eloInputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number; worldRanking?: number | null }> = [];
for (const participant of participants) {
const eloVal = formData.get(`elo_${participant.id}`) as string;
const rankVal = formData.get(`rank_${participant.id}`) as string;
if (eloVal && eloVal.trim() !== '') {
const elo = Number(eloVal);
if (!isNaN(elo) && elo > 0) {
const ranking = rankVal && rankVal.trim() !== '' ? Number(rankVal) : null;
eloInputs.push({
participantId: participant.id,
sportsSeasonId,
sourceElo: elo,
worldRanking: ranking && !isNaN(ranking) && ranking > 0 ? ranking : null,
});
}
}
}
if (eloInputs.length === 0) {
return { success: false, message: 'Please enter an Elo rating for at least one participant' };
}
if (!sportsSeason.sport?.simulatorType) {
return { success: false, message: 'This sport has no simulator type configured. Set one on the sport in the admin panel.' };
}
if (sportsSeason.simulationStatus === 'running') {
return { success: false, message: 'A simulation is already running. Please wait.' };
}
// Persist Elo ratings and world rankings
await batchSaveSourceElos(eloInputs);
// Auto-run simulation
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'running' });
try {
const simulator = getSimulator(sportsSeason.sport.simulatorType as SimulatorType);
const results = await simulator.simulate(sportsSeasonId);
if (results.length === 0) {
throw new Error('Simulation returned no results.');
}
// Zero out any participants not in simulation results
const simulatedIds = new Set(results.map(r => r.participantId));
const ZERO_PROBS = {
probFirst: 0, probSecond: 0, probThird: 0, probFourth: 0,
probFifth: 0, probSixth: 0, probSeventh: 0, probEighth: 0,
};
const evInputs = [
...results.map(r => ({
participantId: r.participantId,
sportsSeasonId,
probabilities: r.probabilities,
scoringRules: DEFAULT_SCORING_RULES,
source: 'elo_simulation' as const,
})),
...participants
.filter(p => !simulatedIds.has(p.id))
.map(p => ({
participantId: p.id,
sportsSeasonId,
probabilities: ZERO_PROBS,
scoringRules: DEFAULT_SCORING_RULES,
source: 'elo_simulation' as const,
})),
];
await batchUpsertParticipantEVs(evInputs);
// Refresh projected points in team standings
const seasonSports = await database().query.seasonSports.findMany({
where: eq(schema.seasonSports.sportsSeasonId, sportsSeasonId),
});
await Promise.all(seasonSports.map(({ seasonId }) => recalculateStandings(seasonId)));
// EV snapshot
const today = new Date().toISOString().slice(0, 10);
await batchUpsertParticipantEvSnapshots(
results.map(r => ({
participantId: r.participantId,
sportsSeasonId,
snapshotDate: today,
probFirst: r.probabilities.probFirst,
probSecond: r.probabilities.probSecond,
probThird: r.probabilities.probThird,
probFourth: r.probabilities.probFourth,
probFifth: r.probabilities.probFifth,
probSixth: r.probabilities.probSixth,
probSeventh: r.probabilities.probSeventh,
probEighth: r.probabilities.probEighth,
calculatedEV: calculateEV(r.probabilities, DEFAULT_SCORING_RULES),
source: r.source,
}))
);
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'idle' });
} catch (error) {
await updateSportsSeason(sportsSeasonId, { simulationStatus: 'failed' });
logger.error('Error running snooker simulation:', error);
return {
success: false,
message: error instanceof Error ? error.message : 'Simulation failed',
};
}
return redirect(`/admin/sports-seasons/${sportsSeasonId}/expected-values`);
}
export default function AdminSportsSeasonSnookerElo() {
const { sportsSeason, participants, existingData } = useLoaderData<typeof loader>();
const actionData = useActionData<ActionData>();
const navigation = useNavigation();
const [eloValues, setEloValues] = useState<Record<string, string>>(() => {
const initial: Record<string, string> = {};
participants.forEach(p => {
const d = existingData[p.id];
if (d?.elo !== null && d?.elo !== undefined) initial[p.id] = d.elo.toString();
});
return initial;
});
const [rankValues, setRankValues] = useState<Record<string, string>>(() => {
const initial: Record<string, string> = {};
participants.forEach(p => {
const d = existingData[p.id];
if (d?.ranking !== null && d?.ranking !== undefined) initial[p.id] = d.ranking.toString();
});
return initial;
});
// Bulk import state: "Player Name, 1800, 1" format (name, elo, optional world ranking)
const [bulkText, setBulkText] = useState('');
const [parseResults, setParseResults] = useState<{
matched: Array<{ participantId: string; name: string; elo: number; ranking: number | null; inputName: string }>;
unmatched: Array<{ inputName: string; elo: number; ranking: number | null }>;
} | null>(null);
function findParticipantMatch(inputName: string) {
const normalizedInput = normalizeName(inputName);
const normalized = participants.map(p => ({ p, n: normalizeName(p.name) }));
const exact = normalized.find(({ n }) => n === normalizedInput);
if (exact) return exact.p;
const contains = normalized.find(({ n }) => n.includes(normalizedInput) || normalizedInput.includes(n));
if (contains) return contains.p;
const inputWords = normalizedInput.split(' ').filter(w => w.length > 2);
const overlap = normalized.find(({ n }) => {
const pWords = n.split(' ').filter(w => w.length > 2);
const shared = inputWords.filter(w => pWords.includes(w));
return shared.length > 0 && shared.length >= Math.min(inputWords.length, pWords.length) * 0.5;
});
return overlap?.p ?? null;
}
function parseBulkText() {
// Formats supported:
// "Player Name, 1800, 1" (name, elo, world ranking)
// "Player Name, 1800" (name, elo — ranking omitted)
// "Player Name: 1800: 1" (colon-separated)
const lines = bulkText.split('\n');
const matched: typeof parseResults extends null ? never : NonNullable<typeof parseResults>['matched'] = [];
const unmatched: typeof parseResults extends null ? never : NonNullable<typeof parseResults>['unmatched'] = [];
const seen = new Set<string>();
for (const line of lines) {
const trimmed = line.trim();
if (!trimmed) continue;
// Match "Name, Elo" or "Name, Elo, Ranking" (comma, colon, or tab separated)
const match = /^(.+?)[\s,:\t]+(\d{3,5})(?:[\s,:\t]+(\d{1,3}))?\s*$/.exec(trimmed);
if (!match) continue;
const inputName = match[1].trim();
const elo = parseInt(match[2], 10);
const ranking = match[3] ? parseInt(match[3], 10) : null;
if (isNaN(elo) || elo < 500 || elo > 5000) continue;
if (ranking !== null && (isNaN(ranking) || ranking < 1 || ranking > 256)) continue;
const participant = findParticipantMatch(inputName);
if (participant && !seen.has(participant.id)) {
seen.add(participant.id);
matched.push({ participantId: participant.id, name: participant.name, elo, ranking, inputName });
} else if (!participant) {
unmatched.push({ inputName, elo, ranking });
}
}
setParseResults({ matched, unmatched });
}
function applyMatches() {
if (!parseResults) return;
const newElos = { ...eloValues };
const newRanks = { ...rankValues };
for (const m of parseResults.matched) {
newElos[m.participantId] = m.elo.toString();
if (m.ranking !== null) {
newRanks[m.participantId] = m.ranking.toString();
}
}
setEloValues(newElos);
setRankValues(newRanks);
setParseResults(null);
setBulkText('');
}
const isSubmitting = navigation.state === 'submitting';
// Sort participants for display: by current rank (ascending), then unranked alphabetically
const sortedParticipants = [...participants].toSorted((a, b) => {
const rankA = rankValues[a.id] ? parseInt(rankValues[a.id], 10) : null;
const rankB = rankValues[b.id] ? parseInt(rankValues[b.id], 10) : null;
if (rankA !== null && rankB !== null) return rankA - rankB;
if (rankA !== null) return -1;
if (rankB !== null) return 1;
return a.name.localeCompare(b.name);
});
return (
<div className="container mx-auto py-8">
<div className="mb-8">
<h1 className="text-3xl font-bold mb-2">Snooker Elo &amp; World Rankings</h1>
<p className="text-muted-foreground">
{sportsSeason.sport.name} {sportsSeason.name}
</p>
</div>
{/* Bulk Import */}
<Card className="mb-6">
<CardHeader>
<CardTitle>Bulk Import</CardTitle>
<CardDescription>
Paste one player per line. Format:{' '}
<code>Player Name, 1800, 1</code> (name, Elo, world ranking).
The world ranking is required for bracket seeding the top 16 ranked players
are seeded, the rest are drawn as qualifiers. Omit the ranking and the simulator
will seed by Elo order instead.
Player names are fuzzy-matched to participants.
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<Textarea
placeholder={`Judd Trump, 2050, 1\nKyren Wilson, 1980, 2\nNeil Robertson, 1960, 3`}
value={bulkText}
onChange={e => { setBulkText(e.target.value); setParseResults(null); }}
rows={10}
className="font-mono text-sm"
/>
<Button type="button" variant="outline" onClick={parseBulkText} disabled={!bulkText.trim()}>
Parse
</Button>
{parseResults && (
<div className="space-y-3">
{parseResults.matched.length > 0 && (
<div>
<div className="flex items-center gap-2 text-sm font-medium text-emerald-400 mb-2">
<CheckCircle2 className="h-4 w-4" />
Matched ({parseResults.matched.length})
</div>
<div className="rounded-md border border-emerald-500/30 bg-emerald-500/10 divide-y divide-emerald-500/20 text-sm">
{parseResults.matched.map(m => (
<div key={m.participantId} className="flex justify-between px-3 py-1.5">
<span className="text-muted-foreground">{m.inputName}</span>
<span className="font-medium">
{m.name} &rarr; Elo {m.elo}{m.ranking !== null ? `, Rank #${m.ranking}` : ''}
</span>
</div>
))}
</div>
</div>
)}
{parseResults.unmatched.length > 0 && (
<div>
<div className="flex items-center gap-2 text-sm font-medium text-amber-700 mb-2">
<AlertCircle className="h-4 w-4" />
Not matched ({parseResults.unmatched.length}) enter manually below
</div>
<div className="rounded-md border border-amber-200 bg-amber-50 divide-y divide-amber-100 text-sm">
{parseResults.unmatched.map(u => (
<div key={u.inputName} className="flex justify-between px-3 py-1.5">
<span>{u.inputName}</span>
<span className="font-medium">
Elo {u.elo}{u.ranking !== null ? `, Rank #${u.ranking}` : ''}
</span>
</div>
))}
</div>
</div>
)}
{parseResults.matched.length > 0 && (
<Button type="button" onClick={applyMatches}>
Apply {parseResults.matched.length} matched entries to form
</Button>
)}
</div>
)}
</CardContent>
</Card>
<div className="grid gap-6 lg:grid-cols-2">
<Card>
<CardHeader>
<CardTitle>Player Elo &amp; Rankings</CardTitle>
<CardDescription>
Enter each player's Snooker Elo and world ranking. World ranking determines bracket
seeding (top 16 seeded, rest randomly drawn). Saving will automatically run the
simulation and update expected values.
</CardDescription>
</CardHeader>
<CardContent>
<Form method="post" className="space-y-4">
<div className="grid grid-cols-[1fr_100px_80px] gap-x-3 gap-y-2 items-center text-xs font-medium text-muted-foreground mb-1">
<span>Player</span>
<span>Elo</span>
<span>Rank #</span>
</div>
<div className="space-y-2">
{sortedParticipants.map(participant => (
<div key={participant.id} className="grid grid-cols-[1fr_100px_80px] gap-x-3 items-center">
<Label htmlFor={`elo_${participant.id}`} className="truncate text-sm">
{participant.name}
</Label>
<Input
type="number"
id={`elo_${participant.id}`}
name={`elo_${participant.id}`}
placeholder="1600"
value={eloValues[participant.id] ?? ''}
onChange={e =>
setEloValues(prev => ({ ...prev, [participant.id]: e.target.value }))
}
className="h-8 text-sm"
/>
<Input
type="number"
name={`rank_${participant.id}`}
placeholder="—"
value={rankValues[participant.id] ?? ''}
onChange={e =>
setRankValues(prev => ({ ...prev, [participant.id]: e.target.value }))
}
className="h-8 text-sm"
/>
</div>
))}
</div>
{actionData && !actionData.success && actionData.message && (
<div className="text-sm text-destructive">{actionData.message}</div>
)}
<Button type="submit" disabled={isSubmitting}>
{isSubmitting && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
{isSubmitting ? 'Saving & Running Simulation...' : 'Save & Run Simulation'}
</Button>
</Form>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle>How It Works</CardTitle>
</CardHeader>
<CardContent className="text-sm space-y-2">
<ol className="list-decimal list-inside space-y-2">
<li>Save Elo ratings and world rankings for all players</li>
<li>Top 16 seeds placed in fixed bracket positions; remaining players randomly drawn as qualifiers per simulation</li>
<li>Qualifiers (seeds 17+) play best-of-19 qualifying rounds to fill the 32-player bracket if more than 16 are present</li>
<li>Per-frame win probability: p = 1 / (1 + e^(ΔElo/700))</li>
<li>Match win probability via Bernoulli frames model for each round's best-of length</li>
<li>Run 50,000 Monte Carlo simulations of the full bracket</li>
<li>Distribute probabilities across 1st8th place buckets</li>
</ol>
<div className="mt-4 text-muted-foreground text-xs space-y-1">
<div>Round formats: R32 best-of-19, R16/QF best-of-25, SF best-of-33, Final best-of-35</div>
<div>If world ranking is omitted, players are seeded by Elo order.</div>
<div>Once the bracket draw is announced, add players to the bracket event for live simulation.</div>
</div>
</CardContent>
</Card>
</div>
</div>
);
}

View file

@ -144,6 +144,7 @@ function makeEVRows(eloOverride?: Map<string, number>) {
return PARTICIPANT_IDS.map((participantId) => ({
participantId,
sourceElo: eloOverride?.get(participantId) ?? ELO_BASE,
worldRanking: null,
}));
}
@ -371,56 +372,49 @@ describe("SnookerSimulator.simulate() — Path B (pre-bracket)", () => {
select: MockInstance;
};
// 32 participants: use names that match the hardcoded rankings
const RANKED_NAMES = [
"Judd Trump", "Kyren Wilson", "Mark Selby", "Ronnie O'Sullivan",
"Mark Allen", "Luca Brecel", "Neil Robertson", "John Higgins",
"Ryan Day", "Zhao Xintong", "Jak Jones", "Si Jiahui",
"Barry Hawkins", "Ding Junhui", "Pang Junxu", "Zhang Anda",
"Xiao Guodong", "Jack Lisowski", "Shaun Murphy", "David Gilbert",
"Anthony McGill", "Tom Ford", "Stuart Bingham", "Andrew Higginson",
"Chris Wakelin", "Gary Wilson", "Matthew Selt", "Gerard Greene",
"Ben Woollaston", "Jamie Jones", "Robbie Williams", "Mark Williams",
];
const SEASON_PARTICIPANTS = RANKED_NAMES.map((name, i) => ({
// 32 participants — names don't drive seeding anymore; worldRanking in EV rows does.
const SEASON_PARTICIPANTS = Array.from({ length: 32 }, (_, i) => ({
id: `player-${i + 1}`,
name,
name: `Player ${i + 1}`,
}));
beforeEach(async () => {
const { database } = await import("~/database/context");
// select() is called twice in Path B:
// 1. for participantExpectedValues (EV/Elo rows)
// 2. for participants (all players in the season)
const eloRows = SEASON_PARTICIPANTS.map(p => ({ participantId: p.id, sourceElo: ELO_BASE }));
const participantRows = SEASON_PARTICIPANTS;
// Build EV rows including worldRanking (rank 1 = player-1, rank 2 = player-2, etc.)
function makeEvRows(rankOverride?: Map<string, number | null>) {
return SEASON_PARTICIPANTS.map((p, i) => ({
participantId: p.id,
sourceElo: ELO_BASE,
worldRanking: rankOverride?.has(p.id) ? rankOverride.get(p.id) : i + 1,
}));
}
function setupMockDb(evRows: ReturnType<typeof makeEvRows>, participantRows = SEASON_PARTICIPANTS) {
mockDb = {
query: {
scoringEvents: { findFirst: vi.fn() },
playoffMatches: { findMany: vi.fn() },
},
select: vi.fn()
// First select(): participantExpectedValues (Elo + worldRanking)
.mockReturnValueOnce({
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(eloRows) }),
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(evRows) }),
})
// Second select(): participants (id + name)
.mockReturnValueOnce({
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(participantRows) }),
}),
};
(database as unknown as MockInstance).mockReturnValue(mockDb);
mockDb.query.scoringEvents.findFirst.mockResolvedValue({
id: "event-1",
sportsSeasonId: "season-1",
eventType: "playoff_game",
});
// No matches → triggers Path B
mockDb.query.playoffMatches.findMany.mockResolvedValue([]);
}
beforeEach(async () => {
const { database } = await import("~/database/context");
setupMockDb(makeEvRows());
(database as unknown as MockInstance).mockReturnValue(mockDb);
});
it("returns 32 results when bracket is not yet populated", async () => {
@ -444,10 +438,59 @@ describe("SnookerSimulator.simulate() — Path B (pre-bracket)", () => {
}
});
it("top-seeded player (rank 1, highest Elo) has highest win probability", async () => {
const { database } = await import("~/database/context");
// Give the seed-1 player a big Elo advantage; everyone else gets low Elo
const eloRows = SEASON_PARTICIPANTS.map((p, i) => ({
participantId: p.id,
sourceElo: i === 0 ? 3000 : 1500,
worldRanking: i + 1,
}));
setupMockDb(eloRows);
(database as unknown as MockInstance).mockReturnValue(mockDb);
const sim = new SnookerSimulator();
const results = await sim.simulate("season-1");
const topSeedResult = results.find(r => r.participantId === "player-1");
const otherProbFirsts = results
.filter(r => r.participantId !== "player-1")
.map(r => r.probabilities.probFirst);
expect(topSeedResult).toBeDefined();
expect(topSeedResult!.probabilities.probFirst).toBeGreaterThan(Math.max(...otherProbFirsts));
});
it("falls back to Elo order when no world rankings are stored", async () => {
const { database } = await import("~/database/context");
// No worldRanking on any row — simulator should use Elo order
const eloRows = SEASON_PARTICIPANTS.map((p, i) => ({
participantId: p.id,
sourceElo: i === 0 ? 3000 : 1500, // player-1 has highest Elo
worldRanking: null,
}));
setupMockDb(eloRows);
(database as unknown as MockInstance).mockReturnValue(mockDb);
const sim = new SnookerSimulator();
const results = await sim.simulate("season-1");
// player-1 with the highest Elo should be treated as seed 1
const topEloResult = results.find(r => r.participantId === "player-1");
const otherProbFirsts = results
.filter(r => r.participantId !== "player-1")
.map(r => r.probabilities.probFirst);
expect(topEloResult).toBeDefined();
expect(topEloResult!.probabilities.probFirst).toBeGreaterThan(Math.max(...otherProbFirsts));
});
it("throws if fewer than 17 participants exist", async () => {
const { database } = await import("~/database/context");
const tooFew = SEASON_PARTICIPANTS.slice(0, 10);
const eloRows = tooFew.map(p => ({ participantId: p.id, sourceElo: ELO_BASE }));
const eloRows = tooFew.map((p, i) => ({ participantId: p.id, sourceElo: ELO_BASE, worldRanking: i + 1 }));
(database as unknown as MockInstance).mockReturnValue({
...mockDb,

View file

@ -7,15 +7,15 @@
*
* Algorithm:
* 1. Load the bracket scoring event and all playoff matches from DB.
* 2. Load Elo ratings from participantExpectedValues.sourceElo.
* 2. Load Elo ratings and world rankings from participantExpectedValues.
* 3. Compute per-match win probability using the Bernoulli frame model:
* p_frame = 1 / (1 + e^(-(Elo1 - Elo2) / ELO_DIVISOR))
* P(win match) = sum_{w2=0}^{F-1} C(F-1+w2, w2) * p^F * (1-p)^w2
* where F = frames to win, which varies by round.
* 4. Two simulation paths:
* a. Bracket populated: simulate from actual draw, respecting completed matches.
* b. No bracket: simulate qualifying (ranks 17-48 play one round best-of-19),
* randomly pair 16 winners vs top 16 seeds, then simulate 5-round bracket.
* b. No bracket: sort players by worldRanking (fallback: Elo order), place top 16
* as seeds, randomly draw the rest into seed slots 17-32 each simulation.
* 5. Track integer placement counts per tier across 50,000 simulations.
* 6. Convert to probability distributions using exact denominators (column sums = 1.0).
*
@ -34,7 +34,8 @@
* R16 losers all 0
* R32 losers all 0
*
* World rankings (for pre-bracket path): hardcoded below. Update annually.
* World rankings (for pre-bracket path): loaded from participantExpectedValues.worldRanking.
* Set via the snooker-elo admin page. Falls back to Elo order if no rankings are stored.
*/
import { database } from "~/database/context";
@ -75,62 +76,6 @@ const ELO_DIVISOR = 700;
*/
const FRAMES_TO_WIN = [10, 13, 13, 17, 18] as const;
// ─── Tournament seedings (2025 World Snooker Championship) ────────────────────
// Seed 1 = defending champion; seeds 2-16 = world ranking order (skipping champion).
// Seeds 17+ = qualifiers — only their relative order here matters (all > 16).
// Update this map each year when a new snooker season is added.
// Players not in this map default to seed 999 (treated as qualifiers).
const SEEDINGS_2026: Record<string, number> = {
"Judd Trump": 1,
"Kyren Wilson": 2,
"Neil Robertson": 3,
"Mark Williams": 4,
"Zhao Xintong": 5,
"John Higgins": 6,
"Mark Selby": 7,
"Shaun Murphy": 8,
"Xiao Guodong": 9,
"Ronnie O'Sullivan": 10,
"Barry Hawkins": 11,
"Wu Yize": 12,
"Chris Wakelin": 13,
"Mark Allen": 14,
"Si Jiahui": 15,
"Ding Junhui": 16,
"Stuart Bingham": 17,
"Jack Lisowski": 18,
"Jak Jones": 19,
"Zhang Anda": 20,
"Elliot Slessor": 21,
"Thepchaiya Un-Nooh": 22,
"Ali Carter": 23,
"Gary Wilson": 24,
"Zhou Yuelong": 25,
"David Gilbert": 26,
"Stephen Maguire": 27,
"Joe O'Connor": 28,
"Pang Junxu": 29,
"Lei Peifan": 30,
"Yuan Sijun": 31,
"Tom Ford": 32,
"Hossein Vafaei": 33,
"Jimmy Robertson": 34,
"Ryan Day": 35,
"Jackson Page": 36,
"Matthew Selt": 37,
"Xu Si": 38,
"Ben Woollaston": 39,
"Aaron Hill": 40,
"Daniel Wells": 41,
"Anthony McGill": 42,
"Zak Surety": 43,
"Stan Moody": 44,
"Noppon Saengkham": 45,
"Luca Brecel": 46,
"He Guoqiang": 47,
"Matthew Stevens": 48,
};
/**
* Standard seeded R32 bracket for 32-player single-elimination.
@ -153,22 +98,6 @@ const R32_BRACKET: Array<[number, number]> = [
[15, 18], [2, 31],
];
// ─── Name normalization ──────────────────────────────────────────────────────
// Normalize unicode apostrophes/quotes so DB names (which may use curly quotes
// like U+2019 ') match the ASCII apostrophes (U+0027 ') in SEEDINGS keys.
function normalizeApostrophes(name: string): string {
return name.replace(/[\u2018\u2019\u2032\u0060]/g, "'");
}
const SEEDINGS_NORMALIZED = new Map(
Object.entries(SEEDINGS_2026).map(([name, seed]) => [normalizeApostrophes(name), seed])
);
function getSeedingForName(name: string): number {
return SEEDINGS_NORMALIZED.get(normalizeApostrophes(name)) ?? 999;
}
// ─── Math helpers ──────────────────────────────────────────────────────────────
/**
@ -248,23 +177,28 @@ export class SnookerSimulator implements Simulator {
})
: [];
// 3. Load Elo ratings from participantExpectedValues.
// 3. Load Elo ratings and world rankings from participantExpectedValues.
const evRows = await db
.select({
participantId: schema.participantExpectedValues.participantId,
sourceElo: schema.participantExpectedValues.sourceElo,
worldRanking: schema.participantExpectedValues.worldRanking,
})
.from(schema.participantExpectedValues)
.where(eq(schema.participantExpectedValues.sportsSeasonId, sportsSeasonId));
// Build Elo map; fall back to 1500 for any participant with no stored rating.
// Build Elo and ranking maps; fall back to 1500 for any participant with no stored rating.
const eloMap = new Map<string, number>();
const rankingMap = new Map<string, number>();
for (const r of evRows) {
if (r.sourceElo !== null && r.sourceElo !== undefined) {
eloMap.set(r.participantId, r.sourceElo);
} else if (!eloMap.has(r.participantId)) {
eloMap.set(r.participantId, 1500);
}
if (r.worldRanking !== null && r.worldRanking !== undefined) {
rankingMap.set(r.participantId, r.worldRanking);
}
}
// Determine which simulation path to take.
@ -274,7 +208,7 @@ export class SnookerSimulator implements Simulator {
if (bracketPopulated) {
return this.simulateBracket(allMatches, eloMap);
} else {
return this.simulatePreBracket(sportsSeasonId, eloMap, db);
return this.simulatePreBracket(sportsSeasonId, eloMap, rankingMap, db);
}
}
@ -442,14 +376,18 @@ export class SnookerSimulator implements Simulator {
}
// ─── Path B: Pre-bracket simulation ─────────────────────────────────────────
// Players 17-48 haven't qualified yet. Each simulation:
// 1. Randomly pairs the qualifiers (17-48) and simulates 16 best-of-19 matches.
// 2. The 16 winners are shuffled and randomly drawn into seed slots 17-32.
// Players beyond the top 16 seeds haven't been drawn yet. Each simulation:
// 1. Randomly pairs qualifiers (seeds 17+) and simulates best-of-19 matches if >16.
// 2. The 16 remaining qualifiers are shuffled and drawn into seed slots 17-32.
// 3. The full 32-player bracket is then simulated using the proper seeded structure.
//
// Seeding is determined by worldRanking from participantExpectedValues (ascending).
// Falls back to Elo order (descending) for players with no ranking stored.
private async simulatePreBracket(
sportsSeasonId: string,
eloMap: Map<string, number>,
rankingMap: Map<string, number>,
db: ReturnType<typeof database>
): Promise<SimulationResult[]> {
const allParticipants = await db
@ -464,15 +402,20 @@ export class SnookerSimulator implements Simulator {
);
}
// Sort by seeding. Unranked players default to 999 (treated as qualifiers).
// Sort by world ranking (ascending). Unranked players fall back to Elo order (descending).
const fallbackElo = 1500;
const ranked = allParticipants.toSorted((a, b) => {
return getSeedingForName(a.name) - getSeedingForName(b.name);
const rankA = rankingMap.get(a.id);
const rankB = rankingMap.get(b.id);
if (rankA !== undefined && rankB !== undefined) return rankA - rankB;
if (rankA !== undefined) return -1;
if (rankB !== undefined) return 1;
return (eloMap.get(b.id) ?? fallbackElo) - (eloMap.get(a.id) ?? fallbackElo);
});
const topSeeds = ranked.slice(0, 16); // Fixed seed positions 1-16
const qualifiers = ranked.slice(16); // Randomly drawn into positions 17-32
const fallbackElo = 1500;
const matchProbCache = new Map<string, number>();
const simMatch = (p1Id: string, p2Id: string, framesToWin: number): string => {
const elo1 = eloMap.get(p1Id) ?? fallbackElo;