SPB Git

Repository Public

ktr_pyramid.py 11.8 KB 313 lines python

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/dem/ktr_pyramid.py11# Description      : KA Maps — pyramide de relief .ktr (voir12#                    docs/TILE_ENGINE.md, « Format .ktr »).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"""KA Maps — pyramide de relief .ktr (voir docs/TILE_ENGINE.md, « Format .ktr »).9192Étapes (chacune reprend sur les fichiers de l'étape précédente) :93  grid   GeoTIFF Float32 (mètres, grille de NŒUDS Web Mercator) -> grille brute i32 en décimètres94  down   grille du zoom z -> zoom z-1 (filtre binomial 3x3 centré sur les nœuds pairs, puis décimation)95  tiles  découpe en tuiles 257x257 (bords partagés avec les voisines), encodage .ktr, écriture atomique9697Une grille de zoom z couvre les tuiles [x0, x1) x [y0, y1) et contient (nx*256+1) x (ny*256+1) nœuds :98le nœud (i, j) est le coin de pixel (x0*256+i, y0*256+j) de la pyramide XYZ. Deux tuiles voisines lisent99donc exactement les mêmes nœuds sur leur bord commun : pas de fissure entre maillages.100"""101import argparse, json, os, struct, sys, zlib102from multiprocessing import Pool103import numpy as np104105NODATA = -32768106DM_MAX = 32767107108109def grid_shape(meta):110    return ((meta["y1"] - meta["y0"]) * 256 + 1, (meta["x1"] - meta["x0"]) * 256 + 1)111112113def load_meta(path):114    with open(path + ".json") as f:115        return json.load(f)116117118def save_meta(path, meta):119    with open(path + ".json", "w") as f:120        json.dump(meta, f)121122123def encode_ktr(tile_dm):124    """tile_dm : int32 (257, 257) en décimètres, NODATA_I32 = absence. Retourne les octets .ktr."""125    valid = tile_dm != NODATA126    flags = 0127    v = tile_dm128    if valid.any() and int(v[valid].max()) > DM_MAX:129        # Altitudes > 3276,7 m : la tuile entière passe en mètres (drapeau bit 0).130        flags |= 1131        v = np.where(valid, np.rint(v / 10.0).astype(np.int64), NODATA)132    v = np.clip(v, -32768, 32767).astype(np.int16)133    v = np.where(valid, np.maximum(v, -32767), NODATA).astype(np.int16)134    d = np.empty_like(v)135    d[:, 1:] = v[:, 1:] - v[:, :-1]          # arithmétique modulo 2^16136    d[1:, 0] = v[1:, 0] - v[:-1, 0]137    d[0, 0] = v[0, 0]138    co = zlib.compressobj(9, zlib.DEFLATED, -15)  # deflate brut (RFC 1951)139    body = co.compress(d.astype("<i2").tobytes()) + co.flush()140    return b"KTR1" + struct.pack("<HH", 257, flags) + body141142143def decode_ktr(buf):144    """Décodeur de référence. Retourne (float64 mètres avec NaN pour l'absence, drapeaux)."""145    if buf[:4] != b"KTR1":146        raise ValueError("signature")147    w, flags = struct.unpack("<HH", buf[4:8])148    raw = zlib.decompress(buf[8:], -15)149    if len(raw) != w * w * 2:150        raise ValueError("taille")151    d = np.frombuffer(raw, "<i2").reshape(w, w).astype(np.int16)152    v = d.copy()153    v[:, 0] = np.cumsum(d[:, 0].astype(np.int64)).astype(np.int16)154    v = np.cumsum(v.astype(np.int64), axis=1).astype(np.int16)155    out = v.astype(np.float64) * (1.0 if flags & 1 else 0.1)156    out[v == NODATA] = np.nan157    return out, flags158159160def cmd_grid(a):161    from osgeo import gdal162    ds = gdal.Open(a.src)163    meta = dict(z=a.z, x0=a.x0, y0=a.y0, x1=a.x1, y1=a.y1)164    h, w = grid_shape(meta)165    if (ds.RasterYSize, ds.RasterXSize) != (h, w):166        sys.exit(f"dimensions {ds.RasterXSize}x{ds.RasterYSize} != grille {w}x{h}")167    band = ds.GetRasterBand(1)168    nd = band.GetNoDataValue()169    out = np.lib.format.open_memmap(a.out, mode="w+", dtype=np.int32, shape=(h, w))170    step = 2048171    nfill = 0172    for r in range(0, h, step):173        n = min(step, h - r)174        blk = band.ReadAsArray(0, r, w, n).astype(np.float64)175        bad = ~np.isfinite(blk)176        if nd is not None:177            bad |= blk == nd178        nfill += int(bad.sum())179        if a.clamp_sea:180            blk = np.maximum(blk, 0.0)181        blk[bad] = a.fill182        out[r:r + n] = np.rint(blk * 10.0).astype(np.int32)183        print(f"grid {r + n}/{h}", flush=True)184    if a.wrap:185        # Monde entier : la première et la dernière colonne sont le même méridien (±180°).186        step = 4096187        for r in range(0, h, step):188            m = (out[r:r + step, 0].astype(np.int64) + out[r:r + step, w - 1]) // 2189            out[r:r + step, 0] = m190            out[r:r + step, w - 1] = m191    out.flush()192    meta["filled_nodes"] = nfill193    save_meta(a.out, meta)194195196def _smooth_rows(src, r0, r1, wrap):197    """Lignes filtrées [r0, r1) de la grille parente (indices enfants pairs 2*r)."""198    h, w = src.shape199    lo = max(2 * r0 - 1, 0)200    hi = min(2 * (r1 - 1) + 1, h - 1)201    blk = np.asarray(src[lo:hi + 1], dtype=np.int64)202    # filtre vertical [1 2 1] aux lignes paires, bords répliqués203    idx = np.arange(r0, r1) * 2204    up = np.clip(idx - 1, 0, h - 1) - lo205    dn = np.clip(idx + 1, 0, h - 1) - lo206    v = blk[up] + 2 * blk[idx - lo] + blk[dn]207    c = v[:, 0::2]208    left = np.empty_like(c)209    right = np.empty_like(c)210    left[:, 1:] = v[:, 1:-1:2]211    right[:, :-1] = v[:, 1::2]212    if wrap:   # monde entier : la colonne 0 et la dernière sont le même méridien213        left[:, 0] = v[:, -2]214        right[:, -1] = v[:, 1]215    else:216        left[:, 0] = v[:, 0]217        right[:, -1] = v[:, -1]218    s = left + 2 * c + right219    return np.floor_divide(s + 8, 16).astype(np.int32)220221222def cmd_down(a):223    src = np.load(a.src, mmap_mode="r")224    m = load_meta(a.src)225    for k in ("x0", "y0", "x1", "y1"):226        if m[k] % 2:227            sys.exit("la grille doit être alignée sur des tuiles paires")228    meta = dict(z=m["z"] - 1, x0=m["x0"] // 2, y0=m["y0"] // 2, x1=m["x1"] // 2, y1=m["y1"] // 2)229    h, w = grid_shape(meta)230    out = np.lib.format.open_memmap(a.out, mode="w+", dtype=np.int32, shape=(h, w))231    step = 1024232    for r in range(0, h, step):233        n = min(step, h - r)234        out[r:r + n] = _smooth_rows(src, r, r + n, a.wrap)235    out.flush()236    save_meta(a.out, meta)237    print(f"down z{meta['z']} {w}x{h}", flush=True)238239240_G = {}241242243def _init(path):244    _G["g"] = np.load(path, mmap_mode="r")245246247def _tile_row(job):248    z, ty, x0, y0, nx, outdir, skip_const = job249    g = _G["g"]250    j = (ty - y0) * 256251    rows = np.asarray(g[j:j + 257])252    stats = []253    for tx in range(x0, x0 + nx):254        i = (tx - x0) * 256255        t = rows[:, i:i + 257]256        if skip_const is not None and t.min() == skip_const and t.max() == skip_const:257            stats.append(0)258            continue259        buf = encode_ktr(t)260        d = f"{outdir}/{z}/{tx}"261        os.makedirs(d, exist_ok=True)262        tmp = f"{d}/{ty}.ktr.tmp"263        with open(tmp, "wb") as f:264            f.write(buf)265        os.replace(tmp, f"{d}/{ty}.ktr")266        stats.append(len(buf))267    return stats268269270def cmd_tiles(a):271    m = load_meta(a.src)272    z, x0, y0 = m["z"], m["x0"], m["y0"]273    nx, ny = m["x1"] - x0, m["y1"] - y0274    jobs = [(z, ty, x0, y0, nx, a.out, a.skip_const) for ty in range(y0, y0 + ny)]275    sizes = []276    with Pool(a.jobs, initializer=_init, initargs=(a.src,)) as p:277        for k, s in enumerate(p.imap_unordered(_tile_row, jobs, chunksize=1)):278            sizes.extend(s)279            if k % 64 == 0:280                print(f"tiles z{z} {k}/{ny}", flush=True)281    s = np.array([x for x in sizes if x > 0])282    rep = dict(z=z, x0=x0, y0=y0, x1=m["x1"], y1=m["y1"], tiles=int(len(s)), skipped=int(len(sizes) - len(s)),283               bytes=int(s.sum()), min=int(s.min()), median=float(np.median(s)), max=int(s.max()))284    os.makedirs(f"{a.out}/meta", exist_ok=True)285    with open(f"{a.out}/meta/z{z}{a.tag}.json", "w") as f:286        json.dump(rep, f)287    print(json.dumps(rep), flush=True)288289290def main():291    p = argparse.ArgumentParser()292    sp = p.add_subparsers(dest="cmd", required=True)293    g = sp.add_parser("grid")294    g.add_argument("src"); g.add_argument("out")295    for k in ("z", "x0", "y0", "x1", "y1"):296        g.add_argument("--" + k, type=int, required=True)297    g.add_argument("--fill", type=float, default=0.0, help="altitude (m) des nœuds sans donnée")298    g.add_argument("--clamp-sea", action="store_true", help="ramène les altitudes négatives à 0")299    g.add_argument("--wrap", action="store_true", help="grille mondiale : colonnes extrêmes identiques")300    d = sp.add_parser("down")301    d.add_argument("src"); d.add_argument("out"); d.add_argument("--wrap", action="store_true")302    t = sp.add_parser("tiles")303    t.add_argument("src"); t.add_argument("out"); t.add_argument("--jobs", type=int, default=8)304    t.add_argument("--skip-const", type=int, default=None,305                   help="n'écrit pas les tuiles uniformément égales à cette valeur (dm)")306    t.add_argument("--tag", default="")307    a = p.parse_args()308    {"grid": cmd_grid, "down": cmd_down, "tiles": cmd_tiles}[a.cmd](a)309310311if __name__ == "__main__":312    main()313
Files main
Menu

Theme