Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/inondation.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-2313# Last Modified : 2026-08-2314#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# inondation.py : risque d'inondation à l'adresse — BDZI (gouv. du Québec)91#92# Source : Base de données des zones à risque d'inondation (BDZI, MELCCFP),93# donnée ouverte officielle (Données Québec), GeoPackage EPSG:3857.94# `build()` éclate les multipolygones de la couche ZOI_s (pleine précision)95# en polygones simples indexés R*Tree dans data/inondation.db (+ la couche96# Carto_ZI_S : périmètres couverts par une cartographie — sans elle,97# « aucune zone » ne veut rien dire), puis `lookup(lat, lng)` fait un test98# point-dans-polygone exact (shapely) sur les seuls candidats de la boîte.99#100# Types BDZI : « Zone de grand courant » (récurrence 0-20 ans, risque101# élevé), « Zone de faible courant » (20-100 ans), « Zone de crue102# 0-100 ans », variantes « - Pont » et « Autre zone inondable ».103#104# Usage : python run.py inondation-build (une fois, GPKG requis)105# lookup(lat, lng) -> dict (fiche, /api/inondation)106# -----------------------------------------------------------------------------107from __future__ import annotations108109import math110import sqlite3111from pathlib import Path112113DATA = Path(__file__).resolve().parent.parent / "data"114DB_PATH = DATA / "inondation.db"115GPKG = DATA / "BDZI_GPK.gpkg"116117# rayon de tolérance : géocodage + emprise du bâtiment118NEAR_M = 30.0119# au-delà, on signale quand même une zone toute proche (information utile)120WARN_M = 100.0121122_SEVERITE = {123 "Zone de grand courant": ("eleve", "récurrence 0-20 ans"),124 "Zone de grand courant - Pont": ("eleve", "récurrence 0-20 ans"),125 "Zone de faible courant": ("modere", "récurrence 20-100 ans"),126 "Zone de faible courant - Pont": ("modere", "récurrence 20-100 ans"),127 "Zone de crue 0-100 ans": ("present", "récurrence 0-100 ans"),128 "Zone de crue 0-100 ans - Pont": ("present", "récurrence 0-100 ans"),129 "Autre zone inondable": ("present", ""),130}131132_R = 20037508.342789244133134135def _to_3857(lat: float, lng: float) -> tuple[float, float]:136 x = lng * _R / 180.0137 y = math.log(math.tan((90 + lat) * math.pi / 360.0)) * _R / math.pi138 return x, y139140141def _gpkg_wkb(blob: bytes) -> bytes:142 """Retire l'en-tête GeoPackage (magic GP + drapeaux + enveloppe)."""143 if blob[:2] != b"GP":144 return blob145 flags = blob[3]146 env = (flags >> 1) & 0x07147 env_len = {0: 0, 1: 32, 2: 48, 3: 48, 4: 64}.get(env, 0)148 return blob[8 + env_len:]149150151def build(gpkg: Path = GPKG) -> None:152 """Construit data/inondation.db à partir du GeoPackage BDZI."""153 from shapely import wkb as _swkb154155 src = sqlite3.connect(gpkg)156 con = sqlite3.connect(DB_PATH)157 con.executescript("""158 DROP TABLE IF EXISTS zi; DROP TABLE IF EXISTS zi_rtree;159 DROP TABLE IF EXISTS couverture; DROP TABLE IF EXISTS couv_rtree;160 CREATE TABLE zi (id INTEGER PRIMARY KEY, description TEXT,161 rapport TEXT, date_rapport TEXT, wkb BLOB);162 CREATE VIRTUAL TABLE zi_rtree USING rtree(id, xmin, xmax, ymin, ymax);163 CREATE TABLE couverture (id INTEGER PRIMARY KEY, nom TEXT, wkb BLOB);164 CREATE VIRTUAL TABLE couv_rtree USING rtree(id, xmin, xmax, ymin, ymax);165 """)166 nid = 0167 for desc, rapport, date_r, blob in src.execute(168 "SELECT Description, Nm_rapport, Date_rapport, Shape FROM ZOI_s"):169 geom = _swkb.loads(_gpkg_wkb(blob))170 polys = geom.geoms if geom.geom_type == "MultiPolygon" else [geom]171 for poly in polys:172 if poly.is_empty:173 continue174 nid += 1175 con.execute("INSERT INTO zi VALUES (?,?,?,?,?)",176 (nid, desc, rapport, date_r, poly.wkb))177 x0, y0, x1, y1 = poly.bounds178 con.execute("INSERT INTO zi_rtree VALUES (?,?,?,?,?)",179 (nid, x0, x1, y0, y1))180 if nid % 500 < len(polys):181 print(f"[inondation] {nid} polygones…", flush=True)182 cid = 0183 for nom, blob in src.execute("SELECT Nom_Carte, Shape FROM Carto_ZI_S"):184 geom = _swkb.loads(_gpkg_wkb(blob))185 polys = geom.geoms if geom.geom_type == "MultiPolygon" else [geom]186 for poly in polys:187 if poly.is_empty:188 continue189 cid += 1190 con.execute("INSERT INTO couverture VALUES (?,?,?)",191 (cid, nom, poly.wkb))192 x0, y0, x1, y1 = poly.bounds193 con.execute("INSERT INTO couv_rtree VALUES (?,?,?,?,?)",194 (cid, x0, x1, y0, y1))195 con.commit()196 con.execute("VACUUM")197 print(f"[inondation] {nid} polygones de zones, {cid} périmètres "198 f"cartographiés -> {DB_PATH}")199 con.close()200 src.close()201202203def lookup(lat: float, lng: float) -> dict | None:204 """Risque d'inondation BDZI au point (WGS84). None si base absente."""205 if not DB_PATH.exists():206 return None207 from shapely import wkb as _swkb208 from shapely.geometry import Point209210 x, y = _to_3857(lat, lng)211 # les distances 3857 sont dilatées d'un facteur 1/cos(lat)212 scale = 1.0 / max(0.2, math.cos(math.radians(lat)))213 pad = WARN_M * scale214 pt = Point(x, y)215216 con = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)217 zones: list[dict] = []218 for zid, desc, rapport, date_r, blob in con.execute(219 "SELECT z.id, z.description, z.rapport, z.date_rapport, z.wkb "220 "FROM zi z JOIN zi_rtree r ON z.id = r.id "221 "WHERE r.xmax >= ? AND r.xmin <= ? AND r.ymax >= ? AND r.ymin <= ?",222 (x - pad, x + pad, y - pad, y + pad)):223 poly = _swkb.loads(blob)224 d = poly.distance(pt) / scale # ~mètres réels225 if poly.contains(pt):226 d = 0.0227 elif d > WARN_M:228 continue229 sev, rec = _SEVERITE.get(desc, ("present", ""))230 zones.append({"type": desc, "severite": sev, "recurrence": rec,231 "distance_m": round(d),232 "date_rapport": (date_r or "")[:10] or None})233 couvert = False234 for (blob,) in con.execute(235 "SELECT c.wkb FROM couverture c JOIN couv_rtree r ON c.id = r.id "236 "WHERE r.xmax >= ? AND r.xmin <= ? AND r.ymax >= ? AND r.ymin <= ?",237 (x, x, y, y)):238 if _swkb.loads(blob).contains(pt):239 couvert = True240 break241 con.close()242243 zones.sort(key=lambda z: (z["distance_m"],244 {"eleve": 0, "modere": 1, "present": 2}245 .get(z["severite"], 3)))246 dans = [z for z in zones if z["distance_m"] <= NEAR_M]247 if dans:248 statut = "en_zone"249 pire = dans[0]["severite"]250 elif zones:251 statut, pire = "a_proximite", zones[0]["severite"]252 elif couvert:253 statut, pire = "hors_zone", None254 else:255 statut, pire = "non_cartographie", None256 return {"statut": statut, "severite": pire, "couvert": couvert,257 "zones": zones[:5]}258