Repository Public
1#!/bin/bash2# =============================================================================3# SP BOUCHER | INFRASTRUCTURE & AUTOMATION4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# Project : KA Maps Engine8# File : server/pipeline/04b-landcover-lowzoom.sh9# Module : server10# Repository : https://git.spboucher.ai/ka-maps-engine11# Created : 2026-12-0112# Last Modified : 2026-12-0113#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: support@spboucher.ai22# Technical Contact: dev@spboucher.ai23# Security/Admin : admin@spboucher.ai24#25# Copyright (c) 202626# Simon-Pierre Boucher27# All rights reserved where applicable. This file is governed by the28# applicable project license, copyright notices and relevant law.29# Existing third-party rights and notices remain unaffected.30#31# License : None specified (no license file in this repository)32#33# Do not embed credentials, private keys, access tokens,34# certificates or confidential personal information.35#36# =============================================================================37# END OF SP BOUCHER SOURCE HEADER38# =============================================================================3940# Couvert du sol généralisé par trame : tables landcover_z4 … landcover_z9 et landcover_fill du schéma donné.41#42# Deux sources, peintes sur une même grille (maille = 16 unités de tuile du zoom visé, soit un pixel d'une tuile43# de 256 px ; à 8 unités, une fois le nord entièrement couvert par RNCan, les tuiles z6–z7 dépassaient le budget) :44# 1. fond : « Couverture des terres du Canada 2020 » de RNCan (30 m, OGL-Canada), ramenée à la maille par45# classe majoritaire — forêts, toundra, milieux humides, cultures, roche, glace là où OSM n'a rien dessiné46# (nord du Québec, Labrador, Nunavut, Ontario) ;47# 2. par-dessus : les polygones OSM (OSM l'emporte partout où il existe).48# Puis : amas de moins de 6 mailles retirés, revectorisation en grands polygones par nature, lissage des escaliers.49# `landcover_fill` (maille du z9, OSM masqué) sert de fond à z10–z11 sous les polygones OSM vectoriels.50# La mosaïque OSM (millions de petits polygones) ne se généralise pas bien par simple filtre d'aire : d'où la trame.51# Outils : GDAL (gdalwarp, gdal_rasterize, gdal_sieve, gdal_polygonize). Usage : 04b-landcover-lowzoom.sh <schéma>52. "$(dirname "$0")/env.sh"53SCHEMA=${1:-osm_next}54LCC=${KM_LANDCOVER_TIF:-$KM_SRC/ext/landcover-2020-classification.tif}55T=$(mktemp -d /var/tmp/km-landcover.XXXXXX); trap 'rm -rf "$T"' EXIT56OGR="PG:$(echo "$KM_DB_URL" | sed -E 's#postgres://([^:]+):([^@]+)@([^:]+):([0-9]+)/(.+)#host=\3 port=\4 dbname=\5 user=\1 password=\2#')"57# ordre de peinture OSM : le dernier l'emporte. Codes : 1 forest 2 grass 3 farmland 4 wetland 5 scrub 6 rock 7 sand 8 glacier58KINDS="grass:2 scrub:5 farmland:3 forest:1 wetland:4 sand:7 rock:6 glacier:8"59# Emprises (EPSG:4326 → 3857). Aux zooms 4 à 8 une vue du Québec montre aussi l'Ontario, les Prairies et60# l'Arctique : tout le Canada couvert par RNCan est peint, sinon le fond s'arrête sur un bord droit. À z9 (et pour61# le fond des z10–z11), l'est du Canada suffit.62extent() { # ouest sud est nord → X0 Y0 X1 Y1 arrondis à 10 km63 psql -X -At -F' ' "$KM_DB_URL" -c "SELECT floor(ST_XMin(b)/10000)*10000, floor(ST_YMin(b)/10000)*10000, ceil(ST_XMax(b)/10000)*10000, ceil(ST_YMax(b)/10000)*10000 FROM (SELECT ST_Transform(ST_MakeEnvelope($1, $2, $3, $4, 4326), 3857) b) q"64}65EXT_WIDE="$(extent -141.0 41.6 -52.0 72.0)"66EXT_EAST="$(extent -96.0 41.6 -52.0 64.0)"67[ -s "$LCC" ] && log "fond RNCan : $LCC" || log "AVERTISSEMENT : $LCC absent — couvert du sol OSM seul"6869# Classes RNCan 2020 → codes ka1. 17 (urbain) et 18 (eau) restent vides : l'eau et l'usage du sol ont leurs couches.70cat > "$T/reclass.py" <<'PY'71import sys72import numpy as np73from osgeo import gdal74lut = np.zeros(256, dtype=np.uint8)75for src, dst in {1: 1, 2: 1, 5: 1, 6: 1, 8: 5, 11: 5, 10: 2, 12: 2, 13: 6, 16: 6, 14: 4, 15: 3, 19: 8}.items():76 lut[src] = dst77ds = gdal.Open(sys.argv[1], gdal.GA_Update)78b = ds.GetRasterBand(1)79for y in range(0, ds.RasterYSize, 2048):80 n = min(2048, ds.RasterYSize - y)81 b.WriteArray(lut[b.ReadAsArray(0, y, ds.RasterXSize, n)], 0, y)82ds.FlushCache()83PY8485# Revectorisation par blocs de 512 mailles : sans cela la forêt boréale forme un seul polygone de plusieurs86# millions de sommets et de dizaines de milliers de trous, que PostGIS met des dizaines de minutes à lisser et à87# découper. Chaque bloc est vectorisé avec une marge de 8 mailles, lissé, puis recoupé à son emprise exacte : les88# polygones de deux blocs voisins se rejoignent sur une arête droite commune et se refondent au service (fusion par89# nature dans chaque tuile). Sans la marge, le lissage rognait les angles sur la couture et laissait un filet clair90# le long de chaque limite de bloc (vu au rendu à z4–z6).91cat > "$T/polygonize_blocks.py" <<'PY'92import sys93from osgeo import gdal, ogr, osr94src = gdal.Open(sys.argv[1])95band = src.GetRasterBand(1)96gt = src.GetGeoTransform()97srs = osr.SpatialReference(); srs.ImportFromEPSG(3857)98out = ogr.GetDriverByName("GPKG").CreateDataSource(sys.argv[2])99lyr = out.CreateLayer("lc", srs, ogr.wkbPolygon)100lyr.CreateField(ogr.FieldDefn("dn", ogr.OFTInteger))101for f in ("bx0", "by0", "bx1", "by1"): # emprise exacte du bloc (sans la marge)102 lyr.CreateField(ogr.FieldDefn(f, ogr.OFTReal))103B, M = 512, 8104mem = gdal.GetDriverByName("MEM")105vmem = ogr.GetDriverByName("Memory") or ogr.GetDriverByName("MEM")106defn = lyr.GetLayerDefn()107lyr.StartTransaction()108for y in range(0, src.RasterYSize, B):109 for x in range(0, src.RasterXSize, B):110 w, h = min(B, src.RasterXSize - x), min(B, src.RasterYSize - y)111 if not band.ReadAsArray(x, y, w, h).any():112 continue113 mx0, my0 = max(0, x - M), max(0, y - M)114 mw, mh = min(src.RasterXSize, x + w + M) - mx0, min(src.RasterYSize, y + h + M) - my0115 d = mem.Create("", mw, mh, 1, gdal.GDT_Byte)116 d.SetGeoTransform((gt[0] + mx0 * gt[1], gt[1], 0, gt[3] + my0 * gt[5], 0, gt[5]))117 b = d.GetRasterBand(1)118 b.WriteArray(band.ReadAsArray(mx0, my0, mw, mh))119 b.SetNoDataValue(0)120 tds = vmem.CreateDataSource("blk")121 tl = tds.CreateLayer("b", srs, ogr.wkbPolygon)122 tl.CreateField(ogr.FieldDefn("dn", ogr.OFTInteger))123 gdal.Polygonize(b, b, tl, 0, [])124 box = (gt[0] + x * gt[1], gt[3] + (y + h) * gt[5], gt[0] + (x + w) * gt[1], gt[3] + y * gt[5])125 for ft in tl:126 o = ogr.Feature(defn)127 o.SetGeometry(ft.GetGeometryRef())128 o.SetField("dn", ft.GetField("dn"))129 for k, v in zip(("bx0", "by0", "bx1", "by1"), box):130 o.SetField(k, v)131 lyr.CreateFeature(o)132lyr.CommitTransaction()133PY134135vectorize() { # raster table cell136 local s=$T/$2.s.tif137 gdal_sieve.py -q -st 6 -4 "$1" "$s"138 python3 "$T/polygonize_blocks.py" "$s" "$T/$2.gpkg"139 ogr2ogr -f PostgreSQL "$OGR" "$T/$2.gpkg" -nln "$SCHEMA.${2}_raw" -overwrite -lco GEOMETRY_NAME=geom -lco FID=gid \140 -lco SPATIAL_INDEX=NONE -nlt POLYGON -a_srs EPSG:3857 -where "dn > 0" --config PG_USE_COPY YES 2>&1 | grep -v 'event trigger' || true141 psql -X -q -v ON_ERROR_STOP=1 "$KM_DB_URL" <<SQL142SET client_min_messages = warning;143DROP TABLE IF EXISTS $SCHEMA.$2 CASCADE;144CREATE TABLE $SCHEMA.$2 AS145 SELECT kind, a AS area, (ST_Dump(ST_Subdivide(g, 256))).geom::geometry(Polygon,3857) AS geom FROM (146 SELECT kind, ST_Area(g)::real AS a, g FROM (147 SELECT (ARRAY['forest','grass','farmland','wetland','scrub','rock','sand','glacier'])[dn] AS kind,148 (ST_Dump(ST_CollectionExtract(ST_MakeValid(ST_ClipByBox2D(ST_MakeValid(149 ST_Simplify(ST_ChaikinSmoothing(ST_Simplify(meta.km_drop_small_holes(geom, 6 * $3 * $3), $3 * 0.75), 1), $3 * 0.2)),150 ST_MakeEnvelope(bx0, by0, bx1, by1, 3857))), 3))).geom AS g151 FROM $SCHEMA.${2}_raw WHERE dn BETWEEN 1 AND 8) s152 WHERE NOT ST_IsEmpty(g) AND ST_Area(g) >= 0.5 * $3 * $3) t;153CREATE INDEX ON $SCHEMA.$2 USING gist (geom);154ANALYZE $SCHEMA.$2;155DROP TABLE $SCHEMA.${2}_raw;156SQL157 log "$2 : maille $3 m, $(psql -X -At "$KM_DB_URL" -c "SELECT count(*) || ' polygones, ' || sum(ST_NPoints(geom)) || ' sommets' FROM $SCHEMA.$2")"158}159160one_zoom() {161 set -euo pipefail162 local z=$1 cell min r=$T/lc$1.tif X0 Y0 X1 Y1163 if [ "$z" -ge 9 ]; then read -r X0 Y0 X1 Y1 <<<"$EXT_EAST"; else read -r X0 Y0 X1 Y1 <<<"$EXT_WIDE"; fi164 cell=$(python3 -c "print(round(40075016.686/4096/2**$z*16, 3))")165 min=$(python3 -c "print(($cell*0.7)**2)")166 if [ -s "$LCC" ]; then167 gdalwarp -q -overwrite -t_srs EPSG:3857 -te $X0 $Y0 $X1 $Y1 -tr $cell $cell -r mode -ot Byte -dstnodata 0 \168 -wo NUM_THREADS=4 -co COMPRESS=DEFLATE -co TILED=YES "$LCC" "$r"169 python3 "$T/reclass.py" "$r"170 else171 gdal_create -q -of GTiff -ot Byte -co COMPRESS=DEFLATE -co TILED=YES -a_srs EPSG:3857 -a_nodata 0 \172 -outsize $(python3 -c "import math; print(math.ceil(($X1-$X0)/$cell), math.ceil(($Y1-$Y0)/$cell))") \173 -a_ullr $X0 $Y1 $(python3 -c "import math; print($X0+math.ceil(($X1-$X0)/$cell)*$cell, $Y1-math.ceil(($Y1-$Y0)/$cell)*$cell)") -burn 0 "$r"174 fi175 if [ "$z" = 9 ] && [ -s "$LCC" ]; then176 # fond des zooms 10–11 : classes RNCan là où OSM n'a aucun polygone de couvert177 cp "$r" "$T/fill.tif"178 gdal_rasterize -q -burn 0 -sql "SELECT geom FROM $SCHEMA.landcover WHERE area >= $min" "$OGR" "$T/fill.tif"179 vectorize "$T/fill.tif" landcover_fill "$cell"180 fi181 for kv in $KINDS; do182 gdal_rasterize -q -burn "${kv#*:}" -sql "SELECT geom FROM $SCHEMA.landcover WHERE kind = '${kv%%:*}' AND area >= $min" "$OGR" "$r"183 done184 vectorize "$r" "landcover_z$z" "$cell"185}186export -f one_zoom vectorize log; export T OGR KINDS EXT_WIDE EXT_EAST SCHEMA KM_DB_URL LCC187printf '%s\n' 4 5 6 7 8 9 | xargs -P 6 -I{} bash -c 'one_zoom {}'188psql -X -q "$KM_DB_URL" -c "CREATE TABLE IF NOT EXISTS $SCHEMA.landcover_fill (kind text, area real, geom geometry(Polygon,3857))"189for z in 4 5 6 7 8 9; do190 [ "$(psql -X -At "$KM_DB_URL" -c "SELECT to_regclass('$SCHEMA.landcover_z$z') IS NOT NULL")" = "t" ] || { log "ERREUR : landcover_z$z n'a pas été produite"; exit 1; }191done192