SPB Git

Repository Public

kascores.py 22.1 KB 539 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/kascores.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-1813# Last Modified    : 2026-08-1814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# kascores.py : les KA Scores — famille de scores maison 0-100 par immeuble.91#92#   KA Walk Score     marchabilité (besoins quotidiens à pied)93#   KA Transit Score  desserte en transport collectif94#   KA Bike Score     praticité du vélo95#   KA Calme Score    tranquillité estimée du secteur96#   KA Services Score richesse des services (1 km / 3 km)97#   KA Score global   moyenne pondérée (personnalisable côté client)98#99#   Sources : OpenStreetMap (© contributeurs OSM, ODbL) via environment.py,100#   mesures de proximité StatCan (PMD 2021, quartier.db) pour le volet101#   fréquence/qualité du transport collectif. AUCUNE donnée inventée :102#   secteur sans données → NULL (« Données insuffisantes »), territoire sans103#   arrêt → NULL transit (« Non desservi »), et chaque score expose son104#   détail (details JSON) affiché sur la fiche.105#106#   Honnêteté méthodologique (affichée sur /ka-scores) :107#   · distances à vol d'oiseau × 1,3 (facteur réseau usuel), pas un routage ;108#   · le Calme est une estimation d'environnement, pas une mesure sonore ;109#   · le Bike ignore le dénivelé (v1) ;110#   · barème versionné — tout changement recalcule l'ensemble du parc.111# -----------------------------------------------------------------------------112from __future__ import annotations113114import json115import math116import sqlite3117import time118from pathlib import Path119120from . import db121from .environment import load_tile122from .poi import TILE, _haversine_m, _tile_of123124VERSION = "2026.08-v1"125DETOUR = 1.3                      # vol d'oiseau → distance de marche estimée126QUARTIER_DB = Path(__file__).resolve().parent.parent / "data" / "quartier.db"127128# --- barème Walk : (catégorie, poids, pleine note ≤ m, zéro au-delà de m) ---129WALK_BAREME = [130    ("epicerie",     3.0, 400, 1600),131    ("pharmacie",    2.0, 400, 1600),132    ("parc",         2.0, 300, 1200),133    ("cafe",         1.5, 300, 1200),134    ("ecole",        1.5, 500, 1600),135    ("clinique",     1.5, 600, 2400),136    ("garderie",     1.0, 500, 1600),137    ("depanneur",    1.0, 250, 1000),138    ("gym",          1.0, 500, 2000),139    ("bibliotheque", 1.0, 500, 2000),140]141142# --- barème Services : famille → (catégories, rayon m, saturation, poids) ---143SERVICES_BAREME = [144    ("commerces", ("epicerie", "depanneur", "cafe"),        1000, 15, 0.35),145    ("sante",     ("pharmacie", "clinique", "hopital"),     3000,  8, 0.25),146    ("education", ("ecole", "garderie", "bibliotheque"),    3000,  8, 0.20),147    ("loisirs",   ("gym", "parc"),                          1000,  6, 0.20),148]149150# --- pondérations par défaut du score global (personnalisables client) ---151GLOBAL_POIDS = {"walk": 0.30, "transit": 0.20, "bike": 0.15,152                "calme": 0.20, "services": 0.15}153154LABELS = [(85, "Exceptionnel"), (70, "Excellent"), (55, "Très bon"),155          (40, "Moyen"), (0, "Faible")]156157158def label(score: float | None) -> str | None:159    if score is None:160        return None161    for seuil, lbl in LABELS:162        if score >= seuil:163            return lbl164    return "Faible"165166167# ---------------------------------------------------------------------------168# Index spatial en grille (cellules ~0,01° ≈ 1,1 km) — recherches locales169# ---------------------------------------------------------------------------170171class Grid:172    def __init__(self, cell: float = 0.01) -> None:173        self.cell = cell174        self.cells: dict[tuple[int, int], list[tuple[float, float]]] = {}175176    def add(self, lat: float, lng: float) -> None:177        key = (int(lat // self.cell), int(lng // self.cell))178        self.cells.setdefault(key, []).append((lat, lng))179180    def near(self, lat: float, lng: float, radius_m: float):181        """Tous les points à ≤ radius_m (parcours des cellules voisines)."""182        r_lat = radius_m / 111000.0183        r_lng = radius_m / (111000.0 * max(0.2, math.cos(math.radians(lat))))184        span = int(max(r_lat, r_lng) // self.cell) + 1185        cy, cx = int(lat // self.cell), int(lng // self.cell)186        for dy in range(-span, span + 1):187            for dx in range(-span, span + 1):188                for plat, plng in self.cells.get((cy + dy, cx + dx), ()):189                    if abs(plat - lat) > r_lat or abs(plng - lng) > r_lng:190                        continue191                    d = _haversine_m(lat, lng, plat, plng)192                    if d <= radius_m:193                        yield d, plat, plng194195    def nearest(self, lat: float, lng: float, radius_m: float) -> float | None:196        best = None197        for d, _la, _ln in self.near(lat, lng, radius_m):198            if best is None or d < best:199                best = d200        return best201202    def count(self, lat: float, lng: float, radius_m: float) -> int:203        return sum(1 for _ in self.near(lat, lng, radius_m))204205206class TileIndex:207    """Grilles par classe pour une tuile d'environnement."""208209    def __init__(self, env: dict) -> None:210        self.pois: dict[str, Grid] = {}211        for cat, pts in env.get("pois", {}).items():212            g = Grid()213            for lat, lng in pts:214                g.add(lat, lng)215            self.pois[cat] = g216        self.points: dict[str, Grid] = {}217        for cls, pts in env.get("points", {}).items():218            g = Grid()219            for lat, lng in pts:220                g.add(lat, lng)221            self.points[cls] = g222        # lignes : nœuds DENSIFIÉS (≤ 60 m) dans une grille — la distance au223        # nœud le plus proche approxime alors la distance à la voie, même224        # sur les longs segments droits (autoroutes rurales)225        self.lines: dict[str, Grid] = {}226        self.cyclable_seglen: dict[tuple[int, int], float] = {}227        for cls, ways in env.get("lines", {}).items():228            g = self.lines.setdefault(cls, Grid())229            for way in ways:230                for i, (lat, lng) in enumerate(way):231                    g.add(lat, lng)232                    if i == 0:233                        continue234                    plat, plng = way[i - 1]235                    seg = _haversine_m(plat, plng, lat, lng)236                    if cls == "cyclable":237                        mid_lat, mid_lng = (lat + plat) / 2, (lng + plng) / 2238                        key = (int(mid_lat // 0.01), int(mid_lng // 0.01))239                        self.cyclable_seglen[key] = (240                            self.cyclable_seglen.get(key, 0.0) + seg)241                    if seg > 60:242                        n = int(seg // 60)243                        for j in range(1, n + 1):244                            t = j / (n + 1)245                            g.add(plat + (lat - plat) * t, plng + (lng - plng) * t)246247    def cyclable_metres(self, lat: float, lng: float, radius_m: float) -> float:248        """Mètres de voies cyclables ~dans le rayon (somme par cellule)."""249        r_cells = int(radius_m / 1100) + 1250        cy, cx = int(lat // 0.01), int(lng // 0.01)251        total = 0.0252        for dy in range(-r_cells, r_cells + 1):253            for dx in range(-r_cells, r_cells + 1):254                total += self.cyclable_seglen.get((cy + dy, cx + dx), 0.0)255        return total256257258# ---------------------------------------------------------------------------259# Calcul des scores pour une coordonnée260# ---------------------------------------------------------------------------261262def _decroissance(dist_m: float, pleine: float, zero: float) -> float:263    """1 en deçà de `pleine`, 0 au-delà de `zero`, linéaire entre les deux."""264    if dist_m <= pleine:265        return 1.0266    if dist_m >= zero:267        return 0.0268    return (zero - dist_m) / (zero - pleine)269270271def score_walk(idx: TileIndex, lat: float, lng: float) -> tuple[float | None, dict]:272    total_poids = sum(p for _c, p, _f, _z in WALK_BAREME)273    acquis = 0.0274    cats = []275    trouvees = 0276    for cat, poids, pleine, zero in WALK_BAREME:277        g = idx.pois.get(cat)278        brut = g.nearest(lat, lng, zero / DETOUR + 200) if g else None279        if brut is None:280            cats.append({"cat": cat, "dist_m": None, "pts": 0.0})281            continue282        marche = brut * DETOUR283        part = _decroissance(marche, pleine, zero)284        acquis += poids * part285        trouvees += 1286        cats.append({"cat": cat, "dist_m": round(marche), "pts": round(part * 100)})287    if trouvees < 2:288        return None, {"cats": cats, "raison": "moins de 2 commodités cartographiées"}289    # bonus de choix : plusieurs épiceries/cafés à ≤ 800 m de marche290    bonus = 0.0291    for cat in ("epicerie", "cafe"):292        g = idx.pois.get(cat)293        if g and g.count(lat, lng, 800 / DETOUR) >= 3:294            bonus += 2.5295    score = min(100.0, 100.0 * acquis / total_poids + bonus)296    return round(score, 1), {"cats": cats, "bonus_choix": bonus}297298299def score_transit(idx: TileIndex, lat: float, lng: float,300                  pmd_pct: float | None) -> tuple[float | None, dict]:301    g_bus, g_metro = idx.pois.get("bus"), idx.pois.get("metro")302    d_bus = g_bus.nearest(lat, lng, 900) if g_bus else None303    d_metro = g_metro.nearest(lat, lng, 1600) if g_metro else None304    prox = 0.0305    if d_bus is not None:306        prox = max(prox, 100.0 * _decroissance(d_bus * DETOUR, 200, 900))307    if d_metro is not None:308        prox = max(prox, 100.0 * _decroissance(d_metro * DETOUR, 600, 1800) * 1.15)309    prox = min(100.0, prox)310    detail = {311        "arret_bus_m": round(d_bus * DETOUR) if d_bus is not None else None,312        "station_metro_m": round(d_metro * DETOUR) if d_metro is not None else None,313        "pmd_percentile": round(pmd_pct) if pmd_pct is not None else None,314    }315    if d_bus is None and d_metro is None:316        if pmd_pct is None or pmd_pct <= 1:317            return None, {**detail, "raison": "aucun arrêt à distance de marche"}318        return round(pmd_pct * 0.5, 1), detail   # desserte lointaine plausible319    if pmd_pct is None:320        return round(prox * 0.85, 1), detail     # proximité seule, prudente321    # proximité de l'arrêt × qualité de desserte du secteur (PMD StatCan)322    return round(0.45 * prox + 0.55 * pmd_pct, 1), detail323324325def score_bike(idx: TileIndex, lat: float, lng: float) -> tuple[float | None, dict]:326    km = idx.cyclable_metres(lat, lng, 1000) / 1000.0327    infra = min(60.0, km * 11.0)328    # accessibilité des besoins quotidiens à vélo (seuils marche × 3)329    total_poids = sum(p for _c, p, _f, _z in WALK_BAREME)330    acquis = 0.0331    trouvees = 0332    for cat, poids, pleine, zero in WALK_BAREME:333        g = idx.pois.get(cat)334        brut = g.nearest(lat, lng, zero * 3 / DETOUR + 400) if g else None335        if brut is None:336            continue337        acquis += poids * _decroissance(brut * DETOUR, pleine * 3, zero * 3)338        trouvees += 1339    if trouvees < 2 and km == 0:340        return None, {"raison": "réseau cyclable et commodités non cartographiés"}341    access = 40.0 * acquis / total_poids342    return round(min(100.0, infra + access), 1), {343        "km_cyclables_1km": round(km, 1),344        "note": "dénivelé non pris en compte (v1)",345    }346347348def score_calme(idx: TileIndex, lat: float, lng: float) -> tuple[float, dict]:349    score = 88.0350    sources = []351352    def penalite(cls: str, rayon: float, poids: float, nom: str,353                 lignes: bool = True) -> None:354        nonlocal score355        g = idx.lines.get(cls) if lignes else idx.points.get(cls)356        d = g.nearest(lat, lng, rayon) if g else None357        if d is not None:358            p = poids * _decroissance(d, rayon * 0.08, rayon)359            if p > 0.5:360                score -= p361                sources.append({"source": nom, "dist_m": round(d), "pen": round(p, 1)})362363    penalite("autoroute", 800, 42, "autoroute")364    penalite("artere", 400, 22, "artère principale")365    penalite("rail", 500, 18, "voie ferrée")366    penalite("aeroport", 3000, 25, "aéroport/héliport", lignes=False)367    penalite("industriel", 600, 14, "zone industrielle", lignes=False)368369    g_bar = idx.points.get("bar")370    n_bars = g_bar.count(lat, lng, 250) if g_bar else 0371    if n_bars >= 2:372        p = min(12.0, 4.0 * (n_bars - 1))373        score -= p374        sources.append({"source": f"{n_bars} bars/boîtes à moins de 250 m",375                        "dist_m": None, "pen": round(p, 1)})376377    g_parc = idx.pois.get("parc")378    d_parc = g_parc.nearest(lat, lng, 700) if g_parc else None379    bonus = 0.0380    if d_parc is not None:381        bonus = 8.0 if d_parc <= 300 else 4.0382        score += bonus383    return round(max(0.0, min(100.0, score)), 1), {384        "sources_bruit": sources, "bonus_parc": bonus,385        "note": "estimation basée sur l'environnement, pas une mesure sonore",386    }387388389def score_services(idx: TileIndex, lat: float, lng: float) -> tuple[float | None, dict]:390    total = 0.0391    familles = {}392    n_cats = 0393    for fam, cats, rayon, sat, poids in SERVICES_BAREME:394        n = sum((idx.pois.get(c).count(lat, lng, rayon) if idx.pois.get(c) else 0)395                for c in cats)396        n_cats += 1 if n > 0 else 0397        part = min(1.0, math.log1p(n) / math.log1p(sat))398        total += poids * part399        familles[fam] = n400    if n_cats == 0:401        return None, {"familles": familles, "raison": "aucun service cartographié"}402    return round(100.0 * total, 1), {"familles": familles}403404405def score_global(scores: dict[str, float | None]) -> float | None:406    poids_total = 0.0407    acquis = 0.0408    for k, p in GLOBAL_POIDS.items():409        if scores.get(k) is not None:410            poids_total += p411            acquis += p * scores[k]           # type: ignore[operator]412    if poids_total < 0.5:                     # trop peu de composantes fiables413        return None414    return round(acquis / poids_total, 1)415416417# ---------------------------------------------------------------------------418# Recalcul du parc419# ---------------------------------------------------------------------------420421def _pmd_transit_by_dauid() -> dict[str, float]:422    """Percentile PMD « transport collectif » par aire de diffusion."""423    if not QUARTIER_DB.exists():424        return {}425    qcon = sqlite3.connect(QUARTIER_DB)426    qcon.row_factory = sqlite3.Row427    try:428        return {r["dauid"]: r["prox_transport"] for r in qcon.execute(429            "SELECT dauid, prox_transport FROM da_pmd_pct"430            " WHERE prox_transport IS NOT NULL")}431    except sqlite3.OperationalError:432        return {}433    finally:434        qcon.close()435436437def run(recompute_all: bool = False) -> dict:438    """Calcule les KA Scores de tous les immeubles couverts par env_tiles.439440    Incrémental : seules les coordonnées sans score (ou d'une version de441    barème antérieure) sont recalculées, sauf `recompute_all`.442    """443    con = db.connect()444    t0 = time.time()445    pmd = _pmd_transit_by_dauid()446447    rows = con.execute(448        """SELECT ROUND(lat,4) la, ROUND(lng,4) ln,449                  MAX(dauid) dauid450           FROM listings451           WHERE active=1 AND lat IS NOT NULL AND lng IS NOT NULL452           GROUP BY la, ln""").fetchall()453454    existants = {r["coord_key"] for r in con.execute(455        "SELECT coord_key FROM kascores WHERE version=?", (VERSION,))}456457    par_tuile: dict[tuple[int, int], list] = {}458    for r in rows:459        key = f"{r['la']},{r['ln']}"460        if not recompute_all and key in existants:461            continue462        par_tuile.setdefault(_tile_of(r["la"], r["ln"]), []).append(463            (key, r["la"], r["ln"], r["dauid"]))464465    calcules = sans_tuile = 0466    for tile, coords in sorted(par_tuile.items()):467        env = load_tile(con, *tile)468        if env is None:469            sans_tuile += len(coords)470            continue471        idx = TileIndex(env)472        for key, lat, lng, dauid in coords:473            pmd_pct = pmd.get(dauid) if dauid and dauid != "hors-zone" else None474            walk, d_walk = score_walk(idx, lat, lng)475            transit, d_transit = score_transit(idx, lat, lng, pmd_pct)476            bike, d_bike = score_bike(idx, lat, lng)477            calme, d_calme = score_calme(idx, lat, lng)478            services, d_services = score_services(idx, lat, lng)479            scores = {"walk": walk, "transit": transit, "bike": bike,480                      "calme": calme, "services": services}481            glob = score_global(scores)482            details = {483                "walk": d_walk, "transit": d_transit, "bike": d_bike,484                "calme": d_calme, "services": d_services,485                "labels": {k: label(v) for k, v in scores.items()},486            }487            con.execute(488                """INSERT OR REPLACE INTO kascores489                   (coord_key, lat, lng, walk, transit, bike, calme, services,490                    global, details, version, computed_at)491                   VALUES (?,?,?,?,?,?,?,?,?,?,?,?)""",492                (key, lat, lng, walk, transit, bike, calme, services, glob,493                 json.dumps(details, ensure_ascii=False), VERSION, time.time()))494            calcules += 1495        con.commit()496        print(f"  tuile {tile[0]},{tile[1]} : {len(coords)} immeubles")497498    # clé de jointure sur les annonces (nouvelles incluses)499    con.execute(500        """UPDATE listings501           SET coord_key = ROUND(lat,4) || ',' || ROUND(lng,4)502           WHERE lat IS NOT NULL AND lng IS NOT NULL503             AND (coord_key IS NULL504                  OR coord_key != ROUND(lat,4) || ',' || ROUND(lng,4))""")505    con.commit()506507    # calibration : distribution du score global sur le parc508    dist = [r["global"] for r in con.execute(509        "SELECT global FROM kascores WHERE global IS NOT NULL ORDER BY global")]510    deciles = ([round(dist[int(len(dist) * q / 10)]) for q in range(10)] +511               [round(dist[-1])]) if dist else []512    con.close()513    return {"immeubles_calcules": calcules, "sans_tuile_env": sans_tuile,514            "scores_en_base": len(dist), "deciles_global": deciles,515            "version": VERSION, "duree_s": round(time.time() - t0, 1)}516517518def stats() -> dict:519    """Couverture et distributions — page méthodologie + Stats Lou-Ka."""520    con = db.connect()521    total = con.execute(522        """SELECT COUNT(*) c FROM listings523           WHERE active=1 AND published=1 AND dup_of IS NULL""").fetchone()["c"]524    scored = con.execute(525        """SELECT COUNT(*) c FROM listings l JOIN kascores k526           ON k.coord_key = l.coord_key527           WHERE l.active=1 AND l.published=1 AND l.dup_of IS NULL528             AND k.global IS NOT NULL""").fetchone()["c"]529    out: dict = {"annonces": total, "avec_score": scored,530                 "couverture_pct": round(100.0 * scored / total, 1) if total else 0,531                 "version": VERSION, "moyennes": {}}532    for col in ("walk", "transit", "bike", "calme", "services", "global"):533        r = con.execute(534            f"SELECT AVG({col}) m, COUNT({col}) n FROM kascores").fetchone()535        out["moyennes"][col] = {"moyenne": round(r["m"], 1) if r["m"] else None,536                                "n": r["n"]}537    con.close()538    return out539
Files main
Menu

Theme