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/pipeline/lib/load_nrcan.py11# Description : Charge dans ext.nrcan_building les bâtiments RNCan12# (GeoParquet national) situés dans l'emprise du Québec.13# Module : server14# Repository : https://git.spboucher.ai/ka-maps-engine15# Created : 2026-12-0116# Last Modified : 2026-12-0117#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author : Simon-Pierre Boucher23# Position : Professor of Finance24# Institution : Université du Québec en Outaouais (UQO)25# Department : Département des sciences administratives26# Organization : SP Boucher27#28# Website : https://spboucher.ai29# Git : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General : info@spboucher.ai36# Professional : contact@spboucher.ai37# Direct : simon@spboucher.ai38# Research : research@spboucher.ai39# Development : dev@spboucher.ai40# Support : support@spboucher.ai41# Security/Admin : admin@spboucher.ai42# Notifications : notifications@spboucher.ai43#44# Preferred Contact: support@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification : Public69# Distribution : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License : None specified (no license file in this repository)83# Maintainer : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Charge dans ext.nrcan_building les bâtiments RNCan (GeoParquet national) situés dans l'emprise du Québec.9192Seules les colonnes utiles sont lues ; le filtre d'emprise utilise la colonne `geometry_bbox` du fichier.93Hauteurs : `heightmax`/`heightmin` = hauteur du bâtiment au-dessus du sol, mesurée par LiDAR aéroporté.94"""95import io96import os97import sys9899import psycopg2100import pyarrow.parquet as pq101102W, S, E, N = -79.9, 44.9, -57.0, 62.7103path = sys.argv[1]104conn = psycopg2.connect(os.environ["KM_DB_URL"])105cur = conn.cursor()106cur.execute("""107DROP TABLE IF EXISTS ext.nrcan_building;108CREATE TABLE ext.nrcan_building (109 feature_id text, heightmax real, heightmin real, elevmax real, elevmin real, vaccmax real, datemax text, provider text, qltylvl smallint,110 geom geometry(Geometry, 4617));111""")112f = pq.ParquetFile(path)113cols = ["feature_id", "heightmax", "heightmin", "elevmax", "elevmin", "vaccmax", "datemax", "providerfr", "qltylvl", "geometry", "geometry_bbox"]114total = kept = 0115for rg in range(f.metadata.num_row_groups):116 # statistiques du groupe : on saute les groupes hors emprise sans les lire117 md = f.metadata.row_group(rg)118 skip = False119 for ci in range(md.num_columns):120 c = md.column(ci)121 if c.statistics is None or not c.statistics.has_min_max:122 continue123 p = c.path_in_schema124 if p == "geometry_bbox.xmin" and c.statistics.min > E:125 skip = True126 if p == "geometry_bbox.xmax" and c.statistics.max < W:127 skip = True128 if p == "geometry_bbox.ymin" and c.statistics.min > N:129 skip = True130 if p == "geometry_bbox.ymax" and c.statistics.max < S:131 skip = True132 total += md.num_rows133 if skip:134 continue135 t = f.read_row_group(rg, columns=cols).to_pydict()136 buf = io.StringIO()137 n = 0138 for i in range(len(t["feature_id"])):139 b = t["geometry_bbox"][i]140 if b["xmax"] < W or b["xmin"] > E or b["ymax"] < S or b["ymin"] > N:141 continue142 h = t["heightmax"][i]143 if h is None:144 continue145 def s(v):146 return "\\N" if v is None else str(v).replace("\t", " ").replace("\n", " ").replace("\\", "")147 buf.write("\t".join([s(t["feature_id"][i]), s(h), s(t["heightmin"][i]), s(t["elevmax"][i]), s(t["elevmin"][i]), s(t["vaccmax"][i]), s(t["datemax"][i]),148 s(t["providerfr"][i]), s(t["qltylvl"][i]), t["geometry"][i].hex()]) + "\n")149 n += 1150 if n:151 buf.seek(0)152 cur.copy_expert("COPY ext.nrcan_building FROM STDIN", buf)153 kept += n154cur.execute("""155ALTER TABLE ext.nrcan_building ALTER COLUMN geom TYPE geometry(MultiPolygon, 3857)156 USING ST_Multi(ST_CollectionExtract(ST_MakeValid(ST_Transform(ST_Force2D(geom), 3857)), 3));157DELETE FROM ext.nrcan_building WHERE ST_IsEmpty(geom) OR heightmax < 2 OR heightmax > 600;158CREATE INDEX ON ext.nrcan_building USING gist (geom);159ANALYZE ext.nrcan_building;160""")161conn.commit()162cur.execute("SELECT count(*) FROM ext.nrcan_building")163print(f"RNCan : {total} bâtiments au Canada, {kept} dans l'emprise, {cur.fetchone()[0]} conservés")164