Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : tests/test_kascores.py10# Module : tests11# 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# test_kascores.py : barème des KA Scores — décroissance, bornes, labels,91# non-aberration spatiale (deux immeubles voisins → scores proches).92# -----------------------------------------------------------------------------93import json94import math9596import pytest9798from louka import kascores99from louka.kascores import (100 Grid, TileIndex, _decroissance, label, score_calme, score_global,101 score_services, score_transit, score_walk,102)103104105def test_decroissance():106 assert _decroissance(100, 400, 1600) == 1.0107 assert _decroissance(400, 400, 1600) == 1.0108 assert _decroissance(1600, 400, 1600) == 0.0109 assert _decroissance(2500, 400, 1600) == 0.0110 assert 0.49 < _decroissance(1000, 400, 1600) < 0.51111112113def test_labels():114 assert label(92) == "Exceptionnel"115 assert label(71) == "Excellent"116 assert label(60) == "Très bon"117 assert label(45) == "Moyen"118 assert label(10) == "Faible"119 assert label(None) is None120121122def _env_urbain(lat=45.52, lng=-73.58):123 """Micro-quartier synthétique : tout à ~200 m."""124 d = 0.002 # ~200 m125 pois = {cat: [[lat + d, lng]] for cat, *_ in kascores.WALK_BAREME}126 pois["bus"] = [[lat, lng + d]]127 pois["metro"] = [[lat - d, lng]]128 pois["hopital"] = [[lat + 2 * d, lng]]129 return {"lines": {}, "points": {}, "pois": pois}130131132def test_walk_urbain_vs_desert():133 idx = TileIndex(_env_urbain())134 s, det = score_walk(idx, 45.52, -73.58)135 assert s is not None and s > 85136 vide = TileIndex({"lines": {}, "points": {}, "pois": {}})137 s2, det2 = score_walk(vide, 45.52, -73.58)138 assert s2 is None and "raison" in det2 # honnêteté : pas de 0 trompeur139140141def test_transit_non_desservi_et_blend():142 vide = TileIndex({"lines": {}, "points": {}, "pois": {}})143 s, det = score_transit(vide, 45.52, -73.58, None)144 assert s is None and "raison" in det # « Non desservi », pas 0145 idx = TileIndex(_env_urbain())146 proche, _ = score_transit(idx, 45.52, -73.58, 90.0)147 loin, _ = score_transit(idx, 45.52, -73.58, 10.0)148 assert proche is not None and loin is not None and proche > loin149150151def test_calme_autoroute_penalise():152 lat, lng = 45.52, -73.58153 calme_env = {"lines": {}, "points": {}, "pois": {}}154 bruyant_env = {155 "lines": {"autoroute": [[[lat + 0.0005, lng - 0.01],156 [lat + 0.0005, lng + 0.01]]]},157 "points": {}, "pois": {},158 }159 s_calme, _ = score_calme(TileIndex(calme_env), lat, lng)160 s_bruyant, d = score_calme(TileIndex(bruyant_env), lat, lng)161 assert s_calme - s_bruyant > 25162 assert any("autoroute" in x["source"] for x in d["sources_bruit"])163164165def test_services_rendement_decroissant():166 lat, lng = 45.52, -73.58167 def env(n):168 return {"lines": {}, "points": {}, "pois": {169 "epicerie": [[lat + 0.001 * i, lng] for i in range(1, n + 1)]}}170 s3, _ = score_services(TileIndex(env(3)), lat, lng)171 s6, _ = score_services(TileIndex(env(6)), lat, lng)172 s12, _ = score_services(TileIndex(env(12)), lat, lng)173 assert s3 < s6 < s12174 assert (s6 - s3) > (s12 - s6) # passer de 3→6 vaut plus que 6→12... x2175176177def test_global_renormalise_sans_transit():178 s = score_global({"walk": 80, "transit": None, "bike": 60,179 "calme": 70, "services": 50})180 assert s is not None and 60 < s < 75181 assert score_global({"walk": 80, "transit": None, "bike": None,182 "calme": None, "services": None}) is None183184185def test_coherence_spatiale_sur_le_parc():186 """Deux immeubles à < 200 m → scores globaux proches (médiane < 8 pts)."""187 from louka import db188 con = db.connect()189 rows = con.execute(190 "SELECT lat, lng, global AS g FROM kascores"191 " WHERE global IS NOT NULL ORDER BY coord_key LIMIT 3000").fetchall()192 con.close()193 if len(rows) < 200:194 pytest.skip("pas assez de scores calculés")195 g = Grid()196 vals = {}197 for r in rows:198 g.add(r["lat"], r["lng"])199 vals[(round(r["lat"], 5), round(r["lng"], 5))] = r["g"]200 diffs = []201 for r in rows[:800]:202 for d, la, ln in g.near(r["lat"], r["lng"], 200):203 if d < 1:204 continue205 v = vals.get((round(la, 5), round(ln, 5)))206 if v is not None:207 diffs.append(abs(v - r["g"]))208 assert diffs, "aucune paire voisine trouvée"209 diffs.sort()210 mediane = diffs[len(diffs) // 2]211 assert mediane < 8, f"médiane des écarts voisins : {mediane}"212