Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : tests/statistical/parties-simulees.test.ts9 * Module : tests10 * Repository : https://git.spboucher.ai/uqo-eval-jeux11 * Project Website : https://jeux.uqo-eval.app12 * Created : 2026-11-2513 * Last Modified : 2026-11-2514 *15 * Author : Simon-Pierre Boucher16 * Position : Professor of Finance17 * Institution : Université du Québec en Outaouais (UQO)18 * Organization : SP Boucher19 * Website : https://spboucher.ai20 * Git : https://git.spboucher.ai21 *22 * Preferred Contact: contact@spboucher.ai23 * Development : dev@spboucher.ai24 * Support : support@spboucher.ai25 * Security/Admin : admin@spboucher.ai26 *27 * Copyright (c) 202628 * Simon-Pierre Boucher29 * All rights reserved where applicable. This file is governed by the30 * applicable project license, copyright notices and relevant law.31 * Existing third-party rights and notices remain unaffected.32 *33 * License : None specified (no license file in this repository)34 *35 * Do not embed credentials, private keys, access tokens,36 * certificates or confidential personal information.37 *38 * =============================================================================39 * END OF SP BOUCHER SOURCE HEADER40 * =============================================================================41 */4243/**44 * Parties simulées : 60 tournois de 50 joueurs (3 000 parties de 100 propriétés) sur des banques45 * tirées de l'extrait réel. Cinq niveaux de joueurs ; chacun estime le prix avec une erreur46 * log-normale d'écart-type σ, puis retient le choix le plus proche de son estimation. Le joueur47 * « hasard » tire un choix au sort. Graines fixes : résultats reproductibles.48 */49import { afterAll, describe, expect, it } from "vitest";50import {51 compareEntries,52 createRng,53 generateChoices,54 priceBandOf,55 rankEntries,56 selectProperties,57 summarize,58 titleFor,59 type AnswerRecord,60 type Ranked,61 type RankInput,62 type Rng,63} from "../../packages/engine/src/index.ts";64import { marketBounds, marketPricesOf } from "../helpers/datasets.ts";65import { loadRealData } from "../helpers/realdata.ts";66import { zProportion } from "../helpers/stats.ts";6768const LEVELS = [69 { key: "expert", sigma: 0.02 },70 { key: "avancé", sigma: 0.06 },71 { key: "intermédiaire", sigma: 0.12 },72 { key: "débutant", sigma: 0.25 },73 { key: "hasard", sigma: null },74] as const;75const PLAYERS_PER_LEVEL = 10;76const BANKS = 12;77const TOURNAMENTS_PER_BANK = 5;7879interface Question { price: number; choices: number[]; record: Omit<AnswerRecord, "chosenPrice" | "index"> }80interface Entry extends RankInput { level: number; answered: number }8182function gaussian(rng: Rng): number {83 const u = Math.max(rng.next(), 1e-12);84 return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * rng.next());85}8687const data = loadRealData();88const bounds = marketBounds(data.eligible);89const marketPrices = marketPricesOf(data.eligible);9091function buildQuestions(seed: string): Question[] {92 return selectProperties(data.eligible, { size: 100 }, createRng(`${seed}:banque`)).map((item) => {93 const p = item.property;94 const b = bounds.get(p.category)!;95 const g = generateChoices(p.price, item.difficulty, createRng(`${seed}:choix:${p.sourceUid}`), { floorPrice: b.floor, ceilPrice: b.ceil, marketPrices });96 return {97 price: p.price,98 choices: [...g.prices],99 record: { correctPrice: p.price, category: p.category, regionCode: p.regionCode, regionName: p.regionName, priceBand: priceBandOf(p.price).key, difficulty: item.difficulty, phase: item.phase },100 };101 });102}103104function play(questions: Question[], sigma: number | null, rng: Rng): AnswerRecord[] {105 return questions.map((q, index) => {106 let chosen: number;107 if (sigma === null) chosen = rng.pick(q.choices);108 else {109 const estimate = Math.log(q.price) + sigma * gaussian(rng);110 chosen = q.choices.reduce((best, c) => (Math.abs(Math.log(c) - estimate) < Math.abs(Math.log(best) - estimate) ? c : best));111 }112 return { ...q.record, index, chosenPrice: chosen };113 });114}115116const tournaments: Ranked<Entry>[][] = [];117const allGames: { level: number; records: AnswerRecord[]; correct: number; mape: number }[] = [];118119for (let b = 0; b < BANKS; b++) {120 const questions = buildQuestions(`simulation:${b}`);121 for (let t = 0; t < TOURNAMENTS_PER_BANK; t++) {122 const entries: Entry[] = [];123 LEVELS.forEach((level, levelIndex) => {124 for (let k = 0; k < PLAYERS_PER_LEVEL; k++) {125 const id = `b${b}-t${t}-n${levelIndex}-j${k}`;126 const records = play(questions, level.sigma, createRng(`joueur:${id}`));127 const summary = summarize(records);128 entries.push({ id, level: levelIndex, correct: summary.correct, mape: summary.mape, medianRelError: summary.medianRelError, answered: summary.answered });129 allGames.push({ level: levelIndex, records, correct: summary.correct, mape: summary.mape });130 }131 });132 tournaments.push(rankEntries(entries));133 }134}135136const mean = (values: number[]): number => values.reduce((a, b) => a + b, 0) / values.length;137const byLevel = <T,>(f: (level: number) => T): T[] => LEVELS.map((_, i) => f(i));138const measured: string[] = [];139afterAll(() => {140 console.log(`\n[MESURES · parties simulées]\n${measured.join("\n")}\n`);141});142143describe("Parties simulées — cohérence des classements", () => {144 it("simule plusieurs milliers de parties complètes de 100 propriétés", () => {145 expect(allGames).toHaveLength(BANKS * TOURNAMENTS_PER_BANK * LEVELS.length * PLAYERS_PER_LEVEL);146 expect(allGames.length).toBeGreaterThanOrEqual(3_000);147 expect(allGames.every((g) => g.records.length === 100)).toBe(true);148 });149150 it("un joueur plus fort obtient en moyenne plus de bonnes réponses et une erreur moyenne plus faible", () => {151 const correct = byLevel((level) => mean(allGames.filter((g) => g.level === level).map((g) => g.correct)));152 const mape = byLevel((level) => mean(allGames.filter((g) => g.level === level).map((g) => g.mape)));153 measured.push(`bonnes réponses moyennes sur 100 | ${LEVELS.map((l, i) => `${l.key} ${correct[i]!.toFixed(1)}`).join(" · ")}`);154 measured.push(`erreur relative moyenne (%) | ${LEVELS.map((l, i) => `${l.key} ${mape[i]!.toFixed(2)}`).join(" · ")}`);155 for (let i = 1; i < LEVELS.length; i++) {156 expect(correct[i - 1]! - correct[i]!, `${LEVELS[i - 1]!.key} > ${LEVELS[i]!.key}`).toBeGreaterThan(3);157 expect(mape[i]! - mape[i - 1]!, `${LEVELS[i - 1]!.key} < ${LEVELS[i]!.key}`).toBeGreaterThan(0.3);158 }159 });160161 it("un joueur plus fort est en moyenne mieux classé, niveau par niveau", () => {162 const ranks = byLevel((level) => mean(tournaments.flatMap((t) => t.filter((e) => e.level === level).map((e) => e.rank))));163 measured.push(`rang moyen sur 50 joueurs | ${LEVELS.map((l, i) => `${l.key} ${ranks[i]!.toFixed(1)}`).join(" · ")}`);164 for (let i = 1; i < LEVELS.length; i++) expect(ranks[i]! - ranks[i - 1]!).toBeGreaterThan(5);165 expect(ranks[0]).toBeLessThan(8);166 expect(ranks[LEVELS.length - 1]).toBeGreaterThan(43);167 });168169 it("dans un duel, le joueur du niveau supérieur devance celui du niveau voisin dans la grande majorité des cas", () => {170 const winRates: number[] = [];171 for (let level = 0; level < LEVELS.length - 1; level++) {172 let wins = 0;173 let duels = 0;174 for (const t of tournaments) {175 const strong = t.filter((e) => e.level === level);176 const weak = t.filter((e) => e.level === level + 1);177 for (const s of strong) for (const w of weak) {178 duels += 1;179 if (compareEntries(s, w) < 0) wins += 1;180 }181 }182 winRates.push(wins / duels);183 }184 measured.push(`duels gagnés par le niveau supérieur | ${winRates.map((r, i) => `${LEVELS[i]!.key} > ${LEVELS[i + 1]!.key} : ${(100 * r).toFixed(1)} %`).join(" · ")}`);185 for (const rate of winRates) expect(rate).toBeGreaterThan(0.85);186 });187188 it("le podium revient presque toujours au meilleur niveau, jamais au hasard", () => {189 let expertWins = 0;190 for (const t of tournaments) {191 const first = t.filter((e) => e.rank === 1);192 if (first.every((e) => e.level === 0)) expertWins += 1;193 expect(t.filter((e) => e.rank <= 3).some((e) => e.level === LEVELS.length - 1)).toBe(false);194 }195 measured.push(`tournois gagnés par un joueur « expert » | ${expertWins} sur ${tournaments.length}`);196 expect(expertWins / tournaments.length).toBeGreaterThan(0.95);197 });198199 it("le joueur qui répond au hasard obtient 25 % (|z| < 3,29, α = 0,001)", () => {200 const games = allGames.filter((g) => g.level === LEVELS.length - 1);201 const correct = games.reduce((acc, g) => acc + g.correct, 0);202 const n = games.length * 100;203 const z = zProportion(correct, n, 0.25);204 measured.push(`joueur au hasard | ${correct} bonnes réponses sur ${n} = ${((100 * correct) / n).toFixed(2)} % (z = ${z.toFixed(2)})`);205 expect(Math.abs(z)).toBeLessThan(3.29);206 });207208 it("chaque classement respecte l'ordre officiel et la règle des rangs partagés", () => {209 for (const t of tournaments) {210 expect(t).toHaveLength(LEVELS.length * PLAYERS_PER_LEVEL);211 expect(t[0]!.rank).toBe(1);212 for (let i = 1; i < t.length; i++) {213 const order = compareEntries(t[i - 1]!, t[i]!);214 expect(order).toBeLessThanOrEqual(0);215 if (order === 0) {216 expect(t[i]!.rank).toBe(t[i - 1]!.rank);217 expect(t[i]!.tied && t[i - 1]!.tied).toBe(true);218 } else expect(t[i]!.rank).toBe(i + 1);219 }220 // Le rang d'un joueur = 1 + nombre de joueurs strictement meilleurs (recalcul indépendant).221 for (const e of t) expect(e.rank).toBe(1 + t.filter((o) => compareEntries(o, e) < 0).length);222 }223 });224225 it("le sommaire officiel concorde avec un recalcul indépendant, partie par partie", () => {226 for (const game of allGames) {227 const exact = game.records.filter((r) => r.chosenPrice === r.correctPrice).length;228 const mape = (100 * game.records.reduce((acc, r) => acc + Math.abs(r.chosenPrice - r.correctPrice) / r.correctPrice, 0)) / game.records.length;229 expect(game.correct).toBe(exact);230 expect(game.mape).toBeCloseTo(mape, 9);231 }232 });233234 it("les titres de reconnaissance suivent le niveau des joueurs", () => {235 const order = ["explorateur", "en-formation", "analyste", "stratege", "expert", "maitre", "legende"];236 const meanTitle = byLevel((level) => mean(allGames.filter((g) => g.level === level).map((g) => order.indexOf(titleFor(g.correct, 100).key))));237 for (let i = 1; i < LEVELS.length; i++) expect(meanTitle[i - 1]!).toBeGreaterThan(meanTitle[i]!);238 expect(allGames.filter((g) => g.level === LEVELS.length - 1).every((g) => titleFor(g.correct, 100).key === "explorateur" || titleFor(g.correct, 100).key === "en-formation")).toBe(true);239 });240});241