Repository Public
1/**2 * =============================================================================3 * SP BOUCHER | SOFTWARE & RESEARCH4 * ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project : Vrai-Prix8 * File : scripts/eval-immoka.ts9 * Module : scripts10 * Repository : https://git.spboucher.ai/vrai-prix11 * Created : 2026-09-0812 * Last Modified : 2026-09-0813 *14 * Author : Simon-Pierre Boucher15 * Position : Professor of Finance16 * Institution : Université du Québec en Outaouais (UQO)17 * Organization : SP Boucher18 * Website : https://spboucher.ai19 * Git : https://git.spboucher.ai20 *21 * Preferred Contact: contact@spboucher.ai22 * Development : dev@spboucher.ai23 * Support : support@spboucher.ai24 * Security/Admin : admin@spboucher.ai25 *26 * Copyright (c) 202627 * Simon-Pierre Boucher28 * All rights reserved where applicable. This file is governed by the29 * applicable project license, copyright notices and relevant law.30 * Existing third-party rights and notices remain unaffected.31 *32 * License : None specified (no license file in this repository)33 *34 * Do not embed credentials, private keys, access tokens,35 * certificates or confidential personal information.36 *37 * =============================================================================38 * END OF SP BOUCHER SOURCE HEADER39 * =============================================================================40 */4142/**43 * scripts/eval-immoka.ts — évalue en lot les annonces actives d'Immo-Ka avec44 * le moteur Vrai-Prix (même chemin que estimateByUnitId, sans le contexte45 * marché, inutile pour les agrégats).46 *47 * Jumelage 100 % spatial : chaque annonce (lat/lng géocodés par Immo-Ka) est48 * appariée à l'unité du rôle MAMH la plus proche (bbox sur idx_units_geo,49 * haversine ≤ 75 m puis repli ≤ 250 m), départagée par compatibilité de type,50 * superficie habitable et année de construction — indispensable pour les51 * condos/plex où plusieurs unités partagent les mêmes coordonnées.52 *53 * Sharding par processus (14 cœurs M4M36) :54 * SHARDS=6 SHARD=0..5 npx tsx scripts/eval-immoka.ts55 * Chaque shard écrit tmp/eval-shards/shard-N.jsonl ; la fusion + les agrégats56 * sont faits par scripts/build-marche-stats.mjs.57 *58 * Env : IMMOKA_DB (défaut data/immoka.db), VRAIPRIX_DB (défaut data/vraiprix.db),59 * LIMIT (test), SHARD/SHARDS.60 */61import Database from "better-sqlite3";62import fs from "fs";63import path from "path";64import { getCandidates, getDb, getMarketIndex, type TxRow, type UnitRow } from "../src/lib/db";65import { estimate, haversineM, type CompInput, type Subject } from "../src/lib/engine";66import { indexType } from "../src/lib/estimator";6768const SHARD = Number(process.env.SHARD ?? 0);69const SHARDS = Number(process.env.SHARDS ?? 1);70const LIMIT = Number(process.env.LIMIT ?? 0);71const IMMOKA_DB = process.env.IMMOKA_DB ?? path.join(process.cwd(), "data", "immoka.db");72const OUT_DIR = path.join(process.cwd(), "tmp", "eval-shards");7374// --- répliques des helpers privés d'estimator.ts (même logique exactement) ---75function toComps(rows: TxRow[]): CompInput[] {76 return rows.map((r) => ({77 id: r.id,78 date: r.date,79 amount: r.amount,80 lat: r.lat,81 lng: r.lng,82 propertyType: r.property_type,83 yearBuilt: r.year_built,84 floorArea: r.floor_area,85 street: r.street,86 city: r.city,87 }));88}89function since(months: number): string {90 const d = new Date();91 d.setMonth(d.getMonth() - months);92 return d.toISOString().slice(0, 10);93}94function candidatesAround(lat: number, lng: number): TxRow[] {95 for (const halfDeg of [0.02, 0.1]) {96 const rows = getCandidates(lat, lng, halfDeg, since(30), 600);97 if (rows.length >= 30) return rows;98 }99 return getCandidates(lat, lng, 0.25, since(36), 600);100}101const nowISO = new Date().toISOString().slice(0, 10);102103// L'indice de marché ne dépend que du type (3 valeurs) — cache évident en lot.104const idxCache = new Map<string, { month: string; idx: number }[]>();105function idxFor(typeProp: string) {106 const k = indexType(typeProp);107 let v = idxCache.get(k);108 if (!v) {109 v = getMarketIndex(k);110 idxCache.set(k, v);111 }112 return v;113}114115/* ------------------------- jumelage spatial lat/lng ------------------------- */116// types d'unités plausibles selon le type d'annonce Immo-Ka (clé pliée)117function typeBucket(pt: string | null): Set<string> | null {118 const t = (pt ?? "")119 .normalize("NFD")120 .replace(/[\u0300-\u036f]/g, "")121 .toLowerCase();122 if (!t) return null; // inconnu → aucune contrainte123 if (t.includes("condo")) return new Set(["condo_ou_multi", "unifamilial", "plex"]);124 if (/(du|tri|multi|quadru)plex/.test(t) || t.includes("plex")) return new Set(["plex", "condo_ou_multi"]);125 if (t.includes("terrain") || t.includes("lot")) return new Set(["terrain"]);126 if (t.includes("commerc") || t.includes("industri") || t.includes("bureau")) return new Set(["autre"]);127 if (t.includes("chalet")) return new Set(["chalet", "unifamilial"]);128 if (t.includes("ferme")) return new Set(["unifamilial", "autre", "terrain"]);129 if (t.includes("mobile")) return new Set(["maison_mobile", "unifamilial"]);130 // maison, jumelé, détachée, maison de ville, propriétés résidentielles…131 return new Set(["unifamilial", "chalet", "maison_mobile"]);132}133134const unitsInBox = getDb().prepare(135 `SELECT * FROM units136 WHERE lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?`137);138139interface ListingRow {140 uid: string;141 price: number;142 lat: number;143 lng: number;144 property_type: string | null;145 area_sqft: number | null;146 year_built: number | null;147}148149/** Unité la plus plausible pour l'annonce : distance + type + superficie + année. */150function matchUnit(l: ListingRow): { u: UnitRow; dist: number } | null {151 const bucket = typeBucket(l.property_type);152 const areaM2 = l.area_sqft && l.area_sqft > 100 ? l.area_sqft * 0.092903 : null;153 for (const [halfDeg, capM] of [154 [0.001, 75],155 [0.003, 250],156 ] as const) {157 const cands = unitsInBox.all(158 l.lat - halfDeg,159 l.lat + halfDeg,160 l.lng - halfDeg,161 l.lng + halfDeg162 ) as UnitRow[];163 let best: { u: UnitRow; dist: number; score: number } | null = null;164 for (const u of cands) {165 if (u.lat == null || u.lng == null) continue;166 const dist = haversineM(l.lat, l.lng, u.lat, u.lng);167 if (dist > capM) continue;168 let score = dist;169 if (bucket && !bucket.has(u.type_prop)) score += 120;170 if (areaM2 && u.aire_etages_m2 && u.aire_etages_m2 > 10)171 score += Math.min(1.5, Math.abs(areaM2 - u.aire_etages_m2) / u.aire_etages_m2) * 150;172 if (l.year_built && u.annee_construction && u.annee_construction > 1500)173 score += Math.min(50, Math.abs(l.year_built - u.annee_construction)) * 1.5;174 if (!best || score < best.score) best = { u, dist, score };175 }176 if (best) return { u: best.u, dist: best.dist };177 }178 return null;179}180181/* --------------- méthodes additionnelles : coût & rôle indexé --------------- */182/**183 * Méthode du coût, calibrée sur le marché par la technique du184 * résiduel : terrain au marché = valeur_terrain(rôle) × ratio de vente médian185 * du type ; bâtiment = aire d'étages × coût unitaire net médian $/m², lu dans186 * les ventes des 18 derniers mois (résiduel = prix ajusté au marché − terrain)187 * par type × tranche d'âge — la dépréciation est donc observée, pas imposée.188 * Méthode du rôle indexé (étude de ratios IAAO) : valeur = valeur_role ×189 * ratio médian vente/rôle de la municipalité (repli : province), par type.190 */191const AGE_BANDS = [5, 15, 30, 50, 75, Infinity];192const ageBand = (age: number | null): string => {193 if (age == null || age < 0) return "?";194 return String(AGE_BANDS.find((b) => age <= b));195};196197interface CalibTx {198 amount: number;199 date: string;200 type_prop: string;201 municipalite: string | null;202 valeur_terrain: number | null;203 aire_etages_m2: number | null;204 annee_construction: number | null;205 valeur_role: number | null;206}207const nowYear = new Date().getFullYear();208const idxByMonth = (bucket: string) => {209 const m = new Map<string, number>();210 for (const p of getMarketIndex(bucket)) m.set(p.month, p.idx);211 return m;212};213const calib = (() => {214 const txs = getDb()215 .prepare(216 `SELECT t.amount, t.date, u.type_prop, u.municipalite, u.valeur_terrain,217 u.aire_etages_m2, u.annee_construction, u.valeur_role218 FROM transactions t JOIN units u ON u.id_provinc = t.id_provinc219 WHERE t.date >= ? AND t.amount BETWEEN 50000 AND 5000000`220 )221 .all(since(18)) as CalibTx[];222 const idx: Record<string, Map<string, number>> = {223 unifamilial: idxByMonth("unifamilial"),224 plex: idxByMonth("plex"),225 condo: idxByMonth("condo"),226 };227 const adj = (t: CalibTx) => {228 const i = idx[indexType(t.type_prop)]?.get(t.date.slice(0, 7));229 return i && i > 0.3 ? t.amount / i : t.amount;230 };231 const med = (xs: number[]) => {232 const s = [...xs].sort((x, y) => x - y);233 const m = Math.floor(s.length / 2);234 return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;235 };236 // --- rôle indexé : ratio médian vente/rôle par municipalité×type (n≥12)237 const groups = new Map<string, number[]>();238 for (const t of txs) {239 if (!t.valeur_role || t.valeur_role < 10000) continue;240 const r = adj(t) / t.valeur_role;241 if (r < 0.3 || r > 4) continue;242 const bucket = indexType(t.type_prop);243 for (const k of [`${t.municipalite ?? "?"}|${bucket}`, `*|${bucket}`]) {244 if (!groups.has(k)) groups.set(k, []);245 groups.get(k)!.push(r);246 }247 }248 const roleRatio = new Map<string, number>();249 for (const [k, rs] of groups) if (rs.length >= 12) roleRatio.set(k, med(rs));250251 // --- coût : terrain × r* + résiduel médian $/m² par type × tranche d'âge252 const landFactor = new Map<string, number>();253 for (const bucket of ["unifamilial", "plex", "condo"]) {254 const r = roleRatio.get(`*|${bucket}`);255 if (r) landFactor.set(bucket, r);256 }257 const resid = new Map<string, number[]>();258 for (const t of txs) {259 if (!t.valeur_terrain || t.valeur_terrain <= 1000) continue;260 if (!t.aire_etages_m2 || t.aire_etages_m2 <= 20) continue;261 const bucket = indexType(t.type_prop);262 const lf = landFactor.get(bucket);263 if (!lf) continue;264 const rpm2 = (adj(t) - lf * t.valeur_terrain) / t.aire_etages_m2;265 if (rpm2 < -1000 || rpm2 > 10000) continue;266 const band = ageBand(t.annee_construction && t.annee_construction > 1500 ? nowYear - t.annee_construction : null);267 for (const k of [`${bucket}|${band}`, `${bucket}|*`]) {268 if (!resid.has(k)) resid.set(k, []);269 resid.get(k)!.push(rpm2);270 }271 }272 const costUnit = new Map<string, number>();273 for (const [k, rs] of resid) if (rs.length >= 150) costUnit.set(k, med(rs));274 console.log(275 `[shard ${SHARD}] calibration : ${txs.length} ventes 18 mois · coût ${[...costUnit.entries()]276 .filter(([k]) => k.endsWith("|*"))277 .map(([k, v]) => `${k.split("|")[0]} ${v.toFixed(0)}$/m²`)278 .join(" · ")} (${costUnit.size} cellules) · ${roleRatio.size} ratios rôle`279 );280 return { costUnit, landFactor, roleRatio };281})();282283function costEstimate(u: UnitRow): number | null {284 const bucket = indexType(u.type_prop);285 const lf = calib.landFactor.get(bucket);286 if (!lf || !u.valeur_terrain || u.valeur_terrain <= 1000) return null;287 if (!u.aire_etages_m2 || u.aire_etages_m2 <= 20) return null;288 const age = u.annee_construction && u.annee_construction > 1500 ? nowYear - u.annee_construction : null;289 const cpm2 = calib.costUnit.get(`${bucket}|${ageBand(age)}`) ?? calib.costUnit.get(`${bucket}|*`);290 if (cpm2 == null) return null;291 const v = lf * u.valeur_terrain + cpm2 * u.aire_etages_m2;292 return v > 0 ? Math.round(v / 100) * 100 : null;293}294function roleEstimate(u: UnitRow): number | null {295 if (!u.valeur_role || u.valeur_role < 10000) return null;296 const bucket = indexType(u.type_prop);297 const r = calib.roleRatio.get(`${u.municipalite ?? "?"}|${bucket}`) ?? calib.roleRatio.get(`*|${bucket}`);298 return r ? Math.round((u.valeur_role * r) / 100) * 100 : null;299}300const medianOf = (xs: number[]) => {301 const s = [...xs].sort((a, b) => a - b);302 const m = Math.floor(s.length / 2);303 return s.length % 2 ? s[m] : (s[m - 1] + s[m]) / 2;304};305306/* ---------------------------------- lot ---------------------------------- */307const immo = new Database(IMMOKA_DB, { readonly: true, fileMustExist: true });308const rows = immo309 .prepare(310 `SELECT uid, price, lat, lng, property_type, area_sqft, year_built FROM listings311 WHERE status='a-vendre' AND published=1 AND active=1 AND dup_hidden=0312 AND price > 0 AND lat IS NOT NULL AND lng IS NOT NULL313 AND (rowid % ?) = ?314 ${LIMIT ? "LIMIT " + LIMIT : ""}`315 )316 .all(SHARDS, SHARD) as ListingRow[];317318fs.mkdirSync(OUT_DIR, { recursive: true });319const outPath = path.join(OUT_DIR, `shard-${SHARD}.jsonl`);320const out = fs.createWriteStream(outPath);321322let done = 0;323let noUnit = 0;324const t0 = Date.now();325for (const r of rows) {326 const m = matchUnit(r);327 if (!m) {328 noUnit++;329 continue;330 }331 const u = m.u;332 const subject: Subject = {333 lat: u.lat,334 lng: u.lng,335 typeProp: u.type_prop,336 floorArea: u.aire_etages_m2,337 yearBuilt: u.annee_construction,338 landArea: u.superficie_terrain_m2,339 modelEstimate: u.est_2026,340 modelP10: u.p10,341 modelP90: u.p90,342 };343 const res = estimate(subject, toComps(candidatesAround(u.lat, u.lng)), idxFor(u.type_prop), nowISO);344 // méthodes complémentaires (la mesure principale reste l'hybride 65/35)345 const cost = costEstimate(u);346 const ridx = roleEstimate(u);347 const parts = [res.estimate, cost, ridx].filter((v): v is number => v != null && v > 0);348 const ens = parts.length ? Math.round(medianOf(parts)) : null;349 out.write(350 JSON.stringify({351 uid: r.uid,352 unit_id: u.id_provinc,353 match_m: Math.round(m.dist * 10) / 10,354 price: r.price,355 est: res.estimate,356 low: res.low,357 high: res.high,358 cpct: res.confidencePct,359 clevel: res.confidenceLevel,360 model: res.modelEstimate,361 comps: res.compsEstimate,362 mw: res.modelWeight,363 ncomps: res.nCompsUsed,364 cost,365 ridx,366 ens,367 role: u.valeur_role,368 type: u.type_prop,369 muni: u.municipalite,370 }) + "\n"371 );372 done++;373 if (done % 2000 === 0) {374 const rate = done / ((Date.now() - t0) / 1000);375 console.log(`[shard ${SHARD}] ${done}/${rows.length} (${rate.toFixed(0)}/s)`);376 }377}378out.end();379console.log(380 `[shard ${SHARD}] terminé : ${done} évaluées, ${noUnit} sans unité à ≤250 m, ` +381 `${((Date.now() - t0) / 1000).toFixed(0)} s → ${outPath}`382);383