SPB Git

Repository Public

scoring.ts 7.8 KB 224 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : UQO Éval — Le Grand Défi Immobilier8 * File             : packages/engine/src/scoring.ts9 * Module           : engine10 * 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 * Scoring Engine — seul lieu où se calculent les scores et les erreurs.45 * Toujours exécuté côté serveur.46 */47import type { Category, Difficulty, PriceBandKey } from "./types.ts";4849export interface AnswerMetrics {50  isCorrect: boolean;51  /** |prix choisi − prix affiché|, en dollars. */52  absError: number;53  /** |prix choisi − prix affiché| / prix affiché. */54  relError: number;55  /** (prix choisi − prix affiché) / prix affiché : positif = surestimation. */56  signedRelError: number;57}5859export function answerMetrics(chosenPrice: number, correctPrice: number): AnswerMetrics {60  const diff = chosenPrice - correctPrice;61  return {62    isCorrect: diff === 0,63    absError: Math.abs(diff),64    relError: Math.abs(diff) / correctPrice,65    signedRelError: diff / correctPrice,66  };67}6869export interface AnswerRecord {70  /** Position dans la partie (0 = première propriété). */71  index: number;72  chosenPrice: number;73  correctPrice: number;74  category: Category;75  regionCode: string | null;76  regionName: string | null;77  priceBand: PriceBandKey;78  difficulty: Difficulty;79  phase: number;80}8182export interface GroupStat {83  key: string;84  label: string;85  n: number;86  correct: number;87  /** Taux de bonnes réponses dans [0, 1]. */88  rate: number;89  /** Erreur relative moyenne, en pourcentage. */90  mape: number;91  /** Biais moyen signé, en pourcentage. */92  bias: number;93}9495export interface ScoreSummary {96  answered: number;97  correct: number;98  wrong: number;99  /** Erreur absolue moyenne en pourcentage (MAPE), sur toutes les réponses. */100  mape: number;101  /** Erreur relative médiane, en pourcentage. */102  medianRelError: number;103  /** Erreur absolue moyenne, en dollars. */104  meanAbsError: number;105  maxAbsError: number;106  /** Erreur relative maximale, en pourcentage. */107  maxRelError: number;108  /** Biais moyen signé, en pourcentage (positif = tendance à surestimer). */109  bias: number;110  overestimates: number;111  underestimates: number;112  bestStreak: number;113  currentStreak: number;114  /** Longueurs de toutes les séries de bonnes réponses, dans l'ordre. */115  streaks: number[];116}117118export function median(values: readonly number[]): number {119  if (values.length === 0) return 0;120  const s = [...values].sort((a, b) => a - b);121  const mid = Math.floor(s.length / 2);122  return s.length % 2 ? s[mid]! : (s[mid - 1]! + s[mid]!) / 2;123}124125export function mean(values: readonly number[]): number {126  return values.length ? values.reduce((a, b) => a + b, 0) / values.length : 0;127}128129export function summarize(records: readonly AnswerRecord[]): ScoreSummary {130  const ordered = [...records].sort((a, b) => a.index - b.index);131  const metrics = ordered.map((r) => answerMetrics(r.chosenPrice, r.correctPrice));132  const streaks: number[] = [];133  let run = 0;134  for (const m of metrics) {135    if (m.isCorrect) run += 1;136    else {137      if (run > 0) streaks.push(run);138      run = 0;139    }140  }141  if (run > 0) streaks.push(run);142  const correct = metrics.filter((m) => m.isCorrect).length;143  return {144    answered: metrics.length,145    correct,146    wrong: metrics.length - correct,147    mape: 100 * mean(metrics.map((m) => m.relError)),148    medianRelError: 100 * median(metrics.map((m) => m.relError)),149    meanAbsError: mean(metrics.map((m) => m.absError)),150    maxAbsError: metrics.reduce((acc, m) => Math.max(acc, m.absError), 0),151    maxRelError: 100 * metrics.reduce((acc, m) => Math.max(acc, m.relError), 0),152    bias: 100 * mean(metrics.map((m) => m.signedRelError)),153    overestimates: metrics.filter((m) => m.signedRelError > 0).length,154    underestimates: metrics.filter((m) => m.signedRelError < 0).length,155    bestStreak: streaks.reduce((a, b) => Math.max(a, b), 0),156    currentStreak: run,157    streaks,158  };159}160161export function groupStats<T extends AnswerRecord>(162  records: readonly T[],163  keyOf: (r: T) => string | null,164  labelOf: (r: T) => string,165): GroupStat[] {166  const groups = new Map<string, { label: string; items: T[] }>();167  for (const r of records) {168    const key = keyOf(r);169    if (key === null) continue;170    const g = groups.get(key) ?? { label: labelOf(r), items: [] };171    g.items.push(r);172    groups.set(key, g);173  }174  return [...groups.entries()]175    .map(([key, g]) => {176      const m = g.items.map((r) => answerMetrics(r.chosenPrice, r.correctPrice));177      const correct = m.filter((x) => x.isCorrect).length;178      return {179        key,180        label: g.label,181        n: g.items.length,182        correct,183        rate: correct / g.items.length,184        mape: 100 * mean(m.map((x) => x.relError)),185        bias: 100 * mean(m.map((x) => x.signedRelError)),186      };187    })188    .sort((a, b) => b.n - a.n || a.label.localeCompare(b.label, "fr"));189}190191export interface RecognitionTitle {192  key: string;193  title: string;194  min: number;195  max: number;196}197198/** Titres ludiques, sur une base de 100. Sans valeur de qualification professionnelle. */199export const TITLES: readonly RecognitionTitle[] = [200  { key: "explorateur", title: "Explorateur du marché", min: 0, max: 39 },201  { key: "en-formation", title: "Analyste en formation", min: 40, max: 59 },202  { key: "analyste", title: "Analyste immobilier", min: 60, max: 74 },203  { key: "stratege", title: "Stratège immobilier", min: 75, max: 84 },204  { key: "expert", title: "Expert du marché", min: 85, max: 94 },205  { key: "maitre", title: "Maître du marché", min: 95, max: 99 },206  { key: "legende", title: "Légende immobilière", min: 100, max: 100 },207];208209export function titleFor(correct: number, total: number): RecognitionTitle {210  const percent = total > 0 ? Math.floor((correct * 100) / total) : 0;211  const exact = correct === total && total > 0 ? 100 : Math.min(percent, 99);212  return TITLES.find((t) => exact >= t.min && exact <= t.max) ?? TITLES[0]!;213}214215/** Meilleure et moins bonne catégorie (au moins `minN` réponses chacune). */216export function strengths(groups: readonly GroupStat[], minN = 3): { best: GroupStat | null; worst: GroupStat | null } {217  const usable = groups.filter((g) => g.n >= minN);218  if (usable.length < 2) return { best: usable[0] ?? null, worst: null };219  const ranked = [...usable].sort((a, b) => b.rate - a.rate || a.mape - b.mape);220  const best = ranked[0]!;221  const worst = ranked[ranked.length - 1]!;222  return { best, worst: worst.key === best.key ? null : worst };223}224
Files main
Menu

Theme