|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Generate reference expected-output PNG tiles for the live merge tests. |
| 3 | +
|
| 4 | +Runs the merger against the committed GEBCO and JAXA fixture files, extracts |
| 5 | +a small set of key output tiles as lossless PNG files, and writes them to |
| 6 | +test/fixtures/expected/. The comparison test (TestLiveMerge.test_output_matches_expected_tiles) |
| 7 | +loads these PNGs, decodes to elevation values, and checks that new runs of the |
| 8 | +merger produce the same results within 1 m tolerance. |
| 9 | +
|
| 10 | +Run this script whenever you intentionally change merger behaviour so that the |
| 11 | +reference tiles stay in sync: |
| 12 | +
|
| 13 | + python test/generate_expected_tiles.py |
| 14 | +""" |
| 15 | + |
| 16 | +import io |
| 17 | +import json |
| 18 | +import os |
| 19 | +import sys |
| 20 | +import sqlite3 |
| 21 | +import tempfile |
| 22 | +import traceback |
| 23 | +from pathlib import Path |
| 24 | + |
| 25 | +from PIL import Image |
| 26 | + |
| 27 | +# Allow running from the repo root without installing the package. |
| 28 | +sys.path.insert(0, str(Path(__file__).parent.parent)) |
| 29 | + |
| 30 | +from click.testing import CliRunner |
| 31 | +from rio_rgbify.scripts.cli import main_group as cli |
| 32 | + |
| 33 | +# --------------------------------------------------------------------------- |
| 34 | +# Paths |
| 35 | +# --------------------------------------------------------------------------- |
| 36 | + |
| 37 | +FIXTURES_DIR = Path(__file__).parent / "fixtures" |
| 38 | +GEBCO_FIXTURE = FIXTURES_DIR / "gebco_sample.mbtiles" |
| 39 | +JAXA_FIXTURE = FIXTURES_DIR / "jaxa_sample.mbtiles" |
| 40 | +EXPECTED_DIR = Path(__file__).parent / "expected" |
| 41 | + |
| 42 | +# --------------------------------------------------------------------------- |
| 43 | +# Key tiles to capture as reference output — (z, x, y, description). |
| 44 | +# |
| 45 | +# z=0/x=0/y=0 global overview — always present |
| 46 | +# z=2/x=2/y=1 East Asia / Pacific coast — JAXA land wins over GEBCO depths |
| 47 | +# z=2/x=0/y=2 South Atlantic open ocean — GEBCO-only depths |
| 48 | +# --------------------------------------------------------------------------- |
| 49 | + |
| 50 | +KEY_TILES = [ |
| 51 | + (0, 0, 0, "global_z0"), |
| 52 | + (2, 2, 1, "east_asia_z2"), |
| 53 | + (2, 0, 2, "south_atlantic_z2"), |
| 54 | +] |
| 55 | + |
| 56 | + |
| 57 | +def _decode_elevation(tile_bytes: bytes): |
| 58 | + """Decode mapbox-encoded RGB(A) tile bytes -> elevation float64 array.""" |
| 59 | + img = Image.open(io.BytesIO(tile_bytes)).convert("RGB") |
| 60 | + arr = __import__("numpy").array(img).astype(__import__("numpy").float64) |
| 61 | + r, g, b = arr[:, :, 0], arr[:, :, 1], arr[:, :, 2] |
| 62 | + return -10000 + ((r * 256 * 256 + g * 256 + b) * 0.1) |
| 63 | + |
| 64 | + |
| 65 | +def main() -> int: |
| 66 | + if not GEBCO_FIXTURE.exists() or not JAXA_FIXTURE.exists(): |
| 67 | + print("ERROR: Fixture files not found.") |
| 68 | + print(" Run `python test/download_fixtures.py` first.") |
| 69 | + return 1 |
| 70 | + |
| 71 | + EXPECTED_DIR.mkdir(parents=True, exist_ok=True) |
| 72 | + |
| 73 | + with tempfile.TemporaryDirectory() as tmp: |
| 74 | + out = os.path.join(tmp, "merged.mbtiles") |
| 75 | + cfg_path = os.path.join(tmp, "config.json") |
| 76 | + |
| 77 | + # Mirror the TestLiveMerge._run_merge config but force output_format=png |
| 78 | + # so the reference tiles are stored losslessly. |
| 79 | + cfg = { |
| 80 | + "output_type": "mbtiles", |
| 81 | + "sources": [ |
| 82 | + { |
| 83 | + "path": str(JAXA_FIXTURE), |
| 84 | + "encoding": "mapbox", |
| 85 | + "mask_values": [-10000, 0, -1], |
| 86 | + }, |
| 87 | + { |
| 88 | + "path": str(GEBCO_FIXTURE), |
| 89 | + "encoding": "mapbox", |
| 90 | + "mask_values": [-10000], |
| 91 | + }, |
| 92 | + ], |
| 93 | + "output_path": out, |
| 94 | + "output_encoding": "mapbox", |
| 95 | + "output_format": "png", |
| 96 | + "resampling": "cubic", |
| 97 | + "min_zoom": 0, |
| 98 | + "max_zoom": 2, |
| 99 | + } |
| 100 | + |
| 101 | + with open(cfg_path, "w") as f: |
| 102 | + json.dump(cfg, f) |
| 103 | + |
| 104 | + print("Running merger (this may take ~60 seconds) ...") |
| 105 | + runner = CliRunner() |
| 106 | + result = runner.invoke(cli, ["merge", "--config", cfg_path, "-j", "1"]) |
| 107 | + |
| 108 | + if result.exit_code != 0: |
| 109 | + print("ERROR: Merger failed:") |
| 110 | + print(result.output) |
| 111 | + if result.exception: |
| 112 | + traceback.print_exception( |
| 113 | + type(result.exception), |
| 114 | + result.exception, |
| 115 | + result.exception.__traceback__, |
| 116 | + ) |
| 117 | + return 1 |
| 118 | + |
| 119 | + print("Extracting key tiles ...") |
| 120 | + conn = sqlite3.connect(out) |
| 121 | + saved = 0 |
| 122 | + |
| 123 | + for z, x, y, desc in KEY_TILES: |
| 124 | + row = conn.execute( |
| 125 | + "SELECT tile_data FROM tiles" |
| 126 | + " WHERE zoom_level=? AND tile_column=? AND tile_row=?", |
| 127 | + (z, x, y), |
| 128 | + ).fetchone() |
| 129 | + |
| 130 | + if row is None: |
| 131 | + print(f" SKIP z={z}/x={x}/y={y} ({desc}) - tile not in output") |
| 132 | + continue |
| 133 | + |
| 134 | + fname = EXPECTED_DIR / f"z{z}_x{x}_y{y}.png" |
| 135 | + fname.write_bytes(row[0]) |
| 136 | + saved += 1 |
| 137 | + |
| 138 | + img = Image.open(io.BytesIO(row[0])) |
| 139 | + elev = _decode_elevation(row[0]) |
| 140 | + import numpy as np |
| 141 | + print( |
| 142 | + f" OK z={z}/x={x}/y={y} ({desc})" |
| 143 | + f" [{img.size[0]}x{img.size[1]}]" |
| 144 | + f" median elev = {np.median(elev):.1f} m" |
| 145 | + ) |
| 146 | + |
| 147 | + conn.close() |
| 148 | + |
| 149 | + print(f"\nDone. {saved} reference tiles written to {EXPECTED_DIR}") |
| 150 | + return 0 |
| 151 | + |
| 152 | + |
| 153 | +if __name__ == "__main__": |
| 154 | + sys.exit(main()) |
0 commit comments