SPB Git

Repository Public

vector.ts 8.8 KB 144 lines typescript

1/**2 * =============================================================================3 *                  SP BOUCHER | SOFTWARE & RESEARCH4 *             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5 * =============================================================================6 *7 * Project          : Vrai-Prix8 * File             : src/lib/cost/ai/vector.ts9 * Module           : lib10 * 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 * Property Vector (§119-123, 154-155) : représentation canonique textuelle44 * déterministe + vecteur numérique déterministe (one-hot des catégories +45 * numériques normalisés). Modèle « vrai-prix-technical-v1 » : aucun appel46 * externe, reproductible ; l'interface `Embedder` permet de brancher plus tard47 * un modèle d'embedding réel. Module PUR.48 */49import type { MergedFacts } from "./merge";5051export const EMBEDDING_MODEL = "vrai-prix-technical-v1";5253export interface Embedder { model: string; embed(canonicalText: string, facts: MergedFacts): Promise<number[]> | number[] }5455const CATS = {56  buildingType: ["detached", "semi_detached", "row", "plex", "condo", "chalet", "mobile", "other"],57  quality: ["economy", "standard", "superior", "prestige"],58  basement: ["none", "crawl", "unfinished", "partial", "finished", "walkout"],59  garage: ["none", "attached", "detached", "integrated", "carport"],60  roof: ["asphalt_shingle", "metal", "membrane", "cedar", "slate_tile"],61  roofGeometry: ["gable", "hip", "flat", "mansard", "complex"],62  windows: ["pvc", "hybrid", "aluminum", "wood"],63  heating: ["electric_baseboard", "heat_pump", "furnace_electric", "furnace_gas", "furnace_oil", "hydronic", "geothermal", "wood"],64  foundation: ["poured_concrete", "concrete_block", "slab_on_grade", "piers", "stone"],65  structure: ["wood_frame", "steel", "concrete", "log", "masonry"],66  siding: ["vinyl", "brick", "fiber_cement", "wood", "stone", "stucco", "aluminum", "steel"],67  flooring: ["hardwood", "engineered", "vinyl_plank", "laminate", "ceramic", "carpet"],68  pool: ["none", "above_ground", "inground"],69  condition: ["poor", "below_average", "average", "good", "very_good", "excellent", "renovated", "new"],70} as const;71const CONDITION_GROUPS = ["structure", "roof", "exterior", "windows", "interior", "kitchen", "bathroom", "mechanical", "electrical", "site"];7273/** Dimension fixe du vecteur (documentée) : 8+4×3+6+5+5+5+4+8+5+5+8+6+3 = 80 catégoriels + 12 numériques + 10 conditions = 102. */74export const EMBEDDING_DIMENSION = 8 + 4 * 3 + 6 + 5 + 5 + 5 + 4 + 8 + 5 + 5 + 8 + 6 + 3 + 12 + 10;7576function oneHot(list: readonly string[], v: string | null | undefined): number[] {77  return list.map((x) => (x === v ? 1 : 0));78}79function shares(list: readonly string[], m: Record<string, number | undefined> | null): number[] {80  return list.map((x) => Math.max(0, Math.min(1, m?.[x] ?? 0)));81}8283export function canonicalText(m: MergedFacts): string {84  const t = m.buildingType.value.replace(/_/g, " ");85  const parts = [86    `${t.charAt(0).toUpperCase()}${t.slice(1)}.`,87    m.yearBuilt.value ? `${m.yearBuilt.value}.` : "Year unknown.",88    `${Math.round(m.grossFloorAreaSqft.value)} sqft.`,89    `${Math.round(m.stories.value)} ${m.stories.value > 1 ? "stories" : "story"}.`,90    `${m.structure.value.replace(/_/g, " ")}.`,91    `${m.foundation.value.replace(/_/g, " ")} foundation.`,92    `${Object.entries(m.siding.value).sort((a, b) => (b[1] ?? 0) - (a[1] ?? 0)).map(([k, v]) => `${k.replace(/_/g, " ")} ${Math.round((v ?? 0) * 100)}%`).join(", ")} exterior.`,93    `${m.roof.value.replace(/_/g, " ")} ${m.roofGeometry.value} roof.`,94    m.garage.value.type === "none" ? "No garage." : `${m.garage.value.type} ${m.garage.value.spaces}-car garage.`,95    `${m.basement.value} basement${m.basementFinishedPct.value ? ` ${Math.round(m.basementFinishedPct.value * 100)}% finished` : ""}.`,96    `${m.kitchenQuality.value} kitchen.`,97    `${m.bathrooms.value} bathrooms${m.powderRooms.value ? `, ${m.powderRooms.value} powder rooms` : ""}.`,98    `${m.bathroomQuality.value} bathrooms quality.`,99    Object.keys(m.flooring.value ?? {}).length ? `${Object.entries(m.flooring.value).sort((a, b) => b[1] - a[1]).map(([k]) => k.replace(/_/g, " ")).join(" and ")} floors.` : "",100    `${m.heating.value.replace(/_/g, " ")}${m.hasAirConditioning.value ? ", air conditioning" : ""}${m.hasAirExchanger.value ? ", air exchanger" : ""}.`,101    `${m.windows.value} windows.`,102    m.deckSqft.value ? `Deck ${Math.round(m.deckSqft.value)} sqft.` : "",103    m.pool.value !== "none" ? `${m.pool.value.replace(/_/g, " ")} pool.` : "",104    `Overall quality ${m.quality.value}.`,105    Object.keys(m.conditions).length ? `Condition ${Object.entries(m.conditions).map(([k, v]) => `${k} ${v}`).join(", ")}.` : "",106  ];107  return parts.filter(Boolean).join("\n");108}109110export function technicalVector(m: MergedFacts): number[] {111  const condIdx = (g: string) => { const c = m.conditions[g]; const i = c ? CATS.condition.indexOf(c as (typeof CATS.condition)[number]) : -1; return i < 0 ? 0.5 : i / (CATS.condition.length - 1); };112  const v = [113    ...oneHot(CATS.buildingType, m.buildingType.value),114    ...oneHot(CATS.quality, m.quality.value), ...oneHot(CATS.quality, m.kitchenQuality.value), ...oneHot(CATS.quality, m.bathroomQuality.value),115    ...oneHot(CATS.basement, m.basement.value), ...oneHot(CATS.garage, m.garage.value.type), ...oneHot(CATS.roof, m.roof.value), ...oneHot(CATS.roofGeometry, m.roofGeometry.value),116    ...oneHot(CATS.windows, m.windows.value), ...oneHot(CATS.heating, m.heating.value), ...oneHot(CATS.foundation, m.foundation.value), ...oneHot(CATS.structure, m.structure.value),117    ...shares(CATS.siding, m.siding.value as Record<string, number | undefined>), ...shares(CATS.flooring, m.flooring.value), ...oneHot(CATS.pool, m.pool.value),118    // numériques normalisés119    Math.min(1, Math.log10(Math.max(200, m.grossFloorAreaSqft.value)) / 4.5), Math.min(1, m.stories.value / 4), Math.min(1, ((new Date().getFullYear() - (m.yearBuilt.value ?? 1980)) || 0) / 120),120    Math.min(1, m.bathrooms.value / 5), Math.min(1, m.powderRooms.value / 3), Math.min(1, (m.bedrooms.value ?? 3) / 6), Math.min(1, m.deckSqft.value / 1000), Math.min(1, m.drivewaySqft.value / 2000),121    m.hasAirConditioning.value ? 1 : 0, m.hasAirExchanger.value ? 1 : 0, Math.min(1, m.basementFinishedPct.value), Math.min(1, m.garage.value.spaces / 3),122    ...CONDITION_GROUPS.map(condIdx),123  ];124  if (v.length !== EMBEDDING_DIMENSION) throw new Error(`dimension du vecteur ${v.length} ≠ ${EMBEDDING_DIMENSION}`);125  return v.map((x) => Math.round(x * 10000) / 10000);126}127128export const technicalEmbedder: Embedder = { model: EMBEDDING_MODEL, embed: (_t, facts) => technicalVector(facts) };129130export function cosine(a: number[], b: number[]): number {131  let dot = 0, na = 0, nb = 0;132  for (let i = 0; i < Math.min(a.length, b.length); i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }133  return na && nb ? dot / Math.sqrt(na * nb) : 0;134}135136/** Vecteur de structure de coût (§201) : parts normalisées par grande famille. */137export function costProfileVector(categories: { category: string; adjusted: number }[]): Record<string, number> {138  const fam: Record<string, string[]> = { foundation: ["site", "excavation", "foundation"], structure: ["structure"], envelope: ["roofing", "envelope", "openings", "insulation", "finishes_ext"], finish: ["interior", "kitchen", "bathroom", "basement"], mechanical: ["plumbing", "hvac", "electrical"], exterior: ["garage", "exterior"] };139  const total = categories.reduce((s, c) => s + c.adjusted, 0) || 1;140  const out: Record<string, number> = {};141  for (const [k, cats] of Object.entries(fam)) out[k] = Math.round((1000 * categories.filter((c) => cats.includes(c.category)).reduce((s, c) => s + c.adjusted, 0)) / total) / 1000;142  return out;143}144
Files main
Menu

Theme