Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/air.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# air.py : qualité de l'air à l'adresse — RSQAQ (MELCCFP, Données Québec)91#92# Sources ouvertes officielles du Réseau de surveillance de la qualité de93# l'air du Québec :94# · stations (rsqaq-stations) : coordonnées, ouverture/fermeture ;95# · données horaires continues (PM2.5, NO2, O3, SO2, CO) 2024-2025 ;96# · données séquentielles (Concentration PST / PM10 + métaux) 2007-2026 —97# les particules en suspension totales demandées (étiquette PST).98# `refresh()` télécharge les CSV et réduit tout en moyennes annuelles par99# station dans data/air.db (minuscule) ; `lookup(lat, lng)` remonte la100# station la plus proche (≤ 60 km) avec ses mesures les plus récentes,101# comparées aux repères annuels de l'OMS (2021).102# -----------------------------------------------------------------------------103from __future__ import annotations104105import csv106import io107import math108import sqlite3109import time110import urllib.request111from pathlib import Path112113DB_PATH = Path(__file__).resolve().parent.parent / "data" / "air.db"114UA = "LouKaBot/1.0 (+https://www.lou-ka.com; contact@spboucher.ai)"115116URL_STATIONS = ("https://www.donneesquebec.ca/recherche/dataset/"117 "8656ad05-c174-41c5-9ed7-8c69d308beb9/resource/"118 "cebea532-a9e0-4a39-8c2d-54f33d937c73/download/"119 "rsqaq_stations_de_la_qualite_de_lair.csv")120URL_HORAIRE = {121 2025: ("https://www.donneesquebec.ca/recherche/dataset/"122 "a80757bd-d442-4d3d-9269-11628330b727/resource/"123 "370a6be4-1530-4c2b-92f3-0a308224f284/download/"124 "rsqaq_continues_horaires_2025.csv"),125 2024: ("https://www.donneesquebec.ca/recherche/dataset/"126 "a80757bd-d442-4d3d-9269-11628330b727/resource/"127 "135146b7-fd4a-4564-b10b-b1ae94257889/download/"128 "rsqaq_continues_horaires_2024.csv"),129}130URL_SEQ = ("https://www.donneesquebec.ca/recherche/dataset/"131 "bff56fad-22c3-450b-aafa-4ccdad6c91f2/resource/"132 "b83cac3b-6199-4cfd-a903-cdec2369630c/download/"133 "rsqaq_sequentielles_2007-2026.csv")134135# colonnes horaires retenues -> polluant canonique136_HOURLY = {"PM2.5-T640": "PM2.5", "PM2.5-BAM": "PM2.5", "NO2": "NO2",137 "O3": "O3", "SO2": "SO2", "CO": "CO"}138# contaminants séquentiels retenus (concentrations de particules)139_SEQ = {"Concentration PST": "PST", "Concentration PM10": "PM10"}140141# repères ANNUELS (moyenne) : OMS 2021 pour PM2.5/PM10/NO2 ; PST : norme142# annuelle du Règlement sur l'assainissement de l'atmosphère (Québec)143REFS = {"PM2.5": ("OMS 2021", 5.0), "PM10": ("OMS 2021", 15.0),144 "NO2": ("OMS 2021", 10.0), "PST": ("RAA Québec", 60.0)}145UNITES = {"PM2.5": "µg/m³", "PM10": "µg/m³", "PST": "µg/m³",146 "NO2": "ppb", "O3": "ppb", "SO2": "ppb", "CO": "ppm"}147148149def _dl(url: str) -> io.StringIO:150 req = urllib.request.Request(url, headers={"User-Agent": UA})151 with urllib.request.urlopen(req, timeout=300) as r:152 return io.StringIO(r.read().decode("utf-8-sig"))153154155def refresh() -> None:156 stations: dict[str, dict] = {}157 for row in csv.DictReader(_dl(URL_STATIONS)):158 sid = row["ID_STATION"].strip().lstrip("0")159 stations[sid] = {"nom": row["NOM_STATION"], "ville": row["MUNICIPALITE"],160 "lat": float(row["LATITUDE"] or 0),161 "lng": float(row["LONGITUDE"] or 0)}162 print(f"[air] {len(stations)} stations")163164 # (station, annee, polluant) -> [somme, n]165 acc: dict[tuple, list[float]] = {}166167 def _sid(label: str) -> str:168 return label.split(" - ")[0].strip().lstrip("0")169170 for annee, url in URL_HORAIRE.items():171 n = 0172 rd = csv.DictReader(_dl(url))173 cols = [c for c in (rd.fieldnames or []) if c in _HOURLY]174 for row in rd:175 sid = _sid(row["Station"])176 for c in cols:177 v = row.get(c)178 if not v:179 continue180 try:181 x = float(v)182 except ValueError:183 continue184 if x < 0:185 continue186 a = acc.setdefault((sid, annee, _HOURLY[c]), [0.0, 0])187 a[0] += x188 a[1] += 1189 n += 1190 print(f"[air] horaires {annee} : {n} mesures")191192 n = 0193 for row in csv.DictReader(_dl(URL_SEQ)):194 pol = _SEQ.get(row["Contaminant"])195 if not pol:196 continue197 annee = int(row["Date"][:4])198 if annee < 2022:199 continue200 v = row.get("Resultat")201 if not v:202 ld = row.get("LD")203 if not ld:204 continue205 try:206 x = float(ld) / 2.0 # convention < LD -> LD/2207 except ValueError:208 continue209 else:210 try:211 x = float(v)212 except ValueError:213 continue214 a = acc.setdefault((_sid(row["Station"]), annee, pol), [0.0, 0])215 a[0] += x216 a[1] += 1217 n += 1218 print(f"[air] séquentielles PST/PM10 : {n} mesures (≥ 2022)")219220 con = sqlite3.connect(DB_PATH)221 con.executescript("""222 DROP TABLE IF EXISTS air_stats;223 CREATE TABLE air_stats (station TEXT, nom TEXT, ville TEXT,224 lat REAL, lng REAL, annee INTEGER, polluant TEXT,225 moyenne REAL, n INTEGER);226 CREATE INDEX idx_air_latlng ON air_stats (lat, lng);227 """)228 now = time.strftime("%Y-%m-%d")229 rows = []230 for (sid, annee, pol), (somme, cnt) in acc.items():231 st = stations.get(sid)232 # minimum de couverture : 30 jours d'heures ou 15 échantillons233 if not st or cnt < (720 if pol in ("PM2.5", "NO2", "O3", "SO2", "CO")234 else 15):235 continue236 rows.append((sid, st["nom"], st["ville"], st["lat"], st["lng"],237 annee, pol, round(somme / cnt, 2), cnt))238 with con:239 con.executemany("INSERT INTO air_stats VALUES (?,?,?,?,?,?,?,?,?)",240 rows)241 con.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v)")242 con.execute("INSERT OR REPLACE INTO meta VALUES ('maj', ?)", (now,))243 print(f"[air] {len(rows)} agrégats station-année-polluant -> {DB_PATH}")244 con.close()245246247def _dist_km(lat1, lng1, lat2, lng2) -> float:248 dlat = math.radians(lat2 - lat1)249 dlng = math.radians(lng2 - lng1)250 a = (math.sin(dlat / 2) ** 2 + math.cos(math.radians(lat1))251 * math.cos(math.radians(lat2)) * math.sin(dlng / 2) ** 2)252 return 6371 * 2 * math.asin(math.sqrt(a))253254255def lookup(lat: float, lng: float, max_km: float = 60.0) -> dict | None:256 """Mesures de la station RSQAQ la plus proche (année la plus récente)."""257 if not DB_PATH.exists():258 return None259 con = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)260 con.row_factory = sqlite3.Row261 d = max_km / 111.0262 rows = con.execute(263 "SELECT * FROM air_stats WHERE lat BETWEEN ? AND ? AND lng BETWEEN "264 "? AND ?", (lat - d, lat + d, lng - d / max(0.2, math.cos(265 math.radians(lat))), lng + d / max(0.2, math.cos(266 math.radians(lat))))).fetchall()267 con.close()268 if not rows:269 return {"station": None}270 # station la plus proche disposant de données récentes271 best: dict[str, dict] = {}272 for r in rows:273 km = _dist_km(lat, lng, r["lat"], r["lng"])274 if km > max_km:275 continue276 b = best.setdefault(r["station"], {"km": km, "rows": [], "r": r})277 b["rows"].append(r)278 if not best:279 return {"station": None}280 sid, b = min(best.items(), key=lambda kv: kv[1]["km"])281 # par polluant : l'année la plus récente282 mesures: dict[str, dict] = {}283 for r in sorted(b["rows"], key=lambda r: -r["annee"]):284 if r["polluant"] in mesures:285 continue286 ref = REFS.get(r["polluant"])287 mesures[r["polluant"]] = {288 "moyenne": r["moyenne"], "annee": r["annee"], "n": r["n"],289 "unite": UNITES.get(r["polluant"], ""),290 "ref": ref[1] if ref else None,291 "ref_nom": ref[0] if ref else None}292 st = b["r"]293 return {"station": st["nom"], "ville": st["ville"],294 "distance_km": round(b["km"], 1), "mesures": mesures}295