SPB Git

Repository Public

build_recensement.py 22.9 KB 553 lines python

1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# =============================================================================4#                  SP BOUCHER | SOFTWARE & RESEARCH5#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6# =============================================================================7#8# PROJECT METADATA9# -----------------------------------------------------------------------------10# Project          : Lou·Ka11# File             : scripts/build_recensement.py12# Description      : build_recensement.py — Construit13#                    data/staging-recensement.db pour Lou-Ka.14# Module           : scripts15# Repository       : https://git.spboucher.ai/lou-ka16# Created          : 2026-08-0817# Last Modified    : 2026-08-0818#19# =============================================================================20# AUTHOR & PROFESSIONAL AFFILIATION21# =============================================================================22#23# Author           : Simon-Pierre Boucher24# Position         : Professor of Finance25# Institution      : Université du Québec en Outaouais (UQO)26# Department       : Département des sciences administratives27# Organization     : SP Boucher28#29# Website          : https://spboucher.ai30# Git              : https://git.spboucher.ai31#32# =============================================================================33# OFFICIAL CONTACT DIRECTORY34# =============================================================================35#36# General          : info@spboucher.ai37# Professional     : contact@spboucher.ai38# Direct           : simon@spboucher.ai39# Research         : research@spboucher.ai40# Development      : dev@spboucher.ai41# Support          : support@spboucher.ai42# Security/Admin   : admin@spboucher.ai43# Notifications    : notifications@spboucher.ai44#45# Preferred Contact: contact@spboucher.ai46#47# =============================================================================48# COPYRIGHT & INTELLECTUAL PROPERTY49# =============================================================================50#51# Copyright (c) 202652# Simon-Pierre Boucher53#54# All rights reserved where applicable.55#56# This file is governed by the applicable project license,57# copyright notices, institutional agreements and relevant law.58#59# Unless expressly authorized by the applicable license or60# rights holder, copying, redistribution, sublicensing,61# publication and commercial exploitation are not permitted.62#63# Existing third-party rights and notices remain unaffected.64#65# =============================================================================66# CONFIDENTIALITY & SECURITY67# =============================================================================68#69# Classification   : Public70# Distribution     : Public repository; use is governed by the project license71# Security Contact : admin@spboucher.ai72#73# Access to this source does not independently grant permission74# to redistribute or disclose confidential materials.75#76# Do not embed credentials, private keys, access tokens,77# certificates or confidential personal information.78#79# =============================================================================80# LICENSE & MAINTENANCE81# =============================================================================82#83# License          : None specified (no license file in this repository)84# Maintainer       : Simon-Pierre Boucher85# Technical Contact: dev@spboucher.ai86#87# =============================================================================88# END OF SP BOUCHER SOURCE HEADER89# =============================================================================9091"""92build_recensement.py — Construit data/staging-recensement.db pour Lou-Ka.9394Tables produites (schéma contractuel) :95  1. da_poly(dauid, lat_min, lat_max, lng_min, lng_max, poly)96     - polygones des aires de diffusion (AD) 2021 du Québec, en WGS84,97       restreints à la zone de couverture des annonces98       (lat 44.9–47.7 / lng -74.6–-70.2 : Québec, Lévis, Grand Montréal + périphérie).99  2. da_stats(dauid, population, densite, age_median, revenu_median,100              pct_locataires, loyer_moyen, pct_francais, pct_univ)101     - statistiques du Recensement de 2021 (Profil du recensement).102  3. meta(cle, valeur) — provenance et attribution.103104Sources (Statistique Canada, licence ouverte) :105  - Polygones : Fichiers des limites cartographiques 2021 (92-160-X / index 92-169-X),106    shapefile « aires de diffusion », projection Lambert conforme de107    Statistique Canada (EPSG:3347) :108    https://www12.statcan.gc.ca/census-recensement/2021/geo/sip-pis/boundary-limites/files-fichiers/lda_000b21a_e.zip109    (page index : https://www12.statcan.gc.ca/census-recensement/2021/geo/sip-pis/boundary-limites/index2021-fra.cfm)110  - Statistiques : Profil du recensement 2021, 98-401-X2021006, fichier111    « Québec » au niveau des aires de diffusion (CSV, ~2 Go décompressé) :112    https://www12.statcan.gc.ca/census-recensement/2021/dp-pd/prof/details/download-telecharger/comp/GetFile.cfm?Lang=F&FILETYPE=CSV&GEONO=006_Quebec113    (page : https://www12.statcan.gc.ca/census-recensement/2021/dp-pd/prof/details/download-telecharger.cfm?Lang=F)114115Usage :116  .venv/bin/python scripts/build_recensement.py \117      --shp /tmp/louka-recensement/lda/lda_000b21a_e.shp \118      --csv /tmp/louka-recensement/profil/<fichier>.csv \119      --db  data/staging-recensement.db \120      [--etape poly|stats|valider|tout]121122Le CSV du profil est STREAMÉ (jamais chargé en mémoire). Les valeurs123supprimées par StatCan (confidentialité : symboles x, F, ..., etc.)124restent NULL — rien n'est inventé.125"""126127import argparse128import csv129import datetime130import json131import os132import sqlite3133import sys134135import pyproj136import shapefile  # pyshp137138# ---------------------------------------------------------------------------139# Zone de couverture (bbox des annonces Lou-Ka, WGS84)140# 2026-08-08 : élargie à toute la province habitée (expansion provinciale —141# Gatineau, Estrie, Mauricie, Saguenay, Abitibi, Bas-Saint-Laurent, Côte-Nord,142# Gaspésie). Toutes les AD 24* passent le filtre.143# ---------------------------------------------------------------------------144LAT_MIN, LAT_MAX = 44.5, 63.0145LNG_MIN, LNG_MAX = -80.0, -56.0146147# Projection source du shapefile StatCan : Lambert conforme conique148# « NAD83_Statistics_Canada_Lambert » = EPSG:3347. Cible : WGS84 (EPSG:4326).149TRANSFORMER = pyproj.Transformer.from_crs("EPSG:3347", "EPSG:4326", always_xy=True)150151# ---------------------------------------------------------------------------152# Variables retenues dans le Profil du recensement (98-401-X2021006, français).153# Chaque entrée : nom exact de la caractéristique (colonne NOM_CARACTÉRISTIQUE,154# sans l'indentation) -> clé interne. Les ID (ID_CARACTÉRISTIQUE) sont155# découverts dynamiquement en scannant la liste des caractéristiques de la156# première géographie du fichier, ce qui rend le script robuste aux157# renumérotations éventuelles.158# ---------------------------------------------------------------------------159CARACTERISTIQUES = {160    # population et densité (ID attendus : 1 et 6)161    "Population, 2021": "population",162    "Densité de la population au kilomètre carré": "densite",163    # âge médian de la population (ID 40)164    "Âge médian de la population": "age_median",165    # revenu total médian des ménages en 2020 (ID 243)166    "Revenu total médian des ménages en 2020 ($)": "revenu_median",167    # mode d'occupation : total des ménages (ID 1414) ; « Locataire »168    # (ID 1416) est résolu par position (voir ENFANTS)169    "Total - Ménages privés selon le mode d'occupation - Données-échantillon (25 %)": "menages_total",170    # loyer mensuel moyen des logements loués = frais de logement mensuels171    # moyens des ménages locataires (ID 1495)172    "Frais de logement mensuels moyens pour les logements occupés par un ménage locataire ($)": "loyer_moyen",173    # langue parlée le plus souvent à la maison : total (ID 735) ; le174    # « Français » (ID 739) est résolu par position (voir ENFANTS)175    "Total - Langue parlée le plus souvent à la maison pour la population totale à l'exclusion des résidents d'un établissement institutionnel - Données intégrales (100 %)": "langue_total",176    # scolarité 25-64 ans : total (ID 2014) ; « Baccalauréat ou grade177    # supérieur » (ID 2024) est résolu par position (voir ENFANTS)178    "Total - Plus haut certificat, diplôme ou grade pour la population âgée de 25 à 64 ans dans les ménages privés - Données-échantillon (25 %)": "scol_total",179}180181# Sous-caractéristiques ambiguës (leur nom apparaît plusieurs fois dans le182# profil, p. ex. « Français » dans chaque section linguistique) : on prend la183# PREMIÈRE occurrence qui SUIT la ligne « Total » de leur section.184#   clé du total parent -> (nom normalisé de l'enfant, clé interne de l'enfant)185ENFANTS = {186    "menages_total": ("Locataire", "locataires"),               # ID 1416187    "langue_total": ("Français", "francais"),                   # ID 739188    "scol_total": ("Baccalauréat ou grade supérieur", "pct_univ_taux"),  # ID 2024189}190191192def _normaliser_nom(nom):193    """Nettoie un NOM_CARACTÉRISTIQUE : enlève l'indentation et uniformise194    les apostrophes (le fichier mélange 0x27 et 0x92/'’')."""195    return nom.strip().replace("\x92", "'").replace("’", "'")196197198# clés normalisées une fois pour toutes199CARACTERISTIQUES = {_normaliser_nom(k): v for k, v in CARACTERISTIQUES.items()}200201202def log(msg):203    print(msg, flush=True)204205206# ===========================================================================207# ÉTAPE 1 — POLYGONES (da_poly)208# ===========================================================================209def construire_poly(chemin_shp, conn):210    """Lit le shapefile des AD, filtre Québec (PRUID 24) + bbox de couverture,211    reprojette EPSG:3347 -> WGS84 et écrit da_poly."""212    conn.execute("DROP TABLE IF EXISTS da_poly")213    conn.execute(214        """CREATE TABLE da_poly(215               dauid   TEXT PRIMARY KEY,216               lat_min REAL, lat_max REAL,217               lng_min REAL, lng_max REAL,218               poly    TEXT)"""219    )220221    lecteur = shapefile.Reader(chemin_shp)222    champs = [f[0] for f in lecteur.fields[1:]]223    i_dauid = champs.index("DAUID")224    i_pruid = champs.index("PRUID")225226    n_qc = n_gardees = 0227    lot = []228    for sr in lecteur.iterShapeRecords():229        rec = sr.record230        if rec[i_pruid] != "24":231            continue232        n_qc += 1233        shp = sr.shape234235        # Pré-filtre grossier : on reprojette les 4 coins de la bbox projetée ;236        # si même la bbox élargie ne touche pas la zone, on saute la géométrie237        # complète (économise ~40 % du temps de reprojection).238        x0, y0, x1, y1 = shp.bbox239        cx, cy = TRANSFORMER.transform([x0, x1, x0, x1], [y0, y0, y1, y1])240        marge = 0.05  # la bbox projetée n'est pas alignée sur les méridiens241        if (max(cy) + marge < LAT_MIN or min(cy) - marge > LAT_MAX242                or max(cx) + marge < LNG_MIN or min(cx) - marge > LNG_MAX):243            continue244245        # Reprojection complète de la géométrie (tous les anneaux).246        pts = shp.points247        xs = [p[0] for p in pts]248        ys = [p[1] for p in pts]249        lngs, lats = TRANSFORMER.transform(xs, ys)250251        lat_min, lat_max = min(lats), max(lats)252        lng_min, lng_max = min(lngs), max(lngs)253        # Filtre exact : intersection de la bbox WGS84 avec la zone visée.254        if (lat_max < LAT_MIN or lat_min > LAT_MAX255                or lng_max < LNG_MIN or lng_min > LNG_MAX):256            continue257258        # Reconstitution des anneaux (parts) : le 1er anneau d'un polygone259        # shapefile est l'anneau extérieur ; les trous / autres polygones260        # suivent. Coordonnées [lng, lat], arrondies à 6 décimales (~10 cm).261        bornes = list(shp.parts) + [len(pts)]262        anneaux = []263        for a in range(len(shp.parts)):264            d, f = bornes[a], bornes[a + 1]265            anneaux.append(266                [[round(lngs[i], 6), round(lats[i], 6)] for i in range(d, f)]267            )268269        lot.append((270            rec[i_dauid],271            round(lat_min, 6), round(lat_max, 6),272            round(lng_min, 6), round(lng_max, 6),273            json.dumps(anneaux, separators=(",", ":")),274        ))275        n_gardees += 1276        if len(lot) >= 500:277            conn.executemany("INSERT INTO da_poly VALUES (?,?,?,?,?,?)", lot)278            lot = []279280    if lot:281        conn.executemany("INSERT INTO da_poly VALUES (?,?,?,?,?,?)", lot)282    conn.commit()283    log(f"da_poly : {n_gardees} AD retenues sur {n_qc} AD au Québec")284    return n_gardees285286287# ===========================================================================288# ÉTAPE 2 — STATISTIQUES (da_stats)289# ===========================================================================290def _detecter_colonnes(entete):291    """Repère les colonnes utiles du CSV (le fichier FR utilise des noms292    français ; on tolère les variantes EN par prudence)."""293    def trouver(*candidats):294        for c in candidats:295            for i, nom in enumerate(entete):296                if nom.strip().lstrip("").upper() == c.upper():297                    return i298        raise KeyError(f"colonne introuvable : {candidats} dans {entete}")299300    return {301        "geo_level": trouver("NIVEAU_GÉO", "GEO_LEVEL"),302        "alt_geo": trouver("CODE_GÉO_ALT", "ALT_GEO_CODE"),303        "car_id": trouver("ID_CARACTÉRISTIQUE", "CHARACTERISTIC_ID"),304        "car_nom": trouver("NOM_CARACTÉRISTIQUE", "CHARACTERISTIC_NAME"),305        "total": trouver("C1_CHIFFRE_TOTAL", "C1_COUNT_TOTAL"),306    }307308309def decouvrir_ids(chemin_csv):310    """1re passe (rapide) : lit les caractéristiques de la première géographie311    du fichier pour associer chaque variable à son ID_CARACTÉRISTIQUE."""312    ids = {}313    en_attente = []  # [(nom enfant recherché, clé interne)]314    with open(chemin_csv, newline="", encoding="latin-1") as f:315        lecteur = csv.reader(f)316        entete = next(lecteur)317        col = _detecter_colonnes(entete)318        premier_geo = None319        for ligne in lecteur:320            geo = ligne[col["alt_geo"]]321            if premier_geo is None:322                premier_geo = geo323            elif geo != premier_geo:324                break  # une géographie = la liste complète des caractéristiques325            cid = int(ligne[col["car_id"]])326            nom = _normaliser_nom(ligne[col["car_nom"]])327            # sous-caractéristique attendue après son « Total » parent ?328            for i, (nom_enfant, cle_enfant) in enumerate(en_attente):329                if nom == nom_enfant and cle_enfant not in ids:330                    ids[cle_enfant] = cid331                    en_attente.pop(i)332                    break333            cle = CARACTERISTIQUES.get(nom)334            if cle and cle not in ids:335                ids[cle] = cid336                if cle in ENFANTS:337                    en_attente.append(ENFANTS[cle])338    return ids, col339340341def _nombre(txt):342    """Convertit une cellule du profil en float, ou None si valeur supprimée343    (x, F, .., ..., vide) — on n'invente rien."""344    txt = (txt or "").strip().replace(",", ".")345    if not txt or txt in {"x", "F", "..", "...", "r", "t"}:346        return None347    try:348        return float(txt)349    except ValueError:350        return None351352353def construire_stats(chemin_csv, conn):354    """2e passe : streame tout le CSV, ne garde que les lignes des AD retenues355    dans da_poly et les 12 caractéristiques utiles, puis calcule les 8356    variables finales."""357    dauids = {r[0] for r in conn.execute("SELECT dauid FROM da_poly")}358    if not dauids:359        raise SystemExit("da_poly est vide — lancer l'étape poly d'abord")360361    ids, col = decouvrir_ids(chemin_csv)362    attendues = set(CARACTERISTIQUES.values()) | {c for _, c in ENFANTS.values()}363    manquants = attendues - set(ids)364    if manquants:365        raise SystemExit(f"IDs de caractéristiques introuvables : {manquants}")366    log(f"IDs des caractéristiques : {ids}")367    ids_voulus = {v: k for k, v in ids.items()}  # cid -> clé interne368369    # accumulation : dauid -> {clé interne: valeur brute}370    donnees = {}371    niveaux_ad = {"Aire de diffusion", "Dissemination area"}372    n_lignes = 0373    with open(chemin_csv, newline="", encoding="latin-1") as f:374        lecteur = csv.reader(f)375        next(lecteur)  # entête376        i_niv, i_geo = col["geo_level"], col["alt_geo"]377        i_cid, i_tot = col["car_id"], col["total"]378        for ligne in lecteur:379            n_lignes += 1380            if ligne[i_niv] not in niveaux_ad:381                continue382            geo = ligne[i_geo]383            if geo not in dauids:384                continue385            cle = ids_voulus.get(int(ligne[i_cid]))386            if cle is None:387                continue388            donnees.setdefault(geo, {})[cle] = _nombre(ligne[i_tot])389    log(f"CSV : {n_lignes} lignes lues, {len(donnees)} AD avec données")390391    conn.execute("DROP TABLE IF EXISTS da_stats")392    conn.execute(393        """CREATE TABLE da_stats(394               dauid          TEXT PRIMARY KEY,395               population     INTEGER,396               densite        REAL,397               age_median     REAL,398               revenu_median  REAL,399               pct_locataires REAL,400               loyer_moyen    REAL,401               pct_francais   REAL,402               pct_univ       REAL)"""403    )404405    def pct(part, total):406        """Pourcentage part/total, NULL si l'un des deux est supprimé/nul."""407        if part is None or not total:408            return None409        return round(100.0 * part / total, 1)410411    lot = []412    for dauid, d in donnees.items():413        lot.append((414            dauid,415            int(d["population"]) if d.get("population") is not None else None,416            d.get("densite"),417            d.get("age_median"),418            d.get("revenu_median"),419            pct(d.get("locataires"), d.get("menages_total")),420            d.get("loyer_moyen"),421            pct(d.get("francais"), d.get("langue_total")),422            pct(d.get("pct_univ_taux"), d.get("scol_total")),423        ))424    conn.executemany("INSERT INTO da_stats VALUES (?,?,?,?,?,?,?,?,?)", lot)425    conn.commit()426    log(f"da_stats : {len(lot)} AD insérées")427    return len(lot)428429430# ===========================================================================431# ÉTAPE 3 — MÉTADONNÉES (meta)432# ===========================================================================433def ecrire_meta(conn):434    conn.execute("DROP TABLE IF EXISTS meta")435    conn.execute("CREATE TABLE meta(cle TEXT PRIMARY KEY, valeur TEXT)")436    meta = {437        "source_polygones": (438            "Statistique Canada, Fichiers des limites cartographiques du "439            "Recensement de 2021 (92-160-X), aires de diffusion, "440            "lda_000b21a_e.zip — https://www12.statcan.gc.ca/census-recensement/"441            "2021/geo/sip-pis/boundary-limites/files-fichiers/lda_000b21a_e.zip"442        ),443        "source_stats": (444            "Statistique Canada, Profil du recensement, Recensement de la "445            "population de 2021, no 98-401-X2021006 au catalogue, fichier "446            "Québec au niveau des aires de diffusion — "447            "https://www12.statcan.gc.ca/census-recensement/2021/dp-pd/prof/"448            "details/download-telecharger.cfm?Lang=F"449        ),450        "date_construction": datetime.date.today().isoformat(),451        "attribution": (452            "Statistique Canada, Recensement de la population de 2021 "453            "(reproduit et diffusé « tel quel » avec la permission de "454            "Statistique Canada — Licence ouverte de Statistique Canada)"455        ),456        "projection_source": "EPSG:3347 (NAD83 Statistics Canada Lambert) -> EPSG:4326 (WGS84)",457        "zone_couverture": f"lat {LAT_MIN}–{LAT_MAX}, lng {LNG_MIN}–{LNG_MAX} (Québec/Lévis/Grand Montréal + périphérie)",458    }459    conn.executemany("INSERT INTO meta VALUES (?,?)", meta.items())460    conn.commit()461462463# ===========================================================================464# VALIDATIONS465# ===========================================================================466def point_dans_poly(lat, lng, anneaux):467    """Ray casting pair/impair sur l'ensemble des anneaux (gère les trous)."""468    dedans = False469    for anneau in anneaux:470        n = len(anneau)471        j = n - 1472        for i in range(n):473            xi, yi = anneau[i]474            xj, yj = anneau[j]475            if (yi > lat) != (yj > lat) and \476               lng < (xj - xi) * (lat - yi) / (yj - yi) + xi:477                dedans = not dedans478            j = i479    return dedans480481482def trouver_dauid(conn, lat, lng):483    """Retourne le DAUID contenant le point (candidats par bbox, puis PIP)."""484    for dauid, poly in conn.execute(485        "SELECT dauid, poly FROM da_poly "486        "WHERE ? BETWEEN lat_min AND lat_max AND ? BETWEEN lng_min AND lng_max",487        (lat, lng),488    ):489        if point_dans_poly(lat, lng, json.loads(poly)):490            return dauid491    return None492493494def valider(conn):495    n_poly = conn.execute("SELECT COUNT(*) FROM da_poly").fetchone()[0]496    n_stats = conn.execute(497        "SELECT COUNT(*) FROM da_stats WHERE dauid IN (SELECT dauid FROM da_poly)"498    ).fetchone()[0]499    log(f"Validation : {n_poly} AD dans da_poly ; couverture da_stats = "500        f"{n_stats}/{n_poly} ({100.0 * n_stats / max(n_poly, 1):.1f} %)")501502    # point de contrôle : colline Parlementaire / Vieux-Québec503    dauid = trouver_dauid(conn, 46.8139, -71.2329)504    ok = dauid == "24231035"505    log(f"Point (46.8139, -71.2329) -> DAUID {dauid} "506        f"({'OK' if ok else 'ÉCHEC, attendu 24231035'})")507508    # échantillon lisible509    for nom, lat, lng in [510        ("Saint-Roch (Québec)", 46.8163, -71.2258),511        ("Sillery (Québec)", 46.7702, -71.2601),512        ("Plateau Mont-Royal (Mtl)", 45.5230, -73.5817),513    ]:514        d = trouver_dauid(conn, lat, lng)515        row = conn.execute(516            "SELECT population, revenu_median, pct_locataires, loyer_moyen, "517            "pct_francais, pct_univ FROM da_stats WHERE dauid=?", (d,)518        ).fetchone() if d else None519        log(f"  {nom}: DAUID={d} stats={row}")520    return ok and n_poly > 0 and n_stats >= 0.95 * n_poly521522523# ===========================================================================524def main():525    ap = argparse.ArgumentParser(description=__doc__)526    ap.add_argument("--shp", help="chemin du shapefile lda_000b21a_e.shp")527    ap.add_argument("--csv", help="chemin du CSV du profil (98-401-X2021006, Québec)")528    ap.add_argument("--db", default="data/staging-recensement.db")529    ap.add_argument("--etape", default="tout",530                    choices=["poly", "stats", "valider", "tout"])531    args = ap.parse_args()532533    conn = sqlite3.connect(args.db)534    try:535        if args.etape in ("poly", "tout"):536            if not args.shp:537                ap.error("--shp requis pour l'étape poly")538            construire_poly(args.shp, conn)539        if args.etape in ("stats", "tout"):540            if not args.csv:541                ap.error("--csv requis pour l'étape stats")542            construire_stats(args.csv, conn)543            ecrire_meta(conn)544        if args.etape in ("valider", "tout"):545            ok = valider(conn)546            sys.exit(0 if ok else 1)547    finally:548        conn.close()549550551if __name__ == "__main__":552    main()553
Files main
Menu

Theme