SPB Git

Repository Public

datasets.ts 6.9 KB 154 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/helpers/datasets.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/** Jeux de questions simulées, partagés par les tests statistiques (calculés une seule fois). */44import { DIFFICULTIES, createRng, generateChoices, type Difficulty, type GeneratedChoices, type NormalizedProperty } from "../../packages/engine/src/index.ts";45import { loadRealData } from "./realdata.ts";4647/** Centile par interpolation linéaire (même définition que `percentile_cont` de PostgreSQL). */48export function percentileCont(values: readonly number[], q: number): number {49  const s = [...values].sort((a, b) => a - b);50  const pos = (s.length - 1) * q;51  const lo = Math.floor(pos);52  const hi = Math.ceil(pos);53  return s[lo]! + (s[hi]! - s[lo]!) * (pos - lo);54}5556/** Bornes de plausibilité par catégorie, calculées comme dans apps/api/src/bank.ts (priceBounds). */57export function marketBounds(pool: readonly NormalizedProperty[]): Map<string, { floor: number; ceil: number }> {58  const groups = new Map<string, number[]>();59  for (const p of pool) groups.set(p.category, [...(groups.get(p.category) ?? []), p.price]);60  return new Map([...groups].map(([category, prices]) => [category, { floor: Math.floor(percentileCont(prices, 0.005) * 0.7), ceil: Math.ceil(percentileCont(prices, 0.995) * 1.3) }]));61}6263/** Marché de la production (apps/api/src/bank.ts, priceMarket) : tous les prix admissibles, triés, doublons conservés. */64export function marketPricesOf(pool: readonly NormalizedProperty[]): number[] {65  return pool.map((p) => p.price).sort((a, b) => a - b);66}6768export interface Dataset {69  label: string;70  /** Prix connus du « tricheur » pour apprendre les terminaisons — propriétés disjointes de celles évaluées. */71  trainingPrices: number[];72  /** Marché complet passé au moteur (vide en mode grille). */73  marketPrices: number[];74  /** Questions générées sur les propriétés d'apprentissage : servent aux stratégies « apprises ». */75  trainingGames: Record<Difficulty, GeneratedChoices[]>;76  /** Questions évaluées. */77  byDifficulty: Record<Difficulty, GeneratedChoices[]>;78  n: number;79}8081const cache = new Map<string, Dataset>();8283/**84 * Données réelles. La moitié des propriétés admissibles sert à l'apprentissage ; l'autre moitié est85 * évaluée, 10 tirages par propriété et par difficulté (≈ 23 900 questions par difficulté), avec les86 * bornes de marché de la production.87 *  - mode « market » (production) : `marketPrices` = tous les prix admissibles ;88 *  - mode « grid » : aucun marché, grille de repli seule.89 */90export function realDataset(mode: "market" | "grid" = "market"): Dataset {91  const hit = cache.get(`reel:${mode}`);92  if (hit) return hit;93  const { eligible } = loadRealData();94  const bounds = marketBounds(eligible);95  const marketPrices = mode === "market" ? marketPricesOf(eligible) : [];96  const training = eligible.filter((_, i) => i % 2 === 0);97  const evaluated = eligible.filter((_, i) => i % 2 === 1);98  const build = (pool: NormalizedProperty[], draws: number, tag: string): Record<Difficulty, GeneratedChoices[]> => {99    const out = {} as Record<Difficulty, GeneratedChoices[]>;100    for (const difficulty of DIFFICULTIES) {101      const games: GeneratedChoices[] = [];102      for (let draw = 0; draw < draws; draw++) {103        for (const p of pool) {104          const b = bounds.get(p.category)!;105          games.push(generateChoices(p.price, difficulty, createRng(`stat:reel:${mode}:${tag}:${difficulty}:${draw}:${p.sourceUid}`), {106            floorPrice: b.floor, ceilPrice: b.ceil, ...(mode === "market" ? { marketPrices } : {}),107          }));108        }109      }110      out[difficulty] = games;111    }112    return out;113  };114  const dataset: Dataset = {115    label: mode === "market" ? "données réelles, marché (production)" : "données réelles, grille de repli",116    trainingPrices: training.map((p) => p.price),117    marketPrices,118    trainingGames: build(training, 4, "appr"),119    byDifficulty: build(evaluated, 10, "eval"),120    n: evaluated.length * 10,121  };122  cache.set(`reel:${mode}`, dataset);123  return dataset;124}125126/** Prix synthétiques : log-uniformes de 90 000 $ à 2 500 000 $, arrondis à 100 $ (terminaisons sans convention). */127export function syntheticPrices(n: number, seed: string): number[] {128  const rng = createRng(seed);129  return Array.from({ length: n }, () => Math.round(Math.exp(rng.range(Math.log(90_000), Math.log(2_500_000))) / 100) * 100);130}131132/** Prix synthétiques, grille seule (aucun marché). */133export function syntheticDataset(): Dataset {134  const hit = cache.get("synthetique");135  if (hit) return hit;136  const prices = syntheticPrices(24_000, "stat:synthetique:prix");137  const trainingPrices = syntheticPrices(24_000, "stat:synthetique:apprentissage");138  const build = (list: number[], tag: string): Record<Difficulty, GeneratedChoices[]> => {139    const out = {} as Record<Difficulty, GeneratedChoices[]>;140    for (const difficulty of DIFFICULTIES) out[difficulty] = list.map((price, i) => generateChoices(price, difficulty, createRng(`stat:syn:${tag}${difficulty}:${i}`)));141    return out;142  };143  const dataset: Dataset = {144    label: "prix synthétiques, grille",145    trainingPrices,146    marketPrices: [],147    trainingGames: build(trainingPrices.slice(0, 8_000), "appr:"),148    byDifficulty: build(prices, ""),149    n: prices.length,150  };151  cache.set("synthetique", dataset);152  return dataset;153}154
Files main
Menu

Theme