Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : KA Maps Engine10# File : server/km-geo/tests/eval_geo.py11# Description : Évaluation de km-geo contre le service en marche.12# Module : server13# Repository : https://git.spboucher.ai/ka-maps-engine14# Created : 2026-12-0115# Last Modified : 2026-12-0116#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: support@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Évaluation de km-geo contre le service en marche. Sorties JSON à reporter dans docs/TEST_REPORT.md.9091 eval_geo.py testset construit tests/geocode_sample.tsv : adresses réelles tirées d'OpenStreetMap (geo.osm_addr),92 source INDÉPENDANTE des adresses servies (OSM n'est pas fusionné dans geo.address)93 eval_geo.py geocode taux de réussite et erreur de position (jeu manuel + échantillon OSM)94 eval_geo.py gate garde-fou des reconstructions : échoue si le jeu de test passe sous les seuils de gate.json95 eval_geo.py reverse géocodage inverse et appartenance aux limites96 eval_geo.py latency p50 / p95 / p99 par point d'accès97 eval_geo.py isochrone bornes de vraisemblance et latences de /v1/isochrone et /v1/route98 eval_geo.py sources écart de position entre sources d'adresses (base)99100Dépendances : bibliothèque standard ; `psql kamaps` (socket locale) pour testset, reverse et sources.101"""102import json, math, os, statistics, subprocess, sys, time, unicodedata, urllib.parse, urllib.request103from concurrent.futures import ThreadPoolExecutor104105HERE = os.path.dirname(os.path.abspath(__file__))106BASE = os.environ.get("KM_GEO_URL", "http://127.0.0.1:8902")107SAMPLE = os.path.join(HERE, "geocode_sample.tsv")108109STRATA = [ # (strate, condition SQL sur la municipalité, nombre)110 ("Montréal", "m.id = 66023", 40),111 ("Québec", "m.id = 23027", 30),112 ("Gatineau", "m.id = 81017", 25),113 ("Sherbrooke", "m.id = 43027", 25),114 ("Saguenay", "m.id = 94068", 25),115 ("autres villes (> 20 000 adresses)", "m.n_addr > 20000 AND m.id NOT IN (66023, 23027, 81017, 43027, 94068)", 30),116 ("villes moyennes (3 000 à 20 000)", "m.n_addr BETWEEN 3000 AND 20000", 30),117 ("petites municipalités rurales (< 3 000 adresses)", "m.n_addr < 3000", 45),118]119120121def psql(sql):122 out = subprocess.run(["psql", "kamaps", "-X", "-At", "-F", "\t", "-c", sql], capture_output=True, text=True, check=True).stdout123 return [l.split("\t") for l in out.splitlines() if l]124125126_last = [0.0]127THROTTLED = [0]128129130def get(path, params=None, method="GET", body=None):131 # Hors boucle locale, au plus ~18 requêtes/s : le service limite chaque IP à 20/s (rafale 60).132 wait = _last[0] + 0.055 - time.perf_counter()133 if wait > 0 and "127.0.0.1" not in BASE:134 time.sleep(wait)135 _last[0] = time.perf_counter()136 url = BASE + path + ("?" + urllib.parse.urlencode(params) if params else "")137 req = urllib.request.Request(url, data=body, method=method, headers={"Content-Type": "application/json"} if body else {})138 t0 = time.perf_counter()139 try:140 with urllib.request.urlopen(req, timeout=10) as r:141 data = r.read()142 code = r.status143 except urllib.error.HTTPError as e:144 data, code = e.read(), e.code145 dt = (time.perf_counter() - t0) * 1000146 if code == 429:147 THROTTLED[0] += 1148 try:149 js = json.loads(data)150 except Exception:151 js = None152 return code, js, dt153154155def fold(s):156 s = unicodedata.normalize("NFD", s.lower())157 s = "".join(c for c in s if unicodedata.category(c) != "Mn")158 return " ".join("".join(c if c.isalnum() else " " for c in s).split())159160161def dist_m(lon1, lat1, lon2, lat2):162 p = math.pi / 180163 a = math.sin((lat2 - lat1) * p / 2) ** 2 + math.cos(lat1 * p) * math.cos(lat2 * p) * math.sin((lon2 - lon1) * p / 2) ** 2164 return 2 * 6371008.8 * math.asin(math.sqrt(a))165166167def pct(v, q):168 if not v:169 return None170 v = sorted(v)171 return round(v[min(len(v) - 1, int(math.ceil(q * len(v))) - 1)], 2)172173174def cmd_testset():175 rows = []176 for name, cond, n in STRATA:177 # Tirage déterministe (md5 de l'identifiant OSM) ; au plus 2 adresses par rue pour varier.178 got = psql(f"""179 WITH c AS (180 SELECT o.ref, o.num, o.suffix, o.street, coalesce(o.city, m.name) AS city, m.name AS mun,181 round(ST_X(o.pt)::numeric, 6) AS lon, round(ST_Y(o.pt)::numeric, 6) AS lat,182 row_number() OVER (PARTITION BY o.mun_id, o.street ORDER BY md5(o.ref)) AS rn183 FROM geo.osm_addr o JOIN geo.mun m ON m.id = o.mun_id184 WHERE {cond} AND o.street !~ '[\\t\\n]' AND length(o.street) BETWEEN 4 AND 60)185 SELECT ref, num || suffix, street, city, mun, lon, lat FROM c WHERE rn <= 2 ORDER BY md5(ref || 'kamaps-2026') LIMIT {n}""")186 for r in got:187 rows.append([name] + r)188 with open(SAMPLE, "w", encoding="utf-8") as f:189 f.write("# Échantillon d'adresses © les contributeurs d'OpenStreetMap (ODbL 1.0) — extrait non substantiel, pour test.\n")190 f.write("# strate\tosm\tnumero\true\tville_osm\tmunicipalite\tlon\tlat\n")191 for r in rows:192 f.write("\t".join(r) + "\n")193 print(json.dumps({"rows": len(rows), "file": SAMPLE}))194195196def check_manual(case):197 code, js, dt = get("/v1/search", {"q": case["q"], "limit": 5})198 res = (js or {}).get("results", []) if code == 200 else []199 top = res[0] if res else None200 def ok(r):201 if r["type"] != case["type"]:202 return False203 lab = fold(r.get("label", "") + " " + (r.get("postcode") or ""))204 if not all(fold(c) in lab for c in case.get("contains", [])):205 return False206 if case["type"] == "address" and r.get("approx"):207 return False208 if "near" in case:209 lon, lat, mx = case["near"]210 if dist_m(lon, lat, r["lon"], r["lat"]) > mx:211 return False212 return True213 hit1 = bool(top and ok(top))214 hit5 = any(ok(r) for r in res)215 return dict(q=case["q"], cat=case["cat"], hit1=hit1, hit5=hit5, got=(top or {}).get("label"), got_type=(top or {}).get("type"), ms=dt)216217218def cmd_geocode():219 manual = json.load(open(os.path.join(HERE, "cases_manual.json"), encoding="utf-8"))220 mres = [check_manual(c) for c in manual]221 cats = {}222 for r in mres:223 c = cats.setdefault(r["cat"], dict(n=0, hit1=0, hit5=0))224 c["n"] += 1; c["hit1"] += r["hit1"]; c["hit5"] += r["hit5"]225 sample = [l.rstrip("\n").split("\t") for l in open(SAMPLE, encoding="utf-8") if not l.startswith("#")]226 strata, errs, sres = {}, [], []227 ierrs, nerrs = [], []228 for stratum, ref, num, street, city, mun, lon, lat in sample:229 lon, lat = float(lon), float(lat)230 q = f"{num} {street}, {city}"231 code, js, dt = get("/v1/search", {"q": q, "limit": 5})232 res = (js or {}).get("results", []) if code == 200 else []233 def match(r):234 return r["type"] == "address" and not r.get("approx") and fold(r["housenumber"]) == fold(num)235 top = res[0] if res else None236 hit1 = bool(top and match(top))237 hit5 = any(match(r) for r in res)238 s = strata.setdefault(stratum, dict(n=0, hit1=0, hit5=0, interpolated=0, nearest=0, none=0, err=[], ierr=[], lerr=[]))239 s["n"] += 1; s["hit1"] += hit1; s["hit5"] += hit5240 e = None241 method = (top or {}).get("method") if top and top["type"] == "address" else None242 if top and top["type"] == "address":243 e = dist_m(lon, lat, top["lon"], top["lat"])244 if hit1:245 s["err"].append(e); errs.append(e); s["lerr"].append(e)246 elif method == "interpolated":247 s["interpolated"] += 1; s["ierr"].append(e); ierrs.append(e); s["lerr"].append(e)248 elif method == "nearest":249 s["nearest"] += 1; nerrs.append(e)250 else:251 s["none"] += 1252 sres.append(dict(q=q, stratum=stratum, hit1=hit1, hit5=hit5, method=method, err_m=None if e is None else round(e, 1),253 got=(top or {}).get("label"), src=(top or {}).get("source")))254 def summ(s):255 e = s.pop("err"); ie = s.pop("ierr", []); le = s.pop("lerr", [])256 s.update(hit1_pct=round(100 * s["hit1"] / s["n"], 1), hit5_pct=round(100 * s["hit5"] / s["n"], 1),257 err_median_m=pct(e, 0.5), err_p90_m=pct(e, 0.9),258 interpolated_err_median_m=pct(ie, 0.5), interpolated_err_p90_m=pct(ie, 0.9),259 located_pct=round(100 * len(le) / s["n"], 1), located_err_median_m=pct(le, 0.5), located_err_p90_m=pct(le, 0.9))260 return s261 all_s = dict(n=len(sample), hit1=sum(r["hit1"] for r in sres), hit5=sum(r["hit5"] for r in sres), err=list(errs),262 interpolated=len(ierrs), nearest=len(nerrs), none=len(sample) - len(errs) - len(ierrs) - len(nerrs),263 ierr=list(ierrs), lerr=list(errs) + list(ierrs), nearest_err_median_m=pct(nerrs, 0.5))264 rep = dict(265 manual=dict(n=len(mres), hit1=sum(r["hit1"] for r in mres), hit5=sum(r["hit5"] for r in mres),266 hit1_pct=round(100 * sum(r["hit1"] for r in mres) / len(mres), 1),267 hit5_pct=round(100 * sum(r["hit5"] for r in mres) / len(mres), 1), by_category=cats,268 failures=[dict(q=r["q"], cat=r["cat"], got=r["got"], got_type=r["got_type"], in_top5=r["hit5"]) for r in mres if not r["hit1"]]),269 osm_sample=dict(overall=summ(all_s),270 within_25m_pct=round(100 * sum(e <= 25 for e in errs) / max(1, len(errs)), 1),271 within_50m_pct=round(100 * sum(e <= 50 for e in errs) / max(1, len(errs)), 1),272 within_100m_pct=round(100 * sum(e <= 100 for e in errs) / max(1, len(errs)), 1),273 by_stratum={k: summ(v) for k, v in strata.items()},274 failures=[r for r in sres if not r["hit1"]][:80]),275 total_cases=len(mres) + len(sample),276 )277 if RETURN_REPORT[0]:278 return rep279 print(json.dumps(rep, ensure_ascii=False, indent=1))280281282RETURN_REPORT = [False]283284285def cmd_gate():286 """Garde-fou d'une reconstruction : le jeu de test ne doit pas régresser sous les seuils de tests/gate.json."""287 RETURN_REPORT[0] = True288 rep = cmd_geocode()289 gate = json.load(open(os.path.join(HERE, "gate.json"), encoding="utf-8"))290 got = dict(manual_hit1_pct=rep["manual"]["hit1_pct"], manual_hit5_pct=rep["manual"]["hit5_pct"],291 osm_exact_pct=rep["osm_sample"]["overall"]["hit1_pct"], osm_located_pct=rep["osm_sample"]["overall"]["located_pct"],292 osm_err_median_m=rep["osm_sample"]["overall"]["err_median_m"])293 bad = [k for k in ("manual_hit1_pct", "manual_hit5_pct", "osm_exact_pct", "osm_located_pct") if got[k] < gate[k + "_min"]]294 if got["osm_err_median_m"] is None or got["osm_err_median_m"] > gate["osm_err_median_m_max"]:295 bad.append("osm_err_median_m")296 print(json.dumps(dict(ok=not bad, failed=bad, measured=got, thresholds=gate), ensure_ascii=False))297 sys.exit(1 if bad or THROTTLED[0] else 0)298299300def cmd_reverse():301 rep = {}302 # 1. Cohérence interne : inverse au point d'une adresse servie → même adresse303 rows = psql("""SELECT a.id, a.num || a.suffix, s.name, m.name, ST_X(ST_Transform(a.pt, 4326)), ST_Y(ST_Transform(a.pt, 4326))304 FROM geo.address a TABLESAMPLE SYSTEM (0.05) JOIN geo.street s ON s.id = a.street_id JOIN geo.mun m ON m.id = s.mun_id305 ORDER BY md5(a.id::text) LIMIT 400""")306 same = same_mun = 0307 for _id, house, street, mun, lon, lat in rows:308 code, js, _ = get("/v1/reverse", {"lon": lon, "lat": lat})309 a = (js or {}).get("address") or {}310 # plusieurs adresses peuvent partager exactement le même point (immeubles) : on compare l'identifiant ou la distance nulle311 same += a.get("id") == f"address:{_id}" or (a.get("distance_m") == 0.0)312 same_mun += ((js or {}).get("municipality") or {}).get("name") == mun313 rep["self_consistency"] = dict(n=len(rows), same_point_address_pct=round(100 * same / len(rows), 1),314 same_municipality_pct=round(100 * same_mun / len(rows), 1))315 # 2. Source indépendante : inverse au point d'une adresse OSM → rue et numéro316 sample = [l.rstrip("\n").split("\t") for l in open(SAMPLE, encoding="utf-8") if not l.startswith("#")]317 st_ok = num_ok = mun_ok = city_cmp = city_ok = street_field_ok = 0318 d = []319 conf = {}320 def same(a, b):321 a, b = fold(a), fold(b)322 return bool(a) and (a == b or a in b or b in a)323 for stratum, ref, num, street, city, mun, lon, lat in sample:324 code, js, _ = get("/v1/reverse", {"lon": lon, "lat": lat})325 js = js or {}326 a = js.get("address") or {}327 s_ok = same(a.get("street", ""), street)328 st_ok += s_ok329 street_field_ok += same((js.get("street") or {}).get("name", ""), street)330 num_ok += s_ok and fold(a.get("housenumber", "")) == fold(num)331 c = conf.setdefault(js.get("confidence"), dict(n=0, same_street=0, same_number=0))332 c["n"] += 1; c["same_street"] += s_ok; c["same_number"] += s_ok and fold(a.get("housenumber", "")) == fold(num)333 if a:334 d.append(a["distance_m"])335 m = (js.get("municipality") or {}).get("name")336 mun_ok += m == mun337 if city and fold(city) != "":338 city_cmp += 1339 names = [fold(m or "")] + [fold((js.get(k) or {}).get("name", "")) for k in ("borough",)] + [fold(q["name"]) for q in js.get("neighbourhoods", [])]340 city_ok += fold(city) in names341 rep["osm_points"] = dict(n=len(sample), address_same_street_pct=round(100 * st_ok / len(sample), 1),342 street_field_same_street_pct=round(100 * street_field_ok / len(sample), 1),343 same_street_and_number_pct=round(100 * num_ok / len(sample), 1), by_confidence=conf,344 nearest_address_distance_median_m=pct(d, 0.5), nearest_address_distance_p90_m=pct(d, 0.9),345 municipality_matches_pipeline_pct=round(100 * mun_ok / len(sample), 1),346 osm_addr_city_compared=city_cmp,347 osm_addr_city_equals_our_municipality_or_borough_pct=round(100 * city_ok / max(1, city_cmp), 1))348 # 3. Appartenance aux limites : points de repère connus349 known = [350 ("Hôtel de ville de Montréal", -73.5540, 45.5088, dict(municipality="Montréal", borough="Ville-Marie", mrc="Montréal", region="Montréal")),351 ("Stade olympique", -73.5515, 45.5580, dict(municipality="Montréal", borough="Mercier - Hochelaga-Maisonneuve", region="Montréal")),352 ("Avenue du Mont-Royal / Saint-Denis", -73.5815, 45.5245, dict(municipality="Montréal", borough="Le Plateau-Mont-Royal")),353 ("Château Frontenac", -71.2050, 46.8119, dict(municipality="Québec", borough="La Cité-Limoilou", region="Capitale-Nationale")),354 ("Université Laval", -71.2747, 46.7817, dict(municipality="Québec", borough="Sainte-Foy - Sillery - Cap-Rouge")),355 ("Maison du citoyen, Gatineau", -75.7130, 45.4280, dict(municipality="Gatineau", region="Outaouais")),356 ("Hôtel de ville de Sherbrooke", -71.8929, 45.4010, dict(municipality="Sherbrooke", region="Estrie")),357 ("Chicoutimi, centre", -71.0650, 48.4280, dict(municipality="Saguenay", borough="Chicoutimi", region="Saguenay–Lac-Saint-Jean")),358 ("Jonquière, centre", -71.2480, 48.4160, dict(municipality="Saguenay", borough="Jonquière")),359 ("Trois-Rivières, centre", -72.5430, 46.3430, dict(municipality="Trois-Rivières", region="Mauricie")),360 ("Rimouski, centre", -68.5240, 48.4490, dict(municipality="Rimouski", mrc="Rimouski-Neigette", region="Bas-Saint-Laurent")),361 ("Vieux-Longueuil", -73.5180, 45.5370, dict(municipality="Longueuil", borough="Le Vieux-Longueuil", region="Montérégie")),362 ("Laval, centre", -73.7200, 45.5700, dict(municipality="Laval", region="Laval")),363 ("Lévis, traverse", -71.1830, 46.8090, dict(municipality="Lévis", region="Chaudière-Appalaches")),364 ("Westmount", -73.5990, 45.4850, dict(municipality="Westmount", mrc="Montréal")),365 ("Tadoussac", -69.7170, 48.1430, dict(municipality="Tadoussac", region="Côte-Nord")),366 ("Kuujjuaq", -68.4000, 58.1060, dict(municipality="Kuujjuaq", region="Nord-du-Québec")),367 ("Percé", -64.2130, 48.5230, dict(municipality="Percé", region="Gaspésie–Îles-de-la-Madeleine")),368 ("Val-d'Or", -77.7830, 48.0980, dict(municipality="Val-d'Or", region="Abitibi-Témiscamingue")),369 ("Îles-de-la-Madeleine (Cap-aux-Meules)", -61.8600, 47.3800, dict(municipality="Les Îles-de-la-Madeleine")),370 ("Ottawa (hors Québec)", -75.6972, 45.4215, dict(municipality=None, region=None)),371 ]372 checks = fails = 0373 failed = []374 for name, lon, lat, exp in known:375 code, js, _ = get("/v1/reverse", {"lon": lon, "lat": lat})376 js = js or {}377 for k, v in exp.items():378 got = (js.get(k) or {}).get("name")379 checks += 1380 if got != v:381 fails += 1382 failed.append(dict(point=name, level=k, expected=v, got=got))383 rep["boundary_containment"] = dict(points=len(known), checks=checks, failed=fails, failures=failed)384 # 4. Limites : le centre renvoyé par /v1/boundaries/{niveau}/{id} est contenu dans la limite (toutes les limites)385 ids = [r[0] for r in psql("SELECT id FROM geo.boundary ORDER BY md5(id) LIMIT 250")]386 okc = 0387 sizes = []388 for bid in ids:389 code, js, _ = get(f"/v1/boundaries/{bid}", {"zoom": 12})390 if code != 200:391 continue392 sizes.append(len(json.dumps(js)))393 cx, cy = js["properties"]["center"]394 c2, j2, _ = get("/v1/boundaries", {"lon": cx, "lat": cy})395 okc += any(b["id"] == bid for b in (j2 or {}).get("boundaries", []))396 rep["boundary_roundtrip"] = dict(n=len(ids), center_inside_pct=round(100 * okc / len(ids), 1),397 geojson_bytes_median_zoom12=pct(sizes, 0.5), geojson_bytes_max_zoom12=max(sizes))398 print(json.dumps(rep, ensure_ascii=False, indent=1))399400401def cmd_latency():402 sample = [l.rstrip("\n").split("\t") for l in open(SAMPLE, encoding="utf-8") if not l.startswith("#")]403 manual = json.load(open(os.path.join(HERE, "cases_manual.json"), encoding="utf-8"))404 pts = [(float(r[6]), float(r[7])) for r in sample]405 full = [f"{r[2]} {r[3]}, {r[4]}" for r in sample]406 # autocomplétion : préfixes croissants des requêtes (ce que tape un utilisateur)407 typed = []408 for q in full[:80]:409 for k in (3, 5, 8, 12, 16, 22):410 if k < len(q):411 typed.append(q[:k])412 work = {413 "search (adresse complète)": [("/v1/search", {"q": q}) for q in full],414 "search (autocomplétion, préfixes)": [("/v1/search", {"q": q}) for q in typed],415 "search (jeu manuel : fautes, lieux, POI)": [("/v1/search", {"q": c["q"]}) for c in manual] * 2,416 "search (avec near)": [("/v1/search", {"q": q[:10], "near": f"{p[0]},{p[1]}"}) for q, p in zip(full, pts)],417 "reverse": [("/v1/reverse", {"lon": p[0], "lat": p[1]}) for p in pts],418 "boundaries?lon&lat": [("/v1/boundaries", {"lon": p[0], "lat": p[1]}) for p in pts],419 "boundaries/{niveau}/{id}?zoom=12": [(f"/v1/boundaries/{b[0]}", {"zoom": 12}) for b in psql("SELECT id FROM geo.boundary ORDER BY md5(id) LIMIT 200")],420 "boundaries/search": [("/v1/boundaries/search", {"q": c["q"]}) for c in manual if c["type"] == "place"] * 3,421 "nearby (1 km, défaut)": [("/v1/nearby", {"lon": p[0], "lat": p[1]}) for p in pts],422 "nearby (5 km, transit)": [("/v1/nearby", {"lon": p[0], "lat": p[1], "radius": 5000, "kinds": "transit"}) for p in pts],423 "elevation": [("/v1/elevation", {"lon": p[0], "lat": p[1]}) for p in pts],424 "measure (GET)": [("/v1/measure", {"points": f"{p[0]},{p[1]};{p[0]+0.01},{p[1]};{p[0]+0.01},{p[1]+0.01}", "close": "true"}) for p in pts],425 }426 rep = {}427 for name, reqs in work.items():428 for path, params in reqs[:20]: # échauffement (cache PostgreSQL, plans)429 get(path, params)430 # 10 requêtes/s au plus pour rester sous la limite par IP (20/s, rafale 60)431 lat, codes = [], {}432 for path, params in reqs:433 code, _, dt = get(path, params)434 codes[code] = codes.get(code, 0) + 1435 lat.append(dt)436 rep[name] = dict(n=len(lat), p50_ms=pct(lat, 0.5), p95_ms=pct(lat, 0.95), p99_ms=pct(lat, 0.99), max_ms=round(max(lat), 2), status=codes)437 print(json.dumps(rep, ensure_ascii=False, indent=1))438439440def point_in_ring(ring, p):441 inside = False442 j = len(ring) - 1443 for i in range(len(ring)):444 xi, yi = ring[i]; xj, yj = ring[j]445 if (yi > p[1]) != (yj > p[1]) and p[0] < (xj - xi) * (p[1] - yi) / (yj - yi) + xi:446 inside = not inside447 j = i448 return inside449450451def heavy(path, params):452 if "127.0.0.1" not in BASE:453 time.sleep(0.36) # limite propre aux calculs de réseau : 3/s par IP (la boucle locale n'est pas limitée)454 return get(path, params)455456457def cmd_isochrone():458 """Bornes de vraisemblance et latences de /v1/isochrone et /v1/route (origines non mises en cache)."""459 rep = {"sanity": [], "latency": {}}460 ok_all = True461 def iso(lon, lat, profile, minutes, **kw):462 code, js, dt = heavy("/v1/isochrone", dict(lon=lon, lat=lat, profile=profile, minutes=minutes, **kw))463 return code, js, dt464 def check(name, cond, detail):465 nonlocal ok_all466 ok_all &= bool(cond)467 rep["sanity"].append(dict(check=name, ok=bool(cond), **detail))468 # 1. Marche 15 min : portée le long des rues ≈ 1,1 à 1,3 km (4,8 km/h = 1 200 m, + marge de 40 m)469 for name, lon, lat in [("Plateau-Mont-Royal", -73.5815, 45.5245), ("Limoilou, Québec", -71.2280, 46.8290),470 ("Vieux-Hull, Gatineau", -75.7170, 45.4290), ("Centre de Sherbrooke", -71.8929, 45.4010),471 ("Chicoutimi", -71.0650, 48.4280)]:472 code, js, dt = iso(lon, lat, "walking", 15)473 ring = js["features"][0]["geometry"]["coordinates"][0]474 o = js["origin"]475 far = max(dist_m(o["lon"], o["lat"], x, y) for x, y in ring)476 area = js["features"][0]["properties"]["area_km2"]477 check(f"marche 15 min, {name} : portée maximale entre 1,0 et 1,35 km", 1000 <= far <= 1350,478 dict(max_reach_m=round(far), area_km2=area, vertices=len(ring) - 1, ms=round(dt, 1)))479 check(f"marche 15 min, {name} : superficie entre 1,2 et 4,6 km² (disque de 1,2 km = 4,5 km²)", 1.2 <= area <= 4.6, dict(area_km2=area))480 # 2. Rivières et fleuve respectés481 code, js, _ = iso(-73.5815, 45.5245, "walking", 30)482 ring = js["features"][0]["geometry"]["coordinates"][0]483 check("marche 30 min depuis le Plateau : Longueuil (rive sud) hors du polygone", not point_in_ring(ring, (-73.5180, 45.5370)), {})484 check("marche 30 min depuis le Plateau : île Sainte-Hélène hors du polygone", not point_in_ring(ring, (-73.5340, 45.5170)), {})485 check("marche 30 min depuis le Plateau : parc La Fontaine dans le polygone", point_in_ring(ring, (-73.5695, 45.5265)), {})486 code, js, _ = iso(-73.5540, 45.5050, "walking", 20)487 ring = js["features"][0]["geometry"]["coordinates"][0]488 check("marche 20 min depuis le Vieux-Montréal : milieu du fleuve hors du polygone", not point_in_ring(ring, (-73.5400, 45.5060)), {})489 code, js, _ = iso(-71.2030, 46.8130, "walking", 30)490 ring = js["features"][0]["geometry"]["coordinates"][0]491 check("marche 30 min depuis le Vieux-Québec : Lévis hors du polygone (traversier exclu)", not point_in_ring(ring, (-71.1800, 46.8090)), {})492 # Par les ponts (≈ 25 km) : hors de portée en 30 min avec nos vitesses à vide prudentes, atteint en 45 min.493 code, js, _ = iso(-71.2030, 46.8130, "driving", "45,30")494 r45, r30 = (f["geometry"]["coordinates"][0] for f in js["features"])495 check("auto 45 min depuis le Vieux-Québec : Lévis dans le polygone (par les ponts)", point_in_ring(r45, (-71.1800, 46.8090)),496 dict(levis_in_30_min=point_in_ring(r30, (-71.1800, 46.8090))))497 code, js, _ = iso(-73.5815, 45.5245, "driving", "10,20,30", max_vertices=180)498 f = js["features"]499 check("auto 10/20/30 min : trois anneaux, du plus grand au plus petit, ≤ 180 sommets",500 len(f) == 3 and f[0]["properties"]["area_km2"] > f[1]["properties"]["area_km2"] > f[2]["properties"]["area_km2"]501 and all(x["properties"]["vertices"] <= 180 for x in f),502 dict(areas_km2=[x["properties"]["area_km2"] for x in f], vertices=[x["properties"]["vertices"] for x in f]))503 check("auto 30 min depuis le Plateau : Longueuil dans le polygone (ponts)", point_in_ring(f[0]["geometry"]["coordinates"][0], (-73.5180, 45.5370)), {})504 check("champ notice présent, en français", "sans la circulation" in js.get("notice", ""), {})505 # ordre de grandeur des modes : vélo 15 min ≈ (16 / 4,8)² fois la marche en superficie, au plus506 cw, jw, _ = iso(-73.6200, 45.5450, "walking", 15)507 cb, jb, _ = iso(-73.6200, 45.5450, "cycling", 15)508 aw, ab = jw["features"][0]["properties"]["area_km2"], jb["features"][0]["properties"]["area_km2"]509 check("vélo 15 min : entre 4 et 12 fois la superficie de la marche (Villeray)", 4 <= ab / aw <= 12, dict(walking_km2=aw, cycling_km2=ab))510 # 3. Trajets : distances connues511 for name, a, b, prof, lo, hi in [512 ("Montréal → Québec en auto (≈ 255 km par la 20 ou la 40)", (-73.5673, 45.5017), (-71.2080, 46.8139), "driving", 245e3, 270e3),513 ("Plateau → hôtel de ville de Montréal à pied (≈ 3 km)", (-73.5815, 45.5245), (-73.5540, 45.5088), "walking", 2700, 3400),514 ("Vieux-Hull → UQO à vélo (≈ 2 km)", (-75.7170, 45.4290), (-75.7386, 45.4227), "cycling", 1700, 3000),515 ("Chicoutimi → Jonquière en auto (15 à 20 km selon l'itinéraire)", (-71.0650, 48.4280), (-71.2480, 48.4160), "driving", 13e3, 21e3),516 ]:517 code, js, dt = heavy("/v1/route", {"from": f"{a[0]},{a[1]}", "to": f"{b[0]},{b[1]}", "profile": prof})518 d = (js or {}).get("distance_m", 0)519 check(f"trajet {name}", code == 200 and lo <= d <= hi, dict(distance_m=d, duration_min=(js or {}).get("duration_min"), ms=round(dt, 1)))520 code, js, _ = heavy("/v1/route", {"from": "-73.5815,45.5245", "to": "-61.8600,47.3800", "profile": "walking"})521 check("trajet à pied vers les Îles-de-la-Madeleine : refusé (pas de traversier)", code == 404, dict(status=code))522 if os.environ.get("ISO_SANITY_ONLY"):523 rep["ok"] = ok_all524 print(json.dumps(rep, ensure_ascii=False, indent=1))525 return526 # 4. Latences (origines distinctes : adresses de l'échantillon, donc sans effet de cache)527 sample = [l.rstrip("\n").split("\t") for l in open(SAMPLE, encoding="utf-8") if not l.startswith("#")]528 pts = [(float(r[6]), float(r[7])) for r in sample]529 urban = [p for r, p in zip(sample, pts) if not r[0].startswith("petites")]530 runs = {531 "isochrone walking 15 min": ("walking", "15", pts[:120]),532 "isochrone walking 30 min": ("walking", "30", pts[:120]),533 "isochrone walking 10,20,30 (≤ 180 sommets)": ("walking", "10,20,30", pts[:120]),534 "isochrone cycling 30 min": ("cycling", "30", pts[:120]),535 "isochrone driving 10 min": ("driving", "10", pts[:120]),536 "isochrone driving 30 min (toutes origines)": ("driving", "30", pts[:120]),537 "isochrone driving 30 min (origines urbaines)": ("driving", "30", urban[:120]),538 "isochrone driving 10,20,30 (≤ 180 sommets, origines urbaines)": ("driving", "10,20,30", urban[60:160]),539 "isochrone driving 60 min (origines urbaines)": ("driving", "60", urban[:60]),540 }541 k = 0542 for name, (prof, minutes, origins) in runs.items():543 lat, codes = [], {}544 for lon, la in origins:545 k += 1546 # décalage de quelques dizaines de mètres par série pour ne jamais retomber sur une entrée de cache547 code, js, dt = iso(round(lon + 0.0003 * (k % 7), 6), la, prof, minutes, max_vertices=180)548 codes[code] = codes.get(code, 0) + 1549 if code == 200:550 lat.append(dt)551 rep["latency"][name] = dict(n=len(lat), p50_ms=pct(lat, 0.5), p95_ms=pct(lat, 0.95), max_ms=round(max(lat), 1), status=codes)552 lat = []553 for lon, la in pts[:60]:554 code, js, dt = iso(lon, la, "walking", "15", max_vertices=180)555 lat.append(dt)556 rep["latency"]["isochrone walking 15 min (2e appel, en cache)"] = dict(n=len(lat), p50_ms=pct(lat, 0.5), p95_ms=pct(lat, 0.95), max_ms=round(max(lat), 1))557 for prof, pairs in [("walking", [(a, b) for a, b in zip(urban[:80], urban[1:81]) if dist_m(a[0], a[1], b[0], b[1]) < 15000]),558 ("driving", list(zip(pts[:100], pts[37:137])))]:559 lat, codes, dist = [], {}, []560 for a, b in pairs:561 code, js, dt = heavy("/v1/route", {"from": f"{a[0]},{a[1]}", "to": f"{b[0]},{b[1]}", "profile": prof})562 codes[code] = codes.get(code, 0) + 1563 if code == 200:564 lat.append(dt); dist.append(js["distance_m"])565 rep["latency"][f"route {prof}"] = dict(n=len(lat), p50_ms=pct(lat, 0.5), p95_ms=pct(lat, 0.95), max_ms=round(max(lat), 1) if lat else None,566 status=codes, distance_km_median=round(pct(dist, 0.5) / 1000, 1) if dist else None,567 distance_km_max=round(max(dist) / 1000, 1) if dist else None)568 rep["ok"] = ok_all569 print(json.dumps(rep, ensure_ascii=False, indent=1))570571572def cmd_sources():573 """Écart entre sources pour une même adresse (même municipalité, même rue normalisée, même numéro)."""574 q = """575 WITH k AS (576 SELECT a.mun_id, n.norm, a.num, a.suffix, a.src, (array_agg(a.pt))[1] AS pt577 FROM geo.addr_m a JOIN geo.name_norm n ON n.name = a.street GROUP BY 1, 2, 3, 4, 5),578 p AS (579 SELECT x.src AS a, y.src AS b, ST_Distance(x.pt::geography, y.pt::geography) AS d580 FROM k x JOIN k y USING (mun_id, norm, num, suffix) WHERE x.src < y.src AND {where})581 SELECT a, b, count(*), round(percentile_cont(0.5) WITHIN GROUP (ORDER BY d)::numeric, 1),582 round(percentile_cont(0.9) WITHIN GROUP (ORDER BY d)::numeric, 1),583 round(100.0 * count(*) FILTER (WHERE d <= 50) / count(*), 1)584 FROM p GROUP BY 1, 2 ORDER BY 3 DESC"""585 rows = psql(q.format(where="(x.src = 'nar' OR y.src = 'nar') AND x.src <> 'oda' AND y.src <> 'oda'"))586 rep = dict(pairs_with_nar=[dict(a=r[0], b=r[1], n=int(r[2]), median_m=float(r[3]), p90_m=float(r[4]), within_50m_pct=float(r[5])) for r in rows])587 # Adresses servies comparées à OSM (indépendant), toute la base588 rows = psql("""589 WITH o AS (SELECT o.mun_id, n.norm, o.num, o.suffix, o.pt FROM geo.osm_addr o590 JOIN LATERAL (SELECT norm FROM geo.name_norm nn WHERE nn.name = o.street) n ON true),591 j AS (SELECT a.src, ST_Distance(ST_Transform(a.pt, 4326)::geography, o.pt::geography) AS d592 FROM o JOIN geo.street s ON s.mun_id = o.mun_id AND s.norm = o.norm593 JOIN geo.address a ON a.street_id = s.id AND a.num = o.num AND a.suffix = o.suffix)594 SELECT src, count(*), round(percentile_cont(0.5) WITHIN GROUP (ORDER BY d)::numeric, 1),595 round(percentile_cont(0.9) WITHIN GROUP (ORDER BY d)::numeric, 1), round(100.0 * count(*) FILTER (WHERE d <= 50) / count(*), 1)596 FROM j GROUP BY ROLLUP (src) ORDER BY 2 DESC""")597 rep["served_vs_osm"] = [dict(source=r[0] or "toutes", n=int(r[1]), median_m=float(r[2]), p90_m=float(r[3]), within_50m_pct=float(r[4])) for r in rows]598 rows = psql("""SELECT (SELECT count(*) FROM geo.osm_addr),599 (SELECT count(*) FROM geo.osm_addr o WHERE EXISTS (SELECT 1 FROM geo.name_norm n JOIN geo.street s ON s.norm = n.norm AND s.mun_id = o.mun_id600 JOIN geo.address a ON a.street_id = s.id AND a.num = o.num WHERE n.name = o.street))""")601 rep["osm_addresses_total"], rep["osm_addresses_found_in_served"] = int(rows[0][0]), int(rows[0][1])602 rep["coverage_of_osm_pct"] = round(100 * rep["osm_addresses_found_in_served"] / rep["osm_addresses_total"], 1)603 print(json.dumps(rep, ensure_ascii=False, indent=1))604605606if __name__ == "__main__":607 import atexit608 atexit.register(lambda: THROTTLED[0] and sys.stderr.write(f"ATTENTION : {THROTTLED[0]} réponses 429 — résultats faussés\n"))609 {"gate": cmd_gate, "isochrone": cmd_isochrone, "testset": cmd_testset, "geocode": cmd_geocode, "reverse": cmd_reverse, "latency": cmd_latency, "sources": cmd_sources}[sys.argv[1]]()610