Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : UQO Éval — Le Grand Défi Immobilier8 * File : apps/web/src/components/Charts.tsx9 * Module : components10 * 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/** Graphiques du rapport : SVG sur mesure, lisibles sans la couleur (formes, étiquettes, valeurs écrites). */44import { motion } from "motion/react";45import type { ReactNode } from "react";46import type { GroupStat } from "@jeux/engine";47import { formatMoney, formatPercent } from "@jeux/engine/format";4849const W = 560;50const H = 260;51const PAD = { top: 16, right: 16, bottom: 34, left: 46 };5253function scale(domain: [number, number], range: [number, number]): (v: number) => number {54 const [d0, d1] = domain;55 const [r0, r1] = range;56 const span = d1 - d0 || 1;57 return (v) => r0 + ((v - d0) / span) * (r1 - r0);58}5960function ticks(max: number, count = 4): number[] {61 if (max <= 0) return [0];62 const raw = max / count;63 const pow = 10 ** Math.floor(Math.log10(raw));64 const step = [1, 2, 2.5, 5, 10].map((m) => m * pow).find((s) => s >= raw) ?? raw;65 const out: number[] = [];66 for (let v = 0; v <= max + step * 0.01; v += step) out.push(Number(v.toFixed(6)));67 return out;68}6970export function ChartCard({ title, note, wide, children }: { title: string; note?: string; wide?: boolean; children: ReactNode }) {71 return (72 <figure className={`chart-card${wide ? " wide" : ""}`}>73 <figcaption><h3>{title}</h3></figcaption>74 {children}75 {note && <p className="small muted">{note}</p>}76 </figure>77 );78}7980/** Courbe (score cumulatif, erreur moyenne mobile…). */81export function LineChart({ points, yMax, yFormat, label, reference, color = "var(--forest)" }: { points: { x: number; y: number }[]; yMax: number; yFormat: (v: number) => string; label: string; reference?: { points: { x: number; y: number }[]; label: string }; color?: string }) {82 if (points.length === 0) return null;83 const xMax = Math.max(...points.map((p) => p.x));84 const sx = scale([Math.min(1, xMax), xMax], [PAD.left, W - PAD.right]);85 const sy = scale([0, yMax], [H - PAD.bottom, PAD.top]);86 const path = (pts: { x: number; y: number }[]): string => pts.map((p, i) => `${i ? "L" : "M"}${sx(p.x).toFixed(1)},${sy(p.y).toFixed(1)}`).join(" ");87 const xt = xMax <= 10 ? points.map((p) => p.x) : [1, ...[0.25, 0.5, 0.75, 1].map((f) => Math.round(xMax * f))];88 return (89 <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={label}>90 {ticks(yMax).map((t) => (91 <g key={t}>92 <line x1={PAD.left} x2={W - PAD.right} y1={sy(t)} y2={sy(t)} stroke="var(--stone)" strokeWidth={t === 0 ? 1.2 : 0.6} />93 <text x={PAD.left - 8} y={sy(t) + 4} textAnchor="end" className="chart-axis">{yFormat(t)}</text>94 </g>95 ))}96 {[...new Set(xt)].map((t) => <text key={t} x={sx(t)} y={H - 10} textAnchor="middle" className="chart-axis">{t}</text>)}97 {reference && <path d={path(reference.points)} fill="none" stroke="var(--stone-2)" strokeWidth={1.5} strokeDasharray="5 5" />}98 <motion.path d={path(points)} fill="none" stroke={color} strokeWidth={2.4} strokeLinejoin="round" strokeLinecap="round" initial={{ pathLength: 0 }} whileInView={{ pathLength: 1 }} viewport={{ once: true }} transition={{ duration: 1.4, ease: "easeOut" }} />99 {reference && <text x={W - PAD.right} y={PAD.top + 10} textAnchor="end" className="chart-axis">- - {reference.label}</text>}100 </svg>101 );102}103104/** Colonnes (distribution des erreurs, séries…). */105export function ColumnChart({ data, label, color = "var(--forest)" }: { data: { label: string; value: number; highlight?: boolean }[]; label: string; color?: string }) {106 const max = Math.max(1, ...data.map((d) => d.value));107 const band = (W - PAD.left - PAD.right) / Math.max(1, data.length);108 const sy = scale([0, max], [H - PAD.bottom, PAD.top + 14]);109 return (110 <svg viewBox={`0 0 ${W} ${H}`} role="img" aria-label={`${label} : ${data.map((d) => `${d.label} ${d.value}`).join(", ")}`}>111 <line x1={PAD.left} x2={W - PAD.right} y1={H - PAD.bottom} y2={H - PAD.bottom} stroke="var(--stone-2)" />112 {data.map((d, i) => {113 const x = PAD.left + i * band + band * 0.16;114 const w = band * 0.68;115 const y = sy(d.value);116 return (117 <g key={d.label}>118 <motion.rect x={x} width={w} y={y} height={H - PAD.bottom - y} rx={3} fill={d.highlight ? "var(--teal-deep)" : color} initial={{ scaleY: 0 }} whileInView={{ scaleY: 1 }} viewport={{ once: true }} transition={{ duration: 0.7, delay: i * 0.04, ease: [0.16, 1, 0.3, 1] }} style={{ transformOrigin: "bottom", transformBox: "fill-box" }} />119 <text x={x + w / 2} y={y - 6} textAnchor="middle" className="chart-axis" style={{ fontWeight: 600, fill: "var(--graphite)" }}>{d.value}</text>120 <text x={x + w / 2} y={H - 12} textAnchor="middle" className="chart-axis">{d.label}</text>121 </g>122 );123 })}124 </svg>125 );126}127128/** Barres horizontales par groupe : taux de réussite, avec l'effectif et l'erreur moyenne. */129export function GroupBars({ groups, metric = "rate" }: { groups: GroupStat[]; metric?: "rate" | "mape" }) {130 if (groups.length === 0) return <p className="muted small">Données insuffisantes.</p>;131 const max = metric === "rate" ? 1 : Math.max(1, ...groups.map((g) => g.mape));132 return (133 <div className="bars" role="list">134 {groups.map((g, i) => {135 const value = metric === "rate" ? g.rate : g.mape;136 return (137 <div className="bar-row" role="listitem" key={g.key}>138 <span>{g.label} <span className="muted">({g.n})</span></span>139 <span className="bar-track"><motion.span className="bar-fill" initial={{ scaleX: 0 }} whileInView={{ scaleX: value / max }} viewport={{ once: true }} transition={{ duration: 0.8, delay: i * 0.04, ease: [0.16, 1, 0.3, 1] }} style={{ width: "100%" }} /></span>140 <span className="bar-value tabular">{metric === "rate" ? `${g.correct}/${g.n} · ${formatPercent(g.rate * 100, 0)}` : formatPercent(g.mape, 1)}</span>141 </div>142 );143 })}144 </div>145 );146}147148/** Nuage de points : prix affiché (horizontal) contre prix choisi (vertical), avec la diagonale à 45°. */149export function ScatterChart({ points }: { points: { n: number; actual: number; chosen: number; correct: boolean }[] }) {150 if (points.length === 0) return null;151 const SH = 360;152 const all = points.flatMap((p) => [p.actual, p.chosen]);153 const lo = Math.max(1, Math.min(...all) * 0.9);154 const hi = Math.max(...all) * 1.1;155 // Échelle logarithmique : les prix s'étalent de 100 000 $ à plusieurs millions.156 const log = (v: number): number => Math.log10(v);157 const sx = scale([log(lo), log(hi)], [PAD.left + 24, W - PAD.right]);158 const sy = scale([log(lo), log(hi)], [SH - PAD.bottom, PAD.top]);159 const marks = [100_000, 200_000, 300_000, 500_000, 750_000, 1_000_000, 2_000_000, 5_000_000, 10_000_000].filter((v) => v >= lo && v <= hi);160 const short = (v: number): string => (v >= 1_000_000 ? `${(v / 1_000_000).toLocaleString("fr-CA")} M$` : `${Math.round(v / 1000)} k$`);161 return (162 <svg viewBox={`0 0 ${W} ${SH}`} role="img" aria-label={`Nuage de points de ${points.length} réponses : prix choisi en fonction du prix affiché. Les points au-dessus de la diagonale sont des surestimations, en dessous des sous-estimations.`}>163 {marks.map((m) => (164 <g key={m}>165 <line x1={sx(log(m))} x2={sx(log(m))} y1={PAD.top} y2={SH - PAD.bottom} stroke="var(--stone)" strokeWidth={0.5} />166 <line x1={PAD.left + 24} x2={W - PAD.right} y1={sy(log(m))} y2={sy(log(m))} stroke="var(--stone)" strokeWidth={0.5} />167 <text x={sx(log(m))} y={SH - 12} textAnchor="middle" className="chart-axis">{short(m)}</text>168 <text x={PAD.left + 16} y={sy(log(m)) + 4} textAnchor="end" className="chart-axis">{short(m)}</text>169 </g>170 ))}171 <line x1={sx(log(lo))} y1={sy(log(lo))} x2={sx(log(hi))} y2={sy(log(hi))} stroke="var(--graphite-2)" strokeWidth={1.2} strokeDasharray="6 4" />172 <text x={W - PAD.right - 4} y={PAD.top + 26} textAnchor="end" className="chart-axis">Surestimations ↑</text>173 <text x={W - PAD.right - 4} y={SH - PAD.bottom - 10} textAnchor="end" className="chart-axis">Sous-estimations ↓</text>174 {points.map((p) =>175 p.correct ? (176 <circle key={p.n} cx={sx(log(p.actual))} cy={sy(log(p.chosen))} r={4.2} fill="var(--success)" opacity={0.85}><title>{`Propriété ${p.n} : exact, ${formatMoney(p.actual)}`}</title></circle>177 ) : (178 <rect key={p.n} x={sx(log(p.actual)) - 4} y={sy(log(p.chosen)) - 4} width={8} height={8} fill="none" stroke="var(--error)" strokeWidth={1.8} transform={`rotate(45 ${sx(log(p.actual))} ${sy(log(p.chosen))})`}><title>{`Propriété ${p.n} : affiché ${formatMoney(p.actual)}, choisi ${formatMoney(p.chosen)}`}</title></rect>179 ),180 )}181 </svg>182 );183}184185/** Répartition surestimations / exactes / sous-estimations sur une seule barre. */186export function BiasBar({ over, under, exact }: { over: number; under: number; exact: number }) {187 const total = Math.max(1, over + under + exact);188 const parts = [189 { key: "under", label: "Sous-estimations", value: under, color: "var(--blue)" },190 { key: "exact", label: "Réponses exactes", value: exact, color: "var(--success)" },191 { key: "over", label: "Surestimations", value: over, color: "var(--coral)" },192 ];193 return (194 <div className="stack" style={{ "--gap": "var(--s-3)" } as React.CSSProperties}>195 <div style={{ display: "flex", height: 28, borderRadius: 6, overflow: "hidden", gap: 2 }} role="img" aria-label={parts.map((p) => `${p.label} : ${p.value}`).join(", ")}>196 {parts.map((p) => p.value > 0 && <motion.span key={p.key} initial={{ flexGrow: 0 }} whileInView={{ flexGrow: p.value / total }} viewport={{ once: true }} transition={{ duration: 0.9, ease: [0.16, 1, 0.3, 1] }} style={{ background: p.color, flexBasis: 0 }} />)}197 </div>198 <div className="row" style={{ "--gap": "var(--s-5)" } as React.CSSProperties}>199 {parts.map((p) => (200 <span key={p.key} className="small"><span aria-hidden="true" style={{ display: "inline-block", width: 10, height: 10, borderRadius: 2, background: p.color, marginRight: 6 }} />{p.label} : <strong className="tabular">{p.value}</strong></span>201 ))}202 </div>203 </div>204 );205}206