SPB Git

Repository Public

select.test.ts 12.4 KB 223 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : tests/unit/select.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 */4243import { describe, expect, it } from "vitest";44import { atypicality, createRng, participantOrder, phaseOfIndex, priceProfiles, selectProperties } from "../../packages/engine/src/index.ts";45import { makePool, makeProperty } from "../helpers/factories.ts";4647const pool = makePool(1200);48const uids = (items: { property: { sourceUid: string } }[]): string[] => items.map((s) => s.property.sourceUid);4950describe("selectProperties — banque de 100", () => {51  const bank = selectProperties(pool, { size: 100 }, createRng("banque-test"));5253  it("retourne exactement la taille demandée, sans aucun doublon", () => {54    expect(bank).toHaveLength(100);55    expect(new Set(uids(bank)).size).toBe(100);56  });5758  it("répartit 100 propriétés en quatre phases de 25, de difficulté croissante", () => {59    for (const phase of [1, 2, 3, 4]) expect(bank.filter((s) => s.phase === phase)).toHaveLength(25);60    expect(new Set(bank.filter((s) => s.phase === 1).map((s) => s.difficulty))).toEqual(new Set(["initiation"]));61    expect(new Set(bank.filter((s) => s.phase === 2).map((s) => s.difficulty))).toEqual(new Set(["intermediaire"]));62    expect(new Set(bank.filter((s) => s.phase === 3).map((s) => s.difficulty))).toEqual(new Set(["avance"]));63    expect(new Set(bank.filter((s) => s.phase === 4).map((s) => s.difficulty))).toEqual(new Set(["expert"]));64  });6566  it("ordonne les phases par atypie croissante", () => {67    const maxOf = (phase: number): number => Math.max(...bank.filter((s) => s.phase === phase).map((s) => s.atypicality));68    const minOf = (phase: number): number => Math.min(...bank.filter((s) => s.phase === phase).map((s) => s.atypicality));69    expect(maxOf(1)).toBeLessThanOrEqual(minOf(2));70    expect(maxOf(2)).toBeLessThanOrEqual(minOf(3));71    expect(maxOf(3)).toBeLessThanOrEqual(minOf(4));72  });7374  it("est reproductible avec la même graine", () => {75    const again = selectProperties(pool, { size: 100 }, createRng("banque-test"));76    expect(again.map((s) => [s.property.sourceUid, s.phase, s.difficulty])).toEqual(bank.map((s) => [s.property.sourceUid, s.phase, s.difficulty]));77  });7879  it("ne dépend pas de l'ordre d'arrivée du bassin", () => {80    const shuffled = createRng("melange").shuffle(pool);81    expect(uids(selectProperties(shuffled, { size: 100 }, createRng("banque-test")))).toEqual(uids(bank));82  });8384  it("produit une banque différente avec une autre graine", () => {85    const other = selectProperties(pool, { size: 100 }, createRng("autre-graine"));86    const common = uids(other).filter((u) => new Set(uids(bank)).has(u)).length;87    expect(common).toBeLessThan(60);88    expect(uids(other)).not.toEqual(uids(bank));89  });9091  it("plafonne la part d'une même municipalité (6 % par défaut, soit 6 sur 100)", () => {92    const counts = new Map<string, number>();93    for (const s of bank) counts.set(s.property.municipality, (counts.get(s.property.municipality) ?? 0) + 1);94    expect(Math.max(...counts.values())).toBeLessThanOrEqual(6);95  });96});9798describe("selectProperties — plafond par municipalité", () => {99  // 70 % du bassin dans une seule ville : sans plafond, elle dominerait la banque.100  const skewed = makePool(1500, (_p, i) => (i % 10 < 7 ? { municipality: "Mégapole" } : undefined));101102  it("limite la municipalité dominante au plafond quand le reste du bassin suffit", () => {103    const bank = selectProperties(skewed, { size: 100 }, createRng("plafond"));104    expect(bank.filter((s) => s.property.municipality === "Mégapole").length).toBeLessThanOrEqual(6);105    expect(bank).toHaveLength(100);106  });107108  it("applique le paramètre maxMunicipalityShare", () => {109    const bank = selectProperties(skewed, { size: 100, maxMunicipalityShare: 0.2 }, createRng("plafond"));110    const mega = bank.filter((s) => s.property.municipality === "Mégapole").length;111    expect(mega).toBeLessThanOrEqual(20);112    expect(mega).toBeGreaterThan(6);113  });114115  it("garde un plancher de deux propriétés par municipalité pour les petites banques", () => {116    const bank = selectProperties(skewed, { size: 10 }, createRng("petite"));117    expect(bank.filter((s) => s.property.municipality === "Mégapole").length).toBeLessThanOrEqual(2);118  });119120  it("dépasse le plafond plutôt que d'échouer quand une seule municipalité peut fournir la banque", () => {121    const single = makePool(300, () => ({ municipality: "Seule-Ville" }));122    const bank = selectProperties(single, { size: 50 }, createRng("seule"));123    expect(bank).toHaveLength(50);124    expect(new Set(uids(bank)).size).toBe(50);125  });126127  it("ne relâche le plafond que pour ce qui manque : les autres municipalités sont servies d'abord", () => {128    // 200 propriétés dans une ville, 30 réparties ailleurs (15 villes de 2) ; banque de 60, plafond de 4.129    const pool = makePool(230, (_p, i) => (i < 200 ? { municipality: "Grande-Ville" } : { municipality: `Petite-${Math.floor((i - 200) / 2)}` }));130    const bank = selectProperties(pool, { size: 60 }, createRng("relache"));131    expect(bank).toHaveLength(60);132    const elsewhere = bank.filter((s) => s.property.municipality !== "Grande-Ville").length;133    expect(elsewhere).toBe(30);134  });135});136137describe("selectProperties — filtres et erreurs", () => {138  it("respecte le filtre de catégories", () => {139    const bank = selectProperties(pool, { size: 40, categories: ["condo", "plex"] }, createRng("f1"));140    expect(bank).toHaveLength(40);141    expect(bank.every((s) => s.property.category === "condo" || s.property.category === "plex")).toBe(true);142  });143  it("respecte le filtre de régions", () => {144    const bank = selectProperties(pool, { size: 40, regionCodes: ["07", "15"] }, createRng("f2"));145    expect(bank.every((s) => s.property.regionCode === "07" || s.property.regionCode === "15")).toBe(true);146  });147  it("exclut les propriétés sans région quand un filtre de régions est actif", () => {148    const withUnknown = [...pool, ...makePool(50).map((p) => ({ ...p, sourceUid: `nr:${p.sourceUid}`, regionCode: null, regionName: null, dedupeKeys: [`nr:${p.sourceUid}`] }))];149    const bank = selectProperties(withUnknown, { size: 60, regionCodes: ["07"] }, createRng("f2b"));150    expect(bank.every((s) => s.property.regionCode === "07")).toBe(true);151  });152  it("respecte les bornes de prix, bornes incluses", () => {153    const bank = selectProperties(pool, { size: 40, priceMin: 300_000, priceMax: 500_000 }, createRng("f3"));154    expect(bank.every((s) => s.property.price >= 300_000 && s.property.price <= 500_000)).toBe(true);155    const exact = selectProperties([...makePool(10).map((p) => ({ ...p, price: 300_000 }))], { size: 10, priceMin: 300_000, priceMax: 300_000, maxMunicipalityShare: 1 }, createRng("f3b"));156    expect(exact).toHaveLength(10);157  });158  it("écarte les identifiants exclus", () => {159    const first = selectProperties(pool, { size: 100 }, createRng("f4"));160    const excluded = new Set(uids(first));161    const second = selectProperties(pool, { size: 100, excludeUids: excluded }, createRng("f4"));162    expect(uids(second).some((u) => excluded.has(u))).toBe(false);163  });164  it("impose une difficulté unique avec fixedDifficulty, sans toucher aux phases", () => {165    const bank = selectProperties(pool, { size: 20, fixedDifficulty: "avance" }, createRng("f5"));166    expect(new Set(bank.map((s) => s.difficulty))).toEqual(new Set(["avance"]));167    expect(bank.filter((s) => s.phase === 1)).toHaveLength(5);168  });169  it("lève une erreur explicite quand le bassin filtré est insuffisant", () => {170    expect(() => selectProperties(makePool(99), { size: 100 }, createRng("e1"))).toThrow(/Banque insuffisante : 99 propriétés admissibles pour 100/);171    expect(() => selectProperties(pool, { size: 50, categories: ["fermette"] }, createRng("e2"))).toThrow(/Banque insuffisante/);172  });173  it("lève une erreur quand les doublons empêchent d'atteindre la taille", () => {174    // 30 propriétés mais seulement 10 clés de déduplication distinctes.175    const dupes = makePool(30).map((p, i) => ({ ...p, dedupeKeys: [`adr:${i % 10}`] }));176    expect(() => selectProperties(dupes, { size: 20, maxMunicipalityShare: 1 }, createRng("e3"))).toThrow(/Banque insuffisante après déduplication : 10 sur 20/);177  });178  it("ne retient jamais deux propriétés partageant une clé de déduplication", () => {179    const dupes = makePool(400).map((p, i) => ({ ...p, dedupeKeys: [`adr:${Math.floor(i / 2)}`] }));180    const bank = selectProperties(dupes, { size: 100 }, createRng("d1"));181    const keys = bank.flatMap((s) => s.property.dedupeKeys);182    expect(new Set(keys).size).toBe(keys.length);183  });184  it("sélectionne tout le bassin quand la taille demandée l'égale", () => {185    const small = makePool(12);186    const bank = selectProperties(small, { size: 12, maxMunicipalityShare: 1 }, createRng("tout"));187    expect(new Set(uids(bank))).toEqual(new Set(small.map((p) => p.sourceUid)));188  });189});190191describe("atypicality", () => {192  it("donne un indice proche de 0 à une unifamiliale au prix médian et bien documentée, et le borne à [0, 1]", () => {193    const profiles = priceProfiles(pool);194    const center = Math.exp(profiles.get("unifamiliale")!.center);195    expect(atypicality(makeProperty({ price: Math.round(center) }), profiles)).toBeLessThan(0.02);196    const odd = makeProperty({ category: "fermette", price: 14_000_000, waterfront: "Lac", lotAreaSqft: 900_000, yearBuilt: 1890, garage: null, basement: null, heating: null, siding: null, parking: null, rooms: null });197    const value = atypicality(odd, priceProfiles([...pool, odd]));198    expect(value).toBeLessThanOrEqual(1);199    expect(value).toBeGreaterThan(0.9);200  });201});202203describe("phaseOfIndex et participantOrder", () => {204  it("découpe une partie de 100 en quatre phases de 25", () => {205    expect([0, 24, 25, 49, 50, 74, 75, 99].map((i) => phaseOfIndex(i, 100))).toEqual([1, 1, 2, 2, 3, 3, 4, 4]);206    expect([0, 2, 3, 5, 7, 9].map((i) => phaseOfIndex(i, 10))).toEqual([1, 1, 2, 3, 3, 4]);207  });208  it("mélange à l'intérieur de chaque phase, jamais entre les phases", () => {209    const questions = Array.from({ length: 100 }, (_, i) => ({ id: i, phase: Math.floor(i / 25) + 1 }));210    const ordered = participantOrder(questions, createRng("joueur-1"));211    expect(ordered).toHaveLength(100);212    expect(new Set(ordered.map((q) => q.id)).size).toBe(100);213    expect(ordered.map((q) => q.phase)).toEqual(questions.map((q) => q.phase));214    expect(ordered.map((q) => q.id)).not.toEqual(questions.map((q) => q.id));215  });216  it("donne le même ordre pour la même graine et un ordre différent pour un autre participant", () => {217    const questions = Array.from({ length: 100 }, (_, i) => ({ id: i, phase: Math.floor(i / 25) + 1 }));218    const a = participantOrder(questions, createRng("joueur-1")).map((q) => q.id);219    expect(participantOrder(questions, createRng("joueur-1")).map((q) => q.id)).toEqual(a);220    expect(participantOrder(questions, createRng("joueur-2")).map((q) => q.id)).not.toEqual(a);221  });222});223
Files main
Menu

Theme