SPB Git

Repository Public

verify_pyramid.py 11.2 KB 258 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/km-terrain/tests/verify_pyramid.py11# Description      : Vérification de la pyramide de relief : altitudes de12#                    repères connus, continuité des bords, tailles.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"""Vérification de la pyramide de relief : altitudes de repères connus, continuité des bords, tailles.9192  python3 -I verify_pyramid.py [/var/lib/kamaps/dem] [--pairs 3000] [--http https://terrain.spboucher.ai]9394Sortie : JSON (valeurs mesurées, à reporter dans docs/TEST_REPORT.md). Code de retour 1 si un contrôle échoue.95"""96import argparse, glob, json, math, os, random, sys, urllib.request97import numpy as np9899sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..", "pipeline", "dem"))100from ktr_pyramid import decode_ktr  # noqa: E402101102# (nom, lat, lon, altitude publiée en m, source de la valeur publiée[, tolérance en m — 15 par défaut])103# Mont Tremblant : la valeur couramment publiée (968 m) n'est reproduite ni par MRDEM-30 (931,5 m) ni par Copernicus104# GLO-30 (935 m, modèle de surface) ; tolérance élargie, l'écart est rapporté tel quel.105# Mont D'Iberville : arête alpine étroite, écrêtée par un modèle à 30 m.106SUMMITS = [107    ("Mont Royal (sommet)", 45.5071, -73.5874, 233, "Ville de Montréal"),108    ("Mont Jacques-Cartier", 48.9906, -65.9433, 1268, "Commission de toponymie / Sépaq"),109    ("Mont Tremblant", 46.2581, -74.5562, 968, "Sépaq", 40),110    ("Mont Mégantic", 45.4556, -71.1525, 1105, "Sépaq"),111    ("Mont Orford", 45.3128, -72.2414, 853, "Sépaq"),112    ("Mont Sainte-Anne", 47.0817, -70.9090, 800, "Sépaq"),113    ("Mont Albert (sommet sud)", 48.9100, -66.1850, 1151, "Sépaq"),114    ("Mont D'Iberville (Torngat)", 58.8875, -63.7125, 1652, "Commission de toponymie", 80),115]116# (nom, lat, lon, altitude attendue, tolérance)117LEVELS = [118    ("Estuaire du Saint-Laurent, large de Rimouski", 48.60, -68.50, 0.0, 1.0),119    ("Estuaire, large de Baie-Comeau", 49.00, -68.00, 0.0, 1.0),120    ("Golfe du Saint-Laurent", 48.00, -62.00, 0.0, 1.0),121    ("Baie d'Hudson (côte du Nunavik)", 58.00, -79.50, 0.0, 1.0),122    ("Fleuve à Québec (entre Québec et Lévis)", 46.8130, -71.1930, 0.0, 3.0),123    ("Lac Saint-Jean (centre)", 48.60, -72.00, 99.0, 3.0),124    ("Lac Champlain (côté États-Unis, GLO-30)", 44.75, -73.38, 29.0, 3.0),125]126127128def tile_xy(lon, lat, z):129    n = 2 ** z130    x = (lon + 180) / 360 * n131    y = (1 - math.asinh(math.tan(math.radians(lat))) / math.pi) / 2 * n132    return x, y133134135class Pyramid:136    def __init__(self, root, http=None):137        self.root, self.http, self.cache = root, http, {}138139    def tile(self, z, x, y):140        k = (z, x, y)141        if k not in self.cache:142            if len(self.cache) > 64:143                self.cache.clear()144            try:145                if self.http:146                    with urllib.request.urlopen(f"{self.http}/v1/dem/{z}/{x}/{y}.ktr", timeout=20) as r:147                        buf = r.read() if r.status == 200 else None148                else:149                    with open(f"{self.root}/{z}/{x}/{y}.ktr", "rb") as f:150                        buf = f.read()151                self.cache[k] = decode_ktr(buf)[0] if buf else None152            except FileNotFoundError:153                self.cache[k] = None154        return self.cache[k]155156    def sample(self, lon, lat, z=12):157        fx, fy = tile_xy(lon, lat, z)158        x, y = int(fx), int(fy)159        t = self.tile(z, x, y)160        if t is None:161            return None162        cx, cy = (fx - x) * 256, (fy - y) * 256163        c0, r0 = min(int(cx), 255), min(int(cy), 255)164        tx, ty = cx - c0, cy - r0165        return float((t[r0, c0] * (1 - tx) + t[r0, c0 + 1] * tx) * (1 - ty) + (t[r0 + 1, c0] * (1 - tx) + t[r0 + 1, c0 + 1] * tx) * ty)166167    def window_max(self, lon, lat, radius_m=3000, z=12):168        """Plus haut nœud dans un rayon donné : les coordonnées nominales d'un sommet sont rarement exactes."""169        dlat = radius_m / 111320.0170        dlon = dlat / math.cos(math.radians(lat))171        x0, y0 = tile_xy(lon - dlon, lat + dlat, z)172        x1, y1 = tile_xy(lon + dlon, lat - dlat, z)173        best = -1e9174        for tx in range(int(x0), int(x1) + 1):175            for ty in range(int(y0), int(y1) + 1):176                t = self.tile(z, tx, ty)177                if t is None:178                    continue179                c0, c1 = max(0, int((x0 - tx) * 256)), min(256, int((x1 - tx) * 256) + 1)180                r0, r1 = max(0, int((y0 - ty) * 256)), min(256, int((y1 - ty) * 256) + 1)181                if c1 >= c0 and r1 >= r0:182                    best = max(best, float(np.nanmax(t[r0:r1 + 1, c0:c1 + 1])))183        return best184185186def seams(root, pairs, seed=20261201):187    rng = random.Random(seed)188    out = {}189    for zdir in sorted(glob.glob(f"{root}/[0-9]*"), key=lambda p: int(os.path.basename(p))):190        z = int(os.path.basename(zdir))191        xs = [int(os.path.basename(p)) for p in glob.glob(f"{zdir}/*")]192        checked = bad = maxdiff = 0193        tries = 0194        target = min(pairs, max(1, len(xs) * 4))195        while checked < target and tries < target * 20:196            tries += 1197            x = rng.choice(xs)198            ys = os.listdir(f"{zdir}/{x}")199            y = int(rng.choice(ys).split(".")[0])200            horiz = rng.random() < 0.5201            nx, ny = (x + 1, y) if horiz else (x, y + 1)202            if z > 0 and horiz and z <= 7:203                nx %= 2 ** z      # monde : la tuile la plus à l'est touche la plus à l'ouest204            p1, p2 = f"{zdir}/{x}/{y}.ktr", f"{root}/{z}/{nx}/{ny}.ktr"205            if not os.path.exists(p2) or (nx, ny) == (x, y):206                continue207            a = decode_ktr(open(p1, "rb").read())208            b = decode_ktr(open(p2, "rb").read())209            ea, eb = (a[0][:, 256], b[0][:, 0]) if horiz else (a[0][256, :], b[0][0, :])210            d = np.abs(ea - eb)211            # tuiles en unités différentes (mètres / décimètres) : écart d'arrondi ≤ 0,5 m admis212            tol = 1e-9 if a[1] == b[1] else 0.5 + 1e-9213            checked += 1214            if np.nanmax(d) > tol:215                bad += 1216            maxdiff = max(maxdiff, float(np.nanmax(d)))217        out[z] = dict(pairs=checked, mismatched=bad, max_diff_m=round(maxdiff, 3))218    return out219220221def main():222    ap = argparse.ArgumentParser()223    ap.add_argument("root", nargs="?", default="/var/lib/kamaps/dem")224    ap.add_argument("--pairs", type=int, default=3000)225    ap.add_argument("--http", default=None, help="lit les repères par HTTP plutôt que sur disque")226    a = ap.parse_args()227    pyr = Pyramid(a.root, a.http)228    ok = True229    rep = {"summits": [], "levels": [], "http": a.http}230    for name, lat, lon, ref, src, *tol in SUMMITS:231        tol = tol[0] if tol else 15232        at = pyr.sample(lon, lat)233        mx = pyr.window_max(lon, lat, 12000 if "Iberville" in name else 3000)234        rep["summits"].append(dict(name=name, published_m=ref, published_by=src, at_point_m=round(at, 1), max_within_3km=round(mx, 1),235                                   diff_m=round(mx - ref, 1), tolerance_m=tol))236        ok &= abs(mx - ref) <= tol237    for name, lat, lon, ref, tol in LEVELS:238        v = pyr.sample(lon, lat)239        rep["levels"].append(dict(name=name, expected_m=ref, tolerance_m=tol, measured_m=round(v, 1)))240        ok &= abs(v - ref) <= tol241    if not a.http:242        rep["seams"] = seams(a.root, a.pairs)243        ok &= all(v["mismatched"] == 0 for v in rep["seams"].values())244        sizes = {}245        for f in sorted(glob.glob(f"{a.root}/meta/z*.json")):246            r = json.load(open(f))247            sizes[r["z"]] = dict(tiles=r["tiles"], bytes=r["bytes"], min=r["min"], median=r["median"], max=r["max"])248        rep["sizes"] = dict(sorted(sizes.items()))249        rep["total_bytes"] = sum(v["bytes"] for v in sizes.values())250        rep["total_tiles"] = sum(v["tiles"] for v in sizes.values())251    rep["ok"] = bool(ok)252    print(json.dumps(rep, ensure_ascii=False, indent=1))253    sys.exit(0 if ok else 1)254255256if __name__ == "__main__":257    main()258
Files main
Menu

Theme