Add PDC World Darts Championship simulator with Elo-based bracket (#248)
Fixes #123 * Add PDC World Darts Championship simulator (128-player bracket) - New DartsSimulator: 128-player single-elimination, 7 rounds with PDC-accurate best-of-sets formats (bo3/bo5/bo5/bo7/bo7/bo11/bo13). ELO_DIVISOR=500 via set-level Bernoulli model. Two simulation paths: Path A (bracket drawn) simulates from actual DB matches; Path B (pre-bracket) seeds top 32 by world ranking in fixed positions and randomly draws the remaining 96 per simulation run (50,000 iterations). - darts_bracket added to simulatorTypeEnum and simulator registry. - world_ranking nullable integer column added to participant_expected_values (migration 0067); batchSaveSourceElos now accepts and persists it. - Admin route /admin/sports-seasons/:id/darts-elo: bulk import with format "Player Name, 2099, 1" (name, Elo, optional world ranking), fuzzy name matching, auto-runs simulation and updates EV/snapshots on save. - DARTS_128 bracket template added (scoring starts at Quarterfinals). - 30 unit tests: math helpers, bracket seeding structure, Path A/B integration. https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz * Review fixes: pre-compute hot-loop invariants, import normalizeName - Pre-compute seededSlots and getSeededMatchOrder(32) before the 50k simulation loop — was being recomputed every iteration - Pad unseeded pool to 96 once before the loop instead of inside it - Inline bracket-building in the hot loop using pre-computed seededSlots; removes the per-iteration call to buildR1Bracket/getSeededMatchOrder - Remove dead SEEDED_R1_PAIRS constant (was never referenced) - Import normalizeName from ~/lib/fuzzy-match instead of redefining it locally https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz * Fix lint failures: unused vars, eqeqeq, toSorted - Remove unused seededSet/unseededSet variables in test - Replace != null with !== null && !== undefined (eqeqeq rule) - Replace .sort() with .toSorted() in simulator and route (unicorn/no-array-sort) https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz * Fix TS2552: restore seededSet declaration removed during lint fix https://claude.ai/code/session_01WZ6FjMmC2eBeZ1564M9Ruz --------- Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
parent
efbd28b446
commit
8c3663e01b
11 changed files with 5997 additions and 4 deletions
|
|
@ -302,6 +302,73 @@ export const SIMPLE_32: BracketTemplate = {
|
||||||
],
|
],
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* PDC World Darts Championship (128 players)
|
||||||
|
* R1 (128) → R2 (64) → R3 (32) → R4 (16) → Quarterfinals → Semifinals → Final
|
||||||
|
* Only Quarterfinals and beyond score points.
|
||||||
|
*
|
||||||
|
* Match formats:
|
||||||
|
* R1: best-of-3 sets (first to 2)
|
||||||
|
* R2: best-of-5 sets (first to 3)
|
||||||
|
* R3: best-of-5 sets (first to 3)
|
||||||
|
* R4: best-of-7 sets (first to 4)
|
||||||
|
* QF: best-of-7 sets (first to 4)
|
||||||
|
* SF: best-of-11 sets (first to 6)
|
||||||
|
* Final: best-of-13 sets (first to 7)
|
||||||
|
*
|
||||||
|
* Seeding: top 32 seeds placed in fixed positions; remaining 96 randomly drawn.
|
||||||
|
*/
|
||||||
|
export const DARTS_128: BracketTemplate = {
|
||||||
|
id: "darts_128",
|
||||||
|
name: "PDC World Darts Championship (128 Players)",
|
||||||
|
totalTeams: 128,
|
||||||
|
scoringStartsAtRound: "Quarterfinals",
|
||||||
|
rounds: [
|
||||||
|
{
|
||||||
|
name: "Round 1",
|
||||||
|
matchCount: 64,
|
||||||
|
feedsInto: "Round 2",
|
||||||
|
isScoring: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Round 2",
|
||||||
|
matchCount: 32,
|
||||||
|
feedsInto: "Round 3",
|
||||||
|
isScoring: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Round 3",
|
||||||
|
matchCount: 16,
|
||||||
|
feedsInto: "Round 4",
|
||||||
|
isScoring: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Round 4",
|
||||||
|
matchCount: 8,
|
||||||
|
feedsInto: "Quarterfinals",
|
||||||
|
isScoring: false,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Quarterfinals",
|
||||||
|
matchCount: 4,
|
||||||
|
feedsInto: "Semi-Finals",
|
||||||
|
isScoring: true, // QF losers share 5th–8th
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Semi-Finals",
|
||||||
|
matchCount: 2,
|
||||||
|
feedsInto: "Final",
|
||||||
|
isScoring: true, // SF losers share 3rd–4th
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: "Final",
|
||||||
|
matchCount: 1,
|
||||||
|
feedsInto: null,
|
||||||
|
isScoring: true, // Winner 1st, Loser 2nd
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* NCAA March Madness (68 teams)
|
* NCAA March Madness (68 teams)
|
||||||
* First Four (play-in) → Round of 64 → Round of 32 → Sweet Sixteen → Elite Eight → Final Four → Championship
|
* First Four (play-in) → Round of 64 → Round of 32 → Sweet Sixteen → Elite Eight → Final Four → Championship
|
||||||
|
|
@ -578,6 +645,7 @@ export const BRACKET_TEMPLATES: Record<string, BracketTemplate> = {
|
||||||
nfl_14: NFL_14,
|
nfl_14: NFL_14,
|
||||||
afl_10: AFL_10,
|
afl_10: AFL_10,
|
||||||
fifa_48: FIFA_48,
|
fifa_48: FIFA_48,
|
||||||
|
darts_128: DARTS_128,
|
||||||
};
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|
|
||||||
|
|
@ -29,6 +29,7 @@ export interface ParticipantEV {
|
||||||
source: ProbabilitySource | null;
|
source: ProbabilitySource | null;
|
||||||
sourceOdds: number | null;
|
sourceOdds: number | null;
|
||||||
sourceElo?: number | null;
|
sourceElo?: number | null;
|
||||||
|
worldRanking?: number | null;
|
||||||
calculatedAt: Date;
|
calculatedAt: Date;
|
||||||
updatedAt: Date;
|
updatedAt: Date;
|
||||||
}
|
}
|
||||||
|
|
@ -362,12 +363,13 @@ export async function batchSaveSourceOdds(
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persist raw Elo ratings for a batch of participants (used by Elo-based simulators like snooker_bracket).
|
* Persist raw Elo ratings (and optional world rankings) for a batch of participants.
|
||||||
|
* Used by Elo-based simulators like snooker_bracket and darts_bracket.
|
||||||
* Creates stub records if none exist; does not touch probabilities or EV.
|
* Creates stub records if none exist; does not touch probabilities or EV.
|
||||||
* Uses INSERT ... ON CONFLICT DO UPDATE to avoid N+1 queries.
|
* Uses INSERT ... ON CONFLICT DO UPDATE to avoid N+1 queries.
|
||||||
*/
|
*/
|
||||||
export async function batchSaveSourceElos(
|
export async function batchSaveSourceElos(
|
||||||
inputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number }>
|
inputs: Array<{ participantId: string; sportsSeasonId: string; sourceElo: number; worldRanking?: number | null }>
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
if (inputs.length === 0) return;
|
if (inputs.length === 0) return;
|
||||||
const db = database();
|
const db = database();
|
||||||
|
|
@ -376,7 +378,7 @@ export async function batchSaveSourceElos(
|
||||||
await db
|
await db
|
||||||
.insert(participantExpectedValues)
|
.insert(participantExpectedValues)
|
||||||
.values(
|
.values(
|
||||||
inputs.map(({ participantId, sportsSeasonId, sourceElo }) => ({
|
inputs.map(({ participantId, sportsSeasonId, sourceElo, worldRanking }) => ({
|
||||||
participantId,
|
participantId,
|
||||||
sportsSeasonId,
|
sportsSeasonId,
|
||||||
probFirst: "0",
|
probFirst: "0",
|
||||||
|
|
@ -390,6 +392,7 @@ export async function batchSaveSourceElos(
|
||||||
expectedValue: "0",
|
expectedValue: "0",
|
||||||
source: "elo_simulation" as const,
|
source: "elo_simulation" as const,
|
||||||
sourceElo,
|
sourceElo,
|
||||||
|
worldRanking: worldRanking ?? null,
|
||||||
calculatedAt: now,
|
calculatedAt: now,
|
||||||
updatedAt: now,
|
updatedAt: now,
|
||||||
}))
|
}))
|
||||||
|
|
@ -398,6 +401,7 @@ export async function batchSaveSourceElos(
|
||||||
target: [participantExpectedValues.participantId, participantExpectedValues.sportsSeasonId],
|
target: [participantExpectedValues.participantId, participantExpectedValues.sportsSeasonId],
|
||||||
set: {
|
set: {
|
||||||
sourceElo: sql`excluded.source_elo`,
|
sourceElo: sql`excluded.source_elo`,
|
||||||
|
worldRanking: sql`excluded.world_ranking`,
|
||||||
updatedAt: sql`excluded.updated_at`,
|
updatedAt: sql`excluded.updated_at`,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -95,6 +95,10 @@ export default [
|
||||||
"sports-seasons/:id/surface-elo",
|
"sports-seasons/:id/surface-elo",
|
||||||
"routes/admin.sports-seasons.$id.surface-elo.tsx"
|
"routes/admin.sports-seasons.$id.surface-elo.tsx"
|
||||||
),
|
),
|
||||||
|
route(
|
||||||
|
"sports-seasons/:id/darts-elo",
|
||||||
|
"routes/admin.sports-seasons.$id.darts-elo.tsx"
|
||||||
|
),
|
||||||
route(
|
route(
|
||||||
"sports-seasons/:id/golf-skills",
|
"sports-seasons/:id/golf-skills",
|
||||||
"routes/admin.sports-seasons.$id.golf-skills.tsx"
|
"routes/admin.sports-seasons.$id.golf-skills.tsx"
|
||||||
|
|
|
||||||
470
app/routes/admin.sports-seasons.$id.darts-elo.tsx
Normal file
470
app/routes/admin.sports-seasons.$id.darts-elo.tsx
Normal file
|
|
@ -0,0 +1,470 @@
|
||||||
|
import { Form, redirect, useLoaderData, useActionData, useNavigation } from 'react-router';
|
||||||
|
import type { Route } from './+types/admin.sports-seasons.$id.darts-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: `Darts 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 darts simulation:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
message: error instanceof Error ? error.message : 'Simulation failed',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return redirect(`/admin/sports-seasons/${sportsSeasonId}/expected-values`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AdminSportsSeasonDartsElo() {
|
||||||
|
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, 2099, 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, 2099, 1" (name, elo, world ranking)
|
||||||
|
// "Player Name, 2099" (name, elo — ranking omitted)
|
||||||
|
// "Player Name: 2099: 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">Darts Elo & 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, 2099, 1</code> (name, Elo, world ranking).
|
||||||
|
World ranking is optional — omit it and the simulator will use Elo order for seeding.
|
||||||
|
Player names are fuzzy-matched to participants.
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-4">
|
||||||
|
<Textarea
|
||||||
|
placeholder={`Luke Littler, 2099, 1\nMichael van Gerwen, 1950, 2\nLuke Humphries, 1947, 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} → 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 & Rankings</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
Enter each player's Darts Elo and world ranking. World ranking determines bracket seeding
|
||||||
|
(top 32 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="1800"
|
||||||
|
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 128 players</li>
|
||||||
|
<li>Top 32 seeds placed in fixed bracket positions; remaining 96 randomly drawn per simulation</li>
|
||||||
|
<li>Per-set win probability: p = 1 / (1 + e^(−ΔElo/500))</li>
|
||||||
|
<li>Match win probability via Bernoulli sets 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 1st–8th place buckets</li>
|
||||||
|
<li>Calculate expected fantasy value per player</li>
|
||||||
|
</ol>
|
||||||
|
<div className="mt-4 text-muted-foreground text-xs space-y-1">
|
||||||
|
<div>Round formats: R1 bo3, R2/R3 bo5, R4/QF bo7, SF bo11, Final bo13</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>
|
||||||
|
);
|
||||||
|
}
|
||||||
455
app/services/simulations/__tests__/darts-simulator.test.ts
Normal file
455
app/services/simulations/__tests__/darts-simulator.test.ts
Normal file
|
|
@ -0,0 +1,455 @@
|
||||||
|
import { describe, it, expect, vi, beforeEach, type MockInstance } from "vitest";
|
||||||
|
import {
|
||||||
|
setWinProb,
|
||||||
|
matchWinProb,
|
||||||
|
getSeededMatchOrder,
|
||||||
|
buildR1Bracket,
|
||||||
|
DartsSimulator,
|
||||||
|
} from "../darts-simulator";
|
||||||
|
|
||||||
|
// ─── Pure math: setWinProb ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("setWinProb", () => {
|
||||||
|
it("returns 0.5 for equal Elo", () => {
|
||||||
|
expect(setWinProb(1800, 1800)).toBeCloseTo(0.5, 5);
|
||||||
|
expect(setWinProb(2000, 2000)).toBeCloseTo(0.5, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns > 0.5 for positive Elo advantage, < 0.5 for negative", () => {
|
||||||
|
expect(setWinProb(2000, 1700)).toBeGreaterThan(0.5);
|
||||||
|
expect(setWinProb(1700, 2000)).toBeLessThan(0.5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("is symmetric: setWinProb(a, b) + setWinProb(b, a) = 1", () => {
|
||||||
|
expect(setWinProb(2000, 1700) + setWinProb(1700, 2000)).toBeCloseTo(1.0, 5);
|
||||||
|
expect(setWinProb(2099, 1952) + setWinProb(1952, 2099)).toBeCloseTo(1.0, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("larger Elo gap → higher win probability (monotonic)", () => {
|
||||||
|
const p100 = setWinProb(1900, 1800);
|
||||||
|
const p300 = setWinProb(2100, 1800);
|
||||||
|
const p500 = setWinProb(2300, 1800);
|
||||||
|
expect(p300).toBeGreaterThan(p100);
|
||||||
|
expect(p500).toBeGreaterThan(p300);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns value strictly in (0, 1) for any finite Elo", () => {
|
||||||
|
expect(setWinProb(3000, 1000)).toBeLessThan(1);
|
||||||
|
expect(setWinProb(3000, 1000)).toBeGreaterThan(0);
|
||||||
|
expect(setWinProb(1000, 3000)).toBeLessThan(1);
|
||||||
|
expect(setWinProb(1000, 3000)).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("calibration: 100-pt gap → ~55% per set (ELO_DIVISOR=500)", () => {
|
||||||
|
// 1 / (1 + e^(-100/500)) ≈ 0.5499
|
||||||
|
expect(setWinProb(1900, 1800)).toBeCloseTo(0.5499, 2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Pure math: matchWinProb ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("matchWinProb", () => {
|
||||||
|
it("returns 0.5 for equal players (p=0.5) at any match length", () => {
|
||||||
|
// PDC formats: bo3 (S=2), bo5 (S=3), bo7 (S=4), bo11 (S=6), bo13 (S=7)
|
||||||
|
expect(matchWinProb(0.5, 2)).toBeCloseTo(0.5, 3);
|
||||||
|
expect(matchWinProb(0.5, 3)).toBeCloseTo(0.5, 3);
|
||||||
|
expect(matchWinProb(0.5, 4)).toBeCloseTo(0.5, 3);
|
||||||
|
expect(matchWinProb(0.5, 6)).toBeCloseTo(0.5, 3);
|
||||||
|
expect(matchWinProb(0.5, 7)).toBeCloseTo(0.5, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("approaches 1.0 as p → 1.0", () => {
|
||||||
|
expect(matchWinProb(0.9999, 2)).toBeCloseTo(1.0, 3);
|
||||||
|
expect(matchWinProb(0.9999, 7)).toBeCloseTo(1.0, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("approaches 0.0 as p → 0.0", () => {
|
||||||
|
expect(matchWinProb(0.0001, 2)).toBeCloseTo(0.0, 3);
|
||||||
|
expect(matchWinProb(0.0001, 7)).toBeCloseTo(0.0, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("longer matches amplify stronger player's advantage", () => {
|
||||||
|
// p=0.6: win prob should be higher in best-of-13 than best-of-3
|
||||||
|
const bo3 = matchWinProb(0.6, 2);
|
||||||
|
const bo13 = matchWinProb(0.6, 7);
|
||||||
|
expect(bo13).toBeGreaterThan(bo3);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("match win prob + opponent win prob sums to 1.0", () => {
|
||||||
|
const p = 0.63;
|
||||||
|
expect(matchWinProb(p, 3) + matchWinProb(1 - p, 3)).toBeCloseTo(1.0, 5);
|
||||||
|
expect(matchWinProb(p, 6) + matchWinProb(1 - p, 6)).toBeCloseTo(1.0, 5);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("best-of-3 (S=2): reference check for p=0.6 → ~0.648", () => {
|
||||||
|
// P(2-0) = 0.6^2 = 0.36; P(2-1) = 2 * 0.6^2 * 0.4 = 0.288; total = 0.648
|
||||||
|
expect(matchWinProb(0.6, 2)).toBeCloseTo(0.648, 3);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Bracket structure: getSeededMatchOrder ──────────────────────────────────
|
||||||
|
|
||||||
|
describe("getSeededMatchOrder", () => {
|
||||||
|
it("for n=2, returns [1, 2]", () => {
|
||||||
|
expect(getSeededMatchOrder(2)).toEqual([1, 2]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("for n=4, seed 1 vs 4 in top half, seed 2 vs 3 in bottom half", () => {
|
||||||
|
// Algorithm: start [1,2] → expand to [1,4,2,3]
|
||||||
|
expect(getSeededMatchOrder(4)).toEqual([1, 4, 2, 3]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("for n=8, seed 1 and seed 2 are in opposite halves", () => {
|
||||||
|
const order = getSeededMatchOrder(8);
|
||||||
|
expect(order).toHaveLength(8);
|
||||||
|
const idx1 = order.indexOf(1);
|
||||||
|
const idx2 = order.indexOf(2);
|
||||||
|
// Seeds 1 and 2 should be in different halves (0-3 vs 4-7)
|
||||||
|
expect(Math.floor(idx1 / 4)).not.toBe(Math.floor(idx2 / 4));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("for n=32, contains all seeds 1–32 exactly once", () => {
|
||||||
|
const order = getSeededMatchOrder(32);
|
||||||
|
expect(order).toHaveLength(32);
|
||||||
|
const sorted = [...order].toSorted((a, b) => a - b);
|
||||||
|
expect(sorted).toEqual(Array.from({ length: 32 }, (_, i) => i + 1));
|
||||||
|
});
|
||||||
|
|
||||||
|
it("for n=32, seed 1 and seed 2 are in opposite halves", () => {
|
||||||
|
const order = getSeededMatchOrder(32);
|
||||||
|
const idx1 = order.indexOf(1);
|
||||||
|
const idx2 = order.indexOf(2);
|
||||||
|
// Opposite halves: one in [0,15], other in [16,31]
|
||||||
|
expect(Math.floor(idx1 / 16)).not.toBe(Math.floor(idx2 / 16));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Bracket structure: buildR1Bracket ───────────────────────────────────────
|
||||||
|
|
||||||
|
describe("buildR1Bracket", () => {
|
||||||
|
const seeded = Array.from({ length: 32 }, (_, i) => `seed-${i + 1}`);
|
||||||
|
const unseeded = Array.from({ length: 96 }, (_, i) => `unseed-${i}`);
|
||||||
|
|
||||||
|
it("returns exactly 64 pairs", () => {
|
||||||
|
const pairs = buildR1Bracket(seeded, unseeded);
|
||||||
|
expect(pairs).toHaveLength(64);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("covers all 128 players (32 seeded + 96 unseeded)", () => {
|
||||||
|
const pairs = buildR1Bracket(seeded, unseeded);
|
||||||
|
const allPlayers = pairs.flat();
|
||||||
|
expect(allPlayers).toHaveLength(128);
|
||||||
|
|
||||||
|
for (const [a, b] of pairs) {
|
||||||
|
expect(a).toBeTruthy();
|
||||||
|
expect(b).toBeTruthy();
|
||||||
|
}
|
||||||
|
|
||||||
|
// All seeded players appear exactly once
|
||||||
|
for (const s of seeded) {
|
||||||
|
expect(allPlayers.filter(p => p === s)).toHaveLength(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// All unseeded players appear exactly once
|
||||||
|
for (const u of unseeded) {
|
||||||
|
expect(allPlayers.filter(p => p === u)).toHaveLength(1);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("each of the 32 seeded players faces an unseeded opponent in their R1 match", () => {
|
||||||
|
const pairs = buildR1Bracket(seeded, unseeded);
|
||||||
|
const seededSet = new Set(seeded);
|
||||||
|
|
||||||
|
// First 32 pairs: seeded vs unseeded
|
||||||
|
for (let i = 0; i < 32; i++) {
|
||||||
|
const [a, b] = pairs[i];
|
||||||
|
const aSeeded = seededSet.has(a);
|
||||||
|
const bSeeded = seededSet.has(b);
|
||||||
|
// One must be seeded, the other unseeded
|
||||||
|
expect(aSeeded !== bSeeded).toBe(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("last 32 pairs: all unseeded vs unseeded", () => {
|
||||||
|
const pairs = buildR1Bracket(seeded, unseeded);
|
||||||
|
const seededSet = new Set(seeded);
|
||||||
|
|
||||||
|
for (let i = 32; i < 64; i++) {
|
||||||
|
const [a, b] = pairs[i];
|
||||||
|
expect(seededSet.has(a)).toBe(false);
|
||||||
|
expect(seededSet.has(b)).toBe(false);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Integration tests with mocked DB ────────────────────────────────────────
|
||||||
|
|
||||||
|
const PARTICIPANT_IDS = Array.from({ length: 128 }, (_, i) => `player-${i + 1}`);
|
||||||
|
const ELO_BASE = 1750;
|
||||||
|
|
||||||
|
function makeMatch(
|
||||||
|
round: string,
|
||||||
|
matchNumber: number,
|
||||||
|
p1Index: number,
|
||||||
|
p2Index: number,
|
||||||
|
opts: { winnerId?: string; loserId?: string; isComplete?: boolean } = {}
|
||||||
|
) {
|
||||||
|
return {
|
||||||
|
id: `${round}-match-${matchNumber}`,
|
||||||
|
scoringEventId: "event-1",
|
||||||
|
round,
|
||||||
|
matchNumber,
|
||||||
|
participant1Id: PARTICIPANT_IDS[p1Index],
|
||||||
|
participant2Id: PARTICIPANT_IDS[p2Index],
|
||||||
|
winnerId: opts.winnerId ?? null,
|
||||||
|
loserId: opts.loserId ?? null,
|
||||||
|
isComplete: opts.isComplete ?? false,
|
||||||
|
isScoring: true,
|
||||||
|
templateRound: round,
|
||||||
|
seedInfo: null,
|
||||||
|
participant1Score: null,
|
||||||
|
participant2Score: null,
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build a full 7-round bracket (128 players, 127 matches). */
|
||||||
|
function makeFullBracket(): ReturnType<typeof makeMatch>[] {
|
||||||
|
const matches: ReturnType<typeof makeMatch>[] = [];
|
||||||
|
for (let i = 0; i < 64; i++) matches.push(makeMatch("Round 1", i + 1, i * 2, i * 2 + 1));
|
||||||
|
for (let i = 0; i < 32; i++) matches.push(makeMatch("Round 2", i + 1, 0, 1));
|
||||||
|
for (let i = 0; i < 16; i++) matches.push(makeMatch("Round 3", i + 1, 0, 1));
|
||||||
|
for (let i = 0; i < 8; i++) matches.push(makeMatch("Round 4", i + 1, 0, 1));
|
||||||
|
for (let i = 0; i < 4; i++) matches.push(makeMatch("Quarter-Finals", i + 1, 0, 1));
|
||||||
|
for (let i = 0; i < 2; i++) matches.push(makeMatch("Semi-Finals", i + 1, 0, 1));
|
||||||
|
matches.push(makeMatch("Final", 1, 0, 1));
|
||||||
|
return matches;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeEVRows(eloOverride?: Map<string, number>) {
|
||||||
|
return PARTICIPANT_IDS.map((participantId) => ({
|
||||||
|
participantId,
|
||||||
|
sourceElo: eloOverride?.get(participantId) ?? ELO_BASE,
|
||||||
|
worldRanking: null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
vi.mock("~/database/context", () => ({
|
||||||
|
database: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
describe("DartsSimulator.simulate() — Path A (bracket populated)", () => {
|
||||||
|
let mockDb: {
|
||||||
|
query: {
|
||||||
|
scoringEvents: { findFirst: MockInstance };
|
||||||
|
playoffMatches: { findMany: MockInstance };
|
||||||
|
};
|
||||||
|
select: MockInstance;
|
||||||
|
};
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const { database } = await import("~/database/context");
|
||||||
|
|
||||||
|
mockDb = {
|
||||||
|
query: {
|
||||||
|
scoringEvents: { findFirst: vi.fn() },
|
||||||
|
playoffMatches: { findMany: vi.fn() },
|
||||||
|
},
|
||||||
|
select: vi.fn().mockReturnValue({
|
||||||
|
from: vi.fn().mockReturnValue({
|
||||||
|
where: vi.fn().mockResolvedValue(makeEVRows()),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
(database as unknown as MockInstance).mockReturnValue(mockDb);
|
||||||
|
|
||||||
|
mockDb.query.scoringEvents.findFirst.mockResolvedValue({
|
||||||
|
id: "event-1",
|
||||||
|
sportsSeasonId: "season-1",
|
||||||
|
eventType: "playoff_game",
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws if bracket does not have exactly 7 rounds", async () => {
|
||||||
|
// Only 6 rounds (missing Final)
|
||||||
|
const matches = [
|
||||||
|
...Array.from({ length: 64 }, (_, i) => makeMatch("Round 1", i + 1, i * 2, i * 2 + 1)),
|
||||||
|
...Array.from({ length: 32 }, (_, i) => makeMatch("Round 2", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 16 }, (_, i) => makeMatch("Round 3", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 8 }, (_, i) => makeMatch("Round 4", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 4 }, (_, i) => makeMatch("Quarter-Finals", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 2 }, (_, i) => makeMatch("Semi-Finals", i + 1, 0, 1)),
|
||||||
|
];
|
||||||
|
mockDb.query.playoffMatches.findMany.mockResolvedValue(matches);
|
||||||
|
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
await expect(sim.simulate("season-1")).rejects.toThrow(/Expected 7 rounds/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws if R1 does not have 64 matches", async () => {
|
||||||
|
const matches = [
|
||||||
|
...Array.from({ length: 32 }, (_, i) => makeMatch("Round 1", i + 1, i * 2, i * 2 + 1)),
|
||||||
|
...Array.from({ length: 32 }, (_, i) => makeMatch("Round 2", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 16 }, (_, i) => makeMatch("Round 3", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 8 }, (_, i) => makeMatch("Round 4", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 4 }, (_, i) => makeMatch("Quarter-Finals", i + 1, 0, 1)),
|
||||||
|
...Array.from({ length: 2 }, (_, i) => makeMatch("Semi-Finals", i + 1, 0, 1)),
|
||||||
|
makeMatch("Final", 1, 0, 1),
|
||||||
|
];
|
||||||
|
mockDb.query.playoffMatches.findMany.mockResolvedValue(matches);
|
||||||
|
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
await expect(sim.simulate("season-1")).rejects.toThrow(/Expected 64 R1 matches/);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 128 results with valid probability distributions", async () => {
|
||||||
|
mockDb.query.playoffMatches.findMany.mockResolvedValue(makeFullBracket());
|
||||||
|
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
const results = await sim.simulate("season-1");
|
||||||
|
|
||||||
|
expect(results).toHaveLength(128);
|
||||||
|
for (const r of results) {
|
||||||
|
const p = r.probabilities;
|
||||||
|
expect(p.probFirst).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(p.probFirst).toBeLessThanOrEqual(1);
|
||||||
|
const sum = p.probFirst + p.probSecond + p.probThird + p.probFourth +
|
||||||
|
p.probFifth + p.probSixth + p.probSeventh + p.probEighth;
|
||||||
|
expect(sum).toBeGreaterThanOrEqual(0);
|
||||||
|
expect(sum).toBeLessThanOrEqual(1.001);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("each probability column sums to 1.0 across all 128 participants", async () => {
|
||||||
|
mockDb.query.playoffMatches.findMany.mockResolvedValue(makeFullBracket());
|
||||||
|
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
const results = await sim.simulate("season-1");
|
||||||
|
|
||||||
|
const keys = [
|
||||||
|
"probFirst", "probSecond", "probThird", "probFourth",
|
||||||
|
"probFifth", "probSixth", "probSeventh", "probEighth",
|
||||||
|
] as const;
|
||||||
|
for (const key of keys) {
|
||||||
|
const colSum = results.reduce((s, r) => s + r.probabilities[key], 0);
|
||||||
|
expect(colSum).toBeCloseTo(1.0, 2);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("labels results with darts_world_championship_monte_carlo source", async () => {
|
||||||
|
mockDb.query.playoffMatches.findMany.mockResolvedValue(makeFullBracket());
|
||||||
|
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
const results = await sim.simulate("season-1");
|
||||||
|
|
||||||
|
expect(results.every(r => r.source === "darts_world_championship_monte_carlo")).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Path B: pre-bracket simulation ──────────────────────────────────────────
|
||||||
|
|
||||||
|
describe("DartsSimulator.simulate() — Path B (pre-bracket)", () => {
|
||||||
|
let mockDb: {
|
||||||
|
query: {
|
||||||
|
scoringEvents: { findFirst: MockInstance };
|
||||||
|
playoffMatches: { findMany: MockInstance };
|
||||||
|
};
|
||||||
|
select: MockInstance;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 128 participants with world rankings
|
||||||
|
const SEASON_PARTICIPANTS = Array.from({ length: 128 }, (_, i) => ({
|
||||||
|
id: `player-${i + 1}`,
|
||||||
|
name: `Player ${i + 1}`,
|
||||||
|
}));
|
||||||
|
|
||||||
|
function makeEVRowsWithRankings() {
|
||||||
|
return SEASON_PARTICIPANTS.map((p, i) => ({
|
||||||
|
participantId: p.id,
|
||||||
|
sourceElo: ELO_BASE - i * 2, // higher seed = higher Elo
|
||||||
|
worldRanking: i + 1,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
const { database } = await import("~/database/context");
|
||||||
|
|
||||||
|
const eloRows = makeEVRowsWithRankings();
|
||||||
|
const participantRows = SEASON_PARTICIPANTS;
|
||||||
|
|
||||||
|
mockDb = {
|
||||||
|
query: {
|
||||||
|
scoringEvents: { findFirst: vi.fn() },
|
||||||
|
playoffMatches: { findMany: vi.fn() },
|
||||||
|
},
|
||||||
|
select: vi.fn()
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(eloRows) }),
|
||||||
|
})
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(participantRows) }),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
(database as unknown as MockInstance).mockReturnValue(mockDb);
|
||||||
|
|
||||||
|
mockDb.query.scoringEvents.findFirst.mockResolvedValue(null);
|
||||||
|
mockDb.query.playoffMatches.findMany.mockResolvedValue([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("returns 128 results when bracket is not yet populated", async () => {
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
const results = await sim.simulate("season-1");
|
||||||
|
|
||||||
|
expect(results).toHaveLength(128);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("each probability column sums to 1.0 across all 128 participants", async () => {
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
const results = await sim.simulate("season-1");
|
||||||
|
|
||||||
|
const keys = [
|
||||||
|
"probFirst", "probSecond", "probThird", "probFourth",
|
||||||
|
"probFifth", "probSixth", "probSeventh", "probEighth",
|
||||||
|
] as const;
|
||||||
|
for (const key of keys) {
|
||||||
|
const colSum = results.reduce((s, r) => s + r.probabilities[key], 0);
|
||||||
|
expect(colSum).toBeCloseTo(1.0, 2);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
it("world #1 (highest Elo) has the highest probFirst", async () => {
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
const results = await sim.simulate("season-1");
|
||||||
|
|
||||||
|
const sorted = [...results].toSorted((a, b) => b.probabilities.probFirst - a.probabilities.probFirst);
|
||||||
|
// player-1 is world #1 with the highest Elo — should have highest win probability
|
||||||
|
expect(sorted[0].participantId).toBe("player-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("throws if fewer than 2 participants exist", async () => {
|
||||||
|
const { database } = await import("~/database/context");
|
||||||
|
const tooFew = [{ id: "player-1", name: "Solo" }];
|
||||||
|
const eloRowsFew = [{ participantId: "player-1", sourceElo: ELO_BASE, worldRanking: 1 }];
|
||||||
|
|
||||||
|
(database as unknown as MockInstance).mockReturnValue({
|
||||||
|
...mockDb,
|
||||||
|
query: {
|
||||||
|
scoringEvents: { findFirst: vi.fn().mockResolvedValue(null) },
|
||||||
|
playoffMatches: { findMany: vi.fn().mockResolvedValue([]) },
|
||||||
|
},
|
||||||
|
select: vi.fn()
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(eloRowsFew) }),
|
||||||
|
})
|
||||||
|
.mockReturnValueOnce({
|
||||||
|
from: vi.fn().mockReturnValue({ where: vi.fn().mockResolvedValue(tooFew) }),
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const sim = new DartsSimulator();
|
||||||
|
await expect(sim.simulate("season-1")).rejects.toThrow(/at least 2 participants/);
|
||||||
|
});
|
||||||
|
});
|
||||||
629
app/services/simulations/darts-simulator.ts
Normal file
629
app/services/simulations/darts-simulator.ts
Normal file
|
|
@ -0,0 +1,629 @@
|
||||||
|
/**
|
||||||
|
* PDC World Darts Championship Simulator
|
||||||
|
*
|
||||||
|
* Monte Carlo simulation of the PDC World Darts Championship.
|
||||||
|
* The tournament is a 128-player single-elimination bracket with 7 rounds,
|
||||||
|
* using best-of-sets formats that increase in length each round.
|
||||||
|
*
|
||||||
|
* Algorithm:
|
||||||
|
* 1. Load all participants and their Elo + world ranking from participantExpectedValues.
|
||||||
|
* 2. Two simulation paths:
|
||||||
|
* a. Bracket populated: simulate from actual draw, respecting completed matches.
|
||||||
|
* b. Pre-bracket: top 32 seeds placed into fixed balanced bracket positions;
|
||||||
|
* remaining 96 players randomly drawn into unseeded slots each simulation.
|
||||||
|
* 3. Compute per-set win probability using the logistic sigmoid:
|
||||||
|
* p_set = 1 / (1 + e^(-(Elo1 - Elo2) / ELO_DIVISOR))
|
||||||
|
* 4. Compute match win probability using the Bernoulli sets model:
|
||||||
|
* P(win) = sum_{w2=0}^{S-1} C(S-1+w2, w2) * p^S * (1-p)^w2
|
||||||
|
* where S = sets to win, which varies by round.
|
||||||
|
* 5. Track integer placement counts per tier across 50,000 simulations.
|
||||||
|
* 6. Convert to probability distributions using exact denominators (column sums = 1.0).
|
||||||
|
*
|
||||||
|
* Round format (PDC World Championship):
|
||||||
|
* R1 (R128): best-of-3 sets, first to 2
|
||||||
|
* R2 (R64): best-of-5 sets, first to 3
|
||||||
|
* R3 (R32): best-of-5 sets, first to 3
|
||||||
|
* R4 (R16): best-of-7 sets, first to 4
|
||||||
|
* QF: best-of-7 sets, first to 4
|
||||||
|
* SF: best-of-11 sets, first to 6
|
||||||
|
* Final: best-of-13 sets, first to 7
|
||||||
|
*
|
||||||
|
* Seeding (pre-bracket path):
|
||||||
|
* Top 32 players (by world ranking) are seeded into fixed bracket positions
|
||||||
|
* using the standard balanced bracket structure:
|
||||||
|
* R1 seeds: 1v32, 16v17, 9v24, 8v25 (top half) + 5v28, 12v21, 13v20, 4v29
|
||||||
|
* 3v30, 14v19, 11v22, 6v27 (bottom half) + 7v26, 10v23, 15v18, 2v31
|
||||||
|
* Each seed's unseeded opponent slot is randomly filled from the 96 unseeded players
|
||||||
|
* in each simulation run — spreading the draw uncertainty across all simulations.
|
||||||
|
*
|
||||||
|
* Placement bucketing (8-slot probability model):
|
||||||
|
* probFirst → Champion
|
||||||
|
* probSecond → Finalist
|
||||||
|
* probThird/Fourth → SF losers (2/sim)
|
||||||
|
* probFifth–Eighth → QF losers (4/sim)
|
||||||
|
* Earlier rounds → all 0
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { database } from "~/database/context";
|
||||||
|
import { eq, and } from "drizzle-orm";
|
||||||
|
import * as schema from "~/database/schema";
|
||||||
|
import type { Simulator, SimulationResult } from "./types";
|
||||||
|
|
||||||
|
// ─── Simulation parameters ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
const NUM_SIMULATIONS = 50000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Controls how much Elo gaps affect per-set win probability.
|
||||||
|
* Higher = softer probabilities (more randomness).
|
||||||
|
* Lower = sharper (Elo differences matter more).
|
||||||
|
*
|
||||||
|
* Standard chess uses 400. Snooker (more random than chess) uses 700.
|
||||||
|
* Darts is moderately volatile; 500 gives:
|
||||||
|
* 100-pt gap → ~55% per set
|
||||||
|
* 300-pt gap → ~63% per set
|
||||||
|
* 500-pt gap → ~73% per set
|
||||||
|
*/
|
||||||
|
const ELO_DIVISOR = 500;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets needed to win per round, in bracket order (R1 first, Final last).
|
||||||
|
* Index 0 = R1/R128 (64 matches, best-of-3, need 2)
|
||||||
|
* Index 1 = R2/R64 (32 matches, best-of-5, need 3)
|
||||||
|
* Index 2 = R3/R32 (16 matches, best-of-5, need 3)
|
||||||
|
* Index 3 = R4/R16 (8 matches, best-of-7, need 4)
|
||||||
|
* Index 4 = QF (4 matches, best-of-7, need 4)
|
||||||
|
* Index 5 = SF (2 matches, best-of-11, need 6)
|
||||||
|
* Index 6 = Final (1 match, best-of-13, need 7)
|
||||||
|
*/
|
||||||
|
const SETS_TO_WIN = [2, 3, 3, 4, 4, 6, 7] as const;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Number of seeds that get fixed bracket positions.
|
||||||
|
* The remaining (128 - TOP_SEEDS) players are randomly drawn.
|
||||||
|
*/
|
||||||
|
const TOP_SEEDS = 32;
|
||||||
|
|
||||||
|
// ─── Math helpers ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-set win probability for player 1 vs player 2 based on Elo.
|
||||||
|
* Exported for unit testing.
|
||||||
|
*/
|
||||||
|
export function setWinProb(elo1: number, elo2: number): number {
|
||||||
|
return 1 / (1 + Math.exp(-(elo1 - elo2) / ELO_DIVISOR));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Match win probability for player 1 using the Bernoulli sets model.
|
||||||
|
* For a best-of-(2S-1) match (first to S sets):
|
||||||
|
* P(win) = sum_{w2=0}^{S-1} C(S-1+w2, w2) * p^S * (1-p)^w2
|
||||||
|
* Exported for unit testing.
|
||||||
|
*/
|
||||||
|
export function matchWinProb(p: number, setsToWin: number): number {
|
||||||
|
const S = setsToWin;
|
||||||
|
let prob = 0;
|
||||||
|
for (let w2 = 0; w2 < S; w2++) {
|
||||||
|
prob += binomialCoeff(S - 1 + w2, w2) * Math.pow(p, S) * Math.pow(1 - p, w2);
|
||||||
|
}
|
||||||
|
return prob;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Binomial coefficient C(n, k) via iterative multiplication. */
|
||||||
|
function binomialCoeff(n: number, k: number): number {
|
||||||
|
if (k === 0) return 1;
|
||||||
|
if (k > n - k) k = n - k;
|
||||||
|
let result = 1;
|
||||||
|
for (let i = 0; i < k; i++) {
|
||||||
|
result = (result * (n - i)) / (i + 1);
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns the 128-player seeded bracket R1 pair list.
|
||||||
|
* Each entry is [participantIdA, participantIdB].
|
||||||
|
* Top 32 seeded players fill fixed positions; 96 unseeded players are randomly
|
||||||
|
* shuffled and assigned to the remaining slots.
|
||||||
|
*
|
||||||
|
* Structure:
|
||||||
|
* - 32 seeded-vs-unseeded matches (seeds 1–32 each face a randomly drawn unseeded opponent)
|
||||||
|
* - 32 unseeded-vs-unseeded matches (remaining 64 unseeded players paired randomly)
|
||||||
|
* Total: 64 R1 matches ✓ (128 players)
|
||||||
|
*
|
||||||
|
* Note: in the hot simulation loop, seeded positions are pre-computed via getSeededMatchOrder
|
||||||
|
* and inlined directly — this function is used for testing and bracket-draw path only.
|
||||||
|
*
|
||||||
|
* Exported for unit testing.
|
||||||
|
*/
|
||||||
|
export function buildR1Bracket(
|
||||||
|
seededIds: string[], // exactly 32, index 0 = seed 1
|
||||||
|
unseededIds: string[] // exactly 96, shuffled
|
||||||
|
): Array<[string, string]> {
|
||||||
|
// The 32 seeded players each face one of the first 32 unseeded opponents.
|
||||||
|
// Seeds are arranged in bracket order using the standard balanced structure
|
||||||
|
// for 32 seeds (same algorithm as snooker's R32_BRACKET but generalised).
|
||||||
|
const seededMatchOrder = getSeededMatchOrder(32); // returns 32 seed positions in bracket order
|
||||||
|
|
||||||
|
const pairs: Array<[string, string]> = [];
|
||||||
|
|
||||||
|
// 32 seeded-vs-unseeded R1 matches
|
||||||
|
for (let i = 0; i < 32; i++) {
|
||||||
|
const seedPos = seededMatchOrder[i] - 1; // 0-indexed
|
||||||
|
pairs.push([seededIds[seedPos], unseededIds[i]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 32 unseeded-vs-unseeded R1 matches (players 32–95)
|
||||||
|
for (let i = 32; i < 96; i += 2) {
|
||||||
|
pairs.push([unseededIds[i], unseededIds[i + 1]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return pairs;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns seed positions in standard balanced bracket order for N seeds.
|
||||||
|
* Guarantees seed 1 and seed 2 can only meet in the Final.
|
||||||
|
* E.g. for N=4: [1, 4, 3, 2] → match order 1v4, 3v2 in the top/bottom halves.
|
||||||
|
*
|
||||||
|
* Algorithm: start with [1, 2], repeatedly interleave (n+1 - seed) complements.
|
||||||
|
* Exported for unit testing.
|
||||||
|
*/
|
||||||
|
export function getSeededMatchOrder(n: number): number[] {
|
||||||
|
let order = [1, 2];
|
||||||
|
while (order.length < n) {
|
||||||
|
const size = order.length;
|
||||||
|
const newOrder: number[] = [];
|
||||||
|
for (const seed of order) {
|
||||||
|
newOrder.push(seed);
|
||||||
|
newOrder.push(2 * size + 1 - seed);
|
||||||
|
}
|
||||||
|
order = newOrder;
|
||||||
|
}
|
||||||
|
return order;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fisher-Yates shuffle (in-place, returns array). */
|
||||||
|
function shuffle<T>(arr: T[]): T[] {
|
||||||
|
for (let i = arr.length - 1; i > 0; i--) {
|
||||||
|
const j = Math.floor(Math.random() * (i + 1));
|
||||||
|
[arr[i], arr[j]] = [arr[j], arr[i]];
|
||||||
|
}
|
||||||
|
return arr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Simulator ────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
export class DartsSimulator implements Simulator {
|
||||||
|
async simulate(sportsSeasonId: string): Promise<SimulationResult[]> {
|
||||||
|
const db = database();
|
||||||
|
|
||||||
|
// 1. Find the bracket scoring event (if it exists).
|
||||||
|
const bracketEvent = await db.query.scoringEvents.findFirst({
|
||||||
|
where: and(
|
||||||
|
eq(schema.scoringEvents.sportsSeasonId, sportsSeasonId),
|
||||||
|
eq(schema.scoringEvents.eventType, "playoff_game")
|
||||||
|
),
|
||||||
|
});
|
||||||
|
|
||||||
|
// 2. Load playoff matches (empty if bracket hasn't been drawn yet).
|
||||||
|
const allMatches = bracketEvent
|
||||||
|
? await db.query.playoffMatches.findMany({
|
||||||
|
where: eq(schema.playoffMatches.scoringEventId, bracketEvent.id),
|
||||||
|
orderBy: (m, { asc }) => [asc(m.matchNumber)],
|
||||||
|
})
|
||||||
|
: [];
|
||||||
|
|
||||||
|
// 3. Load Elo ratings and world rankings.
|
||||||
|
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));
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
if (r.worldRanking !== null && r.worldRanking !== undefined) {
|
||||||
|
rankingMap.set(r.participantId, r.worldRanking);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine simulation path.
|
||||||
|
const bracketPopulated = allMatches.some((m) => m.participant1Id && m.participant2Id);
|
||||||
|
|
||||||
|
if (bracketPopulated) {
|
||||||
|
return this.simulateBracket(allMatches, eloMap);
|
||||||
|
} else {
|
||||||
|
return this.simulatePreBracket(sportsSeasonId, eloMap, rankingMap, db);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Path A: Bracket drawn ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
private async simulateBracket(
|
||||||
|
allMatches: Awaited<ReturnType<ReturnType<typeof database>["query"]["playoffMatches"]["findMany"]>>,
|
||||||
|
eloMap: Map<string, number>
|
||||||
|
): Promise<SimulationResult[]> {
|
||||||
|
// Group matches by round, sorted by match count descending (R1 first = most matches).
|
||||||
|
const byRound = new Map<string, typeof allMatches>();
|
||||||
|
for (const m of allMatches) {
|
||||||
|
if (!byRound.has(m.round)) byRound.set(m.round, []);
|
||||||
|
byRound.get(m.round)?.push(m);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sortedRounds = [...byRound.values()]
|
||||||
|
.toSorted((a, b) => b.length - a.length)
|
||||||
|
.map((matches) => matches.sort((a, b) => a.matchNumber - b.matchNumber));
|
||||||
|
|
||||||
|
if (sortedRounds.length !== 7) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected 7 rounds for PDC World Darts Championship, found ${sortedRounds.length}. ` +
|
||||||
|
`Rounds: ${[...byRound.keys()].join(", ")}`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [r1Matches, r2Matches, r3Matches, r4Matches, qfMatches, sfMatches, finalMatches] = sortedRounds;
|
||||||
|
|
||||||
|
if (r1Matches.length !== 64) {
|
||||||
|
throw new Error(
|
||||||
|
`Expected 64 R1 matches (128-player bracket), found ${r1Matches.length}.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Collect all 128 participant IDs from R1.
|
||||||
|
const participantIds: string[] = [];
|
||||||
|
for (const m of r1Matches) {
|
||||||
|
if (!m.participant1Id || !m.participant2Id) {
|
||||||
|
throw new Error(
|
||||||
|
`R1 match ${m.matchNumber} is missing participants. ` +
|
||||||
|
`Assign all 128 players to the bracket before running simulation.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
participantIds.push(m.participant1Id, m.participant2Id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fallbackElo = 1600;
|
||||||
|
|
||||||
|
// Cache matchWinProb — Elo values are fixed across simulations.
|
||||||
|
const matchProbCache = new Map<string, number>();
|
||||||
|
const simMatch = (p1: string, p2: string, setsToWin: number): { winner: string; loser: string } => {
|
||||||
|
const elo1 = eloMap.get(p1) ?? fallbackElo;
|
||||||
|
const elo2 = eloMap.get(p2) ?? fallbackElo;
|
||||||
|
const cacheKey = `${elo1},${elo2},${setsToWin}`;
|
||||||
|
let winProb = matchProbCache.get(cacheKey);
|
||||||
|
if (winProb === undefined) {
|
||||||
|
winProb = matchWinProb(setWinProb(elo1, elo2), setsToWin);
|
||||||
|
matchProbCache.set(cacheKey, winProb);
|
||||||
|
}
|
||||||
|
const winner = Math.random() < winProb ? p1 : p2;
|
||||||
|
return { winner, loser: winner === p1 ? p2 : p1 };
|
||||||
|
};
|
||||||
|
|
||||||
|
const r1ByNum = new Map(r1Matches.map((m) => [m.matchNumber, m]));
|
||||||
|
const r2ByNum = new Map(r2Matches.map((m) => [m.matchNumber, m]));
|
||||||
|
const r3ByNum = new Map(r3Matches.map((m) => [m.matchNumber, m]));
|
||||||
|
const r4ByNum = new Map(r4Matches.map((m) => [m.matchNumber, m]));
|
||||||
|
const qfByNum = new Map(qfMatches.map((m) => [m.matchNumber, m]));
|
||||||
|
const sfByNum = new Map(sfMatches.map((m) => [m.matchNumber, m]));
|
||||||
|
const finalMatch = finalMatches[0];
|
||||||
|
|
||||||
|
const championCounts = new Map<string, number>(participantIds.map((id) => [id, 0]));
|
||||||
|
const finalistCounts = new Map<string, number>(participantIds.map((id) => [id, 0]));
|
||||||
|
const sfLoserCounts = new Map<string, number>(participantIds.map((id) => [id, 0]));
|
||||||
|
const qfLoserCounts = new Map<string, number>(participantIds.map((id) => [id, 0]));
|
||||||
|
|
||||||
|
for (let s = 0; s < NUM_SIMULATIONS; s++) {
|
||||||
|
// R1 (64 matches)
|
||||||
|
const r1Winners: string[] = [];
|
||||||
|
for (let i = 1; i <= 64; i++) {
|
||||||
|
const m = r1ByNum.get(i);
|
||||||
|
if (!m) continue;
|
||||||
|
if (m.isComplete && m.winnerId) {
|
||||||
|
r1Winners.push(m.winnerId);
|
||||||
|
} else {
|
||||||
|
const { winner } = simMatch(m.participant1Id ?? "", m.participant2Id ?? "", SETS_TO_WIN[0]);
|
||||||
|
r1Winners.push(winner);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// R2 (32 matches)
|
||||||
|
const r2Winners: string[] = [];
|
||||||
|
for (let i = 1; i <= 32; i++) {
|
||||||
|
const dbMatch = r2ByNum.get(i);
|
||||||
|
let winner: string;
|
||||||
|
if (dbMatch?.isComplete && dbMatch.winnerId) {
|
||||||
|
winner = dbMatch.winnerId;
|
||||||
|
} else {
|
||||||
|
const p1 = r1Winners[(i - 1) * 2];
|
||||||
|
const p2 = r1Winners[(i - 1) * 2 + 1];
|
||||||
|
({ winner } = simMatch(p1, p2, SETS_TO_WIN[1]));
|
||||||
|
}
|
||||||
|
r2Winners.push(winner);
|
||||||
|
}
|
||||||
|
|
||||||
|
// R3 (16 matches)
|
||||||
|
const r3Winners: string[] = [];
|
||||||
|
for (let i = 1; i <= 16; i++) {
|
||||||
|
const dbMatch = r3ByNum.get(i);
|
||||||
|
let winner: string;
|
||||||
|
if (dbMatch?.isComplete && dbMatch.winnerId) {
|
||||||
|
winner = dbMatch.winnerId;
|
||||||
|
} else {
|
||||||
|
const p1 = r2Winners[(i - 1) * 2];
|
||||||
|
const p2 = r2Winners[(i - 1) * 2 + 1];
|
||||||
|
({ winner } = simMatch(p1, p2, SETS_TO_WIN[2]));
|
||||||
|
}
|
||||||
|
r3Winners.push(winner);
|
||||||
|
}
|
||||||
|
|
||||||
|
// R4 (8 matches)
|
||||||
|
const r4Winners: string[] = [];
|
||||||
|
for (let i = 1; i <= 8; i++) {
|
||||||
|
const dbMatch = r4ByNum.get(i);
|
||||||
|
let winner: string;
|
||||||
|
if (dbMatch?.isComplete && dbMatch.winnerId) {
|
||||||
|
winner = dbMatch.winnerId;
|
||||||
|
} else {
|
||||||
|
const p1 = r3Winners[(i - 1) * 2];
|
||||||
|
const p2 = r3Winners[(i - 1) * 2 + 1];
|
||||||
|
({ winner } = simMatch(p1, p2, SETS_TO_WIN[3]));
|
||||||
|
}
|
||||||
|
r4Winners.push(winner);
|
||||||
|
}
|
||||||
|
|
||||||
|
// QF (4 matches)
|
||||||
|
const qfWinners: string[] = [];
|
||||||
|
for (let i = 1; i <= 4; i++) {
|
||||||
|
const dbMatch = qfByNum.get(i);
|
||||||
|
let winner: string;
|
||||||
|
let loser: string;
|
||||||
|
if (dbMatch?.isComplete && dbMatch.winnerId && dbMatch.loserId) {
|
||||||
|
winner = dbMatch.winnerId;
|
||||||
|
loser = dbMatch.loserId;
|
||||||
|
} else {
|
||||||
|
const p1 = r4Winners[(i - 1) * 2];
|
||||||
|
const p2 = r4Winners[(i - 1) * 2 + 1];
|
||||||
|
({ winner, loser } = simMatch(p1, p2, SETS_TO_WIN[4]));
|
||||||
|
}
|
||||||
|
qfWinners.push(winner);
|
||||||
|
qfLoserCounts.set(loser, (qfLoserCounts.get(loser) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SF (2 matches)
|
||||||
|
const sfWinners: string[] = [];
|
||||||
|
for (let i = 1; i <= 2; i++) {
|
||||||
|
const dbMatch = sfByNum.get(i);
|
||||||
|
let winner: string;
|
||||||
|
let loser: string;
|
||||||
|
if (dbMatch?.isComplete && dbMatch.winnerId && dbMatch.loserId) {
|
||||||
|
winner = dbMatch.winnerId;
|
||||||
|
loser = dbMatch.loserId;
|
||||||
|
} else {
|
||||||
|
const p1 = qfWinners[(i - 1) * 2];
|
||||||
|
const p2 = qfWinners[(i - 1) * 2 + 1];
|
||||||
|
({ winner, loser } = simMatch(p1, p2, SETS_TO_WIN[5]));
|
||||||
|
}
|
||||||
|
sfWinners.push(winner);
|
||||||
|
sfLoserCounts.set(loser, (sfLoserCounts.get(loser) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Final
|
||||||
|
let champion: string;
|
||||||
|
let finalist: string;
|
||||||
|
if (finalMatch?.isComplete && finalMatch.winnerId && finalMatch.loserId) {
|
||||||
|
champion = finalMatch.winnerId;
|
||||||
|
finalist = finalMatch.loserId;
|
||||||
|
} else {
|
||||||
|
({ winner: champion, loser: finalist } = simMatch(sfWinners[0], sfWinners[1], SETS_TO_WIN[6]));
|
||||||
|
}
|
||||||
|
championCounts.set(champion, (championCounts.get(champion) ?? 0) + 1);
|
||||||
|
finalistCounts.set(finalist, (finalistCounts.get(finalist) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildResults(participantIds, NUM_SIMULATIONS, {
|
||||||
|
championCounts,
|
||||||
|
finalistCounts,
|
||||||
|
sfLoserCounts,
|
||||||
|
qfLoserCounts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Path B: Pre-bracket simulation ──────────────────────────────────────────
|
||||||
|
// Top 32 seeds are placed into fixed bracket positions.
|
||||||
|
// Remaining 96 players are randomly drawn into unseeded slots each simulation.
|
||||||
|
|
||||||
|
private async simulatePreBracket(
|
||||||
|
sportsSeasonId: string,
|
||||||
|
eloMap: Map<string, number>,
|
||||||
|
rankingMap: Map<string, number>,
|
||||||
|
db: ReturnType<typeof database>
|
||||||
|
): Promise<SimulationResult[]> {
|
||||||
|
const allParticipants = await db
|
||||||
|
.select({ id: schema.participants.id, name: schema.participants.name })
|
||||||
|
.from(schema.participants)
|
||||||
|
.where(eq(schema.participants.sportsSeasonId, sportsSeasonId));
|
||||||
|
|
||||||
|
if (allParticipants.length < 2) {
|
||||||
|
throw new Error(
|
||||||
|
`Pre-bracket simulation requires at least 2 participants (got ${allParticipants.length}). ` +
|
||||||
|
`Add players to this sports season first.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const fallbackElo = 1600;
|
||||||
|
|
||||||
|
// Sort participants by world ranking (ascending). Fall back to Elo order (descending) for
|
||||||
|
// any without a ranking, then alphabetical as a final tiebreak.
|
||||||
|
const sorted = [...allParticipants].toSorted((a, b) => {
|
||||||
|
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; // ranked before unranked
|
||||||
|
if (rankB !== undefined) return 1;
|
||||||
|
// Both unranked — sort by Elo descending
|
||||||
|
return (eloMap.get(b.id) ?? fallbackElo) - (eloMap.get(a.id) ?? fallbackElo);
|
||||||
|
});
|
||||||
|
|
||||||
|
const topSeeds = sorted.slice(0, TOP_SEEDS).map((p) => p.id); // seeds 1–32
|
||||||
|
const unseeded = sorted.slice(TOP_SEEDS).map((p) => p.id); // remaining players
|
||||||
|
|
||||||
|
const allParticipantIds = allParticipants.map((p) => p.id);
|
||||||
|
const championCounts = new Map<string, number>(allParticipantIds.map((id) => [id, 0]));
|
||||||
|
const finalistCounts = new Map<string, number>(allParticipantIds.map((id) => [id, 0]));
|
||||||
|
const sfLoserCounts = new Map<string, number>(allParticipantIds.map((id) => [id, 0]));
|
||||||
|
const qfLoserCounts = new Map<string, number>(allParticipantIds.map((id) => [id, 0]));
|
||||||
|
|
||||||
|
// Cache set-level probabilities — fixed across all simulations.
|
||||||
|
const matchProbCache = new Map<string, number>();
|
||||||
|
const simMatch = (p1Id: string, p2Id: string, setsToWin: number): string => {
|
||||||
|
const elo1 = eloMap.get(p1Id) ?? fallbackElo;
|
||||||
|
const elo2 = eloMap.get(p2Id) ?? fallbackElo;
|
||||||
|
const cacheKey = `${elo1},${elo2},${setsToWin}`;
|
||||||
|
let winProb = matchProbCache.get(cacheKey);
|
||||||
|
if (winProb === undefined) {
|
||||||
|
winProb = matchWinProb(setWinProb(elo1, elo2), setsToWin);
|
||||||
|
matchProbCache.set(cacheKey, winProb);
|
||||||
|
}
|
||||||
|
return Math.random() < winProb ? p1Id : p2Id;
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pre-compute fixed seeded bracket positions once — only the unseeded draw changes per sim.
|
||||||
|
const seededMatchOrder = getSeededMatchOrder(TOP_SEEDS);
|
||||||
|
const seededSlots = seededMatchOrder.map(seed => topSeeds[seed - 1]);
|
||||||
|
|
||||||
|
// Pad unseeded pool to 96 once before the loop.
|
||||||
|
// In practice the admin should always load 128 players; this guards against edge cases.
|
||||||
|
const unseededPool = [...unseeded];
|
||||||
|
while (unseededPool.length + topSeeds.length < 128) {
|
||||||
|
unseededPool.push(`__bye_${unseededPool.length}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (let s = 0; s < NUM_SIMULATIONS; s++) {
|
||||||
|
// Draw: shuffle the unseeded pool — seeded positions are pre-computed.
|
||||||
|
const drawnUnseeded = shuffle([...unseededPool]);
|
||||||
|
|
||||||
|
// Build R1 pairs inline using pre-computed seeded slots.
|
||||||
|
const r1Pairs: Array<[string, string]> = [];
|
||||||
|
for (let i = 0; i < TOP_SEEDS; i++) {
|
||||||
|
r1Pairs.push([seededSlots[i], drawnUnseeded[i]]);
|
||||||
|
}
|
||||||
|
for (let i = TOP_SEEDS; i < drawnUnseeded.length; i += 2) {
|
||||||
|
r1Pairs.push([drawnUnseeded[i], drawnUnseeded[i + 1]]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// R1 (64 matches)
|
||||||
|
const r1Winners: string[] = [];
|
||||||
|
for (const [p1, p2] of r1Pairs) {
|
||||||
|
r1Winners.push(simMatch(p1, p2, SETS_TO_WIN[0]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// R2–R4 (32 / 16 / 8 matches)
|
||||||
|
const r2Winners: string[] = [];
|
||||||
|
for (let i = 0; i < r1Winners.length; i += 2) {
|
||||||
|
r2Winners.push(simMatch(r1Winners[i], r1Winners[i + 1], SETS_TO_WIN[1]));
|
||||||
|
}
|
||||||
|
const r3Winners: string[] = [];
|
||||||
|
for (let i = 0; i < r2Winners.length; i += 2) {
|
||||||
|
r3Winners.push(simMatch(r2Winners[i], r2Winners[i + 1], SETS_TO_WIN[2]));
|
||||||
|
}
|
||||||
|
const r4Winners: string[] = [];
|
||||||
|
for (let i = 0; i < r3Winners.length; i += 2) {
|
||||||
|
r4Winners.push(simMatch(r3Winners[i], r3Winners[i + 1], SETS_TO_WIN[3]));
|
||||||
|
}
|
||||||
|
|
||||||
|
// QF (4 matches)
|
||||||
|
const qfWinners: string[] = [];
|
||||||
|
for (let i = 0; i < r4Winners.length; i += 2) {
|
||||||
|
const p1 = r4Winners[i], p2 = r4Winners[i + 1];
|
||||||
|
const winner = simMatch(p1, p2, SETS_TO_WIN[4]);
|
||||||
|
const loser = winner === p1 ? p2 : p1;
|
||||||
|
qfWinners.push(winner);
|
||||||
|
qfLoserCounts.set(loser, (qfLoserCounts.get(loser) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// SF (2 matches)
|
||||||
|
const sfWinners: string[] = [];
|
||||||
|
for (let i = 0; i < qfWinners.length; i += 2) {
|
||||||
|
const p1 = qfWinners[i], p2 = qfWinners[i + 1];
|
||||||
|
const winner = simMatch(p1, p2, SETS_TO_WIN[5]);
|
||||||
|
const loser = winner === p1 ? p2 : p1;
|
||||||
|
sfWinners.push(winner);
|
||||||
|
sfLoserCounts.set(loser, (sfLoserCounts.get(loser) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Final
|
||||||
|
const champion = simMatch(sfWinners[0], sfWinners[1], SETS_TO_WIN[6]);
|
||||||
|
const finalist = champion === sfWinners[0] ? sfWinners[1] : sfWinners[0];
|
||||||
|
championCounts.set(champion, (championCounts.get(champion) ?? 0) + 1);
|
||||||
|
finalistCounts.set(finalist, (finalistCounts.get(finalist) ?? 0) + 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildResults(allParticipantIds, NUM_SIMULATIONS, {
|
||||||
|
championCounts,
|
||||||
|
finalistCounts,
|
||||||
|
sfLoserCounts,
|
||||||
|
qfLoserCounts,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Shared result builder ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
function buildResults(
|
||||||
|
participantIds: string[],
|
||||||
|
N: number,
|
||||||
|
counts: {
|
||||||
|
championCounts: Map<string, number>;
|
||||||
|
finalistCounts: Map<string, number>;
|
||||||
|
sfLoserCounts: Map<string, number>;
|
||||||
|
qfLoserCounts: Map<string, number>;
|
||||||
|
}
|
||||||
|
): SimulationResult[] {
|
||||||
|
const { championCounts, finalistCounts, sfLoserCounts, qfLoserCounts } = counts;
|
||||||
|
|
||||||
|
const results: SimulationResult[] = participantIds.map((participantId) => {
|
||||||
|
const c = championCounts.get(participantId) ?? 0;
|
||||||
|
const f = finalistCounts.get(participantId) ?? 0;
|
||||||
|
const sf = sfLoserCounts.get(participantId) ?? 0;
|
||||||
|
const qf = qfLoserCounts.get(participantId) ?? 0;
|
||||||
|
return {
|
||||||
|
participantId,
|
||||||
|
probabilities: {
|
||||||
|
probFirst: c / N,
|
||||||
|
probSecond: f / N,
|
||||||
|
probThird: sf / (2 * N),
|
||||||
|
probFourth: sf / (2 * N),
|
||||||
|
probFifth: qf / (4 * N),
|
||||||
|
probSixth: qf / (4 * N),
|
||||||
|
probSeventh: qf / (4 * N),
|
||||||
|
probEighth: qf / (4 * N),
|
||||||
|
},
|
||||||
|
source: "darts_world_championship_monte_carlo",
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// Per-position column normalisation — ensures sums are exactly 1.0.
|
||||||
|
const positionKeys: Array<keyof typeof results[0]["probabilities"]> = [
|
||||||
|
"probFirst", "probSecond", "probThird", "probFourth",
|
||||||
|
"probFifth", "probSixth", "probSeventh", "probEighth",
|
||||||
|
];
|
||||||
|
for (const key of positionKeys) {
|
||||||
|
const colSum = results.reduce((s, r) => s + r.probabilities[key], 0);
|
||||||
|
const residual = 1.0 - colSum;
|
||||||
|
if (residual !== 0) {
|
||||||
|
const maxResult = results.reduce((best, r) =>
|
||||||
|
r.probabilities[key] > best.probabilities[key] ? r : best
|
||||||
|
);
|
||||||
|
maxResult.probabilities[key] += residual;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
@ -18,6 +18,7 @@ import { NHLSimulator } from "./nhl-simulator";
|
||||||
import { AFLSimulator } from "./afl-simulator";
|
import { AFLSimulator } from "./afl-simulator";
|
||||||
import { SnookerSimulator } from "./snooker-simulator";
|
import { SnookerSimulator } from "./snooker-simulator";
|
||||||
import { TennisSimulator } from "./tennis-simulator";
|
import { TennisSimulator } from "./tennis-simulator";
|
||||||
|
import { DartsSimulator } from "./darts-simulator";
|
||||||
import { MLBSimulator } from "./mlb-simulator";
|
import { MLBSimulator } from "./mlb-simulator";
|
||||||
import { WNBASimulator } from "./wnba-simulator";
|
import { WNBASimulator } from "./wnba-simulator";
|
||||||
import { WorldCupSimulator } from "./world-cup-simulator";
|
import { WorldCupSimulator } from "./world-cup-simulator";
|
||||||
|
|
@ -38,6 +39,7 @@ export const SIMULATOR_TYPES = [
|
||||||
"mlb_bracket",
|
"mlb_bracket",
|
||||||
"wnba_bracket",
|
"wnba_bracket",
|
||||||
"world_cup",
|
"world_cup",
|
||||||
|
"darts_bracket",
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export type SimulatorType = typeof SIMULATOR_TYPES[number];
|
export type SimulatorType = typeof SIMULATOR_TYPES[number];
|
||||||
|
|
@ -122,6 +124,10 @@ const REGISTRY: Record<SimulatorType, { info: SimulatorInfo; create: () => Simul
|
||||||
info: { name: "FIFA World Cup 2026 Monte Carlo", description: "Simulates the full 48-team World Cup: round-robin group stage (12 groups), best-8 third-place selection, R32→R16→QF→SF→3rd place game→Final. Uses blended Elo + futures odds." },
|
info: { name: "FIFA World Cup 2026 Monte Carlo", description: "Simulates the full 48-team World Cup: round-robin group stage (12 groups), best-8 third-place selection, R32→R16→QF→SF→3rd place game→Final. Uses blended Elo + futures odds." },
|
||||||
create: () => new WorldCupSimulator(),
|
create: () => new WorldCupSimulator(),
|
||||||
},
|
},
|
||||||
|
darts_bracket: {
|
||||||
|
info: { name: "PDC World Darts Championship Monte Carlo", description: "Simulates the 128-player World Darts Championship bracket using set-level Bernoulli win probability and Elo ratings. Top 32 seeds placed in fixed positions; remaining 96 players randomly drawn per simulation." },
|
||||||
|
create: () => new DartsSimulator(),
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function getSimulator(simulatorType: SimulatorType): Simulator {
|
export function getSimulator(simulatorType: SimulatorType): Simulator {
|
||||||
|
|
|
||||||
|
|
@ -98,6 +98,7 @@ export const simulatorTypeEnum = pgEnum("simulator_type", [
|
||||||
"mlb_bracket",
|
"mlb_bracket",
|
||||||
"wnba_bracket",
|
"wnba_bracket",
|
||||||
"world_cup",
|
"world_cup",
|
||||||
|
"darts_bracket",
|
||||||
]);
|
]);
|
||||||
|
|
||||||
export const playoffMatchGameStatusEnum = pgEnum("playoff_match_game_status", [
|
export const playoffMatchGameStatusEnum = pgEnum("playoff_match_game_status", [
|
||||||
|
|
@ -588,7 +589,8 @@ export const participantExpectedValues = pgTable("participant_expected_values",
|
||||||
// Metadata
|
// Metadata
|
||||||
source: probabilitySourceEnum("source").default("manual"), // How probabilities were generated
|
source: probabilitySourceEnum("source").default("manual"), // How probabilities were generated
|
||||||
sourceOdds: integer("source_odds"), // Original odds if source is futures_odds (American odds format)
|
sourceOdds: integer("source_odds"), // Original odds if source is futures_odds (American odds format)
|
||||||
sourceElo: integer("source_elo"), // Raw Elo rating if source is elo-based simulator (e.g. snooker_bracket)
|
sourceElo: integer("source_elo"), // Raw Elo rating if source is elo-based simulator (e.g. snooker_bracket, darts_bracket)
|
||||||
|
worldRanking: integer("world_ranking"), // World ranking for sports that use it for bracket seeding (e.g. darts_bracket)
|
||||||
calculatedAt: timestamp("calculated_at").defaultNow().notNull(),
|
calculatedAt: timestamp("calculated_at").defaultNow().notNull(),
|
||||||
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
updatedAt: timestamp("updated_at").defaultNow().notNull(),
|
||||||
}, (t) => ({
|
}, (t) => ({
|
||||||
|
|
|
||||||
2
drizzle/0067_darts_bracket.sql
Normal file
2
drizzle/0067_darts_bracket.sql
Normal file
|
|
@ -0,0 +1,2 @@
|
||||||
|
ALTER TYPE "public"."simulator_type" ADD VALUE 'darts_bracket';--> statement-breakpoint
|
||||||
|
ALTER TABLE "participant_expected_values" ADD COLUMN "world_ranking" integer;
|
||||||
4346
drizzle/meta/0067_snapshot.json
Normal file
4346
drizzle/meta/0067_snapshot.json
Normal file
File diff suppressed because it is too large
Load diff
|
|
@ -470,6 +470,13 @@
|
||||||
"when": 1774802533652,
|
"when": 1774802533652,
|
||||||
"tag": "0066_stiff_siren",
|
"tag": "0066_stiff_siren",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 67,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1774900000000,
|
||||||
|
"tag": "0067_darts_bracket",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
Loading…
Add table
Reference in a new issue