gen-topo.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. #!/usr/bin/env python3
  2. """Generate the Mount Rainier contour lines used by the site background.
  3. Downloads Terrarium elevation tiles from the AWS Open Data "Terrain Tiles"
  4. bucket, traces contour lines with marching squares, simplifies them, and
  5. writes a compact delta-encoded JSON file to public/data/rainier-topo.json.
  6. Depends on numpy and Pillow. Run with: python3 scripts/gen-topo.py
  7. Data: Terrain Tiles (https://registry.opendata.aws/terrain-tiles/),
  8. sources include USGS 3DEP/NED and SRTM.
  9. """
  10. import io
  11. import json
  12. import math
  13. import os
  14. import urllib.request
  15. import zlib
  16. from collections import defaultdict
  17. import numpy as np
  18. from PIL import Image
  19. SUMMIT = (46.8523, -121.7603) # Columbia Crest
  20. LAT_SPAN = 0.17 # degrees each side of the summit
  21. LON_SPAN = 0.25
  22. ZOOM = 12
  23. GRID = 300 # output grid resolution (cells along the longer side)
  24. LEVEL_STEP = 150 # metres between contour lines
  25. MIN_LEVEL = 600
  26. SMOOTH_SIGMA = 1.6
  27. SIMPLIFY = 0.35 # Ramer-Douglas-Peucker tolerance in grid cells
  28. OUT_SCALE = 1000 # output coordinate space (longer side)
  29. TILE_URL = "https://s3.amazonaws.com/elevation-tiles-prod/terrarium/{z}/{x}/{y}.png"
  30. OUT = os.path.join(os.path.dirname(__file__), "..", "public", "data", "rainier-topo.json")
  31. def lon_to_x(lon, z):
  32. return (lon + 180.0) / 360.0 * (1 << z)
  33. def lat_to_y(lat, z):
  34. r = math.radians(lat)
  35. return (1.0 - math.log(math.tan(r) + 1.0 / math.cos(r)) / math.pi) / 2.0 * (1 << z)
  36. def fetch_tile(x, y, z):
  37. """Fetch one tile; set TOPO_CACHE to a directory to reuse downloads."""
  38. cache = os.environ.get("TOPO_CACHE")
  39. path = cache and os.path.join(cache, f"{z}-{x}-{y}.png")
  40. if path and os.path.exists(path):
  41. data = open(path, "rb").read()
  42. else:
  43. with urllib.request.urlopen(TILE_URL.format(z=z, x=x, y=y), timeout=60) as r:
  44. data = r.read()
  45. if path:
  46. os.makedirs(cache, exist_ok=True)
  47. open(path, "wb").write(data)
  48. rgb = np.asarray(Image.open(io.BytesIO(data)).convert("RGB"), dtype=np.float64)
  49. return rgb[:, :, 0] * 256 + rgb[:, :, 1] + rgb[:, :, 2] / 256 - 32768
  50. def gaussian(a, sigma):
  51. radius = int(math.ceil(sigma * 3))
  52. k = np.exp(-0.5 * (np.arange(-radius, radius + 1) / sigma) ** 2)
  53. k /= k.sum()
  54. pad = np.pad(a, radius, mode="edge")
  55. tmp = np.apply_along_axis(lambda m: np.convolve(m, k, mode="valid"), 1, pad)
  56. return np.apply_along_axis(lambda m: np.convolve(m, k, mode="valid"), 0, tmp)
  57. def marching_squares(grid, level):
  58. """Return contour segments as (x0, y0, x1, y1) in grid coordinates."""
  59. h, w = grid.shape
  60. tl, tr = grid[:-1, :-1], grid[:-1, 1:]
  61. bl, br = grid[1:, :-1], grid[1:, 1:]
  62. idx = (tl > level) * 8 + (tr > level) * 4 + (br > level) * 2 + (bl > level) * 1
  63. ys, xs = np.nonzero((idx > 0) & (idx < 15))
  64. segs = []
  65. def interp(a, b):
  66. d = b - a
  67. return 0.5 if d == 0 else (level - a) / d
  68. for y, x in zip(ys, xs):
  69. a, b, c, d = tl[y, x], tr[y, x], br[y, x], bl[y, x]
  70. top = (x + interp(a, b), y)
  71. right = (x + 1, y + interp(b, c))
  72. bottom = (x + interp(d, c), y + 1)
  73. left = (x, y + interp(a, d))
  74. case = idx[y, x]
  75. pairs = {
  76. 1: [(left, bottom)], 2: [(bottom, right)], 3: [(left, right)],
  77. 4: [(top, right)], 6: [(top, bottom)], 7: [(left, top)],
  78. 8: [(left, top)], 9: [(top, bottom)], 11: [(top, right)],
  79. 12: [(left, right)], 13: [(bottom, right)], 14: [(left, bottom)],
  80. 5: [(left, top), (bottom, right)], 10: [(top, right), (left, bottom)],
  81. }[case]
  82. segs.extend(pairs)
  83. return segs
  84. def join_segments(segs):
  85. key = lambda p: (round(p[0], 4), round(p[1], 4))
  86. ends = defaultdict(list)
  87. for i, (p, q) in enumerate(segs):
  88. ends[key(p)].append(i)
  89. ends[key(q)].append(i)
  90. used = [False] * len(segs)
  91. lines = []
  92. for i in range(len(segs)):
  93. if used[i]:
  94. continue
  95. used[i] = True
  96. line = [segs[i][0], segs[i][1]]
  97. for forward in (True, False):
  98. while True:
  99. tip = line[-1] if forward else line[0]
  100. nxt = None
  101. for j in ends[key(tip)]:
  102. if not used[j]:
  103. nxt = j
  104. break
  105. if nxt is None:
  106. break
  107. used[nxt] = True
  108. p, q = segs[nxt]
  109. other = q if key(p) == key(tip) else p
  110. if forward:
  111. line.append(other)
  112. else:
  113. line.insert(0, other)
  114. lines.append(line)
  115. return lines
  116. def rdp(points, eps):
  117. if len(points) < 3:
  118. return points
  119. pts = np.asarray(points)
  120. keep = np.zeros(len(pts), dtype=bool)
  121. keep[0] = keep[-1] = True
  122. stack = [(0, len(pts) - 1)]
  123. while stack:
  124. s, e = stack.pop()
  125. if e <= s + 1:
  126. continue
  127. seg = pts[e] - pts[s]
  128. norm = np.hypot(*seg)
  129. v = pts[s + 1 : e] - pts[s]
  130. if norm < 1e-9: # closed ring: measure distance from the start point
  131. d = np.hypot(v[:, 0], v[:, 1])
  132. else:
  133. d = np.abs(seg[0] * v[:, 1] - seg[1] * v[:, 0]) / norm
  134. i = int(np.argmax(d))
  135. if d[i] > eps:
  136. keep[s + 1 + i] = True
  137. stack.append((s, s + 1 + i))
  138. stack.append((s + 1 + i, e))
  139. return [tuple(p) for p in pts[keep]]
  140. def main():
  141. lat0, lon0 = SUMMIT
  142. north, south = lat0 + LAT_SPAN, lat0 - LAT_SPAN
  143. west, east = lon0 - LON_SPAN, lon0 + LON_SPAN
  144. fx0, fx1 = lon_to_x(west, ZOOM), lon_to_x(east, ZOOM)
  145. fy0, fy1 = lat_to_y(north, ZOOM), lat_to_y(south, ZOOM)
  146. tx0, tx1, ty0, ty1 = int(fx0), int(fx1), int(fy0), int(fy1)
  147. rows = []
  148. for ty in range(ty0, ty1 + 1):
  149. row = []
  150. for tx in range(tx0, tx1 + 1):
  151. print(f"tile {ZOOM}/{tx}/{ty}")
  152. row.append(fetch_tile(tx, ty, ZOOM))
  153. rows.append(np.hstack(row))
  154. mosaic = np.vstack(rows)
  155. px0, px1 = int((fx0 - tx0) * 256), int((fx1 - tx0) * 256)
  156. py0, py1 = int((fy0 - ty0) * 256), int((fy1 - ty0) * 256)
  157. elev = mosaic[py0:py1, px0:px1]
  158. # Resample so the longer side has GRID cells (block mean keeps it smooth).
  159. h, w = elev.shape
  160. step = max(h, w) / GRID
  161. gh, gw = int(h / step), int(w / step)
  162. ys = (np.arange(gh + 1) * step).astype(int)
  163. xs = (np.arange(gw + 1) * step).astype(int)
  164. grid = np.array([[elev[ys[i] : ys[i + 1], xs[j] : xs[j + 1]].mean() for j in range(gw)] for i in range(gh)])
  165. grid = gaussian(grid, SMOOTH_SIGMA)
  166. sy = (lat_to_y(lat0, ZOOM) - ty0) * 256 - py0
  167. sx = (lon_to_x(lon0, ZOOM) - tx0) * 256 - px0
  168. scale = OUT_SCALE / max(gw - 1, gh - 1)
  169. levels = []
  170. top = int(grid.max())
  171. for level in range(MIN_LEVEL, top, LEVEL_STEP):
  172. lines = join_segments(marching_squares(grid, level))
  173. enc = []
  174. for line in lines:
  175. if len(line) < 6:
  176. continue
  177. simple = rdp(line, SIMPLIFY)
  178. if len(simple) < 3:
  179. continue
  180. pts = [(round(x * scale), round(y * scale)) for x, y in simple]
  181. flat, px, py = [], 0, 0
  182. for i, (x, y) in enumerate(pts):
  183. if i and x == px and y == py:
  184. continue
  185. flat += [x - px, y - py] if i else [x, y]
  186. px, py = x, y
  187. if len(flat) >= 6:
  188. enc.append(flat)
  189. if enc:
  190. levels.append({"e": level, "l": enc})
  191. print(f"level {level}: {len(enc)} lines")
  192. out = {
  193. "w": round((gw - 1) * scale),
  194. "h": round((gh - 1) * scale),
  195. "summit": [round(sx / step * scale), round(sy / step * scale)],
  196. "step": LEVEL_STEP,
  197. "levels": levels,
  198. }
  199. os.makedirs(os.path.dirname(OUT), exist_ok=True)
  200. with open(OUT, "w") as f:
  201. json.dump(out, f, separators=(",", ":"))
  202. raw = os.path.getsize(OUT)
  203. gz = len(zlib.compress(open(OUT, "rb").read(), 9))
  204. print(f"wrote {OUT}: {raw / 1024:.1f}KB raw, ~{gz / 1024:.1f}KB compressed, max elev {grid.max():.0f}m")
  205. if __name__ == "__main__":
  206. main()